codex/gate-2a-pilot-workbook-6864754244772568979
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 296 lines 11.1 KB
Raw
1 from dataclasses import dataclass
2 from decimal import Decimal, InvalidOperation
3 from io import BytesIO
4 from typing import Any
5
6 from openpyxl import load_workbook
7 from openpyxl.worksheet.worksheet import Worksheet
8
9
10 @dataclass(frozen=True)
11 class ValidationIssue:
12 severity: str
13 code: str
14 sheet: str
15 row: int
16 field: str
17 message: str
18
19
20 @dataclass(frozen=True)
21 class ValidationResult:
22 is_valid: bool
23 issues: list[ValidationIssue]
24
25
26 REQUIRED_SHEETS = [
27 "Company",
28 "Accounts",
29 "Notes",
30 "Mapping",
31 "Test_Log",
32 "Checks",
33 "Guide_FA",
34 "Lists",
35 ]
36
37 EXPECTED_HEADERS = {
38 "Company": ["company_code", "company_name", "fiscal_year", "status"],
39 "Accounts": [
40 "company_code",
41 "fiscal_year",
42 "account_code",
43 "account_name",
44 "t1_code",
45 "t2_code",
46 "t3_code",
47 "t4_code",
48 "nature",
49 "opening",
50 "debit",
51 "credit",
52 "closing",
53 ],
54 "Notes": ["company_code", "fiscal_year", "note_number", "title", "row_order", "label"],
55 "Mapping": ["company_code", "fiscal_year", "mapping_id", "account_code", "note_number", "mapping_type"],
56 "Test_Log": ["test_id", "description", "result"],
57 "Checks": ["check_name", "status"],
58 "Guide_FA": ["راهنما (Guide)"],
59 "Lists": ["List_Name", "Value"],
60 }
61
62 def _validate_headers(sheet: Worksheet, sheet_name: str, issues: list[ValidationIssue]) -> bool:
63 if sheet_name not in EXPECTED_HEADERS:
64 return True
65
66 expected = EXPECTED_HEADERS[sheet_name]
67 row_iter = sheet.iter_rows(min_row=1, max_row=1, values_only=True)
68 try:
69 actual_row = next(row_iter)
70 except StopIteration:
71 actual_row = []
72
73 actual = [str(val).strip() if val is not None else "" for val in actual_row]
74
75 if actual[:len(expected)] != expected:
76 issues.append(
77 ValidationIssue(
78 severity="ERROR",
79 code="INVALID_HEADERS",
80 sheet=sheet_name,
81 row=1,
82 field="Headers",
83 message=f"Expected headers {expected}, got {actual}",
84 )
85 )
86 return False
87 return True
88
89 def validate_pilot_workbook(workbook_bytes: bytes) -> ValidationResult:
90 """Preflight API to validate a Pilot workbook without persisting data."""
91 issues: list[ValidationIssue] = []
92
93 try:
94 wb = load_workbook(filename=BytesIO(workbook_bytes), data_only=True, read_only=True)
95 except Exception as e:
96 issues.append(
97 ValidationIssue(
98 severity="ERROR",
99 code="INVALID_FILE",
100 sheet="Global",
101 row=0,
102 field="File",
103 message=f"Failed to load workbook: {e}",
104 )
105 )
106 return ValidationResult(is_valid=False, issues=issues)
107
108 for required in REQUIRED_SHEETS:
109 if required not in wb.sheetnames:
110 issues.append(
111 ValidationIssue(
112 severity="ERROR",
113 code="MISSING_SHEET",
114 sheet=required,
115 row=0,
116 field="Sheet",
117 message=f"Missing required sheet: {required}",
118 )
119 )
120
121 if issues:
122 wb.close()
123 return ValidationResult(is_valid=False, issues=issues)
124
125 for sheet_name in REQUIRED_SHEETS:
126 _validate_headers(wb[sheet_name], sheet_name, issues)
127
128 if issues:
129 wb.close()
130 return ValidationResult(is_valid=False, issues=issues)
131
132 defined_company_years = set()
133 accounts_set = set()
134
135 # Validate Company
136 for row_idx, row in enumerate(wb["Company"].iter_rows(min_row=2, values_only=True), start=2):
137 if not any(row):
138 continue
139 c_code, c_name, year, status = row[:4]
140 if not c_code or not year:
141 continue
142
143 if isinstance(c_code, (int, float)):
144 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Company", row_idx, "company_code", "Codes must be text, not numeric"))
145
146 try:
147 year_int = int(year)
148 if year_int <= 0:
149 raise ValueError
150 except (ValueError, TypeError):
151 issues.append(ValidationIssue("ERROR", "INVALID_TYPE", "Company", row_idx, "fiscal_year", "Must be positive integer"))
152 continue
153
154 key = (str(c_code), year_int)
155 if key in defined_company_years:
156 issues.append(ValidationIssue("ERROR", "DUPLICATE_KEY", "Company", row_idx, "company_code", "Duplicate company/year"))
157 defined_company_years.add(key)
158
159 if status not in {"Draft", "Reviewed", "Approved"}:
160 issues.append(ValidationIssue("ERROR", "INVALID_STATUS", "Company", row_idx, "status", "Invalid status"))
161
162 # Validate Accounts
163 for row_idx, row in enumerate(wb["Accounts"].iter_rows(min_row=2, values_only=True), start=2):
164 padded_row = list(row) + [None] * (max(13, len(row)) - len(row))
165
166 # Limit to the expected length
167 is_empty = all(val is None or str(val).strip() == "" for val in padded_row[:13])
168 if is_empty:
169 continue
170
171 c_code, year, a_code = padded_row[:3]
172 if not c_code or str(c_code).strip() == "" or not year or str(year).strip() == "" or a_code is None or str(a_code).strip() == "":
173 issues.append(ValidationIssue("ERROR", "INCOMPLETE_ROW", "Accounts", row_idx, "Keys", "Missing company, year or account code"))
174 continue
175
176 if isinstance(c_code, (int, float)):
177 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Accounts", row_idx, "company_code", "Codes must be text, not numeric"))
178
179 if isinstance(a_code, (int, float)):
180 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Accounts", row_idx, "account_code", "Codes must be text, not numeric"))
181
182 try:
183 year_int = int(year)
184 except (ValueError, TypeError):
185 year_int = None
186
187 key = (str(c_code), year_int)
188 if key not in defined_company_years:
189 issues.append(ValidationIssue("ERROR", "UNKNOWN_COMPANY_YEAR", "Accounts", row_idx, "company_code", "References undefined company/year"))
190
191 a_code_str = str(a_code)
192 account_key = (str(c_code), year_int, a_code_str)
193 if account_key in accounts_set:
194 issues.append(ValidationIssue("ERROR", "DUPLICATE_KEY", "Accounts", row_idx, "account_code", "Duplicate account code"))
195 accounts_set.add(account_key)
196
197 # Financials
198 financials = padded_row[9:13]
199 parsed_fin = []
200 for i, val in enumerate(financials):
201 try:
202 dec = Decimal(str(val))
203 if not dec.is_finite():
204 raise InvalidOperation
205 parsed_fin.append(dec)
206 except (InvalidOperation, TypeError):
207 col_name = ["opening", "debit", "credit", "closing"][i]
208 issues.append(ValidationIssue("ERROR", "INVALID_TYPE", "Accounts", row_idx, col_name, "Must be a finite Decimal"))
209 parsed_fin.append(None)
210
211 if all(f is not None for f in parsed_fin):
212 op, db, cr, cl = parsed_fin
213 delta = op + db - cr - cl
214 if delta != Decimal(0):
215 issues.append(ValidationIssue("ERROR", "NON_ZERO_DELTA", "Accounts", row_idx, "closing", f"closing_delta is non-zero: {delta}"))
216
217 # Validate Notes
218 notes_set = set()
219 for row_idx, row in enumerate(wb["Notes"].iter_rows(min_row=2, values_only=True), start=2):
220 if not any(row):
221 continue
222 c_code, year, n_num = row[:3]
223 if not c_code or not year or n_num is None:
224 issues.append(ValidationIssue("ERROR", "INCOMPLETE_ROW", "Notes", row_idx, "Keys", "Missing keys"))
225 continue
226
227 if isinstance(c_code, (int, float)):
228 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Notes", row_idx, "company_code", "Codes must be text, not numeric"))
229
230 if isinstance(n_num, (int, float)):
231 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Notes", row_idx, "note_number", "Codes must be text, not numeric"))
232
233 try:
234 year_int = int(year)
235 except (ValueError, TypeError):
236 year_int = None
237
238 key = (str(c_code), year_int)
239 if key not in defined_company_years:
240 issues.append(ValidationIssue("ERROR", "UNKNOWN_COMPANY_YEAR", "Notes", row_idx, "company_code", "References undefined company/year"))
241
242 # Row order uniqueness per note is not strictly duplicate note_number error, but combination
243 row_order = row[4]
244 note_key = (str(c_code), year_int, str(n_num), row_order)
245 if note_key in notes_set:
246 issues.append(ValidationIssue("ERROR", "DUPLICATE_KEY", "Notes", row_idx, "row_order", "Duplicate row order in note"))
247 notes_set.add(note_key)
248
249 # Validate Mapping
250 mappings_set = set()
251 for row_idx, row in enumerate(wb["Mapping"].iter_rows(min_row=2, values_only=True), start=2):
252 if not any(row):
253 continue
254 c_code, year, m_id, a_code = row[:4]
255 target_n_num = row[4] if len(row) > 4 else None
256
257 if not c_code or not year or m_id is None or a_code is None or target_n_num is None:
258 issues.append(ValidationIssue("ERROR", "INCOMPLETE_ROW", "Mapping", row_idx, "Keys", "Missing keys"))
259 continue
260
261 if isinstance(c_code, (int, float)):
262 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Mapping", row_idx, "company_code", "Codes must be text, not numeric"))
263
264 if isinstance(m_id, (int, float)):
265 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Mapping", row_idx, "mapping_id", "Codes must be text, not numeric"))
266
267 if isinstance(a_code, (int, float)):
268 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Mapping", row_idx, "account_code", "Codes must be text, not numeric"))
269
270 if isinstance(target_n_num, (int, float)):
271 issues.append(ValidationIssue("ERROR", "NUMERIC_CODE", "Mapping", row_idx, "note_number", "Codes must be text, not numeric"))
272
273 try:
274 year_int = int(year)
275 except (ValueError, TypeError):
276 year_int = None
277
278 key = (str(c_code), year_int)
279 if key not in defined_company_years:
280 issues.append(ValidationIssue("ERROR", "UNKNOWN_COMPANY_YEAR", "Mapping", row_idx, "company_code", "References undefined company/year"))
281
282 mapping_key = (str(c_code), year_int, str(m_id))
283 if mapping_key in mappings_set:
284 issues.append(ValidationIssue("ERROR", "DUPLICATE_KEY", "Mapping", row_idx, "mapping_id", "Duplicate mapping id"))
285 mappings_set.add(mapping_key)
286
287 account_key = (str(c_code), year_int, str(a_code))
288 if account_key not in accounts_set and key in defined_company_years:
289 issues.append(ValidationIssue("ERROR", "UNKNOWN_ACCOUNT", "Mapping", row_idx, "account_code", "Mapped account not found in Accounts sheet"))
290
291 wb.close()
292
293 # Sort issues deterministically
294 issues.sort(key=lambda i: (i.sheet, i.row, i.field, i.code))
295
296 return ValidationResult(is_valid=len(issues) == 0, issues=issues)