Spaces:
Running

File size: 4,312 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
"""Read-only Phase 9 API, mounted by core under ``/packs/ecommerce`` (next to ``api.py``).



Contract (for the web dashboard):



* ``GET /reports/latest?period=daily|weekly`` -> ``{id, period, start, end (exclusive),

  metrics, narrative, narrative_source: "llm"|"template", validation: {ok, numbers, unknown,

  rejected_drafts}, created_at}``; 404 if no report yet.

* ``GET /anomalies?status=open&limit=50`` -> ``{"items": [{id, type: "notify", metric, day,

  value, baseline, zscore, direction, severity, status, message, created_at}]}``.

* ``GET /tasks?status=&assignee=me|<uuid>&open_only=true&limit=50&offset=0`` ->

  ``{"items": [{number, title, description, status, priority, assignee_user_id, due_at,

  order_number, created_at, completed_at}], "total": int}``.

* ``GET /forecasts/latest`` -> ``{"items": [{sku, method, horizon_days, quantiles: {p10, p50,

  p90, daily}, backtest, mape, wape, sigma_daily, history_days, created_at}]}``.

* ``GET /purchase-orders?status=`` -> ``{"items": [{number, supplier, status, total_cost,

  reason, lines: [{sku, quantity, unit_cost, line_total, rationale}], created_at,

  submitted_at}]}``.



Sessions are bound to the caller's tenant (RLS). Writes go through the gateway only.

"""

from __future__ import annotations

import uuid
from typing import Any, Literal

from fastapi import APIRouter, Depends, HTTPException, Query, Request

from core.auth.deps import Principal, current_principal
from core.db.session import Database
from packs.ecommerce.views_ops import (
    latest_forecasts,
    latest_report,
    list_anomalies,
    list_purchase_orders,
    list_tasks_view,
    report_view,
)

router = APIRouter()


def _db(request: Request) -> Database:
    db: Database = request.app.state.services.db
    return db


@router.get("/reports/latest")
async def report_latest(

    period: Literal["daily", "weekly"] | None = None,

    p: Principal = Depends(current_principal),

    db: Database = Depends(_db),

) -> dict[str, Any]:
    async with db.session(tenant_id=p.tenant_id) as s:
        r = await latest_report(s, period)
        if r is None:
            raise HTTPException(404, "no report yet")
        return report_view(r)


@router.get("/anomalies")
async def anomalies(

    status: Literal["open", "acknowledged"] | None = None,

    limit: int = Query(default=50, ge=1, le=200),

    p: Principal = Depends(current_principal),

    db: Database = Depends(_db),

) -> dict[str, Any]:
    async with db.session(tenant_id=p.tenant_id) as s:
        return {"items": await list_anomalies(s, status=status, limit=limit)}


@router.get("/tasks")
async def tasks(

    status: Literal["todo", "in_progress", "done"] | None = None,

    assignee: str | None = Query(default=None, description="'me' or a user id"),

    open_only: bool = False,

    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]:
    who: uuid.UUID | None = None
    if assignee == "me":
        who = p.user_id
    elif assignee:
        try:
            who = uuid.UUID(assignee)
        except ValueError as exc:
            raise HTTPException(422, "assignee must be 'me' or a user id") from exc
    async with db.session(tenant_id=p.tenant_id) as s:
        items, total = await list_tasks_view(
            s, status=status, assignee=who, open_only=open_only, limit=limit, offset=offset
        )
    return {"items": items, "total": total}


@router.get("/forecasts/latest")
async def forecasts(

    p: Principal = Depends(current_principal),

    db: Database = Depends(_db),

) -> dict[str, Any]:
    async with db.session(tenant_id=p.tenant_id) as s:
        return {"items": await latest_forecasts(s)}


@router.get("/purchase-orders")
async def purchase_orders(

    status: Literal["draft", "submitted", "cancelled", "received"] | None = None,

    limit: int = Query(default=50, ge=1, le=200),

    p: Principal = Depends(current_principal),

    db: Database = Depends(_db),

) -> dict[str, Any]:
    async with db.session(tenant_id=p.tenant_id) as s:
        return {"items": await list_purchase_orders(s, status=status, limit=limit)}