@davoodmehraban89 / Aram-2 Mirror · read-only / commits / 00bcece
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 18:15 UTC

feat(mapping): safe XLSX preview, export and atomic mapping import

davoodmehraban89 committed Oct 23, 2026 at 02:42 UTC 00bcece60d00a19ae5852922bd482827e27ea713
1 file changed +149
backend/src/aram_backend/mapping_excel.py new
+149
@@ -0,0 +1,149 @@
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 (BadZipFile, ValueError) as exc:
44 + raise MappingValidationError("Invalid XLSX archive") from exc
45 +
46 +
47 +def _parse_int(value: object, label: str, row_number: int) -> int:
48 + if type(value) is not int or value <= 0:
49 + raise MappingValidationError(f"Row {row_number}: {label} must be a positive integer")
50 + return value
51 +
52 +
53 +def _parse_text(value: object, label: str, limit: int, row_number: int) -> str:
54 + if not isinstance(value, str) or not value or value.strip() != value or len(value) > limit:
55 + raise MappingValidationError(f"Row {row_number}: invalid {label}")
56 + return value
57 +
58 +
59 +def preview_mapping_workbook(content: bytes) -> tuple[MappingEntry, ...]:
60 + """Read and validate an XLSX mapping sheet without modifying any database."""
61 + _safe_archive(content)
62 + try:
63 + book = load_workbook(BytesIO(content), read_only=True, data_only=False, keep_links=False)
64 + except (OSError, ValueError, KeyError, BadZipFile) as exc:
65 + raise MappingValidationError("Unreadable XLSX workbook") from exc
66 + try:
67 + if book.sheetnames != [SHEET]:
68 + raise MappingValidationError("Workbook must contain only a Mapping sheet")
69 + sheet = book[SHEET]
70 + if sheet.max_row is not None and sheet.max_row > MAX_ROWS + 1:
71 + raise MappingValidationError("Too many mapping rows")
72 + if sheet.max_column is not None and sheet.max_column > len(HEADERS):
73 + raise MappingValidationError("Unexpected columns in Mapping sheet")
74 + rows = sheet.iter_rows(values_only=False)
75 + header = next(rows, ())
76 + if tuple(cell.value for cell in header) != HEADERS:
77 + raise MappingValidationError("Mapping sheet headers do not match the contract")
78 + entries: list[MappingEntry] = []
79 + seen: set[tuple[str, int]] = set()
80 + for row_number, cells in enumerate(rows, start=2):
81 + if row_number > MAX_ROWS + 1:
82 + raise MappingValidationError("Too many mapping rows")
83 + if any(cell.data_type == "f" for cell in cells):
84 + raise MappingValidationError(f"Row {row_number}: formulas are prohibited")
85 + values = tuple(cell.value for cell in cells)
86 + if all(value is None for value in values):
87 + continue
88 + if len(values) != len(HEADERS):
89 + raise MappingValidationError(f"Row {row_number}: invalid column count")
90 + entry = MappingEntry(
91 + rule_key=_parse_text(values[0], "rule_key", 128, row_number),
92 + account_code=_parse_text(values[1], "account_code", 64, row_number),
93 + target_note_id=_parse_int(values[2], "target_note_id", row_number),
94 + mapping_type=_parse_text(values[3], "mapping_type", 32, row_number),
95 + version=_parse_int(values[4], "version", row_number),
96 + )
97 + identity = (entry.rule_key, entry.version)
98 + if identity in seen:
99 + raise MappingValidationError(f"Row {row_number}: duplicate rule key/version")
100 + seen.add(identity)
101 + entries.append(entry)
102 + if not entries:
103 + raise MappingValidationError("Mapping sheet contains no mapping entries")
104 + return tuple(entries)
105 + finally:
106 + book.close()
107 +
108 +
109 +def export_mapping_workbook(entries: tuple[MappingEntry, ...]) -> bytes:
110 + """Create a deterministic-structure XLSX; force text cells to prevent formula execution."""
111 + if not entries or len(entries) > MAX_ROWS:
112 + raise MappingValidationError("Mapping export must contain 1 to 10000 entries")
113 + book = Workbook()
114 + sheet = book.active
115 + sheet.title = SHEET
116 + sheet.append(HEADERS)
117 + seen: set[tuple[str, int]] = set()
118 + for index, entry in enumerate(entries, start=2):
119 + if not isinstance(entry, MappingEntry):
120 + raise MappingValidationError(f"Row {index}: invalid mapping entry")
121 + key = (_parse_text(entry.rule_key, "rule_key", 128, index),
122 + _parse_int(entry.version, "version", index))
123 + if key in seen:
124 + raise MappingValidationError(f"Row {index}: duplicate rule key/version")
125 + seen.add(key)
126 + row = (
127 + key[0], _parse_text(entry.account_code, "account_code", 64, index),
128 + _parse_int(entry.target_note_id, "target_note_id", index),
129 + _parse_text(entry.mapping_type, "mapping_type", 32, index), key[1],
130 + )
131 + sheet.append(row)
132 + for col in (1, 2, 4):
133 + sheet.cell(index, col).data_type = "s"
134 + stream = BytesIO()
135 + book.save(stream)
136 + return stream.getvalue()
137 +
138 +
139 +def import_mapping_workbook(session: Session, *, year_id: int, content: bytes) -> int:
140 + """Stage all valid mappings atomically, without committing the caller's transaction."""
141 + entries = preview_mapping_workbook(content)
142 + with session.begin_nested():
143 + for entry in entries:
144 + save_mapping_rule(
145 + session, year_id=year_id, rule_key=entry.rule_key,
146 + account_code=entry.account_code, target_note_id=entry.target_note_id,
147 + mapping_type=entry.mapping_type, version=entry.version,
148 + )
149 + return len(entries)