feat(reviews): enhance get_reviews with pagination & star breakdown, add submit_review with server-side verified purchase check
This commit is contained in:
parent
fa9b058914
commit
36878838a3
5 changed files with 277 additions and 15 deletions
|
|
@ -9,6 +9,10 @@ from typing import Any, Dict, List, Optional
|
|||
|
||||
from app.core.database.db_session import get_db
|
||||
from app.services.StorefrontCmsService import StorefrontCmsService
|
||||
from app.schemas.StorefrontCmsSchema import (
|
||||
StorefrontReviewCreate,
|
||||
ProductReviewSummaryResponse,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/storefront", tags=["Storefront Dynamic Services"])
|
||||
|
||||
|
|
@ -48,12 +52,30 @@ def get_catalog_filters(db: Session = Depends(get_db)) -> Any:
|
|||
return svc.get_catalog_filters()
|
||||
|
||||
|
||||
@router.get("/reviews/{product_id}")
|
||||
def get_product_reviews(product_id: str, db: Session = Depends(get_db)) -> List[Any]:
|
||||
"""Returns only approved customer reviews for a given product (live from DB)."""
|
||||
@router.get("/reviews/{product_id}", response_model=ProductReviewSummaryResponse)
|
||||
def get_product_reviews(
|
||||
product_id: str,
|
||||
page: int = Query(1, ge=1),
|
||||
limit: int = Query(10, ge=1, le=50),
|
||||
sort: str = Query("newest"),
|
||||
db: Session = Depends(get_db)
|
||||
) -> Any:
|
||||
"""Returns paginated approved customer reviews and star distribution for a given product."""
|
||||
from app.services.StorefrontService import StorefrontService
|
||||
svc = StorefrontService(db)
|
||||
return svc.get_reviews(product_id)
|
||||
return svc.get_reviews(product_id=product_id, page=page, limit=limit, sort=sort)
|
||||
|
||||
|
||||
@router.post("/reviews/{product_id}", status_code=201)
|
||||
def submit_product_review(
|
||||
product_id: str,
|
||||
payload: StorefrontReviewCreate,
|
||||
db: Session = Depends(get_db)
|
||||
) -> Any:
|
||||
"""Submits a customer review with server-side verified purchase validation."""
|
||||
from app.services.StorefrontService import StorefrontService
|
||||
svc = StorefrontService(db)
|
||||
return svc.submit_review(product_id=product_id, payload=payload)
|
||||
|
||||
|
||||
@router.get("/trust-badges")
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ from app.models.BrandModel import Brand
|
|||
from app.models.DeviceCatalogModel import ServiceType
|
||||
from app.models.CustomerFeedbackModel import CustomerFeedback
|
||||
from app.schemas.Catalog import ProductResponse
|
||||
from app.schemas.StorefrontCmsSchema import (
|
||||
StorefrontReviewCreate,
|
||||
ProductReviewSummaryResponse,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/storefront", tags=["Public Storefront Dynamic Services"])
|
||||
|
||||
|
|
@ -218,13 +222,32 @@ def submit_customer_feedback(payload: FeedbackCreatePayload, db: Session = Depen
|
|||
}
|
||||
|
||||
|
||||
@router.get("/reviews/{product_id}")
|
||||
def get_product_reviews(product_id: str, db: Session = Depends(get_db)):
|
||||
@router.get("/reviews/{product_id}", response_model=ProductReviewSummaryResponse)
|
||||
def get_product_reviews(
|
||||
product_id: str,
|
||||
page: int = Query(1, ge=1),
|
||||
limit: int = Query(10, ge=1, le=50),
|
||||
sort: str = Query("newest"),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Returns approved customer reviews for a given product.
|
||||
Returns approved customer reviews and star distribution for a given product.
|
||||
"""
|
||||
service = StorefrontService(db)
|
||||
return service.get_reviews(product_id)
|
||||
return service.get_reviews(product_id=product_id, page=page, limit=limit, sort=sort)
|
||||
|
||||
|
||||
@router.post("/reviews/{product_id}", status_code=201)
|
||||
def submit_product_review(
|
||||
product_id: str,
|
||||
payload: StorefrontReviewCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Submits a customer review with server-side verified purchase validation.
|
||||
"""
|
||||
service = StorefrontService(db)
|
||||
return service.submit_review(product_id=product_id, payload=payload)
|
||||
|
||||
@router.get("/settings/public")
|
||||
def get_public_settings(group: Optional[str] = Query(None), db: Session = Depends(get_db)):
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
@repository StorefrontRepository (Backend/app/repositories/StorefrontRepository.py)
|
||||
@purpose Data access layer for StorefrontContent, ProductReviews, and Settings.
|
||||
"""
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select, and_
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
from sqlalchemy import select, and_, or_, func
|
||||
from typing import List, Optional, Tuple, Dict, Any
|
||||
import ulid
|
||||
|
||||
from app.models.StorefrontContentModel import StorefrontContent, ContentStatusEnum
|
||||
|
|
@ -34,10 +34,122 @@ class StorefrontRepository:
|
|||
def get_approved_reviews(self, product_id: str) -> List[ProductReview]:
|
||||
return self.db.execute(
|
||||
select(ProductReview)
|
||||
.options(selectinload(ProductReview.images))
|
||||
.where(and_(ProductReview.product_id == product_id, ProductReview.is_approved == True))
|
||||
.order_by(ProductReview.created_at.desc())
|
||||
).scalars().all()
|
||||
|
||||
def get_approved_reviews_paginated(
|
||||
self, product_id: str, page: int = 1, limit: int = 10, sort: str = "newest"
|
||||
) -> Tuple[List[ProductReview], int]:
|
||||
base_query = select(ProductReview).where(
|
||||
and_(ProductReview.product_id == product_id, ProductReview.is_approved == True)
|
||||
)
|
||||
total = self.db.execute(select(func.count(ProductReview.review_id)).where(
|
||||
and_(ProductReview.product_id == product_id, ProductReview.is_approved == True)
|
||||
)).scalar() or 0
|
||||
|
||||
query = base_query.options(selectinload(ProductReview.images))
|
||||
if sort == "highest":
|
||||
query = query.order_by(ProductReview.rating.desc(), ProductReview.created_at.desc())
|
||||
elif sort == "lowest":
|
||||
query = query.order_by(ProductReview.rating.asc(), ProductReview.created_at.desc())
|
||||
elif sort == "helpful":
|
||||
query = query.order_by(ProductReview.helpful_count.desc(), ProductReview.created_at.desc())
|
||||
else: # newest default
|
||||
query = query.order_by(ProductReview.created_at.desc())
|
||||
|
||||
offset = max(0, (page - 1) * limit)
|
||||
reviews = self.db.execute(query.offset(offset).limit(limit)).scalars().all()
|
||||
return list(reviews), total
|
||||
|
||||
def get_review_metrics(self, product_id: str) -> Dict[str, Any]:
|
||||
rows = self.db.execute(
|
||||
select(ProductReview.rating, func.count(ProductReview.review_id))
|
||||
.where(and_(ProductReview.product_id == product_id, ProductReview.is_approved == True))
|
||||
.group_by(ProductReview.rating)
|
||||
).all()
|
||||
|
||||
star_distribution: Dict[str, int] = {"5": 0, "4": 0, "3": 0, "2": 0, "1": 0}
|
||||
total_reviews = 0
|
||||
sum_rating = 0
|
||||
|
||||
for r_rating, r_count in rows:
|
||||
key = str(int(r_rating))
|
||||
if key in star_distribution:
|
||||
star_distribution[key] = int(r_count)
|
||||
total_reviews += int(r_count)
|
||||
sum_rating += int(r_rating) * int(r_count)
|
||||
|
||||
average_rating = round(float(sum_rating) / float(total_reviews), 1) if total_reviews > 0 else 0.0
|
||||
|
||||
verified_count = self.db.execute(
|
||||
select(func.count(ProductReview.review_id)).where(
|
||||
and_(
|
||||
ProductReview.product_id == product_id,
|
||||
ProductReview.is_approved == True,
|
||||
ProductReview.verified_purchase == True
|
||||
)
|
||||
)
|
||||
).scalar() or 0
|
||||
|
||||
return {
|
||||
"average_rating": average_rating,
|
||||
"total_reviews": total_reviews,
|
||||
"star_distribution": star_distribution,
|
||||
"verified_count": verified_count
|
||||
}
|
||||
|
||||
def check_verified_purchase(
|
||||
self, product_id: str, user_id: Optional[str] = None, email: Optional[str] = None
|
||||
) -> bool:
|
||||
if not user_id and not email:
|
||||
return False
|
||||
try:
|
||||
from app.models.OrderModel import Order, OrderItem
|
||||
conditions = []
|
||||
if user_id:
|
||||
conditions.append(Order.customer_id == user_id)
|
||||
if email:
|
||||
clean_email = email.strip().lower()
|
||||
conditions.append(func.lower(Order.customer_email) == clean_email)
|
||||
conditions.append(func.lower(Order.guest_email) == clean_email)
|
||||
|
||||
stmt = select(func.count(OrderItem.item_id)).join(
|
||||
Order, Order.order_id == OrderItem.order_id
|
||||
).where(
|
||||
OrderItem.product_id == product_id,
|
||||
or_(*conditions),
|
||||
Order.status.in_(["delivered", "completed", "shipped"])
|
||||
)
|
||||
count = self.db.execute(stmt).scalar() or 0
|
||||
return count > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def create_product_review(
|
||||
self, review: ProductReview, image_urls: Optional[List[str]] = None
|
||||
) -> ProductReview:
|
||||
self.db.add(review)
|
||||
self.db.flush()
|
||||
|
||||
if image_urls:
|
||||
for idx, url in enumerate(image_urls):
|
||||
clean_url = str(url).strip()
|
||||
if clean_url:
|
||||
img = ProductReviewImage(
|
||||
image_id=str(ulid.new()),
|
||||
review_id=review.review_id,
|
||||
image_url=clean_url,
|
||||
display_order=idx,
|
||||
is_approved=True
|
||||
)
|
||||
self.db.add(img)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(review)
|
||||
return review
|
||||
|
||||
def create_review(self, review: ProductReview) -> ProductReview:
|
||||
self.db.add(review)
|
||||
self.db.commit()
|
||||
|
|
|
|||
|
|
@ -205,3 +205,40 @@ class ReviewModerationResponse(BaseModel):
|
|||
|
||||
class ReviewApprovalPayload(BaseModel):
|
||||
admin_reply: Optional[str] = Field(None, max_length=1000)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public Storefront Review Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class StorefrontReviewCreate(BaseModel):
|
||||
rating: int = Field(..., ge=1, le=5)
|
||||
title: str = Field(..., min_length=2, max_length=255)
|
||||
comment: str = Field(..., min_length=5, max_length=5000)
|
||||
author_name: str = Field(..., min_length=2, max_length=128)
|
||||
author_email: Optional[str] = Field(None, max_length=255)
|
||||
image_urls: List[str] = []
|
||||
|
||||
|
||||
class ProductReviewItem(BaseModel):
|
||||
review_id: str
|
||||
product_id: str
|
||||
author_name: str
|
||||
rating: int
|
||||
title: str
|
||||
comment: str
|
||||
verified_buyer: bool
|
||||
helpful_count: int
|
||||
admin_reply: Optional[str] = None
|
||||
review_date: Optional[str] = None
|
||||
images: List[str] = []
|
||||
|
||||
|
||||
class ProductReviewSummaryResponse(BaseModel):
|
||||
average_rating: float
|
||||
total_reviews: int
|
||||
star_distribution: Dict[str, int]
|
||||
verified_count: int
|
||||
page: int
|
||||
limit: int
|
||||
reviews: List[ProductReviewItem]
|
||||
|
|
|
|||
|
|
@ -44,14 +44,20 @@ class StorefrontService:
|
|||
else:
|
||||
cache.clear()
|
||||
|
||||
def get_reviews(self, product_id: str) -> List[Dict[str, Any]]:
|
||||
cache_key = f"reviews:{product_id}"
|
||||
def get_reviews(
|
||||
self, product_id: str, page: int = 1, limit: int = 10, sort: str = "newest"
|
||||
) -> Dict[str, Any]:
|
||||
cache_key = f"reviews:{product_id}:page={page}:limit={limit}:sort={sort}"
|
||||
cached_reviews = cache.get(cache_key)
|
||||
if cached_reviews is not None:
|
||||
return cached_reviews
|
||||
|
||||
reviews = self.repo.get_approved_reviews(product_id)
|
||||
result = [
|
||||
metrics = self.repo.get_review_metrics(product_id)
|
||||
reviews, total = self.repo.get_approved_reviews_paginated(
|
||||
product_id=product_id, page=page, limit=limit, sort=sort
|
||||
)
|
||||
|
||||
serialized_reviews = [
|
||||
{
|
||||
"review_id": r.review_id,
|
||||
"product_id": r.product_id,
|
||||
|
|
@ -68,9 +74,71 @@ class StorefrontService:
|
|||
for r in reviews
|
||||
]
|
||||
|
||||
result = {
|
||||
"average_rating": metrics["average_rating"],
|
||||
"total_reviews": metrics["total_reviews"],
|
||||
"star_distribution": metrics["star_distribution"],
|
||||
"verified_count": metrics["verified_count"],
|
||||
"page": page,
|
||||
"limit": limit,
|
||||
"reviews": serialized_reviews
|
||||
}
|
||||
|
||||
cache.set(cache_key, result, ttl_seconds=cache.TTL_SETTINGS)
|
||||
return result
|
||||
|
||||
def submit_review(
|
||||
self, product_id: str, payload: Any, user_id: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
from app.services.ReviewModerationService import PROFANITY_BLOCKLIST
|
||||
|
||||
comment_lower = f"{getattr(payload, 'title', '')} {getattr(payload, 'comment', '')}".lower()
|
||||
contains_blocked = any(word in comment_lower for word in PROFANITY_BLOCKLIST)
|
||||
|
||||
author_email = getattr(payload, "author_email", None)
|
||||
is_verified = self.repo.check_verified_purchase(
|
||||
product_id=product_id,
|
||||
user_id=user_id,
|
||||
email=author_email
|
||||
)
|
||||
|
||||
# Approved by default if no blocked words, otherwise queued for moderation
|
||||
is_approved = not contains_blocked
|
||||
|
||||
review = ProductReview(
|
||||
review_id=str(ulid.new()),
|
||||
product_id=product_id,
|
||||
user_id=user_id,
|
||||
author_name=getattr(payload, "author_name", "Anonymous").strip(),
|
||||
author_email=author_email.strip() if author_email else None,
|
||||
rating=int(getattr(payload, "rating", 5)),
|
||||
title=getattr(payload, "title", "").strip(),
|
||||
comment=getattr(payload, "comment", "").strip(),
|
||||
verified_purchase=is_verified,
|
||||
is_approved=is_approved,
|
||||
helpful_count=0
|
||||
)
|
||||
|
||||
image_urls = getattr(payload, "image_urls", []) or []
|
||||
saved_review = self.repo.create_product_review(review, image_urls)
|
||||
|
||||
# Invalidate reviews cache for this product
|
||||
cache.invalidate_prefix(f"reviews:{product_id}")
|
||||
|
||||
return {
|
||||
"review_id": saved_review.review_id,
|
||||
"product_id": saved_review.product_id,
|
||||
"author_name": saved_review.author_name,
|
||||
"rating": saved_review.rating,
|
||||
"title": saved_review.title,
|
||||
"comment": saved_review.comment,
|
||||
"verified_buyer": saved_review.verified_purchase,
|
||||
"is_approved": saved_review.is_approved,
|
||||
"helpful_count": 0,
|
||||
"review_date": saved_review.created_at.strftime("%Y-%m-%d") if saved_review.created_at else None,
|
||||
"images": image_urls
|
||||
}
|
||||
|
||||
def get_public_settings(self, group: Optional[str] = None) -> Dict[str, Any]:
|
||||
cache_key = f"settings:public:{group or 'all'}"
|
||||
cached_settings = cache.get(cache_key)
|
||||
|
|
|
|||
Loading…
Reference in a new issue