Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 17:00 UTC
feat(control): recompute BS, IS and equity summaries from line-level traces
davoodmehraban89 committed
Oct 31, 2026 at 11:21 UTC
357f3270196957815918786edac2ed2807f20c3f
1 file changed
+280
-9
backend/src/aram_backend/cross_statement_reconciliation.py
+280
-9
@@ -12,13 +12,22 @@ import json
12
import re
13
from typing import Any, Sequence
14
15
-from aram_backend.balance_sheet_candidate import BalanceSheetCandidate
15
+from aram_backend.balance_sheet_candidate import (
16
+ CATEGORIES as BALANCE_SHEET_CATEGORIES,
17
+ BalanceSheetCandidate, CandidateBalanceSheetLine,
18
+)
19
from aram_backend.cash_flow_direct_candidate import (
20
CashAccountReconciliation, CashFlowLine, DirectCashFlowCandidate,
21
)
22
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
23
+from aram_backend.equity_changes_candidate import (
24
+ EQUITY_COMPONENTS, MOVEMENT_CATEGORIES, EquityAccountMovement,
25
+ EquityChangesCandidate, EquityComponentTotal, EquityNoteMovement,
26
+)
27
+from aram_backend.income_statement_candidate import (
28
+ CATEGORIES as INCOME_STATEMENT_CATEGORIES,
29
+ CandidateIncomeStatementLine, IncomeStatementCandidate,
30
+)
31
from aram_backend.reconciliation_review import _money, _sum_exact
32
from aram_backend.trial_balance_diagnostic import (
33
TrialBalanceAccount, TrialBalanceDiagnostic,
@@ -110,16 +119,34 @@ def _text(value: object, label: str, *, blank_ok: bool = False) -> str:
119
120
def _validate_candidate(candidate: object, label: str, expected_type: type) -> None:
121
if type(candidate) is not expected_type:
113
- raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_OBJECT")
122
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_OBJECT")
123
if getattr(candidate, "kind", None) != EXPECTED_KINDS[label]:
115
- raise CoverageError("INVALID_CROSS_STATEMENT_" + label + "_KIND")
124
+ raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_KIND")
125
forbidden = (
126
"official_financial_statement", "independently_reviewed",
127
"export_authorized", "releasable", "accounting_policy_authorized",
119
- "trusted_approvals",
128
+ "trusted_approvals", "source_ledger_completeness_verified",
129
+ "cash_account_scope_owner_approved",
130
+ "transaction_ledger_completeness_verified",
131
+ "accounting_policies_verified",
132
+ )
133
+ for flag in forbidden:
134
+ if hasattr(candidate, flag):
135
+ value = getattr(candidate, flag)
136
+ if type(value) is not bool or value:
137
+ raise CoverageError("CROSS_STATEMENT_APPROVAL_PROVENANCE_INVALID")
138
+ eligible_field = (
139
+ "balanced_for_analyst_review" if label == "trial_balance"
140
+ else "eligible_for_analyst_review"
141
)
121
- if any(getattr(candidate, flag, False) for flag in forbidden):
122
- raise CoverageError("CROSS_STATEMENT_APPROVAL_PROVENANCE_INVALID")
142
+ eligible = getattr(candidate, eligible_field, None)
143
+ if type(eligible) is not bool:
144
+ raise CoverageError("CROSS_STATEMENT_CANDIDATE_ELIGIBILITY_INVALID")
145
+ findings = getattr(candidate, "findings", None)
146
+ if (not isinstance(findings, tuple)
147
+ or any(not isinstance(item, str) or not item for item in findings)
148
+ or (eligible and findings)):
149
+ raise CoverageError("CROSS_STATEMENT_CANDIDATE_FINDINGS_INVALID")
150
_hash(candidate.source_sha256, label.upper() + "_SOURCE_HASH")
151
for hash_field in (
152
"note_references_sha256", "presentation_policies_sha256",
@@ -132,6 +159,249 @@ def _validate_candidate(candidate: object, label: str, expected_type: type) -> N
159
raise CoverageError("INVALID_CROSS_STATEMENT_" + label.upper() + "_YEAR")
160
161
162
+def _balance_sheet_detail_bridge(balance: BalanceSheetCandidate) -> bool:
163
+ if not isinstance(balance.lines, tuple) or not balance.lines:
164
+ return False
165
+ buckets: dict[str, list[Decimal]] = {
166
+ category: [] for category in BALANCE_SHEET_CATEGORIES
167
+ }
168
+ seen: set[tuple[str, str, str]] = set()
169
+ for line in balance.lines:
170
+ if not isinstance(line, CandidateBalanceSheetLine):
171
+ return False
172
+ key = (
173
+ _text(line.statement_section, "BS_DETAIL_SECTION"),
174
+ _text(line.note_number, "BS_DETAIL_NOTE"),
175
+ _text(line.subnote_code, "BS_DETAIL_SUBNOTE", blank_ok=True),
176
+ )
177
+ if key in seen or line.category not in BALANCE_SHEET_CATEGORIES:
178
+ return False
179
+ seen.add(key)
180
+ if type(line.sign_multiplier) is not int or line.sign_multiplier not in (-1, 1):
181
+ return False
182
+ source = _money(line.source_closing_exposure)
183
+ amount = _money(line.presentation_amount)
184
+ if amount != source * line.sign_multiplier or amount < 0:
185
+ return False
186
+ _text(line.line_label, "BS_DETAIL_LABEL")
187
+ _text(line.note_reference_evidence, "BS_DETAIL_REFERENCE")
188
+ _text(line.policy_evidence_ref, "BS_DETAIL_POLICY")
189
+ buckets[line.category].append(amount)
190
+ totals = {key: _sum_exact(values) for key, values in buckets.items()}
191
+ return (
192
+ all(buckets[key] for key in BALANCE_SHEET_CATEGORIES)
193
+ and totals["ASSETS"] == _money(balance.assets_total)
194
+ and totals["LIABILITIES"] == _money(balance.liabilities_total)
195
+ and totals["EQUITY"] == _money(balance.equity_total)
196
+ and _sum_exact([
197
+ totals["ASSETS"], -totals["LIABILITIES"], -totals["EQUITY"],
198
+ ]) == _money(balance.balance_difference) == 0
199
+ and balance.arithmetically_balanced is True
200
+ )
201
+
202
+
203
+def _income_detail_bridge(income: IncomeStatementCandidate) -> bool:
204
+ if not isinstance(income.lines, tuple) or not income.lines:
205
+ return False
206
+ buckets: dict[str, list[Decimal]] = {
207
+ category: [] for category in INCOME_STATEMENT_CATEGORIES
208
+ }
209
+ seen: set[tuple[str, str, str]] = set()
210
+ for line in income.lines:
211
+ if not isinstance(line, CandidateIncomeStatementLine):
212
+ return False
213
+ key = (
214
+ _text(line.statement_section, "IS_DETAIL_SECTION"),
215
+ _text(line.note_number, "IS_DETAIL_NOTE"),
216
+ _text(line.subnote_code, "IS_DETAIL_SUBNOTE", blank_ok=True),
217
+ )
218
+ if key in seen or line.category not in INCOME_STATEMENT_CATEGORIES:
219
+ return False
220
+ seen.add(key)
221
+ if type(line.sign_multiplier) is not int or line.sign_multiplier not in (-1, 1):
222
+ return False
223
+ source = _money(line.source_closing_exposure)
224
+ amount = _money(line.presentation_amount)
225
+ if amount != source * line.sign_multiplier or amount < 0:
226
+ return False
227
+ _text(line.line_label, "IS_DETAIL_LABEL")
228
+ _text(line.note_reference_evidence, "IS_DETAIL_REFERENCE")
229
+ _text(line.policy_evidence_ref, "IS_DETAIL_POLICY")
230
+ buckets[line.category].append(amount)
231
+ totals = {key: _sum_exact(values) for key, values in buckets.items()}
232
+ revenue = totals["REVENUE"]
233
+ cost = totals["COST_OF_REVENUE"]
234
+ gross = _sum_exact([revenue, -cost])
235
+ operating = _sum_exact([gross, -totals["OPERATING_EXPENSE"]])
236
+ pretax = _sum_exact([
237
+ operating, totals["OTHER_INCOME"], -totals["OTHER_EXPENSE"],
238
+ ])
239
+ net = _sum_exact([pretax, -totals["TAX_EXPENSE"]])
240
+ return (
241
+ bool(buckets["REVENUE"])
242
+ and any(buckets[key] for key in (
243
+ "COST_OF_REVENUE", "OPERATING_EXPENSE",
244
+ "OTHER_EXPENSE", "TAX_EXPENSE",
245
+ ))
246
+ and revenue == _money(income.revenue_total)
247
+ and cost == _money(income.cost_of_revenue_total)
248
+ and gross == _money(income.gross_profit)
249
+ and totals["OPERATING_EXPENSE"] == _money(income.operating_expense_total)
250
+ and operating == _money(income.operating_profit)
251
+ and totals["OTHER_INCOME"] == _money(income.other_income_total)
252
+ and totals["OTHER_EXPENSE"] == _money(income.other_expense_total)
253
+ and pretax == _money(income.profit_before_tax)
254
+ and totals["TAX_EXPENSE"] == _money(income.tax_expense_total)
255
+ and net == _money(income.net_result)
256
+ )
257
+
258
+
259
+def _equity_detail_bridge(equity: EquityChangesCandidate) -> bool:
260
+ if (not isinstance(equity.note_movements, tuple) or not equity.note_movements
261
+ or not isinstance(equity.account_movements, tuple)
262
+ or not equity.account_movements
263
+ or not isinstance(equity.component_totals, tuple)):
264
+ return False
265
+ accounts_by_note: dict[tuple[str, str, str], list[EquityAccountMovement]] = {}
266
+ seen_accounts: set[str] = set()
267
+ for account in equity.account_movements:
268
+ if not isinstance(account, EquityAccountMovement):
269
+ return False
270
+ code = _text(account.account_code, "EQ_DETAIL_ACCOUNT")
271
+ if code in seen_accounts:
272
+ return False
273
+ seen_accounts.add(code)
274
+ key = (
275
+ _text(account.statement_section, "EQ_DETAIL_SECTION"),
276
+ _text(account.note_number, "EQ_DETAIL_NOTE"),
277
+ _text(account.subnote_code, "EQ_DETAIL_SUBNOTE", blank_ok=True),
278
+ )
279
+ if (account.equity_component not in EQUITY_COMPONENTS
280
+ or account.movement_category not in MOVEMENT_CATEGORIES
281
+ or type(account.sign_multiplier) is not int
282
+ or account.sign_multiplier not in (-1, 1)
283
+ or type(account.source_excel_row) is not int
284
+ or account.source_excel_row < 2
285
+ or type(account.source_row) is not int
286
+ or account.source_row <= 0):
287
+ return False
288
+ opening = _money(account.opening_balance)
289
+ debit = _money(account.debit_turnover)
290
+ credit = _money(account.credit_turnover)
291
+ movement = _money(account.movement_amount)
292
+ closing = _money(account.closing_balance)
293
+ if (debit < 0 or credit < 0
294
+ or movement != _sum_exact([debit, -credit]) * account.sign_multiplier
295
+ or _sum_exact([opening, movement, -closing]) != 0):
296
+ return False
297
+ _text(account.account_name, "EQ_DETAIL_ACCOUNT_NAME")
298
+ _text(account.policy_evidence_ref, "EQ_DETAIL_POLICY")
299
+ accounts_by_note.setdefault(key, []).append(account)
300
+
301
+ note_by_key: dict[tuple[str, str, str], EquityNoteMovement] = {}
302
+ category_movements: dict[str, list[Decimal]] = {
303
+ category: [] for category in MOVEMENT_CATEGORIES
304
+ }
305
+ component_values: dict[str, dict[str, list[Decimal]]] = {}
306
+ opening_values: list[Decimal] = []
307
+ movement_values: list[Decimal] = []
308
+ closing_values: list[Decimal] = []
309
+ for note in equity.note_movements:
310
+ if not isinstance(note, EquityNoteMovement):
311
+ return False
312
+ key = (
313
+ _text(note.statement_section, "EQ_DETAIL_SECTION"),
314
+ _text(note.note_number, "EQ_DETAIL_NOTE"),
315
+ _text(note.subnote_code, "EQ_DETAIL_SUBNOTE", blank_ok=True),
316
+ )
317
+ if key in note_by_key or key not in accounts_by_note:
318
+ return False
319
+ if (note.equity_component not in EQUITY_COMPONENTS
320
+ or note.movement_category not in MOVEMENT_CATEGORIES):
321
+ return False
322
+ _text(note.line_label, "EQ_DETAIL_LABEL")
323
+ _text(note.note_reference_evidence, "EQ_DETAIL_REFERENCE")
324
+ _text(note.policy_evidence_ref, "EQ_DETAIL_POLICY")
325
+ rows = accounts_by_note[key]
326
+ if any(
327
+ row.equity_component != note.equity_component
328
+ or row.movement_category != note.movement_category
329
+ for row in rows
330
+ ):
331
+ return False
332
+ opening = _sum_exact([_money(row.opening_balance) for row in rows])
333
+ movement = _sum_exact([_money(row.movement_amount) for row in rows])
334
+ closing = _sum_exact([_money(row.closing_balance) for row in rows])
335
+ raw_closing = _sum_exact([
336
+ _money(row.closing_balance) * row.sign_multiplier for row in rows
337
+ ])
338
+ note_opening = _money(note.opening_balance)
339
+ note_movement = _money(note.movement_amount)
340
+ note_closing = _money(note.closing_balance)
341
+ if (
342
+ opening != note_opening or movement != note_movement
343
+ or closing != note_closing
344
+ or raw_closing != _money(note.source_closing_exposure)
345
+ or _sum_exact([note_opening, note_movement, -note_closing]) != 0
346
+ ):
347
+ return False
348
+ note_by_key[key] = note
349
+ opening_values.append(note_opening)
350
+ movement_values.append(note_movement)
351
+ closing_values.append(note_closing)
352
+ category_movements[note.movement_category].append(note_movement)
353
+ group = component_values.setdefault(note.equity_component, {
354
+ "opening": [], "movement": [], "closing": [],
355
+ })
356
+ group["opening"].append(note_opening)
357
+ group["movement"].append(note_movement)
358
+ group["closing"].append(note_closing)
359
+ if set(accounts_by_note) != set(note_by_key):
360
+ return False
361
+
362
+ component_by_key: dict[str, EquityComponentTotal] = {}
363
+ for item in equity.component_totals:
364
+ if not isinstance(item, EquityComponentTotal):
365
+ return False
366
+ if item.equity_component not in EQUITY_COMPONENTS or item.equity_component in component_by_key:
367
+ return False
368
+ component_by_key[item.equity_component] = item
369
+ if set(component_by_key) != set(component_values):
370
+ return False
371
+ for component, group in component_values.items():
372
+ item = component_by_key[component]
373
+ if (
374
+ _money(item.opening_balance) != _sum_exact(group["opening"])
375
+ or _money(item.movement_amount) != _sum_exact(group["movement"])
376
+ or _money(item.closing_balance) != _sum_exact(group["closing"])
377
+ ):
378
+ return False
379
+
380
+ summary_categories = {
381
+ "CAPITAL_CONTRIBUTION": equity.capital_contributions,
382
+ "NET_PROFIT_LOSS": equity.net_profit_loss_movements,
383
+ "DIVIDENDS": equity.dividends,
384
+ "OTHER_COMPREHENSIVE_INCOME": equity.other_comprehensive_income,
385
+ "TRANSFER": equity.transfers,
386
+ "PRIOR_PERIOD_ADJUSTMENT": equity.prior_period_adjustments,
387
+ "OTHER_MOVEMENT": equity.other_movements,
388
+ }
389
+ return (
390
+ _sum_exact(opening_values) == _money(equity.opening_equity_total)
391
+ and _sum_exact(movement_values) == _money(equity.total_movement)
392
+ and _sum_exact(closing_values) == _money(equity.closing_equity_total)
393
+ and _sum_exact([
394
+ _money(equity.opening_equity_total),
395
+ _money(equity.total_movement),
396
+ -_money(equity.closing_equity_total),
397
+ ]) == _money(equity.rollforward_difference) == 0
398
+ and all(
399
+ _sum_exact(category_movements[category]) == _money(amount)
400
+ for category, amount in summary_categories.items()
401
+ )
402
+ )
403
+
404
+
405
def _income_bridge(income: IncomeStatementCandidate) -> bool:
406
revenue = _money(income.revenue_total)
407
cost = _money(income.cost_of_revenue_total)
@@ -144,7 +414,8 @@ def _income_bridge(income: IncomeStatementCandidate) -> bool:
414
tax = _money(income.tax_expense_total)
415
net = _money(income.net_result)
416
return (
147
- _sum_exact([revenue, -cost, -gross]) == 0
417
+ _income_detail_bridge(income)
418
+ and _sum_exact([revenue, -cost, -gross]) == 0
419
and _sum_exact([gross, -operating_expense, -operating]) == 0
420
and _sum_exact([operating, other_income, -other_expense, -pretax]) == 0
421
and _sum_exact([pretax, -tax, -net]) == 0