46 lines
2.7 KiB
Python
46 lines
2.7 KiB
Python
from __future__ import annotations
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from app.db.models import AppUser
|
|
from app.features.payments import get_razorpay_service
|
|
from .deps import get_checkout_service, get_current_user
|
|
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
|
|
from .service import CheckoutService
|
|
router = APIRouter(prefix="/checkout", tags=["Checkout & Payments"])
|
|
|
|
@router.get("/config")
|
|
async def get_checkout_config():
|
|
try: return {"razorpay_key_id": get_razorpay_service().key_id}
|
|
except RuntimeError as exc: raise HTTPException(503, detail=str(exc)) from exc
|
|
|
|
@router.post("/create-order", response_model=CheckoutOrderResponse)
|
|
async def create_checkout_order(payload: CheckoutOrderRequest, user: AppUser = Depends(get_current_user), service: CheckoutService = Depends(get_checkout_service)):
|
|
try: return await service.create_order(user, payload)
|
|
except ValueError as exc: raise HTTPException(400, detail=str(exc)) from exc
|
|
except RuntimeError as exc: raise HTTPException(503, detail=str(exc)) from exc
|
|
except Exception as exc: raise HTTPException(502, detail=f"Razorpay checkout initialization failed: {exc}") from exc
|
|
|
|
@router.post("/verify")
|
|
async def verify_checkout_payment(payload: CheckoutVerifyRequest, user: AppUser = Depends(get_current_user), service: CheckoutService = Depends(get_checkout_service)):
|
|
try: return await service.verify(user, payload)
|
|
except LookupError as exc: raise HTTPException(404, detail=str(exc)) from exc
|
|
except ValueError as exc: raise HTTPException(400, detail=str(exc)) from exc
|
|
except RuntimeError as exc: raise HTTPException(503, detail=str(exc)) from exc
|
|
|
|
@router.get("/payment/{payment_id}/invoice")
|
|
async def get_checkout_payment_invoice(payment_id: str, user: AppUser = Depends(get_current_user), service: CheckoutService = Depends(get_checkout_service)):
|
|
from sqlalchemy import select
|
|
from app.db.models import PaymentTransaction
|
|
from app.features.admin.service import AdminService
|
|
tx = (await service.session.execute(select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id, PaymentTransaction.user_id == user.id))).scalar_one_or_none()
|
|
if not tx:
|
|
raise HTTPException(404, detail="Transaction record not found or access denied.")
|
|
try:
|
|
url, _, _ = await AdminService(service.session).get_or_create_invoice(payment_id)
|
|
if not url:
|
|
raise HTTPException(500, detail="Razorpay invoice does not have a download URL.")
|
|
return {"short_url": url}
|
|
except HTTPException:
|
|
raise
|
|
except Exception as exc:
|
|
raise HTTPException(502, detail=f"Failed to generate invoice from Razorpay: {exc}") from exc
|