"""Read-only pack API, mounted by core under ``/packs/ecommerce``. Contract (consumed by the web dashboard): * ``GET /orders?status=&payment_method=&risk_band=&q=&limit=50&offset=0`` -> ``{"items": [{number, customer_name, city, total, payment_method, status, fulfillment_status, risk: null|{score, band, reasons}, confirmation_status: null|str, courier: null|{name, tracking, status}, created_at}], "total": int}`` * ``GET /orders/{number}`` -> the list-row fields plus ``items``, ``customer``, ``shipments``, ``messages``, ``tickets``, ``refunds`` and money/address details. * ``GET /cod/summary`` -> ``{pending_confirmation, confirmed, rto_rate: float|null, cod_outstanding, by_band: {low, medium, high}}``. Every query runs in a session bound to the caller's tenant, so RLS applies. Writes never go through these routes: they go through the gateway (chat, approvals, MCP). """ from __future__ import annotations from typing import Any, Literal from fastapi import APIRouter, Depends, HTTPException, Query, Request from sqlalchemy import and_, func, select from core.auth.deps import Principal, current_principal from core.db.session import Database from packs.ecommerce.models import Order, Shipment from packs.ecommerce.views import list_orders, order_by_number, order_detail router = APIRouter() def _db(request: Request) -> Database: db: Database = request.app.state.services.db return db @router.get("/orders") async def orders( status: str | None = None, payment_method: Literal["COD", "prepaid", "cod"] | None = None, risk_band: Literal["low", "medium", "high"] | None = None, q: str | None = Query(default=None, max_length=100), limit: int = Query(default=50, ge=1, le=200), offset: int = Query(default=0, ge=0), p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: items, total = await list_orders( s, limit=limit, offset=offset, status=status or None, payment_method=payment_method, risk_band=risk_band, text=q or None, ) return {"items": items, "total": total} @router.get("/orders/{number}") async def order( number: str, p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: o = await order_by_number(s, number) if o is None: raise HTTPException(404, f"order {number} not found") return await order_detail(s, o) @router.get("/cod/summary") async def cod_summary( p: Principal = Depends(current_principal), db: Database = Depends(_db), ) -> dict[str, Any]: async with db.session(tenant_id=p.tenant_id) as s: cod = Order.payment_method == "COD" open_order = Order.status.notin_(("cancelled", "returned", "delivered")) pending = ( await s.execute( select(func.count()).where( cod, Order.confirmation_status == "pending", Order.status == "pending" ) ) ).scalar_one() confirmed = ( await s.execute( select(func.count()).where( cod, Order.confirmation_status == "confirmed", open_order ) ) ).scalar_one() delivered, returned = ( await s.execute( select( func.count().filter(Order.status == "delivered"), func.count().filter(Order.status == "returned"), ).where(cod) ) ).one() outstanding = ( await s.execute( select(func.coalesce(func.sum(Shipment.cod_amount), 0)) .join(Order, Order.id == Shipment.order_id) .where( and_( cod, Shipment.status.notin_(("returned", "cancelled")), Shipment.remitted_at.is_(None), ) ) ) ).scalar_one() bands = dict( ( await s.execute( select(Order.risk_band, func.count()) .where(cod, open_order, Order.risk_band.is_not(None)) .group_by(Order.risk_band) ) ).all() ) finished = int(delivered) + int(returned) return { "pending_confirmation": int(pending), "confirmed": int(confirmed), "rto_rate": round(int(returned) / finished, 4) if finished else None, "cod_outstanding": int(outstanding), "by_band": {b: int(bands.get(b, 0)) for b in ("low", "medium", "high")}, }