codex/aram-cross-statement-controls-20261031
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 333 lines 12.9 KB
Raw
1 """Read-only preview of account-to-note Mapping coverage.
2
3 NEVER use the returned amounts as official financial statements. The workbook
4 can claim 'Approved', but a cell is not a verified reviewer identity. This
5 module performs no database writes, postings, imports or export of reports.
6 """
7 from __future__ import annotations
8
9 from collections import defaultdict
10 from dataclasses import asdict, dataclass
11 from decimal import Decimal, InvalidOperation, localcontext
12 from hashlib import sha256
13 from io import BytesIO
14 from typing import Any
15 from zipfile import BadZipFile, ZipFile
16
17 from openpyxl import load_workbook
18
19 from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook
20
21 MAX_INPUT_BYTES = 20 * 1024 * 1024
22 MAX_ZIP_ENTRIES = 500
23 MAX_EXPANDED_BYTES = 128 * 1024 * 1024
24
25
26 class CoverageError(ValueError):
27 """A deterministic fail-closed coverage precondition violation."""
28
29 def __init__(self, code: str) -> None:
30 self.code = code
31 super().__init__(code)
32
33
34 @dataclass(frozen=True)
35 class CoverageException:
36 code: str
37 account_code: str
38 account_excel_row: int
39 mapping_excel_rows: tuple[int, ...]
40
41
42 @dataclass(frozen=True)
43 class AccountTrace:
44 account_code: str
45 account_name: str
46 account_excel_row: int
47 source_row: int
48 closing_exposure: str
49 mapping_excel_row: int | None
50 mapping_id: str | None
51 target_statement: str | None
52 target_section: str | None
53 target_note: str | None
54 target_subnote: str | None
55 included: bool
56
57
58 @dataclass(frozen=True)
59 class NoteExposure:
60 statement: str
61 section: str
62 note_number: str
63 subnote_code: str
64 closing_exposure: str
65 account_codes: tuple[str, ...]
66
67
68 @dataclass(frozen=True)
69 class CoveragePreview:
70 company_code: str
71 fiscal_year: int
72 source_sha256: str
73 workbook_company_status: str
74 account_count: int
75 candidate_mapped_accounts: int
76 blocked_accounts: int
77 source_closing_exposure: str
78 candidate_closing_exposure: str
79 blocked_closing_exposure: str
80 notes: tuple[NoteExposure, ...]
81 accounts: tuple[AccountTrace, ...]
82 exceptions: tuple[CoverageException, ...]
83 kind: str = "UNAPPROVED_MAPPING_COVERAGE_PREVIEW"
84 financial_statement: bool = False
85 trusted_approvals: bool = False
86 releasable: bool = False
87
88 def to_dict(self) -> dict[str, Any]:
89 return asdict(self)
90
91
92 def _guard_archive(content: bytes) -> None:
93 try:
94 with ZipFile(BytesIO(content)) as archive:
95 members = archive.infolist()
96 if len(members) > MAX_ZIP_ENTRIES:
97 raise CoverageError("WORKBOOK_ARCHIVE_LIMIT")
98 expanded = 0
99 for member in members:
100 if member.file_size < 0 or member.file_size > MAX_EXPANDED_BYTES:
101 raise CoverageError("WORKBOOK_ARCHIVE_LIMIT")
102 expanded += member.file_size
103 if expanded > MAX_EXPANDED_BYTES:
104 raise CoverageError("WORKBOOK_ARCHIVE_LIMIT")
105 except (BadZipFile, ValueError, OSError) as exc:
106 if isinstance(exc, CoverageError):
107 raise
108 raise CoverageError("WORKBOOK_ARCHIVE_INVALID") from exc
109
110
111 def _read_rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
112 rows = []
113 for excel_row, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2):
114 row = dict(zip(headers, values))
115 if any(value is not None and str(value).strip() for value in row.values()):
116 rows.append((excel_row, row))
117 return rows
118
119
120 def _literal_code(value: Any) -> str:
121 if not isinstance(value, str) or not value.strip() or value.lstrip().startswith("="):
122 raise CoverageError("INVALID_ACCOUNT_OR_NOTE_CODE")
123 return value.strip()
124
125
126 def _closing_decimal(value: Any) -> Decimal:
127 if value is None or isinstance(value, bool):
128 raise CoverageError("INVALID_CLOSING")
129 try:
130 amount = Decimal(str(value).strip())
131 except (TypeError, ValueError, InvalidOperation) as exc:
132 raise CoverageError("INVALID_CLOSING") from exc
133 if not amount.is_finite() or (amount != 0 and abs(amount.adjusted()) > 70):
134 raise CoverageError("UNSUPPORTED_CLOSING_MAGNITUDE")
135 return amount
136
137
138 def _assert_visible(sheet: Any) -> None:
139 if sheet.sheet_state != "visible":
140 raise CoverageError("HIDDEN_INPUT")
141 if any(item.hidden for item in sheet.row_dimensions.values()):
142 raise CoverageError("HIDDEN_INPUT")
143 if any(item.hidden for item in sheet.column_dimensions.values()):
144 raise CoverageError("HIDDEN_INPUT")
145 if sheet.merged_cells.ranges:
146 raise CoverageError("MERGED_INPUT")
147
148
149 def preview_mapping_coverage(
150 content: bytes, *, company_code: str, fiscal_year: int
151 ) -> CoveragePreview:
152 """Inspect one explicit company/year in a structurally valid Pilot workbook.
153
154 Only unique mapping rows marked Approved+Valid *inside the untrusted file*
155 contribute to a CANDIDATE closing-exposure grouping. Ambiguous, missing
156 and non-approved mappings stay blocked. No financial statement is created.
157 """
158 if not isinstance(company_code, str) or not company_code.strip():
159 raise CoverageError("COMPANY_SCOPE_REQUIRED")
160 if type(fiscal_year) is not int or fiscal_year <= 0:
161 raise CoverageError("FISCAL_YEAR_SCOPE_REQUIRED")
162 if not isinstance(content, bytes) or not 0 < len(content) <= MAX_INPUT_BYTES:
163 raise CoverageError("WORKBOOK_SIZE_INVALID")
164 _guard_archive(content)
165
166 try:
167 preflight = preflight_pilot_workbook(content)
168 except Exception as exc:
169 raise CoverageError("WORKBOOK_INVALID") from exc
170 if not preflight.valid:
171 raise CoverageError("WORKBOOK_INVALID")
172
173 scope = (company_code.strip(), fiscal_year)
174
175 def scoped(row: dict[str, Any]) -> bool:
176 return (
177 isinstance(row.get("company_code"), str)
178 and row["company_code"].strip() == scope[0]
179 and type(row.get("fiscal_year")) is int
180 and row["fiscal_year"] == scope[1]
181 )
182
183 try:
184 book = load_workbook(BytesIO(content), read_only=False, data_only=False,
185 keep_links=False)
186 except Exception as exc:
187 raise CoverageError("WORKBOOK_INVALID") from exc
188
189 try:
190 # The read-only preview must not ignore concealed data in helper
191 # sheets or unexpected extra tabs, even when Pilot preflight does.
192 for sheet in book.worksheets:
193 _assert_visible(sheet)
194 for name, expected in SHEET_HEADERS.items():
195 if name not in book:
196 raise CoverageError("WORKBOOK_INVALID")
197 headers = tuple(cell.value for cell in book[name][1])
198 if headers != expected:
199 raise CoverageError("WORKBOOK_INVALID")
200
201 company_rows = [
202 row for _, row in _read_rows(book["Company"], SHEET_HEADERS["Company"])
203 if scoped(row)
204 ]
205 if len(company_rows) != 1:
206 raise CoverageError("COMPANY_SCOPE_NOT_FOUND")
207 status = str(company_rows[0]["status"])
208
209 accounts: dict[str, tuple[int, dict[str, Any], Decimal]] = {}
210 for excel_row, row in _read_rows(book["Accounts"], SHEET_HEADERS["Accounts"]):
211 if not scoped(row):
212 continue
213 code = _literal_code(row["account_full_code"])
214 if code in accounts:
215 raise CoverageError("DUPLICATE_ACCOUNT")
216 accounts[code] = (excel_row, row, _closing_decimal(row["closing"]))
217 if not accounts:
218 raise CoverageError("NO_ACCOUNTS_IN_SCOPE")
219
220 note_keys = {
221 (
222 str(row["statement"]).strip(),
223 str(row["statement_section"]).strip(),
224 _literal_code(row["note_number"]),
225 row["subnote_code"].strip() if isinstance(row["subnote_code"], str) else "",
226 )
227 for _, row in _read_rows(book["Notes"], SHEET_HEADERS["Notes"])
228 if scoped(row)
229 }
230
231 mappings: dict[str, list[tuple[int, dict[str, Any]]]] = defaultdict(list)
232 for excel_row, row in _read_rows(book["Mapping"], SHEET_HEADERS["Mapping"]):
233 if not scoped(row):
234 continue
235 code = _literal_code(row["account_full_code"])
236 if code not in accounts:
237 raise CoverageError("UNKNOWN_MAPPING_ACCOUNT")
238 mappings[code].append((excel_row, row))
239
240 exceptions: list[CoverageException] = []
241 traces: list[AccountTrace] = []
242 grouped: dict[tuple[str, str, str, str], list[tuple[str, Decimal]]] = defaultdict(list)
243 eligible: list[Decimal] = []
244 blocked: list[Decimal] = []
245 all_amounts: list[Decimal] = []
246
247 for code in sorted(accounts):
248 excel_row, source, closing = accounts[code]
249 all_amounts.append(closing)
250 matches = mappings.get(code, [])
251 candidate = False
252 target: tuple[str, str, str, str] | None = None
253 mapping_row: int | None = None
254 mapping_id: str | None = None
255 if not matches:
256 exceptions.append(CoverageException("UNMAPPED_ACCOUNT", code, excel_row, ()))
257 elif len(matches) != 1:
258 exceptions.append(CoverageException(
259 "AMBIGUOUS_ACCOUNT_MAPPING", code, excel_row,
260 tuple(number for number, _ in matches),
261 ))
262 else:
263 mapping_row, mapping = matches[0]
264 mapping_id = _literal_code(mapping["mapping_id"])
265 if (mapping["approval_status"] != "Approved"
266 or mapping["validation_status"] != "Valid"):
267 exceptions.append(CoverageException(
268 "MAPPING_NOT_FILE_MARKED_APPROVED", code, excel_row,
269 (mapping_row,),
270 ))
271 else:
272 target = (
273 str(mapping["target_statement"]).strip(),
274 str(mapping["statement_section"]).strip(),
275 _literal_code(mapping["note_number"]),
276 mapping["subnote_code"].strip()
277 if isinstance(mapping["subnote_code"], str) else "",
278 )
279 if target not in note_keys:
280 raise CoverageError("UNKNOWN_MAPPING_NOTE")
281 grouped[target].append((code, closing))
282 candidate = True
283 (eligible if candidate else blocked).append(closing)
284 traces.append(AccountTrace(
285 account_code=code, account_name=str(source["account_name"]),
286 account_excel_row=excel_row, source_row=int(source["source_row"]),
287 closing_exposure=str(closing), mapping_excel_row=mapping_row,
288 mapping_id=mapping_id,
289 target_statement=target[0] if target else None,
290 target_section=target[1] if target else None,
291 target_note=target[2] if target else None,
292 target_subnote=target[3] if target else None,
293 included=candidate,
294 ))
295
296 # Exact decimal aggregation, including mixed tiny and huge balances.
297 positive_digits = max((amount.adjusted() + 1 for amount in all_amounts if amount), default=1)
298 fractional_digits = max(0, *(-amount.as_tuple().exponent for amount in all_amounts))
299 precision = max(100, positive_digits + fractional_digits + len(str(len(all_amounts))) + 4)
300 with localcontext() as ctx:
301 ctx.prec = precision
302 source_total = sum(all_amounts, Decimal(0))
303 eligible_total = sum(eligible, Decimal(0))
304 blocked_total = sum(blocked, Decimal(0))
305 if source_total != eligible_total + blocked_total:
306 raise CoverageError("COVERAGE_RECONCILIATION_FAILED")
307 note_results = tuple(
308 NoteExposure(
309 statement=key[0], section=key[1],
310 note_number=key[2], subnote_code=key[3],
311 closing_exposure=str(sum(
312 (amount for _, amount in grouped[key]), Decimal(0)
313 )),
314 account_codes=tuple(code for code, _ in grouped[key]),
315 )
316 for key in sorted(grouped)
317 )
318
319 return CoveragePreview(
320 company_code=scope[0], fiscal_year=fiscal_year,
321 source_sha256=sha256(content).hexdigest(),
322 workbook_company_status=status, account_count=len(accounts),
323 candidate_mapped_accounts=len(eligible), blocked_accounts=len(blocked),
324 source_closing_exposure=str(source_total),
325 candidate_closing_exposure=str(eligible_total),
326 blocked_closing_exposure=str(blocked_total),
327 notes=note_results, accounts=tuple(traces),
328 exceptions=tuple(sorted(
329 exceptions, key=lambda entry: (entry.account_code, entry.code)
330 )),
331 )
332 finally:
333 book.close()