ifixkart-backend/app/services/StorefrontService.py

151 lines
6 KiB
Python

"""
@service StorefrontService (Backend/app/services/StorefrontService.py)
@purpose Domain service handling business logic, layout assembly, review moderation workflows, and cache invalidation.
"""
from sqlalchemy.orm import Session
from typing import List, Dict, Any, Optional
import ulid
from app.repositories.StorefrontRepository import StorefrontRepository
from app.models.StorefrontContentModel import StorefrontContent, ContentStatusEnum
from app.models.ProductReviewModel import ProductReview
from app.core.database.cache_manager import cache
class StorefrontService:
def __init__(self, db: Session):
self.repo = StorefrontRepository(db)
def get_layout(self, page: str, region: Optional[str] = None) -> List[Dict[str, Any]]:
# No in-memory cache here — layout changes via admin must reflect immediately
contents = self.repo.get_active_content(page, region)
result = [
{
"content_id": c.content_id,
"page": c.page,
"region": c.region,
"type": c.type,
"title": c.title,
"subtitle": c.subtitle,
"image_url": c.image_url,
"button_text": c.button_text,
"button_url": c.button_url,
"display_order": c.display_order,
# Expose under both keys so frontend works regardless of which it checks
"metadata": c.metadata_json or {},
"metadata_json": c.metadata_json or {}
}
for c in contents
]
return result
def invalidate_cache(self, pattern: Optional[str] = None):
if pattern:
cache.invalidate_prefix(pattern)
else:
cache.clear()
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
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,
"author_name": r.author_name,
"rating": r.rating,
"title": r.title,
"comment": r.comment,
"verified_buyer": r.verified_purchase,
"helpful_count": r.helpful_count,
"admin_reply": r.admin_reply,
"review_date": r.created_at.strftime("%Y-%m-%d") if r.created_at else "2026-07-25",
"images": [img.image_url for img in r.images if img.is_approved] if r.images else []
}
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)
if cached_settings is not None:
return cached_settings
settings = self.repo.get_public_settings(group)
result = {s.setting_key: s.setting_value for s in settings}
cache.set(cache_key, result, ttl_seconds=cache.TTL_SETTINGS)
return result