Spaces:
Running

WorkPilot-AI / packs /ecommerce /api_cod.py
Aynkhn's picture
Deploy WorkPilot demo (part 2)
0776bd5 verified
Raw History Blame Contribute Delete
10.7 kB
"""Phase 8 COD API, mounted by core under ``/packs/ecommerce`` (next to ``api.py``).
Read-only (tenant-bound sessions, RLS applies):
* ``GET /cod/reconciliation?status=open|resolved|all&limit=200`` -> ``{"summary": {open_issues,
by_kind, amount_difference, missing_amount, statements, remitted_total, outstanding},
"issues": [{kind, tracking_number, courier, order_number, expected_amount,
remitted_amount, difference, days_outstanding, detail, status, created_at, resolved_at}],
"statements": [{courier, statement_ref, source, line_count, total_cod, total_fees,
total_net, match: {matched, amount_mismatch, ...}, imported_at}]}``
* ``GET /cod/whatsapp-costs?days=30`` -> the WhatsApp cost ledger and cost per confirmed
order (see ``wa_costs``).
* ``GET /cod/confirmations?status=pending&limit=100`` -> ``{"items": [attempt...]}``.
* ``GET /orders/{number}/risk`` -> the risk card ``{score, band, reasons, reason_details,
model_version, features, history: [{score, band, stage, created_at}]}``.
Write (through the gateway, as the operator, audited):
* ``POST /cod/remittances`` with JSON ``{"courier", "statement_ref", "csv"}`` (or a
``text/csv`` body with ``?courier=&statement_ref=``) runs the T1 tool
``ecommerce.import_remittance``. ``200`` with the import + reconciliation summary;
``400`` for a bad file, ``403`` if the gateway denies.
"""
from __future__ import annotations
from collections import defaultdict
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from sqlalchemy import func, select
from core.auth.deps import Principal, current_principal, require_role
from core.gateway.gateway import ToolCall
from core.services import Services
from core.tenancy.models import Role, Tenant
from packs.ecommerce.models import Order, Shipment
from packs.ecommerce.models_cod import (
CodConfirmation,
CodReconIssue,
CodRemittance,
CodRemittanceLine,
RtoScore,
)
from packs.ecommerce.tools.cod import attempt_view
from packs.ecommerce.views import iso, order_by_number
from packs.ecommerce.wa_costs import whatsapp_costs
router = APIRouter()
def _svc(request: Request) -> Services:
svc: Services = request.app.state.services
return svc
def issue_view(i: CodReconIssue) -> dict[str, Any]:
return {
"kind": i.kind,
"tracking_number": i.tracking_number,
"courier": i.courier,
"order_number": i.order_number,
"expected_amount": i.expected_amount,
"remitted_amount": i.remitted_amount,
"difference": i.difference,
"days_outstanding": i.days_outstanding,
"detail": i.detail,
"status": i.status,
"created_at": iso(i.created_at),
"resolved_at": iso(i.resolved_at),
}
@router.get("/cod/reconciliation")
async def reconciliation_report(
status: Literal["open", "resolved", "all"] = "open",
limit: int = Query(default=200, ge=1, le=1000),
p: Principal = Depends(current_principal),
svc: Services = Depends(_svc),
) -> dict[str, Any]:
async with svc.db.session(tenant_id=p.tenant_id) as s:
q = select(CodReconIssue).order_by(CodReconIssue.kind, CodReconIssue.tracking_number)
if status != "all":
q = q.where(CodReconIssue.status == status)
issues = list((await s.execute(q.limit(limit))).scalars())
open_rows = list(
(await s.execute(select(CodReconIssue).where(CodReconIssue.status == "open"))).scalars()
)
statements = list(
(
await s.execute(
select(CodRemittance).order_by(CodRemittance.imported_at.desc()).limit(50)
)
).scalars()
)
match_rows = (
await s.execute(
select(
CodRemittanceLine.remittance_id, CodRemittanceLine.match_status, func.count()
).group_by(CodRemittanceLine.remittance_id, CodRemittanceLine.match_status)
)
).all()
remitted_total = (
await s.execute(select(func.coalesce(func.sum(CodRemittance.total_net), 0)))
).scalar_one()
outstanding = (
await s.execute(
select(func.coalesce(func.sum(Shipment.cod_amount), 0))
.join(Order, Order.id == Shipment.order_id)
.where(
Order.payment_method == "COD",
Shipment.status == "delivered",
Shipment.remitted_at.is_(None),
)
)
).scalar_one()
matches: dict[Any, dict[str, int]] = defaultdict(dict)
for rid, ms, n in match_rows:
matches[rid][ms] = int(n)
by_kind: dict[str, int] = defaultdict(int)
for i in open_rows:
by_kind[i.kind] += 1
return {
"summary": {
"open_issues": len(open_rows),
"by_kind": dict(sorted(by_kind.items())),
"amount_difference": sum(
i.difference or 0 for i in open_rows if i.kind == "amount_mismatch"
),
"missing_amount": sum(
i.expected_amount or 0 for i in open_rows if i.kind == "missing_remittance"
),
"statements": len(statements),
"remitted_total": int(remitted_total),
"outstanding": int(outstanding),
},
"issues": [issue_view(i) for i in issues],
"statements": [
{
"courier": r.courier,
"statement_ref": r.statement_ref,
"source": r.source,
"line_count": r.line_count,
"total_cod": r.total_cod,
"total_fees": r.total_fees,
"total_net": r.total_net,
"match": matches.get(r.id, {}),
"imported_at": iso(r.imported_at),
}
for r in statements
],
}
class RemittanceUpload(BaseModel):
courier: str = Field(min_length=2, max_length=40)
statement_ref: str = Field(min_length=1, max_length=100)
csv: str = Field(min_length=1, max_length=2_000_000)
@router.post("/cod/remittances")
async def upload_remittance(
request: Request,
courier: str | None = None,
statement_ref: str | None = None,
p: Principal = Depends(require_role(Role.MANAGER)),
svc: Services = Depends(_svc),
) -> dict[str, Any]:
ctype = request.headers.get("content-type", "")
if ctype.startswith("text/csv") or ctype.startswith("text/plain"):
if not courier or not statement_ref:
raise HTTPException(400, "a CSV body needs ?courier=&statement_ref=")
raw = await request.body()
if len(raw) > 2_000_000:
raise HTTPException(413, "file too large")
body = RemittanceUpload(
courier=courier, statement_ref=statement_ref, csv=raw.decode("utf-8-sig")
)
else:
try:
body = RemittanceUpload.model_validate(await request.json())
except ValueError as exc:
raise HTTPException(400, f"bad request: {exc}") from exc
outcome = await svc.gateway.execute(
ToolCall(
tenant_id=p.tenant_id,
actor=p.actor,
tool="ecommerce.import_remittance",
args={
"courier": body.courier,
"statement_ref": body.statement_ref,
"source": "csv",
"csv_text": body.csv,
},
)
)
if outcome.status == "executed" and outcome.result is not None and outcome.result.ok:
return {"status": "imported", **(outcome.result.data or {})}
reason = outcome.reason or (outcome.result.error if outcome.result else outcome.status)
raise HTTPException(400 if outcome.status == "failed" else 403, reason or "import failed")
@router.get("/cod/whatsapp-costs")
async def whatsapp_cost_report(
days: int = Query(default=30, ge=1, le=365),
p: Principal = Depends(current_principal),
svc: Services = Depends(_svc),
) -> dict[str, Any]:
since = datetime.now(UTC) - timedelta(days=days)
async with svc.db.session(tenant_id=p.tenant_id) as s:
settings = (
await s.execute(select(Tenant.settings).where(Tenant.id == p.tenant_id))
).scalar_one_or_none()
return await whatsapp_costs(s, dict(settings or {}), since)
@router.get("/cod/confirmations")
async def confirmations(
status: Literal["pending", "confirmed", "rejected", "no_answer", "superseded"] | None = (
"pending"
),
limit: int = Query(default=100, ge=1, le=500),
p: Principal = Depends(current_principal),
svc: Services = Depends(_svc),
) -> dict[str, Any]:
q = (
select(CodConfirmation, Order.number)
.join(Order, Order.id == CodConfirmation.order_id)
.order_by(CodConfirmation.created_at.desc())
.limit(limit)
)
if status:
q = q.where(CodConfirmation.status == status)
async with svc.db.session(tenant_id=p.tenant_id) as s:
rows = (await s.execute(q)).all()
return {"items": [attempt_view(a, n) for a, n in rows]}
@router.get("/orders/{number}/risk")
async def order_risk(
number: str,
p: Principal = Depends(current_principal),
svc: Services = Depends(_svc),
) -> dict[str, Any]:
async with svc.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")
scores = list(
(
await s.execute(
select(RtoScore)
.where(RtoScore.order_id == o.id)
.order_by(RtoScore.created_at.desc())
)
).scalars()
)
if not scores:
raise HTTPException(404, f"order {number} has no risk score yet")
latest = scores[0]
return {
"order_number": o.number,
"score": latest.score,
"band": latest.band,
"reasons": [r.get("text") for r in latest.reasons],
"reason_details": latest.reasons,
"model_version": latest.model_version,
"features": latest.features,
"history": [
{"score": r.score, "band": r.band, "stage": r.stage, "created_at": iso(r.created_at)}
for r in scores
],
}