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
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,
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,
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"]