Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 18:15 UTC
feat(coverage): add fail-closed read-only mapping exposure preview
davoodmehraban89 committed
Oct 31, 2026 at 00:16 UTC
1b993a2557537fa2f4c57e9e83251c1daf5c7584
1 file changed
+331
backend/src/aram_backend/coverage_preview.py
new
+331
@@ -0,0 +1,331 @@
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
+ for name in ("Company", "Accounts", "Notes", "Mapping"):
191
+ if name not in book:
192
+ raise CoverageError("WORKBOOK_INVALID")
193
+ sheet = book[name]
194
+ _assert_visible(sheet)
195
+ headers = tuple(cell.value for cell in sheet[1])
196
+ if headers != SHEET_HEADERS[name]:
197
+ raise CoverageError("WORKBOOK_INVALID")
198
+
199
+ company_rows = [
200
+ row for _, row in _read_rows(book["Company"], SHEET_HEADERS["Company"])
201
+ if scoped(row)
202
+ ]
203
+ if len(company_rows) != 1:
204
+ raise CoverageError("COMPANY_SCOPE_NOT_FOUND")
205
+ status = str(company_rows[0]["status"])
206
+
207
+ accounts: dict[str, tuple[int, dict[str, Any], Decimal]] = {}
208
+ for excel_row, row in _read_rows(book["Accounts"], SHEET_HEADERS["Accounts"]):
209
+ if not scoped(row):
210
+ continue
211
+ code = _literal_code(row["account_full_code"])
212
+ if code in accounts:
213
+ raise CoverageError("DUPLICATE_ACCOUNT")
214
+ accounts[code] = (excel_row, row, _closing_decimal(row["closing"]))
215
+ if not accounts:
216
+ raise CoverageError("NO_ACCOUNTS_IN_SCOPE")
217
+
218
+ note_keys = {
219
+ (
220
+ str(row["statement"]).strip(),
221
+ str(row["statement_section"]).strip(),
222
+ _literal_code(row["note_number"]),
223
+ row["subnote_code"].strip() if isinstance(row["subnote_code"], str) else "",
224
+ )
225
+ for _, row in _read_rows(book["Notes"], SHEET_HEADERS["Notes"])
226
+ if scoped(row)
227
+ }
228
+
229
+ mappings: dict[str, list[tuple[int, dict[str, Any]]]] = defaultdict(list)
230
+ for excel_row, row in _read_rows(book["Mapping"], SHEET_HEADERS["Mapping"]):
231
+ if not scoped(row):
232
+ continue
233
+ code = _literal_code(row["account_full_code"])
234
+ if code not in accounts:
235
+ raise CoverageError("UNKNOWN_MAPPING_ACCOUNT")
236
+ mappings[code].append((excel_row, row))
237
+
238
+ exceptions: list[CoverageException] = []
239
+ traces: list[AccountTrace] = []
240
+ grouped: dict[tuple[str, str, str, str], list[tuple[str, Decimal]]] = defaultdict(list)
241
+ eligible: list[Decimal] = []
242
+ blocked: list[Decimal] = []
243
+ all_amounts: list[Decimal] = []
244
+
245
+ for code in sorted(accounts):
246
+ excel_row, source, closing = accounts[code]
247
+ all_amounts.append(closing)
248
+ matches = mappings.get(code, [])
249
+ candidate = False
250
+ target: tuple[str, str, str, str] | None = None
251
+ mapping_row: int | None = None
252
+ mapping_id: str | None = None
253
+ if not matches:
254
+ exceptions.append(CoverageException("UNMAPPED_ACCOUNT", code, excel_row, ()))
255
+ elif len(matches) != 1:
256
+ exceptions.append(CoverageException(
257
+ "AMBIGUOUS_ACCOUNT_MAPPING", code, excel_row,
258
+ tuple(number for number, _ in matches),
259
+ ))
260
+ else:
261
+ mapping_row, mapping = matches[0]
262
+ mapping_id = _literal_code(mapping["mapping_id"])
263
+ if (mapping["approval_status"] != "Approved"
264
+ or mapping["validation_status"] != "Valid"):
265
+ exceptions.append(CoverageException(
266
+ "MAPPING_NOT_FILE_MARKED_APPROVED", code, excel_row,
267
+ (mapping_row,),
268
+ ))
269
+ else:
270
+ target = (
271
+ str(mapping["target_statement"]).strip(),
272
+ str(mapping["statement_section"]).strip(),
273
+ _literal_code(mapping["note_number"]),
274
+ mapping["subnote_code"].strip()
275
+ if isinstance(mapping["subnote_code"], str) else "",
276
+ )
277
+ if target not in note_keys:
278
+ raise CoverageError("UNKNOWN_MAPPING_NOTE")
279
+ grouped[target].append((code, closing))
280
+ candidate = True
281
+ (eligible if candidate else blocked).append(closing)
282
+ traces.append(AccountTrace(
283
+ account_code=code, account_name=str(source["account_name"]),
284
+ account_excel_row=excel_row, source_row=int(source["source_row"]),
285
+ closing_exposure=str(closing), mapping_excel_row=mapping_row,
286
+ mapping_id=mapping_id,
287
+ target_statement=target[0] if target else None,
288
+ target_section=target[1] if target else None,
289
+ target_note=target[2] if target else None,
290
+ target_subnote=target[3] if target else None,
291
+ included=candidate,
292
+ ))
293
+
294
+ # Exact decimal aggregation, including mixed tiny and huge balances.
295
+ positive_digits = max(1, *(amount.adjusted() + 1 for amount in all_amounts if amount))
296
+ fractional_digits = max(0, *(-amount.as_tuple().exponent for amount in all_amounts))
297
+ precision = max(100, positive_digits + fractional_digits + len(str(len(all_amounts))) + 4)
298
+ with localcontext() as ctx:
299
+ ctx.prec = precision
300
+ source_total = sum(all_amounts, Decimal(0))
301
+ eligible_total = sum(eligible, Decimal(0))
302
+ blocked_total = sum(blocked, Decimal(0))
303
+ if source_total != eligible_total + blocked_total:
304
+ raise CoverageError("COVERAGE_RECONCILIATION_FAILED")
305
+ note_results = tuple(
306
+ NoteExposure(
307
+ statement=key[0], section=key[1],
308
+ note_number=key[2], subnote_code=key[3],
309
+ closing_exposure=str(sum(
310
+ (amount for _, amount in grouped[key]), Decimal(0)
311
+ )),
312
+ account_codes=tuple(code for code, _ in grouped[key]),
313
+ )
314
+ for key in sorted(grouped)
315
+ )
316
+
317
+ return CoveragePreview(
318
+ company_code=scope[0], fiscal_year=fiscal_year,
319
+ source_sha256=sha256(content).hexdigest(),
320
+ workbook_company_status=status, account_count=len(accounts),
321
+ candidate_mapped_accounts=len(eligible), blocked_accounts=len(blocked),
322
+ source_closing_exposure=str(source_total),
323
+ candidate_closing_exposure=str(eligible_total),
324
+ blocked_closing_exposure=str(blocked_total),
325
+ notes=note_results, accounts=tuple(traces),
326
+ exceptions=tuple(sorted(
327
+ exceptions, key=lambda entry: (entry.account_code, entry.code)
328
+ )),
329
+ )
330
+ finally:
331
+ book.close()