@davoodmehraban89 / Aram / commits / 495612b
Fork 0

feat(statements): add explicit-policy read-only BS presentation candidate with balance equation

davoodmehraban89 committed Oct 31, 2026 at 00:33 UTC 495612b907417385a81890e848443afab557d00e
1 file changed +217
backend/src/aram_backend/balance_sheet_candidate.py new
+217
@@ -0,0 +1,217 @@
1 +"""Non-official balance-sheet presentation candidate with explicit accounting policy.
2 +
3 +This is a read-only analyst preview, not an Iranian statutory financial
4 +statement. It uses full-precision Decimal arithmetic and never infers a
5 +debit/credit nature, classification or sign from the source chart of accounts.
6 +An independently authorized finance owner must still approve each policy.
7 +"""
8 +from __future__ import annotations
9 +
10 +from dataclasses import asdict, dataclass
11 +from decimal import Decimal
12 +from hashlib import sha256
13 +import json
14 +from typing import Any, Sequence
15 +
16 +from aram_backend.coverage_preview import CoverageError
17 +from aram_backend.reconciliation_review import (
18 + NoteReference, ReconciliationReview, _money, _sum_exact,
19 + reconcile_workbook_for_review,
20 +)
21 +
22 +MAX_POLICIES = 10_000
23 +CATEGORIES = frozenset({"ASSETS", "LIABILITIES", "EQUITY"})
24 +
25 +
26 +@dataclass(frozen=True)
27 +class BalanceSheetLinePolicy:
28 + """Explicit external presentation rule; never a source of financial authority."""
29 +
30 + statement_section: str
31 + note_number: str
32 + subnote_code: str
33 + category: str
34 + sign_multiplier: int
35 + line_label: str
36 + policy_evidence_ref: str
37 +
38 +
39 +@dataclass(frozen=True)
40 +class CandidateBalanceSheetLine:
41 + statement_section: str
42 + note_number: str
43 + subnote_code: str
44 + category: str
45 + sign_multiplier: int
46 + line_label: str
47 + source_closing_exposure: str
48 + presentation_amount: str
49 + note_reference_evidence: str
50 + policy_evidence_ref: str
51 +
52 +
53 +@dataclass(frozen=True)
54 +class BalanceSheetCandidate:
55 + company_code: str
56 + fiscal_year: int
57 + source_sha256: str
58 + note_references_sha256: str
59 + presentation_policies_sha256: str
60 + assets_total: str
61 + liabilities_total: str
62 + equity_total: str
63 + balance_difference: str
64 + lines: tuple[CandidateBalanceSheetLine, ...]
65 + findings: tuple[str, ...]
66 + arithmetically_balanced: bool
67 + eligible_for_analyst_review: bool
68 + kind: str = "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE"
69 + official_financial_statement: bool = False
70 + accounting_policy_authorized: bool = False
71 + independently_reviewed: bool = False
72 + export_authorized: bool = False
73 + releasable: bool = False
74 +
75 + def to_dict(self) -> dict[str, Any]:
76 + return asdict(self)
77 +
78 +
79 +def _required_text(value: object, label: str, *, blank_ok: bool = False) -> str:
80 + if not isinstance(value, str) or len(value) > 256:
81 + raise CoverageError("INVALID_PRESENTATION_" + label)
82 + if (value != value.strip() or (not value and not blank_ok)
83 + or any(ord(char) < 32 or ord(char) == 127 for char in value)):
84 + raise CoverageError("INVALID_PRESENTATION_" + label)
85 + return value
86 +
87 +
88 +def _key(policy: BalanceSheetLinePolicy) -> tuple[str, str, str]:
89 + return policy.statement_section, policy.note_number, policy.subnote_code
90 +
91 +
92 +def _policies(
93 + policies: Sequence[BalanceSheetLinePolicy],
94 +) -> tuple[dict[tuple[str, str, str], BalanceSheetLinePolicy], str]:
95 + if not isinstance(policies, (tuple, list)) or len(policies) > MAX_POLICIES:
96 + raise CoverageError("INVALID_PRESENTATION_POLICIES")
97 + selected: dict[tuple[str, str, str], BalanceSheetLinePolicy] = {}
98 + for policy in policies:
99 + if not isinstance(policy, BalanceSheetLinePolicy):
100 + raise CoverageError("INVALID_PRESENTATION_POLICY")
101 + _required_text(policy.statement_section, "SECTION")
102 + _required_text(policy.note_number, "NOTE")
103 + _required_text(policy.subnote_code, "SUBNOTE", blank_ok=True)
104 + _required_text(policy.line_label, "LABEL")
105 + _required_text(policy.policy_evidence_ref, "EVIDENCE")
106 + if policy.category not in CATEGORIES:
107 + raise CoverageError("INVALID_PRESENTATION_CATEGORY")
108 + if type(policy.sign_multiplier) is not int or policy.sign_multiplier not in {-1, 1}:
109 + raise CoverageError("INVALID_PRESENTATION_SIGN")
110 + key = _key(policy)
111 + if key in selected:
112 + raise CoverageError("DUPLICATE_PRESENTATION_POLICY")
113 + selected[key] = policy
114 + canonical = [
115 + asdict(selected[key]) for key in sorted(selected)
116 + ]
117 + digest = sha256(
118 + json.dumps(
119 + canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":"),
120 + ).encode("utf-8")
121 + ).hexdigest()
122 + return selected, digest
123 +
124 +
125 +def build_balance_sheet_candidate(
126 + workbook_bytes: bytes, *,
127 + company_code: str,
128 + fiscal_year: int,
129 + references: Sequence[NoteReference],
130 + policies: Sequence[BalanceSheetLinePolicy],
131 +) -> BalanceSheetCandidate:
132 + """Build ONLY a traceable unsigned BS analyst presentation candidate.
133 +
134 + Every candidate BS note must have an exact reference AND one explicit
135 + accounting policy. Other statement notes are not presented as BS rows.
136 + All mapped accounts across statements still undergo reconciliation.
137 + """
138 + policy_by_note, policy_digest = _policies(policies)
139 + review: ReconciliationReview = reconcile_workbook_for_review(
140 + workbook_bytes, company_code=company_code,
141 + fiscal_year=fiscal_year, references=references,
142 + )
143 + if (review.kind != "UNAPPROVED_NOTE_RECONCILIATION_REVIEW"
144 + or review.financial_statement or review.trusted_approvals
145 + or review.approved or review.releasable):
146 + raise CoverageError("REVIEW_PROVENANCE_INVALID")
147 +
148 + bs_notes = {
149 + (note.section, note.note_number, note.subnote_code): note
150 + for note in review.notes if note.statement == "BS"
151 + }
152 + findings: list[str] = []
153 + if not review.matched_for_analyst_review:
154 + findings.append("UPSTREAM_RECONCILIATION_BLOCKED")
155 + if not bs_notes:
156 + findings.append("NO_BALANCE_SHEET_NOTES")
157 + missing = sorted(set(bs_notes) - set(policy_by_note))
158 + extra = sorted(set(policy_by_note) - set(bs_notes))
159 + if missing:
160 + findings.append("MISSING_EXPLICIT_PRESENTATION_POLICY")
161 + if extra:
162 + findings.append("ORPHAN_PRESENTATION_POLICY")
163 +
164 + buckets: dict[str, list[Decimal]] = {cat: [] for cat in sorted(CATEGORIES)}
165 + output: list[CandidateBalanceSheetLine] = []
166 + for target in sorted(set(bs_notes) & set(policy_by_note)):
167 + note = bs_notes[target]
168 + policy = policy_by_note[target]
169 + if not note.matched or note.candidate_closing_exposure is None:
170 + continue
171 + # Display amount uses an explicit sign; never guessed from account codes.
172 + exposure = _money(note.candidate_closing_exposure)
173 + with __import__("decimal").localcontext() as context:
174 + context.prec = 256
175 + displayed = exposure * policy.sign_multiplier
176 + buckets[policy.category].append(displayed)
177 + if displayed < 0:
178 + findings.append("NEGATIVE_PRESENTATION_AMOUNT")
179 + output.append(CandidateBalanceSheetLine(
180 + statement_section=policy.statement_section,
181 + note_number=policy.note_number, subnote_code=policy.subnote_code,
182 + category=policy.category, sign_multiplier=policy.sign_multiplier,
183 + line_label=policy.line_label,
184 + source_closing_exposure=str(exposure),
185 + presentation_amount=str(displayed),
186 + note_reference_evidence=note.evidence_ref or "",
187 + policy_evidence_ref=policy.policy_evidence_ref,
188 + ))
189 +
190 + totals = {key: _sum_exact(values) for key, values in buckets.items()}
191 + diff = _sum_exact([
192 + totals["ASSETS"], -totals["LIABILITIES"], -totals["EQUITY"]
193 + ])
194 + if diff != 0:
195 + findings.append("BALANCE_SHEET_DOES_NOT_BALANCE")
196 + # A balanced collection of negative offsetting lines is not accepted
197 + # as analyst-ready even when the equation happens to hold.
198 + if not any(line.category == "ASSETS" for line in output):
199 + findings.append("NO_ASSET_LINES")
200 + if not any(line.category == "LIABILITIES" for line in output):
201 + findings.append("NO_LIABILITY_LINES")
202 + if not any(line.category == "EQUITY" for line in output):
203 + findings.append("NO_EQUITY_LINES")
204 +
205 + return BalanceSheetCandidate(
206 + company_code=review.company_code, fiscal_year=review.fiscal_year,
207 + source_sha256=review.source_sha256,
208 + note_references_sha256=review.reference_sha256,
209 + presentation_policies_sha256=policy_digest,
210 + assets_total=str(totals["ASSETS"]),
211 + liabilities_total=str(totals["LIABILITIES"]),
212 + equity_total=str(totals["EQUITY"]),
213 + balance_difference=str(diff), lines=tuple(output),
214 + findings=tuple(sorted(set(findings))),
215 + arithmetically_balanced=diff == 0,
216 + eligible_for_analyst_review=not findings and bool(output),
217 + )