Spaces:
Running
Running
File size: 10,692 Bytes
0776bd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | """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
],
}
|