1
+"""R2: C-05..C-15 — a positive and a negative case for every control.
2
+
3
+Plus the booklet 2.1 rule: a control that cannot run reports «اجرا نشد: دلیل» and
4
+blocks approval; approval is only possible when the whole ERROR set has run and
5
+passed.
6
+"""
7
+
8
+from __future__ import annotations
9
+
10
+from decimal import Decimal
11
+
12
+from aram_backend.domain.controls import (
13
+ BalanceRow,
14
+ ControlContext,
15
+ EquityMovement,
16
+ MappingTarget,
17
+ OfficialComparison,
18
+ check_c05,
19
+ check_c06,
20
+ check_c07,
21
+ check_c08,
22
+ check_c09,
23
+ check_c10,
24
+ check_c11,
25
+ check_c12,
26
+ check_c13,
27
+ check_c14,
28
+ check_c15,
29
+ run_controls,
30
+)
31
+from aram_backend.services.approval import approve_year
32
+from aram_backend.services.control_context import build_control_context
33
+from test_approval_gate import _balanced
34
+from test_statement_build import _setup
35
+
36
+D = Decimal
37
+
38
+
39
+def _row(code, opening, closing, debit=None, credit=None, row=1):
40
+ move = closing - opening
41
+ return BalanceRow(
42
+ row_number=row,
43
+ account_code=code,
44
+ opening=opening,
45
+ debit=debit if debit is not None else max(move, D(0)),
46
+ credit=credit if credit is not None else max(-move, D(0)),
47
+ closing=closing,
48
+ )
49
+
50
+
51
+class TestC05PriorYear:
52
+ def test_matching_carry_forward_passes(self):
53
+ rows = [_row("148348", D(100), D(150))]
54
+ assert check_c05(rows, {"148348": D(100)}).passed
55
+
56
+ def test_mismatched_opening_fails(self):
57
+ rows = [_row("148348", D(90), D(150))]
58
+ result = check_c05(rows, {"148348": D(100)})
59
+ assert not result.passed and result.severity == "ERROR"
60
+ assert result.affected == ("148348",)
61
+
62
+ def test_missing_prior_year_is_unrun_and_blocking(self):
63
+ result = check_c05([_row("148348", D(0), D(1))], None)
64
+ assert not result.passed and not result.ran
65
+ assert result.message_fa.startswith("اجرا نشد:")
66
+
67
+
68
+class TestC06BalanceEquation:
69
+ def test_equation_holds(self):
70
+ assert check_c06({"Assets": D(100), "Liabilities": D(60), "Equity": D(40)}).passed
71
+
72
+ def test_equation_violated(self):
73
+ result = check_c06({"Assets": D(100), "Liabilities": D(60), "Equity": D(30)})
74
+ assert not result.passed and result.severity == "ERROR"
75
+
76
+ def test_missing_section_is_unrun(self):
77
+ result = check_c06({"Assets": D(100)})
78
+ assert not result.ran and "بخشهای غایب" in result.message_fa
79
+
80
+
81
+class TestC07NoteVsLine:
82
+ def test_note_equals_line(self):
83
+ assert check_c07({"BS:6": D(100)}, {"BS:6": D(100)}).passed
84
+
85
+ def test_note_differs_from_line(self):
86
+ result = check_c07({"BS:6": D(100)}, {"BS:6": D(99)})
87
+ assert not result.passed and result.affected == ("BS:6",)
88
+
89
+ def test_missing_inputs_unrun(self):
90
+ assert not check_c07(None, {"BS:6": D(1)}).ran
91
+
92
+
93
+class TestC08ProfitVsRetained:
94
+ def test_profit_equals_retained_change(self):
95
+ assert check_c08(D(50), D(50)).passed
96
+
97
+ def test_explicit_adjustment_is_respected(self):
98
+ assert check_c08(D(50), D(40), D(10)).passed
99
+
100
+ def test_unexplained_difference_fails(self):
101
+ result = check_c08(D(50), D(40))
102
+ assert not result.passed and result.severity == "ERROR"
103
+
104
+ def test_missing_input_unrun(self):
105
+ assert not check_c08(None, D(0)).ran
106
+
107
+
108
+class TestC09EquityIdentity:
109
+ def test_opening_plus_changes_equals_closing(self):
110
+ moves = (EquityMovement("EQ:12", D(40), D(10), D(50)),)
111
+ assert check_c09(moves).passed
112
+
113
+ def test_identity_violated(self):
114
+ result = check_c09((EquityMovement("EQ:12", D(40), D(10), D(55)),))
115
+ assert not result.passed and result.affected == ("EQ:12",)
116
+
117
+ def test_no_equity_rows_is_unrun(self):
118
+ assert not check_c09(()).ran
119
+
120
+
121
+class TestC10CashFlow:
122
+ def test_net_change_matches_cash_movement(self):
123
+ assert check_c10(D(20), D(100), D(120)).passed
124
+
125
+ def test_mismatch_fails(self):
126
+ result = check_c10(D(20), D(100), D(130))
127
+ assert not result.passed and result.severity == "ERROR"
128
+
129
+ def test_missing_cash_unrun(self):
130
+ assert not check_c10(D(20), None, D(120)).ran
131
+
132
+
133
+class TestC11Hierarchy:
134
+ def test_parent_exists_and_children_sum(self):
135
+ rows = [_row("14", D(0), D(100), row=1), _row("148348", D(0), D(100), row=2)]
136
+ assert check_c11(rows, frozenset({"14", "148348"})).passed
137
+
138
+ def test_missing_parent_fails(self):
139
+ result = check_c11([_row("148348", D(0), D(100))], frozenset({"148348"}))
140
+ assert not result.passed and result.affected == ("148348",)
141
+
142
+ def test_children_not_summing_to_parent_fails(self):
143
+ rows = [_row("14", D(0), D(100), row=1), _row("148348", D(0), D(90), row=2)]
144
+ result = check_c11(rows, frozenset({"14", "148348"}))
145
+ assert not result.passed and "14" in result.affected
146
+
147
+ def test_no_chart_is_unrun(self):
148
+ assert not check_c11([_row("148348", D(0), D(1))], None).ran
149
+
150
+
151
+class TestC12NoteCoverage:
152
+ def test_every_note_mapped_and_no_dangling(self):
153
+ assert check_c12({"148348": [MappingTarget("1")]}, frozenset({"1"})).passed
154
+
155
+ def test_unmapped_note_fails(self):
156
+ result = check_c12({"148348": [MappingTarget("1")]}, frozenset({"1", "2"}))
157
+ assert not result.passed and "2" in result.affected
158
+
159
+ def test_mapping_to_missing_note_fails(self):
160
+ result = check_c12({"148348": [MappingTarget("9")]}, frozenset({"1"}))
161
+ assert not result.passed and "9" in result.affected
162
+
163
+
164
+class TestC13Official:
165
+ def test_matching_official_passes(self):
166
+ official = (OfficialComparison("BS:6", D(100), D(100)),)
167
+ assert check_c13(official).passed
168
+
169
+ def test_difference_is_info_in_ui(self):
170
+ result = check_c13((OfficialComparison("BS:6", D(100), D(90)),), "ui")
171
+ assert not result.passed and result.severity == "INFO"
172
+
173
+ def test_difference_is_error_in_ci(self):
174
+ result = check_c13((OfficialComparison("BS:6", D(100), D(90)),), "ci")
175
+ assert not result.passed and result.severity == "ERROR"
176
+
177
+
178
+class TestC14SuddenChange:
179
+ def test_small_change_passes(self):
180
+ rows = [_row("148348", D(100), D(110))]
181
+ assert check_c14(rows, {"148348": D(100)}).passed
182
+
183
+ def test_large_change_warns_not_blocks(self):
184
+ rows = [_row("148348", D(100), D(300))]
185
+ result = check_c14(rows, {"148348": D(100)})
186
+ assert not result.passed and result.severity == "WARN"
187
+
188
+ def test_threshold_is_configurable(self):
189
+ rows = [_row("148348", D(100), D(300))]
190
+ assert check_c14(rows, {"148348": D(100)}, D(500)).passed
191
+
192
+
193
+class TestC15Nature:
194
+ def test_balance_matches_nature(self):
195
+ rows = [_row("148348", D(0), D(100))]
196
+ assert check_c15(rows, {"148348": "debit"}).passed
197
+
198
+ def test_credit_balance_on_debit_account_warns(self):
199
+ rows = [_row("148348", D(0), D(-100))]
200
+ result = check_c15(rows, {"148348": "debit"})
201
+ assert not result.passed and result.severity == "WARN"
202
+
203
+ def test_persian_nature_is_recognised(self):
204
+ rows = [_row("241001", D(0), D(-60))]
205
+ assert check_c15(rows, {"241001": "بستانکار"}).passed
206
+
207
+ def test_no_natures_is_unrun(self):
208
+ assert not check_c15([_row("148348", D(0), D(1))], None).ran
209
+
210
+
211
+class TestFullSet:
212
+ def test_fifteen_controls_always_present(self):
213
+ results = run_controls([], {})
214
+ assert len(results) == 15
215
+ assert [r.code for r in results] == [f"C-{i:02d}" for i in range(1, 16)]
216
+
217
+ def test_unrun_error_controls_block(self):
218
+ results = run_controls([], {})
219
+ blocking = [r.code for r in results if r.severity == "ERROR" and not r.passed]
220
+ assert "C-05" in blocking and "C-13" not in blocking # C-13 is INFO in UI
221
+
222
+ def test_failing_warn_is_not_a_blocking_severity(self):
223
+ # A 200% jump trips C-14 (WARN); nothing about it may be ERROR severity.
224
+ rows = [_row("148348", D(100), D(300), row=1), _row("241001", D(-100), D(-300), row=2)]
225
+ results = run_controls(rows, {}, ControlContext(prior_closing={"148348": D(100), "241001": D(-100)}))
226
+ c14 = next(r for r in results if r.code == "C-14")
227
+ assert not c14.passed and c14.severity == "WARN"
228
+ blocking = {r.code for r in results if r.severity == "ERROR" and not r.passed}
229
+ assert "C-14" not in blocking and "C-15" not in blocking
230
+
231
+
232
+class TestApprovalRejectsIncompleteControls:
233
+ def test_year_without_prior_or_statements_cannot_be_approved(self, session):
234
+ year, _ = _setup(session)
235
+ result = approve_year(session, year.id)
236
+ assert not result.approved
237
+ codes = {r.code for r in result.blocking}
238
+ assert {"C-05", "C-06", "C-09", "C-10"}.issubset(codes)
239
+ assert all(r.message_fa.startswith("اجرا نشد:") or not r.ran for r in result.blocking
240
+ if r.code in {"C-05", "C-06"})
241
+
242
+ def test_complete_year_passes_all_fifteen(self, session):
243
+ year, _ = _balanced(session)
244
+ ctx = build_control_context(session, year.id)
245
+ assert ctx.prior_closing is not None and ctx.bs_sections is not None
246
+ result = approve_year(session, year.id, actor="reviewer")
247
+ session.commit()
248
+ assert result.approved, [r.message_fa for r in result.controls if not r.passed]
249
+ assert len(result.controls) == 15
250
+ assert all(r.ran for r in result.controls if r.severity == "ERROR")
251
+
252
+ def test_broken_equity_identity_blocks_a_otherwise_clean_year(self, session):
253
+ year, cash_note = _balanced(session)
254
+ # Corrupt one equity balance so opening + changes != closing.
255
+ from sqlalchemy import select
256
+
257
+ from aram_backend.models import LedgerBalance
258
+
259
+ eq = session.scalar(
260
+ select(LedgerBalance).where(
261
+ LedgerBalance.year_id == year.id, LedgerBalance.account_full_code == "341001"
262
+ )
263
+ )
264
+ eq.closing = eq.closing - D(5)
265
+ session.flush()
266
+ result = approve_year(session, year.id)
267
+ assert not result.approved
268
+ assert any(r.code == "C-09" for r in result.blocking)
269
+
270
+
271
+class TestPreflightApi:
272
+ """Acceptance (R2): the preflight endpoint shows all 15 controls."""
273
+
274
+ def _year(self, api_client):
275
+ return api_client.post(
276
+ "/api/v1/companies", json={"code": "R2", "name": "شرکت", "year": 1404}
277
+ ).json()["year_id"]
278
+
279
+ def test_preflight_returns_fifteen_controls_with_ran_flags(self, api_client):
280
+ year_id = self._year(api_client)
281
+ response = api_client.get(f"/api/v1/years/{year_id}/preflight")
282
+ assert response.status_code == 200, response.text
283
+ body = response.json()
284
+ assert [c["code"] for c in body["controls"]] == [f"C-{i:02d}" for i in range(1, 16)]
285
+ assert all("ran" in c for c in body["controls"])
286
+ assert body["can_approve"] is False
287
+ unrun = [c for c in body["controls"] if not c["ran"]]
288
+ assert unrun and all(c["message_fa"].startswith("اجرا نشد:") for c in unrun)
289
+
290
+ def test_approval_is_rejected_when_error_controls_did_not_run(self, api_client):
291
+ year_id = self._year(api_client)
292
+ response = api_client.post(f"/api/v1/years/{year_id}/approve", json={})
293
+ assert response.status_code == 200, response.text
294
+ body = response.json()
295
+ assert body["approved"] is False
296
+ assert {"C-05", "C-06"} <= {b["code"] for b in body["blocking"]}
297
+
298
+
299
+class TestCompleteYearThroughApi:
300
+ """The public API alone must be enough to reach an approvable year (R2)."""
301
+
302
+ def test_all_fifteen_run_and_approval_succeeds(self, api_client):
303
+ from helpers_complete_year import complete_year_via_api
304
+
305
+ year_id, _ = complete_year_via_api(api_client)
306
+ pre = api_client.get(f"/api/v1/years/{year_id}/preflight").json()
307
+ assert len(pre["controls"]) == 15
308
+ errors = [c for c in pre["controls"] if c["severity"] == "ERROR"]
309
+ assert all(c["ran"] for c in errors), [c for c in errors if not c["ran"]]
310
+ assert pre["can_approve"] is True, [c for c in pre["controls"] if not c["passed"]]
311
+ approved = api_client.post(f"/api/v1/years/{year_id}/approve", json={})
312
+ assert approved.status_code == 200, approved.text
313
+ assert approved.json()["approved"] is True
314
+
315
+ def test_duplicate_year_is_refused(self, api_client):
316
+ created = api_client.post(
317
+ "/api/v1/companies", json={"code": "DY", "name": "x", "year": 1404}
318
+ ).json()
319
+ again = api_client.post(
320
+ f"/api/v1/companies/{created['company_id']}/years", json={"year": 1404}
321
+ )
322
+ assert again.status_code == 422
323
+
324
+ def test_note_role_round_trips(self, api_client):
325
+ from helpers_complete_year import complete_year_via_api
326
+
327
+ year_id, notes = complete_year_via_api(api_client)
328
+ listed = api_client.get(f"/api/v1/years/{year_id}/notes").json()["notes"]
329
+ by_id = {n["note_id"]: n for n in listed}
330
+ assert by_id[notes["cash"]]["role"] == "cash"
331
+ assert by_id[notes["equity"]]["role"] == "retained_earnings"
332
+ assert by_id[notes["payable"]]["role"] is None
333
+
334
+ def test_invalid_note_role_is_refused(self, api_client):
335
+ year_id = api_client.post(
336
+ "/api/v1/companies", json={"code": "NR", "name": "x", "year": 1404}
337
+ ).json()["year_id"]
338
+ bad = api_client.post(
339
+ f"/api/v1/years/{year_id}/notes",
340
+ json={
341
+ "note_number": "1",
342
+ "title": "x",
343
+ "statement": "BS",
344
+ "section": "Assets",
345
+ "role": "guessed",
346
+ },
347
+ )
348
+ assert bad.status_code == 422