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