Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_banking.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_banking.py · 35.4 KB · 820 lines
1"""Bank-statement import primitives: parsing, hashing, and the self-checks.
2
3Pure helpers over packages/app-banking's collections, same posture as
4object_stock.py (derived stock levels) and object_finance.py (journal
5folds): a plain importable library, not a registered object.
6
7The design point (plan/bank-import-reconciliation-spec.md): **import is not
8ETL, it is evidence handling.** A bank statement is the only record in the
9system authored by an independent third party -- that independence IS the
10anti-fraud control. So imported lines are append-only, keep their original
11text verbatim in `raw`, and are never hand-edited; parsed fields are a VIEW
12of raw, never a replacement.
13
14"Are the imports good?" has a real answer because a statement carries its
15own checksum. Three gates live here:
16
17- **tie_out**: opening + sum(lines) == closing. A truncated or tampered
18 file fails arithmetic.
19- **continuity**: this statement's opening equals the account's previous
20 closing. Gaps and edited files surface as a mismatch.
21- **dedup**: external_id (OFX FITID) when the format has one, else
22 line_hash over (date, amount, description, ordinal-within-day) so genuine
23 same-day twins still both land.
24
25CSV exports often lack balances and always lack transaction ids, so a
26profile records what the format actually supports and an import records
27which checks actually RAN. Honest weaker assurance beats pretended strong
28assurance -- a reconciliation that silently skipped its checks is worse
29than none.
30"""
31
32from __future__ import annotations
33
34import csv
35import hashlib
36import io
37import json
38from datetime import datetime
39from decimal import Decimal, InvalidOperation
40from pathlib import Path
41from typing import Any, Iterable
42
43import object_collections
44import object_finance
45import object_records
46from object_versions import DEFAULT_DATA_DIR
47
48IMPORTS_COLLECTION = "bank_statement_imports"
49LINES_COLLECTION = "bank_lines"
50
51STATUS_ACCEPTED = "accepted"
52STATUS_FLAGGED = "flagged"
53
54
55class ImportError_(Exception):
56 """Unusable import input (bad profile, unparseable content)."""
57
58
59def is_present(value: Any) -> bool:
60 """True when a numeric field was actually supplied.
61
62 Deliberately not `bool(value)`: 0 is a real balance (a new account
63 opens at zero) and must not read as "not provided" -- that distinction
64 decides whether a self-check runs at all.
65 """
66 return value is not None and str(value).strip() != ""
67
68
69def file_hash(content: str) -> str:
70 """Stable hash of the statement file itself -- re-importing the same
71 file is a no-op, the same provenance posture generated_from gives
72 composed journals."""
73 return hashlib.sha256(content.encode("utf-8", "replace")).hexdigest()
74
75
76def line_hash(posted_on: str, amount_cents: int, description: str, ordinal: int = 0) -> str:
77 """Identity of a statement line when the bank gives us no id.
78
79 The ordinal distinguishes genuine same-day twins (two identical $4.50
80 coffees) from a re-imported duplicate: within one statement the second
81 twin gets ordinal 1, so both land; across statements the same twin
82 hashes the same way and is rejected.
83 """
84 parts = f"{posted_on}|{int(amount_cents)}|{' '.join(str(description or '').split())}|{ordinal}"
85 return hashlib.sha256(parts.encode("utf-8", "replace")).hexdigest()[:32]
86
87
88def parse_cents(value: Any, *, decimal_sep: str = ".") -> int:
89 """Parse a money string from a bank export into integer cents.
90
91 Handles thousands separators, currency symbols, parenthesised negatives
92 ("(45.00)" = -4500, the accounting convention many exports use), and
93 European "1.234,56" when the profile says the decimal separator is a
94 comma. Decimal throughout -- never a float (00-doctrine-and-contract).
95 """
96 text = str(value or "").strip()
97 if not text:
98 return 0
99 negative = text.startswith("(") and text.endswith(")")
100 if negative:
101 text = text[1:-1].strip()
102 cleaned = []
103 for ch in text:
104 if ch.isdigit() or ch == "-":
105 cleaned.append(ch)
106 elif ch == decimal_sep:
107 cleaned.append(".")
108 # every other character (currency symbol, thousands separator,
109 # stray space) is noise between the digits
110 text = "".join(cleaned)
111 if not text or text in ("-", "."):
112 return 0
113 try:
114 amount = Decimal(text)
115 except InvalidOperation as exc:
116 raise ImportError_(f"Unparseable amount: {value!r}") from exc
117 if negative:
118 amount = -amount
119 return int((amount * 100).to_integral_value())
120
121
122def parse_date(value: Any, date_format: str = "") -> str:
123 """Normalise a statement date to ISO (YYYY-MM-DD).
124
125 A profile may pin the bank's format explicitly (%m/%d/%Y); without one
126 we try the common exports rather than guessing per row.
127 """
128 text = str(value or "").strip()
129 if not text:
130 return ""
131 formats = [date_format] if date_format else []
132 formats += ["%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%m/%d/%y", "%d.%m.%Y",
133 "%Y/%m/%d", "%d-%b-%Y", "%b %d, %Y"]
134 for fmt in formats:
135 if not fmt:
136 continue
137 try:
138 return datetime.strptime(text[:len(text)], fmt).date().isoformat()
139 except ValueError:
140 continue
141 raise ImportError_(f"Unparseable date: {value!r}")
142
143
144def _column(row: dict, header: list[str], key: Any) -> Any:
145 """Resolve a column_map entry: a header name or a 0-based index."""
146 if key is None or key == "":
147 return ""
148 if isinstance(key, int) or (isinstance(key, str) and key.isdigit()):
149 index = int(key)
150 return row.get(header[index], "") if 0 <= index < len(header) else ""
151 return row.get(key, "")
152
153
154def parse_statement_csv(content: str, column_map: dict) -> list[dict]:
155 """Parse a CSV export into canonical line dicts using a saved profile.
156
157 column_map keys: date, description, amount (one signed column) OR
158 debit/credit (a pair), external_id (optional), plus date_format,
159 decimal_sep, and sign ("normal" | "flip" for banks that export
160 withdrawals as positive numbers).
161
162 Returns [{posted_on, amount_cents, description, external_id, raw}] in
163 file order. Blank rows are skipped; a row whose date or amount cannot
164 be parsed raises -- a half-read statement is worse than a refused one.
165 """
166 if not isinstance(column_map, dict) or not column_map:
167 raise ImportError_("Profile has no column_map")
168 text = content.lstrip("")
169 reader = csv.DictReader(io.StringIO(text))
170 header = list(reader.fieldnames or [])
171 if not header:
172 raise ImportError_("CSV has no header row")
173
174 date_format = str(column_map.get("date_format") or "")
175 decimal_sep = str(column_map.get("decimal_sep") or ".")
176 flip = str(column_map.get("sign") or "normal").lower() == "flip"
177 has_pair = bool(column_map.get("debit") or column_map.get("credit"))
178
179 lines = []
180 for row in reader:
181 if not any(str(v or "").strip() for v in row.values()):
182 continue
183 raw = "\t".join(str(row.get(col, "") or "") for col in header)
184 if has_pair:
185 debit = parse_cents(_column(row, header, column_map.get("debit")), decimal_sep=decimal_sep)
186 credit = parse_cents(_column(row, header, column_map.get("credit")), decimal_sep=decimal_sep)
187 # Money out of the account is negative in the canonical shape.
188 amount_cents = credit - abs(debit) if credit else -abs(debit)
189 else:
190 amount_cents = parse_cents(
191 _column(row, header, column_map.get("amount")), decimal_sep=decimal_sep)
192 if flip:
193 amount_cents = -amount_cents
194 lines.append({
195 "posted_on": parse_date(_column(row, header, column_map.get("date")), date_format),
196 "amount_cents": amount_cents,
197 "description": " ".join(str(_column(row, header, column_map.get("description")) or "").split()),
198 "external_id": str(_column(row, header, column_map.get("external_id")) or "").strip(),
199 "raw": raw,
200 })
201 return lines
202
203
204def assign_line_hashes(lines: Iterable[dict]) -> list[dict]:
205 """Stamp line_hash on parsed lines, ordinal-disambiguating same-day
206 twins so two identical transactions on one statement both survive."""
207 seen: dict[tuple, int] = {}
208 out = []
209 for line in lines:
210 key = (line.get("posted_on"), int(line.get("amount_cents") or 0),
211 line.get("description"))
212 ordinal = seen.get(key, 0)
213 seen[key] = ordinal + 1
214 stamped = dict(line)
215 stamped["line_hash"] = line_hash(
216 line.get("posted_on", ""), int(line.get("amount_cents") or 0),
217 line.get("description", ""), ordinal)
218 out.append(stamped)
219 return out
220
221
222# --- reads that gates depend on -------------------------------------------------
223#
224# The four readers below answer "is it already here?" for a gate: the
225# duplicate-line gate, the file-level idempotency gate, the continuity
226# check. Each used to turn ANY failure to read into "nothing found", so with
227# the ledger unreadable the duplicate gate passed the duplicate and the same
228# deposit went on file twice. A gate that passes because it could not look is
229# not a gate.
230#
231# `strict=True` makes a failed read raise (whatever the read raised) so the
232# caller refuses. A collection that is simply NOT INSTALLED is still "no
233# rows" under strict: nothing can be on file in a collection that does not
234# exist, and that is a true answer rather than an unknown one.
235#
236# The default stays lenient for now, and that is a debt, not a judgement
237# that lenient is right. Each caller has to be moved to strict together
238# with what it does about the refusal. Moved (2026-11-28): both statement
239# importers -- every read before their import row refuses with a 409, and
240# the reads after it are recoverable because re-importing the file resumes
241# a half-written import (land_import, below); and hook_bank_lines, whose
242# duplicate gate answers 503 when it cannot read the lines on file.
243#
244# Each function makes its own object_records.read_collection_records call
245# rather than sharing a wrapper: tests/test_findings_money_gates.py injects
246# a read failure "for this caller only" by looking at the calling frame.
247
248
249def existing_line_keys(bank_account_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR,
250 strict: bool = False) -> tuple[set, set]:
251 """(external_ids, line_hashes) already stored for one bank account.
252
253 `strict`: raise when bank_lines cannot be read, instead of answering
254 "none on file" -- see the note above."""
255 external_ids, hashes = set(), set()
256 try:
257 rows = object_records.read_collection_records(LINES_COLLECTION, base_dir=base_dir)
258 except object_collections.CollectionNotFoundError:
259 return external_ids, hashes
260 except Exception:
261 if strict:
262 raise
263 return external_ids, hashes
264 for row in rows:
265 if row.get("bank_account_id") != bank_account_id:
266 continue
267 if row.get("external_id"):
268 external_ids.add(row["external_id"])
269 if row.get("line_hash"):
270 hashes.add(row["line_hash"])
271 return external_ids, hashes
272
273
274def is_duplicate_line(record: dict, *, base_dir: Path | str = DEFAULT_DATA_DIR,
275 strict: bool = False) -> bool:
276 """True when this line is already on file for its bank account.
277
278 `strict`: raise when bank_lines cannot be read, instead of answering
279 "not a duplicate"."""
280 external_ids, hashes = existing_line_keys(
281 str(record.get("bank_account_id") or ""), base_dir=base_dir, strict=strict)
282 if record.get("external_id") and record["external_id"] in external_ids:
283 return True
284 return bool(record.get("line_hash")) and record["line_hash"] in hashes
285
286
287def find_import_by_file_hash(bank_account_id: str, digest: str, *,
288 base_dir: Path | str = DEFAULT_DATA_DIR,
289 strict: bool = False) -> dict | None:
290 """The prior import of this exact file, if any (file-level idempotency).
291
292 `strict`: raise when bank_statement_imports cannot be read, instead of
293 answering "never imported"."""
294 try:
295 rows = object_records.read_collection_records(IMPORTS_COLLECTION, base_dir=base_dir)
296 except object_collections.CollectionNotFoundError:
297 return None
298 except Exception:
299 if strict:
300 raise
301 return None
302 for row in rows:
303 if row.get("bank_account_id") == bank_account_id and row.get("file_hash") == digest:
304 return row
305 return None
306
307
308def previous_import(bank_account_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR,
309 before: str = "", strict: bool = False) -> dict | None:
310 """The account's latest accepted-or-flagged import before `before`
311 (by period_end) -- the continuity check's comparison point.
312
313 `strict`: raise when bank_statement_imports cannot be read, instead of
314 answering "no prior statement"."""
315 try:
316 rows = object_records.read_collection_records(IMPORTS_COLLECTION, base_dir=base_dir)
317 except object_collections.CollectionNotFoundError:
318 return None
319 except Exception:
320 if strict:
321 raise
322 return None
323 candidates = [r for r in rows
324 if r.get("bank_account_id") == bank_account_id
325 and (r.get("period_end") or "")
326 and (not before or (r.get("period_end") or "") <= before)]
327 if not candidates:
328 return None
329 return max(candidates, key=lambda r: (r.get("period_end") or "", r.get("created_at") or ""))
330
331
332def run_gates(lines: list[dict], *, bank_account_id: str,
333 opening_balance_cents: Any, closing_balance_cents: Any,
334 period_start: str = "", base_dir: Path | str = DEFAULT_DATA_DIR,
335 strict: bool = False) -> dict:
336 """Run tie-out and continuity, returning the import's flags block.
337
338 Shape: {"checks": {...ran/passed...}, "status": accepted|flagged}. The
339 flags record which checks RAN, not just which passed -- a balance-less
340 CSV that "passed" nothing must not look as trustworthy as a tied-out
341 OFX file.
342
343 `strict`: raise when the prior import cannot be read. Without it an
344 unreadable bank_statement_imports is recorded on the import as
345 continuity "not run: no prior statement for this account" -- a reason
346 that is false, written into the evidence.
347 """
348 checks: dict[str, Any] = {}
349 total = sum(int(l.get("amount_cents") or 0) for l in lines)
350 checks["line_total_cents"] = total
351
352 # `or ""` would be wrong here: a zero opening balance is a real balance
353 # (a new account starts at zero), and treating it as "no balance given"
354 # would silently skip the tie-out check on exactly the statement whose
355 # arithmetic is easiest to verify.
356 has_balances = is_present(opening_balance_cents) and is_present(closing_balance_cents)
357 if has_balances:
358 opening = int(opening_balance_cents or 0)
359 closing = int(closing_balance_cents or 0)
360 expected = opening + total
361 checks["tie_out"] = {
362 "ran": True,
363 "passed": expected == closing,
364 "expected_closing_cents": expected,
365 "stated_closing_cents": closing,
366 "delta_cents": closing - expected,
367 }
368 prior = previous_import(bank_account_id, base_dir=base_dir, before=period_start,
369 strict=strict)
370 if prior is not None and str(prior.get("closing_balance_cents") or "").strip():
371 prior_closing = int(prior["closing_balance_cents"])
372 checks["continuity"] = {
373 "ran": True,
374 "passed": prior_closing == opening,
375 "previous_closing_cents": prior_closing,
376 "this_opening_cents": opening,
377 "gap_cents": opening - prior_closing,
378 "previous_import_id": prior.get("id", ""),
379 }
380 else:
381 checks["continuity"] = {"ran": False,
382 "reason": "no prior statement for this account"}
383 else:
384 checks["tie_out"] = {"ran": False,
385 "reason": "statement carried no opening/closing balance"}
386 checks["continuity"] = {"ran": False, "reason": "no balances to chain"}
387
388 failed = [name for name, c in checks.items()
389 if isinstance(c, dict) and c.get("ran") and not c.get("passed")]
390 return {
391 "checks": checks,
392 "failed": failed,
393 "status": STATUS_FLAGGED if failed else STATUS_ACCEPTED,
394 }
395
396
397def flags_json(gates: dict) -> str:
398 return json.dumps(gates.get("checks", {}), sort_keys=True)
399
400
401# --- landing an import ------------------------------------------------------
402#
403# The import row is what marks a file as imported, and bank_lines.import_id
404# is a relation to it, so the row has to be written before its lines. Until
405# 2026-11-28 that made a crash mid-import permanent: one line on file, the
406# file "already imported", and the missing lines could never load
407# (bug-reports/2026-11-28-06-14-38-CST-bank-import-partial-failure-
408# unrecoverable). Now a re-import of a file that already has an import row
409# RESUMES it: the same landing loop runs again under that row's id, the
410# lines that are on file are skipped by the ordinary line dedup, and only
411# the missing ones are written. Re-importing a complete file is still a
412# no-op (everything is a duplicate). The import row itself -- its gates,
413# its status, its balances -- is never rewritten: it was stated once.
414#
415# The import id is derived from (account, file hash) rather than random,
416# so two overlapping first imports of one file converge on one row: the
417# second create of that id is refused, and answered "already imported"
418# while the first finishes (a retry later resumes it if it did not).
419#
420# Every read is strict (see the note above), and the importers make each
421# one BEFORE the import row is written -- the line keys included, passed in
422# as `known` -- so an unreadable history is a refusal with nothing written.
423# An unreadable bank_lines read as "no lines on file" would put every line
424# on file twice.
425#
426# Two retries of the SAME interrupted import racing each other would both
427# write a missing line if the dedup were only this read. It is not:
428# bank_lines declares external_id and line_hash unique within
429# bank_account_id, so the second write is refused inside the write lock,
430# and a UniqueConstraintError from a line write is treated as "on file".
431
432def import_id_for(bank_account_id: str, digest: str) -> str:
433 """The deterministic id of the import of this file into this account."""
434 import uuid
435 return str(uuid.uuid5(uuid.NAMESPACE_URL,
436 f"dbbasic:bank_statement_imports:{bank_account_id}:{digest}"))
437
438
439def land_lines(import_id: str, bank_account_id: str, lines: list[dict], *,
440 account: dict, user_id: str, base_dir: Path | str = DEFAULT_DATA_DIR,
441 actor: str, known: tuple[set, set] | None = None) -> dict:
442 """Write the lines of an import that are not on file yet.
443
444 Idempotent: run it again and it writes only what is still missing.
445 `known` is existing_line_keys(..., strict=True), read by the caller
446 BEFORE anything is written so an unreadable bank_lines is refused with
447 nothing changed; when omitted it is read here (and a failure raises).
448 Returns {"imported", "duplicates"}. A failed write raises, and running
449 it again resumes."""
450 import object_ids
451
452 if known is None:
453 known = existing_line_keys(bank_account_id, base_dir=base_dir, strict=True)
454 known_ids, known_hashes = set(known[0]), set(known[1])
455 imported = duplicates = 0
456 for line in lines:
457 # The bank's own id (OFX FITID) first: it survives the bank
458 # re-wording a memo, which a content hash does not.
459 if (line.get("external_id") and line["external_id"] in known_ids) or \
460 line["line_hash"] in known_hashes:
461 duplicates += 1
462 continue
463 row = {
464 "id": object_ids.new_uuid4(),
465 "import_id": import_id,
466 "bank_account_id": bank_account_id,
467 "posted_on": line["posted_on"],
468 "amount_cents": str(line["amount_cents"]),
469 "description": line["description"],
470 "external_id": line["external_id"],
471 "line_hash": line["line_hash"],
472 "raw": line["raw"],
473 "match_status": "unmatched",
474 "owner_id": user_id,
475 }
476 if account.get("entity_id"):
477 row["entity_id"] = account["entity_id"]
478 try:
479 object_records.create_collection_record(LINES_COLLECTION, row,
480 base_dir=base_dir, actor=actor)
481 except object_records.UniqueConstraintError:
482 duplicates += 1 # landed by a concurrent writer
483 continue
484 if line.get("external_id"):
485 known_ids.add(line["external_id"])
486 known_hashes.add(line["line_hash"])
487 imported += 1
488 return {"imported": imported, "duplicates": duplicates}
489
490
491def land_import(import_row: dict, lines: list[dict], *, account: dict,
492 user_id: str, base_dir: Path | str = DEFAULT_DATA_DIR,
493 actor: str, known: tuple[set, set] | None = None) -> dict | None:
494 """Write a new import's row, then its lines (land_lines).
495
496 Returns land_lines' counts, or None when the row's id already exists:
497 another request is importing this same file right now."""
498 try:
499 object_records.create_collection_record(
500 IMPORTS_COLLECTION, import_row, base_dir=base_dir, actor=actor)
501 except (object_records.DuplicateRecordIdError,
502 object_records.UniqueConstraintError):
503 return None
504 return land_lines(import_row["id"], import_row["bank_account_id"], lines,
505 account=account, user_id=user_id, base_dir=base_dir,
506 actor=actor, known=known)
507
508
509# --- matching ---------------------------------------------------------------
510#
511# Matching is DERIVED and non-authoritative: the matcher proposes, a human
512# (or an explicitly configured auto-match tier) disposes. That split is the
513# control -- reconciliation performed invisibly by whoever moves the money
514# is the classic fraud hole, so the act of confirming is an ordinary
515# attributed update and shows up in the change log with a name on it.
516
517# Fields of a bank line that are EVIDENCE: what the bank said, verbatim.
518# An update may never touch them -- corrections come from re-importing a
519# corrected statement, not from editing the record to agree with the books.
520EVIDENCE_FIELDS = ("import_id", "bank_account_id", "posted_on", "amount_cents",
521 "description", "external_id", "line_hash", "raw")
522
523
524def _day_gap(left: str, right: str) -> int | None:
525 try:
526 a = datetime.strptime(str(left)[:10], "%Y-%m-%d").date()
527 b = datetime.strptime(str(right)[:10], "%Y-%m-%d").date()
528 except (ValueError, TypeError):
529 return None
530 return abs((a - b).days)
531
532
533def _reference_hit(description: str, reference: str) -> bool:
534 """Does the statement text carry this record's reference?
535
536 Banks mangle memos (case, padding, truncation), so compare
537 case-insensitively on collapsed alphanumerics. A reference shorter than
538 four characters is too weak to assert identity on -- "12" appears in
539 half of all descriptions.
540 """
541 ref = "".join(ch for ch in str(reference or "") if ch.isalnum()).upper()
542 if len(ref) < 4:
543 return False
544 haystack = "".join(ch for ch in str(description or "") if ch.isalnum()).upper()
545 return ref in haystack
546
547
548def candidate_matches(line: dict, candidates: Iterable[dict], *,
549 window_days: int = 5, max_combination: int = 3) -> list[dict]:
550 """Propose book-side records for one bank line, best first.
551
552 `candidates` are dicts of {ref, amount_cents, date, reference} where
553 amount_cents is already expressed in the LINE's sign convention (money
554 into the account positive) and `ref` is "collection/id".
555
556 Tiers, strongest to weakest:
557 1. the record's reference appears in the statement text AND the
558 amount agrees -- two independent signals, safe to auto-confirm
559 2. exact amount within the date window -- one signal; plausible but a
560 same-priced invoice from another customer looks identical
561 3. a same-window combination of 2..max_combination records summing to
562 the line -- the batched deposit case; always suggestion-only
563 """
564 amount = int(line.get("amount_cents") or 0)
565 posted_on = str(line.get("posted_on") or "")
566 description = str(line.get("description") or "")
567
568 near = []
569 for cand in candidates:
570 gap = _day_gap(posted_on, cand.get("date"))
571 if gap is None or gap > window_days:
572 continue
573 near.append((gap, cand))
574
575 proposals = []
576 for gap, cand in near:
577 same_amount = int(cand.get("amount_cents") or 0) == amount
578 if same_amount and _reference_hit(description, cand.get("reference")):
579 proposals.append({
580 "tier": 1, "refs": [cand["ref"]], "day_gap": gap,
581 "why": f"reference {cand.get('reference')} appears in the statement text "
582 f"and the amount matches exactly",
583 })
584 elif same_amount:
585 proposals.append({
586 "tier": 2, "refs": [cand["ref"]], "day_gap": gap,
587 "why": f"exact amount within {gap} day(s)",
588 })
589
590 if not any(p["tier"] == 1 for p in proposals) and max_combination >= 2:
591 proposals.extend(_combination_matches(amount, near, max_combination))
592
593 proposals.sort(key=lambda p: (p["tier"], p.get("day_gap", 99), len(p["refs"])))
594 return proposals
595
596
597def _combination_matches(amount: int, near: list, max_combination: int) -> list[dict]:
598 """Batched-deposit case: several book records banked as one line.
599
600 Bounded on purpose (few candidates, small k): an unbounded subset search
601 over a busy account would both hang and produce coincidences that are
602 worse than no suggestion at all.
603 """
604 from itertools import combinations
605
606 pool = [c for _, c in near][:12]
607 found = []
608 for size in range(2, min(max_combination, len(pool)) + 1):
609 for combo in combinations(pool, size):
610 if sum(int(c.get("amount_cents") or 0) for c in combo) != amount:
611 continue
612 found.append({
613 "tier": 3,
614 "refs": [c["ref"] for c in combo],
615 "day_gap": 0,
616 "why": f"{size} records sum to this line (batched deposit)",
617 })
618 if len(found) >= 3: # a handful of options, not a catalogue
619 return found
620 return found
621
622
623def evidence_changes(existing: dict, changes: dict) -> list[str]:
624 """Which evidence fields an update is trying to alter (should be none)."""
625 touched = []
626 for field in EVIDENCE_FIELDS:
627 if field not in changes:
628 continue
629 if str(changes.get(field) or "") != str(existing.get(field) or ""):
630 touched.append(field)
631 return touched
632
633
634# --- the reconciliation statement --------------------------------------------
635#
636# plan/bank-import-reconciliation-spec.md section 6: "bank closing balance
637# (last accepted import) vs. book cash balance (fin account), reconciled by:
638# matched total, outstanding timing items, unresolved tail." Nothing here
639# writes anything -- it is a fold over already-stored state, the same
640# posture as object_finance.trial_balance().
641
642ACCOUNTS_COLLECTION = "value_accounts"
643JOURNALS_COLLECTION = "fin_journals"
644JOURNAL_LINES_COLLECTION = "fin_journal_lines"
645
646_STATUS_POSTED = "posted"
647
648ASSURANCE_VERIFIED = "verified"
649ASSURANCE_UNVERIFIED = "unverified"
650ASSURANCE_FLAGGED = "flagged"
651
652
653def _safe_read(collection: str, base_dir: Path | str) -> list[dict]:
654 """read_collection_records, folding a missing/uninstalled collection to
655 an empty list instead of raising -- this report must degrade to "not
656 enough data" rather than a 500 when a dependent package (app-finance)
657 or a not-yet-imported account has nothing on file yet."""
658 try:
659 return object_records.read_collection_records(collection, base_dir=base_dir)
660 except Exception:
661 return []
662
663
664def _latest_by_period_end(rows: list[dict]) -> dict | None:
665 return max(rows, key=lambda r: (r.get("period_end") or "", r.get("created_at") or ""),
666 default=None)
667
668
669def _assurance_from_flags(flags_raw: Any) -> str:
670 """verified/unverified/flagged from one import's flags JSON (the
671 `checks` block run_gates() produces).
672
673 "flagged" is deliberately keyed on ANY failed check (tie_out or
674 continuity), not just tie_out, because a broken chain of statements is
675 exactly as much of an anti-fraud gap as a broken statement -- both mean
676 the evidence trail cannot be trusted yet. "unverified" is the honest
677 middle ground for a balance-less CSV: nothing failed because nothing
678 that could fail was even run.
679 """
680 try:
681 checks = json.loads(flags_raw or "{}")
682 except (ValueError, TypeError):
683 checks = {}
684 if not isinstance(checks, dict):
685 checks = {}
686 failed = any(isinstance(c, dict) and c.get("ran") and not c.get("passed")
687 for c in checks.values())
688 if failed:
689 return ASSURANCE_FLAGGED
690 tie_out = checks.get("tie_out")
691 if isinstance(tie_out, dict) and tie_out.get("ran") and tie_out.get("passed"):
692 return ASSURANCE_VERIFIED
693 return ASSURANCE_UNVERIFIED
694
695
696def reconciliation(bank_account_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR,
697 as_of: str = "") -> dict:
698 """The classic bank reconciliation statement for one account.
699
700 Two independent truths are folded and compared, never merged: the
701 bank's (bank_statement_imports/bank_lines, imported evidence) and the
702 books' (fin_journals/fin_journal_lines through the account's own
703 fin_account_id). bank_closing_cents deliberately comes from the latest
704 ACCEPTED import only -- an import whose own tie-out either passed or
705 was never claimed to run -- because a statement that failed its own
706 arithmetic check is not something to build a "you're reconciled" claim
707 on top of. `assurance`, by contrast, is read off the single most
708 recent import regardless of its status: a fresh statement that just
709 failed tie-out is exactly the thing this view exists to surface, even
710 while the number it displays quietly falls back to the last
711 trustworthy one.
712
713 The tie: once every bank line is either matched to a book record or
714 resolved (composing its own journal via action_resolve_bank_line),
715 bank_closing_cents - book_balance_cents should equal exactly the sum
716 of lines resolved as "timing" (on the statement, deliberately never
717 booked -- see object_banking module docstring / the resolution-verbs
718 tests). Any remaining unmatched or merely-suggested line is slack in
719 that equation, which is what `reconciled` actually tests: it is not
720 "do the two numbers match", it is "do they match FOR AN EXPLAINED
721 REASON".
722
723 as_of, when given (ISO date), scopes the statement to that date:
724 imports with a period_end after it and posted journals dated after it
725 are excluded, so a caller can ask "were we reconciled as of last
726 month-end" without waiting for a fresh import.
727
728 Never raises -- a bank account that does not exist, one with no
729 fin_account_id set, or collections that are not installed all fold to
730 a dict of mostly-None fields. This is a report a caller may render for
731 a not-yet-configured account, not a gate.
732 """
733 accounts = _safe_read(ACCOUNTS_COLLECTION, base_dir)
734 account = next((a for a in accounts if a.get("id") == bank_account_id), None)
735 fin_account_id = str((account or {}).get("fin_account_id") or "")
736
737 imports = [r for r in _safe_read(IMPORTS_COLLECTION, base_dir)
738 if r.get("bank_account_id") == bank_account_id
739 and (r.get("period_end") or "")
740 and (not as_of or (r.get("period_end") or "") <= as_of)]
741 latest_import = _latest_by_period_end(imports)
742 latest_accepted = _latest_by_period_end(
743 [r for r in imports if r.get("status") == STATUS_ACCEPTED])
744
745 bank_closing_cents = None
746 bank_statement_date = None
747 if latest_accepted is not None and is_present(latest_accepted.get("closing_balance_cents")):
748 bank_closing_cents = int(latest_accepted["closing_balance_cents"])
749 bank_statement_date = latest_accepted.get("period_end") or ""
750
751 assurance = _assurance_from_flags(latest_import.get("flags")) if latest_import else None
752
753 book_balance_cents = None
754 if fin_account_id:
755 posted_ids = {
756 j.get("id") for j in _safe_read(JOURNALS_COLLECTION, base_dir)
757 if j.get("status") == _STATUS_POSTED
758 and (not as_of or (j.get("date") or "") <= as_of)
759 }
760 debit_total = credit_total = 0
761 for line in _safe_read(JOURNAL_LINES_COLLECTION, base_dir):
762 if line.get("journal_id") not in posted_ids or line.get("account_id") != fin_account_id:
763 continue
764 # object_finance.to_cents, not bare int(): every other ledger fold
765 # in this codebase parses defensively (Decimal, floor, blank -> 0)
766 # because a hand-edited TSV row or a half-filled draft can leave a
767 # *_cents field blank or fractional. A bare int() raises ValueError
768 # on exactly those rows -- and this is the reconciliation view, the
769 # one page whose job is to keep working when the data is wrong.
770 debit_total += object_finance.to_cents(line.get("debit_cents"))
771 credit_total += object_finance.to_cents(line.get("credit_cents"))
772 # An asset account: debits increase the balance, credits decrease
773 # it -- the same convention object_finance.py uses throughout.
774 book_balance_cents = debit_total - credit_total
775
776 matched_cents = timing_cents = unmatched_cents = 0
777 unmatched_count = timing_count = suggested_count = 0
778 for row in _safe_read(LINES_COLLECTION, base_dir):
779 if row.get("bank_account_id") != bank_account_id:
780 continue
781 amount = int(row.get("amount_cents") or 0)
782 status = row.get("match_status") or "unmatched"
783 if status == "matched":
784 matched_cents += amount
785 elif status == "resolved":
786 if (row.get("resolved_as") or "") == "timing":
787 timing_cents += amount
788 timing_count += 1
789 else:
790 matched_cents += amount
791 else:
792 # unmatched and suggested are both still an open tail -- a
793 # suggestion is the matcher's opinion, not a human decision
794 # (object_banking module docstring), so it has not yet earned
795 # its way into matched_cents.
796 unmatched_cents += amount
797 if status == "suggested":
798 suggested_count += 1
799 else:
800 unmatched_count += 1
801
802 difference_cents = None
803 if bank_closing_cents is not None and book_balance_cents is not None:
804 difference_cents = bank_closing_cents - book_balance_cents
805 reconciled = difference_cents is not None and difference_cents == timing_cents
806
807 return {
808 "bank_closing_cents": bank_closing_cents,
809 "bank_statement_date": bank_statement_date,
810 "book_balance_cents": book_balance_cents,
811 "matched_cents": matched_cents,
812 "unmatched_cents": unmatched_cents,
813 "timing_cents": timing_cents,
814 "unmatched_count": unmatched_count,
815 "timing_count": timing_count,
816 "suggested_count": suggested_count,
817 "difference_cents": difference_cents,
818 "reconciled": reconciled,
819 "assurance": assurance,
820 }