@davoodmehraban89 / Aram-1 / commits / aa8d1f0
Fork 0

test(integration): assemble Mapping core and XLSX modules for combined CI

davoodmehraban89 committed Oct 30, 2026 at 17:34 UTC aa8d1f0a914db3aac1d8501ef4d66f77d3417d41
1 file changed +205
backend/src/aram_backend/mapping_excel.py new
+205
@@ -0,0 +1,205 @@
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 +from xml.etree import ElementTree
12 +
13 +from openpyxl import Workbook, load_workbook
14 +from sqlalchemy.orm import Session
15 +
16 +from aram_backend.mapping_service import MappingValidationError, save_mapping_rule
17 +
18 +HEADERS = ("rule_key", "account_code", "target_note_id", "mapping_type", "version")
19 +SHEET = "Mapping"
20 +MAX_FILE_BYTES = 10 * 1024 * 1024
21 +MAX_UNCOMPRESSED_BYTES = 40 * 1024 * 1024
22 +MAX_ROWS = 10_000
23 +
24 +
25 +@dataclass(frozen=True)
26 +class MappingEntry:
27 + rule_key: str
28 + account_code: str
29 + target_note_id: int
30 + mapping_type: str
31 + version: int
32 +
33 +
34 +def _safe_archive(content: bytes) -> None:
35 + if not isinstance(content, bytes) or not content or len(content) > MAX_FILE_BYTES:
36 + raise MappingValidationError("XLSX must be nonempty and at most 10 MiB")
37 + try:
38 + with ZipFile(BytesIO(content)) as archive:
39 + infos = archive.infolist()
40 + if len(infos) > 1_000 or sum(i.file_size for i in infos) > MAX_UNCOMPRESSED_BYTES:
41 + raise MappingValidationError("XLSX archive exceeds safety limits")
42 + if any(i.flag_bits & 0x1 for i in infos):
43 + raise MappingValidationError("Encrypted XLSX entries are not supported")
44 + except MappingValidationError:
45 + raise
46 + except (BadZipFile, ValueError) as exc:
47 + raise MappingValidationError("Invalid XLSX archive") from exc
48 +
49 +
50 +def _reject_hidden_dimensions(content: bytes, worksheet_path: str) -> None:
51 + """Stream worksheet XML to detect hidden row/column metadata safely.
52 +
53 + openpyxl's read-only worksheet deliberately lacks row_dimensions and
54 + column_dimensions. Loading arbitrary XLSX in full-memory mode merely to
55 + inspect visibility would defeat the bounded streaming parser.
56 + """
57 + try:
58 + with ZipFile(BytesIO(content)) as archive:
59 + with archive.open(worksheet_path.lstrip("/")) as worksheet:
60 + for action, element in ElementTree.iterparse(
61 + worksheet, events=("start", "end")
62 + ):
63 + if action == "start":
64 + kind = element.tag.rsplit("}", 1)[-1]
65 + if element.attrib.get("hidden", "").lower() not in ("1", "true"):
66 + continue
67 + if kind == "row":
68 + # Any hidden row can conceal Mapping decisions, including
69 + # a header or a visually empty spacer.
70 + raise MappingValidationError("Hidden Mapping row is prohibited")
71 + if kind == "col":
72 + try:
73 + first = int(element.attrib["min"])
74 + last = int(element.attrib["max"])
75 + except (ValueError, KeyError) as exc:
76 + raise MappingValidationError(
77 + "Hidden Mapping column range is invalid"
78 + ) from exc
79 + if first <= len(HEADERS) and last >= 1:
80 + raise MappingValidationError(
81 + "Hidden Mapping column is prohibited"
82 + )
83 + else:
84 + element.clear()
85 + except MappingValidationError:
86 + raise
87 + except (BadZipFile, KeyError, OSError, ValueError, ElementTree.ParseError) as exc:
88 + raise MappingValidationError("Unreadable XLSX worksheet visibility metadata") from exc
89 +
90 +
91 +def _parse_int(value: object, label: str, row_number: int) -> int:
92 + if type(value) is not int or value <= 0:
93 + raise MappingValidationError(f"Row {row_number}: {label} must be a positive integer")
94 + return value
95 +
96 +
97 +def _parse_text(value: object, label: str, limit: int, row_number: int) -> str:
98 + if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit:
99 + raise MappingValidationError(f"Row {row_number}: invalid {label}")
100 + return value
101 +
102 +
103 +def preview_mapping_workbook(content: bytes) -> tuple[MappingEntry, ...]:
104 + """Read and validate an XLSX mapping sheet without modifying any database."""
105 + _safe_archive(content)
106 + try:
107 + book = load_workbook(BytesIO(content), read_only=True, data_only=False, keep_links=False)
108 + except (OSError, ValueError, KeyError, BadZipFile) as exc:
109 + raise MappingValidationError("Unreadable XLSX workbook") from exc
110 + try:
111 + if book.sheetnames != [SHEET]:
112 + raise MappingValidationError("Workbook must contain only a Mapping sheet")
113 + sheet = book[SHEET]
114 + if sheet.sheet_state != "visible":
115 + raise MappingValidationError("Hidden Mapping sheet is prohibited")
116 + # Visibility is checked from the same bounded workbook archive, before
117 + # any mapping entry is parsed or a database transaction can be staged.
118 + _reject_hidden_dimensions(content, sheet._worksheet_path)
119 + if sheet.max_row is not None and sheet.max_row > MAX_ROWS + 1:
120 + raise MappingValidationError("Too many mapping rows")
121 + if sheet.max_column is not None and sheet.max_column > len(HEADERS):
122 + raise MappingValidationError("Unexpected columns in Mapping sheet")
123 + rows = sheet.iter_rows(values_only=False)
124 + header = next(rows, ())
125 + if tuple(cell.value for cell in header) != HEADERS:
126 + raise MappingValidationError("Mapping sheet headers do not match the contract")
127 + entries: list[MappingEntry] = []
128 + seen: set[tuple[str, int]] = set()
129 + for row_number, cells in enumerate(rows, start=2):
130 + if row_number > MAX_ROWS + 1:
131 + raise MappingValidationError("Too many mapping rows")
132 + if any(cell.data_type == "f" for cell in cells):
133 + raise MappingValidationError(f"Row {row_number}: formulas are prohibited")
134 + values = tuple(cell.value for cell in cells)
135 + if all(value is None for value in values):
136 + continue
137 + if len(values) != len(HEADERS):
138 + raise MappingValidationError(f"Row {row_number}: invalid column count")
139 + entry = MappingEntry(
140 + rule_key=_parse_text(values[0], "rule_key", 128, row_number),
141 + account_code=_parse_text(values[1], "account_code", 64, row_number),
142 + target_note_id=_parse_int(values[2], "target_note_id", row_number),
143 + mapping_type=_parse_text(values[3], "mapping_type", 32, row_number),
144 + version=_parse_int(values[4], "version", row_number),
145 + )
146 + identity = (entry.rule_key, entry.version)
147 + if identity in seen:
148 + raise MappingValidationError(f"Row {row_number}: duplicate rule key/version")
149 + seen.add(identity)
150 + entries.append(entry)
151 + if not entries:
152 + raise MappingValidationError("Mapping sheet contains no mapping entries")
153 + return tuple(entries)
154 + finally:
155 + book.close()
156 +
157 +
158 +def export_mapping_workbook(entries: tuple[MappingEntry, ...]) -> bytes:
159 + """Create a deterministic-structure XLSX; force text cells to prevent formula execution."""
160 + if not entries or len(entries) > MAX_ROWS:
161 + raise MappingValidationError("Mapping export must contain 1 to 10000 entries")
162 + book = Workbook()
163 + sheet = book.active
164 + sheet.title = SHEET
165 + sheet.append(HEADERS)
166 + seen: set[tuple[str, int]] = set()
167 + for index, entry in enumerate(entries, start=2):
168 + if not isinstance(entry, MappingEntry):
169 + raise MappingValidationError(f"Row {index}: invalid mapping entry")
170 + key = (_parse_text(entry.rule_key, "rule_key", 128, index),
171 + _parse_int(entry.version, "version", index))
172 + if key in seen:
173 + raise MappingValidationError(f"Row {index}: duplicate rule key/version")
174 + seen.add(key)
175 + row = (
176 + key[0], _parse_text(entry.account_code, "account_code", 64, index),
177 + _parse_int(entry.target_note_id, "target_note_id", index),
178 + _parse_text(entry.mapping_type, "mapping_type", 32, index), key[1],
179 + )
180 + sheet.append(row)
181 + for col in (1, 2, 4):
182 + sheet.cell(index, col).data_type = "s"
183 + stream = BytesIO()
184 + book.save(stream)
185 + return stream.getvalue()
186 +
187 +
188 +def import_mapping_workbook(session: Session, *, year_id: int, content: bytes) -> int:
189 + """Stage all valid mappings atomically, without committing the caller's transaction."""
190 + entries = preview_mapping_workbook(content)
191 + # SQLite's legacy transaction mode does not issue a real BEGIN for a SAVEPOINT.
192 + # Without an outer BEGIN, releasing the savepoint can persist rows despite
193 + # session.rollback(). Start the physical transaction explicitly when absent.
194 + if session.get_bind().dialect.name == "sqlite":
195 + connection = session.connection()
196 + if not connection.connection.driver_connection.in_transaction:
197 + connection.exec_driver_sql("BEGIN")
198 + with session.begin_nested():
199 + for entry in entries:
200 + save_mapping_rule(
201 + session, year_id=year_id, rule_key=entry.rule_key,
202 + account_code=entry.account_code, target_note_id=entry.target_note_id,
203 + mapping_type=entry.mapping_type, version=entry.version,
204 + )
205 + return len(entries)