fix(cart): validate coupons strictly against database and verify active/expiry status #6

Merged
amit merged 1 commits from fix/cart-coupon-db-validation into main 2026-10-06 12:22:46 +00:00
4 changed files with 25 additions and 12 deletions

View File

@ -45,20 +45,31 @@ class CartRepository:
items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price))
return items
async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None:
if not code:
return None
async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
if not code or not code.strip():
return None, None
clean_code = code.strip().upper()
now = datetime.now(timezone.utc)
coupon = (await self.session.execute(select(Coupon).where(Coupon.code == code.strip().upper(), Coupon.is_active.is_(True), Coupon.start_date <= now, Coupon.end_date >= now))).scalar_one_or_none()
coupon = (await self.session.execute(select(Coupon).where(Coupon.code == clean_code))).scalar_one_or_none()
if not coupon:
return None
return None, "Invalid or expired coupon code."
if not coupon.is_active:
return None, "This coupon code is currently inactive."
s_date = coupon.start_date.replace(tzinfo=timezone.utc) if coupon.start_date.tzinfo is None else coupon.start_date
e_date = coupon.end_date.replace(tzinfo=timezone.utc) if coupon.end_date.tzinfo is None else coupon.end_date
if now < s_date:
return None, "This coupon code is not active yet."
if now > e_date:
return None, "Invalid or expired coupon code."
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
return None, "Coupon usage limit reached."
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
value = Decimal(coupon.value)
if coupon.discount_type == "flat":
if coupon.discount_type in {"flat", "flat_amount"}:
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
if isinstance(currency_values, dict) and currency.upper() in currency_values:
value = Decimal(str(currency_values[currency.upper()]))
return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit))
return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit)), None
async def get_owned_categories(self, user_id: UUID) -> list[str]:
rows = (await self.session.execute(select(UserEntitlement, Module).join(Module, Module.id == UserEntitlement.module_id).where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE))).all()

View File

@ -22,6 +22,7 @@ class CartCalculationResponse(BaseModel):
bundle_discount_amount: float
coupon_applied: str
coupon_discount_amount: float
coupon_error: str | None = None
total_discounts: float
convenience_fee_rate: float
convenience_fee: float

View File

@ -16,7 +16,7 @@ class CartService:
resolved = {i.code.upper() for i in items}
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
coupon = await self.repository.get_coupon(request.coupon_code, currency)
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency)
owned = await self.repository.get_owned_categories(user_id) if user_id else request.owned_category_names
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first))
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))

View File

@ -27,7 +27,7 @@ class PricingCoupon:
class PricingEngine:
"""Preserves the legacy bundle/loyalty/fee rules while sourcing prices from commerce.access_plans."""
def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool) -> dict[str, Any]:
def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool, coupon_error: str | None = None) -> dict[str, Any]:
curr = currency.upper()
base = sum((item.price for item in items), Decimal("0"))
categories = {item.category for item in items}
@ -56,9 +56,9 @@ class PricingEngine:
coupon_text = "None"
if coupon:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type == "flat":
if coupon.discount_type in {"flat", "flat_amount"}:
coupon_discount = min(coupon.value, after_bundle)
elif coupon.discount_type == "percentage":
elif coupon.discount_type in {"percentage", "percent"}:
coupon_discount = after_bundle * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
@ -74,6 +74,7 @@ class PricingEngine:
"bundle_discount_amount": float(q(bundle)),
"coupon_applied": coupon_text,
"coupon_discount_amount": float(q(coupon_discount)),
"coupon_error": coupon_error,
"total_discounts": float(q(bundle + coupon_discount)),
"convenience_fee_rate": float(fee_rate * 100),
"convenience_fee": float(fee),