Coverage for app / router / app / budgets / router.py: 100%
92 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"""
2Budgets — `/app/budgets` (cost-control plan, A1.2).
4Where every cost cap governing the request's workspace stands: what its
5period has spent, what is left, when it resets, the period before, and a
6forecast. Read from the cap's own reading, so a budget reads ``reached``
7exactly when the next turn it governs would be refused. See
8``app/services/budgets`` and ``docs/guides/cost-monitoring.md#budgets``.
9"""
11from typing import Literal
12from uuid import UUID
14from fastapi import APIRouter, Depends
15from pydantic import BaseModel
16from sqlalchemy.orm import Session
18from app.db.postgres.models import User
19from app.dependency.base import get_db
20from app.dependency.user.context import get_current_user
21from app.dependency.workspace import request_workspace
22from app.services.budgets import status as budget_service
23from app.util.time import UTCDateTime
25budgets_router = APIRouter(prefix="/budgets", tags=["App - Budgets"])
28class BudgetForecast(BaseModel):
29 """A projection of the period's spend at its end — or why there is none."""
31 available: bool
32 #: ``trailing_window``, ``not_enough_history`` or ``unreadable``.
33 unavailable: str | None = None
34 note: str | None = None
35 projected_usd: float | None = None
36 #: One standard deviation of the trailing days' spend either side.
37 low_usd: float | None = None
38 high_usd: float | None = None
39 daily_rate_usd: float | None = None
40 days_used: int = 0
41 #: When the cap is reached at that rate, if before the period ends.
42 reaches_cap_at: UTCDateTime | None = None
45class BudgetMember(BaseModel):
46 """What one member spent against a budget — for those who govern the
47 workspace only."""
49 user_id: UUID
50 name: str
51 spent_usd: float
54class Budget(BaseModel):
55 """One cost cap, where it stands."""
57 rule_id: UUID
58 rule_name: str
59 #: Which of the rule's actions it is.
60 action_index: int
61 #: Why it is in this workspace: ``own``, ``inherited`` or ``required``.
62 origin: str | None = None
63 home_workspace: str | None = None
64 scope_type: str | None = None
65 scope_id: str | None = None
66 required_for_projects: bool = False
67 #: The rule's conditions: above 0, it caps only the work they match.
68 conditions: int = 0
69 period: str | None = None
70 period_label: str | None = None
71 window_seconds: int | None = None
72 #: ``shared`` (one allowance for everyone it counts) or ``per_member``.
73 share: str | None = None
74 #: Whose spend the figures are: ``workspace``, or ``yours`` for a cap
75 #: given to each member.
76 counts: Literal["workspace", "yours"] | None = None
77 execution_types: list[str] = []
78 #: ``block`` or ``warn``.
79 on_reach: str | None = None
80 #: When it alerts those who govern the workspace, in their inbox
81 #: (``QuotaAlert``: ``50``, ``80``, ``100``, ``projected``).
82 alert_at: list[str] = []
83 cap_usd: float | None = None
84 spent_usd: float | None = None
85 remaining_usd: float | None = None
86 #: Spent over cap, 0–1 (above 1 once a turn in flight overshot it).
87 used_share: float | None = None
88 period_start: UTCDateTime | None = None
89 resets_at: UTCDateTime | None = None
90 previous_spent_usd: float | None = None
91 forecast: BudgetForecast | None = None
92 #: ``reached``, ``projected_over``, ``near``, ``ok`` or ``unavailable``.
93 status: str
94 #: Whether the next turn it governs would be refused: used up, or with
95 #: less left than a turn usually costs (its room to finish one).
96 blocks: bool = False
97 #: What a turn must find left to start — a typical turn in the workspace
98 #: — when the cap keeps room to finish one (``reserve``).
99 reserve_usd: float | None = None
100 #: Who spent what — only for those who govern the workspace.
101 members: list[BudgetMember] | None = None
102 note: str | None = None
105class PlatformAllowance(BaseModel):
106 """CHAIN-R's own monthly cap on the workspace's spend — or, for a
107 project, its parent's (``app/services/budgets/allowance.py``). Set by the
108 deployment, editable by nobody here, and read as a cost cap is."""
110 name: str
111 #: ``personal`` or ``organisation``: whose allowance it is.
112 holder: str
113 #: That workspace's key.
114 holder_workspace: str
115 cap_usd: float | None = None
116 period: str | None = None
117 period_label: str | None = None
118 spent_usd: float | None = None
119 remaining_usd: float | None = None
120 used_share: float | None = None
121 period_start: UTCDateTime | None = None
122 resets_at: UTCDateTime | None = None
123 previous_spent_usd: float | None = None
124 forecast: BudgetForecast | None = None
125 status: str
126 blocks: bool = False
127 reserve_usd: float | None = None
128 note: str | None = None
131class SpendOverview(BaseModel):
132 """The workspace's calendar month, counted as a budget for it would be."""
134 period_start: UTCDateTime
135 resets_at: UTCDateTime | None = None
136 spent_usd: float | None = None
137 last_month_usd: float | None = None
138 forecast: BudgetForecast
141class BudgetsResponse(BaseModel):
142 workspace: str
143 #: Whether the caller governs the workspace (sees ``members``, and may
144 #: add a budget).
145 governs: bool
146 overview: SpendOverview | None = None
147 #: Worst first.
148 budgets: list[Budget]
149 #: The platform's allowance, when the deployment sets one.
150 allowance: PlatformAllowance | None = None
151 #: What a turn in the workspace usually costs — what a cap keeps back.
152 typical_turn_usd: float | None = None
155@budgets_router.get("", response_model=BudgetsResponse)
156def list_budgets(
157 db: Session = Depends(get_db),
158 current_user: User = Depends(get_current_user),
159):
160 """Every budget governing the request's workspace, worst first, the
161 platform allowance it counts against, and the workspace's month so far,
162 last month and forecast."""
163 ws = request_workspace(db, current_user)
164 return budget_service.budgets(db, current_user, ws)