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

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

Synced Dec 4, 14:15 UTC

dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1
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 396 lines 15.4 KB
Raw
1 """R2: C-05..C-15 — a positive and a negative case for every control.
2
3 Plus the booklet 2.1 rule: a control that cannot run reports «اجرا نشد: دلیل» and
4 blocks approval; approval is only possible when the whole ERROR set has run and
5 passed.
6 """
7
8 from __future__ import annotations
9
10 from decimal import Decimal
11
12 from aram_backend.domain.controls import (
13 BalanceRow,
14 ControlContext,
15 EquityMovement,
16 MappingTarget,
17 OfficialComparison,
18 check_c05,
19 check_c06,
20 check_c07,
21 check_c08,
22 check_c09,
23 check_c10,
24 check_c11,
25 check_c12,
26 check_c13,
27 check_c14,
28 check_c15,
29 run_controls,
30 )
31 from aram_backend.services.approval import approve_year
32 from aram_backend.services.control_context import build_control_context
33 from test_approval_gate import _balanced, _carry
34 from test_statement_build import _setup
35
36 D = Decimal
37
38
39 def _row(code, opening, closing, debit=None, credit=None, row=1):
40 move = closing - opening
41 return BalanceRow(
42 row_number=row,
43 account_code=code,
44 opening=opening,
45 debit=debit if debit is not None else max(move, D(0)),
46 credit=credit if credit is not None else max(-move, D(0)),
47 closing=closing,
48 )
49
50
51 class TestC05PriorYear:
52 def test_matching_carry_forward_passes(self):
53 rows = [_row("148348", D(100), D(150))]
54 assert check_c05(rows, {"148348": D(100)}).passed
55
56 def test_mismatched_opening_fails(self):
57 rows = [_row("148348", D(90), D(150))]
58 result = check_c05(rows, {"148348": D(100)})
59 assert not result.passed and result.severity == "ERROR"
60 assert result.affected == ("148348",)
61
62 def test_missing_prior_year_is_unrun_and_blocking(self):
63 result = check_c05([_row("148348", D(0), D(1))], None)
64 assert not result.passed and not result.ran
65 assert result.message_fa.startswith("اجرا نشد:")
66
67
68 class TestC06BalanceEquation:
69 def test_equation_holds(self):
70 assert check_c06({"Assets": D(100), "Liabilities": D(60), "Equity": D(40)}).passed
71
72 def test_equation_violated(self):
73 result = check_c06({"Assets": D(100), "Liabilities": D(60), "Equity": D(30)})
74 assert not result.passed and result.severity == "ERROR"
75
76 def test_missing_section_is_unrun(self):
77 result = check_c06({"Assets": D(100)})
78 assert not result.ran and "بخش‌های غایب" in result.message_fa
79
80
81 class TestC07NoteVsLine:
82 def test_note_equals_line(self):
83 assert check_c07({"BS:6": D(100)}, {"BS:6": D(100)}).passed
84
85 def test_note_differs_from_line(self):
86 result = check_c07({"BS:6": D(100)}, {"BS:6": D(99)})
87 assert not result.passed and result.affected == ("BS:6",)
88
89 def test_missing_inputs_unrun(self):
90 assert not check_c07(None, {"BS:6": D(1)}).ran
91
92
93 class TestC08ProfitVsRetained:
94 def test_profit_equals_retained_change(self):
95 assert check_c08(D(50), D(50)).passed
96
97 def test_explicit_adjustment_is_respected(self):
98 assert check_c08(D(50), D(40), D(10)).passed
99
100 def test_unexplained_difference_fails(self):
101 result = check_c08(D(50), D(40))
102 assert not result.passed and result.severity == "ERROR"
103
104 def test_missing_input_unrun(self):
105 assert not check_c08(None, D(0)).ran
106
107
108 class TestC09EquityIdentity:
109 def test_opening_plus_changes_equals_closing(self):
110 moves = (EquityMovement("EQ:12", D(40), D(10), D(50)),)
111 assert check_c09(moves).passed
112
113 def test_identity_violated(self):
114 result = check_c09((EquityMovement("EQ:12", D(40), D(10), D(55)),))
115 assert not result.passed and result.affected == ("EQ:12",)
116
117 def test_no_equity_rows_is_unrun(self):
118 assert not check_c09(()).ran
119
120
121 class TestC10CashFlow:
122 def test_net_change_matches_cash_movement(self):
123 assert check_c10(D(20), D(100), D(120)).passed
124
125 def test_mismatch_fails(self):
126 result = check_c10(D(20), D(100), D(130))
127 assert not result.passed and result.severity == "ERROR"
128
129 def test_missing_cash_unrun(self):
130 assert not check_c10(D(20), None, D(120)).ran
131
132
133 class TestC11Hierarchy:
134 def test_parent_exists_and_children_sum(self):
135 rows = [_row("14", D(0), D(100), row=1), _row("148348", D(0), D(100), row=2)]
136 assert check_c11(rows, frozenset({"14", "148348"})).passed
137
138 def test_missing_parent_fails(self):
139 result = check_c11([_row("148348", D(0), D(100))], frozenset({"148348"}))
140 assert not result.passed and result.affected == ("148348",)
141
142 def test_children_not_summing_to_parent_fails(self):
143 rows = [_row("14", D(0), D(100), row=1), _row("148348", D(0), D(90), row=2)]
144 result = check_c11(rows, frozenset({"14", "148348"}))
145 assert not result.passed and "14" in result.affected
146
147 def test_no_chart_is_unrun(self):
148 assert not check_c11([_row("148348", D(0), D(1))], None).ran
149
150
151 class TestC12NoteCoverage:
152 def test_every_note_mapped_and_no_dangling(self):
153 assert check_c12({"148348": [MappingTarget("1")]}, frozenset({"1"})).passed
154
155 def test_unmapped_note_fails(self):
156 result = check_c12({"148348": [MappingTarget("1")]}, frozenset({"1", "2"}))
157 assert not result.passed and "2" in result.affected
158
159 def test_mapping_to_missing_note_fails(self):
160 result = check_c12({"148348": [MappingTarget("9")]}, frozenset({"1"}))
161 assert not result.passed and "9" in result.affected
162
163
164 class TestC13Official:
165 def test_matching_official_passes(self):
166 official = (OfficialComparison("BS:6", D(100), D(100)),)
167 assert check_c13(official).passed
168
169 def test_difference_is_info_in_ui(self):
170 result = check_c13((OfficialComparison("BS:6", D(100), D(90)),), "ui")
171 assert not result.passed and result.severity == "INFO"
172
173 def test_difference_is_error_in_ci(self):
174 result = check_c13((OfficialComparison("BS:6", D(100), D(90)),), "ci")
175 assert not result.passed and result.severity == "ERROR"
176
177
178 class TestC14SuddenChange:
179 def test_small_change_passes(self):
180 rows = [_row("148348", D(100), D(110))]
181 assert check_c14(rows, {"148348": D(100)}).passed
182
183 def test_large_change_warns_not_blocks(self):
184 rows = [_row("148348", D(100), D(300))]
185 result = check_c14(rows, {"148348": D(100)})
186 assert not result.passed and result.severity == "WARN"
187
188 def test_threshold_is_configurable(self):
189 rows = [_row("148348", D(100), D(300))]
190 assert check_c14(rows, {"148348": D(100)}, D(500)).passed
191
192
193 class TestC15Nature:
194 def test_balance_matches_nature(self):
195 rows = [_row("148348", D(0), D(100))]
196 assert check_c15(rows, {"148348": "debit"}).passed
197
198 def test_credit_balance_on_debit_account_warns(self):
199 rows = [_row("148348", D(0), D(-100))]
200 result = check_c15(rows, {"148348": "debit"})
201 assert not result.passed and result.severity == "WARN"
202
203 def test_persian_nature_is_recognised(self):
204 rows = [_row("241001", D(0), D(-60))]
205 assert check_c15(rows, {"241001": "بستانکار"}).passed
206
207 def test_no_natures_is_unrun(self):
208 assert not check_c15([_row("148348", D(0), D(1))], None).ran
209
210
211 class TestFullSet:
212 def test_fifteen_controls_always_present(self):
213 results = run_controls([], {})
214 assert len(results) == 15
215 assert [r.code for r in results] == [f"C-{i:02d}" for i in range(1, 16)]
216
217 def test_unrun_error_controls_block(self):
218 results = run_controls([], {})
219 blocking = [r.code for r in results if r.severity == "ERROR" and not r.passed]
220 assert "C-05" in blocking and "C-13" not in blocking # C-13 is INFO in UI
221
222 def test_failing_warn_is_not_a_blocking_severity(self):
223 # A 200% jump trips C-14 (WARN); nothing about it may be ERROR severity.
224 rows = [_row("148348", D(100), D(300), row=1), _row("241001", D(-100), D(-300), row=2)]
225 results = run_controls(rows, {}, ControlContext(prior_closing={"148348": D(100), "241001": D(-100)}))
226 c14 = next(r for r in results if r.code == "C-14")
227 assert not c14.passed and c14.severity == "WARN"
228 blocking = {r.code for r in results if r.severity == "ERROR" and not r.passed}
229 assert "C-14" not in blocking and "C-15" not in blocking
230
231
232 class TestApprovalRejectsIncompleteControls:
233 def test_year_without_prior_or_statements_cannot_be_approved(self, session):
234 year, _ = _setup(session)
235 result = approve_year(session, year.id)
236 assert not result.approved
237 codes = {r.code for r in result.blocking}
238 assert {"C-05", "C-06", "C-09", "C-10"}.issubset(codes)
239 assert all(r.message_fa.startswith("اجرا نشد:") or not r.ran for r in result.blocking
240 if r.code in {"C-05", "C-06"})
241
242 def test_complete_year_passes_all_fifteen(self, session):
243 year, _ = _balanced(session)
244 ctx = build_control_context(session, year.id)
245 assert ctx.prior_closing is not None and ctx.bs_sections is not None
246 result = approve_year(session, year.id, actor="reviewer")
247 session.commit()
248 assert result.approved, [r.message_fa for r in result.controls if not r.passed]
249 assert len(result.controls) == 15
250 assert all(r.ran for r in result.controls if r.severity == "ERROR")
251
252 def test_broken_equity_identity_blocks_a_otherwise_clean_year(self, session):
253 year, cash_note = _balanced(session)
254 # Corrupt one equity balance so opening + changes != closing.
255 from sqlalchemy import select
256
257 from aram_backend.models import LedgerBalance
258
259 eq = session.scalar(
260 select(LedgerBalance).where(
261 LedgerBalance.year_id == year.id, LedgerBalance.account_full_code == "341001"
262 )
263 )
264 eq.closing = eq.closing - D(5)
265 session.flush()
266 result = approve_year(session, year.id)
267 assert not result.approved
268 assert any(r.code == "C-09" for r in result.blocking)
269
270
271 class TestPreflightApi:
272 """Acceptance (R2): the preflight endpoint shows all 15 controls."""
273
274 def _year(self, api_client):
275 return api_client.post(
276 "/api/v1/companies", json={"code": "R2", "name": "شرکت", "year": 1404}
277 ).json()["year_id"]
278
279 def test_preflight_returns_fifteen_controls_with_ran_flags(self, api_client):
280 year_id = self._year(api_client)
281 response = api_client.get(f"/api/v1/years/{year_id}/preflight")
282 assert response.status_code == 200, response.text
283 body = response.json()
284 assert [c["code"] for c in body["controls"]] == [f"C-{i:02d}" for i in range(1, 16)]
285 assert all("ran" in c for c in body["controls"])
286 assert body["can_approve"] is False
287 unrun = [c for c in body["controls"] if not c["ran"]]
288 assert unrun and all(c["message_fa"].startswith("اجرا نشد:") for c in unrun)
289
290 def test_approval_is_rejected_when_error_controls_did_not_run(self, api_client):
291 year_id = self._year(api_client)
292 response = api_client.post(f"/api/v1/years/{year_id}/approve", json={})
293 assert response.status_code == 200, response.text
294 body = response.json()
295 assert body["approved"] is False
296 assert {"C-05", "C-06"} <= {b["code"] for b in body["blocking"]}
297
298
299 class TestCompleteYearThroughApi:
300 """The public API alone must be enough to reach an approvable year (R2)."""
301
302 def test_all_fifteen_run_and_approval_succeeds(self, api_client):
303 from helpers_complete_year import complete_year_via_api
304
305 year_id, _ = complete_year_via_api(api_client)
306 pre = api_client.get(f"/api/v1/years/{year_id}/preflight").json()
307 assert len(pre["controls"]) == 15
308 errors = [c for c in pre["controls"] if c["severity"] == "ERROR"]
309 assert all(c["ran"] for c in errors), [c for c in errors if not c["ran"]]
310 assert pre["can_approve"] is True, [c for c in pre["controls"] if not c["passed"]]
311 approved = api_client.post(f"/api/v1/years/{year_id}/approve", json={})
312 assert approved.status_code == 200, approved.text
313 assert approved.json()["approved"] is True
314
315 def test_duplicate_year_is_refused(self, api_client):
316 created = api_client.post(
317 "/api/v1/companies", json={"code": "DY", "name": "x", "year": 1404}
318 ).json()
319 again = api_client.post(
320 f"/api/v1/companies/{created['company_id']}/years", json={"year": 1404}
321 )
322 assert again.status_code == 422
323
324 def test_note_role_round_trips(self, api_client):
325 from helpers_complete_year import complete_year_via_api
326
327 year_id, notes = complete_year_via_api(api_client)
328 listed = api_client.get(f"/api/v1/years/{year_id}/notes").json()["notes"]
329 by_id = {n["note_id"]: n for n in listed}
330 assert by_id[notes["cash"]]["role"] == "cash"
331 assert by_id[notes["equity"]]["role"] == "retained_earnings"
332 assert by_id[notes["payable"]]["role"] is None
333
334 def test_invalid_note_role_is_refused(self, api_client):
335 year_id = api_client.post(
336 "/api/v1/companies", json={"code": "NR", "name": "x", "year": 1404}
337 ).json()["year_id"]
338 bad = api_client.post(
339 f"/api/v1/years/{year_id}/notes",
340 json={
341 "note_number": "1",
342 "title": "x",
343 "statement": "BS",
344 "section": "Assets",
345 "role": "guessed",
346 },
347 )
348 assert bad.status_code == 422
349
350
351 class TestReclassifiedRowsAgreeWithTheEngine:
352 """C-06/C-07 must use the same figure `build_statements` uses.
353
354 A reclassified source row carries `statement_balance` instead of CLOSING.
355 Both engines must prefer it and apply the section sign exactly once,
356 otherwise the control compares two different rules and invents a difference.
357 """
358
359 def test_display_prefers_the_reclassified_figure_then_signs_it(self):
360 # ADR-032: statement_balance is debit-positive like CLOSING, so the
361 # section sign applies to it too (measured: BS 16/16 vs official 1404).
362 row = BalanceRow(1, "241001", D(0), D(0), D(0), D(0), statement_balance=D(-250))
363 assert row.display(D(1)) == D(-250)
364 assert row.display(D(-1)) == D(250)
365
366 def test_display_signs_ordinary_closing(self):
367 row = BalanceRow(1, "241001", D(0), D(0), D(60), D(-60))
368 assert row.display(D(-1)) == D(60)
369
370 def test_context_and_engine_agree_on_a_reclassified_row(self, session):
371 from sqlalchemy import select
372
373 from aram_backend.models import LedgerBalance, StatementLine
374 from aram_backend.services.statement_build import build_statements
375 from test_statement_build import _map, _note, _setup
376
377 year, source = _setup(session)
378 _carry(session, year, source, "148348", D(0), D(0), 3)
379 row = session.scalar(
380 select(LedgerBalance).where(
381 LedgerBalance.year_id == year.id, LedgerBalance.account_full_code == "148348"
382 )
383 )
384 row.statement_balance = D(777)
385 note = _note(session, year, "6", "نقد", "BS", "Assets")
386 _map(session, year, "148348", note)
387 session.flush()
388 build_statements(session, year.id)
389 session.flush()
390
391 line = session.scalar(select(StatementLine).where(StatementLine.target_note_id == note.id))
392 ctx = build_control_context(session, year.id)
393 assert line.mapped_total == D(777)
394 assert ctx.note_totals["BS:6"] == D(777)
395 assert ctx.line_totals["BS:6"] == D(777)
396 assert check_c07(ctx.note_totals, ctx.line_totals).passed