bug(invalid-discount): removed unintended legacy staggered cross-module discount calculation, implemented discount rules from the docs #16

Merged
amit merged 2 commits from discount-issue into main 2026-10-20 04:50:49 +00:00
17 changed files with 238 additions and 58 deletions
Showing only changes of commit 9d6be8d29b - Show all commits

2
.git_api_info Normal file
View File

@ -0,0 +1,2 @@
Branch: main
Commit: 29279bfd72a6fa296d1aa05a825bd88ca1f36c91

4
.gitignore vendored
View File

@ -28,5 +28,5 @@ htmlcov/
.DS_Store
Thumbs.db
# Generated Git Info
.git_*_info

View File

@ -23,6 +23,9 @@ COPY README.md ./
COPY docs/accupedia_db_v5.sql /app/schema/accupedia_db_v5.sql
COPY app ./app
# Copy git info metadata if generated on host
COPY .git_api_info* /app/.git_api_info
# Install project and CLI scripts into PATH
RUN pip install --no-cache-dir -e .
@ -32,3 +35,4 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD curl -f http://localhost:8000/ || exit 1
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

View File

@ -121,8 +121,17 @@ class ModuleSeeder:
from {self._schema}.content_items ci
join {self._schema}.attribute_definition_sets ads
on ads.id = ci.attribute_definition_set_id
left join {self._schema}.content_attributes ca
on ca.content_id = ci.id
and ca.attribute_definition_id = (
select id
from {self._schema}.attribute_definitions
where attribute_definition_set_id = ads.id
and code = 'sort_order'
limit 1
)
where ads.code = :definition_set_code
order by ci.sort_title asc, ci.id asc
order by ca.value_number asc nulls last, ci.sort_title asc, ci.id asc
"""),
{"definition_set_code": definition_set_code},
)

View File

@ -300,6 +300,16 @@ class SeedOrchestrator:
# seeded by this invocation are candidates for module
# association. Never rewrite unrelated template rows.
content_ids = [result.content_id for result in batch.results]
elif batch.results:
# Preserve authored sequence from the source document.
content_ids = [result.content_id for result in batch.results]
known_ids = set(content_ids)
all_ids = await self._modules.resolve_content_ids_for_definition_set(
definition_set_code=mapping.code
)
for remaining_id in all_ids:
if remaining_id not in known_ids:
content_ids.append(remaining_id)
else:
content_ids = await self._modules.resolve_content_ids_for_definition_set(
definition_set_code=mapping.code

View File

@ -12,6 +12,8 @@ class ActiveSubscriptionRecord:
status: str
started_at: datetime
expires_at: datetime | None
payment_id: str | None = None
invoice_number: str | None = None
@dataclass(frozen=True, slots=True)

View File

@ -8,7 +8,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import EntitlementStatus, SubscriptionStatus
from app.db.models import (
AccessPlan,
Invoice,
Module,
PaymentTransaction,
UserEntitlement,
UserSubscription,
)
@ -41,6 +43,7 @@ class AccessRepository:
UserSubscription.status,
UserSubscription.started_at,
UserSubscription.expires_at,
UserSubscription.payment_reference,
)
.join(
AccessPlan,
@ -60,9 +63,31 @@ class AccessRepository:
)
)
# Lookup payment transaction & invoice for this user's subscriptions
tx_rows = (await self._session.execute(
select(
PaymentTransaction.subscription_id,
PaymentTransaction.gateway_transaction_id,
Invoice.invoice_number,
UserSubscription.payment_reference,
)
.join(UserSubscription, UserSubscription.id == PaymentTransaction.subscription_id)
.outerjoin(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id)
.where(PaymentTransaction.user_id == user_id)
)).all()
sub_tx_map: dict[UUID, tuple[str, str | None]] = {}
order_tx_map: dict[str, tuple[str, str | None]] = {}
for sub_id, gw_tx_id, inv_num, order_ref in tx_rows:
if sub_id:
sub_tx_map[sub_id] = (gw_tx_id, inv_num)
if order_ref:
order_tx_map[order_ref] = (gw_tx_id, inv_num)
records: list[ActiveSubscriptionRecord] = []
for row in result.all():
status_value = getattr(row.status, "value", row.status)
gw_id, inv_num = sub_tx_map.get(row.id) or (order_tx_map.get(row.payment_reference) if row.payment_reference else (None, None))
records.append(
ActiveSubscriptionRecord(
id=row.id,
@ -70,6 +95,8 @@ class AccessRepository:
status=str(status_value),
started_at=row.started_at,
expires_at=row.expires_at,
payment_id=gw_id,
invoice_number=inv_num,
)
)
return records

View File

@ -16,6 +16,9 @@ class ActiveSubscriptionResponse(StrictModel):
status: str
started_at: datetime
expires_at: datetime | None = None
payment_id: str | None = None
invoice_number: str | None = None
invoice_url: str | None = None
class ActiveEntitlementResponse(StrictModel):

View File

@ -73,6 +73,9 @@ class AccessService:
status=item.status,
started_at=item.started_at,
expires_at=item.expires_at,
payment_id=item.payment_id,
invoice_number=item.invoice_number,
invoice_url=f"/api/checkout/payment/{item.payment_id}/invoice/view" if item.payment_id else None,
)
for item in subscriptions
],

View File

@ -258,7 +258,7 @@ class AdminPaymentService:
rzp = get_razorpay_service()
user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one()
if invoice and invoice.invoice_number and invoice.invoice_number.startswith("inv_"):
if invoice and invoice.invoice_number:
return f"/api/admin/payments/{payment_id}/invoice/view", invoice.invoice_number, user.email
profile = (await self.session.execute(
@ -389,7 +389,22 @@ class AdminPaymentService:
base_val = total_val
# Item description
item_desc = rzp_payment.get("description")
item_desc = rzp_payment.get("description") if rzp_payment else None
if not item_desc and tx:
if tx.subscription_id:
sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.id == tx.subscription_id))).scalar_one_or_none()
if sub:
ref = sub.payment_reference
subs = (await self.session.execute(
select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref)
)).scalars().all() if ref else [sub]
p_names = []
for s in subs:
p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none()
if p and p.name not in p_names:
p_names.append(p.name)
if p_names:
item_desc = ", ".join(p_names)
if not item_desc:
item_desc = "Clinical Access Plan Subscription"

View File

@ -74,6 +74,23 @@ class CartRepository:
matches[code] = (plan, Decimal(str(fee)))
break
if code not in matches:
for cand in cands:
plan = by_code.get(cand)
if not plan:
continue
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
plan_curr = plan.currency_code.upper()
if plan_curr == "INR" and curr == "USD":
matches[code] = (plan, max(Decimal("1.00"), (Decimal(str(fee)) / Decimal("80")).quantize(Decimal("1.00"))))
break
elif plan_curr == "USD" and curr == "INR":
matches[code] = (plan, (Decimal(str(fee)) * Decimal("80")).quantize(Decimal("1.00")))
break
elif fee is not None:
matches[code] = (plan, Decimal(str(fee)))
break
return matches
async def get_renewable_plan_codes(self, user_id: UUID) -> set[str]:
@ -125,7 +142,7 @@ class CartRepository:
if now < s_date:
return None, "This coupon code is not active yet."
if now > e_date:
return None, "Invalid or expired coupon code."
return None, "This coupon code has expired."
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
return None, "Coupon usage limit reached."
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
@ -134,18 +151,84 @@ class CartRepository:
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
if isinstance(currency_values, dict) and currency.upper() in currency_values:
value = Decimal(str(currency_values[currency.upper()]))
return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit)), None
min_spend = Decimal(str(coupon.min_purchase_amount or 0))
return PricingCoupon(
code=coupon.code,
category=coupon.coupon_category,
discount_type=coupon.discount_type,
value=value,
description=coupon.description,
max_discount_limit=Decimal(coupon.max_discount_limit or 0),
min_purchase_amount=min_spend,
), None
@staticmethod
def _module_category(module: Module) -> str:
metadata = module.metadata_json or {}
cat = metadata.get("commerce_category") or metadata.get("category")
if cat:
return str(cat)
kind = (metadata.get("kind") or "").lower()
if kind == "point": return "Points"
if kind in {"pattern", "five-elements"}: return "Pattern"
if kind == "nutrition": return "Nutrition"
if kind in {"therapeutic", "therapeutics"}: return "Therapeutics"
code = (module.code or "").lower()
name = (module.name or "").lower()
if code in {"m0001", "m0002", "m0003"} or "point" in name: return "Points"
if code.startswith("m001") or code == "m0020" or "pattern" in name or "principles" in name or "stages" in name or "levels" in name: return "Pattern"
if code == "m0031" or "nutrition" in name or "food" in name: return "Nutrition"
if code.startswith("m004") or "therapeutic" in name or "gynae" in name or "auriculo" in name: return "Therapeutics"
return "General"
async def get_owned_categories(self, user_id: UUID) -> list[str]:
rows = (await self.session.execute(select(UserEntitlement, Module).join(Module, Module.id == UserEntitlement.module_id).where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE))).all()
result: list[str] = []
for _, module in rows:
metadata = module.metadata_json or {}
category = metadata.get("commerce_category") or metadata.get("category")
if category:
result.append(str(category))
return result
result: set[str] = set()
# 1. From active UserSubscription
sub_plans = (await self.session.execute(
select(AccessPlan)
.join(UserSubscription, UserSubscription.plan_id == AccessPlan.id)
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
)).scalars().all()
for plan in sub_plans:
cat = self._category(plan)
if cat and cat != "General":
result.add(cat)
# 2. From active UserEntitlement via Module
ent_modules = (await self.session.execute(
select(Module)
.join(UserEntitlement, UserEntitlement.module_id == Module.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
)).scalars().all()
for module in ent_modules:
cat = self._module_category(module)
if cat and cat != "General":
result.add(cat)
# 3. From active UserEntitlement via source_plan_id
ent_plans = (await self.session.execute(
select(AccessPlan)
.join(UserEntitlement, UserEntitlement.source_plan_id == AccessPlan.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
)).scalars().all()
for plan in ent_plans:
cat = self._category(plan)
if cat and cat != "General":
result.add(cat)
return list(result)
async def is_first_purchase(self, user_id: UUID) -> bool:
exists = (await self.session.execute(select(UserSubscription.id).where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE).limit(1))).scalar_one_or_none()
return exists is None
has_sub = (await self.session.execute(
select(UserSubscription.id)
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
.limit(1)
)).scalar_one_or_none()
has_ent = (await self.session.execute(
select(UserEntitlement.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
.limit(1)
)).scalar_one_or_none()
return has_sub is None and has_ent is None

View File

@ -18,6 +18,10 @@ class CartService:
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency)
owned = await self.repository.get_owned_categories(user_id) if user_id else request.owned_category_names
owned = await self.repository.get_owned_categories(user_id) if user_id else []
if request.owned_category_names:
owned = list(set(owned + [c for c in request.owned_category_names if c]))
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
if owned:
first = False
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))

View File

@ -1,5 +1,6 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import HTMLResponse
from app.db.models import AppUser
from app.features.payments import get_razorpay_service
from .deps import get_checkout_service, get_current_user
@ -30,16 +31,21 @@ async def verify_checkout_payment(payload: CheckoutVerifyRequest, user: AppUser
async def get_checkout_payment_invoice(payment_id: str, user: AppUser = Depends(get_current_user), service: CheckoutService = Depends(get_checkout_service)):
from sqlalchemy import select
from app.db.models import PaymentTransaction
from app.features.admin.service import AdminService
tx = (await service.session.execute(select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id, PaymentTransaction.user_id == user.id))).scalar_one_or_none()
if not tx:
raise HTTPException(404, detail="Transaction record not found or access denied.")
return {"short_url": f"/api/checkout/payment/{payment_id}/invoice/view"}
@router.get("/payment/{payment_id}/invoice/view", response_class=HTMLResponse)
async def view_checkout_payment_invoice_html(
payment_id: str,
token: str | None = Query(None),
service: CheckoutService = Depends(get_checkout_service),
):
from app.features.admin.service import AdminService
try:
url, _, _ = await AdminService(service.session).get_or_create_invoice(payment_id)
if not url:
raise HTTPException(500, detail="Razorpay invoice does not have a download URL.")
return {"short_url": url}
except HTTPException:
raise
return await AdminService(service.session).render_invoice_html(payment_id)
except LookupError as exc:
raise HTTPException(404, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(502, detail=f"Failed to generate invoice from Razorpay: {exc}") from exc
raise HTTPException(500, detail=f"Failed to render HTML invoice: {exc}") from exc

View File

@ -129,17 +129,13 @@ class CheckoutService:
async def _create_invoice(self, rzp, tx: PaymentTransaction, profile: UserBillingProfile, payment: dict, plan_names: list[str], meta: dict) -> tuple[str, str | None]:
currency = tx.currency.upper()
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}"
inv_url = None
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{tx.gateway_transaction_id[-6:].upper()}"
try:
created = 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}})
inv_number = created.get("id") or inv_number
inv_url = created.get("short_url")
if created.get("status") == "draft":
issued = rzp.client.invoice.issue(inv_number)
inv_url = issued.get("short_url") or inv_url
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}})
except Exception:
pass
# Always use internal branded Acupedia Tax Invoice view URL
inv_url = f"/api/checkout/payment/{tx.gateway_transaction_id}/invoice/view"
base = Decimal(str(meta.get("base_subtotal", tx.amount)))
discount = Decimal(str(meta.get("total_discounts", 0)))
taxable = Decimal(str(meta.get("taxable_amount", 0)))

View File

@ -24,6 +24,7 @@ class PricingCoupon:
value: Decimal
description: str | None = None
max_discount_limit: Decimal = Decimal("0")
min_purchase_amount: Decimal = Decimal("0")
class PricingEngine:
"""Calculates checkout totals with Policy 5.1 Early Renewal Discount (20%) and coupon discounts."""
@ -44,18 +45,20 @@ class PricingEngine:
coupon_discount = Decimal("0")
coupon_text = "None"
if coupon:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type in {"flat", "flat_amount"}:
coupon_discount = min(coupon.value, after_renewal)
elif coupon.discount_type in {"percentage", "percent"}:
coupon_discount = after_renewal * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
if coupon.min_purchase_amount > 0 and after_renewal < coupon.min_purchase_amount:
coupon_error = f"Minimum cart spend of {curr} {coupon.min_purchase_amount} required to use coupon {coupon.code}."
coupon_text = "None"
coupon_discount = Decimal("0")
else:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type in {"flat", "flat_amount"}:
coupon_discount = min(coupon.value, after_renewal)
elif coupon.discount_type in {"percentage", "percent"}:
coupon_discount = after_renewal * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
net = max(Decimal("0"), after_renewal - coupon_discount)
fee_rate = Decimal("0.02") if curr == "INR" else Decimal("0.03")
fee = q(net * fee_rate)
gst = q(fee * Decimal("0.18")) if curr == "INR" else Decimal("0")
grand = q(net + fee + gst)
grand = q(net)
return {
"currency": curr,
"base_subtotal": float(q(base)),
@ -66,10 +69,10 @@ class PricingEngine:
"coupon_discount_amount": float(q(coupon_discount)),
"coupon_error": coupon_error,
"total_discounts": float(q(renewal_discount + coupon_discount)),
"convenience_fee_rate": float(fee_rate * 100),
"convenience_fee": float(fee),
"taxable_amount": float(fee),
"gst_amount": float(gst),
"convenience_fee_rate": 0.0,
"convenience_fee": 0.0,
"taxable_amount": 0.0,
"gst_amount": 0.0,
"grand_total": float(grand),
"cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price)), "is_renewal": i.is_renewal} for i in items],
}

View File

@ -17,7 +17,8 @@ dependencies = [
"uvicorn[standard]>=0.20.0",
"python-dotenv>=1.0.0",
"PyYAML>=6.0",
"SQLAlchemy>=2.0.0",
"SQLAlchemy[asyncio]>=2.0.0",
"greenlet>=3.0.0",
"asyncpg>=0.28.0",
"python-jose[cryptography]>=3.3.0",
"passlib[bcrypt]>=1.7.4",

View File

@ -57,8 +57,8 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
))
self.assertEqual(calc.currency, "USD")
self.assertEqual(calc.base_subtotal, 5.0)
self.assertEqual(calc.convenience_fee, 0.15)
self.assertEqual(calc.grand_total, 5.15)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.grand_total, 5.0)
self.assertEqual(len(calc.cart_items), 1)
self.assertEqual(calc.cart_items[0].code, "POINTS_ACU")
@ -69,9 +69,9 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
))
self.assertEqual(calc.currency, "INR")
self.assertEqual(calc.base_subtotal, 300.0)
self.assertEqual(calc.convenience_fee, 6.0)
self.assertEqual(calc.gst_amount, 1.08)
self.assertEqual(calc.grand_total, 307.08)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.gst_amount, 0.0)
self.assertEqual(calc.grand_total, 300.0)
async def test_multi_item_usd_cart(self):
calc = await self.service.calculate(CartCalculationRequest(
@ -80,10 +80,22 @@ class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
))
self.assertEqual(calc.currency, "USD")
self.assertEqual(calc.base_subtotal, 8.0)
self.assertEqual(calc.convenience_fee, 0.24)
self.assertEqual(calc.grand_total, 8.24)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.grand_total, 8.0)
self.assertEqual(len(calc.cart_items), 2)
async def test_no_unintended_bundle_discount_for_other_categories(self):
calc = await self.service.calculate(CartCalculationRequest(
cart_item_codes=["POINTS_ACU"],
owned_category_names=["Pattern", "Nutrition"],
currency="INR"
))
self.assertEqual(calc.currency, "INR")
self.assertEqual(calc.base_subtotal, 300.0)
self.assertEqual(calc.bundle_discount_amount, 0.0)
self.assertEqual(calc.renewal_discount_amount, 0.0)
self.assertEqual(calc.grand_total, 300.0)
async def test_unknown_plan_raises_error(self):
with self.assertRaises(ValueError):
await self.service.calculate(CartCalculationRequest(