codex/aram-mapping-source-parser-20261101
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
| 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 | mapping_count: int |
| 52 | target_statement: str | None |
| 53 | target_section: str | None |
| 54 | target_note: str | None |
| 55 | target_subnote: str | None |
| 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 | |
| 74 | |
| 75 | @dataclass(frozen=True) |
| 76 | class NoteExposure: |
| 77 | statement: str |
| 78 | section: str |
| 79 | note_number: str |
| 80 | subnote_code: str |
| 81 | closing_exposure: str |
| 82 | account_codes: tuple[str, ...] |
| 83 | |
| 84 | |
| 85 | @dataclass(frozen=True) |
| 86 | class CoveragePreview: |
| 87 | company_code: str |
| 88 | fiscal_year: int |
| 89 | source_sha256: str |
| 90 | workbook_company_status: str |
| 91 | account_count: int |
| 92 | candidate_mapped_accounts: int |
| 93 | blocked_accounts: int |
| 94 | source_closing_exposure: str |
| 95 | candidate_closing_exposure: str |
| 96 | blocked_closing_exposure: str |
| 97 | notes: tuple[NoteExposure, ...] |
| 98 | accounts: tuple[AccountTrace, ...] |
| 99 | mappings: tuple[MappingTrace, ...] |
| 100 | exceptions: tuple[CoverageException, ...] |
| 101 | kind: str = "UNAPPROVED_MAPPING_COVERAGE_PREVIEW" |
| 102 | financial_statement: bool = False |
| 103 | trusted_approvals: bool = False |
| 104 | releasable: bool = False |
| 105 | |
| 106 | def to_dict(self) -> dict[str, Any]: |
| 107 | return asdict(self) |
| 108 | |
| 109 | |
| 110 | def _guard_archive(content: bytes) -> None: |
| 111 | try: |
| 112 | with ZipFile(BytesIO(content)) as archive: |
| 113 | members = archive.infolist() |
| 114 | if len(members) > MAX_ZIP_ENTRIES: |
| 115 | raise CoverageError("WORKBOOK_ARCHIVE_LIMIT") |
| 116 | expanded = 0 |
| 117 | for member in members: |
| 118 | if member.file_size < 0 or member.file_size > MAX_EXPANDED_BYTES: |
| 119 | raise CoverageError("WORKBOOK_ARCHIVE_LIMIT") |
| 120 | expanded += member.file_size |
| 121 | if expanded > MAX_EXPANDED_BYTES: |
| 122 | raise CoverageError("WORKBOOK_ARCHIVE_LIMIT") |
| 123 | except (BadZipFile, ValueError, OSError) as exc: |
| 124 | if isinstance(exc, CoverageError): |
| 125 | raise |
| 126 | raise CoverageError("WORKBOOK_ARCHIVE_INVALID") from exc |
| 127 | |
| 128 | |
| 129 | def _read_rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]: |
| 130 | rows = [] |
| 131 | for excel_row, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2): |
| 132 | row = dict(zip(headers, values)) |
| 133 | if any(value is not None and str(value).strip() for value in row.values()): |
| 134 | rows.append((excel_row, row)) |
| 135 | return rows |
| 136 | |
| 137 | |
| 138 | def _literal_code(value: Any) -> str: |
| 139 | if not isinstance(value, str) or not value.strip() or value.lstrip().startswith("="): |
| 140 | raise CoverageError("INVALID_ACCOUNT_OR_NOTE_CODE") |
| 141 | return value.strip() |
| 142 | |
| 143 | |
| 144 | def _closing_decimal(value: Any) -> Decimal: |
| 145 | if value is None or isinstance(value, bool): |
| 146 | raise CoverageError("INVALID_CLOSING") |
| 147 | try: |
| 148 | amount = Decimal(str(value).strip()) |
| 149 | except (TypeError, ValueError, InvalidOperation) as exc: |
| 150 | raise CoverageError("INVALID_CLOSING") from exc |
| 151 | if not amount.is_finite() or (amount != 0 and abs(amount.adjusted()) > 70): |
| 152 | raise CoverageError("UNSUPPORTED_CLOSING_MAGNITUDE") |
| 153 | return amount |
| 154 | |
| 155 | |
| 156 | def _assert_visible(sheet: Any) -> None: |
| 157 | if sheet.sheet_state != "visible": |
| 158 | raise CoverageError("HIDDEN_INPUT") |
| 159 | if any(item.hidden for item in sheet.row_dimensions.values()): |
| 160 | raise CoverageError("HIDDEN_INPUT") |
| 161 | if any(item.hidden for item in sheet.column_dimensions.values()): |
| 162 | raise CoverageError("HIDDEN_INPUT") |
| 163 | if sheet.merged_cells.ranges: |
| 164 | raise CoverageError("MERGED_INPUT") |
| 165 | |
| 166 | |
| 167 | def preview_mapping_coverage( |
| 168 | content: bytes, *, company_code: str, fiscal_year: int |
| 169 | ) -> CoveragePreview: |
| 170 | """Preview one source account against one mapping per target statement. |
| 171 | |
| 172 | One account may feed multiple distinct statements (for example BS and EQ), |
| 173 | but may not feed multiple notes within the same statement. Each target is |
| 174 | independently file-marked Approved+Valid; those flags remain untrusted. |
| 175 | Source totals count each account once, while note exposures are grouped by |
| 176 | every approved mapping. No financial statement or approval is created. |
| 177 | """ |
| 178 | if not isinstance(company_code, str) or not company_code.strip(): |
| 179 | raise CoverageError("COMPANY_SCOPE_REQUIRED") |
| 180 | if type(fiscal_year) is not int or fiscal_year <= 0: |
| 181 | raise CoverageError("FISCAL_YEAR_SCOPE_REQUIRED") |
| 182 | if not isinstance(content, bytes) or not 0 < len(content) <= MAX_INPUT_BYTES: |
| 183 | raise CoverageError("WORKBOOK_SIZE_INVALID") |
| 184 | _guard_archive(content) |
| 185 | |
| 186 | try: |
| 187 | preflight = preflight_pilot_workbook(content) |
| 188 | except Exception as exc: |
| 189 | raise CoverageError("WORKBOOK_INVALID") from exc |
| 190 | if not preflight.valid: |
| 191 | raise CoverageError("WORKBOOK_INVALID") |
| 192 | |
| 193 | scope = (company_code.strip(), fiscal_year) |
| 194 | |
| 195 | def scoped(row: dict[str, Any]) -> bool: |
| 196 | return ( |
| 197 | isinstance(row.get("company_code"), str) |
| 198 | and row["company_code"].strip() == scope[0] |
| 199 | and type(row.get("fiscal_year")) is int |
| 200 | and row["fiscal_year"] == scope[1] |
| 201 | ) |
| 202 | |
| 203 | try: |
| 204 | book = load_workbook( |
| 205 | BytesIO(content), read_only=False, data_only=False, keep_links=False, |
| 206 | ) |
| 207 | except Exception as exc: |
| 208 | raise CoverageError("WORKBOOK_INVALID") from exc |
| 209 | |
| 210 | try: |
| 211 | for sheet in book.worksheets: |
| 212 | _assert_visible(sheet) |
| 213 | for name, expected in SHEET_HEADERS.items(): |
| 214 | if name not in book: |
| 215 | raise CoverageError("WORKBOOK_INVALID") |
| 216 | if tuple(cell.value for cell in book[name][1]) != expected: |
| 217 | raise CoverageError("WORKBOOK_INVALID") |
| 218 | |
| 219 | company_rows = [ |
| 220 | row for _, row in _read_rows(book["Company"], SHEET_HEADERS["Company"]) |
| 221 | if scoped(row) |
| 222 | ] |
| 223 | if len(company_rows) != 1: |
| 224 | raise CoverageError("COMPANY_SCOPE_NOT_FOUND") |
| 225 | status = str(company_rows[0]["status"]) |
| 226 | |
| 227 | accounts: dict[str, tuple[int, dict[str, Any], Decimal]] = {} |
| 228 | for excel_row, row in _read_rows(book["Accounts"], SHEET_HEADERS["Accounts"]): |
| 229 | if not scoped(row): |
| 230 | continue |
| 231 | code = _literal_code(row["account_full_code"]) |
| 232 | if code in accounts: |
| 233 | raise CoverageError("DUPLICATE_ACCOUNT") |
| 234 | accounts[code] = (excel_row, row, _closing_decimal(row["closing"])) |
| 235 | if not accounts: |
| 236 | raise CoverageError("NO_ACCOUNTS_IN_SCOPE") |
| 237 | |
| 238 | note_keys = { |
| 239 | ( |
| 240 | str(row["statement"]).strip(), |
| 241 | str(row["statement_section"]).strip(), |
| 242 | _literal_code(row["note_number"]), |
| 243 | row["subnote_code"].strip() if isinstance(row["subnote_code"], str) else "", |
| 244 | ) |
| 245 | for _, row in _read_rows(book["Notes"], SHEET_HEADERS["Notes"]) |
| 246 | if scoped(row) |
| 247 | } |
| 248 | |
| 249 | mappings_by_account: dict[str, list[tuple[int, dict[str, Any]]]] = defaultdict(list) |
| 250 | for excel_row, row in _read_rows(book["Mapping"], SHEET_HEADERS["Mapping"]): |
| 251 | if not scoped(row): |
| 252 | continue |
| 253 | code = _literal_code(row["account_full_code"]) |
| 254 | if code not in accounts: |
| 255 | raise CoverageError("UNKNOWN_MAPPING_ACCOUNT") |
| 256 | mappings_by_account[code].append((excel_row, row)) |
| 257 | |
| 258 | exceptions: list[CoverageException] = [] |
| 259 | account_traces: list[AccountTrace] = [] |
| 260 | mapping_traces: list[MappingTrace] = [] |
| 261 | grouped: dict[tuple[str, str, str, str], list[tuple[str, Decimal]]] = defaultdict(list) |
| 262 | eligible_amounts: list[Decimal] = [] |
| 263 | blocked_amounts: list[Decimal] = [] |
| 264 | all_amounts: list[Decimal] = [] |
| 265 | |
| 266 | for code in sorted(accounts): |
| 267 | excel_row, source, closing = accounts[code] |
| 268 | all_amounts.append(closing) |
| 269 | matches = mappings_by_account.get(code, []) |
| 270 | parsed: list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]] = [] |
| 271 | by_statement: dict[str, list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]]] = defaultdict(list) |
| 272 | |
| 273 | for mapping_row, mapping in matches: |
| 274 | mapping_id = _literal_code(mapping["mapping_id"]) |
| 275 | target = ( |
| 276 | str(mapping["target_statement"]).strip(), |
| 277 | str(mapping["statement_section"]).strip(), |
| 278 | _literal_code(mapping["note_number"]), |
| 279 | mapping["subnote_code"].strip() |
| 280 | if isinstance(mapping["subnote_code"], str) else "", |
| 281 | ) |
| 282 | if target not in note_keys: |
| 283 | raise CoverageError("UNKNOWN_MAPPING_NOTE") |
| 284 | item = (mapping_row, mapping_id, target, mapping) |
| 285 | parsed.append(item) |
| 286 | by_statement[target[0]].append(item) |
| 287 | |
| 288 | included_rows: list[tuple[int, str, tuple[str, str, str, str], dict[str, Any]]] = [] |
| 289 | if not matches: |
| 290 | exceptions.append(CoverageException("UNMAPPED_ACCOUNT", code, excel_row, ())) |
| 291 | else: |
| 292 | for statement in sorted(by_statement): |
| 293 | statement_rows = by_statement[statement] |
| 294 | if len(statement_rows) > 1: |
| 295 | exceptions.append(CoverageException( |
| 296 | "AMBIGUOUS_ACCOUNT_MAPPING", code, excel_row, |
| 297 | tuple(sorted(item[0] for item in statement_rows)), |
| 298 | )) |
| 299 | continue |
| 300 | mapping_row, mapping_id, target, mapping = statement_rows[0] |
| 301 | if (mapping["approval_status"] != "Approved" |
| 302 | or mapping["validation_status"] != "Valid"): |
| 303 | exceptions.append(CoverageException( |
| 304 | "MAPPING_NOT_FILE_MARKED_APPROVED", code, excel_row, |
| 305 | (mapping_row,), |
| 306 | )) |
| 307 | continue |
| 308 | included_rows.append((mapping_row, mapping_id, target, mapping)) |
| 309 | grouped[target].append((code, closing)) |
| 310 | |
| 311 | candidate = bool(included_rows) |
| 312 | if candidate: |
| 313 | eligible_amounts.append(closing) |
| 314 | else: |
| 315 | blocked_amounts.append(closing) |
| 316 | |
| 317 | for mapping_row, mapping_id, target, mapping in parsed: |
| 318 | mapping_traces.append(MappingTrace( |
| 319 | account_code=code, account_name=str(source["account_name"]), |
| 320 | account_excel_row=excel_row, source_row=int(source["source_row"]), |
| 321 | closing_exposure=str(closing), mapping_excel_row=mapping_row, |
| 322 | mapping_id=mapping_id, target_statement=target[0], |
| 323 | target_section=target[1], target_note=target[2], |
| 324 | target_subnote=target[3], |
| 325 | included=any(row[0] == mapping_row for row in included_rows), |
| 326 | )) |
| 327 | |
| 328 | single = parsed[0] if len(parsed) == 1 else None |
| 329 | single_included = bool(single and any(row[0] == single[0] for row in included_rows)) |
| 330 | account_traces.append(AccountTrace( |
| 331 | account_code=code, account_name=str(source["account_name"]), |
| 332 | account_excel_row=excel_row, source_row=int(source["source_row"]), |
| 333 | closing_exposure=str(closing), |
| 334 | mapping_excel_row=single[0] if single else None, |
| 335 | mapping_id=single[1] if single else None, |
| 336 | mapping_count=len(matches), |
| 337 | target_statement=single[2][0] if single and single_included else None, |
| 338 | target_section=single[2][1] if single and single_included else None, |
| 339 | target_note=single[2][2] if single and single_included else None, |
| 340 | target_subnote=single[2][3] if single and single_included else None, |
| 341 | included=candidate, |
| 342 | )) |
| 343 | |
| 344 | positive_digits = max( |
| 345 | (amount.adjusted() + 1 for amount in all_amounts if amount), |
| 346 | default=1, |
| 347 | ) |
| 348 | fractional_digits = max(0, *(-amount.as_tuple().exponent for amount in all_amounts)) |
| 349 | precision = max( |
| 350 | 100, positive_digits + fractional_digits + len(str(len(all_amounts))) + 4, |
| 351 | ) |
| 352 | with localcontext() as ctx: |
| 353 | ctx.prec = precision |
| 354 | source_total = sum(all_amounts, Decimal(0)) |
| 355 | eligible_total = sum(eligible_amounts, Decimal(0)) |
| 356 | blocked_total = sum(blocked_amounts, Decimal(0)) |
| 357 | if source_total != eligible_total + blocked_total: |
| 358 | raise CoverageError("COVERAGE_RECONCILIATION_FAILED") |
| 359 | note_results = tuple( |
| 360 | NoteExposure( |
| 361 | statement=key[0], section=key[1], |
| 362 | note_number=key[2], subnote_code=key[3], |
| 363 | closing_exposure=str(sum( |
| 364 | (amount for _, amount in grouped[key]), Decimal(0), |
| 365 | )), |
| 366 | account_codes=tuple(code for code, _ in grouped[key]), |
| 367 | ) |
| 368 | for key in sorted(grouped) |
| 369 | ) |
| 370 | |
| 371 | return CoveragePreview( |
| 372 | company_code=scope[0], fiscal_year=fiscal_year, |
| 373 | source_sha256=sha256(content).hexdigest(), |
| 374 | workbook_company_status=status, account_count=len(accounts), |
| 375 | candidate_mapped_accounts=len(eligible_amounts), |
| 376 | blocked_accounts=len(blocked_amounts), |
| 377 | source_closing_exposure=str(source_total), |
| 378 | candidate_closing_exposure=str(eligible_total), |
| 379 | blocked_closing_exposure=str(blocked_total), |
| 380 | notes=note_results, accounts=tuple(account_traces), |
| 381 | mappings=tuple(sorted( |
| 382 | mapping_traces, |
| 383 | key=lambda item: (item.account_code, item.mapping_excel_row), |
| 384 | )), |
| 385 | exceptions=tuple(sorted( |
| 386 | exceptions, key=lambda entry: ( |
| 387 | entry.account_code, entry.code, entry.mapping_excel_rows, |
| 388 | ), |
| 389 | )), |
| 390 | ) |
| 391 | finally: |
| 392 | book.close() |