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
py 179 lines 6.71 KB
Raw
1 from __future__ import annotations
2
3 from collections.abc import Iterator
4 from dataclasses import dataclass
5 from io import BytesIO
6 from zipfile import BadZipFile, ZipFile
7 from typing import Any
8
9 from openpyxl import load_workbook
10
11 from aram_backend.workbook_inspection import MAX_HEADER_COLUMNS, inspect_xlsx
12
13
14 MAX_MAPPING_ROWS = 100_000
15 MAX_MAPPING_INPUT_BYTES = 20 * 1024 * 1024
16 MAX_MAPPING_ZIP_ENTRIES = 500
17 MAX_MAPPING_EXPANDED_BYTES = 128 * 1024 * 1024
18
19 _REQUIRED_HEADERS = (
20 "کد حساب",
21 "نوع",
22 "کد یادداشت",
23 "شرح یادداشت",
24 "فرمول یادداشت اصلی",
25 "فرمول یادداشت فرعی",
26 )
27
28
29 @dataclass(frozen=True)
30 class MappingSourceRow:
31 """One untouched source mapping row with its original Excel row number."""
32
33 row_number: int
34 account_code: str
35 mapping_type: str
36 note_code: str
37 note_description: str
38 main_formula: str
39 sub_formula: str
40 source_values: tuple[tuple[str, Any], ...]
41
42
43 class MappingSourceParseError(ValueError):
44 """Raised when a mapping workbook row cannot be read unambiguously."""
45
46
47 def parse_mapping_source(content: bytes) -> Iterator[MappingSourceRow]:
48 """Stream mapping rows without evaluating formulas or inventing precedence.
49
50 All source columns are retained in source_values so later matching logic can
51 explicitly interpret dimensions only after their real headers are reviewed.
52 Formula cells are read as formulas (data_only=False), never executed.
53 """
54
55 _guard_mapping_archive(content)
56 inspection = inspect_xlsx(content, document_type="mapping")
57 workbook = load_workbook(
58 BytesIO(content), read_only=True, data_only=False, keep_links=False
59 )
60 try:
61 worksheet = workbook[inspection.data_sheet]
62 if worksheet.max_column > MAX_HEADER_COLUMNS:
63 raise MappingSourceParseError("mapping workbook has too many columns")
64 header_values = next(
65 worksheet.iter_rows(
66 min_row=inspection.header_row,
67 max_row=inspection.header_row,
68 values_only=True,
69 )
70 )
71 headers = tuple(
72 str(value).strip() if value is not None else ""
73 for value in header_values
74 )
75 indexes = {header: index for index, header in enumerate(headers) if header}
76 missing = set(_REQUIRED_HEADERS).difference(indexes)
77 if missing:
78 raise MappingSourceParseError(
79 f"required mapping headers are missing: {sorted(missing)}"
80 )
81
82 parsed_rows = 0
83 for row_number, values in enumerate(
84 worksheet.iter_rows(
85 min_row=inspection.header_row + 1,
86 max_col=len(headers),
87 values_only=True,
88 ),
89 start=inspection.header_row + 1,
90 ):
91 if not any(value is not None for value in values):
92 continue
93 parsed_rows += 1
94 if parsed_rows > MAX_MAPPING_ROWS:
95 raise MappingSourceParseError("mapping workbook exceeds row limit")
96
97 def cell(header: str) -> Any:
98 index = indexes[header]
99 return values[index] if index < len(values) else None
100
101 account_code = _required_code(cell("کد حساب"), row_number, "کد حساب")
102 mapping_type = _required_text(cell("نوع"), row_number, "نوع")
103 note_code = _required_code(cell("کد یادداشت"), row_number, "کد یادداشت")
104 note_description = _optional_text(
105 cell("شرح یادداشت"), row_number, "شرح یادداشت"
106 )
107 main_formula = _optional_text(
108 cell("فرمول یادداشت اصلی"), row_number, "فرمول یادداشت اصلی"
109 )
110 sub_formula = _optional_text(
111 cell("فرمول یادداشت فرعی"), row_number, "فرمول یادداشت فرعی"
112 )
113 source_values = tuple(
114 (header, values[index] if index < len(values) else None)
115 for index, header in enumerate(headers)
116 if header
117 )
118 yield MappingSourceRow(
119 row_number=row_number,
120 account_code=account_code,
121 mapping_type=mapping_type,
122 note_code=note_code,
123 note_description=note_description,
124 main_formula=main_formula,
125 sub_formula=sub_formula,
126 source_values=source_values,
127 )
128 finally:
129 workbook.close()
130
131
132 def _required_text(value: object, row_number: int, field: str) -> str:
133 result = _optional_text(value, row_number, field)
134 if not result:
135 raise MappingSourceParseError(f"row {row_number}: {field} is required")
136 return result
137
138
139 def _optional_text(value: object, row_number: int, field: str) -> str:
140 if value is None:
141 return ""
142 if isinstance(value, bool):
143 raise MappingSourceParseError(f"row {row_number}: {field} is not valid text")
144 result = str(value).strip()
145 if len(result) > 2_000:
146 raise MappingSourceParseError(f"row {row_number}: {field} exceeds length limit")
147 return result
148
149
150 def _required_code(value: object, row_number: int, field: str) -> str:
151 result = _optional_text(value, row_number, field)
152 if not result:
153 raise MappingSourceParseError(f"row {row_number}: {field} is required")
154 if isinstance(value, float) and not value.is_integer():
155 raise MappingSourceParseError(f"row {row_number}: {field} must be an integer code")
156 if isinstance(value, float):
157 return str(int(value))
158 return result
159
160
161 def _guard_mapping_archive(content: bytes) -> None:
162 if not isinstance(content, bytes) or not 0 < len(content) <= MAX_MAPPING_INPUT_BYTES:
163 raise MappingSourceParseError("mapping workbook size is invalid")
164 try:
165 with ZipFile(BytesIO(content)) as archive:
166 members = archive.infolist()
167 if len(members) > MAX_MAPPING_ZIP_ENTRIES:
168 raise MappingSourceParseError("mapping workbook archive has too many entries")
169 expanded = 0
170 for member in members:
171 if member.file_size < 0 or member.file_size > MAX_MAPPING_EXPANDED_BYTES:
172 raise MappingSourceParseError("mapping workbook expanded size is excessive")
173 expanded += member.file_size
174 if expanded > MAX_MAPPING_EXPANDED_BYTES:
175 raise MappingSourceParseError("mapping workbook expanded size is excessive")
176 except (BadZipFile, OSError, ValueError) as exc:
177 if isinstance(exc, MappingSourceParseError):
178 raise
179 raise MappingSourceParseError("mapping workbook archive is invalid") from exc