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

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

Synced Dec 3, 15:45 UTC

codex/aram-five-statement-cli-20261031
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 444 lines 18.2 KB
Raw
1 """End-to-end synthetic integration tests for all five ARAM statement engines."""
2 from __future__ import annotations
3
4 from dataclasses import asdict
5 from io import BytesIO
6 import json
7
8 import pytest
9 from openpyxl import Workbook
10
11 from aram_backend.balance_sheet_candidate import BalanceSheetLinePolicy
12 from aram_backend.cash_flow_direct_candidate import (
13 CashAccountPolicy, CashCounterpartPolicy, CashFlowEntry,
14 )
15 from aram_backend.coverage_preview import CoverageError
16 from aram_backend.cross_statement_reconciliation import CashBalanceNoteSelection
17 from aram_backend.equity_changes_candidate import EquityMovementPolicy
18 from aram_backend.income_statement_candidate import IncomeStatementLinePolicy
19 from aram_backend.pilot_workbook import SHEET_HEADERS
20 from aram_backend.reconciliation_review import NoteReference
21 from aram_backend.five_statement_pipeline import build_five_statement_pipeline
22 from aram_backend.five_statement_pipeline_cli import main as pipeline_cli_main
23
24
25 COMPANY = "001"
26 YEAR = 1404
27
28
29 def source_workbook() -> bytes:
30 """One debit-net balanced ledger shared by every candidate builder."""
31 book = Workbook()
32 book.remove(book.active)
33 for name, headers in SHEET_HEADERS.items():
34 book.create_sheet(name).append(list(headers))
35
36 def add(sheet: str, **values: object) -> None:
37 book[sheet].append([values.get(column) for column in SHEET_HEADERS[sheet]])
38
39 add(
40 "Company", company_code=COMPANY, company_name="Synthetic integration only",
41 fiscal_year=YEAR, currency="IRR", unit="Rial", prepared_by="Test fixture",
42 status="Draft",
43 )
44 ledger = (
45 # code, name, opening, debit, credit, closing
46 ("CASH", "Cash", "40", "30", "20", "50"),
47 ("AR", "Receivables", "50", "0", "0", "50"),
48 ("AP", "Payables", "-20", "10", "0", "-10"),
49 ("CAP", "Share capital", "-70", "0", "0", "-70"),
50 ("REV", "Revenue", "0", "0", "40", "-40"),
51 ("EXP", "Cost of revenue", "0", "20", "0", "20"),
52 )
53 for index, (code, name, opening, debit, credit, closing) in enumerate(ledger, 101):
54 add(
55 "Accounts", company_code=COMPANY, fiscal_year=YEAR,
56 general_code=code, general_name=name, account_full_code=code,
57 account_name=name, opening=opening, debit=debit, credit=credit,
58 closing=closing, source_row=index, row_status="Draft",
59 closing_delta="0",
60 )
61
62 notes = (
63 ("BS", "Current assets", "C01", "Cash"),
64 ("BS", "Current assets", "A01", "Receivables"),
65 ("BS", "Current liabilities", "L01", "Payables"),
66 ("BS", "Equity", "E01", "Equity"),
67 ("IS", "Revenue", "R01", "Revenue"),
68 ("IS", "Cost of revenue", "X01", "Cost of revenue"),
69 ("EQ", "Share capital", "E01", "Share capital"),
70 ("EQ", "Current year result", "P01", "Current year result"),
71 )
72 for statement, section, note, title in notes:
73 add(
74 "Notes", company_code=COMPANY, fiscal_year=YEAR,
75 statement=statement, statement_section=section,
76 note_number=note, note_title=title, subnote_code="",
77 subnote_title="",
78 )
79
80 mappings = (
81 ("CASH", "BS", "Current assets", "C01"),
82 ("AR", "BS", "Current assets", "A01"),
83 ("AP", "BS", "Current liabilities", "L01"),
84 ("CAP", "BS", "Equity", "E01"),
85 ("CAP", "EQ", "Share capital", "E01"),
86 ("REV", "IS", "Revenue", "R01"),
87 ("REV", "BS", "Equity", "E01"),
88 ("REV", "EQ", "Current year result", "P01"),
89 ("EXP", "IS", "Cost of revenue", "X01"),
90 ("EXP", "BS", "Equity", "E01"),
91 ("EXP", "EQ", "Current year result", "P01"),
92 )
93 for index, (account, statement, section, note) in enumerate(mappings, 1):
94 add(
95 "Mapping", mapping_id=f"SYNTH-M-{index:02d}",
96 company_code=COMPANY, fiscal_year=YEAR,
97 account_full_code=account, account_level="General",
98 general_code=account, target_statement=statement,
99 statement_section=section, note_number=note, subnote_code="",
100 mapping_version=1, approval_status="Approved",
101 reviewer="Synthetic fixture only", review_date="2026-10-31",
102 source="Synthetic test", notes="Not an authenticated approval",
103 validation_status="Valid",
104 )
105
106 output = BytesIO()
107 book.save(output)
108 book.close()
109 return output.getvalue()
110
111
112 def references() -> tuple[NoteReference, ...]:
113 return (
114 NoteReference("BS", "Current assets", "C01", "", "50", "SYNTH-BS-CASH"),
115 NoteReference("BS", "Current assets", "A01", "", "50", "SYNTH-BS-AR"),
116 NoteReference("BS", "Current liabilities", "L01", "", "-10", "SYNTH-BS-AP"),
117 NoteReference("BS", "Equity", "E01", "", "-90", "SYNTH-BS-EQ"),
118 NoteReference("IS", "Revenue", "R01", "", "-40", "SYNTH-IS-REV"),
119 NoteReference("IS", "Cost of revenue", "X01", "", "20", "SYNTH-IS-COST"),
120 NoteReference("EQ", "Share capital", "E01", "", "-70", "SYNTH-EQ-CAP"),
121 NoteReference("EQ", "Current year result", "P01", "", "-20", "SYNTH-EQ-PROFIT"),
122 )
123
124
125 def cash_transactions() -> tuple[CashFlowEntry, ...]:
126 return (
127 CashFlowEntry(
128 company_code=COMPANY, fiscal_year=YEAR, line_id="CF-L1",
129 transaction_id="CF-V1", posting_date="1404-01-01",
130 cash_account_code="CASH", counterpart_account_code="REV",
131 cash_debit="30", cash_credit="0", counterpart_debit="0",
132 counterpart_credit="30", evidence_ref="SYNTH-TXN-1",
133 ),
134 CashFlowEntry(
135 company_code=COMPANY, fiscal_year=YEAR, line_id="CF-L2",
136 transaction_id="CF-V2", posting_date="1404-01-02",
137 cash_account_code="CASH", counterpart_account_code="EXP",
138 cash_debit="0", cash_credit="20", counterpart_debit="20",
139 counterpart_credit="0", evidence_ref="SYNTH-TXN-2",
140 ),
141 )
142
143
144 def build_pipeline(
145 data: bytes | None = None, *, transactions=None, refs=None,
146 ):
147 source = source_workbook() if data is None else data
148 return build_five_statement_pipeline(
149 source, company_code=COMPANY, fiscal_year=YEAR,
150 references=references() if refs is None else refs,
151 balance_sheet_policies=(
152 BalanceSheetLinePolicy(
153 "Current assets", "C01", "", "ASSETS", 1,
154 "Cash and cash equivalents", "SYNTH-POL-BS-CASH",
155 ),
156 BalanceSheetLinePolicy(
157 "Current assets", "A01", "", "ASSETS", 1,
158 "Trade receivables", "SYNTH-POL-BS-AR",
159 ),
160 BalanceSheetLinePolicy(
161 "Current liabilities", "L01", "", "LIABILITIES", -1,
162 "Trade payables", "SYNTH-POL-BS-AP",
163 ),
164 BalanceSheetLinePolicy(
165 "Equity", "E01", "", "EQUITY", -1,
166 "Total equity", "SYNTH-POL-BS-EQ",
167 ),
168 ),
169 income_statement_policies=(
170 IncomeStatementLinePolicy(
171 "Revenue", "R01", "", "REVENUE", -1,
172 "Revenue", "SYNTH-POL-IS-REV",
173 ),
174 IncomeStatementLinePolicy(
175 "Cost of revenue", "X01", "", "COST_OF_REVENUE", 1,
176 "Cost of revenue", "SYNTH-POL-IS-COST",
177 ),
178 ),
179 equity_movement_policies=(
180 EquityMovementPolicy(
181 "Share capital", "E01", "", "SHARE_CAPITAL",
182 "CAPITAL_CONTRIBUTION", -1, "Share capital",
183 "SYNTH-POL-EQ-CAP",
184 ),
185 EquityMovementPolicy(
186 "Current year result", "P01", "", "RETAINED_EARNINGS",
187 "NET_PROFIT_LOSS", -1, "Current year profit",
188 "SYNTH-POL-EQ-PROFIT",
189 ),
190 ),
191 currency="IRR", unit="Rial",
192 cash_accounts=(CashAccountPolicy("CASH", "SYNTH-CASH-SCOPE"),),
193 counterpart_policies=(
194 CashCounterpartPolicy("REV", "OPERATING", "SYNTH-REV-CLASS"),
195 CashCounterpartPolicy("EXP", "OPERATING", "SYNTH-EXP-CLASS"),
196 ),
197 transactions=cash_transactions() if transactions is None else transactions,
198 cash_balance_notes=(
199 CashBalanceNoteSelection(
200 "Current assets", "C01", "", "SYNTH-CASH-NOTE-SELECTION",
201 ),
202 ),
203 )
204
205
206 def build_all(data: bytes | None = None, *, transactions=None):
207 pipeline = build_pipeline(data, transactions=transactions)
208 return (
209 pipeline.balance_sheet, pipeline.income_statement,
210 pipeline.equity_changes, pipeline.cash_flow,
211 pipeline.trial_balance, pipeline.reconciliation,
212 )
213
214
215
216 def pipeline_manifest(*, transactions=None):
217 return {
218 "schema_version": 1,
219 "company_code": COMPANY,
220 "fiscal_year": YEAR,
221 "currency": "IRR",
222 "unit": "Rial",
223 "references": [asdict(item) for item in references()],
224 "balance_sheet_policies": [
225 {
226 "statement_section": "Current assets", "note_number": "C01",
227 "subnote_code": "", "category": "ASSETS", "sign_multiplier": 1,
228 "line_label": "Cash and cash equivalents",
229 "policy_evidence_ref": "SYNTH-POL-BS-CASH",
230 },
231 {
232 "statement_section": "Current assets", "note_number": "A01",
233 "subnote_code": "", "category": "ASSETS", "sign_multiplier": 1,
234 "line_label": "Trade receivables", "policy_evidence_ref": "SYNTH-POL-BS-AR",
235 },
236 {
237 "statement_section": "Current liabilities", "note_number": "L01",
238 "subnote_code": "", "category": "LIABILITIES", "sign_multiplier": -1,
239 "line_label": "Trade payables", "policy_evidence_ref": "SYNTH-POL-BS-AP",
240 },
241 {
242 "statement_section": "Equity", "note_number": "E01",
243 "subnote_code": "", "category": "EQUITY", "sign_multiplier": -1,
244 "line_label": "Total equity", "policy_evidence_ref": "SYNTH-POL-BS-EQ",
245 },
246 ],
247 "income_statement_policies": [
248 {
249 "statement_section": "Revenue", "note_number": "R01",
250 "subnote_code": "", "category": "REVENUE", "sign_multiplier": -1,
251 "line_label": "Revenue", "policy_evidence_ref": "SYNTH-POL-IS-REV",
252 },
253 {
254 "statement_section": "Cost of revenue", "note_number": "X01",
255 "subnote_code": "", "category": "COST_OF_REVENUE", "sign_multiplier": 1,
256 "line_label": "Cost of revenue", "policy_evidence_ref": "SYNTH-POL-IS-COST",
257 },
258 ],
259 "equity_movement_policies": [
260 {
261 "statement_section": "Share capital", "note_number": "E01",
262 "subnote_code": "", "equity_component": "SHARE_CAPITAL",
263 "movement_category": "CAPITAL_CONTRIBUTION", "sign_multiplier": -1,
264 "line_label": "Share capital", "policy_evidence_ref": "SYNTH-POL-EQ-CAP",
265 },
266 {
267 "statement_section": "Current year result", "note_number": "P01",
268 "subnote_code": "", "equity_component": "RETAINED_EARNINGS",
269 "movement_category": "NET_PROFIT_LOSS", "sign_multiplier": -1,
270 "line_label": "Current year profit", "policy_evidence_ref": "SYNTH-POL-EQ-PROFIT",
271 },
272 ],
273 "cash_accounts": [
274 {"account_code": "CASH", "evidence_ref": "SYNTH-CASH-SCOPE"},
275 ],
276 "counterpart_policies": [
277 {"account_code": "REV", "activity": "OPERATING", "evidence_ref": "SYNTH-REV-CLASS"},
278 {"account_code": "EXP", "activity": "OPERATING", "evidence_ref": "SYNTH-EXP-CLASS"},
279 ],
280 "transactions": [
281 asdict(item) for item in (
282 cash_transactions() if transactions is None else transactions
283 )
284 ],
285 "cash_balance_notes": [
286 {
287 "statement_section": "Current assets", "note_number": "C01",
288 "subnote_code": "", "evidence_ref": "SYNTH-CASH-NOTE-SELECTION",
289 },
290 ],
291 }
292
293
294
295 def test_all_five_real_builders_reconcile_from_one_immutable_workbook():
296 bs, income, equity, cash, trial, result = build_all()
297
298 assert bs.eligible_for_analyst_review and not bs.findings
299 assert income.eligible_for_analyst_review and not income.findings
300 assert equity.eligible_for_analyst_review and not equity.findings
301 assert cash.eligible_for_analyst_review and not cash.findings
302 assert trial.balanced_for_analyst_review and not trial.findings
303 assert len({item.source_sha256 for item in (bs, income, equity, cash, trial)}) == 1
304 assert len({
305 bs.note_references_sha256,
306 income.note_references_sha256,
307 equity.note_references_sha256,
308 }) == 1
309
310 assert bs.assets_total == "100"
311 assert bs.liabilities_total == "10"
312 assert bs.equity_total == "90"
313 assert income.net_result == "20"
314 assert equity.opening_equity_total == "70"
315 assert equity.net_profit_loss_movements == "20"
316 assert equity.closing_equity_total == "90"
317 assert cash.opening_cash_and_equivalents == "40"
318 assert cash.net_change_in_cash == "10"
319 assert cash.closing_cash_and_equivalents == "50"
320 assert trial.opening_debit_net_total == "0"
321 assert trial.debit_turnover_total == "60"
322 assert trial.credit_turnover_total == "60"
323 assert trial.closing_debit_net_total == "0"
324
325 assert result.eligible_for_analyst_review
326 assert result.findings == ()
327 assert result.balance_sheet_equity_difference == "0"
328 assert result.net_profit_equity_difference == "0"
329 assert result.balance_sheet_cash_difference == "0"
330 assert result.cash_accounts_match_trial_balance
331 assert result.cash_account_totals_valid
332 assert not result.source_ledger_completeness_verified
333 assert not result.accounting_policy_authorized
334 assert not result.independently_reviewed
335 assert not result.official_financial_statement
336 assert not result.export_authorized
337 assert not result.releasable
338
339
340 def test_missing_cash_transaction_blocks_real_five_statement_pipeline():
341 bs, income, equity, cash, trial, result = build_all(
342 transactions=cash_transactions()[:-1],
343 )
344 assert bs.eligible_for_analyst_review
345 assert income.eligible_for_analyst_review
346 assert equity.eligible_for_analyst_review
347 assert trial.balanced_for_analyst_review
348 assert not cash.eligible_for_analyst_review
349 assert not result.eligible_for_analyst_review
350 assert "CASH_FLOW_CANDIDATE_BLOCKED" in result.findings
351 assert "CASH_FLOW_BRIDGE_INVALID" in result.findings or "CASH_ACCOUNT_TURNOVER_OR_TOTALS_INVALID" in result.findings
352
353
354 def test_pipeline_result_is_nonofficial_and_freezes_reference_collection():
355 result = build_pipeline()
356 payload = result.to_dict()
357 assert result.eligible_for_analyst_review
358 assert payload["kind"] == "UNAPPROVED_FIVE_STATEMENT_PIPELINE_CANDIDATE"
359 assert payload["source_sha256"] == result.source_sha256
360 for flag in (
361 "source_ledger_completeness_verified", "accounting_policy_authorized",
362 "independently_reviewed", "trusted_approvals",
363 "official_financial_statement", "export_authorized", "releasable",
364 ):
365 assert payload[flag] is False
366
367 with pytest.raises(CoverageError) as error:
368 build_pipeline(refs=iter(references()))
369 assert error.value.code == "INVALID_FIVE_STATEMENT_NOTE_REFERENCES"
370
371
372 def test_offline_pipeline_cli_emits_json_without_creating_output_files(tmp_path, capsys):
373 workbook_path = tmp_path / "synthetic.xlsx"
374 manifest_path = tmp_path / "pipeline.json"
375 workbook_path.write_bytes(source_workbook())
376 manifest_path.write_text(
377 json.dumps(pipeline_manifest(), ensure_ascii=True),
378 encoding="utf-8",
379 )
380
381 exit_code = pipeline_cli_main([
382 "--file", str(workbook_path), "--manifest", str(manifest_path),
383 ])
384 captured = capsys.readouterr()
385 payload = json.loads(captured.out)
386 assert exit_code == 0
387 assert payload["eligible_for_analyst_review"] is True
388 assert payload["kind"] == "UNAPPROVED_FIVE_STATEMENT_PIPELINE_CANDIDATE"
389 assert payload["official_financial_statement"] is False
390 assert payload["releasable"] is False
391 assert {item.name for item in tmp_path.iterdir()} == {
392 "synthetic.xlsx", "pipeline.json",
393 }
394
395
396 def test_offline_pipeline_cli_returns_blocked_exit_for_incomplete_transactions(
397 tmp_path, capsys,
398 ):
399 workbook_path = tmp_path / "synthetic.xlsx"
400 manifest_path = tmp_path / "pipeline.json"
401 workbook_path.write_bytes(source_workbook())
402 manifest_path.write_text(
403 json.dumps(pipeline_manifest(transactions=cash_transactions()[:-1])),
404 encoding="utf-8",
405 )
406
407 exit_code = pipeline_cli_main([
408 "--file", str(workbook_path), "--manifest", str(manifest_path),
409 ])
410 payload = json.loads(capsys.readouterr().out)
411 assert exit_code == 3
412 assert payload["eligible_for_analyst_review"] is False
413 assert "CASH_FLOW_CANDIDATE_BLOCKED" in payload["findings"]
414
415
416 def test_pipeline_manifest_rejects_duplicate_keys_and_nonfinite_numbers():
417 from aram_backend.five_statement_pipeline_cli import parse_pipeline_manifest
418
419 with pytest.raises(CoverageError) as duplicate:
420 parse_pipeline_manifest(b'{"schema_version":1,"schema_version":1}')
421 assert duplicate.value.code == "DUPLICATE_MANIFEST_KEY"
422
423 document = pipeline_manifest()
424 document["fiscal_year"] = float("nan")
425 with pytest.raises(CoverageError) as nonfinite:
426 parse_pipeline_manifest(json.dumps(document).encode("utf-8"))
427 assert nonfinite.value.code == "PIPELINE_MANIFEST_NONFINITE_NUMBER"
428
429
430 def test_pipeline_manifest_rejects_unknown_fields_and_missing_cash_registry():
431 from aram_backend.five_statement_pipeline_cli import parse_pipeline_manifest
432
433 document = pipeline_manifest()
434 document["unexpected"] = True
435 with pytest.raises(CoverageError) as unknown:
436 parse_pipeline_manifest(json.dumps(document).encode("utf-8"))
437 assert unknown.value.code == "PIPELINE_MANIFEST_SCHEMA_INVALID"
438
439 document = pipeline_manifest()
440 document["cash_accounts"] = []
441 with pytest.raises(CoverageError) as missing:
442 parse_pipeline_manifest(json.dumps(document).encode("utf-8"))
443 assert missing.value.code == "PIPELINE_MANIFEST_CASH_ACCOUNTS_INVALID"
444