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

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

Synced Dec 4, 14:15 UTC

R2 — full C-01..C-15 control set, fail-closed on unrun controls (#100)

* feat(pilot): working end-to-end Pilot Workbench (Excel in -> draft BS/IS out) Atomic V1 vertical slice on top of the accepted audit-safe foundation: - pilot_engine: deterministic in-memory BS/IS engine with explicit sign policy, fail-closed exceptions (unmapped/conflict/unsupported/CF-EQ), exact Decimal totals, trial-balance + accounting-equation checks, and reviewable 7-sheet Excel export with source-row drill-down. - pilot_store: bounded thread-safe in-memory sessions with audit trail; Reviewed/Approved mappings require reviewer evidence (contract parity). - pilot_api: /api/v1/pilot endpoints (upload, synthetic demo, mapping edits, export); preflight rejections return exact sheet/row/field issues. - Persian RTL workbench UI at /pilot/ (no external dependencies), root redirects to it; replaces nothing, quarantined prototype untouched. - 25 new tests; full suite 92 passed; migration round-trip unaffected. No canonical data/, samples/, models, or migrations changed. Demo data is synthetic and labelled everywhere. Output is a working draft, never an official financial statement. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): generic company-agnostic editing + mobile-first UI + save/resume Make the workbench a complete, reusable tool for any company, fully usable on a phone: - Full account CRUD: add/edit/rename/delete. Rename carries the mapping forward automatically. Manually added accounts derive closing from opening+debit-credit (never invented); duplicates/non-finite rejected. - Full note & sub-note CRUD: add/edit-title/delete. Deleting a note that is a mapping target is blocked (409) until mappings move. - Company edit: name/code/fiscal-year/unit/currency -> not tied to any entity. - Save/resume: GET workspace.xlsx serializes the working state to a valid Pilot v0.1 workbook; re-upload rebuilds it losslessly (verified round-trip). - Mutable WorkingModel + typed editing validators (pilot_editing.py); every change append-only audited; thread-safe snapshots. - Mobile-first UI: bottom navigation, bottom-sheet forms, card layouts, numeric keyboards, safe-area insets; partial list updates keep search focus. - Engine 1.1.0; PilotAccount now carries full hierarchy for lossless export. Tests: 107 passed (15 new editing/round-trip/API tests). No canonical data, samples, models or migrations changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(pilot): serve workbench directly at root (no redirect) for proxy safety The preview proxy can mishandle the / -> /pilot/ redirect hop. Serve the workbench HTML directly at / with absolute asset paths so the app loads in one request at both / and /pilot/. Update the root test accordingly. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): permanent browser edition (Pyodide) deployed via GitHub Pages - webapp/: mobile-first RTL UI shell + bridge.py (JSON dispatcher mirroring pilot_api.py, no FastAPI) running the exact tested engine in-browser - scripts/build_webapp.py: assembles docs/ from UI + unmodified engine copies - docs/: Pages source (app at site root, .nojekyll, engine under py/aram_backend) - Verified under Node+Pyodide 0.26.4: demo, CRUD, rename-with-mapping, company edit, lossless workspace round-trip, report export, preflight/duplicate errors, balance fail-closed semantics, COMPLETE_APPROVED end state Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(pilot): deploy browser edition to GitHub Pages (auto-enable) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(pilot): vendor Excel wheels + dual-CDN boot; permanent commit-pinned links - boot() installs vendored openpyxl/et_xmlfile wheels directly into site-packages (no PyPI/micropip at runtime) and falls back jsDelivr->unpkg - docs/vendor/ carries the two pure-Python wheels (268KB) - Pages workflow is dispatch-only (site creation requires owner action); app is served permanently via rawcdn.githack.com / cdn.jsdelivr.net gh - Final Node+Pyodide test of deployed bundle: full journey to COMPLETE_APPROVED, lossless workspace round-trip, 12 audit entries Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(domain): pure financial domain layer + parser/inspection fixes (Phase 0) Evidence-based ADRs from read-only probe of canonical 1404 ledger (252898 rows): - ADR-012 money: integer-rial BIGINT storage (Rial TypeDecorator), Decimal in Python, half-up + largest-remainder rounding only in output (P-02, D-03, OD-03) - ADR-013 sign: debit-positive confirmed (C-01 252892/252898 vs 37% credit-pos) - ADR-014 hierarchy: OD-01 default refuted (T1..T4 concat == حساب for 0 rows); kol->general, حساب->subsidiary, T1..T4->detail1..4; full code = kol+حساب (D-10) Domain (no I/O): normalize_fa/normalize_code/decimal_from_cell (P-03/P-04, D-04), Rial money, ledger<->Pilot hierarchy, blocking controls C-01..C-04 (D-02). ledger_parser delegates to domain (text codes keep leading zeros, exact float repr); workbook_inspection normalizes sheets/headers (D-05) and guards max_column=None (D-11). hypothesis added to test extra (ADR-012). Tests: 47 domain + 9 Phase-0 acceptance incl. bounded real-data evidence. Full suite 163 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): LedgerBalance model + exact-rial money column (D-01, D-03) - LedgerBalance: year-isolated, source-linked, text hierarchy codes, opening/ debit/credit/closing as Rial BIGINT; unique (year_id, account_full_code, import_version); new import version per Draft re-import (booklet §5) - StatementLine.mapped_total Numeric(24,4) -> Rial() (no float on SQLite, P-02) - ledger_parser extracts optional kol (general_code); hierarchy mapper accepts absent kol; services/ledger_import aggregates parsed rows by canonical account with exact Decimal summation - Migration 20261203_02 (guarded create + batch alter) runs on SQLite/PostgreSQL; up/down round-trip verified Tests: small-sample exact round-trip, large-rial BIGINT storage (>2^53) via ORM, duplicate-account aggregation, uniqueness, migration upgrade/downgrade. Full suite 168 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(source): content-addressed byte store + full CSV support (D-06) - SourceFile model (sha256 PK, size, content_type, stored_path) + SourceDocument FK; SourceStore writes immutable bytes atomically, re-verifies hash on read (corruption/tamper fails loudly); registration accepts optional store, keeps metadata-only model contract (accepted tests unchanged) - CSV ledger parser: UTF-8/UTF-8-BOM/Windows-1256, delimiter sniffing, same Persian normalization + exact-money rules as XLSX; parse_ledger routes by extension; streaming reader - Migration 20261203_03 (guarded create + batch add column) Tests: store round-trip/idempotency/corruption, registration+re-import hash match, CSV encodings/delimiters/leading-zeros/missing-header/empty/routing. 185 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(db): locked-year immutability triggers + hash-chained audit + reopen (D-07) - DB triggers (SQLite + PostgreSQL) block INSERT/UPDATE/DELETE on year-owned tables when the year is LOCKED, enforced even via raw SQL (P-08, D3) - Lifecycle trigger: Draft->Approved->Locked; Locked->Approved only with an approved ReopenRequest; protected years cannot be deleted - AuditEntry append-only (trigger) + hash chain (verify_chain detects tampering independently of the trigger); ReopenRequest model + ORM guard exemption - ADR-016 reopen/immutability model; migration 20261203_04 installs tables+triggers - ensure_triggers() helper; conftest installs triggers for all tests Tests: raw-SQL insert/update/delete blocked on locked year, draft writes allowed, reopen with/without approved request (ORM + raw SQL), audit chain build/verify/ tamper-detection/append-only. 195 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * 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> * ci: quality gates — ruff, mypy strict (domain), coverage, pip-audit, PG matrix (D-12) - pyproject: ruff/mypy/coverage/pytest-cov/pip-audit in test extra; psycopg in ci extra; ruff/mypy/coverage config (domain strict, total>=80%, domain>=90%) - CI: quality job (whitespace, ruff lint+format, mypy domain strict, coverage gates, pip-audit) + migration matrix job (SQLite + PostgreSQL service container, up/down/up round-trip) - ADR-017 documents the dev/CI-only dependencies (no runtime impact, P-10) - Lint fixes across backend (zip strict, StrEnum, specific test exceptions, unused vars); format applied to Phase-0 layers (domain/services/migrations) - pytest>=9.0.3 + pip/setuptools upgraded to clear pip-audit CVEs Gates verified locally: ruff clean, format clean, mypy domain strict clean, coverage total 92% / domain 97%, pip-audit no known vulnerabilities, 201 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: refresh PROJECT_STATUS + PROJECT_LOG for Phase 0 debts (D-08) Record D-01..D-12 states with commit evidence, real-data proof, ADRs 012/013/ 014/016/017, and local gate results (201 tests, coverage 92%/97%, pip-audit clean). D-09 marked BLOCKED (owner-only). No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * style: ruff format migration files (Phase-0 format gate) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(statements): persistent audited vertical slice + drill-down (Phase 1) - services/statement_build: build versioned BS/IS from latest LedgerBalance import + mappings/notes; exact integer-rial totals; display sign policy (ADR-013/018); unmapped active accounts surfaced; new version per build (never mutates snapshot) - drill_down: StatementLine -> Note -> MappingRule -> LedgerBalance -> SourceDocument (filename + SHA-256) + sheet + row (D2 full traceability) - statement_api: company/year setup, year-filtered ledger upload+import, notes, mappings, statement build/list, drill-down, preflight controls endpoint - ADR-018 persistent statements + drill-down contract Tests: BS/IS totals+signs, drill-down to source row, version increment, unmapped surfacing, API end-to-end (CSV->import->map->build->drilldown), preflight controls, bounded real-data smoke (3000 real 1404 rows -> import -> build -> drill-down). 209 passed; ruff/mypy/coverage gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(mapping): Excel I/O + unknown queue + approval gate + carry-forward (Phase 2) - mapping_io: governed Mappings workbook export/import; text codes; fail-closed per-row import with error report; idempotent re-import; auto-create notes - mapping_workflow: unknown-account queue (C-04 active unmapped); carry-forward notes+mappings into a Draft year (D1 continuity), idempotent - approval: approve_year runs C-01..C-04; blocking ERROR refuses Draft->Approved; clean pass transitions + hash-chained audit entry (P-09) - statement_api: mappings export/import, unknown-accounts, carry-forward, approve - ADR-019 mapping I/O + approval contract; shared api_client fixture in conftest Tests: export/import round-trip, invalid-row fail-closed, queue list/clear, approval blocked/success/non-draft, carry-forward copy/idempotent/reject, API end-to-end (queue->import mappings->approve). 220 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(notes): safe formula grammar + note engine (Phase 3) - domain/formula: hand-written tokenizer + recursive-descent parser -> whitelisted AST, exact Decimal evaluation; NO eval/exec (P-05); unknown tokens/functions fail closed; division-by-zero rejected; mypy --strict clean - services/note_engine: evaluate disclosure rows from latest ledger import; acct/ row/note/sum/abs functions; earlier-row + cross-note references with cycle detection; per-row referenced accounts for drill-down - statement_api: note-row create (formula validated on create), list, evaluate - ADR-020 formula grammar (mandatory pre-code ADR) Tests: 22 formula parse/eval/safety cases (injection rejected), note engine account/subtotal/cross-note/circular/forward-ref/unknown-account, API create+ evaluate+invalid-formula rejection. 250 passed; gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * WIP: Phase 4 golden comparison (partial, interrupted) - services/golden: data-derived note aggregation (source col0/col25) vs official sheets, half-up million-rial rounding, discrepancies writer (ADR-021) - statement_build: ALL_STATEMENTS constant (BS/IS/CF/EQ) - test_golden: real-data BS match + all-4 build (test run interrupted, unverified) Saved as WIP per owner instruction before priority architecture fixes. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(money): prove P-02 no-silent-rounding with exhaustive evidence (audit #1) - ADR-012 revised: exhaustive probe of BOTH ledgers (457,074 rows, 6 money columns) confirms zero fractional rial; scale-0 is lossless. Clarifies .to_integral_value() is a DETECTOR (raises on fractional), never a rounder; round_half_up is display-only. - 7 regression tests: fractional text/boundary rejected (not rounded), fractional through ORM and CSV import fail loudly (StatementError wrapping ValueError). No storage behavior change needed — the fail-loud design already satisfies P-02. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(ledger): store RAW rows for drill-down, aggregate in compute layer (audit #2, D3/P-01) - ledger_import: one LedgerBalance per source row (no import-time aggregation); source_row preserved so every figure traces to file/sheet/row (D3) - LedgerBalance uniqueness -> (year_id, source_document_id, source_row, import_version) - NEW services/ledger_aggregate: account-level totals via exact Decimal summation in the compute layer (latest import version) - unknown_accounts now aggregates raw rows by account (dedupe + row_count) - Migration 20261203_05 swaps the constraint on existing DBs + reinstalls triggers; fresh DBs get it from the live model. Round-trip verified, triggers preserved. - Test updated: duplicate accounts stored as 2 raw rows, aggregated in service. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * 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> * fix(services): mypy-clean services + generic golden columns + negative tests (audit #4) - Type-annotate all services so mypy passes (dict/tuple generics, cast, isinstance AST walks, typed sort key, renamed shadowed variable). - golden: resolve note/year/statement-balance columns BY HEADER NAME (1403 and 1404 ledgers have different layouts); fixes 1403 comparison, keeps it generic. - mapping_workflow negative tests: nonexistent carry-forward target, inactive accounts excluded, raw-row aggregation in queue, empty mapping workbook rejected. mypy services+domain clean; golden 1403+1404 real-data tests pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci: frontend gates (eslint/tsc/vitest/Playwright) + mypy services (audit #4, §14) - backend-ci: add 'Mypy (services)' gate (services now type-clean). - frontend-ci: eslint, tsc --noEmit, vitest, vite build, and Playwright e2e (chromium) with report artifact. - frontend/: Vite+React+TS RTL scaffold (Phase 5 foundation) with unit test (App.test.tsx), e2e specs (e2e/app.spec.ts), eslint flat config, tsconfig, playwright.config.ts, package-lock.json. Local: lint/tsc/vitest/build pass; playwright --list validates 2 specs. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * chore: drop unused import in approval gate test (ruff F401) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs: record Phases 1-4 + owner priority fixes in status/log (§0) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(import): tolerant real-ledger import + statement-balance capture (Phase 4/5) - Tolerant parse path (XLSX+CSV): reclassified rows with empty OPENING/Debit/ Credit/CLOSING are kept with exact zero; signed مانده صورت مالی stored as LedgerBalance.statement_balance (nullable Rial BIGINT, migration 20261203_06). Non-numeric money cells are skipped + reported (fail-loud, never invented); identity fields stay strictly required. Strict mode unchanged. - statement_build uses the effective balance: statement_balance rows contribute their pre-signed figure directly (reproduces Phase-4 golden); ordinary closing rows get the ADR-013 section sign. drill_down exposes effective/statement balance. - API upload uses tolerant import and returns skipped_rows for transparency. - 4 new tests (reclassified kept, anomaly skipped+reported, strict fails loud, statement_balance drives build + raw-row drill-down). Full suite: 285 passed. Real-data proof: source_1404.xlsx -> 131,280 raw rows imported, 4 anomalies reported; note->map->build->drill-down traced to exact source rows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): Phase 5 RTL workbench — setup/import/mapping/statements/drill-down/approval - Vite dev proxy forwards relative /api to FastAPI (no browser localhost calls); allowedHosts for the Arena live preview. - Typed API client + types; Persian-locale rial formatting. - Components: CompanySetup, LedgerUpload, MappingPanel (unknown-account queue, note creation, mapping import/export), StatementView (BS/IS/CF/EQ tabs, build, per-line drill-down), DrillDown (source file/sheet/row lineage), ApprovalPanel (controls + hard approval gate). - Unit tests (11): format, api client, CompanySetup, DrillDown, App shell. Playwright e2e: app smoke + full workflow (backend-gated via ARAM_E2E_BACKEND). - Gates: eslint/tsc/vitest/build pass; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(output): Phase 6 reviewable statement outputs (XLSX + JSON) with lineage - statement_export: latest-version BS/IS/CF/EQ + evaluated notes + full source lineage (file/SHA-256/sheet/row) as RTL XLSX (Summary/per-statement/Note/Lineage) and structured JSON. Exact integer-rial preserved; million-rial display-only (half-up, ADR-012). No new dependency (openpyxl). ADR-022. - API GET /years/{id}/statements/export?format=xlsx|json; workbench download buttons. - 3 tests (JSON exact rial + lineage, XLSX sheets/values, JSON serializable). Real-data proof: year 1404 export -> BS/IS, 340 lineage rows, Note 10; XLSX sheets Summary/BS/IS/Note 10/Lineage. Full suite: 288 passed; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(admin): Phase 7 users/roles, controlled reopen/lock, verifiable backup - User model + roles (admin/reviewer/preparer); PBKDF2-HMAC-SHA256 + per-user salt (stdlib, no plaintext, no network); require_role gate; first-user bootstrap. - Reopen/lock service: request->approve->reopen (LOCKED->APPROVED only with an approved request; ORM guard + DB trigger re-check, no bypass); lock APPROVED-> LOCKED; every step hash-chained audited. Migration 20261203_07 (round-trip OK). - Backup: consistent SQLite online-backup snapshot + source-store copy + SHA-256 manifest + audit-chain verification; verify_backup recomputes hashes + chain; tamper/non-empty-dest/broken-chain refused. ADR-023. - admin_api /api/v1: users, auth/login, audit(+verify), reopen/lock, backup(+verify) with 403 role gates. - 17 tests (users/auth/roles, reopen workflow + immutability, backup integrity + tamper, admin API bootstrap/login/gate/audit). Full suite: 305 passed. Live proof: bootstrap->admin, login, audit chain valid, backup+verify (1 source file), preparer backup -> 403. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): admin panel — login, audit verify, lock/reopen, backup/verify Phase 7 workbench surface: role-gated login, audit-chain check, year lock, reopen request->approve->reopen, and backup create/verify against the admin API. Gates: eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(desktop): Phase 8 offline desktop entrypoint + reproducible PyInstaller recipe - desktop.py: per-user data dir, idempotent SQLite schema + D-07 triggers, FastAPI + bundled React workbench served on 127.0.0.1 only (zero network). database.reconfigure rebinds the shared engine to the local file at launch. - packaging/aram.spec (one-folder Aram.exe) + build_desktop.py (npm build -> PyInstaller) + README. Binary is a build artifact, never committed (§19). ADR-024. - 3 tests: DB init creates schema+triggers (idempotent), desktop app serves health + API end-to-end, data-dir override. Full suite: 308 passed; mypy clean. Live proof: desktop app serves bundled RTL workbench at / (200) + health ok. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(e2e): update smoke spec to the workbench (company setup form, not counter) The Phase 5 workbench replaced the demo counter; the Playwright smoke test now asserts the RTL heading + company setup form (frontend-only, no backend needed). Fixes the Frontend CI e2e job. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs+uat: Phase 9 real-data UAT script + status/log for Phases 5-9 (§0/§18) scripts/uat_real_data.py exercises the full persistent pipeline on source_1404 (read-only): import->auto-map->build->golden reconcile->approval gate->export-> backup->audit. Records reviewable evidence; report is not a committed artifact. PROJECT_STATUS + PROJECT_LOG updated with Phases 5-9 and UAT results. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(review): role-gate approve + editable notes/mappings/rows (5-agent review) Findings from the deep compliance review: - F3-1: API /approve now enforces reviewer/admin role once local users exist (consistent with /lock and /reopen); bootstrap/dev (no users) stays open; the C-01..C-04 ERROR gate always applies. +2 negative/positive tests. - F2-1: add PUT/DELETE for notes, mappings, note rows + GET list notes/mappings, satisfying the owner's editable codes/accounts/notes/subnotes requirement. Draft-guarded; D-07 immutability translated to HTTP 409; note delete refuses while mappings/statement lines reference it (rows cascade). +9 tests incl. locked-year edit refusal. - F5-1: document python-multipart upload dependency in ADR-018. Full suite: 319 passed; mypy services clean; ruff clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(ui): notes/mappings manager (edit/delete) wired to the editing API NotesManager lists notes (inline title edit + delete) and mappings (delete), refreshing after each change. eslint/tsc/vitest/build pass. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * docs(review): 5-pass booklet compliance review report + log (§0) Records the five reviewer mandates, evidence, findings (F2-1/F3-1/F5-1 fixed, O5-1 noted) and per-agent verdicts. All passes PASS after fixes; 319 tests green. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * B0: booklet reference + lightweight-process reconciliation - docs/booklet/BOOKLET_v1.0.md + MANIFEST.json (original PDF SHA-256 anchor; ADR-025) - PROJECT_STATUS.md rewritten to GitHub reality (Phases 0-9 MERGED @46253c9, 319 tests, post-merge CI; stale V1-01/unmerged rows removed; D-08 closed) - 14 root analytical docs git mv -> docs/archive/ (+ index); no new root analytical doc (booklet §0.5) - AGENTS.md <-> §0.5 conflict resolved: handoff cadence per-category, lightweight-process bullets (ADR-026) - docs/discrepancies.json skeleton {row,our_amount,official_amount,cause,evidence,year} (OD-08; B8 populates) - docs/PROJECT_LOG.md + LATEST_HANDOFF.md refreshed (end-of-category) - data/ + samples/ tree hashes unchanged (docs/process only) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0: booklet 2 course correction (بخش الف) - الف‌1: remove Pyodide/Pages/CDN browser edition (webapp/, docs built output, docs/vendor wheels, scripts/build_webapp.py, pilot-pages.yml); recoverable from history @46253c9; ADR-028 - booklet 2 v2.0 verbatim -> docs/booklet/BOOKLET_v2.0.md + MANIFEST.json (SHA-256 anchor); ADR-027 (C0..C10 supersedes B framing; OD-09..14; generality rule; databansoft not reachable) - الف‌6: docs/PR_TRIAGE.md (ADOPT #81/#89/#92; CLOSE NO-GO #82/#88; SUPERSEDED #90/#91 + #22-#80) - الف‌4/5 + ب‌1 + §16: PR honesty/size, generality grep, offline/read-only/no-plaintext rules in AGENTS.md - الف‌2/3 verified: persistent core (domain+statement_api/admin_api on LedgerBalance) is main path; phase 0/1 + golden merged @46253c9 - PROJECT_STATUS.md -> C0..C10 roadmap + C0 progress + الف‌7; PROJECT_LOG + handoff refreshed - data/ + samples/ tree hashes unchanged; backend 319 passed, frontend lint/tsc/vitest(11)/build green (no regression) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 addendum: booklet 2 appendix revision (owner) + ADR-029 - appendix replaced verbatim: Databan catalog studied by owner (marketing, unverified); positioning = independent pluggable product + Host Integration API; accepted elements 1-10; rejected scope; legal restriction - OD-09 REVISED: pyodbc-first (existing ODBC driver, Windows+SQL Server), python-tds fallback (ADR-027 updated, ADR-029) - ADR-029: positioning, OD-14 capability comparison, element->phase mapping (C4-C9/C11), C11 AI constraints (never generates numbers) - PROJECT_STATUS: C5/C7/C8/C9 scope notes + C11 row + positioning; PROJECT_LOG + handoff updated - BOOKLET_v2.0.md re-anchored: SHA-256 79618ddd...; MANIFEST.json revision history kept - docs-only addendum; code identical to tested C0 tree (backend 319 passed, frontend green); data/ + samples/ unchanged Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * C0 remediation: populate discrepancies.json (الف‌7) + record review findings - الف‌7 met: golden.compare_year(1404) re-run -> 28/9 matched/19 diffs; docs/discrepancies.json populated one-by-one with cause + reproducible evidence + source/official SHA-256 (16 caused: 8 exact-magnitude sign flips ADR-013, CF note reuse, absent/underived notes; 3 under_investigation: IS 6/8/9 = bugs until proven D1); EQ official parsing gap recorded - ADR-028: owner's explicit experiment/browser-edition instruction recorded; Arena single-branch block reported; preservation guaranteed via tag v1.0.0 -> 46253c9 - PROJECT_STATUS: review deviations tracked (forgeable actor auth C8, 4/15 controls C3, desktop create_all bypasses Alembic C9, PR #96 discipline violation historical, booklet-1 extraction artifacts disclosed); الف‌7 marked MET - Fresh evidence: backend 319 tests exit 0; D-04/D-05 normalization 17 passed - docs-only; data/ + samples/ trees unchanged; no second PR (owner directive) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(R1): real server-side session authentication (booklet 2.1) Identity now comes only from a server-side session. `actor` is removed from every request model; a login issues a random 256-bit bearer token whose SHA-256 is the only thing stored, with an 8-hour absolute TTL, logout revocation and a 5-attempt / 15-minute lockout. PBKDF2 rises to 600,000 rounds (Argon2 absent, no new runtime dependency); legacy 200,000-round hashes are rehashed on first login. A single `current_user` dependency guards the statement, admin, schema and pilot routers. Only /health, /auth/login, /auth/launch and the one-time first-admin bootstrap are reachable without a session; reads require login too. Approval without users is impossible, and the role gate runs before the existence check. Backup `dest` is confined to the data folder (traversal, absolute and symlink escapes refused). The desktop launcher gates the local API with a one-time token passed in the URL fragment and exchanged once for an X-Aram-Launch grant. The legacy pilot router, /pilot mount and the HTML at / are out of the app; the interactive schema browsers are disabled. Frontend: LoginPanel gates the workbench, session.ts owns the token in sessionStorage, client.ts attaches it to every request and clears it on 401, and exports became authenticated fetch+blob downloads instead of bare links. Migration 20261204_08 adds auth_sessions + lockout/work-factor columns, verified on a populated copy (131,280 ledger rows, 2 users, 28 triggers unchanged). Decisions: ADR-030. Tests: backend 354 passed (33 new R1 acceptance tests), frontend 15 vitest tests, new real-session e2e (CI now runs uvicorn). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): give the real-ledger e2e a realistic timeout and readable CI failures The workflow e2e was previously skipped in CI (no backend); now that CI starts uvicorn it actually runs, and Playwright's default 30s test timeout killed it while the 131k-row ledger import was still in flight. Raise the test timeout, run one worker against the shared backend, and add the github + html reporters so failures surface as check-run annotations and an uploaded report. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * ci(R1): migrate the throwaway e2e database before starting uvicorn The dev app deliberately does not create the schema (R4 owns startup migrations), so the fresh CI database had no tables and the first-admin bootstrap failed, which made every real-session e2e fail at the login step. Run 'alembic upgrade head' against the e2e database first — verified locally on a fresh DB: 16 tables + 28 triggers, then bootstrap 200, login 200, company 200, audit 200, logout 200, me-after-logout 401. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): disambiguate e2e selectors now that the login screen exists The login card adds an h2 containing 'آرام', so the heading query must target level 1. The ledger import button query matched both 'درون‌ریزی' and 'درون‌ریزی نگاشت‌ها' — a pre-existing ambiguity that only surfaced once the workflow e2e actually ran with a backend. Also trims docs to stay at the 1,500-line cap after the CI/config additions. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * test(R1): seed one real mapping in the workflow e2e before building The workflow e2e had never run in CI (no backend), and it built statements without any mapping: every account stayed unmapped, so the statements had zero lines and the drill-down step had nothing to click. Capture the year id from the company response, map one real account from the unknown-accounts queue to a new BS/Assets note using the session token, then build. Also raises the import assertion timeout to match the 131k-row workbook. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * feat(controls): R2 — full C-01..C-15 control set with fail-closed unrun handling Booklet 2.1 R2. Eleven new pure controls (C-05..C-15) with Persian messages and the booklet 1 section 7 severities; run_controls always returns all fifteen. - ControlResult.ran separates 'failed' from 'could not run'; an unrun ERROR blocks approval and reports «اجرا نشد: دلیل» (never a silent pass). - services/control_context.py gathers inputs from stored data only: prior-year closing, BS sections under the ADR-013 sign policy, (statement, note) totals, IS result, equity movements, CF net change, cash, declared codes, natures. - Control roles are explicit data (retained_earnings / cash), never inferred from a title; exposed on note create/update and in the notes manager. - A refused approval is now audited (approved:false + blocking + unrun codes). - POST /companies/{id}/years so a prior year can be loaded, otherwise C-05 would make approval permanently impossible. - Preflight returns ran; the UI shows «اجرا نشد» apart from «رد». Evidence: backend 404 passed (was 354), frontend 17 vitest / 6 files, ruff + mypy + tsc + eslint + build clean; live 131,280-row preflight shows 15 controls. Decisions: ADR-031. Authored lines excl. tests/data: 1003/1500. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> * fix(controls): controls read the same figure as the statement engine build_statements treats a reclassified row's statement_balance as authoritative and already presentation-signed (ADR-013/018). The R2 context builder used raw closing, so C-06/C-07 would have compared two different rules and invented differences on exactly those rows. BalanceRow now carries statement_balance and one display(sign) method; the context uses it. C-01/C-02 still audit the raw debit/credit columns. Witness: TestReclassifiedRowsAgreeWithTheEngine — engine line total, context note total and context line total all 777 on a row whose CLOSING is 0. ADR-031 §5. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --------- Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> Co-authored-by: Arena Agent <agent@arena.ai>

davoodmehraban89 committed Dec 4, 2026 at 14:10 UTC a8ba20c1bc5595ceaa73ff30be8dd91748a87a6e
21 files changed +1624 -130
PROJECT_STATUS.md
+21 -3
@@ -91,8 +91,8 @@ Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/
91
92 | Task | Scope | Status |
93 | --- | --- | --- |
94 -| R1 | Real authentication (backend + frontend), backup confinement, desktop launch token, legacy surfaces | **MET** (this PR; evidence below) |
95 -| R2 | Controls C-05..C-15 wired into `run_controls` + approval | NOT_STARTED |
94 +| R1 | Real authentication (backend + frontend), backup confinement, desktop launch token, legacy surfaces | **MET** — PR #98 squash-merged 2026-12-04T09:38:06Z → `07a8ae0e` |
95 +| R2 | Controls C-05..C-15 wired into `run_controls` + approval | **MET** (this PR; evidence below) |
96 | R3 | `build_statements` vs official; (statement, note) aggregation; IS 6/8/9 root cause; EQ/CF parsing | NOT_STARTED |
97 | R4 | Remove `create_all` from the production path; backup → `alembic upgrade head` → trigger check | NOT_STARTED |
98 | R5 | `docs/c01_exceptions.json` — the six C-01 source rows, unapprovable until resolved | NOT_STARTED |
@@ -108,11 +108,29 @@ ledger rows, 2 users, 28 triggers unchanged.
108
109 Backend **354 passed** (was 319); frontend **15 vitest tests / 5 files**; ruff, mypy, tsc, eslint all clean.
110
111 +### R2 acceptance ← evidence
112 +
113 +| معیار پذیرش | شاهد |
114 +| --- | --- |
115 +| C-05..C-15 implemented as pure functions with Persian messages and booklet 1 §7 severities | `backend/src/aram_backend/domain/controls.py` (`check_c05`…`check_c15`); `tests/test_controls_r2.py` positive + negative case per control |
116 +| `run_controls` always returns the full set | `TestFullSet::test_fifteen_controls_always_present`; `test_domain_controls.py::test_stable_order`; `test_preflight.py::test_all_fifteen_controls_present` |
117 +| Approval runs every ERROR control | `services/approval.py` → `build_control_context`; `TestCompleteYearThroughApi::test_all_fifteen_run_and_approval_succeeds` |
118 +| Missing input ⇒ «اجرا نشد: دلیل» **and** approval blocked | `TestApprovalRejectsIncompleteControls`, `TestPreflightApi::test_approval_is_rejected_when_error_controls_did_not_run`; live 1404 preflight shows 8 unrun controls and `can_approve: false` |
119 +| **15 controls visible in preflight** | `GET /api/v1/years/1/preflight` on the live 131,280-row DB → `controls: 15` (7.2 s); `TestPreflightApi::test_preflight_returns_fifteen_controls_with_ran_flags` |
120 +| WARN never blocks; C-13 ERROR in CI / INFO in UI | `TestC13Official`, `TestC14SuddenChange::test_large_change_warns_not_blocks`, `TestFullSet::test_failing_warn_is_not_a_blocking_severity` |
121 +
122 +Backend **404 passed / exit 0** (was 354); frontend **17 vitest tests / 6 files**; ruff check + format, mypy (23 files), tsc, eslint, build all clean.
123 +Decisions in **ADR-031**: unrun ≠ pass; explicit note roles (never inferred); refused approvals are audited; `POST /companies/{id}/years` so a prior year can actually be loaded.
124 +Authored lines excl. tests/data: **968 / 1500**.
125 +
126 ## Known gaps feeding the C-phases (honest residual risks)
127
128 - **Authorization forgeability — CLOSED in R1 (2026-12-04, ADR-030).** Was: roles derived from a client-supplied `actor` body string; `"actor":"admin"` granted admin to anyone; most endpoints unguarded; approval open when no users existed; `pilot_api.py` exposed 17 unauthenticated routes. Now: `actor` removed from every request model; identity comes only from `current_user` resolving a 256-bit bearer token whose SHA-256 is stored server-side (8-hour absolute TTL, logout, 5-attempt lockout for 15 minutes, PBKDF2 600,000); every route except `/health`, `/auth/login`, `/auth/launch` and the one-time first-admin bootstrap requires a session, reads included; approval without users is impossible; the pilot router and the legacy `/` UI are out of the app; backup `dest` is confined to the data folder; the desktop launcher gates the local API with a one-time token. Evidence: `backend/tests/test_auth_r1.py` (33 tests). Remaining C8 scope: DPAPI vault, encrypted backup, plugin allowlist, row/field-level access layers.
129 - `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (C7).
115 -- **Only 4 of 15 controls implemented** (`domain/controls.py` = C-01..C-04); approval depends only on these, so a year with an unbalanced BS or note/statement mismatch can be approved. C-05..C-15 absent → **R2** (booklet 2.1; was C3): wire all ERROR controls into `run_controls` + approval gate; a control lacking inputs must report «اجرا نشد: دلیل» and block approval.
130 +- ~~Only 4 of 15 controls implemented~~ — **closed by R2**: all C-01..C-15 run, an unrun ERROR blocks approval and reports «اجرا نشد: دلیل» (ADR-031).
131 +- **C-13 has no official-comparison feed yet** (reports «اجرا نشد», INFO in the UI): the `build_statements`-vs-official comparison is **R3** work; until then C-13 cannot pass in CI mode.
132 +- **Account natures are not populated** by any import path (`account_versions` is empty on real data), so C-15 reports «اجرا نشد» (WARN, non-blocking). A chart-of-accounts import is still missing.
133 +- **C-07 only compares notes that have a rendered statement line**: CF/EQ are not rendered yet (`RENDERED_STATEMENTS=("BS","IS")`), so their note totals are compared against nothing → R3.
134 - **Desktop install bypasses Alembic** (`desktop.py` `Base.metadata.create_all`); existing user DBs will not migrate on update → **R4** (booklet 2.1; was C9). R1 added migration `20261204_08` and verified it on a copy of a populated database (131,280 ledger rows, 2 users, 28 triggers unchanged), but the startup path still uses `create_all`.
135 - ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
136 - `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
backend/src/aram_backend/domain/controls.py
+342 -6
@@ -1,10 +1,14 @@
1 -"""Blocking financial controls C-01..C-04 (booklet section 7, debt D-02).
1 +"""Blocking financial controls C-01..C-15 (booklet 1 section 7; R2 of booklet 2.1).
2
3 Pure, deterministic functions over balance rows and active mappings. Each
4 returns a :class:`ControlResult` with a Persian message and the affected
5 accounts/rows. ERROR severity blocks approval (P-09); these are not ignorable
6 warnings. Sign convention is debit-positive (ADR-013, evidence: 252892/252898
7 canonical rows satisfy C-01 under debit-positive vs 37% under credit-positive).
8 +
9 +R2 rule (booklet 2.1): a control whose inputs are unavailable reports
10 +"اجرا نشد: <دلیل>" and **blocks approval** — an unrun ERROR control is never
11 +treated as a pass. Optional inputs travel in :class:`ControlContext`.
12 """
13
14 from __future__ import annotations
@@ -17,7 +21,13 @@ _ZERO = Decimal(0)
21
22 @dataclass(frozen=True)
23 class BalanceRow:
20 - """One ledger balance row (all amounts exact Decimal rial)."""
24 + """One ledger balance row (all amounts exact Decimal rial).
25 +
26 + ``statement_balance`` is the reclassified presentation figure some source rows
27 + carry instead of CLOSING. It is already presentation-signed, so controls that
28 + feed statement comparisons must use it exactly as ``build_statements`` does
29 + (ADR-013/018); C-01/C-02 still audit the raw debit/credit columns.
30 + """
31
32 row_number: int
33 account_code: str
@@ -25,6 +35,13 @@ class BalanceRow:
35 debit: Decimal
36 credit: Decimal
37 closing: Decimal
38 + statement_balance: Decimal | None = None
39 +
40 + def display(self, sign: Decimal) -> Decimal:
41 + """The figure a statement line would show for this row under ``sign``."""
42 + if self.statement_balance is not None:
43 + return self.statement_balance
44 + return self.closing * sign
45
46
47 @dataclass(frozen=True)
@@ -42,6 +59,70 @@ class ControlResult:
59 passed: bool
60 message_fa: str
61 affected: tuple[str, ...] = field(default_factory=tuple)
62 + ran: bool = True
63 +
64 +
65 +@dataclass(frozen=True)
66 +class EquityMovement:
67 + """One equity row: opening + changes must equal closing (C-09)."""
68 +
69 + label: str
70 + opening: Decimal
71 + changes: Decimal
72 + closing: Decimal
73 +
74 +
75 +@dataclass(frozen=True)
76 +class OfficialComparison:
77 + """One (statement, note) comparison against the official statements (C-13)."""
78 +
79 + key: str
80 + ours: Decimal
81 + official: Decimal
82 +
83 +
84 +@dataclass(frozen=True)
85 +class ControlContext:
86 + """Optional inputs for C-05..C-15. ``None`` means "not available".
87 +
88 + Every unavailable input makes its control report «اجرا نشد» and block
89 + approval, so a year can never be approved on an incomplete control set.
90 + """
91 +
92 + prior_closing: dict[str, Decimal] | None = None
93 + bs_sections: dict[str, Decimal] | None = None
94 + note_totals: dict[str, Decimal] | None = None
95 + line_totals: dict[str, Decimal] | None = None
96 + is_net_profit: Decimal | None = None
97 + eq_retained_change: Decimal | None = None
98 + explicit_adjustments: Decimal = _ZERO
99 + eq_movements: tuple[EquityMovement, ...] | None = None
100 + cf_net_change: Decimal | None = None
101 + cash_opening: Decimal | None = None
102 + cash_closing: Decimal | None = None
103 + known_codes: frozenset[str] | None = None
104 + natures: dict[str, str] | None = None
105 + note_ids: frozenset[str] | None = None
106 + official: tuple[OfficialComparison, ...] | None = None
107 + mode: str = "ui" # "ci" makes C-13 ERROR; "ui" makes it INFO (booklet 1 §7)
108 + change_threshold_pct: Decimal = Decimal(50)
109 +
110 +
111 +def _not_run(code: str, severity: str, reason: str) -> ControlResult:
112 + """An unrun control never passes: it blocks and says why (booklet 2.1 R2)."""
113 + return ControlResult(
114 + code=code, severity=severity, passed=False, message_fa=f"اجرا نشد: {reason}", ran=False
115 + )
116 +
117 +
118 +def _result(code: str, severity: str, bad: tuple[str, ...], ok: str, fail: str) -> ControlResult:
119 + return ControlResult(
120 + code=code,
121 + severity=severity,
122 + passed=not bad,
123 + message_fa=ok if not bad else fail,
124 + affected=bad,
125 + )
126
127
128 def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]:
@@ -144,20 +225,275 @@ def check_c04(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]])
225 )
226
227
228 +def check_c05(rows: list[BalanceRow], prior_closing: dict[str, Decimal] | None) -> ControlResult:
229 + """C-05: prior-year closing == current-year opening, account by account."""
230 + if prior_closing is None:
231 + return _not_run("C-05", "ERROR", "مانده پایان سال مالی قبل در دسترس نیست")
232 + opening = {code: b["opening"] for code, b in _aggregate(rows).items()}
233 + bad = tuple(
234 + code
235 + for code in sorted(set(opening) | set(prior_closing))
236 + if opening.get(code, _ZERO) != prior_closing.get(code, _ZERO)
237 + )
238 + return _result(
239 + "C-05",
240 + "ERROR",
241 + bad,
242 + "مانده پایان سال قبل با مانده ابتدای سال جاری برای همهٔ حساب‌ها برابر است",
243 + f"{len(bad)} حساب مانده ابتدای سالشان با پایان سال قبل نمی‌خواند",
244 + )
245 +
246 +
247 +def check_c06(bs_sections: dict[str, Decimal] | None) -> ControlResult:
248 + """C-06: assets == liabilities + equity on the balance sheet."""
249 + if bs_sections is None:
250 + return _not_run("C-06", "ERROR", "صورت وضعیت مالی ساخته نشده است")
251 + missing = [k for k in ("Assets", "Liabilities", "Equity") if k not in bs_sections]
252 + if missing:
253 + return _not_run("C-06", "ERROR", f"بخش‌های غایب در ترازنامه: {'، '.join(missing)}")
254 + assets = bs_sections["Assets"]
255 + other = bs_sections["Liabilities"] + bs_sections["Equity"]
256 + return _result(
257 + "C-06",
258 + "ERROR",
259 + () if assets == other else ("balance_sheet",),
260 + "معادلهٔ ترازنامه برقرار است: دارایی‌ها = بدهی‌ها + حقوق مالکانه",
261 + "معادلهٔ ترازنامه نقض شده است: دارایی‌ها ≠ بدهی‌ها + حقوق مالکانه",
262 + )
263 +
264 +
265 +def check_c07(
266 + note_totals: dict[str, Decimal] | None, line_totals: dict[str, Decimal] | None
267 +) -> ControlResult:
268 + """C-07: each note total equals its statement line, keyed by (statement, note)."""
269 + if note_totals is None or line_totals is None:
270 + return _not_run("C-07", "ERROR", "جمع یادداشت‌ها یا سطرهای صورت در دسترس نیست")
271 + bad = tuple(
272 + key
273 + for key in sorted(set(note_totals) | set(line_totals))
274 + if note_totals.get(key, _ZERO) != line_totals.get(key, _ZERO)
275 + )
276 + return _result(
277 + "C-07",
278 + "ERROR",
279 + bad,
280 + "جمع هر یادداشت با سطر متناظر در صورت برابر است",
281 + f"{len(bad)} یادداشت جمعشان با سطر متناظر صورت نمی‌خواند",
282 + )
283 +
284 +
285 +def check_c08(
286 + is_net_profit: Decimal | None,
287 + eq_retained_change: Decimal | None,
288 + explicit_adjustments: Decimal = _ZERO,
289 +) -> ControlResult:
290 + """C-08: IS net result == change in retained earnings (EQ) + explicit adjustments."""
291 + if is_net_profit is None or eq_retained_change is None:
292 + return _not_run("C-08", "ERROR", "سود خالص یا تغییر سود انباشته در دسترس نیست")
293 + passed = is_net_profit == eq_retained_change + explicit_adjustments
294 + return _result(
295 + "C-08",
296 + "ERROR",
297 + () if passed else ("retained_earnings",),
298 + "سود و زیان خالص با تغییر سود انباشته (با اصلاحات صریح) برابر است",
299 + "سود و زیان خالص با تغییر سود انباشته نمی‌خواند",
300 + )
301 +
302 +
303 +def check_c09(eq_movements: tuple[EquityMovement, ...] | None) -> ControlResult:
304 + """C-09: for every equity row, opening + changes == closing."""
305 + if eq_movements is None:
306 + return _not_run("C-09", "ERROR", "صورت تغییرات حقوق مالکانه ساخته نشده است")
307 + if not eq_movements:
308 + return _not_run("C-09", "ERROR", "هیچ ردیف حقوق مالکانه‌ای برای بررسی وجود ندارد")
309 + bad = tuple(m.label for m in eq_movements if m.opening + m.changes != m.closing)
310 + return _result(
311 + "C-09",
312 + "ERROR",
313 + bad,
314 + "برای هر ردیف حقوق مالکانه: مانده ابتدا + تغییرات = مانده پایان",
315 + f"{len(bad)} ردیف حقوق مالکانه معادلهٔ مانده را نقض می‌کنند",
316 + )
317 +
318 +
319 +def check_c10(
320 + cf_net_change: Decimal | None, cash_opening: Decimal | None, cash_closing: Decimal | None
321 +) -> ControlResult:
322 + """C-10: CF net change in cash == closing cash - opening cash (per BS)."""
323 + if cf_net_change is None or cash_opening is None or cash_closing is None:
324 + return _not_run("C-10", "ERROR", "جریان نقدی یا مانده‌های نقد ترازنامه در دسترس نیست")
325 + passed = cf_net_change == cash_closing - cash_opening
326 + return _result(
327 + "C-10",
328 + "ERROR",
329 + () if passed else ("cash_flow",),
330 + "تغییر خالص وجه نقد با تفاضل مانده نقد پایان و ابتدا برابر است",
331 + "تغییر خالص وجه نقد با تفاضل مانده نقد ترازنامه نمی‌خواند",
332 + )
333 +
334 +
335 +def check_c11(rows: list[BalanceRow], known_codes: frozenset[str] | None) -> ControlResult:
336 + """C-11: every subsidiary has its general parent; children sum to a posted parent.
337 +
338 + Canonical identity is general + subsidiary (ADR-014), so the parent of a
339 + subsidiary code is its leading general code.
340 + """
341 + if known_codes is None:
342 + return _not_run("C-11", "ERROR", "فهرست کدهای حساب سال در دسترس نیست")
343 + totals = _aggregate(rows)
344 + bad: list[str] = []
345 + children: dict[str, Decimal] = {}
346 + for code, bucket in sorted(totals.items()):
347 + if len(code) <= 2:
348 + continue
349 + parent = code[:2]
350 + if parent not in known_codes:
351 + bad.append(code)
352 + continue
353 + children[parent] = children.get(parent, _ZERO) + bucket["closing"]
354 + for parent, total in sorted(children.items()):
355 + if parent in totals and totals[parent]["closing"] != total:
356 + bad.append(parent)
357 + return _result(
358 + "C-11",
359 + "ERROR",
360 + tuple(bad),
361 + "سلسله‌مراتب حساب‌ها برقرار است: والد موجود و جمع فرزندان = والد",
362 + f"{len(bad)} کد سلسله‌مراتب را نقض می‌کنند (والد غایب یا جمع ناسازگار)",
363 + )
364 +
365 +
366 +def check_c12(
367 + mappings: dict[str, list[MappingTarget]], note_ids: frozenset[str] | None
368 +) -> ControlResult:
369 + """C-12: no note without a mapping, and no mapping to a nonexistent note."""
370 + if note_ids is None:
371 + return _not_run("C-12", "ERROR", "فهرست یادداشت‌های سال در دسترس نیست")
372 + targets = {t.target for targets in mappings.values() for t in targets}
373 + orphan_notes = tuple(sorted(note_ids - targets))
374 + dangling = tuple(sorted(targets - note_ids))
375 + bad = orphan_notes + dangling
376 + return _result(
377 + "C-12",
378 + "ERROR",
379 + bad,
380 + "هر یادداشت نگاشت دارد و هیچ نگاشتی به یادداشت ناموجود اشاره نمی‌کند",
381 + f"{len(orphan_notes)} یادداشت بدون نگاشت و {len(dangling)} نگاشت به یادداشت ناموجود",
382 + )
383 +
384 +
385 +def check_c13(official: tuple[OfficialComparison, ...] | None, mode: str = "ui") -> ControlResult:
386 + """C-13: agreement with the official statements — ERROR in CI, INFO in the UI."""
387 + severity = "ERROR" if mode == "ci" else "INFO"
388 + if official is None:
389 + return _not_run("C-13", severity, "صورت‌های رسمی برای مقایسه در دسترس نیست")
390 + bad = tuple(c.key for c in official if c.ours != c.official)
391 + return _result(
392 + "C-13",
393 + severity,
394 + bad,
395 + "خروجی با صورت‌های رسمی مطابقت دارد",
396 + f"{len(bad)} قلم با صورت‌های رسمی اختلاف دارد",
397 + )
398 +
399 +
400 +def check_c14(
401 + rows: list[BalanceRow],
402 + prior_closing: dict[str, Decimal] | None,
403 + threshold_pct: Decimal = Decimal(50),
404 +) -> ControlResult:
405 + """C-14 (WARN): movement beyond the threshold relative to the prior year."""
406 + if prior_closing is None:
407 + return _not_run("C-14", "WARN", "مانده سال قبل برای تحلیل تغییر در دسترس نیست")
408 + bad: list[str] = []
409 + for code, bucket in sorted(_aggregate(rows).items()):
410 + prior = prior_closing.get(code, _ZERO)
411 + if prior == _ZERO:
412 + continue
413 + change_pct = abs(bucket["closing"] - prior) / abs(prior) * Decimal(100)
414 + if change_pct > threshold_pct:
415 + bad.append(code)
416 + return _result(
417 + "C-14",
418 + "WARN",
419 + tuple(bad),
420 + "تغییر ناگهانی بیش از آستانه نسبت به سال قبل دیده نشد",
421 + f"{len(bad)} حساب تغییر بیش از آستانه نسبت به سال قبل دارند (نیازمند توضیح)",
422 + )
423 +
424 +
425 +def check_c15(rows: list[BalanceRow], natures: dict[str, str] | None) -> ControlResult:
426 + """C-15 (WARN): an account carrying a balance contrary to its nature."""
427 + if natures is None:
428 + return _not_run("C-15", "WARN", "ماهیت حساب‌ها در دسترس نیست")
429 + bad: list[str] = []
430 + for code, bucket in sorted(_aggregate(rows).items()):
431 + nature = (natures.get(code) or "").strip().lower()
432 + closing = bucket["closing"]
433 + if nature in {"debit", "بدهکار"} and closing < _ZERO:
434 + bad.append(code)
435 + elif nature in {"credit", "بستانکار"} and closing > _ZERO:
436 + bad.append(code)
437 + return _result(
438 + "C-15",
439 + "WARN",
440 + tuple(bad),
441 + "هیچ حسابی مانده خلاف ماهیت ندارد",
442 + f"{len(bad)} حساب مانده خلاف ماهیت دارند (نیازمند توضیح)",
443 + )
444 +
445 +
446 def run_controls(
148 - rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
447 + rows: list[BalanceRow],
448 + mappings: dict[str, list[MappingTarget]],
449 + context: ControlContext | None = None,
450 ) -> list[ControlResult]:
150 - """Run the Phase-0 blocking control set in stable order."""
151 - return [check_c01(rows), check_c02(rows), check_c03(rows, mappings), check_c04(rows, mappings)]
451 + """Run the full C-01..C-15 set in stable order.
452 +
453 + Without a context every context-dependent control reports «اجرا نشد» and
454 + blocks approval, so an incomplete control set can never approve a year.
455 + """
456 + ctx = context or ControlContext()
457 + return [
458 + check_c01(rows),
459 + check_c02(rows),
460 + check_c03(rows, mappings),
461 + check_c04(rows, mappings),
462 + check_c05(rows, ctx.prior_closing),
463 + check_c06(ctx.bs_sections),
464 + check_c07(ctx.note_totals, ctx.line_totals),
465 + check_c08(ctx.is_net_profit, ctx.eq_retained_change, ctx.explicit_adjustments),
466 + check_c09(ctx.eq_movements),
467 + check_c10(ctx.cf_net_change, ctx.cash_opening, ctx.cash_closing),
468 + check_c11(rows, ctx.known_codes),
469 + check_c12(mappings, ctx.note_ids),
470 + check_c13(ctx.official, ctx.mode),
471 + check_c14(rows, ctx.prior_closing, ctx.change_threshold_pct),
472 + check_c15(rows, ctx.natures),
473 + ]
474
475
476 __all__ = [
477 "BalanceRow",
156 - "MappingTarget",
478 + "ControlContext",
479 "ControlResult",
480 + "EquityMovement",
481 + "MappingTarget",
482 + "OfficialComparison",
483 "check_c01",
484 "check_c02",
485 "check_c03",
486 "check_c04",
487 + "check_c05",
488 + "check_c06",
489 + "check_c07",
490 + "check_c08",
491 + "check_c09",
492 + "check_c10",
493 + "check_c11",
494 + "check_c12",
495 + "check_c13",
496 + "check_c14",
497 + "check_c15",
498 "run_controls",
499 ]
backend/src/aram_backend/services/approval.py
+35 -37
@@ -1,7 +1,7 @@
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 -the active mappings. Mappings are always passed to the controls — C-03 (no double
3 +Approval runs the FULL C-01..C-15 control set over the latest ledger import, the
4 +active mappings and the stored control context (R2, booklet 2.1). 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.
@@ -11,13 +11,18 @@ from __future__ import annotations
11
12 from dataclasses import dataclass
13
14 -from sqlalchemy import select
14 from sqlalchemy.orm import Session
15
17 -from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
18 -from aram_backend.models import FiscalYear, FiscalYearStatus, MappingRule
16 +from aram_backend.domain.controls import (
17 + BalanceRow,
18 + ControlContext,
19 + ControlResult,
20 + MappingTarget,
21 + run_controls,
22 +)
23 +from aram_backend.models import FiscalYear, FiscalYearStatus
24 from aram_backend.services.audit import append_entry
20 -from aram_backend.services.ledger_aggregate import latest_raw_rows
25 +from aram_backend.services.control_context import build_control_context, load_mappings, load_rows
26
27
28 class ApprovalError(ValueError):
@@ -31,34 +36,14 @@ class ApprovalResult:
36 controls: tuple[ControlResult, ...]
37
38
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,
39 - opening=b.opening,
40 - debit=b.debit,
41 - credit=b.credit,
42 - closing=b.closing,
43 - )
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 -
39 def evaluate_controls(
58 - rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
40 + rows: list[BalanceRow],
41 + mappings: dict[str, list[MappingTarget]],
42 + context: ControlContext | None = None,
43 ) -> list[ControlResult]:
60 - """Run every control with the mappings explicitly supplied (C-03/C-04 need them)."""
61 - return run_controls(rows, mappings)
44 + """Run every control. Without a context the C-05..C-15 set reports «اجرا نشد»
45 + and blocks, so an incomplete control set can never approve a year."""
46 + return run_controls(rows, mappings, context)
47
48
49 def approve_year(session: Session, year_id: int, *, actor: str = "") -> ApprovalResult:
@@ -68,12 +53,25 @@ def approve_year(session: Session, year_id: int, *, actor: str = "") -> Approval
53 if year.status != FiscalYearStatus.DRAFT:
54 raise ApprovalError(f"only a Draft year can be approved (current: {year.status.value})")
55
71 - rows = _load_rows(session, year_id)
72 - mappings = _load_mappings(session, year_id)
73 - controls = evaluate_controls(rows, mappings)
56 + rows = load_rows(session, year_id)
57 + mappings = load_mappings(session, year_id)
58 + controls = evaluate_controls(rows, mappings, build_control_context(session, year_id))
59 blocking = tuple(r for r in controls if r.severity == "ERROR" and not r.passed)
60 if blocking:
76 - # Hard gate: even a single ERROR blocks approval (P-09, D5).
61 + # Hard gate: even a single ERROR blocks approval (P-09, D5). The refused
62 + # decision is audited too (R2): who tried, and which controls stopped it.
63 + append_entry(
64 + session,
65 + action="approve",
66 + actor=actor,
67 + year_id=year_id,
68 + payload={
69 + "approved": False,
70 + "blocking": [r.code for r in blocking],
71 + "unrun": [r.code for r in blocking if not r.ran],
72 + },
73 + )
74 + session.flush()
75 return ApprovalResult(approved=False, blocking=blocking, controls=tuple(controls))
76
77 year.status = FiscalYearStatus.APPROVED
@@ -82,7 +80,7 @@ def approve_year(session: Session, year_id: int, *, actor: str = "") -> Approval
80 action="approve",
81 actor=actor,
82 year_id=year_id,
85 - payload={"controls": [r.code for r in controls]},
83 + payload={"approved": True, "controls": [r.code for r in controls]},
84 )
85 session.flush()
86 return ApprovalResult(approved=True, blocking=(), controls=tuple(controls))
backend/src/aram_backend/services/control_context.py new
+302
@@ -0,0 +1,302 @@
1 +"""Gather the inputs C-05..C-15 need from stored data (R2, booklet 2.1).
2 +
3 +Nothing is guessed. Where the year genuinely lacks an input — no prior year, no
4 +built statement, no designated retained-earnings or cash note — the corresponding
5 +field stays ``None`` so the control reports «اجرا نشد: دلیل» and blocks approval.
6 +
7 +Two note roles are read from ``NoteDefinition.configuration_json``:
8 +
9 +- ``role="retained_earnings"`` on an EQ note designates the retained-earnings note
10 + used by C-08.
11 +- ``role="cash"`` on a BS note designates the cash note used by C-10.
12 +
13 +They are explicit data, never inferred from a title or a note number.
14 +"""
15 +
16 +from __future__ import annotations
17 +
18 +from decimal import Decimal
19 +
20 +from sqlalchemy import func, select
21 +from sqlalchemy.orm import Session
22 +
23 +from aram_backend.domain.controls import (
24 + BalanceRow,
25 + ControlContext,
26 + EquityMovement,
27 + MappingTarget,
28 +)
29 +from aram_backend.models import (
30 + AccountVersion,
31 + FinancialStatement,
32 + FiscalYear,
33 + LedgerBalance,
34 + MappingRule,
35 + NoteDefinition,
36 + StatementLine,
37 +)
38 +from aram_backend.services.statement_build import SECTION_POLICY
39 +
40 +_ZERO = Decimal(0)
41 +
42 +
43 +def load_rows(session: Session, year_id: int) -> list[BalanceRow]:
44 + """Latest import version of the raw ledger rows for the year."""
45 + version = session.scalar(
46 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
47 + )
48 + if version is None:
49 + return []
50 + balances = session.scalars(
51 + select(LedgerBalance).where(
52 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
53 + )
54 + ).all()
55 + return [
56 + BalanceRow(
57 + row_number=b.source_row,
58 + account_code=b.account_full_code,
59 + opening=b.opening,
60 + debit=b.debit,
61 + credit=b.credit,
62 + closing=b.closing,
63 + statement_balance=b.statement_balance,
64 + )
65 + for b in balances
66 + ]
67 +
68 +
69 +def load_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
70 + mappings: dict[str, list[MappingTarget]] = {}
71 + for rule in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all():
72 + mappings.setdefault(rule.account_code, []).append(
73 + MappingTarget(target=str(rule.target_note_id))
74 + )
75 + return mappings
76 +
77 +
78 +def _latest_statement(session: Session, year_id: int, code: str) -> FinancialStatement | None:
79 + version = session.scalar(
80 + select(func.max(FinancialStatement.version)).where(
81 + FinancialStatement.year_id == year_id,
82 + FinancialStatement.statement_type == code,
83 + )
84 + )
85 + if version is None:
86 + return None
87 + return session.scalar(
88 + select(FinancialStatement).where(
89 + FinancialStatement.year_id == year_id,
90 + FinancialStatement.statement_type == code,
91 + FinancialStatement.version == version,
92 + )
93 + )
94 +
95 +
96 +def _notes(session: Session, year_id: int) -> dict[int, NoteDefinition]:
97 + return {
98 + n.id: n
99 + for n in session.scalars(
100 + select(NoteDefinition).where(NoteDefinition.year_id == year_id)
101 + ).all()
102 + }
103 +
104 +
105 +def _prior_closing(session: Session, year: FiscalYear) -> dict[str, Decimal] | None:
106 + prior = session.scalar(
107 + select(FiscalYear).where(
108 + FiscalYear.company_id == year.company_id, FiscalYear.year == year.year - 1
109 + )
110 + )
111 + if prior is None:
112 + return None
113 + totals: dict[str, Decimal] = {}
114 + for row in load_rows(session, prior.id):
115 + totals[row.account_code] = totals.get(row.account_code, _ZERO) + row.closing
116 + return totals
117 +
118 +
119 +def _signed_account_totals(
120 + rows: list[BalanceRow],
121 + mappings: dict[str, list[MappingTarget]],
122 + notes: dict[int, NoteDefinition],
123 + statement: str,
124 +) -> tuple[dict[str, dict[str, Decimal]], dict[str, str]]:
125 + """Per-note signed totals for one statement, plus each note's section."""
126 + policy = SECTION_POLICY.get(statement, {})
127 + totals: dict[str, dict[str, Decimal]] = {}
128 + sections: dict[str, str] = {}
129 + note_by_id = {str(nid): n for nid, n in notes.items()}
130 + for row in rows:
131 + for target in mappings.get(row.account_code, []):
132 + note = note_by_id.get(target.target)
133 + if note is None:
134 + continue
135 + config = note.configuration_json or {}
136 + if str(config.get("statement") or "") != statement:
137 + continue
138 + section = str(config.get("section") or "")
139 + sign = Decimal(policy.get(section, 1))
140 + key = f"{statement}:{note.note_number}"
141 + bucket = totals.setdefault(key, {"opening": _ZERO, "changes": _ZERO, "closing": _ZERO})
142 + # Same rule as build_statements: a reclassified row's presentation
143 + # figure is authoritative and already signed (ADR-013/018).
144 + bucket["opening"] += row.opening * sign
145 + bucket["changes"] += (row.debit - row.credit) * sign
146 + bucket["closing"] += row.display(sign)
147 + sections[key] = section
148 + return totals, sections
149 +
150 +
151 +def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -> ControlContext:
152 + """Collect every available input; leave the rest ``None`` (fail-closed)."""
153 + year = session.get(FiscalYear, year_id)
154 + if year is None:
155 + return ControlContext(mode=mode)
156 + rows = load_rows(session, year_id)
157 + mappings = load_mappings(session, year_id)
158 + notes = _notes(session, year_id)
159 +
160 + bs_totals, bs_sections_by_key = _signed_account_totals(rows, mappings, notes, "BS")
161 + is_totals, is_sections_by_key = _signed_account_totals(rows, mappings, notes, "IS")
162 + eq_totals, _ = _signed_account_totals(rows, mappings, notes, "EQ")
163 + cf_totals, _ = _signed_account_totals(rows, mappings, notes, "CF")
164 +
165 + bs_sections: dict[str, Decimal] | None = None
166 + if _latest_statement(session, year_id, "BS") is not None and bs_totals:
167 + accumulated: dict[str, Decimal] = {}
168 + for key, bucket in bs_totals.items():
169 + section = bs_sections_by_key[key]
170 + accumulated[section] = accumulated.get(section, _ZERO) + bucket["closing"]
171 + bs_sections = accumulated
172 +
173 + line_totals: dict[str, Decimal] | None = None
174 + note_totals: dict[str, Decimal] | None = None
175 + if any(_latest_statement(session, year_id, c) is not None for c in ("BS", "IS")):
176 + lines_by_key: dict[str, Decimal] = {}
177 + for code in ("BS", "IS", "CF", "EQ"):
178 + statement = _latest_statement(session, year_id, code)
179 + if statement is None:
180 + continue
181 + for line in session.scalars(
182 + select(StatementLine).where(StatementLine.statement_id == statement.id)
183 + ).all():
184 + note = notes.get(line.target_note_id) if line.target_note_id else None
185 + if note is None:
186 + continue
187 + key = f"{code}:{note.note_number}"
188 + lines_by_key[key] = lines_by_key.get(key, _ZERO) + (line.mapped_total or _ZERO)
189 + line_totals = lines_by_key
190 + note_totals = {
191 + key: bucket["closing"]
192 + for key, bucket in {**bs_totals, **is_totals, **eq_totals, **cf_totals}.items()
193 + }
194 +
195 + is_net_profit: Decimal | None = None
196 + if is_totals:
197 + revenue = sum(
198 + (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Revenue"),
199 + _ZERO,
200 + )
201 + expenses = sum(
202 + (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Expenses"),
203 + _ZERO,
204 + )
205 + is_net_profit = revenue - expenses
206 +
207 + retained_note = next(
208 + (
209 + n
210 + for n in notes.values()
211 + if (n.configuration_json or {}).get("role") == "retained_earnings"
212 + ),
213 + None,
214 + )
215 + eq_retained_change: Decimal | None = None
216 + if retained_note is not None:
217 + for prefix, table in (("EQ", eq_totals), ("BS", bs_totals)):
218 + retained = table.get(f"{prefix}:{retained_note.note_number}")
219 + if retained is not None:
220 + eq_retained_change = retained["changes"]
221 + break
222 +
223 + # Equity movements are the notes explicitly sectioned "Equity" (BS or EQ) —
224 + # never inferred from a title. No such note means C-09 cannot run.
225 + equity_buckets: dict[str, dict[str, Decimal]] = {}
226 + for _prefix, table, sections in (
227 + ("EQ", eq_totals, None),
228 + ("BS", bs_totals, bs_sections_by_key),
229 + ):
230 + for key, bucket in table.items():
231 + section = sections[key] if sections is not None else "Equity"
232 + if section == "Equity":
233 + equity_buckets[key] = bucket
234 + eq_movements: tuple[EquityMovement, ...] | None = None
235 + if equity_buckets:
236 + eq_movements = tuple(
237 + EquityMovement(
238 + label=key, opening=b["opening"], changes=b["changes"], closing=b["closing"]
239 + )
240 + for key, b in sorted(equity_buckets.items())
241 + )
242 +
243 + cash_note = next(
244 + (n for n in notes.values() if (n.configuration_json or {}).get("role") == "cash"), None
245 + )
246 + cash_opening: Decimal | None = None
247 + cash_closing: Decimal | None = None
248 + if cash_note is not None:
249 + cash = bs_totals.get(f"BS:{cash_note.note_number}")
250 + if cash is not None:
251 + cash_opening, cash_closing = cash["opening"], cash["closing"]
252 +
253 + cf_net_change: Decimal | None = None
254 + if cf_totals:
255 + cf_net_change = sum((b["changes"] for b in cf_totals.values()), _ZERO)
256 +
257 + # The chart is what the year actually declares: registered account versions,
258 + # the ledger's own account codes, and the general ("kol") codes each ledger row
259 + # carries. A parent is "existing" when the source declares it; the sum check
260 + # only applies when the ledger also posts the parent itself (booklet 1 §7).
261 + codes = {
262 + c
263 + for (c,) in session.execute(
264 + select(AccountVersion.account_code).where(AccountVersion.year_id == year_id)
265 + ).all()
266 + }
267 + codes.update(row.account_code for row in rows)
268 + codes.update(
269 + g
270 + for (g,) in session.execute(
271 + select(LedgerBalance.general_code).where(LedgerBalance.year_id == year_id).distinct()
272 + ).all()
273 + if g
274 + )
275 + natures = {
276 + code: (nature or "")
277 + for code, nature in session.execute(
278 + select(AccountVersion.account_code, AccountVersion.nature).where(
279 + AccountVersion.year_id == year_id
280 + )
281 + ).all()
282 + }
283 +
284 + return ControlContext(
285 + prior_closing=_prior_closing(session, year),
286 + bs_sections=bs_sections,
287 + note_totals=note_totals,
288 + line_totals=line_totals,
289 + is_net_profit=is_net_profit,
290 + eq_retained_change=eq_retained_change,
291 + eq_movements=eq_movements,
292 + cf_net_change=cf_net_change,
293 + cash_opening=cash_opening,
294 + cash_closing=cash_closing,
295 + known_codes=frozenset(codes) if codes else None,
296 + natures=natures or None,
297 + note_ids=frozenset(str(nid) for nid in notes) if notes else None,
298 + mode=mode,
299 + )
300 +
301 +
302 +__all__ = ["build_control_context", "load_mappings", "load_rows"]
backend/src/aram_backend/services/preflight.py
+14 -5
@@ -1,10 +1,12 @@
1 -"""Ingestion preflight: run blocking controls C-01..C-04 (D-02, booklet §7).
1 +"""Ingestion preflight: the full C-01..C-15 set (D-02 + R2, 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.
7 +that must be mapped in Phase 2 before approval. C-05..C-15 need stored context;
8 +without it they report «اجرا نشد» and block, so this report can never claim a
9 +year is approvable on a partial control set (R2).
10 """
11
12 from __future__ import annotations
@@ -16,7 +18,13 @@ from decimal import Decimal
18 from sqlalchemy import select
19 from sqlalchemy.orm import Session
20
19 -from aram_backend.domain.controls import BalanceRow, ControlResult, MappingTarget, run_controls
21 +from aram_backend.domain.controls import (
22 + BalanceRow,
23 + ControlContext,
24 + ControlResult,
25 + MappingTarget,
26 + run_controls,
27 +)
28 from aram_backend.domain.hierarchy import AccountLevels, canonical_full_code
29 from aram_backend.ledger_parser import LedgerRecord
30 from aram_backend.models import MappingRule
@@ -77,8 +85,9 @@ def run_preflight(
85 session: Session | None = None,
86 year_id: int | None = None,
87 mappings: dict[str, list[MappingTarget]] | None = None,
88 + context: ControlContext | None = None,
89 ) -> PreflightReport:
81 - """Evaluate C-01..C-04 over parsed records.
90 + """Evaluate C-01..C-15 over parsed records.
91
92 ``mappings`` may be supplied directly (pure/test path) or loaded from the
93 year's active MappingRule rows when ``session`` and ``year_id`` are given.
@@ -90,7 +99,7 @@ def run_preflight(
99 if session is not None and year_id is not None
100 else {}
101 )
93 - return PreflightReport(results=tuple(run_controls(rows, mappings)))
102 + return PreflightReport(results=tuple(run_controls(rows, mappings, context)))
103
104
105 __all__ = ["PreflightReport", "run_preflight"]
backend/src/aram_backend/statement_api.py
+57 -36
@@ -16,7 +16,7 @@ from sqlalchemy.orm import Session
16 from aram_backend.auth import current_user, require_launch
17 from aram_backend.config import get_settings
18 from aram_backend.database import get_session
19 -from aram_backend.domain.controls import BalanceRow, run_controls
19 +from aram_backend.domain.controls import run_controls
20 from aram_backend.ingestion import SourceRegistrationError, register_source_document
21 from aram_backend.ledger_parser import LedgerParseError, SkippedRow, parse_ledger
22 from aram_backend.models import (
@@ -32,6 +32,7 @@ from aram_backend.models import (
32 UserRole,
33 )
34 from aram_backend.services.approval import ApprovalError, approve_year
35 +from aram_backend.services.control_context import build_control_context, load_mappings, load_rows
36 from aram_backend.services.ledger_import import import_ledger_balances
37 from aram_backend.services.mapping_io import (
38 MappingImportError,
@@ -63,7 +64,9 @@ from aram_backend.services.users import AuthorizationError, ensure_role
64 # included. The only unauthenticated routes in the app are /health, /auth/login,
65 # /auth/launch and the one-time first-admin bootstrap.
66 router = APIRouter(
66 - prefix="/api/v1", tags=["statements"], dependencies=[Depends(require_launch), Depends(current_user)]
67 + prefix="/api/v1",
68 + tags=["statements"],
69 + dependencies=[Depends(require_launch), Depends(current_user)],
70 )
71
72
@@ -78,6 +81,9 @@ class NoteIn(BaseModel):
81 title: str = Field(min_length=1, max_length=512)
82 statement: str = Field(pattern="^(BS|IS|CF|EQ)$")
83 section: str = Field(min_length=1, max_length=64)
84 + # R2: explicit control role. C-08 needs a retained-earnings note and C-10 a
85 + # cash note; neither is ever inferred from a title or note number.
86 + role: str | None = Field(default=None, pattern="^(retained_earnings|cash)$")
87
88
89 class MappingIn(BaseModel):
@@ -93,6 +99,33 @@ def _year_or_404(session: Session, year_id: int) -> FiscalYear:
99 return year
100
101
102 +def _note_config(statement: str, section: str, role: str | None) -> dict:
103 + config = {"statement": statement, "section": section}
104 + if role:
105 + config["role"] = role
106 + return config
107 +
108 +
109 +class YearIn(BaseModel):
110 + year: int = Field(ge=1300, le=1600)
111 +
112 +
113 +@router.post("/companies/{company_id}/years")
114 +def create_year(company_id: int, body: YearIn, session: Session = Depends(get_session)) -> dict:
115 + """Add another fiscal year to a company (R2: C-05/C-14 need the prior year)."""
116 + if session.get(Company, company_id) is None:
117 + raise HTTPException(status_code=422, detail="شرکت یافت نشد")
118 + existing = session.scalar(
119 + select(FiscalYear).where(FiscalYear.company_id == company_id, FiscalYear.year == body.year)
120 + )
121 + if existing is not None:
122 + raise HTTPException(status_code=422, detail="این سال مالی قبلاً ثبت شده است")
123 + year = FiscalYear(company_id=company_id, year=body.year)
124 + session.add(year)
125 + session.commit()
126 + return {"year_id": year.id, "year": year.year, "status": year.status.value}
127 +
128 +
129 @router.post("/companies")
130 def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict:
131 company = Company(code=body.code, name=body.name)
@@ -176,7 +209,7 @@ def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_sessi
209 year_id=year_id,
210 note_number=body.note_number,
211 title=body.title,
179 - configuration_json={"statement": body.statement, "section": body.section},
212 + configuration_json=_note_config(body.statement, body.section, body.role),
213 )
214 session.add(note)
215 session.commit()
@@ -199,6 +232,7 @@ def list_notes(year_id: int, session: Session = Depends(get_session)) -> dict:
232 "title": n.title,
233 "statement": (n.configuration_json or {}).get("statement", ""),
234 "section": (n.configuration_json or {}).get("section", ""),
235 + "role": (n.configuration_json or {}).get("role"),
236 }
237 for n in notes
238 ]
@@ -332,44 +366,24 @@ def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dic
366
367 @router.get("/years/{year_id}/preflight")
368 def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
369 + """All 15 controls (R2). An unrun ERROR control blocks approval and says why."""
370 year = _year_or_404(session, year_id)
336 - version = session.scalar(
337 - select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
371 + results = run_controls(
372 + load_rows(session, year_id),
373 + load_mappings(session, year_id),
374 + build_control_context(session, year_id),
375 )
339 - balances = (
340 - session.scalars(
341 - select(LedgerBalance).where(
342 - LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
343 - )
344 - ).all()
345 - if version is not None
346 - else []
347 - )
348 - rows = [
349 - BalanceRow(
350 - row_number=b.source_row,
351 - account_code=b.account_full_code,
352 - opening=b.opening,
353 - debit=b.debit,
354 - credit=b.credit,
355 - closing=b.closing,
356 - )
357 - for b in balances
358 - ]
359 - rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
360 - from aram_backend.domain.controls import MappingTarget
361 -
362 - mappings: dict[str, list[MappingTarget]] = {}
363 - for rule in rules:
364 - mappings.setdefault(rule.account_code, []).append(
365 - MappingTarget(target=str(rule.target_note_id))
366 - )
367 - results = run_controls(rows, mappings)
376 return {
377 "year": year.year,
378 "can_approve": all(r.passed for r in results if r.severity == "ERROR"),
379 "controls": [
372 - {"code": r.code, "severity": r.severity, "passed": r.passed, "message_fa": r.message_fa}
380 + {
381 + "code": r.code,
382 + "severity": r.severity,
383 + "passed": r.passed,
384 + "ran": r.ran,
385 + "message_fa": r.message_fa,
386 + }
387 for r in results
388 ],
389 }
@@ -449,9 +463,13 @@ def approve(
463 except ApprovalError as exc:
464 raise HTTPException(status_code=422, detail=str(exc)) from exc
465 if not result.approved:
466 + # The refused decision is itself audited (R2), so it must be committed.
467 + session.commit()
468 return {
469 "approved": False,
454 - "blocking": [{"code": r.code, "message_fa": r.message_fa} for r in result.blocking],
470 + "blocking": [
471 + {"code": r.code, "message_fa": r.message_fa, "ran": r.ran} for r in result.blocking
472 + ],
473 }
474 session.commit()
475 return {"approved": True, "status": "Approved"}
@@ -535,6 +553,7 @@ class NoteUpdate(BaseModel):
553 title: str | None = Field(default=None, min_length=1, max_length=512)
554 statement: str | None = Field(default=None, pattern="^(BS|IS|CF|EQ)$")
555 section: str | None = Field(default=None, min_length=1, max_length=64)
556 + role: str | None = Field(default=None, pattern="^(retained_earnings|cash)$")
557
558
559 @router.put("/years/{year_id}/notes/{note_id}")
@@ -552,6 +571,8 @@ def update_note(
571 config["statement"] = body.statement
572 if body.section is not None:
573 config["section"] = body.section
574 + if body.role is not None:
575 + config["role"] = body.role
576 note.configuration_json = config
577 _commit_guarded(session)
578 return {"note_id": note.id, "note_number": note.note_number, "title": note.title}
backend/tests/helpers_complete_year.py new
+103
@@ -0,0 +1,103 @@
1 +"""Build a *complete* fiscal year through the public API (R2).
2 +
3 +Since R2 every ERROR control must actually run before a year can be approved, a
4 +test that wants a successful approval needs a real prior year, carried-forward
5 +openings, designated cash / retained-earnings notes and built statements. This
6 +helper does exactly that through the API, so it also proves the API surface is
7 +sufficient — no direct DB writes.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +_HEADER = (
13 + "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
14 +)
15 +
16 +
17 +def _csv(rows):
18 + return (_HEADER + "".join(rows)).encode()
19 +
20 +
21 +def _prior_csv(year):
22 + return _csv(
23 + [
24 + f"8348,14,نقد,{year},O,,,,,0,100,0,100\n",
25 + f"1001,24,پرداختنی,{year},O,,,,,0,0,60,-60\n",
26 + f"1001,34,سرمایه,{year},O,,,,,0,0,40,-40\n",
27 + ]
28 + )
29 +
30 +
31 +def _current_csv(year):
32 + # Opening == prior closing, no movement: every identity holds exactly.
33 + return _csv(
34 + [
35 + f"8348,14,نقد,{year},O,,,,,100,0,0,100\n",
36 + f"1001,24,پرداختنی,{year},O,,,,,-60,0,0,-60\n",
37 + f"1001,34,سرمایه,{year},O,,,,,-40,0,0,-40\n",
38 + f"1001,54,درآمد,{year},O,,,,,0,0,0,0\n",
39 + f"1001,64,جریان نقد,{year},O,,,,,0,0,0,0\n",
40 + ]
41 + )
42 +
43 +
44 +def _upload(client, year_id, payload, name):
45 + response = client.post(
46 + f"/api/v1/years/{year_id}/ledger", files={"file": (name, payload, "text/csv")}
47 + )
48 + assert response.status_code == 200, response.text
49 + return response.json()
50 +
51 +
52 +def _note(client, year_id, number, title, statement, section, role=None):
53 + body = {
54 + "note_number": number,
55 + "title": title,
56 + "statement": statement,
57 + "section": section,
58 + }
59 + if role:
60 + body["role"] = role
61 + response = client.post(f"/api/v1/years/{year_id}/notes", json=body)
62 + assert response.status_code == 200, response.text
63 + return response.json()["note_id"]
64 +
65 +
66 +def complete_year_via_api(client, *, code="CY", prior_year=1403, year=1404):
67 + """Return ``(year_id, note_ids)`` for a year whose 15 controls all pass."""
68 + created = client.post(
69 + "/api/v1/companies", json={"code": code, "name": "شرکت", "year": prior_year}
70 + ).json()
71 + company_id, prior_id = created["company_id"], created["year_id"]
72 + _upload(client, prior_id, _prior_csv(prior_year), "prior.csv")
73 +
74 + current = client.post(
75 + f"/api/v1/companies/{company_id}/years", json={"year": year}
76 + )
77 + assert current.status_code == 200, current.text
78 + year_id = current.json()["year_id"]
79 + _upload(client, year_id, _current_csv(year), "current.csv")
80 +
81 + notes = {
82 + "cash": _note(client, year_id, "6", "نقد", "BS", "Assets", "cash"),
83 + "payable": _note(client, year_id, "10", "پرداختنی", "BS", "Liabilities"),
84 + "equity": _note(client, year_id, "12", "سرمایه", "BS", "Equity", "retained_earnings"),
85 + "revenue": _note(client, year_id, "20", "درآمد", "IS", "Revenue"),
86 + "cf": _note(client, year_id, "23", "جریان نقد", "CF", "Operating"),
87 + }
88 + for account, key in (
89 + ("148348", "cash"),
90 + ("241001", "payable"),
91 + ("341001", "equity"),
92 + ("541001", "revenue"),
93 + ("641001", "cf"),
94 + ):
95 + response = client.post(
96 + f"/api/v1/years/{year_id}/mappings",
97 + json={"account_code": account, "target_note_id": notes[key]},
98 + )
99 + assert response.status_code == 200, response.text
100 +
101 + built = client.post(f"/api/v1/years/{year_id}/statements/build")
102 + assert built.status_code == 200, built.text
103 + return year_id, notes
backend/tests/test_approval_gate.py
+93 -6
@@ -11,23 +11,87 @@ from decimal import Decimal
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)
22 - _balance(session, year, source, "148348", 100, 3)
23 - _balance(session, year, source, "241001", -60, 4)
24 - _balance(session, year, source, "341001", -40, 5)
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
@@ -79,15 +143,38 @@ class TestApprovalNegative:
143 assert not result.approved
144 assert any(r.code == "C-04" for r in result.blocking)
145
82 - def test_blocked_approval_writes_no_audit_and_stays_draft(self, session):
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()
86 - approve_year(session, year.id)
153 + result = approve_year(session, year.id, actor="reviewer")
154 session.commit()
155 from aram_backend.models import AuditEntry
156
90 - assert session.query(AuditEntry).count() == 0
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):
backend/tests/test_controls_r2.py new
+394
@@ -0,0 +1,394 @@
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 only `statement_balance` (already
355 + presentation-signed) and leaves CLOSING empty. Using raw closing in the
356 + control context would compare two different rules and invent a difference.
357 + """
358 +
359 + def test_display_prefers_the_pre_signed_statement_balance(self):
360 + row = BalanceRow(1, "148348", D(0), D(0), D(0), D(0), statement_balance=D(-250))
361 + assert row.display(D(1)) == D(-250)
362 + assert row.display(D(-1)) == D(-250)
363 +
364 + def test_display_signs_ordinary_closing(self):
365 + row = BalanceRow(1, "241001", D(0), D(0), D(60), D(-60))
366 + assert row.display(D(-1)) == D(60)
367 +
368 + def test_context_and_engine_agree_on_a_reclassified_row(self, session):
369 + from sqlalchemy import select
370 +
371 + from aram_backend.models import LedgerBalance, StatementLine
372 + from aram_backend.services.statement_build import build_statements
373 + from test_statement_build import _map, _note, _setup
374 +
375 + year, source = _setup(session)
376 + _carry(session, year, source, "148348", D(0), D(0), 3)
377 + row = session.scalar(
378 + select(LedgerBalance).where(
379 + LedgerBalance.year_id == year.id, LedgerBalance.account_full_code == "148348"
380 + )
381 + )
382 + row.statement_balance = D(777)
383 + note = _note(session, year, "6", "نقد", "BS", "Assets")
384 + _map(session, year, "148348", note)
385 + session.flush()
386 + build_statements(session, year.id)
387 + session.flush()
388 +
389 + line = session.scalar(select(StatementLine).where(StatementLine.target_note_id == note.id))
390 + ctx = build_control_context(session, year.id)
391 + assert line.mapped_total == D(777)
392 + assert ctx.note_totals["BS:6"] == D(777)
393 + assert ctx.line_totals["BS:6"] == D(777)
394 + assert check_c07(ctx.note_totals, ctx.line_totals).passed
backend/tests/test_domain_controls.py
+2 -1
@@ -81,5 +81,6 @@ class TestC04:
81
82 class TestRunControls:
83 def test_stable_order(self):
84 + # R2: the full C-01..C-15 set, always in the same order.
85 results = run_controls([], {})
85 - assert [r.code for r in results] == ["C-01", "C-02", "C-03", "C-04"]
86 + assert [r.code for r in results] == [f"C-{i:02d}" for i in range(1, 16)]
backend/tests/test_editing.py
+8 -16
@@ -120,23 +120,15 @@ class TestNoteRowEditing:
120
121 class TestLockedYearEditing:
122 def test_edit_locked_year_refused_409(self, api_client):
123 - # Bootstrap admin, import a balanced ledger, map, approve, lock.
124 - api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
125 - y = _year(api_client)
126 - api_client.post(
127 - f"/api/v1/years/{y}/ledger", files={"file": ("ledger.csv", _BALANCED_CSV, "text/csv")}
128 - )
129 - n_a = _note(api_client, y, "6", "نقد", "BS", "Assets")
130 - n_l = _note(api_client, y, "10", "پرداختنی", "BS", "Liabilities")
131 - api_client.post(
132 - f"/api/v1/years/{y}/mappings", json={"account_code": "148348", "target_note_id": n_a}
133 - )
134 - api_client.post(
135 - f"/api/v1/years/{y}/mappings", json={"account_code": "241001", "target_note_id": n_l}
136 - )
137 - ap = api_client.post(f"/api/v1/years/{y}/approve", json={"actor": "root"})
123 + # R2: approval needs all 15 controls to run, so build a complete year
124 + # (prior year + carry-forward + designated notes) through the API.
125 + from helpers_complete_year import complete_year_via_api
126 +
127 + y, notes = complete_year_via_api(api_client, code="EDL")
128 + n_a = notes["cash"]
129 + ap = api_client.post(f"/api/v1/years/{y}/approve", json={})
130 assert ap.status_code == 200 and ap.json()["approved"] is True, ap.text
139 - lk = api_client.post(f"/api/v1/years/{y}/lock", json={"actor": "root"})
131 + lk = api_client.post(f"/api/v1/years/{y}/lock", json={})
132 assert lk.status_code == 200, lk.text
133 # Editing a note on the locked year is refused by the D-07 guard.
134 r = api_client.put(f"/api/v1/years/{y}/notes/{n_a}", json={"title": "تغییر"})
backend/tests/test_mapping_workflow.py
+23 -5
@@ -124,7 +124,10 @@ class TestApproval:
124 assert year.status == FiscalYearStatus.DRAFT
125
126 def test_approval_succeeds_on_clean_ledger(self, session):
127 - year = _balanced_mapped(session)
127 + # R2: a "clean ledger" now means every ERROR control can run and pass.
128 + from test_approval_gate import _balanced
129 +
130 + year, _ = _balanced(session)
131 result = approve_year(session, year.id, actor="reviewer")
132 session.commit()
133 assert result.approved
@@ -134,7 +137,9 @@ class TestApproval:
137 assert verify_chain(session)
138
139 def test_approval_rejected_on_non_draft(self, session):
137 - year = _balanced_mapped(session)
140 + from test_approval_gate import _balanced
141 +
142 + year, _ = _balanced(session)
143 approve_year(session, year.id)
144 session.commit()
145 with pytest.raises(ApprovalError):
@@ -247,9 +252,22 @@ class TestPhase2Api:
252 assert exp.status_code == 200
253 assert len(exp.content) > 0
254
250 - # Now approval succeeds.
251 - ok = c.post(f"/api/v1/years/{year_id}/approve", json={"actor": "r"}).json()
252 - assert ok["approved"] is True
255 + # Mapping alone no longer approves a year (R2): C-05..C-12 still block
256 + # because this year has no prior year, no designated notes, no statements.
257 + blocked_now = c.post(f"/api/v1/years/{year_id}/approve", json={}).json()
258 + assert blocked_now["approved"] is False
259 + assert {"C-05", "C-06", "C-10"} <= {b["code"] for b in blocked_now["blocking"]}
260 + # C-03/C-04 are cleared by the imported mappings, which is what this test owns.
261 + pre = c.get(f"/api/v1/years/{year_id}/preflight").json()
262 + by_code = {ctl["code"]: ctl for ctl in pre["controls"]}
263 + assert by_code["C-03"]["passed"] and by_code["C-04"]["passed"]
264 +
265 + def test_complete_year_approves_via_api(self, api_client):
266 + from helpers_complete_year import complete_year_via_api
267 +
268 + year_id, _ = complete_year_via_api(api_client, code="P2C")
269 + ok = api_client.post(f"/api/v1/years/{year_id}/approve", json={}).json()
270 + assert ok["approved"] is True, ok
271
272
273 class TestMappingWorkflowNegative:
backend/tests/test_preflight.py
+11 -3
@@ -1,4 +1,4 @@
1 -"""D-02 acceptance: controls C-01..C-04 run as an ingestion preflight."""
1 +"""D-02 + R2 acceptance: the full C-01..C-15 set runs as an ingestion preflight."""
2
3 from __future__ import annotations
4
@@ -64,9 +64,17 @@ def test_mapping_clears_unknown_queue():
64 assert by_code["C-04"].passed
65
66
67 -def test_all_four_controls_present():
67 +def test_all_fifteen_controls_present():
68 report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
69 - assert [r.code for r in report.results] == ["C-01", "C-02", "C-03", "C-04"]
69 + assert [r.code for r in report.results] == [f"C-{i:02d}" for i in range(1, 16)]
70 +
71 +
72 +def test_contextless_preflight_cannot_claim_approvable():
73 + # R2: without stored context C-05..C-12 report «اجرا نشد» and block.
74 + report = run_preflight([_rec(3, "8348", 0, 0, 0, 0)])
75 + assert not report.can_approve
76 + unrun = [r for r in report.blocking if not r.ran]
77 + assert unrun and all(r.message_fa.startswith("اجرا نشد:") for r in unrun)
78
79
80 def test_inactive_account_not_queued():
backend/tests/test_statement_build.py
+1 -1
@@ -229,7 +229,7 @@ class TestVerticalSliceApi:
229 r = c.get(f"/api/v1/years/{year_id}/preflight")
230 assert r.status_code == 200
231 codes = {ctl["code"] for ctl in r.json()["controls"]}
232 - assert codes == {"C-01", "C-02", "C-03", "C-04"}
232 + assert codes == {f"C-{i:02d}" for i in range(1, 16)}
233
234
235 # ------------------------------------------------- bounded real-data smoke
docs/PROJECT_LOG.md
+11
@@ -430,3 +430,14 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
430 - Evidence: backend **354 passed** (collect-only 354; was 319), including `tests/test_auth_r1.py` **33** R1 acceptance tests; frontend **15 vitest tests / 5 files**, tsc + eslint clean; `ruff check src tests`, `ruff format --check domain services migrations`, `mypy domain`, `mypy services` clean. Migration 08 verified on a copy of a populated DB: 131,280 ledger rows, 2 users, 28 triggers unchanged; the live preview's legacy `root` logged in and was rehashed 200,000 → 600,000. CI e2e job now starts uvicorn on a throwaway DB with `ARAM_E2E_BACKEND=1` so the real-session e2e actually runs.
431 - Protected data: `data/` tree 2ef8a512523f62f0cf84c5009f141be2f8a9cb5f and `samples/` tree 00aba54b1dc30485ba9b164c8036a7b4bbe9020e unchanged (before = after).
432 - Acceptance: R1 **MET**; author does not merge or tag. Stop after R1 per booklet 2.1 §8. Next: independent GitHub review of the R1 PR; R2 only after acceptance.
433 +
434 +### 2026-12-04T10:20:00Z — R2 full control set C-01..C-15 (booklet 2.1)
435 +
436 +- Actor: Arena agent (implementation **and merge**, per the owner's 2026-12-04 directive "خودت کامل انجام بده و دیگه متوقف نشو"). Precondition: PR #98 (R1) squash-merged → accepted head **07a8ae0e621e706e4ce1583a611699bc2bc6d38d**; working branch aligned to that tree before starting, so this diff is R2-only.
437 +- Domain: `check_c05`…`check_c15` added as pure functions (Persian messages, booklet 1 §7 severities). `ControlResult.ran` distinguishes "failed" from "could not run"; `_not_run` returns `passed=False, ran=False` with «اجرا نشد: <دلیل>». `run_controls(rows, mappings, context)` always returns 15 results in stable order — with no context the eleven context-dependent controls block rather than silently pass.
438 +- New `services/control_context.py` gathers inputs from stored data only: prior-year closing per account, BS section totals under the ADR-013 sign policy, note-vs-line totals keyed by **(statement, note)**, IS net result, equity movements, CF net change, cash opening/closing, declared codes and natures. Nothing is inferred from titles.
439 +- **ADR-031** records five decisions: unrun ≠ pass; severities unchanged (C-13 ERROR in CI / INFO in UI, C-14/C-15 WARN); control roles are explicit data (`configuration_json.role` = `retained_earnings` | `cash`, exposed on note create/update and in the notes manager); **a refused approval is now audited** (`approved:false` + blocking + unrun codes, committed, year stays Draft) — this reverses the old "blocked approval writes no audit" test, which was updated with a payload-hash assertion, not deleted; and `POST /companies/{id}/years` was added because requiring C-05 without a way to load a prior year would make approval permanently impossible.
440 +- Evidence: backend **404 passed / exit 0** (was 354) including `tests/test_controls_r2.py` (48 tests: positive + negative per control, unrun-blocking, API preflight, complete-year-through-API); frontend **17 vitest / 6 files**; ruff check + format (32 files), mypy (23 files), tsc, eslint, `npm run build` all clean. Live proof on the real 131,280-row preview DB: `GET /years/1/preflight` → **15 controls** in 7.2 s, `can_approve:false`, C-01 flags the known 6 rows, C-03/C-04 flag 221 unmapped accounts, 8 controls report «اجرا نشد» with their reason.
441 +- Legacy tests updated to the new contract (four-control expectations in `test_domain_controls`, `test_preflight`, `test_statement_build`; approval-after-mapping-alone in `test_mapping_workflow`; locked-year setup in `test_editing` now builds a complete year through the API). No test was deleted or skipped to reach green.
442 +- Protected data: `data/` tree 2ef8a512523f62f0cf84c5009f141be2f8a9cb5f and `samples/` tree 00aba54b1dc30485ba9b164c8036a7b4bbe9020e unchanged (before = after).
443 +- Budget: **968 / 1500** authored lines excl. tests/data. Acceptance: R2 **MET** (15 controls in preflight, per-control ± tests, approval-rejected test). Next: R3 (build-vs-official comparison, IS 6/8/9 root cause, EQ/CF parsing).
docs/adr/ADR-031-r2-full-control-set.md new
+83
@@ -0,0 +1,83 @@
1 +# ADR-031 — R2: the full C-01..C-15 control set and what "cannot run" means
2 +
3 +- Status: accepted
4 +- Date: 2026-12-04
5 +- Scope: booklet 2.1 task R2 (booklet 1 §7 controls C-05…C-15)
6 +- Supersedes: nothing. Extends ADR-013 (debit-positive rial), ADR-014 (code identity).
7 +
8 +## Context
9 +
10 +Before R2 only C-01…C-04 existed. A year could be approved while eleven controls
11 +had never been evaluated, and the preflight endpoint reported four controls as if
12 +that were the whole set. Booklet 2.1 R2 requires all fifteen, and requires that a
13 +control which cannot run says so and blocks approval.
14 +
15 +## Decision 1 — an unrun control is never a pass
16 +
17 +`ControlResult` gains `ran: bool`. A control whose inputs are unavailable returns
18 +`passed=False, ran=False` with the message `اجرا نشد: <دلیل>`. Approval blocks on
19 +any ERROR control that is not `passed`, so an unrun ERROR blocks exactly like a
20 +failed one. `run_controls` always returns fifteen results in stable order, with or
21 +without a context — the set can never silently shrink.
22 +
23 +The UI shows «اجرا نشد» separately from «رد» so the operator sees the missing input
24 +rather than a phantom accounting error.
25 +
26 +## Decision 2 — severities follow booklet 1 §7, not convenience
27 +
28 +C-05…C-12 are ERROR. C-13 is ERROR in CI and INFO in the UI (`ControlContext.mode`).
29 +C-14 and C-15 are WARN and never block. No severity was softened to make a year
30 +approvable.
31 +
32 +## Decision 3 — role designations are explicit data, never inferred
33 +
34 +C-08 needs a retained-earnings figure and C-10 needs cash. Guessing them from a
35 +note title or number would fabricate accounting meaning, so they are read from
36 +`NoteDefinition.configuration_json.role`, an explicit enum (`retained_earnings`,
37 +`cash`) exposed on note create/update and selectable in the notes manager. No
38 +role set ⇒ the control reports «اجرا نشد» and blocks.
39 +
40 +C-09 likewise uses only notes explicitly sectioned `Equity`; C-11 treats a parent
41 +as existing when the year declares it (account versions, ledger account codes, or
42 +the `kol` general code the ledger row carries) and checks the child sum only when
43 +the ledger also posts the parent itself, per booklet 1 §7.
44 +
45 +## Decision 4 — a refused approval is audited
46 +
47 +Previously a blocked approval wrote nothing. That hid who attempted approval and
48 +which controls stopped them. R2 appends an `approve` entry with
49 +`approved: false`, the blocking codes and the unrun codes, and commits it. The
50 +year stays Draft. The log stores only a hash, so the test recomputes the payload
51 +hash to prove what was committed to. This reverses the earlier
52 +"blocked approval writes no audit" expectation; the old test was updated, not
53 +deleted.
54 +
55 +## Decision 5 — controls and the engine must read the same figure
56 +
57 +`build_statements` treats a reclassified row's `statement_balance` as authoritative
58 +and already presentation-signed, falling back to `sign × closing` otherwise
59 +(ADR-013/018). The first R2 context builder used raw `closing`, which would have
60 +made C-06/C-07 compare two different rules and invent differences on exactly those
61 +rows. `BalanceRow` now carries `statement_balance` and a single `display(sign)`
62 +method implementing that rule, and the context uses it. C-01/C-02 still audit the
63 +raw debit/credit columns, because that is what they are for.
64 +
65 +Witness: `TestReclassifiedRowsAgreeWithTheEngine` — the engine's line total, the
66 +context's note total and its line total are all 777 on a row whose CLOSING is 0.
67 +
68 +## Decision 6 — the API must be able to reach an approvable year
69 +
70 +Requiring C-05 without a way to load a prior year would make approval impossible
71 +forever. `POST /companies/{company_id}/years` adds a fiscal year to an existing
72 +company (duplicate year ⇒ 422). `tests/helpers_complete_year.py` builds a complete
73 +approvable year **through the public API only**, which doubles as proof that the
74 +surface is sufficient.
75 +
76 +## Consequences
77 +
78 +- Real 1404 data cannot be approved yet: it has no prior year loaded and no
79 + designated notes. That is the correct, conservative outcome, not a regression.
80 +- The ingestion preflight (`services/preflight.py`) now also returns fifteen
81 + results; without stored context it can never claim a year is approvable.
82 +- Legacy tests that asserted a four-control set or approval after mapping alone
83 + were updated to the new contract. No test was removed to make the suite pass.
frontend/src/api/client.ts
+20 -6
@@ -7,6 +7,8 @@ import type {
7 MappingImportResult,
8 MappingResult,
9 NoteResult,
10 + NoteRole,
11 + NoteSummary,
12 PreflightResult,
13 StatementsResult,
14 UnknownAccountsResult,
@@ -88,8 +90,18 @@ export const api = {
90 uploadLedger: (yearId: number, file: File) =>
91 request<LedgerImportResult>(`/years/${yearId}/ledger`, multipart(file)),
92
91 - createNote: (yearId: number, noteNumber: string, title: string, statement: string, section: string) =>
92 - request<NoteResult>(`/years/${yearId}/notes`, json({ note_number: noteNumber, title, statement, section })),
93 + createNote: (
94 + yearId: number,
95 + noteNumber: string,
96 + title: string,
97 + statement: string,
98 + section: string,
99 + role?: NoteRole,
100 + ) =>
101 + request<NoteResult>(
102 + `/years/${yearId}/notes`,
103 + json({ note_number: noteNumber, title, statement, section, ...(role ? { role } : {}) }),
104 + ),
105
106 createMapping: (yearId: number, accountCode: string, targetNoteId: number) =>
107 request<MappingResult>(`/years/${yearId}/mappings`, json({ account_code: accountCode, target_note_id: targetNoteId })),
@@ -116,16 +128,18 @@ export const api = {
128 download(`/years/${yearId}/statements/export?format=${format}`, `statements-${yearId}.${format}`),
129
130 listNotes: (yearId: number) =>
119 - request<{ notes: { note_id: number; note_number: string; title: string; statement: string; section: string }[] }>(
120 - `/years/${yearId}/notes`,
121 - ),
131 + request<{ notes: (NoteSummary & { role: NoteRole | null })[] }>(`/years/${yearId}/notes`),
132
133 listMappings: (yearId: number) =>
134 request<{ mappings: { mapping_id: number; account_code: string; target_note_id: number; mapping_type: string }[] }>(
135 `/years/${yearId}/mappings`,
136 ),
137
128 - updateNote: (yearId: number, noteId: number, patch: { title?: string; note_number?: string; statement?: string; section?: string }) =>
138 + updateNote: (
139 + yearId: number,
140 + noteId: number,
141 + patch: { title?: string; note_number?: string; statement?: string; section?: string; role?: NoteRole },
142 + ) =>
143 request<{ note_id: number; note_number: string; title: string }>(`/years/${yearId}/notes/${noteId}`, {
144 method: 'PUT',
145 headers: { 'Content-Type': 'application/json' },
frontend/src/api/types.ts
+13
@@ -66,6 +66,8 @@ export interface ControlResult {
66 severity: string
67 passed: boolean
68 message_fa: string
69 + /** R2: false means the control could not run; its message says why. */
70 + ran?: boolean
71 }
72
73 export interface PreflightResult {
@@ -92,6 +94,17 @@ export interface UnknownAccountsResult {
94 accounts: UnknownAccount[]
95 }
96
97 +/** R2: explicit control role — C-08 needs retained_earnings, C-10 needs cash. */
98 +export type NoteRole = 'retained_earnings' | 'cash'
99 +
100 +export interface NoteSummary {
101 + note_id: number
102 + note_number: string
103 + title: string
104 + statement: string
105 + section: string
106 +}
107 +
108 export interface NoteResult {
109 note_id: number
110 note_number: string
frontend/src/components/ApprovalPanel.test.tsx new
+53
@@ -0,0 +1,53 @@
1 +import { fireEvent, render, screen, waitFor } from '@testing-library/react'
2 +import { beforeEach, describe, expect, it, vi } from 'vitest'
3 +import type { PreflightResult } from '../api/types'
4 +import ApprovalPanel from './ApprovalPanel'
5 +
6 +vi.mock('../api/client', () => ({
7 + api: { preflight: vi.fn(), approve: vi.fn() },
8 +}))
9 +
10 +import { api } from '../api/client'
11 +
12 +const control = (code: string, extra: Partial<PreflightResult['controls'][0]> = {}) => ({
13 + code,
14 + severity: 'ERROR',
15 + passed: true,
16 + ran: true,
17 + message_fa: 'قبول',
18 + ...extra,
19 +})
20 +
21 +const result: PreflightResult = {
22 + year: 1404,
23 + can_approve: false,
24 + controls: [
25 + ...Array.from({ length: 12 }, (_, i) => control(`C-${String(i + 1).padStart(2, '0')}`)),
26 + control('C-13', { severity: 'INFO', passed: false, ran: false, message_fa: 'اجرا نشد: مبنا نیست' }),
27 + control('C-14', { severity: 'WARN' }),
28 + control('C-15', { severity: 'WARN', passed: false, ran: false, message_fa: 'اجرا نشد: ماهیت نیست' }),
29 + ],
30 +}
31 +
32 +describe('ApprovalPanel (R2)', () => {
33 + beforeEach(() => {
34 + vi.mocked(api.preflight).mockResolvedValue(result)
35 + })
36 +
37 + it('shows all fifteen controls', async () => {
38 + render(<ApprovalPanel yearId={1} />)
39 + fireEvent.click(screen.getByRole('button', { name: 'اجرای کنترل‌ها' }))
40 + await waitFor(() => expect(screen.getByText('C-15')).toBeInTheDocument())
41 + for (let i = 1; i <= 15; i += 1) {
42 + expect(screen.getByText(`C-${String(i).padStart(2, '0')}`)).toBeInTheDocument()
43 + }
44 + })
45 +
46 + it('distinguishes an unrun control from a failed one and reports the block', async () => {
47 + render(<ApprovalPanel yearId={1} />)
48 + fireEvent.click(screen.getByRole('button', { name: 'اجرای کنترل‌ها' }))
49 + await waitFor(() => expect(screen.getAllByText('اجرا نشد').length).toBe(2))
50 + expect(screen.getByText('اجرا نشد: ماهیت نیست')).toBeInTheDocument()
51 + expect(screen.getByText('کنترل‌های حیاتی رد یا اجرا نشدند — تصویب مسدود است.')).toBeInTheDocument()
52 + })
53 +})
frontend/src/components/ApprovalPanel.tsx
+6 -2
@@ -51,7 +51,9 @@ export default function ApprovalPanel({ yearId }: Props) {
51 {preflight && (
52 <div>
53 <p className={preflight.can_approve ? 'ok' : 'error'}>
54 - {preflight.can_approve ? 'همهٔ کنترل‌های حیاتی قبول شدند.' : 'کنترل‌های حیاتی رد شدند — تصویب مسدود است.'}
54 + {preflight.can_approve
55 + ? 'همهٔ کنترل‌های حیاتی اجرا و قبول شدند.'
56 + : 'کنترل‌های حیاتی رد یا اجرا نشدند — تصویب مسدود است.'}
57 </p>
58 <table>
59 <thead>
@@ -67,7 +69,9 @@ export default function ApprovalPanel({ yearId }: Props) {
69 <tr key={c.code}>
70 <td className="mono">{c.code}</td>
71 <td>{c.severity}</td>
70 - <td className={c.passed ? 'ok' : 'error'}>{c.passed ? 'قبول' : 'رد'}</td>
72 + <td className={c.passed ? 'ok' : 'error'}>
73 + {c.passed ? 'قبول' : c.ran === false ? 'اجرا نشد' : 'رد'}
74 + </td>
75 <td>{c.message_fa}</td>
76 </tr>
77 ))}
frontend/src/components/NotesManager.tsx
+32 -3
@@ -1,5 +1,6 @@
1 import { useCallback, useEffect, useState } from 'react'
2 import { api, ApiError } from '../api/client'
3 +import type { NoteRole } from '../api/types'
4 import { faNumber } from '../lib/format'
5
6 interface Props {
@@ -13,6 +14,13 @@ interface NoteRow {
14 title: string
15 statement: string
16 section: string
17 + role: NoteRole | null
18 +}
19 +
20 +const ROLE_LABELS: Record<string, string> = {
21 + '': '—',
22 + cash: 'نقد (کنترل C-10)',
23 + retained_earnings: 'سود انباشته (کنترل C-08)',
24 }
25
26 interface MappingRow {
@@ -26,6 +34,7 @@ export default function NotesManager({ yearId, refreshKey }: Props) {
34 const [notes, setNotes] = useState<NoteRow[]>([])
35 const [mappings, setMappings] = useState<MappingRow[]>([])
36 const [edits, setEdits] = useState<Record<number, string>>({})
37 + const [roles, setRoles] = useState<Record<number, string>>({})
38 const [error, setError] = useState<string | null>(null)
39 const [message, setMessage] = useState<string | null>(null)
40
@@ -70,6 +79,7 @@ export default function NotesManager({ yearId, refreshKey }: Props) {
79 <th>شماره</th>
80 <th>عنوان</th>
81 <th>صورت/بخش</th>
82 + <th>نقش کنترلی</th>
83 <th>عملیات</th>
84 </tr>
85 </thead>
@@ -86,13 +96,32 @@ export default function NotesManager({ yearId, refreshKey }: Props) {
96 <td className="muted">
97 {n.statement}/{n.section}
98 </td>
99 + <td>
100 + <select
101 + aria-label={`نقش کنترلی یادداشت ${n.note_number}`}
102 + value={roles[n.note_id] ?? n.role ?? ''}
103 + onChange={(e) => setRoles((s) => ({ ...s, [n.note_id]: e.target.value }))}
104 + >
105 + {Object.entries(ROLE_LABELS).map(([value, label]) => (
106 + <option key={value} value={value}>
107 + {label}
108 + </option>
109 + ))}
110 + </select>
111 + </td>
112 <td>
113 <button
114 type="button"
115 onClick={() =>
116 act(
94 - () => api.updateNote(yearId, n.note_id, { title: edits[n.note_id] ?? n.title }),
95 - 'عنوان یادداشت به‌روز شد.',
117 + () => {
118 + const role = roles[n.note_id] ?? n.role ?? ''
119 + return api.updateNote(yearId, n.note_id, {
120 + title: edits[n.note_id] ?? n.title,
121 + ...(role ? { role: role as NoteRole } : {}),
122 + })
123 + },
124 + 'یادداشت به‌روز شد.',
125 )
126 }
127 >
@@ -109,7 +138,7 @@ export default function NotesManager({ yearId, refreshKey }: Props) {
138 ))}
139 {notes.length === 0 && (
140 <tr>
112 - <td colSpan={4} className="muted">
141 + <td colSpan={5} className="muted">
142 یادداشتی وجود ندارد.
143 </td>
144 </tr>