from __future__ import annotations import uuid from datetime import datetime, timedelta, timezone from decimal import Decimal from uuid import UUID 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, UserBillingProfile, UserEntitlement, UserSubscription from app.features.cart.repository import CartRepository from app.features.cart.schema import CartCalculationRequest from app.features.cart.service import CartService from app.features.payments import get_razorpay_service from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest class CheckoutService: def __init__(self, *, session: AsyncSession, cart_repository: CartRepository) -> None: self.session = session self.cart_service = CartService(cart_repository) async def create_order(self, user: AppUser, request: CheckoutOrderRequest) -> CheckoutOrderResponse: calc = await self.cart_service.calculate(CartCalculationRequest(cart_item_codes=request.cart_item_codes, coupon_code=request.coupon_code, currency=request.currency), user_id=user.id) if calc.grand_total <= 0: raise ValueError("Grand total must be greater than zero to checkout.") rzp = get_razorpay_service() if not user.external_ref: try: customer = rzp.create_customer(name=user.display_name or user.email, email=user.email, phone=user.phone_number) user.external_ref = customer.get("id") await self.session.flush() except Exception: pass receipt = f"rcpt_{uuid.uuid4().hex[:12]}" order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""}) plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency) seen_plan_ids = set() plans: list[AccessPlan] = [] for plan, _ in plan_matches.values(): if plan.id not in seen_plan_ids: seen_plan_ids.add(plan.id) plans.append(plan) now = datetime.now(timezone.utc) pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency} for plan in plans: self.session.add(UserSubscription(user_id=user.id, plan_id=plan.id, status=SubscriptionStatus.PENDING, started_at=now, auto_renew=False, payment_provider="razorpay", payment_reference=order["id"], metadata_json=dict(pricing_meta))) await self.session.commit() return CheckoutOrderResponse(razorpay_order_id=order["id"], amount=calc.grand_total, currency=calc.currency, receipt=receipt, base_subtotal=calc.base_subtotal, total_discounts=calc.total_discounts, convenience_fee=calc.convenience_fee, convenience_fee_rate=calc.convenience_fee_rate, taxable_amount=calc.taxable_amount, gst_amount=calc.gst_amount, grand_total=calc.grand_total) async def verify(self, user: AppUser, request: CheckoutVerifyRequest) -> dict: rzp = get_razorpay_service() if not rzp.verify_payment_signature(razorpay_order_id=request.razorpay_order_id, razorpay_payment_id=request.razorpay_payment_id, razorpay_signature=request.razorpay_signature): raise ValueError("Payment verification failed: Signature does not match.") payment = rzp.fetch_payment(request.razorpay_payment_id) if payment.get("status") not in {"captured", "authorized"}: raise ValueError(f"Payment is not captured/authorized (status={payment.get('status')}).") existing_tx = (await self.session.execute(select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == request.razorpay_payment_id))).scalar_one_or_none() if existing_tx: return {"status": "success", "message": "This transaction was already successfully processed and verified.", "razorpay_payment_id": request.razorpay_payment_id} subs = (await self.session.execute(select(UserSubscription).where(UserSubscription.user_id == user.id, UserSubscription.status == SubscriptionStatus.PENDING, UserSubscription.payment_reference == request.razorpay_order_id))).scalars().all() if not subs: raise LookupError("No pending order subscription record matches this checkout ID.") profile = await self._billing_profile(user, request.billing_profile_id) meta = subs[0].metadata_json or {} gateway_total = Decimal(str(payment.get("amount", 0))) / Decimal("100") final_total = Decimal(str(meta.get("grand_total", gateway_total))) gateway_currency = str(payment.get("currency", request.currency)).upper() expected_subunits = int((final_total * 100).quantize(Decimal("1"))) if int(payment.get("amount", -1)) != expected_subunits or gateway_currency != str(meta.get("currency", request.currency)).upper(): raise ValueError("Gateway amount/currency does not match the checkout order.") now = datetime.now(timezone.utc) transaction = PaymentTransaction(user_id=user.id, subscription_id=subs[0].id, gateway_name="razorpay", gateway_transaction_id=request.razorpay_payment_id, status=PaymentStatus.SUCCESS, amount=final_total, currency=gateway_currency) self.session.add(transaction) await self.session.flush() plan_names: list[str] = [] for sub in subs: 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) if plan: plan_names.append(plan.name) 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 == 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=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)) invoice_number, invoice_url = await self._create_invoice(rzp, transaction, profile, payment, plan_names, meta) await self.session.commit() return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice_number, "invoice_url": invoice_url} async def _billing_profile(self, user: AppUser, billing_profile_id: UUID | None) -> UserBillingProfile: stmt = select(UserBillingProfile).where(UserBillingProfile.user_id == user.id) if billing_profile_id: stmt = stmt.where(UserBillingProfile.id == billing_profile_id) else: stmt = stmt.where(UserBillingProfile.is_default.is_(True)) profile = (await self.session.execute(stmt)).scalar_one_or_none() if profile: return profile profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True) self.session.add(profile) await self.session.flush() return profile async def _create_invoice(self, rzp, tx: PaymentTransaction, profile: UserBillingProfile, payment: dict, plan_names: list[str], meta: dict) -> tuple[str, str | None]: currency = tx.currency.upper() inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}" inv_url = None try: created = rzp.client.invoice.create(data={"type":"invoice","customer":{"name":profile.billing_name,"email":profile.billing_email, **({"contact": profile.billing_phone} if profile.billing_phone else {})},"line_items":[{"name": (", ".join(plan_names) or "Access Subscription")[:250],"amount": int(Decimal(tx.amount)*100),"currency":currency,"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":tx.gateway_transaction_id}}) inv_number = created.get("id") or inv_number inv_url = created.get("short_url") if created.get("status") == "draft": issued = rzp.client.invoice.issue(inv_number) inv_url = issued.get("short_url") or inv_url except Exception: pass base = Decimal(str(meta.get("base_subtotal", tx.amount))) discount = Decimal(str(meta.get("total_discounts", 0))) taxable = Decimal(str(meta.get("taxable_amount", 0))) gst = Decimal(str(meta.get("gst_amount", 0))) self.session.add(Invoice(payment_transaction_id=tx.id, invoice_number=inv_number, billing_name=profile.billing_name, billing_email=profile.billing_email, billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}", gstin=profile.gstin, billing_profile_id=profile.id, base_amount=base, discount_amount=discount, taxable_amount=taxable, gst_amount=gst, total_amount=Decimal(tx.amount), currency_code=currency, exchange_rate_to_inr=Decimal("1"), total_amount_inr=Decimal(tx.amount) if currency == "INR" else None)) return inv_number, inv_url