1
+"""Acceptance tests for Phase-0 debts D-04, D-05, D-11 and real-data evidence.
2
+
3
+These prove the booklet's required fixes at the parser/inspection level and
4
+record the evidence behind ADR-013 (sign) and ADR-014 (hierarchy) on a bounded
5
+sample of the canonical 1404 ledger (read-only; skipped if data is absent).
6
+"""
7
+
8
+from __future__ import annotations
9
+
10
+import io
11
+import re
12
+import zipfile
13
+from decimal import Decimal
14
+from pathlib import Path
15
+
16
+import pytest
17
+from openpyxl import Workbook, load_workbook
18
+
19
+from aram_backend.domain.controls import BalanceRow, check_c01
20
+from aram_backend.domain.hierarchy import ledger_to_pilot
21
+from aram_backend.ledger_parser import parse_general_ledger
22
+from aram_backend.workbook_inspection import inspect_xlsx
23
+
24
+GL_HEADERS = [
25
+ "حساب", "ACCOUNT_NAME", "year", "نوع",
26
+ "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
27
+ "OPENING", "Debit", "Credit", "CLOSING",
28
+]
29
+REPO_ROOT = Path(__file__).resolve().parents[2]
30
+LEDGER_1404 = REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
31
+
32
+
33
+def _gl_bytes(*rows, headers=None):
34
+ wb = Workbook()
35
+ ws = wb.active
36
+ ws.title = "Source"
37
+ ws.append(["source ledger"])
38
+ ws.append(headers or GL_HEADERS)
39
+ for r in rows:
40
+ ws.append(r)
41
+ buf = io.BytesIO()
42
+ wb.save(buf)
43
+ wb.close()
44
+ return buf.getvalue()
45
+
46
+
47
+def _strip_dimension(raw: bytes) -> bytes:
48
+ zin = zipfile.ZipFile(io.BytesIO(raw))
49
+ out = io.BytesIO()
50
+ zout = zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED)
51
+ for item in zin.infolist():
52
+ data = zin.read(item.filename)
53
+ if item.filename == "xl/worksheets/sheet1.xml":
54
+ data = re.sub(rb"<dimension[^>]*/>", b"", data)
55
+ zout.writestr(item, data)
56
+ zout.close()
57
+ return out.getvalue()
58
+
59
+
60
+def _row(code="0101", opening=0, debit=0, credit=0, closing=0):
61
+ return [code, "x", 1404, "O", None, None, None, None, opening, debit, credit, closing]
62
+
63
+
64
+class TestD04CodesAndMoney:
65
+ def test_text_leading_zero_code_preserved(self):
66
+ rec = next(parse_general_ledger(_gl_bytes(_row(code="0101"))))
67
+ assert rec.account_code == "0101"
68
+
69
+ def test_persian_digit_code_normalized_to_text(self):
70
+ rec = next(parse_general_ledger(_gl_bytes(_row(code="۰۱۰۱"))))
71
+ assert rec.account_code == "0101"
72
+
73
+ def test_integer_code_exact(self):
74
+ rec = next(parse_general_ledger(_gl_bytes(_row(code=8348))))
75
+ assert rec.account_code == "8348"
76
+
77
+ def test_float_money_exact_roundtrip(self):
78
+ # repr path: exact shortest round-trip, not the binary expansion.
79
+ rec = next(parse_general_ledger(_gl_bytes(_row(debit=1234.56789012345))))
80
+ assert rec.debit == Decimal("1234.56789012345")
81
+
82
+
83
+class TestD05Normalization:
84
+ def test_persian_financial_statement_sheets_accepted(self):
85
+ # Persian ی/ک variants of the canonical Arabic sheet names.
86
+ names = ["سودوزیان", "وضعیت مالی", "حقوق مالکانه", "جریان های نقدی"]
87
+ wb = Workbook()
88
+ wb.remove(wb.active)
89
+ for n in names:
90
+ wb.create_sheet(n)
91
+ buf = io.BytesIO()
92
+ wb.save(buf)
93
+ wb.close()
94
+ result = inspect_xlsx(buf.getvalue(), document_type="financial_statement")
95
+ assert result.sheet_names == tuple(names)
96
+
97
+ def test_arabic_kaf_mapping_headers_accepted(self):
98
+ # "كد حساب" with Arabic kaf must match the Persian "کد حساب" requirement.
99
+ headers = ["كد حساب", "نوع", "كد یادداشت", "شرح یادداشت",
100
+ "فرمول یادداشت اصلی", "فرمول یادداشت فرعی"]
101
+ wb = Workbook()
102
+ ws = wb.active
103
+ ws.title = "Data"
104
+ ws.append(headers)
105
+ buf = io.BytesIO()
106
+ wb.save(buf)
107
+ wb.close()
108
+ result = inspect_xlsx(buf.getvalue(), document_type="mapping")
109
+ assert result.data_sheet == "Data"
110
+
111
+
112
+class TestD11NoDimension:
113
+ def test_dimensionless_file_inspects_and_parses(self):
114
+ raw = _strip_dimension(_gl_bytes(_row()))
115
+ # Confirm the fixture really has no dimension (max_column is None).
116
+ probe = load_workbook(io.BytesIO(raw), read_only=True)
117
+ assert probe["Source"].max_column is None
118
+ probe.close()
119
+ result = inspect_xlsx(raw, document_type="general_ledger")
120
+ assert result.data_sheet == "Source"
121
+ rec = next(parse_general_ledger(raw))
122
+ assert rec.account_code == "0101"
123
+
124
+
125
+@pytest.mark.skipif(not LEDGER_1404.exists(), reason="canonical ledger not present")
126
+class TestRealDataEvidence:
127
+ """Bounded read-only evidence for ADR-013 (sign) and ADR-014 (hierarchy)."""
128
+
129
+ def _sample(self, limit=20000):
130
+ wb = load_workbook(LEDGER_1404, read_only=True, data_only=True, keep_links=False)
131
+ ws = wb["Source"]
132
+ rows = ws.iter_rows(values_only=True)
133
+ next(rows)
134
+ header = next(rows)
135
+ idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
136
+ out = []
137
+ for vals in rows:
138
+ if not any(v is not None for v in vals):
139
+ continue
140
+ out.append((idx, vals))
141
+ if len(out) >= limit:
142
+ break
143
+ wb.close()
144
+ return out
145
+
146
+ def test_hierarchy_invariant_on_sample(self):
147
+ for idx, vals in self._sample():
148
+ kol = vals[idx["kol"]]
149
+ hesab = vals[idx["حساب"]]
150
+ levels = ledger_to_pilot(kol=kol, hesab=hesab, row=0)
151
+ assert levels.subsidiary_code == str(hesab).strip()
152
+ assert levels.general_code == str(kol).strip()
153
+
154
+ def test_debit_positive_sign_dominates(self):
155
+ debit_pos = 0
156
+ credit_pos = 0
157
+ n = 0
158
+ for idx, vals in self._sample():
159
+ o = Decimal(str(vals[idx["OPENING"]] or 0))
160
+ d = Decimal(str(vals[idx["Debit"]] or 0))
161
+ c = Decimal(str(vals[idx["Credit"]] or 0))
162
+ cl = Decimal(str(vals[idx["CLOSING"]] or 0))
163
+ n += 1
164
+ if o + d - c - cl == 0:
165
+ debit_pos += 1
166
+ if o - d + c - cl == 0:
167
+ credit_pos += 1
168
+ assert n > 0
169
+ assert debit_pos >= credit_pos
170
+ assert debit_pos >= 0.99 * n
171
+ # And the domain control agrees with the chosen convention.
172
+ rows = [BalanceRow(1, "x", Decimal(0), Decimal(0), Decimal(0), Decimal(0))]
173
+ assert check_c01(rows).passed