Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 13:00 UTC
fix(approval): make C-03 enforcement explicit + hard ERROR gate (audit #3, D5)
- approve_year loads rows AND mappings, passes both to evaluate_controls -> run_controls; C-03 (double mapping) and C-04 (unknown queue) always evaluated. Even one ERROR blocks Draft->Approved; no bypass path. - 13 negative/positive tests: double-mapping blocks via C-03, C-01/C-02/C-04 block, blocked approval writes no audit + stays Draft, non-draft/nonexistent rejected, clean ledger approves + audit chain valid, locked year immutable after approval, evaluate_controls proves mappings drive C-03/C-04 (incl. valid 100% split). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
davoodmehraban89 committed
Dec 3, 2026 at 10:35 UTC
1844a62920b41debaef33ed2185fe57fc9b1e3cf
2 files changed
+187
-23
backend/src/aram_backend/services/approval.py
+27
-23
@@ -1,20 +1,23 @@
1
-"""Approval gate (Phase 2, P-09): ERROR controls block Draft -> Approved.
1
+"""Approval gate (Phase 2, P-09, D5): ERROR controls block Draft -> Approved.
2
3
-Approval runs the full C-01..C-04 control set over the latest ledger import and
4
-active mappings. Any blocking ERROR refuses the transition and is reported; a
5
-clean pass transitions the year and writes a hash-chained audit entry.
3
+Approval runs the FULL C-01..C-04 control set over the latest ledger import AND
4
+the active mappings. Mappings are always passed to the controls — C-03 (no double
5
+mapping / valid 100% split) and C-04 (unknown queue) depend on them. Any blocking
6
+ERROR refuses the transition; a clean pass transitions the year and writes a
7
+hash-chained audit entry. There is no path that approves while a control fails.
8
"""
9
10
from __future__ import annotations
11
12
from dataclasses import dataclass
13
12
-from sqlalchemy import func, select
14
+from sqlalchemy import select
15
from sqlalchemy.orm import Session
16
17
from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
16
-from aram_backend.models import FiscalYear, FiscalYearStatus, LedgerBalance, MappingRule
18
+from aram_backend.models import FiscalYear, FiscalYearStatus, MappingRule
19
from aram_backend.services.audit import append_entry
20
+from aram_backend.services.ledger_aggregate import latest_raw_rows
21
22
23
class ApprovalError(ValueError):
@@ -28,20 +31,8 @@ class ApprovalResult:
31
controls: tuple[ControlResult, ...]
32
33
31
-def _controls(session: Session, year_id: int) -> list[ControlResult]:
32
- version = session.scalar(
33
- select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
34
- )
35
- balances = (
36
- session.scalars(
37
- select(LedgerBalance).where(
38
- LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
39
- )
40
- ).all()
41
- if version is not None
42
- else []
43
- )
44
- rows = [
34
+def _load_rows(session: Session, year_id: int) -> list[BalanceRow]:
35
+ return [
36
BalanceRow(
37
row_number=b.source_row,
38
account_code=b.account_full_code,
@@ -50,13 +41,23 @@ def _controls(session: Session, year_id: int) -> list[ControlResult]:
41
credit=b.credit,
42
closing=b.closing,
43
)
53
- for b in balances
44
+ for b in latest_raw_rows(session, year_id)
45
]
46
+
47
+
48
+def _load_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
49
mappings: dict[str, list[MappingTarget]] = {}
50
for rule in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all():
51
mappings.setdefault(rule.account_code, []).append(
52
MappingTarget(target=str(rule.target_note_id))
53
)
54
+ return mappings
55
+
56
+
57
+def evaluate_controls(
58
+ rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
59
+) -> list[ControlResult]:
60
+ """Run every control with the mappings explicitly supplied (C-03/C-04 need them)."""
61
return run_controls(rows, mappings)
62
63
@@ -67,9 +68,12 @@ def approve_year(session: Session, year_id: int, *, actor: str = "") -> Approval
68
if year.status != FiscalYearStatus.DRAFT:
69
raise ApprovalError(f"only a Draft year can be approved (current: {year.status.value})")
70
70
- controls = _controls(session, year_id)
71
+ rows = _load_rows(session, year_id)
72
+ mappings = _load_mappings(session, year_id)
73
+ controls = evaluate_controls(rows, mappings)
74
blocking = tuple(r for r in controls if r.severity == "ERROR" and not r.passed)
75
if blocking:
76
+ # Hard gate: even a single ERROR blocks approval (P-09, D5).
77
return ApprovalResult(approved=False, blocking=blocking, controls=tuple(controls))
78
79
year.status = FiscalYearStatus.APPROVED
@@ -84,4 +88,4 @@ def approve_year(session: Session, year_id: int, *, actor: str = "") -> Approval
88
return ApprovalResult(approved=True, blocking=(), controls=tuple(controls))
89
90
87
-__all__ = ["approve_year", "ApprovalResult", "ApprovalError"]
91
+__all__ = ["approve_year", "evaluate_controls", "ApprovalResult", "ApprovalError"]
backend/tests/test_approval_gate.py
new
+160
@@ -0,0 +1,160 @@
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.models import FiscalYear, FiscalYearStatus
15
+from aram_backend.services.approval import ApprovalError, approve_year, evaluate_controls
16
+from aram_backend.services.audit import verify_chain
17
+from test_statement_build import _balance, _map, _note, _setup
18
+
19
+
20
+def _balanced(session):
21
+ year, source = _setup(session)
22
+ _balance(session, year, source, "148348", 100, 3)
23
+ _balance(session, year, source, "241001", -60, 4)
24
+ _balance(session, year, source, "341001", -40, 5)
25
+ n_a = _note(session, year, "6", "نقد", "BS", "Assets")
26
+ n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
27
+ n_e = _note(session, year, "12", "سرمایه", "BS", "Equity")
28
+ _map(session, year, "148348", n_a)
29
+ _map(session, year, "241001", n_l)
30
+ _map(session, year, "341001", n_e)
31
+ session.flush()
32
+ return year, n_a
33
+
34
+
35
+class TestApprovalNegative:
36
+ def test_double_mapping_blocks_via_c03(self, session):
37
+ # The exact audit concern: one account mapped to TWO notes must block.
38
+ year, n_a = _balanced(session)
39
+ n_a2 = _note(session, year, "6b", "نقد دوم", "BS", "Assets")
40
+ _map(session, year, "148348", n_a2) # second mapping for the same account
41
+ session.flush()
42
+ result = approve_year(session, year.id)
43
+ assert not result.approved
44
+ assert any(r.code == "C-03" for r in result.blocking)
45
+ assert year.status == FiscalYearStatus.DRAFT
46
+
47
+ def test_c01_violation_blocks(self, session):
48
+ year, source = _setup(session)
49
+ _balance(session, year, source, "148348", 100, 3)
50
+ # Corrupt the closing so opening+debit-credit-closing != 0.
51
+ from aram_backend.models import LedgerBalance
52
+
53
+ b = session.query(LedgerBalance).filter_by(year_id=year.id).one()
54
+ b.closing = Decimal(999)
55
+ n = _note(session, year, "6", "نقد", "BS", "Assets")
56
+ _map(session, year, "148348", n)
57
+ session.flush()
58
+ result = approve_year(session, year.id)
59
+ assert not result.approved
60
+ assert any(r.code == "C-01" for r in result.blocking)
61
+
62
+ def test_c02_imbalance_blocks(self, session):
63
+ year, source = _setup(session)
64
+ _balance(session, year, source, "148348", 100, 3)
65
+ _balance(session, year, source, "148349", 50, 4) # no offsetting credit
66
+ n = _note(session, year, "6", "نقد", "BS", "Assets")
67
+ _map(session, year, "148348", n)
68
+ _map(session, year, "148349", n)
69
+ session.flush()
70
+ result = approve_year(session, year.id)
71
+ assert not result.approved
72
+ assert any(r.code == "C-02" for r in result.blocking)
73
+
74
+ def test_unmapped_blocks_via_c04(self, session):
75
+ year, source = _setup(session)
76
+ _balance(session, year, source, "148348", 100, 3)
77
+ session.flush()
78
+ result = approve_year(session, year.id)
79
+ assert not result.approved
80
+ assert any(r.code == "C-04" for r in result.blocking)
81
+
82
+ def test_blocked_approval_writes_no_audit_and_stays_draft(self, session):
83
+ year, source = _setup(session)
84
+ _balance(session, year, source, "148348", 100, 3)
85
+ session.flush()
86
+ approve_year(session, year.id)
87
+ session.commit()
88
+ from aram_backend.models import AuditEntry
89
+
90
+ assert session.query(AuditEntry).count() == 0
91
+ assert year.status == FiscalYearStatus.DRAFT
92
+
93
+ def test_non_draft_rejected(self, session):
94
+ year, _ = _balanced(session)
95
+ approve_year(session, year.id)
96
+ session.commit()
97
+ with pytest.raises(ApprovalError):
98
+ approve_year(session, year.id)
99
+
100
+ def test_nonexistent_year_rejected(self, session):
101
+ with pytest.raises(ApprovalError):
102
+ approve_year(session, 999999)
103
+
104
+
105
+class TestApprovalPositive:
106
+ def test_clean_ledger_approves_and_audits(self, session):
107
+ year, _ = _balanced(session)
108
+ result = approve_year(session, year.id, actor="reviewer")
109
+ session.commit()
110
+ assert result.approved
111
+ assert result.blocking == ()
112
+ assert year.status == FiscalYearStatus.APPROVED
113
+ assert verify_chain(session)
114
+
115
+ def test_locked_after_approval_is_immutable(self, session):
116
+ year, _ = _balanced(session)
117
+ approve_year(session, year.id)
118
+ session.commit()
119
+ year.status = FiscalYearStatus.LOCKED
120
+ session.commit()
121
+ from sqlalchemy import text
122
+ from sqlalchemy.exc import IntegrityError
123
+
124
+ with pytest.raises(IntegrityError):
125
+ session.execute(
126
+ text("UPDATE ledger_balances SET debit = 1 WHERE year_id = :y"), {"y": year.id}
127
+ )
128
+ session.rollback()
129
+
130
+
131
+class TestEvaluateControlsUsesMappings:
132
+ """Prove mappings are actually passed to the controls (C-03/C-04)."""
133
+
134
+ def _rows(self):
135
+ return [BalanceRow(row_number=3, account_code="148348", opening=Decimal(0),
136
+ debit=Decimal(100), credit=Decimal(0), closing=Decimal(100))]
137
+
138
+ def test_no_mappings_fails_c03_c04(self):
139
+ results = {r.code: r for r in evaluate_controls(self._rows(), {})}
140
+ assert not results["C-03"].passed
141
+ assert not results["C-04"].passed
142
+
143
+ def test_single_mapping_passes_c03_c04(self):
144
+ mappings = {"148348": [MappingTarget(target="1")]}
145
+ results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
146
+ assert results["C-03"].passed
147
+ assert results["C-04"].passed
148
+
149
+ def test_double_mapping_fails_c03(self):
150
+ mappings = {"148348": [MappingTarget(target="1"), MappingTarget(target="2")]}
151
+ results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
152
+ assert not results["C-03"].passed
153
+
154
+ def test_valid_100_split_passes_c03(self):
155
+ mappings = {
156
+ "148348": [MappingTarget(target="1", weight=Decimal(60)),
157
+ MappingTarget(target="2", weight=Decimal(40))]
158
+ }
159
+ results = {r.code: r for r in evaluate_controls(self._rows(), mappings)}
160
+ assert results["C-03"].passed