codex/post-gate2a-control-reconciliation
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 | from __future__ import annotations |
| 2 | |
| 3 | from collections import Counter |
| 4 | from dataclasses import dataclass |
| 5 | from decimal import Decimal, InvalidOperation |
| 6 | from io import BytesIO |
| 7 | from typing import Any |
| 8 | from zipfile import BadZipFile |
| 9 | |
| 10 | from openpyxl import load_workbook |
| 11 | from openpyxl.utils.exceptions import InvalidFileException |
| 12 | |
| 13 | |
| 14 | SHEET_HEADERS: dict[str, tuple[str, ...]] = { |
| 15 | "Company": ( |
| 16 | "company_code", "company_name", "fiscal_year", "currency", "unit", |
| 17 | "prepared_by", "status", |
| 18 | ), |
| 19 | "Accounts": ( |
| 20 | "company_code", "fiscal_year", "general_code", "general_name", |
| 21 | "subsidiary_code", "subsidiary_name", "detail1_code", "detail1_name", |
| 22 | "detail2_code", "detail2_name", "detail3_code", "detail3_name", |
| 23 | "detail4_code", "detail4_name", "account_full_code", "account_name", |
| 24 | "opening", "debit", "credit", "closing", "source_row", "row_status", |
| 25 | "closing_delta", |
| 26 | ), |
| 27 | "Notes": ( |
| 28 | "company_code", "fiscal_year", "statement", "statement_section", |
| 29 | "note_number", "note_title", "subnote_code", "subnote_title", |
| 30 | ), |
| 31 | "Mapping": ( |
| 32 | "mapping_id", "company_code", "fiscal_year", "account_full_code", |
| 33 | "account_level", "general_code", "subsidiary_code", "detail1_code", |
| 34 | "detail2_code", "detail3_code", "detail4_code", "target_statement", |
| 35 | "statement_section", "note_number", "subnote_code", "mapping_version", |
| 36 | "approval_status", "reviewer", "review_date", "source", "notes", |
| 37 | "validation_status", |
| 38 | ), |
| 39 | "Test_Log": ( |
| 40 | "tester", "feature", "expected_result", "actual_result", "status", |
| 41 | "severity", "evidence", "notes", |
| 42 | ), |
| 43 | "Checks": ("check_code", "check_name", "status", "affected_rows", "details"), |
| 44 | "Guide_FA": ("section", "instruction"), |
| 45 | "Lists": ("list_name", "value"), |
| 46 | } |
| 47 | |
| 48 | _SHEET_ORDER = {name: position for position, name in enumerate(SHEET_HEADERS)} |
| 49 | _CODE_FIELDS = { |
| 50 | "company_code", "general_code", "subsidiary_code", "detail1_code", |
| 51 | "detail2_code", "detail3_code", "detail4_code", "account_full_code", |
| 52 | "note_number", "subnote_code", "mapping_id", |
| 53 | } |
| 54 | _REQUIRED: dict[str, set[str]] = { |
| 55 | "Company": {"company_code", "company_name", "fiscal_year", "status"}, |
| 56 | "Accounts": { |
| 57 | "company_code", "fiscal_year", "general_code", "general_name", |
| 58 | "account_full_code", "account_name", "opening", "debit", "credit", |
| 59 | "closing", "source_row", "row_status", |
| 60 | }, |
| 61 | "Notes": {"company_code", "fiscal_year", "statement", "note_number", "note_title"}, |
| 62 | "Mapping": { |
| 63 | "mapping_id", "company_code", "fiscal_year", "account_full_code", |
| 64 | "account_level", "mapping_version", "approval_status", |
| 65 | }, |
| 66 | } |
| 67 | |
| 68 | |
| 69 | @dataclass(frozen=True) |
| 70 | class PilotIssue: |
| 71 | severity: str |
| 72 | code: str |
| 73 | sheet: str |
| 74 | row: int |
| 75 | field: str |
| 76 | message: str |
| 77 | |
| 78 | |
| 79 | @dataclass(frozen=True) |
| 80 | class PilotPreflightResult: |
| 81 | valid: bool |
| 82 | issues: tuple[PilotIssue, ...] |
| 83 | issue_counts: dict[str, int] |
| 84 | |
| 85 | |
| 86 | def _empty(value: Any) -> bool: |
| 87 | return value is None or (isinstance(value, str) and not value.strip()) |
| 88 | |
| 89 | |
| 90 | def _issue(issues: list[PilotIssue], code: str, sheet: str, row: int, |
| 91 | field: str, message: str, severity: str = "ERROR") -> None: |
| 92 | issues.append(PilotIssue(severity, code, sheet, row, field, message)) |
| 93 | |
| 94 | |
| 95 | def _text_code(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 96 | field: str) -> str | None: |
| 97 | if _empty(value): |
| 98 | return None |
| 99 | if not isinstance(value, str): |
| 100 | _issue(issues, "CODE_NOT_TEXT", sheet, row, field, |
| 101 | "Code cells must use Excel text format; numeric coercion is forbidden.") |
| 102 | return None |
| 103 | return value.strip() |
| 104 | |
| 105 | |
| 106 | def _positive_int(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 107 | field: str) -> int | None: |
| 108 | if _empty(value): |
| 109 | return None |
| 110 | if isinstance(value, bool) or not isinstance(value, int) or value <= 0: |
| 111 | _issue(issues, "INVALID_POSITIVE_INTEGER", sheet, row, field, |
| 112 | "Value must be a positive integer.") |
| 113 | return None |
| 114 | return value |
| 115 | |
| 116 | |
| 117 | def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 118 | field: str) -> Decimal | None: |
| 119 | if _empty(value): |
| 120 | return None |
| 121 | if isinstance(value, bool) or isinstance(value, str) and value.startswith("="): |
| 122 | _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field, |
| 123 | "Financial values must be finite numbers, not booleans or formulas.") |
| 124 | return None |
| 125 | try: |
| 126 | parsed = Decimal(str(value).strip()) |
| 127 | except (InvalidOperation, ValueError): |
| 128 | _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field, |
| 129 | "Financial value is not a valid decimal number.") |
| 130 | return None |
| 131 | if not parsed.is_finite(): |
| 132 | _issue(issues, "NON_FINITE_FINANCIAL_VALUE", sheet, row, field, |
| 133 | "NaN and Infinity are not permitted.") |
| 134 | return None |
| 135 | return parsed |
| 136 | |
| 137 | |
| 138 | def _rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]: |
| 139 | result: list[tuple[int, dict[str, Any]]] = [] |
| 140 | for row_number, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2): |
| 141 | row = dict(zip(headers, values)) |
| 142 | if any(not _empty(value) for value in row.values()): |
| 143 | result.append((row_number, row)) |
| 144 | return result |
| 145 | |
| 146 | |
| 147 | def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult: |
| 148 | """Validate a Pilot workbook fully in memory without persistence or mutation.""" |
| 149 | issues: list[PilotIssue] = [] |
| 150 | try: |
| 151 | workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=False) |
| 152 | except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError) as exc: |
| 153 | issue = PilotIssue("ERROR", "INVALID_WORKBOOK", "__workbook__", 0, "__file__", str(exc)) |
| 154 | return PilotPreflightResult(False, (issue,), {"ERROR": 1}) |
| 155 | |
| 156 | valid_sheets: set[str] = set() |
| 157 | for sheet_name, expected in SHEET_HEADERS.items(): |
| 158 | if sheet_name not in workbook.sheetnames: |
| 159 | _issue(issues, "MISSING_SHEET", sheet_name, 1, "__sheet__", |
| 160 | f"Required sheet {sheet_name!r} is missing.") |
| 161 | continue |
| 162 | actual = tuple(cell.value for cell in workbook[sheet_name][1]) |
| 163 | if actual != expected: |
| 164 | _issue(issues, "HEADER_MISMATCH", sheet_name, 1, "__headers__", |
| 165 | f"Expected exact header order: {', '.join(expected)}.") |
| 166 | continue |
| 167 | valid_sheets.add(sheet_name) |
| 168 | |
| 169 | parsed: dict[str, list[tuple[int, dict[str, Any]]]] = { |
| 170 | name: _rows(workbook[name], SHEET_HEADERS[name]) |
| 171 | for name in valid_sheets |
| 172 | } |
| 173 | workbook.close() |
| 174 | |
| 175 | for sheet_name in ("Company", "Accounts", "Notes", "Mapping"): |
| 176 | for row_number, row in parsed.get(sheet_name, []): |
| 177 | for field in _REQUIRED[sheet_name]: |
| 178 | if _empty(row[field]): |
| 179 | _issue(issues, "REQUIRED_FIELD", sheet_name, row_number, field, |
| 180 | "Required field is empty.") |
| 181 | for field in _CODE_FIELDS.intersection(row): |
| 182 | _text_code(row[field], issues, sheet_name, row_number, field) |
| 183 | _positive_int(row.get("fiscal_year"), issues, sheet_name, row_number, "fiscal_year") |
| 184 | |
| 185 | companies: set[tuple[str, int]] = set() |
| 186 | for row_number, row in parsed.get("Company", []): |
| 187 | code = _text_code(row["company_code"], [], "Company", row_number, "company_code") |
| 188 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 189 | if code and year and year > 0: |
| 190 | key = (code, year) |
| 191 | if key in companies: |
| 192 | _issue(issues, "DUPLICATE_COMPANY_YEAR", "Company", row_number, |
| 193 | "company_code", "Company/fiscal-year key must be unique.") |
| 194 | companies.add(key) |
| 195 | if not _empty(row["status"]) and row["status"] not in {"Draft", "Approved", "Locked"}: |
| 196 | _issue(issues, "INVALID_LIFECYCLE", "Company", row_number, "status", |
| 197 | "Allowed values are Draft, Approved, and Locked.") |
| 198 | |
| 199 | account_keys: set[tuple[str, int, str]] = set() |
| 200 | for row_number, row in parsed.get("Accounts", []): |
| 201 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 202 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 203 | account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None |
| 204 | if code and year and (code.strip(), year) not in companies: |
| 205 | _issue(issues, "UNKNOWN_COMPANY_YEAR", "Accounts", row_number, "company_code", |
| 206 | "Referenced company/fiscal year is not defined in Company.") |
| 207 | if code and year and account: |
| 208 | key = (code.strip(), year, account.strip()) |
| 209 | if key in account_keys: |
| 210 | _issue(issues, "DUPLICATE_ACCOUNT", "Accounts", row_number, |
| 211 | "account_full_code", "Account key is duplicated within company/fiscal year.") |
| 212 | account_keys.add(key) |
| 213 | values = [_finite_decimal(row[field], issues, "Accounts", row_number, field) |
| 214 | for field in ("opening", "debit", "credit", "closing")] |
| 215 | _positive_int(row["source_row"], issues, "Accounts", row_number, "source_row") |
| 216 | if not _empty(row["row_status"]) and row["row_status"] not in {"Draft", "Reviewed", "Approved"}: |
| 217 | _issue(issues, "INVALID_LIFECYCLE", "Accounts", row_number, "row_status", |
| 218 | "Allowed values are Draft, Reviewed, and Approved.") |
| 219 | if all(value is not None for value in values): |
| 220 | delta = values[0] + values[1] - values[2] - values[3] |
| 221 | if delta != 0: |
| 222 | _issue(issues, "NON_ZERO_CLOSING_DELTA", "Accounts", row_number, |
| 223 | "closing_delta", f"opening + debit - credit - closing equals {delta}.") |
| 224 | |
| 225 | for sheet_name in ("Notes", "Mapping"): |
| 226 | for row_number, row in parsed.get(sheet_name, []): |
| 227 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 228 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 229 | if code and year and (code.strip(), year) not in companies: |
| 230 | _issue(issues, "UNKNOWN_COMPANY_YEAR", sheet_name, row_number, |
| 231 | "company_code", "Referenced company/fiscal year is not defined in Company.") |
| 232 | |
| 233 | mapping_ids: set[str] = set() |
| 234 | for row_number, row in parsed.get("Mapping", []): |
| 235 | mapping_id = row["mapping_id"] if isinstance(row["mapping_id"], str) else None |
| 236 | if mapping_id: |
| 237 | if mapping_id.strip() in mapping_ids: |
| 238 | _issue(issues, "DUPLICATE_MAPPING_ID", "Mapping", row_number, |
| 239 | "mapping_id", "Mapping ID must be unique.") |
| 240 | mapping_ids.add(mapping_id.strip()) |
| 241 | _positive_int(row["mapping_version"], issues, "Mapping", row_number, "mapping_version") |
| 242 | if not _empty(row["approval_status"]) and row["approval_status"] not in {"Draft", "Reviewed", "Approved"}: |
| 243 | _issue(issues, "INVALID_LIFECYCLE", "Mapping", row_number, "approval_status", |
| 244 | "Allowed values are Draft, Reviewed, and Approved.") |
| 245 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 246 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 247 | account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None |
| 248 | if code and year and account and (code.strip(), year, account.strip()) not in account_keys: |
| 249 | _issue(issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number, |
| 250 | "account_full_code", "Mapped account does not exist in Accounts for this company/fiscal year.") |
| 251 | |
| 252 | ordered = tuple(sorted(issues, key=lambda item: ( |
| 253 | _SHEET_ORDER.get(item.sheet, -1), item.row, |
| 254 | SHEET_HEADERS.get(item.sheet, ()).index(item.field) |
| 255 | if item.field in SHEET_HEADERS.get(item.sheet, ()) else -1, |
| 256 | item.code, item.message, |
| 257 | ))) |
| 258 | counts = dict(sorted(Counter(item.severity for item in ordered).items())) |
| 259 | return PilotPreflightResult(not any(item.severity == "ERROR" for item in ordered), ordered, counts) |