Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
feat(statements): create explicit-policy read-only income statement candidate
davoodmehraban89 committed
Oct 31, 2026 at 06:46 UTC
ff74627acf43f111a72c2da377aac53de41d7c39
1 file changed
+229
backend/src/aram_backend/income_statement_candidate.py
new
+229
@@ -0,0 +1,229 @@
1
+"""Unsigned, read-only income statement candidate from reconciled Pilot XLSX.
2
+
3
+No statutory statement, tax assessment, accounting sign inference, database
4
+write, approval or export is performed. Every source-note classification and
5
+sign is an explicit, untrusted external policy requiring later independent
6
+finance-owner approval.
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, _money, _sum_exact, reconcile_workbook_for_review,
19
+)
20
+
21
+MAX_POLICIES = 10_000
22
+CATEGORIES = frozenset({
23
+ "REVENUE", "COST_OF_REVENUE", "OPERATING_EXPENSE",
24
+ "OTHER_INCOME", "OTHER_EXPENSE", "TAX_EXPENSE",
25
+})
26
+_EXPENSES = frozenset({
27
+ "COST_OF_REVENUE", "OPERATING_EXPENSE", "OTHER_EXPENSE", "TAX_EXPENSE",
28
+})
29
+
30
+
31
+@dataclass(frozen=True)
32
+class IncomeStatementLinePolicy:
33
+ statement_section: str
34
+ note_number: str
35
+ subnote_code: str
36
+ category: str
37
+ sign_multiplier: int
38
+ line_label: str
39
+ policy_evidence_ref: str
40
+
41
+
42
+@dataclass(frozen=True)
43
+class CandidateIncomeStatementLine:
44
+ statement_section: str
45
+ note_number: str
46
+ subnote_code: str
47
+ category: str
48
+ sign_multiplier: int
49
+ line_label: str
50
+ source_closing_exposure: str
51
+ presentation_amount: str
52
+ note_reference_evidence: str
53
+ policy_evidence_ref: str
54
+
55
+
56
+@dataclass(frozen=True)
57
+class IncomeStatementCandidate:
58
+ company_code: str
59
+ fiscal_year: int
60
+ source_sha256: str
61
+ note_references_sha256: str
62
+ presentation_policies_sha256: str
63
+ revenue_total: str
64
+ cost_of_revenue_total: str
65
+ gross_profit: str
66
+ operating_expense_total: str
67
+ operating_profit: str
68
+ other_income_total: str
69
+ other_expense_total: str
70
+ profit_before_tax: str
71
+ tax_expense_total: str
72
+ net_result: str
73
+ lines: tuple[CandidateIncomeStatementLine, ...]
74
+ findings: tuple[str, ...]
75
+ eligible_for_analyst_review: bool
76
+ kind: str = "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE"
77
+ official_financial_statement: bool = False
78
+ accounting_policy_authorized: bool = False
79
+ independently_reviewed: bool = False
80
+ export_authorized: bool = False
81
+ releasable: bool = False
82
+
83
+ def to_dict(self) -> dict[str, Any]:
84
+ return asdict(self)
85
+
86
+
87
+def _required_text(value: object, label: str, *, blank_ok: bool = False) -> str:
88
+ if (not isinstance(value, str) or len(value) > 256
89
+ or value != value.strip() or (not blank_ok and not value)
90
+ or any(ord(char) < 32 or ord(char) == 127 for char in value)):
91
+ raise CoverageError("INVALID_INCOME_POLICY_" + label)
92
+ return value
93
+
94
+
95
+def _key(policy: IncomeStatementLinePolicy) -> tuple[str, str, str]:
96
+ return policy.statement_section, policy.note_number, policy.subnote_code
97
+
98
+
99
+def _validate_policies(
100
+ policies: Sequence[IncomeStatementLinePolicy],
101
+) -> tuple[dict[tuple[str, str, str], IncomeStatementLinePolicy], str]:
102
+ if not isinstance(policies, (list, tuple)) or len(policies) > MAX_POLICIES:
103
+ raise CoverageError("INVALID_INCOME_POLICIES")
104
+ result: dict[tuple[str, str, str], IncomeStatementLinePolicy] = {}
105
+ for policy in policies:
106
+ if not isinstance(policy, IncomeStatementLinePolicy):
107
+ raise CoverageError("INVALID_INCOME_POLICY")
108
+ _required_text(policy.statement_section, "SECTION")
109
+ _required_text(policy.note_number, "NOTE")
110
+ _required_text(policy.subnote_code, "SUBNOTE", blank_ok=True)
111
+ _required_text(policy.line_label, "LABEL")
112
+ _required_text(policy.policy_evidence_ref, "EVIDENCE")
113
+ if not isinstance(policy.category, str) or policy.category not in CATEGORIES:
114
+ raise CoverageError("INVALID_INCOME_POLICY_CATEGORY")
115
+ if type(policy.sign_multiplier) is not int or policy.sign_multiplier not in (-1, 1):
116
+ raise CoverageError("INVALID_INCOME_POLICY_SIGN")
117
+ key = _key(policy)
118
+ if key in result:
119
+ raise CoverageError("DUPLICATE_INCOME_POLICY")
120
+ result[key] = policy
121
+ canonical = [asdict(result[key]) for key in sorted(result)]
122
+ digest = sha256(json.dumps(
123
+ canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":"),
124
+ ).encode("utf-8")).hexdigest()
125
+ return result, digest
126
+
127
+
128
+def build_income_statement_candidate(
129
+ workbook_bytes: bytes, *, company_code: str, fiscal_year: int,
130
+ references: Sequence[NoteReference],
131
+ policies: Sequence[IncomeStatementLinePolicy],
132
+) -> IncomeStatementCandidate:
133
+ """Create a complete-reference, explicit-sign analyst-only income preview.
134
+
135
+ No financial-standard assumptions about account nature, cash versus
136
+ accrual basis, taxes, extraordinary items or comparative periods are made.
137
+ """
138
+ selected, policy_hash = _validate_policies(policies)
139
+ review = 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("INVALID_REVIEW_PROVENANCE")
147
+
148
+ income_notes = {
149
+ (note.section, note.note_number, note.subnote_code): note
150
+ for note in review.notes if note.statement == "IS"
151
+ }
152
+ findings: list[str] = []
153
+ if not review.matched_for_analyst_review:
154
+ findings.append("UPSTREAM_RECONCILIATION_BLOCKED")
155
+ if not income_notes:
156
+ findings.append("NO_INCOME_STATEMENT_NOTES")
157
+ if set(income_notes) - set(selected):
158
+ findings.append("MISSING_INCOME_POLICY")
159
+ if set(selected) - set(income_notes):
160
+ findings.append("ORPHAN_INCOME_POLICY")
161
+
162
+ lines: list[CandidateIncomeStatementLine] = []
163
+ amounts_by_category: dict[str, list[Decimal]] = {
164
+ category: [] for category in sorted(CATEGORIES)
165
+ }
166
+
167
+ for target in sorted(set(income_notes) & set(selected)):
168
+ note = income_notes[target]
169
+ policy = selected[target]
170
+ if not note.matched or note.candidate_closing_exposure is None:
171
+ continue
172
+ exposure = _money(note.candidate_closing_exposure)
173
+ # Decimal source/reference exponent and digit limits are checked
174
+ # upstream; 400-digit precision ensures no presentation rounding.
175
+ with localcontext() as ctx:
176
+ ctx.prec = 400
177
+ displayed = exposure * policy.sign_multiplier
178
+ if displayed < 0:
179
+ findings.append("NEGATIVE_INCOME_PRESENTATION_AMOUNT")
180
+ amounts_by_category[policy.category].append(displayed)
181
+ lines.append(CandidateIncomeStatementLine(
182
+ statement_section=policy.statement_section,
183
+ note_number=policy.note_number, subnote_code=policy.subnote_code,
184
+ category=policy.category, sign_multiplier=policy.sign_multiplier,
185
+ line_label=policy.line_label,
186
+ source_closing_exposure=str(exposure),
187
+ presentation_amount=str(displayed),
188
+ note_reference_evidence=note.evidence_ref or "",
189
+ policy_evidence_ref=policy.policy_evidence_ref,
190
+ ))
191
+
192
+ totals = {
193
+ category: _sum_exact(amounts)
194
+ for category, amounts in amounts_by_category.items()
195
+ }
196
+ revenue = totals["REVENUE"]
197
+ cost = totals["COST_OF_REVENUE"]
198
+ operating_expense = totals["OPERATING_EXPENSE"]
199
+ other_income = totals["OTHER_INCOME"]
200
+ other_expense = totals["OTHER_EXPENSE"]
201
+ tax = totals["TAX_EXPENSE"]
202
+ gross = _sum_exact([revenue, -cost])
203
+ operating = _sum_exact([gross, -operating_expense])
204
+ before_tax = _sum_exact([operating, other_income, -other_expense])
205
+ net = _sum_exact([before_tax, -tax])
206
+
207
+ if not any(line.category == "REVENUE" for line in lines):
208
+ findings.append("NO_REVENUE_LINES")
209
+ if not any(line.category in _EXPENSES for line in lines):
210
+ findings.append("NO_EXPENSE_LINES")
211
+
212
+ return IncomeStatementCandidate(
213
+ company_code=review.company_code, fiscal_year=review.fiscal_year,
214
+ source_sha256=review.source_sha256,
215
+ note_references_sha256=review.reference_sha256,
216
+ presentation_policies_sha256=policy_hash,
217
+ revenue_total=str(revenue),
218
+ cost_of_revenue_total=str(cost),
219
+ gross_profit=str(gross),
220
+ operating_expense_total=str(operating_expense),
221
+ operating_profit=str(operating),
222
+ other_income_total=str(other_income),
223
+ other_expense_total=str(other_expense),
224
+ profit_before_tax=str(before_tax),
225
+ tax_expense_total=str(tax),
226
+ net_result=str(net),
227
+ lines=tuple(lines), findings=tuple(sorted(set(findings))),
228
+ eligible_for_analyst_review=not findings and bool(lines),
229
+ )