@davoodmehraban89 / Aram / commits / f7c3b4a
Fork 0

fix(ledger): store RAW rows for drill-down, aggregate in compute layer (audit #2, D3/P-01)

- ledger_import: one LedgerBalance per source row (no import-time aggregation); source_row preserved so every figure traces to file/sheet/row (D3) - LedgerBalance uniqueness -> (year_id, source_document_id, source_row, import_version) - NEW services/ledger_aggregate: account-level totals via exact Decimal summation in the compute layer (latest import version) - unknown_accounts now aggregates raw rows by account (dedupe + row_count) - Migration 20261203_05 swaps the constraint on existing DBs + reinstalls triggers; fresh DBs get it from the live model. Round-trip verified, triggers preserved. - Test updated: duplicate accounts stored as 2 raw rows, aggregated in service. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 10:15 UTC f7c3b4a46e2e788c8b28aec1b90c7ea053e45754
6 files changed +205 -78
backend/migrations/versions/20261203_05_raw_ledger_rows.py new
+60
@@ -0,0 +1,60 @@
1 +"""Raw ledger rows: uniqueness per source row instead of per account (D3, P-01).
2 +
3 +LedgerBalance now stores one row per source ledger row (no import-time
4 +aggregation) so drill-down to file/sheet/row is preserved. Fresh databases get the
5 +new constraint from the live model; this revision swaps it on pre-existing DBs and
6 +reinstalls the D-07 triggers (batch-alter recreates the table).
7 +
8 +Revision ID: 20261203_05
9 +Revises: 20261203_04
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 = "20261203_05"
18 +down_revision = "20261203_04"
19 +branch_labels = None
20 +depends_on = None
21 +
22 +_OLD = "uq_ledger_balance_year_code_version"
23 +_NEW = "uq_ledger_balance_year_source_row_version"
24 +_NEW_COLS = ["year_id", "source_document_id", "source_row", "import_version"]
25 +_OLD_COLS = ["year_id", "account_full_code", "import_version"]
26 +
27 +
28 +def _unique_names(bind) -> set:
29 + inspector = sa.inspect(bind)
30 + if "ledger_balances" not in inspector.get_table_names():
31 + return set()
32 + return {c["name"] for c in inspector.get_unique_constraints("ledger_balances")}
33 +
34 +
35 +def upgrade() -> None:
36 + bind = op.get_bind()
37 + names = _unique_names(bind)
38 + if not names and "ledger_balances" not in sa.inspect(bind).get_table_names():
39 + return
40 + if _OLD in names or _NEW not in names:
41 + with op.batch_alter_table("ledger_balances") as batch:
42 + if _OLD in names:
43 + batch.drop_constraint(_OLD, type_="unique")
44 + if _NEW not in names:
45 + batch.create_unique_constraint(_NEW, _NEW_COLS)
46 + install_triggers(bind)
47 +
48 +
49 +def downgrade() -> None:
50 + bind = op.get_bind()
51 + names = _unique_names(bind)
52 + if not names and "ledger_balances" not in sa.inspect(bind).get_table_names():
53 + return
54 + if _NEW in names or _OLD not in names:
55 + with op.batch_alter_table("ledger_balances") as batch:
56 + if _NEW in names:
57 + batch.drop_constraint(_NEW, type_="unique")
58 + if _OLD not in names:
59 + batch.create_unique_constraint(_OLD, _OLD_COLS)
60 + install_triggers(bind)
backend/src/aram_backend/models.py
+8 -5
@@ -165,18 +165,21 @@ class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
165 """Persisted account balance from a source ledger import (D-01, booklet §5).
166
167 Money is exact integer rial via the ``Rial`` TypeDecorator (P-02). Codes are
168 - text (P-03). One row per ``(year_id, account_full_code, import_version)``;
169 - a new import for a Draft year creates a new version rather than mutating the
170 - previous one. Full immutability triggers are delivered with D-07/Phase 7.
168 + text (P-03). **One row per source ledger row** (raw, never aggregated on
169 + import) so every figure drills down to its exact file/sheet/row (D3, P-01).
170 + Unique per ``(year_id, source_document_id, source_row, import_version)``; a new
171 + import for a Draft year creates a new version rather than mutating the prior
172 + snapshot. Account-level totals are computed in the service layer.
173 """
174
175 __tablename__ = "ledger_balances"
176 __table_args__ = (
177 UniqueConstraint(
178 "year_id",
177 - "account_full_code",
179 + "source_document_id",
180 + "source_row",
181 "import_version",
179 - name="uq_ledger_balance_year_code_version",
182 + name="uq_ledger_balance_year_source_row_version",
183 ),
184 CheckConstraint("import_version > 0", name="positive_import_version"),
185 CheckConstraint("source_row > 0", name="positive_source_row"),
backend/src/aram_backend/services/ledger_aggregate.py new
+83
@@ -0,0 +1,83 @@
1 +"""Account-level aggregation over raw ledger rows (compute layer, D3/P-01).
2 +
3 +Raw LedgerBalance rows are stored one-per-source-row (never collapsed on import).
4 +Account totals are derived here, in the compute layer, by exact Decimal summation
5 +of the latest import version. This keeps drill-down intact while giving the
6 +statement/preflight/mapping services the account-level figures they need.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from dataclasses import dataclass
12 +from decimal import Decimal
13 +
14 +from sqlalchemy import func, select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import LedgerBalance
18 +
19 +_ZERO = Decimal(0)
20 +
21 +
22 +@dataclass(frozen=True)
23 +class AccountTotal:
24 + account_full_code: str
25 + account_name: str
26 + opening: Decimal
27 + debit: Decimal
28 + credit: Decimal
29 + closing: Decimal
30 + row_count: int
31 + first_source_row: int
32 +
33 +
34 +def latest_import_version(session: Session, year_id: int) -> int | None:
35 + return session.scalar(
36 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
37 + )
38 +
39 +
40 +def latest_raw_rows(session: Session, year_id: int) -> list[LedgerBalance]:
41 + version = latest_import_version(session, year_id)
42 + if version is None:
43 + return []
44 + return list(
45 + session.scalars(
46 + select(LedgerBalance)
47 + .where(LedgerBalance.year_id == year_id, LedgerBalance.import_version == version)
48 + .order_by(LedgerBalance.source_row)
49 + ).all()
50 + )
51 +
52 +
53 +def aggregate_by_account(session: Session, year_id: int) -> dict[str, AccountTotal]:
54 + """Sum raw rows per canonical account (exact Decimal, no rounding)."""
55 + totals: dict[str, AccountTotal] = {}
56 + for row in latest_raw_rows(session, year_id):
57 + existing = totals.get(row.account_full_code)
58 + if existing is None:
59 + totals[row.account_full_code] = AccountTotal(
60 + account_full_code=row.account_full_code,
61 + account_name=row.account_name,
62 + opening=row.opening,
63 + debit=row.debit,
64 + credit=row.credit,
65 + closing=row.closing,
66 + row_count=1,
67 + first_source_row=row.source_row,
68 + )
69 + else:
70 + totals[row.account_full_code] = AccountTotal(
71 + account_full_code=existing.account_full_code,
72 + account_name=existing.account_name,
73 + opening=existing.opening + row.opening,
74 + debit=existing.debit + row.debit,
75 + credit=existing.credit + row.credit,
76 + closing=existing.closing + row.closing,
77 + row_count=existing.row_count + 1,
78 + first_source_row=min(existing.first_source_row, row.source_row),
79 + )
80 + return totals
81 +
82 +
83 +__all__ = ["AccountTotal", "aggregate_by_account", "latest_import_version", "latest_raw_rows"]
backend/src/aram_backend/services/ledger_import.py
+24 -44
@@ -1,17 +1,18 @@
1 -"""Persist parsed ledger rows as exact LedgerBalance records (D-01).
1 +"""Persist parsed ledger rows as RAW LedgerBalance records (D-01, D3, P-01).
2
3 -One balance row per ``(year_id, account_full_code, import_version)``. Rows that
4 -share an account are aggregated by exact Decimal summation (no float, no
5 -rounding). The canonical account identity is ``general + subsidiary`` (ADR-014).
6 -The caller owns the transaction. Full-ledger semantics (entry-type filtering,
7 -None-money handling, lineage edges) are delivered in Phase 1; this service is the
8 -Phase-0 persistence foundation proven by a small-sample exact round-trip.
3 +One LedgerBalance row per source ledger row, preserving ``source_row`` so every
4 +figure is traceable to its exact origin (file/sheet/row). **No aggregation happens
5 +here** — aggregation is a compute-layer concern (see ``ledger_aggregate`` and the
6 +statement/preflight services). This preserves drill-down (D3) and the sacred-source
7 +principle (P-01): raw rows are never collapsed or rewritten on the way in.
8 +
9 +The canonical account identity is ``general + subsidiary`` (ADR-014). The caller
10 +owns the transaction.
11 """
12
13 from __future__ import annotations
14
15 from collections.abc import Iterable
14 -from decimal import Decimal
16
17 from sqlalchemy.orm import Session
18
@@ -19,8 +20,6 @@ from aram_backend.domain.hierarchy import canonical_full_code, ledger_to_pilot
20 from aram_backend.ledger_parser import LedgerRecord
21 from aram_backend.models import LedgerBalance
22
22 -_ZERO = Decimal(0)
23 -
23
24 def import_ledger_balances(
25 session: Session,
@@ -31,13 +30,13 @@ def import_ledger_balances(
30 source_sheet: str = "Source",
31 import_version: int = 1,
32 ) -> int:
34 - """Aggregate parsed records by account and persist exact balances.
33 + """Persist each parsed record as a distinct raw row; return the row count.
34
36 - Returns the number of distinct account balances written. Raises on a
37 - uniqueness conflict (re-using an import version); a new import for a Draft
38 - year must use a new ``import_version``.
35 + Raises on a uniqueness conflict (re-importing the same source rows under the
36 + same import version). A new import for a Draft year uses a new
37 + ``import_version``; prior versions remain immutable snapshots.
38 """
40 - aggregated: dict[str, dict[str, object]] = {}
39 + count = 0
40 for record in records:
41 levels = ledger_to_pilot(
42 kol=record.general_code,
@@ -48,50 +47,31 @@ def import_ledger_balances(
47 t4=record.t4_code,
48 row=record.row_number,
49 )
51 - full_code = canonical_full_code(levels)
52 - bucket = aggregated.get(full_code)
53 - if bucket is None:
54 - aggregated[full_code] = {
55 - "levels": levels,
56 - "account_name": record.account_name,
57 - "entry_type": record.entry_type,
58 - "source_row": record.row_number,
59 - "opening": record.opening,
60 - "debit": record.debit,
61 - "credit": record.credit,
62 - "closing": record.closing,
63 - }
64 - else:
65 - for key in ("opening", "debit", "credit", "closing"):
66 - bucket[key] = bucket[key] + getattr(record, key) # type: ignore[operator]
67 - bucket["source_row"] = min(bucket["source_row"], record.row_number) # type: ignore[type-var]
68 -
69 - for full_code, bucket in aggregated.items():
70 - levels = bucket["levels"]
50 session.add(
51 LedgerBalance(
52 year_id=year_id,
53 source_document_id=source_document_id,
54 source_sheet=source_sheet,
76 - source_row=bucket["source_row"],
55 + source_row=record.row_number,
56 import_version=import_version,
78 - account_full_code=full_code,
57 + account_full_code=canonical_full_code(levels),
58 general_code=levels.general_code,
59 subsidiary_code=levels.subsidiary_code,
60 detail1_code=levels.detail1_code,
61 detail2_code=levels.detail2_code,
62 detail3_code=levels.detail3_code,
63 detail4_code=levels.detail4_code,
85 - account_name=bucket["account_name"],
86 - opening=bucket["opening"],
87 - debit=bucket["debit"],
88 - credit=bucket["credit"],
89 - closing=bucket["closing"],
90 - entry_type=bucket["entry_type"],
64 + account_name=record.account_name,
65 + opening=record.opening,
66 + debit=record.debit,
67 + credit=record.credit,
68 + closing=record.closing,
69 + entry_type=record.entry_type,
70 )
71 )
72 + count += 1
73 session.flush()
94 - return len(aggregated)
74 + return count
75
76
77 __all__ = ["import_ledger_balances"]
backend/src/aram_backend/services/mapping_workflow.py
+11 -24
@@ -10,16 +10,16 @@ from __future__ import annotations
10 from dataclasses import dataclass
11 from decimal import Decimal
12
13 -from sqlalchemy import func, select
13 +from sqlalchemy import select
14 from sqlalchemy.orm import Session
15
16 from aram_backend.models import (
17 FiscalYear,
18 FiscalYearStatus,
19 - LedgerBalance,
19 MappingRule,
20 NoteDefinition,
21 )
22 +from aram_backend.services.ledger_aggregate import aggregate_by_account
23
24 _ZERO = Decimal(0)
25
@@ -28,37 +28,24 @@ class CarryForwardError(ValueError):
28 """Raised when carry-forward is attempted on an invalid state."""
29
30
31 -def _latest_balances(session: Session, year_id: int) -> list[LedgerBalance]:
32 - version = session.scalar(
33 - select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
34 - )
35 - if version is None:
36 - return []
37 - return list(
38 - session.scalars(
39 - select(LedgerBalance).where(
40 - LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
41 - )
42 - ).all()
43 - )
44 -
45 -
31 def unknown_accounts(session: Session, year_id: int) -> list[dict]:
32 + """Active accounts with no mapping, aggregated from raw rows (compute layer)."""
33 mapped = {
34 r.account_code
35 for r in session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
36 }
37 queue = []
52 - for balance in _latest_balances(session, year_id):
53 - if balance.account_full_code in mapped:
38 + for code, total in aggregate_by_account(session, year_id).items():
39 + if code in mapped:
40 continue
55 - if any(getattr(balance, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
41 + if any(getattr(total, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
42 queue.append(
43 {
58 - "account_full_code": balance.account_full_code,
59 - "account_name": balance.account_name,
60 - "closing": str(balance.closing),
61 - "source_row": balance.source_row,
44 + "account_full_code": code,
45 + "account_name": total.account_name,
46 + "closing": str(total.closing),
47 + "source_row": total.first_source_row,
48 + "row_count": total.row_count,
49 }
50 )
51 queue.sort(key=lambda item: item["account_full_code"])
backend/tests/test_ledger_balance.py
+19 -5
@@ -142,17 +142,31 @@ class TestLedgerBalanceImport:
142 assert isinstance(raw, int)
143 assert raw == int(big)
144
145 - def test_duplicate_accounts_aggregated(self, session):
145 + def test_duplicate_accounts_stored_raw_and_aggregated_in_service(self, session):
146 + # D3/P-01: raw rows are preserved (one per source row); aggregation is a
147 + # compute-layer concern, never done on import.
148 + from aram_backend.services.ledger_aggregate import aggregate_by_account
149 +
150 year = _make_year(session)
151 content = _ledger_bytes(
152 _row("8348", "14", debit=100, closing=100),
153 _row("8348", "14", debit=200, closing=200),
154 )
155 count = _import(session, year, content)
152 - assert count == 1
153 - balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
154 - assert balance.debit == Decimal(300)
155 - assert balance.closing == Decimal(300)
156 + assert count == 2 # two raw rows, NOT collapsed
157 + rows = (
158 + session.query(LedgerBalance)
159 + .filter_by(year_id=year.id)
160 + .order_by(LedgerBalance.source_row)
161 + .all()
162 + )
163 + assert [r.source_row for r in rows] == [3, 4]
164 + assert [r.debit for r in rows] == [Decimal(100), Decimal(200)]
165 + # Aggregation happens in the service layer.
166 + totals = aggregate_by_account(session, year.id)
167 + assert totals["148348"].debit == Decimal(300)
168 + assert totals["148348"].closing == Decimal(300)
169 + assert totals["148348"].row_count == 2
170
171 def test_uniqueness_per_import_version(self, session):
172 year = _make_year(session)