@davoodmehraban89 / Aram-1 / commits / 9c33586
Fork 0

feat(statements): persistent audited vertical slice + drill-down (Phase 1)

- services/statement_build: build versioned BS/IS from latest LedgerBalance import + mappings/notes; exact integer-rial totals; display sign policy (ADR-013/018); unmapped active accounts surfaced; new version per build (never mutates snapshot) - drill_down: StatementLine -> Note -> MappingRule -> LedgerBalance -> SourceDocument (filename + SHA-256) + sheet + row (D2 full traceability) - statement_api: company/year setup, year-filtered ledger upload+import, notes, mappings, statement build/list, drill-down, preflight controls endpoint - ADR-018 persistent statements + drill-down contract Tests: BS/IS totals+signs, drill-down to source row, version increment, unmapped surfacing, API end-to-end (CSV->import->map->build->drilldown), preflight controls, bounded real-data smoke (3000 real 1404 rows -> import -> build -> drill-down). 209 passed; ruff/mypy/coverage gates green. No source data changed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 09:49 UTC 9c3358654488f14700b06a55de3b91f8a0443997
6 files changed +931
backend/src/aram_backend/config.py
+1
@@ -7,6 +7,7 @@ class Settings(BaseSettings):
7 app_name: str = "Aram API"
8 environment: str = "development"
9 database_url: str = "sqlite:///./aram.db"
10 + source_store_root: str = "./source_store"
11 model_config = SettingsConfigDict(env_prefix="ARAM_", env_file=".env")
12
13
backend/src/aram_backend/main.py
+2
@@ -9,10 +9,12 @@ from aram_backend.config import get_settings
9 from aram_backend.models import FiscalYearStatus, StatementType
10 from aram_backend.pilot_api import router as pilot_router
11 from aram_backend.schemas import EntityDescriptor, EnumCatalog, HealthResponse, SchemaCatalog
12 +from aram_backend.statement_api import router as statement_router
13
14 settings = get_settings()
15 app = FastAPI(title=settings.app_name, version=__version__)
16 app.include_router(pilot_router)
17 +app.include_router(statement_router)
18 app.mount(
19 "/pilot",
20 StaticFiles(directory=Path(__file__).parent / "static" / "pilot", html=True),
backend/src/aram_backend/services/statement_build.py new
+252
@@ -0,0 +1,252 @@
1 +"""Persistent, audited statement build + drill-down lineage (Phase 1, ADR-018).
2 +
3 +Turns imported LedgerBalance rows + active mappings/notes into versioned
4 +FinancialStatement/StatementLine records with exact integer-rial totals and a
5 +full lineage back to the source file/sheet/row. Display signs follow ADR-013
6 +(debit-positive closing; display = sign x closing).
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +from dataclasses import dataclass
12 +from decimal import Decimal
13 +
14 +from sqlalchemy import func, select
15 +from sqlalchemy.orm import Session
16 +
17 +from aram_backend.models import (
18 + FinancialStatement,
19 + FiscalYear,
20 + LedgerBalance,
21 + MappingRule,
22 + NoteDefinition,
23 + SourceDocument,
24 + StatementLine,
25 + StatementType,
26 +)
27 +
28 +_ZERO = Decimal(0)
29 +
30 +# Display sign policy (ADR-013/018). Closing is debit-positive.
31 +SECTION_POLICY: dict[str, dict[str, int]] = {
32 + "BS": {"Assets": 1, "Liabilities": -1, "Equity": -1},
33 + "IS": {"Revenue": -1, "Expenses": 1},
34 + "CF": {"Operating": 1, "Investing": 1, "Financing": 1},
35 + "EQ": {"Equity": -1},
36 +}
37 +SECTION_ORDER: dict[str, list[str]] = {
38 + "BS": ["Assets", "Liabilities", "Equity"],
39 + "IS": ["Revenue", "Expenses"],
40 + "CF": ["Operating", "Investing", "Financing"],
41 + "EQ": ["Equity"],
42 +}
43 +STATEMENT_LABELS_FA = {
44 + "BS": "ترازنامه",
45 + "IS": "صورت سود و زیان",
46 + "CF": "صورت جریان‌های نقدی",
47 + "EQ": "صورت تغییرات حقوق مالکانه",
48 +}
49 +SECTION_LABELS_FA = {
50 + "Assets": "دارایی‌ها",
51 + "Liabilities": "بدهی‌ها",
52 + "Equity": "حقوق مالکانه",
53 + "Revenue": "درآمدها",
54 + "Expenses": "هزینه‌ها",
55 + "Operating": "عملیاتی",
56 + "Investing": "سرمایه‌گذاری",
57 + "Financing": "تأمین مالی",
58 +}
59 +RENDERED_STATEMENTS = ("BS", "IS")
60 +
61 +
62 +class StatementBuildError(ValueError):
63 + """Raised when a statement cannot be built safely."""
64 +
65 +
66 +@dataclass(frozen=True)
67 +class BuildResult:
68 + statements: tuple[FinancialStatement, ...]
69 + unmapped_accounts: tuple[str, ...]
70 +
71 +
72 +def _latest_import_version(session: Session, year_id: int) -> int | None:
73 + return session.scalar(
74 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
75 + )
76 +
77 +
78 +def _latest_balances(session: Session, year_id: int) -> list[LedgerBalance]:
79 + version = _latest_import_version(session, year_id)
80 + if version is None:
81 + return []
82 + return list(
83 + session.scalars(
84 + select(LedgerBalance).where(
85 + LedgerBalance.year_id == year_id,
86 + LedgerBalance.import_version == version,
87 + )
88 + ).all()
89 + )
90 +
91 +
92 +def _next_statement_version(session: Session, year_id: int, stype: StatementType) -> int:
93 + current = session.scalar(
94 + select(func.max(FinancialStatement.version)).where(
95 + FinancialStatement.year_id == year_id,
96 + FinancialStatement.statement_type == stype,
97 + )
98 + )
99 + return (current or 0) + 1
100 +
101 +
102 +def build_statements(
103 + session: Session,
104 + year_id: int,
105 + *,
106 + statement_types: tuple[str, ...] = RENDERED_STATEMENTS,
107 +) -> BuildResult:
108 + """Build persisted, versioned statements for a Draft year.
109 +
110 + Aggregates the latest ledger import per mapped note, applies the display sign
111 + policy, and writes a new FinancialStatement version per requested type.
112 + Unmapped active accounts are surfaced (they block approval via preflight).
113 + """
114 + year = session.get(FiscalYear, year_id)
115 + if year is None:
116 + raise StatementBuildError(f"fiscal year {year_id} does not exist")
117 +
118 + balances = _latest_balances(session, year_id)
119 + notes = {
120 + n.id: n
121 + for n in session.scalars(
122 + select(NoteDefinition).where(NoteDefinition.year_id == year_id)
123 + ).all()
124 + }
125 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
126 +
127 + account_to_notes: dict[str, list[int]] = {}
128 + for rule in rules:
129 + account_to_notes.setdefault(rule.account_code, []).append(rule.target_note_id)
130 +
131 + note_totals: dict[int, Decimal] = {}
132 + unmapped: list[str] = []
133 + for balance in balances:
134 + targets = account_to_notes.get(balance.account_full_code, [])
135 + if not targets:
136 + if any(getattr(balance, k) != _ZERO for k in ("opening", "debit", "credit", "closing")):
137 + unmapped.append(balance.account_full_code)
138 + continue
139 + for note_id in targets:
140 + note_totals[note_id] = note_totals.get(note_id, _ZERO) + balance.closing
141 +
142 + built: list[FinancialStatement] = []
143 + for stype_code in statement_types:
144 + if stype_code not in SECTION_POLICY:
145 + raise StatementBuildError(f"unknown statement type {stype_code}")
146 + stype = StatementType(stype_code)
147 + policy = SECTION_POLICY[stype_code]
148 + order = SECTION_ORDER[stype_code]
149 +
150 + member_notes = [
151 + n for n in notes.values() if n.configuration_json.get("statement") == stype_code
152 + ]
153 + member_notes.sort(
154 + key=lambda n: (
155 + order.index(n.configuration_json.get("section"))
156 + if n.configuration_json.get("section") in order
157 + else len(order),
158 + n.note_number,
159 + )
160 + )
161 +
162 + statement = FinancialStatement(
163 + year_id=year_id,
164 + statement_type=stype,
165 + version=_next_statement_version(session, year_id, stype),
166 + )
167 + session.add(statement)
168 + session.flush()
169 +
170 + for line_order, note in enumerate(member_notes):
171 + section = note.configuration_json.get("section", "")
172 + sign = policy.get(section)
173 + if sign is None:
174 + raise StatementBuildError(
175 + f"note {note.note_number}: section '{section}' has no sign policy for {stype_code}"
176 + )
177 + total = sign * note_totals.get(note.id, _ZERO)
178 + session.add(
179 + StatementLine(
180 + statement_id=statement.id,
181 + line_order=line_order,
182 + line_label=f"{note.note_number} — {note.title}",
183 + target_note_id=note.id,
184 + mapped_total=total,
185 + )
186 + )
187 + built.append(statement)
188 +
189 + session.flush()
190 + return BuildResult(statements=tuple(built), unmapped_accounts=tuple(sorted(set(unmapped))))
191 +
192 +
193 +def drill_down(session: Session, statement_line_id: int) -> dict:
194 + """Return the full lineage of a statement line to source file/sheet/row."""
195 + line = session.get(StatementLine, statement_line_id)
196 + if line is None:
197 + raise StatementBuildError(f"statement line {statement_line_id} does not exist")
198 + note = line.target_note
199 + if note is None:
200 + return {"line_id": line.id, "note": None, "accounts": []}
201 +
202 + rules = session.scalars(select(MappingRule).where(MappingRule.target_note_id == note.id)).all()
203 + codes = sorted({r.account_code for r in rules})
204 + version = _latest_import_version(session, note.year_id)
205 + balances = (
206 + session.scalars(
207 + select(LedgerBalance).where(
208 + LedgerBalance.year_id == note.year_id,
209 + LedgerBalance.import_version == version,
210 + LedgerBalance.account_full_code.in_(codes),
211 + )
212 + ).all()
213 + if version is not None and codes
214 + else []
215 + )
216 +
217 + accounts = []
218 + for balance in balances:
219 + source = session.get(SourceDocument, balance.source_document_id)
220 + accounts.append(
221 + {
222 + "account_full_code": balance.account_full_code,
223 + "account_name": balance.account_name,
224 + "closing": str(balance.closing),
225 + "source": {
226 + "filename": source.filename if source else None,
227 + "file_hash": source.file_hash if source else None,
228 + "sheet": balance.source_sheet,
229 + "row": balance.source_row,
230 + },
231 + }
232 + )
233 + return {
234 + "line_id": line.id,
235 + "line_label": line.line_label,
236 + "mapped_total": str(line.mapped_total) if line.mapped_total is not None else None,
237 + "note": {"id": note.id, "note_number": note.note_number, "title": note.title},
238 + "accounts": accounts,
239 + }
240 +
241 +
242 +__all__ = [
243 + "build_statements",
244 + "drill_down",
245 + "BuildResult",
246 + "StatementBuildError",
247 + "SECTION_POLICY",
248 + "SECTION_ORDER",
249 + "STATEMENT_LABELS_FA",
250 + "SECTION_LABELS_FA",
251 + "RENDERED_STATEMENTS",
252 +]
backend/src/aram_backend/statement_api.py new
+277
@@ -0,0 +1,277 @@
1 +"""HTTP API for the persistent, audited vertical slice (Phase 1, ADR-018).
2 +
3 +Company/year setup -> source upload + year-filtered import -> notes + mappings ->
4 +statement build -> drill-down to source file/sheet/row. All mutations are
5 +year-isolated and subject to the D-07 immutability guards.
6 +"""
7 +
8 +from __future__ import annotations
9 +
10 +from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
11 +from pydantic import BaseModel, Field
12 +from sqlalchemy import func, select
13 +from sqlalchemy.orm import Session
14 +
15 +from aram_backend.config import get_settings
16 +from aram_backend.database import get_session
17 +from aram_backend.domain.controls import BalanceRow, run_controls
18 +from aram_backend.ingestion import SourceRegistrationError, register_source_document
19 +from aram_backend.ledger_parser import LedgerParseError, parse_ledger
20 +from aram_backend.models import (
21 + Company,
22 + FinancialStatement,
23 + FiscalYear,
24 + LedgerBalance,
25 + MappingRule,
26 + NoteDefinition,
27 + StatementLine,
28 +)
29 +from aram_backend.services.ledger_import import import_ledger_balances
30 +from aram_backend.services.source_store import SourceStore, SourceStoreError
31 +from aram_backend.services.statement_build import (
32 + SECTION_LABELS_FA,
33 + STATEMENT_LABELS_FA,
34 + StatementBuildError,
35 + build_statements,
36 + drill_down,
37 +)
38 +
39 +router = APIRouter(prefix="/api/v1", tags=["statements"])
40 +
41 +
42 +class CompanyIn(BaseModel):
43 + code: str = Field(min_length=1, max_length=64)
44 + name: str = Field(min_length=1, max_length=256)
45 + year: int = Field(gt=0)
46 +
47 +
48 +class NoteIn(BaseModel):
49 + note_number: str = Field(min_length=1, max_length=32)
50 + title: str = Field(min_length=1, max_length=512)
51 + statement: str = Field(pattern="^(BS|IS|CF|EQ)$")
52 + section: str = Field(min_length=1, max_length=64)
53 +
54 +
55 +class MappingIn(BaseModel):
56 + account_code: str = Field(min_length=1, max_length=64)
57 + target_note_id: int
58 + mapping_type: str = Field(default="closing", max_length=32)
59 +
60 +
61 +def _year_or_404(session: Session, year_id: int) -> FiscalYear:
62 + year = session.get(FiscalYear, year_id)
63 + if year is None:
64 + raise HTTPException(status_code=404, detail="fiscal year not found")
65 + return year
66 +
67 +
68 +@router.post("/companies")
69 +def create_company(body: CompanyIn, session: Session = Depends(get_session)) -> dict:
70 + company = Company(code=body.code, name=body.name)
71 + session.add(company)
72 + session.flush()
73 + year = FiscalYear(company_id=company.id, year=body.year)
74 + session.add(year)
75 + session.commit()
76 + return {
77 + "company_id": company.id,
78 + "year_id": year.id,
79 + "year": year.year,
80 + "status": year.status.value,
81 + }
82 +
83 +
84 +@router.post("/years/{year_id}/ledger")
85 +def upload_ledger(
86 + year_id: int,
87 + file: UploadFile = File(...),
88 + session: Session = Depends(get_session),
89 +) -> dict:
90 + year = _year_or_404(session, year_id)
91 + content = file.file.read()
92 + store = SourceStore(get_settings().source_store_root)
93 + try:
94 + source = register_source_document(
95 + session,
96 + year_id=year_id,
97 + filename=file.filename or "ledger.xlsx",
98 + document_type="general_ledger",
99 + content=content,
100 + store=store,
101 + )
102 + except (SourceRegistrationError, SourceStoreError) as exc:
103 + raise HTTPException(status_code=422, detail=str(exc)) from exc
104 +
105 + try:
106 + records = [
107 + rec
108 + for rec in parse_ledger(content, file.filename or "ledger.xlsx")
109 + if rec.source_year == year.year
110 + ]
111 + except LedgerParseError as exc:
112 + raise HTTPException(status_code=422, detail=str(exc)) from exc
113 +
114 + next_version = (
115 + session.scalar(
116 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
117 + )
118 + or 0
119 + ) + 1
120 + try:
121 + count = import_ledger_balances(
122 + session,
123 + year_id=year_id,
124 + source_document_id=source.id,
125 + records=records,
126 + import_version=next_version,
127 + )
128 + except ValueError as exc:
129 + raise HTTPException(status_code=422, detail=str(exc)) from exc
130 + session.commit()
131 + return {
132 + "source_document_id": source.id,
133 + "file_hash": source.file_hash,
134 + "import_version": next_version,
135 + "accounts_imported": count,
136 + "rows_for_year": len(records),
137 + }
138 +
139 +
140 +@router.post("/years/{year_id}/notes")
141 +def create_note(year_id: int, body: NoteIn, session: Session = Depends(get_session)) -> dict:
142 + _year_or_404(session, year_id)
143 + note = NoteDefinition(
144 + year_id=year_id,
145 + note_number=body.note_number,
146 + title=body.title,
147 + configuration_json={"statement": body.statement, "section": body.section},
148 + )
149 + session.add(note)
150 + session.commit()
151 + return {"note_id": note.id, "note_number": note.note_number}
152 +
153 +
154 +@router.post("/years/{year_id}/mappings")
155 +def create_mapping(year_id: int, body: MappingIn, session: Session = Depends(get_session)) -> dict:
156 + _year_or_404(session, year_id)
157 + note = session.get(NoteDefinition, body.target_note_id)
158 + if note is None or note.year_id != year_id:
159 + raise HTTPException(status_code=422, detail="target note not found in this year")
160 + rule = MappingRule(
161 + year_id=year_id,
162 + rule_key=f"{body.account_code}->{body.target_note_id}",
163 + account_code=body.account_code,
164 + target_note_id=body.target_note_id,
165 + mapping_type=body.mapping_type,
166 + )
167 + session.add(rule)
168 + session.commit()
169 + return {"mapping_id": rule.id, "account_code": rule.account_code}
170 +
171 +
172 +@router.post("/years/{year_id}/statements/build")
173 +def build(year_id: int, session: Session = Depends(get_session)) -> dict:
174 + _year_or_404(session, year_id)
175 + try:
176 + result = build_statements(session, year_id)
177 + except StatementBuildError as exc:
178 + raise HTTPException(status_code=422, detail=str(exc)) from exc
179 + session.commit()
180 + return {
181 + "statements": [
182 + {"id": s.id, "type": s.statement_type.value, "version": s.version}
183 + for s in result.statements
184 + ],
185 + "unmapped_accounts": list(result.unmapped_accounts),
186 + }
187 +
188 +
189 +@router.get("/years/{year_id}/statements")
190 +def list_statements(year_id: int, session: Session = Depends(get_session)) -> dict:
191 + _year_or_404(session, year_id)
192 + statements = session.scalars(
193 + select(FinancialStatement)
194 + .where(FinancialStatement.year_id == year_id)
195 + .order_by(FinancialStatement.statement_type, FinancialStatement.version)
196 + ).all()
197 + payload = []
198 + for statement in statements:
199 + lines = session.scalars(
200 + select(StatementLine)
201 + .where(StatementLine.statement_id == statement.id)
202 + .order_by(StatementLine.line_order)
203 + ).all()
204 + payload.append(
205 + {
206 + "id": statement.id,
207 + "type": statement.statement_type.value,
208 + "label_fa": STATEMENT_LABELS_FA.get(statement.statement_type.value, ""),
209 + "version": statement.version,
210 + "lines": [
211 + {
212 + "id": ln.id,
213 + "line_order": ln.line_order,
214 + "label": ln.line_label,
215 + "mapped_total": str(ln.mapped_total)
216 + if ln.mapped_total is not None
217 + else None,
218 + "target_note_id": ln.target_note_id,
219 + }
220 + for ln in lines
221 + ],
222 + }
223 + )
224 + return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA}
225 +
226 +
227 +@router.get("/statement-lines/{line_id}/drilldown")
228 +def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict:
229 + try:
230 + return drill_down(session, line_id)
231 + except StatementBuildError as exc:
232 + raise HTTPException(status_code=404, detail=str(exc)) from exc
233 +
234 +
235 +@router.get("/years/{year_id}/preflight")
236 +def preflight(year_id: int, session: Session = Depends(get_session)) -> dict:
237 + year = _year_or_404(session, year_id)
238 + version = session.scalar(
239 + select(func.max(LedgerBalance.import_version)).where(LedgerBalance.year_id == year_id)
240 + )
241 + balances = (
242 + session.scalars(
243 + select(LedgerBalance).where(
244 + LedgerBalance.year_id == year_id, LedgerBalance.import_version == version
245 + )
246 + ).all()
247 + if version is not None
248 + else []
249 + )
250 + rows = [
251 + BalanceRow(
252 + row_number=b.source_row,
253 + account_code=b.account_full_code,
254 + opening=b.opening,
255 + debit=b.debit,
256 + credit=b.credit,
257 + closing=b.closing,
258 + )
259 + for b in balances
260 + ]
261 + rules = session.scalars(select(MappingRule).where(MappingRule.year_id == year_id)).all()
262 + from aram_backend.domain.controls import MappingTarget
263 +
264 + mappings: dict[str, list[MappingTarget]] = {}
265 + for rule in rules:
266 + mappings.setdefault(rule.account_code, []).append(
267 + MappingTarget(target=str(rule.target_note_id))
268 + )
269 + results = run_controls(rows, mappings)
270 + return {
271 + "year": year.year,
272 + "can_approve": all(r.passed for r in results if r.severity == "ERROR"),
273 + "controls": [
274 + {"code": r.code, "severity": r.severity, "passed": r.passed, "message_fa": r.message_fa}
275 + for r in results
276 + ],
277 + }
backend/tests/test_statement_build.py new
+340
@@ -0,0 +1,340 @@
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
docs/adr/ADR-018-persistent-statements-drilldown.md new
+59
@@ -0,0 +1,59 @@
1 +# ADR-018 — Persistent statements and drill-down lineage (Phase 1)
2 +
3 +- Status: Accepted (Phase 1 vertical slice)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 1, D1/D2 (year continuity, drill-down to file/sheet/row)
6 +
7 +## Context
8 +
9 +Phase 0 delivered the domain, `LedgerBalance`, mappings, notes and the
10 +`FinancialStatement`/`StatementLine` models, but no service that turns imported
11 +balances + mappings into persisted, versioned, auditable statements with a
12 +traceable lineage back to the source file/sheet/row.
13 +
14 +## Decision
15 +
16 +### Statement build
17 +
18 +`services/statement_build.build_statements(session, year_id, statement_types)`:
19 +
20 +- Reads the **latest import version** of `LedgerBalance` for the year.
21 +- Reads active `MappingRule` (account_code → note) and `NoteDefinition`
22 + (`configuration_json` carries `statement` and `section`).
23 +- Aggregates exact integer-rial closing balances per note, applies the display
24 + sign policy (ADR-013: debit-positive closing; display = sign × closing), and
25 + persists a new `FinancialStatement` version with ordered `StatementLine` rows
26 + (`mapped_total` in Rial, `target_note_id` set).
27 +- Only Draft years may build; Approved/Locked are blocked by the D-07 triggers.
28 +- Each build creates a new version (never mutates a prior snapshot).
29 +
30 +### Display sign policy (single source for the persistent engine)
31 +
32 +| Statement | Section | sign |
33 +|---|---|---|
34 +| BS | Assets | +1 |
35 +| BS | Liabilities | −1 |
36 +| BS | Equity | −1 |
37 +| IS | Revenue | −1 |
38 +| IS | Expenses | +1 |
39 +
40 +Phase 1 renders BS/IS; CF/EQ are deferred to Phase 4.
41 +
42 +### Drill-down lineage (D2)
43 +
44 +`drill_down(session, statement_line_id)` returns the full chain:
45 +`StatementLine → NoteDefinition → MappingRule(s) → LedgerBalance row(s) →
46 +SourceDocument (filename + SHA-256) + source_sheet + source_row`. Every statement
47 +total is therefore traceable to the exact source file, sheet and row.
48 +
49 +## Consequences
50 +
51 +- Statements are persisted, versioned, year-isolated and immutable once locked.
52 +- Any figure can be audited down to the originating ledger row.
53 +- The in-memory Pilot workbench remains the interactive editor; this persistent
54 + engine is the audited system of record.
55 +
56 +## Rejected alternatives
57 +
58 +- Storing drill-down as a denormalized blob on StatementLine: loses the live
59 + join to source and duplicates data; the relational chain is authoritative.