fixed-issue(50):Fixed invoice issue and added invoice download button for users as well on the storefront
This commit is contained in:
parent
29279bfd72
commit
5fabcd6c4c
|
|
@ -12,6 +12,8 @@ class ActiveSubscriptionRecord:
|
||||||
status: str
|
status: str
|
||||||
started_at: datetime
|
started_at: datetime
|
||||||
expires_at: datetime | None
|
expires_at: datetime | None
|
||||||
|
payment_id: str | None = None
|
||||||
|
invoice_number: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
||||||
from app.db.models import (
|
from app.db.models import (
|
||||||
AccessPlan,
|
AccessPlan,
|
||||||
|
Invoice,
|
||||||
Module,
|
Module,
|
||||||
|
PaymentTransaction,
|
||||||
UserEntitlement,
|
UserEntitlement,
|
||||||
UserSubscription,
|
UserSubscription,
|
||||||
)
|
)
|
||||||
|
|
@ -41,6 +43,7 @@ class AccessRepository:
|
||||||
UserSubscription.status,
|
UserSubscription.status,
|
||||||
UserSubscription.started_at,
|
UserSubscription.started_at,
|
||||||
UserSubscription.expires_at,
|
UserSubscription.expires_at,
|
||||||
|
UserSubscription.payment_reference,
|
||||||
)
|
)
|
||||||
.join(
|
.join(
|
||||||
AccessPlan,
|
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] = []
|
records: list[ActiveSubscriptionRecord] = []
|
||||||
for row in result.all():
|
for row in result.all():
|
||||||
status_value = getattr(row.status, "value", row.status)
|
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(
|
records.append(
|
||||||
ActiveSubscriptionRecord(
|
ActiveSubscriptionRecord(
|
||||||
id=row.id,
|
id=row.id,
|
||||||
|
|
@ -70,6 +95,8 @@ class AccessRepository:
|
||||||
status=str(status_value),
|
status=str(status_value),
|
||||||
started_at=row.started_at,
|
started_at=row.started_at,
|
||||||
expires_at=row.expires_at,
|
expires_at=row.expires_at,
|
||||||
|
payment_id=gw_id,
|
||||||
|
invoice_number=inv_num,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return records
|
return records
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,9 @@ class ActiveSubscriptionResponse(StrictModel):
|
||||||
status: str
|
status: str
|
||||||
started_at: datetime
|
started_at: datetime
|
||||||
expires_at: datetime | None = None
|
expires_at: datetime | None = None
|
||||||
|
payment_id: str | None = None
|
||||||
|
invoice_number: str | None = None
|
||||||
|
invoice_url: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class ActiveEntitlementResponse(StrictModel):
|
class ActiveEntitlementResponse(StrictModel):
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,9 @@ class AccessService:
|
||||||
status=item.status,
|
status=item.status,
|
||||||
started_at=item.started_at,
|
started_at=item.started_at,
|
||||||
expires_at=item.expires_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
|
for item in subscriptions
|
||||||
],
|
],
|
||||||
|
|
|
||||||
|
|
@ -258,7 +258,7 @@ class AdminPaymentService:
|
||||||
rzp = get_razorpay_service()
|
rzp = get_razorpay_service()
|
||||||
user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one()
|
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
|
return f"/api/admin/payments/{payment_id}/invoice/view", invoice.invoice_number, user.email
|
||||||
|
|
||||||
profile = (await self.session.execute(
|
profile = (await self.session.execute(
|
||||||
|
|
@ -389,7 +389,22 @@ class AdminPaymentService:
|
||||||
base_val = total_val
|
base_val = total_val
|
||||||
|
|
||||||
# Item description
|
# 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:
|
if not item_desc:
|
||||||
item_desc = "Clinical Access Plan Subscription"
|
item_desc = "Clinical Access Plan Subscription"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
from __future__ import annotations
|
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.db.models import AppUser
|
||||||
from app.features.payments import get_razorpay_service
|
from app.features.payments import get_razorpay_service
|
||||||
from .deps import get_checkout_service, get_current_user
|
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)):
|
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 sqlalchemy import select
|
||||||
from app.db.models import PaymentTransaction
|
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()
|
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:
|
if not tx:
|
||||||
raise HTTPException(404, detail="Transaction record not found or access denied.")
|
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:
|
try:
|
||||||
url, _, _ = await AdminService(service.session).get_or_create_invoice(payment_id)
|
return await AdminService(service.session).render_invoice_html(payment_id)
|
||||||
if not url:
|
except LookupError as exc:
|
||||||
raise HTTPException(500, detail="Razorpay invoice does not have a download URL.")
|
raise HTTPException(404, detail=str(exc)) from exc
|
||||||
return {"short_url": url}
|
|
||||||
except HTTPException:
|
|
||||||
raise
|
|
||||||
except Exception as 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
|
||||||
|
|
|
||||||
|
|
@ -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]:
|
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()
|
currency = tx.currency.upper()
|
||||||
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}"
|
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{tx.gateway_transaction_id[-6:].upper()}"
|
||||||
inv_url = None
|
|
||||||
try:
|
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}})
|
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
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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)))
|
base = Decimal(str(meta.get("base_subtotal", tx.amount)))
|
||||||
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)))
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue