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

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

Synced Dec 4, 15:30 UTC

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>

davoodmehraban89 committed Dec 4, 2026 at 10:18 UTC f8816dc1a1f4313434e6b16c38137fe50cdd159d
21 files changed +1548 -129
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
+328 -5
@@ -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
@@ -42,6 +46,70 @@ class ControlResult:
46 passed: bool
47 message_fa: str
48 affected: tuple[str, ...] = field(default_factory=tuple)
49 + ran: bool = True
50 +
51 +
52 +@dataclass(frozen=True)
53 +class EquityMovement:
54 + """One equity row: opening + changes must equal closing (C-09)."""
55 +
56 + label: str
57 + opening: Decimal
58 + changes: Decimal
59 + closing: Decimal
60 +
61 +
62 +@dataclass(frozen=True)
63 +class OfficialComparison:
64 + """One (statement, note) comparison against the official statements (C-13)."""
65 +
66 + key: str
67 + ours: Decimal
68 + official: Decimal
69 +
70 +
71 +@dataclass(frozen=True)
72 +class ControlContext:
73 + """Optional inputs for C-05..C-15. ``None`` means "not available".
74 +
75 + Every unavailable input makes its control report «اجرا نشد» and block
76 + approval, so a year can never be approved on an incomplete control set.
77 + """
78 +
79 + prior_closing: dict[str, Decimal] | None = None
80 + bs_sections: dict[str, Decimal] | None = None
81 + note_totals: dict[str, Decimal] | None = None
82 + line_totals: dict[str, Decimal] | None = None
83 + is_net_profit: Decimal | None = None
84 + eq_retained_change: Decimal | None = None
85 + explicit_adjustments: Decimal = _ZERO
86 + eq_movements: tuple[EquityMovement, ...] | None = None
87 + cf_net_change: Decimal | None = None
88 + cash_opening: Decimal | None = None
89 + cash_closing: Decimal | None = None
90 + known_codes: frozenset[str] | None = None
91 + natures: dict[str, str] | None = None
92 + note_ids: frozenset[str] | None = None
93 + official: tuple[OfficialComparison, ...] | None = None
94 + mode: str = "ui" # "ci" makes C-13 ERROR; "ui" makes it INFO (booklet 1 §7)
95 + change_threshold_pct: Decimal = Decimal(50)
96 +
97 +
98 +def _not_run(code: str, severity: str, reason: str) -> ControlResult:
99 + """An unrun control never passes: it blocks and says why (booklet 2.1 R2)."""
100 + return ControlResult(
101 + code=code, severity=severity, passed=False, message_fa=f"اجرا نشد: {reason}", ran=False
102 + )
103 +
104 +
105 +def _result(code: str, severity: str, bad: tuple[str, ...], ok: str, fail: str) -> ControlResult:
106 + return ControlResult(
107 + code=code,
108 + severity=severity,
109 + passed=not bad,
110 + message_fa=ok if not bad else fail,
111 + affected=bad,
112 + )
113
114
115 def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]:
@@ -144,20 +212,275 @@ def check_c04(rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]])
212 )
213
214
215 +def check_c05(rows: list[BalanceRow], prior_closing: dict[str, Decimal] | None) -> ControlResult:
216 + """C-05: prior-year closing == current-year opening, account by account."""
217 + if prior_closing is None:
218 + return _not_run("C-05", "ERROR", "مانده پایان سال مالی قبل در دسترس نیست")
219 + opening = {code: b["opening"] for code, b in _aggregate(rows).items()}
220 + bad = tuple(
221 + code
222 + for code in sorted(set(opening) | set(prior_closing))
223 + if opening.get(code, _ZERO) != prior_closing.get(code, _ZERO)
224 + )
225 + return _result(
226 + "C-05",
227 + "ERROR",
228 + bad,
229 + "مانده پایان سال قبل با مانده ابتدای سال جاری برای همهٔ حساب‌ها برابر است",
230 + f"{len(bad)} حساب مانده ابتدای سالشان با پایان سال قبل نمی‌خواند",
231 + )
232 +
233 +
234 +def check_c06(bs_sections: dict[str, Decimal] | None) -> ControlResult:
235 + """C-06: assets == liabilities + equity on the balance sheet."""
236 + if bs_sections is None:
237 + return _not_run("C-06", "ERROR", "صورت وضعیت مالی ساخته نشده است")
238 + missing = [k for k in ("Assets", "Liabilities", "Equity") if k not in bs_sections]
239 + if missing:
240 + return _not_run("C-06", "ERROR", f"بخش‌های غایب در ترازنامه: {'، '.join(missing)}")
241 + assets = bs_sections["Assets"]
242 + other = bs_sections["Liabilities"] + bs_sections["Equity"]
243 + return _result(
244 + "C-06",
245 + "ERROR",
246 + () if assets == other else ("balance_sheet",),
247 + "معادلهٔ ترازنامه برقرار است: دارایی‌ها = بدهی‌ها + حقوق مالکانه",
248 + "معادلهٔ ترازنامه نقض شده است: دارایی‌ها ≠ بدهی‌ها + حقوق مالکانه",
249 + )
250 +
251 +
252 +def check_c07(
253 + note_totals: dict[str, Decimal] | None, line_totals: dict[str, Decimal] | None
254 +) -> ControlResult:
255 + """C-07: each note total equals its statement line, keyed by (statement, note)."""
256 + if note_totals is None or line_totals is None:
257 + return _not_run("C-07", "ERROR", "جمع یادداشت‌ها یا سطرهای صورت در دسترس نیست")
258 + bad = tuple(
259 + key
260 + for key in sorted(set(note_totals) | set(line_totals))
261 + if note_totals.get(key, _ZERO) != line_totals.get(key, _ZERO)
262 + )
263 + return _result(
264 + "C-07",
265 + "ERROR",
266 + bad,
267 + "جمع هر یادداشت با سطر متناظر در صورت برابر است",
268 + f"{len(bad)} یادداشت جمعشان با سطر متناظر صورت نمی‌خواند",
269 + )
270 +
271 +
272 +def check_c08(
273 + is_net_profit: Decimal | None,
274 + eq_retained_change: Decimal | None,
275 + explicit_adjustments: Decimal = _ZERO,
276 +) -> ControlResult:
277 + """C-08: IS net result == change in retained earnings (EQ) + explicit adjustments."""
278 + if is_net_profit is None or eq_retained_change is None:
279 + return _not_run("C-08", "ERROR", "سود خالص یا تغییر سود انباشته در دسترس نیست")
280 + passed = is_net_profit == eq_retained_change + explicit_adjustments
281 + return _result(
282 + "C-08",
283 + "ERROR",
284 + () if passed else ("retained_earnings",),
285 + "سود و زیان خالص با تغییر سود انباشته (با اصلاحات صریح) برابر است",
286 + "سود و زیان خالص با تغییر سود انباشته نمی‌خواند",
287 + )
288 +
289 +
290 +def check_c09(eq_movements: tuple[EquityMovement, ...] | None) -> ControlResult:
291 + """C-09: for every equity row, opening + changes == closing."""
292 + if eq_movements is None:
293 + return _not_run("C-09", "ERROR", "صورت تغییرات حقوق مالکانه ساخته نشده است")
294 + if not eq_movements:
295 + return _not_run("C-09", "ERROR", "هیچ ردیف حقوق مالکانه‌ای برای بررسی وجود ندارد")
296 + bad = tuple(m.label for m in eq_movements if m.opening + m.changes != m.closing)
297 + return _result(
298 + "C-09",
299 + "ERROR",
300 + bad,
301 + "برای هر ردیف حقوق مالکانه: مانده ابتدا + تغییرات = مانده پایان",
302 + f"{len(bad)} ردیف حقوق مالکانه معادلهٔ مانده را نقض می‌کنند",
303 + )
304 +
305 +
306 +def check_c10(
307 + cf_net_change: Decimal | None, cash_opening: Decimal | None, cash_closing: Decimal | None
308 +) -> ControlResult:
309 + """C-10: CF net change in cash == closing cash - opening cash (per BS)."""
310 + if cf_net_change is None or cash_opening is None or cash_closing is None:
311 + return _not_run("C-10", "ERROR", "جریان نقدی یا مانده‌های نقد ترازنامه در دسترس نیست")
312 + passed = cf_net_change == cash_closing - cash_opening
313 + return _result(
314 + "C-10",
315 + "ERROR",
316 + () if passed else ("cash_flow",),
317 + "تغییر خالص وجه نقد با تفاضل مانده نقد پایان و ابتدا برابر است",
318 + "تغییر خالص وجه نقد با تفاضل مانده نقد ترازنامه نمی‌خواند",
319 + )
320 +
321 +
322 +def check_c11(rows: list[BalanceRow], known_codes: frozenset[str] | None) -> ControlResult:
323 + """C-11: every subsidiary has its general parent; children sum to a posted parent.
324 +
325 + Canonical identity is general + subsidiary (ADR-014), so the parent of a
326 + subsidiary code is its leading general code.
327 + """
328 + if known_codes is None:
329 + return _not_run("C-11", "ERROR", "فهرست کدهای حساب سال در دسترس نیست")
330 + totals = _aggregate(rows)
331 + bad: list[str] = []
332 + children: dict[str, Decimal] = {}
333 + for code, bucket in sorted(totals.items()):
334 + if len(code) <= 2:
335 + continue
336 + parent = code[:2]
337 + if parent not in known_codes:
338 + bad.append(code)
339 + continue
340 + children[parent] = children.get(parent, _ZERO) + bucket["closing"]
341 + for parent, total in sorted(children.items()):
342 + if parent in totals and totals[parent]["closing"] != total:
343 + bad.append(parent)
344 + return _result(
345 + "C-11",
346 + "ERROR",
347 + tuple(bad),
348 + "سلسله‌مراتب حساب‌ها برقرار است: والد موجود و جمع فرزندان = والد",
349 + f"{len(bad)} کد سلسله‌مراتب را نقض می‌کنند (والد غایب یا جمع ناسازگار)",
350 + )
351 +
352 +
353 +def check_c12(
354 + mappings: dict[str, list[MappingTarget]], note_ids: frozenset[str] | None
355 +) -> ControlResult:
356 + """C-12: no note without a mapping, and no mapping to a nonexistent note."""
357 + if note_ids is None:
358 + return _not_run("C-12", "ERROR", "فهرست یادداشت‌های سال در دسترس نیست")
359 + targets = {t.target for targets in mappings.values() for t in targets}
360 + orphan_notes = tuple(sorted(note_ids - targets))
361 + dangling = tuple(sorted(targets - note_ids))
362 + bad = orphan_notes + dangling
363 + return _result(
364 + "C-12",
365 + "ERROR",
366 + bad,
367 + "هر یادداشت نگاشت دارد و هیچ نگاشتی به یادداشت ناموجود اشاره نمی‌کند",
368 + f"{len(orphan_notes)} یادداشت بدون نگاشت و {len(dangling)} نگاشت به یادداشت ناموجود",
369 + )
370 +
371 +
372 +def check_c13(official: tuple[OfficialComparison, ...] | None, mode: str = "ui") -> ControlResult:
373 + """C-13: agreement with the official statements — ERROR in CI, INFO in the UI."""
374 + severity = "ERROR" if mode == "ci" else "INFO"
375 + if official is None:
376 + return _not_run("C-13", severity, "صورت‌های رسمی برای مقایسه در دسترس نیست")
377 + bad = tuple(c.key for c in official if c.ours != c.official)
378 + return _result(
379 + "C-13",
380 + severity,
381 + bad,
382 + "خروجی با صورت‌های رسمی مطابقت دارد",
383 + f"{len(bad)} قلم با صورت‌های رسمی اختلاف دارد",
384 + )
385 +
386 +
387 +def check_c14(
388 + rows: list[BalanceRow],
389 + prior_closing: dict[str, Decimal] | None,
390 + threshold_pct: Decimal = Decimal(50),
391 +) -> ControlResult:
392 + """C-14 (WARN): movement beyond the threshold relative to the prior year."""
393 + if prior_closing is None:
394 + return _not_run("C-14", "WARN", "مانده سال قبل برای تحلیل تغییر در دسترس نیست")
395 + bad: list[str] = []
396 + for code, bucket in sorted(_aggregate(rows).items()):
397 + prior = prior_closing.get(code, _ZERO)
398 + if prior == _ZERO:
399 + continue
400 + change_pct = abs(bucket["closing"] - prior) / abs(prior) * Decimal(100)
401 + if change_pct > threshold_pct:
402 + bad.append(code)
403 + return _result(
404 + "C-14",
405 + "WARN",
406 + tuple(bad),
407 + "تغییر ناگهانی بیش از آستانه نسبت به سال قبل دیده نشد",
408 + f"{len(bad)} حساب تغییر بیش از آستانه نسبت به سال قبل دارند (نیازمند توضیح)",
409 + )
410 +
411 +
412 +def check_c15(rows: list[BalanceRow], natures: dict[str, str] | None) -> ControlResult:
413 + """C-15 (WARN): an account carrying a balance contrary to its nature."""
414 + if natures is None:
415 + return _not_run("C-15", "WARN", "ماهیت حساب‌ها در دسترس نیست")
416 + bad: list[str] = []
417 + for code, bucket in sorted(_aggregate(rows).items()):
418 + nature = (natures.get(code) or "").strip().lower()
419 + closing = bucket["closing"]
420 + if nature in {"debit", "بدهکار"} and closing < _ZERO:
421 + bad.append(code)
422 + elif nature in {"credit", "بستانکار"} and closing > _ZERO:
423 + bad.append(code)
424 + return _result(
425 + "C-15",
426 + "WARN",
427 + tuple(bad),
428 + "هیچ حسابی مانده خلاف ماهیت ندارد",
429 + f"{len(bad)} حساب مانده خلاف ماهیت دارند (نیازمند توضیح)",
430 + )
431 +
432 +
433 def run_controls(
148 - rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
434 + rows: list[BalanceRow],
435 + mappings: dict[str, list[MappingTarget]],
436 + context: ControlContext | None = None,
437 ) -> 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)]
438 + """Run the full C-01..C-15 set in stable order.
439 +
440 + Without a context every context-dependent control reports «اجرا نشد» and
441 + blocks approval, so an incomplete control set can never approve a year.
442 + """
443 + ctx = context or ControlContext()
444 + return [
445 + check_c01(rows),
446 + check_c02(rows),
447 + check_c03(rows, mappings),
448 + check_c04(rows, mappings),
449 + check_c05(rows, ctx.prior_closing),
450 + check_c06(ctx.bs_sections),
451 + check_c07(ctx.note_totals, ctx.line_totals),
452 + check_c08(ctx.is_net_profit, ctx.eq_retained_change, ctx.explicit_adjustments),
453 + check_c09(ctx.eq_movements),
454 + check_c10(ctx.cf_net_change, ctx.cash_opening, ctx.cash_closing),
455 + check_c11(rows, ctx.known_codes),
456 + check_c12(mappings, ctx.note_ids),
457 + check_c13(ctx.official, ctx.mode),
458 + check_c14(rows, ctx.prior_closing, ctx.change_threshold_pct),
459 + check_c15(rows, ctx.natures),
460 + ]
461
462
463 __all__ = [
464 "BalanceRow",
156 - "MappingTarget",
465 + "ControlContext",
466 "ControlResult",
467 + "EquityMovement",
468 + "MappingTarget",
469 + "OfficialComparison",
470 "check_c01",
471 "check_c02",
472 "check_c03",
473 "check_c04",
474 + "check_c05",
475 + "check_c06",
476 + "check_c07",
477 + "check_c08",
478 + "check_c09",
479 + "check_c10",
480 + "check_c11",
481 + "check_c12",
482 + "check_c13",
483 + "check_c14",
484 + "check_c15",
485 "run_controls",
486 ]
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
+299
@@ -0,0 +1,299 @@
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 + )
64 + for b in balances
65 + ]
66 +
67 +
68 +def load_mappings(session: Session, year_id: int) -> dict[str, list[MappingTarget]]:
69 + mappings: dict[str, list[MappingTarget]] = {}
70 + for rule in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all():
71 + mappings.setdefault(rule.account_code, []).append(
72 + MappingTarget(target=str(rule.target_note_id))
73 + )
74 + return mappings
75 +
76 +
77 +def _latest_statement(session: Session, year_id: int, code: str) -> FinancialStatement | None:
78 + version = session.scalar(
79 + select(func.max(FinancialStatement.version)).where(
80 + FinancialStatement.year_id == year_id,
81 + FinancialStatement.statement_type == code,
82 + )
83 + )
84 + if version is None:
85 + return None
86 + return session.scalar(
87 + select(FinancialStatement).where(
88 + FinancialStatement.year_id == year_id,
89 + FinancialStatement.statement_type == code,
90 + FinancialStatement.version == version,
91 + )
92 + )
93 +
94 +
95 +def _notes(session: Session, year_id: int) -> dict[int, NoteDefinition]:
96 + return {
97 + n.id: n
98 + for n in session.scalars(
99 + select(NoteDefinition).where(NoteDefinition.year_id == year_id)
100 + ).all()
101 + }
102 +
103 +
104 +def _prior_closing(session: Session, year: FiscalYear) -> dict[str, Decimal] | None:
105 + prior = session.scalar(
106 + select(FiscalYear).where(
107 + FiscalYear.company_id == year.company_id, FiscalYear.year == year.year - 1
108 + )
109 + )
110 + if prior is None:
111 + return None
112 + totals: dict[str, Decimal] = {}
113 + for row in load_rows(session, prior.id):
114 + totals[row.account_code] = totals.get(row.account_code, _ZERO) + row.closing
115 + return totals
116 +
117 +
118 +def _signed_account_totals(
119 + rows: list[BalanceRow],
120 + mappings: dict[str, list[MappingTarget]],
121 + notes: dict[int, NoteDefinition],
122 + statement: str,
123 +) -> tuple[dict[str, dict[str, Decimal]], dict[str, str]]:
124 + """Per-note signed totals for one statement, plus each note's section."""
125 + policy = SECTION_POLICY.get(statement, {})
126 + totals: dict[str, dict[str, Decimal]] = {}
127 + sections: dict[str, str] = {}
128 + note_by_id = {str(nid): n for nid, n in notes.items()}
129 + for row in rows:
130 + for target in mappings.get(row.account_code, []):
131 + note = note_by_id.get(target.target)
132 + if note is None:
133 + continue
134 + config = note.configuration_json or {}
135 + if str(config.get("statement") or "") != statement:
136 + continue
137 + section = str(config.get("section") or "")
138 + sign = Decimal(policy.get(section, 1))
139 + key = f"{statement}:{note.note_number}"
140 + bucket = totals.setdefault(key, {"opening": _ZERO, "changes": _ZERO, "closing": _ZERO})
141 + bucket["opening"] += row.opening * sign
142 + bucket["changes"] += (row.debit - row.credit) * sign
143 + bucket["closing"] += row.closing * sign
144 + sections[key] = section
145 + return totals, sections
146 +
147 +
148 +def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -> ControlContext:
149 + """Collect every available input; leave the rest ``None`` (fail-closed)."""
150 + year = session.get(FiscalYear, year_id)
151 + if year is None:
152 + return ControlContext(mode=mode)
153 + rows = load_rows(session, year_id)
154 + mappings = load_mappings(session, year_id)
155 + notes = _notes(session, year_id)
156 +
157 + bs_totals, bs_sections_by_key = _signed_account_totals(rows, mappings, notes, "BS")
158 + is_totals, is_sections_by_key = _signed_account_totals(rows, mappings, notes, "IS")
159 + eq_totals, _ = _signed_account_totals(rows, mappings, notes, "EQ")
160 + cf_totals, _ = _signed_account_totals(rows, mappings, notes, "CF")
161 +
162 + bs_sections: dict[str, Decimal] | None = None
163 + if _latest_statement(session, year_id, "BS") is not None and bs_totals:
164 + accumulated: dict[str, Decimal] = {}
165 + for key, bucket in bs_totals.items():
166 + section = bs_sections_by_key[key]
167 + accumulated[section] = accumulated.get(section, _ZERO) + bucket["closing"]
168 + bs_sections = accumulated
169 +
170 + line_totals: dict[str, Decimal] | None = None
171 + note_totals: dict[str, Decimal] | None = None
172 + if any(_latest_statement(session, year_id, c) is not None for c in ("BS", "IS")):
173 + lines_by_key: dict[str, Decimal] = {}
174 + for code in ("BS", "IS", "CF", "EQ"):
175 + statement = _latest_statement(session, year_id, code)
176 + if statement is None:
177 + continue
178 + for line in session.scalars(
179 + select(StatementLine).where(StatementLine.statement_id == statement.id)
180 + ).all():
181 + note = notes.get(line.target_note_id) if line.target_note_id else None
182 + if note is None:
183 + continue
184 + key = f"{code}:{note.note_number}"
185 + lines_by_key[key] = lines_by_key.get(key, _ZERO) + (line.mapped_total or _ZERO)
186 + line_totals = lines_by_key
187 + note_totals = {
188 + key: bucket["closing"]
189 + for key, bucket in {**bs_totals, **is_totals, **eq_totals, **cf_totals}.items()
190 + }
191 +
192 + is_net_profit: Decimal | None = None
193 + if is_totals:
194 + revenue = sum(
195 + (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Revenue"),
196 + _ZERO,
197 + )
198 + expenses = sum(
199 + (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Expenses"),
200 + _ZERO,
201 + )
202 + is_net_profit = revenue - expenses
203 +
204 + retained_note = next(
205 + (
206 + n
207 + for n in notes.values()
208 + if (n.configuration_json or {}).get("role") == "retained_earnings"
209 + ),
210 + None,
211 + )
212 + eq_retained_change: Decimal | None = None
213 + if retained_note is not None:
214 + for prefix, table in (("EQ", eq_totals), ("BS", bs_totals)):
215 + retained = table.get(f"{prefix}:{retained_note.note_number}")
216 + if retained is not None:
217 + eq_retained_change = retained["changes"]
218 + break
219 +
220 + # Equity movements are the notes explicitly sectioned "Equity" (BS or EQ) —
221 + # never inferred from a title. No such note means C-09 cannot run.
222 + equity_buckets: dict[str, dict[str, Decimal]] = {}
223 + for _prefix, table, sections in (
224 + ("EQ", eq_totals, None),
225 + ("BS", bs_totals, bs_sections_by_key),
226 + ):
227 + for key, bucket in table.items():
228 + section = sections[key] if sections is not None else "Equity"
229 + if section == "Equity":
230 + equity_buckets[key] = bucket
231 + eq_movements: tuple[EquityMovement, ...] | None = None
232 + if equity_buckets:
233 + eq_movements = tuple(
234 + EquityMovement(
235 + label=key, opening=b["opening"], changes=b["changes"], closing=b["closing"]
236 + )
237 + for key, b in sorted(equity_buckets.items())
238 + )
239 +
240 + cash_note = next(
241 + (n for n in notes.values() if (n.configuration_json or {}).get("role") == "cash"), None
242 + )
243 + cash_opening: Decimal | None = None
244 + cash_closing: Decimal | None = None
245 + if cash_note is not None:
246 + cash = bs_totals.get(f"BS:{cash_note.note_number}")
247 + if cash is not None:
248 + cash_opening, cash_closing = cash["opening"], cash["closing"]
249 +
250 + cf_net_change: Decimal | None = None
251 + if cf_totals:
252 + cf_net_change = sum((b["changes"] for b in cf_totals.values()), _ZERO)
253 +
254 + # The chart is what the year actually declares: registered account versions,
255 + # the ledger's own account codes, and the general ("kol") codes each ledger row
256 + # carries. A parent is "existing" when the source declares it; the sum check
257 + # only applies when the ledger also posts the parent itself (booklet 1 §7).
258 + codes = {
259 + c
260 + for (c,) in session.execute(
261 + select(AccountVersion.account_code).where(AccountVersion.year_id == year_id)
262 + ).all()
263 + }
264 + codes.update(row.account_code for row in rows)
265 + codes.update(
266 + g
267 + for (g,) in session.execute(
268 + select(LedgerBalance.general_code).where(LedgerBalance.year_id == year_id).distinct()
269 + ).all()
270 + if g
271 + )
272 + natures = {
273 + code: (nature or "")
274 + for code, nature in session.execute(
275 + select(AccountVersion.account_code, AccountVersion.nature).where(
276 + AccountVersion.year_id == year_id
277 + )
278 + ).all()
279 + }
280 +
281 + return ControlContext(
282 + prior_closing=_prior_closing(session, year),
283 + bs_sections=bs_sections,
284 + note_totals=note_totals,
285 + line_totals=line_totals,
286 + is_net_profit=is_net_profit,
287 + eq_retained_change=eq_retained_change,
288 + eq_movements=eq_movements,
289 + cf_net_change=cf_net_change,
290 + cash_opening=cash_opening,
291 + cash_closing=cash_closing,
292 + known_codes=frozenset(codes) if codes else None,
293 + natures=natures or None,
294 + note_ids=frozenset(str(nid) for nid in notes) if notes else None,
295 + mode=mode,
296 + )
297 +
298 +
299 +__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
+348
@@ -0,0 +1,348 @@
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
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
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
+70
@@ -0,0 +1,70 @@
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 — the API must be able to reach an approvable year
56 +
57 +Requiring C-05 without a way to load a prior year would make approval impossible
58 +forever. `POST /companies/{company_id}/years` adds a fiscal year to an existing
59 +company (duplicate year ⇒ 422). `tests/helpers_complete_year.py` builds a complete
60 +approvable year **through the public API only**, which doubles as proof that the
61 +surface is sufficient.
62 +
63 +## Consequences
64 +
65 +- Real 1404 data cannot be approved yet: it has no prior year loaded and no
66 + designated notes. That is the correct, conservative outcome, not a regression.
67 +- The ingestion preflight (`services/preflight.py`) now also returns fifteen
68 + results; without stored context it can never claim a year is approvable.
69 +- Legacy tests that asserted a four-control set or approval after mapping alone
70 + 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>