feat(statements): require paired cash journal lines for direct cash flow candidate
davoodmehraban89 committed
Oct 31, 2026 at 08:22 UTC
a9c8df06e60b25c94cd01bda0c7ce0ea57af032d
1 file changed
+488
backend/src/aram_backend/cash_flow_direct_candidate.py
new
+488
@@ -0,0 +1,488 @@
1
+"""Direct-method cash flow candidate from paired, classified cash journal lines.
2
+
3
+This module deliberately requires transaction-level cash/counterpart postings.
4
+Aggregate account debit/credit totals alone cannot identify operating, investing
5
+or financing activity and must never be guessed into a cash flow statement.
6
+"""
7
+from __future__ import annotations
8
+
9
+from dataclasses import asdict, dataclass
10
+from decimal import Decimal
11
+from hashlib import sha256
12
+from io import BytesIO
13
+import json
14
+import re
15
+from typing import Any, Sequence
16
+
17
+from openpyxl import load_workbook
18
+
19
+from aram_backend.coverage_preview import (
20
+ CoverageError, MAX_INPUT_BYTES, _assert_visible, _guard_archive,
21
+)
22
+from aram_backend.pilot_workbook import SHEET_HEADERS, preflight_pilot_workbook
23
+from aram_backend.reconciliation_review import _money, _sum_exact
24
+
25
+MAX_CASH_ACCOUNTS = 5_000
26
+MAX_COUNTERPART_POLICIES = 20_000
27
+MAX_CASH_TRANSACTIONS = 30_000
28
+ACTIVITIES = frozenset({"OPERATING", "INVESTING", "FINANCING"})
29
+
30
+
31
+@dataclass(frozen=True)
32
+class CashAccountPolicy:
33
+ account_code: str
34
+ evidence_ref: str
35
+
36
+
37
+@dataclass(frozen=True)
38
+class CashCounterpartPolicy:
39
+ account_code: str
40
+ activity: str
41
+ evidence_ref: str
42
+
43
+
44
+@dataclass(frozen=True)
45
+class CashFlowEntry:
46
+ company_code: str
47
+ fiscal_year: int
48
+ line_id: str
49
+ transaction_id: str
50
+ posting_date: str
51
+ cash_account_code: str
52
+ counterpart_account_code: str
53
+ cash_debit: str
54
+ cash_credit: str
55
+ counterpart_debit: str
56
+ counterpart_credit: str
57
+ evidence_ref: str
58
+
59
+
60
+@dataclass(frozen=True)
61
+class CashAccountReconciliation:
62
+ account_code: str
63
+ account_name: str
64
+ source_row: int
65
+ opening_balance: str
66
+ source_debit_turnover: str
67
+ source_credit_turnover: str
68
+ closing_balance: str
69
+ transaction_debit_turnover: str
70
+ transaction_credit_turnover: str
71
+ debit_difference: str
72
+ credit_difference: str
73
+ rollforward_difference: str
74
+ policy_evidence_ref: str
75
+
76
+
77
+@dataclass(frozen=True)
78
+class CashFlowLine:
79
+ line_id: str
80
+ transaction_id: str
81
+ posting_date: str
82
+ cash_account_code: str
83
+ counterpart_account_code: str
84
+ activity: str
85
+ cash_inflow: str
86
+ cash_outflow: str
87
+ source_evidence_ref: str
88
+ classification_evidence_ref: str | None
89
+
90
+
91
+@dataclass(frozen=True)
92
+class DirectCashFlowCandidate:
93
+ company_code: str
94
+ fiscal_year: int
95
+ currency: str
96
+ unit: str
97
+ source_sha256: str
98
+ transaction_ledger_sha256: str
99
+ classification_policies_sha256: str
100
+ cash_account_count: int
101
+ transaction_count: int
102
+ opening_cash_and_equivalents: str
103
+ operating_inflows: str
104
+ operating_outflows: str
105
+ operating_net_cash_flow: str
106
+ investing_inflows: str
107
+ investing_outflows: str
108
+ investing_net_cash_flow: str
109
+ financing_inflows: str
110
+ financing_outflows: str
111
+ financing_net_cash_flow: str
112
+ internal_transfer_inflows: str
113
+ internal_transfer_outflows: str
114
+ net_change_in_cash: str
115
+ closing_cash_and_equivalents: str
116
+ rollforward_difference: str
117
+ account_reconciliations: tuple[CashAccountReconciliation, ...]
118
+ cash_flow_lines: tuple[CashFlowLine, ...]
119
+ findings: tuple[str, ...]
120
+ eligible_for_analyst_review: bool
121
+ kind: str = "UNAPPROVED_DIRECT_CASH_FLOW_CANDIDATE"
122
+ cash_account_scope_owner_approved: bool = False
123
+ transaction_ledger_completeness_verified: bool = False
124
+ accounting_policy_authorized: bool = False
125
+ official_financial_statement: bool = False
126
+ independently_reviewed: bool = False
127
+ export_authorized: bool = False
128
+ releasable: bool = False
129
+
130
+ def to_dict(self) -> dict[str, Any]:
131
+ return asdict(self)
132
+
133
+
134
+def _text(value: object, label: str, *, max_length: int = 256) -> str:
135
+ if (not isinstance(value, str) or not value or len(value) > max_length
136
+ or value != value.strip()
137
+ or any(ord(char) < 32 or ord(char) == 127 for char in value)):
138
+ raise CoverageError("INVALID_CASH_FLOW_" + label)
139
+ return value
140
+
141
+
142
+def _date(value: object, fiscal_year: int) -> str:
143
+ result = _text(value, "POSTING_DATE", max_length=10)
144
+ if (not re.fullmatch(r"\d{4}-\d{2}-\d{2}", result)
145
+ or int(result[:4]) != fiscal_year
146
+ or not 1 <= int(result[5:7]) <= 12
147
+ or not 1 <= int(result[8:10]) <= 31):
148
+ raise CoverageError("INVALID_CASH_FLOW_POSTING_DATE")
149
+ # Year is the explicitly selected source fiscal-year label; no Gregorian
150
+ # or Jalali conversion is attempted here.
151
+ return result
152
+
153
+
154
+def _policies(
155
+ cash_accounts: Sequence[CashAccountPolicy],
156
+ counterparts: Sequence[CashCounterpartPolicy],
157
+) -> tuple[dict[str, CashAccountPolicy], dict[str, CashCounterpartPolicy], str]:
158
+ if (not isinstance(cash_accounts, (list, tuple))
159
+ or not 0 < len(cash_accounts) <= MAX_CASH_ACCOUNTS):
160
+ raise CoverageError("INVALID_CASH_ACCOUNT_POLICIES")
161
+ if (not isinstance(counterparts, (list, tuple))
162
+ or len(counterparts) > MAX_COUNTERPART_POLICIES):
163
+ raise CoverageError("INVALID_CASH_COUNTERPART_POLICIES")
164
+ cash: dict[str, CashAccountPolicy] = {}
165
+ other: dict[str, CashCounterpartPolicy] = {}
166
+ for policy in cash_accounts:
167
+ if not isinstance(policy, CashAccountPolicy):
168
+ raise CoverageError("INVALID_CASH_ACCOUNT_POLICY")
169
+ code = _text(policy.account_code, "ACCOUNT_CODE")
170
+ evidence = _text(policy.evidence_ref, "ACCOUNT_EVIDENCE")
171
+ if code in cash:
172
+ raise CoverageError("DUPLICATE_CASH_ACCOUNT_POLICY")
173
+ cash[code] = policy
174
+ for policy in counterparts:
175
+ if not isinstance(policy, CashCounterpartPolicy):
176
+ raise CoverageError("INVALID_CASH_COUNTERPART_POLICY")
177
+ code = _text(policy.account_code, "COUNTERPART_CODE")
178
+ evidence = _text(policy.evidence_ref, "COUNTERPART_EVIDENCE")
179
+ if code in cash:
180
+ raise CoverageError("CASH_ACCOUNT_CANNOT_BE_COUNTERPART_POLICY")
181
+ if policy.activity not in ACTIVITIES:
182
+ raise CoverageError("INVALID_CASH_FLOW_ACTIVITY")
183
+ if code in other:
184
+ raise CoverageError("DUPLICATE_CASH_COUNTERPART_POLICY")
185
+ other[code] = policy
186
+ canonical = {
187
+ "cash_accounts": [
188
+ asdict(cash[key]) for key in sorted(cash)
189
+ ],
190
+ "counterparts": [
191
+ asdict(other[key]) for key in sorted(other)
192
+ ],
193
+ }
194
+ digest = sha256(json.dumps(
195
+ canonical, ensure_ascii=True, sort_keys=True, separators=(",", ":"),
196
+ ).encode("utf-8")).hexdigest()
197
+ return cash, other, digest
198
+
199
+
200
+def build_direct_cash_flow_candidate(
201
+ workbook_bytes: bytes, *, company_code: str, fiscal_year: int,
202
+ currency: str, unit: str,
203
+ cash_accounts: Sequence[CashAccountPolicy],
204
+ counterpart_policies: Sequence[CashCounterpartPolicy],
205
+ transactions: Sequence[CashFlowEntry],
206
+) -> DirectCashFlowCandidate:
207
+ """Build a direct-method analyst preview using paired cash journal entries.
208
+
209
+ Every row represents exactly one cash posting paired with its opposite
210
+ counterpart posting. If a voucher has multiple counterpart lines, provide
211
+ one separately identified pair per line. Cash-to-cash transfers are
212
+ recognized only when both cash accounts are explicitly registered and are
213
+ excluded from operating/investing/financing totals.
214
+ """
215
+ if not isinstance(company_code, str) or not company_code or company_code != company_code.strip():
216
+ raise CoverageError("CASH_FLOW_COMPANY_SCOPE_INVALID")
217
+ if type(fiscal_year) is not int or fiscal_year <= 0:
218
+ raise CoverageError("CASH_FLOW_YEAR_SCOPE_INVALID")
219
+ currency = _text(currency, "CURRENCY", max_length=16)
220
+ unit = _text(unit, "UNIT", max_length=32)
221
+ cash_policy, counterpart_policy, policy_hash = _policies(
222
+ cash_accounts, counterpart_policies,
223
+ )
224
+ if (not isinstance(transactions, (list, tuple))
225
+ or len(transactions) > MAX_CASH_TRANSACTIONS):
226
+ raise CoverageError("INVALID_CASH_FLOW_TRANSACTIONS")
227
+ if (not isinstance(workbook_bytes, bytes)
228
+ or not 0 < len(workbook_bytes) <= MAX_INPUT_BYTES):
229
+ raise CoverageError("CASH_FLOW_WORKBOOK_SIZE_INVALID")
230
+ _guard_archive(workbook_bytes)
231
+ try:
232
+ preflight = preflight_pilot_workbook(workbook_bytes)
233
+ except Exception as exc:
234
+ raise CoverageError("CASH_FLOW_WORKBOOK_INVALID") from exc
235
+ if not preflight.valid:
236
+ raise CoverageError("CASH_FLOW_WORKBOOK_INVALID")
237
+ try:
238
+ book = load_workbook(
239
+ BytesIO(workbook_bytes), read_only=False,
240
+ data_only=False, keep_links=False,
241
+ )
242
+ except Exception as exc:
243
+ raise CoverageError("CASH_FLOW_WORKBOOK_INVALID") from exc
244
+
245
+ try:
246
+ for sheet in book.worksheets:
247
+ _assert_visible(sheet)
248
+ for name, headers in SHEET_HEADERS.items():
249
+ if name not in book or tuple(cell.value for cell in book[name][1]) != headers:
250
+ raise CoverageError("CASH_FLOW_WORKBOOK_INVALID")
251
+
252
+ scope_company = company_code.strip()
253
+ companies = []
254
+ for values in book["Company"].iter_rows(min_row=2, values_only=True):
255
+ row = dict(zip(SHEET_HEADERS["Company"], values))
256
+ if (isinstance(row.get("company_code"), str)
257
+ and row["company_code"].strip() == scope_company
258
+ and type(row.get("fiscal_year")) is int
259
+ and row["fiscal_year"] == fiscal_year):
260
+ companies.append(row)
261
+ if len(companies) != 1:
262
+ raise CoverageError("CASH_FLOW_COMPANY_NOT_FOUND")
263
+ company = companies[0]
264
+ if company.get("currency") != currency or company.get("unit") != unit:
265
+ raise CoverageError("CASH_FLOW_CURRENCY_UNIT_MISMATCH")
266
+
267
+ source_accounts: dict[str, tuple[int, dict[str, Any]]] = {}
268
+ for row_number, values in enumerate(
269
+ book["Accounts"].iter_rows(min_row=2, values_only=True), 2,
270
+ ):
271
+ row = dict(zip(SHEET_HEADERS["Accounts"], values))
272
+ if not any(value is not None and str(value).strip() for value in row.values()):
273
+ continue
274
+ if (isinstance(row.get("company_code"), str)
275
+ and row["company_code"].strip() == scope_company
276
+ and type(row.get("fiscal_year")) is int
277
+ and row["fiscal_year"] == fiscal_year):
278
+ code = row.get("account_full_code")
279
+ if not isinstance(code, str) or not code.strip():
280
+ raise CoverageError("CASH_FLOW_ACCOUNT_CODE_INVALID")
281
+ code = code.strip()
282
+ if code in source_accounts:
283
+ raise CoverageError("CASH_FLOW_DUPLICATE_SOURCE_ACCOUNT")
284
+ source_accounts[code] = (row_number, row)
285
+
286
+ if set(cash_policy) - set(source_accounts):
287
+ raise CoverageError("CASH_ACCOUNT_NOT_FOUND_IN_SOURCE")
288
+
289
+ source_balances: dict[str, tuple[Decimal, Decimal, Decimal, Decimal, int, str]] = {}
290
+ for code, policy in cash_policy.items():
291
+ row_number, row = source_accounts[code]
292
+ opening, debit, credit, closing = (
293
+ _money(str(row[field]))
294
+ for field in ("opening", "debit", "credit", "closing")
295
+ )
296
+ if debit < 0 or credit < 0:
297
+ raise CoverageError("CASH_ACCOUNT_NEGATIVE_TURNOVER")
298
+ row_difference = _sum_exact([opening, debit, -credit, -closing])
299
+ if row_difference != 0:
300
+ raise CoverageError("CASH_ACCOUNT_ROLLFORWARD_INVALID")
301
+ if type(row.get("source_row")) is not int or row["source_row"] <= 0:
302
+ raise CoverageError("CASH_ACCOUNT_SOURCE_ROW_INVALID")
303
+ source_balances[code] = (
304
+ opening, debit, credit, closing, row["source_row"],
305
+ str(row["account_name"]),
306
+ )
307
+
308
+ line_ids: set[str] = set()
309
+ used_counterparts: set[str] = set()
310
+ transaction_turnovers: dict[str, tuple[list[Decimal], list[Decimal]]] = {
311
+ code: ([], []) for code in cash_policy
312
+ }
313
+ activity_totals: dict[str, dict[str, list[Decimal]]] = {
314
+ activity: {"inflows": [], "outflows": []}
315
+ for activity in sorted(ACTIVITIES)
316
+ }
317
+ transfer_inflows: list[Decimal] = []
318
+ transfer_outflows: list[Decimal] = []
319
+ output_lines: list[CashFlowLine] = []
320
+ canonical_transactions: list[dict[str, Any]] = []
321
+ findings: list[str] = []
322
+
323
+ for entry in transactions:
324
+ if not isinstance(entry, CashFlowEntry):
325
+ raise CoverageError("INVALID_CASH_FLOW_TRANSACTION")
326
+ company_value = _text(entry.company_code, "TRANSACTION_COMPANY")
327
+ if company_value != scope_company or type(entry.fiscal_year) is not int or entry.fiscal_year != fiscal_year:
328
+ raise CoverageError("CASH_FLOW_TRANSACTION_SCOPE_MISMATCH")
329
+ line_id = _text(entry.line_id, "LINE_ID")
330
+ transaction_id = _text(entry.transaction_id, "TRANSACTION_ID")
331
+ posting_date = _date(entry.posting_date, fiscal_year)
332
+ cash_code = _text(entry.cash_account_code, "CASH_ACCOUNT_CODE")
333
+ counterpart_code = _text(entry.counterpart_account_code, "COUNTERPART_ACCOUNT_CODE")
334
+ evidence = _text(entry.evidence_ref, "TRANSACTION_EVIDENCE")
335
+ if line_id in line_ids:
336
+ raise CoverageError("DUPLICATE_CASH_FLOW_LINE_ID")
337
+ line_ids.add(line_id)
338
+ if cash_code not in cash_policy:
339
+ raise CoverageError("UNREGISTERED_CASH_ACCOUNT_IN_TRANSACTION")
340
+ if counterpart_code == cash_code or counterpart_code not in source_accounts:
341
+ raise CoverageError("INVALID_CASH_COUNTERPART_ACCOUNT")
342
+
343
+ cash_debit, cash_credit, counterpart_debit, counterpart_credit = (
344
+ _money(value) for value in (
345
+ entry.cash_debit, entry.cash_credit,
346
+ entry.counterpart_debit, entry.counterpart_credit,
347
+ )
348
+ )
349
+ if min(cash_debit, cash_credit, counterpart_debit, counterpart_credit) < 0:
350
+ raise CoverageError("NEGATIVE_CASH_FLOW_POSTING")
351
+ debit_side = cash_debit > 0 and cash_credit == 0
352
+ credit_side = cash_credit > 0 and cash_debit == 0
353
+ if not (debit_side or credit_side):
354
+ raise CoverageError("CASH_FLOW_ENTRY_MUST_HAVE_ONE_CASH_SIDE")
355
+ if debit_side:
356
+ if counterpart_credit != cash_debit or counterpart_debit != 0:
357
+ raise CoverageError("CASH_FLOW_COUNTERPART_NOT_BALANCED")
358
+ elif counterpart_debit != cash_credit or counterpart_credit != 0:
359
+ raise CoverageError("CASH_FLOW_COUNTERPART_NOT_BALANCED")
360
+
361
+ transaction_turnovers[cash_code][0].append(cash_debit)
362
+ transaction_turnovers[cash_code][1].append(cash_credit)
363
+ if counterpart_code in cash_policy:
364
+ transaction_turnovers[counterpart_code][0].append(counterpart_debit)
365
+ transaction_turnovers[counterpart_code][1].append(counterpart_credit)
366
+ activity = "CASH_TRANSFER"
367
+ classification_evidence = cash_policy[counterpart_code].evidence_ref
368
+ if cash_debit:
369
+ transfer_inflows.append(cash_debit)
370
+ else:
371
+ transfer_outflows.append(cash_credit)
372
+ else:
373
+ policy = counterpart_policy.get(counterpart_code)
374
+ if policy is None:
375
+ activity = "UNCLASSIFIED"
376
+ classification_evidence = None
377
+ findings.append("MISSING_COUNTERPART_ACTIVITY_POLICY")
378
+ else:
379
+ used_counterparts.add(counterpart_code)
380
+ activity = policy.activity
381
+ classification_evidence = policy.evidence_ref
382
+ if cash_debit:
383
+ activity_totals[activity]["inflows"].append(cash_debit)
384
+ else:
385
+ activity_totals[activity]["outflows"].append(cash_credit)
386
+
387
+ output_lines.append(CashFlowLine(
388
+ line_id=line_id, transaction_id=transaction_id,
389
+ posting_date=posting_date, cash_account_code=cash_code,
390
+ counterpart_account_code=counterpart_code, activity=activity,
391
+ cash_inflow=str(cash_debit), cash_outflow=str(cash_credit),
392
+ source_evidence_ref=evidence,
393
+ classification_evidence_ref=classification_evidence,
394
+ ))
395
+ canonical_transactions.append(asdict(entry))
396
+
397
+ if set(counterpart_policy) - used_counterparts:
398
+ findings.append("ORPHAN_COUNTERPART_ACTIVITY_POLICY")
399
+
400
+ reconciliations: list[CashAccountReconciliation] = []
401
+ opening_values: list[Decimal] = []
402
+ closing_values: list[Decimal] = []
403
+ for code in sorted(cash_policy):
404
+ opening, source_debit, source_credit, closing, source_row, name = source_balances[code]
405
+ txn_debit = _sum_exact(transaction_turnovers[code][0])
406
+ txn_credit = _sum_exact(transaction_turnovers[code][1])
407
+ debit_diff = _sum_exact([txn_debit, -source_debit])
408
+ credit_diff = _sum_exact([txn_credit, -source_credit])
409
+ rollforward = _sum_exact([opening, source_debit, -source_credit, -closing])
410
+ if debit_diff != 0:
411
+ findings.append("CASH_ACCOUNT_DEBIT_TURNOVER_MISMATCH")
412
+ if credit_diff != 0:
413
+ findings.append("CASH_ACCOUNT_CREDIT_TURNOVER_MISMATCH")
414
+ if rollforward != 0:
415
+ findings.append("CASH_ACCOUNT_ROLLFORWARD_MISMATCH")
416
+ reconciliations.append(CashAccountReconciliation(
417
+ account_code=code, account_name=name, source_row=source_row,
418
+ opening_balance=str(opening),
419
+ source_debit_turnover=str(source_debit),
420
+ source_credit_turnover=str(source_credit),
421
+ closing_balance=str(closing),
422
+ transaction_debit_turnover=str(txn_debit),
423
+ transaction_credit_turnover=str(txn_credit),
424
+ debit_difference=str(debit_diff), credit_difference=str(credit_diff),
425
+ rollforward_difference=str(rollforward),
426
+ policy_evidence_ref=cash_policy[code].evidence_ref,
427
+ ))
428
+ opening_values.append(opening)
429
+ closing_values.append(closing)
430
+
431
+ totals = {
432
+ activity: {
433
+ "inflows": _sum_exact(activity_totals[activity]["inflows"]),
434
+ "outflows": _sum_exact(activity_totals[activity]["outflows"]),
435
+ }
436
+ for activity in sorted(ACTIVITIES)
437
+ }
438
+ net_by_activity = {
439
+ activity: _sum_exact([
440
+ totals[activity]["inflows"], -totals[activity]["outflows"],
441
+ ])
442
+ for activity in sorted(ACTIVITIES)
443
+ }
444
+ opening_total = _sum_exact(opening_values)
445
+ closing_total = _sum_exact(closing_values)
446
+ net_change = _sum_exact(list(net_by_activity.values()))
447
+ rollforward_difference = _sum_exact([
448
+ opening_total, net_change, -closing_total,
449
+ ])
450
+ if rollforward_difference != 0:
451
+ findings.append("CASH_FLOW_CASH_BALANCE_ROLLFORWARD_MISMATCH")
452
+
453
+ transaction_hash = sha256(json.dumps(
454
+ sorted(canonical_transactions, key=lambda row: row["line_id"]),
455
+ ensure_ascii=True, sort_keys=True, separators=(",", ":"),
456
+ ).encode("utf-8")).hexdigest()
457
+ return DirectCashFlowCandidate(
458
+ company_code=scope_company, fiscal_year=fiscal_year,
459
+ currency=currency, unit=unit,
460
+ source_sha256=sha256(workbook_bytes).hexdigest(),
461
+ transaction_ledger_sha256=transaction_hash,
462
+ classification_policies_sha256=policy_hash,
463
+ cash_account_count=len(cash_policy),
464
+ transaction_count=len(transactions),
465
+ opening_cash_and_equivalents=str(opening_total),
466
+ operating_inflows=str(totals["OPERATING"]["inflows"]),
467
+ operating_outflows=str(totals["OPERATING"]["outflows"]),
468
+ operating_net_cash_flow=str(net_by_activity["OPERATING"]),
469
+ investing_inflows=str(totals["INVESTING"]["inflows"]),
470
+ investing_outflows=str(totals["INVESTING"]["outflows"]),
471
+ investing_net_cash_flow=str(net_by_activity["INVESTING"]),
472
+ financing_inflows=str(totals["FINANCING"]["inflows"]),
473
+ financing_outflows=str(totals["FINANCING"]["outflows"]),
474
+ financing_net_cash_flow=str(net_by_activity["FINANCING"]),
475
+ internal_transfer_inflows=str(_sum_exact(transfer_inflows)),
476
+ internal_transfer_outflows=str(_sum_exact(transfer_outflows)),
477
+ net_change_in_cash=str(net_change),
478
+ closing_cash_and_equivalents=str(closing_total),
479
+ rollforward_difference=str(rollforward_difference),
480
+ account_reconciliations=tuple(reconciliations),
481
+ cash_flow_lines=tuple(sorted(
482
+ output_lines, key=lambda line: (line.posting_date, line.line_id),
483
+ )),
484
+ findings=tuple(sorted(set(findings))),
485
+ eligible_for_analyst_review=not findings and bool(cash_policy),
486
+ )
487
+ finally:
488
+ book.close()