Coverage for app / router / app / statements / router.py: 100%
193 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Statements — `/app/statements` (cost-control plan A4.1; the monthly
3organisation statement).
5A workspace's month as figures: its spend and what governed it, aggregate
6only. A finished month's statement is the one written when it closed
7(``spend_statements``), served exactly as kept; the current month is a draft
8computed now; a finished month not yet closed is computed now too, and says
9so. See ``app/services/statements`` and
10``docs/guides/cost-monitoring.md#monthly-statements``.
11"""
13from __future__ import annotations
15from typing import Any
17from fastapi import APIRouter, Depends, HTTPException, Query, Response
18from pydantic import BaseModel, Field
19from sqlalchemy.orm import Session
21from app.db.postgres.models import SpendStatement, User
22from app.dependency.base import get_db
23from app.dependency.user.context import get_current_user
24from app.dependency.workspace import request_workspace
25from app.services import statements as statement_service
26from app.services.budgets import status as budget_status
27from app.services.statements import store as statement_store
28from app.util.time import UTCDateTime, aware_utcnow
30statements_router = APIRouter(prefix="/statements", tags=["App - Statements"])
32#: How far back a month may be asked for.
33HISTORY_MONTHS = 24
36class StatementPeriod(BaseModel):
37 key: str
38 label: str
39 start: UTCDateTime
40 end: UTCDateTime
43class StatementWorkspace(BaseModel):
44 key: str
45 kind: str
46 #: An organisation's or Personal workspace's statement counts its
47 #: projects too.
48 counts_projects: bool = False
49 #: Its name and the code finance files it under, as they stood when the
50 #: statement was written (schema 2; absent from older ones).
51 name: str | None = None
52 cost_centre: str | None = None
55class PreviousMonth(BaseModel):
56 key: str
57 spend_usd: float | None = None
58 counted_usd: float | None = None
61class SpendFigures(BaseModel):
62 #: What the ledger measured; None only when nothing could be priced.
63 spend_usd: float | None = None
64 #: What budgets count: measured, plus a high estimate for unpriced calls.
65 counted_usd: float | None = None
66 unpriced_calls: int = 0
67 #: Governed turns: answers, skill runs, evaluation cells, tiles.
68 decisions: int = 0
69 calls: int = 0
70 input_tokens: int = 0
71 output_tokens: int = 0
72 failed_spend_usd: float | None = None
73 previous_month: PreviousMonth | None = None
76class StatementPlan(BaseModel):
77 kind: str
78 currency: str = "USD"
79 fee_usd: float = 0.0
80 markup_percent: float = 0.0
81 included_usd: float = 0.0
84class StatementCharges(BaseModel):
85 """The month under the workspace's plan (``services/plans.py``): an
86 estimate to invoice by hand (schema 2)."""
88 title: str
89 plan: StatementPlan
90 currency: str = "USD"
91 fee_usd: float = 0.0
92 usage_usd: float = 0.0
93 included_usd: float = 0.0
94 usage_above_usd: float = 0.0
95 markup_percent: float = 0.0
96 usage_charge_usd: float = 0.0
97 total_usd: float = 0.0
98 unpriced_calls: int = 0
99 note: str | None = None
102class StatementRow(BaseModel):
103 key: str
104 label: str
105 #: A project's cost centre, on the by-project table (schema 2).
106 cost_centre: str | None = None
107 spend_usd: float | None = None
108 counted_usd: float | None = None
109 unpriced_calls: int = 0
110 decisions: int = 0
111 calls: int = 0
112 input_tokens: int = 0
113 output_tokens: int = 0
116class StatementTable(BaseModel):
117 title: str
118 rows: list[StatementRow]
121class StatementDay(BaseModel):
122 date: str
123 spend_usd: float | None = None
124 counted_usd: float | None = None
125 decisions: int = 0
128class StatementBudget(BaseModel):
129 key: str
130 label: str
131 #: ``rule`` (a cost cap) or ``platform`` (the platform allowance).
132 kind: str
133 cap_usd: float | None = None
134 period: str | None = None
135 period_label: str | None = None
136 #: What the month spent against it, as it counts.
137 spent_usd: float | None = None
138 #: Turns it refused up front, stopped part-way, and let through past it.
139 refused: int = 0
140 stopped: int = 0
141 let_through: int = 0
144class GovernanceFigures(BaseModel):
145 rules_in_force: dict[str, int] = Field(default_factory=dict)
146 rule_outcomes: dict[str, int] = Field(default_factory=dict)
149class ReviewFigures(BaseModel):
150 raised: int = 0
151 decided: int = 0
152 decided_by_status: dict[str, int] = Field(default_factory=dict)
153 open_at_end: int = 0
154 median_hours_to_decision: float | None = None
157class EvaluationFigures(BaseModel):
158 runs_completed: int = 0
159 regressions_caught: int = 0
162class DecisionFigures(BaseModel):
163 governed: int = 0
164 verified: int = 0
165 verdicts: dict[str, int] = Field(default_factory=dict)
166 corrections_captured: int = 0
169class Statement(BaseModel):
170 """One workspace's month (``app/services/statements``)."""
172 schema_version: int
173 workspace: StatementWorkspace
174 period: StatementPeriod
175 #: Written when the month closed, and kept unchanged; otherwise a draft.
176 closed: bool
177 generated_at: UTCDateTime
178 #: SHA-256 of the kept statement's canonical JSON — a closed one only.
179 content_sha256: str | None = None
180 spend: SpendFigures
181 #: Set when the workspace has a plan (schema 2).
182 charges: StatementCharges | None = None
183 by_source: StatementTable | None = None
184 by_agent: StatementTable | None = None
185 by_model: StatementTable | None = None
186 by_kind: StatementTable | None = None
187 by_project: StatementTable | None = None
188 daily: list[StatementDay] = Field(default_factory=list)
189 budgets: list[StatementBudget] = Field(default_factory=list)
190 governance: GovernanceFigures
191 reviews: ReviewFigures
192 evaluations: EvaluationFigures
193 decisions: DecisionFigures
196class StatementSummary(BaseModel):
197 period: StatementPeriod
198 closed: bool
199 closed_at: UTCDateTime | None = None
200 spend_usd: float | None = None
201 counted_usd: float | None = None
202 decisions: int = 0
205class StatementList(BaseModel):
206 workspace: str
207 #: The month so far, as a draft.
208 current: StatementSummary
209 #: Closed months, newest first.
210 closed: list[StatementSummary]
213def _month(key: str) -> statement_service.Month:
214 try:
215 month = statement_service.Month.parse(key)
216 except ValueError as exc:
217 raise HTTPException(status_code=422, detail=str(exc)) from exc
218 now = statement_service.Month.of(aware_utcnow())
219 if (month.year, month.month) > (now.year, now.month):
220 raise HTTPException(status_code=404, detail="That month has not begun.")
221 oldest = now
222 for _ in range(HISTORY_MONTHS):
223 oldest = oldest.previous()
224 if (month.year, month.month) < (oldest.year, oldest.month):
225 raise HTTPException(status_code=404, detail="Statements go back two years.")
226 return month
229def _statement(db: Session, ws: Any, month: statement_service.Month) -> dict:
230 row = statement_store.stored(db, ws.key, month)
231 if row is not None:
232 return {**row.content, "content_sha256": row.content_sha256}
233 return statement_service.build(db, ws, month)
236def _summary(content: dict, row: SpendStatement | None = None) -> dict:
237 spend = content.get("spend") or {}
238 return {
239 "period": content["period"],
240 "closed": bool(content.get("closed")),
241 "closed_at": row.closed_at if row is not None else None,
242 "spend_usd": spend.get("spend_usd"),
243 "counted_usd": spend.get("counted_usd"),
244 "decisions": spend.get("decisions") or 0,
245 }
248@statements_router.get("", response_model=StatementList)
249def list_statements(
250 db: Session = Depends(get_db),
251 current_user: User = Depends(get_current_user),
252):
253 """The workspace's month so far, and every month it has closed."""
254 ws = request_workspace(db, current_user)
255 current = statement_service.build(
256 db, ws, statement_service.Month.of(aware_utcnow())
257 )
258 rows = (
259 db.query(SpendStatement)
260 .filter(SpendStatement.workspace_key == ws.key)
261 .order_by(SpendStatement.period_start.desc())
262 .limit(HISTORY_MONTHS)
263 .all()
264 )
265 return {
266 "workspace": ws.key,
267 "current": _summary(current),
268 "closed": [_summary(row.content, row) for row in rows],
269 }
272#: The most months one finance export covers.
273EXPORT_MONTHS = 24
276@statements_router.get("/export")
277def export_statements(
278 from_month: str = Query(..., alias="from"),
279 to_month: str = Query(..., alias="to"),
280 db: Session = Depends(get_db),
281 current_user: User = Depends(get_current_user),
282):
283 """The workspace's statements from ``from`` to ``to`` (``YYYY-MM``, at
284 most :data:`EXPORT_MONTHS` months) as one CSV for finance (A4.2): every
285 figure a row, naming its month and the cost centre it is filed under. A
286 closed month as it was kept; the current one as a draft. For those who
287 govern the workspace: it spans its projects."""
288 ws = request_workspace(db, current_user)
289 if not budget_status.governs(db, ws, current_user):
290 raise HTTPException(
291 status_code=403,
292 detail="Only those who govern this workspace may export its statements.",
293 )
294 first, last = _month(from_month), _month(to_month)
295 if (first.year, first.month) > (last.year, last.month):
296 raise HTTPException(status_code=422, detail="The range ends before it starts.")
297 months = [first]
298 while months[-1] != last:
299 months.append(months[-1].next())
300 if len(months) > EXPORT_MONTHS:
301 raise HTTPException(
302 status_code=422,
303 detail=f"An export covers at most {EXPORT_MONTHS} months.",
304 )
305 statements = [
306 Statement.model_validate(_statement(db, ws, month)).model_dump(mode="json")
307 for month in months
308 ]
309 filename = f"chainr-statements-{ws.kind.value}-{first.key}-to-{last.key}.csv"
310 return Response(
311 content=statement_service.to_export_csv(statements),
312 media_type="text/csv; charset=utf-8",
313 headers={"Content-Disposition": f'attachment; filename="{filename}"'},
314 )
317@statements_router.get("/{month}", response_model=Statement)
318def get_statement(
319 month: str,
320 db: Session = Depends(get_db),
321 current_user: User = Depends(get_current_user),
322):
323 """One month's statement: as kept when it closed, or computed now."""
324 ws = request_workspace(db, current_user)
325 return _statement(db, ws, _month(month))
328@statements_router.get("/{month}/csv")
329def get_statement_csv(
330 month: str,
331 db: Session = Depends(get_db),
332 current_user: User = Depends(get_current_user),
333):
334 """One month's statement as a CSV: one row per figure."""
335 ws = request_workspace(db, current_user)
336 found = _month(month)
337 content = Statement.model_validate(_statement(db, ws, found)).model_dump(
338 mode="json"
339 )
340 filename = f"chainr-statement-{ws.kind.value}-{found.key}.csv"
341 return Response(
342 content=statement_service.to_csv(content),
343 media_type="text/csv; charset=utf-8",
344 headers={"Content-Disposition": f'attachment; filename="{filename}"'},
345 )