Merge pull request 'fixed-issue(3): enabled automatic loyalty discount for owned categories' (#12) from loyalty-discount into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-api/pulls/12 Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
commit
3c31343f66
|
|
@ -138,16 +138,73 @@ class CartRepository:
|
|||
min_purchase_amount=min_spend,
|
||||
), 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]:
|
||||
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] = []
|
||||
for _, module in rows:
|
||||
metadata = module.metadata_json or {}
|
||||
category = metadata.get("commerce_category") or metadata.get("category")
|
||||
if category:
|
||||
result.append(str(category))
|
||||
return result
|
||||
result: set[str] = set()
|
||||
|
||||
# 1. From active UserSubscription
|
||||
sub_plans = (await self.session.execute(
|
||||
select(AccessPlan)
|
||||
.join(UserSubscription, UserSubscription.plan_id == AccessPlan.id)
|
||||
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
|
||||
)).scalars().all()
|
||||
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:
|
||||
exists = (await self.session.execute(select(UserSubscription.id).where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE).limit(1))).scalar_one_or_none()
|
||||
return exists is None
|
||||
has_sub = (await self.session.execute(
|
||||
select(UserSubscription.id)
|
||||
.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,6 +17,10 @@ class CartService:
|
|||
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)}")
|
||||
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 request.owned_category_names
|
||||
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
||||
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
|
||||
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))
|
||||
|
|
|
|||
|
|
@ -40,18 +40,24 @@ class PricingEngine:
|
|||
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)"
|
||||
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)
|
||||
coupon_discount = Decimal("0")
|
||||
coupon_text = "None"
|
||||
|
|
|
|||
|
|
@ -84,6 +84,18 @@ 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):
|
||||
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):
|
||||
with self.assertRaises(ValueError):
|
||||
await self.service.calculate(CartCalculationRequest(
|
||||
|
|
|
|||
Loading…
Reference in New Issue