@davoodmehraban89 / Aram-2 Mirror · read-only / commits / a3c330b
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 4, 14:15 UTC

feat(db): LedgerBalance model + exact-rial money column (D-01, D-03)

- LedgerBalance: year-isolated, source-linked, text hierarchy codes, opening/ debit/credit/closing as Rial BIGINT; unique (year_id, account_full_code, import_version); new import version per Draft re-import (booklet §5) - StatementLine.mapped_total Numeric(24,4) -> Rial() (no float on SQLite, P-02) - ledger_parser extracts optional kol (general_code); hierarchy mapper accepts absent kol; services/ledger_import aggregates parsed rows by canonical account with exact Decimal summation - Migration 20261203_02 (guarded create + batch alter) runs on SQLite/PostgreSQL; up/down round-trip verified Tests: small-sample exact round-trip, large-rial BIGINT storage (>2^53) via ORM, duplicate-account aggregation, uniqueness, migration upgrade/downgrade. Full suite 168 passed. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:11 UTC a3c330b8da1868fc3130e453607818a14811e1ae
7 files changed +372 -3
backend/migrations/versions/20261203_02_ledger_balance_and_rial.py new
+49
@@ -0,0 +1,49 @@
1 +"""LedgerBalance table + exact integer-rial money column (D-01, D-03).
2 +
3 +Revision ID: 20261203_02
4 +Revises: 20260820_01
5 +
6 +The initial revision uses ``Base.metadata.create_all``, so on a fresh database
7 +the table may already exist; creation is therefore guarded. The money column is
8 +converted to ``BIGINT`` (the ``Rial`` TypeDecorator's impl) in batch mode so the
9 +migration runs identically on SQLite and PostgreSQL (P-11).
10 +"""
11 +
12 +import sqlalchemy as sa
13 +from alembic import op
14 +
15 +from aram_backend.models import LedgerBalance
16 +
17 +revision = "20261203_02"
18 +down_revision = "20260820_01"
19 +branch_labels = None
20 +depends_on = None
21 +
22 +
23 +def upgrade() -> None:
24 + bind = op.get_bind()
25 + inspector = sa.inspect(bind)
26 + if "ledger_balances" not in inspector.get_table_names():
27 + # Use the model table so naming conventions match create_all exactly.
28 + LedgerBalance.__table__.create(bind=bind)
29 + with op.batch_alter_table("statement_lines") as batch:
30 + batch.alter_column(
31 + "mapped_total",
32 + existing_type=sa.Numeric(24, 4),
33 + type_=sa.BigInteger(),
34 + existing_nullable=True,
35 + )
36 +
37 +
38 +def downgrade() -> None:
39 + with op.batch_alter_table("statement_lines") as batch:
40 + batch.alter_column(
41 + "mapped_total",
42 + existing_type=sa.BigInteger(),
43 + type_=sa.Numeric(24, 4),
44 + existing_nullable=True,
45 + )
46 + bind = op.get_bind()
47 + inspector = sa.inspect(bind)
48 + if "ledger_balances" in inspector.get_table_names():
49 + op.drop_table("ledger_balances")
backend/src/aram_backend/domain/hierarchy.py
+1 -1
@@ -62,7 +62,7 @@ def ledger_to_pilot(
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")
65 + general = normalize_code(kol, row=row, field="kol") if kol not in (None, "") else ""
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 ""
backend/src/aram_backend/ledger_parser.py
+7
@@ -20,6 +20,7 @@ from aram_backend.workbook_inspection import inspect_xlsx
20 class LedgerRecord:
21 row_number: int
22 account_code: str
23 + general_code: str | None
24 account_name: str
25 source_year: int
26 entry_type: str
@@ -79,6 +80,7 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
80 for index, value in enumerate(header_values)
81 if value is not None
82 }
83 + kol_index = indexes.get(normalize_fa("kol"))
84
85 for row_number, values in enumerate(
86 worksheet.iter_rows(
@@ -95,6 +97,11 @@ def parse_general_ledger(content: bytes) -> Iterator[LedgerRecord]:
97 yield LedgerRecord(
98 row_number=row_number,
99 account_code=_required_code(value("account_code"), row_number, "حساب"),
100 + general_code=(
101 + _optional_code(values[kol_index], row_number, "kol")
102 + if kol_index is not None
103 + else None
104 + ),
105 account_name=_required_text(
106 value("account_name"), row_number, "ACCOUNT_NAME"
107 ),
backend/src/aram_backend/models.py
+42 -2
@@ -12,7 +12,6 @@ from sqlalchemy import (
12 Enum,
13 ForeignKey,
14 Integer,
15 - Numeric,
15 String,
16 Text,
17 UniqueConstraint,
@@ -23,6 +22,7 @@ from sqlalchemy import (
22 from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
23
24 from aram_backend.database import Base
25 +from aram_backend.domain.money import Rial
26
27
28 def utc_now() -> datetime:
@@ -107,6 +107,46 @@ class AccountVersion(TimestampMixin, YearOwnedMixin, Base):
107 nature: Mapped[str | None] = mapped_column(String(64))
108
109
110 +class LedgerBalance(TimestampMixin, YearOwnedMixin, Base):
111 + """Persisted account balance from a source ledger import (D-01, booklet §5).
112 +
113 + Money is exact integer rial via the ``Rial`` TypeDecorator (P-02). Codes are
114 + text (P-03). One row per ``(year_id, account_full_code, import_version)``;
115 + a new import for a Draft year creates a new version rather than mutating the
116 + previous one. Full immutability triggers are delivered with D-07/Phase 7.
117 + """
118 +
119 + __tablename__ = "ledger_balances"
120 + __table_args__ = (
121 + UniqueConstraint(
122 + "year_id", "account_full_code", "import_version",
123 + name="uq_ledger_balance_year_code_version",
124 + ),
125 + CheckConstraint("import_version > 0", name="positive_import_version"),
126 + CheckConstraint("source_row > 0", name="positive_source_row"),
127 + )
128 + id: Mapped[int] = mapped_column(primary_key=True)
129 + source_document_id: Mapped[int] = mapped_column(
130 + ForeignKey("source_documents.id", ondelete="RESTRICT"), index=True
131 + )
132 + source_sheet: Mapped[str] = mapped_column(String(128))
133 + source_row: Mapped[int] = mapped_column(Integer)
134 + import_version: Mapped[int] = mapped_column(Integer, default=1)
135 + account_full_code: Mapped[str] = mapped_column(String(64), index=True)
136 + general_code: Mapped[str] = mapped_column(String(64), default="")
137 + subsidiary_code: Mapped[str] = mapped_column(String(64), default="")
138 + detail1_code: Mapped[str] = mapped_column(String(128), default="")
139 + detail2_code: Mapped[str] = mapped_column(String(128), default="")
140 + detail3_code: Mapped[str] = mapped_column(String(128), default="")
141 + detail4_code: Mapped[str] = mapped_column(String(128), default="")
142 + account_name: Mapped[str] = mapped_column(String(512))
143 + opening: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
144 + debit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
145 + credit: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
146 + closing: Mapped[Decimal] = mapped_column(Rial(), default=Decimal(0))
147 + entry_type: Mapped[str] = mapped_column(String(32), default="")
148 +
149 +
150 class NoteDefinition(TimestampMixin, YearOwnedMixin, Base):
151 __tablename__ = "note_definitions"
152 __table_args__ = (
@@ -176,7 +216,7 @@ class StatementLine(TimestampMixin, Base):
216 line_order: Mapped[int] = mapped_column(Integer)
217 line_label: Mapped[str] = mapped_column(String(512))
218 target_note_id: Mapped[int | None] = mapped_column(ForeignKey("note_definitions.id", ondelete="RESTRICT"))
179 - mapped_total: Mapped[Decimal | None] = mapped_column(Numeric(24, 4))
219 + mapped_total: Mapped[Decimal | None] = mapped_column(Rial())
220 statement: Mapped[FinancialStatement] = relationship(back_populates="lines")
221 target_note: Mapped[NoteDefinition | None] = relationship()
222
backend/src/aram_backend/services/__init__.py new
+6
@@ -0,0 +1,6 @@
1 +"""Service layer: import, mapping, calculation, workflow (booklet section 4).
2 +
3 +Services orchestrate the pure domain rules with persistence. They contain no
4 +financial guesswork; all money/sign/hierarchy decisions live in the domain layer
5 +and its ADRs.
6 +"""
backend/src/aram_backend/services/ledger_import.py new
+97
@@ -0,0 +1,97 @@
1 +"""Persist parsed ledger rows as exact LedgerBalance records (D-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.
9 +"""
10 +
11 +from __future__ import annotations
12 +
13 +from collections.abc import Iterable
14 +from decimal import Decimal
15 +
16 +from sqlalchemy.orm import Session
17 +
18 +from aram_backend.domain.hierarchy import canonical_full_code, ledger_to_pilot
19 +from aram_backend.ledger_parser import LedgerRecord
20 +from aram_backend.models import LedgerBalance
21 +
22 +_ZERO = Decimal(0)
23 +
24 +
25 +def import_ledger_balances(
26 + session: Session,
27 + *,
28 + year_id: int,
29 + source_document_id: int,
30 + records: Iterable[LedgerRecord],
31 + source_sheet: str = "Source",
32 + import_version: int = 1,
33 +) -> int:
34 + """Aggregate parsed records by account and persist exact balances.
35 +
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``.
39 + """
40 + aggregated: dict[str, dict[str, object]] = {}
41 + for record in records:
42 + levels = ledger_to_pilot(
43 + kol=record.general_code,
44 + hesab=record.account_code,
45 + t1=record.t1_code,
46 + t2=record.t2_code,
47 + t3=record.t3_code,
48 + t4=record.t4_code,
49 + row=record.row_number,
50 + )
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"]
71 + session.add(
72 + LedgerBalance(
73 + year_id=year_id,
74 + source_document_id=source_document_id,
75 + source_sheet=source_sheet,
76 + source_row=bucket["source_row"],
77 + import_version=import_version,
78 + account_full_code=full_code,
79 + general_code=levels.general_code,
80 + subsidiary_code=levels.subsidiary_code,
81 + detail1_code=levels.detail1_code,
82 + detail2_code=levels.detail2_code,
83 + detail3_code=levels.detail3_code,
84 + 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"],
91 + )
92 + )
93 + session.flush()
94 + return len(aggregated)
95 +
96 +
97 +__all__ = ["import_ledger_balances"]
backend/tests/test_ledger_balance.py new
+170
@@ -0,0 +1,170 @@
1 +"""D-01/D-03 acceptance: LedgerBalance persistence with exact integer rial.
2 +
3 +Proves a small-sample import stores and reads exact Decimal values, aggregates
4 +duplicate accounts, persists money as BIGINT integers (no float), and that the
5 +migration upgrades and downgrades cleanly (P-11).
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +import io
11 +import os
12 +import subprocess
13 +import sys
14 +from decimal import Decimal
15 +from pathlib import Path
16 +
17 +import pytest
18 +from openpyxl import Workbook
19 +from sqlalchemy import text
20 +
21 +from aram_backend.ingestion import register_source_document
22 +from aram_backend.ledger_parser import parse_general_ledger
23 +from aram_backend.models import Company, FiscalYear, LedgerBalance
24 +from aram_backend.services.ledger_import import import_ledger_balances
25 +
26 +REPO_ROOT = Path(__file__).resolve().parents[2]
27 +BACKEND_DIR = REPO_ROOT / "backend"
28 +
29 +HEADERS = [
30 + "حساب", "kol", "ACCOUNT_NAME", "year", "نوع",
31 + "T1_CODE", "T2_CODE", "T3_CODE", "T4_CODE",
32 + "OPENING", "Debit", "Credit", "CLOSING",
33 +]
34 +
35 +
36 +def _ledger_bytes(*rows):
37 + wb = Workbook()
38 + ws = wb.active
39 + ws.title = "Source"
40 + ws.append(["source ledger"])
41 + ws.append(HEADERS)
42 + for r in rows:
43 + ws.append(r)
44 + buf = io.BytesIO()
45 + wb.save(buf)
46 + wb.close()
47 + return buf.getvalue()
48 +
49 +
50 +def _row(code, kol, opening=0, debit=0, credit=0, closing=0, name="حساب نمونه"):
51 + return [code, kol, name, 1404, "O", None, None, None, None,
52 + opening, debit, credit, closing]
53 +
54 +
55 +def _make_year(session):
56 + company = Company(code="C1", name="شرکت نمونه")
57 + session.add(company)
58 + session.flush()
59 + year = FiscalYear(company_id=company.id, year=1404)
60 + session.add(year)
61 + session.flush()
62 + return year
63 +
64 +
65 +def _import(session, year, content):
66 + doc = register_source_document(
67 + session, year_id=year.id, filename="ledger.xlsx",
68 + document_type="general_ledger", content=content,
69 + )
70 + records = list(parse_general_ledger(content))
71 + count = import_ledger_balances(
72 + session, year_id=year.id, source_document_id=doc.id, records=records
73 + )
74 + session.commit()
75 + return count
76 +
77 +
78 +class TestLedgerBalanceImport:
79 + def test_small_sample_exact_roundtrip(self, session):
80 + year = _make_year(session)
81 + content = _ledger_bytes(_row("8348", "14", opening=100, debit=50, credit=20, closing=130))
82 + count = _import(session, year, content)
83 + assert count == 1
84 + balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
85 + assert balance.account_full_code == "148348"
86 + assert balance.general_code == "14"
87 + assert balance.subsidiary_code == "8348"
88 + assert balance.opening == Decimal(100)
89 + assert balance.debit == Decimal(50)
90 + assert balance.credit == Decimal(20)
91 + assert balance.closing == Decimal(130)
92 + assert all(isinstance(getattr(balance, f), Decimal)
93 + for f in ("opening", "debit", "credit", "closing"))
94 +
95 + def test_large_rial_no_silent_rounding(self, session):
96 + # Insert via the ORM (bypassing Excel's own float64 cell storage, which
97 + # cannot represent integers above 2**53). This proves the D-03 fix: the
98 + # Rial BIGINT column stores large rial exactly, unlike Numeric-on-SQLite.
99 + year = _make_year(session)
100 + doc = register_source_document(
101 + session, year_id=year.id, filename="l.xlsx",
102 + document_type="general_ledger", content=_ledger_bytes(_row("8348", "14")),
103 + )
104 + big = Decimal("10823163409740108") # > 2**53, the canonical total debit
105 + session.add(LedgerBalance(
106 + year_id=year.id, source_document_id=doc.id, source_sheet="Source",
107 + source_row=3, account_full_code="148348", general_code="14",
108 + subsidiary_code="8348", account_name="x", debit=big, credit=big,
109 + ))
110 + session.commit()
111 + balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
112 + assert balance.debit == big
113 + # Raw column value must be an integer (BIGINT), not a float.
114 + raw = session.execute(text("SELECT debit FROM ledger_balances")).scalar_one()
115 + assert isinstance(raw, int)
116 + assert raw == int(big)
117 +
118 + def test_duplicate_accounts_aggregated(self, session):
119 + year = _make_year(session)
120 + content = _ledger_bytes(
121 + _row("8348", "14", debit=100, closing=100),
122 + _row("8348", "14", debit=200, closing=200),
123 + )
124 + count = _import(session, year, content)
125 + assert count == 1
126 + balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
127 + assert balance.debit == Decimal(300)
128 + assert balance.closing == Decimal(300)
129 +
130 + def test_uniqueness_per_import_version(self, session):
131 + year = _make_year(session)
132 + content = _ledger_bytes(_row("8348", "14"))
133 + _import(session, year, content)
134 + # Re-importing the same version conflicts; a new version is allowed.
135 + doc = session.query(LedgerBalance).first().source_document_id
136 + records = list(parse_general_ledger(content))
137 + with pytest.raises(Exception):
138 + import_ledger_balances(
139 + session, year_id=year.id, source_document_id=doc,
140 + records=records, import_version=1,
141 + )
142 + session.rollback()
143 +
144 +
145 +class TestMigrationRoundTrip:
146 + def test_upgrade_downgrade_clean(self, tmp_path):
147 + db = tmp_path / "mig.db"
148 + env = {**os.environ, "ARAM_DATABASE_URL": f"sqlite:///{db}"}
149 + up = subprocess.run(
150 + [sys.executable, "-m", "alembic", "upgrade", "head"],
151 + cwd=BACKEND_DIR, env=env, capture_output=True, text=True,
152 + )
153 + assert up.returncode == 0, up.stderr
154 + # ledger_balances exists and mapped_total is BIGINT after upgrade.
155 + import sqlite3
156 + con = sqlite3.connect(db)
157 + tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
158 + assert "ledger_balances" in tables
159 + cols = {r[1]: r[2] for r in con.execute("PRAGMA table_info(statement_lines)")}
160 + assert cols["mapped_total"].upper() in ("BIGINT", "INTEGER")
161 + con.close()
162 + down = subprocess.run(
163 + [sys.executable, "-m", "alembic", "downgrade", "base"],
164 + cwd=BACKEND_DIR, env=env, capture_output=True, text=True,
165 + )
166 + assert down.returncode == 0, down.stderr
167 + con = sqlite3.connect(db)
168 + tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
169 + assert "ledger_balances" not in tables
170 + con.close()