codex/aram-multistatement-mapping-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 528 lines 21.8 KB
Raw
1 """Cross-statement arithmetic and provenance gate for unsigned ARAM candidates.
2
3 Consumes only the typed, nonofficial candidate objects produced by the earlier
4 read-only engines. Exact matches are necessary, not sufficient, for approval.
5 """
6 from __future__ import annotations
7
8 from dataclasses import asdict, dataclass
9 from decimal import Decimal
10 from hashlib import sha256
11 import json
12 import re
13 from typing import Any, Sequence
14
15 from aram_backend.balance_sheet_candidate import BalanceSheetCandidate
16 from aram_backend.cash_flow_direct_candidate import (
17 CashAccountReconciliation, CashFlowLine, DirectCashFlowCandidate,
18 )
19 from aram_backend.coverage_preview import CoverageError
20 from aram_backend.equity_changes_candidate import EquityChangesCandidate
21 from aram_backend.income_statement_candidate import IncomeStatementCandidate
22 from aram_backend.reconciliation_review import _money, _sum_exact
23 from aram_backend.trial_balance_diagnostic import (
24 TrialBalanceAccount, TrialBalanceDiagnostic,
25 )
26
27 EXPECTED_KINDS = {
28 "balance_sheet": "UNAPPROVED_BALANCE_SHEET_PRESENTATION_CANDIDATE",
29 "income_statement": "UNAPPROVED_INCOME_STATEMENT_PRESENTATION_CANDIDATE",
30 "equity_changes": "UNAPPROVED_EQUITY_CHANGES_PRESENTATION_CANDIDATE",
31 "cash_flow": "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE",
32 "trial_balance": "UNAPPROVED_TRIAL_BALANCE_DIAGNOSTIC",
33 }
34
35
36 @dataclass(frozen=True)
37 class CashBalanceNoteSelection:
38 statement_section: str
39 note_number: str
40 subnote_code: str
41 evidence_ref: str
42
43
44 @dataclass(frozen=True)
45 class SelectedCashBalanceNote:
46 statement_section: str
47 note_number: str
48 subnote_code: str
49 presentation_amount: str
50 evidence_ref: str
51
52
53 @dataclass(frozen=True)
54 class CrossStatementReconciliation:
55 company_code: str
56 fiscal_year: int
57 source_sha256: str
58 cash_flow_transaction_ledger_sha256: str
59 cash_note_selection_sha256: str
60 same_source_snapshot: bool
61 trial_balance_opening_debit_net_total: str
62 trial_balance_movement_difference: str
63 trial_balance_closing_debit_net_total: str
64 trial_balance_rollforward_difference: str
65 balance_sheet_difference: str
66 balance_sheet_equity_total: str
67 equity_statement_closing_total: str
68 balance_sheet_equity_difference: str
69 income_statement_net_result: str
70 equity_net_profit_loss_movements: str
71 net_profit_equity_difference: str
72 balance_sheet_cash_total: str
73 cash_flow_closing_cash: str
74 balance_sheet_cash_difference: str
75 income_statement_bridge_valid: bool
76 cash_flow_bridge_valid: bool
77 equity_rollforward_valid: bool
78 trial_balance_arithmetic_valid: bool
79 cash_accounts_match_trial_balance: bool
80 cash_account_totals_valid: bool
81 selected_cash_notes: tuple[SelectedCashBalanceNote, ...]
82 findings: tuple[str, ...]
83 eligible_for_analyst_review: bool
84 kind: str = "UNAPPROVED_CROSS_STATEMENT_RECONCILIATION"
85 source_ledger_completeness_verified: bool = False
86 accounting_policy_authorized: bool = False
87 independently_reviewed: bool = False
88 trusted_approvals: bool = False
89 official_financial_statement: bool = False
90 export_authorized: bool = False
91 releasable: bool = False
92
93 def to_dict(self) -> dict[str, Any]:
94 return asdict(self)
95
96
97 def _hash(value: object, label: str) -> str:
98 if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
99 raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
100 return value
101
102
103 def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
104 if (not isinstance(value, str) or len(value) > 256
105 or value != value.strip() or (not value and not blank_ok)
106 or any(ord(char) < 32 or ord(char) == 127 for char in value)):
107 raise CoverageError("INVALID_CROSS_STATEMENT_" + label)
108 return value
109
110
111 def _validate_candidate(candidate: object, label: str, expected_type: type) -> None:
112 if type(candidate) is not expected_type:
113 raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_OBJECT")
114 if getattr(candidate, "kind", None) != EXPECTED_KINDS[label]:
115 raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_KIND")
116 forbidden = (
117 "official_financial_statement", "independently_reviewed",
118 "export_authorized", "releasable", "accounting_policy_authorized",
119 "trusted_approvals",
120 )
121 if any(getattr(candidate, flag, False) for flag in forbidden):
122 raise CoverageError("CROSS_STATEMENT_APPROVAL_PROVENANCE_INVALID")
123 _hash(candidate.source_sha256, label.upper() + "_SOURCE_HASH")
124 for hash_field in (
125 "note_references_sha256", "presentation_policies_sha256",
126 "transaction_ledger_sha256", "classification_policies_sha256",
127 ):
128 if hasattr(candidate, hash_field):
129 _hash(getattr(candidate, hash_field), label.upper() + "_" + hash_field.upper())
130 _text(candidate.company_code, label.upper() + "_COMPANY")
131 if type(candidate.fiscal_year) is not int or candidate.fiscal_year <= 0:
132 raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_YEAR")
133
134
135 def _income_bridge(income: IncomeStatementCandidate) -> bool:
136 revenue = _money(income.revenue_total)
137 cost = _money(income.cost_of_revenue_total)
138 gross = _money(income.gross_profit)
139 operating_expense = _money(income.operating_expense_total)
140 operating = _money(income.operating_profit)
141 other_income = _money(income.other_income_total)
142 other_expense = _money(income.other_expense_total)
143 pretax = _money(income.profit_before_tax)
144 tax = _money(income.tax_expense_total)
145 net = _money(income.net_result)
146 return (
147 _sum_exact([revenue, -cost, -gross]) == 0
148 and _sum_exact([gross, -operating_expense, -operating]) == 0
149 and _sum_exact([operating, other_income, -other_expense, -pretax]) == 0
150 and _sum_exact([pretax, -tax, -net]) == 0
151 )
152
153
154 def _cash_flow_bridge(cash: DirectCashFlowCandidate) -> bool:
155 categories = {
156 activity: {"inflows": [], "outflows": []}
157 for activity in ("OPERATING", "INVESTING", "FINANCING")
158 }
159 line_ids: set[str] = set()
160 transfer_values: list[Decimal] = []
161 if (type(cash.transaction_count) is not int
162 or cash.transaction_count != len(cash.cash_flow_lines)):
163 return False
164 for line in cash.cash_flow_lines:
165 if not isinstance(line, CashFlowLine):
166 return False
167 line_id = _text(line.line_id, "CASH_FLOW_LINE_ID")
168 if line_id in line_ids:
169 return False
170 line_ids.add(line_id)
171 inflow = _money(line.cash_inflow)
172 outflow = _money(line.cash_outflow)
173 if inflow < 0 or outflow < 0 or not ((inflow > 0) ^ (outflow > 0)):
174 return False
175 if line.activity in categories:
176 categories[line.activity]["inflows"].append(inflow)
177 categories[line.activity]["outflows"].append(outflow)
178 elif line.activity == "CASH_TRANSFER":
179 transfer_values.append(_sum_exact([inflow, outflow]))
180 else:
181 return False
182
183 operating = _sum_exact([
184 _sum_exact(categories["OPERATING"]["inflows"]),
185 -_sum_exact(categories["OPERATING"]["outflows"]),
186 ])
187 investing = _sum_exact([
188 _sum_exact(categories["INVESTING"]["inflows"]),
189 -_sum_exact(categories["INVESTING"]["outflows"]),
190 ])
191 financing = _sum_exact([
192 _sum_exact(categories["FINANCING"]["inflows"]),
193 -_sum_exact(categories["FINANCING"]["outflows"]),
194 ])
195 net_change = _money(cash.net_change_in_cash)
196 transfer_total = _sum_exact(transfer_values)
197 rollforward = _sum_exact([
198 _money(cash.opening_cash_and_equivalents), net_change,
199 -_money(cash.closing_cash_and_equivalents),
200 ])
201 return (
202 _sum_exact(categories["OPERATING"]["inflows"]) == _money(cash.operating_inflows)
203 and _sum_exact(categories["OPERATING"]["outflows"]) == _money(cash.operating_outflows)
204 and operating == _money(cash.operating_net_cash_flow)
205 and _sum_exact(categories["INVESTING"]["inflows"]) == _money(cash.investing_inflows)
206 and _sum_exact(categories["INVESTING"]["outflows"]) == _money(cash.investing_outflows)
207 and investing == _money(cash.investing_net_cash_flow)
208 and _sum_exact(categories["FINANCING"]["inflows"]) == _money(cash.financing_inflows)
209 and _sum_exact(categories["FINANCING"]["outflows"]) == _money(cash.financing_outflows)
210 and financing == _money(cash.financing_net_cash_flow)
211 and _sum_exact([operating, investing, financing, -net_change]) == 0
212 and _money(cash.internal_transfer_inflows) == transfer_total
213 and _money(cash.internal_transfer_outflows) == transfer_total
214 and rollforward == _money(cash.rollforward_difference) == 0
215 )
216
217
218 def _trial_balance_bridge(trial: TrialBalanceDiagnostic) -> bool:
219 if (type(trial.account_count) is not int
220 or trial.account_count != len(trial.accounts) or not trial.accounts):
221 return False
222 seen: set[str] = set()
223 openings: list[Decimal] = []
224 debits: list[Decimal] = []
225 credits: list[Decimal] = []
226 closings: list[Decimal] = []
227 for account in trial.accounts:
228 if not isinstance(account, TrialBalanceAccount):
229 return False
230 code = _text(account.account_code, "TRIAL_BALANCE_ACCOUNT_CODE")
231 if code in seen:
232 return False
233 seen.add(code)
234 opening = _money(account.opening)
235 debit = _money(account.debit)
236 credit = _money(account.credit)
237 closing = _money(account.closing)
238 if _sum_exact([debit, -credit]) != _money(account.debit_net_movement):
239 return False
240 openings.append(opening)
241 debits.append(debit)
242 credits.append(credit)
243 closings.append(closing)
244 opening_total = _sum_exact(openings)
245 debit_total = _sum_exact(debits)
246 credit_total = _sum_exact(credits)
247 closing_total = _sum_exact(closings)
248 movement = _sum_exact([debit_total, -credit_total])
249 rollforward = _sum_exact([opening_total, movement, -closing_total])
250 return (
251 trial.balanced_for_analyst_review
252 and opening_total == _money(trial.opening_debit_net_total)
253 and debit_total == _money(trial.debit_turnover_total)
254 and credit_total == _money(trial.credit_turnover_total)
255 and closing_total == _money(trial.closing_debit_net_total)
256 and movement == _money(trial.movement_difference) == 0
257 and opening_total == 0 and closing_total == 0
258 and rollforward == _money(trial.opening_to_closing_difference) == 0
259 )
260
261
262 def _cash_accounts_match_trial_balance(
263 cash: DirectCashFlowCandidate, trial: TrialBalanceDiagnostic,
264 ) -> tuple[bool, bool]:
265 findings_valid = True
266 totals_valid = True
267 if (type(trial.account_count) is not int
268 or trial.account_count != len(trial.accounts)):
269 findings_valid = False
270 trial_by_code: dict[str, TrialBalanceAccount] = {}
271 for account in trial.accounts:
272 if (not isinstance(account, TrialBalanceAccount)
273 or not isinstance(account.account_code, str)
274 or account.account_code in trial_by_code):
275 findings_valid = False
276 continue
277 trial_by_code[account.account_code] = account
278
279 if (type(cash.cash_account_count) is not int
280 or cash.cash_account_count != len(cash.account_reconciliations)):
281 findings_valid = False
282 seen: set[str] = set()
283 opening_values: list[Decimal] = []
284 closing_values: list[Decimal] = []
285 for item in cash.account_reconciliations:
286 if (not isinstance(item, CashAccountReconciliation)
287 or not isinstance(item.account_code, str)
288 or item.account_code in seen):
289 findings_valid = False
290 continue
291 seen.add(item.account_code)
292 trial_account = trial_by_code.get(item.account_code)
293 if trial_account is None:
294 findings_valid = False
295 continue
296 source_values = (
297 _money(item.opening_balance), _money(item.source_debit_turnover),
298 _money(item.source_credit_turnover), _money(item.closing_balance),
299 )
300 trial_values = (
301 _money(trial_account.opening), _money(trial_account.debit),
302 _money(trial_account.credit), _money(trial_account.closing),
303 )
304 if (source_values != trial_values
305 or item.source_row != trial_account.source_row):
306 findings_valid = False
307 debit_difference = _sum_exact([
308 _money(item.transaction_debit_turnover),
309 -_money(item.source_debit_turnover),
310 ])
311 credit_difference = _sum_exact([
312 _money(item.transaction_credit_turnover),
313 -_money(item.source_credit_turnover),
314 ])
315 rollforward = _sum_exact([
316 source_values[0], source_values[1], -source_values[2], -source_values[3],
317 ])
318 if (debit_difference != 0 or credit_difference != 0 or rollforward != 0
319 or _money(item.debit_difference) != debit_difference
320 or _money(item.credit_difference) != credit_difference
321 or _money(item.rollforward_difference) != rollforward):
322 totals_valid = False
323 opening_values.append(source_values[0])
324 closing_values.append(source_values[3])
325
326 if (_sum_exact(opening_values) != _money(cash.opening_cash_and_equivalents)
327 or _sum_exact(closing_values) != _money(cash.closing_cash_and_equivalents)):
328 totals_valid = False
329 return findings_valid, totals_valid
330
331
332 def reconcile_cross_statements(
333 *, balance_sheet: BalanceSheetCandidate,
334 income_statement: IncomeStatementCandidate,
335 equity_changes: EquityChangesCandidate,
336 cash_flow: DirectCashFlowCandidate,
337 trial_balance: TrialBalanceDiagnostic,
338 cash_balance_notes: Sequence[CashBalanceNoteSelection],
339 ) -> CrossStatementReconciliation:
340 """Reconcile BS/IS/EQ/CF/TB candidates without granting financial approval.
341
342 The caller must explicitly select the BS asset notes that represent cash
343 and cash equivalents. This policy is evidence-bearing and untrusted. Exact
344 Decimal comparison uses zero tolerance; any scope/hash mismatch or blocked
345 upstream candidate prevents analyst eligibility.
346 """
347 candidates = (
348 ("balance_sheet", balance_sheet, BalanceSheetCandidate),
349 ("income_statement", income_statement, IncomeStatementCandidate),
350 ("equity_changes", equity_changes, EquityChangesCandidate),
351 ("cash_flow", cash_flow, DirectCashFlowCandidate),
352 ("trial_balance", trial_balance, TrialBalanceDiagnostic),
353 )
354 for label, candidate, expected_type in candidates:
355 _validate_candidate(candidate, label, expected_type)
356
357 if not isinstance(cash_balance_notes, (list, tuple)) or not 0 < len(cash_balance_notes) <= 5_000:
358 raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
359
360 selected: dict[tuple[str, str, str], CashBalanceNoteSelection] = {}
361 for item in cash_balance_notes:
362 if not isinstance(item, CashBalanceNoteSelection):
363 raise CoverageError("INVALID_CASH_BALANCE_NOTE_SELECTION")
364 key = (
365 _text(item.statement_section, "CASH_NOTE_SECTION"),
366 _text(item.note_number, "CASH_NOTE_NUMBER"),
367 _text(item.subnote_code, "CASH_NOTE_SUBNOTE", blank_ok=True),
368 )
369 _text(item.evidence_ref, "CASH_NOTE_EVIDENCE")
370 if key in selected:
371 raise CoverageError("DUPLICATE_CASH_BALANCE_NOTE_SELECTION")
372 selected[key] = item
373 selection_hash = sha256(json.dumps(
374 [asdict(selected[key]) for key in sorted(selected)],
375 ensure_ascii=True, sort_keys=True, separators=(",", ":"),
376 ).encode("utf-8")).hexdigest()
377
378 findings: list[str] = []
379 base = balance_sheet
380 if any(
381 candidate.company_code != base.company_code
382 or candidate.fiscal_year != base.fiscal_year
383 for _, candidate, _ in candidates
384 ):
385 findings.append("CROSS_STATEMENT_COMPANY_YEAR_MISMATCH")
386
387 hashes = {candidate.source_sha256 for _, candidate, _ in candidates}
388 same_snapshot = len(hashes) == 1
389 if not same_snapshot:
390 findings.append("CROSS_STATEMENT_SOURCE_SNAPSHOT_MISMATCH")
391 source_hash = base.source_sha256
392
393 for label, candidate, _ in candidates:
394 eligible = (
395 getattr(candidate, "eligible_for_analyst_review", None)
396 if label != "trial_balance"
397 else candidate.balanced_for_analyst_review
398 )
399 if not eligible:
400 findings.append(label.upper() + "_CANDIDATE_BLOCKED")
401
402 bs_computed_difference = _sum_exact([
403 _money(balance_sheet.assets_total),
404 -_money(balance_sheet.liabilities_total),
405 -_money(balance_sheet.equity_total),
406 ])
407 bs_reported_difference = _money(balance_sheet.balance_difference)
408 if (bs_computed_difference != bs_reported_difference
409 or bs_reported_difference != 0
410 or not balance_sheet.arithmetically_balanced):
411 findings.append("BALANCE_SHEET_EQUATION_INVALID")
412
413 equity_difference = _sum_exact([
414 _money(balance_sheet.equity_total),
415 -_money(equity_changes.closing_equity_total),
416 ])
417 if equity_difference != 0:
418 findings.append("BALANCE_SHEET_EQUITY_CLOSING_MISMATCH")
419
420 profit_difference = _sum_exact([
421 _money(income_statement.net_result),
422 -_money(equity_changes.net_profit_loss_movements),
423 ])
424 if profit_difference != 0:
425 findings.append("INCOME_RESULT_EQUITY_MOVEMENT_MISMATCH")
426
427 income_valid = _income_bridge(income_statement)
428 if not income_valid:
429 findings.append("INCOME_STATEMENT_BRIDGE_INVALID")
430
431 equity_rollforward = _sum_exact([
432 _money(equity_changes.opening_equity_total),
433 _money(equity_changes.total_movement),
434 -_money(equity_changes.closing_equity_total),
435 ])
436 equity_rollforward_valid = (
437 equity_rollforward == 0
438 and _money(equity_changes.rollforward_difference) == 0
439 )
440 if not equity_rollforward_valid:
441 findings.append("EQUITY_STATEMENT_ROLLFORWARD_INVALID")
442
443 bs_lines = {}
444 for line in balance_sheet.lines:
445 key = (line.statement_section, line.note_number, line.subnote_code)
446 if key in bs_lines:
447 findings.append("DUPLICATE_BALANCE_SHEET_NOTE_LINE")
448 else:
449 bs_lines[key] = line
450 selected_lines: list[SelectedCashBalanceNote] = []
451 cash_amounts: list[Decimal] = []
452 for key in sorted(selected):
453 line = bs_lines.get(key)
454 if line is None:
455 findings.append("CASH_BALANCE_NOTE_NOT_FOUND_IN_BALANCE_SHEET")
456 continue
457 if line.category != "ASSETS":
458 findings.append("CASH_BALANCE_NOTE_NOT_ASSET")
459 continue
460 amount = _money(line.presentation_amount)
461 cash_amounts.append(amount)
462 selected_lines.append(SelectedCashBalanceNote(
463 statement_section=key[0], note_number=key[1],
464 subnote_code=key[2], presentation_amount=str(amount),
465 evidence_ref=selected[key].evidence_ref,
466 ))
467 if len(selected_lines) != len(selected):
468 findings.append("CASH_BALANCE_NOTE_SELECTION_INCOMPLETE")
469 bs_cash_total = _sum_exact(cash_amounts)
470 cash_difference = _sum_exact([
471 bs_cash_total, -_money(cash_flow.closing_cash_and_equivalents),
472 ])
473 if cash_difference != 0:
474 findings.append("BALANCE_SHEET_CASH_FLOW_CLOSING_MISMATCH")
475
476 cash_valid = _cash_flow_bridge(cash_flow)
477 if not cash_valid:
478 findings.append("CASH_FLOW_BRIDGE_INVALID")
479
480 cash_accounts_match_tb, cash_account_totals_valid = (
481 _cash_accounts_match_trial_balance(cash_flow, trial_balance)
482 )
483 if not cash_accounts_match_tb:
484 findings.append("CASH_ACCOUNTS_TRIAL_BALANCE_MISMATCH")
485 if not cash_account_totals_valid:
486 findings.append("CASH_ACCOUNT_TURNOVER_OR_TOTALS_INVALID")
487
488 trial_valid = _trial_balance_bridge(trial_balance)
489 if not trial_valid:
490 findings.append("TRIAL_BALANCE_ARITHMETIC_INVALID")
491
492 tb_opening = _money(trial_balance.opening_debit_net_total)
493 tb_movement = _money(trial_balance.movement_difference)
494 tb_closing = _money(trial_balance.closing_debit_net_total)
495 tb_rollforward = _money(trial_balance.opening_to_closing_difference)
496
497 return CrossStatementReconciliation(
498 company_code=base.company_code, fiscal_year=base.fiscal_year,
499 source_sha256=source_hash,
500 cash_flow_transaction_ledger_sha256=_hash(
501 cash_flow.transaction_ledger_sha256, "CASH_FLOW_TRANSACTION_HASH",
502 ),
503 cash_note_selection_sha256=selection_hash,
504 same_source_snapshot=same_snapshot,
505 trial_balance_opening_debit_net_total=str(tb_opening),
506 trial_balance_movement_difference=str(tb_movement),
507 trial_balance_closing_debit_net_total=str(tb_closing),
508 trial_balance_rollforward_difference=str(tb_rollforward),
509 balance_sheet_difference=str(bs_reported_difference),
510 balance_sheet_equity_total=str(_money(balance_sheet.equity_total)),
511 equity_statement_closing_total=str(_money(equity_changes.closing_equity_total)),
512 balance_sheet_equity_difference=str(equity_difference),
513 income_statement_net_result=str(_money(income_statement.net_result)),
514 equity_net_profit_loss_movements=str(_money(equity_changes.net_profit_loss_movements)),
515 net_profit_equity_difference=str(profit_difference),
516 balance_sheet_cash_total=str(bs_cash_total),
517 cash_flow_closing_cash=str(_money(cash_flow.closing_cash_and_equivalents)),
518 balance_sheet_cash_difference=str(cash_difference),
519 income_statement_bridge_valid=income_valid,
520 cash_flow_bridge_valid=cash_valid,
521 equity_rollforward_valid=equity_rollforward_valid,
522 trial_balance_arithmetic_valid=trial_valid,
523 cash_accounts_match_trial_balance=cash_accounts_match_tb,
524 cash_account_totals_valid=cash_account_totals_valid,
525 selected_cash_notes=tuple(selected_lines),
526 findings=tuple(sorted(set(findings))),
527 eligible_for_analyst_review=not findings,
528 )