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
+]