Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 01:45 UTC
fix(ingestion): enforce strict matching for idempotent source registration
Co-authored-by: davoodmehraban89 <57283229+davoodmehraban89@users.noreply.github.com>
google-labs-jules[bot] committed
Aug 24, 2026 at 07:37 UTC
bc8ca5f1e2620cb586fe9f7ec281f2cb64594eb9
6 files changed
+712
backend/src/aram_backend/ingestion.py
new
+78
@@ -0,0 +1,78 @@
1
+from __future__ import annotations
2
+
3
+import hashlib
4
+from pathlib import Path
5
+
6
+from sqlalchemy import select
7
+from sqlalchemy.orm import Session
8
+
9
+from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument
10
+
11
+
12
+ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
13
+ALLOWED_DOCUMENT_TYPES = frozenset(
14
+ {"financial_statement", "general_ledger", "mapping", "trial_balance"}
15
+)
16
+
17
+
18
+class SourceRegistrationError(ValueError):
19
+ """Raised when source metadata cannot be registered safely."""
20
+
21
+
22
+def register_source_document(
23
+ session: Session,
24
+ *,
25
+ year_id: int,
26
+ filename: str,
27
+ document_type: str,
28
+ content: bytes,
29
+) -> SourceDocument:
30
+ """Register immutable source metadata without persisting source bytes.
31
+
32
+ Re-registering the same bytes for the same fiscal year is idempotent. The
33
+ caller owns the transaction and may inspect the returned row before commit.
34
+ """
35
+
36
+ if not filename or "/" in filename or "\\" in filename:
37
+ raise SourceRegistrationError("filename must not contain a path")
38
+ safe_name = Path(filename).name
39
+ if Path(safe_name).suffix.lower() not in ALLOWED_SOURCE_SUFFIXES:
40
+ raise SourceRegistrationError("only .csv and .xlsx source files are supported")
41
+ if document_type not in ALLOWED_DOCUMENT_TYPES:
42
+ raise SourceRegistrationError("unsupported source document type")
43
+ if not content:
44
+ raise SourceRegistrationError("source file must not be empty")
45
+
46
+ year = session.get(FiscalYear, year_id)
47
+ if year is None:
48
+ raise SourceRegistrationError(f"fiscal year {year_id} does not exist")
49
+ if year.status is not FiscalYearStatus.DRAFT:
50
+ raise SourceRegistrationError(
51
+ f"fiscal year {year_id} is {year.status.value.lower()} and cannot accept sources"
52
+ )
53
+
54
+ file_hash = hashlib.sha256(content).hexdigest()
55
+ existing = session.scalar(
56
+ select(SourceDocument).where(
57
+ SourceDocument.year_id == year_id,
58
+ SourceDocument.file_hash == file_hash,
59
+ )
60
+ )
61
+ if existing is not None:
62
+ if existing.document_type != document_type and existing.filename != safe_name:
63
+ raise SourceRegistrationError(f"document type and filename mismatch for existing content hash")
64
+ if existing.document_type != document_type:
65
+ raise SourceRegistrationError(f"document type mismatch for existing content hash")
66
+ if existing.filename != safe_name:
67
+ raise SourceRegistrationError(f"filename mismatch for existing content hash")
68
+ return existing
69
+
70
+ source = SourceDocument(
71
+ year_id=year_id,
72
+ filename=safe_name,
73
+ file_hash=file_hash,
74
+ document_type=document_type,
75
+ )
76
+ session.add(source)
77
+ session.flush()
78
+ return source
backend/src/aram_backend/ledger_parser.py
new
+150
@@ -0,0 +1,150 @@
1
+from __future__ import annotations
2
+
3
+from collections.abc import Iterator
4
+from dataclasses import dataclass
5
+from decimal import Decimal, InvalidOperation
6
+from io import BytesIO
7
+
8
+from openpyxl import load_workbook
9
+
10
+from aram_backend.workbook_inspection import inspect_xlsx
11
+
12
+
13
+@dataclass(frozen=True)
14
+class LedgerRecord:
15
+ row_number: int
16
+ account_code: str
17
+ account_name: str
18
+ source_year: int
19
+ entry_type: str
20
+ t1_code: str | None
21
+ t2_code: str | None
22
+ t3_code: str | None
23
+ t4_code: str | None
24
+ opening: Decimal
25
+ debit: Decimal
26
+ credit: Decimal
27
+ closing: Decimal
28
+
29
+
30
+class LedgerParseError(ValueError):
31
+ """Raised when a source ledger row cannot be represented safely."""
32
+
33
+
34
+_FIELDS = {
35
+ "account_code": "حساب",
36
+ "account_name": "ACCOUNT_NAME",
37
+ "source_year": "year",
38
+ "entry_type": "نوع",
39
+ "t1_code": "T1_CODE",
40
+ "t2_code": "T2_CODE",
41
+ "t3_code": "T3_CODE",
42
+ "t4_code": "T4_CODE",
43
+ "opening": "OPENING",
44
+ "debit": "Debit",
45
+ "credit": "Credit",
46
+ "closing": "CLOSING",
47
+}
48
+
49
+
50
+def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
51
+ """Stream typed ledger rows without persisting or calculating values."""
52
+
53
+ inspection = inspect_xlsx(content, document_type="general_ledger")
54
+ workbook = load_workbook(
55
+ BytesIO(content), read_only=True, data_only=True, keep_links=False
56
+ )
57
+ try:
58
+ worksheet = workbook[inspection.data_sheet]
59
+ header_values = next(
60
+ worksheet.iter_rows(
61
+ min_row=inspection.header_row,
62
+ max_row=inspection.header_row,
63
+ values_only=True,
64
+ )
65
+ )
66
+ indexes = {
67
+ str(value).strip(): index
68
+ for index, value in enumerate(header_values)
69
+ if value is not None
70
+ }
71
+
72
+ for row_number, values in enumerate(
73
+ worksheet.iter_rows(
74
+ min_row=inspection.header_row + 1, values_only=True
75
+ ),
76
+ start=inspection.header_row + 1,
77
+ ):
78
+ if not any(value is not None for value in values):
79
+ continue
80
+
81
+ def value(field: str):
82
+ return values[indexes[_FIELDS[field]]]
83
+
84
+ yield LedgerRecord(
85
+ row_number=row_number,
86
+ account_code=_required_code(value("account_code"), row_number, "حساب"),
87
+ account_name=_required_text(
88
+ value("account_name"), row_number, "ACCOUNT_NAME"
89
+ ),
90
+ source_year=_required_year(value("source_year"), row_number),
91
+ entry_type=_required_text(value("entry_type"), row_number, "نوع"),
92
+ t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
93
+ t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
94
+ t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
95
+ t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
96
+ opening=_required_decimal(value("opening"), row_number, "OPENING"),
97
+ debit=_required_decimal(value("debit"), row_number, "Debit"),
98
+ credit=_required_decimal(value("credit"), row_number, "Credit"),
99
+ closing=_required_decimal(value("closing"), row_number, "CLOSING"),
100
+ )
101
+ finally:
102
+ workbook.close()
103
+
104
+
105
+def _required_text(value: object, row_number: int, field: str) -> str:
106
+ text = str(value).strip() if value is not None else ""
107
+ if not text:
108
+ raise LedgerParseError(f"row {row_number}: {field} is required")
109
+ return text
110
+
111
+
112
+def _required_year(value: object, row_number: int) -> int:
113
+ parsed = _required_decimal(value, row_number, "year")
114
+ if parsed != parsed.to_integral_value() or parsed <= 0:
115
+ raise LedgerParseError(f"row {row_number}: year must be a positive integer")
116
+ return int(parsed)
117
+
118
+
119
+def _required_code(value: object, row_number: int, field: str) -> str:
120
+ code = _optional_code(value, row_number, field)
121
+ if code is None:
122
+ raise LedgerParseError(f"row {row_number}: {field} is required")
123
+ return code
124
+
125
+
126
+def _optional_code(value: object, row_number: int, field: str) -> str | None:
127
+ if value is None:
128
+ return None
129
+ if isinstance(value, bool):
130
+ raise LedgerParseError(f"row {row_number}: {field} is not a valid code")
131
+ if isinstance(value, str):
132
+ code = value.strip()
133
+ return code or None
134
+ parsed = _required_decimal(value, row_number, field)
135
+ if parsed != parsed.to_integral_value():
136
+ raise LedgerParseError(f"row {row_number}: {field} must be an integer code")
137
+ return str(int(parsed))
138
+
139
+
140
+def _required_decimal(value: object, row_number: int, field: str) -> Decimal:
141
+ if value is None or isinstance(value, bool):
142
+ raise LedgerParseError(f"row {row_number}: {field} is required and numeric")
143
+ candidate = str(value).strip().replace(",", "").replace("٬", "")
144
+ try:
145
+ parsed = Decimal(candidate)
146
+ except (InvalidOperation, ValueError) as exc:
147
+ raise LedgerParseError(f"row {row_number}: {field} is not numeric") from exc
148
+ if not parsed.is_finite():
149
+ raise LedgerParseError(f"row {row_number}: {field} must be finite")
150
+ return parsed
backend/src/aram_backend/workbook_inspection.py
new
+136
@@ -0,0 +1,136 @@
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
+ {
34
+ "حساب",
35
+ "ACCOUNT_NAME",
36
+ "year",
37
+ "نوع",
38
+ "T1_CODE",
39
+ "T2_CODE",
40
+ "T3_CODE",
41
+ "T4_CODE",
42
+ "OPENING",
43
+ "Debit",
44
+ "Credit",
45
+ "CLOSING",
46
+ }
47
+ ),
48
+ },
49
+ "mapping": {
50
+ "sheet": "Data",
51
+ "header_row": 1,
52
+ "required_headers": frozenset(
53
+ {
54
+ "کد حساب",
55
+ "نوع",
56
+ "کد یادداشت",
57
+ "شرح یادداشت",
58
+ "فرمول یادداشت اصلی",
59
+ "فرمول یادداشت فرعی",
60
+ }
61
+ ),
62
+ },
63
+}
64
+
65
+_PRIMARY_STATEMENT_SHEETS = frozenset(
66
+ {"سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"}
67
+)
68
+
69
+
70
+def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
71
+ """Validate workbook structure without importing rows or evaluating formulas."""
72
+
73
+ if not content:
74
+ raise WorkbookInspectionError("workbook must not be empty")
75
+ if document_type not in {*_TABULAR_PROFILES, "financial_statement"}:
76
+ raise WorkbookInspectionError("document type has no XLSX inspection profile")
77
+
78
+ try:
79
+ workbook = load_workbook(
80
+ BytesIO(content), read_only=True, data_only=False, keep_links=False
81
+ )
82
+ except (BadZipFile, InvalidFileException, OSError, ValueError) as exc:
83
+ raise WorkbookInspectionError("invalid or unreadable XLSX workbook") from exc
84
+
85
+ try:
86
+ sheet_names = tuple(workbook.sheetnames)
87
+ if len(sheet_names) > MAX_WORKSHEETS:
88
+ raise WorkbookInspectionError("workbook contains too many worksheets")
89
+
90
+ if document_type == "financial_statement":
91
+ missing = _PRIMARY_STATEMENT_SHEETS.difference(sheet_names)
92
+ if missing:
93
+ raise WorkbookInspectionError(
94
+ f"financial statement workbook is missing sheets: {sorted(missing)}"
95
+ )
96
+ return WorkbookInspection(
97
+ document_type=document_type,
98
+ sheet_names=sheet_names,
99
+ data_sheet=None,
100
+ header_row=None,
101
+ headers=(),
102
+ )
103
+
104
+ profile = _TABULAR_PROFILES[document_type]
105
+ sheet_name = profile["sheet"]
106
+ if sheet_name not in workbook:
107
+ raise WorkbookInspectionError(f"required worksheet is missing: {sheet_name}")
108
+
109
+ worksheet = workbook[sheet_name]
110
+ header_row = profile["header_row"]
111
+ values = next(
112
+ worksheet.iter_rows(
113
+ min_row=header_row,
114
+ max_row=header_row,
115
+ max_col=min(worksheet.max_column, MAX_HEADER_COLUMNS),
116
+ values_only=True,
117
+ ),
118
+ (),
119
+ )
120
+ headers = tuple(str(value).strip() for value in values if value is not None)
121
+ if len(headers) != len(set(headers)):
122
+ raise WorkbookInspectionError("header row contains duplicate names")
123
+
124
+ missing = profile["required_headers"].difference(headers)
125
+ if missing:
126
+ raise WorkbookInspectionError(f"required headers are missing: {sorted(missing)}")
127
+
128
+ return WorkbookInspection(
129
+ document_type=document_type,
130
+ sheet_names=sheet_names,
131
+ data_sheet=sheet_name,
132
+ header_row=header_row,
133
+ headers=headers,
134
+ )
135
+ finally:
136
+ workbook.close()
backend/tests/test_ingestion.py
new
+167
@@ -0,0 +1,167 @@
1
+import hashlib
2
+
3
+import pytest
4
+
5
+from aram_backend.ingestion import SourceRegistrationError, register_source_document
6
+from aram_backend.models import Company, FiscalYear, FiscalYearStatus, SourceDocument
7
+
8
+
9
+def make_year(session, year=1404):
10
+ company = Company(code=f"ING-{year}", name="Ingestion Test Company")
11
+ fiscal_year = FiscalYear(company=company, year=year)
12
+ session.add(company)
13
+ session.commit()
14
+ return fiscal_year
15
+
16
+
17
+def test_registers_hash_and_metadata_without_source_payload(session):
18
+ year = make_year(session)
19
+ payload = b"account_code,amount\n1000,125\n"
20
+
21
+ source = register_source_document(
22
+ session,
23
+ year_id=year.id,
24
+ filename="ledger.csv",
25
+ document_type="general_ledger",
26
+ content=payload,
27
+ )
28
+ session.commit()
29
+
30
+ assert source.file_hash == hashlib.sha256(payload).hexdigest()
31
+ assert source.filename == "ledger.csv"
32
+ assert not hasattr(source, "content")
33
+
34
+
35
+def test_registration_is_idempotent_within_a_year(session):
36
+ year = make_year(session)
37
+ arguments = {
38
+ "year_id": year.id,
39
+ "filename": "trial-balance.xlsx",
40
+ "document_type": "trial_balance",
41
+ "content": b"safe-test-bytes",
42
+ }
43
+
44
+ first = register_source_document(session, **arguments)
45
+ session.commit()
46
+ second = register_source_document(session, **arguments)
47
+ session.commit()
48
+
49
+ assert second.id == first.id
50
+ assert session.query(SourceDocument).count() == 1
51
+
52
+
53
+def test_same_source_is_isolated_between_fiscal_years(session):
54
+ first_year = make_year(session, 1403)
55
+ second_year = make_year(session, 1404)
56
+ payload = b"same-source"
57
+
58
+ first = register_source_document(
59
+ session,
60
+ year_id=first_year.id,
61
+ filename="source.csv",
62
+ document_type="general_ledger",
63
+ content=payload,
64
+ )
65
+ second = register_source_document(
66
+ session,
67
+ year_id=second_year.id,
68
+ filename="source.csv",
69
+ document_type="general_ledger",
70
+ content=payload,
71
+ )
72
+ session.commit()
73
+
74
+ assert first.id != second.id
75
+ assert first.file_hash == second.file_hash
76
+
77
+
78
+@pytest.mark.parametrize("status", [FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED])
79
+def test_protected_year_rejects_source_registration(session, status):
80
+ year = make_year(session)
81
+ year.status = FiscalYearStatus.APPROVED
82
+ session.commit()
83
+ if status is FiscalYearStatus.LOCKED:
84
+ year.status = FiscalYearStatus.LOCKED
85
+ session.commit()
86
+
87
+ with pytest.raises(SourceRegistrationError, match="cannot accept sources"):
88
+ register_source_document(
89
+ session,
90
+ year_id=year.id,
91
+ filename="blocked.xlsx",
92
+ document_type="financial_statement",
93
+ content=b"blocked",
94
+ )
95
+
96
+
97
+@pytest.mark.parametrize(
98
+ ("filename", "document_type", "content"),
99
+ [
100
+ ("../ledger.csv", "general_ledger", b"data"),
101
+ ("..\\ledger.csv", "general_ledger", b"data"),
102
+ ("ledger.exe", "general_ledger", b"data"),
103
+ ("ledger.csv", "unknown", b"data"),
104
+ ("ledger.csv", "general_ledger", b""),
105
+ ],
106
+)
107
+def test_rejects_unsafe_or_unsupported_source_metadata(
108
+ session, filename, document_type, content
109
+):
110
+ year = make_year(session)
111
+
112
+ with pytest.raises(SourceRegistrationError):
113
+ register_source_document(
114
+ session,
115
+ year_id=year.id,
116
+ filename=filename,
117
+ document_type=document_type,
118
+ content=content,
119
+ )
120
+
121
+def test_duplicate_registration_different_document_type_rejected(session):
122
+ year = make_year(session)
123
+ arguments = {
124
+ "year_id": year.id,
125
+ "filename": "trial-balance.xlsx",
126
+ "document_type": "trial_balance",
127
+ "content": b"safe-test-bytes-conflict",
128
+ }
129
+
130
+ first = register_source_document(session, **arguments)
131
+ session.commit()
132
+
133
+ conflict_arguments = arguments.copy()
134
+ conflict_arguments["document_type"] = "general_ledger"
135
+
136
+ with pytest.raises(SourceRegistrationError, match="document type mismatch for existing content hash"):
137
+ register_source_document(session, **conflict_arguments)
138
+
139
+ session.rollback()
140
+ assert session.query(SourceDocument).count() == 1
141
+ existing = session.query(SourceDocument).first()
142
+ assert existing.document_type == "trial_balance"
143
+ assert existing.filename == "trial-balance.xlsx"
144
+
145
+def test_duplicate_registration_different_filename_rejected(session):
146
+ year = make_year(session)
147
+ arguments = {
148
+ "year_id": year.id,
149
+ "filename": "trial-balance.xlsx",
150
+ "document_type": "trial_balance",
151
+ "content": b"safe-test-bytes-conflict-2",
152
+ }
153
+
154
+ first = register_source_document(session, **arguments)
155
+ session.commit()
156
+
157
+ conflict_arguments = arguments.copy()
158
+ conflict_arguments["filename"] = "other.xlsx"
159
+
160
+ with pytest.raises(SourceRegistrationError, match="filename mismatch for existing content hash"):
161
+ register_source_document(session, **conflict_arguments)
162
+
163
+ session.rollback()
164
+ assert session.query(SourceDocument).count() == 1
165
+ existing = session.query(SourceDocument).first()
166
+ assert existing.document_type == "trial_balance"
167
+ assert existing.filename == "trial-balance.xlsx"
backend/tests/test_ledger_parser.py
new
+90
@@ -0,0 +1,90 @@
1
+from decimal import Decimal
2
+from io import BytesIO
3
+
4
+import pytest
5
+from openpyxl import Workbook
6
+
7
+from aram_backend.ledger_parser import LedgerParseError, parse_general_ledger
8
+
9
+
10
+HEADERS = [
11
+ "حساب",
12
+ "ACCOUNT_NAME",
13
+ "year",
14
+ "نوع",
15
+ "T1_CODE",
16
+ "T2_CODE",
17
+ "T3_CODE",
18
+ "T4_CODE",
19
+ "OPENING",
20
+ "Debit",
21
+ "Credit",
22
+ "CLOSING",
23
+]
24
+
25
+
26
+def ledger_bytes(*rows):
27
+ workbook = Workbook()
28
+ sheet = workbook.active
29
+ sheet.title = "Source"
30
+ sheet.append(["source ledger"])
31
+ sheet.append(HEADERS)
32
+ for row in rows:
33
+ sheet.append(row)
34
+ output = BytesIO()
35
+ workbook.save(output)
36
+ workbook.close()
37
+ return output.getvalue()
38
+
39
+
40
+def valid_row(**overrides):
41
+ values = {
42
+ "حساب": "0001",
43
+ "ACCOUNT_NAME": "Test account",
44
+ "year": "1404",
45
+ "نوع": "O",
46
+ "T1_CODE": None,
47
+ "T2_CODE": None,
48
+ "T3_CODE": None,
49
+ "T4_CODE": None,
50
+ "OPENING": "0",
51
+ "Debit": "0",
52
+ "Credit": "0",
53
+ "CLOSING": "0",
54
+ }
55
+ values.update(overrides)
56
+ return [values[header] for header in HEADERS]
57
+
58
+
59
+def test_streams_typed_records_without_calculation():
60
+ records = list(parse_general_ledger(ledger_bytes(valid_row())))
61
+
62
+ assert len(records) == 1
63
+ assert records[0].row_number == 3
64
+ assert records[0].account_code == "0001"
65
+ assert records[0].opening == Decimal("0")
66
+ assert records[0].closing == Decimal("0")
67
+
68
+
69
+def test_skips_completely_blank_rows():
70
+ records = list(parse_general_ledger(ledger_bytes([None] * len(HEADERS), valid_row())))
71
+
72
+ assert [record.row_number for record in records] == [4]
73
+
74
+
75
+@pytest.mark.parametrize(
76
+ ("field", "invalid", "message"),
77
+ [
78
+ ("Debit", "NaN", "must be finite"),
79
+ ("Credit", "Infinity", "must be finite"),
80
+ ("CLOSING", "not-numeric", "is not numeric"),
81
+ ("ACCOUNT_NAME", None, "is required"),
82
+ ("year", "1404.5", "positive integer"),
83
+ ("T1_CODE", 12.5, "integer code"),
84
+ ],
85
+)
86
+def test_rejects_unsafe_or_incomplete_rows(field, invalid, message):
87
+ content = ledger_bytes(valid_row(**{field: invalid}))
88
+
89
+ with pytest.raises(LedgerParseError, match=message):
90
+ list(parse_general_ledger(content))
backend/tests/test_workbook_inspection.py
new
+91
@@ -0,0 +1,91 @@
1
+from io import BytesIO
2
+
3
+import pytest
4
+from openpyxl import Workbook
5
+
6
+from aram_backend.workbook_inspection import WorkbookInspectionError, inspect_xlsx
7
+
8
+
9
+def workbook_bytes(sheet_rows):
10
+ workbook = Workbook()
11
+ default = workbook.active
12
+ workbook.remove(default)
13
+ for sheet_name, rows in sheet_rows:
14
+ sheet = workbook.create_sheet(sheet_name)
15
+ for row in rows:
16
+ sheet.append(row)
17
+ output = BytesIO()
18
+ workbook.save(output)
19
+ workbook.close()
20
+ return output.getvalue()
21
+
22
+
23
+def test_inspects_accepted_general_ledger_structure():
24
+ headers = [
25
+ "حساب",
26
+ "ACCOUNT_NAME",
27
+ "year",
28
+ "نوع",
29
+ "T1_CODE",
30
+ "T2_CODE",
31
+ "T3_CODE",
32
+ "T4_CODE",
33
+ "OPENING",
34
+ "Debit",
35
+ "Credit",
36
+ "CLOSING",
37
+ ]
38
+ content = workbook_bytes([("Source", [["source ledger"], headers])])
39
+
40
+ result = inspect_xlsx(content, document_type="general_ledger")
41
+
42
+ assert result.data_sheet == "Source"
43
+ assert result.header_row == 2
44
+ assert result.headers == tuple(headers)
45
+
46
+
47
+def test_inspects_accepted_mapping_structure():
48
+ headers = [
49
+ "کد حساب",
50
+ "نوع",
51
+ "کد یادداشت",
52
+ "شرح یادداشت",
53
+ "فرمول یادداشت اصلی",
54
+ "فرمول یادداشت فرعی",
55
+ ]
56
+ content = workbook_bytes([("Data", [headers])])
57
+
58
+ result = inspect_xlsx(content, document_type="mapping")
59
+
60
+ assert result.data_sheet == "Data"
61
+ assert result.header_row == 1
62
+
63
+
64
+def test_inspects_primary_financial_statement_sheet_set():
65
+ names = ["سودوزيان", "وضعيت مالي", "حقوق مالكانه", "جريان هاي نقدي"]
66
+ content = workbook_bytes([(name, []) for name in names])
67
+
68
+ result = inspect_xlsx(content, document_type="financial_statement")
69
+
70
+ assert result.sheet_names == tuple(names)
71
+ assert result.headers == ()
72
+
73
+
74
+@pytest.mark.parametrize(
75
+ "content",
76
+ [
77
+ workbook_bytes([("Wrong", [["not the expected sheet"]])]),
78
+ workbook_bytes([("Source", [["source ledger"], ["حساب"]])]),
79
+ b"not-an-xlsx-file",
80
+ ],
81
+)
82
+def test_rejects_invalid_or_mismatched_workbooks(content):
83
+ with pytest.raises(WorkbookInspectionError):
84
+ inspect_xlsx(content, document_type="general_ledger")
85
+
86
+
87
+def test_rejects_document_type_without_an_xlsx_profile():
88
+ content = workbook_bytes([("Sheet", [])])
89
+
90
+ with pytest.raises(WorkbookInspectionError, match="no XLSX inspection profile"):
91
+ inspect_xlsx(content, document_type="trial_balance")