bug(invalid-discount): removed unintended legacy staggered cross-module discount calculation, implemented discount rules from the docs #16

Merged
amit merged 2 commits from discount-issue into main 2026-10-20 04:50:49 +00:00
5 changed files with 75 additions and 33 deletions
Showing only changes of commit f8917f013a - Show all commits

View File

@ -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]:

View File

@ -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

View File

@ -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]

View File

@ -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()

View File

@ -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],
}