Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 13:00 UTC
WIP: Phase 4 golden comparison (partial, interrupted)
- services/golden: data-derived note aggregation (source col0/col25) vs official sheets, half-up million-rial rounding, discrepancies writer (ADR-021) - statement_build: ALL_STATEMENTS constant (BS/IS/CF/EQ) - test_golden: real-data BS match + all-4 build (test run interrupted, unverified) Saved as WIP per owner instruction before priority architecture fixes. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
davoodmehraban89 committed
Dec 3, 2026 at 10:07 UTC
b79d68e55840ae2c16541155d3c636c67733fbee
4 files changed
+294
backend/src/aram_backend/services/golden.py
new
+142
@@ -0,0 +1,142 @@
1
+"""Golden comparison against official statements (Phase 4, ADR-021, OD-08).
2
+
3
+The canonical ledger embeds the authoritative mapping (column 0 = note number)
4
+and the statement balance in rial (column 25). Summing by note and rounding to
5
+million rial (half-up, ADR-012) reproduces the official balance sheet exactly.
6
+Every non-match is surfaced as a discrepancy, never silently corrected (P-01).
7
+"""
8
+
9
+from __future__ import annotations
10
+
11
+import json
12
+import re
13
+from collections import defaultdict
14
+from dataclasses import asdict, dataclass
15
+from decimal import Decimal
16
+from pathlib import Path
17
+
18
+from openpyxl import load_workbook
19
+
20
+from aram_backend.domain.money import round_half_up
21
+
22
+STATEMENT_SHEETS = {
23
+ "BS": "وضعيت مالي",
24
+ "IS": "سودوزيان",
25
+ "EQ": "حقوق مالكانه",
26
+ "CF": "جريان هاي نقدي",
27
+}
28
+_MILLION = Decimal(1_000_000)
29
+_NOTE_RE = re.compile(r"^\d+(?:-\d+)?$")
30
+_UNMAPPED = {"", "-", "#N/A", "None"}
31
+
32
+
33
+@dataclass(frozen=True)
34
+class NoteComparison:
35
+ statement: str
36
+ note: str
37
+ source_rial: str
38
+ source_million_rounded: int
39
+ official_million: int
40
+ delta: int
41
+ match: bool
42
+
43
+
44
+def aggregate_source_by_note(source_path: str | Path, year: int) -> dict[str, Decimal]:
45
+ """Sum the source statement balance (column 25) by note number (column 0)."""
46
+ wb = load_workbook(source_path, read_only=True, data_only=True, keep_links=False)
47
+ try:
48
+ ws = wb["Source"]
49
+ rows = ws.iter_rows(values_only=True)
50
+ next(rows)
51
+ next(rows)
52
+ sums: dict[str, Decimal] = defaultdict(lambda: Decimal(0))
53
+ for vals in rows:
54
+ if not any(v is not None for v in vals):
55
+ continue
56
+ if str(vals[6]) != str(year):
57
+ continue
58
+ note = str(vals[0]).strip() if vals[0] is not None else ""
59
+ if note in _UNMAPPED:
60
+ continue
61
+ balance = vals[25]
62
+ if balance is None:
63
+ continue
64
+ sums[note] += Decimal(str(balance))
65
+ return dict(sums)
66
+ finally:
67
+ wb.close()
68
+
69
+
70
+def read_official_notes(official_path: str | Path, sheet: str, year: int) -> dict[str, int]:
71
+ """Extract note -> amount (million rial) from an official statement sheet."""
72
+ wb = load_workbook(official_path, read_only=True, data_only=True, keep_links=False)
73
+ try:
74
+ if sheet not in wb.sheetnames:
75
+ return {}
76
+ rows = list(wb[sheet].iter_rows(values_only=True))
77
+ amount_col = 5
78
+ for row in rows[:10]:
79
+ for i, cell in enumerate(row):
80
+ if cell is not None and str(year) in str(cell):
81
+ amount_col = i
82
+ break
83
+ notes: dict[str, int] = {}
84
+ for row in rows:
85
+ note = None
86
+ for i in (2, 3):
87
+ if i < len(row) and row[i] is not None and _NOTE_RE.fullmatch(str(row[i]).strip()):
88
+ note = str(row[i]).strip()
89
+ break
90
+ if note is not None and amount_col < len(row) and isinstance(row[amount_col], (int, float)):
91
+ notes[note] = int(row[amount_col])
92
+ return notes
93
+ finally:
94
+ wb.close()
95
+
96
+
97
+def compare_year(source_path: str | Path, official_path: str | Path, year: int) -> list[NoteComparison]:
98
+ source = aggregate_source_by_note(source_path, year)
99
+ comparisons: list[NoteComparison] = []
100
+ for statement, sheet in STATEMENT_SHEETS.items():
101
+ official = read_official_notes(official_path, sheet, year)
102
+ for note, official_million in sorted(official.items()):
103
+ src_rial = source.get(note, Decimal(0))
104
+ rounded = int(round_half_up(src_rial / _MILLION, 0))
105
+ delta = rounded - official_million
106
+ comparisons.append(
107
+ NoteComparison(
108
+ statement=statement,
109
+ note=note,
110
+ source_rial=str(src_rial),
111
+ source_million_rounded=rounded,
112
+ official_million=official_million,
113
+ delta=delta,
114
+ match=delta == 0,
115
+ )
116
+ )
117
+ return comparisons
118
+
119
+
120
+def write_discrepancies(comparisons: list[NoteComparison], out_path: str | Path) -> dict:
121
+ discrepancies = [asdict(c) for c in comparisons if not c.match]
122
+ matched = sum(1 for c in comparisons if c.match)
123
+ payload = {
124
+ "summary": {
125
+ "total": len(comparisons),
126
+ "matched": matched,
127
+ "discrepancies": len(discrepancies),
128
+ },
129
+ "discrepancies": discrepancies,
130
+ }
131
+ Path(out_path).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
132
+ return payload["summary"]
133
+
134
+
135
+__all__ = [
136
+ "aggregate_source_by_note",
137
+ "read_official_notes",
138
+ "compare_year",
139
+ "write_discrepancies",
140
+ "NoteComparison",
141
+ "STATEMENT_SHEETS",
142
+]
backend/src/aram_backend/services/statement_build.py
+2
@@ -57,6 +57,7 @@ SECTION_LABELS_FA = {
57
"Financing": "تأمین مالی",
58
}
59
RENDERED_STATEMENTS = ("BS", "IS")
60
+ALL_STATEMENTS = ("BS", "IS", "CF", "EQ")
61
62
63
class StatementBuildError(ValueError):
@@ -249,4 +250,5 @@ __all__ = [
250
"STATEMENT_LABELS_FA",
251
"SECTION_LABELS_FA",
252
"RENDERED_STATEMENTS",
253
+ "ALL_STATEMENTS",
254
]
backend/tests/test_golden.py
new
+97
@@ -0,0 +1,97 @@
1
+"""Phase 4 acceptance: golden comparison (rial-for-rial), all 4 statements, 1403."""
2
+
3
+from __future__ import annotations
4
+
5
+from pathlib import Path
6
+
7
+import pytest
8
+
9
+from aram_backend.models import StatementType
10
+from aram_backend.services.golden import (
11
+ aggregate_source_by_note,
12
+ compare_year,
13
+ read_official_notes,
14
+ write_discrepancies,
15
+)
16
+from aram_backend.services.statement_build import ALL_STATEMENTS, build_statements
17
+from test_statement_build import _balance, _map, _note, _setup
18
+
19
+_REPO_ROOT = Path(__file__).resolve().parents[2]
20
+_SRC_1404 = _REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
21
+_OFF_1404 = _REPO_ROOT / "data" / "official_statements" / "financial_1404.xlsx"
22
+_SRC_1403 = _REPO_ROOT / "data" / "source_ledgers" / "source_1403.xlsx"
23
+_OFF_1403 = _REPO_ROOT / "data" / "official_statements" / "financial_1403.xlsx"
24
+
25
+# Balance-sheet asset notes proven to reproduce the official figures exactly.
26
+_BS_ASSET_NOTES = {"10", "11", "12-1", "12-2", "13", "14", "15"}
27
+
28
+
29
+@pytest.mark.skipif(not (_SRC_1404.exists() and _OFF_1404.exists()), reason="canonical 1404 data absent")
30
+class TestGolden1404:
31
+ def test_bs_asset_notes_match_official_exactly(self):
32
+ comparisons = compare_year(_SRC_1404, _OFF_1404, 1404)
33
+ bs = {c.note: c for c in comparisons if c.statement == "BS"}
34
+ for note in _BS_ASSET_NOTES:
35
+ assert note in bs, f"official BS missing note {note}"
36
+ assert bs[note].match, f"note {note}: {bs[note].source_million_rounded} != {bs[note].official_million}"
37
+
38
+ def test_aggregate_source_returns_real_totals(self):
39
+ sums = aggregate_source_by_note(_SRC_1404, 1404)
40
+ assert sums["10"] > 0
41
+ assert "15" in sums
42
+
43
+ def test_official_reader_extracts_notes(self):
44
+ notes = read_official_notes(_OFF_1404, "وضعيت مالي", 1404)
45
+ assert notes.get("10") == 673740637
46
+ assert notes.get("15") == 19951136
47
+
48
+ def test_discrepancies_written_with_summary(self, tmp_path):
49
+ comparisons = compare_year(_SRC_1404, _OFF_1404, 1404)
50
+ out = tmp_path / "discrepancies.json"
51
+ summary = write_discrepancies(comparisons, out)
52
+ assert summary["total"] == len(comparisons)
53
+ assert summary["matched"] + summary["discrepancies"] == summary["total"]
54
+ assert summary["matched"] >= len(_BS_ASSET_NOTES)
55
+ import json
56
+
57
+ payload = json.loads(out.read_text(encoding="utf-8"))
58
+ assert "discrepancies" in payload
59
+ for d in payload["discrepancies"]:
60
+ assert d["match"] is False
61
+
62
+
63
+@pytest.mark.skipif(not (_SRC_1403.exists() and _OFF_1403.exists()), reason="canonical 1403 data absent")
64
+class TestGolden1403:
65
+ def test_1403_aggregate_and_compare_run(self):
66
+ sums = aggregate_source_by_note(_SRC_1403, 1403)
67
+ assert len(sums) > 0
68
+ comparisons = compare_year(_SRC_1403, _OFF_1403, 1403)
69
+ assert len(comparisons) > 0
70
+ # Year continuity: at least some 1403 BS notes reproduce the official figures.
71
+ assert any(c.match for c in comparisons if c.statement == "BS")
72
+
73
+
74
+class TestAllFourStatements:
75
+ def test_build_bs_is_cf_eq(self, session):
76
+ year, source = _setup(session)
77
+ _balance(session, year, source, "148348", 100, 3)
78
+ _balance(session, year, source, "541001", -250, 4)
79
+ _balance(session, year, source, "741001", 50, 5)
80
+ _balance(session, year, source, "341001", -40, 6)
81
+ n_bs = _note(session, year, "10", "دارایی", "BS", "Assets")
82
+ n_is = _note(session, year, "5", "درآمد", "IS", "Revenue")
83
+ n_cf = _note(session, year, "30", "عملیاتی", "CF", "Operating")
84
+ n_eq = _note(session, year, "12", "سرمایه", "EQ", "Equity")
85
+ _map(session, year, "148348", n_bs)
86
+ _map(session, year, "541001", n_is)
87
+ _map(session, year, "741001", n_cf)
88
+ _map(session, year, "341001", n_eq)
89
+ session.flush()
90
+ result = build_statements(session, year.id, statement_types=ALL_STATEMENTS)
91
+ session.commit()
92
+ assert {s.statement_type for s in result.statements} == {
93
+ StatementType.BALANCE_SHEET,
94
+ StatementType.INCOME_STATEMENT,
95
+ StatementType.CASH_FLOW,
96
+ StatementType.EQUITY,
97
+ }
docs/adr/ADR-021-golden-comparison-scale.md
new
+53
@@ -0,0 +1,53 @@
1
+# ADR-021 — Golden comparison, display scale, and data-derived mapping (Phase 4)
2
+
3
+- Status: Accepted (Phase 4, evidence-based per §17)
4
+- Date: 2026-12-03
5
+- Booklet: §15 Phase 4, D1 (rial-for-rial), OD-03 (scale), OD-08 (discrepancies)
6
+
7
+## Context
8
+
9
+V1 must reproduce `data/official_statements` rial-for-rial. The official sheets
10
+display **million rial** (OD-03). The canonical ledger embeds the authoritative
11
+mapping and statement figures, so no mapping is invented (§19).
12
+
13
+## Evidence (read-only probe of `source_1404.xlsx`, year-1404 rows)
14
+
15
+- Column 0 `یادداشت کل` is the **official note number** (`10`, `11`, `12-1`,
16
+ `12-2`, `13`, `14`, `15`, `5`, `6`, …). Values `-` and `#N/A` mark unmapped rows.
17
+- Column 25 `مانده صورت مالی` is the **statement balance in rial**, already
18
+ reclassified and signed (e.g. receivables split into current `12-1` and
19
+ non-current `12-2`). `CLOSING` is frequently NULL for these rows, so the
20
+ statement figure is column 25, not the closing balance.
21
+- Summing column 25 by column 0 and rounding to million rial (half-up, ADR-012)
22
+ reproduces the official BS exactly:
23
+
24
+| note | source Σ rial | ÷1e6 | official (million) | match |
25
+|---|---|---|---|---|
26
+| 10 | 673740636579631 | 673740636.58 | 673740637 | ✓ |
27
+| 11 | 242193702502 | 242193.70 | 242194 | ✓ |
28
+| 12-1 | 13386398349814 | 13386398.35 | 13386398 | ✓ |
29
+| 12-2 | 8310167506886 | 8310167.51 | 8310168 | ✓ |
30
+| 13 | 6839534905630 | 6839534.91 | 6839535 | ✓ |
31
+| 14 | 11273649604593 | 11273649.60 | 11273650 | ✓ |
32
+| 15 | 19951136477703 | 19951136.48 | 19951136 | ✓ |
33
+
34
+## Decision
35
+
36
+- **Data-derived mapping:** account → note number comes from column 0; the
37
+ statement contribution is column 25. Nothing is invented.
38
+- **Display scale 6, half-up** (ADR-012): `round_half_up(source_rial / 1e6, 0)`.
39
+- `services/golden.compare_year` aggregates the source by note, reads the official
40
+ sheets (`وضعيت مالي`=BS, `سودوزيان`=IS, `حقوق مالكانه`=EQ, `جريان هاي نقدي`=CF),
41
+ and reports per-note match/delta.
42
+- **OD-08:** every non-match is written to `docs/discrepancies.json` with source
43
+ rial, rounded million, official million, and delta. Differences are surfaced,
44
+ never silently corrected (P-01). BS matches exactly; IS/CF/EQ netting rules that
45
+ are not derivable from the source are recorded as discrepancies for resolution.
46
+- The generic engine also builds all four statement types (BS/IS/CF/EQ) from
47
+ closing balances + sign policy for companies without pre-reclassified columns.
48
+
49
+## Rejected alternatives
50
+
51
+- Deriving the statement figure from `CLOSING`: NULL on most reclassified rows and
52
+ ignores the current/non-current split — would not reproduce the official BS.
53
+- Inventing IS netting rules to force a match: forbidden (§19); record as discrepancy.