fix(invoices): serve custom Acupedia tax invoice template instead of Razorpay link

This commit is contained in:
Urvish Prajapati 2026-09-11 16:11:05 +05:30
parent 7afa8e1913
commit bbae243054
2 changed files with 341 additions and 74 deletions

View File

@ -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

View File

@ -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"""<!DOCTYPE html>
<html lang="en">
@ -374,76 +405,312 @@ class AdminPaymentService:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tax Invoice - {inv_number}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
* {{ box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', sans-serif; }}
body {{ background-color: #f8fafc; color: #1e293b; padding: 30px 16px; }}
.no-print-bar {{ max-width: 800px; margin: 0 auto 20px auto; display: flex; justify-content: space-between; align-items: center; background: #fff; padding: 12px 20px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }}
.btn {{ display: inline-flex; align-items: center; gap: 8px; padding: 8px 16px; font-size: 14px; font-weight: 600; border-radius: 8px; cursor: pointer; border: none; }}
.btn-primary {{ background-color: #4f46e5; color: #fff; }}
.invoice-card {{ max-width: 800px; margin: 0 auto; background: #fff; border-radius: 16px; padding: 40px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); border: 1px solid #e2e8f0; }}
.header {{ display: flex; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 24px; margin-bottom: 28px; }}
.logo-box h1 {{ font-size: 24px; font-weight: 800; color: #4f46e5; }}
.meta-table {{ width: 100%; border-collapse: collapse; margin-top: 24px; }}
.meta-table th, .meta-table td {{ padding: 12px; text-align: left; border-bottom: 1px solid #e2e8f0; font-size: 14px; }}
.meta-table th {{ background-color: #f8fafc; color: #64748b; font-size: 12px; text-transform: uppercase; }}
.total-row td {{ font-weight: 700; font-size: 16px; color: #0f172a; border-top: 2px solid #0f172a; }}
@media print {{ .no-print-bar {{ display: none !important; }} body {{ background: #fff; padding: 0; }} .invoice-card {{ box-shadow: none; border: none; padding: 0; }} }}
* {{
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}}
body {{
background-color: #f8fafc;
color: #1e293b;
padding: 30px 16px;
}}
.no-print-bar {{
max-width: 800px;
margin: 0 auto 20px auto;
display: flex;
justify-content: space-between;
align-items: center;
background: #ffffff;
padding: 12px 20px;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
border: 1px solid #e2e8f0;
}}
.btn {{
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
font-size: 14px;
font-weight: 600;
border-radius: 8px;
cursor: pointer;
text-decoration: none;
border: none;
transition: all 0.15s ease;
}}
.btn-primary {{
background-color: #4f46e5;
color: #ffffff;
}}
.btn-primary:hover {{
background-color: #4338ca;
}}
.btn-secondary {{
background-color: #f1f5f9;
color: #475569;
}}
.btn-secondary:hover {{
background-color: #e2e8f0;
}}
.invoice-card {{
max-width: 800px;
margin: 0 auto;
background: #ffffff;
border-radius: 16px;
padding: 40px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
border: 1px solid #e2e8f0;
}}
.header {{
display: flex;
justify-content: space-between;
align-items: flex-start;
border-bottom: 2px solid #f1f5f9;
padding-bottom: 24px;
margin-bottom: 28px;
}}
.logo-box h1 {{
font-size: 24px;
font-weight: 800;
color: #4f46e5;
letter-spacing: -0.5px;
}}
.logo-box p {{
font-size: 13px;
color: #64748b;
margin-top: 2px;
}}
.invoice-badge-box {{
text-align: right;
}}
.badge-paid {{
display: inline-block;
background: #ecfdf5;
color: #059669;
padding: 4px 12px;
border-radius: 9999px;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
border: 1px solid #a7f3d0;
margin-bottom: 8px;
}}
.invoice-title {{
font-size: 20px;
font-weight: 700;
color: #0f172a;
}}
.invoice-num {{
font-size: 13px;
font-family: monospace;
color: #64748b;
margin-top: 4px;
}}
.grid-details {{
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
margin-bottom: 32px;
}}
.section-label {{
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
color: #94a3b8;
margin-bottom: 6px;
}}
.detail-text {{
font-size: 14px;
color: #334155;
line-height: 1.5;
}}
.detail-strong {{
font-weight: 600;
color: #0f172a;
}}
.table-wrap {{
margin-bottom: 24px;
border: 1px solid #e2e8f0;
border-radius: 10px;
overflow: hidden;
}}
table {{
width: 100%;
border-collapse: collapse;
text-align: left;
}}
th {{
background: #f8fafc;
padding: 12px 16px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
color: #64748b;
border-bottom: 1px solid #e2e8f0;
}}
td {{
padding: 16px;
font-size: 14px;
color: #334155;
border-bottom: 1px solid #f1f5f9;
}}
tr:last-child td {{
border-bottom: none;
}}
.summary-wrap {{
display: flex;
justify-content: flex-end;
margin-bottom: 32px;
}}
.summary-card {{
width: 320px;
background: #f8fafc;
border-radius: 12px;
padding: 16px 20px;
border: 1px solid #e2e8f0;
}}
.summary-row {{
display: flex;
justify-content: space-between;
font-size: 13px;
color: #64748b;
margin-bottom: 8px;
}}
.summary-row.total {{
border-top: 2px solid #cbd5e1;
padding-top: 10px;
margin-top: 10px;
margin-bottom: 0;
font-size: 16px;
font-weight: 700;
color: #0f172a;
}}
.footer-note {{
border-top: 1px dashed #e2e8f0;
padding-top: 20px;
text-align: center;
font-size: 12px;
color: #94a3b8;
line-height: 1.6;
}}
@media print {{
body {{
background-color: #ffffff !important;
padding: 0 !important;
}}
.no-print-bar {{
display: none !important;
}}
.invoice-card {{
box-shadow: none !important;
border: none !important;
padding: 20px 0 !important;
max-width: 100% !important;
}}
}}
</style>
</head>
<body>
<div class="no-print-bar">
<span style="font-weight: 600; color: #64748b;">Panacea Clinical Platform - Official Tax Invoice</span>
<button class="btn btn-primary" onclick="window.print()">Print / Save PDF</button>
<div style="font-size: 13px; color: #64748b; font-weight: 500;">
Acupedia Official Tax Invoice &bull; <strong>{inv_number}</strong>
</div>
<div style="display: flex; gap: 8px;">
<button class="btn btn-secondary" onclick="window.close()">Close</button>
<button class="btn btn-primary" onclick="window.print()">
<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
Print / Save PDF
</button>
</div>
</div>
<div class="invoice-card">
<div class="header">
<div class="logo-box">
<h1>ACUPEDIA</h1>
<p style="color: #64748b; font-size: 13px;">Clinical Acupuncture Intelligence Platform</p>
<h1>ACUPEDIA ACCESS</h1>
<p>Clinical Reference &amp; TCM Modular Portal</p>
<p style="font-size: 12px; color: #94a3b8; margin-top: 4px;">billing@acupedia.in &bull; acupedia.in</p>
</div>
<div style="text-align: right;">
<h2 style="font-size: 20px; font-weight: 700; color: #0f172a;">TAX INVOICE</h2>
<p style="font-size: 14px; color: #4f46e5; font-weight: 600; margin-top: 4px;">{inv_number}</p>
<p style="font-size: 13px; color: #64748b; margin-top: 2px;">Date: {inv_date}</p>
<div class="invoice-badge-box">
<span class="badge-paid">&#10003; PAID</span>
<div class="invoice-title">TAX INVOICE</div>
<div class="invoice-num">No: {inv_number}</div>
<div style="font-size: 12px; color: #64748b; margin-top: 2px;">Date: {inv_date}</div>
</div>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 30px; font-size: 14px;">
<div class="grid-details">
<div>
<p style="font-size: 12px; font-weight: 700; color: #94a3b8; text-transform: uppercase;">Billed To:</p>
<p style="font-weight: 700; color: #0f172a; margin-top: 4px;">{cust_name}</p>
<p style="color: #64748b;">{cust_email}</p>
<p style="color: #64748b; max-width: 260px;">{cust_address}</p>
<div class="section-label">Billed To</div>
<div class="detail-text detail-strong">{cust_name}</div>
<div class="detail-text">{cust_email}</div>
{f'<div class="detail-text">{cust_phone}</div>' if cust_phone else ''}
<div class="detail-text" style="color: #64748b; margin-top: 4px;">{cust_address}</div>
</div>
<div style="text-align: right;">
<p style="font-size: 12px; font-weight: 700; color: #94a3b8; text-transform: uppercase;">Payment Details:</p>
<p style="color: #64748b; margin-top: 4px;">Gateway Ref: <span style="font-weight: 600; color: #0f172a;">{payment_id}</span></p>
<p style="color: #64748b;">Status: <span style="font-weight: 700; color: #16a34a;">PAID</span></p>
<div class="section-label">Payment Overview</div>
<div class="detail-text">Gateway Reference: <span class="detail-strong" style="font-family: monospace;">{payment_id}</span></div>
<div class="detail-text">Payment Method: <span class="detail-strong">{pay_method}</span></div>
<div class="detail-text">Currency: <span class="detail-strong">{currency}</span></div>
<div class="detail-text">Status: <span class="detail-strong" style="color: #059669;">Completed / Captured</span></div>
</div>
</div>
<table class="meta-table">
<thead>
<tr>
<th>Description</th>
<th style="text-align: right;">Quantity</th>
<th style="text-align: right;">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td style="font-weight: 600; color: #0f172a;">Acupedia Platform Subscription</td>
<td style="text-align: right; color: #64748b;">1</td>
<td style="text-align: right; font-weight: 600; color: #0f172a;">{curr_symbol}{total_val:.2f}</td>
</tr>
<tr class="total-row">
<td colspan="2" style="text-align: right;">Total Amount Paid:</td>
<td style="text-align: right; color: #4f46e5;">{curr_symbol}{total_val:.2f}</td>
</tr>
</tbody>
</table>
<div style="margin-top: 40px; border-top: 1px solid #f1f5f9; padding-top: 20px; text-align: center; color: #94a3b8; font-size: 12px;">
<p>This is a computer-generated tax invoice and does not require a physical signature.</p>
<p style="margin-top: 4px;">Thank you for partnering with Acupedia Clinical Platform.</p>
<div class="table-wrap">
<table>
<thead>
<tr>
<th style="width: 50px;">#</th>
<th>Item Description</th>
<th style="text-align: center; width: 80px;">Qty</th>
<th style="text-align: right; width: 120px;">Price</th>
<th style="text-align: right; width: 120px;">Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<div style="font-weight: 600; color: #0f172a;">{item_desc}</div>
<div style="font-size: 12px; color: #64748b; margin-top: 2px;">Digital Subscription &amp; Clinical Module Access</div>
</td>
<td style="text-align: center;">1</td>
<td style="text-align: right;">{curr_symbol}{total_val:.2f}</td>
<td style="text-align: right; font-weight: 600;">{curr_symbol}{total_val:.2f}</td>
</tr>
</tbody>
</table>
</div>
<div class="summary-wrap">
<div class="summary-card">
<div class="summary-row">
<span>Base Subtotal:</span>
<span>{curr_symbol}{base_val:.2f}</span>
</div>
<div class="summary-row">
<span>Taxes &amp; Fees (Included):</span>
<span>{curr_symbol}0.00</span>
</div>
<div class="summary-row total">
<span>Grand Total Paid:</span>
<span style="color: #4f46e5;">{curr_symbol}{total_val:.2f} {currency}</span>
</div>
</div>
</div>
<div class="footer-note">
This is an electronically generated Tax Invoice &amp; Payment Receipt.<br>
Thank you for choosing Acupedia Clinical TCM Systems. For inquiries or support, contact support@acupedia.in.
</div>
</div>
</body>