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

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

Synced Dec 3, 19:30 UTC

feat(statements): add explicit-policy read-only changes-in-equity candidate

davoodmehraban89 committed Oct 31, 2026 at 08:13 UTC f028a9b18971bbaf8811ad347d286872806fbddb
1 file changed +417
backend/src/aram_backend/equity_changes_candidate.py new
+417
@@ -0,0 +1,417 @@
1 +"""Unsigned statement of changes in equity candidate.
2 +
3 +Read-only, exact-Decimal arithmetic over a scoped Pilot workbook. Requires
4 +explicit note-level component, movement classification and debit-net sign
5 +policies. It does not infer the nature of an equity transaction or issue an
6 +official financial statement.
7 +"""
8 +from __future__ import annotations
9 +
10 +from dataclasses import asdict, dataclass
11 +from decimal import Decimal
12 +from hashlib import sha256
13 +from io import BytesIO
14 +import json
15 +from typing import Any, Sequence
16 +
17 +from openpyxl import load_workbook
18 +
19 +from aram_backend.coverage_preview import (
20 + CoverageError, _assert_visible, _guard_archive, preview_mapping_coverage,
21 +)
22 +from aram_backend.pilot_workbook import SHEET_HEADERS
23 +from aram_backend.reconciliation_review import (
24 + NoteReference, _money, _sum_exact, reconcile_workbook_for_review,
25 +)
26 +
27 +MAX_POLICIES = 10_000
28 +EQUITY_COMPONENTS = frozenset({
29 + "SHARE_CAPITAL", "SHARE_PREMIUM", "RETAINED_EARNINGS",
30 + "REVALUATION_SURPLUS", "OTHER_RESERVES", "NONCONTROLLING_INTEREST",
31 + "OTHER_EQUITY",
32 +})
33 +MOVEMENT_CATEGORIES = frozenset({
34 + "CAPITAL_CONTRIBUTION", "NET_PROFIT_LOSS", "DIVIDENDS",
35 + "OTHER_COMPREHENSIVE_INCOME", "TRANSFER",
36 + "PRIOR_PERIOD_ADJUSTMENT", "OTHER_MOVEMENT",
37 +})
38 +
39 +
40 +@dataclass(frozen=True)
41 +class EquityMovementPolicy:
42 + statement_section: str
43 + note_number: str
44 + subnote_code: str
45 + equity_component: str
46 + movement_category: str
47 + sign_multiplier: int
48 + line_label: str
49 + policy_evidence_ref: str
50 +
51 +
52 +@dataclass(frozen=True)
53 +class EquityAccountMovement:
54 + account_code: str
55 + account_name: str
56 + source_excel_row: int
57 + source_row: int
58 + statement_section: str
59 + note_number: str
60 + subnote_code: str
61 + equity_component: str
62 + movement_category: str
63 + sign_multiplier: int
64 + opening_balance: str
65 + debit_turnover: str
66 + credit_turnover: str
67 + movement_amount: str
68 + closing_balance: str
69 + policy_evidence_ref: str
70 +
71 +
72 +@dataclass(frozen=True)
73 +class EquityNoteMovement:
74 + statement_section: str
75 + note_number: str
76 + subnote_code: str
77 + equity_component: str
78 + movement_category: str
79 + opening_balance: str
80 + movement_amount: str
81 + closing_balance: str
82 + source_closing_exposure: str
83 + note_reference_evidence: str
84 + policy_evidence_ref: str
85 +
86 +
87 +@dataclass(frozen=True)
88 +class EquityComponentTotal:
89 + equity_component: str
90 + opening_balance: str
91 + movement_amount: str
92 + closing_balance: str
93 +
94 +
95 +@dataclass(frozen=True)
96 +class EquityChangesCandidate:
97 + company_code: str
98 + fiscal_year: int
99 + source_sha256: str
100 + note_references_sha256: str
101 + presentation_policies_sha256: str
102 + opening_equity_total: str
103 + capital_contributions: str
104 + net_profit_loss_movements: str
105 + dividends: str
106 + other_comprehensive_income: str
107 + transfers: str
108 + prior_period_adjustments: str
109 + other_movements: str
110 + total_movement: str
111 + closing_equity_total: str
112 + rollforward_difference: str
113 + component_totals: tuple[EquityComponentTotal, ...]
114 + note_movements: tuple[EquityNoteMovement, ...]
115 + account_movements: tuple[EquityAccountMovement, ...]
116 + findings: tuple[str, ...]
117 + eligible_for_analyst_review: bool
118 + kind: str = "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE"
119 + official_financial_statement: bool = False
120 + accounting_policy_authorized: bool = False
121 + source_ledger_completeness_verified: bool = False
122 + independently_reviewed: bool = False
123 + export_authorized: bool = False
124 + releasable: bool = False
125 +
126 + def to_dict(self) -> dict[str, Any]:
127 + return asdict(self)
128 +
129 +
130 +def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
131 + if (not isinstance(value, str) or len(value) > 256
132 + or value != value.strip() or (not value and not blank_ok)
133 + or any(ord(char) < 32 or ord(char) == 127 for char in value)):
134 + raise CoverageError("INVALID_EQUITY_POLICY_" + label)
135 + return value
136 +
137 +
138 +def _policy_key(
139 + policy: EquityMovementPolicy,
140 +) -> tuple[str, str, str]:
141 + return policy.statement_section, policy.note_number, policy.subnote_code
142 +
143 +
144 +def _validate_policies(
145 + policies: Sequence[EquityMovementPolicy],
146 +) -> tuple[dict[tuple[str, str, str], EquityMovementPolicy], str]:
147 + if not isinstance(policies, (tuple, list)) or len(policies) > MAX_POLICIES:
148 + raise CoverageError("INVALID_EQUITY_POLICIES")
149 + selected: dict[tuple[str, str, str], EquityMovementPolicy] = {}
150 + for policy in policies:
151 + if not isinstance(policy, EquityMovementPolicy):
152 + raise CoverageError("INVALID_EQUITY_POLICY")
153 + _text(policy.statement_section, "SECTION")
154 + _text(policy.note_number, "NOTE")
155 + _text(policy.subnote_code, "SUBNOTE", blank_ok=True)
156 + _text(policy.line_label, "LABEL")
157 + _text(policy.policy_evidence_ref, "EVIDENCE")
158 + if (not isinstance(policy.equity_component, str)
159 + or policy.equity_component not in EQUITY_COMPONENTS):
160 + raise CoverageError("INVALID_EQUITY_COMPONENT")
161 + if (not isinstance(policy.movement_category, str)
162 + or policy.movement_category not in MOVEMENT_CATEGORIES):
163 + raise CoverageError("INVALID_EQUITY_MOVEMENT_CATEGORY")
164 + if type(policy.sign_multiplier) is not int or policy.sign_multiplier not in (-1, 1):
165 + raise CoverageError("INVALID_EQUITY_SIGN")
166 + key = _policy_key(policy)
167 + if key in selected:
168 + raise CoverageError("DUPLICATE_EQUITY_POLICY")
169 + selected[key] = policy
170 + canonical = [asdict(selected[key]) for key in sorted(selected)]
171 + digest = sha256(json.dumps(
172 + canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":"),
173 + ).encode("utf-8")).hexdigest()
174 + return selected, digest
175 +
176 +
177 +def build_equity_changes_candidate(
178 + workbook_bytes: bytes, *, company_code: str, fiscal_year: int,
179 + references: Sequence[NoteReference],
180 + policies: Sequence[EquityMovementPolicy],
181 +) -> EquityChangesCandidate:
182 + """Create a nonofficial equity movement candidate from explicit note policies.
183 +
184 + Source balances are assumed to be debit-net signed. Each note's sign
185 + multiplier converts its opening, debit-credit movement and closing to
186 + presentation sign. All accounts assigned to one note inherit that note's
187 + single movement classification; use separate subnotes when a note mixes
188 + transaction types. That constraint is intentionally explicit.
189 + """
190 + selected, policy_hash = _validate_policies(policies)
191 + preview = preview_mapping_coverage(
192 + workbook_bytes, company_code=company_code, fiscal_year=fiscal_year,
193 + )
194 + review = reconcile_workbook_for_review(
195 + workbook_bytes, company_code=company_code,
196 + fiscal_year=fiscal_year, references=references,
197 + )
198 + if (review.kind != "UNAPPROVED_NOTE_RECONCILIATION_REVIEW"
199 + or review.financial_statement or review.trusted_approvals
200 + or review.approved or review.releasable
201 + or preview.financial_statement or preview.trusted_approvals
202 + or preview.releasable
203 + or preview.source_sha256 != review.source_sha256):
204 + raise CoverageError("EQUITY_REVIEW_PROVENANCE_INVALID")
205 +
206 + eq_notes = {
207 + (note.section, note.note_number, note.subnote_code): note
208 + for note in preview.notes if note.statement == "EQ"
209 + }
210 + findings: list[str] = []
211 + if not review.matched_for_analyst_review:
212 + findings.append("UPSTREAM_RECONCILIATION_BLOCKED")
213 + if not eq_notes:
214 + findings.append("NO_EQUITY_NOTES")
215 + if set(eq_notes) - set(selected):
216 + findings.append("MISSING_EQUITY_POLICY")
217 + if set(selected) - set(eq_notes):
218 + findings.append("ORPHAN_EQUITY_POLICY")
219 +
220 + ref_by_key = {
221 + (note.statement, note.section, note.note_number, note.subnote_code): note
222 + for note in review.notes
223 + }
224 + trace_by_note: dict[tuple[str, str, str], list[Any]] = {}
225 + for trace in preview.accounts:
226 + if trace.included and trace.target_statement == "EQ":
227 + key = (trace.target_section or "", trace.target_note or "",
228 + trace.target_subnote or "")
229 + trace_by_note.setdefault(key, []).append(trace)
230 +
231 + try:
232 + book = load_workbook(
233 + BytesIO(workbook_bytes), read_only=False,
234 + data_only=False, keep_links=False,
235 + )
236 + except Exception as exc:
237 + raise CoverageError("EQUITY_WORKBOOK_INVALID") from exc
238 + try:
239 + for sheet in book.worksheets:
240 + _assert_visible(sheet)
241 + for name, headers in SHEET_HEADERS.items():
242 + if name not in book or tuple(cell.value for cell in book[name][1]) != headers:
243 + raise CoverageError("EQUITY_WORKBOOK_INVALID")
244 +
245 + account_rows: dict[str, tuple[int, dict[str, Any]]] = {}
246 + sheet = book["Accounts"]
247 + for row_number, values in enumerate(
248 + sheet.iter_rows(min_row=2, values_only=True), 2,
249 + ):
250 + row = dict(zip(SHEET_HEADERS["Accounts"], values))
251 + if not any(value is not None and str(value).strip() for value in row.values()):
252 + continue
253 + if (row.get("company_code") == review.company_code
254 + and type(row.get("fiscal_year")) is int
255 + and row["fiscal_year"] == review.fiscal_year):
256 + code = row.get("account_full_code")
257 + if not isinstance(code, str) or not code.strip():
258 + raise CoverageError("EQUITY_ACCOUNT_CODE_INVALID")
259 + code = code.strip()
260 + if code in account_rows:
261 + raise CoverageError("EQUITY_DUPLICATE_ACCOUNT")
262 + account_rows[code] = (row_number, row)
263 +
264 + note_lines: list[EquityNoteMovement] = []
265 + account_lines: list[EquityAccountMovement] = []
266 + component_opening: dict[str, list[Decimal]] = {
267 + item: [] for item in sorted(EQUITY_COMPONENTS)
268 + }
269 + component_movement: dict[str, list[Decimal]] = {
270 + item: [] for item in sorted(EQUITY_COMPONENTS)
271 + }
272 + component_closing: dict[str, list[Decimal]] = {
273 + item: [] for item in sorted(EQUITY_COMPONENTS)
274 + }
275 + movement_buckets: dict[str, list[Decimal]] = {
276 + item: [] for item in sorted(MOVEMENT_CATEGORIES)
277 + }
278 + opening_values: list[Decimal] = []
279 + closing_values: list[Decimal] = []
280 + movement_values: list[Decimal] = []
281 +
282 + for key in sorted(set(eq_notes) & set(selected)):
283 + note = eq_notes[key]
284 + policy = selected[key]
285 + matched = ref_by_key.get(("EQ", *key))
286 + if matched is None or not matched.matched:
287 + findings.append("EQUITY_NOTE_REFERENCE_NOT_MATCHED")
288 + continue
289 + traces = trace_by_note.get(key, [])
290 + if not traces:
291 + findings.append("EQUITY_NOTE_WITHOUT_ACCOUNTS")
292 + continue
293 + note_openings: list[Decimal] = []
294 + note_debits: list[Decimal] = []
295 + note_credits: list[Decimal] = []
296 + note_closings: list[Decimal] = []
297 + for trace in traces:
298 + source = account_rows.get(trace.account_code)
299 + if source is None:
300 + raise CoverageError("EQUITY_SOURCE_ACCOUNT_MISSING")
301 + excel_row, row = source
302 + if excel_row != trace.account_excel_row:
303 + raise CoverageError("EQUITY_SOURCE_ROW_MISMATCH")
304 + opening, debit, credit, closing = (
305 + _money(str(row[field]))
306 + for field in ("opening", "debit", "credit", "closing")
307 + )
308 + source_movement = _sum_exact([debit, -credit])
309 + if _sum_exact([opening, source_movement, -closing]) != 0:
310 + raise CoverageError("EQUITY_ACCOUNT_ROLLFORWARD_INVALID")
311 + if debit < 0 or credit < 0:
312 + raise CoverageError("EQUITY_NEGATIVE_TURNOVER")
313 + sign = policy.sign_multiplier
314 + shown_opening = opening * sign
315 + shown_movement = source_movement * sign
316 + shown_closing = closing * sign
317 + note_openings.append(opening)
318 + note_debits.append(debit)
319 + note_credits.append(credit)
320 + note_closings.append(closing)
321 + component_opening[policy.equity_component].append(shown_opening)
322 + component_movement[policy.equity_component].append(shown_movement)
323 + component_closing[policy.equity_component].append(shown_closing)
324 + movement_buckets[policy.movement_category].append(shown_movement)
325 + account_lines.append(EquityAccountMovement(
326 + account_code=trace.account_code,
327 + account_name=trace.account_name,
328 + source_excel_row=excel_row,
329 + source_row=trace.source_row,
330 + statement_section=key[0], note_number=key[1],
331 + subnote_code=key[2],
332 + equity_component=policy.equity_component,
333 + movement_category=policy.movement_category,
334 + sign_multiplier=sign,
335 + opening_balance=str(shown_opening),
336 + debit_turnover=str(debit),
337 + credit_turnover=str(credit),
338 + movement_amount=str(shown_movement),
339 + closing_balance=str(shown_closing),
340 + policy_evidence_ref=policy.policy_evidence_ref,
341 + ))
342 + opening_raw = _sum_exact(note_openings)
343 + debit_raw = _sum_exact(note_debits)
344 + credit_raw = _sum_exact(note_credits)
345 + closing_raw = _sum_exact(note_closings)
346 + if _money(note.closing_exposure) != closing_raw:
347 + raise CoverageError("EQUITY_NOTE_CLOSING_MISMATCH")
348 + opening_shown = opening_raw * policy.sign_multiplier
349 + movement_shown = _sum_exact([debit_raw, -credit_raw]) * policy.sign_multiplier
350 + closing_shown = closing_raw * policy.sign_multiplier
351 + if _sum_exact([opening_shown, movement_shown, -closing_shown]) != 0:
352 + findings.append("EQUITY_NOTE_ROLLFORWARD_MISMATCH")
353 + opening_values.append(opening_shown)
354 + movement_values.append(movement_shown)
355 + closing_values.append(closing_shown)
356 + note_lines.append(EquityNoteMovement(
357 + statement_section=key[0], note_number=key[1],
358 + subnote_code=key[2], equity_component=policy.equity_component,
359 + movement_category=policy.movement_category,
360 + opening_balance=str(opening_shown),
361 + movement_amount=str(movement_shown),
362 + closing_balance=str(closing_shown),
363 + source_closing_exposure=str(closing_raw),
364 + note_reference_evidence=matched.evidence_ref or "",
365 + policy_evidence_ref=policy.policy_evidence_ref,
366 + ))
367 +
368 + opening_total = _sum_exact(opening_values)
369 + movement_total = _sum_exact(movement_values)
370 + closing_total = _sum_exact(closing_values)
371 + rollforward = _sum_exact([opening_total, movement_total, -closing_total])
372 + if rollforward != 0:
373 + findings.append("EQUITY_TOTAL_ROLLFORWARD_MISMATCH")
374 +
375 + component_totals = tuple(
376 + EquityComponentTotal(
377 + equity_component=component,
378 + opening_balance=str(_sum_exact(component_opening[component])),
379 + movement_amount=str(_sum_exact(component_movement[component])),
380 + closing_balance=str(_sum_exact(component_closing[component])),
381 + )
382 + for component in sorted(EQUITY_COMPONENTS)
383 + if (component_opening[component] or component_movement[component]
384 + or component_closing[component])
385 + )
386 + movement_totals = {
387 + category: _sum_exact(values)
388 + for category, values in movement_buckets.items()
389 + }
390 + if not any(note_lines):
391 + findings.append("NO_EQUITY_MOVEMENTS")
392 + return EquityChangesCandidate(
393 + company_code=review.company_code, fiscal_year=review.fiscal_year,
394 + source_sha256=review.source_sha256,
395 + note_references_sha256=review.reference_sha256,
396 + presentation_policies_sha256=policy_hash,
397 + opening_equity_total=str(opening_total),
398 + capital_contributions=str(movement_totals["CAPITAL_CONTRIBUTION"]),
399 + net_profit_loss_movements=str(movement_totals["NET_PROFIT_LOSS"]),
400 + dividends=str(movement_totals["DIVIDENDS"]),
401 + other_comprehensive_income=str(movement_totals["OTHER_COMPREHENSIVE_INCOME"]),
402 + transfers=str(movement_totals["TRANSFER"]),
403 + prior_period_adjustments=str(movement_totals["PRIOR_PERIOD_ADJUSTMENT"]),
404 + other_movements=str(movement_totals["OTHER_MOVEMENT"]),
405 + total_movement=str(movement_total),
406 + closing_equity_total=str(closing_total),
407 + rollforward_difference=str(rollforward),
408 + component_totals=component_totals,
409 + note_movements=tuple(note_lines),
410 + account_movements=tuple(sorted(
411 + account_lines, key=lambda item: item.account_code,
412 + )),
413 + findings=tuple(sorted(set(findings))),
414 + eligible_for_analyst_review=not findings and bool(note_lines),
415 + )
416 + finally:
417 + book.close()