@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/setup-node-6
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-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 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 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 251 lines 10.1 KB
Raw
1 from __future__ import annotations
2
3 from decimal import Decimal
4 from io import BytesIO
5
6 import pytest
7 from openpyxl import load_workbook
8
9 from aram_backend.pilot_engine import (
10 PilotModelError,
11 build_report,
12 export_report_workbook,
13 parse_pilot_model,
14 )
15 from test_pilot_workbook import workbook_bytes
16
17
18 def account_row(code, name, closing, *, debit=0, credit=0, source_row=2):
19 opening = closing - debit + credit
20 return (
21 "C1", 1404, code, "کل", None, None, None, None, None, None, None,
22 None, None, None, code, name, opening, debit, credit, closing,
23 source_row, "Draft", 0,
24 )
25
26
27 def note_row(statement, section, number, title):
28 return ("C1", 1404, statement, section, number, title, None, None)
29
30
31 def mapping_row(mid, code, statement, section, number, *, approval="Approved"):
32 reviewed = approval in {"Reviewed", "Approved"}
33 return (
34 mid, "C1", 1404, code, "General", code, None, None, None, None, None,
35 statement, section, number, None, 1, approval,
36 "tester" if reviewed else None, "2026-12-03" if reviewed else None,
37 "test", None, "Valid" if approval == "Approved" else "Pending",
38 )
39
40
41 BALANCED_NOTES = [
42 note_row("BS", "Assets", "01", "نقد"),
43 note_row("BS", "Liabilities", "02", "پرداختنی"),
44 note_row("BS", "Equity", "03", "سرمایه"),
45 note_row("IS", "Revenue", "04", "فروش"),
46 note_row("IS", "Expenses", "05", "هزینه"),
47 ]
48 BALANCED_ACCOUNTS = [
49 account_row("10", "نقد", 100, debit=150, credit=50, source_row=10),
50 account_row("20", "پرداختنی", -60, credit=60, source_row=11),
51 account_row("30", "سرمایه", -30, credit=30, source_row=12),
52 account_row("40", "فروش", -20, credit=20, source_row=13),
53 account_row("50", "هزینه", 10, debit=10, source_row=14),
54 ]
55 BALANCED_MAPPINGS = [
56 mapping_row("M1", "10", "BS", "Assets", "01"),
57 mapping_row("M2", "20", "BS", "Liabilities", "02"),
58 mapping_row("M3", "30", "BS", "Equity", "03"),
59 mapping_row("M4", "40", "IS", "Revenue", "04"),
60 mapping_row("M5", "50", "IS", "Expenses", "05"),
61 ]
62
63
64 def balanced_rows():
65 return {
66 "Company": [("C1", "شرکت آزمون", 1404, "IRR", "rial", "tester", "Draft")],
67 "Accounts": list(BALANCED_ACCOUNTS),
68 "Notes": list(BALANCED_NOTES),
69 "Mapping": list(BALANCED_MAPPINGS),
70 }
71
72
73 def build_balanced_workbook() -> bytes:
74 return workbook_bytes(balanced_rows())
75
76
77 def test_balanced_workbook_produces_complete_approved_report():
78 model = parse_pilot_model(build_balanced_workbook())
79 report = build_report(model, model.mappings)
80 assert report["status"] == {
81 "label": "COMPLETE_APPROVED", "complete": True, "all_mappings_approved": True,
82 }
83 assert report["totals"]["assets"] == "100"
84 assert report["totals"]["liabilities"] == "60"
85 assert report["totals"]["equity"] == "30"
86 assert report["totals"]["liabilities_and_equity"] == "90"
87 assert report["totals"]["profit"] == "10"
88 assert all(check["passed"] for check in report["checks"])
89 assert report["exceptions"] == []
90 assets = report["statements"]["BS"]["sections"][0]
91 assert assets["total"] == "100"
92 line = assets["lines"][0]
93 assert line["accounts"][0]["source_row"] == 10
94 assert line["accounts"][0]["display"] == "100"
95
96
97 def test_unmapped_account_blocks_completeness_and_enters_queue():
98 rows = balanced_rows()
99 rows["Mapping"] = rows["Mapping"][:-1] # expense account unmapped
100 model = parse_pilot_model(workbook_bytes(rows))
101 report = build_report(model, model.mappings)
102 assert report["status"]["label"] == "INCOMPLETE"
103 assert [e["code"] for e in report["exceptions"]] == ["UNMAPPED_ACCOUNT"]
104 assert report["exceptions"][0]["account_code"] == "50"
105 failed = {c["code"] for c in report["checks"] if not c["passed"]}
106 assert failed == {"FULL_COVERAGE", "ACCOUNTING_EQUATION"}
107
108
109 def test_deferred_cf_and_eq_targets_are_reported_not_rendered():
110 rows = balanced_rows()
111 rows["Notes"].append(note_row("CF", "Operating", "06", "جریان نقدی"))
112 rows["Mapping"][4] = mapping_row("M5", "50", "CF", "Operating", "06")
113 model = parse_pilot_model(workbook_bytes(rows))
114 report = build_report(model, model.mappings)
115 assert report["status"]["label"] == "INCOMPLETE"
116 assert report["exceptions"][0]["code"] == "DEFERRED_STATEMENT"
117 assert set(report["statements"]) == {"BS", "IS"}
118
119
120 def test_unknown_section_fails_closed_instead_of_guessing():
121 rows = balanced_rows()
122 rows["Notes"].append(note_row("BS", "Mystery", "06", "بخش ناشناخته"))
123 rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Mystery", "06")
124 model = parse_pilot_model(workbook_bytes(rows))
125 report = build_report(model, model.mappings)
126 assert report["exceptions"][0]["code"] == "UNSUPPORTED_SECTION"
127 assert report["statements"]["BS"]["sections"][0]["total"] == "0"
128
129
130 def test_conflicting_mappings_are_excluded_until_explicit_resolution():
131 rows = balanced_rows()
132 rows["Notes"].append(note_row("BS", "Assets", "06", "مقصد دوم"))
133 rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "06"))
134 model = parse_pilot_model(workbook_bytes(rows))
135 assert "10" in model.conflicts and "10" not in model.mappings
136 report = build_report(model, model.mappings)
137 assert report["exceptions"][0]["code"] == "MAPPING_CONFLICT"
138
139 # An explicit workbench mapping resolves the conflict, with provenance.
140 from aram_backend.pilot_engine import MappingEntry
141 resolved = dict(model.mappings)
142 resolved["10"] = MappingEntry(
143 "10", "BS", "Assets", "01", "", "Draft", "", "workbench", "WB-1"
144 )
145 report = build_report(model, resolved)
146 assert all(e["code"] != "MAPPING_CONFLICT" for e in report["exceptions"])
147 assert report["statements"]["BS"]["sections"][0]["total"] == "100"
148
149
150 def test_identical_duplicate_mappings_are_deduplicated():
151 rows = balanced_rows()
152 rows["Mapping"].append(mapping_row("M6", "10", "BS", "Assets", "01"))
153 model = parse_pilot_model(workbook_bytes(rows))
154 assert not model.conflicts
155 report = build_report(model, model.mappings)
156 assert report["coverage"]["mapped_accounts"] == 5
157 assert report["status"]["complete"]
158
159
160 def test_draft_mappings_keep_output_in_draft_state():
161 rows = balanced_rows()
162 rows["Mapping"][0] = mapping_row("M1", "10", "BS", "Assets", "01", approval="Draft")
163 model = parse_pilot_model(workbook_bytes(rows))
164 report = build_report(model, model.mappings)
165 assert report["status"] == {
166 "label": "COMPLETE_DRAFT", "complete": True, "all_mappings_approved": False,
167 }
168
169
170 def test_decimal_precision_is_preserved_as_exact_strings():
171 rows = balanced_rows()
172 rows["Accounts"] = [
173 account_row("10", "نقد", Decimal("10.10")),
174 account_row("20", "پرداختنی", Decimal("-6.06")),
175 account_row("30", "سرمایه", Decimal("-3.03")),
176 account_row("40", "فروش", Decimal("-2.02")),
177 account_row("50", "هزینه", Decimal("1.01")),
178 ]
179 model = parse_pilot_model(workbook_bytes(rows))
180 report = build_report(model, model.mappings)
181 # Excel numeric storage drops trailing zeros (10.10 -> 10.1) but the
182 # decimal value itself must survive exactly, with no float drift.
183 assert report["totals"]["assets"] == "10.1"
184 assert report["totals"]["profit"] == "1.01"
185 assert report["totals"]["liabilities_and_equity"] == "9.09"
186 assert report["status"]["complete"]
187
188
189 def test_invalid_workbook_raises_typed_error_with_issues():
190 rows = balanced_rows()
191 broken = list(rows["Accounts"][0])
192 broken[19] = 999 # closing no longer ties
193 rows["Accounts"][0] = tuple(broken)
194 with pytest.raises(PilotModelError) as exc:
195 parse_pilot_model(workbook_bytes(rows))
196 assert any(i.code == "NON_ZERO_CLOSING_DELTA" for i in exc.value.issues)
197
198
199 def test_multiple_companies_are_rejected_explicitly():
200 rows = balanced_rows()
201 rows["Company"].append(("C2", "شرکت دوم", 1404, "IRR", "rial", "t", "Draft"))
202 with pytest.raises(PilotModelError) as exc:
203 parse_pilot_model(workbook_bytes(rows))
204 assert exc.value.issues[0].code == "WORKBENCH_SINGLE_COMPANY_REQUIRED"
205
206
207 def test_empty_accounts_never_report_complete():
208 rows = balanced_rows()
209 rows["Accounts"] = []
210 rows["Mapping"] = []
211 model = parse_pilot_model(workbook_bytes(rows))
212 report = build_report(model, model.mappings)
213 assert report["status"]["label"] == "INCOMPLETE"
214 assert not report["checks"][0]["passed"]
215
216
217 def test_report_is_deterministic():
218 data = build_balanced_workbook()
219 first = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
220 second = build_report(parse_pilot_model(data), parse_pilot_model(data).mappings)
221 assert first == second
222
223
224 def test_export_contains_all_sheets_and_exact_provenance():
225 model = parse_pilot_model(build_balanced_workbook())
226 report = build_report(model, model.mappings)
227 trail = [{"at": "2026-12-03T00:00:00+00:00", "actor": "tester", "account_code": "10",
228 "action": "set_mapping", "before": "(بدون نگاشت)", "after": "BS/Assets/01"}]
229 data = export_report_workbook(model, model.mappings, report, trail, "upload")
230 book = load_workbook(BytesIO(data))
231 assert book.sheetnames == [
232 "Info", "Checks", "BalanceSheet", "IncomeStatement",
233 "Coverage", "Exceptions", "AuditTrail",
234 ]
235 info = {row[0]: row[1] for row in book["Info"].iter_rows(min_row=2, values_only=True)}
236 assert info["source_sha256"] == model.source_sha256
237 assert info["status"] == "COMPLETE_APPROVED"
238 amounts = [row[4] for row in book["BalanceSheet"].iter_rows(min_row=2, values_only=True)
239 if row[0] == "note"]
240 assert 100.0 in amounts
241 assert book["Coverage"].max_row == 6 # header + 5 accounts
242 assert book["AuditTrail"].max_row == 2
243 book.close()
244
245
246 def test_engine_never_writes_files(tmp_path, monkeypatch):
247 monkeypatch.chdir(tmp_path)
248 model = parse_pilot_model(build_balanced_workbook())
249 report = build_report(model, model.mappings)
250 export_report_workbook(model, model.mappings, report, [], "demo")
251 assert list(tmp_path.iterdir()) == []