fix(cart): resolve currency-specific access plans dynamically for cart calculation and checkout
This commit is contained in:
parent
64d5097e1b
commit
a9604759b9
|
|
@ -25,24 +25,65 @@ class CartRepository:
|
||||||
if code.startswith("THERAPEUTIC"): return "Therapeutics"
|
if code.startswith("THERAPEUTIC"): return "Therapeutics"
|
||||||
return str(metadata.get("access_group") or "General")
|
return str(metadata.get("access_group") or "General")
|
||||||
|
|
||||||
async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]:
|
async def get_plan_matches(self, codes: list[str], currency: str) -> dict[str, tuple[AccessPlan, Decimal]]:
|
||||||
|
curr = currency.strip().upper()
|
||||||
normalized = [c.strip().upper() for c in codes if c.strip()]
|
normalized = [c.strip().upper() for c in codes if c.strip()]
|
||||||
rows = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_(normalized), AccessPlan.is_active.is_(True)))).scalars().all()
|
if not normalized:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
curr_rows = (await self.session.execute(
|
||||||
|
select(AccessPlan.currency_code).where(AccessPlan.is_active.is_(True)).distinct()
|
||||||
|
)).scalars().all()
|
||||||
|
known_currencies = {c.upper() for c in curr_rows if c}
|
||||||
|
known_currencies.add(curr)
|
||||||
|
|
||||||
|
candidates: set[str] = set()
|
||||||
|
code_candidates_map: dict[str, list[str]] = {}
|
||||||
|
for code in normalized:
|
||||||
|
cands: list[str] = []
|
||||||
|
base = code
|
||||||
|
parts = code.rsplit("_", 1)
|
||||||
|
if len(parts) == 2 and parts[1] in known_currencies:
|
||||||
|
base = parts[0]
|
||||||
|
|
||||||
|
for cand in [f"{base}_{curr}", code, base]:
|
||||||
|
if cand not in cands:
|
||||||
|
cands.append(cand)
|
||||||
|
code_candidates_map[code] = cands
|
||||||
|
candidates.update(cands)
|
||||||
|
|
||||||
|
rows = (await self.session.execute(
|
||||||
|
select(AccessPlan).where(AccessPlan.code.in_(candidates), AccessPlan.is_active.is_(True))
|
||||||
|
)).scalars().all()
|
||||||
by_code = {p.code.upper(): p for p in rows}
|
by_code = {p.code.upper(): p for p in rows}
|
||||||
|
|
||||||
|
matches: dict[str, tuple[AccessPlan, Decimal]] = {}
|
||||||
|
for code in normalized:
|
||||||
|
cands = code_candidates_map[code]
|
||||||
|
for cand in cands:
|
||||||
|
plan = by_code.get(cand)
|
||||||
|
if not plan:
|
||||||
|
continue
|
||||||
|
metadata = plan.metadata_json or {}
|
||||||
|
prices = metadata.get("prices") if isinstance(metadata, dict) else None
|
||||||
|
if isinstance(prices, dict) and curr in prices:
|
||||||
|
matches[code] = (plan, Decimal(str(prices[curr])))
|
||||||
|
break
|
||||||
|
elif plan.currency_code.upper() == curr:
|
||||||
|
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
|
||||||
|
matches[code] = (plan, Decimal(str(fee)))
|
||||||
|
break
|
||||||
|
|
||||||
|
return matches
|
||||||
|
|
||||||
|
async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]:
|
||||||
|
matches = await self.get_plan_matches(codes, currency)
|
||||||
|
normalized = [c.strip().upper() for c in codes if c.strip()]
|
||||||
items: list[PricingItem] = []
|
items: list[PricingItem] = []
|
||||||
for code in normalized:
|
for code in normalized:
|
||||||
plan = by_code.get(code)
|
if code in matches:
|
||||||
if not plan:
|
plan, price = matches[code]
|
||||||
continue
|
items.append(PricingItem(code=code, name=plan.name, category=self._category(plan), price=price))
|
||||||
metadata = plan.metadata_json or {}
|
|
||||||
prices = metadata.get("prices") if isinstance(metadata, dict) else None
|
|
||||||
if isinstance(prices, dict) and currency.upper() in prices:
|
|
||||||
price = Decimal(str(prices[currency.upper()]))
|
|
||||||
elif plan.currency_code.upper() == currency.upper():
|
|
||||||
price = Decimal(plan.total_fee)
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price))
|
|
||||||
return items
|
return items
|
||||||
|
|
||||||
async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None:
|
async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None:
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,13 @@ class CheckoutService:
|
||||||
pass
|
pass
|
||||||
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
||||||
order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""})
|
order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""})
|
||||||
plans = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_([c.upper() for c in request.cart_item_codes]), AccessPlan.is_active.is_(True)))).scalars().all()
|
plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency)
|
||||||
|
seen_plan_ids = set()
|
||||||
|
plans: list[AccessPlan] = []
|
||||||
|
for plan, _ in plan_matches.values():
|
||||||
|
if plan.id not in seen_plan_ids:
|
||||||
|
seen_plan_ids.add(plan.id)
|
||||||
|
plans.append(plan)
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency}
|
pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency}
|
||||||
for plan in plans:
|
for plan in plans:
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,95 @@
|
||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from decimal import Decimal
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||||
|
from sqlalchemy.pool import NullPool
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.features.cart.repository import CartRepository
|
||||||
|
from app.features.cart.service import CartService
|
||||||
|
from app.features.cart.schema import CartCalculationRequest
|
||||||
|
|
||||||
|
class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.engine = create_async_engine(settings.database_url, poolclass=NullPool)
|
||||||
|
self.session_factory = async_sessionmaker(bind=self.engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
self.session = self.session_factory()
|
||||||
|
self.repo = CartRepository(self.session)
|
||||||
|
self.service = CartService(self.repo)
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.session.close()
|
||||||
|
await self.engine.dispose()
|
||||||
|
|
||||||
|
async def test_resolve_points_acu_usd(self):
|
||||||
|
items = await self.repo.get_items(["POINTS_ACU"], "USD")
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
self.assertEqual(items[0].code, "POINTS_ACU")
|
||||||
|
self.assertEqual(items[0].price, Decimal("5.00"))
|
||||||
|
|
||||||
|
async def test_resolve_points_acu_inr(self):
|
||||||
|
items = await self.repo.get_items(["POINTS_ACU"], "INR")
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
self.assertEqual(items[0].code, "POINTS_ACU")
|
||||||
|
self.assertEqual(items[0].price, Decimal("300.00"))
|
||||||
|
|
||||||
|
async def test_resolve_suffixed_code_usd(self):
|
||||||
|
items = await self.repo.get_items(["POINTS_ACU_USD"], "USD")
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
self.assertEqual(items[0].code, "POINTS_ACU_USD")
|
||||||
|
self.assertEqual(items[0].price, Decimal("5.00"))
|
||||||
|
|
||||||
|
async def test_resolve_lifetime_all_usd(self):
|
||||||
|
items = await self.repo.get_items(["LIFETIME_ALL"], "USD")
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
self.assertEqual(items[0].code, "LIFETIME_ALL")
|
||||||
|
self.assertEqual(items[0].price, Decimal("350.00"))
|
||||||
|
|
||||||
|
async def test_resolve_lifetime_all_inr(self):
|
||||||
|
items = await self.repo.get_items(["LIFETIME_ALL"], "INR")
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
self.assertEqual(items[0].code, "LIFETIME_ALL")
|
||||||
|
self.assertEqual(items[0].price, Decimal("15000.00"))
|
||||||
|
|
||||||
|
async def test_calculate_usd_cart(self):
|
||||||
|
calc = await self.service.calculate(CartCalculationRequest(
|
||||||
|
cart_item_codes=["POINTS_ACU"],
|
||||||
|
currency="USD"
|
||||||
|
))
|
||||||
|
self.assertEqual(calc.currency, "USD")
|
||||||
|
self.assertEqual(calc.base_subtotal, 5.0)
|
||||||
|
self.assertEqual(calc.convenience_fee, 0.15)
|
||||||
|
self.assertEqual(calc.grand_total, 5.15)
|
||||||
|
self.assertEqual(len(calc.cart_items), 1)
|
||||||
|
self.assertEqual(calc.cart_items[0].code, "POINTS_ACU")
|
||||||
|
|
||||||
|
async def test_calculate_inr_cart(self):
|
||||||
|
calc = await self.service.calculate(CartCalculationRequest(
|
||||||
|
cart_item_codes=["POINTS_ACU"],
|
||||||
|
currency="INR"
|
||||||
|
))
|
||||||
|
self.assertEqual(calc.currency, "INR")
|
||||||
|
self.assertEqual(calc.base_subtotal, 300.0)
|
||||||
|
self.assertEqual(calc.convenience_fee, 6.0)
|
||||||
|
self.assertEqual(calc.gst_amount, 1.08)
|
||||||
|
self.assertEqual(calc.grand_total, 307.08)
|
||||||
|
|
||||||
|
async def test_multi_item_usd_cart(self):
|
||||||
|
calc = await self.service.calculate(CartCalculationRequest(
|
||||||
|
cart_item_codes=["POINTS_ACU", "POINTS_EAR"],
|
||||||
|
currency="USD"
|
||||||
|
))
|
||||||
|
self.assertEqual(calc.currency, "USD")
|
||||||
|
self.assertEqual(calc.base_subtotal, 8.0)
|
||||||
|
self.assertEqual(calc.convenience_fee, 0.24)
|
||||||
|
self.assertEqual(calc.grand_total, 8.24)
|
||||||
|
self.assertEqual(len(calc.cart_items), 2)
|
||||||
|
|
||||||
|
async def test_unknown_plan_raises_error(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
await self.service.calculate(CartCalculationRequest(
|
||||||
|
cart_item_codes=["NON_EXISTENT_PLAN_XYZ"],
|
||||||
|
currency="USD"
|
||||||
|
))
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loading…
Reference in New Issue