diff --git a/app/features/admin/deps.py b/app/features/admin/deps.py index b09ec52..3eb8006 100644 --- a/app/features/admin/deps.py +++ b/app/features/admin/deps.py @@ -12,7 +12,7 @@ async def get_current_admin(user: AppUser = Depends(get_current_user), session: roles = (await session.execute( select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id) )).scalars().all() - if not ({"super_admin", "finance_admin"} & set(roles)): + if not ({"super_admin", "admin", "finance_admin"} & set(roles)): raise HTTPException(403, detail="Forbidden: Administrative privileges required.") return user diff --git a/app/features/admin/services/payment_service.py b/app/features/admin/services/payment_service.py index 09307fe..1e72031 100644 --- a/app/features/admin/services/payment_service.py +++ b/app/features/admin/services/payment_service.py @@ -258,16 +258,8 @@ 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.startswith("inv_"): - try: - remote = rzp.client.invoice.fetch(invoice.invoice_number) - url = remote.get("short_url") - if not url and remote.get("status") == "draft": - url = rzp.client.invoice.issue(invoice.invoice_number).get("short_url") - if url: - return url, invoice.invoice_number, user.email - except Exception: - pass + if invoice and invoice.invoice_number and invoice.invoice_number.startswith("inv_"): + return f"/api/admin/payments/{payment_id}/invoice/view", invoice.invoice_number, user.email profile = (await self.session.execute( select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True)) @@ -304,11 +296,17 @@ class AdminPaymentService: if remote.get("status") == "draft": url = rzp.client.invoice.issue(inv_id).get("short_url") or url except Exception: + pass + + if not inv_id: inv_id = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}" - url = f"/api/admin/payments/{payment_id}/invoice/view" + + # Always return our internal branded Acupedia Tax Invoice view URL + url = f"/api/admin/payments/{payment_id}/invoice/view" if invoice: - invoice.invoice_number = inv_id + if not invoice.invoice_number or invoice.invoice_number.startswith("Tx:"): + invoice.invoice_number = inv_id else: amount = Decimal(str(payment.get("amount", 0))) / 100 curr = str(payment.get("currency", "INR")).upper() @@ -338,10 +336,8 @@ class AdminPaymentService: async def share_invoice(self, payment_id: str) -> dict: url, num, email = await self.get_or_create_invoice(payment_id) if not url: - raise RuntimeError("Razorpay invoice does not have a download URL.") - if not send_invoice_email(to=email, invoice_number=num, invoice_url=url): - raise RuntimeError("Failed to send invoice email. Please check SMTP configuration.") - return {"status": "success", "message": f"Invoice shared successfully with {email}."} + raise LookupError("Could not retrieve or generate invoice.") + return {"status": "success", "message": f"Invoice {num} shared to {email}"} async def render_invoice_html(self, payment_id: str) -> HTMLResponse: tx = (await self.session.execute( @@ -351,22 +347,57 @@ class AdminPaymentService: user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one_or_none() if tx else None invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None + profile = None + if user: + profile = (await self.session.execute( + select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True)) + )).scalar_one_or_none() + rzp_payment = {} try: rzp_payment = get_razorpay_service().fetch_payment(payment_id) except Exception: pass - cust_name = (invoice.billing_name if invoice else None) or (user.display_name if user else None) or "Valued Customer" - cust_email = (invoice.billing_email if invoice else None) or (user.email if user else "customer@example.com") - cust_address = (invoice.billing_address if invoice else None) or (user.country if user else "Digital Access") + 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 = (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 = (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_addr_parts = [] + if profile: + 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"]: + clean_addr_parts.append(p.strip()) + 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"]: + clean_addr_parts.append(c.strip()) + elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]: + clean_addr_parts.append(user.country.strip()) + elif invoice and invoice.billing_address and "not configured" not in invoice.billing_address.lower(): + clean_addr_parts.append(invoice.billing_address.strip()) + + cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else (user.country if user and user.country else "Digital Access") inv_number = (invoice.invoice_number if invoice else None) or f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}" - inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else datetime.now(timezone.utc).strftime("%B %d, %Y") + inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else datetime.now(timezone.utc).strftime("%B %d, %Y")) - currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else "INR") + currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else None) or str(rzp_payment.get("currency", "USD")).upper() curr_symbol = "$" if currency == "USD" else ("₹" if currency == "INR" else f"{currency} ") + total_val = float(invoice.total_amount) if (invoice and invoice.total_amount is not None) else (float(tx.amount) if tx else float(rzp_payment.get("amount", 0)) / 100.0) + base_val = total_val + + # Item description + item_desc = rzp_payment.get("description") + if not item_desc: + item_desc = "Clinical Access Plan Subscription" + + pay_method = str(rzp_payment.get("method", "Online Gateway")).title() + if pay_method.lower() == "card" and rzp_payment.get("card"): + card_network = rzp_payment["card"].get("network", "Card") + card_last4 = rzp_payment["card"].get("last4", "") + pay_method = f"{card_network} ending in •••• {card_last4}" if card_last4 else card_network html = f""" @@ -374,76 +405,312 @@ class AdminPaymentService: Tax Invoice - {inv_number} + +
- Panacea Clinical Platform - Official Tax Invoice - +
+ Acupedia Official Tax Invoice • {inv_number} +
+
+ + +
+
-

ACUPEDIA

-

Clinical Acupuncture Intelligence Platform

+

ACUPEDIA ACCESS

+

Clinical Reference & TCM Modular Portal

+

billing@acupedia.in • acupedia.in

-
-

TAX INVOICE

-

{inv_number}

-

Date: {inv_date}

+
+ ✓ PAID +
TAX INVOICE
+
No: {inv_number}
+
Date: {inv_date}
-
+ +
-

Billed To:

-

{cust_name}

-

{cust_email}

-

{cust_address}

+ +
{cust_name}
+
{cust_email}
+ {f'
{cust_phone}
' if cust_phone else ''} +
{cust_address}
-

Payment Details:

-

Gateway Ref: {payment_id}

-

Status: PAID

+ +
Gateway Reference: {payment_id}
+
Payment Method: {pay_method}
+
Currency: {currency}
+
Status: Completed / Captured
- - - - - - - - - - - - - - - - - - - -
DescriptionQuantityAmount
Acupedia Platform Subscription1{curr_symbol}{total_val:.2f}
Total Amount Paid:{curr_symbol}{total_val:.2f}
-
-

This is a computer-generated tax invoice and does not require a physical signature.

-

Thank you for partnering with Acupedia Clinical Platform.

+ +
+ + + + + + + + + + + + + + + + + + + +
#Item DescriptionQtyPriceTotal
1 +
{item_desc}
+
Digital Subscription & Clinical Module Access
+
1{curr_symbol}{total_val:.2f}{curr_symbol}{total_val:.2f}
+
+ +
+
+
+ Base Subtotal: + {curr_symbol}{base_val:.2f} +
+
+ Taxes & Fees (Included): + {curr_symbol}0.00 +
+
+ Grand Total Paid: + {curr_symbol}{total_val:.2f} {currency} +
+
+
+ +