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

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

Synced Dec 4, 04:15 UTC

feat(output): Phase 6 reviewable statement outputs (XLSX + JSON) with lineage

- statement_export: latest-version BS/IS/CF/EQ + evaluated notes + full source lineage (file/SHA-256/sheet/row) as RTL XLSX (Summary/per-statement/Note/Lineage) and structured JSON. Exact integer-rial preserved; million-rial display-only (half-up, ADR-012). No new dependency (openpyxl). ADR-022. - API GET /years/{id}/statements/export?format=xlsx|json; workbench download buttons. - 3 tests (JSON exact rial + lineage, XLSX sheets/values, JSON serializable). Real-data proof: year 1404 export -> BS/IS, 340 lineage rows, Note 10; XLSX sheets Summary/BS/IS/Note 10/Lineage. Full suite: 288 passed; mypy services clean. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 11:22 UTC c4c37c0cff567814e2c5180ddadcc62a1ac5c2a6
7 files changed +477
backend/src/aram_backend/services/statement_export.py new
+259
@@ -0,0 +1,259 @@
1 +"""Reviewable statement outputs (Phase 6, booklet §15).
2 +
3 +Exports the persisted, audited statements (BS/IS/CF/EQ) plus evaluated notes and
4 +a full source-lineage register as a governed XLSX workbook and as structured
5 +JSON. Every figure is the exact integer-rial ``mapped_total`` from the latest
6 +statement version; a million-rial display column (half-up, ADR-012) is added for
7 +readability only and never replaces the exact rial. The lineage sheet traces each
8 +statement line to its source file/SHA-256/sheet/row (D2/D3), so the output is
9 +independently auditable. No new dependency: openpyxl is already required.
10 +"""
11 +
12 +from __future__ import annotations
13 +
14 +import json
15 +from datetime import UTC, datetime
16 +from decimal import Decimal
17 +from io import BytesIO
18 +from typing import Any, cast
19 +
20 +from openpyxl import Workbook
21 +from openpyxl.styles import Alignment, Font
22 +from openpyxl.utils import get_column_letter
23 +from sqlalchemy import func, select
24 +from sqlalchemy.orm import Session
25 +
26 +from aram_backend.domain.money import round_half_up
27 +from aram_backend.models import (
28 + FinancialStatement,
29 + FiscalYear,
30 + StatementLine,
31 + StatementType,
32 +)
33 +from aram_backend.services.note_engine import evaluate_year_notes
34 +from aram_backend.services.statement_build import (
35 + ALL_STATEMENTS,
36 + STATEMENT_LABELS_FA,
37 + drill_down,
38 +)
39 +
40 +_MILLION = Decimal(1_000_000)
41 +_RTL = Alignment(horizontal="right", readingOrder=2)
42 +
43 +
44 +class StatementExportError(ValueError):
45 + """Raised when statements cannot be exported safely."""
46 +
47 +
48 +def _latest_statement(
49 + session: Session, year_id: int, stype: StatementType
50 +) -> FinancialStatement | None:
51 + version = session.scalar(
52 + select(func.max(FinancialStatement.version)).where(
53 + FinancialStatement.year_id == year_id,
54 + FinancialStatement.statement_type == stype,
55 + )
56 + )
57 + if version is None:
58 + return None
59 + return session.scalar(
60 + select(FinancialStatement).where(
61 + FinancialStatement.year_id == year_id,
62 + FinancialStatement.statement_type == stype,
63 + FinancialStatement.version == version,
64 + )
65 + )
66 +
67 +
68 +def _ordered_lines(session: Session, statement_id: int) -> list[StatementLine]:
69 + return list(
70 + session.scalars(
71 + select(StatementLine)
72 + .where(StatementLine.statement_id == statement_id)
73 + .order_by(StatementLine.line_order)
74 + ).all()
75 + )
76 +
77 +
78 +def _million(rial: Decimal | None) -> int | None:
79 + if rial is None:
80 + return None
81 + return int(round_half_up(rial / _MILLION, 0))
82 +
83 +
84 +def collect_export(session: Session, year_id: int) -> dict[str, Any]:
85 + """Assemble the full export payload (statements + notes + lineage)."""
86 + year = session.get(FiscalYear, year_id)
87 + if year is None:
88 + raise StatementExportError(f"fiscal year {year_id} does not exist")
89 +
90 + statements: list[dict[str, Any]] = []
91 + lineage: list[dict[str, Any]] = []
92 + for code in ALL_STATEMENTS:
93 + statement = _latest_statement(session, year_id, StatementType(code))
94 + if statement is None:
95 + continue
96 + lines = _ordered_lines(session, statement.id)
97 + line_payload = []
98 + for line in lines:
99 + line_payload.append(
100 + {
101 + "line_order": line.line_order,
102 + "label": line.line_label,
103 + "mapped_total_rial": str(line.mapped_total)
104 + if line.mapped_total is not None
105 + else None,
106 + "mapped_total_million": _million(line.mapped_total),
107 + "target_note_id": line.target_note_id,
108 + }
109 + )
110 + detail = drill_down(session, line.id)
111 + note = detail.get("note")
112 + note_number = note.get("note_number") if isinstance(note, dict) else None
113 + for acc in cast(list[Any], detail.get("accounts", [])):
114 + if not isinstance(acc, dict):
115 + continue
116 + source = acc.get("source", {})
117 + lineage.append(
118 + {
119 + "statement": code,
120 + "line_label": line.line_label,
121 + "note_number": note_number,
122 + "account_full_code": acc.get("account_full_code"),
123 + "account_name": acc.get("account_name"),
124 + "effective_balance_rial": acc.get("effective_balance"),
125 + "filename": source.get("filename"),
126 + "file_hash": source.get("file_hash"),
127 + "sheet": source.get("sheet"),
128 + "source_row": source.get("row"),
129 + }
130 + )
131 + statements.append(
132 + {
133 + "type": code,
134 + "label_fa": STATEMENT_LABELS_FA.get(code, code),
135 + "version": statement.version,
136 + "lines": line_payload,
137 + }
138 + )
139 +
140 + notes = evaluate_year_notes(session, year_id)
141 + return {
142 + "year": year.year,
143 + "year_id": year_id,
144 + "company": year.company.name if year.company else "",
145 + "status": year.status.value,
146 + "generated_at": datetime.now(UTC).isoformat(),
147 + "statements": statements,
148 + "notes": notes,
149 + "lineage": lineage,
150 + }
151 +
152 +
153 +def export_statements_json(session: Session, year_id: int) -> dict[str, Any]:
154 + return collect_export(session, year_id)
155 +
156 +
157 +def _style_header(ws: Any, ncols: int) -> None:
158 + for col in range(1, ncols + 1):
159 + cell = ws.cell(row=1, column=col)
160 + cell.font = Font(bold=True)
161 + cell.alignment = _RTL
162 + ws.freeze_panes = "A2"
163 + ws.sheet_view.rightToLeft = True
164 +
165 +
166 +def _autosize(ws: Any) -> None:
167 + for col in ws.columns:
168 + width = max((len(str(c.value)) for c in col if c.value is not None), default=8)
169 + ws.column_dimensions[get_column_letter(col[0].column)].width = min(max(width + 2, 10), 60)
170 +
171 +
172 +def export_statements_workbook(session: Session, year_id: int) -> bytes:
173 + payload = collect_export(session, year_id)
174 + wb = Workbook()
175 +
176 + summary = wb.active
177 + summary.title = "Summary"
178 + summary.append(["field", "value"])
179 + summary.append(["year", payload["year"]])
180 + summary.append(["company", payload["company"]])
181 + summary.append(["status", payload["status"]])
182 + summary.append(["generated_at", payload["generated_at"]])
183 + for st in payload["statements"]:
184 + summary.append([f"{st['type']} version", st["version"]])
185 + summary.append(["lineage rows", len(payload["lineage"])])
186 + _style_header(summary, 2)
187 + _autosize(summary)
188 +
189 + for st in payload["statements"]:
190 + ws = wb.create_sheet(title=st["type"])
191 + ws.append(["line_order", "label", "mapped_total_rial", "mapped_total_million"])
192 + for line in st["lines"]:
193 + ws.append(
194 + [
195 + line["line_order"],
196 + line["label"],
197 + line["mapped_total_rial"],
198 + line["mapped_total_million"],
199 + ]
200 + )
201 + _style_header(ws, 4)
202 + _autosize(ws)
203 +
204 + for note in payload["notes"]:
205 + number = str(note.get("note_number", ""))
206 + title = f"Note {number}"[:31]
207 + ws = wb.create_sheet(title=title)
208 + ws.append(["row_order", "label", "formula", "value_rial", "accounts_referenced"])
209 + for row in note.get("rows", []):
210 + ws.append(
211 + [
212 + row.get("row_order"),
213 + row.get("label"),
214 + row.get("formula"),
215 + row.get("value"),
216 + ", ".join(row.get("accounts_referenced", [])),
217 + ]
218 + )
219 + _style_header(ws, 5)
220 + _autosize(ws)
221 +
222 + lineage_ws = wb.create_sheet(title="Lineage")
223 + headers = [
224 + "statement",
225 + "line_label",
226 + "note_number",
227 + "account_full_code",
228 + "account_name",
229 + "effective_balance_rial",
230 + "filename",
231 + "file_hash",
232 + "sheet",
233 + "source_row",
234 + ]
235 + lineage_ws.append(headers)
236 + for row in payload["lineage"]:
237 + lineage_ws.append([row.get(h) for h in headers])
238 + _style_header(lineage_ws, len(headers))
239 + _autosize(lineage_ws)
240 +
241 + buf = BytesIO()
242 + wb.save(buf)
243 + wb.close()
244 + return buf.getvalue()
245 +
246 +
247 +def export_statements_json_bytes(session: Session, year_id: int) -> bytes:
248 + return json.dumps(
249 + export_statements_json(session, year_id), ensure_ascii=False, indent=2
250 + ).encode("utf-8")
251 +
252 +
253 +__all__ = [
254 + "collect_export",
255 + "export_statements_json",
256 + "export_statements_json_bytes",
257 + "export_statements_workbook",
258 + "StatementExportError",
259 +]
backend/src/aram_backend/statement_api.py
+30
@@ -49,6 +49,11 @@ from aram_backend.services.statement_build import (
49 build_statements,
50 drill_down,
51 )
52 +from aram_backend.services.statement_export import (
53 + StatementExportError,
54 + export_statements_json_bytes,
55 + export_statements_workbook,
56 +)
57
58 router = APIRouter(prefix="/api/v1", tags=["statements"])
59
@@ -240,6 +245,31 @@ def list_statements(year_id: int, session: Session = Depends(get_session)) -> di
245 return {"statements": payload, "section_labels_fa": SECTION_LABELS_FA}
246
247
248 +@router.get("/years/{year_id}/statements/export")
249 +def export_statements(
250 + year_id: int, format: str = "xlsx", session: Session = Depends(get_session)
251 +) -> StreamingResponse:
252 + _year_or_404(session, year_id)
253 + try:
254 + if format == "json":
255 + data = export_statements_json_bytes(session, year_id)
256 + media = "application/json"
257 + ext = "json"
258 + elif format == "xlsx":
259 + data = export_statements_workbook(session, year_id)
260 + media = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
261 + ext = "xlsx"
262 + else:
263 + raise HTTPException(status_code=422, detail="format must be 'xlsx' or 'json'")
264 + except StatementExportError as exc:
265 + raise HTTPException(status_code=422, detail=str(exc)) from exc
266 + return StreamingResponse(
267 + iter([data]),
268 + media_type=media,
269 + headers={"Content-Disposition": f'attachment; filename="aram-statements-{year_id}.{ext}"'},
270 + )
271 +
272 +
273 @router.get("/statement-lines/{line_id}/drilldown")
274 def line_drilldown(line_id: int, session: Session = Depends(get_session)) -> dict:
275 try:
backend/tests/test_statement_export.py new
+120
@@ -0,0 +1,120 @@
1 +"""Phase 6 reviewable outputs: XLSX + JSON export with exact rial and lineage."""
2 +
3 +from __future__ import annotations
4 +
5 +import json
6 +from decimal import Decimal
7 +from io import BytesIO
8 +
9 +from openpyxl import load_workbook
10 +
11 +from aram_backend.ledger_parser import parse_ledger
12 +from aram_backend.models import (
13 + Company,
14 + FiscalYear,
15 + MappingRule,
16 + NoteDefinition,
17 + NoteRow,
18 + SourceDocument,
19 +)
20 +from aram_backend.services.ledger_import import import_ledger_balances
21 +from aram_backend.services.statement_build import build_statements
22 +from aram_backend.services.statement_export import (
23 + export_statements_json,
24 + export_statements_workbook,
25 +)
26 +
27 +_HEADER = (
28 + "حساب,ACCOUNT_NAME,year,نوع,kol,T1_CODE,T2_CODE,T3_CODE,T4_CODE,"
29 + "OPENING,Debit,Credit,CLOSING,مانده صورت مالی"
30 +)
31 +
32 +
33 +def _setup(session):
34 + company = Company(code="X1", name="شرکت نمونه")
35 + session.add(company)
36 + session.flush()
37 + year = FiscalYear(company_id=company.id, year=1404)
38 + session.add(year)
39 + session.flush()
40 + # Ordinary closing-based row: acct() reads closing (ADR-020) and the BS
41 + # Assets sign (+1) keeps it positive, so note value == statement line total.
42 + content = (_HEADER + "\n1101,نقد و بانک,1404,e,11,,,,,0,0,0,673740637000000,\n").encode("utf-8")
43 + records = list(parse_ledger(content, "ledger.csv", tolerant=True))
44 + src = SourceDocument(
45 + year_id=year.id, filename="ledger.csv", document_type="general_ledger", file_hash="a" * 64
46 + )
47 + session.add(src)
48 + session.flush()
49 + import_ledger_balances(
50 + session, year_id=year.id, source_document_id=src.id, records=records, import_version=1
51 + )
52 + note = NoteDefinition(
53 + year_id=year.id,
54 + note_number="10",
55 + title="دارایی‌های جاری",
56 + configuration_json={"statement": "BS", "section": "Assets"},
57 + )
58 + session.add(note)
59 + session.flush()
60 + session.add(
61 + MappingRule(
62 + year_id=year.id,
63 + rule_key="111101->n",
64 + account_code="111101",
65 + target_note_id=note.id,
66 + mapping_type="closing",
67 + )
68 + )
69 + session.add(NoteRow(note_id=note.id, row_order=0, label="جمع", formula_logic='acct("111101")'))
70 + session.flush()
71 + build_statements(session, year.id, statement_types=("BS",))
72 + return year.id
73 +
74 +
75 +def test_json_export_exact_rial_and_lineage(session):
76 + year_id = _setup(session)
77 + payload = export_statements_json(session, year_id)
78 + assert payload["year"] == 1404
79 + bs = next(s for s in payload["statements"] if s["type"] == "BS")
80 + line = bs["lines"][0]
81 + assert line["mapped_total_rial"] == "673740637000000"
82 + assert line["mapped_total_million"] == 673740637
83 + # Lineage traces to the exact source row.
84 + assert payload["lineage"], "lineage must not be empty"
85 + row = payload["lineage"][0]
86 + assert row["filename"] == "ledger.csv"
87 + assert row["source_row"] == 2
88 + assert row["effective_balance_rial"] == "673740637000000"
89 + # Note evaluated.
90 + note = payload["notes"][0]
91 + assert note["rows"][0]["value"] == "673740637000000"
92 +
93 +
94 +def test_xlsx_export_sheets_and_values(session):
95 + year_id = _setup(session)
96 + data = export_statements_workbook(session, year_id)
97 + wb = load_workbook(BytesIO(data), data_only=True)
98 + assert "Summary" in wb.sheetnames
99 + assert "BS" in wb.sheetnames
100 + assert "Lineage" in wb.sheetnames
101 + assert "Note 10" in wb.sheetnames
102 + bs = wb["BS"]
103 + # header row + one line; rial column is exact integer text.
104 + assert bs.cell(row=2, column=3).value == "673740637000000"
105 + assert bs.cell(row=2, column=4).value == 673740637
106 + lineage = wb["Lineage"]
107 + assert lineage.max_row >= 2
108 + wb.close()
109 +
110 +
111 +def test_json_export_is_serializable(session):
112 + year_id = _setup(session)
113 + payload = export_statements_json(session, year_id)
114 + # Must round-trip through JSON without Decimal leakage.
115 + text = json.dumps(payload, ensure_ascii=False)
116 + assert "673740637000000" in text
117 + assert isinstance(payload["statements"][0]["lines"][0]["mapped_total_rial"], str)
118 + assert Decimal(payload["statements"][0]["lines"][0]["mapped_total_rial"]) == Decimal(
119 + "673740637000000"
120 + )
docs/adr/ADR-022-statement-outputs.md new
+57
@@ -0,0 +1,57 @@
1 +# ADR-022 — Reviewable statement outputs (Phase 6)
2 +
3 +- Status: Accepted (Phase 6)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 6 (reviewable output), D2/D3 (drill-down lineage)
6 +
7 +## Context
8 +
9 +Phases 1–5 persist audited, versioned statements (BS/IS/CF/EQ) with exact
10 +integer-rial totals and a live drill-down chain to the source file/sheet/row, and
11 +provide an RTL workbench to build and inspect them. The product still needs a
12 +portable, independently reviewable artifact: an output a reviewer can open without
13 +the application and audit rial-for-rial against the source and the official
14 +statements.
15 +
16 +## Decision
17 +
18 +`services/statement_export.py` produces two artifacts from the **latest statement
19 +version** per type for a year:
20 +
21 +1. **XLSX workbook** (`export_statements_workbook`):
22 + - `Summary`: year, company, status, generation timestamp, per-statement version,
23 + lineage row count.
24 + - One sheet per statement (`BS`/`IS`/`CF`/`EQ`): ordered lines with the exact
25 + `mapped_total_rial` (text, never rounded) and a `mapped_total_million`
26 + display column (half-up, ADR-012) for readability only.
27 + - One sheet per evaluated note (`Note {number}`): row order, label, formula,
28 + exact `value_rial`, and referenced accounts.
29 + - `Lineage`: every statement line traced to account, effective balance, source
30 + filename, SHA-256, sheet and row (D2/D3).
31 + - Sheets are RTL (`rightToLeft`, reading order 2) with frozen header rows.
32 +2. **Structured JSON** (`export_statements_json` / `_bytes`): the same payload for
33 + machine review and diffing; all money is exact integer-rial **strings** (no
34 + float/Decimal leakage).
35 +
36 +API: `GET /api/v1/years/{id}/statements/export?format=xlsx|json` streams the
37 +artifact as an attachment. The workbench exposes both as download buttons.
38 +
39 +## Consequences
40 +
41 +- The exact rial is always preserved; the million-rial column is display-only and
42 + never replaces it (P-02, ADR-012).
43 +- Every output figure is independently traceable to its source row (D2/D3).
44 +- No new dependency: openpyxl is already required (ADR-017). PDF output is
45 + deliberately deferred — it would need a new rendering dependency and a separate
46 + ADR; XLSX + JSON already satisfy reviewable, auditable output.
47 +- Export reads the latest persisted version; it never mutates statements or source
48 + data and works on Approved/Locked years (read-only).
49 +
50 +## Rejected alternatives
51 +
52 +- Rendering PDF directly: adds a dependency (reportlab/weasyprint) without a
53 + present need; XLSX matches the official workbook format reviewers already use.
54 +- Exporting rounded million-rial as the primary figure: violates exact-rial
55 + preservation (P-02); rounding is display-only.
56 +- Recomputing totals at export time: would diverge from the persisted, audited
57 + statement version; export must reflect the system of record exactly.
frontend/src/App.test.tsx
+2
@@ -19,6 +19,8 @@ vi.mock('./api/client', async () => {
19 createMapping: vi.fn(),
20 importMappings: vi.fn(),
21 exportMappingsUrl: (id: number) => `/api/v1/years/${id}/mappings/export`,
22 + exportStatementsUrl: (id: number, format: string) =>
23 + `/api/v1/years/${id}/statements/export?format=${format}`,
24 },
25 }
26 })
frontend/src/api/client.ts
+3
@@ -83,4 +83,7 @@ export const api = {
83 request<MappingImportResult>(`/years/${yearId}/mappings/import`, multipart(file)),
84
85 exportMappingsUrl: (yearId: number) => `${BASE}/years/${yearId}/mappings/export`,
86 +
87 + exportStatementsUrl: (yearId: number, format: 'xlsx' | 'json') =>
88 + `${BASE}/years/${yearId}/statements/export?format=${format}`,
89 }
frontend/src/components/StatementView.tsx
+6
@@ -62,6 +62,12 @@ export default function StatementView({ yearId, refreshKey }: Props) {
62 <button type="button" onClick={build} disabled={busy}>
63 {busy ? 'در حال ساخت…' : 'ساخت صورت‌های مالی'}
64 </button>
65 + <a className="button" href={api.exportStatementsUrl(yearId, 'xlsx')} download>
66 + خروجی اکسل
67 + </a>
68 + <a className="button" href={api.exportStatementsUrl(yearId, 'json')} download>
69 + خروجی JSON
70 + </a>
71 <div className="tabs">
72 {['BS', 'IS', 'CF', 'EQ'].map((t) => (
73 <button