284 lines
13 KiB
Python
284 lines
13 KiB
Python
from __future__ import annotations
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
from uuid import UUID
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
|
from app.db.models import AccessPlan, AccessPlanModule, Coupon, Module, UserEntitlement, UserSubscription
|
|
from app.features.payments.pricing import PricingCoupon, PricingItem
|
|
|
|
class CartRepository:
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
|
|
@staticmethod
|
|
def _category(plan: AccessPlan) -> str:
|
|
metadata = plan.metadata_json or {}
|
|
if metadata.get("category"):
|
|
return str(metadata["category"])
|
|
code = plan.code.upper()
|
|
if code == "LIFETIME_ALL": return "Lifetime"
|
|
if code.startswith("POINT"): return "Points"
|
|
if code.startswith("PATTERN"): return "Pattern"
|
|
if code.startswith("NUTRITION"): return "Nutrition"
|
|
if code.startswith("THERAPEUTIC"): return "Therapeutics"
|
|
return str(metadata.get("access_group") or "General")
|
|
|
|
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()]
|
|
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}
|
|
|
|
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
|
|
|
|
if code not in matches:
|
|
for cand in cands:
|
|
plan = by_code.get(cand)
|
|
if not plan:
|
|
continue
|
|
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
|
|
plan_curr = plan.currency_code.upper()
|
|
if plan_curr == "INR" and curr == "USD":
|
|
matches[code] = (plan, max(Decimal("1.00"), (Decimal(str(fee)) / Decimal("80")).quantize(Decimal("1.00"))))
|
|
break
|
|
elif plan_curr == "USD" and curr == "INR":
|
|
matches[code] = (plan, (Decimal(str(fee)) * Decimal("80")).quantize(Decimal("1.00")))
|
|
break
|
|
elif fee is not None:
|
|
matches[code] = (plan, Decimal(str(fee)))
|
|
break
|
|
|
|
return matches
|
|
|
|
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()
|
|
|
|
plan_ids = [plan.id for plan, _ in matches.values()]
|
|
plan_module_map: dict[str, list[str]] = {}
|
|
if plan_ids:
|
|
apm_rows = (await self.session.execute(
|
|
select(AccessPlanModule.plan_id, AccessPlanModule.module_id)
|
|
.where(AccessPlanModule.plan_id.in_(plan_ids))
|
|
)).all()
|
|
for pid, mid in apm_rows:
|
|
plan_module_map.setdefault(str(pid), []).append(str(mid))
|
|
|
|
for code in normalized:
|
|
if code in matches:
|
|
plan, price = matches[code]
|
|
is_renewal = (code in ren) or (plan.code.upper() in ren)
|
|
p_str = str(plan.id)
|
|
m_ids = tuple(plan_module_map.get(p_str, []))
|
|
items.append(PricingItem(
|
|
code=code,
|
|
name=plan.name,
|
|
category=self._category(plan),
|
|
price=price,
|
|
is_renewal=is_renewal,
|
|
plan_id=p_str,
|
|
module_ids=m_ids,
|
|
))
|
|
return items
|
|
|
|
async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
|
|
if not code or not code.strip():
|
|
return None, None
|
|
clean_code = code.strip().upper()
|
|
now = datetime.now(timezone.utc)
|
|
coupon = (await self.session.execute(select(Coupon).where(Coupon.code == clean_code))).scalar_one_or_none()
|
|
if not coupon:
|
|
return None, "Invalid or expired coupon code."
|
|
if not coupon.is_active:
|
|
return None, "This coupon code is currently inactive."
|
|
s_date = coupon.start_date.replace(tzinfo=timezone.utc) if coupon.start_date.tzinfo is None else coupon.start_date
|
|
e_date = coupon.end_date.replace(tzinfo=timezone.utc) if coupon.end_date.tzinfo is None else coupon.end_date
|
|
if now < s_date:
|
|
return None, "This coupon code is not active yet."
|
|
if now > e_date:
|
|
return None, "This coupon code has expired."
|
|
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
|
|
return None, "Coupon usage limit reached."
|
|
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
|
|
value = Decimal(coupon.value)
|
|
if coupon.discount_type in {"flat", "flat_amount"}:
|
|
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
|
|
if isinstance(currency_values, dict) and currency.upper() in currency_values:
|
|
value = Decimal(str(currency_values[currency.upper()]))
|
|
min_spend = Decimal(str(coupon.min_purchase_amount or 0))
|
|
|
|
app_plan_ids: set[str] = set()
|
|
if coupon.applicable_plan_ids:
|
|
for pid in coupon.applicable_plan_ids:
|
|
app_plan_ids.add(str(pid))
|
|
# Include paired currency versions (e.g. LIFETIME_ALL and LIFETIME_ALL_USD)
|
|
p_rows = (await self.session.execute(
|
|
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
|
|
)).scalars().all()
|
|
base_codes: set[str] = set()
|
|
for c in p_rows:
|
|
code_up = c.upper()
|
|
base_codes.add(code_up[:-4] if code_up.endswith("_USD") else code_up)
|
|
if base_codes:
|
|
sibling_codes: set[str] = set()
|
|
for bc in base_codes:
|
|
sibling_codes.add(bc)
|
|
sibling_codes.add(f"{bc}_USD")
|
|
sibling_rows = (await self.session.execute(
|
|
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
|
|
)).scalars().all()
|
|
for sid in sibling_rows:
|
|
app_plan_ids.add(str(sid))
|
|
|
|
app_mod_ids = tuple(str(mid) for mid in coupon.applicable_module_ids) if coupon.applicable_module_ids else ()
|
|
|
|
return PricingCoupon(
|
|
code=coupon.code,
|
|
category=coupon.coupon_category,
|
|
discount_type=coupon.discount_type,
|
|
value=value,
|
|
description=coupon.description,
|
|
max_discount_limit=Decimal(coupon.max_discount_limit or 0),
|
|
min_purchase_amount=min_spend,
|
|
applicable_plan_ids=tuple(app_plan_ids),
|
|
applicable_module_ids=app_mod_ids,
|
|
), 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]:
|
|
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:
|
|
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
|