From 77f3063f5822056937d238310815e5486b2289df Mon Sep 17 00:00:00 2001 From: Urvish Date: Thu, 5 Nov 2026 14:10:59 +0530 Subject: [PATCH] fix(pricing): enforce plan and module restrictions on scoped coupons --- app/features/cart/repository.py | 53 +++++++++++++++- app/features/payments/pricing.py | 44 ++++++++++--- tests/unit/test_cart_pricing.py | 106 +++++++++++++++++++++++++++++++ 3 files changed, 192 insertions(+), 11 deletions(-) diff --git a/app/features/cart/repository.py b/app/features/cart/repository.py index 319a770..a4aca09 100644 --- a/app/features/cart/repository.py +++ b/app/features/cart/repository.py @@ -5,7 +5,7 @@ from uuid import UUID from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.db.enums import EntitlementStatus, SubscriptionStatus -from app.db.models import AccessPlan, Coupon, Module, UserEntitlement, UserSubscription +from app.db.models import AccessPlan, AccessPlanModule, Coupon, Module, UserEntitlement, UserSubscription from app.features.payments.pricing import PricingCoupon, PricingItem class CartRepository: @@ -120,11 +120,32 @@ class CartRepository: normalized = [c.strip().upper() for c in codes if c.strip()] items: list[PricingItem] = [] ren = renewable_codes or set() + + plan_ids = [plan.id for plan, _ in matches.values()] + plan_module_map: dict[str, list[str]] = {} + if plan_ids: + apm_rows = (await self.session.execute( + select(AccessPlanModule.plan_id, AccessPlanModule.module_id) + .where(AccessPlanModule.plan_id.in_(plan_ids)) + )).all() + for pid, mid in apm_rows: + plan_module_map.setdefault(str(pid), []).append(str(mid)) + for code in normalized: if code in matches: plan, price = matches[code] is_renewal = (code in ren) or (plan.code.upper() in ren) - items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price, is_renewal=is_renewal)) + p_str = str(plan.id) + m_ids = tuple(plan_module_map.get(p_str, [])) + items.append(PricingItem( + code=code, + name=plan.name, + category=self._category(plan), + price=price, + is_renewal=is_renewal, + plan_id=p_str, + module_ids=m_ids, + )) return items async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]: @@ -152,6 +173,32 @@ class CartRepository: if isinstance(currency_values, dict) and currency.upper() in currency_values: value = Decimal(str(currency_values[currency.upper()])) min_spend = Decimal(str(coupon.min_purchase_amount or 0)) + + app_plan_ids: set[str] = set() + if coupon.applicable_plan_ids: + for pid in coupon.applicable_plan_ids: + app_plan_ids.add(str(pid)) + # Include paired currency versions (e.g. LIFETIME_ALL and LIFETIME_ALL_USD) + p_rows = (await self.session.execute( + select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids)) + )).scalars().all() + base_codes: set[str] = set() + for c in p_rows: + code_up = c.upper() + base_codes.add(code_up[:-4] if code_up.endswith("_USD") else code_up) + if base_codes: + sibling_codes: set[str] = set() + for bc in base_codes: + sibling_codes.add(bc) + sibling_codes.add(f"{bc}_USD") + sibling_rows = (await self.session.execute( + select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes)) + )).scalars().all() + for sid in sibling_rows: + app_plan_ids.add(str(sid)) + + app_mod_ids = tuple(str(mid) for mid in coupon.applicable_module_ids) if coupon.applicable_module_ids else () + return PricingCoupon( code=coupon.code, category=coupon.coupon_category, @@ -160,6 +207,8 @@ class CartRepository: description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit or 0), min_purchase_amount=min_spend, + applicable_plan_ids=tuple(app_plan_ids), + applicable_module_ids=app_mod_ids, ), None @staticmethod diff --git a/app/features/payments/pricing.py b/app/features/payments/pricing.py index 03eb171..fa9091b 100644 --- a/app/features/payments/pricing.py +++ b/app/features/payments/pricing.py @@ -15,6 +15,8 @@ class PricingItem: category: str price: Decimal is_renewal: bool = False + plan_id: str | None = None + module_ids: tuple[str, ...] = () @dataclass(frozen=True) class PricingCoupon: @@ -25,6 +27,8 @@ class PricingCoupon: description: str | None = None max_discount_limit: Decimal = Decimal("0") min_purchase_amount: Decimal = Decimal("0") + applicable_plan_ids: tuple[str, ...] = () + applicable_module_ids: tuple[str, ...] = () class PricingEngine: """Calculates checkout totals with Policy 5.1 Early Renewal Discount (20%) and coupon discounts.""" @@ -45,18 +49,40 @@ class PricingEngine: coupon_discount = Decimal("0") coupon_text = "None" if coupon: - if coupon.min_purchase_amount > 0 and after_renewal < coupon.min_purchase_amount: - coupon_error = f"Minimum cart spend of {curr} {coupon.min_purchase_amount} required to use coupon {coupon.code}." + allowed_plans = set(coupon.applicable_plan_ids) + allowed_modules = set(coupon.applicable_module_ids) + has_scope_restriction = bool(allowed_plans or allowed_modules) + + qualifying_items = [ + item for item in items + if (not has_scope_restriction) + or (item.plan_id and item.plan_id in allowed_plans) + or (any(m in allowed_modules for m in item.module_ids)) + ] + + if has_scope_restriction and not qualifying_items: + coupon_error = "This promo code is not valid for items in your cart." coupon_text = "None" coupon_discount = Decimal("0") else: - coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -") - if coupon.discount_type in {"flat", "flat_amount"}: - coupon_discount = min(coupon.value, after_renewal) - elif coupon.discount_type in {"percentage", "percent"}: - coupon_discount = after_renewal * (coupon.value / Decimal("100")) - if coupon.max_discount_limit > 0: - coupon_discount = min(coupon_discount, coupon.max_discount_limit) + # Calculate eligible spend after applicable item-level renewal discounts + eligible_spend = sum( + (max(Decimal("0"), item.price - (q(item.price * Decimal("0.20")) if item.is_renewal else Decimal("0"))) + for item in qualifying_items), + Decimal("0") + ) + if coupon.min_purchase_amount > 0 and eligible_spend < coupon.min_purchase_amount: + coupon_error = f"Minimum cart spend of {curr} {coupon.min_purchase_amount} required to use coupon {coupon.code}." + coupon_text = "None" + coupon_discount = Decimal("0") + else: + coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -") + if coupon.discount_type in {"flat", "flat_amount"}: + coupon_discount = min(coupon.value, eligible_spend) + elif coupon.discount_type in {"percentage", "percent"}: + coupon_discount = eligible_spend * (coupon.value / Decimal("100")) + if coupon.max_discount_limit > 0: + coupon_discount = min(coupon_discount, coupon.max_discount_limit) net = max(Decimal("0"), after_renewal - coupon_discount) grand = q(net) return { diff --git a/tests/unit/test_cart_pricing.py b/tests/unit/test_cart_pricing.py index c8d33f5..65573b7 100644 --- a/tests/unit/test_cart_pricing.py +++ b/tests/unit/test_cart_pricing.py @@ -226,6 +226,112 @@ class TestPricingEngineCouponRules: assert result["coupon_error"] is not None assert "Minimum cart spend" in result["coupon_error"] + def test_plan_scoped_coupon_rejected_on_unmatched_items(self, engine: PricingEngine) -> None: + lifetime_plan_id = "11111111-1111-1111-1111-111111111111" + yearly_plan_id = "22222222-2222-2222-2222-222222222222" + + items = [ + PricingItem(code="POINTS_1YR", name="Points 1-Year", category="Points", price=Decimal("2000.00"), plan_id=yearly_plan_id) + ] + coupon = PricingCoupon( + code="LIFETIMEONLY", + category="specific", + discount_type="percentage", + value=Decimal("20.00"), + applicable_plan_ids=(lifetime_plan_id,), + ) + result = engine.calculate( + items=items, + owned_categories=[], + coupon=coupon, + currency="INR", + is_first_purchase=True, + ) + assert result["coupon_discount_amount"] == 0.0 + assert result["coupon_applied"] == "None" + assert result["coupon_error"] == "This promo code is not valid for items in your cart." + assert result["grand_total"] == 2000.0 + + def test_plan_scoped_coupon_applied_on_matched_lifetime_item(self, engine: PricingEngine) -> None: + lifetime_plan_id = "11111111-1111-1111-1111-111111111111" + + items = [ + PricingItem(code="LIFETIME_ALL", name="Lifetime All", category="Lifetime", price=Decimal("10000.00"), plan_id=lifetime_plan_id) + ] + coupon = PricingCoupon( + code="LIFETIMEONLY", + category="specific", + discount_type="percentage", + value=Decimal("20.00"), + applicable_plan_ids=(lifetime_plan_id,), + ) + result = engine.calculate( + items=items, + owned_categories=[], + coupon=coupon, + currency="INR", + is_first_purchase=True, + ) + assert result["coupon_discount_amount"] == 2000.0 + assert result["coupon_error"] is None + assert "LIFETIMEONLY" in result["coupon_applied"] + assert result["grand_total"] == 8000.0 + + def test_plan_scoped_coupon_mixed_cart_applies_only_to_qualifying_spend(self, engine: PricingEngine) -> None: + lifetime_plan_id = "11111111-1111-1111-1111-111111111111" + yearly_plan_id = "22222222-2222-2222-2222-222222222222" + + items = [ + PricingItem(code="POINTS_1YR", name="Points 1-Year", category="Points", price=Decimal("2000.00"), plan_id=yearly_plan_id), + PricingItem(code="LIFETIME_ALL", name="Lifetime All", category="Lifetime", price=Decimal("10000.00"), plan_id=lifetime_plan_id), + ] + coupon = PricingCoupon( + code="LIFETIMEONLY", + category="specific", + discount_type="percentage", + value=Decimal("10.00"), + applicable_plan_ids=(lifetime_plan_id,), + ) + result = engine.calculate( + items=items, + owned_categories=[], + coupon=coupon, + currency="INR", + is_first_purchase=True, + ) + # 10% of 10000 = 1000 discount (does not discount the 2000 1-yr item) + assert result["base_subtotal"] == 12000.0 + assert result["coupon_discount_amount"] == 1000.0 + assert result["grand_total"] == 11000.0 + assert result["coupon_error"] is None + + def test_module_scoped_coupon(self, engine: PricingEngine) -> None: + mod_id = "33333333-3333-3333-3333-333333333333" + other_mod_id = "44444444-4444-4444-4444-444444444444" + + items = [ + PricingItem(code="PLAN_A", name="Plan A", category="Cat", price=Decimal("1000.00"), module_ids=(other_mod_id,)) + ] + coupon = PricingCoupon( + code="MODONLY", + category="specific", + discount_type="flat", + value=Decimal("200.00"), + applicable_module_ids=(mod_id,), + ) + # Unmatched module + res1 = engine.calculate(items=items, owned_categories=[], coupon=coupon, currency="INR", is_first_purchase=True) + assert res1["coupon_discount_amount"] == 0.0 + assert res1["coupon_error"] == "This promo code is not valid for items in your cart." + + # Matched module + items_match = [ + PricingItem(code="PLAN_B", name="Plan B", category="Cat", price=Decimal("1000.00"), module_ids=(mod_id,)) + ] + res2 = engine.calculate(items=items_match, owned_categories=[], coupon=coupon, currency="INR", is_first_purchase=True) + assert res2["coupon_discount_amount"] == 200.0 + assert res2["coupon_error"] is None + def test_introductory_flat_coupon_disables_unit_bundle_discount(self, engine: PricingEngine) -> None: items = [ PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")), -- 2.34.1