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 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)) )).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 if not inv_id: inv_id = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}" # 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 = 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 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") 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 (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 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""" Tax Invoice - {inv_number}
Acupedia Official Tax Invoice • {inv_number}

ACUPEDIA ACCESS

Clinical Reference & TCM Modular Portal

billing@acupedia.in • acupedia.in

✓ PAID
TAX INVOICE
No: {inv_number}
Date: {inv_date}
{cust_name}
{cust_email}
{f'
{cust_phone}
' if cust_phone else ''}
{cust_address}
Gateway Reference: {payment_id}
Payment Method: {pay_method}
Currency: {currency}
Status: Completed / Captured
# Item Description Qty Price Total
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}
""" return HTMLResponse(content=html)