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

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

Synced Dec 3, 19:30 UTC

codex/aram-five-statement-orchestrator-20261031
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 420 lines 17.3 KB
Raw
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 line_label: str
80 opening_balance: str
81 movement_amount: str
82 closing_balance: str
83 source_closing_exposure: str
84 note_reference_evidence: str
85 policy_evidence_ref: str
86
87
88 @dataclass(frozen=True)
89 class EquityComponentTotal:
90 equity_component: str
91 opening_balance: str
92 movement_amount: str
93 closing_balance: str
94
95
96 @dataclass(frozen=True)
97 class EquityChangesCandidate:
98 company_code: str
99 fiscal_year: int
100 source_sha256: str
101 note_references_sha256: str
102 presentation_policies_sha256: str
103 opening_equity_total: str
104 capital_contributions: str
105 net_profit_loss_movements: str
106 dividends: str
107 other_comprehensive_income: str
108 transfers: str
109 prior_period_adjustments: str
110 other_movements: str
111 total_movement: str
112 closing_equity_total: str
113 rollforward_difference: str
114 component_totals: tuple[EquityComponentTotal, ...]
115 note_movements: tuple[EquityNoteMovement, ...]
116 account_movements: tuple[EquityAccountMovement, ...]
117 findings: tuple[str, ...]
118 eligible_for_analyst_review: bool
119 kind: str = "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE"
120 official_financial_statement: bool = False
121 accounting_policy_authorized: bool = False
122 source_ledger_completeness_verified: bool = False
123 independently_reviewed: bool = False
124 export_authorized: bool = False
125 releasable: bool = False
126
127 def to_dict(self) -> dict[str, Any]:
128 return asdict(self)
129
130
131 def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
132 if (not isinstance(value, str) or len(value) > 256
133 or value != value.strip() or (not value and not blank_ok)
134 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
135 raise CoverageError("INVALID_EQUITY_POLICY_" + label)
136 return value
137
138
139 def _policy_key(
140 policy: EquityMovementPolicy,
141 ) -> tuple[str, str, str]:
142 return policy.statement_section, policy.note_number, policy.subnote_code
143
144
145 def _validate_policies(
146 policies: Sequence[EquityMovementPolicy],
147 ) -> tuple[dict[tuple[str, str, str], EquityMovementPolicy], str]:
148 if not isinstance(policies, (tuple, list)) or len(policies) > MAX_POLICIES:
149 raise CoverageError("INVALID_EQUITY_POLICIES")
150 selected: dict[tuple[str, str, str], EquityMovementPolicy] = {}
151 for policy in policies:
152 if not isinstance(policy, EquityMovementPolicy):
153 raise CoverageError("INVALID_EQUITY_POLICY")
154 _text(policy.statement_section, "SECTION")
155 _text(policy.note_number, "NOTE")
156 _text(policy.subnote_code, "SUBNOTE", blank_ok=True)
157 _text(policy.line_label, "LABEL")
158 _text(policy.policy_evidence_ref, "EVIDENCE")
159 if (not isinstance(policy.equity_component, str)
160 or policy.equity_component not in EQUITY_COMPONENTS):
161 raise CoverageError("INVALID_EQUITY_COMPONENT")
162 if (not isinstance(policy.movement_category, str)
163 or policy.movement_category not in MOVEMENT_CATEGORIES):
164 raise CoverageError("INVALID_EQUITY_MOVEMENT_CATEGORY")
165 if type(policy.sign_multiplier) is not int or policy.sign_multiplier not in (-1, 1):
166 raise CoverageError("INVALID_EQUITY_SIGN")
167 key = _policy_key(policy)
168 if key in selected:
169 raise CoverageError("DUPLICATE_EQUITY_POLICY")
170 selected[key] = policy
171 canonical = [asdict(selected[key]) for key in sorted(selected)]
172 digest = sha256(json.dumps(
173 canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":"),
174 ).encode("utf-8")).hexdigest()
175 return selected, digest
176
177
178 def build_equity_changes_candidate(
179 workbook_bytes: bytes, *, company_code: str, fiscal_year: int,
180 references: Sequence[NoteReference],
181 policies: Sequence[EquityMovementPolicy],
182 ) -> EquityChangesCandidate:
183 """Create a nonofficial equity movement candidate from explicit note policies.
184
185 Source balances are assumed to be debit-net signed. Each note's sign
186 multiplier converts its opening, debit-credit movement and closing to
187 presentation sign. All accounts assigned to one note inherit that note's
188 single movement classification; use separate subnotes when a note mixes
189 transaction types. That constraint is intentionally explicit.
190 """
191 selected, policy_hash = _validate_policies(policies)
192 preview = preview_mapping_coverage(
193 workbook_bytes, company_code=company_code, fiscal_year=fiscal_year,
194 )
195 review = reconcile_workbook_for_review(
196 workbook_bytes, company_code=company_code,
197 fiscal_year=fiscal_year, references=references,
198 )
199 if (review.kind != "UNAPPROVED_NOTE_RECONCILIATION_REVIEW"
200 or review.financial_statement or review.trusted_approvals
201 or review.approved or review.releasable
202 or preview.financial_statement or preview.trusted_approvals
203 or preview.releasable
204 or preview.source_sha256 != review.source_sha256):
205 raise CoverageError("EQUITY_REVIEW_PROVENANCE_INVALID")
206
207 eq_notes = {
208 (note.section, note.note_number, note.subnote_code): note
209 for note in preview.notes if note.statement == "EQ"
210 }
211 findings: list[str] = []
212 if not review.matched_for_analyst_review:
213 findings.append("UPSTREAM_RECONCILIATION_BLOCKED")
214 if not eq_notes:
215 findings.append("NO_EQUITY_NOTES")
216 if set(eq_notes) - set(selected):
217 findings.append("MISSING_EQUITY_POLICY")
218 if set(selected) - set(eq_notes):
219 findings.append("ORPHAN_EQUITY_POLICY")
220
221 ref_by_key = {
222 (note.statement, note.section, note.note_number, note.subnote_code): note
223 for note in review.notes
224 }
225 trace_by_note: dict[tuple[str, str, str], list[Any]] = {}
226 for trace in preview.mappings:
227 if trace.included and trace.target_statement == "EQ":
228 key = (trace.target_section or "", trace.target_note or "",
229 trace.target_subnote or "")
230 trace_by_note.setdefault(key, []).append(trace)
231
232 try:
233 book = load_workbook(
234 BytesIO(workbook_bytes), read_only=False,
235 data_only=False, keep_links=False,
236 )
237 except Exception as exc:
238 raise CoverageError("EQUITY_WORKBOOK_INVALID") from exc
239 try:
240 for sheet in book.worksheets:
241 _assert_visible(sheet)
242 for name, headers in SHEET_HEADERS.items():
243 if name not in book or tuple(cell.value for cell in book[name][1]) != headers:
244 raise CoverageError("EQUITY_WORKBOOK_INVALID")
245
246 account_rows: dict[str, tuple[int, dict[str, Any]]] = {}
247 sheet = book["Accounts"]
248 for row_number, values in enumerate(
249 sheet.iter_rows(min_row=2, values_only=True), 2,
250 ):
251 row = dict(zip(SHEET_HEADERS["Accounts"], values))
252 if not any(value is not None and str(value).strip() for value in row.values()):
253 continue
254 if (isinstance(row.get("company_code"), str)
255 and row["company_code"].strip() == review.company_code
256 and type(row.get("fiscal_year")) is int
257 and row["fiscal_year"] == review.fiscal_year):
258 code = row.get("account_full_code")
259 if not isinstance(code, str) or not code.strip():
260 raise CoverageError("EQUITY_ACCOUNT_CODE_INVALID")
261 code = code.strip()
262 if code in account_rows:
263 raise CoverageError("EQUITY_DUPLICATE_ACCOUNT")
264 account_rows[code] = (row_number, row)
265
266 note_lines: list[EquityNoteMovement] = []
267 account_lines: list[EquityAccountMovement] = []
268 component_opening: dict[str, list[Decimal]] = {
269 item: [] for item in sorted(EQUITY_COMPONENTS)
270 }
271 component_movement: dict[str, list[Decimal]] = {
272 item: [] for item in sorted(EQUITY_COMPONENTS)
273 }
274 component_closing: dict[str, list[Decimal]] = {
275 item: [] for item in sorted(EQUITY_COMPONENTS)
276 }
277 movement_buckets: dict[str, list[Decimal]] = {
278 item: [] for item in sorted(MOVEMENT_CATEGORIES)
279 }
280 opening_values: list[Decimal] = []
281 closing_values: list[Decimal] = []
282 movement_values: list[Decimal] = []
283
284 for key in sorted(set(eq_notes) & set(selected)):
285 note = eq_notes[key]
286 policy = selected[key]
287 matched = ref_by_key.get(("EQ", *key))
288 if matched is None or not matched.matched:
289 findings.append("EQUITY_NOTE_REFERENCE_NOT_MATCHED")
290 continue
291 traces = trace_by_note.get(key, [])
292 if not traces:
293 findings.append("EQUITY_NOTE_WITHOUT_ACCOUNTS")
294 continue
295 note_openings: list[Decimal] = []
296 note_debits: list[Decimal] = []
297 note_credits: list[Decimal] = []
298 note_closings: list[Decimal] = []
299 for trace in traces:
300 source = account_rows.get(trace.account_code)
301 if source is None:
302 raise CoverageError("EQUITY_SOURCE_ACCOUNT_MISSING")
303 excel_row, row = source
304 if excel_row != trace.account_excel_row:
305 raise CoverageError("EQUITY_SOURCE_ROW_MISMATCH")
306 opening, debit, credit, closing = (
307 _money(str(row[field]))
308 for field in ("opening", "debit", "credit", "closing")
309 )
310 source_movement = _sum_exact([debit, -credit])
311 if _sum_exact([opening, source_movement, -closing]) != 0:
312 raise CoverageError("EQUITY_ACCOUNT_ROLLFORWARD_INVALID")
313 if debit < 0 or credit < 0:
314 raise CoverageError("EQUITY_NEGATIVE_TURNOVER")
315 sign = policy.sign_multiplier
316 shown_opening = opening * sign
317 shown_movement = source_movement * sign
318 shown_closing = closing * sign
319 note_openings.append(opening)
320 note_debits.append(debit)
321 note_credits.append(credit)
322 note_closings.append(closing)
323 component_opening[policy.equity_component].append(shown_opening)
324 component_movement[policy.equity_component].append(shown_movement)
325 component_closing[policy.equity_component].append(shown_closing)
326 movement_buckets[policy.movement_category].append(shown_movement)
327 account_lines.append(EquityAccountMovement(
328 account_code=trace.account_code,
329 account_name=trace.account_name,
330 source_excel_row=excel_row,
331 source_row=trace.source_row,
332 statement_section=key[0], note_number=key[1],
333 subnote_code=key[2],
334 equity_component=policy.equity_component,
335 movement_category=policy.movement_category,
336 sign_multiplier=sign,
337 opening_balance=str(shown_opening),
338 debit_turnover=str(debit),
339 credit_turnover=str(credit),
340 movement_amount=str(shown_movement),
341 closing_balance=str(shown_closing),
342 policy_evidence_ref=policy.policy_evidence_ref,
343 ))
344 opening_raw = _sum_exact(note_openings)
345 debit_raw = _sum_exact(note_debits)
346 credit_raw = _sum_exact(note_credits)
347 closing_raw = _sum_exact(note_closings)
348 if _money(note.closing_exposure) != closing_raw:
349 raise CoverageError("EQUITY_NOTE_CLOSING_MISMATCH")
350 opening_shown = opening_raw * policy.sign_multiplier
351 movement_shown = _sum_exact([debit_raw, -credit_raw]) * policy.sign_multiplier
352 closing_shown = closing_raw * policy.sign_multiplier
353 if _sum_exact([opening_shown, movement_shown, -closing_shown]) != 0:
354 findings.append("EQUITY_NOTE_ROLLFORWARD_MISMATCH")
355 opening_values.append(opening_shown)
356 movement_values.append(movement_shown)
357 closing_values.append(closing_shown)
358 note_lines.append(EquityNoteMovement(
359 statement_section=key[0], note_number=key[1],
360 subnote_code=key[2], equity_component=policy.equity_component,
361 movement_category=policy.movement_category,
362 line_label=policy.line_label,
363 opening_balance=str(opening_shown),
364 movement_amount=str(movement_shown),
365 closing_balance=str(closing_shown),
366 source_closing_exposure=str(closing_raw),
367 note_reference_evidence=matched.evidence_ref or "",
368 policy_evidence_ref=policy.policy_evidence_ref,
369 ))
370
371 opening_total = _sum_exact(opening_values)
372 movement_total = _sum_exact(movement_values)
373 closing_total = _sum_exact(closing_values)
374 rollforward = _sum_exact([opening_total, movement_total, -closing_total])
375 if rollforward != 0:
376 findings.append("EQUITY_TOTAL_ROLLFORWARD_MISMATCH")
377
378 component_totals = tuple(
379 EquityComponentTotal(
380 equity_component=component,
381 opening_balance=str(_sum_exact(component_opening[component])),
382 movement_amount=str(_sum_exact(component_movement[component])),
383 closing_balance=str(_sum_exact(component_closing[component])),
384 )
385 for component in sorted(EQUITY_COMPONENTS)
386 if (component_opening[component] or component_movement[component]
387 or component_closing[component])
388 )
389 movement_totals = {
390 category: _sum_exact(values)
391 for category, values in movement_buckets.items()
392 }
393 if not any(note_lines):
394 findings.append("NO_EQUITY_MOVEMENTS")
395 return EquityChangesCandidate(
396 company_code=review.company_code, fiscal_year=review.fiscal_year,
397 source_sha256=review.source_sha256,
398 note_references_sha256=review.reference_sha256,
399 presentation_policies_sha256=policy_hash,
400 opening_equity_total=str(opening_total),
401 capital_contributions=str(movement_totals["CAPITAL_CONTRIBUTION"]),
402 net_profit_loss_movements=str(movement_totals["NET_PROFIT_LOSS"]),
403 dividends=str(movement_totals["DIVIDENDS"]),
404 other_comprehensive_income=str(movement_totals["OTHER_COMPREHENSIVE_INCOME"]),
405 transfers=str(movement_totals["TRANSFER"]),
406 prior_period_adjustments=str(movement_totals["PRIOR_PERIOD_ADJUSTMENT"]),
407 other_movements=str(movement_totals["OTHER_MOVEMENT"]),
408 total_movement=str(movement_total),
409 closing_equity_total=str(closing_total),
410 rollforward_difference=str(rollforward),
411 component_totals=component_totals,
412 note_movements=tuple(note_lines),
413 account_movements=tuple(sorted(
414 account_lines, key=lambda item: item.account_code,
415 )),
416 findings=tuple(sorted(set(findings))),
417 eligible_for_analyst_review=not findings and bool(note_lines),
418 )
419 finally:
420 book.close()