@davoodmehraban89 / Aram / commits / ac565e9
Fork 0

feat(domain): pure financial domain layer + parser/inspection fixes (Phase 0)

Evidence-based ADRs from read-only probe of canonical 1404 ledger (252898 rows): - ADR-012 money: integer-rial BIGINT storage (Rial TypeDecorator), Decimal in Python, half-up + largest-remainder rounding only in output (P-02, D-03, OD-03) - ADR-013 sign: debit-positive confirmed (C-01 252892/252898 vs 37% credit-pos) - ADR-014 hierarchy: OD-01 default refuted (T1..T4 concat == حساب for 0 rows); kol->general, حساب->subsidiary, T1..T4->detail1..4; full code = kol+حساب (D-10) Domain (no I/O): normalize_fa/normalize_code/decimal_from_cell (P-03/P-04, D-04), Rial money, ledger<->Pilot hierarchy, blocking controls C-01..C-04 (D-02). ledger_parser delegates to domain (text codes keep leading zeros, exact float repr); workbook_inspection normalizes sheets/headers (D-05) and guards max_column=None (D-11). hypothesis added to test extra (ADR-012). Tests: 47 domain + 9 Phase-0 acceptance incl. bounded real-data evidence. Full suite 163 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:05 UTC ac565e9263cd7f80c495fd7052a72a07cf3855b7
16 files changed +1230 -30
backend/pyproject.toml
+1
@@ -21,6 +21,7 @@ dependencies = [
21 test = [
22 "httpx>=0.28,<1",
23 "pytest>=8.3,<9",
24 + "hypothesis>=6.100,<7",
25 ]
26
27 [tool.setuptools.packages.find]
backend/src/aram_backend/domain/__init__.py new
+24
@@ -0,0 +1,24 @@
1 +"""Pure domain rules for Aram (no I/O, no database).
2 +
3 +This package holds the non-negotiable financial primitives mandated by the
4 +executive booklet: Persian normalization (P-04), exact money (P-02), text codes
5 +(P-03), the evidence-based account hierarchy (OD-01), and the blocking financial
6 +controls (C-01..C-04). Every function here is deterministic and unit-testable
7 +without a database (booklet section 4, domain layer).
8 +"""
9 +
10 +from aram_backend.domain.normalization import (
11 + decimal_from_cell,
12 + normalize_code,
13 + normalize_fa,
14 +)
15 +from aram_backend.domain.money import Rial, round_half_up, allocate_remainder
16 +
17 +__all__ = [
18 + "normalize_fa",
19 + "normalize_code",
20 + "decimal_from_cell",
21 + "Rial",
22 + "round_half_up",
23 + "allocate_remainder",
24 +]
backend/src/aram_backend/domain/controls.py new
+169
@@ -0,0 +1,169 @@
1 +"""Blocking financial controls C-01..C-04 (booklet section 7, debt D-02).
2 +
3 +Pure, deterministic functions over balance rows and active mappings. Each
4 +returns a :class:`ControlResult` with a Persian message and the affected
5 +accounts/rows. ERROR severity blocks approval (P-09); these are not ignorable
6 +warnings. Sign convention is debit-positive (ADR-013, evidence: 252892/252898
7 +canonical rows satisfy C-01 under debit-positive vs 37% under credit-positive).
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from dataclasses import dataclass, field
13 +from decimal import Decimal
14 +
15 +_ZERO = Decimal(0)
16 +
17 +
18 +@dataclass(frozen=True)
19 +class BalanceRow:
20 + """One ledger balance row (all amounts exact Decimal rial)."""
21 +
22 + row_number: int
23 + account_code: str
24 + opening: Decimal
25 + debit: Decimal
26 + credit: Decimal
27 + closing: Decimal
28 +
29 +
30 +@dataclass(frozen=True)
31 +class MappingTarget:
32 + """One active mapping target for an account; weight is a percentage."""
33 +
34 + target: str
35 + weight: Decimal = Decimal(100)
36 +
37 +
38 +@dataclass(frozen=True)
39 +class ControlResult:
40 + code: str
41 + severity: str
42 + passed: bool
43 + message_fa: str
44 + affected: tuple[str, ...] = field(default_factory=tuple)
45 +
46 +
47 +def _aggregate(rows: list[BalanceRow]) -> dict[str, dict[str, Decimal]]:
48 + totals: dict[str, dict[str, Decimal]] = {}
49 + for row in rows:
50 + bucket = totals.setdefault(
51 + row.account_code,
52 + {"opening": _ZERO, "debit": _ZERO, "credit": _ZERO, "closing": _ZERO},
53 + )
54 + bucket["opening"] += row.opening
55 + bucket["debit"] += row.debit
56 + bucket["credit"] += row.credit
57 + bucket["closing"] += row.closing
58 + return totals
59 +
60 +
61 +def check_c01(rows: list[BalanceRow]) -> ControlResult:
62 + """C-01: every row satisfies opening + debit - credit - closing = 0."""
63 + bad = tuple(
64 + str(r.row_number)
65 + for r in rows
66 + if r.opening + r.debit - r.credit - r.closing != _ZERO
67 + )
68 + return ControlResult(
69 + code="C-01",
70 + severity="ERROR",
71 + passed=not bad,
72 + message_fa=(
73 + "همهٔ ردیف‌ها: ابتدای دوره + بدهکار − بستانکار − پایان دوره = ۰"
74 + if not bad
75 + else f"{len(bad)} ردیف معادلهٔ مانده را نقض می‌کنند"
76 + ),
77 + affected=bad,
78 + )
79 +
80 +
81 +def check_c02(rows: list[BalanceRow]) -> ControlResult:
82 + """C-02: trial balance — total debit == total credit and sum(closing) == 0."""
83 + total_debit = sum((r.debit for r in rows), _ZERO)
84 + total_credit = sum((r.credit for r in rows), _ZERO)
85 + total_closing = sum((r.closing for r in rows), _ZERO)
86 + passed = total_debit == total_credit and total_closing == _ZERO
87 + return ControlResult(
88 + code="C-02",
89 + severity="ERROR",
90 + passed=passed,
91 + message_fa=(
92 + "تراز کل برقرار است: جمع بدهکار = جمع بستانکار و جمع مانده‌ها صفر"
93 + if passed
94 + else "تراز کل نقض شده است: جمع بدهکار ≠ جمع بستانکار یا جمع مانده‌ها ≠ صفر"
95 + ),
96 + affected=() if passed else ("trial_balance",),
97 + )
98 +
99 +
100 +def _is_active(bucket: dict[str, Decimal]) -> bool:
101 + return any(bucket[k] != _ZERO for k in ("opening", "debit", "credit", "closing"))
102 +
103 +
104 +def check_c03(
105 + rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
106 +) -> ControlResult:
107 + """C-03: each active account has exactly one active mapping (or 100% split)."""
108 + bad: list[str] = []
109 + for code, bucket in sorted(_aggregate(rows).items()):
110 + if not _is_active(bucket):
111 + continue
112 + targets = mappings.get(code, [])
113 + if len(targets) == 0:
114 + bad.append(code)
115 + elif len(targets) > 1:
116 + if sum((t.weight for t in targets), _ZERO) != Decimal(100):
117 + bad.append(code)
118 + return ControlResult(
119 + code="C-03",
120 + severity="ERROR",
121 + passed=not bad,
122 + message_fa=(
123 + "هر حساب فعال دقیقاً یک نگاشت فعال دارد (یا تقسیم ۱۰۰٪)"
124 + if not bad
125 + else f"{len(bad)} حساب فعال نگاشت معتبر ندارند"
126 + ),
127 + affected=tuple(bad),
128 + )
129 +
130 +
131 +def check_c04(
132 + rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
133 +) -> ControlResult:
134 + """C-04: unmapped active accounts enter the unknown queue and block approval."""
135 + queue = tuple(
136 + code
137 + for code, bucket in sorted(_aggregate(rows).items())
138 + if _is_active(bucket) and not mappings.get(code)
139 + )
140 + return ControlResult(
141 + code="C-04",
142 + severity="ERROR",
143 + passed=not queue,
144 + message_fa=(
145 + "صف حساب‌های ناشناخته خالی است"
146 + if not queue
147 + else f"{len(queue)} حساب بدون نگاشت در صف ناشناخته؛ تا تعیین تکلیف مانع تأیید"
148 + ),
149 + affected=queue,
150 + )
151 +
152 +
153 +def run_controls(
154 + rows: list[BalanceRow], mappings: dict[str, list[MappingTarget]]
155 +) -> list[ControlResult]:
156 + """Run the Phase-0 blocking control set in stable order."""
157 + return [check_c01(rows), check_c02(rows), check_c03(rows, mappings), check_c04(rows, mappings)]
158 +
159 +
160 +__all__ = [
161 + "BalanceRow",
162 + "MappingTarget",
163 + "ControlResult",
164 + "check_c01",
165 + "check_c02",
166 + "check_c03",
167 + "check_c04",
168 + "run_controls",
169 +]
backend/src/aram_backend/domain/hierarchy.py new
+124
@@ -0,0 +1,124 @@
1 +"""Evidence-based account hierarchy mapping: ledger <-> Pilot (D-10, OD-01).
2 +
3 +The booklet OD-01 default (map T1..T4 to general..detail4 in order and expect
4 +their concatenation to equal the ``حساب`` column) is **refuted by the canonical
5 +data**: a read-only probe of all 252898 rows of source_1404.xlsx found 0 matches.
6 +
7 +What the data actually shows (ADR-014):
8 +* ``kol`` -> 2-digit general account (``general_code``).
9 +* ``حساب`` -> 4-digit subsidiary account (``subsidiary_code``); it is the leaf,
10 + not a concatenation of the T-codes.
11 +* ``T1_CODE..T4_CODE`` -> auxiliary detail dimensions (``detail1..4_code``),
12 + preserved as text but not part of the canonical account identity.
13 +* ``AccountId`` is unreliable (only ~77% equal ``kol + حساب``) and is NOT used.
14 +
15 +The canonical account full code is therefore ``general_code + subsidiary_code``
16 +(``kol + حساب``). The verifiable invariant is that for 100% of rows the
17 +subsidiary segment equals ``حساب`` and the general segment equals ``kol``.
18 +"""
19 +
20 +from __future__ import annotations
21 +
22 +from dataclasses import dataclass
23 +
24 +from aram_backend.domain.normalization import normalize_code
25 +
26 +
27 +@dataclass(frozen=True)
28 +class AccountLevels:
29 + """Six text levels of the Pilot hierarchy (P-03: codes are always text)."""
30 +
31 + general_code: str = ""
32 + subsidiary_code: str = ""
33 + detail1_code: str = ""
34 + detail2_code: str = ""
35 + detail3_code: str = ""
36 + detail4_code: str = ""
37 +
38 + def as_tuple(self) -> tuple[str, str, str, str, str, str]:
39 + return (
40 + self.general_code,
41 + self.subsidiary_code,
42 + self.detail1_code,
43 + self.detail2_code,
44 + self.detail3_code,
45 + self.detail4_code,
46 + )
47 +
48 +
49 +def ledger_to_pilot(
50 + *,
51 + kol: object,
52 + hesab: object,
53 + t1: object = None,
54 + t2: object = None,
55 + t3: object = None,
56 + t4: object = None,
57 + row: int = 0,
58 +) -> AccountLevels:
59 + """Map a canonical ledger row to Pilot levels (ADR-014).
60 +
61 + ``kol`` -> general, ``حساب`` -> subsidiary, ``T1..T4`` -> detail1..4.
62 + Empty/``None`` auxiliary codes become the empty string; codes keep their
63 + text form and leading zeros (P-03).
64 + """
65 + general = normalize_code(kol, row=row, field="kol")
66 + subsidiary = normalize_code(hesab, row=row, field="حساب")
67 + details = [
68 + normalize_code(t, row=row, field=f"T{i}_CODE") if t not in (None, "") else ""
69 + for i, t in enumerate((t1, t2, t3, t4), start=1)
70 + ]
71 + return AccountLevels(
72 + general_code=general,
73 + subsidiary_code=subsidiary,
74 + detail1_code=details[0],
75 + detail2_code=details[1],
76 + detail3_code=details[2],
77 + detail4_code=details[3],
78 + )
79 +
80 +
81 +def pilot_to_ledger(levels: AccountLevels) -> dict[str, str]:
82 + """Inverse mapping for the bidirectional conversion test (D-10)."""
83 + return {
84 + "kol": levels.general_code,
85 + "حساب": levels.subsidiary_code,
86 + "T1_CODE": levels.detail1_code,
87 + "T2_CODE": levels.detail2_code,
88 + "T3_CODE": levels.detail3_code,
89 + "T4_CODE": levels.detail4_code,
90 + }
91 +
92 +
93 +def canonical_full_code(levels: AccountLevels) -> str:
94 + """Canonical account identity = general + subsidiary (ADR-014).
95 +
96 + Auxiliary detail codes are preserved on the level record but do not change
97 + the canonical account identity of the canonical ledger.
98 + """
99 + return levels.general_code + levels.subsidiary_code
100 +
101 +
102 +def reconstruct_full_code(levels: AccountLevels) -> str:
103 + """Pilot-style concatenation of every non-empty level, in order."""
104 + return "".join(code for code in levels.as_tuple() if code)
105 +
106 +
107 +def account_level(levels: AccountLevels) -> str:
108 + """Deepest populated level name, matching the Pilot contract vocabulary."""
109 + names = ("General", "Subsidiary", "Detail1", "Detail2", "Detail3", "Detail4")
110 + deepest = "General"
111 + for name, code in zip(names, levels.as_tuple()):
112 + if code:
113 + deepest = name
114 + return deepest
115 +
116 +
117 +__all__ = [
118 + "AccountLevels",
119 + "ledger_to_pilot",
120 + "pilot_to_ledger",
121 + "canonical_full_code",
122 + "reconstruct_full_code",
123 + "account_level",
124 +]
backend/src/aram_backend/domain/money.py new
+98
@@ -0,0 +1,98 @@
1 +"""Exact money: scaled-integer storage, Decimal in Python (P-02, D-03, OD-03).
2 +
3 +No float ever touches persistence. Amounts are stored as scaled integers in a
4 +``BIGINT`` column and exposed as :class:`~decimal.Decimal`. The scale is fixed at
5 +0 (full rial) because a read-only probe of the canonical 1404 ledger found zero
6 +fractional-rial cells; this is recorded in ADR-012. Rounding happens only in the
7 +display/output layer through :func:`round_half_up`, and the rounding difference
8 +between rows and their total is allocated by the largest-remainder method
9 +(:func:`allocate_remainder`) so displayed rows always sum to the displayed total.
10 +"""
11 +
12 +from __future__ import annotations
13 +
14 +from decimal import Decimal, ROUND_HALF_UP
15 +from typing import Any
16 +
17 +from sqlalchemy import BigInteger
18 +from sqlalchemy.engine.interfaces import Dialect
19 +from sqlalchemy.types import TypeDecorator
20 +
21 +#: Integer rial; evidence-based (ADR-012). 10**0 == 1.
22 +RIAL_SCALE = 0
23 +_FACTOR = 10**RIAL_SCALE
24 +
25 +
26 +class Rial(TypeDecorator[Decimal]):
27 + """Store a Decimal rial amount as an exact scaled integer (P-02).
28 +
29 + Works identically on SQLite and PostgreSQL (``BIGINT``). Accepts Decimal,
30 + int, or exact numeric text; rejects float and fractional rial loudly (P-09)
31 + so no silent rounding can occur on the way into the database.
32 + """
33 +
34 + impl = BigInteger
35 + cache_ok = True
36 +
37 + def process_bind_param(self, value: Any, dialect: Dialect) -> int | None:
38 + if value is None:
39 + return None
40 + if isinstance(value, float):
41 + raise TypeError("float is forbidden for money (P-02); pass Decimal")
42 + if isinstance(value, Decimal):
43 + number = value
44 + elif isinstance(value, int):
45 + number = Decimal(value)
46 + elif isinstance(value, str):
47 + number = Decimal(value)
48 + else:
49 + raise TypeError(f"unsupported money type: {type(value).__name__}")
50 + if not number.is_finite():
51 + raise ValueError("money must be finite")
52 + scaled = number * _FACTOR
53 + if scaled != scaled.to_integral_value():
54 + raise ValueError(
55 + f"fractional rial is not representable at scale {RIAL_SCALE}: {number}"
56 + )
57 + return int(scaled)
58 +
59 + def process_result_value(self, value: Any, dialect: Dialect) -> Decimal | None:
60 + if value is None:
61 + return None
62 + return Decimal(int(value)) / _FACTOR
63 +
64 +
65 +def round_half_up(value: Decimal, places: int = 0) -> Decimal:
66 + """The single central rounding rule: half-up (OD-03), output layer only."""
67 + quantum = Decimal(1).scaleb(-places)
68 + return value.quantize(quantum, rounding=ROUND_HALF_UP)
69 +
70 +
71 +def allocate_remainder(
72 + values: list[Decimal], total: Decimal, places: int = 0
73 +) -> list[Decimal]:
74 + """Round rows so they sum exactly to the rounded total (largest remainder).
75 +
76 + Deterministic and stable: rows are adjusted in order of their rounding
77 + error, ties broken by original index. Guarantees
78 + ``sum(result) == round_half_up(total, places)``.
79 + """
80 + if not values:
81 + return []
82 + quantum = Decimal(1).scaleb(-places)
83 + rounded = [round_half_up(v, places) for v in values]
84 + target = round_half_up(total, places)
85 + diff = target - sum(rounded)
86 + if diff == 0:
87 + return rounded
88 + steps = int(diff / quantum)
89 + errors = [v - r for v, r in zip(values, rounded)]
90 + order = sorted(range(len(values)), key=lambda i: (errors[i], -i), reverse=steps > 0)
91 + result = list(rounded)
92 + sign = 1 if steps > 0 else -1
93 + for k in range(abs(steps)):
94 + result[order[k % len(order)]] += sign * quantum
95 + return result
96 +
97 +
98 +__all__ = ["Rial", "RIAL_SCALE", "round_half_up", "allocate_remainder"]
backend/src/aram_backend/domain/normalization.py new
+116
@@ -0,0 +1,116 @@
1 +"""Single-source Persian normalization and exact cell decoding (P-03, P-04).
2 +
3 +Every Persian text input passes through :func:`normalize_fa` (booklet P-04).
4 +Account/note codes are always text and keep leading zeros and length (P-03);
5 +they are never numerified. Excel floats become :class:`~decimal.Decimal` through
6 +the shortest round-trip ``repr`` so no binary float artifact survives (D-04).
7 +
8 +Evidence (read-only probe of data/source_ledgers/source_1404.xlsx, 252898 rows):
9 +the canonical ``حساب`` and ``kol`` cells are stored as integers and there are no
10 +fractional rial cells. The booklet D-04 default "raw numeric code -> explicit
11 +error" is therefore refuted by the real data (section 17 rule 3, evidence wins):
12 +integral numeric codes are accepted and converted to text exactly, text codes
13 +keep their leading zeros, and only non-integral/ambiguous numeric codes raise.
14 +"""
15 +
16 +from __future__ import annotations
17 +
18 +from decimal import Decimal, InvalidOperation
19 +
20 +# Arabic -> Persian letters and Persian/Arabic-Indic digits -> Latin (P-04, §8).
21 +_TRANSLATION = {
22 + 0x064A: 0x06CC, # Arabic yeh ي -> Persian yeh ی
23 + 0x0643: 0x06A9, # Arabic kaf ك -> Persian kaf ک
24 + 0x0640: None, # tatweel / kashida ـ removed
25 + 0x00A0: None, # no-break space removed
26 + 0x200B: None, # zero-width space removed
27 + 0x200E: None, # left-to-right mark removed
28 + 0x200F: None, # right-to-left mark removed
29 + 0xFEFF: None, # zero-width no-break space / BOM removed
30 +}
31 +for _i in range(10):
32 + _TRANSLATION[0x06F0 + _i] = 0x30 + _i # Persian digits ۰-۹
33 + _TRANSLATION[0x0660 + _i] = 0x30 + _i # Arabic digits ٠-٩
34 +# Control characters (except tab/newline which trim handles) are removed.
35 +for _c in range(0x20):
36 + if _c not in (0x09, 0x0A, 0x0D):
37 + _TRANSLATION[_c] = None
38 +_TRANSLATION[0x7F] = None
39 +
40 +# Thousands separators that may appear inside numeric text cells.
41 +_SEPARATORS = str.maketrans({",": None, "٬": None, "،": None, " ": None, "\u200c": None})
42 +
43 +
44 +class NormalizationError(ValueError):
45 + """Raised when a cell cannot be normalized safely (fail loud, P-09)."""
46 +
47 +
48 +def normalize_fa(text: str) -> str:
49 + """Normalize Persian text: letters, digits, invisible chars, trim (P-04).
50 +
51 + Idempotent: ``normalize_fa(normalize_fa(x)) == normalize_fa(x)``. The
52 + zero-width non-joiner (U+200C, the Persian half-space) is preserved because
53 + it is linguistically meaningful; only invisible *format* controls are dropped.
54 + """
55 + cleaned = text.translate(_TRANSLATION)
56 + return cleaned.strip()
57 +
58 +
59 +def normalize_code(value: object, *, row: int, field: str) -> str:
60 + """Return an account/note code as text, preserving leading zeros (P-03, D-04).
61 +
62 + * ``str`` -> :func:`normalize_fa`, leading zeros and length preserved.
63 + * ``int`` -> exact decimal text (the canonical ledger stores codes as int).
64 + * integral ``float``/``Decimal`` -> exact integer text.
65 + * non-integral numeric, ``bool``, ``None`` -> :class:`NormalizationError`.
66 +
67 + A code is never silently truncated or numerified; ``'0101'`` stays ``'0101'``.
68 + """
69 + if value is None or isinstance(value, bool):
70 + raise NormalizationError(f"row {row}: {field} is not a valid code")
71 + if isinstance(value, str):
72 + code = normalize_fa(value)
73 + if not code:
74 + raise NormalizationError(f"row {row}: {field} is empty")
75 + return code
76 + if isinstance(value, int):
77 + return str(value)
78 + if isinstance(value, (float, Decimal)):
79 + number = decimal_from_cell(value, row=row, field=field)
80 + if number != number.to_integral_value():
81 + raise NormalizationError(
82 + f"row {row}: {field} must be an integer code, got {number}"
83 + )
84 + return str(int(number))
85 + raise NormalizationError(f"row {row}: {field} is not a valid code")
86 +
87 +
88 +def decimal_from_cell(value: object, *, row: int, field: str) -> Decimal:
89 + """Decode a numeric cell to an exact :class:`Decimal` (D-04, §8).
90 +
91 + Floats use the shortest round-trip ``repr`` (never ``str(float)`` artifacts
92 + nor the exact binary expansion). Text is Persian-normalized and thousands
93 + separators are removed before parsing. Non-finite or non-numeric values
94 + raise :class:`NormalizationError`.
95 + """
96 + if value is None or isinstance(value, bool):
97 + raise NormalizationError(f"row {row}: {field} is required and numeric")
98 + if isinstance(value, Decimal):
99 + parsed = value
100 + elif isinstance(value, int):
101 + parsed = Decimal(value)
102 + elif isinstance(value, float):
103 + parsed = Decimal(repr(value))
104 + elif isinstance(value, str):
105 + candidate = normalize_fa(value).translate(_SEPARATORS)
106 + if not candidate:
107 + raise NormalizationError(f"row {row}: {field} is required and numeric")
108 + try:
109 + parsed = Decimal(candidate)
110 + except InvalidOperation as exc:
111 + raise NormalizationError(f"row {row}: {field} is not numeric") from exc
112 + else:
113 + raise NormalizationError(f"row {row}: {field} is not numeric")
114 + if not parsed.is_finite():
115 + raise NormalizationError(f"row {row}: {field} must be finite")
116 + return parsed
backend/src/aram_backend/ledger_parser.py
+23 -23
@@ -2,11 +2,17 @@ from __future__ import annotations
2
3 from collections.abc import Iterator
4 from dataclasses import dataclass
5 -from decimal import Decimal, InvalidOperation
5 +from decimal import Decimal
6 from io import BytesIO
7
8 from openpyxl import load_workbook
9
10 +from aram_backend.domain.normalization import (
11 + NormalizationError,
12 + decimal_from_cell,
13 + normalize_code,
14 + normalize_fa,
15 +)
16 from aram_backend.workbook_inspection import inspect_xlsx
17
18
@@ -48,7 +54,12 @@ _FIELDS = {
54
55
56 def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
51 - """Stream typed ledger rows without persisting or calculating values."""
57 + """Stream typed ledger rows without persisting or calculating values.
58 +
59 + Codes are normalized as text (leading zeros preserved, P-03/D-04) and money
60 + is decoded to exact Decimal via the shortest round-trip repr (D-04). Header
61 + matching is Persian-normalized (D-05).
62 + """
63
64 inspection = inspect_xlsx(content, document_type="general_ledger")
65 workbook = load_workbook(
@@ -64,7 +75,7 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
75 )
76 )
77 indexes = {
67 - str(value).strip(): index
78 + normalize_fa(str(value)): index
79 for index, value in enumerate(header_values)
80 if value is not None
81 }
@@ -79,7 +90,7 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
90 continue
91
92 def value(field: str):
82 - return values[indexes[_FIELDS[field]]]
93 + return values[indexes[normalize_fa(_FIELDS[field])]]
94
95 yield LedgerRecord(
96 row_number=row_number,
@@ -103,7 +114,7 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
114
115
116 def _required_text(value: object, row_number: int, field: str) -> str:
106 - text = str(value).strip() if value is not None else ""
117 + text = normalize_fa(str(value)) if value is not None else ""
118 if not text:
119 raise LedgerParseError(f"row {row_number}: {field} is required")
120 return text
@@ -126,25 +137,14 @@ def _required_code(value: object, row_number: int, field: str) -> str:
137 def _optional_code(value: object, row_number: int, field: str) -> str | None:
138 if value is None:
139 return None
129 - if isinstance(value, bool):
130 - raise LedgerParseError(f"row {row_number}: {field} is not a valid code")
131 - if isinstance(value, str):
132 - code = value.strip()
133 - return code or None
134 - parsed = _required_decimal(value, row_number, field)
135 - if parsed != parsed.to_integral_value():
136 - raise LedgerParseError(f"row {row_number}: {field} must be an integer code")
137 - return str(int(parsed))
140 + try:
141 + return normalize_code(value, row=row_number, field=field)
142 + except NormalizationError as exc:
143 + raise LedgerParseError(str(exc)) from exc
144
145
146 def _required_decimal(value: object, row_number: int, field: str) -> Decimal:
141 - if value is None or isinstance(value, bool):
142 - raise LedgerParseError(f"row {row_number}: {field} is required and numeric")
143 - candidate = str(value).strip().replace(",", "").replace("٬", "")
147 try:
145 - parsed = Decimal(candidate)
146 - except (InvalidOperation, ValueError) as exc:
147 - raise LedgerParseError(f"row {row_number}: {field} is not numeric") from exc
148 - if not parsed.is_finite():
149 - raise LedgerParseError(f"row {row_number}: {field} must be finite")
150 - return parsed
148 + return decimal_from_cell(value, row=row_number, field=field)
149 + except NormalizationError as exc:
150 + raise LedgerParseError(str(exc)) from exc
backend/src/aram_backend/workbook_inspection.py
+21 -7
@@ -7,6 +7,8 @@ from zipfile import BadZipFile
7 from openpyxl import load_workbook
8 from openpyxl.utils.exceptions import InvalidFileException
9
10 +from aram_backend.domain.normalization import normalize_fa
11 +
12
13 MAX_WORKSHEETS = 100
14 MAX_HEADER_COLUMNS = 256
@@ -88,7 +90,10 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
90 raise WorkbookInspectionError("workbook contains too many worksheets")
91
92 if document_type == "financial_statement":
91 - missing = _PRIMARY_STATEMENT_SHEETS.difference(sheet_names)
93 + actual_normalized = {normalize_fa(name) for name in sheet_names}
94 + missing = {
95 + normalize_fa(name) for name in _PRIMARY_STATEMENT_SHEETS
96 + }.difference(actual_normalized)
97 if missing:
98 raise WorkbookInspectionError(
99 f"financial statement workbook is missing sheets: {sorted(missing)}"
@@ -102,26 +107,35 @@ def inspect_xlsx(content: bytes, *, document_type: str) -> WorkbookInspection:
107 )
108
109 profile = _TABULAR_PROFILES[document_type]
105 - sheet_name = profile["sheet"]
106 - if sheet_name not in workbook:
107 - raise WorkbookInspectionError(f"required worksheet is missing: {sheet_name}")
110 + target_normalized = normalize_fa(profile["sheet"])
111 + sheets_by_normalized = {normalize_fa(name): name for name in workbook.sheetnames}
112 + if target_normalized not in sheets_by_normalized:
113 + raise WorkbookInspectionError(
114 + f"required worksheet is missing: {profile['sheet']}"
115 + )
116 + sheet_name = sheets_by_normalized[target_normalized]
117
118 worksheet = workbook[sheet_name]
119 header_row = profile["header_row"]
120 + # D-11: read-only worksheets may report max_column=None (no dimension).
121 + max_column = worksheet.max_column
122 + if max_column is None:
123 + max_column = MAX_HEADER_COLUMNS
124 values = next(
125 worksheet.iter_rows(
126 min_row=header_row,
127 max_row=header_row,
115 - max_col=min(worksheet.max_column, MAX_HEADER_COLUMNS),
128 + max_col=min(max_column, MAX_HEADER_COLUMNS),
129 values_only=True,
130 ),
131 (),
132 )
120 - headers = tuple(str(value).strip() for value in values if value is not None)
133 + headers = tuple(normalize_fa(str(value)) for value in values if value is not None)
134 if len(headers) != len(set(headers)):
135 raise WorkbookInspectionError("header row contains duplicate names")
136
124 - missing = profile["required_headers"].difference(headers)
137 + required_normalized = {normalize_fa(h) for h in profile["required_headers"]}
138 + missing = required_normalized.difference(headers)
139 if missing:
140 raise WorkbookInspectionError(f"required headers are missing: {sorted(missing)}")
141
backend/tests/test_domain_controls.py new
+85
@@ -0,0 +1,85 @@
1 +"""Positive and negative tests for blocking controls C-01..C-04 (D-02)."""
2 +
3 +from decimal import Decimal
4 +
5 +from aram_backend.domain.controls import (
6 + BalanceRow,
7 + MappingTarget,
8 + check_c01,
9 + check_c02,
10 + check_c03,
11 + check_c04,
12 + run_controls,
13 +)
14 +
15 +
16 +def row(n, code, o, d, c, cl):
17 + return BalanceRow(n, code, Decimal(o), Decimal(d), Decimal(c), Decimal(cl))
18 +
19 +
20 +class TestC01:
21 + def test_pass(self):
22 + rows = [row(2, "148348", 100, 50, 20, 130)]
23 + assert check_c01(rows).passed
24 +
25 + def test_fail_detects_row(self):
26 + rows = [row(2, "148348", 100, 50, 20, 999)]
27 + result = check_c01(rows)
28 + assert not result.passed
29 + assert result.severity == "ERROR"
30 + assert result.affected == ("2",)
31 +
32 +
33 +class TestC02:
34 + def test_pass(self):
35 + rows = [row(2, "a", 0, 100, 0, 100), row(3, "b", 0, 0, 100, -100)]
36 + assert check_c02(rows).passed
37 +
38 + def test_fail_unbalanced(self):
39 + rows = [row(2, "a", 0, 100, 0, 100)]
40 + assert not check_c02(rows).passed
41 +
42 +
43 +class TestC03:
44 + def test_single_mapping_pass(self):
45 + rows = [row(2, "a", 0, 100, 0, 100)]
46 + mappings = {"a": [MappingTarget("BS/Assets/04")]}
47 + assert check_c03(rows, mappings).passed
48 +
49 + def test_no_mapping_fail(self):
50 + rows = [row(2, "a", 0, 100, 0, 100)]
51 + result = check_c03(rows, {})
52 + assert not result.passed
53 + assert result.affected == ("a",)
54 +
55 + def test_split_100_pass(self):
56 + rows = [row(2, "a", 0, 100, 0, 100)]
57 + mappings = {"a": [MappingTarget("x", Decimal(60)), MappingTarget("y", Decimal(40))]}
58 + assert check_c03(rows, mappings).passed
59 +
60 + def test_split_not_100_fail(self):
61 + rows = [row(2, "a", 0, 100, 0, 100)]
62 + mappings = {"a": [MappingTarget("x", Decimal(60)), MappingTarget("y", Decimal(30))]}
63 + assert not check_c03(rows, mappings).passed
64 +
65 + def test_zero_balance_account_ignored(self):
66 + rows = [row(2, "a", 0, 0, 0, 0)]
67 + assert check_c03(rows, {}).passed
68 +
69 +
70 +class TestC04:
71 + def test_empty_queue_pass(self):
72 + rows = [row(2, "a", 0, 100, 0, 100)]
73 + assert check_c04(rows, {"a": [MappingTarget("x")]}).passed
74 +
75 + def test_unmapped_active_blocks(self):
76 + rows = [row(2, "a", 0, 100, 0, 100), row(3, "b", 0, 0, 0, 0)]
77 + result = check_c04(rows, {})
78 + assert not result.passed
79 + assert result.affected == ("a",) # zero-balance b is not queued
80 +
81 +
82 +class TestRunControls:
83 + def test_stable_order(self):
84 + results = run_controls([], {})
85 + assert [r.code for r in results] == ["C-01", "C-02", "C-03", "C-04"]
backend/tests/test_domain_hierarchy.py new
+60
@@ -0,0 +1,60 @@
1 +"""Bidirectional hierarchy conversion tests (D-10, OD-01, ADR-014)."""
2 +
3 +from aram_backend.domain.hierarchy import (
4 + AccountLevels,
5 + account_level,
6 + canonical_full_code,
7 + ledger_to_pilot,
8 + pilot_to_ledger,
9 + reconstruct_full_code,
10 +)
11 +
12 +
13 +class TestLedgerToPilot:
14 + def test_evidence_based_mapping(self):
15 + levels = ledger_to_pilot(kol=14, hesab=8348, t1=117001, t2="22200000000899", row=2)
16 + assert levels.general_code == "14"
17 + assert levels.subsidiary_code == "8348"
18 + assert levels.detail1_code == "117001"
19 + assert levels.detail2_code == "22200000000899"
20 + assert levels.detail3_code == ""
21 + assert levels.detail4_code == ""
22 +
23 + def test_canonical_full_code_is_general_plus_subsidiary(self):
24 + levels = ledger_to_pilot(kol=14, hesab=8348, row=2)
25 + assert canonical_full_code(levels) == "148348"
26 +
27 + def test_leading_zeros_preserved(self):
28 + levels = ledger_to_pilot(kol="01", hesab="0101", row=2)
29 + assert levels.general_code == "01"
30 + assert levels.subsidiary_code == "0101"
31 + assert canonical_full_code(levels) == "010101"
32 +
33 + def test_account_level(self):
34 + assert account_level(ledger_to_pilot(kol=14, hesab=8348, row=2)) == "Subsidiary"
35 + deep = AccountLevels("14", "8348", "117001", "222", "3", "4")
36 + assert account_level(deep) == "Detail4"
37 +
38 + def test_reconstruct_concatenates_all_levels(self):
39 + deep = AccountLevels("14", "8348", "117001", "222", "", "")
40 + assert reconstruct_full_code(deep) == "148348117001222"
41 +
42 +
43 +class TestBidirectionalRoundTrip:
44 + def test_roundtrip(self):
45 + levels = ledger_to_pilot(kol=19, hesab=8312, t1=117001, t2="22100000571471", row=5)
46 + back = pilot_to_ledger(levels)
47 + assert back["kol"] == "19"
48 + assert back["حساب"] == "8312"
49 + assert back["T1_CODE"] == "117001"
50 + assert back["T2_CODE"] == "22100000571471"
51 + again = ledger_to_pilot(
52 + kol=back["kol"],
53 + hesab=back["حساب"],
54 + t1=back["T1_CODE"],
55 + t2=back["T2_CODE"],
56 + t3=back["T3_CODE"],
57 + t4=back["T4_CODE"],
58 + row=5,
59 + )
60 + assert again == levels
backend/tests/test_domain_money.py new
+90
@@ -0,0 +1,90 @@
1 +"""Exact-money tests (P-02, D-03, OD-03), including Hypothesis property tests."""
2 +
3 +from decimal import Decimal
4 +
5 +import pytest
6 +from hypothesis import given, settings
7 +from hypothesis import strategies as st
8 +
9 +from aram_backend.domain.money import (
10 + Rial,
11 + allocate_remainder,
12 + round_half_up,
13 +)
14 +
15 +rial = Rial()
16 +
17 +
18 +class TestRialRoundTrip:
19 + @given(st.integers(min_value=-(10**18 - 1), max_value=10**18 - 1))
20 + @settings(max_examples=300)
21 + def test_exact_roundtrip_up_to_18_digits(self, n):
22 + value = Decimal(n)
23 + stored = rial.process_bind_param(value, dialect=None)
24 + assert isinstance(stored, int)
25 + assert rial.process_result_value(stored, dialect=None) == value
26 +
27 + def test_none_roundtrip(self):
28 + assert rial.process_bind_param(None, dialect=None) is None
29 + assert rial.process_result_value(None, dialect=None) is None
30 +
31 + def test_float_rejected(self):
32 + with pytest.raises(TypeError):
33 + rial.process_bind_param(1.5, dialect=None)
34 +
35 + def test_fractional_rial_rejected(self):
36 + with pytest.raises(ValueError):
37 + rial.process_bind_param(Decimal("1.5"), dialect=None)
38 +
39 + def test_non_finite_rejected(self):
40 + with pytest.raises(ValueError):
41 + rial.process_bind_param(Decimal("NaN"), dialect=None)
42 +
43 + def test_int_and_text_accepted(self):
44 + assert rial.process_bind_param(100, dialect=None) == 100
45 + assert rial.process_bind_param("100", dialect=None) == 100
46 +
47 + def test_large_rial_no_silent_rounding(self):
48 + big = Decimal("10823163409740108")
49 + assert rial.process_result_value(
50 + rial.process_bind_param(big, dialect=None), dialect=None
51 + ) == big
52 +
53 +
54 +class TestRoundHalfUp:
55 + def test_half_up(self):
56 + assert round_half_up(Decimal("2.5")) == Decimal("3")
57 + assert round_half_up(Decimal("2.4")) == Decimal("2")
58 + assert round_half_up(Decimal("-2.5")) == Decimal("-3")
59 +
60 + def test_places(self):
61 + assert round_half_up(Decimal("1.2345"), 2) == Decimal("1.23")
62 + assert round_half_up(Decimal("1.2355"), 2) == Decimal("1.24")
63 +
64 +
65 +class TestAllocateRemainder:
66 + def test_rows_sum_to_rounded_total(self):
67 + values = [Decimal("0.5"), Decimal("0.5"), Decimal("0.5")]
68 + total = sum(values)
69 + result = allocate_remainder(values, total, 0)
70 + assert sum(result) == round_half_up(total, 0)
71 +
72 + def test_empty(self):
73 + assert allocate_remainder([], Decimal(0), 0) == []
74 +
75 + @given(
76 + st.lists(
77 + st.integers(min_value=-(10**9), max_value=10**9).map(
78 + lambda x: Decimal(x) / 100
79 + ),
80 + min_size=1,
81 + max_size=25,
82 + )
83 + )
84 + @settings(max_examples=200)
85 + def test_property_sum_matches_rounded_total(self, values):
86 + total = sum(values)
87 + for places in (0, 2):
88 + result = allocate_remainder(values, total, places)
89 + assert sum(result) == round_half_up(total, places)
90 + assert len(result) == len(values)
backend/tests/test_domain_normalization.py new
+92
@@ -0,0 +1,92 @@
1 +"""Tests for the single-source Persian normalization (P-03, P-04, D-04, D-05)."""
2 +
3 +from decimal import Decimal
4 +
5 +import pytest
6 +
7 +from aram_backend.domain.normalization import (
8 + NormalizationError,
9 + decimal_from_cell,
10 + normalize_code,
11 + normalize_fa,
12 +)
13 +
14 +
15 +class TestNormalizeFa:
16 + def test_arabic_letters_to_persian(self):
17 + assert normalize_fa("سودوزيان") == "سودوزیان"
18 + assert normalize_fa("وضعيت مالي") == "وضعیت مالی"
19 + assert normalize_fa("حقوق مالكانه") == "حقوق مالکانه"
20 +
21 + def test_persian_and_arabic_digits_to_latin(self):
22 + assert normalize_fa("۱۴۰۴") == "1404"
23 + assert normalize_fa("١٤٠٤") == "1404"
24 +
25 + def test_removes_nbsp_tatweel_and_controls(self):
26 + assert normalize_fa("الف\u00a0بـج\x00د") == "الفبجد"
27 +
28 + def test_preserves_zwnj_half_space(self):
29 + assert normalize_fa("دارایی\u200cها") == "دارایی\u200cها"
30 +
31 + def test_trim(self):
32 + assert normalize_fa(" سلام ") == "سلام"
33 +
34 + def test_idempotent(self):
35 + for sample in ("سودوزيان", "۱۴۰۴", "دارایی\u200cها", "وضعيت مالي"):
36 + once = normalize_fa(sample)
37 + assert normalize_fa(once) == once
38 +
39 +
40 +class TestNormalizeCode:
41 + def test_text_leading_zeros_preserved(self):
42 + assert normalize_code("0101", row=2, field="حساب") == "0101"
43 +
44 + def test_persian_digit_code_stays_text(self):
45 + assert normalize_code("۰۱۰۱", row=2, field="حساب") == "0101"
46 +
47 + def test_integer_code_exact(self):
48 + assert normalize_code(8348, row=2, field="حساب") == "8348"
49 +
50 + def test_integral_float_code(self):
51 + assert normalize_code(101.0, row=2, field="حساب") == "101"
52 +
53 + def test_non_integral_float_code_raises(self):
54 + with pytest.raises(NormalizationError):
55 + normalize_code(101.5, row=2, field="حساب")
56 +
57 + def test_bool_and_none_raise(self):
58 + with pytest.raises(NormalizationError):
59 + normalize_code(True, row=2, field="حساب")
60 + with pytest.raises(NormalizationError):
61 + normalize_code(None, row=2, field="حساب")
62 +
63 + def test_empty_text_raises(self):
64 + with pytest.raises(NormalizationError):
65 + normalize_code(" ", row=2, field="حساب")
66 +
67 +
68 +class TestDecimalFromCell:
69 + def test_float_uses_shortest_roundtrip_repr(self):
70 + # 0.1 + 0.2 must not become the binary expansion nor lose precision.
71 + assert decimal_from_cell(0.1 + 0.2, row=2, field="Debit") == Decimal(
72 + "0.30000000000000004"
73 + )
74 + assert decimal_from_cell(0.1, row=2, field="Debit") == Decimal("0.1")
75 +
76 + def test_integer_and_decimal(self):
77 + assert decimal_from_cell(5, row=2, field="Debit") == Decimal(5)
78 + assert decimal_from_cell(Decimal("1.25"), row=2, field="Debit") == Decimal("1.25")
79 +
80 + def test_persian_digits_and_separators(self):
81 + assert decimal_from_cell("۱۲۳٬۴۵۶", row=2, field="Debit") == Decimal(123456)
82 + assert decimal_from_cell("1,234.5", row=2, field="Debit") == Decimal("1234.5")
83 +
84 + def test_non_numeric_and_non_finite_raise(self):
85 + with pytest.raises(NormalizationError):
86 + decimal_from_cell("abc", row=2, field="Debit")
87 + with pytest.raises(NormalizationError):
88 + decimal_from_cell(float("nan"), row=2, field="Debit")
89 + with pytest.raises(NormalizationError):
90 + decimal_from_cell(None, row=2, field="Debit")
91 + with pytest.raises(NormalizationError):
92 + decimal_from_cell(True, row=2, field="Debit")
backend/tests/test_phase0_fixes.py new
+173
@@ -0,0 +1,173 @@
1 +"""Acceptance tests for Phase-0 debts D-04, D-05, D-11 and real-data evidence.
2 +
3 +These prove the booklet's required fixes at the parser/inspection level and
4 +record the evidence behind ADR-013 (sign) and ADR-014 (hierarchy) on a bounded
5 +sample of the canonical 1404 ledger (read-only; skipped if data is absent).
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import io
11 +import re
12 +import zipfile
13 +from decimal import Decimal
14 +from pathlib import Path
15 +
16 +import pytest
17 +from openpyxl import Workbook, load_workbook
18 +
19 +from aram_backend.domain.controls import BalanceRow, check_c01
20 +from aram_backend.domain.hierarchy import ledger_to_pilot
21 +from aram_backend.ledger_parser import parse_general_ledger
22 +from aram_backend.workbook_inspection import inspect_xlsx
23 +
24 +GL_HEADERS = [
25 + "حساب", "ACCOUNT_NAME", "year", "نوع",
26 + "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
27 + "OPENING", "Debit", "Credit", "CLOSING",
28 +]
29 +REPO_ROOT = Path(__file__).resolve().parents[2]
30 +LEDGER_1404 = REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
31 +
32 +
33 +def _gl_bytes(*rows, headers=None):
34 + wb = Workbook()
35 + ws = wb.active
36 + ws.title = "Source"
37 + ws.append(["source ledger"])
38 + ws.append(headers or GL_HEADERS)
39 + for r in rows:
40 + ws.append(r)
41 + buf = io.BytesIO()
42 + wb.save(buf)
43 + wb.close()
44 + return buf.getvalue()
45 +
46 +
47 +def _strip_dimension(raw: bytes) -> bytes:
48 + zin = zipfile.ZipFile(io.BytesIO(raw))
49 + out = io.BytesIO()
50 + zout = zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED)
51 + for item in zin.infolist():
52 + data = zin.read(item.filename)
53 + if item.filename == "xl/worksheets/sheet1.xml":
54 + data = re.sub(rb"<dimension[^>]*/>", b"", data)
55 + zout.writestr(item, data)
56 + zout.close()
57 + return out.getvalue()
58 +
59 +
60 +def _row(code="0101", opening=0, debit=0, credit=0, closing=0):
61 + return [code, "x", 1404, "O", None, None, None, None, opening, debit, credit, closing]
62 +
63 +
64 +class TestD04CodesAndMoney:
65 + def test_text_leading_zero_code_preserved(self):
66 + rec = next(parse_general_ledger(_gl_bytes(_row(code="0101"))))
67 + assert rec.account_code == "0101"
68 +
69 + def test_persian_digit_code_normalized_to_text(self):
70 + rec = next(parse_general_ledger(_gl_bytes(_row(code="۰۱۰۱"))))
71 + assert rec.account_code == "0101"
72 +
73 + def test_integer_code_exact(self):
74 + rec = next(parse_general_ledger(_gl_bytes(_row(code=8348))))
75 + assert rec.account_code == "8348"
76 +
77 + def test_float_money_exact_roundtrip(self):
78 + # repr path: exact shortest round-trip, not the binary expansion.
79 + rec = next(parse_general_ledger(_gl_bytes(_row(debit=1234.56789012345))))
80 + assert rec.debit == Decimal("1234.56789012345")
81 +
82 +
83 +class TestD05Normalization:
84 + def test_persian_financial_statement_sheets_accepted(self):
85 + # Persian ی/ک variants of the canonical Arabic sheet names.
86 + names = ["سودوزیان", "وضعیت مالی", "حقوق مالکانه", "جریان های نقدی"]
87 + wb = Workbook()
88 + wb.remove(wb.active)
89 + for n in names:
90 + wb.create_sheet(n)
91 + buf = io.BytesIO()
92 + wb.save(buf)
93 + wb.close()
94 + result = inspect_xlsx(buf.getvalue(), document_type="financial_statement")
95 + assert result.sheet_names == tuple(names)
96 +
97 + def test_arabic_kaf_mapping_headers_accepted(self):
98 + # "كد حساب" with Arabic kaf must match the Persian "کد حساب" requirement.
99 + headers = ["كد حساب", "نوع", "كد یادداشت", "شرح یادداشت",
100 + "فرمول یادداشت اصلی", "فرمول یادداشت فرعی"]
101 + wb = Workbook()
102 + ws = wb.active
103 + ws.title = "Data"
104 + ws.append(headers)
105 + buf = io.BytesIO()
106 + wb.save(buf)
107 + wb.close()
108 + result = inspect_xlsx(buf.getvalue(), document_type="mapping")
109 + assert result.data_sheet == "Data"
110 +
111 +
112 +class TestD11NoDimension:
113 + def test_dimensionless_file_inspects_and_parses(self):
114 + raw = _strip_dimension(_gl_bytes(_row()))
115 + # Confirm the fixture really has no dimension (max_column is None).
116 + probe = load_workbook(io.BytesIO(raw), read_only=True)
117 + assert probe["Source"].max_column is None
118 + probe.close()
119 + result = inspect_xlsx(raw, document_type="general_ledger")
120 + assert result.data_sheet == "Source"
121 + rec = next(parse_general_ledger(raw))
122 + assert rec.account_code == "0101"
123 +
124 +
125 +@pytest.mark.skipif(not LEDGER_1404.exists(), reason="canonical ledger not present")
126 +class TestRealDataEvidence:
127 + """Bounded read-only evidence for ADR-013 (sign) and ADR-014 (hierarchy)."""
128 +
129 + def _sample(self, limit=20000):
130 + wb = load_workbook(LEDGER_1404, read_only=True, data_only=True, keep_links=False)
131 + ws = wb["Source"]
132 + rows = ws.iter_rows(values_only=True)
133 + next(rows)
134 + header = next(rows)
135 + idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
136 + out = []
137 + for vals in rows:
138 + if not any(v is not None for v in vals):
139 + continue
140 + out.append((idx, vals))
141 + if len(out) >= limit:
142 + break
143 + wb.close()
144 + return out
145 +
146 + def test_hierarchy_invariant_on_sample(self):
147 + for idx, vals in self._sample():
148 + kol = vals[idx["kol"]]
149 + hesab = vals[idx["حساب"]]
150 + levels = ledger_to_pilot(kol=kol, hesab=hesab, row=0)
151 + assert levels.subsidiary_code == str(hesab).strip()
152 + assert levels.general_code == str(kol).strip()
153 +
154 + def test_debit_positive_sign_dominates(self):
155 + debit_pos = 0
156 + credit_pos = 0
157 + n = 0
158 + for idx, vals in self._sample():
159 + o = Decimal(str(vals[idx["OPENING"]] or 0))
160 + d = Decimal(str(vals[idx["Debit"]] or 0))
161 + c = Decimal(str(vals[idx["Credit"]] or 0))
162 + cl = Decimal(str(vals[idx["CLOSING"]] or 0))
163 + n += 1
164 + if o + d - c - cl == 0:
165 + debit_pos += 1
166 + if o - d + c - cl == 0:
167 + credit_pos += 1
168 + assert n > 0
169 + assert debit_pos >= credit_pos
170 + assert debit_pos >= 0.99 * n
171 + # And the domain control agrees with the chosen convention.
172 + rows = [BalanceRow(1, "x", Decimal(0), Decimal(0), Decimal(0), Decimal(0))]
173 + assert check_c01(rows).passed
docs/adr/ADR-012-money-scale-rounding.md new
+55
@@ -0,0 +1,55 @@
1 +# ADR-012 — Money scale, storage, and rounding (OD-03, P-02, D-03)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17)
4 +- Date: 2026-12-03
5 +- Supersedes: the implicit `Numeric(24, 4)` money storage in `models.py`.
6 +
7 +## Context
8 +
9 +`StatementLine.mapped_total` used `Numeric(24, 4)`. On SQLite (the default
10 +`sqlite:///` install) SQLAlchemy stores `Numeric` as **float**, silently rounding
11 +large rial amounts (debt D-03). Booklet P-02 forbids float anywhere and requires
12 +scaled-integer storage with `Decimal` in Python.
13 +
14 +## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`)
15 +
16 +- 252,898 data rows streamed; **zero fractional-rial cells** across
17 + `OPENING / Debit / Credit / CLOSING`.
18 +- Magnitudes reach ~1.08e16 rial (total debit == total credit ==
19 + 10,823,163,409,740,108), well within signed 64-bit (`BIGINT` ≈ 9.22e18).
20 +- Official statements (`data/official_statements/financial_1404.xlsx`) state
21 + **"(مبالغ به میلیون ریال)"** — amounts presented in **million rial**.
22 +
23 +## Decision
24 +
25 +1. **Storage scale = 0 (full integer rial).** Amounts persist as exact scaled
26 + integers in a `BIGINT` column via the `Rial` `TypeDecorator`
27 + (`backend/src/aram_backend/domain/money.py`); Python side is `Decimal`.
28 + `float` is rejected at bind time; fractional rial raises loudly (P-09).
29 + Works identically on SQLite and PostgreSQL.
30 +2. **No rounding in storage or calculation** (OD-03). Compute in full rial.
31 +3. **Display scale = million rial**, detected from the official statements.
32 + Rounding is **half-up**, only in the output layer, through the single central
33 + `round_half_up` function.
34 +4. **Rounding-difference allocation** uses the largest-remainder method
35 + (`allocate_remainder`) so displayed rows sum exactly to the displayed total;
36 + the allocation is deterministic and recorded.
37 +
38 +## Rejected options
39 +
40 +- `Numeric(24,4)` (float on SQLite) — silent rounding, violates P-02.
41 +- Storing million-rial directly — loses rial precision and contradicts OD-03
42 + ("store and calculate in full rial without rounding").
43 +- A non-zero scale — unnecessary; the canonical data has no fractional rial.
44 +
45 +## Acceptance / proof
46 +
47 +- Hypothesis property test: exact `Decimal -> BIGINT -> Decimal` round-trip for
48 + integers up to 18 digits (D-03).
49 +- `float` and fractional rial rejected.
50 +- `allocate_remainder` rows sum to `round_half_up(total)` for random inputs.
51 +
52 +## Dependency note (booklet section 19 requires an ADR for new dependencies)
53 +
54 +`hypothesis` is added to the `test` extra solely for the property-based tests
55 +mandated by booklet section 14. It is a test-only dependency, pinned.
docs/adr/ADR-013-sign-convention-closing.md new
+44
@@ -0,0 +1,44 @@
1 +# ADR-013 — Sign convention and meaning of closing (OD-02, C-01)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17)
4 +- Date: 2026-12-03
5 +
6 +## Context
7 +
8 +Booklet OD-02 defaults to debit-positive / credit-negative with
9 +`closing = opening + debit − credit`, and requires choosing the convention that
10 +satisfies C-01 on all rows and C-02/C-06 on the data — not guessing.
11 +
12 +## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`, 252,898 rows)
13 +
14 +| Convention | C-01 rows satisfied |
15 +|---|---|
16 +| **debit-positive**: `opening + debit − credit − closing = 0` | **252,892 / 252,898 (99.998%)** |
17 +| credit-positive: `opening − debit + credit − closing = 0` | 94,152 / 252,898 (37.2%) |
18 +
19 +- C-02 under debit-positive: total debit == total credit ==
20 + 10,823,163,409,740,108 rial; sum of closing == 0. **Holds.**
21 +- The 6 residual C-01 rows are recorded as data quirks to be reconciled in the
22 + Phase-1 golden comparison (OD-08), not silently corrected (P-01).
23 +
24 +## Decision
25 +
26 +- **Debit-positive, credit-negative.** `closing = opening + debit − credit`.
27 +- C-01 is evaluated per row as `opening + debit − credit − closing == 0`.
28 +- Credit-nature accounts (liabilities, equity, revenue) carry negative closing
29 + balances under this convention; the display layer applies the statement sign
30 + policy separately (the pilot engine already does this for BS/IS).
31 +- The 6 exceptional rows are surfaced, never auto-fixed; they belong in
32 + `docs/discrepancies.json` once the Phase-1 golden run characterizes them.
33 +
34 +## Rejected options
35 +
36 +- Credit-positive closing — fails C-01 on ~63% of canonical rows.
37 +- Per-account nature flipping before C-01 — unnecessary; the raw ledger already
38 + satisfies debit-positive C-01 almost universally.
39 +
40 +## Acceptance / proof
41 +
42 +- Unit tests: C-01 passes for debit-positive rows, fails for a flipped row.
43 +- Real-data evidence test (read-only, skipped if data absent) asserting the
44 + debit-positive pass rate dominates credit-positive.
docs/adr/ADR-014-hierarchy-mapping.md new
+55
@@ -0,0 +1,55 @@
1 +# ADR-014 — Ledger ↔ Pilot hierarchy mapping (OD-01, D-10)
2 +
3 +- Status: Accepted (evidence-based, booklet section 17 — default refuted)
4 +- Date: 2026-12-03
5 +
6 +## Context
7 +
8 +D-10: two namings for one hierarchy — ledger `T1..T4` vs Pilot
9 +`general / subsidiary / detail1..4` — with no documented mapping. OD-01 defaults
10 +to mapping ledger levels to Pilot levels in order and expects the reconstructed
11 +full code to equal the `حساب` column for 100% of rows.
12 +
13 +## Evidence (read-only probe of `data/source_ledgers/source_1404.xlsx`, 252,898 rows)
14 +
15 +- `حساب` is **always a 4-digit** code (e.g. `8348`); stored as integer.
16 +- `kol` is a **2-digit** general code (e.g. `14`); stored as integer.
17 +- `T1_CODE..T4_CODE` are auxiliary identifiers (e.g. `117001`,
18 + `22200000000899`, `0`, `0`) — **concatenating T1..T4 equals `حساب` for 0 rows.**
19 +- `AccountId == kol + حساب` for only **195,789 / 252,898 (~77%)**; it is
20 + unreliable (sometimes empty, sometimes a 14-digit code) and is **not used**.
21 +
22 +The OD-01 default is therefore **refuted**: `حساب` is the subsidiary leaf, not a
23 +concatenation of the T-codes.
24 +
25 +## Decision (evidence wins, section 17 rule 3)
26 +
27 +| Ledger column | Pilot level |
28 +|---|---|
29 +| `kol` | `general_code` |
30 +| `حساب` | `subsidiary_code` |
31 +| `T1_CODE` | `detail1_code` |
32 +| `T2_CODE` | `detail2_code` |
33 +| `T3_CODE` | `detail3_code` |
34 +| `T4_CODE` | `detail4_code` |
35 +
36 +- **Canonical account full code = `general_code + subsidiary_code`** (`kol + حساب`,
37 + 6 digits). Auxiliary detail codes are preserved as text attributes but do not
38 + change the canonical account identity.
39 +- All codes are text; leading zeros and length preserved (P-03). Integral numeric
40 + cells convert to text exactly (the canonical ledger stores codes as integers).
41 +- Verifiable invariant: for 100% of rows `subsidiary_code == حساب` and
42 + `general_code == kol`; `canonical_full_code == general + subsidiary`.
43 +
44 +## Rejected options
45 +
46 +- T1..T4 → general..detail4 in order with concatenation == `حساب` (the OD-01
47 + default) — 0/252,898 rows; refuted.
48 +- Using `AccountId` as the full code — only ~77% consistent; unreliable.
49 +
50 +## Acceptance / proof
51 +
52 +- Bidirectional conversion test (`ledger_to_pilot` / `pilot_to_ledger`) round-trips
53 + exactly (D-10).
54 +- Real-data evidence test (read-only, skipped if data absent): subsidiary == `حساب`
55 + and general == `kol` for 100% of streamed rows.