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/tests/test_bank_reconciliation.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, 19 minutes ago History
test_bank_reconciliation.py · 20.8 KB · 441 lines
1"""Bank reconciliation (plan/bank-import-reconciliation-spec.md, slice 2):
2the matcher, evidence immutability, and the resolution verbs.
3
4The control being tested is not "does it match things" but "can anyone make
5the evidence agree with the books by hand" -- the answer must be no, and
6every act of reconciliation must carry a name.
7"""
8
9import json
10import pathlib
11
12import pytest
13
14import object_execution
15import object_records
16import python_object_runtime
17from conftest import stage_collection
18
19REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
20PACKAGES = REPO_ROOT / "packages"
21BANKING_OBJECTS = PACKAGES / "app-banking" / "objects"
22RUNTIME = python_object_runtime.PythonObjectRuntime()
23
24ACCOUNT, ACCOUNT_2 = "bank-1", "bank-2"
25CASH, CASH_2 = "acct-cash", "acct-savings"
26FEES, INTEREST, AR, REV = "acct-fees", "acct-interest", "acct-ar", "acct-rev"
27DAN = {"user_id": "dan"}
28
29
30def setup_env(tmp_path, monkeypatch, *, settings=()):
31 data_dir = tmp_path / "data"
32 wanted = [("app-banking", "value_accounts"), ("app-banking", "bank_import_profiles"),
33 ("app-banking", "bank_statement_imports"), ("app-banking", "bank_lines"),
34 ("app-finance", "fin_accounts"), ("app-finance", "fin_journals"),
35 ("app-finance", "fin_journal_lines"),
36 ("app-payments", "payments"), ("app-payments", "refunds"),
37 ("app-invoices", "invoices")]
38 for pkg, name in wanted:
39 stage_collection(data_dir, pkg, name)
40
41 rows = ""
42 for i, (k, v) in enumerate(settings):
43 rows += f"s{i}\t{k}\t{v}\t\n"
44 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
45 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
46
47 for acct, kind in ((CASH, "asset"), (CASH_2, "asset"), (FEES, "expense"),
48 (INTEREST, "income"), (AR, "asset"), (REV, "income")):
49 object_records.create_collection_record(
50 "fin_accounts", {"id": acct, "name": acct, "account_type": kind,
51 "owner_id": "dan"}, base_dir=data_dir)
52 for bank, cash, name in ((ACCOUNT, CASH, "Checking"), (ACCOUNT_2, CASH_2, "Savings")):
53 object_records.create_collection_record(
54 "value_accounts", {"id": bank, "name": name, "fin_account_id": cash,
55 "owner_id": "dan"}, base_dir=data_dir)
56 return data_dir
57
58
59def make_line(data_dir, lid, *, amount, on="2026-07-02", desc="", account=ACCOUNT, **extra):
60 rec = {"id": lid, "bank_account_id": account, "posted_on": on,
61 "amount_cents": str(amount), "description": desc, "raw": f"raw:{desc}",
62 "line_hash": f"h-{lid}", "match_status": "unmatched", "owner_id": "dan"}
63 rec.update(extra)
64 return object_records.create_collection_record("bank_lines", rec, base_dir=data_dir)
65
66
67def make_payment(data_dir, pid, *, cents, on="2026-07-02", reference="", invoice="inv1"):
68 return object_records.create_collection_record(
69 "payments",
70 {"id": pid, "invoice_id": invoice, "amount_cents": str(cents), "method": "card",
71 "received_on": on, "reference": reference, "status": "received", "owner_id": "dan"},
72 base_dir=data_dir)
73
74
75def make_invoice(data_dir, iid="inv1"):
76 return object_records.create_collection_record(
77 "invoices", {"id": iid, "number": "N-1", "customer_name": "Acme",
78 "status": "sent", "total_cents": "500000", "owner_id": "dan"},
79 base_dir=data_dir)
80
81
82def run_object(object_id, payload, method="POST"):
83 return object_execution.execute_object(
84 RUNTIME,
85 object_execution.ObjectExecutionRequest(
86 object_id, method=method, payload={"_identity": DAN, **payload}),
87 roots=[BANKING_OBJECTS]).result
88
89
90def hook(action, record=None, existing=None, changes=None):
91 return object_execution.execute_object(
92 RUNTIME,
93 object_execution.ObjectExecutionRequest(
94 "hook_bank_lines", method="BEFORE_WRITE",
95 payload={"action": action, "collection": "bank_lines",
96 "record": record or {}, "existing": existing or {},
97 "changes": changes or {}}),
98 roots=[BANKING_OBJECTS]).result
99
100
101def line(data_dir, lid):
102 return object_records.get_collection_record("bank_lines", lid, base_dir=data_dir)
103
104
105def journals(data_dir):
106 return object_records.read_collection_records("fin_journals", base_dir=data_dir)
107
108
109def lines_for(data_dir, journal_id):
110 return {l["account_id"]: l for l in
111 object_records.read_collection_records("fin_journal_lines", base_dir=data_dir)
112 if l["journal_id"] == journal_id}
113
114
115# --- the matcher --------------------------------------------------------------
116
117def test_reference_plus_amount_auto_matches_at_tier_1(tmp_path, monkeypatch):
118 data_dir = setup_env(tmp_path, monkeypatch)
119 make_invoice(data_dir)
120 make_payment(data_dir, "p1", cents=150000, reference="INV-1001")
121 make_line(data_dir, "L1", amount=150000, desc="ACME CORP PAYMENT INV-1001")
122
123 result = run_object("system_bank_matcher", {})
124 assert result["auto_matched"] == 1
125 row = line(data_dir, "L1")
126 assert row["match_status"] == "matched"
127 assert row["matched_to"] == "payments/p1"
128 assert json.loads(row["suggestions"])[0]["tier"] == 1
129
130
131def test_amount_only_is_suggested_never_auto_matched(tmp_path, monkeypatch):
132 data_dir = setup_env(tmp_path, monkeypatch)
133 make_invoice(data_dir)
134 make_payment(data_dir, "p1", cents=150000, on="2026-07-01", reference="INV-9999")
135 make_line(data_dir, "L1", amount=150000, on="2026-07-02", desc="DEPOSIT")
136
137 result = run_object("system_bank_matcher", {})
138 assert result["auto_matched"] == 0 and result["suggested"] == 1
139 row = line(data_dir, "L1")
140 assert row["match_status"] == "suggested"
141 assert row["matched_to"] == "" # a suggestion is not a decision
142 proposal = json.loads(row["suggestions"])[0]
143 assert proposal["tier"] == 2 and proposal["refs"] == ["payments/p1"]
144
145
146def test_batched_deposit_is_proposed_as_a_combination(tmp_path, monkeypatch):
147 data_dir = setup_env(tmp_path, monkeypatch)
148 make_invoice(data_dir)
149 make_payment(data_dir, "p1", cents=60000)
150 make_payment(data_dir, "p2", cents=90000)
151 make_line(data_dir, "L1", amount=150000, desc="BATCH DEPOSIT")
152
153 run_object("system_bank_matcher", {})
154 proposals = json.loads(line(data_dir, "L1")["suggestions"])
155 combo = [p for p in proposals if p["tier"] == 3]
156 assert combo and sorted(combo[0]["refs"]) == ["payments/p1", "payments/p2"]
157 assert line(data_dir, "L1")["match_status"] == "suggested"
158
159
160def test_out_of_window_and_claimed_records_are_not_proposed(tmp_path, monkeypatch):
161 data_dir = setup_env(tmp_path, monkeypatch,
162 settings=(("reconcile.date_window_days", "2"),))
163 make_invoice(data_dir)
164 make_payment(data_dir, "p1", cents=150000, on="2026-06-01") # far outside the window
165 make_line(data_dir, "L1", amount=150000, on="2026-07-02", desc="DEPOSIT")
166 assert run_object("system_bank_matcher", {})["suggested"] == 0
167
168 make_payment(data_dir, "p2", cents=150000, on="2026-07-02", reference="INV-1001")
169 make_line(data_dir, "L2", amount=150000, on="2026-07-02", desc="PAYMENT INV-1001")
170 make_line(data_dir, "L3", amount=150000, on="2026-07-02", desc="PAYMENT INV-1001")
171 run_object("system_bank_matcher", {})
172 # One book record cannot satisfy two bank lines.
173 matched = [l for l in object_records.read_collection_records("bank_lines", base_dir=data_dir)
174 if l.get("matched_to") == "payments/p2"]
175 assert len(matched) == 1
176
177
178def test_auto_match_can_be_switched_off_entirely(tmp_path, monkeypatch):
179 data_dir = setup_env(tmp_path, monkeypatch,
180 settings=(("reconcile.auto_match_tier", "0"),))
181 make_invoice(data_dir)
182 make_payment(data_dir, "p1", cents=150000, reference="INV-1001")
183 make_line(data_dir, "L1", amount=150000, desc="PAYMENT INV-1001")
184 result = run_object("system_bank_matcher", {})
185 assert result["auto_matched"] == 0 and result["suggested"] == 1
186 assert line(data_dir, "L1")["match_status"] == "suggested"
187
188
189def test_matcher_is_a_no_op_without_banking_data(tmp_path, monkeypatch):
190 setup_env(tmp_path, monkeypatch)
191 assert run_object("system_bank_matcher", {})["scanned"] == 0
192
193
194# --- evidence immutability ----------------------------------------------------
195
196def test_the_bank_words_cannot_be_edited(tmp_path, monkeypatch):
197 """The schema's `locked_when` (not a hook) freezes the evidence fields,
198 inside the write lock, for every writer."""
199 data_dir = setup_env(tmp_path, monkeypatch)
200 make_line(data_dir, "L1", amount=150000, desc="ACME CORP PAYMENT")
201
202 for field, value in (("amount_cents", "140000"), ("posted_on", "2026-07-03"),
203 ("description", "SOMETHING ELSE"), ("raw", "tampered"),
204 ("bank_account_id", ACCOUNT_2)):
205 with pytest.raises(object_records.RecordLockedError) as refused:
206 object_records.update_collection_record(
207 "bank_lines", "L1", {field: value}, base_dir=data_dir)
208 assert field in refused.value.fields
209 assert "cannot be edited" in str(refused.value)
210 assert line(data_dir, "L1")["amount_cents"] == "150000"
211
212 # Reconciliation work on the same record is allowed.
213 object_records.update_collection_record(
214 "bank_lines", "L1", {"match_status": "matched", "matched_to": "payments/p1"},
215 base_dir=data_dir)
216 object_records.update_collection_record(
217 "bank_lines", "L1", {"resolved_as": "fee", "match_status": "resolved"},
218 base_dir=data_dir)
219
220
221def test_matched_requires_a_well_formed_target(tmp_path, monkeypatch):
222 data_dir = setup_env(tmp_path, monkeypatch)
223 make_line(data_dir, "L1", amount=150000)
224 # Present-or-absent is the field's validation.required_when, for every
225 # writer: the same 400 the hook gave, from the write path itself ...
226 with pytest.raises(object_records.InvalidRecordPayloadError,
227 match="'matched_to' is required when match_status is matched"):
228 object_records.update_collection_record(
229 "bank_lines", "L1", {"match_status": "matched"}, base_dir=data_dir)
230 assert line(data_dir, "L1")["match_status"] == "unmatched"
231 # ... a matched line cannot have its target blanked, and a line cannot
232 # be created already matched to nothing (the hook looked at updates only) ...
233 object_records.update_collection_record(
234 "bank_lines", "L1", {"match_status": "matched", "matched_to": "payments/p1"},
235 base_dir=data_dir)
236 with pytest.raises(object_records.InvalidRecordPayloadError, match="'matched_to' is required"):
237 object_records.update_collection_record(
238 "bank_lines", "L1", {"matched_to": ""}, base_dir=data_dir)
239 with pytest.raises(object_records.InvalidRecordPayloadError, match="'matched_to' is required"):
240 make_line(data_dir, "L2", amount=100, match_status="matched")
241 object_records.update_collection_record(
242 "bank_lines", "L1", {"match_status": "unmatched", "matched_to": ""}, base_dir=data_dir)
243 # ... and the shape is the field's validation.pattern, for every writer.
244 with pytest.raises(object_records.InvalidRecordPayloadError):
245 object_records.update_collection_record(
246 "bank_lines", "L1", {"match_status": "matched", "matched_to": "p1"},
247 base_dir=data_dir)
248 assert line(data_dir, "L1")["match_status"] == "unmatched"
249
250
251def test_confirming_a_match_is_an_ordinary_attributed_update(tmp_path, monkeypatch):
252 """Deliberately NOT an action object: a normal write already carries the
253 actor into the change log, which is what makes reconciliation auditable."""
254 data_dir = setup_env(tmp_path, monkeypatch)
255 make_invoice(data_dir)
256 make_payment(data_dir, "p1", cents=150000)
257 make_line(data_dir, "L1", amount=150000, desc="DEPOSIT")
258 run_object("system_bank_matcher", {})
259
260 object_records.update_collection_record(
261 "bank_lines", "L1", {"match_status": "matched", "matched_to": "payments/p1"},
262 base_dir=data_dir, actor="dan")
263 assert line(data_dir, "L1")["match_status"] == "matched"
264 import object_record_changes
265 entries = object_record_changes.list_record_changes(
266 "bank_lines", record_id="L1", base_dir=data_dir)["changes"]
267 confirmations = [e for e in entries
268 if "match_status" in (e.get("changed_fields") or [])]
269 assert confirmations and confirmations[0]["actor"] == "dan"
270
271
272# --- resolution verbs ---------------------------------------------------------
273
274def test_fee_composes_a_posted_journal_and_is_idempotent(tmp_path, monkeypatch):
275 data_dir = setup_env(tmp_path, monkeypatch,
276 settings=(("reconcile.journal.fees_account", FEES),))
277 make_line(data_dir, "L1", amount=-2500, desc="MONTHLY SERVICE FEE")
278
279 result = run_object("action_resolve_bank_line", {"line_id": "L1", "kind": "fee"})
280 assert result["status"] == 200 and result["journal"]["posted"] is True
281 row = line(data_dir, "L1")
282 assert row["match_status"] == "resolved" and row["resolved_as"] == "fee"
283 booked = lines_for(data_dir, result["journal"]["journal_id"])
284 assert booked[FEES]["debit_cents"] == "2500"
285 assert booked[CASH]["credit_cents"] == "2500"
286
287 again = run_object("action_resolve_bank_line", {"line_id": "L1", "kind": "fee"})
288 assert again["status"] == 409 # already resolved
289 assert len(journals(data_dir)) == 1
290
291
292def test_interest_books_the_other_direction(tmp_path, monkeypatch):
293 data_dir = setup_env(tmp_path, monkeypatch,
294 settings=(("reconcile.journal.interest_account", INTEREST),))
295 make_line(data_dir, "L1", amount=812, desc="INTEREST PAID")
296 result = run_object("action_resolve_bank_line", {"line_id": "L1", "kind": "interest"})
297 booked = lines_for(data_dir, result["journal"]["journal_id"])
298 assert booked[CASH]["debit_cents"] == "812"
299 assert booked[INTEREST]["credit_cents"] == "812"
300
301
302def test_transfer_moves_between_two_own_accounts(tmp_path, monkeypatch):
303 data_dir = setup_env(tmp_path, monkeypatch)
304 make_line(data_dir, "L1", amount=-100000, desc="TRANSFER TO SAVINGS")
305 result = run_object("action_resolve_bank_line",
306 {"line_id": "L1", "kind": "transfer",
307 "counterpart_bank_account_id": ACCOUNT_2})
308 assert result["status"] == 200
309 booked = lines_for(data_dir, result["journal"]["journal_id"])
310 assert booked[CASH_2]["debit_cents"] == "100000" # money into savings
311 assert booked[CASH]["credit_cents"] == "100000" # out of checking
312
313
314def test_nsf_bounces_the_payment_and_reverses_its_journal(tmp_path, monkeypatch):
315 data_dir = setup_env(tmp_path, monkeypatch, settings=(
316 ("payments.accounting_basis", "cash"),
317 ("payments.journal.cash_account", CASH),
318 ("payments.journal.revenue_account", REV)))
319 make_invoice(data_dir)
320 make_payment(data_dir, "p1", cents=150000, reference="INV-1001")
321 make_line(data_dir, "L1", amount=-150000, desc="RETURNED ITEM NSF")
322
323 result = run_object("action_resolve_bank_line",
324 {"line_id": "L1", "kind": "nsf", "payment_id": "p1"})
325 assert result["status"] == 200
326 payment = object_records.get_collection_record("payments", "p1", base_dir=data_dir)
327 assert payment["status"] == "bounced"
328 reversal = [j for j in journals(data_dir)
329 if j["generated_from"] == "payments/p1:bounced"]
330 assert reversal and reversal[0]["kind"] == "reversing"
331 booked = lines_for(data_dir, reversal[0]["id"])
332 assert booked[REV]["debit_cents"] == "150000" # revenue reversed
333 assert booked[CASH]["credit_cents"] == "150000" # cash taken back out
334 assert line(data_dir, "L1")["matched_to"] == "payments/p1"
335
336
337def test_timing_items_carry_forward_without_a_journal(tmp_path, monkeypatch):
338 data_dir = setup_env(tmp_path, monkeypatch)
339 make_line(data_dir, "L1", amount=50000, desc="DEPOSIT IN TRANSIT")
340 result = run_object("action_resolve_bank_line", {"line_id": "L1", "kind": "timing"})
341 assert result["status"] == 200 and result["journal"] is None
342 assert line(data_dir, "L1")["resolved_as"] == "timing"
343 assert journals(data_dir) == []
344
345
346def run_as(user, payload):
347 return object_execution.execute_object(
348 RUNTIME,
349 object_execution.ObjectExecutionRequest(
350 "action_resolve_bank_line", method="POST",
351 payload={"_identity": {"user_id": user}, **payload}),
352 roots=[BANKING_OBJECTS]).result
353
354
355def test_a_line_nobody_owns_is_resolved_by_an_admin_only(tmp_path, monkeypatch):
356 """The check used to be "has an owner who is not me", so any signed-in
357 user could resolve, and post a journal for, a bank line with NO owner;
358 the bank_lines API shows it to nobody but an admin."""
359 data_dir = setup_env(tmp_path, monkeypatch,
360 settings=(("reconcile.journal.fees_account", FEES),))
361 make_line(data_dir, "L1", amount=-2500, desc="FEE", owner_id="")
362 refused = run_as("mallory", {"line_id": "L1", "kind": "fee"})
363 assert refused["status"] == 404
364 assert journals(data_dir) == []
365 assert line(data_dir, "L1")["match_status"] == "unmatched"
366
367 admin = object_execution.execute_object(
368 RUNTIME,
369 object_execution.ObjectExecutionRequest(
370 "action_resolve_bank_line", method="POST",
371 payload={"_identity": {"user_id": "ops", "roles": ["admin"]},
372 "line_id": "L1", "kind": "timing"}),
373 roots=[BANKING_OBJECTS]).result
374 assert admin["status"] == 200
375
376
377def test_nsf_cannot_bounce_a_payment_the_caller_may_not_update(tmp_path, monkeypatch):
378 """payment_id came straight from the request and the payment was read
379 and bounced with no check, so a user with any bank line of their own
380 could mark anybody's payment bounced and post its reversal. Likewise a
381 transfer's counterpart account must be the caller's."""
382 data_dir = setup_env(tmp_path, monkeypatch, settings=(
383 ("payments.accounting_basis", "cash"),
384 ("payments.journal.cash_account", CASH),
385 ("payments.journal.revenue_account", REV)))
386 make_invoice(data_dir)
387 make_payment(data_dir, "p1", cents=150000, reference="INV-1001") # dan's
388 object_records.create_collection_record(
389 "value_accounts", {"id": "bank-m", "name": "Mallory's", "fin_account_id": CASH,
390 "owner_id": "mallory"}, base_dir=data_dir)
391 object_records.create_collection_record(
392 "bank_lines", {"id": "LM", "bank_account_id": "bank-m", "posted_on": "2026-07-02",
393 "amount_cents": "-150000", "description": "NSF", "raw": "raw",
394 "line_hash": "h-LM", "match_status": "unmatched",
395 "owner_id": "mallory"}, base_dir=data_dir)
396
397 result = run_as("mallory", {"line_id": "LM", "kind": "nsf", "payment_id": "p1"})
398 assert result["status"] == 400
399 payment = object_records.get_collection_record("payments", "p1", base_dir=data_dir)
400 assert payment["status"] == "received"
401 assert journals(data_dir) == []
402 assert line(data_dir, "LM")["match_status"] == "unmatched"
403
404 # A transfer into somebody else's account is refused the same way.
405 transfer = run_as("mallory", {"line_id": "LM", "kind": "transfer",
406 "counterpart_bank_account_id": ACCOUNT})
407 assert transfer["status"] == 400
408 assert journals(data_dir) == []
409
410
411def test_resolution_refusals(tmp_path, monkeypatch):
412 data_dir = setup_env(tmp_path, monkeypatch)
413 make_line(data_dir, "L1", amount=-2500, desc="FEE")
414 # Unconfigured expense account: refuse rather than post to nowhere.
415 assert run_object("action_resolve_bank_line",
416 {"line_id": "L1", "kind": "fee"})["status"] == 409
417 assert run_object("action_resolve_bank_line",
418 {"line_id": "L1", "kind": "nonsense"})["status"] == 400
419 assert run_object("action_resolve_bank_line",
420 {"line_id": "missing", "kind": "fee"})["status"] == 404
421 # A transfer with no counterpart named.
422 assert run_object("action_resolve_bank_line",
423 {"line_id": "L1", "kind": "transfer"})["status"] == 400
424 anon = object_execution.execute_object(
425 RUNTIME,
426 object_execution.ObjectExecutionRequest(
427 "action_resolve_bank_line", method="POST",
428 payload={"line_id": "L1", "kind": "timing"}),
429 roots=[BANKING_OBJECTS]).result
430 assert anon["status"] == 403
431
432
433def test_a_bank_account_without_a_book_account_cannot_post(tmp_path, monkeypatch):
434 data_dir = setup_env(tmp_path, monkeypatch,
435 settings=(("reconcile.journal.fees_account", FEES),))
436 object_records.create_collection_record(
437 "value_accounts", {"id": "bank-3", "name": "Unlinked", "owner_id": "dan"},
438 base_dir=data_dir)
439 make_line(data_dir, "L9", amount=-2500, desc="FEE", account="bank-3")
440 outcome = run_object("action_resolve_bank_line", {"line_id": "L9", "kind": "fee"})
441 assert outcome["status"] == 409 and "fin_account_id" in outcome["error"]