Merge pull request 'bug(invalid-discount): removed unintended legacy staggered cross-module discount calculation, implemented discount rules from the docs' (#16) from discount-issue into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-api/pulls/16 Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
commit
75aae4902d
|
|
@ -93,14 +93,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]:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ class PricingItem:
|
|||
name: str
|
||||
category: str
|
||||
price: Decimal
|
||||
is_renewal: bool = False
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PricingCoupon:
|
||||
|
|
@ -26,69 +27,52 @@ class PricingCoupon:
|
|||
min_purchase_amount: 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 owned_categories or not is_first_purchase:
|
||||
n = len(set(owned_categories))
|
||||
if n and items:
|
||||
rate = min(Decimal("0.05") * n, Decimal("0.25"))
|
||||
bundle = base * rate
|
||||
policy = f"Loyalty Discount ({int(rate * 100)}% Off)"
|
||||
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)"
|
||||
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)"
|
||||
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:
|
||||
if coupon.min_purchase_amount > 0 and after_bundle < coupon.min_purchase_amount:
|
||||
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}."
|
||||
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_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)
|
||||
grand = q(net)
|
||||
return {
|
||||
"currency": curr,
|
||||
"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": 0.0,
|
||||
"convenience_fee": 0.0,
|
||||
"taxable_amount": 0.0,
|
||||
"gst_amount": 0.0,
|
||||
"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],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
|
|||
self.assertEqual(calc.grand_total, 8.0)
|
||||
self.assertEqual(len(calc.cart_items), 2)
|
||||
|
||||
async def test_loyalty_discount_with_two_owned_categories(self):
|
||||
async def test_no_unintended_bundle_discount_for_other_categories(self):
|
||||
calc = await self.service.calculate(CartCalculationRequest(
|
||||
cart_item_codes=["POINTS_ACU"],
|
||||
owned_category_names=["Pattern", "Nutrition"],
|
||||
|
|
@ -92,9 +92,9 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
|
|||
))
|
||||
self.assertEqual(calc.currency, "INR")
|
||||
self.assertEqual(calc.base_subtotal, 300.0)
|
||||
self.assertEqual(calc.bundle_discount_amount, 30.0)
|
||||
self.assertEqual(calc.discount_policy, "Loyalty Discount (10% Off)")
|
||||
self.assertEqual(calc.grand_total, 270.0)
|
||||
self.assertEqual(calc.bundle_discount_amount, 0.0)
|
||||
self.assertEqual(calc.renewal_discount_amount, 0.0)
|
||||
self.assertEqual(calc.grand_total, 300.0)
|
||||
|
||||
async def test_unknown_plan_raises_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
|
|
|
|||
Loading…
Reference in New Issue