@davoodmehraban89 / Aram / commits / d64e62d
Fork 0

test(statements): exercise equity rollforward, explicit policies, zero and fail-closed cases

davoodmehraban89 committed Oct 31, 2026 at 08:14 UTC d64e62d405fb22c832d8dbeb630e0f7d834a5856
1 file changed +274
backend/tests/test_equity_changes_candidate.py new
+274
@@ -0,0 +1,274 @@
1 +"""Synthetic-only tests for the unapproved statement of changes in equity."""
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, load_workbook
10 +
11 +from aram_backend.coverage_preview import CoverageError
12 +from aram_backend.equity_changes_candidate import (
13 + EquityMovementPolicy, build_equity_changes_candidate,
14 +)
15 +from aram_backend.pilot_workbook import SHEET_HEADERS
16 +from aram_backend.reconciliation_review import NoteReference
17 +
18 +
19 +ITEMS = (
20 + ("CAP", "Capital", "C01", "-100", "0", "20", "-120",
21 + "SHARE_CAPITAL", "CAPITAL_CONTRIBUTION"),
22 + ("RET", "Retained earnings", "R01", "-50", "0", "5", "-55",
23 + "RETAINED_EARNINGS", "NET_PROFIT_LOSS"),
24 + ("DIV", "Dividends", "D01", "0", "20", "0", "20",
25 + "RETAINED_EARNINGS", "DIVIDENDS"),
26 +)
27 +
28 +
29 +def workbook(*, include_eq=True, bad_delta=False, bad_mapping=False,
30 + negative_turnover=False):
31 + book = Workbook()
32 + book.remove(book.active)
33 + for name, headers in SHEET_HEADERS.items():
34 + book.create_sheet(name).append(list(headers))
35 +
36 + def add(name, **values):
37 + book[name].append([values.get(key) for key in SHEET_HEADERS[name]])
38 +
39 + add("Company", company_code="001", company_name="Synthetic only",
40 + fiscal_year=1404, currency="IRR", unit="Rial", status="Draft")
41 + for index, item in enumerate(ITEMS, 2):
42 + code, label, note, opening, debit, credit, closing, component, movement = item
43 + if bad_delta and code == "CAP":
44 + closing = "-119"
45 + if negative_turnover and code == "DIV":
46 + debit = "-20"
47 + add("Accounts", company_code="001", fiscal_year=1404,
48 + general_code=code, general_name=label, account_full_code=code,
49 + account_name="Synthetic " + label, opening=opening,
50 + debit=debit, credit=credit, closing=closing,
51 + source_row=index + 10, row_status="Draft",
52 + closing_delta="0" if not bad_delta else "1")
53 + if include_eq:
54 + add("Notes", company_code="001", fiscal_year=1404,
55 + statement="EQ", statement_section=label,
56 + note_number=note, note_title=label, subnote_code="",
57 + subnote_title="")
58 + if not (bad_mapping and code == "DIV"):
59 + add("Mapping", mapping_id="M-" + code, company_code="001",
60 + fiscal_year=1404, account_full_code=code,
61 + account_level="General", general_code=code,
62 + target_statement="EQ", statement_section=label,
63 + note_number=note, subnote_code="", mapping_version=1,
64 + approval_status="Approved", reviewer="Synthetic reviewer",
65 + review_date="2026-10-31", source="Synthetic",
66 + validation_status="Valid")
67 + stream = BytesIO()
68 + book.save(stream)
69 + book.close()
70 + return stream.getvalue()
71 +
72 +
73 +def references():
74 + return [
75 + NoteReference("EQ", label, note, "", closing, "SYNTH-REF-" + code)
76 + for code, label, note, opening, debit, credit, closing, component, movement in ITEMS
77 + ]
78 +
79 +
80 +def policies():
81 + return [
82 + EquityMovementPolicy(
83 + label, note, "", component, movement, -1,
84 + "Synthetic " + label, "SYNTH-POL-" + code,
85 + )
86 + for code, label, note, opening, debit, credit, closing, component, movement in ITEMS
87 + ]
88 +
89 +
90 +def build(*, data=None, refs=None, pol=None, company="001", year=1404):
91 + return build_equity_changes_candidate(
92 + workbook() if data is None else data,
93 + company_code=company, fiscal_year=year,
94 + references=references() if refs is None else refs,
95 + policies=policies() if pol is None else pol,
96 + )
97 +
98 +
99 +def edit(data, change):
100 + book = load_workbook(BytesIO(data))
101 + change(book)
102 + out = BytesIO()
103 + book.save(out)
104 + book.close()
105 + return out.getvalue()
106 +
107 +
108 +def test_equity_statement_rollforward_and_category_totals_are_exact():
109 + result = build()
110 + assert result.eligible_for_analyst_review
111 + assert not result.findings
112 + assert result.opening_equity_total == "150"
113 + assert result.capital_contributions == "20"
114 + assert result.net_profit_loss_movements == "5"
115 + assert result.dividends == "-20"
116 + assert result.other_comprehensive_income == "0"
117 + assert result.transfers == "0"
118 + assert result.prior_period_adjustments == "0"
119 + assert result.other_movements == "0"
120 + assert result.total_movement == "5"
121 + assert result.closing_equity_total == "155"
122 + assert result.rollforward_difference == "0"
123 + assert len(result.note_movements) == 3
124 + assert len(result.account_movements) == 3
125 + assert result.kind == "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE"
126 + assert not result.official_financial_statement
127 + assert not result.accounting_policy_authorized
128 + assert not result.source_ledger_completeness_verified
129 + assert not result.independently_reviewed
130 + assert not result.export_authorized
131 + assert not result.releasable
132 + retained = next(x for x in result.component_totals
133 + if x.equity_component == "RETAINED_EARNINGS")
134 + assert retained.opening_balance == "50"
135 + assert retained.movement_amount == "-15"
136 + assert retained.closing_balance == "35"
137 +
138 +
139 +def test_zero_movement_and_zero_balances_are_valid():
140 + def zero(book):
141 + for row in book["Accounts"].iter_rows(min_row=2):
142 + for column in ("opening", "debit", "credit", "closing"):
143 + row[16 + ("opening", "debit", "credit", "closing").index(column)].value = "0"
144 + data = edit(workbook(), zero)
145 + refs = [replace(ref, expected_closing_exposure="0") for ref in references()]
146 + result = build(data=data, refs=refs)
147 + assert result.eligible_for_analyst_review
148 + assert result.opening_equity_total == "0"
149 + assert result.total_movement == "0"
150 + assert result.closing_equity_total == "0"
151 +
152 +
153 +def test_missing_policy_blocks_entire_equity_candidate():
154 + result = build(pol=policies()[:-1])
155 + assert not result.eligible_for_analyst_review
156 + assert "MISSING_EQUITY_POLICY" in result.findings
157 +
158 +
159 +def test_orphan_policy_blocks_candidate():
160 + p = policies()
161 + p.append(EquityMovementPolicy(
162 + "Unknown", "X01", "", "OTHER_EQUITY", "OTHER_MOVEMENT", -1,
163 + "Synthetic extra", "SYNTH-EXTRA",
164 + ))
165 + result = build(pol=p)
166 + assert not result.eligible_for_analyst_review
167 + assert "ORPHAN_EQUITY_POLICY" in result.findings
168 +
169 +
170 +def test_missing_mapping_blocks_even_when_other_equity_notes_match():
171 + result = build(data=workbook(bad_mapping=True))
172 + assert not result.eligible_for_analyst_review
173 + assert "UPSTREAM_RECONCILIATION_BLOCKED" in result.findings
174 +
175 +
176 +def test_reference_mismatch_blocks_candidate():
177 + refs = references()
178 + refs[0] = replace(refs[0], expected_closing_exposure="-121")
179 + result = build(refs=refs)
180 + assert not result.eligible_for_analyst_review
181 + assert "UPSTREAM_RECONCILIATION_BLOCKED" in result.findings
182 +
183 +
184 +def test_invalid_source_rollforward_fails_closed():
185 + with pytest.raises(CoverageError):
186 + build(data=workbook(bad_delta=True))
187 +
188 +
189 +def test_negative_turnover_fails_closed():
190 + with pytest.raises(CoverageError) as error:
191 + build(data=workbook(negative_turnover=True))
192 + assert error.value.code == "EQUITY_NEGATIVE_TURNOVER"
193 +
194 +
195 +@pytest.mark.parametrize("invalid", [
196 + EquityMovementPolicy("Capital", "C01", "", "BAD", "CAPITAL_CONTRIBUTION",
197 + -1, "Capital", "P"),
198 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "BAD",
199 + -1, "Capital", "P"),
200 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "DIVIDENDS",
201 + True, "Capital", "P"),
202 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "DIVIDENDS",
203 + 0, "Capital", "P"),
204 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "DIVIDENDS",
205 + -1, "", "P"),
206 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "DIVIDENDS",
207 + -1, "Capital", ""),
208 + EquityMovementPolicy("Capital", "C01", "", "SHARE_CAPITAL", "DIVIDENDS",
209 + -1, "Bad" + chr(10) + "label", "P"),
210 +])
211 +def test_invalid_equity_policy_fails_closed(invalid):
212 + with pytest.raises(CoverageError):
213 + build(pol=[invalid])
214 +
215 +
216 +def test_duplicate_policy_fails_closed():
217 + p = policies()
218 + with pytest.raises(CoverageError) as error:
219 + build(pol=p + [p[0]])
220 + assert error.value.code == "DUPLICATE_EQUITY_POLICY"
221 +
222 +
223 +def test_wrong_company_and_year_are_not_guessed():
224 + with pytest.raises(CoverageError):
225 + build(company="999")
226 + with pytest.raises(CoverageError):
227 + build(year=1403)
228 +
229 +
230 +def test_missing_equity_notes_blocks():
231 + data = workbook(include_eq=False)
232 + result = build(data=data, refs=[], pol=[])
233 + assert not result.eligible_for_analyst_review
234 + assert "NO_EQUITY_NOTES" in result.findings
235 + assert result.opening_equity_total == "0"
236 + assert result.closing_equity_total == "0"
237 +
238 +
239 +def test_source_unchanged_and_json_safe():
240 + data = workbook()
241 + original = bytes(data)
242 + result = json.loads(json.dumps(build(data=data).to_dict()))
243 + assert data == original
244 + assert result["releasable"] is False
245 + assert len(result["source_sha256"]) == 64
246 + assert len(result["note_references_sha256"]) == 64
247 + assert len(result["presentation_policies_sha256"]) == 64
248 + assert all(isinstance(item["movement_amount"], str)
249 + for item in result["note_movements"])
250 +
251 +
252 +def test_policy_order_does_not_change_hash_or_result():
253 + p = policies()
254 + first = build(pol=p)
255 + second = build(pol=list(reversed(p)))
256 + assert first.note_movements == second.note_movements
257 + assert first.presentation_policies_sha256 == second.presentation_policies_sha256
258 +
259 +
260 +def test_policy_change_changes_policy_hash():
261 + p = policies()
262 + first = build(pol=p)
263 + p[0] = replace(p[0], line_label="Revised synthetic capital")
264 + second = build(pol=p)
265 + assert first.presentation_policies_sha256 != second.presentation_policies_sha256
266 +
267 +
268 +def test_wrong_source_hash_cannot_be_silently_reused():
269 + # References are tied to note keys/amounts, while the source snapshot hash
270 + # is recalculated for each build; a source mutation still needs exact
271 + # reconciliation, so mutate a mapped account's closing without its control.
272 + data = edit(workbook(), lambda book: setattr(book["Accounts"]["T2"], "value", "-121"))
273 + with pytest.raises(CoverageError):
274 + build(data=data)