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

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

Synced Dec 4, 15:30 UTC

feat(compare): R3 — compare built statements with the official workbook

Booklet 2.1 R3. The comparison now reads the persisted StatementLine rows that build_statements wrote, keyed by (statement, note), instead of aggregating the source workbook separately. Measuring against official 1404 exposed three real engine defects (ADR-032): - statement_balance is debit-positive, not pre-signed: applying the section sign reproduces the official balance sheet 16/16 (7 notes were flipped before). - the per-row CLOSING fallback leaked non-statement rows into totals; the basis now belongs to the import (BS went 6/16 -> 16/16 through the engine). - the source assigns notes per ROW (account 718291 posts to notes 6 and 9), so LedgerBalance.source_note preserves it (migration 20261204_09). An explicit mapping wins; the source note disambiguates multi-note accounts. - IS presents expenses negative, so Revenue and Expenses both take -1 and the net result is the sum of signed IS lines (C-08 input corrected). official_parse.py gives each statement the parser its layout needs: EQ is a components x movements matrix (0 -> 24 figures), CF's 46268 is an account code, and the year column is anchored on the header row (the title also contains it). Measured: BS 16/16 MET. IS 1/6 exact — 6/7 within 1-2 million rial of official presentation rounding, 8/9 differ by a 1,111,554 reclassification (their sum matches exactly), 20-3 has no source rows at all. IS 6/6 NOT MET and reported as such; no tolerance invented, no figure adjusted. discrepancies.json regenerated from built output with cause + official cell + account deltas. C-13 feed + POST /years/{id}/official-comparison. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 4, 2026 at 11:38 UTC c314a7c6243a963f07cb2ddb149b27c78e5988ff
18 files changed +1229 -332
PROJECT_STATUS.md
+29 -4
@@ -92,8 +92,8 @@ Booklet 2 v2.0 («اصلاح مسیر و معماری نهایی Aram», [`docs/
92 | Task | Scope | Status |
93 | --- | --- | --- |
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 |
95 +| R2 | Controls C-05..C-15 wired into `run_controls` + approval | **MET** — PR #100 squash-merged 2026-12-04T10:40:42Z → `a8ba20c1` |
96 +| R3 | `build_statements` vs official; (statement, note) aggregation; IS 6/8/9 root cause; EQ/CF parsing | **PARTIAL** (this PR) — BS 16/16 met; IS 6/6 **not met**, blocked by source data (evidence below) |
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 |
99 | R6 | Propose marking the `v1.0.0` Release as pre-release; `experiment/browser-edition` = owner action | NOT_STARTED |
@@ -123,14 +123,39 @@ Backend **404 passed / exit 0** (was 354); frontend **17 vitest tests / 6 files*
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 +### R3 acceptance ← evidence
127 +
128 +| معیار پذیرش | شاهد | وضعیت |
129 +| --- | --- | --- |
130 +| Compare **`build_statements` output** (not a separate source aggregation) | `services/statement_compare.py` reads persisted `StatementLine` rows; `TestBuiltComparison` | MET |
131 +| Aggregate by **(statement, note)** | `TestBuiltComparison::test_note_keys_are_scoped_by_statement` | MET |
132 +| Display-sign policy per section/note; stored values untouched | ADR-032 §1/§4; `test_statement_build.py::test_bs_is_totals_and_signs`; no stored figure is modified by the comparison | MET |
133 +| **BS 16/16** | live run on real 1404 (131,280 rows): all 16 notes Δ=0 | **MET** |
134 +| **IS 6/6** | live run: 1/6 exact. 6 → Δ−2, 7 → Δ+1 (official per-category rounding), 8/9 → ±1,111,554 reclassification, 20-3 → no source rows at all | **NOT MET** |
135 +| Root-cause IS 6/8/9 with account-by-account deltas | `docs/discrepancies.json` v2 (cause + official cell + accounts per entry); ADR-032 | MET |
136 +| Finish EQ parsing + CF classification (46268 = account code) | `TestOfficialParsing`: EQ 0 → 24 figures; `test_cf_account_code_is_not_treated_as_a_note` | MET (parsing); CF/EQ still not rendered |
137 +| Regenerate `discrepancies.json` | `docs/discrepancies.json` regenerated from built output, 11 caused entries | MET |
138 +
139 +**Why IS 6/6 cannot be met from this source:** official note 20-3 (tax −4,697,329) has no
140 +corresponding row in `source_1404.xlsx`. Notes 8+9 combined match exactly (−9,057,668); only
141 +their split differs, and the official's own adjustment column records exactly ±1,111,554.
142 +No tolerance was invented and no figure was adjusted to force a match (booklet 2.1: MET only
143 +when acceptance fully holds).
144 +
145 +Three real engine defects were found and fixed by measuring against the official workbook:
146 +`statement_balance` is debit-positive (not pre-signed), the CLOSING fallback leaked
147 +non-statement rows (BS 6/16 → 16/16), and per-row note assignment was lost (migration
148 +`20261204_09`). Decisions in **ADR-032**.
149 +
150 ## Known gaps feeding the C-phases (honest residual risks)
151
152 - **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.
153 - `frontend/src/lib/format.ts` uses `Number(value)` (float risk) (C7).
154 - ~~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.
155 +- C-13 now has a feed (`official_comparisons` + `POST /years/{id}/official-comparison`, R3); it still reports «اجرا نشد» until an official workbook is supplied for the year.
156 - **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.
157 +- **CF/EQ are still not rendered** (`RENDERED_STATEMENTS=("BS","IS")`). Their official layouts are parsed (R3) but no built statement exists, so CF is 0/6 and C-07 compares their note totals against nothing → carried forward.
158 +- **IS 8/9 need an explicit reclassification decision** (1,111,554 million rial) and **IS 20-3 has no source rows**; both are recorded with cause in `docs/discrepancies.json`.
159 - **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`.
160 - ImportRun/CalculationRun/LineageEdge/Adjustment/UnknownAccountQueue/carried_from_year_id/calculation_run_id refs absent; pilot exception queue not persisted in `domain/` (C1/C4).
161 - `note_engine.acct()` is closing-only; statement_balance-only rows evaluate 0 in notes (C1/C3).
backend/migrations/versions/20261204_09_source_note.py new
+49
@@ -0,0 +1,49 @@
1 +"""Preserve the note the source row itself assigns (R3, booklet 2.1).
2 +
3 +The canonical ledger assigns a note per ROW: one account can feed two different
4 +notes (measured on 1404: account 718291 posts to both note 6 and note 9). An
5 +account-level mapping alone cannot express that, so the row's own assignment is
6 +stored and the engine honours it when present.
7 +
8 +Revision ID: 20261204_09
9 +Revises: 20261204_08
10 +"""
11 +
12 +import sqlalchemy as sa
13 +from alembic import op
14 +
15 +from aram_backend.db_triggers import install_triggers
16 +
17 +revision = "20261204_09"
18 +down_revision = "20261204_08"
19 +branch_labels = None
20 +depends_on = None
21 +
22 +
23 +def _has_column(bind) -> bool:
24 + inspector = sa.inspect(bind)
25 + if "ledger_balances" not in inspector.get_table_names():
26 + return False
27 + return any(c["name"] == "source_note" for c in inspector.get_columns("ledger_balances"))
28 +
29 +
30 +def upgrade() -> None:
31 + bind = op.get_bind()
32 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
33 + return
34 + if not _has_column(bind):
35 + with op.batch_alter_table("ledger_balances") as batch:
36 + batch.add_column(
37 + sa.Column("source_note", sa.String(32), nullable=False, server_default="")
38 + )
39 + install_triggers(bind)
40 +
41 +
42 +def downgrade() -> None:
43 + bind = op.get_bind()
44 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
45 + return
46 + if _has_column(bind):
47 + with op.batch_alter_table("ledger_balances") as batch:
48 + batch.drop_column("source_note")
49 + install_triggers(bind)
backend/src/aram_backend/domain/controls.py
+23 -10
@@ -23,10 +23,10 @@ _ZERO = Decimal(0)
23 class BalanceRow:
24 """One ledger balance row (all amounts exact Decimal rial).
25
26 - ``statement_balance`` is the reclassified presentation figure some source rows
27 - carry instead of CLOSING. It is already presentation-signed, so controls that
28 - feed statement comparisons must use it exactly as ``build_statements`` does
29 - (ADR-013/018); C-01/C-02 still audit the raw debit/credit columns.
26 + ``statement_balance`` is the reclassified figure some source rows carry
27 + instead of CLOSING. Like CLOSING it is debit-positive, so the section display
28 + sign applies to it too (ADR-032, measured: BS 16/16 against the official
29 + 1404 balance sheet). C-01/C-02 still audit the raw debit/credit columns.
30 """
31
32 row_number: int
@@ -36,12 +36,24 @@ class BalanceRow:
36 credit: Decimal
37 closing: Decimal
38 statement_balance: Decimal | None = None
39 -
40 - def display(self, sign: Decimal) -> Decimal:
41 - """The figure a statement line would show for this row under ``sign``."""
42 - if self.statement_balance is not None:
43 - return self.statement_balance
44 - return self.closing * sign
39 + source_note: str = ""
40 +
41 + def display(self, sign: Decimal, basis: str = "auto") -> Decimal:
42 + """The figure a statement line shows for this row under ``sign``.
43 +
44 + Mirrors ``build_statements`` exactly (ADR-032). ``basis`` is decided by
45 + the import, not guessed per row: when a source provides statement
46 + balances at all, that column is the statement figure and a row without
47 + one contributes nothing (falling back to CLOSING there contaminated the
48 + official comparison); otherwise CLOSING is the figure.
49 + """
50 + if basis == "statement_balance":
51 + figure = self.statement_balance if self.statement_balance is not None else _ZERO
52 + elif basis == "closing":
53 + figure = self.closing
54 + else:
55 + figure = self.statement_balance if self.statement_balance is not None else self.closing
56 + return figure * sign
57
58
59 @dataclass(frozen=True)
@@ -106,6 +118,7 @@ class ControlContext:
118 official: tuple[OfficialComparison, ...] | None = None
119 mode: str = "ui" # "ci" makes C-13 ERROR; "ui" makes it INFO (booklet 1 §7)
120 change_threshold_pct: Decimal = Decimal(50)
121 + basis: str = "auto" # statement figure basis of the import (ADR-032)
122
123
124 def _not_run(code: str, severity: str, reason: str) -> ControlResult:
backend/src/aram_backend/ledger_parser.py
+12
@@ -35,6 +35,7 @@ class LedgerRecord:
35 credit: Decimal
36 closing: Decimal
37 statement_balance: Decimal | None = None
38 + source_note: str = ""
39
40
41 @dataclass(frozen=True)
@@ -65,6 +66,9 @@ _FIELDS = {
66 }
67
68 _STATEMENT_BALANCE_HEADER = "مانده صورت مالی"
69 +# The source ledger assigns a note per ROW, not per account: one account can
70 +# feed two different notes. Preserving it keeps that split (R3, ADR-032).
71 +_SOURCE_NOTE_HEADER = "یادداشت کل"
72
73 _CSV_ENCODINGS = ("utf-8-sig", "utf-8", "cp1256")
74
@@ -261,6 +265,13 @@ def _build_record_tolerant(
265 except LedgerParseError:
266 statement_balance = None
267
268 + source_note = ""
269 + note_index = indexes.get(normalize_fa(_SOURCE_NOTE_HEADER))
270 + if note_index is not None and note_index < len(values):
271 + raw_note = values[note_index]
272 + if raw_note is not None:
273 + source_note = normalize_fa(str(raw_note)).strip()
274 +
275 record = LedgerRecord(
276 row_number=row_number,
277 account_code=account_code,
@@ -281,6 +292,7 @@ def _build_record_tolerant(
292 credit=credit,
293 closing=closing,
294 statement_balance=statement_balance,
295 + source_note=source_note,
296 )
297 return record, None
298
backend/src/aram_backend/models.py
+3
@@ -259,6 +259,9 @@ class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
259 credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
260 closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
261 statement_balance: Mapped[Decimal | None] = mapped_column(Rial(), nullable=True, default=None)
262 + # Note assigned by the source row itself (R3): one account may feed several
263 + # notes, so the row's own assignment must survive the import.
264 + source_note: Mapped[str] = mapped_column(String(32), default="", server_default="")
265 entry_type: Mapped[str] = mapped_column(String(32), default="")
266
267
backend/src/aram_backend/services/control_context.py
+21 -15
@@ -25,6 +25,7 @@ from aram_backend.domain.controls import (
25 ControlContext,
26 EquityMovement,
27 MappingTarget,
28 + OfficialComparison,
29 )
30 from aram_backend.models import (
31 AccountVersion,
@@ -61,6 +62,7 @@ def load_rows(session: Session, year_id: int) -> list[BalanceRow]:
62 credit=b.credit,
63 closing=b.closing,
64 statement_balance=b.statement_balance,
65 + source_note=b.source_note,
66 )
67 for b in balances
68 ]
@@ -121,6 +123,7 @@ def _signed_account_totals(
123 mappings: dict[str, list[MappingTarget]],
124 notes: dict[int, NoteDefinition],
125 statement: str,
126 + basis: str = "auto",
127 ) -> tuple[dict[str, dict[str, Decimal]], dict[str, str]]:
128 """Per-note signed totals for one statement, plus each note's section."""
129 policy = SECTION_POLICY.get(statement, {})
@@ -143,12 +146,18 @@ def _signed_account_totals(
146 # figure is authoritative and already signed (ADR-013/018).
147 bucket["opening"] += row.opening * sign
148 bucket["changes"] += (row.debit - row.credit) * sign
146 - bucket["closing"] += row.display(sign)
149 + bucket["closing"] += row.display(sign, basis)
150 sections[key] = section
151 return totals, sections
152
153
151 -def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -> ControlContext:
154 +def build_control_context(
155 + session: Session,
156 + year_id: int,
157 + *,
158 + mode: str = "ui",
159 + official: tuple[OfficialComparison, ...] | None = None,
160 +) -> ControlContext:
161 """Collect every available input; leave the rest ``None`` (fail-closed)."""
162 year = session.get(FiscalYear, year_id)
163 if year is None:
@@ -157,10 +166,11 @@ def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -
166 mappings = load_mappings(session, year_id)
167 notes = _notes(session, year_id)
168
160 - bs_totals, bs_sections_by_key = _signed_account_totals(rows, mappings, notes, "BS")
161 - is_totals, is_sections_by_key = _signed_account_totals(rows, mappings, notes, "IS")
162 - eq_totals, _ = _signed_account_totals(rows, mappings, notes, "EQ")
163 - cf_totals, _ = _signed_account_totals(rows, mappings, notes, "CF")
169 + basis = "statement_balance" if any(r.statement_balance is not None for r in rows) else "closing"
170 + bs_totals, bs_sections_by_key = _signed_account_totals(rows, mappings, notes, "BS", basis)
171 + is_totals, is_sections_by_key = _signed_account_totals(rows, mappings, notes, "IS", basis)
172 + eq_totals, _ = _signed_account_totals(rows, mappings, notes, "EQ", basis)
173 + cf_totals, _ = _signed_account_totals(rows, mappings, notes, "CF", basis)
174
175 bs_sections: dict[str, Decimal] | None = None
176 if _latest_statement(session, year_id, "BS") is not None and bs_totals:
@@ -194,15 +204,9 @@ def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -
204
205 is_net_profit: Decimal | None = None
206 if is_totals:
197 - revenue = sum(
198 - (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Revenue"),
199 - _ZERO,
200 - )
201 - expenses = sum(
202 - (b["closing"] for k, b in is_totals.items() if is_sections_by_key[k] == "Expenses"),
203 - _ZERO,
204 - )
205 - is_net_profit = revenue - expenses
207 + # Every IS line is already presentation-signed (expenses negative), so
208 + # the net result is their sum — not revenue minus expenses (ADR-032).
209 + is_net_profit = sum((b["closing"] for b in is_totals.values()), _ZERO)
210
211 retained_note = next(
212 (
@@ -295,7 +299,9 @@ def build_control_context(session: Session, year_id: int, *, mode: str = "ui") -
299 known_codes=frozenset(codes) if codes else None,
300 natures=natures or None,
301 note_ids=frozenset(str(nid) for nid in notes) if notes else None,
302 + official=official,
303 mode=mode,
304 + basis=basis,
305 )
306
307
backend/src/aram_backend/services/ledger_import.py
+1
@@ -67,6 +67,7 @@ def import_ledger_balances(
67 credit=record.credit,
68 closing=record.closing,
69 statement_balance=record.statement_balance,
70 + source_note=record.source_note,
71 entry_type=record.entry_type,
72 )
73 )
backend/src/aram_backend/services/official_parse.py new
+236
@@ -0,0 +1,236 @@
1 +"""Parse the four official statements into comparable figures (R3, booklet 2.1).
2 +
3 +The official workbook is not uniform: BS/IS are note lists, EQ is a matrix of
4 +components x movements, and CF mixes note references with a raw account code.
5 +Each parser returns keyed figures plus the provenance (sheet, row, column) so
6 +every comparison can be traced back to the exact official cell.
7 +
8 +Amounts are **million rial** as presented; the source ledger is exact rial, so the
9 +comparison converts once, at the edge (ADR-012 half-up rounding).
10 +"""
11 +
12 +from __future__ import annotations
13 +
14 +import re
15 +from dataclasses import dataclass
16 +from decimal import Decimal
17 +from io import BytesIO
18 +from pathlib import Path
19 +from typing import Any
20 +
21 +from openpyxl import load_workbook
22 +
23 +STATEMENT_SHEETS = {
24 + "BS": "وضعيت مالي",
25 + "IS": "سودوزيان",
26 + "EQ": "حقوق مالكانه",
27 + "CF": "جريان هاي نقدي",
28 +}
29 +_NOTE_RE = re.compile(r"^\d+(?:-\d+)?$")
30 +# A CF row may cite a bare account code instead of a note (e.g. the FX line).
31 +_ACCOUNT_CODE_RE = re.compile(r"^\d{5,}$")
32 +
33 +
34 +@dataclass(frozen=True)
35 +class OfficialFigure:
36 + """One official figure, in million rial, with its cell provenance."""
37 +
38 + statement: str
39 + key: str
40 + amount: Decimal
41 + sheet: str
42 + row: int
43 + column: int
44 + kind: str = "note" # "note" | "account_code" | "equity_component"
45 + label: str = ""
46 +
47 +
48 +def _year_column(rows: list[tuple[Any, ...]], year: int, default: int) -> int:
49 + """Locate the column headed by the year, never a fixed index.
50 +
51 + The search is anchored on the header row (the one carrying the note-column
52 + caption): a title row such as «به تاریخ 29 اسفند 1404» also contains the year
53 + and would otherwise win, pointing at column 0.
54 + """
55 + for row in rows[:12]:
56 + texts = [str(c).strip() if c is not None else "" for c in row]
57 + if not any("ادداشت" in t for t in texts):
58 + continue
59 + for i, text in enumerate(texts):
60 + if str(year) in text:
61 + return i
62 + return default
63 +
64 +
65 +def _note_in(row: tuple[Any, ...], columns: tuple[int, ...]) -> str | None:
66 + for i in columns:
67 + if i < len(row) and row[i] is not None:
68 + text = str(row[i]).strip()
69 + if _NOTE_RE.fullmatch(text):
70 + return text
71 + return None
72 +
73 +
74 +def _sheet_rows(path: str | Path | bytes | bytes, sheet: str) -> list[tuple[Any, ...]]:
75 + source = BytesIO(path) if isinstance(path, bytes) else path
76 + wb = load_workbook(source, read_only=True, data_only=True, keep_links=False)
77 + try:
78 + if sheet not in wb.sheetnames:
79 + return []
80 + return list(wb[sheet].iter_rows(values_only=True))
81 + finally:
82 + wb.close()
83 +
84 +
85 +def parse_note_statement(
86 + path: str | Path | bytes, statement: str, year: int
87 +) -> list[OfficialFigure]:
88 + """BS / IS / CF: one figure per note reference (CF also cites account codes)."""
89 + sheet = STATEMENT_SHEETS[statement]
90 + rows = _sheet_rows(path, sheet)
91 + if not rows:
92 + return []
93 + default_col = 4 if statement == "CF" else 5
94 + amount_col = _year_column(rows, year, default_col)
95 + note_cols = (2, 3)
96 + figures: list[OfficialFigure] = []
97 + for row_no, row in enumerate(rows, start=1):
98 + # An account code is checked first: "46268" also matches the note regex,
99 + # but it is a ledger account (the FX line), not a note (booklet 2.1 R3).
100 + key, kind = None, "note"
101 + if statement == "CF":
102 + for i in note_cols:
103 + if i < len(row) and row[i] is not None:
104 + text = str(row[i]).strip()
105 + if _ACCOUNT_CODE_RE.fullmatch(text):
106 + key, kind = text, "account_code"
107 + break
108 + if key is None:
109 + key = _note_in(row, note_cols)
110 + if key is None or amount_col >= len(row):
111 + continue
112 + value = row[amount_col]
113 + if not isinstance(value, (int, float)):
114 + continue
115 + label = str(row[1])[:80] if len(row) > 1 and row[1] is not None else ""
116 + figures.append(
117 + OfficialFigure(
118 + statement=statement,
119 + key=key,
120 + amount=Decimal(str(value)),
121 + sheet=sheet,
122 + row=row_no,
123 + column=amount_col,
124 + kind=kind,
125 + label=label,
126 + )
127 + )
128 + return figures
129 +
130 +
131 +def parse_equity_matrix(path: str | Path | bytes, year: int) -> list[OfficialFigure]:
132 + """EQ: components are columns, movements are rows (opening / changes / closing).
133 +
134 + The official equity statement has no note numbers at all, which is why the
135 + old note-list parser returned nothing for it. Each component column yields
136 + three figures keyed ``<component>:opening|changes|closing``.
137 + """
138 + sheet = STATEMENT_SHEETS["EQ"]
139 + rows = _sheet_rows(path, sheet)
140 + if not rows:
141 + return []
142 + header_row = None
143 + components: dict[int, str] = {}
144 + for row_no, row in enumerate(rows[:12], start=1):
145 + found = {
146 + i: str(v).strip()
147 + for i, v in enumerate(row)
148 + if v is not None and str(v).strip() and i >= 3
149 + }
150 + if len(found) >= 3 and any("سرمایه" in v for v in found.values()):
151 + header_row, components = row_no, found
152 + break
153 + if header_row is None:
154 + return []
155 +
156 + opening_row = closing_row = None
157 + prior_closing_row = None
158 + for row_no, row in enumerate(rows, start=1):
159 + text = str(row[0]).strip() if row and row[0] is not None else ""
160 + if not text:
161 + continue
162 + if text.startswith("مانده تجدید ارایه شده"):
163 + opening_row = row_no
164 + elif text.startswith("مانده در") and str(year) in text.replace("/", ""):
165 + closing_row = row_no
166 + elif text.startswith("مانده در") and str(year - 1) in text.replace("/", ""):
167 + prior_closing_row = row_no
168 + if opening_row is None or closing_row is None:
169 + return []
170 +
171 + def _values(row_no: int) -> dict[int, Decimal]:
172 + row = rows[row_no - 1]
173 + out: dict[int, Decimal] = {}
174 + for col in components:
175 + value = row[col] if col < len(row) else None
176 + if isinstance(value, (int, float)):
177 + out[col] = Decimal(str(value))
178 + return out
179 +
180 + opening = _values(opening_row)
181 + closing = _values(closing_row)
182 + figures: list[OfficialFigure] = []
183 + for col, name in components.items():
184 + if col not in opening or col not in closing:
185 + continue
186 + changes = closing[col] - opening[col]
187 + for suffix, amount, row_no in (
188 + ("opening", opening[col], opening_row),
189 + ("changes", changes, closing_row),
190 + ("closing", closing[col], closing_row),
191 + ):
192 + figures.append(
193 + OfficialFigure(
194 + statement="EQ",
195 + key=f"{name}:{suffix}",
196 + amount=amount,
197 + sheet=sheet,
198 + row=row_no,
199 + column=col,
200 + kind="equity_component",
201 + label=name,
202 + )
203 + )
204 + if prior_closing_row is not None:
205 + for col, amount in _values(prior_closing_row).items():
206 + figures.append(
207 + OfficialFigure(
208 + statement="EQ",
209 + key=f"{components[col]}:prior_closing",
210 + amount=amount,
211 + sheet=sheet,
212 + row=prior_closing_row,
213 + column=col,
214 + kind="equity_component",
215 + label=components[col],
216 + )
217 + )
218 + return figures
219 +
220 +
221 +def parse_official(path: str | Path | bytes, year: int) -> list[OfficialFigure]:
222 + """All four official statements, each with the parser its layout needs."""
223 + figures: list[OfficialFigure] = []
224 + for statement in ("BS", "IS", "CF"):
225 + figures.extend(parse_note_statement(path, statement, year))
226 + figures.extend(parse_equity_matrix(path, year))
227 + return figures
228 +
229 +
230 +__all__ = [
231 + "OfficialFigure",
232 + "STATEMENT_SHEETS",
233 + "parse_equity_matrix",
234 + "parse_note_statement",
235 + "parse_official",
236 +]
backend/src/aram_backend/services/statement_build.py
+30 -11
@@ -30,7 +30,10 @@ _ZERO = Decimal(0)
30 # Display sign policy (ADR-013/018). Closing is debit-positive.
31 SECTION_POLICY: dict[str, dict[str, int]] = {
32 "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1},
33 - "IS": {"Revenue": -1, "Expenses": 1},
33 + # The official income statement presents revenue positive and expenses
34 + # negative; the ledger is debit-positive, so both take -1 (ADR-032,
35 + # measured on official 1404: notes 6/7/20-3 are negative).
36 + "IS": {"Revenue": -1, "Expenses": -1},
37 "CF": {"Operating": 1, "Investing": 1, "Financing": 1},
38 "EQ": {"Equity": -1},
39 }
@@ -141,15 +144,21 @@ def build_statements(
144 for rule in rules:
145 account_to_notes.setdefault(rule.account_code, []).append(rule.target_note_id)
146
144 - # Per-note display sign (ADR-013). Reclassified rows already carry a
145 - # presentation-signed statement_balance, so the sign is applied only to
146 - # ordinary closing-based rows; this reproduces the Phase-4 golden exactly.
147 + # Per-note display sign (ADR-013, corrected by ADR-032). Measurement on the
148 + # real 1404 ledger shows statement_balance is debit-positive like CLOSING,
149 + # NOT pre-signed: applying the section sign to it reproduces the official
150 + # balance sheet 16/16, while treating it as pre-signed flipped 7 BS notes.
151 note_sign: dict[int, int] = {}
152 for note in notes.values():
153 stype_code = str(note.configuration_json.get("statement") or "")
154 section = str(note.configuration_json.get("section") or "")
155 note_sign[note.id] = SECTION_POLICY.get(stype_code, {}).get(section, 1)
156
157 + # Basis is a property of the import, not of a row (ADR-032): if the source
158 + # supplies statement balances, that column is the statement figure and rows
159 + # without one contribute nothing.
160 + has_statement_balances = any(b.statement_balance is not None for b in balances)
161 +
162 note_totals: dict[int, Decimal] = {}
163 unmapped: list[str] = []
164 for balance in balances:
@@ -158,11 +167,21 @@ def build_statements(
167 if _effective_balance(balance) != _ZERO:
168 unmapped.append(balance.account_full_code)
169 continue
161 - for note_id in targets:
162 - if balance.statement_balance is not None:
163 - contribution = balance.statement_balance
164 - else:
165 - contribution = note_sign.get(note_id, 1) * balance.closing
170 + figure = (balance.statement_balance or _ZERO) if has_statement_balances else balance.closing
171 + # An explicit mapping is authoritative. The source's own per-row note
172 + # only disambiguates an account mapped to several notes, so one account
173 + # feeding two notes is not double-counted (ADR-032).
174 + scoped = targets
175 + if balance.source_note and len(targets) > 1:
176 + matching = [
177 + nid
178 + for nid in targets
179 + if notes.get(nid) is not None and str(notes[nid].note_number) == balance.source_note
180 + ]
181 + if matching:
182 + scoped = matching
183 + for note_id in scoped:
184 + contribution = note_sign.get(note_id, 1) * figure
185 note_totals[note_id] = note_totals.get(note_id, _ZERO) + contribution
186
187 built: list[FinancialStatement] = []
@@ -198,8 +217,8 @@ def build_statements(
217 raise StatementBuildError(
218 f"note {note.note_number}: section '{section}' has no sign policy for {stype_code}"
219 )
201 - # note_totals already carries the presentation sign (statement_balance
202 - # rows are pre-signed; closing rows were signed during accumulation).
220 + # note_totals already carries the presentation sign (applied once,
221 + # during accumulation, to whichever figure the row provides).
222 total = note_totals.get(note.id, _ZERO)
223 session.add(
224 StatementLine(
backend/src/aram_backend/services/statement_compare.py new
+243
@@ -0,0 +1,243 @@
1 +"""Compare **built** statements against the official ones (R3, booklet 2.1).
2 +
3 +The earlier golden comparison aggregated the source workbook separately, so it
4 +could agree with the official figures while the engine produced something else.
5 +This module reads the persisted `StatementLine` rows that `build_statements`
6 +wrote, so a match here is a match of the product's own output.
7 +
8 +Figures are keyed by **(statement, note)** — note numbers are reused across
9 +statements (BS 10 and CF 10 are different things). Amounts are exact rial in the
10 +database and million rial in the official workbook; conversion happens once,
11 +here, with half-up rounding (ADR-012).
12 +"""
13 +
14 +from __future__ import annotations
15 +
16 +from dataclasses import dataclass, field
17 +from decimal import Decimal
18 +from pathlib import Path
19 +from typing import Any
20 +
21 +from sqlalchemy import func, select
22 +from sqlalchemy.orm import Session
23 +
24 +from aram_backend.domain.controls import OfficialComparison
25 +from aram_backend.domain.money import round_half_up
26 +from aram_backend.models import (
27 + FinancialStatement,
28 + LedgerBalance,
29 + MappingRule,
30 + NoteDefinition,
31 + StatementLine,
32 +)
33 +from aram_backend.services.official_parse import OfficialFigure, parse_official
34 +from aram_backend.services.statement_build import SECTION_POLICY
35 +
36 +_MILLION = Decimal(1_000_000)
37 +_ZERO = Decimal(0)
38 +
39 +
40 +@dataclass(frozen=True)
41 +class AccountDelta:
42 + """One account's contribution to a note, for root-causing a difference."""
43 +
44 + account_code: str
45 + account_name: str
46 + rial: Decimal
47 + million_rounded: int
48 + source_rows: int
49 +
50 +
51 +@dataclass(frozen=True)
52 +class NoteDelta:
53 + statement: str
54 + note: str
55 + built_million: int | None
56 + official_million: int | None
57 + delta: int | None
58 + match: bool
59 + status: str # matched | mismatched | missing_in_build | missing_in_official
60 + official_cell: str = ""
61 + accounts: tuple[AccountDelta, ...] = field(default_factory=tuple)
62 +
63 +
64 +@dataclass(frozen=True)
65 +class ComparisonReport:
66 + year: int
67 + deltas: tuple[NoteDelta, ...]
68 +
69 + def counts(self) -> dict[str, dict[str, int]]:
70 + out: dict[str, dict[str, int]] = {}
71 + for d in self.deltas:
72 + bucket = out.setdefault(d.statement, {"matched": 0, "total": 0})
73 + bucket["total"] += 1
74 + bucket["matched"] += int(d.match)
75 + return out
76 +
77 +
78 +def _latest_statement(session: Session, year_id: int, code: str) -> FinancialStatement | None:
79 + version = session.scalar(
80 + select(func.max(FinancialStatement.version)).where(
81 + FinancialStatement.year_id == year_id, 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 _account_deltas(
96 + session: Session, year_id: int, note: NoteDefinition, statement: str
97 +) -> tuple[AccountDelta, ...]:
98 + """Per-account signed contributions, using the engine's own display rule."""
99 + config = note.configuration_json or {}
100 + sign = Decimal(SECTION_POLICY.get(statement, {}).get(str(config.get("section") or ""), 1))
101 + version = session.scalar(
102 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
103 + )
104 + if version is None:
105 + return ()
106 + codes = sorted(
107 + {
108 + r.account_code
109 + for r in session.scalars(
110 + select(MappingRule).where(
111 + MappingRule.year_id == year_id, MappingRule.target_note_id == note.id
112 + )
113 + ).all()
114 + }
115 + )
116 + if not codes:
117 + return ()
118 + totals: dict[str, dict[str, Any]] = {}
119 + for balance in session.scalars(
120 + select(LedgerBalance).where(
121 + LedgerBalance.year_id == year_id,
122 + LedgerBalance.import_version == version,
123 + LedgerBalance.account_full_code.in_(codes),
124 + )
125 + ).all():
126 + figure = (
127 + balance.statement_balance if balance.statement_balance is not None else balance.closing
128 + )
129 + bucket = totals.setdefault(
130 + balance.account_full_code,
131 + {"rial": _ZERO, "rows": 0, "name": balance.account_name},
132 + )
133 + bucket["rial"] += figure * sign
134 + bucket["rows"] += 1
135 + return tuple(
136 + AccountDelta(
137 + account_code=code,
138 + account_name=b["name"],
139 + rial=b["rial"],
140 + million_rounded=int(round_half_up(b["rial"] / _MILLION, 0)),
141 + source_rows=b["rows"],
142 + )
143 + for code, b in sorted(totals.items())
144 + )
145 +
146 +
147 +def compare_built_statements(
148 + session: Session, year_id: int, official_path: str | Path | bytes, year: int
149 +) -> ComparisonReport:
150 + """Compare the persisted statement lines against the official workbook."""
151 + official = parse_official(official_path, year)
152 + by_key: dict[tuple[str, str], OfficialFigure] = {}
153 + for figure in official:
154 + if figure.kind == "equity_component":
155 + continue # equity is a matrix; compared by component, not by note
156 + by_key[(figure.statement, figure.key)] = figure
157 +
158 + notes = {
159 + n.id: n
160 + for n in session.scalars(
161 + select(NoteDefinition).where(NoteDefinition.year_id == year_id)
162 + ).all()
163 + }
164 + built: dict[tuple[str, str], int] = {}
165 + built_notes: dict[tuple[str, str], NoteDefinition] = {}
166 + for code in SECTION_POLICY:
167 + built_statement = _latest_statement(session, year_id, code)
168 + if built_statement is None:
169 + continue
170 + for line in session.scalars(
171 + select(StatementLine).where(StatementLine.statement_id == built_statement.id)
172 + ).all():
173 + note = notes.get(line.target_note_id) if line.target_note_id else None
174 + if note is None:
175 + continue
176 + key = (code, note.note_number)
177 + million = int(round_half_up((line.mapped_total or _ZERO) / _MILLION, 0))
178 + built[key] = built.get(key, 0) + million
179 + built_notes[key] = note
180 +
181 + deltas: list[NoteDelta] = []
182 + for key in sorted(set(built) | set(by_key)):
183 + statement, note_number = key
184 + ours = built.get(key)
185 + official_figure = by_key.get(key)
186 + theirs = int(official_figure.amount) if official_figure is not None else None
187 + cell = (
188 + f"{official_figure.sheet}!R{official_figure.row}C{official_figure.column + 1}"
189 + if official_figure
190 + else ""
191 + )
192 + if ours is None:
193 + status, match, delta = "missing_in_build", False, None
194 + elif theirs is None:
195 + status, match, delta = "missing_in_official", False, None
196 + else:
197 + delta = ours - theirs
198 + match = delta == 0
199 + status = "matched" if match else "mismatched"
200 + accounts: tuple[AccountDelta, ...] = ()
201 + if not match and key in built_notes:
202 + accounts = _account_deltas(session, year_id, built_notes[key], statement)
203 + deltas.append(
204 + NoteDelta(
205 + statement=statement,
206 + note=note_number,
207 + built_million=ours,
208 + official_million=theirs,
209 + delta=delta,
210 + match=match,
211 + status=status,
212 + official_cell=cell,
213 + accounts=accounts,
214 + )
215 + )
216 + return ComparisonReport(year=year, deltas=tuple(deltas))
217 +
218 +
219 +__all__ = [
220 + "AccountDelta",
221 + "ComparisonReport",
222 + "NoteDelta",
223 + "compare_built_statements",
224 + "official_comparisons",
225 +]
226 +
227 +
228 +def official_comparisons(report: ComparisonReport) -> tuple[OfficialComparison, ...]:
229 + """Feed C-13 from a built-vs-official report (R3).
230 +
231 + Only keys present on both sides are comparable; a note missing from either
232 + side is a build/coverage gap, reported by the report itself, not a figure
233 + difference. Amounts are million rial, as the official workbook presents.
234 + """
235 + return tuple(
236 + OfficialComparison(
237 + key=f"{d.statement}:{d.note}",
238 + ours=Decimal(d.built_million),
239 + official=Decimal(d.official_million),
240 + )
241 + for d in report.deltas
242 + if d.built_million is not None and d.official_million is not None
243 + )
backend/src/aram_backend/statement_api.py
+42
@@ -53,6 +53,7 @@ from aram_backend.services.statement_build import (
53 build_statements,
54 drill_down,
55 )
56 +from aram_backend.services.statement_compare import compare_built_statements
57 from aram_backend.services.statement_export import (
58 StatementExportError,
59 export_statements_json_bytes,
@@ -390,6 +391,47 @@ def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
391
392
393 # ----------------------------------------------------------- Phase 2: mapping I/O
394 +@router.post("/years/{year_id}/official-comparison")
395 +def official_comparison(
396 + year_id: int,
397 + file: UploadFile = File(...),
398 + session: Session = Depends(get_session),
399 +) -> dict:
400 + """Compare the **built** statements with an uploaded official workbook (R3).
401 +
402 + The workbook is parsed in memory; nothing is written to the source store and
403 + no stored figure is changed. The result also feeds control C-13.
404 + """
405 + year = _year_or_404(session, year_id)
406 + report = compare_built_statements(session, year_id, file.file.read(), year.year)
407 + return {
408 + "year": year.year,
409 + "counts": report.counts(),
410 + "deltas": [
411 + {
412 + "statement": d.statement,
413 + "note": d.note,
414 + "built_million": d.built_million,
415 + "official_million": d.official_million,
416 + "delta": d.delta,
417 + "match": d.match,
418 + "status": d.status,
419 + "official_cell": d.official_cell,
420 + "accounts": [
421 + {
422 + "account_code": a.account_code,
423 + "account_name": a.account_name,
424 + "million_rounded": a.million_rounded,
425 + "source_rows": a.source_rows,
426 + }
427 + for a in d.accounts
428 + ],
429 + }
430 + for d in report.deltas
431 + ],
432 + }
433 +
434 +
435 @router.get("/years/{year_id}/mappings/export")
436 def export_mappings(year_id: int, session: Session = Depends(get_session)) -> StreamingResponse:
437 _year_or_404(session, year_id)
backend/tests/test_controls_r2.py
+8 -6
@@ -351,15 +351,17 @@ class TestCompleteYearThroughApi:
351 class TestReclassifiedRowsAgreeWithTheEngine:
352 """C-06/C-07 must use the same figure `build_statements` uses.
353
354 - A reclassified source row carries only `statement_balance` (already
355 - presentation-signed) and leaves CLOSING empty. Using raw closing in the
356 - control context would compare two different rules and invent a difference.
354 + A reclassified source row carries `statement_balance` instead of CLOSING.
355 + Both engines must prefer it and apply the section sign exactly once,
356 + otherwise the control compares two different rules and invents a difference.
357 """
358
359 - def test_display_prefers_the_pre_signed_statement_balance(self):
360 - row = BalanceRow(1, "148348", D(0), D(0), D(0), D(0), statement_balance=D(-250))
359 + def test_display_prefers_the_reclassified_figure_then_signs_it(self):
360 + # ADR-032: statement_balance is debit-positive like CLOSING, so the
361 + # section sign applies to it too (measured: BS 16/16 vs official 1404).
362 + row = BalanceRow(1, "241001", D(0), D(0), D(0), D(0), statement_balance=D(-250))
363 assert row.display(D(1)) == D(-250)
362 - assert row.display(D(-1)) == D(-250)
364 + assert row.display(D(-1)) == D(250)
365
366 def test_display_signs_ordinary_closing(self):
367 row = BalanceRow(1, "241001", D(0), D(0), D(60), D(-60))
backend/tests/test_statement_build.py
+2 -1
@@ -129,7 +129,8 @@ class TestStatementBuild:
129 )
130 is_totals = {ln.line_label.split(" — ")[0]: ln.mapped_total for ln in is_stmt.lines}
131 assert is_totals["20"] == Decimal(250) # revenue -1 x -250
132 - assert is_totals["22"] == Decimal(200) # expense +1
132 + # ADR-032: the official IS presents expenses negative, so -1 x 200.
133 + assert is_totals["22"] == Decimal(-200)
134
135 def test_drilldown_to_source_row(self, session):
136 year, n_cash = _seed_full(session)
backend/tests/test_statement_compare_r3.py new
+223
@@ -0,0 +1,223 @@
1 +"""R3: official-statement parsing and built-vs-official comparison.
2 +
3 +Covers the four different official layouts, the (statement, note) key, the
4 +display-sign policy, the per-row note assignment, and the C-13 feed.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +from decimal import Decimal
10 +from io import BytesIO
11 +
12 +from openpyxl import Workbook
13 +from sqlalchemy import select
14 +
15 +from aram_backend.domain.controls import check_c13
16 +from aram_backend.models import LedgerBalance, StatementLine
17 +from aram_backend.services.official_parse import (
18 + parse_equity_matrix,
19 + parse_note_statement,
20 + parse_official,
21 +)
22 +from aram_backend.services.statement_build import build_statements
23 +from aram_backend.services.statement_compare import (
24 + compare_built_statements,
25 + official_comparisons,
26 +)
27 +from test_statement_build import _map, _note, _setup
28 +
29 +D = Decimal
30 +
31 +
32 +def _official_bytes():
33 + """A miniature official workbook with the real layouts (BS/IS/EQ/CF)."""
34 + wb = Workbook()
35 + bs = wb.active
36 + bs.title = "وضعيت مالي"
37 + bs.append(["شرکت نمونه"])
38 + bs.append(["به تاریخ 29 اسفند 1404"]) # title also contains the year
39 + bs.append([None, None, "يادداشت", None, None, "سال 1404"])
40 + bs.append([None, "دارایی", "6", "6", None, 100])
41 + bs.append([None, "بدهی", "10", "10", None, 60])
42 +
43 + isx = wb.create_sheet("سودوزيان")
44 + isx.append(["صورت سود و زیان"])
45 + isx.append([None, None, None, "يادداشت", None, "سال 1404"])
46 + isx.append([None, "درآمد", "5", "5", None, 250])
47 + isx.append([None, "هزینه", "7", "7", None, -200])
48 +
49 + eq = wb.create_sheet("حقوق مالكانه")
50 + eq.append(["صورت تغییرات حقوق مالکانه"])
51 + eq.append([None, None, "یادداشت", "سرمایه", None, "اندوخته", None, "جمع کل"])
52 + eq.append(["مانده تجدید ارایه شده در 1404/01/01", None, None, 40, None, 10, None, 50])
53 + eq.append(["مانده در 1404/12/29", None, None, 40, None, 15, None, 55])
54 +
55 + cf = wb.create_sheet("جريان هاي نقدي")
56 + cf.append(["صورت جریان‌های نقدی"])
57 + cf.append([None, None, "يادداشت", None, "سال 1404"])
58 + cf.append([None, "نقد حاصل از عملیات", "23", None, 30])
59 + cf.append([None, "تسعیر ارز", "46268", None, 12])
60 + buf = BytesIO()
61 + wb.save(buf)
62 + return buf.getvalue()
63 +
64 +
65 +class TestOfficialParsing:
66 + def test_year_column_is_not_the_title_row(self, tmp_path):
67 + path = tmp_path / "official.xlsx"
68 + path.write_bytes(_official_bytes())
69 + figures = parse_note_statement(path, "BS", 1404)
70 + assert {f.key: f.amount for f in figures} == {"6": D(100), "10": D(60)}
71 +
72 + def test_income_statement_notes_and_signs(self, tmp_path):
73 + path = tmp_path / "official.xlsx"
74 + path.write_bytes(_official_bytes())
75 + figures = {f.key: f.amount for f in parse_note_statement(path, "IS", 1404)}
76 + assert figures == {"5": D(250), "7": D(-200)}
77 +
78 + def test_equity_matrix_yields_opening_changes_closing(self, tmp_path):
79 + path = tmp_path / "official.xlsx"
80 + path.write_bytes(_official_bytes())
81 + figures = {f.key: f.amount for f in parse_equity_matrix(path, 1404)}
82 + assert figures["سرمایه:opening"] == D(40)
83 + assert figures["سرمایه:closing"] == D(40)
84 + assert figures["اندوخته:changes"] == D(5)
85 + assert figures["جمع کل:closing"] == D(55)
86 +
87 + def test_cf_account_code_is_not_treated_as_a_note(self, tmp_path):
88 + path = tmp_path / "official.xlsx"
89 + path.write_bytes(_official_bytes())
90 + figures = {f.key: f for f in parse_note_statement(path, "CF", 1404)}
91 + assert figures["23"].kind == "note"
92 + assert figures["46268"].kind == "account_code"
93 +
94 + def test_all_four_statements_parse_from_bytes(self):
95 + figures = parse_official(_official_bytes(), 1404)
96 + assert {f.statement for f in figures} == {"BS", "IS", "EQ", "CF"}
97 +
98 + def test_missing_sheet_yields_nothing(self, tmp_path):
99 + wb = Workbook()
100 + wb.active.title = "unrelated"
101 + path = tmp_path / "empty.xlsx"
102 + wb.save(path)
103 + assert parse_note_statement(path, "BS", 1404) == []
104 + assert parse_equity_matrix(path, 1404) == []
105 +
106 +
107 +class TestBuiltComparison:
108 + def _seed(self, session):
109 + year, source = _setup(session)
110 + from test_approval_gate import _carry
111 +
112 + _carry(session, year, source, "148348", D(0), D(100_000_000), 3)
113 + _carry(session, year, source, "241001", D(0), D(-60_000_000), 4)
114 + n_a = _note(session, year, "6", "نقد", "BS", "Assets")
115 + n_l = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
116 + _map(session, year, "148348", n_a)
117 + _map(session, year, "241001", n_l)
118 + session.flush()
119 + build_statements(session, year.id)
120 + session.flush()
121 + return year
122 +
123 + def test_matching_built_lines_report_no_delta(self, session):
124 + year = self._seed(session)
125 + report = compare_built_statements(session, year.id, _official_bytes(), 1404)
126 + bs = {d.note: d for d in report.deltas if d.statement == "BS"}
127 + assert bs["6"].match and bs["6"].built_million == 100
128 + assert bs["10"].match and bs["10"].built_million == 60
129 + assert report.counts()["BS"] == {"matched": 2, "total": 2}
130 +
131 + def test_note_keys_are_scoped_by_statement(self, session):
132 + year = self._seed(session)
133 + report = compare_built_statements(session, year.id, _official_bytes(), 1404)
134 + keys = {(d.statement, d.note) for d in report.deltas}
135 + assert ("BS", "6") in keys and ("IS", "5") in keys
136 + # IS 5 has no built line: the gap is reported, never silently dropped.
137 + is5 = next(d for d in report.deltas if (d.statement, d.note) == ("IS", "5"))
138 + assert is5.status == "missing_in_build" and not is5.match
139 +
140 + def test_mismatch_carries_account_level_deltas(self, session):
141 + year = self._seed(session)
142 + row = session.scalar(
143 + select(LedgerBalance).where(
144 + LedgerBalance.year_id == year.id, LedgerBalance.account_full_code == "148348"
145 + )
146 + )
147 + row.closing = D(90_000_000)
148 + session.flush()
149 + build_statements(session, year.id)
150 + session.flush()
151 + report = compare_built_statements(session, year.id, _official_bytes(), 1404)
152 + bs6 = next(d for d in report.deltas if (d.statement, d.note) == ("BS", "6"))
153 + assert not bs6.match and bs6.delta == -10
154 + assert bs6.accounts and bs6.accounts[0].account_code == "148348"
155 + assert bs6.accounts[0].million_rounded == 90
156 + assert bs6.official_cell # provenance to the exact official cell
157 +
158 + def test_c13_feed_from_the_report(self, session):
159 + year = self._seed(session)
160 + report = compare_built_statements(session, year.id, _official_bytes(), 1404)
161 + feed = official_comparisons(report)
162 + assert feed and all(c.ours == c.official for c in feed)
163 + assert check_c13(feed, "ci").passed
164 +
165 +
166 +class TestStatementBasisAndRowNotes:
167 + def test_statement_balance_basis_excludes_rows_without_one(self, session):
168 + year, source = _setup(session)
169 + from test_approval_gate import _carry
170 +
171 + _carry(session, year, source, "148348", D(0), D(500), 3)
172 + _carry(session, year, source, "241001", D(0), D(0), 4)
173 + rows = session.scalars(select(LedgerBalance).where(LedgerBalance.year_id == year.id)).all()
174 + for r in rows:
175 + if r.account_full_code == "241001":
176 + r.statement_balance = D(100) # only this row feeds the statement
177 + n = _note(session, year, "6", "نقد", "BS", "Assets")
178 + _map(session, year, "148348", n)
179 + _map(session, year, "241001", n)
180 + session.flush()
181 + build_statements(session, year.id)
182 + session.flush()
183 + line = session.scalar(select(StatementLine).where(StatementLine.target_note_id == n.id))
184 + # The 500 closing must NOT leak in: the import supplies statement balances.
185 + assert line.mapped_total == D(100)
186 +
187 + def test_source_note_disambiguates_a_multi_note_account(self, session):
188 + year, source = _setup(session)
189 + from test_approval_gate import _carry
190 +
191 + _carry(session, year, source, "148348", D(0), D(100), 3)
192 + _carry(session, year, source, "148348", D(0), D(40), 4)
193 + rows = session.scalars(
194 + select(LedgerBalance).where(LedgerBalance.year_id == year.id)
195 + ).all()
196 + rows[0].source_note, rows[1].source_note = "6", "7"
197 + n6 = _note(session, year, "6", "نقد", "BS", "Assets")
198 + n7 = _note(session, year, "7", "سایر", "BS", "Assets")
199 + _map(session, year, "148348", n6)
200 + _map(session, year, "148348", n7)
201 + session.flush()
202 + build_statements(session, year.id)
203 + session.flush()
204 + totals = {
205 + ln.target_note_id: ln.mapped_total
206 + for ln in session.scalars(select(StatementLine)).all()
207 + }
208 + assert totals[n6.id] == D(100) and totals[n7.id] == D(40)
209 +
210 + def test_single_explicit_mapping_overrides_the_source_note(self, session):
211 + year, source = _setup(session)
212 + from test_approval_gate import _carry
213 +
214 + _carry(session, year, source, "148348", D(0), D(100), 3)
215 + row = session.scalar(select(LedgerBalance).where(LedgerBalance.year_id == year.id))
216 + row.source_note = "6"
217 + n7 = _note(session, year, "7", "بازطبقه‌بندی", "BS", "Assets")
218 + _map(session, year, "148348", n7)
219 + session.flush()
220 + build_statements(session, year.id)
221 + session.flush()
222 + line = session.scalar(select(StatementLine).where(StatementLine.target_note_id == n7.id))
223 + assert line.mapped_total == D(100)
backend/tests/test_tolerant_import.py
+4 -3
@@ -134,9 +134,10 @@ def test_statement_balance_drives_build_and_drilldown(session):
134
135 result = build_statements(session, year_id, statement_types=("BS",))
136 line = result.statements[0].lines[0]
137 - # Reclassified row contributes its signed statement balance directly;
138 - # the ordinary closing row contributes sign(Assets=+1) * closing.
139 - assert line.mapped_total == Decimal("-673740637000000") + Decimal("1000000")
137 + # ADR-032: the import supplies statement balances, so that column is the
138 + # statement basis and the ordinary CLOSING row contributes nothing (the old
139 + # fallback leaked non-statement rows into the official comparison).
140 + assert line.mapped_total == Decimal("-673740637000000")
141
142 rows = session.query(LedgerBalance).filter_by(year_id=year_id).all()
143 assert len(rows) == 2 # raw rows preserved, not aggregated
docs/PROJECT_LOG.md
+11
@@ -441,3 +441,14 @@ Each new entry must record: UTC timestamp, actor, task/phase, base branch and SH
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).
444 +
445 +### 2026-12-04T11:30:00Z — R3 built-vs-official comparison (booklet 2.1)
446 +
447 +- Actor: Arena agent (implementation and merge). Precondition: PR #100 (R2) squash-merged → accepted head **a8ba20c1bc5595ceaa73ff30be8dd91748a87a6e**; working branch aligned before starting.
448 +- New `services/official_parse.py`: each official statement gets the parser its layout needs. BS/IS/CF are note lists; **EQ is a components × movements matrix** (opening/changes/closing/prior-closing) — it went from **0 parsed figures to 24**. The year column is anchored on the header row, because the title «به تاریخ 29 اسفند 1404» also contains the year and previously won the search (pointing at column 0). CF's **46268 is flagged `account_code`**, not a note.
449 +- New `services/statement_compare.py`: compares the **persisted `StatementLine` rows** that `build_statements` wrote — not a separate source aggregation — keyed by **(statement, note)**, with per-account deltas and the exact official cell for every difference. `official_comparisons()` feeds C-13; `POST /years/{id}/official-comparison` parses an uploaded workbook in memory and changes no stored figure.
450 +- **Three real engine defects found by measuring** (ADR-032): (1) `statement_balance` is debit-positive, not pre-signed — applying the section sign reproduces the official BS **16/16** instead of flipping 7 notes; (2) the per-row CLOSING fallback leaked non-statement rows into totals (BS was 6/16 through the engine) — the basis now belongs to the import; (3) the source assigns notes **per row** (account 718291 posts to notes 6 and 9), so `LedgerBalance.source_note` was added (migration `20261204_09`) with the rule "explicit mapping wins; source note disambiguates multi-note accounts". IS expenses are presented negative, so Revenue and Expenses both take −1 and the net result is the sum of signed IS lines (C-08 input corrected).
451 +- **Measured on real 1404 (131,280 rows): BS 16/16 matched.** IS **1/6 exact**: note 5 matches; notes 6/7 differ by −2/+1 million rial (the official sums per-category rounded values); notes 8/9 differ by a **1,111,554** reclassification (their combined total −9,057,668 matches exactly, and the official's own adjustment column records ±1,111,554); note **20-3 has no source rows at all**. CF 0/6 (still not rendered).
452 +- **Acceptance: R3 PARTIAL — BS 16/16 MET, IS 6/6 NOT MET.** The IS blocker is source data, not code: no tolerance was invented and no figure was adjusted to force a match. Root causes for IS 6/7/8/9/20-3 are established with account-by-account evidence.
453 +- `docs/discrepancies.json` regenerated (schema v2) from the built output: 11 entries, each with cause, official cell and account deltas; source/official SHA-256 recorded.
454 +- Protected data: `data/` and `samples/` trees unchanged. Tag `v1.0.0` untouched.
docs/adr/ADR-032-r3-built-vs-official.md new
+78
@@ -0,0 +1,78 @@
1 +# ADR-032 — R3: compare the engine's own output, and what the 1404 data actually says
2 +
3 +- Status: accepted
4 +- Date: 2026-12-04
5 +- Scope: booklet 2.1 task R3
6 +- Supersedes: the "statement_balance is pre-signed" assumption in ADR-013/018 and
7 + ADR-031 §5. Everything else in those ADRs stands.
8 +
9 +## Context
10 +
11 +The golden comparison aggregated the **source workbook** separately, so it could
12 +agree with the official figures while `build_statements` produced something else.
13 +R3 requires comparing the engine's own persisted output. Doing that exposed three
14 +real defects and one source-data limitation.
15 +
16 +## Decision 1 — `statement_balance` is debit-positive, not pre-signed
17 +
18 +Measured: applying the section display sign to `statement_balance` reproduces the
19 +official 1404 balance sheet **16/16**; treating it as pre-signed flipped 7 notes.
20 +The sign is now applied exactly once, to whichever figure the row provides.
21 +`BalanceRow.display(sign, basis)` and `build_statements` share the rule.
22 +
23 +## Decision 2 — the statement basis belongs to the import, not the row
24 +
25 +If a source supplies statement balances at all, that column is the statement
26 +figure and a row without one contributes **nothing**. The old per-row fallback to
27 +CLOSING leaked non-statement rows into the totals (BS fell to 6/16). Sources
28 +without the column keep using CLOSING, so nothing else changes.
29 +
30 +## Decision 3 — the source assigns notes per row
31 +
32 +Account 718291 posts to both note 6 and note 9. An account-level mapping cannot
33 +express that, so `LedgerBalance.source_note` preserves the row's own assignment
34 +(migration `20261204_09`). Precedence: an explicit mapping wins; the source note
35 +only disambiguates an account mapped to **several** notes. That keeps the mapping
36 +workflow authoritative while preventing double-counting.
37 +
38 +## Decision 4 — the income statement presents expenses negative
39 +
40 +Official 1404 notes 6/7/20-3 are negative while the ledger is debit-positive, so
41 +IS Revenue and Expenses both take −1. The net result is therefore the **sum** of
42 +the signed IS lines, not revenue minus expenses; C-08's input was corrected.
43 +
44 +## Decision 5 — each official statement gets the parser its layout needs
45 +
46 +`official_parse.py` reads BS/IS/CF as note lists and EQ as a components ×
47 +movements matrix (opening / changes / closing / prior closing). The year column is
48 +located from the **header row**, because the title «به تاریخ 29 اسفند 1404» also
49 +contains the year and previously won the search, pointing at column 0. CF's
50 +`46268` is flagged `account_code`, not a note. EQ went from 0 parsed figures to 24.
51 +
52 +## Measured outcome (real 1404, 131,280 rows)
53 +
54 +| Statement | Result |
55 +| --- | --- |
56 +| BS | **16/16 matched** — acceptance met |
57 +| IS | 1/6 exact (note 5); 6 and 7 within 1–2 million rial; 8/9 differ by a 1,111,554 reclassification; 20-3 absent from the source |
58 +| CF | 0/6 — CF is still not rendered (`RENDERED_STATEMENTS = BS, IS`) |
59 +| EQ | 24 official figures parsed; no built EQ statement yet |
60 +
61 +**IS 6/6 is not met and cannot be met from this source.** Note 20-3 (tax expense
62 +−4,697,329) has no corresponding row in `source_1404.xlsx` at all. Notes 8 and 9
63 +together match exactly (−9,057,668); only their split differs, and the official's
64 +own adjustment column records exactly ±1,111,554. Notes 6/7 differ by 1–2 million
65 +rial because the official sums per-category rounded values.
66 +
67 +Per booklet 2.1, this is reported as **not met**, not softened into a pass. No
68 +tolerance was invented and no figure was adjusted to force a match.
69 +
70 +## Consequences
71 +
72 +- `docs/discrepancies.json` is regenerated from the built output, with a cause and
73 + the exact official cell for every difference, plus account-level deltas.
74 +- C-13 can now be fed by `official_comparisons(report)`;
75 + `POST /years/{id}/official-comparison` accepts an official workbook, parses it in
76 + memory and changes no stored figure.
77 +- Remaining R3 work (IS 8/9 reclassification decision, CF/EQ rendering) is carried
78 + forward explicitly rather than claimed.
docs/discrepancies.json
+214 -282
@@ -1,323 +1,255 @@
1 {
2 - "purpose": "OD-08 / D1 / الف‌7: one-by-one record of every golden-test difference (source-aggregated-by-note vs official statement) with cause and evidence. An uncaused difference is a bug until proven otherwise. Numbers are never 'corrected' here — only an Adjustment (C4) or a discrepancy record is permitted (booklet §6.7/§12.60, D1/D2).",
3 - "status": "POPULATED for 1404 golden (source-vs-official, ADR-021). 28 comparisons, 9 matched, 19 recorded. Resolution of causes tracked in C1/C3; build-vs-official comparison added when the engine builds all four statements (C3).",
4 - "scale_note": "Official statements are in million rial; source is exact rial. Comparison rounds source rial to million (half-up, ADR-012/021). our_amount/official_amount are exact rial strings; *_million fields are the comparison basis.",
5 - "record_schema": {
6 - "row": "statement + note identifier",
7 - "statement": "BS/IS/EQ/CF",
8 - "note": "note number as in official sheet",
9 - "our_amount": "source-aggregated exact rial (string)",
10 - "official_amount": "official million rial x 1e6 (string)",
11 - "our_million_rounded": "source rial rounded to million (half-up)",
12 - "official_million": "official million rial",
13 - "delta_million": "our_million_rounded - official_million",
14 - "cause": "root-cause explanation (Persian)",
15 - "cause_status": "caused | under_investigation (under_investigation = bug until proven, D1)",
16 - "evidence": "reproducible proof pointer",
17 - "year": "Jalali fiscal year"
18 - },
19 - "summary": {
20 - "total_comparisons": 28,
21 - "matched": 9,
22 - "recorded": 19,
23 - "by_statement": {
24 - "BS": {
25 - "total": 16,
26 - "matched": 9,
27 - "recorded": 7
28 - },
29 - "IS": {
30 - "total": 6,
31 - "matched": 0,
32 - "recorded": 6
33 - },
34 - "EQ": {
35 - "total": 0,
36 - "matched": 0,
37 - "recorded": 0
38 - },
39 - "CF": {
40 - "total": 6,
41 - "matched": 0,
42 - "recorded": 6
43 - }
44 - },
45 - "by_cause_status": {
46 - "caused": 16,
47 - "under_investigation": 3
2 + "schema": "aram.discrepancies/v2",
3 + "generated_at": "2026-12-04T11:26:02Z",
4 + "basis": "build_statements output (persisted StatementLine rows) vs official workbook — NOT a separate source aggregation (R3).",
5 + "year": 1404,
6 + "source_file": "data/source_ledgers/source_1404.xlsx",
7 + "source_sha256": "5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044",
8 + "official_file": "data/official_statements/financial_1404.xlsx",
9 + "official_sha256": "f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3",
10 + "unit": "million rial (official presentation); source is exact rial, half-up rounded once (ADR-012)",
11 + "counts": {
12 + "BS": {
13 + "matched": 16,
14 + "total": 16
15 + },
16 + "IS": {
17 + "matched": 1,
18 + "total": 6
19 + },
20 + "CF": {
21 + "matched": 0,
22 + "total": 6
23 }
24 },
50 - "coverage_notes": [
51 - "EQ: read_official_notes extracted 0 note rows from the official «حقوق مالكانه» sheet for 1404 (layout differs); EQ official parsing is a C3 coverage gap, not a zero discrepancy.",
52 - "This golden test is source-aggregated-vs-official (ADR-021). A build-vs-official comparison (engine output vs official) is added in C3 once BS/IS/EQ/CF are all built.",
53 - "Approval of the real 1404 year is currently BLOCKED by controls C-01/C-03/C-04 (UAT). Separately, ADR-013 records 6 residual C-01 rows in the 252,898-row source (252,892 satisfy debit-positive); these are source-data quirks to reconcile, not statement discrepancies, and are tracked under C-01/ADR-013."
54 - ],
55 - "records": [
56 - {
57 - "row": "BS note 16",
58 - "statement": "BS",
59 - "note": "16",
60 - "our_amount": "-20000000000000",
61 - "official_amount": "20000000000000",
62 - "our_million_rounded": -20000000,
63 - "official_million": 20000000,
64 - "delta_million": -40000000,
65 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
66 - "cause_status": "caused",
67 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 16 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
68 - "year": 1404
69 - },
25 + "acceptance": {
26 + "BS_16_of_16": true,
27 + "IS_6_of_6": false,
28 + "IS_blocker": "note 20-3 has no source rows at all; notes 8/9 need an explicit reclassification decision; notes 6/7 differ by 1-2 million rial of official presentation rounding"
29 + },
30 + "equity": {
31 + "official_figures_parsed": 24,
32 + "note": "EQ is a components x movements matrix, now parsed (was 0 under the old note-list parser). No built EQ statement yet."
33 + },
34 + "discrepancies": [
35 {
71 - "row": "BS note 18",
72 - "statement": "BS",
73 - "note": "18",
74 - "our_amount": "-1613615852",
75 - "official_amount": "1614000000",
76 - "our_million_rounded": -1614,
77 - "official_million": 1614,
78 - "delta_million": -3228,
79 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
80 - "cause_status": "caused",
81 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 18 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
82 - "year": 1404
36 + "statement": "CF",
37 + "note": "10",
38 + "built_million": null,
39 + "official_million": 0,
40 + "delta_million": null,
41 + "status": "missing_in_build",
42 + "cause": "not_derived",
43 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
44 + "official_cell": "جريان هاي نقدي!R12C5",
45 + "accounts": [],
46 + "accounts_total": 0
47 },
48 {
85 - "row": "BS note 19-1",
86 - "statement": "BS",
87 - "note": "19-1",
88 - "our_amount": "-145241976038754",
89 - "official_amount": "145241976000000",
90 - "our_million_rounded": -145241976,
91 - "official_million": 145241976,
92 - "delta_million": -290483952,
93 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
94 - "cause_status": "caused",
95 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 19-1 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
96 - "year": 1404
49 + "statement": "CF",
50 + "note": "15",
51 + "built_million": null,
52 + "official_million": 3368287,
53 + "delta_million": null,
54 + "status": "missing_in_build",
55 + "cause": "not_derived",
56 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
57 + "official_cell": "جريان هاي نقدي!R21C5",
58 + "accounts": [],
59 + "accounts_total": 0
60 },
61 {
99 - "row": "BS note 19-2",
100 - "statement": "BS",
101 - "note": "19-2",
102 - "our_amount": "-630414220070002",
103 - "official_amount": "630414220000000",
104 - "our_million_rounded": -630414220,
105 - "official_million": 630414220,
106 - "delta_million": -1260828440,
107 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
108 - "cause_status": "caused",
109 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 19-2 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
110 - "year": 1404
62 + "statement": "CF",
63 + "note": "20-1",
64 + "built_million": null,
65 + "official_million": -149426,
66 + "delta_million": null,
67 + "status": "missing_in_build",
68 + "cause": "not_derived",
69 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
70 + "official_cell": "جريان هاي نقدي!R8C5",
71 + "accounts": [],
72 + "accounts_total": 0
73 },
74 {
113 - "row": "BS note 20",
114 - "statement": "BS",
115 - "note": "20",
116 - "our_amount": "-133078120519345",
117 - "official_amount": "133078121000000",
118 - "our_million_rounded": -133078121,
119 - "official_million": 133078121,
120 - "delta_million": -266156242,
121 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
122 - "cause_status": "caused",
123 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
124 - "year": 1404
75 + "statement": "CF",
76 + "note": "23",
77 + "built_million": null,
78 + "official_million": 99230533,
79 + "delta_million": null,
80 + "status": "missing_in_build",
81 + "cause": "not_derived",
82 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
83 + "official_cell": "جريان هاي نقدي!R7C5",
84 + "accounts": [],
85 + "accounts_total": 0
86 },
87 {
127 - "row": "BS note 21",
128 - "statement": "BS",
129 - "note": "21",
130 - "our_amount": "-8833412166636",
131 - "official_amount": "8833412000000",
132 - "our_million_rounded": -8833412,
133 - "official_million": 8833412,
134 - "delta_million": -17666824,
135 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
136 - "cause_status": "caused",
137 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 21 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
138 - "year": 1404
88 + "statement": "CF",
89 + "note": "24",
90 + "built_million": null,
91 + "official_million": 159859431,
92 + "delta_million": null,
93 + "status": "missing_in_build",
94 + "cause": "not_derived",
95 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
96 + "official_cell": "جريان هاي نقدي!R24C5",
97 + "accounts": [],
98 + "accounts_total": 0
99 },
100 {
141 - "row": "BS note 22",
142 - "statement": "BS",
143 - "note": "22",
144 - "our_amount": "-61449318680",
145 - "official_amount": "61449000000",
146 - "our_million_rounded": -61449,
147 - "official_million": 61449,
148 - "delta_million": -122898,
149 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
150 - "cause_status": "caused",
151 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 22 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «وضعيت مالي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
152 - "year": 1404
101 + "statement": "CF",
102 + "note": "46268",
103 + "built_million": null,
104 + "official_million": 12556,
105 + "delta_million": null,
106 + "status": "missing_in_build",
107 + "cause": "not_derived",
108 + "explanation": "CF is not rendered by build_statements (RENDERED_STATEMENTS = BS, IS). The official CF layout is now parsed, including the bare account code 46268 (FX, 12,556) which is an account, not a note.",
109 + "official_cell": "جريان هاي نقدي!R22C5",
110 + "accounts": [],
111 + "accounts_total": 0
112 },
113 {
155 - "row": "IS note 20-3",
114 "statement": "IS",
115 "note": "20-3",
158 - "our_amount": "0",
159 - "official_amount": "-4697329000000",
160 - "our_million_rounded": 0,
116 + "built_million": null,
117 "official_million": -4697329,
162 - "delta_million": 4697329,
163 - "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
164 - "cause_status": "caused",
165 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20-3 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
166 - "year": 1404
118 + "delta_million": null,
119 + "status": "missing_in_build",
120 + "cause": "absent_from_source",
121 + "explanation": "Official tax expense -4,697,329 (سودوزيان R18C6; sheet '30' R9C5) has NO corresponding row in source_1404.xlsx: no account carries that value and no row is labelled note 20-3. Cannot be produced from this source.",
122 + "official_cell": "سودوزيان!R18C6",
123 + "accounts": [],
124 + "accounts_total": 0
125 },
126 {
169 - "row": "IS note 5",
170 - "statement": "IS",
171 - "note": "5",
172 - "our_amount": "-243097685650599",
173 - "official_amount": "243097686000000",
174 - "our_million_rounded": -243097686,
175 - "official_million": 243097686,
176 - "delta_million": -486195372,
177 - "cause": "قرارداد علامت: یادداشت ماهیت بستانکار (بدهی/حقوق مالکانه) دارد؛ جمع منبع با قرارداد بدهکار-مثبت (ADR-013) منفی است ولی صورت رسمی قدرمطلقِ مثبت نشان می‌دهد. قدرمطلق دقیقاً برابر است (|ما| = رسمی)؛ اختلاف فقط علامتِ ارائه است نه مقدار. اصلاح: سیاست علامتِ ارائه به‌تفکیک بخش صورت در C3.",
178 - "cause_status": "caused",
179 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 5 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
180 - "year": 1404
181 - },
182 - {
183 - "row": "IS note 6",
127 "statement": "IS",
128 "note": "6",
186 - "our_amount": "308711587703360",
187 - "official_amount": "-245897444000000",
188 - "our_million_rounded": 308711588,
129 + "built_million": -245897446,
130 "official_million": -245897444,
190 - "delta_million": 554609032,
191 - "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
192 - "cause_status": "under_investigation",
193 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 6 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
194 - "year": 1404
131 + "delta_million": -2,
132 + "status": "mismatched",
133 + "cause": "presentation_rounding",
134 + "explanation": "Official note 6 (sheet '12' R22C11) sums per-category rounded values; the source aggregated per account differs by 2 million rial. The source note column also lumps kol 71 (cost of revenue) and kol 81 (admin) into note 6 — split by general code as mapping data.",
135 + "official_cell": "سودوزيان!R11C6",
136 + "accounts": [
137 + {
138 + "code": "718269",
139 + "name": "کنترل سربار انتقال محصولات",
140 + "million": -239356527,
141 + "rows": 13
142 + },
143 + {
144 + "code": "718291",
145 + "name": "بهای تمام شده خدمات ارائه شده",
146 + "million": -6568962,
147 + "rows": 29
148 + },
149 + {
150 + "code": "568706",
151 + "name": "کنترل هزینه های تعدیلات سنواتی کارکنان",
152 + "million": 0,
153 + "rows": 11
154 + },
155 + {
156 + "code": "898553",
157 + "name": "کمکهای اعطایی طبق قانون بودجه",
158 + "million": 0,
159 + "rows": 1
160 + }
161 + ],
162 + "accounts_total": 4
163 },
164 {
197 - "row": "IS note 7",
165 "statement": "IS",
166 "note": "7",
200 - "our_amount": "0",
201 - "official_amount": "-62814143000000",
202 - "our_million_rounded": 0,
167 + "built_million": -62814142,
168 "official_million": -62814143,
204 - "delta_million": 62814143,
205 - "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
206 - "cause_status": "caused",
207 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 7 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
208 - "year": 1404
169 + "delta_million": 1,
170 + "status": "mismatched",
171 + "cause": "presentation_rounding",
172 + "explanation": "Official note 7 (sheet '13' R20C14) sums per-line rounded values; residual 1 million rial. Source has no note 7: its rows are labelled note 6 and must be remapped by general code 81.",
173 + "official_cell": "سودوزيان!R13C6",
174 + "accounts": [
175 + {
176 + "code": "818331",
177 + "name": "مدیربرنامه ریزی",
178 + "million": -62814142,
179 + "rows": 37486
180 + }
181 + ],
182 + "accounts_total": 1
183 },
184 {
211 - "row": "IS note 8",
185 "statement": "IS",
186 "note": "8",
214 - "our_amount": "-431960487352",
215 - "official_amount": "1543514000000",
216 - "our_million_rounded": -431960,
187 + "built_million": 431960,
188 "official_million": 1543514,
218 - "delta_million": -1975474,
219 - "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
220 - "cause_status": "under_investigation",
221 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 8 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
222 - "year": 1404
189 + "delta_million": -1111554,
190 + "status": "mismatched",
191 + "cause": "source_note_misassignment",
192 + "explanation": "Official note 8 = 1,543,514 (sheet '13' R36C14: 8-1 1,517,952 + 8-2 25,562). Source assigns only account 698521 (431,960) to note 8; 1,111,554 of other income sits in note 9. The official's own adjustment column (سودوزيان R14C12) records exactly +1,111,554.",
193 + "official_cell": "سودوزيان!R14C6",
194 + "accounts": [
195 + {
196 + "code": "698521",
197 + "name": "درامدهای متفرقه غیرعملیاتی",
198 + "million": 431960,
199 + "rows": 14
200 + }
201 + ],
202 + "accounts_total": 1
203 },
204 {
225 - "row": "IS note 9",
205 "statement": "IS",
206 "note": "9",
228 - "our_amount": "9489628188720",
229 - "official_amount": "-10601182000000",
230 - "our_million_rounded": 9489628,
207 + "built_million": -9489628,
208 "official_million": -10601182,
232 - "delta_million": 20090810,
233 - "cause": "اختلاف مقداری واقعی (قدرمطلق‌ها برابر نیستند)؛ علت دقیق هنوز تعیین نشده — احتمال تفاوت دامنهٔ حساب‌های تجمیع‌شده در یادداشت نسبت به رسمی. طبق D1 تا اثبات خلاف باگ تلقی می‌شود؛ بررسی در C3.",
234 - "cause_status": "under_investigation",
235 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 9 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «سودوزيان». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
236 - "year": 1404
237 - },
238 - {
239 - "row": "CF note 10",
240 - "statement": "CF",
241 - "note": "10",
242 - "our_amount": "673740636579631",
243 - "official_amount": "0",
244 - "our_million_rounded": 673740637,
245 - "official_million": 0,
246 - "delta_million": 673740637,
247 - "cause": "بازاستفادهٔ شمارهٔ یادداشت میان صورت‌ها: تجمیع منبع بر پایهٔ شمارهٔ یادداشت (نه صورت) است، بنابراین مقدار یادداشت BS به مقایسهٔ CF نشت می‌کند حالی ردیف رسمی CF آن شماره ۰/متفاوت است. اصلاح: تجمیع note scoped به صورت در C3/C4.",
248 - "cause_status": "caused",
249 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 10 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
250 - "year": 1404
251 - },
252 - {
253 - "row": "CF note 15",
254 - "statement": "CF",
255 - "note": "15",
256 - "our_amount": "19951136477703",
257 - "official_amount": "3368287000000",
258 - "our_million_rounded": 19951136,
259 - "official_million": 3368287,
260 - "delta_million": 16582849,
261 - "cause": "بازاستفادهٔ شمارهٔ یادداشت میان صورت‌ها: تجمیع منبع بر پایهٔ شمارهٔ یادداشت (نه صورت) است، بنابراین مقدار یادداشت BS به مقایسهٔ CF نشت می‌کند حالی ردیف رسمی CF آن شماره ۰/متفاوت است. اصلاح: تجمیع note scoped به صورت در C3/C4.",
262 - "cause_status": "caused",
263 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 15 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
264 - "year": 1404
265 - },
266 - {
267 - "row": "CF note 20-1",
268 - "statement": "CF",
269 - "note": "20-1",
270 - "our_amount": "0",
271 - "official_amount": "-149426000000",
272 - "our_million_rounded": 0,
273 - "official_million": -149426,
274 - "delta_million": 149426,
275 - "cause": "یادداشت در ستون statement_balance منبع حضور ندارد (src_rial=0)؛ تعریف/نگاشت یادداشت یا استخراج آن هنوز انجام نشده (C2/C3)؛ مقدار رسمی غیرصفر است.",
276 - "cause_status": "caused",
277 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 20-1 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
278 - "year": 1404
279 - },
280 - {
281 - "row": "CF note 23",
282 - "statement": "CF",
283 - "note": "23",
284 - "our_amount": "0",
285 - "official_amount": "99230533000000",
286 - "our_million_rounded": 0,
287 - "official_million": 99230533,
288 - "delta_million": -99230533,
289 - "cause": "صورت جریان نقد هنوز توسط موتور محاسبه نشده (C3)؛ یادداشت CF نیازمند محاسبه از گردش‌ها است نه صرفاً statement_balance منبع؛ مقدار رسمی غیرصفر ولی منبع ۰.",
290 - "cause_status": "caused",
291 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 23 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
292 - "year": 1404
293 - },
294 - {
295 - "row": "CF note 24",
296 - "statement": "CF",
297 - "note": "24",
298 - "our_amount": "0",
299 - "official_amount": "159859431000000",
300 - "our_million_rounded": 0,
301 - "official_million": 159859431,
302 - "delta_million": -159859431,
303 - "cause": "صورت جریان نقد هنوز توسط موتور محاسبه نشده (C3)؛ یادداشت CF نیازمند محاسبه از گردش‌ها است نه صرفاً statement_balance منبع؛ مقدار رسمی غیرصفر ولی منبع ۰.",
304 - "cause_status": "caused",
305 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 24 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
306 - "year": 1404
307 - },
308 - {
309 - "row": "CF note 46268",
310 - "statement": "CF",
311 - "note": "46268",
312 - "our_amount": "0",
313 - "official_amount": "12556000000",
314 - "our_million_rounded": 0,
315 - "official_million": 12556,
316 - "delta_million": -12556,
317 - "cause": "ردیف رسمی CF با کلید '46268' ظاهراً کد حساب است نه شمارهٔ یادداشت؛ در تجمیع note منبع حضور ندارد. نیازمند طبقه‌بندی ردیف‌های شیت رسمی در C3.",
318 - "cause_status": "caused",
319 - "evidence": "golden.compare_year (ADR-021): data/source_ledgers/source_1404.xlsx (SHA-256 5b4790dce6e9ea169d61c68751bc6fd5dc390012bc14473b0298ba5aac30d044) note 46268 statement_balance aggregation vs data/official_statements/financial_1404.xlsx (SHA-256 f764e3b6a2b6135997248bfad0b5a60edc9be9ed3dfef8631096c50713552bd3) sheet «جريان هاي نقدي». Reproduce: PYTHONPATH=backend/src python -c \"from aram_backend.services.golden import compare_year; [print(c) for c in compare_year('data/source_ledgers/source_1404.xlsx','data/official_statements/financial_1404.xlsx',1404) if not c.match]\"",
320 - "year": 1404
209 + "delta_million": 1111554,
210 + "status": "mismatched",
211 + "cause": "source_note_misassignment",
212 + "explanation": "Official note 9 = -10,601,182 (sheet '13' R51C14: 9-1 143,087 + 9-2 103,822 + 9-3 12,556 - 9-4 10,860,647). Source note 9 total is -9,489,628; the 1,111,554 difference is the same reclassification as note 8. Notes 8+9 combined match exactly (-9,057,668).",
213 + "official_cell": "سودوزيان!R16C6",
214 + "accounts": [
215 + {
216 + "code": "578490",
217 + "name": "سودوزیان سال جاری",
218 + "million": -10860647,
219 + "rows": 2
220 + },
221 + {
222 + "code": "718291",
223 + "name": "بهای تمام شده خدمات ارائه شده",
224 + "million": -6568962,
225 + "rows": 29
226 + },
227 + {
228 + "code": "618525",
229 + "name": "فروش خدمات",
230 + "million": 1263313,
231 + "rows": 6
232 + },
233 + {
234 + "code": "698773",
235 + "name": "فروش کالا",
236 + "million": 174913,
237 + "rows": 7
238 + },
239 + {
240 + "code": "898774",
241 + "name": "قیمت تمام شده کالای فروش رفته",
242 + "million": -51719,
243 + "rows": 10
244 + },
245 + {
246 + "code": "698259",
247 + "name": "تعدیلات تسعیر نرخ ارز",
248 + "million": 12556,
249 + "rows": 4
250 + }
251 + ],
252 + "accounts_total": 6
253 }
254 ]
323 -}
\ No newline at end of file
255 +}