""" @router SimulationPaymentRouter @purpose Environment-gated SIMULATED payment confirmation for the customer swarm. This router is only registered when PAYMENT_SIMULATOR_ENABLED=true, and it also refuses requests unless SIMULATION_MODE=true. It only accepts orders belonging to seeded simulation customers (email domain from SIM_CUSTOMER_EMAIL_DOMAIN). It deliberately reuses OrderService.confirm_ecommerce_payment so simulated orders follow the exact same stock deduction, invoice, status-history and payment-ledger path as a real online payment. """ from __future__ import annotations import json from typing import Optional import ulid from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel from sqlalchemy.orm import Session from app.core.config.Config import settings from app.core.database.db_session import get_db from app.api.v1.routers.CustomerProfileRouter import get_current_customer from app.models.EcomCustomerModel import EcomCustomer from app.models.InvoiceModel import Invoice from app.models.OrderModel import Order from app.models.PaymentLedgerModel import PaymentLedger from app.services.OrderService import OrderService router = APIRouter(prefix="/api/v1/payment", tags=["Simulation Payment"]) class SimulatePaymentRequest(BaseModel): order_id: str note: Optional[str] = "Swarm simulated payment" def _ensure_simulation_enabled() -> None: if not settings.PAYMENT_SIMULATOR_ENABLED or not settings.SIMULATION_MODE: # 404 keeps the endpoint invisible in normal/production deployments. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found") def _ensure_sim_customer(customer: EcomCustomer) -> None: domain = (settings.SIM_CUSTOMER_EMAIL_DOMAIN or "@sim.local").lower() if not (customer.email or "").lower().endswith(domain): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Simulated payment is only available to simulation customers", ) @router.post("/simulate") def simulate_payment( payload: SimulatePaymentRequest, customer: EcomCustomer = Depends(get_current_customer), db: Session = Depends(get_db), ): """ Capture a payment for a simulation order and finalize it through the real ecommerce confirmation pipeline (stock deduction + invoice + history). """ _ensure_simulation_enabled() _ensure_sim_customer(customer) order = ( db.query(Order) .filter(Order.order_id == payload.order_id) .with_for_update() .first() ) if not order: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Order not found") if order.customer_id != customer.customer_id: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Order does not belong to this customer") if order.status == "CANCELLED": raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot pay a cancelled order") existing_invoice = ( db.query(Invoice).filter(Invoice.order_id == order.order_id).first() ) if order.payment_status == "PAYMENT_CAPTURED": return { "status": "SUCCESS", "message": "Payment already captured", "order_id": order.order_id, "order_no": order.order_no, "status": order.status, "payment_status": order.payment_status, "invoice_id": existing_invoice.invoice_id if existing_invoice else None, "invoice_no": existing_invoice.invoice_no if existing_invoice else None, } ledger = ( db.query(PaymentLedger) .filter( PaymentLedger.order_id == order.order_id, PaymentLedger.provider == "SIMULATED", ) .order_by(PaymentLedger.created_at.desc()) .first() ) now_ref = f"SIMPAY-{ulid.ULID()}" raw = json.dumps( { "simulated": True, "note": payload.note, "order_no": order.order_no, "amount": float(order.final_amount), } ) if ledger: ledger.transaction_ref = now_ref ledger.amount = order.final_amount ledger.currency = "INR" ledger.status = "CAPTURED" ledger.raw_response_json = raw else: ledger = PaymentLedger( payment_id=str(ulid.ULID()), order_id=order.order_id, provider="SIMULATED", transaction_ref=now_ref, amount=order.final_amount, currency="INR", status="CAPTURED", raw_response_json=raw, ) db.add(ledger) db.flush() invoice = OrderService.confirm_ecommerce_payment(db, order, payment_method="SIMULATED") db.refresh(order) return { "status": "SUCCESS", "message": "Simulated payment captured and order confirmed", "order_id": order.order_id, "order_no": order.order_no, "status": order.status, "payment_status": order.payment_status, "payment_id": ledger.payment_id, "transaction_ref": ledger.transaction_ref, "invoice_id": invoice.invoice_id if invoice else None, "invoice_no": invoice.invoice_no if invoice else None, "amount": float(order.final_amount), }