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"""
Clinical Acupuncture Intelligence Platform
{inv_number}
Date: {inv_date}
Billed To:
{cust_name}
{cust_email}
{cust_address}
Payment Details:
Gateway Ref: {payment_id}
Status: PAID
| Description | Quantity | Amount |
|---|---|---|
| Acupedia Platform Subscription | 1 | {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.