from __future__ import annotations from datetime import datetime, timedelta, timezone from decimal import Decimal 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, Coupon, Invoice, PaymentTransaction, UserEntitlement, UserSubscription from app.features.payments import generate_next_invoice_number, record_coupon_redemption class RazorpayWebhookService: def __init__(self, session: AsyncSession) -> None: self.session = session async def handle(self, event: dict) -> dict[str, str]: event_type = event.get("event") payload = event.get("payload") or {} if event_type == "payment.captured": return await self._payment_captured((payload.get("payment") or {}).get("entity") or {}) if event_type in {"subscription.cancelled", "subscription.expired"}: return await self._subscription_ended(event_type, (payload.get("subscription") or {}).get("entity") or {}) return {"status": "accepted"} async def _payment_captured(self, payment: dict) -> dict[str, str]: order_id = payment.get("order_id") payment_id = payment.get("id") if not order_id or not payment_id: return {"status": "ignored", "reason": "No order_id/payment_id found in payment payload"} existing = (await self.session.execute( select(PaymentTransaction.id).where(PaymentTransaction.gateway_transaction_id == payment_id) )).scalar_one_or_none() if existing: return {"status": "accepted"} subs = (await self.session.execute( select(UserSubscription).where( UserSubscription.payment_reference == order_id, UserSubscription.status == SubscriptionStatus.PENDING, ) )).scalars().all() if not subs: return {"status": "accepted"} now = datetime.now(timezone.utc) amount = Decimal(str(payment.get("amount", 0))) / Decimal("100") currency = str(payment.get("currency", "INR")).upper() main = subs[0] meta = main.metadata_json or {} transaction = PaymentTransaction( user_id=main.user_id, subscription_id=main.id, gateway_name="razorpay", gateway_transaction_id=payment_id, status=PaymentStatus.SUCCESS, amount=amount, currency=currency, ) self.session.add(transaction) await self.session.flush() for sub in subs: plan = None if sub.plan_id: plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none() 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) 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="subscription_purchase", expires_at=sub.expires_at, )) 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"))) invoice_number = await generate_next_invoice_number(self.session, dt=now) coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None coupon = (await self.session.execute( select(Coupon).where(Coupon.code == str(coupon_code).strip().upper()) )).scalar_one_or_none() if coupon_code else None if payment.get("contact") and subs: sub_meta = dict(subs[0].metadata_json or {}) if not sub_meta.get("billing_phone"): sub_meta["billing_phone"] = payment.get("contact") subs[0].metadata_json = sub_meta invoice = Invoice( payment_transaction_id=transaction.id, invoice_number=invoice_number, billing_name=((payment.get("card") or {}).get("name") or payment.get("email") or "Customer"), billing_email=payment.get("email") or "unknown@example.invalid", billing_address="Recorded from Gateway Webhook", applied_coupon_id=coupon.id if coupon else None, base_amount=base, discount_amount=discount, taxable_amount=taxable, gst_amount=gst, total_amount=amount, currency_code=currency, exchange_rate_to_inr=Decimal("1"), total_amount_inr=amount if currency == "INR" else None, ) self.session.add(invoice) await self.session.flush() if coupon: await record_coupon_redemption( self.session, coupon=coupon, user_id=main.user_id, invoice_id=invoice.id, ) await self.session.commit() return {"status": "accepted"} async def _subscription_ended(self, event_type: str, entity: dict) -> dict[str, str]: reference = entity.get("id") if not reference: return {"status": "accepted"} sub = (await self.session.execute( select(UserSubscription).where(UserSubscription.payment_reference == reference) )).scalar_one_or_none() if not sub: return {"status": "accepted"} now = datetime.now(timezone.utc) sub.status = SubscriptionStatus.CANCELLED if event_type == "subscription.cancelled" else SubscriptionStatus.EXPIRED sub.cancelled_at = now sub.cancellation_reason = "gateway_callback" 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.revoke_reason = "subscription_expired" await self.session.commit() return {"status": "accepted"}