Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 19:30 UTC
feat(ingestion): add XLSX structural preflight
davoodmehraban89 committed
Aug 24, 2026 at 06:07 UTC
460b58427c8ebe395f258d6d6e1c784838d0f5ad
1 file changed
+123
backend/src/aram_backend/workbook_inspection.py
new
+123
@@ -0,0 +1,123 @@
1
+from __future__ import annotations
2
+
3
+from dataclasses import dataclass
4
+from io import BytesIO
5
+from zipfile import BadZipFile
6
+
7
+from openpyxl import load_workbook
8
+from openpyxl.utils.exceptions import InvalidFileException
9
+
10
+
11
+MAX_WORKSHEETS = 100
12
+MAX_HEADER_COLUMNS = 256
13
+
14
+
15
+@dataclass(frozen=True)
16
+class WorkbookInspection:
17
+ document_type: str
18
+ sheet_names: tuple[str, ...]
19
+ data_sheet: str | None
20
+ header_row: int | None
21
+ headers: tuple[str, ...]
22
+
23
+
24
+class WorkbookInspectionError(ValueError):
25
+ """Raised when an XLSX source does not match an accepted source profile."""
26
+
27
+
28
+_TABULAR_PROFILES = {
29
+ "general_ledger": {
30
+ "sheet": "Source",
31
+ "header_row": 2,
32
+ "required_headers": frozenset(
33
+ {"حساب", "ACCOUNT_NAME", "year", "OPENING", "Debit", "Credit", "CLOSING"}
34
+ ),
35
+ },
36
+ "mapping": {
37
+ "sheet": "Data",
38
+ "header_row": 1,
39
+ "required_headers": frozenset(
40
+ {
41
+ "کد حساب",
42
+ "نوع",
43
+ "کد یادداشت",
44
+ "شرح یادداشت",
45
+ "فرمول یادداشت اصلی",
46
+ "فرمول یادداشت فرعی",
47
+ }
48
+ ),
49
+ },
50
+}
51
+
52
+_PRIMARY_STATEMENT_SHEETS = frozenset(
53
+ {"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"}
54
+)
55
+
56
+
57
+def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
58
+ """Validate workbook structure without importing rows or evaluating formulas."""
59
+
60
+ if not content:
61
+ raise WorkbookInspectionError("workbook must not be empty")
62
+ if document_type not in {*_TABULAR_PROFILES, "financial_statement"}:
63
+ raise WorkbookInspectionError("document type has no XLSX inspection profile")
64
+
65
+ try:
66
+ workbook = load_workbook(
67
+ BytesIO(content), read_only=True, data_only=False, keep_links=False
68
+ )
69
+ except (BadZipFile, InvalidFileException, OSError, ValueError) as exc:
70
+ raise WorkbookInspectionError("invalid or unreadable XLSX workbook") from exc
71
+
72
+ try:
73
+ sheet_names = tuple(workbook.sheetnames)
74
+ if len(sheet_names) > MAX_WORKSHEETS:
75
+ raise WorkbookInspectionError("workbook contains too many worksheets")
76
+
77
+ if document_type == "financial_statement":
78
+ missing = _PRIMARY_STATEMENT_SHEETS.difference(sheet_names)
79
+ if missing:
80
+ raise WorkbookInspectionError(
81
+ f"financial statement workbook is missing sheets: {sorted(missing)}"
82
+ )
83
+ return WorkbookInspection(
84
+ document_type=document_type,
85
+ sheet_names=sheet_names,
86
+ data_sheet=None,
87
+ header_row=None,
88
+ headers=(),
89
+ )
90
+
91
+ profile = _TABULAR_PROFILES[document_type]
92
+ sheet_name = profile["sheet"]
93
+ if sheet_name not in workbook:
94
+ raise WorkbookInspectionError(f"required worksheet is missing: {sheet_name}")
95
+
96
+ worksheet = workbook[sheet_name]
97
+ header_row = profile["header_row"]
98
+ values = next(
99
+ worksheet.iter_rows(
100
+ min_row=header_row,
101
+ max_row=header_row,
102
+ max_col=min(worksheet.max_column, MAX_HEADER_COLUMNS),
103
+ values_only=True,
104
+ ),
105
+ (),
106
+ )
107
+ headers = tuple(str(value).strip() for value in values if value is not None)
108
+ if len(headers) != len(set(headers)):
109
+ raise WorkbookInspectionError("header row contains duplicate names")
110
+
111
+ missing = profile["required_headers"].difference(headers)
112
+ if missing:
113
+ raise WorkbookInspectionError(f"required headers are missing: {sorted(missing)}")
114
+
115
+ return WorkbookInspection(
116
+ document_type=document_type,
117
+ sheet_names=sheet_names,
118
+ data_sheet=sheet_name,
119
+ header_row=header_row,
120
+ headers=headers,
121
+ )
122
+ finally:
123
+ workbook.close()