codex/gate3-mapping-excel-20261023
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 158 lines 7.04 KB
Raw
1 """Strict, non-executing XLSX interchange for explicit mapping decisions.
2
3 The workbook carries only mapping identifiers, not balances or inferred targets.
4 All database changes are staged in a savepoint; the caller owns the outer commit.
5 """
6 from __future__ import annotations
7
8 from dataclasses import dataclass
9 from io import BytesIO
10 from zipfile import BadZipFile, ZipFile
11
12 from openpyxl import Workbook, load_workbook
13 from sqlalchemy.orm import Session
14
15 from aram_backend.mapping_service import MappingValidationError, save_mapping_rule
16
17 HEADERS = ("rule_key", "account_code", "target_note_id", "mapping_type", "version")
18 SHEET = "Mapping"
19 MAX_FILE_BYTES = 10 * 1024 * 1024
20 MAX_UNCOMPRESSED_BYTES = 40 * 1024 * 1024
21 MAX_ROWS = 10_000
22
23
24 @dataclass(frozen=True)
25 class MappingEntry:
26 rule_key: str
27 account_code: str
28 target_note_id: int
29 mapping_type: str
30 version: int
31
32
33 def _safe_archive(content: bytes) -> None:
34 if not isinstance(content, bytes) or not content or len(content) > MAX_FILE_BYTES:
35 raise MappingValidationError("XLSX must be nonempty and at most 10 MiB")
36 try:
37 with ZipFile(BytesIO(content)) as archive:
38 infos = archive.infolist()
39 if len(infos) > 1_000 or sum(i.file_size for i in infos) > MAX_UNCOMPRESSED_BYTES:
40 raise MappingValidationError("XLSX archive exceeds safety limits")
41 if any(i.flag_bits & 0x1 for i in infos):
42 raise MappingValidationError("Encrypted XLSX entries are not supported")
43 except MappingValidationError:
44 raise
45 except (BadZipFile, ValueError) as exc:
46 raise MappingValidationError("Invalid XLSX archive") from exc
47
48
49 def _parse_int(value: object, label: str, row_number: int) -> int:
50 if type(value) is not int or value <= 0:
51 raise MappingValidationError(f"Row {row_number}: {label} must be a positive integer")
52 return value
53
54
55 def _parse_text(value: object, label: str, limit: int, row_number: int) -> str:
56 if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit:
57 raise MappingValidationError(f"Row {row_number}: invalid {label}")
58 return value
59
60
61 def preview_mapping_workbook(content: bytes) -> tuple[MappingEntry, ...]:
62 """Read and validate an XLSX mapping sheet without modifying any database."""
63 _safe_archive(content)
64 try:
65 book = load_workbook(BytesIO(content), read_only=True, data_only=False, keep_links=False)
66 except (OSError, ValueError, KeyError, BadZipFile) as exc:
67 raise MappingValidationError("Unreadable XLSX workbook") from exc
68 try:
69 if book.sheetnames != [SHEET]:
70 raise MappingValidationError("Workbook must contain only a Mapping sheet")
71 sheet = book[SHEET]
72 if sheet.max_row is not None and sheet.max_row > MAX_ROWS + 1:
73 raise MappingValidationError("Too many mapping rows")
74 if sheet.max_column is not None and sheet.max_column > len(HEADERS):
75 raise MappingValidationError("Unexpected columns in Mapping sheet")
76 rows = sheet.iter_rows(values_only=False)
77 header = next(rows, ())
78 if tuple(cell.value for cell in header) != HEADERS:
79 raise MappingValidationError("Mapping sheet headers do not match the contract")
80 entries: list[MappingEntry] = []
81 seen: set[tuple[str, int]] = set()
82 for row_number, cells in enumerate(rows, start=2):
83 if row_number > MAX_ROWS + 1:
84 raise MappingValidationError("Too many mapping rows")
85 if any(cell.data_type == "f" for cell in cells):
86 raise MappingValidationError(f"Row {row_number}: formulas are prohibited")
87 values = tuple(cell.value for cell in cells)
88 if all(value is None for value in values):
89 continue
90 if len(values) != len(HEADERS):
91 raise MappingValidationError(f"Row {row_number}: invalid column count")
92 entry = MappingEntry(
93 rule_key=_parse_text(values[0], "rule_key", 128, row_number),
94 account_code=_parse_text(values[1], "account_code", 64, row_number),
95 target_note_id=_parse_int(values[2], "target_note_id", row_number),
96 mapping_type=_parse_text(values[3], "mapping_type", 32, row_number),
97 version=_parse_int(values[4], "version", row_number),
98 )
99 identity = (entry.rule_key, entry.version)
100 if identity in seen:
101 raise MappingValidationError(f"Row {row_number}: duplicate rule key/version")
102 seen.add(identity)
103 entries.append(entry)
104 if not entries:
105 raise MappingValidationError("Mapping sheet contains no mapping entries")
106 return tuple(entries)
107 finally:
108 book.close()
109
110
111 def export_mapping_workbook(entries: tuple[MappingEntry, ...]) -> bytes:
112 """Create a deterministic-structure XLSX; force text cells to prevent formula execution."""
113 if not entries or len(entries) > MAX_ROWS:
114 raise MappingValidationError("Mapping export must contain 1 to 10000 entries")
115 book = Workbook()
116 sheet = book.active
117 sheet.title = SHEET
118 sheet.append(HEADERS)
119 seen: set[tuple[str, int]] = set()
120 for index, entry in enumerate(entries, start=2):
121 if not isinstance(entry, MappingEntry):
122 raise MappingValidationError(f"Row {index}: invalid mapping entry")
123 key = (_parse_text(entry.rule_key, "rule_key", 128, index),
124 _parse_int(entry.version, "version", index))
125 if key in seen:
126 raise MappingValidationError(f"Row {index}: duplicate rule key/version")
127 seen.add(key)
128 row = (
129 key[0], _parse_text(entry.account_code, "account_code", 64, index),
130 _parse_int(entry.target_note_id, "target_note_id", index),
131 _parse_text(entry.mapping_type, "mapping_type", 32, index), key[1],
132 )
133 sheet.append(row)
134 for col in (1, 2, 4):
135 sheet.cell(index, col).data_type = "s"
136 stream = BytesIO()
137 book.save(stream)
138 return stream.getvalue()
139
140
141 def import_mapping_workbook(session: Session, *, year_id: int, content: bytes) -> int:
142 """Stage all valid mappings atomically, without committing the caller's transaction."""
143 entries = preview_mapping_workbook(content)
144 # SQLite's legacy transaction mode does not issue a real BEGIN for a SAVEPOINT.
145 # Without an outer BEGIN, releasing the savepoint can persist rows despite
146 # session.rollback(). Start the physical transaction explicitly when absent.
147 if session.get_bind().dialect.name == "sqlite":
148 connection = session.connection()
149 if not connection.connection.driver_connection.in_transaction:
150 connection.exec_driver_sql("BEGIN")
151 with session.begin_nested():
152 for entry in entries:
153 save_mapping_rule(
154 session, year_id=year_id, rule_key=entry.rule_key,
155 account_code=entry.account_code, target_note_id=entry.target_note_id,
156 mapping_type=entry.mapping_type, version=entry.version,
157 )
158 return len(entries)