@davoodmehraban89 / Aram / commits / 3504c4d
Fork 0

feat(ingestion): add read-only mapping source parser

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