acupedia-api/app/features/checkout/service.py

295 lines
16 KiB
Python

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, Coupon, 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 generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
EUROPEAN_COUNTRIES = {
"germany", "france", "italy", "spain", "netherlands", "belgium",
"austria", "ireland", "sweden", "denmark", "finland", "portugal",
"greece", "poland", "czech republic", "hungary", "romania",
"iceland", "luxembourg", "croatia", "slovakia", "bulgaria",
"cyprus", "estonia", "latvia", "lithuania", "malta", "slovenia"
}
def validate_user_country_currency(country: str | None, currency: str) -> None:
c = (country or "India").strip().lower()
curr = (currency or "").strip().upper()
if not curr:
raise ValueError("Currency must be specified for checkout.")
if c == "india" or c in {"not configured", "none", "null"}:
if curr != "INR":
raise ValueError(f"Users with billing country India must pay in INR (received {curr}).")
elif c in EUROPEAN_COUNTRIES:
if curr not in {"EUR", "USD"}:
raise ValueError(f"Billing country '{country}' must pay in EUR or USD (received {curr}).")
else:
if curr == "INR":
raise ValueError("INR payments are restricted to domestic Indian billing profiles.")
if curr != "USD":
raise ValueError(f"Billing country '{country}' must pay in USD (received {curr}).")
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:
validate_user_country_currency(user.country, request.currency)
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
else:
try:
edit_data: dict[str, Any] = {"name": user.display_name or user.email, "email": user.email}
if user.phone_number:
edit_data["contact"] = user.phone_number
rzp.client.customer.edit(user.external_ref, data=edit_data)
except Exception:
pass
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
applied_coupon_code = (
request.coupon_code.strip().upper()
if request.coupon_code and calc.coupon_applied and calc.coupon_applied != "None"
else None
)
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": applied_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,
"coupon_code": applied_coupon_code,
"coupon_discount_amount": calc.coupon_discount_amount,
}
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
# If user already had an active unexpired subscription for this plan, extend from previous expiry
prev_sub = (await self.session.execute(
select(UserSubscription)
.where(
UserSubscription.user_id == user.id,
UserSubscription.plan_id == sub.plan_id,
UserSubscription.id != sub.id,
UserSubscription.status == SubscriptionStatus.ACTIVE,
UserSubscription.expires_at > now
).order_by(UserSubscription.expires_at.desc()).limit(1)
)).scalar_one_or_none()
base_expiry = prev_sub.expires_at if prev_sub and prev_sub.expires_at else now
extension_days = 3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365
sub.expires_at = base_expiry + timedelta(days=extension_days)
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_ent = (await self.session.execute(
select(UserEntitlement)
.where(
UserEntitlement.user_id == user.id,
UserEntitlement.module_id == module_id,
UserEntitlement.status == EntitlementStatus.ACTIVE
).limit(1)
)).scalar_one_or_none()
if active_ent:
active_ent.expires_at = sub.expires_at
else:
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))
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
phone_snapshot = profile.billing_phone or payment.get("contact")
if phone_snapshot and subs:
sub_meta = dict(subs[0].metadata_json or {})
sub_meta["billing_phone"] = phone_snapshot
subs[0].metadata_json = sub_meta
invoice, invoice_url = await self._create_invoice(
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
)
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=user.id,
invoice_id=invoice.id,
)
await self.session.commit()
return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice.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:
# Synchronize default/auto-generated profile with user's latest verified contact details
updated = False
if user.phone_number and profile.billing_phone != user.phone_number:
profile.billing_phone = user.phone_number
updated = True
if user.country and profile.country != user.country:
profile.country = user.country
updated = True
if user.display_name and profile.billing_name != user.display_name:
profile.billing_name = user.display_name
updated = True
if updated:
await self.session.flush()
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,
applied_coupon_id: UUID | None = None,
) -> tuple[Invoice, str | None]:
currency = tx.currency.upper()
inv_number = await generate_next_invoice_number(self.session)
# Prioritize current verified user phone and country
phone_to_use = profile.billing_phone or payment.get("contact")
country_to_use = profile.country or "India"
try:
cust_data: dict[str, Any] = {
"name": profile.billing_name,
"email": profile.billing_email,
}
if phone_to_use:
cust_data["contact"] = phone_to_use
rzp.client.invoice.create(data={
"type": "invoice",
"customer": cust_data,
"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},
})
except Exception:
pass
# Always use internal branded Acupedia Tax Invoice view URL
inv_url = f"/api/checkout/payment/{tx.gateway_transaction_id}/invoice/view"
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)))
# Build clean address with current country
addr_parts = [profile.address_line1, profile.city, profile.state, profile.postal_code]
clean_parts = [p.strip() for p in addr_parts if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]]
if country_to_use and country_to_use.strip().lower() not in ["not configured", "none", "null"]:
clean_parts.append(country_to_use.strip())
final_billing_address = ", ".join(clean_parts) if clean_parts else (country_to_use or "Digital Access")
invoice = Invoice(
payment_transaction_id=tx.id,
invoice_number=inv_number,
billing_name=profile.billing_name,
billing_email=profile.billing_email,
billing_address=final_billing_address,
gstin=profile.gstin,
billing_profile_id=profile.id,
applied_coupon_id=applied_coupon_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,
)
self.session.add(invoice)
await self.session.flush()
return invoice, inv_url