acupedia-api/app/features/plans.py

109 lines
4.1 KiB
Python

from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.session import get_db_session
from app.db.models import AccessPlan, AccessPlanModule, Module
router = APIRouter(tags=["Public Plans Catalog"])
@router.get("/plans")
async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> list[dict[str, Any]]:
"""
Returns active subscription plans with dynamic prices in INR & USD
and included clinical module slugs for dynamic storefront rendering.
"""
plans_q = await session.execute(
select(AccessPlan)
.where(AccessPlan.is_active.is_(True))
.order_by(AccessPlan.created_at.asc())
)
all_plans = plans_q.scalars().all()
plan_mods_q = await session.execute(
select(AccessPlanModule.plan_id, Module.slug, Module.name)
.join(Module, AccessPlanModule.module_id == Module.id)
.where(Module.is_active.is_(True))
)
mod_map: dict[str, list[dict[str, str]]] = {}
for pid, slug, name in plan_mods_q.all():
pid_str = str(pid)
if pid_str not in mod_map:
mod_map[pid_str] = []
mod_map[pid_str].append({"slug": slug, "name": name})
groups: dict[str, dict[str, Any]] = {}
for p in all_plans:
code = p.code
is_usd = code.endswith("_USD") or p.currency_code == "USD"
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
base_code = code[:-4] if (code.endswith("_USD") or code.endswith("_EUR")) else code
pid_str = str(p.id)
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
meta = p.metadata_json or {}
if base_code not in groups:
clean_name = (
p.name.replace(" (USD)", "")
.replace(" - USD", "")
.replace(" (EUR)", "")
.replace(" - EUR", "")
)
groups[base_code] = {
"code": base_code,
"name": clean_name,
"description": p.description or "",
"plan_type": getattr(p.plan_type, "value", p.plan_type),
"billing_period": getattr(p.billing_period, "value", p.billing_period),
"price_inr": 0.0,
"price_usd": 0.0,
"price_eur": 0.0,
"is_active": p.is_active,
"badge_text": meta.get("badge_text"),
"heading": meta.get("heading"),
"subtitle": meta.get("subtitle"),
"modules": [],
"module_slugs": [],
"is_featured": meta.get("is_featured", False),
}
grp = groups[base_code]
if is_usd:
grp["price_usd"] = fee
if not grp.get("price_eur"):
grp["price_eur"] = fee # Default fallback if explicit EUR plan not present
elif is_eur:
grp["price_eur"] = fee
else:
grp["price_inr"] = fee
grp["name"] = p.name
grp["description"] = p.description or ""
grp["plan_type"] = getattr(p.plan_type, "value", p.plan_type)
grp["billing_period"] = getattr(p.billing_period, "value", p.billing_period)
grp["is_active"] = p.is_active
grp["is_featured"] = meta.get("is_featured", False)
if meta.get("badge_text"):
grp["badge_text"] = meta.get("badge_text")
if meta.get("heading"):
grp["heading"] = meta.get("heading")
if meta.get("subtitle"):
grp["subtitle"] = meta.get("subtitle")
if pid_str in mod_map and not grp["modules"]:
grp["modules"] = mod_map[pid_str]
grp["module_slugs"] = [m["slug"] for m in mod_map[pid_str]]
result = list(groups.values())
def sort_key(item: dict[str, Any]) -> tuple[int, str]:
if "LIFETIME" in str(item["code"]):
return (0, str(item["name"]))
if item["plan_type"] == "bundle":
return (1, str(item["name"]))
return (2, str(item["name"]))
result.sort(key=sort_key)
return result