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

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

Synced Dec 3, 20:45 UTC

codex/aram-five-statement-cli-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 357 lines 13.8 KB
Raw
1 """Synthetic tests for independent reference reconciliation; no real finance data."""
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, preview_mapping_coverage
12 from aram_backend.pilot_workbook import SHEET_HEADERS
13 from aram_backend.reconciliation_review import (
14 NoteReference, _validated_preview, reconcile_workbook_for_review,
15 )
16
17
18 def workbook(*, include_second_mapping=True, second_draft=False,
19 split_notes=False, second_amount="15.75") -> bytes:
20 book = Workbook()
21 book.remove(book.active)
22 for sheet_name, columns in SHEET_HEADERS.items():
23 book.create_sheet(sheet_name).append(list(columns))
24
25 def add(name, **values):
26 book[name].append([values.get(key) for key in SHEET_HEADERS[name]])
27
28 add("Company", company_code="001", company_name="Synthetic",
29 fiscal_year=1404, status="Draft")
30 for code, amount in [("0010", "110.25"), ("0020", second_amount)]:
31 add("Accounts", company_code="001", fiscal_year=1404,
32 general_code=code, general_name="General", account_full_code=code,
33 account_name="Synthetic " + code, opening=amount,
34 debit="0", credit="0", closing=amount, source_row=7,
35 row_status="Draft", closing_delta="0")
36 add("Notes", company_code="001", fiscal_year=1404,
37 statement="BS", statement_section="Assets",
38 note_number="N01", note_title="Cash")
39 if split_notes:
40 add("Notes", company_code="001", fiscal_year=1404,
41 statement="BS", statement_section="Assets",
42 note_number="N02", note_title="Other")
43
44 for index, code in enumerate(["0010", "0020"]):
45 if index == 1 and not include_second_mapping:
46 continue
47 add("Mapping", mapping_id=f"M{index + 1}", company_code="001",
48 fiscal_year=1404, account_full_code=code, account_level="General",
49 general_code=code, target_statement="BS",
50 statement_section="Assets", note_number="N02" if split_notes
51 and index == 1 else "N01", mapping_version=1,
52 approval_status="Draft" if index == 1 and second_draft else "Approved",
53 reviewer="Synthetic reviewer" if index == 0 or not second_draft else None,
54 review_date="2026-10-31" if index == 0 or not second_draft else None,
55 validation_status="Valid", source="Synthetic")
56
57 output = BytesIO()
58 book.save(output)
59 book.close()
60 return output.getvalue()
61
62
63 def ref(amount="126.00", note="N01", statement="BS",
64 section="Assets", evidence="SYNTHETIC-TB-1") -> NoteReference:
65 return NoteReference(
66 statement=statement, section=section, note_number=note, subnote_code="",
67 expected_closing_exposure=amount, evidence_ref=evidence,
68 )
69
70
71 def evaluate(content=None, references=None, company="001", year=1404):
72 return reconcile_workbook_for_review(
73 content if content is not None else workbook(),
74 company_code=company, fiscal_year=year,
75 references=[ref()] if references is None else references,
76 )
77
78
79 def test_fully_reconciled_is_still_not_financial_approval():
80 reviewed = evaluate()
81 assert reviewed.matched_for_analyst_review
82 assert not reviewed.findings
83 assert reviewed.account_count == reviewed.candidate_mapped_accounts == 2
84 assert reviewed.blocked_accounts == 0
85 assert len(reviewed.notes) == 1
86 assert reviewed.notes[0].difference == "0.00"
87 assert reviewed.notes[0].candidate_closing_exposure == "126.00"
88 assert not reviewed.financial_statement
89 assert not reviewed.trusted_approvals
90 assert not reviewed.approved
91 assert not reviewed.releasable
92
93
94 def test_mismatch_blocks_without_tolerance_or_rounding():
95 reviewed = evaluate(references=[ref("126.01")])
96 assert not reviewed.matched_for_analyst_review
97 assert reviewed.notes[0].difference == "-0.01"
98 assert reviewed.findings[0].code == "NOTE_EXPOSURE_MISMATCH"
99
100
101 def test_missing_account_mapping_blocks_even_with_matching_reference():
102 reviewed = evaluate(content=workbook(include_second_mapping=False),
103 references=[ref("110.25")])
104 assert not reviewed.matched_for_analyst_review
105 assert reviewed.blocked_accounts == 1
106 assert any(e.code == "BLOCKED_ACCOUNT_UNMAPPED_ACCOUNT"
107 and e.account_code == "0020" for e in reviewed.findings)
108
109
110 def test_workbook_marked_draft_is_not_silently_approved():
111 reviewed = evaluate(content=workbook(second_draft=True),
112 references=[ref("110.25")])
113 assert not reviewed.matched_for_analyst_review
114 assert any("NOT_FILE_MARKED_APPROVED" in e.code for e in reviewed.findings)
115
116
117 def test_missing_reference_blocks_and_does_not_invent_a_total():
118 reviewed = evaluate(references=[])
119 assert not reviewed.matched_for_analyst_review
120 assert reviewed.notes[0].reference_closing_exposure is None
121 assert reviewed.notes[0].difference is None
122 assert reviewed.findings[0].code == "MISSING_NOTE_REFERENCE"
123
124
125 def test_extra_reference_blocks_without_creating_a_note():
126 reviewed = evaluate(references=[ref(), ref("1", note="N99")])
127 assert not reviewed.matched_for_analyst_review
128 extra = next(note for note in reviewed.notes if note.note_number == "N99")
129 assert extra.candidate_closing_exposure is None
130 assert extra.reference_closing_exposure == "1"
131 assert any(f.code == "UNKNOWN_REFERENCE_TARGET" for f in reviewed.findings)
132
133
134 def test_separate_notes_reference_order_is_irrelevant():
135 data = workbook(split_notes=True)
136 left = evaluate(content=data, references=[ref("110.25"), ref("15.75", note="N02")])
137 right = evaluate(content=data, references=[ref("15.75", note="N02"), ref("110.25")])
138 assert left.matched_for_analyst_review and right.matched_for_analyst_review
139 assert left.reference_sha256 == right.reference_sha256
140 assert left.notes == right.notes
141
142
143 def test_duplicate_reference_rejected_not_deduplicated():
144 with pytest.raises(CoverageError) as err:
145 evaluate(references=[ref(), ref("126.00", evidence="ANOTHER")])
146 assert str(err.value) == "DUPLICATE_NOTE_REFERENCE"
147
148
149 @pytest.mark.parametrize("refs", [
150 "not a list", (item for item in []), [object()],
151 [ref()] * 10_001,
152 ])
153 def test_reference_collection_fails_closed(refs):
154 with pytest.raises(CoverageError):
155 evaluate(references=refs)
156
157
158 @pytest.mark.parametrize("bad", [
159 ref(statement="OTHER"), ref(note=""), ref(note=" N01"),
160 ref(section="Assets\nInjected"), ref(evidence=""),
161 ref(amount="NaN"), ref(amount="Infinity"), ref(amount="1E+999"),
162 ref(amount="0E-99999999"), ref(amount="nonsense"),
163 ref(amount="1" * 151),
164 ])
165 def test_invalid_reference_rejected(bad):
166 with pytest.raises(CoverageError):
167 evaluate(references=[bad])
168
169
170 def test_reference_amount_must_be_text_not_float_or_bool():
171 with pytest.raises(CoverageError):
172 evaluate(references=[ref(126.0)])
173 with pytest.raises(CoverageError):
174 evaluate(references=[ref(True)])
175
176
177 def test_wrong_company_or_year_has_no_fallback():
178 with pytest.raises(CoverageError):
179 evaluate(company="002")
180 with pytest.raises(CoverageError):
181 evaluate(year=1403)
182
183
184 def test_provenance_hashes_bind_input_and_reference():
185 source = workbook()
186 original = bytes(source)
187 left = evaluate(content=source, references=[ref()])
188 right = evaluate(content=source, references=[ref("126.00", evidence="SYNTHETIC-TB-2")])
189 assert left.source_sha256 == right.source_sha256
190 assert left.reference_sha256 != right.reference_sha256
191 assert len(left.source_sha256) == len(left.reference_sha256) == 64
192 assert source == original
193
194
195 def test_signed_negative_amount_is_compared_without_faking_statement_signs():
196 reviewed = evaluate(content=workbook(second_amount="-15.75"),
197 references=[ref("94.50")])
198 assert reviewed.matched_for_analyst_review
199 assert reviewed.source_closing_exposure == "94.50"
200
201
202 def test_read_only_packet_is_json_safe_and_explicitly_provisional():
203 result = evaluate()
204 data = json.loads(json.dumps(result.to_dict(), sort_keys=True))
205 assert data["kind"] == "UNAPPROVED_NOTE_RECONCILIATION_REVIEW"
206 assert data["matched_for_analyst_review"]
207 assert data["releasable"] is False
208
209
210 def test_untrusted_invalid_excel_fails_before_comparison():
211 with pytest.raises(CoverageError):
212 evaluate(content=b"invalid xlsx")
213
214
215 def test_unmatched_cents_do_not_disappear_in_decimal_context():
216 reviewed = evaluate(references=[ref("126.000000000000001")])
217 assert reviewed.notes[0].difference == "-1E-15"
218 assert not reviewed.matched_for_analyst_review
219
220
221 def test_all_zero_note_reference_does_not_crash_exact_decimal_difference():
222 from openpyxl import load_workbook
223
224 book = load_workbook(BytesIO(workbook()))
225 for row in book["Accounts"].iter_rows(min_row=2):
226 row[16].value = "0" # opening
227 row[19].value = "0" # closing
228 stream = BytesIO()
229 book.save(stream)
230 book.close()
231 reviewed = evaluate(content=stream.getvalue(), references=[ref("0")])
232 assert reviewed.matched_for_analyst_review
233 assert reviewed.notes[0].difference == "0"
234 assert reviewed.candidate_closing_exposure == "0"
235
236
237 def test_one_account_can_reconcile_to_multiple_distinct_statement_notes():
238 source = workbook()
239 book = load_workbook(BytesIO(source))
240 book["Notes"].append([
241 "001", 1404, "EQ", "Equity", "E01", "Equity note", "", "",
242 ])
243 headers = SHEET_HEADERS["Mapping"]
244 base = {
245 header: book["Mapping"].cell(2, index + 1).value
246 for index, header in enumerate(headers)
247 }
248 equity_mapping = dict(base)
249 equity_mapping.update({
250 "mapping_id": "M-EQ-001", "target_statement": "EQ",
251 "statement_section": "Equity", "note_number": "E01",
252 })
253 book["Mapping"].append([
254 equity_mapping.get(header) for header in headers
255 ])
256 updated = BytesIO()
257 book.save(updated)
258 book.close()
259
260 result = reconcile_workbook_for_review(
261 updated.getvalue(), company_code="001", fiscal_year=1404,
262 references=[
263 NoteReference("BS", "Assets", "N01", "", "126", "REF-BS"),
264 NoteReference("EQ", "Equity", "E01", "", "110.25", "REF-EQ"),
265 ],
266 )
267 assert result.matched_for_analyst_review
268 assert result.account_count == 2
269 assert result.candidate_mapped_accounts == 2
270 assert result.blocked_accounts == 0
271 notes = {(note.statement, note.note_number): note for note in result.notes}
272 assert notes[("BS", "N01")].candidate_closing_exposure == "126.00"
273 assert notes[("EQ", "E01")].candidate_closing_exposure == "110.25"
274 assert all(note.matched for note in result.notes)
275
276
277 def test_preview_integrity_rejects_mapping_trace_amount_tampering():
278 data = workbook()
279 preview = preview_mapping_coverage(data, company_code="001", fiscal_year=1404)
280 altered_mapping = replace(preview.mappings[0], closing_exposure="999")
281 altered = replace(
282 preview, mappings=(altered_mapping, *preview.mappings[1:]),
283 )
284 with pytest.raises(CoverageError) as exc:
285 _validated_preview(data, altered)
286 assert exc.value.code == "MAPPING_TRACE_SOURCE_MISMATCH"
287
288
289 def test_ambiguous_bs_mapping_does_not_hide_valid_eq_mapping_or_pass_review():
290 source = workbook()
291 book = load_workbook(BytesIO(source))
292 book["Notes"].append([
293 "001", 1404, "BS", "Assets", "N02", "Second BS note", "", "",
294 ])
295 book["Notes"].append([
296 "001", 1404, "EQ", "Equity", "E01", "Equity note", "", "",
297 ])
298 headers = SHEET_HEADERS["Mapping"]
299 base = {
300 header: book["Mapping"].cell(2, index + 1).value
301 for index, header in enumerate(headers)
302 }
303 second_bs = dict(base)
304 second_bs.update({"mapping_id": "M-BS-SECOND", "note_number": "N02"})
305 book["Mapping"].append([second_bs.get(header) for header in headers])
306 equity_mapping = dict(base)
307 equity_mapping.update({
308 "mapping_id": "M-EQ-001", "target_statement": "EQ",
309 "statement_section": "Equity", "note_number": "E01",
310 })
311 book["Mapping"].append([equity_mapping.get(header) for header in headers])
312 output = BytesIO()
313 book.save(output)
314 book.close()
315 data = output.getvalue()
316
317 preview = preview_mapping_coverage(data, company_code="001", fiscal_year=1404)
318 account = next(row for row in preview.accounts if row.account_code == "0010")
319 assert account.included
320 assert account.mapping_count == 3
321 assert account.mapping_id is None
322 assert any(
323 item.included and item.target_statement == "EQ"
324 and item.account_code == "0010" for item in preview.mappings
325 )
326 assert not any(
327 item.included and item.target_statement == "BS"
328 and item.account_code == "0010" for item in preview.mappings
329 )
330 assert any(
331 item.code == "AMBIGUOUS_ACCOUNT_MAPPING"
332 and item.account_code == "0010" for item in preview.exceptions
333 )
334
335 reviewed = reconcile_workbook_for_review(
336 data, company_code="001", fiscal_year=1404,
337 references=[
338 ref("15.75", note="N01"),
339 ref("110.25", note="E01", statement="EQ", section="Equity"),
340 ],
341 )
342 assert not reviewed.matched_for_analyst_review
343 assert any(
344 finding.code == "BLOCKED_ACCOUNT_AMBIGUOUS_ACCOUNT_MAPPING"
345 and finding.account_code == "0010" for finding in reviewed.findings
346 )
347
348 def test_rejects_stale_account_target_for_unapproved_mapping():
349 data = workbook(second_draft=True)
350 preview = preview_mapping_coverage(data, company_code="001", fiscal_year=1404)
351 rows = list(preview.accounts)
352 i = next(i for i, row in enumerate(rows) if row.account_code == "0020")
353 assert not rows[i].included
354 rows[i] = replace(rows[i], target_statement="BS")
355 altered = replace(preview, accounts=tuple(rows))
356 with pytest.raises(CoverageError):
357 _validated_preview(data, altered)