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_closed_period_composers.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_closed_period_composers.py · 33.9 KB · 673 lines
1"""A closed period stays closed for EVERY writer of journals, the composers
2included -- and a fact that arrives late lands in the next open period,
3flagged, rather than in the closed one or nowhere.
4
5Reported by a simulated-company trial (bug report 2026-11-30-01-58-25-CST):
6November was closed (a fin_closed_periods row for 2026-11-01..30), and
7HTTP journal writes into November were refused. Then an expense incurred
8on 2026-11-15 was approved, and a payment received on 2026-11-29 was
9recorded, and each posted a journal dated inside November. The period
10lock lived in hook_fin_journals, which only the HTTP write path calls;
11every composer writes at the storage level, so the filed month changed
12and nothing told the operator.
13
14Two halves of the fix, both pinned here:
15
161. The rule is a locked check on fin_journals and fin_journal_lines
17 (`locked_checks.closed_period`), so object_records refuses a journal
18 or line write into a closed period whoever makes it.
192. A composer whose natural date is closed books on the first open day
20 after the period (object_finance.compose_posted_journal), keeps the
21 real date in occurred_on, names the period in the description, and
22 sets period_review=pending, which the attention board counts.
23
24Every composer is driven through its real object: system_books
25(payments, refunds, bounces, invoice issue), system_expense_books
26(approval and the reversal on rejection), system_fin_recurring_runner,
27system_stock_books, action_apply_count, action_resolve_bank_line (fee,
28interest, transfer, NSF), action_record_count, system_wallet_books; plus
29action_reverse_journal (which refuses and asks for a date) and
30object_materialize (generic, so it is refused and reports the period).
31"""
32
33import json
34import pathlib
35import threading
36from datetime import date, datetime, timedelta, timezone
37
38import pytest
39
40from conftest import stage_collection
41
42import object_execution
43import object_finance
44import object_materialize
45import object_records
46import python_object_runtime
47
48import test_bank_reconciliation as bank
49import test_books_spine as spine
50import test_cash_counts as cash_counts
51import test_cogs_on_sale as cogs
52import test_expenses as expenses
53import test_inventory_adjustments as stock
54import test_wallet_books as wallets
55from test_attention_declared import ADMIN, shipped_count
56from test_object_server import TEST_ADMIN_TOKEN, enable_admin_token, request
57
58REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
59FINANCE = REPO_ROOT / "packages" / "app-finance"
60RUNTIME = python_object_runtime.PythonObjectRuntime()
61
62NOV_START, NOV_END, DEC_1 = "2026-11-01", "2026-11-30", "2026-12-01"
63
64
65def close(data_dir, *, start=NOV_START, end=NOV_END, owner="", pid="cp-nov",
66 reason="November filed"):
67 """Close a period. fin_closed_periods is staged on first use."""
68 if not (data_dir / "schemas" / "fin_closed_periods.json").exists():
69 stage_collection(data_dir, "app-finance", "fin_closed_periods")
70 return object_records.create_collection_record(
71 "fin_closed_periods",
72 {"id": pid, "start_date": start, "end_date": end, "reason": reason,
73 "owner_id": owner}, base_dir=data_dir)
74
75
76def all_journals(data_dir):
77 return object_records.read_collection_records("fin_journals", base_dir=data_dir)
78
79
80def assert_nothing_in(data_dir, start=NOV_START, end=NOV_END):
81 """The invariant every test ends on: no journal written after the close
82 is dated inside the closed period."""
83 inside = [j for j in all_journals(data_dir) if start <= j["date"][:10] <= end]
84 assert inside == [], inside
85
86
87def assert_redated(journal, *, occurred, booked=DEC_1):
88 assert journal["date"] == booked
89 assert journal["occurred_on"] == occurred
90 assert journal["period_review"] == "pending"
91 assert f"[{occurred} fell in closed period" in journal["description"]
92 assert journal["status"] == "posted"
93
94
95def by_marker(data_dir, marker):
96 [journal] = [j for j in all_journals(data_dir) if j["generated_from"] == marker]
97 return journal
98
99
100# --- the reported cases --------------------------------------------------------
101
102
103def test_a_payment_received_in_a_closed_month_books_on_the_first_open_day(
104 tmp_path, monkeypatch):
105 """The report's payment: received 2026-11-29, recorded after November
106 was closed. It used to post dated 2026-11-29, into the filed month."""
107 data_dir = spine.setup_env(tmp_path, monkeypatch, basis="cash")
108 close(data_dir, owner="dan")
109 object_records.create_collection_record(
110 "payments", {"id": "p1", "invoice_id": "inv1", "amount_cents": "4000",
111 "method": "card", "received_on": "2026-11-29", "reference": "late",
112 "status": "received", "owner_id": "dan"}, base_dir=data_dir)
113
114 result = spine.fire("payments", "p1", "created").result
115 assert result["ok"] and result["posted"] is True, result
116 assert result["redated"]["occurred_on"] == "2026-11-29"
117 assert result["redated"]["date"] == DEC_1
118 assert result["redated"]["closed_periods"][0]["id"] == "cp-nov"
119
120 journal = by_marker(data_dir, "payments/p1")
121 assert_redated(journal, occurred="2026-11-29")
122 lines = {l["account_id"]: l for l in spine.lines_for(data_dir, journal["id"])}
123 assert lines[spine.CASH]["debit_cents"] == "4000" # the money is whole
124 assert lines[spine.REV]["credit_cents"] == "4000"
125
126 # A replayed event finds the journal it booked; nothing twice.
127 again = spine.fire("payments", "p1", "created").result
128 assert again["skipped"].startswith("already composed")
129 assert len(all_journals(data_dir)) == 1
130 assert_nothing_in(data_dir)
131
132
133def test_an_expense_incurred_in_a_closed_month_and_approved_later_books_after_it(
134 tmp_path, monkeypatch):
135 """The report's expense: incurred 2026-11-15, approved after the close."""
136 data_dir = expenses.setup_env(tmp_path, monkeypatch)
137 close(data_dir, owner="dana")
138 expenses.spend(data_dir, "e1", incurred_on="2026-11-15", status="submitted")
139 object_records.update_collection_record("expenses", "e1", {"status": "approved"},
140 base_dir=data_dir)
141
142 result = expenses.post_books(data_dir, "e1")
143 assert result["ok"] and result["posted"] is True, result
144 assert_redated(by_marker(data_dir, "expenses/e1"), occurred="2026-11-15")
145 assert_nothing_in(data_dir)
146
147
148def test_rejecting_an_expense_booked_before_the_close_reverses_it_after(
149 tmp_path, monkeypatch):
150 """The booking is in November and stays there (it was right when it was
151 made); the reversal is the late fact and goes to December."""
152 data_dir = expenses.setup_env(tmp_path, monkeypatch)
153 expenses.spend(data_dir, "e1", incurred_on="2026-11-15", status="submitted")
154 object_records.update_collection_record("expenses", "e1", {"status": "approved"},
155 base_dir=data_dir)
156 booked = expenses.post_books(data_dir, "e1")
157 assert booked["posted"] is True
158 original = by_marker(data_dir, "expenses/e1")
159 assert original["date"] == "2026-11-15"
160
161 close(data_dir, owner="dana")
162 object_records.update_collection_record("expenses", "e1", {"status": "rejected"},
163 base_dir=data_dir)
164 result = expenses.post_books(data_dir, "e1")
165 assert result["reversed"], result
166 reversal = by_marker(data_dir, f"reversal:{original['id']}")
167 assert_redated(reversal, occurred="2026-11-15")
168 assert object_records.get_collection_record(
169 "fin_journals", original["id"], base_dir=data_dir)["date"] == "2026-11-15"
170
171
172# --- every other composer ------------------------------------------------------
173
174
175def test_a_refund_a_bounce_and_an_invoice_issue_in_a_closed_month_book_after_it(
176 tmp_path, monkeypatch):
177 """system_books' other three entries (accrual basis, so the issue entry
178 exists). The invoice was issued, paid and refunded in November, all
179 recorded after the close."""
180 data_dir = spine.setup_env(tmp_path, monkeypatch, basis="accrual")
181 close(data_dir, owner="dan")
182 object_records.update_collection_record(
183 "invoices", "inv1", {"status": "sent", "issue_date": "2026-11-03"}, base_dir=data_dir)
184 assert spine.fire("invoices", "inv1", "updated").result["posted"] is True
185 object_records.create_collection_record(
186 "payments", {"id": "p1", "invoice_id": "inv1", "amount_cents": "10000",
187 "method": "card", "received_on": "2026-11-10", "status": "received",
188 "owner_id": "dan"}, base_dir=data_dir)
189 spine.fire("payments", "p1", "created")
190 object_records.create_collection_record(
191 "refunds", {"id": "r1", "payment_id": "p1", "invoice_id": "inv1",
192 "amount_cents": "2500", "refunded_on": "2026-11-12", "owner_id": "dan"},
193 base_dir=data_dir)
194 assert spine.fire("refunds", "r1", "created").result["posted"] is True
195 object_records.update_collection_record("payments", "p1", {"status": "bounced"},
196 base_dir=data_dir)
197 assert spine.fire("payments", "p1", "updated").result["posted"] is True
198
199 assert_redated(by_marker(data_dir, "invoices/inv1:issued"), occurred="2026-11-03")
200 assert_redated(by_marker(data_dir, "payments/p1"), occurred="2026-11-10")
201 assert_redated(by_marker(data_dir, "refunds/r1"), occurred="2026-11-12")
202 assert_redated(by_marker(data_dir, "payments/p1:bounced"), occurred="2026-11-10")
203 assert_nothing_in(data_dir)
204
205
206def test_a_recurring_entry_due_in_a_closed_month_books_after_it_and_the_schedule_advances(
207 tmp_path, monkeypatch):
208 data_dir = spine.setup_env(tmp_path, monkeypatch)
209 close(data_dir, owner="dan")
210 spine.add_template(data_dir, tid="t1", next_run="2026-11-15")
211 spine.add_template(data_dir, tid="t2", next_run="2026-11-20", auto_post="false")
212
213 result = spine.run_recurring({"today": "2026-12-02"}).result
214 assert result["ran"] == 2, result
215 assert_redated(by_marker(data_dir, "fin_recurring/t1:2026-11-15"), occurred="2026-11-15")
216 draft = by_marker(data_dir, "fin_recurring/t2:2026-11-20")
217 assert draft["status"] == "draft" # auto_post off: still a draft
218 assert (draft["date"], draft["occurred_on"], draft["period_review"]) == (
219 DEC_1, "2026-11-20", "pending")
220 tpl = object_records.get_collection_record("fin_recurring", "t1", base_dir=data_dir)
221 assert (tpl["last_run"], tpl["next_run"]) == ("2026-11-15", "2026-12-15")
222 assert_nothing_in(data_dir)
223
224
225def test_a_stock_loss_and_a_sale_in_a_closed_month_book_after_it(tmp_path, monkeypatch):
226 data_dir = cogs.setup_env(tmp_path, monkeypatch)
227 close(data_dir, owner="shop")
228 object_records.create_collection_record(
229 "stock_moves",
230 {"id": "mv-sale", "product_id": "p1", "from_location_id": "loc-shelf",
231 "to_location_id": "loc-customer", "quantity": "3", "unit_cost_cents": "250",
232 "reason": "sale", "occurred_at": "2026-11-24", "owner_id": "shop"},
233 base_dir=data_dir)
234 object_records.create_collection_record(
235 "stock_moves",
236 {"id": "mv-waste", "product_id": "p1", "from_location_id": "loc-shelf",
237 "to_location_id": "", "quantity": "1", "unit_cost_cents": "250",
238 "reason": "waste", "occurred_at": "2026-11-25T09:30:00Z", "owner_id": "shop"},
239 base_dir=data_dir)
240 assert cogs.fire_stock_books("mv-sale")["posted"] is True
241 assert cogs.fire_stock_books("mv-waste")["posted"] is True
242 assert_redated(by_marker(data_dir, "stock_moves/mv-sale"), occurred="2026-11-24")
243 assert_redated(by_marker(data_dir, "stock_moves/mv-waste"), occurred="2026-11-25")
244 assert_nothing_in(data_dir)
245
246
247def test_a_stock_count_dated_in_a_closed_month_books_its_variance_after_it(
248 tmp_path, monkeypatch):
249 data_dir = stock.setup_env(tmp_path, monkeypatch)
250 stock.make_product(data_dir, cost="250")
251 stock.make_location(data_dir)
252 stock.make_move(data_dir, "mv-in", reason="purchase", qty="10", to_loc="loc1")
253 close(data_dir, owner="dan")
254 result = stock.apply_count({"product_id": "prod1", "location_id": "loc1",
255 "counted_qty": "7", "counted_on": "2026-11-30"})
256 assert result["status"] == 200 and result["journal"]["posted"] is True, result
257 journal = object_records.get_collection_record(
258 "fin_journals", result["journal"]["journal_id"], base_dir=data_dir)
259 assert_redated(journal, occurred="2026-11-30")
260 assert_nothing_in(data_dir)
261
262
263@pytest.mark.parametrize("kind", ["fee", "interest", "transfer", "nsf"])
264def test_a_bank_line_resolved_after_its_month_closed_books_after_it(
265 tmp_path, monkeypatch, kind):
266 """The case fin_closed_periods' own description named in advance: a
267 late bank-line resolution dated into a closed period."""
268 data_dir = bank.setup_env(tmp_path, monkeypatch, settings=(
269 ("reconcile.journal.fees_account", bank.FEES),
270 ("reconcile.journal.interest_account", bank.INTEREST),
271 ("payments.accounting_basis", "cash"),
272 ("payments.journal.cash_account", bank.CASH),
273 ("payments.journal.revenue_account", bank.REV)))
274 payload = {"line_id": "L1", "kind": kind}
275 amount = {"fee": -2500, "interest": 812, "transfer": -100000, "nsf": -150000}[kind]
276 if kind == "transfer":
277 payload["counterpart_bank_account_id"] = bank.ACCOUNT_2
278 if kind == "nsf":
279 bank.make_invoice(data_dir)
280 bank.make_payment(data_dir, "p1", cents=150000, on="2026-11-02")
281 payload["payment_id"] = "p1"
282 bank.make_line(data_dir, "L1", amount=amount, on="2026-11-20", desc=kind.upper())
283 close(data_dir, owner="dan")
284
285 result = bank.run_object("action_resolve_bank_line", payload)
286 assert result["status"] == 200, result
287 assert result["journal"]["posted"] is True, result
288 journal = object_records.get_collection_record(
289 "fin_journals", result["journal"]["journal_id"], base_dir=data_dir)
290 assert_redated(journal, occurred="2026-11-20")
291 assert bank.line(data_dir, "L1")["match_status"] == "resolved"
292 assert_nothing_in(data_dir)
293
294
295def test_a_cash_count_dated_in_a_closed_month_books_its_variance_after_it(
296 tmp_path, monkeypatch):
297 data_dir = cash_counts.setup_env(tmp_path, monkeypatch)
298 cash_counts.make_till(data_dir)
299 cash_counts.book_cash(data_dir, 20000)
300 close(data_dir, owner="dan")
301 result = cash_counts.count({"value_account_id": cash_counts.TILL,
302 "counted_minor": 19750, "counted_on": "2026-11-30"})
303 assert result["status"] == 200 and result["journal"]["posted"] is True, result
304 journal = object_records.get_collection_record(
305 "fin_journals", result["journal"]["journal_id"], base_dir=data_dir)
306 assert_redated(journal, occurred="2026-11-30")
307 assert cash_counts.counts(data_dir)[0]["journal_id"] == journal["id"]
308 assert_nothing_in(data_dir)
309
310
311def test_a_wallet_entry_in_a_closed_stretch_books_after_it(tmp_path, monkeypatch):
312 """A wallet entry is dated when it is written (created_at), so the
313 closed stretch here is the one ending today."""
314 data_dir = wallets.setup_books(tmp_path, monkeypatch)
315 # The server stamps created_at in UTC (object_records._apply_auto_created_at),
316 # so "today" must be the UTC date too, or the test fails every evening west of
317 # Greenwich, when the local date is still yesterday's.
318 today = datetime.now(timezone.utc).date()
319 start, end = (today - timedelta(days=3)).isoformat(), today.isoformat()
320 tomorrow = (today + timedelta(days=1)).isoformat()
321 close(data_dir, start=start, end=end, owner="dan")
322 wallets.stage_entry(data_dir, "e1", 5000, "topup")
323 result = wallets.fire("e1")
324 assert result["ok"] and result["posted"] is True, result
325 assert_redated(by_marker(data_dir, "wallet_entries/e1"), occurred=end, booked=tomorrow)
326 assert_nothing_in(data_dir, start, end)
327
328
329# --- the two that do not move the date -----------------------------------------
330
331
332def test_reversing_by_hand_into_a_closed_month_is_refused_and_asks_for_a_date(
333 tmp_path, monkeypatch):
334 """A person is at the keyboard, so the reversal asks rather than moves
335 (its docstring's rejected alternative), and an open date is honoured."""
336 data_dir = spine.setup_env(tmp_path, monkeypatch)
337 spine.make_posted_journal(data_dir) # dated 2026-07-01
338 close(data_dir, start="2026-07-01", end="2026-07-31", owner="dan", pid="cp-jul")
339 identity = {"user_id": "dan", "roles": []}
340
341 refused = spine.reverse({"journal_id": "j1", "_identity": identity}).result
342 assert refused["status"] == 409 and "closed period" in refused["error"]
343 assert len(all_journals(data_dir)) == 1
344
345 ok = spine.reverse({"journal_id": "j1", "date": "2026-08-03", "_identity": identity}).result
346 assert ok["status"] == 200 and ok["posted"] is True
347 mirror = object_records.get_collection_record("fin_journals", ok["reversal_id"],
348 base_dir=data_dir)
349 assert mirror["date"] == "2026-08-03" and mirror["period_review"] == ""
350
351
352def test_a_period_closed_while_a_reversal_is_in_flight_refuses_it(tmp_path, monkeypatch):
353 """The action's own check passes, then the month closes before the
354 header is written: the locked check refuses the header, and compose
355 (told to refuse) answers that rather than moving the date."""
356 data_dir = spine.setup_env(tmp_path, monkeypatch)
357 spine.make_posted_journal(data_dir)
358 close_in_flight(monkeypatch, data_dir, start="2026-07-01", end="2026-07-31", owner="dan")
359 result = spine.reverse({"journal_id": "j1",
360 "_identity": {"user_id": "dan", "roles": []}}).result
361 assert result["status"] == 409 and "closed period" in result["error"], result
362 assert [j["id"] for j in all_journals(data_dir)] == ["j1"]
363
364
365def test_materialize_never_writes_into_a_closed_period_and_reports_it(tmp_path, monkeypatch):
366 """object_materialize is generic (it does not know which field of an
367 output is its date), so it is not re-dated: the locked check refuses
368 the closed month's header, the pass reports it, and the open months
369 are generated as usual.
370
371 The shipped fin_journal_lines schema validates journal_id and
372 account_id as relations, and materialize writes a journal's lines
373 BEFORE its header (the header is its commit signal), so against the
374 shipped schema it cannot generate a journal at all -- before this
375 change as after it (fin_recurring_runner is the engine that runs).
376 The staged lines schema here drops only those two relations; its
377 locked check is the shipped one, and it lets the orphan lines through
378 (their parent does not exist yet) for the header's check to decide."""
379 data_dir = tmp_path / "data"
380 for name in ("fin_journals", "fin_journal_lines", "fin_recurring"):
381 stage_collection(data_dir, "app-finance", name)
382 lines_schema = data_dir / "schemas" / "fin_journal_lines.json"
383 relaxed = json.loads(lines_schema.read_text())
384 for field in relaxed["fields"]:
385 if field["name"] in ("journal_id", "account_id"):
386 field["type"] = "text"
387 field.pop("relation", None)
388 lines_schema.write_text(json.dumps(relaxed))
389 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
390 close(data_dir, start="2026-06-01", end="2026-06-30")
391 template = json.dumps([
392 {"account_id": "acct_cash", "debit_cents": 1000, "credit_cents": 0},
393 {"account_id": "acct_rev", "debit_cents": 0, "credit_cents": 1000}])
394 object_records.create_collection_record(
395 "fin_recurring", {"id": "rec1", "name": "Rent", "template_lines": template,
396 "frequency": "monthly", "next_run": "2026-05-01",
397 "auto_post": "true", "is_active": "true"}, base_dir=data_dir)
398 definition = {
399 "id": "matgen_rent", "name": "Rent", "source_collection": "fin_recurring",
400 "source_filter": json.dumps({"is_active": "true"}),
401 "trigger": json.dumps({"mode": "scheduled", "interval_seconds": 3600,
402 "period_field": "frequency", "anchor_field": "next_run"}),
403 "output_collection": "fin_journals", "child_collection": "fin_journal_lines",
404 "child_source_field": "template_lines", "child_link_field": "journal_id",
405 "idempotency_key": "matgen_{definition_id}_{source_id}_{period_start}",
406 "mapping": json.dumps({"date": {"from_period": "period_start"},
407 "description": {"template": "Rent ({period_label})"},
408 "status": {"literal": "posted"}}),
409 "balance_check": json.dumps({"debit_field": "debit_cents",
410 "credit_field": "credit_cents"}),
411 "last_run_at": "", "actor": "daemon:materialize", "enabled": "true", "block": "false"}
412 from datetime import datetime, timezone
413 result = object_materialize.generate_definition(
414 definition, base_dir=data_dir, now=datetime(2026, 8, 15, tzinfo=timezone.utc))
415 assert sorted(j["date"] for j in all_journals(data_dir)) == [
416 "2026-05-01", "2026-07-01", "2026-08-01"]
417 [error] = result["errors"]
418 assert error["period_start"] == "2026-06-01" and "are closed" in error["error"]
419 assert_nothing_in(data_dir, "2026-06-01", "2026-06-30")
420
421
422# --- the lock itself -------------------------------------------------------------
423
424
425def books(tmp_path, monkeypatch):
426 data_dir = tmp_path / "data"
427 for name in ("fin_journals", "fin_journal_lines", "fin_accounts", "fin_closed_periods"):
428 stage_collection(data_dir, "app-finance", name)
429 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
430 object_records.create_collection_record(
431 "fin_accounts", {"id": "cash", "name": "Cash", "account_type": "asset",
432 "owner_id": "dan"}, base_dir=data_dir)
433 return data_dir
434
435
436def journal_row(jid, day, **extra):
437 return {"id": jid, "date": day, "description": jid, "status": "draft",
438 "kind": "standard", "owner_id": "dan", **extra}
439
440
441def test_no_storage_level_writer_can_create_edit_move_or_delete_in_a_closed_period(
442 tmp_path, monkeypatch):
443 """What every composer used to do, done directly: below the hooks."""
444 data_dir = books(tmp_path, monkeypatch)
445 object_records.create_collection_record("fin_journals", journal_row("j-nov", "2026-11-10"),
446 base_dir=data_dir)
447 object_records.create_collection_record("fin_journals", journal_row("j-dec", "2026-12-10"),
448 base_dir=data_dir)
449 object_records.create_collection_record(
450 "fin_journal_lines", {"id": "l-nov", "journal_id": "j-nov", "account_id": "cash",
451 "debit_cents": "100", "owner_id": "dan"}, base_dir=data_dir)
452 close(data_dir, owner="dan")
453
454 def refused(call):
455 with pytest.raises(object_records.CheckRefusedError) as caught:
456 call()
457 assert caught.value.check == "closed_period" and caught.value.status == 409
458 assert "2026-11-01 to 2026-11-30" in str(caught.value)
459
460 refused(lambda: object_records.create_collection_record(
461 "fin_journals", journal_row("j-new", "2026-11-29"), base_dir=data_dir))
462 refused(lambda: object_records.update_collection_record(
463 "fin_journals", "j-nov", {"description": "typo"}, base_dir=data_dir))
464 refused(lambda: object_records.update_collection_record( # moved out
465 "fin_journals", "j-nov", {"date": "2026-12-01"}, base_dir=data_dir))
466 refused(lambda: object_records.update_collection_record( # moved in
467 "fin_journals", "j-dec", {"date": "2026-11-30"}, base_dir=data_dir))
468 refused(lambda: object_records.delete_collection_record(
469 "fin_journals", "j-nov", base_dir=data_dir))
470 refused(lambda: object_records.create_collection_record(
471 "fin_journal_lines", {"id": "l-x", "journal_id": "j-nov", "account_id": "cash",
472 "credit_cents": "100", "owner_id": "dan"}, base_dir=data_dir))
473 refused(lambda: object_records.update_collection_record(
474 "fin_journal_lines", "l-nov", {"debit_cents": "1"}, base_dir=data_dir))
475 refused(lambda: object_records.update_collection_record( # moved to December
476 "fin_journal_lines", "l-nov", {"journal_id": "j-dec"}, base_dir=data_dir))
477 refused(lambda: object_records.delete_collection_record(
478 "fin_journal_lines", "l-nov", base_dir=data_dir))
479
480 # December is open, and other books are not bound by dan's close.
481 object_records.update_collection_record("fin_journals", "j-dec", {"description": "fine"},
482 base_dir=data_dir)
483 object_records.create_collection_record(
484 "fin_journals", journal_row("j-pat", "2026-11-29", owner_id="pat"), base_dir=data_dir)
485 # Nothing in November moved.
486 nov = object_records.get_collection_record("fin_journals", "j-nov", base_dir=data_dir)
487 assert (nov["date"], nov["description"]) == ("2026-11-10", "j-nov")
488
489
490def test_an_unreadable_period_list_refuses_the_write_and_the_composer(tmp_path, monkeypatch):
491 """Fail closed both places: the lock answers 503, and compose raises
492 rather than book a date it could not check."""
493 data_dir = books(tmp_path, monkeypatch)
494 path = object_records.collection_records_file("fin_closed_periods", base_dir=data_dir)
495 path.write_text("start_date\tend_date\n2026-11-01\t2026-11-30\n") # no id column
496 with pytest.raises(object_records.CheckRefusedError) as caught:
497 object_records.create_collection_record(
498 "fin_journals", journal_row("j1", "2026-12-05"), base_dir=data_dir)
499 assert caught.value.status == 503
500 with pytest.raises(Exception):
501 object_finance.compose_posted_journal(
502 data_dir, generated_from="x/1", date="2026-12-05", description="x",
503 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
504 "credit_cents": 5}],
505 owner_id="dan")
506 assert all_journals(data_dir) == []
507
508
509def test_consecutive_closed_periods_book_on_the_first_day_after_the_last(tmp_path, monkeypatch):
510 data_dir = books(tmp_path, monkeypatch)
511 close(data_dir, owner="dan")
512 close(data_dir, start="2026-12-01", end="2026-12-31", owner="dan", pid="cp-dec")
513 assert object_finance.next_open_date("2026-11-29", base_dir=data_dir, owner_id="dan")[0] \
514 == "2027-01-01"
515 result = object_finance.compose_posted_journal(
516 data_dir, generated_from="x/1", date="2026-11-29", description="late",
517 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
518 "credit_cents": 5}],
519 owner_id="dan")
520 journal = by_marker(data_dir, "x/1")
521 assert_redated(journal, occurred="2026-11-29", booked="2027-01-01")
522 assert [p["id"] for p in result["redated"]["closed_periods"]] == ["cp-nov", "cp-dec"]
523 assert "2026-11-01 to 2026-12-31" in journal["description"]
524
525
526def test_a_long_description_still_fits_with_its_note(tmp_path, monkeypatch):
527 data_dir = books(tmp_path, monkeypatch)
528 close(data_dir, owner="dan")
529 object_finance.compose_posted_journal(
530 data_dir, generated_from="x/1", date="2026-11-29", description="y" * 300,
531 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
532 "credit_cents": 5}],
533 owner_id="dan")
534 journal = by_marker(data_dir, "x/1")
535 assert len(journal["description"]) == 300
536 assert journal["description"].endswith("fell in closed period 2026-11-01 to 2026-11-30]")
537
538
539def close_in_flight(monkeypatch, data_dir, **period):
540 """Close a period the moment the first fin_journals header write
541 arrives at object_records -- after the composer looked and found the
542 date open, before the write lock."""
543 real = object_records.create_collection_record
544 state = {"armed": True}
545
546 def patched(collection, record, *args, **kwargs):
547 if collection == "fin_journals" and state["armed"]:
548 state["armed"] = False
549 worker = threading.Thread(target=lambda: close(data_dir, **period))
550 worker.start()
551 worker.join(timeout=20)
552 return real(collection, record, *args, **kwargs)
553
554 monkeypatch.setattr(object_records, "create_collection_record", patched)
555
556
557def test_a_period_closed_while_a_composer_is_in_flight_moves_the_entry_not_into_it(
558 tmp_path, monkeypatch):
559 """The composer looked, November was open; it closed before the header
560 landed. The locked check refuses the header and compose looks again."""
561 data_dir = books(tmp_path, monkeypatch)
562 close_in_flight(monkeypatch, data_dir, owner="dan")
563 result = object_finance.compose_posted_journal(
564 data_dir, generated_from="x/1", date="2026-11-29", description="racing",
565 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
566 "credit_cents": 5}],
567 owner_id="dan")
568 assert result["posted"] is True and result["redated"]["date"] == DEC_1
569 assert_redated(by_marker(data_dir, "x/1"), occurred="2026-11-29")
570 assert_nothing_in(data_dir)
571
572
573# --- over HTTP, the review flag, and reopening -----------------------------------
574
575
576AUTH = [("authorization", f"Token {TEST_ADMIN_TOKEN}")]
577
578
579def http(path, method="GET", body=None):
580 status, _, payload = request(path, method=method, headers=AUTH,
581 body=json.dumps(body).encode() if body is not None else b"")
582 return status, payload
583
584
585def http_books(tmp_path, monkeypatch):
586 data_dir = books(tmp_path, monkeypatch)
587 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(FINANCE / "objects"))
588 enable_admin_token(monkeypatch)
589 return data_dir
590
591
592def test_a_direct_http_journal_write_into_a_closed_month_is_still_refused(
593 tmp_path, monkeypatch):
594 data_dir = http_books(tmp_path, monkeypatch)
595 close(data_dir)
596 status, payload = http("/collections/fin_journals/records", "POST",
597 {"date": "2026-11-29", "description": "by hand"})
598 assert status == 409 and payload["code"] == "hook_rejected", payload
599 assert "are closed" in payload["error"]
600 status, payload = http("/collections/fin_journals/records", "POST",
601 {"date": "2026-12-02", "description": "by hand"})
602 assert status in (200, 201), payload
603 assert_nothing_in(data_dir)
604
605
606def test_the_review_flag_is_counted_and_clears_on_a_posted_journal(tmp_path, monkeypatch):
607 """The operator is told (attention), can look, and can say so -- on a
608 journal that is otherwise final."""
609 data_dir = http_books(tmp_path, monkeypatch)
610 close(data_dir)
611 result = object_finance.compose_posted_journal(
612 data_dir, generated_from="payments/p9", date="2026-11-29", description="Payment",
613 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
614 "credit_cents": 5}],
615 owner_id="dan")
616 journal_id = result["journal_id"]
617 assert shipped_count("app-finance", "journals_after_close", data_dir, ADMIN)["count"] == 1
618
619 status, payload = http(f"/collections/fin_journals/records/{journal_id}", "PUT",
620 {"description": "rewritten"})
621 assert status == 409, payload # still final
622 status, payload = http(f"/collections/fin_journals/records/{journal_id}", "PUT",
623 {"period_review": "reviewed"})
624 assert status == 200, payload
625 assert shipped_count("app-finance", "journals_after_close", data_dir, ADMIN)["count"] == 0
626 status, payload = http(f"/collections/fin_journals/records/{journal_id}", "PUT",
627 {"occurred_on": "2026-12-01"})
628 assert status >= 400 # read_only
629
630
631def test_reopening_a_period_lets_writes_and_composers_date_into_it_again(
632 tmp_path, monkeypatch):
633 """Reopening is deleting the row (an attributed act). After it, a hand
634 write and a composer both date into November normally; what was booked
635 in December while November was closed stays where it was (posted is
636 final), still flagged, so the reopening does not silently restate it."""
637 data_dir = http_books(tmp_path, monkeypatch)
638 close(data_dir)
639 moved = object_finance.compose_posted_journal(
640 data_dir, generated_from="payments/p1", date="2026-11-29", description="Payment",
641 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
642 "credit_cents": 5}],
643 owner_id="dan")
644 assert moved["redated"]["date"] == DEC_1
645
646 status, payload = http("/collections/fin_closed_periods/records/cp-nov", "DELETE")
647 assert status in (200, 204), payload
648
649 status, payload = http("/collections/fin_journals/records", "POST",
650 {"date": "2026-11-29", "description": "by hand"})
651 assert status in (200, 201), payload
652 natural = object_finance.compose_posted_journal(
653 data_dir, generated_from="payments/p2", date="2026-11-29", description="Payment",
654 lines=[{"account_id": "cash", "debit_cents": 5}, {"account_id": "cash",
655 "credit_cents": 5}],
656 owner_id="dan")
657 assert "redated" not in natural
658 assert by_marker(data_dir, "payments/p2")["date"] == "2026-11-29"
659 earlier = by_marker(data_dir, "payments/p1")
660 assert (earlier["date"], earlier["period_review"]) == (DEC_1, "pending")
661
662
663def test_the_schemas_declare_the_lock_for_every_writer():
664 """A hook is wired by the schema, and so is a locked check. Pinned so a
665 schema edit cannot quietly put the rule back in the HTTP-only hook."""
666 for name, reads in (("fin_journals", ["fin_closed_periods"]),
667 ("fin_journal_lines", ["fin_journals", "fin_closed_periods"])):
668 schema = json.loads((FINANCE / "schemas" / f"{name}.json").read_text())
669 [check] = schema["locked_checks"]
670 assert check["name"] == object_finance.PERIOD_CHECK
671 assert check["object"] == f"hook_{name}" and check["lock"] == "fin_periods"
672 assert sorted(check["reads"]) == sorted(reads)
673 assert check["on"] == {"create": True, "update": True, "delete": True}