@davoodmehraban89 / Aram-1 / commits / f5fdfb1
Fork 0

feat(mapping): support one account mapping per distinct statement with explicit traces

davoodmehraban89 committed Oct 31, 2026 at 08:46 UTC f5fdfb1b3d8be16d3ee2906524ac7d25400a3a4a
1 file changed +137 -61
backend/src/aram_backend/coverage_preview.py
+137 -61
@@ -48,6 +48,7 @@ class AccountTrace:
48 closing_exposure: str
49 mapping_excel_row: int | None
50 mapping_id: str | None
51 + mapping_count: int
52 target_statement: str | None
53 target_section: str | None
54 target_note: str | None
@@ -55,6 +56,39 @@ class AccountTrace:
56 included: bool
57
58
59 +@dataclass(frozen=True)
60 +class MappingTrace:
61 + account_code: str
62 + account_name: str
63 + account_excel_row: int
64 + source_row: int
65 + closing_exposure: str
66 + mapping_excel_row: int
67 + mapping_id: str
68 + target_statement: str
69 + target_section: str
70 + target_note: str
71 + target_subnote: str
72 + included: bool
73 + mapping_count: int
74 +
75 +
76 +@dataclass(frozen=True)
77 +class MappingTrace:
78 + account_code: str
79 + account_name: str
80 + account_excel_row: int
81 + source_row: int
82 + closing_exposure: str
83 + mapping_excel_row: int
84 + mapping_id: str
85 + target_statement: str
86 + target_section: str
87 + target_note: str
88 + target_subnote: str
89 + included: bool
90 +
91 +
92 @dataclass(frozen=True)
93 class NoteExposure:
94 statement: str
@@ -79,6 +113,7 @@ class CoveragePreview:
113 blocked_closing_exposure: str
114 notes: tuple[NoteExposure, ...]
115 accounts: tuple[AccountTrace, ...]
116 + mappings: tuple[MappingTrace, ...]
117 exceptions: tuple[CoverageException, ...]
118 kind: str = "UNAPPROVED_MAPPING_COVERAGE_PREVIEW"
119 financial_statement: bool = False
@@ -149,11 +184,13 @@ def _assert_visible(sheet: Any) -> None:
184 def preview_mapping_coverage(
185 content: bytes, *, company_code: str, fiscal_year: int
186 ) -> CoveragePreview:
152 - """Inspect one explicit company/year in a structurally valid Pilot workbook.
187 + """Preview one source account against one mapping per target statement.
188
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.
189 + One account may feed multiple distinct statements (for example BS and EQ),
190 + but may not feed multiple notes within the same statement. Each target is
191 + independently file-marked Approved+Valid; those flags remain untrusted.
192 + Source totals count each account once, while note exposures are grouped by
193 + every approved mapping. No financial statement or approval is created.
194 """
195 if not isinstance(company_code, str) or not company_code.strip():
196 raise CoverageError("COMPANY_SCOPE_REQUIRED")
@@ -181,21 +218,19 @@ def preview_mapping_coverage(
218 )
219
220 try:
184 - book = load_workbook(BytesIO(content), read_only=False, data_only=False,
185 - keep_links=False)
221 + book = load_workbook(
222 + BytesIO(content), read_only=False, data_only=False, keep_links=False,
223 + )
224 except Exception as exc:
225 raise CoverageError("WORKBOOK_INVALID") from exc
226
227 try:
190 - # The read-only preview must not ignore concealed data in helper
191 - # sheets or unexpected extra tabs, even when Pilot preflight does.
228 for sheet in book.worksheets:
229 _assert_visible(sheet)
230 for name, expected in SHEET_HEADERS.items():
231 if name not in book:
232 raise CoverageError("WORKBOOK_INVALID")
197 - headers = tuple(cell.value for cell in book[name][1])
198 - if headers != expected:
233 + if tuple(cell.value for cell in book[name][1]) != expected:
234 raise CoverageError("WORKBOOK_INVALID")
235
236 company_rows = [
@@ -228,80 +263,114 @@ def preview_mapping_coverage(
263 if scoped(row)
264 }
265
231 - mappings: dict[str, list[tuple[int, dict[str, Any]]]] = defaultdict(list)
266 + mappings_by_account: dict[str, list[tuple[int, dict[str, Any]]]] = defaultdict(list)
267 for excel_row, row in _read_rows(book["Mapping"], SHEET_HEADERS["Mapping"]):
268 if not scoped(row):
269 continue
270 code = _literal_code(row["account_full_code"])
271 if code not in accounts:
272 raise CoverageError("UNKNOWN_MAPPING_ACCOUNT")
238 - mappings[code].append((excel_row, row))
273 + mappings_by_account[code].append((excel_row, row))
274
275 exceptions: list[CoverageException] = []
241 - traces: list[AccountTrace] = []
276 + account_traces: list[AccountTrace] = []
277 + mapping_traces: list[MappingTrace] = []
278 grouped: dict[tuple[str, str, str, str], list[tuple[str, Decimal]]] = defaultdict(list)
243 - eligible: list[Decimal] = []
244 - blocked: list[Decimal] = []
279 + eligible_amounts: list[Decimal] = []
280 + blocked_amounts: list[Decimal] = []
281 all_amounts: list[Decimal] = []
282
283 for code in sorted(accounts):
284 excel_row, source, closing = accounts[code]
285 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
286 + matches = mappings_by_account.get(code, [])
287 + parsed: list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]] = []
288 + by_statement: dict[str, list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]]] = defaultdict(list)
289 +
290 + for mapping_row, mapping in matches:
291 + mapping_id = _literal_code(mapping["mapping_id"])
292 + target = (
293 + str(mapping["target_statement"]).strip(),
294 + str(mapping["statement_section"]).strip(),
295 + _literal_code(mapping["note_number"]),
296 + mapping["subnote_code"].strip()
297 + if isinstance(mapping["subnote_code"], str) else "",
298 + )
299 + if target not in note_keys:
300 + raise CoverageError("UNKNOWN_MAPPING_NOTE")
301 + item = (mapping_row, mapping_id, target, mapping)
302 + parsed.append(item)
303 + by_statement[target[0]].append(item)
304 +
305 + included_rows: list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]] = []
306 if not matches:
307 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 - ))
308 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")
309 + for statement in sorted(by_statement):
310 + statement_rows = by_statement[statement]
311 + if len(statement_rows) > 1:
312 + exceptions.append(CoverageException(
313 + "AMBIGUOUS_ACCOUNT_MAPPING", code, excel_row,
314 + tuple(sorted(item[0] for item in statement_rows)),
315 + ))
316 + continue
317 + mapping_row, mapping_id, target, mapping = statement_rows[0]
318 + if (mapping["approval_status"] != "Approved"
319 + or mapping["validation_status"] != "Valid"):
320 + exceptions.append(CoverageException(
321 + "MAPPING_NOT_FILE_MARKED_APPROVED", code, excel_row,
322 + (mapping_row,),
323 + ))
324 + continue
325 + included_rows.append((mapping_row, mapping_id, target, mapping))
326 grouped[target].append((code, closing))
282 - candidate = True
283 - (eligible if candidate else blocked).append(closing)
284 - traces.append(AccountTrace(
327 +
328 + candidate = bool(included_rows)
329 + if candidate:
330 + eligible_amounts.append(closing)
331 + else:
332 + blocked_amounts.append(closing)
333 +
334 + for mapping_row, mapping_id, target, mapping in parsed:
335 + mapping_traces.append(MappingTrace(
336 + account_code=code, account_name=str(source["account_name"]),
337 + account_excel_row=excel_row, source_row=int(source["source_row"]),
338 + closing_exposure=str(closing), mapping_excel_row=mapping_row,
339 + mapping_id=mapping_id, target_statement=target[0],
340 + target_section=target[1], target_note=target[2],
341 + target_subnote=target[3],
342 + included=any(row[0] == mapping_row for row in included_rows),
343 + ))
344 +
345 + single = parsed[0] if len(parsed) == 1 else None
346 + single_included = bool(single and any(row[0] == single[0] for row in included_rows))
347 + account_traces.append(AccountTrace(
348 account_code=code, account_name=str(source["account_name"]),
349 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,
350 + closing_exposure=str(closing),
351 + mapping_excel_row=single[0] if single else None,
352 + mapping_id=single[1] if single else None,
353 + mapping_count=len(matches),
354 + target_statement=single[2][0] if single and single_included else None,
355 + target_section=single[2][1] if single and single_included else None,
356 + target_note=single[2][2] if single and single_included else None,
357 + target_subnote=single[2][3] if single and single_included else None,
358 included=candidate,
359 ))
360
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)
361 + positive_digits = max(
362 + (amount.adjusted() + 1 for amount in all_amounts if amount),
363 + default=1,
364 + )
365 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)
366 + precision = max(
367 + 100, positive_digits + fractional_digits + len(str(len(all_amounts))) + 4,
368 + )
369 with localcontext() as ctx:
370 ctx.prec = precision
371 source_total = sum(all_amounts, Decimal(0))
303 - eligible_total = sum(eligible, Decimal(0))
304 - blocked_total = sum(blocked, Decimal(0))
372 + eligible_total = sum(eligible_amounts, Decimal(0))
373 + blocked_total = sum(blocked_amounts, Decimal(0))
374 if source_total != eligible_total + blocked_total:
375 raise CoverageError("COVERAGE_RECONCILIATION_FAILED")
376 note_results = tuple(
@@ -309,7 +378,7 @@ def preview_mapping_coverage(
378 statement=key[0], section=key[1],
379 note_number=key[2], subnote_code=key[3],
380 closing_exposure=str(sum(
312 - (amount for _, amount in grouped[key]), Decimal(0)
381 + (amount for _, amount in grouped[key]), Decimal(0),
382 )),
383 account_codes=tuple(code for code, _ in grouped[key]),
384 )
@@ -320,13 +389,20 @@ def preview_mapping_coverage(
389 company_code=scope[0], fiscal_year=fiscal_year,
390 source_sha256=sha256(content).hexdigest(),
391 workbook_company_status=status, account_count=len(accounts),
323 - candidate_mapped_accounts=len(eligible), blocked_accounts=len(blocked),
392 + candidate_mapped_accounts=len(eligible_amounts),
393 + blocked_accounts=len(blocked_amounts),
394 source_closing_exposure=str(source_total),
395 candidate_closing_exposure=str(eligible_total),
396 blocked_closing_exposure=str(blocked_total),
327 - notes=note_results, accounts=tuple(traces),
397 + notes=note_results, accounts=tuple(account_traces),
398 + mappings=tuple(sorted(
399 + mapping_traces,
400 + key=lambda item: (item.account_code, item.mapping_excel_row),
401 + )),
402 exceptions=tuple(sorted(
329 - exceptions, key=lambda entry: (entry.account_code, entry.code)
403 + exceptions, key=lambda entry: (
404 + entry.account_code, entry.code, entry.mapping_excel_rows,
405 + ),
406 )),
407 )
408 finally: