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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/checkout-7
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 221 lines 7.53 KB
Raw
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 from sqlalchemy.exc import IntegrityError
21
22 from aram_backend.ingestion import register_source_document
23 from aram_backend.ledger_parser import parse_general_ledger
24 from aram_backend.models import Company, FiscalYear, LedgerBalance
25 from aram_backend.services.ledger_import import import_ledger_balances
26
27 REPO_ROOT = Path(__file__).resolve().parents[2]
28 BACKEND_DIR = REPO_ROOT / "backend"
29
30 HEADERS = [
31 "حساب",
32 "kol",
33 "ACCOUNT_NAME",
34 "year",
35 "نوع",
36 "T1_CODE",
37 "T2_CODE",
38 "T3_CODE",
39 "T4_CODE",
40 "OPENING",
41 "Debit",
42 "Credit",
43 "CLOSING",
44 ]
45
46
47 def _ledger_bytes(*rows):
48 wb = Workbook()
49 ws = wb.active
50 ws.title = "Source"
51 ws.append(["source ledger"])
52 ws.append(HEADERS)
53 for r in rows:
54 ws.append(r)
55 buf = io.BytesIO()
56 wb.save(buf)
57 wb.close()
58 return buf.getvalue()
59
60
61 def _row(code, kol, opening=0, debit=0, credit=0, closing=0, name="حساب نمونه"):
62 return [code, kol, name, 1404, "O", None, None, None, None, opening, debit, credit, closing]
63
64
65 def _make_year(session):
66 company = Company(code="C1", name="شرکت نمونه")
67 session.add(company)
68 session.flush()
69 year = FiscalYear(company_id=company.id, year=1404)
70 session.add(year)
71 session.flush()
72 return year
73
74
75 def _import(session, year, content):
76 doc = register_source_document(
77 session,
78 year_id=year.id,
79 filename="ledger.xlsx",
80 document_type="general_ledger",
81 content=content,
82 )
83 records = list(parse_general_ledger(content))
84 count = import_ledger_balances(
85 session, year_id=year.id, source_document_id=doc.id, records=records
86 )
87 session.commit()
88 return count
89
90
91 class TestLedgerBalanceImport:
92 def test_small_sample_exact_roundtrip(self, session):
93 year = _make_year(session)
94 content = _ledger_bytes(_row("8348", "14", opening=100, debit=50, credit=20, closing=130))
95 count = _import(session, year, content)
96 assert count == 1
97 balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
98 assert balance.account_full_code == "148348"
99 assert balance.general_code == "14"
100 assert balance.subsidiary_code == "8348"
101 assert balance.opening == Decimal(100)
102 assert balance.debit == Decimal(50)
103 assert balance.credit == Decimal(20)
104 assert balance.closing == Decimal(130)
105 assert all(
106 isinstance(getattr(balance, f), Decimal)
107 for f in ("opening", "debit", "credit", "closing")
108 )
109
110 def test_large_rial_no_silent_rounding(self, session):
111 # Insert via the ORM (bypassing Excel's own float64 cell storage, which
112 # cannot represent integers above 2**53). This proves the D-03 fix: the
113 # Rial BIGINT column stores large rial exactly, unlike Numeric-on-SQLite.
114 year = _make_year(session)
115 doc = register_source_document(
116 session,
117 year_id=year.id,
118 filename="l.xlsx",
119 document_type="general_ledger",
120 content=_ledger_bytes(_row("8348", "14")),
121 )
122 big = Decimal("10823163409740108") # > 2**53, the canonical total debit
123 session.add(
124 LedgerBalance(
125 year_id=year.id,
126 source_document_id=doc.id,
127 source_sheet="Source",
128 source_row=3,
129 account_full_code="148348",
130 general_code="14",
131 subsidiary_code="8348",
132 account_name="x",
133 debit=big,
134 credit=big,
135 )
136 )
137 session.commit()
138 balance = session.query(LedgerBalance).filter_by(year_id=year.id).one()
139 assert balance.debit == big
140 # Raw column value must be an integer (BIGINT), not a float.
141 raw = session.execute(text("SELECT debit FROM ledger_balances")).scalar_one()
142 assert isinstance(raw, int)
143 assert raw == int(big)
144
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)
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)
173 content = _ledger_bytes(_row("8348", "14"))
174 _import(session, year, content)
175 # Re-importing the same version conflicts; a new version is allowed.
176 doc = session.query(LedgerBalance).first().source_document_id
177 records = list(parse_general_ledger(content))
178 with pytest.raises(IntegrityError):
179 import_ledger_balances(
180 session,
181 year_id=year.id,
182 source_document_id=doc,
183 records=records,
184 import_version=1,
185 )
186 session.rollback()
187
188
189 class TestMigrationRoundTrip:
190 def test_upgrade_downgrade_clean(self, tmp_path):
191 db = tmp_path / "mig.db"
192 env = {**os.environ, "ARAM_DATABASE_URL": f"sqlite:///{db}"}
193 up = subprocess.run(
194 [sys.executable, "-m", "alembic", "upgrade", "head"],
195 cwd=BACKEND_DIR,
196 env=env,
197 capture_output=True,
198 text=True,
199 )
200 assert up.returncode == 0, up.stderr
201 # ledger_balances exists and mapped_total is BIGINT after upgrade.
202 import sqlite3
203
204 con = sqlite3.connect(db)
205 tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
206 assert "ledger_balances" in tables
207 cols = {r[1]: r[2] for r in con.execute("PRAGMA table_info(statement_lines)")}
208 assert cols["mapped_total"].upper() in ("BIGINT", "INTEGER")
209 con.close()
210 down = subprocess.run(
211 [sys.executable, "-m", "alembic", "downgrade", "base"],
212 cwd=BACKEND_DIR,
213 env=env,
214 capture_output=True,
215 text=True,
216 )
217 assert down.returncode == 0, down.stderr
218 con = sqlite3.connect(db)
219 tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
220 assert "ledger_balances" not in tables
221 con.close()