1
+"""Phase 1 acceptance: persistent statement build + drill-down + vertical-slice API."""
2
+
3
+from __future__ import annotations
4
+
5
+from decimal import Decimal
6
+from pathlib import Path
7
+
8
+import pytest
9
+from fastapi.testclient import TestClient
10
+from openpyxl import load_workbook
11
+from sqlalchemy.orm import sessionmaker
12
+
13
+from aram_backend.config import Settings
14
+from aram_backend.database import Base, build_engine, ensure_triggers, get_session
15
+from aram_backend.domain.normalization import decimal_from_cell, normalize_code
16
+from aram_backend.ingestion import register_source_document
17
+from aram_backend.ledger_parser import LedgerRecord
18
+from aram_backend.main import app
19
+from aram_backend.models import (
20
+ Company,
21
+ FiscalYear,
22
+ LedgerBalance,
23
+ MappingRule,
24
+ NoteDefinition,
25
+ StatementType,
26
+)
27
+from aram_backend.services.ledger_import import import_ledger_balances
28
+from aram_backend.services.statement_build import (
29
+ StatementBuildError,
30
+ build_statements,
31
+ drill_down,
32
+)
33
+
34
+
35
+def _setup(session):
36
+ company = Company(code="V1", name="شرکت نمونه")
37
+ session.add(company)
38
+ session.flush()
39
+ year = FiscalYear(company_id=company.id, year=1404)
40
+ session.add(year)
41
+ session.flush()
42
+ source = register_source_document(
43
+ session,
44
+ year_id=year.id,
45
+ filename="source_1404.xlsx",
46
+ document_type="general_ledger",
47
+ content=b"vertical-slice-bytes",
48
+ )
49
+ session.flush()
50
+ return year, source
51
+
52
+
53
+def _balance(session, year, source, code, closing, row):
54
+ session.add(
55
+ LedgerBalance(
56
+ year_id=year.id,
57
+ source_document_id=source.id,
58
+ source_sheet="Source",
59
+ source_row=row,
60
+ import_version=1,
61
+ account_full_code=code,
62
+ general_code=code[:2],
63
+ subsidiary_code=code[2:],
64
+ account_name=f"حساب {code}",
65
+ opening=Decimal(0),
66
+ debit=Decimal(max(closing, 0)),
67
+ credit=Decimal(max(-closing, 0)),
68
+ closing=Decimal(closing),
69
+ )
70
+ )
71
+
72
+
73
+def _note(session, year, number, title, statement, section):
74
+ note = NoteDefinition(
75
+ year_id=year.id,
76
+ note_number=number,
77
+ title=title,
78
+ configuration_json={"statement": statement, "section": section},
79
+ )
80
+ session.add(note)
81
+ session.flush()
82
+ return note
83
+
84
+
85
+def _map(session, year, code, note):
86
+ session.add(
87
+ MappingRule(
88
+ year_id=year.id,
89
+ rule_key=f"{code}->{note.id}",
90
+ account_code=code,
91
+ target_note_id=note.id,
92
+ mapping_type="closing",
93
+ )
94
+ )
95
+
96
+
97
+def _seed_full(session):
98
+ year, source = _setup(session)
99
+ _balance(session, year, source, "148348", 100, 3) # asset
100
+ _balance(session, year, source, "241001", -60, 4) # liability
101
+ _balance(session, year, source, "341001", -40, 5) # equity
102
+ _balance(session, year, source, "541001", -250, 6) # revenue
103
+ _balance(session, year, source, "641001", 200, 7) # expense
104
+ n_cash = _note(session, year, "6", "نقد", "BS", "Assets")
105
+ n_pay = _note(session, year, "10", "پرداختنی", "BS", "Liabilities")
106
+ n_cap = _note(session, year, "12", "سرمایه", "BS", "Equity")
107
+ n_rev = _note(session, year, "20", "فروش", "IS", "Revenue")
108
+ n_exp = _note(session, year, "22", "بهای تمامشده", "IS", "Expenses")
109
+ _map(session, year, "148348", n_cash)
110
+ _map(session, year, "241001", n_pay)
111
+ _map(session, year, "341001", n_cap)
112
+ _map(session, year, "541001", n_rev)
113
+ _map(session, year, "641001", n_exp)
114
+ session.flush()
115
+ return year, n_cash
116
+
117
+
118
+class TestStatementBuild:
119
+ def test_bs_is_totals_and_signs(self, session):
120
+ year, _ = _seed_full(session)
121
+ result = build_statements(session, year.id)
122
+ session.commit()
123
+ assert {s.statement_type for s in result.statements} == {
124
+ StatementType.BALANCE_SHEET,
125
+ StatementType.INCOME_STATEMENT,
126
+ }
127
+ bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
128
+ totals = {ln.line_label.split(" — ")[0]: ln.mapped_total for ln in bs.lines}
129
+ assert totals["6"] == Decimal(100) # asset +1
130
+ assert totals["10"] == Decimal(60) # liability -1 x -60
131
+ assert totals["12"] == Decimal(40) # equity -1 x -40
132
+ is_stmt = next(
133
+ s for s in result.statements if s.statement_type == StatementType.INCOME_STATEMENT
134
+ )
135
+ is_totals = {ln.line_label.split(" — ")[0]: ln.mapped_total for ln in is_stmt.lines}
136
+ assert is_totals["20"] == Decimal(250) # revenue -1 x -250
137
+ assert is_totals["22"] == Decimal(200) # expense +1
138
+
139
+ def test_drilldown_to_source_row(self, session):
140
+ year, n_cash = _seed_full(session)
141
+ result = build_statements(session, year.id)
142
+ session.commit()
143
+ bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
144
+ cash_line = next(ln for ln in bs.lines if ln.target_note_id == n_cash.id)
145
+ lineage = drill_down(session, cash_line.id)
146
+ assert lineage["note"]["note_number"] == "6"
147
+ assert len(lineage["accounts"]) == 1
148
+ acct = lineage["accounts"][0]
149
+ assert acct["account_full_code"] == "148348"
150
+ assert acct["source"]["filename"] == "source_1404.xlsx"
151
+ assert acct["source"]["sheet"] == "Source"
152
+ assert acct["source"]["row"] == 3
153
+ assert acct["source"]["file_hash"]
154
+
155
+ def test_new_version_per_build(self, session):
156
+ year, _ = _seed_full(session)
157
+ r1 = build_statements(session, year.id)
158
+ session.commit()
159
+ r2 = build_statements(session, year.id)
160
+ session.commit()
161
+ v1 = {s.statement_type: s.version for s in r1.statements}
162
+ v2 = {s.statement_type: s.version for s in r2.statements}
163
+ assert v2[StatementType.BALANCE_SHEET] == v1[StatementType.BALANCE_SHEET] + 1
164
+
165
+ def test_unmapped_active_account_surfaced(self, session):
166
+ year, source = _setup(session)
167
+ _balance(session, year, source, "148348", 100, 3)
168
+ session.flush()
169
+ result = build_statements(session, year.id)
170
+ session.commit()
171
+ assert "148348" in result.unmapped_accounts
172
+
173
+ def test_unknown_statement_type_raises(self, session):
174
+ year, _ = _seed_full(session)
175
+ with pytest.raises(StatementBuildError):
176
+ build_statements(session, year.id, statement_types=("XX",))
177
+
178
+
179
+# --------------------------------------------------------------- API e2e
180
+@pytest.fixture
181
+def api_client(tmp_path, monkeypatch):
182
+ engine = build_engine(f"sqlite:///{tmp_path / 'api.db'}")
183
+ Base.metadata.create_all(engine)
184
+ ensure_triggers(engine)
185
+ factory = sessionmaker(bind=engine, expire_on_commit=False)
186
+
187
+ def override_session():
188
+ with factory() as db:
189
+ yield db
190
+
191
+ app.dependency_overrides[get_session] = override_session
192
+ monkeypatch.setattr(
193
+ "aram_backend.statement_api.get_settings",
194
+ lambda: Settings(source_store_root=str(tmp_path / "store")),
195
+ )
196
+ with TestClient(app) as client:
197
+ yield client
198
+ app.dependency_overrides.clear()
199
+
200
+
201
+CSV = (
202
+ "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
203
+ "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
204
+ "1001,24,پرداختنی,1404,O,,,,,0,0,60,-60\n"
205
+).encode()
206
+
207
+
208
+class TestVerticalSliceApi:
209
+ def test_end_to_end(self, api_client):
210
+ c = api_client
211
+ r = c.post("/api/v1/companies", json={"code": "E2E", "name": "شرکت", "year": 1404})
212
+ assert r.status_code == 200
213
+ year_id = r.json()["year_id"]
214
+
215
+ r = c.post(
216
+ f"/api/v1/years/{year_id}/ledger",
217
+ files={"file": ("ledger.csv", CSV, "text/csv")},
218
+ )
219
+ assert r.status_code == 200, r.text
220
+ assert r.json()["accounts_imported"] == 2
221
+
222
+ r = c.post(
223
+ f"/api/v1/years/{year_id}/notes",
224
+ json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
225
+ )
226
+ note_id = r.json()["note_id"]
227
+ r = c.post(
228
+ f"/api/v1/years/{year_id}/mappings",
229
+ json={"account_code": "148348", "target_note_id": note_id},
230
+ )
231
+ assert r.status_code == 200
232
+
233
+ r = c.post(f"/api/v1/years/{year_id}/statements/build")
234
+ assert r.status_code == 200, r.text
235
+ assert "148348" not in r.json()["unmapped_accounts"]
236
+
237
+ r = c.get(f"/api/v1/years/{year_id}/statements")
238
+ assert r.status_code == 200
239
+ bs = next(s for s in r.json()["statements"] if s["type"] == "BS")
240
+ cash_line = next(ln for ln in bs["lines"] if ln["target_note_id"] == note_id)
241
+ assert cash_line["mapped_total"] == "100"
242
+
243
+ r = c.get(f"/api/v1/statement-lines/{cash_line['id']}/drilldown")
244
+ assert r.status_code == 200
245
+ acct = r.json()["accounts"][0]
246
+ assert acct["source"]["filename"] == "ledger.csv"
247
+ assert acct["source"]["row"] == 2
248
+
249
+ def test_preflight_reports_controls(self, api_client):
250
+ c = api_client
251
+ year_id = c.post(
252
+ "/api/v1/companies", json={"code": "PF", "name": "x", "year": 1404}
253
+ ).json()["year_id"]
254
+ c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", CSV, "text/csv")})
255
+ r = c.get(f"/api/v1/years/{year_id}/preflight")
256
+ assert r.status_code == 200
257
+ codes = {ctl["code"] for ctl in r.json()["controls"]}
258
+ assert codes == {"C-01", "C-02", "C-03", "C-04"}
259
+
260
+
261
+# ------------------------------------------------- bounded real-data smoke
262
+_REPO_ROOT = Path(__file__).resolve().parents[2]
263
+_LEDGER_1404 = _REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
264
+
265
+
266
+@pytest.mark.skipif(not _LEDGER_1404.exists(), reason="canonical ledger not present")
267
+class TestRealDataVerticalSlice:
268
+ """Bounded read-only smoke: real 1404 rows -> import -> build -> drill-down.
269
+
270
+ Proves the persistent pipeline and lineage on canonical account codes/rows.
271
+ Full rial-for-rial reconciliation against official statements is Phase 4.
272
+ """
273
+
274
+ def _records(self, limit=3000):
275
+ wb = load_workbook(_LEDGER_1404, read_only=True, data_only=True, keep_links=False)
276
+ ws = wb["Source"]
277
+ rows = ws.iter_rows(values_only=True)
278
+ next(rows)
279
+ header = next(rows)
280
+ idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
281
+ out = []
282
+ for row_number, vals in enumerate(rows, start=3):
283
+ if not any(v is not None for v in vals):
284
+ continue
285
+ try:
286
+ year = int(decimal_from_cell(vals[idx["year"]], row=row_number, field="year"))
287
+ if year != 1404:
288
+ continue
289
+ money = [vals[idx[k]] for k in ("OPENING", "Debit", "Credit", "CLOSING")]
290
+ if any(m is None for m in money):
291
+ continue
292
+ rec = LedgerRecord(
293
+ row_number=row_number,
294
+ account_code=normalize_code(vals[idx["حساب"]], row=row_number, field="حساب"),
295
+ general_code=normalize_code(vals[idx["kol"]], row=row_number, field="kol"),
296
+ account_name=str(vals[idx["ACCOUNT_NAME"]] or ""),
297
+ source_year=year,
298
+ entry_type=str(vals[idx["نوع"]] or ""),
299
+ t1_code=None,
300
+ t2_code=None,
301
+ t3_code=None,
302
+ t4_code=None,
303
+ opening=decimal_from_cell(money[0], row=row_number, field="OPENING"),
304
+ debit=decimal_from_cell(money[1], row=row_number, field="Debit"),
305
+ credit=decimal_from_cell(money[2], row=row_number, field="Credit"),
306
+ closing=decimal_from_cell(money[3], row=row_number, field="CLOSING"),
307
+ )
308
+ except Exception:
309
+ continue
310
+ out.append(rec)
311
+ if len(out) >= limit:
312
+ break
313
+ wb.close()
314
+ return out
315
+
316
+ def test_import_build_drilldown_on_real_rows(self, session):
317
+ records = self._records()
318
+ assert len(records) > 100
319
+ year, source = _setup(session)
320
+ count = import_ledger_balances(
321
+ session, year_id=year.id, source_document_id=source.id, records=records
322
+ )
323
+ assert count > 0
324
+ first = records[0]
325
+ code = (first.general_code or "") + first.account_code
326
+ note = _note(session, year, "6", "نقد", "BS", "Assets")
327
+ _map(session, year, code, note)
328
+ session.flush()
329
+ result = build_statements(session, year.id)
330
+ session.commit()
331
+ bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
332
+ line = next(ln for ln in bs.lines if ln.target_note_id == note.id)
333
+ lineage = drill_down(session, line.id)
334
+ assert lineage["accounts"], "drill-down must reach real ledger rows"
335
+ src = lineage["accounts"][0]["source"]
336
+ assert src["filename"] == "source_1404.xlsx"
337
+ assert src["sheet"] == "Source"
338
+ assert src["row"] >= 3
339
+ # Most real accounts remain unmapped at this stage (Phase 2 resolves them).
340
+ assert len(result.unmapped_accounts) > 0