163 lines
6.6 KiB
Python
163 lines
6.6 KiB
Python
"""
|
|
@repository StorefrontRepository (Backend/app/repositories/StorefrontRepository.py)
|
|
@purpose Data access layer for StorefrontContent, ProductReviews, and Settings.
|
|
"""
|
|
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
|
|
from app.models.ProductReviewModel import ProductReview, ProductReviewImage
|
|
from app.models.SettingModel import Setting
|
|
|
|
class StorefrontRepository:
|
|
def __init__(self, db: Session):
|
|
self.db = db
|
|
|
|
def get_active_content(self, page: str, region: Optional[str] = None) -> List[StorefrontContent]:
|
|
query = select(StorefrontContent).where(StorefrontContent.page == page)
|
|
if region:
|
|
query = query.where(StorefrontContent.region == region)
|
|
query = query.order_by(StorefrontContent.display_order.asc())
|
|
return self.db.execute(query).scalars().all()
|
|
|
|
def get_content_by_id(self, content_id: str) -> Optional[StorefrontContent]:
|
|
return self.db.execute(select(StorefrontContent).where(StorefrontContent.content_id == content_id)).scalar_one_or_none()
|
|
|
|
def create_or_update_content(self, content: StorefrontContent) -> StorefrontContent:
|
|
self.db.add(content)
|
|
self.db.commit()
|
|
self.db.refresh(content)
|
|
return content
|
|
|
|
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.ULID()),
|
|
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()
|
|
self.db.refresh(review)
|
|
return review
|
|
|
|
def get_public_settings(self, group: Optional[str] = None) -> List[Setting]:
|
|
query = select(Setting).where(Setting.is_public == True)
|
|
if group:
|
|
query = query.where(Setting.group == group)
|
|
return self.db.execute(query).scalars().all()
|