codex/aram-five-statement-integration-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 217 lines 8.41 KB
Raw
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, localcontext
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 not isinstance(policy.category, str) or 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 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 )