Merge pull request 'feat/admin-eur-pricing' (#38) from feat/admin-eur-pricing into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-api/pulls/38
This commit is contained in:
commit
7a37e34696
|
|
@ -3,15 +3,15 @@
|
|||
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
||||
|
||||
<!-- START_TEST_STATUS -->
|
||||
[](#test-status--coverage) [](#test-status--coverage)
|
||||
[](#test-status--coverage) [](#test-status--coverage)
|
||||
|
||||
| Metric | Status |
|
||||
| :--- | :--- |
|
||||
| **Test Suite** | `PASSED` |
|
||||
| **Tests Passing** | `11` |
|
||||
| **Tests Passing** | `12` |
|
||||
| **Tests Failing** | `0` |
|
||||
| **Core Coverage** | `75%` |
|
||||
| **Last Updated** | `2026-11-12 08:29:05 UTC` |
|
||||
| **Last Updated** | `2026-11-23 08:57:00 UTC` |
|
||||
<!-- END_TEST_STATUS -->
|
||||
|
||||
---
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ class CreatePlanRequest(BaseModel):
|
|||
billing_period: str = "yearly"
|
||||
price_inr: float
|
||||
price_usd: float
|
||||
price_eur: float | None = None
|
||||
module_ids: list[str] = Field(default_factory=list)
|
||||
is_featured: bool = False
|
||||
badge_text: str | None = None
|
||||
|
|
@ -71,6 +72,7 @@ class CreatePlanRequest(BaseModel):
|
|||
class PlanPricingUpdateRequest(BaseModel):
|
||||
price_inr: float | None = None
|
||||
price_usd: float | None = None
|
||||
price_eur: float | None = None
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
badge_text: str | None = None
|
||||
|
|
|
|||
|
|
@ -51,7 +51,11 @@ class AdminPlanService:
|
|||
for p in all_plans:
|
||||
code = p.code
|
||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
||||
base_code = code[:-4] if code.endswith("_USD") else code
|
||||
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
|
||||
if code.endswith("_USD") or code.endswith("_EUR"):
|
||||
base_code = code[:-4]
|
||||
else:
|
||||
base_code = code
|
||||
p_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 {}
|
||||
|
|
@ -59,7 +63,7 @@ class AdminPlanService:
|
|||
if base_code not in groups:
|
||||
groups[base_code] = {
|
||||
"base_code": base_code,
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", "").replace(" (EUR)", "").replace(" - EUR", ""),
|
||||
"description": p.description or "",
|
||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||
|
|
@ -70,8 +74,10 @@ class AdminPlanService:
|
|||
"subtitle": meta.get("subtitle"),
|
||||
"inr_plan_id": None,
|
||||
"usd_plan_id": None,
|
||||
"eur_plan_id": None,
|
||||
"price_inr": 0.0,
|
||||
"price_usd": 0.0,
|
||||
"price_eur": 0.0,
|
||||
"modules": [],
|
||||
"module_ids": [],
|
||||
"subscribers_count": 0,
|
||||
|
|
@ -82,6 +88,9 @@ class AdminPlanService:
|
|||
if is_usd:
|
||||
grp["usd_plan_id"] = p_str
|
||||
grp["price_usd"] = fee
|
||||
elif is_eur:
|
||||
grp["eur_plan_id"] = p_str
|
||||
grp["price_eur"] = fee
|
||||
else:
|
||||
grp["inr_plan_id"] = p_str
|
||||
grp["price_inr"] = fee
|
||||
|
|
@ -107,6 +116,11 @@ class AdminPlanService:
|
|||
grp["modules"] = mods
|
||||
grp["module_ids"] = [m["id"] for m in mods]
|
||||
|
||||
# Fallback EUR price to USD price if EUR row not yet created
|
||||
for grp in groups.values():
|
||||
if not grp["price_eur"] and grp["price_usd"]:
|
||||
grp["price_eur"] = grp["price_usd"]
|
||||
|
||||
res = list(groups.values())
|
||||
def sort_key(item: dict) -> tuple[int, str]:
|
||||
if "LIFETIME" in item["base_code"]:
|
||||
|
|
@ -123,7 +137,7 @@ class AdminPlanService:
|
|||
raise ValueError("Plan code cannot be empty.")
|
||||
|
||||
existing = (await self.session.execute(
|
||||
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
||||
)).scalar_one_or_none()
|
||||
if existing:
|
||||
raise ValueError(f"Plan code '{base_code}' already exists.")
|
||||
|
|
@ -168,6 +182,22 @@ class AdminPlanService:
|
|||
metadata_json=meta,
|
||||
)
|
||||
self.session.add(usd_plan)
|
||||
|
||||
eur_price = payload.price_eur if payload.price_eur is not None else payload.price_usd
|
||||
eur_plan = AccessPlan(
|
||||
code=f"{base_code}_EUR",
|
||||
name=f"{payload.name} (EUR)",
|
||||
description=payload.description or "",
|
||||
plan_type=p_type,
|
||||
billing_period=b_period,
|
||||
member_fee=Decimal(0),
|
||||
module_fee=Decimal(str(eur_price)),
|
||||
currency_code="EUR",
|
||||
country="European Union",
|
||||
is_active=True,
|
||||
metadata_json=meta,
|
||||
)
|
||||
self.session.add(eur_plan)
|
||||
await self.session.flush()
|
||||
|
||||
for mid_str in payload.module_ids:
|
||||
|
|
@ -175,35 +205,82 @@ class AdminPlanService:
|
|||
mid = UUID(mid_str)
|
||||
self.session.add(AccessPlanModule(plan_id=inr_plan.id, module_id=mid))
|
||||
self.session.add(AccessPlanModule(plan_id=usd_plan.id, module_id=mid))
|
||||
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
await self.session.commit()
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Plan '{payload.name}' created successfully with INR and USD tiers.",
|
||||
"message": f"Plan '{payload.name}' created successfully with INR, USD, and EUR tiers.",
|
||||
"base_code": base_code,
|
||||
"inr_plan_id": str(inr_plan.id),
|
||||
"usd_plan_id": str(usd_plan.id),
|
||||
"eur_plan_id": str(eur_plan.id),
|
||||
}
|
||||
|
||||
async def update_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
|
||||
base_code = plan_code.strip().upper()
|
||||
plans = (await self.session.execute(
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
||||
)).scalars().all()
|
||||
if not plans:
|
||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
||||
|
||||
eur_plan = next((p for p in plans if p.code == f"{base_code}_EUR" or p.currency_code == "EUR"), None)
|
||||
inr_plan = next((p for p in plans if p.code == base_code or p.currency_code == "INR"), plans[0])
|
||||
usd_plan = next((p for p in plans if p.code == f"{base_code}_USD" or p.currency_code == "USD"), None)
|
||||
|
||||
eur_price = payload.price_eur if payload.price_eur is not None else (
|
||||
payload.price_usd if payload.price_usd is not None else (float(usd_plan.module_fee) if usd_plan else None)
|
||||
)
|
||||
|
||||
if eur_plan is None and eur_price is not None:
|
||||
meta = dict(inr_plan.metadata_json or {})
|
||||
if payload.badge_text is not None:
|
||||
meta["badge_text"] = payload.badge_text
|
||||
if payload.heading is not None:
|
||||
meta["heading"] = payload.heading
|
||||
if payload.subtitle is not None:
|
||||
meta["subtitle"] = payload.subtitle
|
||||
|
||||
eur_plan = AccessPlan(
|
||||
code=f"{base_code}_EUR",
|
||||
name=f"{payload.name or inr_plan.name} (EUR)",
|
||||
description=payload.description if payload.description is not None else inr_plan.description,
|
||||
plan_type=inr_plan.plan_type,
|
||||
billing_period=inr_plan.billing_period,
|
||||
member_fee=Decimal(0),
|
||||
module_fee=Decimal(str(eur_price)),
|
||||
currency_code="EUR",
|
||||
country="European Union",
|
||||
is_active=inr_plan.is_active,
|
||||
metadata_json=meta,
|
||||
)
|
||||
self.session.add(eur_plan)
|
||||
await self.session.flush()
|
||||
|
||||
mod_ids = (await self.session.execute(
|
||||
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == inr_plan.id)
|
||||
)).scalars().all()
|
||||
for mid in mod_ids:
|
||||
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
|
||||
plans.append(eur_plan)
|
||||
|
||||
for p in plans:
|
||||
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
||||
if is_usd and payload.price_usd is not None:
|
||||
is_eur = p.code.endswith("_EUR") or p.currency_code == "EUR"
|
||||
|
||||
if is_eur and payload.price_eur is not None:
|
||||
p.module_fee = Decimal(str(payload.price_eur))
|
||||
elif is_usd and payload.price_usd is not None:
|
||||
p.module_fee = Decimal(str(payload.price_usd))
|
||||
elif not is_usd and payload.price_inr is not None:
|
||||
elif not is_usd and not is_eur and payload.price_inr is not None:
|
||||
p.module_fee = Decimal(str(payload.price_inr))
|
||||
|
||||
if payload.name:
|
||||
p.name = f"{payload.name} (USD)" if is_usd else payload.name
|
||||
suffix = " (EUR)" if is_eur else (" (USD)" if is_usd else "")
|
||||
p.name = f"{payload.name}{suffix}"
|
||||
if payload.description is not None:
|
||||
p.description = payload.description
|
||||
|
||||
|
|
@ -222,7 +299,7 @@ class AdminPlanService:
|
|||
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
|
||||
base_code = plan_code.strip().upper()
|
||||
plans = (await self.session.execute(
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
||||
)).scalars().all()
|
||||
if not plans:
|
||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
||||
|
|
|
|||
|
|
@ -37,7 +37,8 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
|||
for p in all_plans:
|
||||
code = p.code
|
||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
||||
base_code = code[:-4] if code.endswith("_USD") else code
|
||||
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)
|
||||
|
||||
|
|
@ -45,7 +46,7 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
|||
if base_code not in groups:
|
||||
groups[base_code] = {
|
||||
"code": base_code,
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||
"name": p.name.replace(" (USD)", "").replace(" - USD", "").replace(" (EUR)", "").replace(" - EUR", ""),
|
||||
"description": p.description or "",
|
||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||
|
|
@ -64,7 +65,10 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
|||
grp = groups[base_code]
|
||||
if is_usd:
|
||||
grp["price_usd"] = fee
|
||||
grp["price_eur"] = fee # EUR equals USD for now
|
||||
if not grp.get("price_eur"):
|
||||
grp["price_eur"] = fee
|
||||
elif is_eur:
|
||||
grp["price_eur"] = fee
|
||||
else:
|
||||
grp["price_inr"] = fee
|
||||
grp["name"] = p.name
|
||||
|
|
|
|||
|
|
@ -0,0 +1,94 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.main import app
|
||||
from app.db.models import AppUser
|
||||
from app.features.admin.deps import get_admin_service, get_current_admin
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_public_plans(async_client: AsyncClient) -> None:
|
||||
response = await async_client.get("/api/plans")
|
||||
assert response.status_code == 200
|
||||
assert isinstance(response.json(), list)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_plans_list_with_eur(
|
||||
async_client: AsyncClient,
|
||||
sample_admin: AppUser,
|
||||
) -> None:
|
||||
mock_service = MagicMock()
|
||||
mock_plans = [
|
||||
{
|
||||
"base_code": "POINTS_ACU",
|
||||
"name": "Acu Points Module (1 Yr)",
|
||||
"description": "",
|
||||
"plan_type": "single_module",
|
||||
"billing_period": "yearly",
|
||||
"is_active": True,
|
||||
"price_inr": 300.0,
|
||||
"price_usd": 5.0,
|
||||
"price_eur": 5.0,
|
||||
"modules": [],
|
||||
"module_ids": [],
|
||||
"subscribers_count": 0,
|
||||
}
|
||||
]
|
||||
mock_service.plans = MagicMock()
|
||||
mock_service.plans.list_plans = AsyncMock(return_value=mock_plans)
|
||||
mock_service.list_plans = AsyncMock(return_value=mock_plans)
|
||||
|
||||
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
||||
app.dependency_overrides[get_admin_service] = lambda: mock_service
|
||||
|
||||
try:
|
||||
response = await async_client.get(
|
||||
"/api/admin/plans",
|
||||
headers={"Authorization": "Bearer admin_token"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data) == 1
|
||||
assert data[0]["price_eur"] == 5.0
|
||||
assert data[0]["price_usd"] == 5.0
|
||||
assert data[0]["price_inr"] == 300.0
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_current_admin, None)
|
||||
app.dependency_overrides.pop(get_admin_service, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_plans_update_pricing_with_eur(
|
||||
async_client: AsyncClient,
|
||||
sample_admin: AppUser,
|
||||
) -> None:
|
||||
mock_service = MagicMock()
|
||||
mock_service.plans = MagicMock()
|
||||
mock_service.plans.update_pricing = AsyncMock(return_value={
|
||||
"status": "success",
|
||||
"message": "Pricing and metadata for plan 'POINTS_ACU' updated successfully."
|
||||
})
|
||||
mock_service.update_plan_pricing = AsyncMock(return_value={
|
||||
"status": "success",
|
||||
"message": "Pricing and metadata for plan 'POINTS_ACU' updated successfully."
|
||||
})
|
||||
|
||||
app.dependency_overrides[get_current_admin] = lambda: sample_admin
|
||||
app.dependency_overrides[get_admin_service] = lambda: mock_service
|
||||
|
||||
try:
|
||||
response = await async_client.put(
|
||||
"/api/admin/plans/POINTS_ACU/pricing",
|
||||
json={"price_inr": 300.0, "price_usd": 5.0, "price_eur": 6.0},
|
||||
headers={"Authorization": "Bearer admin_token"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "success"
|
||||
finally:
|
||||
app.dependency_overrides.pop(get_current_admin, None)
|
||||
app.dependency_overrides.pop(get_admin_service, None)
|
||||
Loading…
Reference in New Issue