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, 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 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] = [] 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)) return items async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None: if not code: return None now = datetime.now(timezone.utc) coupon = (await self.session.execute(select(Coupon).where(Coupon.code == code.strip().upper(), Coupon.is_active.is_(True), Coupon.start_date <= now, Coupon.end_date >= now))).scalar_one_or_none() if not coupon: return None metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {} value = Decimal(coupon.value) if coupon.discount_type == "flat": 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()])) 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)) 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 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