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

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

Synced Dec 3, 20:45 UTC

codex/aram-mapping-source-parser-20261101
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 485 lines 20.9 KB
Raw
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_CASH_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_CASH_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 not isinstance(policy.activity, str) or 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 company_code = _text(company_code, "COMPANY_SCOPE", max_length=64)
216 if type(fiscal_year) is not int or fiscal_year <= 0:
217 raise CoverageError("CASH_FLOW_YEAR_SCOPE_INVALID")
218 currency = _text(currency, "CURRENCY", max_length=16)
219 unit = _text(unit, "UNIT", max_length=32)
220 cash_policy, counterpart_policy, policy_hash = _policies(
221 cash_accounts, counterpart_policies,
222 )
223 if (not isinstance(transactions, (list, tuple))
224 or len(transactions) > MAX_CASH_TRANSACTIONS):
225 raise CoverageError("INVALID_CASH_FLOW_TRANSACTIONS")
226 if (not isinstance(workbook_bytes, bytes)
227 or not 0 < len(workbook_bytes) <= MAX_INPUT_BYTES):
228 raise CoverageError("CASH_FLOW_WORKBOOK_SIZE_INVALID")
229 _guard_archive(workbook_bytes)
230 try:
231 preflight = preflight_pilot_workbook(workbook_bytes)
232 except Exception as exc:
233 raise CoverageError("CASH_FLOW_WORKBOOK_INVALID") from exc
234 if not preflight.valid:
235 raise CoverageError("CASH_FLOW_WORKBOOK_INVALID")
236 try:
237 book = load_workbook(
238 BytesIO(workbook_bytes), read_only=False,
239 data_only=False, keep_links=False,
240 )
241 except Exception as exc:
242 raise CoverageError("CASH_FLOW_WORKBOOK_INVALID") from exc
243
244 try:
245 for sheet in book.worksheets:
246 _assert_visible(sheet)
247 for name, headers in SHEET_HEADERS.items():
248 if name not in book or tuple(cell.value for cell in book[name][1]) != headers:
249 raise CoverageError("CASH_FLOW_WORKBOOK_INVALID")
250
251 scope_company = company_code.strip()
252 companies = []
253 for values in book["Company"].iter_rows(min_row=2, values_only=True):
254 row = dict(zip(SHEET_HEADERS["Company"], values))
255 if (isinstance(row.get("company_code"), str)
256 and row["company_code"].strip() == scope_company
257 and type(row.get("fiscal_year")) is int
258 and row["fiscal_year"] == fiscal_year):
259 companies.append(row)
260 if len(companies) != 1:
261 raise CoverageError("CASH_FLOW_COMPANY_NOT_FOUND")
262 company = companies[0]
263 if company.get("currency") != currency or company.get("unit") != unit:
264 raise CoverageError("CASH_FLOW_CURRENCY_UNIT_MISMATCH")
265
266 source_accounts: dict[str, tuple[int, dict[str, Any]]] = {}
267 for row_number, values in enumerate(
268 book["Accounts"].iter_rows(min_row=2, values_only=True), 2,
269 ):
270 row = dict(zip(SHEET_HEADERS["Accounts"], values))
271 if not any(value is not None and str(value).strip() for value in row.values()):
272 continue
273 if (isinstance(row.get("company_code"), str)
274 and row["company_code"].strip() == scope_company
275 and type(row.get("fiscal_year")) is int
276 and row["fiscal_year"] == fiscal_year):
277 code = row.get("account_full_code")
278 if not isinstance(code, str) or not code.strip():
279 raise CoverageError("CASH_FLOW_ACCOUNT_CODE_INVALID")
280 code = code.strip()
281 if code in source_accounts:
282 raise CoverageError("CASH_FLOW_DUPLICATE_SOURCE_ACCOUNT")
283 source_accounts[code] = (row_number, row)
284
285 if set(cash_policy) - set(source_accounts):
286 raise CoverageError("CASH_ACCOUNT_NOT_FOUND_IN_SOURCE")
287
288 source_balances: dict[str, tuple[Decimal, Decimal, Decimal, Decimal, int, str]] = {}
289 for code, policy in cash_policy.items():
290 row_number, row = source_accounts[code]
291 opening, debit, credit, closing = (
292 _money(str(row[field]))
293 for field in ("opening", "debit", "credit", "closing")
294 )
295 if debit < 0 or credit < 0:
296 raise CoverageError("CASH_ACCOUNT_NEGATIVE_TURNOVER")
297 row_difference = _sum_exact([opening, debit, -credit, -closing])
298 if row_difference != 0:
299 raise CoverageError("CASH_ACCOUNT_ROLLFORWARD_INVALID")
300 if type(row.get("source_row")) is not int or row["source_row"] <= 0:
301 raise CoverageError("CASH_ACCOUNT_SOURCE_ROW_INVALID")
302 source_balances[code] = (
303 opening, debit, credit, closing, row["source_row"],
304 str(row["account_name"]),
305 )
306
307 line_ids: set[str] = set()
308 used_counterparts: set[str] = set()
309 transaction_turnovers: dict[str, tuple[list[Decimal], list[Decimal]]] = {
310 code: ([], []) for code in cash_policy
311 }
312 activity_totals: dict[str, dict[str, list[Decimal]]] = {
313 activity: {"inflows": [], "outflows": []}
314 for activity in sorted(ACTIVITIES)
315 }
316 transfer_inflows: list[Decimal] = []
317 transfer_outflows: list[Decimal] = []
318 output_lines: list[CashFlowLine] = []
319 canonical_transactions: list[dict[str, Any]] = []
320 findings: list[str] = []
321
322 for entry in transactions:
323 if not isinstance(entry, CashFlowEntry):
324 raise CoverageError("INVALID_CASH_FLOW_TRANSACTION")
325 company_value = _text(entry.company_code, "TRANSACTION_COMPANY")
326 if company_value != scope_company or type(entry.fiscal_year) is not int or entry.fiscal_year != fiscal_year:
327 raise CoverageError("CASH_FLOW_TRANSACTION_SCOPE_MISMATCH")
328 line_id = _text(entry.line_id, "LINE_ID")
329 transaction_id = _text(entry.transaction_id, "TRANSACTION_ID")
330 posting_date = _date(entry.posting_date, fiscal_year)
331 cash_code = _text(entry.cash_account_code, "CASH_ACCOUNT_CODE")
332 counterpart_code = _text(entry.counterpart_account_code, "COUNTERPART_ACCOUNT_CODE")
333 evidence = _text(entry.evidence_ref, "TRANSACTION_EVIDENCE")
334 if line_id in line_ids:
335 raise CoverageError("DUPLICATE_CASH_FLOW_LINE_ID")
336 line_ids.add(line_id)
337 if cash_code not in cash_policy:
338 raise CoverageError("UNREGISTERED_CASH_ACCOUNT_IN_TRANSACTION")
339 if counterpart_code == cash_code or counterpart_code not in source_accounts:
340 raise CoverageError("INVALID_CASH_COUNTERPART_ACCOUNT")
341
342 cash_debit, cash_credit, counterpart_debit, counterpart_credit = (
343 _money(value) for value in (
344 entry.cash_debit, entry.cash_credit,
345 entry.counterpart_debit, entry.counterpart_credit,
346 )
347 )
348 if min(cash_debit, cash_credit, counterpart_debit, counterpart_credit) < 0:
349 raise CoverageError("NEGATIVE_CASH_FLOW_POSTING")
350 debit_side = cash_debit > 0 and cash_credit == 0
351 credit_side = cash_credit > 0 and cash_debit == 0
352 if not (debit_side or credit_side):
353 raise CoverageError("CASH_FLOW_ENTRY_MUST_HAVE_ONE_CASH_SIDE")
354 if debit_side:
355 if counterpart_credit != cash_debit or counterpart_debit != 0:
356 raise CoverageError("CASH_FLOW_COUNTERPART_NOT_BALANCED")
357 elif counterpart_debit != cash_credit or counterpart_credit != 0:
358 raise CoverageError("CASH_FLOW_COUNTERPART_NOT_BALANCED")
359
360 transaction_turnovers[cash_code][0].append(cash_debit)
361 transaction_turnovers[cash_code][1].append(cash_credit)
362 if counterpart_code in cash_policy:
363 transaction_turnovers[counterpart_code][0].append(counterpart_debit)
364 transaction_turnovers[counterpart_code][1].append(counterpart_credit)
365 activity = "CASH_TRANSFER"
366 classification_evidence = cash_policy[counterpart_code].evidence_ref
367 transfer_inflows.extend([cash_debit, counterpart_debit])
368 transfer_outflows.extend([cash_credit, counterpart_credit])
369 else:
370 policy = counterpart_policy.get(counterpart_code)
371 if policy is None:
372 activity = "UNCLASSIFIED"
373 classification_evidence = None
374 findings.append("MISSING_COUNTERPART_ACTIVITY_POLICY")
375 else:
376 used_counterparts.add(counterpart_code)
377 activity = policy.activity
378 classification_evidence = policy.evidence_ref
379 if cash_debit:
380 activity_totals[activity]["inflows"].append(cash_debit)
381 else:
382 activity_totals[activity]["outflows"].append(cash_credit)
383
384 output_lines.append(CashFlowLine(
385 line_id=line_id, transaction_id=transaction_id,
386 posting_date=posting_date, cash_account_code=cash_code,
387 counterpart_account_code=counterpart_code, activity=activity,
388 cash_inflow=str(cash_debit), cash_outflow=str(cash_credit),
389 source_evidence_ref=evidence,
390 classification_evidence_ref=classification_evidence,
391 ))
392 canonical_transactions.append(asdict(entry))
393
394 if set(counterpart_policy) - used_counterparts:
395 findings.append("ORPHAN_COUNTERPART_ACTIVITY_POLICY")
396
397 reconciliations: list[CashAccountReconciliation] = []
398 opening_values: list[Decimal] = []
399 closing_values: list[Decimal] = []
400 for code in sorted(cash_policy):
401 opening, source_debit, source_credit, closing, source_row, name = source_balances[code]
402 txn_debit = _sum_exact(transaction_turnovers[code][0])
403 txn_credit = _sum_exact(transaction_turnovers[code][1])
404 debit_diff = _sum_exact([txn_debit, -source_debit])
405 credit_diff = _sum_exact([txn_credit, -source_credit])
406 rollforward = _sum_exact([opening, source_debit, -source_credit, -closing])
407 if debit_diff != 0:
408 findings.append("CASH_ACCOUNT_DEBIT_TURNOVER_MISMATCH")
409 if credit_diff != 0:
410 findings.append("CASH_ACCOUNT_CREDIT_TURNOVER_MISMATCH")
411 if rollforward != 0:
412 findings.append("CASH_ACCOUNT_ROLLFORWARD_MISMATCH")
413 reconciliations.append(CashAccountReconciliation(
414 account_code=code, account_name=name, source_row=source_row,
415 opening_balance=str(opening),
416 source_debit_turnover=str(source_debit),
417 source_credit_turnover=str(source_credit),
418 closing_balance=str(closing),
419 transaction_debit_turnover=str(txn_debit),
420 transaction_credit_turnover=str(txn_credit),
421 debit_difference=str(debit_diff), credit_difference=str(credit_diff),
422 rollforward_difference=str(rollforward),
423 policy_evidence_ref=cash_policy[code].evidence_ref,
424 ))
425 opening_values.append(opening)
426 closing_values.append(closing)
427
428 totals = {
429 activity: {
430 "inflows": _sum_exact(activity_totals[activity]["inflows"]),
431 "outflows": _sum_exact(activity_totals[activity]["outflows"]),
432 }
433 for activity in sorted(ACTIVITIES)
434 }
435 net_by_activity = {
436 activity: _sum_exact([
437 totals[activity]["inflows"], -totals[activity]["outflows"],
438 ])
439 for activity in sorted(ACTIVITIES)
440 }
441 opening_total = _sum_exact(opening_values)
442 closing_total = _sum_exact(closing_values)
443 net_change = _sum_exact(list(net_by_activity.values()))
444 rollforward_difference = _sum_exact([
445 opening_total, net_change, -closing_total,
446 ])
447 if rollforward_difference != 0:
448 findings.append("CASH_FLOW_CASH_BALANCE_ROLLFORWARD_MISMATCH")
449
450 transaction_hash = sha256(json.dumps(
451 sorted(canonical_transactions, key=lambda row: row["line_id"]),
452 ensure_ascii=True, sort_keys=True, separators=(",", ":"),
453 ).encode("utf-8")).hexdigest()
454 return DirectCashFlowCandidate(
455 company_code=scope_company, fiscal_year=fiscal_year,
456 currency=currency, unit=unit,
457 source_sha256=sha256(workbook_bytes).hexdigest(),
458 transaction_ledger_sha256=transaction_hash,
459 classification_policies_sha256=policy_hash,
460 cash_account_count=len(cash_policy),
461 transaction_count=len(transactions),
462 opening_cash_and_equivalents=str(opening_total),
463 operating_inflows=str(totals["OPERATING"]["inflows"]),
464 operating_outflows=str(totals["OPERATING"]["outflows"]),
465 operating_net_cash_flow=str(net_by_activity["OPERATING"]),
466 investing_inflows=str(totals["INVESTING"]["inflows"]),
467 investing_outflows=str(totals["INVESTING"]["outflows"]),
468 investing_net_cash_flow=str(net_by_activity["INVESTING"]),
469 financing_inflows=str(totals["FINANCING"]["inflows"]),
470 financing_outflows=str(totals["FINANCING"]["outflows"]),
471 financing_net_cash_flow=str(net_by_activity["FINANCING"]),
472 internal_transfer_inflows=str(_sum_exact(transfer_inflows)),
473 internal_transfer_outflows=str(_sum_exact(transfer_outflows)),
474 net_change_in_cash=str(net_change),
475 closing_cash_and_equivalents=str(closing_total),
476 rollforward_difference=str(rollforward_difference),
477 account_reconciliations=tuple(reconciliations),
478 cash_flow_lines=tuple(sorted(
479 output_lines, key=lambda line: (line.posting_date, line.line_id),
480 )),
481 findings=tuple(sorted(set(findings))),
482 eligible_for_analyst_review=not findings and bool(cash_policy),
483 )
484 finally:
485 book.close()