Compare commits
No commits in common. "3c31343f6622f72f2ffa0bbb69b2629367b578be" and "9051256b1109afd3a6dd4bd6cb85bced12c35314" have entirely different histories.
3c31343f66
...
9051256b11
|
|
@ -138,73 +138,16 @@ class CartRepository:
|
||||||
min_purchase_amount=min_spend,
|
min_purchase_amount=min_spend,
|
||||||
), None
|
), None
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _module_category(module: Module) -> str:
|
|
||||||
metadata = module.metadata_json or {}
|
|
||||||
cat = metadata.get("commerce_category") or metadata.get("category")
|
|
||||||
if cat:
|
|
||||||
return str(cat)
|
|
||||||
kind = (metadata.get("kind") or "").lower()
|
|
||||||
if kind == "point": return "Points"
|
|
||||||
if kind in {"pattern", "five-elements"}: return "Pattern"
|
|
||||||
if kind == "nutrition": return "Nutrition"
|
|
||||||
if kind in {"therapeutic", "therapeutics"}: return "Therapeutics"
|
|
||||||
|
|
||||||
code = (module.code or "").lower()
|
|
||||||
name = (module.name or "").lower()
|
|
||||||
if code in {"m0001", "m0002", "m0003"} or "point" in name: return "Points"
|
|
||||||
if code.startswith("m001") or code == "m0020" or "pattern" in name or "principles" in name or "stages" in name or "levels" in name: return "Pattern"
|
|
||||||
if code == "m0031" or "nutrition" in name or "food" in name: return "Nutrition"
|
|
||||||
if code.startswith("m004") or "therapeutic" in name or "gynae" in name or "auriculo" in name: return "Therapeutics"
|
|
||||||
return "General"
|
|
||||||
|
|
||||||
async def get_owned_categories(self, user_id: UUID) -> list[str]:
|
async def get_owned_categories(self, user_id: UUID) -> list[str]:
|
||||||
result: set[str] = set()
|
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()
|
||||||
|
result: list[str] = []
|
||||||
# 1. From active UserSubscription
|
for _, module in rows:
|
||||||
sub_plans = (await self.session.execute(
|
metadata = module.metadata_json or {}
|
||||||
select(AccessPlan)
|
category = metadata.get("commerce_category") or metadata.get("category")
|
||||||
.join(UserSubscription, UserSubscription.plan_id == AccessPlan.id)
|
if category:
|
||||||
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
|
result.append(str(category))
|
||||||
)).scalars().all()
|
return result
|
||||||
for plan in sub_plans:
|
|
||||||
cat = self._category(plan)
|
|
||||||
if cat and cat != "General":
|
|
||||||
result.add(cat)
|
|
||||||
|
|
||||||
# 2. From active UserEntitlement via Module
|
|
||||||
ent_modules = (await self.session.execute(
|
|
||||||
select(Module)
|
|
||||||
.join(UserEntitlement, UserEntitlement.module_id == Module.id)
|
|
||||||
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
|
|
||||||
)).scalars().all()
|
|
||||||
for module in ent_modules:
|
|
||||||
cat = self._module_category(module)
|
|
||||||
if cat and cat != "General":
|
|
||||||
result.add(cat)
|
|
||||||
|
|
||||||
# 3. From active UserEntitlement via source_plan_id
|
|
||||||
ent_plans = (await self.session.execute(
|
|
||||||
select(AccessPlan)
|
|
||||||
.join(UserEntitlement, UserEntitlement.source_plan_id == AccessPlan.id)
|
|
||||||
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
|
|
||||||
)).scalars().all()
|
|
||||||
for plan in ent_plans:
|
|
||||||
cat = self._category(plan)
|
|
||||||
if cat and cat != "General":
|
|
||||||
result.add(cat)
|
|
||||||
|
|
||||||
return list(result)
|
|
||||||
|
|
||||||
async def is_first_purchase(self, user_id: UUID) -> bool:
|
async def is_first_purchase(self, user_id: UUID) -> bool:
|
||||||
has_sub = (await self.session.execute(
|
exists = (await self.session.execute(select(UserSubscription.id).where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE).limit(1))).scalar_one_or_none()
|
||||||
select(UserSubscription.id)
|
return exists is None
|
||||||
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
|
|
||||||
.limit(1)
|
|
||||||
)).scalar_one_or_none()
|
|
||||||
has_ent = (await self.session.execute(
|
|
||||||
select(UserEntitlement.id)
|
|
||||||
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
|
|
||||||
.limit(1)
|
|
||||||
)).scalar_one_or_none()
|
|
||||||
return has_sub is None and has_ent is None
|
|
||||||
|
|
|
||||||
|
|
@ -17,10 +17,6 @@ class CartService:
|
||||||
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
|
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)}")
|
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
|
||||||
coupon, coupon_error = 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 []
|
owned = await self.repository.get_owned_categories(user_id) if user_id else request.owned_category_names
|
||||||
if request.owned_category_names:
|
|
||||||
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
|
||||||
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
|
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
|
||||||
if owned:
|
|
||||||
first = False
|
|
||||||
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))
|
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))
|
||||||
|
|
|
||||||
|
|
@ -40,24 +40,18 @@ class PricingEngine:
|
||||||
policy = "Lifetime Bulk Package"
|
policy = "Lifetime Bulk Package"
|
||||||
elif disable_unit:
|
elif disable_unit:
|
||||||
policy = "None (Overridden by New User Event Coupon)"
|
policy = "None (Overridden by New User Event Coupon)"
|
||||||
elif owned_categories or not is_first_purchase:
|
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))
|
n = len(set(owned_categories))
|
||||||
if n and items:
|
if n and items:
|
||||||
rate = min(Decimal("0.05") * n, Decimal("0.25"))
|
rate = min(Decimal("0.05") * n, Decimal("0.25"))
|
||||||
bundle = base * rate
|
bundle = base * rate
|
||||||
policy = f"Loyalty Discount ({int(rate * 100)}% Off)"
|
policy = f"Staggered Buy: {n} owned categories ({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)
|
after_bundle = max(Decimal("0"), base - bundle)
|
||||||
coupon_discount = Decimal("0")
|
coupon_discount = Decimal("0")
|
||||||
coupon_text = "None"
|
coupon_text = "None"
|
||||||
|
|
|
||||||
|
|
@ -84,18 +84,6 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
|
||||||
self.assertEqual(calc.grand_total, 8.0)
|
self.assertEqual(calc.grand_total, 8.0)
|
||||||
self.assertEqual(len(calc.cart_items), 2)
|
self.assertEqual(len(calc.cart_items), 2)
|
||||||
|
|
||||||
async def test_loyalty_discount_with_two_owned_categories(self):
|
|
||||||
calc = await self.service.calculate(CartCalculationRequest(
|
|
||||||
cart_item_codes=["POINTS_ACU"],
|
|
||||||
owned_category_names=["Pattern", "Nutrition"],
|
|
||||||
currency="INR"
|
|
||||||
))
|
|
||||||
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)
|
|
||||||
|
|
||||||
async def test_unknown_plan_raises_error(self):
|
async def test_unknown_plan_raises_error(self):
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
await self.service.calculate(CartCalculationRequest(
|
await self.service.calculate(CartCalculationRequest(
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue