802 lines
32 KiB
Python
802 lines
32 KiB
Python
from __future__ import annotations
|
|
import uuid
|
|
from datetime import datetime, timedelta, timezone
|
|
from decimal import Decimal
|
|
from fastapi.responses import HTMLResponse
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
|
|
from app.db.models import (
|
|
AccessPlan,
|
|
AccessPlanModule,
|
|
AppUser,
|
|
Invoice,
|
|
PaymentTransaction,
|
|
RefundDecision,
|
|
UserBillingProfile,
|
|
UserEntitlement,
|
|
UserSubscription,
|
|
)
|
|
from ..schema import AdminRefundRequest, AdminRefundResponse, AdminSyncResponse
|
|
from app.features.email import send_invoice_email
|
|
from app.features.payments import generate_next_invoice_number, get_razorpay_service
|
|
|
|
|
|
class AdminPaymentService:
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
|
|
async def process_refund(self, request: AdminRefundRequest, admin: AppUser) -> AdminRefundResponse:
|
|
tx = (await self.session.execute(
|
|
select(PaymentTransaction).where(
|
|
PaymentTransaction.id == request.payment_transaction_id,
|
|
PaymentTransaction.status == PaymentStatus.SUCCESS,
|
|
)
|
|
)).scalar_one_or_none()
|
|
if not tx:
|
|
raise LookupError("The specified successful payment transaction could not be located.")
|
|
if request.refund_amount > tx.amount:
|
|
raise ValueError("Refund amount cannot exceed the captured payment amount.")
|
|
|
|
existing = (await self.session.execute(
|
|
select(RefundDecision.id).where(RefundDecision.payment_transaction_id == tx.id).limit(1)
|
|
)).scalar_one_or_none()
|
|
if existing:
|
|
raise ValueError("A refund has already been registered or calculated for this transaction.")
|
|
|
|
sub = (await self.session.execute(
|
|
select(UserSubscription).where(UserSubscription.id == tx.subscription_id)
|
|
)).scalar_one()
|
|
|
|
rzp = get_razorpay_service()
|
|
refund = rzp.create_refund(
|
|
payment_id=tx.gateway_transaction_id,
|
|
amount=request.refund_amount,
|
|
currency=tx.currency,
|
|
notes={
|
|
"support_ticket": request.support_ticket_reference,
|
|
"admin_id": str(admin.id),
|
|
"reason": request.reason_detail or "Customer request",
|
|
},
|
|
)
|
|
|
|
now = datetime.now(timezone.utc)
|
|
start = sub.started_at
|
|
if start.tzinfo is None:
|
|
start = start.replace(tzinfo=timezone.utc)
|
|
active_months = max(1, (now - start).days // 30)
|
|
reduction = (Decimal("1") - (request.refund_amount / Decimal(tx.amount))) * Decimal("100")
|
|
|
|
decision = RefundDecision(
|
|
payment_transaction_id=tx.id,
|
|
original_paid_amount=tx.amount,
|
|
original_currency=tx.currency,
|
|
calculated_reduction_percent=reduction,
|
|
refund_amount=request.refund_amount,
|
|
active_duration_months=active_months,
|
|
support_ticket_reference=request.support_ticket_reference,
|
|
reason_detail=request.reason_detail,
|
|
status="approved",
|
|
approved_by_admin_id=admin.id,
|
|
decided_at=now,
|
|
)
|
|
self.session.add(decision)
|
|
tx.status = PaymentStatus.REVERSED
|
|
sub.status = SubscriptionStatus.REFUNDED
|
|
sub.cancelled_at = now
|
|
sub.cancellation_reason = "refund_processed"
|
|
sub.cancelled_by = admin.id
|
|
|
|
ents = (await self.session.execute(
|
|
select(UserEntitlement).where(
|
|
UserEntitlement.source_subscription_id == sub.id,
|
|
UserEntitlement.status == EntitlementStatus.ACTIVE,
|
|
)
|
|
)).scalars().all()
|
|
for ent in ents:
|
|
ent.status = EntitlementStatus.REVOKED
|
|
ent.revoked_at = now
|
|
ent.revoked_by = admin.id
|
|
ent.revoke_reason = "refund_processed"
|
|
|
|
await self.session.commit()
|
|
await self.session.refresh(decision)
|
|
return AdminRefundResponse(
|
|
status="refunded",
|
|
refund_decision_id=decision.id,
|
|
gateway_refund_id=refund["id"],
|
|
refunded_amount=request.refund_amount,
|
|
currency=tx.currency,
|
|
)
|
|
|
|
async def force_sync(self) -> AdminSyncResponse:
|
|
rzp = get_razorpay_service()
|
|
log: list[str] = []
|
|
count = 0
|
|
payments = rzp.client.payment.all({"count": 100}).get("items", [])
|
|
for payment in payments:
|
|
if payment.get("status") != "captured" or not payment.get("id"):
|
|
continue
|
|
pid = payment["id"]
|
|
if (await self.session.execute(
|
|
select(PaymentTransaction.id).where(PaymentTransaction.gateway_transaction_id == pid)
|
|
)).scalar_one_or_none():
|
|
continue
|
|
order_id = payment.get("order_id")
|
|
if not order_id:
|
|
log.append(f"Skipped {pid}: no Razorpay order_id")
|
|
continue
|
|
sub = (await self.session.execute(
|
|
select(UserSubscription).where(UserSubscription.payment_reference == order_id).limit(1)
|
|
)).scalar_one_or_none()
|
|
if not sub:
|
|
log.append(f"Skipped {pid}: no matching local subscription for {order_id}")
|
|
continue
|
|
await self._reconcile_payment(payment, sub)
|
|
count += 1
|
|
log.append(f"Reconciled {pid} → subscription {sub.id}")
|
|
if not log:
|
|
log.append("All records are already synchronized. No changes needed.")
|
|
await self.session.commit()
|
|
return AdminSyncResponse(
|
|
status="completed",
|
|
message=f"Sync complete. {count} record(s) processed.",
|
|
records_processed=count,
|
|
sync_log=log,
|
|
)
|
|
|
|
async def _reconcile_payment(self, payment: dict, sub: UserSubscription) -> None:
|
|
now = datetime.now(timezone.utc)
|
|
plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none()
|
|
if sub.status == SubscriptionStatus.PENDING:
|
|
sub.status = SubscriptionStatus.ACTIVE
|
|
sub.started_at = now
|
|
sub.expires_at = now + timedelta(days=3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365)
|
|
amount = Decimal(str(payment.get("amount", 0))) / 100
|
|
curr = str(payment.get("currency", "INR")).upper()
|
|
tx = PaymentTransaction(
|
|
user_id=sub.user_id,
|
|
subscription_id=sub.id,
|
|
gateway_name="razorpay",
|
|
gateway_transaction_id=payment["id"],
|
|
status=PaymentStatus.SUCCESS,
|
|
amount=amount,
|
|
currency=curr,
|
|
)
|
|
self.session.add(tx)
|
|
await self.session.flush()
|
|
|
|
meta = sub.metadata_json or {}
|
|
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
|
gst = Decimal(str(meta.get("gst_amount", 0)))
|
|
base = Decimal(str(meta.get("base_subtotal", amount)))
|
|
discount = Decimal(str(meta.get("total_discounts", 0)))
|
|
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
|
|
|
|
invoice_number = await generate_next_invoice_number(self.session, dt=now)
|
|
self.session.add(
|
|
Invoice(
|
|
payment_transaction_id=tx.id,
|
|
invoice_number=invoice_number,
|
|
billing_name=user.display_name or user.email,
|
|
billing_email=user.email,
|
|
billing_address="Synced from Razorpay",
|
|
base_amount=base,
|
|
discount_amount=discount,
|
|
taxable_amount=taxable,
|
|
gst_amount=gst,
|
|
total_amount=amount,
|
|
currency_code=curr,
|
|
exchange_rate_to_inr=Decimal("1"),
|
|
total_amount_inr=amount if curr == "INR" else None,
|
|
)
|
|
)
|
|
|
|
module_ids = (await self.session.execute(
|
|
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id)
|
|
)).scalars().all()
|
|
for module_id in module_ids:
|
|
active = (await self.session.execute(
|
|
select(UserEntitlement.id).where(
|
|
UserEntitlement.user_id == sub.user_id,
|
|
UserEntitlement.module_id == module_id,
|
|
UserEntitlement.status == EntitlementStatus.ACTIVE,
|
|
).limit(1)
|
|
)).scalar_one_or_none()
|
|
if active is None:
|
|
self.session.add(
|
|
UserEntitlement(
|
|
user_id=sub.user_id,
|
|
module_id=module_id,
|
|
source_subscription_id=sub.id,
|
|
source_plan_id=sub.plan_id,
|
|
status=EntitlementStatus.ACTIVE,
|
|
granted_at=now,
|
|
grant_reason="force_sync_reconciliation",
|
|
expires_at=sub.expires_at,
|
|
)
|
|
)
|
|
|
|
async def subscriptions(self) -> list[dict]:
|
|
rows = (await self.session.execute(
|
|
select(UserSubscription, AppUser, AccessPlan)
|
|
.join(AppUser, AppUser.id == UserSubscription.user_id)
|
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
|
.where(UserSubscription.status != SubscriptionStatus.PENDING)
|
|
.order_by(UserSubscription.started_at.desc())
|
|
)).all()
|
|
now = datetime.now(timezone.utc)
|
|
result: list[dict] = []
|
|
for sub, user, plan in rows:
|
|
exp = sub.expires_at
|
|
days = max(0, (exp - now).days) if exp and sub.status == SubscriptionStatus.ACTIVE else 0
|
|
result.append({
|
|
"id": str(sub.id),
|
|
"user_email": user.email,
|
|
"user_name": user.display_name or user.email.split("@")[0].title(),
|
|
"user_phone": user.phone_number,
|
|
"user_external_ref": user.external_ref,
|
|
"plan_code": plan.code if plan else "UNKNOWN",
|
|
"plan_name": plan.name if plan else "Unknown Access Plan",
|
|
"status": getattr(sub.status, "value", sub.status),
|
|
"started_at": sub.started_at.isoformat() if sub.started_at else None,
|
|
"expires_at": exp.isoformat() if exp else None,
|
|
"days_left": days,
|
|
"payment_reference": sub.payment_reference,
|
|
})
|
|
return result
|
|
|
|
async def get_or_create_invoice(self, payment_id: str) -> tuple[str | None, str, str]:
|
|
tx = (await self.session.execute(
|
|
select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id)
|
|
)).scalar_one_or_none()
|
|
if not tx:
|
|
raise LookupError("Payment transaction not found.")
|
|
|
|
invoice = (await self.session.execute(
|
|
select(Invoice).where(Invoice.payment_transaction_id == tx.id)
|
|
)).scalar_one_or_none()
|
|
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:
|
|
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))
|
|
)).scalar_one_or_none()
|
|
payment = rzp.fetch_payment(payment_id)
|
|
customer = {
|
|
"name": profile.billing_name if profile else (user.display_name or user.email),
|
|
"email": payment.get("email") or user.email,
|
|
}
|
|
contact = payment.get("contact") or (profile.billing_phone if profile else user.phone_number)
|
|
if contact:
|
|
customer["contact"] = contact
|
|
|
|
inv_id = None
|
|
url = None
|
|
try:
|
|
remote = rzp.client.invoice.create(data={
|
|
"type": "invoice",
|
|
"customer": customer,
|
|
"line_items": [
|
|
{
|
|
"name": payment.get("description") or "Access Plan Subscription",
|
|
"amount": payment.get("amount"),
|
|
"currency": payment.get("currency", "INR"),
|
|
"quantity": 1,
|
|
}
|
|
],
|
|
"email_notify": False,
|
|
"sms_notify": False,
|
|
"notes": {"payment_id": payment_id},
|
|
})
|
|
inv_id = remote.get("id")
|
|
url = remote.get("short_url")
|
|
if remote.get("status") == "draft":
|
|
url = rzp.client.invoice.issue(inv_id).get("short_url") or url
|
|
except Exception:
|
|
pass
|
|
|
|
# Always return our internal branded Acupedia Tax Invoice view URL
|
|
url = f"/api/admin/payments/{payment_id}/invoice/view"
|
|
|
|
if invoice:
|
|
if not invoice.invoice_number or invoice.invoice_number.startswith("Tx:"):
|
|
invoice.invoice_number = await generate_next_invoice_number(self.session)
|
|
inv_number = invoice.invoice_number
|
|
else:
|
|
inv_number = await generate_next_invoice_number(self.session)
|
|
amount = Decimal(str(payment.get("amount", 0))) / 100
|
|
curr = str(payment.get("currency", "INR")).upper()
|
|
taxable = (amount / Decimal("1.0236") * Decimal("0.02")).quantize(Decimal("0.01")) if curr == "INR" else (amount / Decimal("1.03") * Decimal("0.03")).quantize(Decimal("0.01"))
|
|
gst = (taxable * Decimal("0.18")).quantize(Decimal("0.01")) if curr == "INR" else Decimal("0")
|
|
base = amount - taxable - gst
|
|
self.session.add(
|
|
Invoice(
|
|
payment_transaction_id=tx.id,
|
|
invoice_number=inv_number,
|
|
billing_name=customer["name"],
|
|
billing_email=customer["email"],
|
|
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}" if profile else "Not Configured",
|
|
base_amount=base,
|
|
discount_amount=Decimal("0"),
|
|
taxable_amount=taxable,
|
|
gst_amount=gst,
|
|
total_amount=amount,
|
|
currency_code=curr,
|
|
exchange_rate_to_inr=Decimal("1"),
|
|
total_amount_inr=amount if curr == "INR" else None,
|
|
)
|
|
)
|
|
await self.session.commit()
|
|
return url, inv_number, customer["email"]
|
|
|
|
async def share_invoice(self, payment_id: str) -> dict:
|
|
url, num, email = await self.get_or_create_invoice(payment_id)
|
|
if not url:
|
|
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(
|
|
select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id)
|
|
)).scalar_one_or_none()
|
|
|
|
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 (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")
|
|
|
|
now = datetime.now(timezone.utc)
|
|
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{now.strftime('%b').upper()}-{now.strftime('%Y')}-PREVIEW"
|
|
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 now.strftime("%B %d, %Y"))
|
|
|
|
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 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"
|
|
|
|
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">
|
|
<head>
|
|
<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', -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-x: auto;
|
|
-webkit-overflow-scrolling: touch;
|
|
}}
|
|
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;
|
|
}}
|
|
.payment-id-val {{
|
|
word-break: break-all;
|
|
display: inline-block;
|
|
}}
|
|
@media (max-width: 640px) {{
|
|
body {{
|
|
padding: 12px 8px;
|
|
}}
|
|
.no-print-bar {{
|
|
flex-direction: column;
|
|
align-items: stretch;
|
|
gap: 12px;
|
|
padding: 12px 14px;
|
|
text-align: center;
|
|
}}
|
|
.no-print-actions {{
|
|
display: flex;
|
|
gap: 8px;
|
|
width: 100%;
|
|
}}
|
|
.no-print-actions .btn {{
|
|
flex: 1;
|
|
justify-content: center;
|
|
padding: 10px 8px;
|
|
font-size: 13px;
|
|
}}
|
|
.invoice-card {{
|
|
padding: 24px 16px;
|
|
border-radius: 12px;
|
|
}}
|
|
.header {{
|
|
flex-direction: column;
|
|
align-items: flex-start;
|
|
gap: 16px;
|
|
padding-bottom: 18px;
|
|
margin-bottom: 20px;
|
|
}}
|
|
.invoice-badge-box {{
|
|
text-align: left;
|
|
width: 100%;
|
|
}}
|
|
.grid-details {{
|
|
grid-template-columns: 1fr;
|
|
gap: 20px;
|
|
margin-bottom: 24px;
|
|
}}
|
|
.grid-payment-overview {{
|
|
text-align: left !important;
|
|
}}
|
|
.detail-text {{
|
|
word-break: break-word;
|
|
overflow-wrap: anywhere;
|
|
}}
|
|
.table-wrap table {{
|
|
min-width: 480px;
|
|
}}
|
|
th, td {{
|
|
padding: 10px 12px;
|
|
font-size: 13px;
|
|
}}
|
|
.summary-wrap {{
|
|
justify-content: stretch;
|
|
}}
|
|
.summary-card {{
|
|
width: 100%;
|
|
}}
|
|
}}
|
|
@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">
|
|
<div style="font-size: 13px; color: #64748b; font-weight: 500;">
|
|
Acupedia Official Tax Invoice • <strong>{inv_number}</strong>
|
|
</div>
|
|
<div class="no-print-actions" 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 ACCESS</h1>
|
|
<p>Clinical Reference & TCM Modular Portal</p>
|
|
<p style="font-size: 12px; color: #94a3b8; margin-top: 4px;">billing@acupedia.in • acupedia.in</p>
|
|
</div>
|
|
<div class="invoice-badge-box">
|
|
<span class="badge-paid">✓ 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 class="grid-details">
|
|
<div>
|
|
<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 class="grid-payment-overview" style="text-align: right;">
|
|
<div class="section-label">Payment Overview</div>
|
|
<div class="detail-text">Payment ID: <span class="detail-strong payment-id-val" 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>
|
|
</div>
|
|
|
|
<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 & 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 & 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 & Payment Receipt.<br>
|
|
Thank you for choosing Acupedia Clinical TCM Systems. For inquiries or support, contact support@acupedia.in.
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>"""
|
|
return HTMLResponse(content=html)
|