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()