""" @router Public Storefront Router (Backend/app/api/v1/routers/storefront.py) @purpose Read-only public endpoints for layout widgets, reviews, and settings powered by StorefrontService. """ from fastapi import APIRouter, Depends, Query, HTTPException, status, Request, Response from sqlalchemy.orm import Session, selectinload from sqlalchemy import select from typing import List, Dict, Any, Optional from pydantic import BaseModel from app.core.database.db_session import get_db from app.services.StorefrontService import StorefrontService from app.services.CatalogSearchService import apply_product_search from app.models.ProductModel import Product, ProductVariant, VariantAttribute from app.models.CategoryModel import Category 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"]) @router.get("/live-search") def live_search( q: str = Query(..., min_length=2, max_length=200), category: Optional[str] = Query(None), db: Session = Depends(get_db), ): """ Autocomplete search for the storefront header. Caps results so 500k catalogs stay cheap. """ from app.core.database.cache_manager import cache cache_key = f"storefront:live-search:{q.strip().lower()}:{category or 'all'}" cached = cache.get(cache_key) if cached is not None: return cached stmt = ( select(Product) .options( selectinload(Product.images), selectinload(Product.variants).selectinload(ProductVariant.images), selectinload(Product.variants).selectinload(ProductVariant.attributes).selectinload(VariantAttribute.attribute_type), ) .where(Product.status == "active") ) if category and category != "all": stmt = stmt.join(Category, Product.category_id == Category.category_id).where( (Category.slug == category) | (Category.category_id == category) ) stmt = apply_product_search(stmt, q).order_by(Product.created_at.desc()).limit(8) products = db.execute(stmt).scalars().all() def _variant_label(v) -> str: vals = [] for a in (v.attributes or []): code = ( getattr(getattr(a, "attribute_type", None), "code", None) or getattr(a, "attribute_code", "") or "" ).strip().lower() if code in ("parent_media_key", "media_key", "barcode", "sku", "warranty_months", "country_of_origin") or code.startswith("parent_"): continue if a.attribute_value and a.attribute_value not in vals: if code == "color": vals.insert(0, a.attribute_value) else: vals.append(a.attribute_value) return " ".join(vals) expanded_products = [] for p in products: active_variants = [v for v in (p.variants or []) if getattr(v, "status", "active") == "active"] if len(active_variants) > 1: for v in active_variants: label = _variant_label(v) v_name = f"{p.name} - {label}" if label else p.name v_img = v.images[0].image_url if v.images else (p.images[0].image_url if p.images else None) v_price = float(v.price) if v.price is not None else 0.0 base_price = round(v_price * 0.82, 2) base_compare = round(float(v.compare_price) * 0.82, 2) if v.compare_price is not None else None expanded_products.append({ "product_id": p.product_id, "category_id": p.category_id, "name": v_name, "slug": p.slug, "variant_sku": v.sku, "variant_name": label or None, "variant_url": f"/products/{p.slug}?variant={v.sku}", "price": base_price, "mrp": v_price, "compare_price": base_compare, "thumbnail_url": v_img, "images": [{"image_url": v_img}] if v_img else [], "variants": [{ "variant_id": v.variant_id, "product_id": p.product_id, "sku": v.sku, "price": base_price, "mrp": v_price, "status": "active", }] }) else: first_v = active_variants[0] if active_variants else (p.variants[0] if p.variants else None) v_img = (p.images[0].image_url if p.images else (first_v.images[0].image_url if first_v and first_v.images else None)) if not v_img and p.variants: for alt_v in p.variants: if alt_v.images: v_img = alt_v.images[0].image_url break price_val = float(first_v.price) if first_v and first_v.price is not None else 0.0 base_price = round(price_val * 0.82, 2) base_compare = round(float(first_v.compare_price) * 0.82, 2) if first_v and first_v.compare_price is not None else None expanded_products.append({ "product_id": p.product_id, "category_id": p.category_id, "name": p.name, "slug": p.slug, "variant_sku": first_v.sku if first_v else None, "variant_name": None, "variant_url": f"/products/{p.slug}", "price": base_price, "mrp": price_val, "compare_price": base_compare, "thumbnail_url": v_img, "images": [{"image_url": v_img}] if v_img else [], "variants": [{ "variant_id": first_v.variant_id if first_v else p.product_id, "product_id": p.product_id, "sku": first_v.sku if first_v else "", "price": base_price, "mrp": price_val, "status": "active", }] if first_v else [] }) term = f"%{q.strip()}%" categories = db.execute( select(Category).where(Category.is_active == True, Category.name.ilike(term)).limit(5) ).scalars().all() brands = db.execute( select(Brand).where(Brand.is_active == True, Brand.name.ilike(term)).limit(5) ).scalars().all() services = db.execute( select(ServiceType).where(ServiceType.is_active == True, ServiceType.name.ilike(term)).limit(5) ).scalars().all() payload = { "products": expanded_products, "categories": [ { "category_id": c.category_id, "name": c.name, "slug": c.slug, "parent_category_id": c.parent_category_id, "description": c.description, "image_url": c.image_url, "is_active": c.is_active, } for c in categories ], "brands": [ { "brand_id": b.brand_id, "name": b.name, "slug": b.slug, "logo_url": b.logo_url, "is_active": b.is_active, } for b in brands ], "services": [ { "service_type_id": s.service_type_id if hasattr(s, "service_type_id") else getattr(s, "type_id", None), "name": s.name, "slug": getattr(s, "slug", None), } for s in services ], } cache.set(cache_key, payload, ttl_seconds=15) return payload @router.get("/layout/{page}") def get_storefront_layout(page: str, response: Response, region: Optional[str] = Query(None), db: Session = Depends(get_db)): """ Returns active storefront layout widgets ordered by display_order. """ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" service = StorefrontService(db) return service.get_layout(page, region) class FeedbackCreatePayload(BaseModel): name: str email: str topic: str = "general" order_no: Optional[str] = None rating: int = 5 message: str @router.post("/feedback", status_code=status.HTTP_201_CREATED) def submit_customer_feedback(payload: FeedbackCreatePayload, db: Session = Depends(get_db)): """ Public customer feedback submission from the /feedback page. """ feedback = CustomerFeedback( name=payload.name.strip(), email=payload.email.strip(), topic=payload.topic, order_no=payload.order_no.strip() if payload.order_no else None, rating=max(1, min(5, payload.rating)), message=payload.message.strip(), status="NEW", ) db.add(feedback) db.commit() db.refresh(feedback) return { "message": "Thank you! Your feedback has been received.", "feedback_id": feedback.feedback_id, } @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 and star distribution for a given product. """ service = StorefrontService(db) 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)): """ Returns public key-value store settings. """ service = StorefrontService(db) return service.get_public_settings(group) @router.get("/catalog/categories/{category_id}/parent-hierarchy") def get_category_parent_hierarchy(category_id: str, db: Session = Depends(get_db)): """ Returns the product-derived Brand → Series → Model hierarchy for a category. Only includes brands/series/models that have active products in this category. """ from sqlalchemy import select, distinct from app.models.CategoryModel import Category from app.models.ProductModel import Product from app.models.BrandModel import Brand from app.models.DeviceCatalogModel import DeviceSeries, DeviceModel from app.schemas.Catalog import ( CategoryParentHierarchyResponse, HierarchyBrandItem, HierarchySeriesItem, HierarchyModelItem, ) # Verify category exists category = db.execute( select(Category).where(Category.category_id == category_id) ).scalar_one_or_none() if not category: raise HTTPException(status_code=404, detail="Category not found") # Fetch all active products in this category that have brand + series + model set rows = db.execute( select( Brand.brand_id, Brand.name, Brand.slug, Brand.logo_url, DeviceSeries.series_id, DeviceSeries.name.label("series_name"), DeviceSeries.slug.label("series_slug"), DeviceModel.model_id, DeviceModel.name.label("model_name"), DeviceModel.slug.label("model_slug"), DeviceModel.image_url.label("model_image") ) .select_from(Product) .join(Brand, Product.brand_id == Brand.brand_id) .outerjoin(DeviceModel, Product.device_model_id == DeviceModel.model_id) .outerjoin(DeviceSeries, DeviceModel.series_id == DeviceSeries.series_id) .where( Product.category_id == category_id, Product.status == "active", Brand.is_active == True, (DeviceSeries.series_id == None) | (DeviceSeries.is_active == True), (DeviceModel.model_id == None) | (DeviceModel.is_active == True), ) .distinct() ).all() # Build nested hierarchy in memory brands_map: dict = {} for row in rows: bid = row.brand_id if bid not in brands_map: brands_map[bid] = { "brand_id": bid, "name": row.name, "slug": row.slug, "logo_url": row.logo_url, "series": {}, } sid = row.series_id series_name = row.series_name series_slug = row.series_slug # If a model exists but series is missing, group it under a virtual "General Models" series if not sid and row.model_id: sid = f"no-series-{bid}" series_name = "General Models" series_slug = "general" if sid: if sid not in brands_map[bid]["series"]: brands_map[bid]["series"][sid] = { "series_id": sid, "name": series_name, "slug": series_slug, "models": {}, } mid = row.model_id if mid: if mid not in brands_map[bid]["series"][sid]["models"]: brands_map[bid]["series"][sid]["models"][mid] = { "model_id": mid, "name": row.model_name, "slug": row.model_slug, "image_url": row.model_image, } # Convert maps to sorted lists brands_list = [] for b in brands_map.values(): series_list = [] for s in b["series"].values(): models_list = list(s["models"].values()) series_list.append(HierarchySeriesItem( series_id=s["series_id"], name=s["name"], slug=s["slug"], models=[HierarchyModelItem(**m) for m in models_list] )) brands_list.append(HierarchyBrandItem( brand_id=b["brand_id"], name=b["name"], slug=b["slug"], logo_url=b["logo_url"], series=series_list )) return CategoryParentHierarchyResponse(category_id=category_id, brands=brands_list) @router.get("/coupons") def get_storefront_available_coupons( request: Request, db: Session = Depends(get_db) ): """ Returns active promotional coupons available for storefront customers. Optionally evaluates customer token to flag eligibility (e.g. 1st order rule). """ from datetime import datetime from app.models.CouponModel import Coupon, CouponUsage from app.models.OrderModel import Order from app.core.Token import verify_access_token # 1. Resolve optional customer from Authorization header customer_id = None auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header.split(" ")[1] try: payload = verify_access_token(token) if payload.get("role") == "customer": customer_id = payload.get("sub") except Exception: pass # Customer orders count if logged in customer_order_count = 0 if customer_id: customer_order_count = db.query(Order).filter( Order.customer_id == customer_id, Order.status.notin_(["CANCELLED", "PAYMENT_FAILED"]) ).count() now = datetime.now() coupons = db.query(Coupon).filter( Coupon.is_active == True, Coupon.valid_from <= now, Coupon.valid_to >= now, Coupon.channel_scope.notin_(["POS_ONLY", "STORE_POS"]) ).order_by(Coupon.discount_value.desc()).all() result = [] for c in coupons: # Check global cap if c.usage_limit_total and c.times_used >= c.usage_limit_total: continue is_eligible = True ineligibility_reason = None if customer_id: # Check 1st order rule if c.first_order_only and customer_order_count > 0: is_eligible = False ineligibility_reason = "Valid for first purchase only" # Check per-customer limit if c.usage_limit_per_customer: user_usages = db.query(CouponUsage).filter( CouponUsage.coupon_id == c.coupon_id, CouponUsage.customer_id == customer_id ).count() if user_usages >= c.usage_limit_per_customer: is_eligible = False ineligibility_reason = "Already redeemed" result.append({ "coupon_id": c.coupon_id, "code": c.code, "title": c.title, "description": c.description, "discount_type": c.discount_type, "discount_value": float(c.discount_value), "max_discount_cap": float(c.max_discount_cap) if c.max_discount_cap else None, "min_order_amount": float(c.min_order_amount), "first_order_only": bool(c.first_order_only), "valid_to": c.valid_to.isoformat() if c.valid_to else None, "is_eligible": is_eligible, "ineligibility_reason": ineligibility_reason }) return result