Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 19:30 UTC
codex/aram-equity-changes-candidate-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
| 1 | from __future__ import annotations |
| 2 | |
| 3 | from collections import Counter |
| 4 | from dataclasses import dataclass |
| 5 | from datetime import date, datetime |
| 6 | from decimal import Decimal, InvalidOperation |
| 7 | from io import BytesIO |
| 8 | from typing import Any |
| 9 | from zipfile import BadZipFile |
| 10 | |
| 11 | from openpyxl import load_workbook |
| 12 | from openpyxl.utils.exceptions import InvalidFileException |
| 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", "closing_delta", |
| 60 | }, |
| 61 | "Notes": { |
| 62 | "company_code", "fiscal_year", "statement", "statement_section", |
| 63 | "note_number", "note_title", |
| 64 | }, |
| 65 | "Mapping": { |
| 66 | "mapping_id", "company_code", "fiscal_year", "account_full_code", |
| 67 | "account_level", "target_statement", "statement_section", "note_number", |
| 68 | "mapping_version", "approval_status", "source", "validation_status", |
| 69 | }, |
| 70 | } |
| 71 | |
| 72 | _STATEMENTS = {"BS", "IS", "CF", "EQ"} |
| 73 | _ACCOUNT_LEVELS: dict[str, tuple[str, ...]] = { |
| 74 | "General": ("general_code",), |
| 75 | "Subsidiary": ("general_code", "subsidiary_code"), |
| 76 | "Detail1": ("general_code", "subsidiary_code", "detail1_code"), |
| 77 | "Detail2": ( |
| 78 | "general_code", "subsidiary_code", "detail1_code", "detail2_code", |
| 79 | ), |
| 80 | "Detail3": ( |
| 81 | "general_code", "subsidiary_code", "detail1_code", "detail2_code", |
| 82 | "detail3_code", |
| 83 | ), |
| 84 | "Detail4": ( |
| 85 | "general_code", "subsidiary_code", "detail1_code", "detail2_code", |
| 86 | "detail3_code", "detail4_code", |
| 87 | ), |
| 88 | } |
| 89 | _HIERARCHY_FIELDS = ( |
| 90 | "general_code", "subsidiary_code", "detail1_code", "detail2_code", |
| 91 | "detail3_code", "detail4_code", |
| 92 | ) |
| 93 | |
| 94 | |
| 95 | @dataclass(frozen=True) |
| 96 | class PilotIssue: |
| 97 | severity: str |
| 98 | code: str |
| 99 | sheet: str |
| 100 | row: int |
| 101 | field: str |
| 102 | message: str |
| 103 | |
| 104 | |
| 105 | @dataclass(frozen=True) |
| 106 | class PilotPreflightResult: |
| 107 | valid: bool |
| 108 | issues: tuple[PilotIssue, ...] |
| 109 | issue_counts: dict[str, int] |
| 110 | |
| 111 | |
| 112 | def _empty(value: Any) -> bool: |
| 113 | return value is None or (isinstance(value, str) and not value.strip()) |
| 114 | |
| 115 | |
| 116 | def _issue(issues: list[PilotIssue], code: str, sheet: str, row: int, |
| 117 | field: str, message: str, severity: str = "ERROR") -> None: |
| 118 | issues.append(PilotIssue(severity, code, sheet, row, field, message)) |
| 119 | |
| 120 | |
| 121 | def _text_code(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 122 | field: str) -> str | None: |
| 123 | if _empty(value): |
| 124 | return None |
| 125 | if not isinstance(value, str): |
| 126 | _issue(issues, "CODE_NOT_TEXT", sheet, row, field, |
| 127 | "Code cells must use Excel text format; numeric coercion is forbidden.") |
| 128 | return None |
| 129 | code = value.strip() |
| 130 | if code.startswith("="): |
| 131 | _issue(issues, "CODE_FORMULA_FORBIDDEN", sheet, row, field, |
| 132 | "Code cells must contain literal text; formulas are forbidden.") |
| 133 | return None |
| 134 | return code |
| 135 | |
| 136 | |
| 137 | def _positive_int(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 138 | field: str) -> int | None: |
| 139 | if _empty(value): |
| 140 | return None |
| 141 | if isinstance(value, bool) or not isinstance(value, int) or value <= 0: |
| 142 | _issue(issues, "INVALID_POSITIVE_INTEGER", sheet, row, field, |
| 143 | "Value must be a positive integer.") |
| 144 | return None |
| 145 | return value |
| 146 | |
| 147 | |
| 148 | def _finite_decimal(value: Any, issues: list[PilotIssue], sheet: str, row: int, |
| 149 | field: str) -> Decimal | None: |
| 150 | if _empty(value): |
| 151 | return None |
| 152 | if isinstance(value, bool) or isinstance(value, str) and value.startswith("="): |
| 153 | _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field, |
| 154 | "Financial values must be finite numbers, not booleans or formulas.") |
| 155 | return None |
| 156 | try: |
| 157 | parsed = Decimal(str(value).strip()) |
| 158 | except (InvalidOperation, ValueError): |
| 159 | _issue(issues, "INVALID_FINANCIAL_VALUE", sheet, row, field, |
| 160 | "Financial value is not a valid decimal number.") |
| 161 | return None |
| 162 | if not parsed.is_finite(): |
| 163 | _issue(issues, "NON_FINITE_FINANCIAL_VALUE", sheet, row, field, |
| 164 | "NaN and Infinity are not permitted.") |
| 165 | return None |
| 166 | return parsed |
| 167 | |
| 168 | |
| 169 | def _rows(sheet: Any, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]: |
| 170 | result: list[tuple[int, dict[str, Any]]] = [] |
| 171 | for row_number, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), 2): |
| 172 | row = dict(zip(headers, values)) |
| 173 | if any(not _empty(value) for value in row.values()): |
| 174 | result.append((row_number, row)) |
| 175 | return result |
| 176 | |
| 177 | |
| 178 | def preflight_pilot_workbook(workbook_bytes: bytes) -> PilotPreflightResult: |
| 179 | """Validate a Pilot workbook fully in memory without persistence or mutation.""" |
| 180 | issues: list[PilotIssue] = [] |
| 181 | try: |
| 182 | workbook = load_workbook(BytesIO(workbook_bytes), read_only=True, data_only=False) |
| 183 | except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError) as exc: |
| 184 | issue = PilotIssue("ERROR", "INVALID_WORKBOOK", "__workbook__", 0, "__file__", str(exc)) |
| 185 | return PilotPreflightResult(False, (issue,), {"ERROR": 1}) |
| 186 | |
| 187 | valid_sheets: set[str] = set() |
| 188 | for sheet_name, expected in SHEET_HEADERS.items(): |
| 189 | if sheet_name not in workbook.sheetnames: |
| 190 | _issue(issues, "MISSING_SHEET", sheet_name, 1, "__sheet__", |
| 191 | f"Required sheet {sheet_name!r} is missing.") |
| 192 | continue |
| 193 | actual = tuple(cell.value for cell in workbook[sheet_name][1]) |
| 194 | if actual != expected: |
| 195 | _issue(issues, "HEADER_MISMATCH", sheet_name, 1, "__headers__", |
| 196 | f"Expected exact header order: {', '.join(expected)}.") |
| 197 | continue |
| 198 | valid_sheets.add(sheet_name) |
| 199 | |
| 200 | parsed: dict[str, list[tuple[int, dict[str, Any]]]] = { |
| 201 | name: _rows(workbook[name], SHEET_HEADERS[name]) |
| 202 | for name in valid_sheets |
| 203 | } |
| 204 | workbook.close() |
| 205 | |
| 206 | for sheet_name in ("Company", "Accounts", "Notes", "Mapping"): |
| 207 | for row_number, row in parsed.get(sheet_name, []): |
| 208 | for field in _REQUIRED[sheet_name]: |
| 209 | if _empty(row[field]): |
| 210 | _issue(issues, "REQUIRED_FIELD", sheet_name, row_number, field, |
| 211 | "Required field is empty.") |
| 212 | for field in _CODE_FIELDS.intersection(row): |
| 213 | _text_code(row[field], issues, sheet_name, row_number, field) |
| 214 | _positive_int(row.get("fiscal_year"), issues, sheet_name, row_number, "fiscal_year") |
| 215 | |
| 216 | companies: set[tuple[str, int]] = set() |
| 217 | for row_number, row in parsed.get("Company", []): |
| 218 | code = _text_code(row["company_code"], [], "Company", row_number, "company_code") |
| 219 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 220 | if code and year and year > 0: |
| 221 | company_key = (code, year) |
| 222 | if company_key in companies: |
| 223 | _issue(issues, "DUPLICATE_COMPANY_YEAR", "Company", row_number, |
| 224 | "company_code", "Company/fiscal-year key must be unique.") |
| 225 | companies.add(company_key) |
| 226 | if not _empty(row["status"]) and row["status"] not in {"Draft", "Approved", "Locked"}: |
| 227 | _issue(issues, "INVALID_LIFECYCLE", "Company", row_number, "status", |
| 228 | "Allowed values are Draft, Approved, and Locked.") |
| 229 | |
| 230 | account_keys: set[tuple[str, int, str]] = set() |
| 231 | account_rows: dict[tuple[str, int, str], dict[str, Any]] = {} |
| 232 | for row_number, row in parsed.get("Accounts", []): |
| 233 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 234 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 235 | account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None |
| 236 | if code and year and (code.strip(), year) not in companies: |
| 237 | _issue(issues, "UNKNOWN_COMPANY_YEAR", "Accounts", row_number, "company_code", |
| 238 | "Referenced company/fiscal year is not defined in Company.") |
| 239 | if code and year and account: |
| 240 | account_key = (code.strip(), year, account.strip()) |
| 241 | if account_key in account_keys: |
| 242 | _issue(issues, "DUPLICATE_ACCOUNT", "Accounts", row_number, |
| 243 | "account_full_code", "Account key is duplicated within company/fiscal year.") |
| 244 | account_keys.add(account_key) |
| 245 | account_rows.setdefault(account_key, row) |
| 246 | opening, debit, credit, closing = ( |
| 247 | _finite_decimal(row[field], issues, "Accounts", row_number, field) |
| 248 | for field in ("opening", "debit", "credit", "closing") |
| 249 | ) |
| 250 | declared_delta = _finite_decimal( |
| 251 | row["closing_delta"], issues, "Accounts", row_number, "closing_delta" |
| 252 | ) |
| 253 | _positive_int(row["source_row"], issues, "Accounts", row_number, "source_row") |
| 254 | if not _empty(row["row_status"]) and row["row_status"] not in {"Draft", "Reviewed", "Approved"}: |
| 255 | _issue(issues, "INVALID_LIFECYCLE", "Accounts", row_number, "row_status", |
| 256 | "Allowed values are Draft, Reviewed, and Approved.") |
| 257 | if ( |
| 258 | opening is not None |
| 259 | and debit is not None |
| 260 | and credit is not None |
| 261 | and closing is not None |
| 262 | ): |
| 263 | delta = opening + debit - credit - closing |
| 264 | if delta != 0: |
| 265 | _issue(issues, "NON_ZERO_CLOSING_DELTA", "Accounts", row_number, |
| 266 | "closing_delta", f"opening + debit - credit - closing equals {delta}.") |
| 267 | if declared_delta is not None and declared_delta != delta: |
| 268 | _issue( |
| 269 | issues, "CLOSING_DELTA_MISMATCH", "Accounts", row_number, |
| 270 | "closing_delta", |
| 271 | f"Declared closing_delta {declared_delta} does not equal computed delta {delta}.", |
| 272 | ) |
| 273 | |
| 274 | for sheet_name in ("Notes", "Mapping"): |
| 275 | for row_number, row in parsed.get(sheet_name, []): |
| 276 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 277 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 278 | if code and year and (code.strip(), year) not in companies: |
| 279 | _issue(issues, "UNKNOWN_COMPANY_YEAR", sheet_name, row_number, |
| 280 | "company_code", "Referenced company/fiscal year is not defined in Company.") |
| 281 | |
| 282 | note_keys: set[tuple[str, int, str, str, str, str]] = set() |
| 283 | for row_number, row in parsed.get("Notes", []): |
| 284 | statement = row["statement"] |
| 285 | if not _empty(statement) and statement not in _STATEMENTS: |
| 286 | _issue( |
| 287 | issues, "INVALID_STATEMENT", "Notes", row_number, "statement", |
| 288 | "Allowed statement values are BS, IS, CF, and EQ.", |
| 289 | ) |
| 290 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 291 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 292 | note_number = row["note_number"] if isinstance(row["note_number"], str) else None |
| 293 | section = row["statement_section"] if isinstance(row["statement_section"], str) else None |
| 294 | subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else "" |
| 295 | if code and year and statement in _STATEMENTS and section and note_number: |
| 296 | note_key = ( |
| 297 | code.strip(), year, statement, section.strip(), note_number.strip(), |
| 298 | subnote.strip(), |
| 299 | ) |
| 300 | if note_key in note_keys: |
| 301 | _issue( |
| 302 | issues, "DUPLICATE_NOTE_TARGET", "Notes", row_number, |
| 303 | "note_number", "Note/sub-note target is duplicated.", |
| 304 | ) |
| 305 | note_keys.add(note_key) |
| 306 | |
| 307 | mapping_ids: set[str] = set() |
| 308 | for row_number, row in parsed.get("Mapping", []): |
| 309 | mapping_id = row["mapping_id"] if isinstance(row["mapping_id"], str) else None |
| 310 | if mapping_id: |
| 311 | if mapping_id.strip() in mapping_ids: |
| 312 | _issue(issues, "DUPLICATE_MAPPING_ID", "Mapping", row_number, |
| 313 | "mapping_id", "Mapping ID must be unique.") |
| 314 | mapping_ids.add(mapping_id.strip()) |
| 315 | _positive_int(row["mapping_version"], issues, "Mapping", row_number, "mapping_version") |
| 316 | if not _empty(row["approval_status"]) and row["approval_status"] not in {"Draft", "Reviewed", "Approved"}: |
| 317 | _issue(issues, "INVALID_LIFECYCLE", "Mapping", row_number, "approval_status", |
| 318 | "Allowed values are Draft, Reviewed, and Approved.") |
| 319 | if not _empty(row["validation_status"]) and row["validation_status"] not in {"Valid", "Invalid", "Pending"}: |
| 320 | _issue( |
| 321 | issues, "INVALID_VALIDATION_STATUS", "Mapping", row_number, |
| 322 | "validation_status", "Allowed values are Valid, Invalid, and Pending.", |
| 323 | ) |
| 324 | if not _empty(row["target_statement"]) and row["target_statement"] not in _STATEMENTS: |
| 325 | _issue( |
| 326 | issues, "INVALID_STATEMENT", "Mapping", row_number, |
| 327 | "target_statement", "Allowed statement values are BS, IS, CF, and EQ.", |
| 328 | ) |
| 329 | |
| 330 | level = row["account_level"] |
| 331 | if not _empty(level) and level not in _ACCOUNT_LEVELS: |
| 332 | _issue( |
| 333 | issues, "INVALID_ACCOUNT_LEVEL", "Mapping", row_number, |
| 334 | "account_level", |
| 335 | "Allowed levels are General, Subsidiary, Detail1, Detail2, Detail3, and Detail4.", |
| 336 | ) |
| 337 | elif level in _ACCOUNT_LEVELS: |
| 338 | required_fields = set(_ACCOUNT_LEVELS[level]) |
| 339 | for field in required_fields: |
| 340 | if _empty(row[field]): |
| 341 | _issue( |
| 342 | issues, "MAPPING_HIERARCHY_MISSING", "Mapping", row_number, |
| 343 | field, f"{field} is required for account level {level}.", |
| 344 | ) |
| 345 | for field in _HIERARCHY_FIELDS[len(_ACCOUNT_LEVELS[level]):]: |
| 346 | if not _empty(row[field]): |
| 347 | _issue( |
| 348 | issues, "MAPPING_HIERARCHY_EXCESS", "Mapping", row_number, |
| 349 | field, f"{field} must be empty for account level {level}.", |
| 350 | ) |
| 351 | |
| 352 | approval_status = row["approval_status"] |
| 353 | if approval_status in {"Reviewed", "Approved"}: |
| 354 | if _empty(row["reviewer"]): |
| 355 | _issue( |
| 356 | issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number, |
| 357 | "reviewer", "Reviewed and Approved mappings require a reviewer.", |
| 358 | ) |
| 359 | review_date = row["review_date"] |
| 360 | if _empty(review_date): |
| 361 | _issue( |
| 362 | issues, "REVIEW_EVIDENCE_REQUIRED", "Mapping", row_number, |
| 363 | "review_date", "Reviewed and Approved mappings require a review date.", |
| 364 | ) |
| 365 | elif not isinstance(review_date, (str, date, datetime)): |
| 366 | _issue( |
| 367 | issues, "INVALID_REVIEW_DATE", "Mapping", row_number, |
| 368 | "review_date", "Review date must be an Excel date or text date.", |
| 369 | ) |
| 370 | if approval_status == "Approved" and row["validation_status"] != "Valid": |
| 371 | _issue( |
| 372 | issues, "APPROVAL_REQUIRES_VALID_MAPPING", "Mapping", row_number, |
| 373 | "validation_status", "Approved mappings must have validation_status Valid.", |
| 374 | ) |
| 375 | |
| 376 | code = row["company_code"] if isinstance(row["company_code"], str) else None |
| 377 | year = row["fiscal_year"] if isinstance(row["fiscal_year"], int) and not isinstance(row["fiscal_year"], bool) else None |
| 378 | account = row["account_full_code"] if isinstance(row["account_full_code"], str) else None |
| 379 | mapping_account_key = ( |
| 380 | (code.strip(), year, account.strip()) |
| 381 | if code and year and account else None |
| 382 | ) |
| 383 | if mapping_account_key and mapping_account_key not in account_keys: |
| 384 | _issue( |
| 385 | issues, "UNKNOWN_MAPPING_ACCOUNT", "Mapping", row_number, |
| 386 | "account_full_code", |
| 387 | "Mapped account does not exist in Accounts for this company/fiscal year.", |
| 388 | ) |
| 389 | elif mapping_account_key: |
| 390 | source_account = account_rows[mapping_account_key] |
| 391 | for field in _HIERARCHY_FIELDS: |
| 392 | mapping_value = row[field].strip() if isinstance(row[field], str) else None |
| 393 | account_value = source_account[field].strip() if isinstance(source_account[field], str) else None |
| 394 | if mapping_value != account_value: |
| 395 | _issue( |
| 396 | issues, "MAPPING_HIERARCHY_MISMATCH", "Mapping", row_number, |
| 397 | field, |
| 398 | f"Mapping hierarchy does not match Accounts for {field}.", |
| 399 | ) |
| 400 | |
| 401 | statement = row["target_statement"] |
| 402 | section = row["statement_section"] if isinstance(row["statement_section"], str) else None |
| 403 | note_number = row["note_number"] if isinstance(row["note_number"], str) else None |
| 404 | subnote = row["subnote_code"] if isinstance(row["subnote_code"], str) else "" |
| 405 | if code and year and statement in _STATEMENTS and section and note_number: |
| 406 | target_key = ( |
| 407 | code.strip(), year, statement, section.strip(), note_number.strip(), |
| 408 | subnote.strip(), |
| 409 | ) |
| 410 | if target_key not in note_keys: |
| 411 | _issue( |
| 412 | issues, "UNKNOWN_MAPPING_TARGET", "Mapping", row_number, |
| 413 | "note_number", |
| 414 | "Mapped statement/note/sub-note target does not exist in Notes.", |
| 415 | ) |
| 416 | |
| 417 | ordered = tuple(sorted(issues, key=lambda item: ( |
| 418 | _SHEET_ORDER.get(item.sheet, -1), item.row, |
| 419 | SHEET_HEADERS.get(item.sheet, ()).index(item.field) |
| 420 | if item.field in SHEET_HEADERS.get(item.sheet, ()) else -1, |
| 421 | item.code, item.message, |
| 422 | ))) |
| 423 | counts = dict(sorted(Counter(item.severity for item in ordered).items())) |
| 424 | return PilotPreflightResult(not any(item.severity == "ERROR" for item in ordered), ordered, counts) |