diff --git a/app/features/access/domain.py b/app/features/access/domain.py index 922b327..a49aa2b 100644 --- a/app/features/access/domain.py +++ b/app/features/access/domain.py @@ -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) diff --git a/app/features/access/repository.py b/app/features/access/repository.py index 354382f..eaff57d 100644 --- a/app/features/access/repository.py +++ b/app/features/access/repository.py @@ -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 diff --git a/app/features/access/schema.py b/app/features/access/schema.py index b9107f2..154a362 100644 --- a/app/features/access/schema.py +++ b/app/features/access/schema.py @@ -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): diff --git a/app/features/access/service.py b/app/features/access/service.py index 4116b4c..79699a3 100644 --- a/app/features/access/service.py +++ b/app/features/access/service.py @@ -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 ], diff --git a/app/features/admin/services/payment_service.py b/app/features/admin/services/payment_service.py index 1e72031..6a7e283 100644 --- a/app/features/admin/services/payment_service.py +++ b/app/features/admin/services/payment_service.py @@ -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" diff --git a/app/features/checkout/api.py b/app/features/checkout/api.py index ebca42c..12afef7 100644 --- a/app/features/checkout/api.py +++ b/app/features/checkout/api.py @@ -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 diff --git a/app/features/checkout/service.py b/app/features/checkout/service.py index be8280f..09365ae 100644 --- a/app/features/checkout/service.py +++ b/app/features/checkout/service.py @@ -104,17 +104,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)))