From f8917f013a475348f44c57b0706e999068005364 Mon Sep 17 00:00:00 2001 From: Urvish Date: Wed, 14 Oct 2026 16:06:04 +0530 Subject: [PATCH] bug(invalid-discount): removed unintended legacy staggered cross-module discount calculation, implemented discount rules from the docs --- app/features/cart/repository.py | 28 ++++++++++++++++++-- app/features/cart/schema.py | 2 ++ app/features/cart/service.py | 3 ++- app/features/checkout/service.py | 31 +++++++++++++++++++--- app/features/payments/pricing.py | 44 ++++++++++++-------------------- 5 files changed, 75 insertions(+), 33 deletions(-) diff --git a/app/features/cart/repository.py b/app/features/cart/repository.py index 6573f3b..7a4af17 100644 --- a/app/features/cart/repository.py +++ b/app/features/cart/repository.py @@ -76,14 +76,38 @@ class CartRepository: return matches - async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]: + async def get_renewable_plan_codes(self, user_id: UUID) -> set[str]: + now = datetime.now(timezone.utc) + stmt = ( + select(AccessPlan.code) + .join(UserSubscription, UserSubscription.plan_id == AccessPlan.id) + .where( + UserSubscription.user_id == user_id, + UserSubscription.status == SubscriptionStatus.ACTIVE, + UserSubscription.expires_at > now, + ) + ) + plan_codes = (await self.session.execute(stmt)).scalars().all() + renewable: set[str] = set() + for c in plan_codes: + code = c.strip().upper() + renewable.add(code) + if code.endswith("_USD"): + renewable.add(code[:-4]) + else: + renewable.add(f"{code}_USD") + return renewable + + async def get_items(self, codes: list[str], currency: str, renewable_codes: set[str] | None = None) -> list[PricingItem]: matches = await self.get_plan_matches(codes, currency) normalized = [c.strip().upper() for c in codes if c.strip()] items: list[PricingItem] = [] + ren = renewable_codes or set() for code in normalized: if code in matches: plan, price = matches[code] - items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price)) + 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)) return items async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]: diff --git a/app/features/cart/schema.py b/app/features/cart/schema.py index f94048d..7030880 100644 --- a/app/features/cart/schema.py +++ b/app/features/cart/schema.py @@ -14,12 +14,14 @@ class CartItemResponse(BaseModel): name: str category: str price: float + is_renewal: bool = False class CartCalculationResponse(BaseModel): currency: str base_subtotal: float discount_policy: str bundle_discount_amount: float + renewal_discount_amount: float = 0.0 coupon_applied: str coupon_discount_amount: float coupon_error: str | None = None diff --git a/app/features/cart/service.py b/app/features/cart/service.py index 1538c0a..1da1361 100644 --- a/app/features/cart/service.py +++ b/app/features/cart/service.py @@ -11,7 +11,8 @@ class CartService: async def calculate(self, request: CartCalculationRequest, user_id: UUID | None = None) -> CartCalculationResponse: currency = request.currency.upper() - items = await self.repository.get_items(request.cart_item_codes, currency) + renewable_codes = await self.repository.get_renewable_plan_codes(user_id) if user_id else set() + items = await self.repository.get_items(request.cart_item_codes, currency, renewable_codes=renewable_codes) if len(items) != len({c.strip().upper() for c in request.cart_item_codes if c.strip()}): resolved = {i.code.upper() for i in items} missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved] diff --git a/app/features/checkout/service.py b/app/features/checkout/service.py index be8280f..836b8aa 100644 --- a/app/features/checkout/service.py +++ b/app/features/checkout/service.py @@ -76,13 +76,38 @@ class CheckoutService: plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none() sub.status = SubscriptionStatus.ACTIVE sub.started_at = now - sub.expires_at = now + timedelta(days=3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365) + + # If user already had an active unexpired subscription for this plan, extend from previous expiry + prev_sub = (await self.session.execute( + select(UserSubscription) + .where( + UserSubscription.user_id == user.id, + UserSubscription.plan_id == sub.plan_id, + UserSubscription.id != sub.id, + UserSubscription.status == SubscriptionStatus.ACTIVE, + UserSubscription.expires_at > now + ).order_by(UserSubscription.expires_at.desc()).limit(1) + )).scalar_one_or_none() + + base_expiry = prev_sub.expires_at if prev_sub and prev_sub.expires_at else now + extension_days = 3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365 + sub.expires_at = base_expiry + timedelta(days=extension_days) + if plan: plan_names.append(plan.name) module_ids = (await self.session.execute(select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id))).scalars().all() for module_id in module_ids: - active = (await self.session.execute(select(UserEntitlement.id).where(UserEntitlement.user_id == user.id, UserEntitlement.module_id == module_id, UserEntitlement.status == EntitlementStatus.ACTIVE).limit(1))).scalar_one_or_none() - if active is None: + active_ent = (await self.session.execute( + select(UserEntitlement) + .where( + UserEntitlement.user_id == user.id, + UserEntitlement.module_id == module_id, + UserEntitlement.status == EntitlementStatus.ACTIVE + ).limit(1) + )).scalar_one_or_none() + if active_ent: + active_ent.expires_at = sub.expires_at + else: self.session.add(UserEntitlement(user_id=user.id, module_id=module_id, source_subscription_id=sub.id, source_plan_id=sub.plan_id, status=EntitlementStatus.ACTIVE, granted_at=now, grant_reason="subscription_purchase", expires_at=sub.expires_at)) invoice_number, invoice_url = await self._create_invoice(rzp, transaction, profile, payment, plan_names, meta) await self.session.commit() diff --git a/app/features/payments/pricing.py b/app/features/payments/pricing.py index 2afa258..6ca0add 100644 --- a/app/features/payments/pricing.py +++ b/app/features/payments/pricing.py @@ -14,6 +14,7 @@ class PricingItem: name: str category: str price: Decimal + is_renewal: bool = False @dataclass(frozen=True) class PricingCoupon: @@ -25,44 +26,32 @@ class PricingCoupon: max_discount_limit: Decimal = Decimal("0") class PricingEngine: - """Preserves the legacy bundle/loyalty/fee rules while sourcing prices from commerce.access_plans.""" + """Calculates checkout totals with Policy 5.1 Early Renewal Discount (20%) and coupon discounts.""" 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} - has_lifetime = any(i.category.lower() == "lifetime" or i.code == "LIFETIME_ALL" for i in items) + + # Policy 5.1: 20% Early Renewal Discount for modules renewed within validity + renewal_discount = sum( + (q(item.price * Decimal("0.20")) for item in items if item.is_renewal), + Decimal("0") + ) bundle = Decimal("0") - policy = "None" - disable_unit = bool(is_first_purchase and coupon and coupon.category == "introductory" and coupon.discount_type == "flat") - if has_lifetime: - policy = "Lifetime Bulk Package" - elif disable_unit: - policy = "None (Overridden by New User Event Coupon)" - elif is_first_purchase: - n = len(categories) - rate = Decimal("0.10") if n == 2 else Decimal("0.20") if n == 3 else Decimal("0.30") if n >= 4 else Decimal("0") - bundle = base * rate - if rate: - policy = f"First-time Buy: {n if n < 4 else '4+'} Units ({int(rate * 100)}% Off)" - else: - n = len(set(owned_categories)) - if n and items: - rate = min(Decimal("0.05") * n, Decimal("0.25")) - bundle = base * rate - policy = f"Staggered Buy: {n} owned categories ({int(rate * 100)}% Off)" - after_bundle = max(Decimal("0"), base - bundle) + policy = "Early Renewal (20% Off)" if renewal_discount > Decimal("0") else "None" + after_renewal = max(Decimal("0"), base - renewal_discount) + coupon_discount = Decimal("0") coupon_text = "None" if coupon: coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -") if coupon.discount_type in {"flat", "flat_amount"}: - coupon_discount = min(coupon.value, after_bundle) + coupon_discount = min(coupon.value, after_renewal) elif coupon.discount_type in {"percentage", "percent"}: - coupon_discount = after_bundle * (coupon.value / Decimal("100")) + coupon_discount = after_renewal * (coupon.value / Decimal("100")) if coupon.max_discount_limit > 0: coupon_discount = min(coupon_discount, coupon.max_discount_limit) - net = max(Decimal("0"), after_bundle - coupon_discount) + net = max(Decimal("0"), after_renewal - coupon_discount) fee_rate = Decimal("0.02") if curr == "INR" else Decimal("0.03") fee = q(net * fee_rate) gst = q(fee * Decimal("0.18")) if curr == "INR" else Decimal("0") @@ -72,14 +61,15 @@ class PricingEngine: "base_subtotal": float(q(base)), "discount_policy": policy, "bundle_discount_amount": float(q(bundle)), + "renewal_discount_amount": float(q(renewal_discount)), "coupon_applied": coupon_text, "coupon_discount_amount": float(q(coupon_discount)), "coupon_error": coupon_error, - "total_discounts": float(q(bundle + coupon_discount)), + "total_discounts": float(q(renewal_discount + coupon_discount)), "convenience_fee_rate": float(fee_rate * 100), "convenience_fee": float(fee), "taxable_amount": float(fee), "gst_amount": float(gst), "grand_total": float(grand), - "cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price))} for i in items], + "cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price)), "is_renewal": i.is_renewal} for i in items], }