Coverage for app / services / statements / build.py: 98%
119 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"""A statement, computed: the month, the sections in order, and its CSV.
3Each part of a statement is a registered section (``sections.py``), so a new
4figure is one class there and nothing here. ``build`` runs them in order for
5one workspace and month and returns the statement as served: what
6``spend_statements.content`` stores for a closed month, and what the current
7month is drawn from live.
8"""
10from __future__ import annotations
12import csv
13import hashlib
14import io
15import json
16from dataclasses import dataclass
17from datetime import date, datetime, timedelta
18from typing import Any
20from sqlalchemy.orm import Session
22from app.services.workspace import Workspace
23from app.util.time import aware_utcnow, utc_isoformat
25#: Bumped whenever a section's shape changes; stored on each statement.
26#: 2: the workspace's name and cost centre, each project's cost centre, and
27#: the charges a plan sets (cost-control plan A4.2, A3). 3: rules in force
28#: counted by layer (access / input / output, migration 105) rather than by
29#: type. A statement closed at an earlier version reads as it was kept.
30SCHEMA_VERSION = 3
33@dataclass(frozen=True)
34class Month:
35 """A calendar month (UTC)."""
37 year: int
38 month: int
40 @classmethod
41 def parse(cls, key: str) -> "Month":
42 """``2026-10`` → October 2026. Raises ``ValueError`` otherwise."""
43 try:
44 year_text, month_text = key.split("-")
45 found = cls(int(year_text), int(month_text))
46 except (AttributeError, TypeError, ValueError):
47 raise ValueError(f"Not a month: {key!r} (expected YYYY-MM)") from None
48 if not (1 <= found.month <= 12 and 2000 <= found.year <= 9999):
49 raise ValueError(f"Not a month: {key!r} (expected YYYY-MM)")
50 return found
52 @classmethod
53 def of(cls, moment: datetime | date) -> "Month":
54 return cls(moment.year, moment.month)
56 @property
57 def key(self) -> str:
58 return f"{self.year:04d}-{self.month:02d}"
60 @property
61 def label(self) -> str:
62 return self.first_day.strftime("%B %Y")
64 @property
65 def first_day(self) -> date:
66 return date(self.year, self.month, 1)
68 @property
69 def begin(self) -> datetime:
70 """Its first instant, naive UTC — as the ledger's columns hold time."""
71 return datetime(self.year, self.month, 1)
73 @property
74 def end(self) -> datetime:
75 """The next month's first instant, naive UTC."""
76 return self.next().begin
78 def next(self) -> "Month":
79 return Month(self.year + self.month // 12, self.month % 12 + 1)
81 def previous(self) -> "Month":
82 return Month(self.year - (self.month == 1), (self.month - 2) % 12 + 1)
84 def days(self) -> list[date]:
85 first = self.first_day
86 return [first + timedelta(days=n) for n in range((self.end - self.begin).days)]
89@dataclass(frozen=True)
90class Context:
91 """What every section is computed from."""
93 db: Session
94 here: Any # scope.Here
95 month: Month
96 now: datetime
98 @property
99 def ws(self) -> Workspace:
100 return self.here.ws
103def build(
104 db: Session,
105 ws: Workspace,
106 month: Month,
107 *,
108 now: datetime | None = None,
109 closed: bool = False,
110) -> dict[str, Any]:
111 """``ws``'s statement for ``month``: every registered section, in order.
112 ``closed`` is a month being closed for good; otherwise a draft."""
113 from . import sections
114 from .scope import Here
116 now = now or aware_utcnow()
117 ctx = Context(db=db, here=Here.of(db, ws), month=month, now=now)
118 name, cost_centre = _identity(db, ws)
119 statement: dict[str, Any] = {
120 "schema_version": SCHEMA_VERSION,
121 "workspace": {
122 "key": ws.key,
123 "kind": ws.kind.value,
124 "counts_projects": ctx.here.counts_projects,
125 # As they stood when it was written: a closed statement keeps
126 # them through a rename or a new code.
127 "name": name,
128 "cost_centre": cost_centre,
129 },
130 "period": {
131 "key": month.key,
132 "label": month.label,
133 "start": utc_isoformat(month.begin),
134 "end": utc_isoformat(month.end),
135 },
136 "closed": closed,
137 "generated_at": utc_isoformat(now),
138 }
139 for section in sections.all_sections():
140 statement[section.key] = section.compute(ctx)
141 return statement
144def _identity(db: Session, ws: Workspace) -> tuple[str | None, str | None]:
145 """``ws``'s name and the cost centre finance files it under."""
146 from app.db.postgres.models import Organisation, Project
147 from app.services.workspace import WorkspaceKind
149 if ws.kind is WorkspaceKind.personal:
150 return ws.name or "Personal", None
151 model = Organisation if ws.kind is WorkspaceKind.organisation else Project
152 row = db.get(model, ws.id)
153 if row is None:
154 return ws.name, None
155 return getattr(row, "name", None) or ws.name, getattr(row, "cost_centre", None)
158def digest(statement: dict[str, Any]) -> str:
159 """SHA-256 of the statement's canonical JSON — stored beside a closed
160 one, so a copy can be checked against what the platform kept."""
161 canonical = json.dumps(statement, sort_keys=True, separators=(",", ":"))
162 return hashlib.sha256(canonical.encode()).hexdigest()
165#: The CSV's columns: one row per figure.
166CSV_COLUMNS = ("section", "item", "label", "figure", "value")
169def _csv_rows(statement: dict[str, Any]):
170 from . import sections
172 for section in sections.all_sections():
173 yield from section.csv_rows(statement.get(section.key))
176#: What a spreadsheet reads as the start of a formula.
177_FORMULA_START = ("=", "+", "-", "@", "\t", "\r")
180def _cell(value: Any) -> Any:
181 """A value safe to open in a spreadsheet: a name someone typed that
182 begins like a formula (``=HYPERLINK(…)``) is kept as text."""
183 if isinstance(value, str) and value.startswith(_FORMULA_START):
184 return "'" + value
185 return "" if value is None else value
188def to_csv(statement: dict[str, Any]) -> str:
189 """The statement as one long CSV: ``section, item, label, figure,
190 value`` — every figure a row, so a spreadsheet pivots it any way."""
191 out = io.StringIO()
192 writer = csv.writer(out)
193 writer.writerow(CSV_COLUMNS)
194 workspace = statement["workspace"]
195 rows = [
196 ["statement", "workspace", "", "key", workspace["key"]],
197 *(
198 [["statement", "workspace", "", "cost_centre", workspace["cost_centre"]]]
199 if workspace.get("cost_centre")
200 else []
201 ),
202 ["statement", "period", "", "month", statement["period"]["key"]],
203 ["statement", "period", "", "closed", statement["closed"]],
204 *_csv_rows(statement),
205 ]
206 for row in rows:
207 writer.writerow([_cell(value) for value in row])
208 return out.getvalue()
211#: The finance export's columns (A4.2): the month, whether it is closed, the
212#: workspace and the cost centre a figure is filed under, then the statement
213#: CSV's own.
214EXPORT_COLUMNS = ("month", "closed", "workspace", "cost_centre", *CSV_COLUMNS)
217def to_export_csv(statements: list[dict[str, Any]]) -> str:
218 """Several months' statements as one long CSV for finance: every figure a
219 row, each naming its month and the cost centre it is filed under — the
220 workspace's, or for a project's line of the by-project table the
221 project's own. An organisation's statement counts its projects, so they
222 appear only as those lines and nothing is counted twice."""
223 out = io.StringIO()
224 writer = csv.writer(out)
225 writer.writerow(EXPORT_COLUMNS)
226 for statement in statements:
227 workspace = statement.get("workspace") or {}
228 own_code = workspace.get("cost_centre")
229 project_codes = {
230 str(row.get("key")): row.get("cost_centre")
231 for row in ((statement.get("by_project") or {}).get("rows") or [])
232 }
233 lead = [
234 statement["period"]["key"],
235 bool(statement.get("closed")),
236 workspace.get("name") or workspace.get("key"),
237 ]
238 for row in _csv_rows(statement):
239 section, item = row[0], row[1]
240 if section == "by_project" and row[3] == "cost_centre":
241 continue # the column says it
242 code = (
243 project_codes.get(str(item), own_code)
244 if section == "by_project" and item not in ("unassigned", "other")
245 else own_code
246 )
247 writer.writerow([_cell(value) for value in [*lead, code, *row]])
248 return out.getvalue()