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

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

Synced Dec 4, 14:15 UTC

feat(ingestion): wire C-01..C-04 controls into preflight (D-02)

- services/preflight.run_preflight evaluates the blocking control set over parsed ledger rows + active mappings; PreflightReport exposes blocking results, can_approve, and the unknown-account queue (C-04) - Mappings loaded from the year's MappingRule rows or supplied directly (pure path) - ERROR results block approval (P-09); unmapped active accounts surface in the unknown queue for Phase 2 resolution Tests: clean ledger passes C-01/C-02, C-01 violation blocks, unmapped accounts queued, mapping clears queue, all four controls present, inactive accounts not queued. 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:26 UTC 8f2f902298ee269612753546989e8bf90092a0d7
2 files changed +164
backend/src/aram_backend/services/preflight.py new
+98
@@ -0,0 +1,98 @@
1 +"""Ingestion preflight: run blocking controls C-01..C-04 (D-02, booklet §7).
2 +
3 +The controls are evaluated against the parsed ledger rows and the active mapping
4 +rules *before* a fiscal year can be approved. ERROR results block approval
5 +(P-09); they are surfaced, never silently dropped. At ingestion time no mappings
6 +exist yet, so C-03/C-04 report the unknown-account queue — exactly the accounts
7 +that must be mapped in Phase 2 before approval.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from collections.abc import Iterable
13 +from dataclasses import dataclass
14 +from decimal import Decimal
15 +
16 +from sqlalchemy import select
17 +from sqlalchemy.orm import Session
18 +
19 +from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
20 +from aram_backend.domain.hierarchy import AccountLevels, canonical_full_code
21 +from aram_backend.ledger_parser import LedgerRecord
22 +from aram_backend.models import MappingRule
23 +
24 +
25 +@dataclass(frozen=True)
26 +class PreflightReport:
27 + results: tuple[ControlResult, ...]
28 +
29 + @property
30 + def blocking(self) -> tuple[ControlResult, ...]:
31 + return tuple(r for r in self.results if r.severity == "ERROR" and not r.passed)
32 +
33 + @property
34 + def can_approve(self) -> bool:
35 + return not self.blocking
36 +
37 + @property
38 + def unknown_accounts(self) -> tuple[str, ...]:
39 + for r in self.results:
40 + if r.code == "C-04":
41 + return r.affected
42 + return ()
43 +
44 +
45 +def _to_balance_rows(records: Iterable[LedgerRecord]) -> list[BalanceRow]:
46 + rows: list[BalanceRow] = []
47 + for rec in records:
48 + code = canonical_full_code(
49 + AccountLevels(general_code=rec.general_code or "", subsidiary_code=rec.account_code)
50 + )
51 + rows.append(
52 + BalanceRow(
53 + row_number=rec.row_number,
54 + account_code=code,
55 + opening=rec.opening,
56 + debit=rec.debit,
57 + credit=rec.credit,
58 + closing=rec.closing,
59 + )
60 + )
61 + return rows
62 +
63 +
64 +def _active_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
65 + rules = session.scalars(
66 + select(MappingRule).where(MappingRule.year_id == year_id)
67 + ).all()
68 + mappings: dict[str, list[MappingTarget]] = {}
69 + for rule in rules:
70 + mappings.setdefault(rule.account_code, []).append(
71 + MappingTarget(target=str(rule.target_note_id), weight=Decimal(100))
72 + )
73 + return mappings
74 +
75 +
76 +def run_preflight(
77 + records: Iterable[LedgerRecord],
78 + *,
79 + session: Session | None = None,
80 + year_id: int | None = None,
81 + mappings: dict[str, list[MappingTarget]] | None = None,
82 +) -> PreflightReport:
83 + """Evaluate C-01..C-04 over parsed records.
84 +
85 + ``mappings`` may be supplied directly (pure/test path) or loaded from the
86 + year's active MappingRule rows when ``session`` and ``year_id`` are given.
87 + """
88 + rows = _to_balance_rows(records)
89 + if mappings is None:
90 + mappings = (
91 + _active_mappings(session, year_id)
92 + if session is not None and year_id is not None
93 + else {}
94 + )
95 + return PreflightReport(results=tuple(run_controls(rows, mappings)))
96 +
97 +
98 +__all__ = ["PreflightReport", "run_preflight"]
backend/tests/test_preflight.py new
+66
@@ -0,0 +1,66 @@
1 +"""D-02 acceptance: controls C-01..C-04 run as an ingestion preflight."""
2 +
3 +from __future__ import annotations
4 +
5 +from decimal import Decimal
6 +
7 +from aram_backend.domain.controls import MappingTarget
8 +from aram_backend.ledger_parser import LedgerRecord
9 +from aram_backend.services.preflight import run_preflight
10 +
11 +
12 +def _rec(row, code, opening, debit, credit, closing, general="14"):
13 + return LedgerRecord(
14 + row_number=row, account_code=code, general_code=general,
15 + account_name="نمونه", source_year=1404, entry_type="O",
16 + t1_code=None, t2_code=None, t3_code=None, t4_code=None,
17 + opening=Decimal(opening), debit=Decimal(debit),
18 + credit=Decimal(credit), closing=Decimal(closing),
19 + )
20 +
21 +
22 +def test_clean_ledger_passes_c01_c02():
23 + # Two accounts that balance: debit total == credit total, closing sums to 0.
24 + records = [
25 + _rec(3, "8348", 0, 100, 0, 100),
26 + _rec(4, "8349", 0, 0, 100, -100),
27 + ]
28 + report = run_preflight(records)
29 + by_code = {r.code: r for r in report.results}
30 + assert by_code["C-01"].passed
31 + assert by_code["C-02"].passed
32 +
33 +
34 +def test_c01_violation_blocks():
35 + records = [_rec(3, "8348", 0, 100, 0, 999)] # closing wrong
36 + report = run_preflight(records)
37 + assert not report.can_approve
38 + assert any(r.code == "C-01" and not r.passed for r in report.blocking)
39 +
40 +
41 +def test_unmapped_accounts_enter_unknown_queue():
42 + records = [_rec(3, "8348", 0, 100, 0, 100)]
43 + report = run_preflight(records) # no mappings
44 + assert report.unknown_accounts == ("148348",)
45 + assert not report.can_approve # C-03/C-04 block approval
46 +
47 +
48 +def test_mapping_clears_unknown_queue():
49 + records = [_rec(3, "8348", 0, 100, 0, 100)]
50 + mappings = {"148348": [MappingTarget(target="note-1")]}
51 + report = run_preflight(records, mappings=mappings)
52 + assert report.unknown_accounts == ()
53 + by_code = {r.code: r for r in report.results}
54 + assert by_code["C-03"].passed
55 + assert by_code["C-04"].passed
56 +
57 +
58 +def test_all_four_controls_present():
59 + report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
60 + assert [r.code for r in report.results] == ["C-01", "C-02", "C-03", "C-04"]
61 +
62 +
63 +def test_inactive_account_not_queued():
64 + # All-zero account is inactive; must not enter the unknown queue.
65 + report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
66 + assert report.unknown_accounts == ()