452 lines
22 KiB
Python
452 lines
22 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 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()
|
|
|
|
self.session.add(
|
|
Invoice(
|
|
payment_transaction_id=tx.id,
|
|
invoice_number=f"INV-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}",
|
|
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.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
|
|
|
|
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:
|
|
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"
|
|
|
|
if invoice:
|
|
invoice.invoice_number = inv_id
|
|
else:
|
|
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_id,
|
|
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_id, 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 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}."}
|
|
|
|
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
|
|
|
|
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")
|
|
|
|
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")
|
|
|
|
currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else "INR")
|
|
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)
|
|
|
|
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 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; }} }}
|
|
</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>
|
|
<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>
|
|
</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>
|
|
</div>
|
|
<div style="display: flex; justify-content: space-between; margin-bottom: 30px; font-size: 14px;">
|
|
<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>
|
|
<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>
|
|
</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>
|
|
</div>
|
|
</body>
|
|
</html>"""
|
|
return HTMLResponse(content=html)
|