feat(storefront): expose available promotional coupons and flexible coupon payload
This commit is contained in:
parent
3ac30e702e
commit
a98332f185
4 changed files with 97 additions and 3 deletions
|
|
@ -44,7 +44,13 @@ class MergeGuestCartRequest(BaseModel):
|
|||
|
||||
|
||||
class ApplyCouponRequest(BaseModel):
|
||||
code: str
|
||||
code: Optional[str] = None
|
||||
coupon_code: Optional[str] = None
|
||||
|
||||
@property
|
||||
def coupon_key(self) -> str:
|
||||
raw = self.code or self.coupon_code or ""
|
||||
return raw.strip().upper()
|
||||
|
||||
|
||||
def _ensure_stock(db: Session, variant_id: str, requested_qty: int, sku: Optional[str] = None) -> None:
|
||||
|
|
@ -367,7 +373,7 @@ def apply_cart_coupon(
|
|||
# Validate coupon via Rule Engine
|
||||
res = CouponService.validate_coupon(
|
||||
db=db,
|
||||
code=payload.code,
|
||||
code=payload.coupon_key,
|
||||
customer_id=customer.customer_id,
|
||||
items=totals_preview["items"],
|
||||
subtotal=subtotal,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
@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
|
||||
from fastapi import APIRouter, Depends, Query, HTTPException, status, Request
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
from sqlalchemy import select
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
|
@ -259,3 +259,89 @@ def get_category_parent_hierarchy(category_id: str, db: Session = Depends(get_db
|
|||
))
|
||||
|
||||
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
|
||||
|
||||
|
|
|
|||
|
|
@ -61,3 +61,4 @@ class CouponUsage(Base):
|
|||
|
||||
coupon = relationship("Coupon", back_populates="usages")
|
||||
order = relationship("Order", backref="coupon_usage")
|
||||
|
||||
|
|
|
|||
|
|
@ -207,3 +207,4 @@ class CouponService:
|
|||
)
|
||||
db.add(usage)
|
||||
return usage
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue