feat/dynamic-catalog-pricing-api #50

Merged
amit merged 4 commits from feat/dynamic-catalog-pricing-api into main 2026-12-04 05:25:52 +00:00
10 changed files with 379 additions and 13 deletions

View File

@ -16,6 +16,7 @@ from .schema import (
LIFETIME_PLAN_CODES = frozenset({
"LIFETIME_ALL",
"LIFETIME_ALL_USD",
"LIFETIME_ALL_EUR",
})

View File

@ -419,6 +419,8 @@ async def update_plan_status(
return await service.toggle_plan_status(plan_code, payload.is_active)
except LookupError as exc:
raise HTTPException(404, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(400, detail=str(exc)) from exc
# =============================================================================

View File

@ -78,6 +78,7 @@ class PlanPricingUpdateRequest(BaseModel):
badge_text: str | None = None
heading: str | None = None
subtitle: str | None = None
module_ids: list[str] | None = None
class PlanStatusUpdateRequest(BaseModel):
is_active: bool

View File

@ -101,7 +101,42 @@ class ModuleBuilderService:
self, module_code: str, repo_root: Any = None
) -> dict[str, Any]:
await self._verify_module_editable(module_code)
return await self.compiler.sync_to_content_repo(module_code, repo_root=repo_root)
result = await self.compiler.sync_to_content_repo(module_code, repo_root=repo_root)
target_dir = result.get("target_dir")
if target_dir:
from pathlib import Path
from app.bootstrap.seed_content.orchestrator import SeedOrchestrator
modules_root = Path(target_dir).parent
config_path = modules_root / "config.json"
if config_path.exists():
from app.bootstrap.seed_content.orchestrator import SeedOrchestrator
clean_code = module_code.strip().lower()
existing_mod = (
await self.session.execute(select(Module).where(Module.code == clean_code))
).scalar_one_or_none()
if existing_mod is None:
if self.session.in_transaction():
await self.session.commit()
summaries = await SeedOrchestrator(self.session).process_config(
config_path=config_path,
modules_root=modules_root,
module_codes={clean_code},
publish_content=True,
skip_search_facets=True,
)
result["db_synced"] = bool(summaries)
else:
result["db_synced"] = True
from .plan_service import AdminPlanService
pending_plan_code = await AdminPlanService(self.session).ensure_pending_pricing_plan_for_module(module_code)
if pending_plan_code:
result["pending_plan_code"] = pending_plan_code
return result
# =========================================================================
# MODULES

View File

@ -362,7 +362,6 @@ class ModuleContentCompiler:
master_detail_items.append({
"code": source_code,
"slug": f"{module_code}-ct0005-{source_code}",
"name": pat.name,
"title": f"{dis.name} - {pat.name}",
"pattern_name": pat.name,
"pattern_number": p_idx + 1,

View File

@ -1,7 +1,7 @@
from __future__ import annotations
from decimal import Decimal
from uuid import UUID
from sqlalchemy import select, func
from sqlalchemy import delete, select, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, PlanType, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Module, UserSubscription
@ -109,6 +109,8 @@ class AdminPlanService:
grp["heading"] = meta.get("heading")
if meta.get("subtitle"):
grp["subtitle"] = meta.get("subtitle")
if meta.get("pricing_status"):
grp["pricing_status"] = meta.get("pricing_status")
grp["subscribers_count"] += sub_counts.get(p_str, 0)
mods = plan_mods_map.get(p_str, [])
@ -291,8 +293,27 @@ class AdminPlanService:
meta["heading"] = payload.heading
if payload.subtitle is not None:
meta["subtitle"] = payload.subtitle
if float(p.module_fee or 0) > 0:
meta["pricing_status"] = "configured"
p.metadata_json = meta
if payload.module_ids is not None:
plan_ids = [p.id for p in plans]
await self.session.execute(
delete(AccessPlanModule).where(AccessPlanModule.plan_id.in_(plan_ids))
)
seen_mids: list[UUID] = []
for mid_str in payload.module_ids:
try:
mid = UUID(mid_str)
except Exception:
continue
if mid not in seen_mids:
seen_mids.append(mid)
for p in plans:
for mid in seen_mids:
self.session.add(AccessPlanModule(plan_id=p.id, module_id=mid))
await self.session.commit()
return {"status": "success", "message": f"Pricing and metadata for plan '{base_code}' updated successfully."}
@ -304,6 +325,15 @@ class AdminPlanService:
if not plans:
raise LookupError(f"No access plans found matching code '{base_code}'.")
if is_active:
has_pending = any((p.metadata_json or {}).get("pricing_status") == "pending_pricing" for p in plans)
has_positive_price = any(float(p.module_fee or 0) > 0 for p in plans)
is_free = any((p.metadata_json or {}).get("is_free") is True for p in plans)
if has_pending or (not has_positive_price and not is_free):
raise ValueError(
"Cannot activate plan before pricing is configured. Please set INR/USD/EUR prices via Edit Info & Price first."
)
for p in plans:
p.is_active = is_active
await self.session.commit()
@ -312,3 +342,67 @@ class AdminPlanService:
"message": f"Plan '{base_code}' has been {'activated' if is_active else 'deactivated'}.",
"is_active": is_active,
}
async def ensure_pending_pricing_plan_for_module(self, module_code: str) -> str | None:
"""Auto-create an inactive 'pending_pricing' single-module plan if none exists."""
clean_code = module_code.strip()
module = (
await self.session.execute(
select(Module).where(func.lower(Module.code) == clean_code.lower())
)
).scalar_one_or_none()
if module is None:
return None
# Check if module already belongs to any single-module one_time plan
existing_links = (
await self.session.execute(
select(AccessPlan)
.join(AccessPlanModule, AccessPlanModule.plan_id == AccessPlan.id)
.where(
AccessPlanModule.module_id == module.id,
AccessPlan.plan_type == PlanType.ONE_TIME,
)
)
).scalars().all()
if existing_links:
return None
base_code = f"MOD_{clean_code.upper()}"
existing_code = (
await self.session.execute(
select(AccessPlan.id).where(
AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"])
)
)
).scalars().first()
if existing_code:
return base_code
meta = {"pricing_status": "pending_pricing"}
desc = module.description or ""
tiers = [
(base_code, module.name, "INR", "India"),
(f"{base_code}_USD", f"{module.name} (USD)", "USD", "International"),
(f"{base_code}_EUR", f"{module.name} (EUR)", "EUR", "European Union"),
]
for code, name, currency, country in tiers:
plan = AccessPlan(
code=code,
name=name,
description=desc,
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
member_fee=Decimal(0),
module_fee=Decimal(0),
currency_code=currency,
country=country,
is_active=False,
metadata_json=dict(meta),
)
self.session.add(plan)
await self.session.flush()
self.session.add(AccessPlanModule(plan_id=plan.id, module_id=module.id))
await self.session.commit()
return base_code

View File

@ -94,6 +94,7 @@ class ModuleResponse(BaseModel):
updated_by: UUID | None = None
created_at: datetime
updated_at: datetime
plan_code: str | None = None
class ModuleListResponse(BaseModel):

View File

@ -125,12 +125,34 @@ class ContentService:
session=self.session,
include_draft=preview,
)
return ModuleListResponse(
modules=[
ModuleResponse.model_validate(module)
for module in modules
]
)
plan_map: dict[UUID, str] = {}
if modules:
from app.db.enums import PlanType
from app.db.models import AccessPlan, AccessPlanModule
rows = (
await self.session.execute(
select(AccessPlanModule.module_id, AccessPlan.code)
.join(AccessPlan, AccessPlanModule.plan_id == AccessPlan.id)
.where(
AccessPlanModule.module_id.in_([m.id for m in modules]),
AccessPlan.plan_type == PlanType.ONE_TIME,
AccessPlan.currency_code == "INR",
AccessPlan.is_active.is_(True),
)
)
).all()
for mod_id, p_code in rows:
if mod_id not in plan_map:
plan_map[mod_id] = p_code
responses = []
for module in modules:
resp = ModuleResponse.model_validate(module)
if module.id in plan_map:
resp.plan_code = plan_map[module.id]
responses.append(resp)
return ModuleListResponse(modules=responses)
if preview:
return await loader()

View File

@ -5,6 +5,7 @@ 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
from app.features.admin.services.module_service import resolve_module_category
router = APIRouter(tags=["Public Plans Catalog"])
@ -22,16 +23,37 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
all_plans = plans_q.scalars().all()
plan_mods_q = await session.execute(
select(AccessPlanModule.plan_id, Module.slug, Module.name)
select(
AccessPlanModule.plan_id,
Module.code,
Module.slug,
Module.name,
Module.description,
Module.metadata_json,
)
.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():
mod_map: dict[str, list[dict[str, Any]]] = {}
for pid, m_code, slug, name, desc, m_meta 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})
meta_dict = m_meta or {}
try:
sort_order = int(meta_dict.get("sort_order", 99999))
except (ValueError, TypeError):
sort_order = 99999
mod_map[pid_str].append({
"code": m_code,
"slug": slug,
"name": name,
"description": desc or "",
"category": resolve_module_category(meta_dict),
"sort_order": sort_order,
})
for mods_list in mod_map.values():
mods_list.sort(key=lambda m: (m["sort_order"], m["name"]))
groups: dict[str, dict[str, Any]] = {}
for p in all_plans:
@ -67,6 +89,8 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
"modules": [],
"module_slugs": [],
"is_featured": meta.get("is_featured", False),
"pricing_status": meta.get("pricing_status"),
"color": meta.get("color"),
}
grp = groups[base_code]

View File

@ -0,0 +1,187 @@
from __future__ import annotations
import uuid
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.db.enums import BillingPeriod, PlanType
from app.features.access.service import LIFETIME_PLAN_CODES
from app.features.admin.schema import PlanPricingUpdateRequest
from app.features.admin.services.plan_service import AdminPlanService
from app.features.plans import get_public_plans
def _exec_result(*, scalar=None, scalars_list=None, rows=None):
res = MagicMock()
res.scalar_one_or_none.return_value = scalar
res.scalars.return_value.first.return_value = scalar
res.scalars.return_value.all.return_value = scalars_list or []
res.all.return_value = rows or []
return res
def test_lifetime_plan_codes_include_eur():
assert {"LIFETIME_ALL", "LIFETIME_ALL_USD", "LIFETIME_ALL_EUR"}.issubset(LIFETIME_PLAN_CODES)
@pytest.mark.asyncio
async def test_ensure_pending_pricing_plan_creates_inactive_three_tier_plans():
mod = SimpleNamespace(
id=uuid.uuid4(),
code="m0044",
name="Pediatric Disorders",
description="TCM pediatrics",
)
session = AsyncMock()
session.add = MagicMock()
session.execute.side_effect = [
_exec_result(scalar=mod), # Module lookup
_exec_result(scalars_list=[]), # Existing ONE_TIME plan links
_exec_result(scalar=None), # Existing MOD_M0044 code check
]
svc = AdminPlanService(session)
code = await svc.ensure_pending_pricing_plan_for_module("m0044")
assert code == "MOD_M0044"
# 3 AccessPlan + 3 AccessPlanModule added
assert session.add.call_count == 6
added_plans = [c.args[0] for c in session.add.call_args_list if hasattr(c.args[0], "currency_code")]
assert [p.code for p in added_plans] == ["MOD_M0044", "MOD_M0044_USD", "MOD_M0044_EUR"]
assert all(p.is_active is False for p in added_plans)
assert all(p.metadata_json == {"pricing_status": "pending_pricing"} for p in added_plans)
session.commit.assert_awaited_once()
@pytest.mark.asyncio
async def test_toggle_status_blocks_pending_pricing_and_update_pricing_configures():
pending_plan = SimpleNamespace(
id=uuid.uuid4(),
code="MOD_M0044",
name="Pediatric Disorders",
description="",
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
module_fee=Decimal(0),
currency_code="INR",
is_active=False,
metadata_json={"pricing_status": "pending_pricing"},
)
session = AsyncMock()
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
svc = AdminPlanService(session)
with pytest.raises(ValueError, match="Cannot activate plan before pricing is configured"):
await svc.toggle_status("MOD_M0044", True)
# Now update pricing -> clears pending_pricing to configured
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
await svc.update_pricing(
"MOD_M0044",
PlanPricingUpdateRequest(price_inr=600, price_usd=15, price_eur=15),
)
assert pending_plan.module_fee == Decimal("600")
assert pending_plan.metadata_json["pricing_status"] == "configured"
# Now activation succeeds
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
res = await svc.toggle_status("MOD_M0044", True)
assert res["is_active"] is True
assert pending_plan.is_active is True
@pytest.mark.asyncio
async def test_get_public_plans_enriches_module_metadata_and_sort_order():
pid = uuid.uuid4()
plan = SimpleNamespace(
id=pid,
code="MOD_M0044",
name="Pediatric Disorders",
description="",
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
module_fee=Decimal("600"),
total_fee=None,
currency_code="INR",
is_active=True,
metadata_json={"pricing_status": "configured", "color": "from-teal-500 to-cyan-500"},
)
session = AsyncMock()
session.execute.side_effect = [
_exec_result(scalars_list=[plan]),
_exec_result(
rows=[
(pid, "m0044", "pediatric-disorders", "Pediatric Disorders", "TCM pediatrics", {"kind": "therapeutic", "sort_order": 40}),
]
),
]
result = await get_public_plans(session=session)
assert len(result) == 1
assert result[0]["code"] == "MOD_M0044"
assert result[0]["color"] == "from-teal-500 to-cyan-500"
assert result[0]["modules"][0] == {
"code": "m0044",
"slug": "pediatric-disorders",
"name": "Pediatric Disorders",
"description": "TCM pediatrics",
"category": "Therapeutics",
"sort_order": 40,
}
@pytest.mark.asyncio
async def test_update_pricing_syncs_bundle_module_ids():
inr_id, usd_id, eur_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
m1, m2 = uuid.uuid4(), uuid.uuid4()
plans = [
SimpleNamespace(
id=inr_id,
code="ALL_IN_ONE",
name="All-in-One",
description="",
module_fee=Decimal("4000"),
currency_code="INR",
is_active=True,
metadata_json={},
),
SimpleNamespace(
id=usd_id,
code="ALL_IN_ONE_USD",
name="All-in-One (USD)",
description="",
module_fee=Decimal("100"),
currency_code="USD",
is_active=True,
metadata_json={},
),
SimpleNamespace(
id=eur_id,
code="ALL_IN_ONE_EUR",
name="All-in-One (EUR)",
description="",
module_fee=Decimal("100"),
currency_code="EUR",
is_active=True,
metadata_json={},
),
]
session = AsyncMock()
session.add = MagicMock()
session.execute.side_effect = [
_exec_result(scalars_list=plans),
_exec_result(),
]
svc = AdminPlanService(session)
res = await svc.update_pricing(
"ALL_IN_ONE",
PlanPricingUpdateRequest(module_ids=[str(m1), str(m2), str(m1), "invalid-uuid"]),
)
assert res["status"] == "success"
added_links = [(c.args[0].plan_id, c.args[0].module_id) for c in session.add.call_args_list]
assert len(added_links) == 6
assert (inr_id, m1) in added_links and (eur_id, m2) in added_links
session.commit.assert_awaited_once()