Compare commits
1 Commits
43152be108
...
adc7a9e2ca
| Author | SHA1 | Date |
|---|---|---|
|
|
adc7a9e2ca |
|
|
@ -3,15 +3,15 @@
|
||||||
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
||||||
|
|
||||||
<!-- START_TEST_STATUS -->
|
<!-- START_TEST_STATUS -->
|
||||||
[](#test-status--coverage) [](#test-status--coverage)
|
[](#test-status--coverage) [](#test-status--coverage)
|
||||||
|
|
||||||
| Metric | Status |
|
| Metric | Status |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| **Test Suite** | `PASSED` |
|
| **Test Suite** | `PASSED` |
|
||||||
| **Tests Passing** | `12` |
|
| **Tests Passing** | `11` |
|
||||||
| **Tests Failing** | `0` |
|
| **Tests Failing** | `0` |
|
||||||
| **Core Coverage** | `75%` |
|
| **Core Coverage** | `75%` |
|
||||||
| **Last Updated** | `2026-11-23 08:57:00 UTC` |
|
| **Last Updated** | `2026-11-12 08:29:05 UTC` |
|
||||||
<!-- END_TEST_STATUS -->
|
<!-- END_TEST_STATUS -->
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -223,7 +223,6 @@ class Coupon(Base):
|
||||||
is_first_purchase_only: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
|
is_first_purchase_only: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||||
description: Mapped[str | None] = mapped_column(Text)
|
description: Mapped[str | None] = mapped_column(Text)
|
||||||
metadata_json: Mapped[dict | None] = mapped_column(JSONB, server_default=text("'{}'::jsonb"))
|
|
||||||
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="SET NULL"))
|
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="SET NULL"))
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,15 +10,13 @@ from collections.abc import AsyncIterator
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
engine = create_async_engine(
|
engine = create_async_engine(settings.database_url, pool_pre_ping=True, future=True)
|
||||||
settings.database_url,
|
# AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||||
pool_size=settings.database_pool_size,
|
|
||||||
max_overflow=settings.database_max_overflow,
|
# async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||||
pool_timeout=settings.database_pool_timeout_seconds,
|
# async with AsyncSessionLocal() as session:
|
||||||
pool_pre_ping=True,
|
# yield session
|
||||||
pool_recycle=1800,
|
|
||||||
future=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
SessionFactory = async_sessionmaker(
|
SessionFactory = async_sessionmaker(
|
||||||
bind=engine,
|
bind=engine,
|
||||||
|
|
@ -29,10 +27,4 @@ SessionFactory = async_sessionmaker(
|
||||||
|
|
||||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||||
async with SessionFactory() as session:
|
async with SessionFactory() as session:
|
||||||
try:
|
yield session
|
||||||
yield session
|
|
||||||
except Exception:
|
|
||||||
await session.rollback()
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
await session.close()
|
|
||||||
|
|
@ -62,7 +62,6 @@ class CreatePlanRequest(BaseModel):
|
||||||
billing_period: str = "yearly"
|
billing_period: str = "yearly"
|
||||||
price_inr: float
|
price_inr: float
|
||||||
price_usd: float
|
price_usd: float
|
||||||
price_eur: float | None = None
|
|
||||||
module_ids: list[str] = Field(default_factory=list)
|
module_ids: list[str] = Field(default_factory=list)
|
||||||
is_featured: bool = False
|
is_featured: bool = False
|
||||||
badge_text: str | None = None
|
badge_text: str | None = None
|
||||||
|
|
@ -72,7 +71,6 @@ class CreatePlanRequest(BaseModel):
|
||||||
class PlanPricingUpdateRequest(BaseModel):
|
class PlanPricingUpdateRequest(BaseModel):
|
||||||
price_inr: float | None = None
|
price_inr: float | None = None
|
||||||
price_usd: float | None = None
|
price_usd: float | None = None
|
||||||
price_eur: float | None = None
|
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
badge_text: str | None = None
|
badge_text: str | None = None
|
||||||
|
|
@ -87,51 +85,31 @@ class CreateCouponRequest(BaseModel):
|
||||||
discount_type: str
|
discount_type: str
|
||||||
coupon_category: str = "general"
|
coupon_category: str = "general"
|
||||||
value: float
|
value: float
|
||||||
value_inr: float | None = None
|
|
||||||
value_usd: float | None = None
|
|
||||||
value_eur: float | None = None
|
|
||||||
max_discount_limit: float = 0.0
|
max_discount_limit: float = 0.0
|
||||||
max_discount_inr: float | None = None
|
|
||||||
max_discount_usd: float | None = None
|
|
||||||
max_discount_eur: float | None = None
|
|
||||||
start_date: str | None = None
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int = 0
|
usage_limit: int = 0
|
||||||
min_purchase_amount: float = 0.0
|
min_purchase_amount: float = 0.0
|
||||||
min_purchase_inr: float | None = None
|
|
||||||
min_purchase_usd: float | None = None
|
|
||||||
min_purchase_eur: float | None = None
|
|
||||||
is_first_purchase_only: bool = False
|
is_first_purchase_only: bool = False
|
||||||
applicable_plan_ids: list[str] | None = None
|
applicable_plan_ids: list[str] | None = None
|
||||||
applicable_module_ids: list[str] | None = None
|
applicable_module_ids: list[str] | None = None
|
||||||
is_active: bool = True
|
is_active: bool = True
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
metadata_json: dict | None = None
|
|
||||||
|
|
||||||
class UpdateCouponRequest(BaseModel):
|
class UpdateCouponRequest(BaseModel):
|
||||||
discount_type: str | None = None
|
discount_type: str | None = None
|
||||||
coupon_category: str | None = None
|
coupon_category: str | None = None
|
||||||
value: float | None = None
|
value: float | None = None
|
||||||
value_inr: float | None = None
|
|
||||||
value_usd: float | None = None
|
|
||||||
value_eur: float | None = None
|
|
||||||
max_discount_limit: float | None = None
|
max_discount_limit: float | None = None
|
||||||
max_discount_inr: float | None = None
|
|
||||||
max_discount_usd: float | None = None
|
|
||||||
max_discount_eur: float | None = None
|
|
||||||
start_date: str | None = None
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int | None = None
|
usage_limit: int | None = None
|
||||||
min_purchase_amount: float | None = None
|
min_purchase_amount: float | None = None
|
||||||
min_purchase_inr: float | None = None
|
|
||||||
min_purchase_usd: float | None = None
|
|
||||||
min_purchase_eur: float | None = None
|
|
||||||
is_first_purchase_only: bool | None = None
|
is_first_purchase_only: bool | None = None
|
||||||
applicable_plan_ids: list[str] | None = None
|
applicable_plan_ids: list[str] | None = None
|
||||||
applicable_module_ids: list[str] | None = None
|
applicable_module_ids: list[str] | None = None
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
metadata_json: dict | None = None
|
|
||||||
|
|
||||||
class CouponStatusToggleRequest(BaseModel):
|
class CouponStatusToggleRequest(BaseModel):
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
|
|
||||||
|
|
@ -18,80 +18,10 @@ def _parse_iso_datetime(value: str | datetime | None, default: datetime | None =
|
||||||
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
|
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
|
||||||
|
|
||||||
|
|
||||||
def _build_coupon_metadata(payload: CreateCouponRequest | UpdateCouponRequest, existing_meta: dict | None = None) -> dict:
|
|
||||||
meta = dict(existing_meta or {})
|
|
||||||
if getattr(payload, "metadata_json", None):
|
|
||||||
meta.update(payload.metadata_json)
|
|
||||||
|
|
||||||
c_vals = dict(meta.get("currency_values") or {})
|
|
||||||
if payload.value_inr is not None:
|
|
||||||
c_vals["INR"] = payload.value_inr
|
|
||||||
elif payload.value is not None and "INR" not in c_vals:
|
|
||||||
c_vals["INR"] = payload.value
|
|
||||||
if payload.value_usd is not None:
|
|
||||||
c_vals["USD"] = payload.value_usd
|
|
||||||
if payload.value_eur is not None:
|
|
||||||
c_vals["EUR"] = payload.value_eur
|
|
||||||
if c_vals:
|
|
||||||
meta["currency_values"] = c_vals
|
|
||||||
|
|
||||||
c_caps = dict(meta.get("currency_caps") or {})
|
|
||||||
if payload.max_discount_inr is not None:
|
|
||||||
c_caps["INR"] = payload.max_discount_inr
|
|
||||||
elif payload.max_discount_limit is not None and "INR" not in c_caps:
|
|
||||||
c_caps["INR"] = payload.max_discount_limit
|
|
||||||
if payload.max_discount_usd is not None:
|
|
||||||
c_caps["USD"] = payload.max_discount_usd
|
|
||||||
if payload.max_discount_eur is not None:
|
|
||||||
c_caps["EUR"] = payload.max_discount_eur
|
|
||||||
if c_caps:
|
|
||||||
meta["currency_caps"] = c_caps
|
|
||||||
|
|
||||||
c_mins = dict(meta.get("currency_min_spends") or {})
|
|
||||||
if payload.min_purchase_inr is not None:
|
|
||||||
c_mins["INR"] = payload.min_purchase_inr
|
|
||||||
elif payload.min_purchase_amount is not None and "INR" not in c_mins:
|
|
||||||
c_mins["INR"] = payload.min_purchase_amount
|
|
||||||
if payload.min_purchase_usd is not None:
|
|
||||||
c_mins["USD"] = payload.min_purchase_usd
|
|
||||||
if payload.min_purchase_eur is not None:
|
|
||||||
c_mins["EUR"] = payload.min_purchase_eur
|
|
||||||
if c_mins:
|
|
||||||
meta["currency_min_spends"] = c_mins
|
|
||||||
|
|
||||||
return meta
|
|
||||||
|
|
||||||
|
|
||||||
class AdminCouponService:
|
class AdminCouponService:
|
||||||
def __init__(self, session: AsyncSession) -> None:
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self.session = session
|
self.session = session
|
||||||
|
|
||||||
async def _expand_plan_ids(self, plan_ids: list[str] | None) -> list[UUID] | None:
|
|
||||||
if not plan_ids:
|
|
||||||
return None
|
|
||||||
uuids = [UUID(pid) for pid in plan_ids]
|
|
||||||
rows = (await self.session.execute(
|
|
||||||
select(AccessPlan.code).where(AccessPlan.id.in_(uuids))
|
|
||||||
)).scalars().all()
|
|
||||||
base_codes: set[str] = set()
|
|
||||||
for c in rows:
|
|
||||||
code_up = c.upper()
|
|
||||||
if code_up.endswith("_USD"):
|
|
||||||
base_codes.add(code_up[:-4])
|
|
||||||
elif code_up.endswith("_EUR"):
|
|
||||||
base_codes.add(code_up[:-4])
|
|
||||||
else:
|
|
||||||
base_codes.add(code_up)
|
|
||||||
all_codes: set[str] = set()
|
|
||||||
for bc in base_codes:
|
|
||||||
all_codes.add(bc)
|
|
||||||
all_codes.add(f"{bc}_USD")
|
|
||||||
all_codes.add(f"{bc}_EUR")
|
|
||||||
all_plan_rows = (await self.session.execute(
|
|
||||||
select(AccessPlan.id).where(AccessPlan.code.in_(all_codes))
|
|
||||||
)).scalars().all()
|
|
||||||
return list(set(uuids + list(all_plan_rows)))
|
|
||||||
|
|
||||||
async def list_coupons(self) -> list[dict]:
|
async def list_coupons(self) -> list[dict]:
|
||||||
coupons = (await self.session.execute(
|
coupons = (await self.session.execute(
|
||||||
select(Coupon).order_by(Coupon.created_at.desc())
|
select(Coupon).order_by(Coupon.created_at.desc())
|
||||||
|
|
@ -131,48 +61,18 @@ class AdminCouponService:
|
||||||
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
|
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
|
||||||
module_names = [all_mods.get(str(mid), str(mid)[:8]) for mid in (c.applicable_module_ids or [])]
|
module_names = [all_mods.get(str(mid), str(mid)[:8]) for mid in (c.applicable_module_ids or [])]
|
||||||
|
|
||||||
metadata = c.metadata_json or {}
|
|
||||||
c_values = metadata.get("currency_values") or {}
|
|
||||||
c_caps = metadata.get("currency_caps") or {}
|
|
||||||
c_mins = metadata.get("currency_min_spends") or {}
|
|
||||||
|
|
||||||
val_inr = float(c_values.get("INR", c.value))
|
|
||||||
val_usd = float(c_values["USD"]) if "USD" in c_values and c_values["USD"] is not None else None
|
|
||||||
val_eur = float(c_values["EUR"]) if "EUR" in c_values and c_values["EUR"] is not None else None
|
|
||||||
|
|
||||||
cap_inr = float(c_caps.get("INR", c.max_discount_limit or 0.0))
|
|
||||||
cap_usd = float(c_caps["USD"]) if "USD" in c_caps and c_caps["USD"] is not None else None
|
|
||||||
cap_eur = float(c_caps["EUR"]) if "EUR" in c_caps and c_caps["EUR"] is not None else None
|
|
||||||
|
|
||||||
min_inr = float(c_mins.get("INR", c.min_purchase_amount or 0.0))
|
|
||||||
min_usd = float(c_mins["USD"]) if "USD" in c_mins and c_mins["USD"] is not None else None
|
|
||||||
min_eur = float(c_mins["EUR"]) if "EUR" in c_mins and c_mins["EUR"] is not None else None
|
|
||||||
|
|
||||||
result.append({
|
result.append({
|
||||||
"id": str(c.id),
|
"id": str(c.id),
|
||||||
"code": c.code,
|
"code": c.code,
|
||||||
"discount_type": c.discount_type,
|
"discount_type": c.discount_type,
|
||||||
"coupon_category": c.coupon_category,
|
"coupon_category": c.coupon_category,
|
||||||
"value": float(c.value),
|
"value": float(c.value),
|
||||||
"value_inr": val_inr,
|
|
||||||
"value_usd": val_usd,
|
|
||||||
"value_eur": val_eur,
|
|
||||||
"max_discount_limit": float(c.max_discount_limit or 0.0),
|
"max_discount_limit": float(c.max_discount_limit or 0.0),
|
||||||
"max_discount_inr": cap_inr,
|
|
||||||
"max_discount_usd": cap_usd,
|
|
||||||
"max_discount_eur": cap_eur,
|
|
||||||
"start_date": s_date.isoformat(),
|
"start_date": s_date.isoformat(),
|
||||||
"end_date": e_date.isoformat(),
|
"end_date": e_date.isoformat(),
|
||||||
"usage_limit": c.usage_limit,
|
"usage_limit": c.usage_limit,
|
||||||
"usage_count": usage_count,
|
"usage_count": usage_count,
|
||||||
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
||||||
"min_purchase_inr": min_inr,
|
|
||||||
"min_purchase_usd": min_usd,
|
|
||||||
"min_purchase_eur": min_eur,
|
|
||||||
"currency_values": c_values,
|
|
||||||
"currency_caps": c_caps,
|
|
||||||
"currency_min_spends": c_mins,
|
|
||||||
"metadata_json": metadata,
|
|
||||||
"is_first_purchase_only": c.is_first_purchase_only,
|
"is_first_purchase_only": c.is_first_purchase_only,
|
||||||
"is_active": c.is_active,
|
"is_active": c.is_active,
|
||||||
"description": c.description or "",
|
"description": c.description or "",
|
||||||
|
|
@ -199,31 +99,25 @@ class AdminCouponService:
|
||||||
if end <= start:
|
if end <= start:
|
||||||
raise ValueError("Invalid date range: End date must be later than start date.")
|
raise ValueError("Invalid date range: End date must be later than start date.")
|
||||||
|
|
||||||
expanded_plan_uuids = await self._expand_plan_ids(payload.applicable_plan_ids)
|
plan_uuids = [UUID(pid) for pid in payload.applicable_plan_ids] if payload.applicable_plan_ids else None
|
||||||
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
||||||
|
|
||||||
base_val = payload.value_inr if payload.value_inr is not None else payload.value
|
|
||||||
base_cap = payload.max_discount_inr if payload.max_discount_inr is not None else (payload.max_discount_limit or 0)
|
|
||||||
base_min = payload.min_purchase_inr if payload.min_purchase_inr is not None else (payload.min_purchase_amount or 0)
|
|
||||||
metadata = _build_coupon_metadata(payload)
|
|
||||||
|
|
||||||
coupon = Coupon(
|
coupon = Coupon(
|
||||||
code=code,
|
code=code,
|
||||||
discount_type=payload.discount_type,
|
discount_type=payload.discount_type,
|
||||||
coupon_category=payload.coupon_category,
|
coupon_category=payload.coupon_category,
|
||||||
value=Decimal(str(base_val)),
|
value=Decimal(str(payload.value)),
|
||||||
max_discount_limit=Decimal(str(base_cap)),
|
max_discount_limit=Decimal(str(payload.max_discount_limit or 0)),
|
||||||
start_date=start,
|
start_date=start,
|
||||||
end_date=end,
|
end_date=end,
|
||||||
usage_limit=payload.usage_limit,
|
usage_limit=payload.usage_limit,
|
||||||
usage_count=0,
|
usage_count=0,
|
||||||
min_purchase_amount=Decimal(str(base_min)),
|
min_purchase_amount=Decimal(str(payload.min_purchase_amount or 0)),
|
||||||
is_first_purchase_only=payload.is_first_purchase_only,
|
is_first_purchase_only=payload.is_first_purchase_only,
|
||||||
applicable_plan_ids=expanded_plan_uuids,
|
applicable_plan_ids=plan_uuids,
|
||||||
applicable_module_ids=module_uuids,
|
applicable_module_ids=module_uuids,
|
||||||
is_active=payload.is_active,
|
is_active=payload.is_active,
|
||||||
description=payload.description,
|
description=payload.description,
|
||||||
metadata_json=metadata,
|
|
||||||
)
|
)
|
||||||
self.session.add(coupon)
|
self.session.add(coupon)
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
|
|
@ -249,13 +143,9 @@ class AdminCouponService:
|
||||||
coupon.discount_type = payload.discount_type
|
coupon.discount_type = payload.discount_type
|
||||||
if payload.coupon_category is not None:
|
if payload.coupon_category is not None:
|
||||||
coupon.coupon_category = payload.coupon_category
|
coupon.coupon_category = payload.coupon_category
|
||||||
if payload.value_inr is not None:
|
if payload.value is not None:
|
||||||
coupon.value = Decimal(str(payload.value_inr))
|
|
||||||
elif payload.value is not None:
|
|
||||||
coupon.value = Decimal(str(payload.value))
|
coupon.value = Decimal(str(payload.value))
|
||||||
if payload.max_discount_inr is not None:
|
if payload.max_discount_limit is not None:
|
||||||
coupon.max_discount_limit = Decimal(str(payload.max_discount_inr))
|
|
||||||
elif payload.max_discount_limit is not None:
|
|
||||||
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
||||||
if payload.start_date is not None:
|
if payload.start_date is not None:
|
||||||
coupon.start_date = new_start
|
coupon.start_date = new_start
|
||||||
|
|
@ -263,14 +153,12 @@ class AdminCouponService:
|
||||||
coupon.end_date = new_end
|
coupon.end_date = new_end
|
||||||
if payload.usage_limit is not None:
|
if payload.usage_limit is not None:
|
||||||
coupon.usage_limit = payload.usage_limit
|
coupon.usage_limit = payload.usage_limit
|
||||||
if payload.min_purchase_inr is not None:
|
if payload.min_purchase_amount is not None:
|
||||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
|
|
||||||
elif payload.min_purchase_amount is not None:
|
|
||||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
||||||
if payload.is_first_purchase_only is not None:
|
if payload.is_first_purchase_only is not None:
|
||||||
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
||||||
if payload.applicable_plan_ids is not None:
|
if payload.applicable_plan_ids is not None:
|
||||||
coupon.applicable_plan_ids = await self._expand_plan_ids(payload.applicable_plan_ids)
|
coupon.applicable_plan_ids = [UUID(pid) for pid in payload.applicable_plan_ids]
|
||||||
if payload.applicable_module_ids is not None:
|
if payload.applicable_module_ids is not None:
|
||||||
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
||||||
if payload.is_active is not None:
|
if payload.is_active is not None:
|
||||||
|
|
@ -278,8 +166,6 @@ class AdminCouponService:
|
||||||
if payload.description is not None:
|
if payload.description is not None:
|
||||||
coupon.description = payload.description
|
coupon.description = payload.description
|
||||||
|
|
||||||
coupon.metadata_json = _build_coupon_metadata(payload, coupon.metadata_json)
|
|
||||||
|
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,8 @@ class ModuleBuilderService:
|
||||||
if legacy_mod:
|
if legacy_mod:
|
||||||
legacy_meta = legacy_mod.metadata_json or {}
|
legacy_meta = legacy_mod.metadata_json or {}
|
||||||
legacy_kind = legacy_meta.get("kind") or "legacy"
|
legacy_kind = legacy_meta.get("kind") or "legacy"
|
||||||
if legacy_kind != "therapeutic":
|
legacy_managed = legacy_meta.get("managed_by")
|
||||||
|
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=403,
|
status_code=403,
|
||||||
detail=(
|
detail=(
|
||||||
|
|
@ -344,7 +345,8 @@ class ModuleBuilderService:
|
||||||
if legacy_mod:
|
if legacy_mod:
|
||||||
legacy_meta = legacy_mod.metadata_json or {}
|
legacy_meta = legacy_mod.metadata_json or {}
|
||||||
legacy_kind = legacy_meta.get("kind") or "legacy"
|
legacy_kind = legacy_meta.get("kind") or "legacy"
|
||||||
if legacy_kind != "therapeutic":
|
legacy_managed = legacy_meta.get("managed_by")
|
||||||
|
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=403,
|
status_code=403,
|
||||||
detail=(
|
detail=(
|
||||||
|
|
@ -467,6 +469,7 @@ class ModuleBuilderService:
|
||||||
)
|
)
|
||||||
res = await self.session.execute(stmt)
|
res = await self.session.execute(stmt)
|
||||||
cat = res.scalar_one()
|
cat = res.scalar_one()
|
||||||
|
await self.session.commit()
|
||||||
|
|
||||||
# Count diseases
|
# Count diseases
|
||||||
count_stmt = select(func.count(BuilderDisease.id)).where(
|
count_stmt = select(func.count(BuilderDisease.id)).where(
|
||||||
|
|
@ -475,7 +478,6 @@ class ModuleBuilderService:
|
||||||
)
|
)
|
||||||
count_res = await self.session.execute(count_stmt)
|
count_res = await self.session.execute(count_stmt)
|
||||||
count = count_res.scalar_one() or 0
|
count = count_res.scalar_one() or 0
|
||||||
await self.session.commit()
|
|
||||||
|
|
||||||
return BuilderCategorySummary(
|
return BuilderCategorySummary(
|
||||||
id=cat.id,
|
id=cat.id,
|
||||||
|
|
@ -489,7 +491,28 @@ class ModuleBuilderService:
|
||||||
|
|
||||||
async def delete_category(self, module_code: str, category_code: str) -> bool:
|
async def delete_category(self, module_code: str, category_code: str) -> bool:
|
||||||
clean_code = module_code.strip().lower()
|
clean_code = module_code.strip().lower()
|
||||||
await self._verify_module_editable(clean_code)
|
|
||||||
|
# 1. Block if legacy module
|
||||||
|
legacy_stmt = select(Module).where(Module.code == clean_code)
|
||||||
|
legacy_res = await self.session.execute(legacy_stmt)
|
||||||
|
legacy_mod = legacy_res.scalar_one_or_none()
|
||||||
|
if legacy_mod:
|
||||||
|
legacy_meta = legacy_mod.metadata_json or {}
|
||||||
|
legacy_kind = legacy_meta.get("kind") or "legacy"
|
||||||
|
legacy_managed = legacy_meta.get("managed_by")
|
||||||
|
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=(
|
||||||
|
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
|
||||||
|
"and cannot be modified via Module Builder."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
|
||||||
|
mod = (await self.session.execute(stmt)).scalar_one_or_none()
|
||||||
|
if not mod:
|
||||||
|
return False
|
||||||
|
|
||||||
del_stmt = delete(BuilderCategory).where(
|
del_stmt = delete(BuilderCategory).where(
|
||||||
BuilderCategory.module_code == clean_code,
|
BuilderCategory.module_code == clean_code,
|
||||||
|
|
@ -648,6 +671,7 @@ class ModuleBuilderService:
|
||||||
)
|
)
|
||||||
res = await self.session.execute(stmt)
|
res = await self.session.execute(stmt)
|
||||||
dis = res.scalar_one()
|
dis = res.scalar_one()
|
||||||
|
await self.session.commit()
|
||||||
|
|
||||||
count_stmt = select(func.count(BuilderPattern.id)).where(
|
count_stmt = select(func.count(BuilderPattern.id)).where(
|
||||||
BuilderPattern.module_code == module_code,
|
BuilderPattern.module_code == module_code,
|
||||||
|
|
@ -677,10 +701,9 @@ class ModuleBuilderService:
|
||||||
updated_at=now,
|
updated_at=now,
|
||||||
)
|
)
|
||||||
await self.session.execute(init_pat)
|
await self.session.execute(init_pat)
|
||||||
|
await self.session.commit()
|
||||||
count = 1
|
count = 1
|
||||||
|
|
||||||
await self.session.commit()
|
|
||||||
|
|
||||||
return BuilderDiseaseSummary(
|
return BuilderDiseaseSummary(
|
||||||
id=dis.id,
|
id=dis.id,
|
||||||
module_code=dis.module_code,
|
module_code=dis.module_code,
|
||||||
|
|
@ -696,7 +719,28 @@ class ModuleBuilderService:
|
||||||
self, module_code: str, category_code: str, disease_code: str
|
self, module_code: str, category_code: str, disease_code: str
|
||||||
) -> bool:
|
) -> bool:
|
||||||
clean_code = module_code.strip().lower()
|
clean_code = module_code.strip().lower()
|
||||||
await self._verify_module_editable(clean_code)
|
|
||||||
|
# 1. Block if legacy module
|
||||||
|
legacy_stmt = select(Module).where(Module.code == clean_code)
|
||||||
|
legacy_res = await self.session.execute(legacy_stmt)
|
||||||
|
legacy_mod = legacy_res.scalar_one_or_none()
|
||||||
|
if legacy_mod:
|
||||||
|
legacy_meta = legacy_mod.metadata_json or {}
|
||||||
|
legacy_kind = legacy_meta.get("kind") or "legacy"
|
||||||
|
legacy_managed = legacy_meta.get("managed_by")
|
||||||
|
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=(
|
||||||
|
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
|
||||||
|
"and cannot be modified via Module Builder."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
|
||||||
|
mod = (await self.session.execute(stmt)).scalar_one_or_none()
|
||||||
|
if not mod:
|
||||||
|
return False
|
||||||
|
|
||||||
stmt = delete(BuilderDisease).where(
|
stmt = delete(BuilderDisease).where(
|
||||||
BuilderDisease.module_code == clean_code,
|
BuilderDisease.module_code == clean_code,
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import copy
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import re
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
@ -19,54 +18,9 @@ from app.db.models import BuilderCategory, BuilderDisease, BuilderModule, Builde
|
||||||
|
|
||||||
logger = logging.getLogger("acupedia.builder.compiler")
|
logger = logging.getLogger("acupedia.builder.compiler")
|
||||||
|
|
||||||
|
DEFAULT_CONTENT_REPO_PATH = Path(
|
||||||
def get_default_content_repo_path() -> Path:
|
"/home/cspl/urvish/CSPL/Panacea/acupedia_content/acupedia-content"
|
||||||
"""Dynamically resolves the content repository path without machine-specific hardcoded paths."""
|
)
|
||||||
# 1. Environment variables
|
|
||||||
for env_var in ("ACUPEDIA_CONTENT_PATH", "CONTENT_PATH", "MODULES_ROOT"):
|
|
||||||
val = os.getenv(env_var)
|
|
||||||
if val:
|
|
||||||
p = Path(val).resolve()
|
|
||||||
if p.exists() and p.is_dir():
|
|
||||||
return p
|
|
||||||
|
|
||||||
# 2. Docker container standard mount (/app/content)
|
|
||||||
container_mount = Path("/app/content")
|
|
||||||
if container_mount.exists() and container_mount.is_dir():
|
|
||||||
return container_mount
|
|
||||||
|
|
||||||
# 3. Dynamic search relative to this source file repository
|
|
||||||
current_file = Path(__file__).resolve()
|
|
||||||
for parent in current_file.parents:
|
|
||||||
candidates = [
|
|
||||||
parent / "acupedia_content" / "acupedia-content",
|
|
||||||
parent / "acupedia-content",
|
|
||||||
parent / "acupedia_content",
|
|
||||||
parent / "content",
|
|
||||||
]
|
|
||||||
for candidate in candidates:
|
|
||||||
if candidate.exists() and (candidate / "config.json").exists():
|
|
||||||
return candidate
|
|
||||||
if candidate.exists() and candidate.is_dir() and (candidate / "modules").exists():
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
# 4. Search relative to current working directory
|
|
||||||
cwd = Path.cwd().resolve()
|
|
||||||
for candidate in [
|
|
||||||
cwd / "acupedia_content" / "acupedia-content",
|
|
||||||
cwd.parent / "acupedia_content" / "acupedia-content",
|
|
||||||
cwd / "acupedia-content",
|
|
||||||
cwd.parent / "acupedia-content",
|
|
||||||
cwd / "content",
|
|
||||||
]:
|
|
||||||
if candidate.exists() and candidate.is_dir():
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
# Fallback relative to project structure
|
|
||||||
try:
|
|
||||||
return current_file.parents[5] / "acupedia_content" / "acupedia-content"
|
|
||||||
except IndexError:
|
|
||||||
return cwd / "content"
|
|
||||||
|
|
||||||
|
|
||||||
class ModuleContentCompiler:
|
class ModuleContentCompiler:
|
||||||
|
|
@ -520,15 +474,11 @@ class ModuleContentCompiler:
|
||||||
repo_root: Path | None = None,
|
repo_root: Path | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
module, files = await self.compile_module(module_code)
|
module, files = await self.compile_module(module_code)
|
||||||
target_root = repo_root or get_default_content_repo_path()
|
target_root = repo_root or DEFAULT_CONTENT_REPO_PATH
|
||||||
if not target_root.exists():
|
if not target_root.exists():
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=500,
|
||||||
detail=(
|
detail=f"Content repository directory not found at: {target_root}",
|
||||||
f"Content repository directory not found on server (checked: {target_root}). "
|
|
||||||
"Please configure the CONTENT_PATH environment variable, or use 'Download Acupedia (.zip)' "
|
|
||||||
"from the Export menu to download the production bundle directly to your computer."
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
module_folder_name = f"{module.code}-{module.slug}"
|
module_folder_name = f"{module.code}-{module.slug}"
|
||||||
|
|
|
||||||
|
|
@ -374,9 +374,9 @@ class AdminPaymentService:
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
cust_name = (user.display_name if user and user.display_name else None) or (profile.billing_name if profile else None) or (invoice.billing_name if invoice else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
|
cust_name = (invoice.billing_name if invoice else None) or (profile.billing_name if profile else None) or (user.display_name if user else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
|
||||||
cust_email = (user.email if user and user.email else None) or (profile.billing_email if profile else None) or (invoice.billing_email if invoice else None) or rzp_payment.get("email") or "customer@example.com"
|
cust_email = (invoice.billing_email if invoice else None) or (profile.billing_email if profile else None) or (user.email if user else None) or rzp_payment.get("email") or "customer@example.com"
|
||||||
cust_phone = (user.phone_number if user and user.phone_number else None) or (profile.billing_phone if profile else None) or rzp_payment.get("contact") or ""
|
cust_phone = (profile.billing_phone if profile else None) or (user.phone_number if user else None) or rzp_payment.get("contact") or ""
|
||||||
|
|
||||||
# Clean address string
|
# Clean address string
|
||||||
clean_addr_parts = []
|
clean_addr_parts = []
|
||||||
|
|
@ -384,7 +384,7 @@ class AdminPaymentService:
|
||||||
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
||||||
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
|
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
|
||||||
clean_addr_parts.append(p.strip())
|
clean_addr_parts.append(p.strip())
|
||||||
c = (user.country if user and user.country else None) or profile.country
|
c = profile.country or (user.country if user else None)
|
||||||
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
|
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
clean_addr_parts.append(c.strip())
|
clean_addr_parts.append(c.strip())
|
||||||
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
|
|
|
||||||
|
|
@ -51,11 +51,7 @@ class AdminPlanService:
|
||||||
for p in all_plans:
|
for p in all_plans:
|
||||||
code = p.code
|
code = p.code
|
||||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
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") else code
|
||||||
if code.endswith("_USD") or code.endswith("_EUR"):
|
|
||||||
base_code = code[:-4]
|
|
||||||
else:
|
|
||||||
base_code = code
|
|
||||||
p_str = str(p.id)
|
p_str = str(p.id)
|
||||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||||
meta = p.metadata_json or {}
|
meta = p.metadata_json or {}
|
||||||
|
|
@ -63,7 +59,7 @@ class AdminPlanService:
|
||||||
if base_code not in groups:
|
if base_code not in groups:
|
||||||
groups[base_code] = {
|
groups[base_code] = {
|
||||||
"base_code": base_code,
|
"base_code": base_code,
|
||||||
"name": p.name.replace(" (USD)", "").replace(" - USD", "").replace(" (EUR)", "").replace(" - EUR", ""),
|
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||||
"description": p.description or "",
|
"description": p.description or "",
|
||||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||||
|
|
@ -74,10 +70,8 @@ class AdminPlanService:
|
||||||
"subtitle": meta.get("subtitle"),
|
"subtitle": meta.get("subtitle"),
|
||||||
"inr_plan_id": None,
|
"inr_plan_id": None,
|
||||||
"usd_plan_id": None,
|
"usd_plan_id": None,
|
||||||
"eur_plan_id": None,
|
|
||||||
"price_inr": 0.0,
|
"price_inr": 0.0,
|
||||||
"price_usd": 0.0,
|
"price_usd": 0.0,
|
||||||
"price_eur": 0.0,
|
|
||||||
"modules": [],
|
"modules": [],
|
||||||
"module_ids": [],
|
"module_ids": [],
|
||||||
"subscribers_count": 0,
|
"subscribers_count": 0,
|
||||||
|
|
@ -88,9 +82,6 @@ class AdminPlanService:
|
||||||
if is_usd:
|
if is_usd:
|
||||||
grp["usd_plan_id"] = p_str
|
grp["usd_plan_id"] = p_str
|
||||||
grp["price_usd"] = fee
|
grp["price_usd"] = fee
|
||||||
elif is_eur:
|
|
||||||
grp["eur_plan_id"] = p_str
|
|
||||||
grp["price_eur"] = fee
|
|
||||||
else:
|
else:
|
||||||
grp["inr_plan_id"] = p_str
|
grp["inr_plan_id"] = p_str
|
||||||
grp["price_inr"] = fee
|
grp["price_inr"] = fee
|
||||||
|
|
@ -116,11 +107,6 @@ class AdminPlanService:
|
||||||
grp["modules"] = mods
|
grp["modules"] = mods
|
||||||
grp["module_ids"] = [m["id"] for m in 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())
|
res = list(groups.values())
|
||||||
def sort_key(item: dict) -> tuple[int, str]:
|
def sort_key(item: dict) -> tuple[int, str]:
|
||||||
if "LIFETIME" in item["base_code"]:
|
if "LIFETIME" in item["base_code"]:
|
||||||
|
|
@ -137,7 +123,7 @@ class AdminPlanService:
|
||||||
raise ValueError("Plan code cannot be empty.")
|
raise ValueError("Plan code cannot be empty.")
|
||||||
|
|
||||||
existing = (await self.session.execute(
|
existing = (await self.session.execute(
|
||||||
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||||
)).scalar_one_or_none()
|
)).scalar_one_or_none()
|
||||||
if existing:
|
if existing:
|
||||||
raise ValueError(f"Plan code '{base_code}' already exists.")
|
raise ValueError(f"Plan code '{base_code}' already exists.")
|
||||||
|
|
@ -182,22 +168,6 @@ class AdminPlanService:
|
||||||
metadata_json=meta,
|
metadata_json=meta,
|
||||||
)
|
)
|
||||||
self.session.add(usd_plan)
|
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()
|
await self.session.flush()
|
||||||
|
|
||||||
for mid_str in payload.module_ids:
|
for mid_str in payload.module_ids:
|
||||||
|
|
@ -205,82 +175,35 @@ class AdminPlanService:
|
||||||
mid = UUID(mid_str)
|
mid = UUID(mid_str)
|
||||||
self.session.add(AccessPlanModule(plan_id=inr_plan.id, module_id=mid))
|
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=usd_plan.id, module_id=mid))
|
||||||
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"Plan '{payload.name}' created successfully with INR, USD, and EUR tiers.",
|
"message": f"Plan '{payload.name}' created successfully with INR and USD tiers.",
|
||||||
"base_code": base_code,
|
"base_code": base_code,
|
||||||
"inr_plan_id": str(inr_plan.id),
|
"inr_plan_id": str(inr_plan.id),
|
||||||
"usd_plan_id": str(usd_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:
|
async def update_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
|
||||||
base_code = plan_code.strip().upper()
|
base_code = plan_code.strip().upper()
|
||||||
plans = (await self.session.execute(
|
plans = (await self.session.execute(
|
||||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
if not plans:
|
if not plans:
|
||||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
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:
|
for p in plans:
|
||||||
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
||||||
is_eur = p.code.endswith("_EUR") or p.currency_code == "EUR"
|
if is_usd and payload.price_usd is not None:
|
||||||
|
|
||||||
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))
|
p.module_fee = Decimal(str(payload.price_usd))
|
||||||
elif not is_usd and not is_eur and payload.price_inr is not None:
|
elif not is_usd and payload.price_inr is not None:
|
||||||
p.module_fee = Decimal(str(payload.price_inr))
|
p.module_fee = Decimal(str(payload.price_inr))
|
||||||
|
|
||||||
if payload.name:
|
if payload.name:
|
||||||
suffix = " (EUR)" if is_eur else (" (USD)" if is_usd else "")
|
p.name = f"{payload.name} (USD)" if is_usd else payload.name
|
||||||
p.name = f"{payload.name}{suffix}"
|
|
||||||
if payload.description is not None:
|
if payload.description is not None:
|
||||||
p.description = payload.description
|
p.description = payload.description
|
||||||
|
|
||||||
|
|
@ -299,7 +222,7 @@ class AdminPlanService:
|
||||||
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
|
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
|
||||||
base_code = plan_code.strip().upper()
|
base_code = plan_code.strip().upper()
|
||||||
plans = (await self.session.execute(
|
plans = (await self.session.execute(
|
||||||
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
|
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
if not plans:
|
if not plans:
|
||||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
||||||
|
|
|
||||||
|
|
@ -46,23 +46,17 @@ class AdminReportService:
|
||||||
for uid, rname in ur_rows:
|
for uid, rname in ur_rows:
|
||||||
user_roles_map.setdefault(uid, []).append(rname)
|
user_roles_map.setdefault(uid, []).append(rname)
|
||||||
|
|
||||||
# Preload spend and orders count by currency
|
# Preload spend and orders count
|
||||||
tx_summary_rows = (await self.session.execute(
|
tx_summary_rows = (await self.session.execute(
|
||||||
select(
|
select(
|
||||||
PaymentTransaction.user_id,
|
PaymentTransaction.user_id,
|
||||||
PaymentTransaction.currency,
|
|
||||||
func.count(PaymentTransaction.id),
|
func.count(PaymentTransaction.id),
|
||||||
func.coalesce(func.sum(PaymentTransaction.amount), 0)
|
func.coalesce(func.sum(PaymentTransaction.amount), 0)
|
||||||
)
|
)
|
||||||
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
|
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
|
||||||
.group_by(PaymentTransaction.user_id, PaymentTransaction.currency)
|
.group_by(PaymentTransaction.user_id)
|
||||||
)).all()
|
)).all()
|
||||||
tx_orders: dict[any, int] = {}
|
tx_summary = {uid: (count, float(total)) for uid, count, total in tx_summary_rows}
|
||||||
tx_spend: dict[any, dict[str, float]] = {}
|
|
||||||
for uid, curr, count, total in tx_summary_rows:
|
|
||||||
tx_orders[uid] = tx_orders.get(uid, 0) + count
|
|
||||||
c_up = (curr or "INR").upper()
|
|
||||||
tx_spend.setdefault(uid, {})[c_up] = tx_spend.get(uid, {}).get(c_up, 0.0) + float(total)
|
|
||||||
|
|
||||||
# Preload active subscriptions count
|
# Preload active subscriptions count
|
||||||
sub_count_rows = (await self.session.execute(
|
sub_count_rows = (await self.session.execute(
|
||||||
|
|
@ -84,20 +78,14 @@ class AdminReportService:
|
||||||
"Account Type",
|
"Account Type",
|
||||||
"Status",
|
"Status",
|
||||||
"Total Orders",
|
"Total Orders",
|
||||||
"Lifetime Spend (INR)",
|
"Lifetime Spend",
|
||||||
"Lifetime Spend (USD)",
|
|
||||||
"Lifetime Spend (EUR)",
|
|
||||||
"Active Subscriptions",
|
"Active Subscriptions",
|
||||||
"Registration Date",
|
"Registration Date",
|
||||||
])
|
])
|
||||||
for u in users:
|
for u in users:
|
||||||
user_roles = user_roles_map.get(u.id, [])
|
user_roles = user_roles_map.get(u.id, [])
|
||||||
user_type = "Admin" if any("admin" in str(r).lower() for r in user_roles) else "Practitioner"
|
user_type = "Admin" if any("admin" in str(r).lower() for r in user_roles) else "Practitioner"
|
||||||
orders_count = tx_orders.get(u.id, 0)
|
orders_count, total_spend = tx_summary.get(u.id, (0, 0.0))
|
||||||
u_spend = tx_spend.get(u.id, {})
|
|
||||||
spend_inr = u_spend.get("INR", 0.0)
|
|
||||||
spend_usd = u_spend.get("USD", 0.0)
|
|
||||||
spend_eur = u_spend.get("EUR", 0.0)
|
|
||||||
active_subs = sub_count_map.get(u.id, 0)
|
active_subs = sub_count_map.get(u.id, 0)
|
||||||
status_label = "Active" if u.is_active else "Suspended"
|
status_label = "Active" if u.is_active else "Suspended"
|
||||||
reg_date = u.created_at.strftime("%Y-%m-%d %H:%M:%S") if u.created_at else ""
|
reg_date = u.created_at.strftime("%Y-%m-%d %H:%M:%S") if u.created_at else ""
|
||||||
|
|
@ -111,9 +99,7 @@ class AdminReportService:
|
||||||
user_type,
|
user_type,
|
||||||
status_label,
|
status_label,
|
||||||
orders_count,
|
orders_count,
|
||||||
f"{spend_inr:.2f}",
|
f"{total_spend:.2f}",
|
||||||
f"{spend_usd:.2f}",
|
|
||||||
f"{spend_eur:.2f}",
|
|
||||||
active_subs,
|
active_subs,
|
||||||
reg_date,
|
reg_date,
|
||||||
])
|
])
|
||||||
|
|
@ -197,10 +183,8 @@ class AdminReportService:
|
||||||
"Customer Name",
|
"Customer Name",
|
||||||
"Customer Email",
|
"Customer Email",
|
||||||
"Phone Number",
|
"Phone Number",
|
||||||
"Customer Country",
|
|
||||||
"Plan Code",
|
"Plan Code",
|
||||||
"Plan Name",
|
"Plan Name",
|
||||||
"Plan Currency",
|
|
||||||
"Billing Cycle",
|
"Billing Cycle",
|
||||||
"Status",
|
"Status",
|
||||||
"Days Remaining",
|
"Days Remaining",
|
||||||
|
|
@ -218,17 +202,6 @@ class AdminReportService:
|
||||||
else:
|
else:
|
||||||
billing_cycle = "Yearly"
|
billing_cycle = "Yearly"
|
||||||
|
|
||||||
plan_curr = "INR"
|
|
||||||
if p:
|
|
||||||
if getattr(p, "currency", None):
|
|
||||||
plan_curr = str(p.currency).upper()
|
|
||||||
elif p.code:
|
|
||||||
code_up = p.code.upper()
|
|
||||||
if code_up.endswith("_EUR"):
|
|
||||||
plan_curr = "EUR"
|
|
||||||
elif code_up.endswith("_USD"):
|
|
||||||
plan_curr = "USD"
|
|
||||||
|
|
||||||
days_remaining = "Lifetime"
|
days_remaining = "Lifetime"
|
||||||
if s.expires_at:
|
if s.expires_at:
|
||||||
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
|
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
|
||||||
|
|
@ -247,10 +220,8 @@ class AdminReportService:
|
||||||
u.display_name if u else "",
|
u.display_name if u else "",
|
||||||
u.email if u else "",
|
u.email if u else "",
|
||||||
u.phone_number if u else "",
|
u.phone_number if u else "",
|
||||||
u.country if u else "",
|
|
||||||
p.code if p else "",
|
p.code if p else "",
|
||||||
p.name if p else "",
|
p.name if p else "",
|
||||||
plan_curr,
|
|
||||||
billing_cycle,
|
billing_cycle,
|
||||||
getattr(s.status, "value", s.status),
|
getattr(s.status, "value", s.status),
|
||||||
days_remaining,
|
days_remaining,
|
||||||
|
|
@ -279,16 +250,10 @@ class AdminReportService:
|
||||||
"Coupon Code",
|
"Coupon Code",
|
||||||
"Category",
|
"Category",
|
||||||
"Description",
|
"Description",
|
||||||
|
"Discount Value",
|
||||||
"Discount Type",
|
"Discount Type",
|
||||||
"Discount (INR)",
|
"Max Cap",
|
||||||
"Discount (USD)",
|
"Min Purchase",
|
||||||
"Discount (EUR)",
|
|
||||||
"Max Cap (INR)",
|
|
||||||
"Max Cap (USD)",
|
|
||||||
"Max Cap (EUR)",
|
|
||||||
"Min Purchase (INR)",
|
|
||||||
"Min Purchase (USD)",
|
|
||||||
"Min Purchase (EUR)",
|
|
||||||
"Usage Count",
|
"Usage Count",
|
||||||
"Usage Limit",
|
"Usage Limit",
|
||||||
"Remaining Uses",
|
"Remaining Uses",
|
||||||
|
|
@ -297,49 +262,10 @@ class AdminReportService:
|
||||||
"End Date",
|
"End Date",
|
||||||
])
|
])
|
||||||
for c in coupons:
|
for c in coupons:
|
||||||
metadata = getattr(c, "metadata_json", {}) if hasattr(c, "metadata_json") else {}
|
val = float(c.value) if c.value is not None else 0.0
|
||||||
if not isinstance(metadata, dict):
|
disc_val = f"{val:.2f}%" if c.discount_type == "percentage" else f"{val:.2f}"
|
||||||
metadata = {}
|
max_cap = f"{float(c.max_discount_limit):.2f}" if c.max_discount_limit else "None"
|
||||||
c_values = metadata.get("currency_values") or {}
|
min_spend = f"{float(c.min_purchase_amount):.2f}" if c.min_purchase_amount else "0.00"
|
||||||
c_caps = metadata.get("currency_caps") or {}
|
|
||||||
c_mins = metadata.get("currency_min_spends") or {}
|
|
||||||
|
|
||||||
val_base = float(c.value) if c.value is not None else 0.0
|
|
||||||
is_pct = c.discount_type in {"percentage", "percent"}
|
|
||||||
|
|
||||||
if is_pct:
|
|
||||||
disc_inr = f"{val_base:.2f}%"
|
|
||||||
disc_usd = f"{val_base:.2f}%"
|
|
||||||
disc_eur = f"{val_base:.2f}%"
|
|
||||||
|
|
||||||
cap_inr_num = float(c_caps.get("INR", c.max_discount_limit or 0.0))
|
|
||||||
cap_usd_num = float(c_caps.get("USD", 0.0)) if "USD" in c_caps and c_caps["USD"] is not None else None
|
|
||||||
cap_eur_num = float(c_caps.get("EUR", 0.0)) if "EUR" in c_caps and c_caps["EUR"] is not None else None
|
|
||||||
|
|
||||||
cap_inr = f"₹{cap_inr_num:.2f}" if cap_inr_num > 0 else "None"
|
|
||||||
cap_usd = f"${cap_usd_num:.2f}" if cap_usd_num and cap_usd_num > 0 else "None"
|
|
||||||
cap_eur = f"€{cap_eur_num:.2f}" if cap_eur_num and cap_eur_num > 0 else "None"
|
|
||||||
else:
|
|
||||||
v_inr = float(c_values.get("INR", val_base))
|
|
||||||
v_usd = float(c_values["USD"]) if "USD" in c_values and c_values["USD"] is not None else None
|
|
||||||
v_eur = float(c_values["EUR"]) if "EUR" in c_values and c_values["EUR"] is not None else None
|
|
||||||
|
|
||||||
disc_inr = f"₹{v_inr:.2f}"
|
|
||||||
disc_usd = f"${v_usd:.2f}" if v_usd is not None else "—"
|
|
||||||
disc_eur = f"€{v_eur:.2f}" if v_eur is not None else "—"
|
|
||||||
|
|
||||||
cap_inr = "N/A (Flat)"
|
|
||||||
cap_usd = "N/A (Flat)"
|
|
||||||
cap_eur = "N/A (Flat)"
|
|
||||||
|
|
||||||
min_inr_num = float(c_mins.get("INR", c.min_purchase_amount or 0.0))
|
|
||||||
min_usd_num = float(c_mins.get("USD", 0.0)) if "USD" in c_mins and c_mins["USD"] is not None else None
|
|
||||||
min_eur_num = float(c_mins.get("EUR", 0.0)) if "EUR" in c_mins and c_mins["EUR"] is not None else None
|
|
||||||
|
|
||||||
min_inr = f"₹{min_inr_num:.2f}" if min_inr_num > 0 else "0.00"
|
|
||||||
min_usd = f"${min_usd_num:.2f}" if min_usd_num and min_usd_num > 0 else "0.00"
|
|
||||||
min_eur = f"€{min_eur_num:.2f}" if min_eur_num and min_eur_num > 0 else "0.00"
|
|
||||||
|
|
||||||
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
|
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
|
||||||
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
|
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
|
||||||
|
|
||||||
|
|
@ -365,16 +291,10 @@ class AdminReportService:
|
||||||
c.code,
|
c.code,
|
||||||
(c.coupon_category or "general").title(),
|
(c.coupon_category or "general").title(),
|
||||||
c.description or "",
|
c.description or "",
|
||||||
|
disc_val,
|
||||||
(c.discount_type or "").capitalize(),
|
(c.discount_type or "").capitalize(),
|
||||||
disc_inr,
|
max_cap,
|
||||||
disc_usd,
|
min_spend,
|
||||||
disc_eur,
|
|
||||||
cap_inr,
|
|
||||||
cap_usd,
|
|
||||||
cap_eur,
|
|
||||||
min_inr,
|
|
||||||
min_usd,
|
|
||||||
min_eur,
|
|
||||||
usage_count,
|
usage_count,
|
||||||
usage_limit_str,
|
usage_limit_str,
|
||||||
remaining_str,
|
remaining_str,
|
||||||
|
|
|
||||||
|
|
@ -238,24 +238,6 @@ class AuthService:
|
||||||
if user is None:
|
if user is None:
|
||||||
raise UserNotFoundError("User not found.")
|
raise UserNotFoundError("User not found.")
|
||||||
|
|
||||||
# Keep default user billing profile in sync with updated contact info
|
|
||||||
from app.db.models import UserBillingProfile
|
|
||||||
from sqlalchemy import update
|
|
||||||
bp_values: dict[str, object] = {}
|
|
||||||
if full_name:
|
|
||||||
bp_values["billing_name"] = full_name
|
|
||||||
if phone:
|
|
||||||
bp_values["billing_phone"] = phone
|
|
||||||
if country:
|
|
||||||
bp_values["country"] = country
|
|
||||||
if bp_values:
|
|
||||||
await self.session.execute(
|
|
||||||
update(UserBillingProfile)
|
|
||||||
.where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
|
||||||
.values(**bp_values)
|
|
||||||
)
|
|
||||||
await self.session.flush()
|
|
||||||
|
|
||||||
roles = await self.repository.get_user_roles(user.id)
|
roles = await self.repository.get_user_roles(user.id)
|
||||||
if not roles:
|
if not roles:
|
||||||
roles = [PRACTITIONER_ROLE]
|
roles = [PRACTITIONER_ROLE]
|
||||||
|
|
|
||||||
|
|
@ -173,42 +173,27 @@ class CartRepository:
|
||||||
value = Decimal(coupon.value)
|
value = Decimal(coupon.value)
|
||||||
if coupon.discount_type in {"flat", "flat_amount"}:
|
if coupon.discount_type in {"flat", "flat_amount"}:
|
||||||
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
|
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
|
||||||
if isinstance(currency_values, dict) and currency.upper() in currency_values and currency_values[currency.upper()] is not None:
|
if isinstance(currency_values, dict) and currency.upper() in currency_values:
|
||||||
value = Decimal(str(currency_values[currency.upper()]))
|
value = Decimal(str(currency_values[currency.upper()]))
|
||||||
|
|
||||||
max_cap = Decimal(coupon.max_discount_limit or 0)
|
|
||||||
currency_caps = metadata.get("currency_caps") if isinstance(metadata, dict) else None
|
|
||||||
if isinstance(currency_caps, dict) and currency.upper() in currency_caps and currency_caps[currency.upper()] is not None:
|
|
||||||
max_cap = Decimal(str(currency_caps[currency.upper()]))
|
|
||||||
|
|
||||||
min_spend = Decimal(str(coupon.min_purchase_amount or 0))
|
min_spend = Decimal(str(coupon.min_purchase_amount or 0))
|
||||||
currency_min_spends = metadata.get("currency_min_spends") if isinstance(metadata, dict) else None
|
|
||||||
if isinstance(currency_min_spends, dict) and currency.upper() in currency_min_spends and currency_min_spends[currency.upper()] is not None:
|
|
||||||
min_spend = Decimal(str(currency_min_spends[currency.upper()]))
|
|
||||||
|
|
||||||
app_plan_ids: set[str] = set()
|
app_plan_ids: set[str] = set()
|
||||||
if coupon.applicable_plan_ids:
|
if coupon.applicable_plan_ids:
|
||||||
for pid in coupon.applicable_plan_ids:
|
for pid in coupon.applicable_plan_ids:
|
||||||
app_plan_ids.add(str(pid))
|
app_plan_ids.add(str(pid))
|
||||||
# Include paired currency versions (e.g. LIFETIME_ALL, LIFETIME_ALL_USD, LIFETIME_ALL_EUR)
|
# Include paired currency versions (e.g. LIFETIME_ALL and LIFETIME_ALL_USD)
|
||||||
p_rows = (await self.session.execute(
|
p_rows = (await self.session.execute(
|
||||||
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
|
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
base_codes: set[str] = set()
|
base_codes: set[str] = set()
|
||||||
for c in p_rows:
|
for c in p_rows:
|
||||||
code_up = c.upper()
|
code_up = c.upper()
|
||||||
if code_up.endswith("_USD"):
|
base_codes.add(code_up[:-4] if code_up.endswith("_USD") else code_up)
|
||||||
base_codes.add(code_up[:-4])
|
|
||||||
elif code_up.endswith("_EUR"):
|
|
||||||
base_codes.add(code_up[:-4])
|
|
||||||
else:
|
|
||||||
base_codes.add(code_up)
|
|
||||||
if base_codes:
|
if base_codes:
|
||||||
sibling_codes: set[str] = set()
|
sibling_codes: set[str] = set()
|
||||||
for bc in base_codes:
|
for bc in base_codes:
|
||||||
sibling_codes.add(bc)
|
sibling_codes.add(bc)
|
||||||
sibling_codes.add(f"{bc}_USD")
|
sibling_codes.add(f"{bc}_USD")
|
||||||
sibling_codes.add(f"{bc}_EUR")
|
|
||||||
sibling_rows = (await self.session.execute(
|
sibling_rows = (await self.session.execute(
|
||||||
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
|
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
|
|
@ -223,7 +208,7 @@ class CartRepository:
|
||||||
discount_type=coupon.discount_type,
|
discount_type=coupon.discount_type,
|
||||||
value=value,
|
value=value,
|
||||||
description=coupon.description,
|
description=coupon.description,
|
||||||
max_discount_limit=max_cap,
|
max_discount_limit=Decimal(coupon.max_discount_limit or 0),
|
||||||
min_purchase_amount=min_spend,
|
min_purchase_amount=min_spend,
|
||||||
applicable_plan_ids=tuple(app_plan_ids),
|
applicable_plan_ids=tuple(app_plan_ids),
|
||||||
applicable_module_ids=app_mod_ids,
|
applicable_module_ids=app_mod_ids,
|
||||||
|
|
|
||||||
|
|
@ -57,14 +57,6 @@ class CheckoutService:
|
||||||
await self.session.flush()
|
await self.session.flush()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
else:
|
|
||||||
try:
|
|
||||||
edit_data: dict[str, Any] = {"name": user.display_name or user.email, "email": user.email}
|
|
||||||
if user.phone_number:
|
|
||||||
edit_data["contact"] = user.phone_number
|
|
||||||
rzp.client.customer.edit(user.external_ref, data=edit_data)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
||||||
applied_coupon_code = (
|
applied_coupon_code = (
|
||||||
request.coupon_code.strip().upper()
|
request.coupon_code.strip().upper()
|
||||||
|
|
@ -193,19 +185,6 @@ class CheckoutService:
|
||||||
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
||||||
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
||||||
if profile:
|
if profile:
|
||||||
# Synchronize default/auto-generated profile with user's latest verified contact details
|
|
||||||
updated = False
|
|
||||||
if user.phone_number and profile.billing_phone != user.phone_number:
|
|
||||||
profile.billing_phone = user.phone_number
|
|
||||||
updated = True
|
|
||||||
if user.country and profile.country != user.country:
|
|
||||||
profile.country = user.country
|
|
||||||
updated = True
|
|
||||||
if user.display_name and profile.billing_name != user.display_name:
|
|
||||||
profile.billing_name = user.display_name
|
|
||||||
updated = True
|
|
||||||
if updated:
|
|
||||||
await self.session.flush()
|
|
||||||
return profile
|
return profile
|
||||||
profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True)
|
profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True)
|
||||||
self.session.add(profile)
|
self.session.add(profile)
|
||||||
|
|
@ -224,31 +203,8 @@ class CheckoutService:
|
||||||
) -> tuple[Invoice, str | None]:
|
) -> tuple[Invoice, str | None]:
|
||||||
currency = tx.currency.upper()
|
currency = tx.currency.upper()
|
||||||
inv_number = await generate_next_invoice_number(self.session)
|
inv_number = await generate_next_invoice_number(self.session)
|
||||||
|
|
||||||
# Prioritize current verified user phone and country
|
|
||||||
phone_to_use = profile.billing_phone or payment.get("contact")
|
|
||||||
country_to_use = profile.country or "India"
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cust_data: dict[str, Any] = {
|
rzp.client.invoice.create(data={"type":"invoice","customer":{"name":profile.billing_name,"email":profile.billing_email, **({"contact": profile.billing_phone} if profile.billing_phone else {})},"line_items":[{"name": (", ".join(plan_names) or "Access Subscription")[:250],"amount": int(Decimal(tx.amount)*100),"currency":currency,"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":tx.gateway_transaction_id}})
|
||||||
"name": profile.billing_name,
|
|
||||||
"email": profile.billing_email,
|
|
||||||
}
|
|
||||||
if phone_to_use:
|
|
||||||
cust_data["contact"] = phone_to_use
|
|
||||||
rzp.client.invoice.create(data={
|
|
||||||
"type": "invoice",
|
|
||||||
"customer": cust_data,
|
|
||||||
"line_items": [{
|
|
||||||
"name": (", ".join(plan_names) or "Access Subscription")[:250],
|
|
||||||
"amount": int(Decimal(tx.amount) * 100),
|
|
||||||
"currency": currency,
|
|
||||||
"quantity": 1,
|
|
||||||
}],
|
|
||||||
"email_notify": False,
|
|
||||||
"sms_notify": False,
|
|
||||||
"notes": {"payment_id": tx.gateway_transaction_id},
|
|
||||||
})
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
# Always use internal branded Acupedia Tax Invoice view URL
|
# Always use internal branded Acupedia Tax Invoice view URL
|
||||||
|
|
@ -257,20 +213,12 @@ class CheckoutService:
|
||||||
discount = Decimal(str(meta.get("total_discounts", 0)))
|
discount = Decimal(str(meta.get("total_discounts", 0)))
|
||||||
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
||||||
gst = Decimal(str(meta.get("gst_amount", 0)))
|
gst = Decimal(str(meta.get("gst_amount", 0)))
|
||||||
|
|
||||||
# Build clean address with current country
|
|
||||||
addr_parts = [profile.address_line1, profile.city, profile.state, profile.postal_code]
|
|
||||||
clean_parts = [p.strip() for p in addr_parts if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]]
|
|
||||||
if country_to_use and country_to_use.strip().lower() not in ["not configured", "none", "null"]:
|
|
||||||
clean_parts.append(country_to_use.strip())
|
|
||||||
final_billing_address = ", ".join(clean_parts) if clean_parts else (country_to_use or "Digital Access")
|
|
||||||
|
|
||||||
invoice = Invoice(
|
invoice = Invoice(
|
||||||
payment_transaction_id=tx.id,
|
payment_transaction_id=tx.id,
|
||||||
invoice_number=inv_number,
|
invoice_number=inv_number,
|
||||||
billing_name=profile.billing_name,
|
billing_name=profile.billing_name,
|
||||||
billing_email=profile.billing_email,
|
billing_email=profile.billing_email,
|
||||||
billing_address=final_billing_address,
|
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}",
|
||||||
gstin=profile.gstin,
|
gstin=profile.gstin,
|
||||||
billing_profile_id=profile.id,
|
billing_profile_id=profile.id,
|
||||||
applied_coupon_id=applied_coupon_id,
|
applied_coupon_id=applied_coupon_id,
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,13 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
||||||
code = p.code
|
code = p.code
|
||||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
||||||
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
|
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
|
||||||
base_code = code[:-4] if (code.endswith("_USD") or code.endswith("_EUR")) else code
|
|
||||||
|
if code.endswith("_USD"):
|
||||||
|
base_code = code[:-4]
|
||||||
|
elif code.endswith("_EUR"):
|
||||||
|
base_code = code[:-4]
|
||||||
|
else:
|
||||||
|
base_code = code
|
||||||
|
|
||||||
pid_str = str(p.id)
|
pid_str = str(p.id)
|
||||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||||
|
|
@ -72,7 +78,7 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
||||||
grp = groups[base_code]
|
grp = groups[base_code]
|
||||||
if is_usd:
|
if is_usd:
|
||||||
grp["price_usd"] = fee
|
grp["price_usd"] = fee
|
||||||
if not grp.get("price_eur"):
|
if grp["price_eur"] == 0.0:
|
||||||
grp["price_eur"] = fee # Default fallback if explicit EUR plan not present
|
grp["price_eur"] = fee # Default fallback if explicit EUR plan not present
|
||||||
elif is_eur:
|
elif is_eur:
|
||||||
grp["price_eur"] = fee
|
grp["price_eur"] = fee
|
||||||
|
|
|
||||||
|
|
@ -39,18 +39,11 @@ With the clean Acupedia naming conventions:
|
||||||
- **Database**: `acupedia_db`
|
- **Database**: `acupedia_db`
|
||||||
- **User**: `db_admin` / Password: `C1234spl`
|
- **User**: `db_admin` / Password: `C1234spl`
|
||||||
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
|
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
|
||||||
- **MinIO Bucket**: `acupedia-media`
|
- **MinIO Bucket**: `accupedia-media`
|
||||||
|
|
||||||
### Step 2.1: Generate Container Git Info Metadata (Recommended)
|
|
||||||
Before building, run the script to capture the branch and commit of `api`, `store`, and `admin`:
|
|
||||||
|
|
||||||
|
### Start the containers:
|
||||||
```bash
|
```bash
|
||||||
cd ~/acupedia/acupedia_ops
|
cd ~/acupedia/acupedia_ops
|
||||||
./scripts/generate-git-info.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 2.2: Start the Containers
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose.dev.yml up -d --build
|
docker compose -f docker-compose.dev.yml up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -70,20 +63,7 @@ docker compose -f docker-compose.dev.yml exec backend \
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Step 3.2: Run Alembic Migrations (Module Builder & Dynamic Content)
|
### Step 3.2: Seed Authentication & Super Admin User
|
||||||
Stamps the baseline DDL (schema v5 includes migrations up to `0003`) and applies new migrations (such as Module Builder tables `content.builder_modules`, `content.builder_categories`, etc.):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose.dev.yml exec backend \
|
|
||||||
alembic stamp 0003_monthly_invoice_seq
|
|
||||||
|
|
||||||
docker compose -f docker-compose.dev.yml exec backend \
|
|
||||||
alembic upgrade head
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Step 3.3: Seed Authentication & Super Admin User
|
|
||||||
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
|
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -95,7 +75,7 @@ docker compose -f docker-compose.dev.yml exec -e ACCUPEDIA_BOOTSTRAP_ADMIN_PASSW
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Step 3.4: Seed Content & Modules
|
### Step 3.3: Seed Content & Modules
|
||||||
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
|
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -109,7 +89,7 @@ docker compose -f docker-compose.dev.yml exec backend \
|
||||||
---
|
---
|
||||||
|
|
||||||
### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
|
### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
|
||||||
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`acupedia-media` bucket) and links them to their respective content items in PostgreSQL:
|
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`accupedia-media` bucket) and links them to their respective content items in PostgreSQL:
|
||||||
|
|
||||||
**Option A (Recommended — Automated 1-line loop for all 4 modules):**
|
**Option A (Recommended — Automated 1-line loop for all 4 modules):**
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -206,25 +186,3 @@ After running the manual steps above, test your endpoints:
|
||||||
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
|
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
|
||||||
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
|
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
|
||||||
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
|
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
|
||||||
|
|
||||||
### Git Identity Verification (Inspect Container Branch & Commit)
|
|
||||||
|
|
||||||
To verify which branch and commit are running inside each container:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1. API Backend
|
|
||||||
docker compose -f docker-compose.dev.yml exec backend cat /app/.git_api_info
|
|
||||||
|
|
||||||
# 2. Storefront
|
|
||||||
docker compose -f docker-compose.dev.yml exec store cat /app/.git_store_info
|
|
||||||
|
|
||||||
# 3. Admin Portal
|
|
||||||
docker compose -f docker-compose.dev.yml exec admin cat /app/.git_admin_info
|
|
||||||
```
|
|
||||||
|
|
||||||
Example output:
|
|
||||||
```text
|
|
||||||
Branch: main
|
|
||||||
Commit: 29279bfd72a6fa296d1aa05a825bd88ca1f36c91
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
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)
|
|
||||||
|
|
@ -1,159 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
import csv
|
|
||||||
import io
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from decimal import Decimal
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
from uuid import uuid4
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.db.enums import PaymentStatus, SubscriptionStatus
|
|
||||||
from app.db.models import AppUser, AccessPlan, Coupon, PaymentTransaction, UserSubscription
|
|
||||||
from app.features.admin.services.report_service import AdminReportService
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_export_report_csv_customers_multi_currency() -> None:
|
|
||||||
uid = uuid4()
|
|
||||||
mock_user = MagicMock(spec=AppUser)
|
|
||||||
mock_user.id = uid
|
|
||||||
mock_user.display_name = "Jane Doe"
|
|
||||||
mock_user.email = "jane@example.com"
|
|
||||||
mock_user.phone_number = "+4912345678"
|
|
||||||
mock_user.country = "Germany"
|
|
||||||
mock_user.is_active = True
|
|
||||||
mock_user.created_at = datetime(2026, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
# 1. select users
|
|
||||||
res_users = MagicMock()
|
|
||||||
res_users.scalars.return_value.all.return_value = [mock_user]
|
|
||||||
|
|
||||||
# 2. select user_roles
|
|
||||||
res_roles = MagicMock()
|
|
||||||
res_roles.all.return_value = []
|
|
||||||
|
|
||||||
# 3. select tx_summary_rows (user_id, currency, count, sum)
|
|
||||||
res_tx = MagicMock()
|
|
||||||
res_tx.all.return_value = [
|
|
||||||
(uid, "EUR", 2, Decimal("40.00")),
|
|
||||||
(uid, "INR", 1, Decimal("500.00")),
|
|
||||||
]
|
|
||||||
|
|
||||||
# 4. select sub_count_rows
|
|
||||||
res_sub = MagicMock()
|
|
||||||
res_sub.all.return_value = [(uid, 1)]
|
|
||||||
|
|
||||||
mock_session.execute.side_effect = [res_users, res_roles, res_tx, res_sub]
|
|
||||||
|
|
||||||
svc = AdminReportService(mock_session)
|
|
||||||
response = await svc.export_report_csv("customers", None, None)
|
|
||||||
|
|
||||||
# Read streamed content
|
|
||||||
chunks = [chunk async for chunk in response.body_iterator]
|
|
||||||
csv_text = b"".join(chunks).decode("utf-8")
|
|
||||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
|
||||||
|
|
||||||
headers = reader[0]
|
|
||||||
assert "Lifetime Spend (INR)" in headers
|
|
||||||
assert "Lifetime Spend (USD)" in headers
|
|
||||||
assert "Lifetime Spend (EUR)" in headers
|
|
||||||
|
|
||||||
row = reader[1]
|
|
||||||
assert row[1] == "Jane Doe"
|
|
||||||
assert row[8] == "500.00" # INR
|
|
||||||
assert row[9] == "0.00" # USD
|
|
||||||
assert row[10] == "40.00" # EUR
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_export_report_csv_subscriptions_multi_currency() -> None:
|
|
||||||
mock_sub = MagicMock(spec=UserSubscription)
|
|
||||||
mock_sub.id = uuid4()
|
|
||||||
mock_sub.status = SubscriptionStatus.ACTIVE
|
|
||||||
mock_sub.started_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
|
||||||
mock_sub.expires_at = None
|
|
||||||
mock_sub.payment_reference = "PAY_REF_123"
|
|
||||||
|
|
||||||
mock_plan = MagicMock(spec=AccessPlan)
|
|
||||||
mock_plan.code = "LIFETIME_ALL_EUR"
|
|
||||||
mock_plan.name = "Lifetime All EUR"
|
|
||||||
mock_plan.currency = "EUR"
|
|
||||||
mock_plan.billing_period = None
|
|
||||||
|
|
||||||
mock_user = MagicMock(spec=AppUser)
|
|
||||||
mock_user.display_name = "Hans Muller"
|
|
||||||
mock_user.email = "hans@example.de"
|
|
||||||
mock_user.phone_number = "+4912345"
|
|
||||||
mock_user.country = "Germany"
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
res_subs = MagicMock()
|
|
||||||
res_subs.all.return_value = [(mock_sub, mock_plan, mock_user)]
|
|
||||||
mock_session.execute.return_value = res_subs
|
|
||||||
|
|
||||||
svc = AdminReportService(mock_session)
|
|
||||||
response = await svc.export_report_csv("subscriptions", None, None)
|
|
||||||
|
|
||||||
chunks = [chunk async for chunk in response.body_iterator]
|
|
||||||
csv_text = b"".join(chunks).decode("utf-8")
|
|
||||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
|
||||||
|
|
||||||
headers = reader[0]
|
|
||||||
assert "Customer Country" in headers
|
|
||||||
assert "Plan Currency" in headers
|
|
||||||
|
|
||||||
row = reader[1]
|
|
||||||
assert row[4] == "Germany"
|
|
||||||
assert row[7] == "EUR"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_export_report_csv_coupons_multi_currency() -> None:
|
|
||||||
mock_coupon = MagicMock(spec=Coupon)
|
|
||||||
mock_coupon.id = uuid4()
|
|
||||||
mock_coupon.code = "EUR50"
|
|
||||||
mock_coupon.coupon_category = "seasonal"
|
|
||||||
mock_coupon.description = "Winter sale"
|
|
||||||
mock_coupon.discount_type = "flat"
|
|
||||||
mock_coupon.value = Decimal("500.00")
|
|
||||||
mock_coupon.max_discount_limit = Decimal("0.00")
|
|
||||||
mock_coupon.min_purchase_amount = Decimal("1000.00")
|
|
||||||
mock_coupon.usage_count = 5
|
|
||||||
mock_coupon.usage_limit = 100
|
|
||||||
mock_coupon.is_active = True
|
|
||||||
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
|
||||||
mock_coupon.end_date = datetime(2026, 12, 31, tzinfo=timezone.utc)
|
|
||||||
mock_coupon.metadata_json = {
|
|
||||||
"currency_values": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
|
|
||||||
"currency_min_spends": {"INR": 1000.0, "USD": 12.0, "EUR": 11.0},
|
|
||||||
}
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
res_coupons = MagicMock()
|
|
||||||
res_coupons.scalars.return_value.all.return_value = [mock_coupon]
|
|
||||||
|
|
||||||
res_redemptions = MagicMock()
|
|
||||||
res_redemptions.all.return_value = [(mock_coupon.id, 5)]
|
|
||||||
|
|
||||||
mock_session.execute.side_effect = [res_coupons, res_redemptions]
|
|
||||||
|
|
||||||
svc = AdminReportService(mock_session)
|
|
||||||
response = await svc.export_report_csv("coupons", None, None)
|
|
||||||
|
|
||||||
chunks = [chunk async for chunk in response.body_iterator]
|
|
||||||
csv_text = b"".join(chunks).decode("utf-8")
|
|
||||||
reader = list(csv.reader(io.StringIO(csv_text)))
|
|
||||||
|
|
||||||
headers = reader[0]
|
|
||||||
assert "Discount (INR)" in headers
|
|
||||||
assert "Discount (USD)" in headers
|
|
||||||
assert "Discount (EUR)" in headers
|
|
||||||
assert "Min Purchase (EUR)" in headers
|
|
||||||
|
|
||||||
row = reader[1]
|
|
||||||
assert row[0] == "EUR50"
|
|
||||||
assert row[4] == "₹500.00"
|
|
||||||
assert row[5] == "$6.00"
|
|
||||||
assert row[6] == "€5.50"
|
|
||||||
assert row[12] == "€11.00"
|
|
||||||
|
|
@ -1,91 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
from decimal import Decimal
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
from uuid import uuid4
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.db.models import Coupon, AccessPlan
|
|
||||||
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
|
|
||||||
from app.features.admin.services.coupon_service import _build_coupon_metadata
|
|
||||||
from app.features.cart.repository import CartRepository
|
|
||||||
|
|
||||||
|
|
||||||
def test_build_coupon_metadata_multi_currency() -> None:
|
|
||||||
req = CreateCouponRequest(
|
|
||||||
code="SAVEBIG",
|
|
||||||
discount_type="flat",
|
|
||||||
value=500.0,
|
|
||||||
value_inr=500.0,
|
|
||||||
value_usd=6.0,
|
|
||||||
value_eur=5.5,
|
|
||||||
max_discount_limit=500.0,
|
|
||||||
max_discount_inr=500.0,
|
|
||||||
max_discount_usd=6.0,
|
|
||||||
max_discount_eur=5.5,
|
|
||||||
min_purchase_amount=1000.0,
|
|
||||||
min_purchase_inr=1000.0,
|
|
||||||
min_purchase_usd=12.0,
|
|
||||||
min_purchase_eur=11.0,
|
|
||||||
)
|
|
||||||
meta = _build_coupon_metadata(req)
|
|
||||||
assert meta["currency_values"] == {"INR": 500.0, "USD": 6.0, "EUR": 5.5}
|
|
||||||
assert meta["currency_caps"] == {"INR": 500.0, "USD": 6.0, "EUR": 5.5}
|
|
||||||
assert meta["currency_min_spends"] == {"INR": 1000.0, "USD": 12.0, "EUR": 11.0}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_get_coupon_resolves_eur_pricing_and_siblings() -> None:
|
|
||||||
plan_inr_id = uuid4()
|
|
||||||
plan_usd_id = uuid4()
|
|
||||||
plan_eur_id = uuid4()
|
|
||||||
|
|
||||||
mock_coupon = MagicMock(spec=Coupon)
|
|
||||||
mock_coupon.code = "EURPROMO"
|
|
||||||
mock_coupon.coupon_category = "general"
|
|
||||||
mock_coupon.discount_type = "flat"
|
|
||||||
mock_coupon.value = Decimal("500.00")
|
|
||||||
mock_coupon.max_discount_limit = Decimal("500.00")
|
|
||||||
mock_coupon.min_purchase_amount = Decimal("1000.00")
|
|
||||||
mock_coupon.is_active = True
|
|
||||||
mock_coupon.usage_limit = 0
|
|
||||||
mock_coupon.usage_count = 0
|
|
||||||
from datetime import datetime, timezone, timedelta
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
mock_coupon.start_date = now - timedelta(days=1)
|
|
||||||
mock_coupon.end_date = now + timedelta(days=30)
|
|
||||||
mock_coupon.applicable_plan_ids = [plan_inr_id]
|
|
||||||
mock_coupon.applicable_module_ids = None
|
|
||||||
mock_coupon.description = "Save in EUR"
|
|
||||||
mock_coupon.metadata_json = {
|
|
||||||
"currency_values": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
|
|
||||||
"currency_caps": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
|
|
||||||
"currency_min_spends": {"INR": 1000.0, "USD": 12.0, "EUR": 11.0},
|
|
||||||
}
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
# 1st execute: select Coupon
|
|
||||||
first_res = MagicMock()
|
|
||||||
first_res.scalar_one_or_none.return_value = mock_coupon
|
|
||||||
|
|
||||||
# 2nd execute: select AccessPlan.code where id in coupon.applicable_plan_ids
|
|
||||||
second_res = MagicMock()
|
|
||||||
second_res.scalars.return_value.all.return_value = ["LIFETIME_ALL"]
|
|
||||||
|
|
||||||
# 3rd execute: select AccessPlan.id where code in sibling_codes
|
|
||||||
third_res = MagicMock()
|
|
||||||
third_res.scalars.return_value.all.return_value = [plan_inr_id, plan_usd_id, plan_eur_id]
|
|
||||||
|
|
||||||
mock_session.execute.side_effect = [first_res, second_res, third_res]
|
|
||||||
|
|
||||||
repo = CartRepository(mock_session)
|
|
||||||
pricing_coupon, err = await repo.get_coupon("EURPROMO", "EUR")
|
|
||||||
|
|
||||||
assert err is None
|
|
||||||
assert pricing_coupon is not None
|
|
||||||
assert pricing_coupon.value == Decimal("5.5")
|
|
||||||
assert pricing_coupon.max_discount_limit == Decimal("5.5")
|
|
||||||
assert pricing_coupon.min_purchase_amount == Decimal("11.0")
|
|
||||||
# All 3 sibling plans should be present
|
|
||||||
assert str(plan_inr_id) in pricing_coupon.applicable_plan_ids
|
|
||||||
assert str(plan_usd_id) in pricing_coupon.applicable_plan_ids
|
|
||||||
assert str(plan_eur_id) in pricing_coupon.applicable_plan_ids
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from decimal import Decimal
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
from uuid import uuid4
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.db.models import AppUser, UserBillingProfile, PaymentTransaction, Invoice
|
|
||||||
from app.features.checkout.service import CheckoutService
|
|
||||||
from app.features.admin.services.payment_service import AdminPaymentService
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_checkout_billing_profile_syncs_updated_user_details() -> None:
|
|
||||||
uid = uuid4()
|
|
||||||
mock_user = MagicMock(spec=AppUser)
|
|
||||||
mock_user.id = uid
|
|
||||||
mock_user.display_name = "Updated User"
|
|
||||||
mock_user.email = "user@example.com"
|
|
||||||
mock_user.phone_number = "+491512345678" # New phone number
|
|
||||||
mock_user.country = "Germany" # New country
|
|
||||||
|
|
||||||
# Existing profile with OLD phone and country
|
|
||||||
existing_profile = UserBillingProfile(
|
|
||||||
id=uuid4(),
|
|
||||||
user_id=uid,
|
|
||||||
label="Default Auto-Generated",
|
|
||||||
billing_name="Initial Name",
|
|
||||||
billing_email="user@example.com",
|
|
||||||
billing_phone="+919876543210", # Old phone number
|
|
||||||
country="India", # Old country
|
|
||||||
address_line1="Not Configured",
|
|
||||||
city="Not Configured",
|
|
||||||
state="Not Configured",
|
|
||||||
postal_code="000000",
|
|
||||||
is_default=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
mock_exec_res = MagicMock()
|
|
||||||
mock_exec_res.scalar_one_or_none.return_value = existing_profile
|
|
||||||
mock_session.execute.return_value = mock_exec_res
|
|
||||||
|
|
||||||
mock_cart_repo = MagicMock()
|
|
||||||
service = CheckoutService(session=mock_session, cart_repository=mock_cart_repo)
|
|
||||||
|
|
||||||
profile = await service._billing_profile(mock_user, None)
|
|
||||||
|
|
||||||
assert profile.billing_phone == "+491512345678"
|
|
||||||
assert profile.country == "Germany"
|
|
||||||
assert profile.billing_name == "Updated User"
|
|
||||||
assert mock_session.flush.called
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_render_invoice_html_uses_updated_phone_and_country() -> None:
|
|
||||||
tx_id = uuid4()
|
|
||||||
mock_tx = MagicMock(spec=PaymentTransaction)
|
|
||||||
mock_tx.id = tx_id
|
|
||||||
mock_tx.user_id = uuid4()
|
|
||||||
mock_tx.gateway_transaction_id = "pay_test123"
|
|
||||||
mock_tx.amount = Decimal("15.00")
|
|
||||||
mock_tx.currency = "EUR"
|
|
||||||
mock_tx.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
|
|
||||||
mock_tx.subscription_id = None
|
|
||||||
|
|
||||||
mock_user = MagicMock(spec=AppUser)
|
|
||||||
mock_user.display_name = "Hans Schmidt"
|
|
||||||
mock_user.email = "hans@example.de"
|
|
||||||
mock_user.phone_number = "+491701122334" # Updated phone
|
|
||||||
mock_user.country = "Germany" # Updated country
|
|
||||||
|
|
||||||
mock_invoice = MagicMock(spec=Invoice)
|
|
||||||
mock_invoice.invoice_number = "INV-2026-0001"
|
|
||||||
mock_invoice.billing_name = "Hans Schmidt"
|
|
||||||
mock_invoice.billing_email = "hans@example.de"
|
|
||||||
mock_invoice.billing_address = "Germany"
|
|
||||||
mock_invoice.currency_code = "EUR"
|
|
||||||
mock_invoice.total_amount = Decimal("15.00")
|
|
||||||
mock_invoice.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
|
|
||||||
|
|
||||||
# Profile with older phone
|
|
||||||
mock_profile = MagicMock(spec=UserBillingProfile)
|
|
||||||
mock_profile.billing_name = "Hans Schmidt"
|
|
||||||
mock_profile.billing_email = "hans@example.de"
|
|
||||||
mock_profile.billing_phone = "+919999988888"
|
|
||||||
mock_profile.country = "India"
|
|
||||||
mock_profile.address_line1 = "Not Configured"
|
|
||||||
mock_profile.city = "Not Configured"
|
|
||||||
mock_profile.state = "Not Configured"
|
|
||||||
mock_profile.postal_code = "000000"
|
|
||||||
|
|
||||||
mock_session = AsyncMock()
|
|
||||||
r_tx = MagicMock()
|
|
||||||
r_tx.scalar_one_or_none.return_value = mock_tx
|
|
||||||
r_user = MagicMock()
|
|
||||||
r_user.scalar_one_or_none.return_value = mock_user
|
|
||||||
r_inv = MagicMock()
|
|
||||||
r_inv.scalar_one_or_none.return_value = mock_invoice
|
|
||||||
r_prof = MagicMock()
|
|
||||||
r_prof.scalar_one_or_none.return_value = mock_profile
|
|
||||||
|
|
||||||
mock_session.execute.side_effect = [r_tx, r_user, r_inv, r_prof]
|
|
||||||
|
|
||||||
svc = AdminPaymentService(mock_session)
|
|
||||||
response = await svc.render_invoice_html("pay_test123")
|
|
||||||
|
|
||||||
html = response.body.decode("utf-8")
|
|
||||||
assert "+491701122334" in html
|
|
||||||
assert "+919999988888" not in html
|
|
||||||
assert "Germany" in html
|
|
||||||
Loading…
Reference in New Issue