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

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

Synced Dec 4, 00:30 UTC

test(statements): cover income bridge, net loss, explicit signs and hostile inputs

davoodmehraban89 committed Oct 31, 2026 at 06:47 UTC 7af990ef34f7899710871c64a15d92620c124981
1 file changed +286
backend/tests/test_income_statement_candidate.py new
+286
@@ -0,0 +1,286 @@
1 +"""Synthetic-only tests for unsigned income statement presentation."""
2 +from __future__ import annotations
3 +
4 +from dataclasses import replace
5 +from io import BytesIO
6 +import json
7 +
8 +import pytest
9 +from openpyxl import Workbook
10 +
11 +from aram_backend.coverage_preview import CoverageError
12 +from aram_backend.income_statement_candidate import (
13 + IncomeStatementLinePolicy,
14 + build_income_statement_candidate,
15 +)
16 +from aram_backend.pilot_workbook import SHEET_HEADERS
17 +from aram_backend.reconciliation_review import NoteReference
18 +
19 +
20 +ITEMS = (
21 + ("REV", "200", "Revenue", "R01", "REVENUE", -1),
22 + ("COS", "110", "Cost", "C01", "COST_OF_REVENUE", 1),
23 + ("OPE", "40", "Operating", "O01", "OPERATING_EXPENSE", 1),
24 + ("OIN", "10", "Other income", "I01", "OTHER_INCOME", -1),
25 + ("OEX", "5", "Other expense", "X01", "OTHER_EXPENSE", 1),
26 + ("TAX", "10", "Taxes", "T01", "TAX_EXPENSE", 1),
27 +)
28 +
29 +
30 +def workbook(*, costs="110", missing_mapping=False, include_bs=False,
31 + revenue="200") -> bytes:
32 + book = Workbook()
33 + book.remove(book.active)
34 + for name, columns in SHEET_HEADERS.items():
35 + book.create_sheet(name).append(list(columns))
36 +
37 + def add(name, **values):
38 + book[name].append([values.get(key) for key in SHEET_HEADERS[name]])
39 +
40 + add("Company", company_code="001", company_name="Synthetic test only",
41 + fiscal_year=1404, status="Draft")
42 + items = tuple(
43 + (code, revenue if code == "REV" else costs if code == "COS" else amount,
44 + section, note, category, sign)
45 + for code, amount, section, note, category, sign in ITEMS
46 + )
47 + if include_bs:
48 + items += (("AST", "0", "Assets", "A01", "BS", 1),)
49 + for index, (code, amount, section, note, category, sign) in enumerate(items, 2):
50 + closing = str(-__import__("decimal").Decimal(amount)) if sign == -1 else amount
51 + add("Accounts", company_code="001", fiscal_year=1404,
52 + general_code=code, general_name=section, account_full_code=code,
53 + account_name="Synthetic " + section, opening=closing, debit="0",
54 + credit="0", closing=closing, closing_delta="0",
55 + source_row=index, row_status="Draft")
56 + statement = "BS" if category == "BS" else "IS"
57 + add("Notes", company_code="001", fiscal_year=1404,
58 + statement=statement, statement_section=section,
59 + note_number=note, note_title=section)
60 + if missing_mapping and code == "TAX":
61 + continue
62 + add("Mapping", mapping_id="M-" + code, company_code="001",
63 + fiscal_year=1404, account_full_code=code, account_level="General",
64 + general_code=code, target_statement=statement,
65 + statement_section=section, note_number=note, mapping_version=1,
66 + approval_status="Approved", reviewer="Synthetic reviewer",
67 + review_date="2026-10-31", validation_status="Valid", source="Synthetic")
68 + stream = BytesIO()
69 + book.save(stream)
70 + book.close()
71 + return stream.getvalue()
72 +
73 +
74 +def references(*, costs="110", include_bs=False, revenue="200"):
75 + result = []
76 + for code, amount, section, note, category, sign in ITEMS:
77 + replacement = revenue if code == "REV" else costs if code == "COS" else amount
78 + closing = str(-__import__("decimal").Decimal(replacement)) if sign == -1 else replacement
79 + result.append(NoteReference("IS", section, note, "", closing, "SYNTH-" + code))
80 + if include_bs:
81 + result.append(NoteReference("BS", "Assets", "A01", "", "0", "SYNTH-BS"))
82 + return result
83 +
84 +
85 +def policies():
86 + return [
87 + IncomeStatementLinePolicy(section, note, "", category, sign,
88 + "Synthetic " + section, "SYNTH-POL-" + code)
89 + for code, _, section, note, category, sign in ITEMS
90 + ]
91 +
92 +
93 +def build(*, data=None, refs=None, pol=None):
94 + return build_income_statement_candidate(
95 + workbook_bytes=workbook() if data is None else data,
96 + company_code="001", fiscal_year=1404,
97 + references=references() if refs is None else refs,
98 + policies=policies() if pol is None else pol,
99 + )
100 +
101 +
102 +def test_complete_profit_bridge_never_claims_approval():
103 + result = build()
104 + assert result.eligible_for_analyst_review
105 + assert not result.findings
106 + assert result.revenue_total == "200"
107 + assert result.cost_of_revenue_total == "110"
108 + assert result.gross_profit == "90"
109 + assert result.operating_expense_total == "40"
110 + assert result.operating_profit == "50"
111 + assert result.other_income_total == "10"
112 + assert result.other_expense_total == "5"
113 + assert result.profit_before_tax == "55"
114 + assert result.tax_expense_total == "10"
115 + assert result.net_result == "45"
116 + assert len(result.lines) == 6
117 + assert result.kind == "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE"
118 + assert not result.official_financial_statement
119 + assert not result.accounting_policy_authorized
120 + assert not result.independently_reviewed
121 + assert not result.export_authorized
122 + assert not result.releasable
123 + assert all(line.policy_evidence_ref for line in result.lines)
124 +
125 +
126 +def test_real_loss_is_not_false_positive_if_expense_exceeds_income():
127 + result = build(data=workbook(costs="290"), refs=references(costs="290"))
128 + assert result.eligible_for_analyst_review
129 + assert result.net_result == "-135"
130 + assert result.gross_profit == "-90"
131 + assert not result.findings
132 +
133 +
134 +def test_no_tax_is_a_valid_zero_amount_with_explicit_reference():
135 + # Source and reference keep the same input amount; no unseen tax estimate.
136 + result = build(data=workbook(costs="0"), refs=references(costs="0"))
137 + assert result.cost_of_revenue_total == "0"
138 + assert result.net_result == "155"
139 + assert result.eligible_for_analyst_review
140 +
141 +
142 +def test_other_statement_reconciled_but_excluded_from_income_rows():
143 + result = build(data=workbook(include_bs=True), refs=references(include_bs=True))
144 + assert result.eligible_for_analyst_review
145 + assert len(result.lines) == 6
146 + assert all(l.note_number != "A01" for l in result.lines)
147 +
148 +
149 +def test_other_statement_missing_reference_blocks_income_preview():
150 + result = build(data=workbook(include_bs=True))
151 + assert not result.eligible_for_analyst_review
152 + assert "UPSTREAM_RECONCILIATION_BLOCKED" in result.findings
153 +
154 +
155 +def test_unmapped_tax_account_blocks_even_with_other_matching_notes():
156 + result = build(data=workbook(missing_mapping=True),
157 + refs=references()[:-1])
158 + assert not result.eligible_for_analyst_review
159 + assert "UPSTREAM_RECONCILIATION_BLOCKED" in result.findings
160 +
161 +
162 +def test_reference_mismatch_blocks_even_when_profit_bridge_can_be_computed():
163 + refs = references()
164 + refs[0] = replace(refs[0], expected_closing_exposure="-201")
165 + result = build(refs=refs)
166 + assert not result.eligible_for_analyst_review
167 + assert "UPSTREAM_RECONCILIATION_BLOCKED" in result.findings
168 +
169 +
170 +def test_missing_income_policy_blocks():
171 + result = build(pol=policies()[:-1])
172 + assert not result.eligible_for_analyst_review
173 + assert "MISSING_INCOME_POLICY" in result.findings
174 +
175 +
176 +def test_orphan_income_policy_blocks():
177 + p = policies()
178 + p.append(IncomeStatementLinePolicy("Extra", "Z1", "", "REVENUE", 1,
179 + "Synthetic extra", "SYNTH-POL"))
180 + result = build(pol=p)
181 + assert "ORPHAN_INCOME_POLICY" in result.findings
182 + assert not result.eligible_for_analyst_review
183 +
184 +
185 +def test_negative_presentation_value_blocked_without_sign_guessing():
186 + p = policies()
187 + p[0] = replace(p[0], sign_multiplier=1)
188 + result = build(pol=p)
189 + assert "NEGATIVE_INCOME_PRESENTATION_AMOUNT" in result.findings
190 + assert not result.eligible_for_analyst_review
191 + assert result.revenue_total == "-200"
192 +
193 +
194 +def test_policy_order_does_not_change_hash_or_rows():
195 + p = policies()
196 + first = build(pol=p)
197 + second = build(pol=list(reversed(p)))
198 + assert first.lines == second.lines
199 + assert first.presentation_policies_sha256 == second.presentation_policies_sha256
200 +
201 +
202 +def test_policy_change_changes_evidence_hash():
203 + p = policies()
204 + first = build(pol=p)
205 + p[0] = replace(p[0], line_label="Synthetic revenues revised")
206 + second = build(pol=p)
207 + assert first.presentation_policies_sha256 != second.presentation_policies_sha256
208 +
209 +
210 +@pytest.mark.parametrize("invalid", [
211 + "invalid", [None], [object()], [policies()[0]] * 10001,
212 +])
213 +def test_policy_collection_invalid(invalid):
214 + with pytest.raises(CoverageError):
215 + build(pol=invalid)
216 +
217 +
218 +@pytest.mark.parametrize("invalid", [
219 + IncomeStatementLinePolicy("Revenue", "R01", "", "REVENUE", True, "Revenue", "P"),
220 + IncomeStatementLinePolicy("Revenue", "R01", "", "REVENUE", 0, "Revenue", "P"),
221 + IncomeStatementLinePolicy("Revenue", "R01", "", "OTHER", 1, "Revenue", "P"),
222 + IncomeStatementLinePolicy("Revenue", "", "", "REVENUE", -1, "Revenue", "P"),
223 + IncomeStatementLinePolicy("Revenue", "R01", "", "REVENUE", -1, "", "P"),
224 + IncomeStatementLinePolicy("Revenue", "R01", "", "REVENUE", -1, "Revenue", ""),
225 + IncomeStatementLinePolicy("Revenue", "R01", "", "REVENUE", -1, "Bad" + chr(10) + "Label", "P"),
226 +])
227 +def test_invalid_policy_blocked(invalid):
228 + with pytest.raises(CoverageError):
229 + build(pol=[invalid])
230 +
231 +
232 +def test_duplicate_policy_is_never_deduplicated():
233 + p = policies()
234 + with pytest.raises(CoverageError) as error:
235 + build(pol=p + [p[0]])
236 + assert error.value.code == "DUPLICATE_INCOME_POLICY"
237 +
238 +
239 +def test_missing_income_notes_is_nonreleasable():
240 + from test_balance_sheet_candidate import workbook as bs_workbook
241 + from test_balance_sheet_candidate import references as bs_references
242 + result = build(data=bs_workbook(), refs=bs_references(), pol=[])
243 + assert not result.eligible_for_analyst_review
244 + assert "NO_INCOME_STATEMENT_NOTES" in result.findings
245 + assert result.net_result == "0"
246 +
247 +
248 +def test_source_bytes_preserved_and_results_json_safe():
249 + content = workbook()
250 + snapshot = bytes(content)
251 + result = json.loads(json.dumps(build(data=content).to_dict()))
252 + assert content == snapshot
253 + assert result["releasable"] is False
254 + assert isinstance(result["net_result"], str)
255 + assert len(result["source_sha256"]) == 64
256 + assert len(result["note_references_sha256"]) == 64
257 + assert len(result["presentation_policies_sha256"]) == 64
258 +
259 +
260 +def test_company_and_year_strict_scoping():
261 + with pytest.raises(CoverageError):
262 + build_income_statement_candidate(
263 + workbook(), company_code="999", fiscal_year=1404,
264 + references=references(), policies=policies(),
265 + )
266 + with pytest.raises(CoverageError):
267 + build_income_statement_candidate(
268 + workbook(), company_code="001", fiscal_year=1403,
269 + references=references(), policies=policies(),
270 + )
271 +
272 +
273 +def test_invalid_xlsx_fails_closed():
274 + with pytest.raises(CoverageError):
275 + build(data=b"not XLSX")
276 +
277 +
278 +def test_tiny_exact_decimal_is_not_rounded_away():
279 + small = "0." + "0" * 30 + "1"
280 + result = build(
281 + data=workbook(costs=small),
282 + refs=references(costs=small),
283 + )
284 + assert result.eligible_for_analyst_review
285 + assert result.cost_of_revenue_total == small
286 + assert result.net_result == str(__import__("decimal").Decimal("155") - __import__("decimal").Decimal(small))