@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 315 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 # ADR-032: the official IS presents expenses negative, so -1 x 200.
133 assert is_totals["22"] == Decimal(-200)
134
135 def test_drilldown_to_source_row(self, session):
136 year, n_cash = _seed_full(session)
137 result = build_statements(session, year.id)
138 session.commit()
139 bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
140 cash_line = next(ln for ln in bs.lines if ln.target_note_id == n_cash.id)
141 lineage = drill_down(session, cash_line.id)
142 assert lineage["note"]["note_number"] == "6"
143 assert len(lineage["accounts"]) == 1
144 acct = lineage["accounts"][0]
145 assert acct["account_full_code"] == "148348"
146 assert acct["source"]["filename"] == "source_1404.xlsx"
147 assert acct["source"]["sheet"] == "Source"
148 assert acct["source"]["row"] == 3
149 assert acct["source"]["file_hash"]
150
151 def test_new_version_per_build(self, session):
152 year, _ = _seed_full(session)
153 r1 = build_statements(session, year.id)
154 session.commit()
155 r2 = build_statements(session, year.id)
156 session.commit()
157 v1 = {s.statement_type: s.version for s in r1.statements}
158 v2 = {s.statement_type: s.version for s in r2.statements}
159 assert v2[StatementType.BALANCE_SHEET] == v1[StatementType.BALANCE_SHEET] + 1
160
161 def test_unmapped_active_account_surfaced(self, session):
162 year, source = _setup(session)
163 _balance(session, year, source, "148348", 100, 3)
164 session.flush()
165 result = build_statements(session, year.id)
166 session.commit()
167 assert "148348" in result.unmapped_accounts
168
169 def test_unknown_statement_type_raises(self, session):
170 year, _ = _seed_full(session)
171 with pytest.raises(StatementBuildError):
172 build_statements(session, year.id, statement_types=("XX",))
173
174
175 # --------------------------------------------------------------- API e2e
176 CSV = (
177 "حساب,kol,ACCOUNT_NAME,year,نوع,T1_CODE,T2_CODE,T3_CODE,T4_CODE,OPENING,Debit,Credit,CLOSING\n"
178 "8348,14,نقد,1404,O,,,,,0,100,0,100\n"
179 "1001,24,پرداختنی,1404,O,,,,,0,0,60,-60\n"
180 ).encode()
181
182
183 class TestVerticalSliceApi:
184 def test_end_to_end(self, api_client):
185 c = api_client
186 r = c.post("/api/v1/companies", json={"code": "E2E", "name": "شرکت", "year": 1404})
187 assert r.status_code == 200
188 year_id = r.json()["year_id"]
189
190 r = c.post(
191 f"/api/v1/years/{year_id}/ledger",
192 files={"file": ("ledger.csv", CSV, "text/csv")},
193 )
194 assert r.status_code == 200, r.text
195 assert r.json()["accounts_imported"] == 2
196
197 r = c.post(
198 f"/api/v1/years/{year_id}/notes",
199 json={"note_number": "6", "title": "نقد", "statement": "BS", "section": "Assets"},
200 )
201 note_id = r.json()["note_id"]
202 r = c.post(
203 f"/api/v1/years/{year_id}/mappings",
204 json={"account_code": "148348", "target_note_id": note_id},
205 )
206 assert r.status_code == 200
207
208 r = c.post(f"/api/v1/years/{year_id}/statements/build")
209 assert r.status_code == 200, r.text
210 assert "148348" not in r.json()["unmapped_accounts"]
211
212 r = c.get(f"/api/v1/years/{year_id}/statements")
213 assert r.status_code == 200
214 bs = next(s for s in r.json()["statements"] if s["type"] == "BS")
215 cash_line = next(ln for ln in bs["lines"] if ln["target_note_id"] == note_id)
216 assert cash_line["mapped_total"] == "100"
217
218 r = c.get(f"/api/v1/statement-lines/{cash_line['id']}/drilldown")
219 assert r.status_code == 200
220 acct = r.json()["accounts"][0]
221 assert acct["source"]["filename"] == "ledger.csv"
222 assert acct["source"]["row"] == 2
223
224 def test_preflight_reports_controls(self, api_client):
225 c = api_client
226 year_id = c.post(
227 "/api/v1/companies", json={"code": "PF", "name": "x", "year": 1404}
228 ).json()["year_id"]
229 c.post(f"/api/v1/years/{year_id}/ledger", files={"file": ("l.csv", CSV, "text/csv")})
230 r = c.get(f"/api/v1/years/{year_id}/preflight")
231 assert r.status_code == 200
232 codes = {ctl["code"] for ctl in r.json()["controls"]}
233 assert codes == {f"C-{i:02d}" for i in range(1, 16)}
234
235
236 # ------------------------------------------------- bounded real-data smoke
237 _REPO_ROOT = Path(__file__).resolve().parents[2]
238 _LEDGER_1404 = _REPO_ROOT / "data" / "source_ledgers" / "source_1404.xlsx"
239
240
241 @pytest.mark.skipif(not _LEDGER_1404.exists(), reason="canonical ledger not present")
242 class TestRealDataVerticalSlice:
243 """Bounded read-only smoke: real 1404 rows -> import -> build -> drill-down.
244
245 Proves the persistent pipeline and lineage on canonical account codes/rows.
246 Full rial-for-rial reconciliation against official statements is Phase 4.
247 """
248
249 def _records(self, limit=3000):
250 wb = load_workbook(_LEDGER_1404, read_only=True, data_only=True, keep_links=False)
251 ws = wb["Source"]
252 rows = ws.iter_rows(values_only=True)
253 next(rows)
254 header = next(rows)
255 idx = {str(v).strip(): i for i, v in enumerate(header) if v is not None}
256 out = []
257 for row_number, vals in enumerate(rows, start=3):
258 if not any(v is not None for v in vals):
259 continue
260 try:
261 year = int(decimal_from_cell(vals[idx["year"]], row=row_number, field="year"))
262 if year != 1404:
263 continue
264 money = [vals[idx[k]] for k in ("OPENING", "Debit", "Credit", "CLOSING")]
265 if any(m is None for m in money):
266 continue
267 rec = LedgerRecord(
268 row_number=row_number,
269 account_code=normalize_code(vals[idx["حساب"]], row=row_number, field="حساب"),
270 general_code=normalize_code(vals[idx["kol"]], row=row_number, field="kol"),
271 account_name=str(vals[idx["ACCOUNT_NAME"]] or ""),
272 source_year=year,
273 entry_type=str(vals[idx["نوع"]] or ""),
274 t1_code=None,
275 t2_code=None,
276 t3_code=None,
277 t4_code=None,
278 opening=decimal_from_cell(money[0], row=row_number, field="OPENING"),
279 debit=decimal_from_cell(money[1], row=row_number, field="Debit"),
280 credit=decimal_from_cell(money[2], row=row_number, field="Credit"),
281 closing=decimal_from_cell(money[3], row=row_number, field="CLOSING"),
282 )
283 except Exception:
284 continue
285 out.append(rec)
286 if len(out) >= limit:
287 break
288 wb.close()
289 return out
290
291 def test_import_build_drilldown_on_real_rows(self, session):
292 records = self._records()
293 assert len(records) > 100
294 year, source = _setup(session)
295 count = import_ledger_balances(
296 session, year_id=year.id, source_document_id=source.id, records=records
297 )
298 assert count > 0
299 first = records[0]
300 code = (first.general_code or "") + first.account_code
301 note = _note(session, year, "6", "نقد", "BS", "Assets")
302 _map(session, year, code, note)
303 session.flush()
304 result = build_statements(session, year.id)
305 session.commit()
306 bs = next(s for s in result.statements if s.statement_type == StatementType.BALANCE_SHEET)
307 line = next(ln for ln in bs.lines if ln.target_note_id == note.id)
308 lineage = drill_down(session, line.id)
309 assert lineage["accounts"], "drill-down must reach real ledger rows"
310 src = lineage["accounts"][0]["source"]
311 assert src["filename"] == "source_1404.xlsx"
312 assert src["sheet"] == "Source"
313 assert src["row"] >= 3
314 # Most real accounts remain unmapped at this stage (Phase 2 resolves them).
315 assert len(result.unmapped_accounts) > 0