@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/upload-artifact-7
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 247 lines 10 KB
Raw
1 """Audit #3/#4: approval gate must run ALL controls (esp. C-03) and block on ERROR.
2
3 Negative tests prove a year can never be approved while any control fails,
4 including the double-mapping case (C-03) flagged in the owner's line-by-line audit.
5 """
6
7 from __future__ import annotations
8
9 from decimal import Decimal
10
11 import pytest
12
13 from aram_backend.domain.controls import BalanceRow, MappingTarget
14 from aram_backend.ingestion import register_source_document
15 from aram_backend.models import FiscalYearStatus
16 from aram_backend.services.approval import ApprovalError, approve_year, evaluate_controls
17 from aram_backend.services.audit import verify_chain
18 from test_statement_build import _balance, _map, _note, _setup
19
20
21 def _carry(session, year, source, code, opening, closing, row):
22 """A ledger row with an explicit opening balance (C-05 needs carry-forward)."""
23 from aram_backend.models import LedgerBalance
24
25 movement = closing - opening
26 session.add(
27 LedgerBalance(
28 year_id=year.id,
29 source_document_id=source.id,
30 source_sheet="Source",
31 source_row=row,
32 import_version=1,
33 account_full_code=code,
34 general_code=code[:2],
35 subsidiary_code=code[2:],
36 account_name=f"حساب {code}",
37 opening=opening,
38 debit=max(movement, Decimal(0)),
39 credit=max(-movement, Decimal(0)),
40 closing=closing,
41 )
42 )
43
44
45 def _balanced(session):
46 """A **complete** year: all 15 controls can genuinely run and pass.
47
48 Balances are carried forward from the prior year with no movement, so the
49 trial balance, the balance-sheet equation, the equity identity, the IS result
50 and the cash-flow identity all hold exactly. Account natures and the general
51 parent codes are registered so C-11/C-15 have real inputs too.
52 """
53 from aram_backend.models import AccountVersion, FiscalYear
54 from aram_backend.services.statement_build import build_statements
55
56 year, source = _setup(session)
57 prior = FiscalYear(company_id=year.company_id, year=year.year - 1)
58 session.add(prior)
59 session.flush()
60 prior_source = register_source_document(
61 session,
62 year_id=prior.id,
63 filename="source_1403.xlsx",
64 document_type="general_ledger",
65 content=b"prior-year-bytes",
66 )
67 session.flush()
68
69 # (code, closing) — carried forward unchanged, so every movement is zero.
70 carried = (("148348", 100), ("241001", -60), ("341001", -40))
71 for i, (code, amount) in enumerate(carried, start=3):
72 _carry(session, prior, prior_source, code, Decimal(0), Decimal(amount), i)
73 _carry(session, year, source, code, Decimal(amount), Decimal(amount), i)
74 # Zero-movement accounts give IS and CF real (empty) inputs to check.
75 _carry(session, year, source, "541001", Decimal(0), Decimal(0), 6)
76 _carry(session, year, source, "641001", Decimal(0), Decimal(0), 7)
77
78 n_a = _note(session, year, "6", "نقد", "BS", "Assets")
79 n_a.configuration_json = {**n_a.configuration_json, "role": "cash"}
80 n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
81 n_e = _note(session, year, "12", "سرمایه", "BS", "Equity")
82 n_e.configuration_json = {**n_e.configuration_json, "role": "retained_earnings"}
83 n_rev = _note(session, year, "20", "درآمد", "IS", "Revenue")
84 n_cf = _note(session, year, "23", "جریان نقد عملیاتی", "CF", "Operating")
85 _map(session, year, "148348", n_a)
86 _map(session, year, "241001", n_l)
87 _map(session, year, "341001", n_e)
88 _map(session, year, "541001", n_rev)
89 _map(session, year, "641001", n_cf)
90
91 for code in ("14", "24", "34", "54", "64", "148348", "241001", "341001", "541001", "641001"):
92 session.add(AccountVersion(year_id=year.id, account_code=code, account_name=f"حساب {code}"))
93 session.flush()
94 build_statements(session, year.id)
95 session.flush()
96 return year, n_a
97
98
99 class TestApprovalNegative:
100 def test_double_mapping_blocks_via_c03(self, session):
101 # The exact audit concern: one account mapped to TWO notes must block.
102 year, n_a = _balanced(session)
103 n_a2 = _note(session, year, "6b", "نقد دوم", "BS", "Assets")
104 _map(session, year, "148348", n_a2) # second mapping for the same account
105 session.flush()
106 result = approve_year(session, year.id)
107 assert not result.approved
108 assert any(r.code == "C-03" for r in result.blocking)
109 assert year.status == FiscalYearStatus.DRAFT
110
111 def test_c01_violation_blocks(self, session):
112 year, source = _setup(session)
113 _balance(session, year, source, "148348", 100, 3)
114 # Corrupt the closing so opening+debit-credit-closing != 0.
115 from aram_backend.models import LedgerBalance
116
117 b = session.query(LedgerBalance).filter_by(year_id=year.id).one()
118 b.closing = Decimal(999)
119 n = _note(session, year, "6", "نقد", "BS", "Assets")
120 _map(session, year, "148348", n)
121 session.flush()
122 result = approve_year(session, year.id)
123 assert not result.approved
124 assert any(r.code == "C-01" for r in result.blocking)
125
126 def test_c02_imbalance_blocks(self, session):
127 year, source = _setup(session)
128 _balance(session, year, source, "148348", 100, 3)
129 _balance(session, year, source, "148349", 50, 4) # no offsetting credit
130 n = _note(session, year, "6", "نقد", "BS", "Assets")
131 _map(session, year, "148348", n)
132 _map(session, year, "148349", n)
133 session.flush()
134 result = approve_year(session, year.id)
135 assert not result.approved
136 assert any(r.code == "C-02" for r in result.blocking)
137
138 def test_unmapped_blocks_via_c04(self, session):
139 year, source = _setup(session)
140 _balance(session, year, source, "148348", 100, 3)
141 session.flush()
142 result = approve_year(session, year.id)
143 assert not result.approved
144 assert any(r.code == "C-04" for r in result.blocking)
145
146 def test_blocked_approval_is_audited_as_refused_and_stays_draft(self, session):
147 # R2 decision (ADR-031): a refused approval is itself an auditable event.
148 # The old expectation "no audit on block" hid who tried and what stopped
149 # them; the year must still stay Draft and nothing may be approved.
150 year, source = _setup(session)
151 _balance(session, year, source, "148348", 100, 3)
152 session.flush()
153 result = approve_year(session, year.id, actor="reviewer")
154 session.commit()
155 from aram_backend.models import AuditEntry
156
157 assert not result.approved
158 entries = session.query(AuditEntry).all()
159 assert len(entries) == 1
160 assert entries[0].action == "approve"
161 assert entries[0].actor == "reviewer"
162 # The log stores only a hash, so verify the refused payload by recomputing
163 # it: the entry must commit to approved=False plus the blocking codes.
164 from aram_backend.services.audit import _payload_hash, verify_chain
165
166 expected = _payload_hash(
167 "approve",
168 "reviewer",
169 year.id,
170 {
171 "approved": False,
172 "blocking": [r.code for r in result.blocking],
173 "unrun": [r.code for r in result.blocking if not r.ran],
174 },
175 )
176 assert entries[0].payload_hash == expected
177 assert verify_chain(session)
178 assert year.status == FiscalYearStatus.DRAFT
179
180 def test_non_draft_rejected(self, session):
181 year, _ = _balanced(session)
182 approve_year(session, year.id)
183 session.commit()
184 with pytest.raises(ApprovalError):
185 approve_year(session, year.id)
186
187 def test_nonexistent_year_rejected(self, session):
188 with pytest.raises(ApprovalError):
189 approve_year(session, 999999)
190
191
192 class TestApprovalPositive:
193 def test_clean_ledger_approves_and_audits(self, session):
194 year, _ = _balanced(session)
195 result = approve_year(session, year.id, actor="reviewer")
196 session.commit()
197 assert result.approved
198 assert result.blocking == ()
199 assert year.status == FiscalYearStatus.APPROVED
200 assert verify_chain(session)
201
202 def test_locked_after_approval_is_immutable(self, session):
203 year, _ = _balanced(session)
204 approve_year(session, year.id)
205 session.commit()
206 year.status = FiscalYearStatus.LOCKED
207 session.commit()
208 from sqlalchemy import text
209 from sqlalchemy.exc import IntegrityError
210
211 with pytest.raises(IntegrityError):
212 session.execute(
213 text("UPDATE ledger_balances SET debit = 1 WHERE year_id = :y"), {"y": year.id}
214 )
215 session.rollback()
216
217
218 class TestEvaluateControlsUsesMappings:
219 """Prove mappings are actually passed to the controls (C-03/C-04)."""
220
221 def _rows(self):
222 return [BalanceRow(row_number=3, account_code="148348", opening=Decimal(0),
223 debit=Decimal(100), credit=Decimal(0), closing=Decimal(100))]
224
225 def test_no_mappings_fails_c03_c04(self):
226 results = {r.code: r for r in evaluate_controls(self._rows(), {})}
227 assert not results["C-03"].passed
228 assert not results["C-04"].passed
229
230 def test_single_mapping_passes_c03_c04(self):
231 mappings = {"148348": [MappingTarget(target="1")]}
232 results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
233 assert results["C-03"].passed
234 assert results["C-04"].passed
235
236 def test_double_mapping_fails_c03(self):
237 mappings = {"148348": [MappingTarget(target="1"), MappingTarget(target="2")]}
238 results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
239 assert not results["C-03"].passed
240
241 def test_valid_100_split_passes_c03(self):
242 mappings = {
243 "148348": [MappingTarget(target="1", weight=Decimal(60)),
244 MappingTarget(target="2", weight=Decimal(40))]
245 }
246 results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
247 assert results["C-03"].passed