arena/094f314c-aram
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 188 lines 6.34 KB
Raw
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 "حساب",
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 REPO_ROOT = Path(__file__).resolve().parents[2]
39 LEDGER_1404 = REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
40
41
42 def _gl_bytes(*rows, headers=None):
43 wb = Workbook()
44 ws = wb.active
45 ws.title = "Source"
46 ws.append(["source ledger"])
47 ws.append(headers or GL_HEADERS)
48 for r in rows:
49 ws.append(r)
50 buf = io.BytesIO()
51 wb.save(buf)
52 wb.close()
53 return buf.getvalue()
54
55
56 def _strip_dimension(raw: bytes) -> bytes:
57 zin = zipfile.ZipFile(io.BytesIO(raw))
58 out = io.BytesIO()
59 zout = zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED)
60 for item in zin.infolist():
61 data = zin.read(item.filename)
62 if item.filename == "xl/worksheets/sheet1.xml":
63 data = re.sub(rb"<dimension[^>]*/>", b"", data)
64 zout.writestr(item, data)
65 zout.close()
66 return out.getvalue()
67
68
69 def _row(code="0101", opening=0, debit=0, credit=0, closing=0):
70 return [code, "x", 1404, "O", None, None, None, None, opening, debit, credit, closing]
71
72
73 class TestD04CodesAndMoney:
74 def test_text_leading_zero_code_preserved(self):
75 rec = next(parse_general_ledger(_gl_bytes(_row(code="0101"))))
76 assert rec.account_code == "0101"
77
78 def test_persian_digit_code_normalized_to_text(self):
79 rec = next(parse_general_ledger(_gl_bytes(_row(code="۰۱۰۱"))))
80 assert rec.account_code == "0101"
81
82 def test_integer_code_exact(self):
83 rec = next(parse_general_ledger(_gl_bytes(_row(code=8348))))
84 assert rec.account_code == "8348"
85
86 def test_float_money_exact_roundtrip(self):
87 # repr path: exact shortest round-trip, not the binary expansion.
88 rec = next(parse_general_ledger(_gl_bytes(_row(debit=1234.56789012345))))
89 assert rec.debit == Decimal("1234.56789012345")
90
91
92 class TestD05Normalization:
93 def test_persian_financial_statement_sheets_accepted(self):
94 # Persian ی/ک variants of the canonical Arabic sheet names.
95 names = ["سودوزیان", "وضعیت مالی", "حقوق مالکانه", "جریان های نقدی"]
96 wb = Workbook()
97 wb.remove(wb.active)
98 for n in names:
99 wb.create_sheet(n)
100 buf = io.BytesIO()
101 wb.save(buf)
102 wb.close()
103 result = inspect_xlsx(buf.getvalue(), document_type="financial_statement")
104 assert result.sheet_names == tuple(names)
105
106 def test_arabic_kaf_mapping_headers_accepted(self):
107 # "كد حساب" with Arabic kaf must match the Persian "کد حساب" requirement.
108 headers = [
109 "كد حساب",
110 "نوع",
111 "كد یادداشت",
112 "شرح یادداشت",
113 "فرمول یادداشت اصلی",
114 "فرمول یادداشت فرعی",
115 ]
116 wb = Workbook()
117 ws = wb.active
118 ws.title = "Data"
119 ws.append(headers)
120 buf = io.BytesIO()
121 wb.save(buf)
122 wb.close()
123 result = inspect_xlsx(buf.getvalue(), document_type="mapping")
124 assert result.data_sheet == "Data"
125
126
127 class TestD11NoDimension:
128 def test_dimensionless_file_inspects_and_parses(self):
129 raw = _strip_dimension(_gl_bytes(_row()))
130 # Confirm the fixture really has no dimension (max_column is None).
131 probe = load_workbook(io.BytesIO(raw), read_only=True)
132 assert probe["Source"].max_column is None
133 probe.close()
134 result = inspect_xlsx(raw, document_type="general_ledger")
135 assert result.data_sheet == "Source"
136 rec = next(parse_general_ledger(raw))
137 assert rec.account_code == "0101"
138
139
140 @pytest.mark.skipif(not LEDGER_1404.exists(), reason="canonical ledger not present")
141 class TestRealDataEvidence:
142 """Bounded read-only evidence for ADR-013 (sign) and ADR-014 (hierarchy)."""
143
144 def _sample(self, limit=20000):
145 wb = load_workbook(LEDGER_1404, read_only=True, data_only=True, keep_links=False)
146 ws = wb["Source"]
147 rows = ws.iter_rows(values_only=True)
148 next(rows)
149 header = next(rows)
150 idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
151 out = []
152 for vals in rows:
153 if not any(v is not None for v in vals):
154 continue
155 out.append((idx, vals))
156 if len(out) >= limit:
157 break
158 wb.close()
159 return out
160
161 def test_hierarchy_invariant_on_sample(self):
162 for idx, vals in self._sample():
163 kol = vals[idx["kol"]]
164 hesab = vals[idx["حساب"]]
165 levels = ledger_to_pilot(kol=kol, hesab=hesab, row=0)
166 assert levels.subsidiary_code == str(hesab).strip()
167 assert levels.general_code == str(kol).strip()
168
169 def test_debit_positive_sign_dominates(self):
170 debit_pos = 0
171 credit_pos = 0
172 n = 0
173 for idx, vals in self._sample():
174 o = Decimal(str(vals[idx["OPENING"]] or 0))
175 d = Decimal(str(vals[idx["Debit"]] or 0))
176 c = Decimal(str(vals[idx["Credit"]] or 0))
177 cl = Decimal(str(vals[idx["CLOSING"]] or 0))
178 n += 1
179 if o + d - c - cl == 0:
180 debit_pos += 1
181 if o - d + c - cl == 0:
182 credit_pos += 1
183 assert n > 0
184 assert debit_pos >= credit_pos
185 assert debit_pos >= 0.99 * n
186 # And the domain control agrees with the chosen convention.
187 rows = [BalanceRow(1, "x", Decimal(0), Decimal(0), Decimal(0), Decimal(0))]
188 assert check_c01(rows).passed