@davoodmehraban89 / Aram-1 / commits / eb9024a
Fork 0

feat(import): tolerant real-ledger import + statement-balance capture (Phase 4/5)

- Tolerant parse path (XLSX+CSV): reclassified rows with empty OPENING/Debit/ Credit/CLOSING are kept with exact zero; signed مانده صورت مالی stored as LedgerBalance.statement_balance (nullable Rial BIGINT, migration 20261203_06). Non-numeric money cells are skipped + reported (fail-loud, never invented); identity fields stay strictly required. Strict mode unchanged. - statement_build uses the effective balance: statement_balance rows contribute their pre-signed figure directly (reproduces Phase-4 golden); ordinary closing rows get the ADR-013 section sign. drill_down exposes effective/statement balance. - API upload uses tolerant import and returns skipped_rows for transparency. - 4 new tests (reclassified kept, anomaly skipped+reported, strict fails loud, statement_balance drives build + raw-row drill-down). Full suite: 285 passed. Real-data proof: source_1404.xlsx -> 131,280 raw rows imported, 4 anomalies reported; note->map->build->drill-down traced to exact source rows. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 11:12 UTC eb9024a8f0133c29d327e3ef76ba13ba2c3fdb76
7 files changed +357 -12
backend/migrations/versions/20261203_06_statement_balance.py new
+48
@@ -0,0 +1,48 @@
1 +"""Preserve the signed statement balance (مانده صورت مالی) on raw ledger rows.
2 +
3 +Reclassified source rows carry only the signed statement-balance figure and leave
4 +OPENING/Debit/Credit/CLOSING empty. The tolerant import keeps those rows (exact
5 +zero for the empty money cells) and stores the statement balance here so the
6 +compute layer can build statements that reconcile rial-for-rial with the official
7 +workbooks (Phase 4 golden). Nullable BIGINT via the Rial type (P-02 exact rial).
8 +
9 +Revision ID: 20261203_06
10 +Revises: 20261203_05
11 +"""
12 +
13 +import sqlalchemy as sa
14 +from alembic import op
15 +
16 +from aram_backend.db_triggers import install_triggers
17 +
18 +revision = "20261203_06"
19 +down_revision = "20261203_05"
20 +branch_labels = None
21 +depends_on = None
22 +
23 +
24 +def _has_column(bind) -> bool:
25 + inspector = sa.inspect(bind)
26 + if "ledger_balances" not in inspector.get_table_names():
27 + return False
28 + return any(c["name"] == "statement_balance" for c in inspector.get_columns("ledger_balances"))
29 +
30 +
31 +def upgrade() -> None:
32 + bind = op.get_bind()
33 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
34 + return
35 + if not _has_column(bind):
36 + with op.batch_alter_table("ledger_balances") as batch:
37 + batch.add_column(sa.Column("statement_balance", sa.BigInteger(), nullable=True))
38 + install_triggers(bind)
39 +
40 +
41 +def downgrade() -> None:
42 + bind = op.get_bind()
43 + if "ledger_balances" not in sa.inspect(bind).get_table_names():
44 + return
45 + if _has_column(bind):
46 + with op.batch_alter_table("ledger_balances") as batch:
47 + batch.drop_column("statement_balance")
48 + install_triggers(bind)
backend/src/aram_backend/ledger_parser.py
+124 -7
@@ -34,6 +34,15 @@ class LedgerRecord:
34 debit: Decimal
35 credit: Decimal
36 closing: Decimal
37 + statement_balance: Decimal | None = None
38 +
39 +
40 +@dataclass(frozen=True)
41 +class SkippedRow:
42 + """A source row that could not be imported, with the reason (fail-loud report)."""
43 +
44 + row_number: int
45 + reason: str
46
47
48 class LedgerParseError(ValueError):
@@ -55,15 +64,23 @@ _FIELDS = {
64 "closing": "CLOSING",
65 }
66
67 +_STATEMENT_BALANCE_HEADER = "مانده صورت مالی"
68 +
69 _CSV_ENCODINGS = ("utf-8-sig", "utf-8", "cp1256")
70
71
61 -def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
72 +def parse_general_ledger(
73 + content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None
74 +) -> Iterator[LedgerRecord]:
75 """Stream typed XLSX ledger rows without persisting or calculating values.
76
77 Codes are normalized as text (leading zeros preserved, P-03/D-04) and money
78 is decoded to exact Decimal via the shortest round-trip repr (D-04). Header
79 matching is Persian-normalized (D-05).
80 +
81 + With ``tolerant=True`` (real-ledger import) reclassified rows whose money
82 + cells are empty are kept with exact zero, ``مانده صورت مالی`` is captured as
83 + ``statement_balance``, and anomalous rows are skipped into ``skipped``.
84 """
85 inspection = inspect_xlsx(content, document_type="general_ledger")
86 workbook = load_workbook(BytesIO(content), read_only=True, data_only=True, keep_links=False)
@@ -82,23 +99,38 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
99 if value is not None
100 }
101 kol_index = indexes.get(normalize_fa("kol"))
102 + statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER))
103 for row_number, values in enumerate(
104 worksheet.iter_rows(min_row=inspection.header_row + 1, values_only=True),
105 start=inspection.header_row + 1,
106 ):
107 if not any(value is not None for value in values):
108 continue
91 - yield _build_record(values, indexes, kol_index, row_number)
109 + if tolerant:
110 + record, skip = _build_record_tolerant(
111 + values, indexes, kol_index, statement_index, row_number
112 + )
113 + if skip is not None:
114 + if skipped is not None:
115 + skipped.append(skip)
116 + continue
117 + if record is not None:
118 + yield record
119 + else:
120 + yield _build_record(values, indexes, kol_index, row_number)
121 finally:
122 workbook.close()
123
124
96 -def parse_general_ledger_csv(content: bytes) -> Iterator[LedgerRecord]:
125 +def parse_general_ledger_csv(
126 + content: bytes, *, tolerant: bool = False, skipped: list[SkippedRow] | None = None
127 +) -> Iterator[LedgerRecord]:
128 """Stream typed CSV ledger rows (D-06, booklet §8).
129
130 Supports UTF-8, UTF-8-BOM and Windows-1256; sniffs the delimiter; applies the
131 same Persian normalization and exact-money rules as the XLSX path. Reading is
132 streaming (csv.reader over the decoded text), never materializing all rows.
133 + With ``tolerant=True`` the same reclassified-row handling as XLSX applies.
134 """
135 text = _decode_csv(content)
136 sample = text[:4096]
@@ -116,19 +148,37 @@ def parse_general_ledger_csv(content: bytes) -> Iterator[LedgerRecord]:
148 if missing:
149 raise LedgerParseError(f"CSV ledger is missing required headers: {sorted(missing)}")
150 kol_index = indexes.get(normalize_fa("kol"))
151 + statement_index = indexes.get(normalize_fa(_STATEMENT_BALANCE_HEADER))
152 for row_number, values in enumerate(reader, start=2):
153 if not any(value.strip() for value in values):
154 continue
122 - yield _build_record(values, indexes, kol_index, row_number)
155 + if tolerant:
156 + record, skip = _build_record_tolerant(
157 + values, indexes, kol_index, statement_index, row_number
158 + )
159 + if skip is not None:
160 + if skipped is not None:
161 + skipped.append(skip)
162 + continue
163 + if record is not None:
164 + yield record
165 + else:
166 + yield _build_record(values, indexes, kol_index, row_number)
167
168
125 -def parse_ledger(content: bytes, filename: str) -> Iterator[LedgerRecord]:
169 +def parse_ledger(
170 + content: bytes,
171 + filename: str,
172 + *,
173 + tolerant: bool = False,
174 + skipped: list[SkippedRow] | None = None,
175 +) -> Iterator[LedgerRecord]:
176 """Route to the XLSX or CSV parser by file extension (D-06)."""
177 lower = filename.lower()
178 if lower.endswith(".csv"):
129 - return parse_general_ledger_csv(content)
179 + return parse_general_ledger_csv(content, tolerant=tolerant, skipped=skipped)
180 if lower.endswith(".xlsx"):
131 - return parse_general_ledger(content)
181 + return parse_general_ledger(content, tolerant=tolerant, skipped=skipped)
182 raise LedgerParseError("only .xlsx and .csv ledger files are supported")
183
184
@@ -168,6 +218,73 @@ def _build_record(values, indexes, kol_index, row_number) -> LedgerRecord:
218 )
219
220
221 +def _build_record_tolerant(
222 + values, indexes, kol_index, statement_index, row_number
223 +) -> tuple[LedgerRecord | None, SkippedRow | None]:
224 + """Build a record for real-ledger import.
225 +
226 + Reclassified source rows carry only ``مانده صورت مالی`` and leave the
227 + OPENING/Debit/Credit/CLOSING cells empty; those are stored as exact zero
228 + (the row is preserved for drill-down, D3). A *non-numeric* money cell is a
229 + genuine anomaly: the row is skipped and reported (fail-loud, never invented).
230 + Identity fields (account code/name/year/type) remain strictly required.
231 + """
232 +
233 + def value(field: str):
234 + i = indexes[normalize_fa(_FIELDS[field])]
235 + return values[i] if i < len(values) else None
236 +
237 + def money(field: str, header: str) -> Decimal:
238 + raw = value(field)
239 + if raw is None or (isinstance(raw, str) and not raw.strip()):
240 + return Decimal(0)
241 + return _required_decimal(raw, row_number, header)
242 +
243 + try:
244 + account_code = _required_code(value("account_code"), row_number, "حساب")
245 + account_name = _required_text(value("account_name"), row_number, "ACCOUNT_NAME")
246 + source_year = _required_year(value("source_year"), row_number)
247 + entry_type = _required_text(value("entry_type"), row_number, "نوع")
248 + opening = money("opening", "OPENING")
249 + debit = money("debit", "Debit")
250 + credit = money("credit", "Credit")
251 + closing = money("closing", "CLOSING")
252 + except LedgerParseError as exc:
253 + return None, SkippedRow(row_number=row_number, reason=str(exc))
254 +
255 + statement_balance: Decimal | None = None
256 + if statement_index is not None and statement_index < len(values):
257 + raw = values[statement_index]
258 + if raw is not None and not (isinstance(raw, str) and not raw.strip()):
259 + try:
260 + statement_balance = _required_decimal(raw, row_number, _STATEMENT_BALANCE_HEADER)
261 + except LedgerParseError:
262 + statement_balance = None
263 +
264 + record = LedgerRecord(
265 + row_number=row_number,
266 + account_code=account_code,
267 + general_code=(
268 + _optional_code(values[kol_index], row_number, "kol")
269 + if kol_index is not None and kol_index < len(values)
270 + else None
271 + ),
272 + account_name=account_name,
273 + source_year=source_year,
274 + entry_type=entry_type,
275 + t1_code=_optional_code(value("t1_code"), row_number, "T1_CODE"),
276 + t2_code=_optional_code(value("t2_code"), row_number, "T2_CODE"),
277 + t3_code=_optional_code(value("t3_code"), row_number, "T3_CODE"),
278 + t4_code=_optional_code(value("t4_code"), row_number, "T4_CODE"),
279 + opening=opening,
280 + debit=debit,
281 + credit=credit,
282 + closing=closing,
283 + statement_balance=statement_balance,
284 + )
285 + return record, None
286 +
287 +
288 def _required_text(value: object, row_number: int, field: str) -> str:
289 text = normalize_fa(str(value)) if value is not None else ""
290 if not text:
backend/src/aram_backend/models.py
+1
@@ -203,6 +203,7 @@ class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
203 debit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
204 credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
205 closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
206 + statement_balance: Mapped[Decimal | None] = mapped_column(Rial(), nullable=True, default=None)
207 entry_type: Mapped[str] = mapped_column(String(32), default="")
208
209
backend/src/aram_backend/services/ledger_import.py
+1
@@ -66,6 +66,7 @@ def import_ledger_balances(
66 debit=record.debit,
67 credit=record.credit,
68 closing=record.closing,
69 + statement_balance=record.statement_balance,
70 entry_type=record.entry_type,
71 )
72 )
backend/src/aram_backend/services/statement_build.py
+34 -3
@@ -70,6 +70,18 @@ class BuildResult:
70 unmapped_accounts: tuple[str, ...]
71
72
73 +def _effective_balance(balance: LedgerBalance) -> Decimal:
74 + """The figure that contributes to a statement line.
75 +
76 + Reclassified source rows carry only ``مانده صورت مالی`` (statement_balance)
77 + and leave CLOSING empty; that signed figure is authoritative for statement
78 + presentation (Phase 4 golden). Ordinary rows use the debit-positive closing.
79 + """
80 + if balance.statement_balance is not None:
81 + return balance.statement_balance
82 + return balance.closing
83 +
84 +
85 def _latest_import_version(session: Session, year_id: int) -> int | None:
86 return session.scalar(
87 select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
@@ -129,16 +141,29 @@ def build_statements(
141 for rule in rules:
142 account_to_notes.setdefault(rule.account_code, []).append(rule.target_note_id)
143
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 + note_sign: dict[int, int] = {}
148 + for note in notes.values():
149 + stype_code = str(note.configuration_json.get("statement") or "")
150 + section = str(note.configuration_json.get("section") or "")
151 + note_sign[note.id] = SECTION_POLICY.get(stype_code, {}).get(section, 1)
152 +
153 note_totals: dict[int, Decimal] = {}
154 unmapped: list[str] = []
155 for balance in balances:
156 targets = account_to_notes.get(balance.account_full_code, [])
157 if not targets:
137 - if any(getattr(balance, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
158 + if _effective_balance(balance) != _ZERO:
159 unmapped.append(balance.account_full_code)
160 continue
161 for note_id in targets:
141 - note_totals[note_id] = note_totals.get(note_id, _ZERO) + balance.closing
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
166 + note_totals[note_id] = note_totals.get(note_id, _ZERO) + contribution
167
168 built: list[FinancialStatement] = []
169 for stype_code in statement_types:
@@ -173,7 +198,9 @@ def build_statements(
198 raise StatementBuildError(
199 f"note {note.note_number}: section '{section}' has no sign policy for {stype_code}"
200 )
176 - total = sign * note_totals.get(note.id, _ZERO)
201 + # note_totals already carries the presentation sign (statement_balance
202 + # rows are pre-signed; closing rows were signed during accumulation).
203 + total = note_totals.get(note.id, _ZERO)
204 session.add(
205 StatementLine(
206 statement_id=statement.id,
@@ -221,6 +248,10 @@ def drill_down(session: Session, statement_line_id: int) -> dict[str, object]:
248 "account_full_code": balance.account_full_code,
249 "account_name": balance.account_name,
250 "closing": str(balance.closing),
251 + "statement_balance": str(balance.statement_balance)
252 + if balance.statement_balance is not None
253 + else None,
254 + "effective_balance": str(_effective_balance(balance)),
255 "source": {
256 "filename": source.filename if source else None,
257 "file_hash": source.file_hash if source else None,
backend/src/aram_backend/statement_api.py
+4 -2
@@ -17,7 +17,7 @@ from aram_backend.config import get_settings
17 from aram_backend.database import get_session
18 from aram_backend.domain.controls import BalanceRow, run_controls
19 from aram_backend.ingestion import SourceRegistrationError, register_source_document
20 -from aram_backend.ledger_parser import LedgerParseError, parse_ledger
20 +from aram_backend.ledger_parser import LedgerParseError, SkippedRow, parse_ledger
21 from aram_backend.models import (
22 Company,
23 FinancialStatement,
@@ -116,10 +116,11 @@ def upload_ledger(
116 except (SourceRegistrationError, SourceStoreError) as exc:
117 raise HTTPException(status_code=422, detail=str(exc)) from exc
118
119 + skipped: list[SkippedRow] = []
120 try:
121 records = [
122 rec
122 - for rec in parse_ledger(content, file.filename or "ledger.xlsx")
123 + for rec in parse_ledger(content, file.filename or "ledger.xlsx", tolerant=True, skipped=skipped)
124 if rec.source_year == year.year
125 ]
126 except LedgerParseError as exc:
@@ -148,6 +149,7 @@ def upload_ledger(
149 "import_version": next_version,
150 "accounts_imported": count,
151 "rows_for_year": len(records),
152 + "skipped_rows": [{"row": s.row_number, "reason": s.reason} for s in skipped],
153 }
154
155
backend/tests/test_tolerant_import.py new
+145
@@ -0,0 +1,145 @@
1 +"""Tolerant real-ledger import: reclassified rows preserved, anomalies reported.
2 +
3 +Proves D3/P-01 (raw rows kept for drill-down) and the Phase-4 statement-balance
4 +capture: empty money cells on reclassified rows become exact zero, the signed
5 +``مانده صورت مالی`` is stored, and a non-numeric money cell is skipped + reported
6 +(fail-loud, never invented).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from decimal import Decimal
12 +
13 +import pytest
14 +
15 +from aram_backend.ledger_parser import SkippedRow, parse_ledger
16 +from aram_backend.models import LedgerBalance
17 +from aram_backend.services.ledger_import import import_ledger_balances
18 +from aram_backend.services.statement_build import build_statements
19 +
20 +# Column order matches _FIELDS plus the optional statement-balance column.
21 +_COLUMNS = [
22 + "حساب",
23 + "ACCOUNT_NAME",
24 + "year",
25 + "نوع",
26 + "kol",
27 + "T1_CODE",
28 + "T2_CODE",
29 + "T3_CODE",
30 + "T4_CODE",
31 + "OPENING",
32 + "Debit",
33 + "Credit",
34 + "CLOSING",
35 + "مانده صورت مالی",
36 +]
37 +
38 +
39 +def _row(**fields: str) -> str:
40 + return ",".join(fields.get(col, "") for col in _COLUMNS)
41 +
42 +
43 +def _csv(rows: list[str]) -> bytes:
44 + return ("\n".join([",".join(_COLUMNS), *rows]) + "\n").encode("utf-8")
45 +
46 +
47 +_BASE = {"حساب": "1101", "ACCOUNT_NAME": "نقد و بانک", "year": "1404", "نوع": "e", "kol": "11"}
48 +
49 +
50 +def test_reclassified_row_kept_with_statement_balance():
51 + content = _csv([_row(**_BASE, **{"مانده صورت مالی": "-52400000000000"})])
52 + skipped: list[SkippedRow] = []
53 + records = list(parse_ledger(content, "ledger.csv", tolerant=True, skipped=skipped))
54 + assert len(records) == 1
55 + rec = records[0]
56 + assert rec.opening == Decimal(0)
57 + assert rec.closing == Decimal(0)
58 + assert rec.statement_balance == Decimal("-52400000000000")
59 + assert skipped == []
60 +
61 +
62 +def test_non_numeric_money_row_skipped_and_reported():
63 + content = _csv([_row(**_BASE, Debit="abc", Credit="0", CLOSING="0", OPENING="0")])
64 + skipped: list[SkippedRow] = []
65 + records = list(parse_ledger(content, "ledger.csv", tolerant=True, skipped=skipped))
66 + assert records == []
67 + assert len(skipped) == 1
68 + assert skipped[0].row_number == 2
69 + assert "Debit" in skipped[0].reason
70 +
71 +
72 +def test_strict_mode_still_fails_loud():
73 + content = _csv([_row(**_BASE, **{"مانده صورت مالی": "-52400000000000"})])
74 + with pytest.raises(ValueError):
75 + list(parse_ledger(content, "ledger.csv"))
76 +
77 +
78 +def test_statement_balance_drives_build_and_drilldown(session):
79 + from aram_backend.models import Company, FiscalYear, MappingRule, NoteDefinition, SourceDocument
80 +
81 + company = Company(code="T1", name="شرکت آزمون")
82 + session.add(company)
83 + session.flush()
84 + year = FiscalYear(company_id=company.id, year=1404)
85 + session.add(year)
86 + session.flush()
87 + year_id = year.id
88 +
89 + content = _csv(
90 + [
91 + _row(**_BASE, **{"مانده صورت مالی": "-673740637000000"}),
92 + _row(
93 + **{**_BASE, "حساب": "1102"}, OPENING="0", Debit="0", Credit="0", CLOSING="1000000"
94 + ),
95 + ]
96 + )
97 + records = list(parse_ledger(content, "ledger.csv", tolerant=True))
98 + src = SourceDocument(
99 + year_id=year_id, filename="ledger.csv", document_type="general_ledger", file_hash="h" * 64
100 + )
101 + session.add(src)
102 + session.flush()
103 + import_ledger_balances(
104 + session, year_id=year_id, source_document_id=src.id, records=records, import_version=1
105 + )
106 +
107 + note = NoteDefinition(
108 + year_id=year_id,
109 + note_number="10",
110 + title="دارایی‌های جاری",
111 + configuration_json={"statement": "BS", "section": "Assets"},
112 + )
113 + session.add(note)
114 + session.flush()
115 + session.add(
116 + MappingRule(
117 + year_id=year_id,
118 + rule_key="111101->n",
119 + account_code="111101",
120 + target_note_id=note.id,
121 + mapping_type="closing",
122 + )
123 + )
124 + session.add(
125 + MappingRule(
126 + year_id=year_id,
127 + rule_key="111102->n",
128 + account_code="111102",
129 + target_note_id=note.id,
130 + mapping_type="closing",
131 + )
132 + )
133 + session.flush()
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")
140 +
141 + rows = session.query(LedgerBalance).filter_by(year_id=year_id).all()
142 + assert len(rows) == 2 # raw rows preserved, not aggregated
143 + reclassified = next(r for r in rows if r.subsidiary_code == "1101")
144 + assert reclassified.statement_balance == Decimal("-673740637000000")
145 + assert reclassified.source_row == 2