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_findings_money_gates.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_findings_money_gates.py · 73.2 KB · 1487 lines
1"""Reproductions of suspected bugs in before-write GATES on money and stock.
2
3Source: config-inventory/hooks-actions.md (a read-only inventory: every
4entry there came from reading code, none from running it). This file is the
5running half. Nothing here is fixed and no existing file was changed.
6
7Convention, the same one tests/test_findings_actions.py and
8tests/test_findings_access_control.py use:
9
10 * every test asserts the CORRECT behaviour -- the invariant holds, or the
11 write is refused;
12 * a finding that is real is ``xfail(strict=True)``, so the suite is green
13 today and goes red the day the gate is fixed (delete the marker then);
14 * a finding that is refuted is a plain passing test pinning what protects
15 the path.
16
17An xfail that can fail for the wrong reason is worse than no test, so the
18xfails are declared ``raises=AssertionError`` and every PRECONDITION of a
19reproduction (the package installed, the user allowed in, the control write
20refused by the gate as it should be) goes through ``must``/``ok``, which
21raise ``SetupBroken`` instead. A missing dependency, a permission refusal
22before the gate, or a validation error on an unrelated field is therefore a
23loud failure, never a quiet xfail. Each xfail below was first run without
24its marker and seen to fail on its last assertion with the numbers quoted
25in its docstring.
26
27How the paths are driven:
28
29 * HTTP-path findings go through the real ASGI app in process, with the
30 real packages installed by ``object_packages.install_package``,
31 permission enforcement ON, and a signed-in NON-admin session (``ann``).
32 Sessions must send ``owner_id`` on create: the row-filtered rule is
33 checked before the server stamps it.
34 * app_settings is the one exception: no rule lets a signed-in user write
35 it, so its hook is only reachable with the admin token, and that is what
36 those tests use (the refusal for ``ann`` is pinned too).
37 * storage-level writers (auto top-up, gift-card issue, bank import) are
38 run as the real objects through ``object_execution.execute_object``.
39 * a race is made deterministic by running the second writer INSIDE a
40 patched call of the first, at the exact point between its check and its
41 write. For the HTTP races the second request runs on its own thread and
42 is joined, so a future fix that holds a lock across check+write makes
43 the test pass rather than deadlock.
44 * a failing read is simulated for ONE caller only: the patched reader
45 raises only when the named collection is read from the named file (the
46 gate's own read), so the write path's reads still work.
47"""
48
49import contextlib
50import json
51import pathlib
52import sys
53import threading
54from datetime import datetime, timezone
55from decimal import Decimal
56
57import pytest
58from conftest import stage_collection
59
60import object_execution
61import object_handlers
62import object_packages
63import object_records
64import object_server
65import object_stock
66import object_stripe
67import object_worker_pool
68import python_object_runtime
69from test_object_server import TEST_ADMIN_TOKEN, request as http_request
70
71REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
72PACKAGES = REPO_ROOT / "packages"
73RUNTIME = python_object_runtime.PythonObjectRuntime()
74ADMIN = [("authorization", f"Token {TEST_ADMIN_TOKEN}"), ("content-type", "application/json")]
75CREATED = (200, 201)
76
77
78class SetupBroken(Exception):
79 """A precondition of a reproduction did not hold. Deliberately NOT an
80 AssertionError, so ``xfail(raises=AssertionError)`` cannot swallow it."""
81
82
83def must(condition, detail):
84 if not condition:
85 raise SetupBroken(detail)
86
87
88def ok(result, what):
89 """The (status, body) of a write that has to succeed for the scenario."""
90 status, body = result
91 must(status in CREATED, f"{what}: expected success, got {status} {body}")
92 return body.get("record", body)
93
94
95def refused_by_hook(result, what, *, status, code="hook_rejected"):
96 """A control: the gate under test really does refuse this, here. `code`
97 names who refuses: the hook by default, or the declaration that replaced
98 the hook (unique_violation, record_locked, check_refused) -- None for the
99 plain validation answer, which carries no code."""
100 got, body = result
101 must(got == status and body.get("code") == code,
102 f"{what}: expected a {code} refusal with {status}, got {got} {body}")
103 return body
104
105
106@pytest.fixture(autouse=True)
107def fresh_handler_index():
108 """The handler index is a module global built from the object root in
109 force when it was first asked; every site here has its own root."""
110 object_handlers.invalidate()
111 yield
112 object_handlers.invalidate()
113
114
115# --- the site ------------------------------------------------------------------
116
117
118class Site:
119 def __init__(self, data, root):
120 self.data = data
121 self.root = root
122 self.headers = {}
123
124 def call(self, method, path, who, body=None, query=""):
125 headers = ADMIN if who == "admin" else self.headers[who]
126 status, _, payload = http_request(
127 path, method=method, query_string=query,
128 body=json.dumps(body).encode("utf-8") if body is not None else b"",
129 headers=list(headers))
130 return status, payload
131
132 def post(self, collection, who, record):
133 if who != "admin":
134 record = {"owner_id": who, **record}
135 return self.call("POST", f"/collections/{collection}/records", who, record)
136
137 def put(self, collection, record_id, who, changes):
138 return self.call("PUT", f"/collections/{collection}/records/{record_id}", who, changes)
139
140 def delete(self, collection, record_id, who):
141 return self.call("DELETE", f"/collections/{collection}/records/{record_id}", who)
142
143 def get(self, collection, record_id):
144 return object_records.get_collection_record(collection, record_id, base_dir=self.data)
145
146 def rows(self, collection, **where):
147 return [row for row in object_records.read_collection_records(collection, base_dir=self.data)
148 if all(row.get(k) == v for k, v in where.items())]
149
150 def exists(self, collection, record_id):
151 return any(row["id"] == record_id for row in self.rows(collection))
152
153
154def build_site(tmp_path, monkeypatch, packages, *, users=("ann",), roles=None, handlers=False):
155 """Real packages, enforcement on, one session per user. Objects run in
156 process (no timeout, no worker pool) so a narrow monkeypatch reaches the
157 hook the server actually runs."""
158 data = tmp_path / "data"
159 root = tmp_path / "objects"
160 root.mkdir()
161 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data))
162 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
163 monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TEST_ADMIN_TOKEN)
164 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
165 monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true")
166 monkeypatch.delenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, raising=False)
167 monkeypatch.delenv(object_worker_pool.WORKER_POOL_SIZE_ENV, raising=False)
168 if handlers:
169 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
170 else:
171 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV, raising=False)
172 for name in packages:
173 object_packages.install_package(name, root=PACKAGES, base_dir=data, object_roots=[root])
174 object_handlers.invalidate()
175
176 site = Site(data, root)
177 for user in users:
178 status, _, created = http_request(
179 "/identity/sessions", method="POST",
180 body=json.dumps({"user_id": user, "roles": list((roles or {}).get(user, []))}).encode(),
181 headers=list(ADMIN))
182 must(status == 201, f"session for {user}: {status} {created}")
183 site.headers[user] = [("authorization", f"Bearer {created['token']}"),
184 ("content-type", "application/json")]
185 status, identity = site.call("GET", "/identity", users[0])
186 must(status == 200 and identity["subject"]["user_id"] == users[0]
187 and identity["auth"]["method"] == "session_token"
188 and identity["permissions"]["enforcement_enabled"] is True,
189 f"not a signed-in non-admin session under enforcement: {identity}")
190 return site
191
192
193@contextlib.contextmanager
194def failing_reads(collection, caller_file):
195 """Make ONE caller's read of one collection raise, and nothing else.
196
197 Yields the list of function names the failure fired in, so a test can
198 insist the simulated failure actually happened inside the gate."""
199 real = object_records.read_collection_records
200 fired = []
201
202 def read(name, *args, **kwargs):
203 frame = sys._getframe(1)
204 if name == collection and frame.f_code.co_filename.endswith(caller_file):
205 fired.append(frame.f_code.co_name)
206 raise OSError(f"simulated: {collection} is unreadable")
207 return real(name, *args, **kwargs)
208
209 object_records.read_collection_records = read
210 try:
211 yield fired
212 finally:
213 object_records.read_collection_records = real
214
215
216def overlap_two_creates(monkeypatch, collection, first, second):
217 """Request A passes its hook; before A's persist, request B runs start
218 to finish; then A persists. Returns (A's result, B's result).
219
220 This is the window AGENTS.md names ("a BEFORE_WRITE hook runs before the
221 write lock"). B runs on its own thread and is joined with a timeout, so
222 if a fix ever holds a lock across hook+write B simply waits for A."""
223 real = object_records.create_collection_record
224 state = {"armed": True, "second": None, "thread": None}
225
226 def create(name, record, *args, **kwargs):
227 if name == collection and state["armed"]:
228 state["armed"] = False
229 worker = threading.Thread(target=lambda: state.__setitem__("second", second()))
230 state["thread"] = worker
231 worker.start()
232 worker.join(timeout=20)
233 return real(name, record, *args, **kwargs)
234
235 monkeypatch.setattr(object_records, "create_collection_record", create)
236 try:
237 first_result = first()
238 must(state["thread"] is not None, "request A never reached its persist: no overlap happened")
239 state["thread"].join(timeout=20)
240 finally:
241 monkeypatch.setattr(object_records, "create_collection_record", real)
242 must(state["second"] is not None, "request B never finished")
243 return first_result, state["second"]
244
245
246def run_object(object_id, payload, package, *, method="POST"):
247 return object_execution.execute_object(
248 RUNTIME,
249 object_execution.ObjectExecutionRequest(object_id, method=method, payload=payload),
250 roots=[PACKAGES / package / "objects"])
251
252
253# --- every gate under test is wired -------------------------------------------
254
255GATED = [
256 ("app-billing", "wallet_entries", "hook_wallet_entries"),
257 ("app-payments", "payments", "hook_payments"),
258 ("app-payments", "refunds", "hook_refunds"),
259 ("app-catalog", "stock_moves", "hook_stock_moves"),
260 ("app-timers", "time_logs", "hook_time_logs"),
261 ("app-finance", "fin_journals", "hook_fin_journals"),
262 ("app-finance", "fin_journal_lines", "hook_fin_journal_lines"),
263 ("app-receiving", "receipt_lines", "hook_receipt_lines"),
264 ("app-shipping", "shipment_lines", "hook_shipment_lines"),
265 ("app-banking", "bank_lines", "hook_bank_lines"),
266]
267
268# Gates that became declarations. Their hook is gone, so the claim "it is
269# wired" is now "it is declared": a schema key object_records checks inside
270# the write lock for every writer.
271DECLARED = [
272 ("app-intake", "scans", "unique"),
273 ("app-intake", "scans", "locked_when"),
274 ("app-settings", "app_settings", "unique"),
275 ("app-billing", "wallets", "unique"),
276 ("app-billing", "usage_events", "unique"),
277]
278
279
280@pytest.mark.parametrize("package,collection,key", DECLARED)
281def test_the_gate_that_became_a_declaration_is_declared(package, collection, key):
282 schema = json.loads((PACKAGES / package / "schemas" / f"{collection}.json").read_text())
283 assert schema.get(key), f"{collection} no longer declares {key}"
284 assert "hooks" not in schema, f"{collection} still names a hook"
285
286
287@pytest.mark.parametrize("package,collection,hook", GATED)
288def test_the_gate_is_declared_by_its_schema(package, collection, hook):
289 """AGENTS.md: a hook is wired by the SCHEMA, not by its name. Every
290 finding below is about a gate that DOES run on create; this pins that,
291 so none of the xfails can be explained away as an unwired hook. (The
292 inventory found no such assertion for eleven of these.)"""
293 schema = json.loads((PACKAGES / package / "schemas" / f"{collection}.json").read_text())
294 assert schema.get("hooks", {}).get("before_write") == hook
295
296
297# =============================================================================
298# 1. hook_wallet_entries does not protect the writers it was written for
299# =============================================================================
300
301def wallet_env(tmp_path, monkeypatch):
302 data = tmp_path / "data"
303 for package, name in (("app-billing", "wallets"), ("app-billing", "wallet_entries"),
304 ("app-settings", "app_settings"), ("app-catalog", "products"),
305 ("app-orders", "orders"), ("app-orders", "order_lines"),
306 ("app-invoices", "invoices"), ("app-payments", "payments"),
307 ("app-payments", "refunds")):
308 stage_collection(data, package, name)
309 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data))
310 return data
311
312
313def ledger(data, **where):
314 return [row for row in object_records.read_collection_records("wallet_entries", base_dir=data)
315 if all(row.get(k) == v for k, v in where.items())]
316
317
318def test_two_overlapping_auto_topups_credit_the_wallet_once(tmp_path, monkeypatch):
319 """The exact scenario hook_wallet_entries' docstring gives as the reason
320 for its Rule 2 ("two overlapping passes both find no marker and both
321 credit the wallet"), run through the REAL replenisher instead of by
322 calling the hook by hand as tests/test_wallet.py does.
323
324 Pass A reads the ledger and reaches Stripe; pass B runs start to finish
325 while A is waiting on Stripe; A then writes. Stripe sees ONE idempotency
326 key and charges the card once (500). Seen today: two auto_topup entries
327 carrying the same generated_from, balance_minor 1000 -- the customer has
328 500 the shop was never paid."""
329 data = wallet_env(tmp_path, monkeypatch)
330 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test")
331 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_test")
332 object_records.create_collection_record("wallets", {
333 "id": "w1", "owner_id": "dan", "is_active": "true",
334 "auto_replenish_enabled": "true", "auto_replenish_threshold_minor": "1000",
335 "auto_replenish_amount_minor": "500", "auto_replenish_monthly_cap_minor": "10000",
336 "stripe_customer_id": "cus_1", "payment_method_ref": "pm_1"}, base_dir=data)
337 # created_at decides the cap month and no caller can set it: run in the
338 # month the records will actually carry (see tests/test_wallet.py).
339 today = datetime.now(timezone.utc).strftime("%Y-%m") + "-25"
340
341 charges = {} # Stripe's view: one intent per idempotency key
342 state = {"nested": False, "inner": None}
343
344 def stripe(config, method, path, params=None, **kwargs):
345 key = kwargs.get("idempotency_key")
346 intent = charges.setdefault(key, {"id": f"pi_{len(charges) + 1}", "amount": params["amount"]})
347 if not state["nested"]:
348 state["nested"] = True
349 state["inner"] = run_object("system_wallet_replenish", {"today": today}, "app-billing")
350 return intent
351
352 monkeypatch.setattr(object_stripe, "api_request", stripe)
353 run_object("system_wallet_replenish", {"today": today}, "app-billing")
354
355 inner = state["inner"]
356 must(inner is not None and inner.ok and inner.result.get("charged") == 1,
357 f"the overlapping pass did not charge: {inner and inner.result}")
358 must(len(charges) == 1, f"expected ONE card charge (one idempotency key), got {charges}")
359 charged = sum(intent["amount"] for intent in charges.values())
360 must(charged == 500, f"card charged {charged}")
361
362 credited = sum(int(row["amount_minor"]) for row in ledger(data, wallet_id="w1"))
363 markers = [row["generated_from"] for row in ledger(data, wallet_id="w1")]
364 assert credited == charged, (
365 f"card charged {charged} once, wallet credited {credited} "
366 f"across {len(markers)} entries with markers {markers}")
367
368
369def test_two_overlapping_payment_events_issue_one_gift_card(tmp_path, monkeypatch):
370 """gift_card_issue says "credits are never gated by hook_wallet_entries".
371 That stopped being true when the marker rule arrived, and the handler
372 HANDLES both payments.record.created and .updated, so two deliveries for
373 one payment are ordinary. Delivery B is run at the point delivery A has
374 read the ledger (no marker) and is about to open its wallet.
375
376 Seen today: two gift_card wallets, each with a 5000 top-up carrying the
377 same marker gift_card/ol1 -- 10000 of spendable credit for one 5000
378 sale."""
379 data = wallet_env(tmp_path, monkeypatch)
380 make = lambda collection, record: object_records.create_collection_record(
381 collection, record, base_dir=data)
382 make("products", {"id": "gc", "name": "Gift Card $50", "price_cents": "5000",
383 "is_gift_card": "true", "product_type": "digital", "owner_id": "shop"})
384 make("invoices", {"id": "inv1", "number": "INV-1", "customer_name": "Ada",
385 "total_cents": "5000", "status": "sent", "owner_id": "shop"})
386 make("orders", {"id": "o1", "number": "SO-1", "customer_name": "Ada",
387 "invoice_id": "inv1", "owner_id": "shop"})
388 make("order_lines", {"id": "ol1", "order_id": "o1", "product_id": "gc",
389 "description": "Gift Card $50", "quantity": "1",
390 "unit_price_cents": "5000", "line_total_cents": "5000",
391 "owner_id": "shop"})
392 payment = make("payments", {"id": "pay1", "invoice_id": "inv1", "amount_cents": "5000",
393 "method": "card", "received_on": "2026-07-24",
394 "status": "received", "owner_id": "shop"})
395 event = {"event": "payments.record.created", "collection": "payments",
396 "record_id": "pay1", "action": "create", "record": payment}
397
398 real = object_records.create_collection_record
399 state = {"nested": False, "inner": None}
400
401 def create(collection, record, *args, **kwargs):
402 if collection == "wallets" and not state["nested"]:
403 state["nested"] = True
404 state["inner"] = run_object("system_gift_card_issue", dict(event),
405 "app-billing", method="EVENT")
406 return real(collection, record, *args, **kwargs)
407
408 monkeypatch.setattr(object_records, "create_collection_record", create)
409 run_object("system_gift_card_issue", dict(event), "app-billing", method="EVENT")
410 monkeypatch.setattr(object_records, "create_collection_record", real)
411
412 inner = state["inner"]
413 must(inner is not None and inner.ok and inner.result.get("issued") == 1,
414 f"the overlapping delivery issued nothing: {inner and inner.result}")
415
416 issued = ledger(data, generated_from="gift_card/ol1")
417 credit = sum(int(row["amount_minor"]) for row in issued)
418 assert credit == 5000, (
419 f"one 5000 gift card was sold; {len(issued)} top-ups totalling {credit} "
420 f"carry the marker gift_card/ol1")
421
422
423def test_a_signed_in_user_cannot_write_the_wallet_ledger_and_the_marker_gate_holds_over_http(
424 tmp_path, monkeypatch):
425 """REFUTES the HTTP half of finding 1, and is the control for the two
426 tests above: over HTTP the ledger is closed to a signed-in user by the
427 permission rule (read only), and for the one principal that can write
428 it there -- the admin token -- the used-once marker rule does run and
429 does refuse. The gate works; the storage-level writers just never ask
430 it.
431
432 Overdraft through the two named writers is refuted by construction, not
433 by a test: both write strictly positive amounts (wallet_replenish.py
434 skips amount <= 0, gift_card_issue.py skips line totals <= 0)."""
435 site = build_site(tmp_path, monkeypatch,
436 ["app-views", "app-settings", "app-entities", "app-finance",
437 "app-invoices", "app-payments", "app-billing"])
438 object_records.create_collection_record(
439 "wallets", {"id": "w1", "owner_id": "ann", "is_active": "true"}, base_dir=site.data)
440
441 status, body = site.post("wallet_entries", "ann", {
442 "id": "e-self", "wallet_id": "w1", "amount_minor": "999999", "kind": "topup"})
443 assert status == 403 and body.get("code") == "forbidden", (status, body)
444 assert site.rows("wallet_entries") == []
445
446 credit = {"wallet_id": "w1", "amount_minor": "500", "kind": "auto_topup",
447 "generated_from": "auto_topup/w1/2026-07/500", "owner_id": "ann"}
448 ok(site.post("wallet_entries", "admin", {"id": "e1", **credit}), "first credit")
449 status, body = site.post("wallet_entries", "admin", {"id": "e2", **credit})
450 assert status == 409 and body.get("code") == "unique_violation", (status, body)
451 assert "already been posted" in body["error"]
452
453 status, body = site.post("wallet_entries", "admin", {
454 "id": "e3", "wallet_id": "w1", "amount_minor": "-501", "kind": "debit", "owner_id": "ann"})
455 assert status == 402 and "Insufficient wallet balance" in body["error"], (status, body)
456 assert [row["id"] for row in site.rows("wallet_entries")] == ["e1"]
457
458
459# =============================================================================
460# 2. gates run on CREATE only, but the owner may UPDATE and DELETE
461# =============================================================================
462
463def payments_site(tmp_path, monkeypatch):
464 """One invoice whose only line is 10000, total stamped by the real
465 invoice_totals handler (handlers on, as any box taking payments runs).
466
467 ann is the business's billing clerk, so she holds role:manager: since
468 app-invoices 0.15.0 an invoice's amounts and status are staff fields (a
469 machine-raised invoice's owner is the customer it bills). She is still
470 not an admin, which is what every gate below distinguishes."""
471 site = build_site(tmp_path, monkeypatch,
472 ["app-views", "app-settings", "app-invoices", "app-payments"],
473 roles={"ann": ["manager"]}, handlers=True)
474 ok(site.post("invoices", "ann", {"id": "inv1", "number": "INV-1", "customer_name": "Acme"}),
475 "invoice")
476 ok(site.post("invoice_lines", "ann", {"id": "l1", "invoice_id": "inv1", "description": "work",
477 "quantity": "1", "unit_price_cents": "10000"}), "line")
478 must(site.get("invoices", "inv1")["total_cents"] == "10000",
479 f"invoice_totals did not stamp the total: {site.get('invoices', 'inv1')}")
480 return site
481
482
483def pay(site, payment_id, amount, invoice_id="inv1"):
484 return site.post("payments", "ann", {"id": payment_id, "invoice_id": invoice_id,
485 "amount_cents": str(amount), "received_on": "2026-07-24"})
486
487
488def refund(site, refund_id, payment_id, amount):
489 return site.post("refunds", "ann", {"id": refund_id, "payment_id": payment_id,
490 "amount_cents": str(amount), "refunded_on": "2026-07-25"})
491
492
493def net_received(site, invoice_id="inv1"):
494 received = sum(int(row["amount_cents"]) for row in site.rows("payments", invoice_id=invoice_id)
495 if (row.get("status") or "received") == "received")
496 refunded = sum(int(row["amount_cents"]) for row in site.rows("refunds", invoice_id=invoice_id))
497 return received - refunded
498
499
500def test_a_payment_cannot_be_raised_past_the_invoice_total_after_it_is_recorded(tmp_path, monkeypatch):
501 """ann records 9000 against a 10000 invoice. A second payment of 2000 is
502 refused by the overpayment gate (409, "remaining balance of 1000") --
503 the control. She then PUTs amount_cents=50000 on the first payment.
504
505 Seen today: 200; payments_received_cents 50000 on a total of 10000,
506 balance_due_cents -40000."""
507 site = payments_site(tmp_path, monkeypatch)
508 ok(pay(site, "p1", 9000), "first payment")
509 refused_by_hook(pay(site, "p2", 2000), "overpayment on create", status=409,
510 code="check_refused")
511
512 status, _ = site.put("payments", "p1", "ann", {"amount_cents": "50000"})
513
514 invoice = site.get("invoices", "inv1")
515 assert net_received(site) <= 10000, (
516 f"PUT answered {status}: {net_received(site)} cents now recorded against a "
517 f"10000 invoice (balance_due_cents {invoice['balance_due_cents']})")
518
519
520def test_a_refund_cannot_be_raised_past_its_payment_after_it_is_recorded(tmp_path, monkeypatch):
521 """Payment 10000, refund 4000. A further refund of 7000 is refused (409,
522 "exceeds the refundable 6000") -- the control. ann then PUTs
523 amount_cents=25000 on the existing refund.
524
525 Seen today: 200; payments.refunded_cents 25000 on a 10000 payment and the
526 invoice's amount_paid_cents -15000."""
527 site = payments_site(tmp_path, monkeypatch)
528 ok(pay(site, "p1", 10000), "payment")
529 ok(refund(site, "r1", "p1", 4000), "refund")
530 refused_by_hook(refund(site, "r2", "p1", 7000), "over-refund on create", status=409)
531
532 status, _ = site.put("refunds", "r1", "ann", {"amount_cents": "25000"})
533
534 refunded = sum(int(row["amount_cents"]) for row in site.rows("refunds", payment_id="p1"))
535 assert refunded <= 10000, (
536 f"PUT answered {status}: {refunded} cents refunded against a 10000 payment "
537 f"(invoice amount_paid_cents {site.get('invoices', 'inv1')['amount_paid_cents']})")
538
539
540def test_a_payment_cannot_be_lowered_below_what_was_already_refunded(tmp_path, monkeypatch):
541 """The same invariant broken from the other side, so fixing hook_refunds
542 alone would not close it. Payment 10000, refunded in full, then the
543 payment's amount_cents is PUT to 100.
544
545 Seen today: 200; a 100 payment carrying refunded_cents 10000, invoice
546 amount_paid_cents -9900 and balance_due_cents 19900 on a 10000 invoice."""
547 site = payments_site(tmp_path, monkeypatch)
548 ok(pay(site, "p1", 10000), "payment")
549 ok(refund(site, "r1", "p1", 10000), "refund")
550
551 status, _ = site.put("payments", "p1", "ann", {"amount_cents": "100"})
552
553 paid = int(site.get("payments", "p1")["amount_cents"])
554 refunded = sum(int(row["amount_cents"]) for row in site.rows("refunds", payment_id="p1"))
555 assert refunded <= paid, (
556 f"PUT answered {status}: {refunded} refunded against a payment now worth {paid} "
557 f"(invoice balance_due_cents {site.get('invoices', 'inv1')['balance_due_cents']})")
558
559
560def test_a_refund_cannot_be_edited_to_a_negative_amount(tmp_path, monkeypatch):
561 """A refund of -5 is refused on create (400, "must be a positive number
562 of cents") -- the control. ann refunds 100 of a 10000 payment, then PUTs
563 amount_cents=-999999 on that refund.
564
565 Seen today: 200; the invoice reads refunded_cents -999999 and
566 amount_paid_cents 1009999 on 10000 actually received."""
567 site = payments_site(tmp_path, monkeypatch)
568 ok(pay(site, "p1", 10000), "payment")
569 refused_by_hook(refund(site, "r0", "p1", -5), "negative refund on create", status=400,
570 code=None)
571 ok(refund(site, "r1", "p1", 100), "refund")
572
573 status, _ = site.put("refunds", "r1", "ann", {"amount_cents": "-999999"})
574
575 stored = int(site.get("refunds", "r1")["amount_cents"])
576 assert stored > 0, (
577 f"PUT answered {status}: refund r1 now reads {stored}; invoice amount_paid_cents "
578 f"{site.get('invoices', 'inv1')['amount_paid_cents']} on 10000 received")
579
580
581def test_a_refund_cannot_be_repointed_at_another_invoice(tmp_path, monkeypatch):
582 """The hook's own words: invoice_id "always comes from the payment,
583 never the client ... the pointer can never disagree with the payment it
584 compensates". On create that holds (a client-sent invoice_id is
585 overwritten -- the control). ann then PUTs invoice_id=inv2 on a refund
586 of a payment against inv1.
587
588 Seen today: 200; the 4000 refund is rolled up on inv2 (which was never
589 paid: amount_paid_cents -4000) and no longer on inv1."""
590 site = payments_site(tmp_path, monkeypatch)
591 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Other"}),
592 "second invoice")
593 ok(pay(site, "p1", 10000), "payment")
594 created = ok(site.post("refunds", "ann", {"id": "r1", "payment_id": "p1", "invoice_id": "inv2",
595 "amount_cents": "4000", "refunded_on": "2026-07-25"}),
596 "refund")
597 must(created["invoice_id"] == "inv1", f"the create-time stamp did not hold: {created}")
598
599 status, _ = site.put("refunds", "r1", "ann", {"invoice_id": "inv2"})
600
601 stored = site.get("refunds", "r1")["invoice_id"]
602 assert stored == "inv1", (
603 f"PUT answered {status}: the refund of payment p1 (invoice inv1) now points at "
604 f"{stored}; inv2 amount_paid_cents {site.get('invoices', 'inv2')['amount_paid_cents']}")
605
606
607def test_deleting_a_refund_does_not_reopen_its_headroom(tmp_path, monkeypatch):
608 """Payment 10000, refunded in full. One more cent is refused (409) -- the
609 control. ann DELETEs the refund, then refunds 10000 again.
610
611 Seen today: DELETE 200, second refund 201. Two refunds of 10000 were
612 accepted against one 10000 payment and only the second is on file;
613 doctrine #3 says money never mutates, it moves."""
614 site = payments_site(tmp_path, monkeypatch)
615 ok(pay(site, "p1", 10000), "payment")
616 ok(refund(site, "r1", "p1", 10000), "full refund")
617 refused_by_hook(refund(site, "r2", "p1", 1), "refund past the payment", status=409)
618
619 deleted, _ = site.delete("refunds", "r1", "ann")
620 again, _ = refund(site, "r3", "p1", 10000)
621
622 accepted = 10000 + (10000 if again in CREATED else 0)
623 assert accepted <= 10000 and site.exists("refunds", "r1"), (
624 f"DELETE answered {deleted}, the second full refund answered {again}: {accepted} "
625 f"cents of refunds accepted against a 10000 payment; on file: "
626 f"{[(r['id'], r['amount_cents']) for r in site.rows('refunds')]}")
627
628
629def test_a_refunded_payment_cannot_be_deleted_out_from_under_its_refund(tmp_path, monkeypatch):
630 """Payment 10000 with a 4000 refund; ann DELETEs the payment.
631
632 Seen today: 200. The refund stays, pointing at a payment that no longer
633 exists; the invoice shows payments_received_cents 0, refunded_cents
634 4000, amount_paid_cents -4000, balance_due_cents 14000 on a 10000
635 invoice."""
636 site = payments_site(tmp_path, monkeypatch)
637 ok(pay(site, "p1", 10000), "payment")
638 ok(refund(site, "r1", "p1", 4000), "refund")
639
640 status, _ = site.delete("payments", "p1", "ann")
641
642 orphans = [row["id"] for row in site.rows("refunds") if not site.exists("payments", row["payment_id"])]
643 invoice = site.get("invoices", "inv1")
644 assert orphans == [], (
645 f"DELETE answered {status}: refunds {orphans} point at a deleted payment; invoice "
646 f"amount_paid_cents {invoice['amount_paid_cents']}, "
647 f"balance_due_cents {invoice['balance_due_cents']}")
648
649
650def stock_site(tmp_path, monkeypatch):
651 site = build_site(tmp_path, monkeypatch,
652 ["app-views", "app-settings", "app-entities", "app-catalog"])
653 ok(site.post("products", "ann", {"id": "mug", "name": "Mug", "cost_cents": "500"}), "product")
654 ok(site.post("locations", "ann", {"id": "shelf", "name": "Shelf"}), "location")
655 return site
656
657
658def move(site, move_id, **fields):
659 return site.post("stock_moves", "ann", {"id": move_id, "product_id": "mug", **fields})
660
661
662def on_hand(site):
663 return object_stock.total_quantity("mug", base_dir=site.data)
664
665
666def test_a_stock_move_cannot_be_edited_to_a_negative_quantity(tmp_path, monkeypatch):
667 """Creating a move of -5 is refused (400, "must be positive") -- the
668 control. ann creates a purchase of 10 and PUTs quantity=-1000.
669
670 Seen today: 200; the stored move reads -1000 and on-hand for the product
671 goes from 10 to -1000 with no compensating move."""
672 site = stock_site(tmp_path, monkeypatch)
673 refused_by_hook(move(site, "m0", to_location_id="shelf", quantity="-5", reason="purchase"),
674 "negative quantity on create", status=400, code=None)
675 ok(move(site, "m1", to_location_id="shelf", quantity="10", reason="purchase"), "purchase")
676 must(on_hand(site) == 10, f"on hand {on_hand(site)}")
677
678 status, _ = site.put("stock_moves", "m1", "ann", {"quantity": "-1000"})
679
680 stored = Decimal(site.get("stock_moves", "m1")["quantity"])
681 assert stored > 0, f"PUT answered {status}: move m1 now reads {stored}, on hand {on_hand(site)}"
682
683
684def test_a_loss_move_cannot_be_edited_into_a_shelf(tmp_path, monkeypatch):
685 """A waste move with a destination is refused on create (400, "cannot
686 have a destination") -- the control. ann wastes 1 mug from the shelf,
687 then PUTs to_location_id=shelf and clears from_location_id.
688
689 Seen today: 200; on hand goes 10 -> 9 -> 11: the written-off mug and one
690 more are back on the shelf, booked as waste."""
691 site = stock_site(tmp_path, monkeypatch)
692 ok(move(site, "m1", to_location_id="shelf", quantity="10", reason="purchase"), "purchase")
693 refused_by_hook(move(site, "m0", from_location_id="shelf", to_location_id="shelf",
694 quantity="1", reason="waste"),
695 "waste into a shelf on create", status=400)
696 ok(move(site, "m2", from_location_id="shelf", quantity="1", reason="waste"), "waste")
697 must(on_hand(site) == 9, f"on hand {on_hand(site)}")
698
699 status, _ = site.put("stock_moves", "m2", "ann",
700 {"to_location_id": "shelf", "from_location_id": ""})
701
702 stored = site.get("stock_moves", "m2")
703 assert stored["from_location_id"] == "shelf" and stored["to_location_id"] == "", (
704 f"PUT answered {status}: waste move m2 now runs from "
705 f"{stored['from_location_id']!r} to {stored['to_location_id']!r}, on hand {on_hand(site)}")
706
707
708def test_a_stock_move_cannot_be_deleted(tmp_path, monkeypatch):
709 """Stock levels ARE the moves (AGENTS.md), and corrections are new
710 compensating moves (the hook's own refusal text). ann DELETEs a purchase
711 of 10.
712
713 Seen today: 200; on hand 10 -> 0 and the ledger is empty."""
714 site = stock_site(tmp_path, monkeypatch)
715 ok(move(site, "m1", to_location_id="shelf", quantity="10", reason="purchase"), "purchase")
716
717 status, _ = site.delete("stock_moves", "m1", "ann")
718
719 assert site.exists("stock_moves", "m1"), (
720 f"DELETE answered {status}: the move is gone and on hand is {on_hand(site)}")
721
722
723def timers_site(tmp_path, monkeypatch):
724 """ann logs two billable hours, submits them, and bob (a manager, so not
725 the owner) approves at the 12000/hour card: 24000 cents stamped."""
726 site = build_site(tmp_path, monkeypatch,
727 ["app-views", "app-projects", "app-tasks", "app-timers"],
728 users=("ann", "bob"), roles={"bob": ["manager"]})
729 ok(site.post("rate_cards", "bob", {"id": "rc1", "label": "Standard",
730 "hourly_rate_cents": "12000", "valid_from": "2026-01-01"}),
731 "rate card")
732 ok(site.post("time_logs", "ann", {"id": "t1", "started_at": "2026-07-01T09:00:00Z",
733 "ended_at": "2026-07-01T11:00:00Z",
734 "duration_seconds": "7200", "billable": "true"}), "time log")
735 ok(site.put("time_logs", "t1", "ann", {"status": "submitted"}), "submit")
736 approved = ok(site.put("time_logs", "t1", "bob", {"status": "approved"}), "approve")
737 must(approved["status"] == "approved" and approved["amount_cents"] == "24000"
738 and approved["approved_by"] == "bob", f"not approved as expected: {approved}")
739 return site
740
741
742def test_an_approved_time_log_cannot_be_deleted_by_its_owner(tmp_path, monkeypatch):
743 """Editing the approved entry is refused (409, "its record of what
744 happened is settled") -- the control. ann then DELETEs it.
745
746 Seen today: 200; the approved, rated 24000-cent entry and bob's approval
747 stamp are gone."""
748 site = timers_site(tmp_path, monkeypatch)
749 refused_by_hook(site.put("time_logs", "t1", "ann", {"duration_seconds": "72000"}),
750 "editing approved time", status=409, code="record_locked")
751
752 status, _ = site.delete("time_logs", "t1", "ann")
753
754 assert site.exists("time_logs", "t1"), f"DELETE answered {status}: the approved entry is gone"
755
756
757def test_a_billed_time_log_cannot_be_deleted_by_its_owner(tmp_path, monkeypatch):
758 """The entry is moved approved -> billed the way the invoice generator
759 does it (a storage-level write). Reopening it is refused by the hook
760 (409, "Billed time cannot be reopened") -- the control. ann DELETEs it.
761
762 Seen today: 200; the invoice line it produced has no time entry behind
763 it."""
764 site = timers_site(tmp_path, monkeypatch)
765 object_records.update_collection_record("time_logs", "t1", {"status": "billed"},
766 base_dir=site.data, actor="generate_tm_invoice")
767 must(site.get("time_logs", "t1")["status"] == "billed", "not billed")
768 refused_by_hook(site.put("time_logs", "t1", "bob", {"status": "rejected"}),
769 "reopening billed time", status=400, code=None)
770
771 status, _ = site.delete("time_logs", "t1", "ann")
772
773 assert site.exists("time_logs", "t1"), f"DELETE answered {status}: the billed entry is gone"
774
775
776def books_site(tmp_path, monkeypatch, *, extra=()):
777 # ann keeps the books: the chart and the journals are role:finance's
778 # and role:owner's since decision 5 (2026-11-30), not every user's.
779 site = build_site(tmp_path, monkeypatch,
780 ["app-views", "app-settings", "app-entities", "app-finance", *extra],
781 roles={"ann": ["finance"]})
782 for account, kind in (("cash", "asset"), ("revenue", "income")):
783 ok(site.post("fin_accounts", "ann", {"id": account, "name": account, "account_type": kind}),
784 account)
785 return site
786
787
788def journal(site, journal_id, date, *, post=True):
789 """A balanced 10000/10000 journal, posted through the real transition
790 (so hook_fin_journals' balance gate has passed it)."""
791 ok(site.post("fin_journals", "ann", {"id": journal_id, "date": date, "description": "sale"}),
792 "journal")
793 ok(site.post("fin_journal_lines", "ann", {"id": f"{journal_id}-dr", "journal_id": journal_id,
794 "account_id": "cash", "debit_cents": "10000"}), "debit")
795 ok(site.post("fin_journal_lines", "ann", {"id": f"{journal_id}-cr", "journal_id": journal_id,
796 "account_id": "revenue", "credit_cents": "10000"}),
797 "credit")
798 if post:
799 ok(site.put("fin_journals", journal_id, "ann", {"status": "posted"}), "post")
800 must(site.get("fin_journals", journal_id)["status"] == "posted", "not posted")
801
802
803def totals(site, journal_id):
804 lines = site.rows("fin_journal_lines", journal_id=journal_id)
805 return (sum(int(line["debit_cents"] or 0) for line in lines),
806 sum(int(line["credit_cents"] or 0) for line in lines))
807
808
809def test_a_line_of_a_posted_journal_cannot_be_deleted(tmp_path, monkeypatch):
810 """Seen today: DELETE 200; the posted journal reads debit 10000, credit
811 0, still status posted."""
812 site = books_site(tmp_path, monkeypatch)
813 journal(site, "j1", "2026-03-10")
814
815 status, _ = site.delete("fin_journal_lines", "j1-cr", "ann")
816
817 debit, credit = totals(site, "j1")
818 assert (debit, credit) == (10000, 10000), (
819 f"DELETE answered {status}: posted journal j1 is now debit {debit} / credit {credit}")
820
821
822def test_a_posted_journal_cannot_be_deleted(tmp_path, monkeypatch):
823 """Un-posting is refused by the schema transition (posted has no way
824 out) -- the control, and proof the design means posted to be final. ann
825 DELETEs the posted journal instead.
826
827 Seen today: 200; the journal is gone and its two lines remain, pointing
828 at nothing."""
829 site = books_site(tmp_path, monkeypatch)
830 journal(site, "j1", "2026-03-10")
831 status, body = site.put("fin_journals", "j1", "ann", {"status": "draft"})
832 must(status == 400 and "cannot move from 'posted' to 'draft'" in body.get("error", ""),
833 f"un-posting was not refused by the transition: {status} {body}")
834
835 status, _ = site.delete("fin_journals", "j1", "ann")
836
837 assert site.exists("fin_journals", "j1"), (
838 f"DELETE answered {status}: the posted journal is gone, "
839 f"{len(site.rows('fin_journal_lines', journal_id='j1'))} lines still reference it")
840
841
842def test_a_posted_journal_header_cannot_be_edited(tmp_path, monkeypatch):
843 """logic-decisions #3: "journals (posted = immutable + reversals)". ann
844 PUTs a new date and description on a posted journal; neither date is in
845 a closed period.
846
847 Seen today: 200; the posted journal moves from 2026-03-10 to 2026-01-05,
848 i.e. into another month's figures."""
849 site = books_site(tmp_path, monkeypatch)
850 journal(site, "j1", "2026-03-10")
851
852 status, _ = site.put("fin_journals", "j1", "ann",
853 {"date": "2026-01-05", "description": "something else"})
854
855 stored = site.get("fin_journals", "j1")
856 assert (stored["date"], stored["description"]) == ("2026-03-10", "sale"), (
857 f"PUT answered {status}: posted journal is now dated {stored['date']} "
858 f"and described {stored['description']!r}")
859
860
861# =============================================================================
862# 3. hook_fin_journal_lines never asks whether the parent journal is posted,
863# and reads only the candidate's journal_id
864# =============================================================================
865
866def test_a_line_of_a_posted_journal_cannot_be_edited(tmp_path, monkeypatch):
867 """Balance is checked once, on draft -> posted. Afterwards ann PUTs
868 debit_cents=1 on the debit line.
869
870 Seen today: 200; the posted journal's rollups read debit_total_cents 1,
871 credit_total_cents 10000."""
872 site = books_site(tmp_path, monkeypatch)
873 journal(site, "j1", "2026-03-10")
874
875 status, _ = site.put("fin_journal_lines", "j1-dr", "ann", {"debit_cents": "1"})
876
877 debit, credit = totals(site, "j1")
878 assert debit == credit == 10000, (
879 f"PUT answered {status}: posted journal j1 is now debit {debit} / credit {credit}")
880
881
882def test_a_line_cannot_be_added_to_a_posted_journal(tmp_path, monkeypatch):
883 """Seen today: 201; the posted journal reads debit 10777, credit 10000."""
884 site = books_site(tmp_path, monkeypatch)
885 journal(site, "j1", "2026-03-10")
886
887 status, _ = site.post("fin_journal_lines", "ann", {
888 "id": "j1-extra", "journal_id": "j1", "account_id": "cash", "debit_cents": "777"})
889
890 debit, credit = totals(site, "j1")
891 assert debit == credit == 10000, (
892 f"POST answered {status}: posted journal j1 is now debit {debit} / credit {credit}")
893
894
895def closed_year(site):
896 """A posted, balanced journal dated 2025-06-10, an open draft journal in
897 2026, and FY2025 closed. Editing a 2025 line in place is refused."""
898 journal(site, "j2025", "2025-06-10")
899 ok(site.post("fin_journals", "ann", {"id": "j2026", "date": "2026-06-10",
900 "description": "this year"}), "open journal")
901 ok(site.post("fin_closed_periods", "ann", {"id": "fy2025", "start_date": "2025-01-01",
902 "end_date": "2025-12-31",
903 "reason": "FY2025 filed"}), "close FY2025")
904 refused_by_hook(site.put("fin_journal_lines", "j2025-dr", "ann", {"debit_cents": "1"}),
905 "editing a closed-period line in place", status=409)
906 refused_by_hook(site.post("fin_journal_lines", "ann", {
907 "id": "late", "journal_id": "j2025", "account_id": "cash", "debit_cents": "5"}),
908 "adding a line to a closed-period journal", status=409)
909
910
911def test_a_line_cannot_be_moved_out_of_a_closed_period_journal(tmp_path, monkeypatch):
912 """Editing the 2025 line's amount is refused, adding a 2025 line is
913 refused (both 409) -- the controls, inside closed_year. ann instead PUTs
914 journal_id=j2026 on the 2025 debit line: the hook looks up the NEW
915 parent, finds it in an open period, and passes.
916
917 Seen today: 200; the filed year's journal reads debit 0 / credit 10000
918 and the 10000 debit now sits in 2026."""
919 site = books_site(tmp_path, monkeypatch)
920 closed_year(site)
921
922 status, _ = site.put("fin_journal_lines", "j2025-dr", "ann", {"journal_id": "j2026"})
923
924 debit, credit = totals(site, "j2025")
925 assert (debit, credit) == (10000, 10000), (
926 f"PUT answered {status}: closed-period journal j2025 is now debit {debit} / "
927 f"credit {credit}; j2026 holds {totals(site, 'j2026')}")
928
929
930def test_a_line_of_a_closed_period_journal_cannot_be_deleted(tmp_path, monkeypatch):
931 """Seen today: DELETE 200; the filed year's journal reads debit 10000 /
932 credit 0."""
933 site = books_site(tmp_path, monkeypatch)
934 closed_year(site)
935
936 status, _ = site.delete("fin_journal_lines", "j2025-cr", "ann")
937
938 debit, credit = totals(site, "j2025")
939 assert (debit, credit) == (10000, 10000), (
940 f"DELETE answered {status}: closed-period journal j2025 is now debit {debit} / "
941 f"credit {credit}")
942
943
944def test_a_closed_period_journal_cannot_be_deleted(tmp_path, monkeypatch):
945 """Editing the journal is refused by the closed-period gate (409) -- the
946 control. ann DELETEs it.
947
948 Seen today: 200; FY2025's 10000 sale is gone from the journal list."""
949 site = books_site(tmp_path, monkeypatch)
950 closed_year(site)
951 refused_by_hook(site.put("fin_journals", "j2025", "ann", {"description": "tidied"}),
952 "editing a closed-period journal", status=409)
953
954 status, _ = site.delete("fin_journals", "j2025", "ann")
955
956 assert site.exists("fin_journals", "j2025"), (
957 f"DELETE answered {status}: the closed-period journal is gone")
958
959
960# =============================================================================
961# 4. receipt_lines / shipment_lines check only the NEW parent
962# =============================================================================
963
964def fulfilment_site(tmp_path, monkeypatch):
965 return build_site(tmp_path, monkeypatch,
966 ["app-views", "app-settings", "app-entities", "app-catalog",
967 "app-orders", "app-receiving", "app-shipping"])
968
969
970def received_delivery(site):
971 """A purchase order for 10, received in full on a receipt that has been
972 signed for; a second, open receipt against the same order."""
973 ok(site.post("orders", "ann", {"id": "po1", "doc_type": "purchase", "number": "PO-1",
974 "customer_name": "Supplier"}), "purchase order")
975 ok(site.post("order_lines", "ann", {"id": "pol1", "order_id": "po1", "description": "mugs",
976 "quantity": "10", "unit_price_cents": "500"}), "po line")
977 ok(site.post("receipts", "ann", {"id": "rc1", "order_id": "po1"}), "receipt")
978 ok(site.post("receipt_lines", "ann", {"id": "rl1", "receipt_id": "rc1",
979 "order_line_id": "pol1", "quantity_received": "10"}),
980 "receipt line")
981 ok(site.put("receipts", "rc1", "ann", {"status": "received"}), "sign for the delivery")
982 ok(site.post("receipts", "ann", {"id": "rc2", "order_id": "po1"}), "second receipt")
983 refused_by_hook(site.put("receipt_lines", "rl1", "ann", {"quantity_received": "1"}),
984 "editing a line of a received receipt", status=409)
985
986
987def test_a_line_cannot_be_moved_out_of_a_received_receipt(tmp_path, monkeypatch):
988 """Editing the settled line in place is refused (409, "already
989 received") -- the control. ann PUTs receipt_id=rc2 (an open receipt),
990 then edits the quantity there.
991
992 Seen today: both 200; the signed-for receipt rc1 has no lines and the
993 line reads quantity_received 1 on rc2 -- nine received units have left
994 the record of a settled delivery."""
995 site = fulfilment_site(tmp_path, monkeypatch)
996 received_delivery(site)
997
998 moved, _ = site.put("receipt_lines", "rl1", "ann", {"receipt_id": "rc2"})
999 edited, _ = site.put("receipt_lines", "rl1", "ann", {"quantity_received": "1"})
1000
1001 stored = site.get("receipt_lines", "rl1")
1002 assert (stored["receipt_id"], stored["quantity_received"]) == ("rc1", "10"), (
1003 f"move answered {moved}, edit answered {edited}: the line is now on "
1004 f"{stored['receipt_id']} with quantity_received {stored['quantity_received']}")
1005
1006
1007def shipped_parcel(site):
1008 ok(site.post("orders", "ann", {"id": "so1", "doc_type": "sale", "number": "SO-1",
1009 "customer_name": "Customer"}), "sales order")
1010 ok(site.post("order_lines", "ann", {"id": "sol1", "order_id": "so1", "description": "mugs",
1011 "quantity": "3", "unit_price_cents": "900"}), "so line")
1012 ok(site.post("shipments", "ann", {"id": "sh1", "order_id": "so1"}), "shipment")
1013 ok(site.post("shipment_lines", "ann", {"id": "sl1", "shipment_id": "sh1",
1014 "order_line_id": "sol1", "quantity": "3"}),
1015 "shipment line")
1016 ok(site.put("shipments", "sh1", "ann", {"status": "packed"}), "pack")
1017 ok(site.put("shipments", "sh1", "ann", {"status": "shipped"}), "ship")
1018 ok(site.post("shipments", "ann", {"id": "sh2", "order_id": "so1"}), "second shipment")
1019 refused_by_hook(site.put("shipment_lines", "sl1", "ann", {"quantity": "1"}),
1020 "editing a line of a shipped shipment", status=409)
1021
1022
1023def test_a_line_cannot_be_moved_out_of_a_shipped_shipment(tmp_path, monkeypatch):
1024 """The mirror image. Editing the shipped line in place is refused (409,
1025 "already shipped") -- the control. ann PUTs shipment_id=sh2, then edits
1026 the quantity.
1027
1028 Seen today: both 200; the manifest the courier took (sh1) is empty and
1029 the line reads quantity 1 on the open sh2, so the order shows 1 of 3
1030 shipped and 2 more can be shipped again."""
1031 site = fulfilment_site(tmp_path, monkeypatch)
1032 shipped_parcel(site)
1033
1034 moved, _ = site.put("shipment_lines", "sl1", "ann", {"shipment_id": "sh2"})
1035 edited, _ = site.put("shipment_lines", "sl1", "ann", {"quantity": "1"})
1036
1037 stored = site.get("shipment_lines", "sl1")
1038 assert (stored["shipment_id"], stored["quantity"]) == ("sh1", "3"), (
1039 f"move answered {moved}, edit answered {edited}: the line is now on "
1040 f"{stored['shipment_id']} with quantity {stored['quantity']}")
1041
1042
1043def test_settled_receipt_and_shipment_lines_cannot_be_deleted_by_their_owner(tmp_path, monkeypatch):
1044 """REFUTES the delete half for these two collections: unlike payments,
1045 refunds, stock_moves, time_logs and the journals, the app-receiving and
1046 app-shipping permission rules grant the owner create/read/update only,
1047 so the unhooked delete path is closed by the permission layer (403)."""
1048 site = fulfilment_site(tmp_path, monkeypatch)
1049 received_delivery(site)
1050 shipped_parcel(site)
1051
1052 for collection, record_id in (("receipt_lines", "rl1"), ("shipment_lines", "sl1"),
1053 ("receipts", "rc1"), ("shipments", "sh1")):
1054 status, body = site.delete(collection, record_id, "ann")
1055 assert status == 403 and body.get("code") == "forbidden", (collection, status, body)
1056 assert site.exists(collection, record_id)
1057
1058
1059# =============================================================================
1060# 5. hook_payments gates on invoices.total_cents, a stamped cache
1061# =============================================================================
1062
1063def test_an_overpayment_is_refused_when_the_stamped_total_is_stale(tmp_path, monkeypatch):
1064 """AGENTS.md: a gate must sum the evidence, not read the cache. The
1065 invoice's one line is 10000 and invoice_totals stamps total_cents 10000.
1066 The reaction then does not run for one write (handlers are best-effort
1067 and off by default; here the flag is dropped for the one request) while
1068 ann reduces the line to 4000. The lines now say 4000; the cache says
1069 10000.
1070
1071 Seen today: a 10000 payment answers 201 -- 6000 more than the invoice's
1072 lines are worth -- and balance_due_cents reads 0."""
1073 site = payments_site(tmp_path, monkeypatch)
1074 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV)
1075 ok(site.put("invoice_lines", "l1", "ann", {"unit_price_cents": "4000"}), "reduce the line")
1076 must(site.get("invoices", "inv1")["total_cents"] == "10000"
1077 and site.get("invoice_lines", "l1")["unit_price_cents"] == "4000",
1078 "the scenario needs a stale total over a cheaper line")
1079
1080 status, _ = pay(site, "p1", 10000)
1081
1082 assert net_received(site) <= 4000, (
1083 f"POST answered {status}: {net_received(site)} cents recorded against an invoice "
1084 f"whose lines total 4000 (stamped total_cents 10000)")
1085
1086
1087def test_an_overpayment_is_refused_when_the_owner_types_the_total(tmp_path, monkeypatch):
1088 """invoices.total_cents is "never typed by hand" by convention only (it
1089 is left owner-writable so the handler can write it; invoice_totals.py
1090 calls this "detection, not prevention"). No invoice_lines write follows,
1091 so nothing restamps it. The invoice's one line is 4000.
1092
1093 Seen today: PUT total_cents=999999 answers 200, and a 999999 payment
1094 answers 201 against 4000 of lines."""
1095 site = payments_site(tmp_path, monkeypatch)
1096 ok(site.put("invoice_lines", "l1", "ann", {"unit_price_cents": "4000"}), "price the line")
1097 must(site.get("invoices", "inv1")["total_cents"] == "4000", "total not restamped to 4000")
1098 refused_by_hook(pay(site, "p0", 4001), "one cent over the real total", status=409,
1099 code="check_refused")
1100
1101 typed, _ = site.put("invoices", "inv1", "ann", {"total_cents": "999999"})
1102 status, _ = pay(site, "p1", 999999)
1103
1104 assert net_received(site) <= 4000, (
1105 f"typing the total answered {typed}, the payment answered {status}: "
1106 f"{net_received(site)} cents recorded against an invoice whose lines total 4000")
1107
1108
1109def test_a_blank_or_unstamped_total_refuses_every_payment(tmp_path, monkeypatch):
1110 """REFUTES the "blank" half of finding 5: a blank total_cents is read as
1111 0, so the gate fails CLOSED -- every payment is refused, none is
1112 over-accepted. The same is true of an invoice whose total was never
1113 stamped because event handlers are off (the default): the cost is that
1114 no payment can be recorded at all, not that too much can."""
1115 site = payments_site(tmp_path, monkeypatch)
1116 ok(site.put("invoices", "inv1", "ann", {"total_cents": ""}), "blank the total")
1117 status, body = pay(site, "p1", 1)
1118 assert status == 409 and "remaining balance of 0 cents" in body["error"], (status, body)
1119
1120 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV)
1121 ok(site.post("invoices", "ann", {"id": "inv2", "number": "INV-2", "customer_name": "Acme"}),
1122 "second invoice")
1123 ok(site.post("invoice_lines", "ann", {"id": "l2", "invoice_id": "inv2", "description": "work",
1124 "quantity": "1", "unit_price_cents": "10000"}), "line")
1125 assert site.get("invoices", "inv2")["total_cents"] == "0"
1126 status, body = pay(site, "p2", 1, invoice_id="inv2")
1127 assert status == 409 and "remaining balance of 0 cents" in body["error"], (status, body)
1128 assert site.rows("payments") == []
1129
1130
1131def test_an_overpayment_is_refused_when_the_stamped_total_does_not_parse(tmp_path, monkeypatch):
1132 """Reachability, stated plainly: schema validation refuses a non-integer
1133 total_cents on BOTH the HTTP path (400) and object_records (pinned
1134 below), so this row can only come from outside them -- a hand-edited or
1135 restored records.tsv, which is how this test makes it. Given such a row,
1136 the gate passes instead of refusing.
1137
1138 Seen today: a 999999 payment answers 201 on an invoice whose lines total
1139 10000."""
1140 site = payments_site(tmp_path, monkeypatch)
1141 status, body = site.put("invoices", "inv1", "ann", {"total_cents": "40.00"})
1142 must(status == 400 and "must be an integer" in body.get("error", ""),
1143 f"validation no longer refuses a non-integer total: {status} {body}")
1144
1145 path = site.data / "collections" / "invoices" / "records.tsv"
1146 header, *lines = path.read_text().split("\n")
1147 column = header.split("\t").index("total_cents")
1148 edited = []
1149 for line in lines:
1150 cells = line.split("\t")
1151 if cells[0] == "inv1":
1152 cells[column] = "40.00"
1153 edited.append("\t".join(cells))
1154 path.write_text("\n".join([header, *edited]))
1155 must(site.get("invoices", "inv1")["total_cents"] == "40.00", "the edited cell did not read back")
1156
1157 status, _ = pay(site, "p1", 999999)
1158
1159 assert net_received(site) <= 10000, (
1160 f"POST answered {status}: {net_received(site)} cents recorded against an invoice "
1161 f"whose lines total 10000 (unparseable total_cents '40.00')")
1162
1163
1164# =============================================================================
1165# 6. fail-open reads inside gates
1166# =============================================================================
1167
1168def banking_site(tmp_path, monkeypatch):
1169 site = build_site(tmp_path, monkeypatch,
1170 ["app-views", "app-settings", "app-entities", "app-finance", "app-banking"])
1171 ok(site.post("value_accounts", "ann", {"id": "bank-1", "name": "Checking", "kind": "bank"}),
1172 "bank account")
1173 return site
1174
1175
1176BANK_LINE = {"bank_account_id": "bank-1", "posted_on": "2026-07-02",
1177 "amount_cents": "150000", "description": "ACME CORP PAYMENT INV-1001"}
1178
1179
1180def test_the_bank_line_duplicate_gate_refuses_when_its_read_fails(tmp_path, monkeypatch):
1181 """With the ledger readable, the same line again is refused (409,
1182 "already on file") -- the control. Then the helper's own read of
1183 bank_lines fails once (only that read; the write path's reads work).
1184
1185 Seen today: 201; two identical 150000 lines on one bank account, i.e.
1186 300000 of deposits to reconcile where the bank reported 150000. The
1187 sibling hooks (usage_events, scans, wallet_entries) refuse in this
1188 situation; this one passes."""
1189 site = banking_site(tmp_path, monkeypatch)
1190 ok(site.post("bank_lines", "ann", {"id": "b1", **BANK_LINE}), "first line")
1191 refused_by_hook(site.post("bank_lines", "ann", {"id": "b2", **BANK_LINE}),
1192 "duplicate line with a readable ledger", status=409,
1193 code="unique_violation")
1194
1195 # The hook that read the ledger first is gone: `unique` holds inside the
1196 # write lock and depends on no look-before-write read, so the helper's
1197 # read failing changes nothing (nothing calls it on this path).
1198 with failing_reads("bank_lines", "object_banking.py"):
1199 status, _ = site.post("bank_lines", "ann", {"id": "b3", **BANK_LINE})
1200 must(status == 409, f"the duplicate was answered {status}")
1201
1202 lines = object_records.read_collection_records("bank_lines", base_dir=site.data)
1203 assert len(lines) == 1, (
1204 f"POST answered {status} while the duplicate check could not read: {len(lines)} "
1205 f"lines totalling {sum(int(l['amount_cents']) for l in lines)} for one 150000 deposit")
1206
1207
1208def bank_import_env(tmp_path, monkeypatch):
1209 data = tmp_path / "data"
1210 for package, name in (("app-banking", "value_accounts"), ("app-banking", "bank_import_profiles"),
1211 ("app-banking", "bank_statement_imports"), ("app-banking", "bank_lines"),
1212 ("app-finance", "fin_accounts")):
1213 stage_collection(data, package, name)
1214 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data))
1215 object_records.create_collection_record(
1216 "value_accounts", {"id": "bank-1", "name": "Checking", "kind": "bank", "owner_id": "ann"},
1217 base_dir=data)
1218 return data
1219
1220
1221COLUMN_MAP = {"date": "Date", "amount": "Amount", "description": "Description",
1222 "date_format": "%m/%d/%Y"}
1223JULY = ("Date,Description,Amount\n"
1224 "07/02/2026,ACME CORP PAYMENT INV-1001,1500.00\n"
1225 "07/05/2026,MONTHLY SERVICE FEE,-25.00\n")
1226JULY_AND_ONE_MORE = JULY + "07/09/2026,OFFICE SUPPLY CO,-142.35\n"
1227
1228
1229def import_csv(content):
1230 result = run_object("action_import_bank_csv",
1231 {"_identity": {"user_id": "ann"}, "bank_account_id": "bank-1",
1232 "column_map": COLUMN_MAP, "content": content}, "app-banking")
1233 must(result.ok, f"the import action crashed: {result}")
1234 return result.result
1235
1236
1237def test_the_file_hash_gate_refuses_when_its_read_fails(tmp_path, monkeypatch):
1238 """Importing the same file twice answers already_imported -- the
1239 control. With the helper's read of bank_statement_imports failing, the
1240 file-level gate passes.
1241
1242 Seen today: status 200, import_status "accepted", imported 0,
1243 duplicates 2: the line-level check (a different read, still working)
1244 saves the lines, but a SECOND bank_statement_imports row now claims the
1245 same file_hash. Money impact is indirect: the statement chain has a
1246 phantom import; with both reads down (see the next test) nothing is
1247 left."""
1248 data = bank_import_env(tmp_path, monkeypatch)
1249 first = import_csv(JULY)
1250 must(first.get("imported") == 2, f"first import: {first}")
1251 must(import_csv(JULY).get("already_imported") is True, "the control re-import was not caught")
1252
1253 with failing_reads("bank_statement_imports", "object_banking.py") as fired:
1254 again = import_csv(JULY)
1255 must("find_import_by_file_hash" in fired, f"the simulated failure fired in {fired}")
1256
1257 imports = object_records.read_collection_records("bank_statement_imports", base_dir=data)
1258 assert len(imports) == 1, (
1259 f"the re-import answered {({k: again.get(k) for k in ('status', 'import_status', 'imported', 'duplicates', 'already_imported', 'error')})}: "
1260 f"{len(imports)} import rows share file_hash "
1261 f"{sorted({row['file_hash'][:12] for row in imports})}")
1262
1263
1264def test_an_overlapping_statement_import_refuses_when_the_line_read_fails(tmp_path, monkeypatch):
1265 """The ordinary reason line-level dedupe exists: July's statement, then
1266 a later export that repeats July's two lines and adds one. With the
1267 ledger readable the import reports imported 1, duplicates 2 (the control
1268 is the passing test just below). Here the helper's read of bank_lines
1269 fails.
1270
1271 Seen today: status 200, import_status "accepted", imported 3,
1272 duplicates 0 -- the 1500.00 deposit and the 25.00 fee are on file
1273 twice."""
1274 data = bank_import_env(tmp_path, monkeypatch)
1275 must(import_csv(JULY).get("imported") == 2, "first import")
1276
1277 with failing_reads("bank_lines", "object_banking.py") as fired:
1278 again = import_csv(JULY_AND_ONE_MORE)
1279 must("existing_line_keys" in fired, f"the simulated failure fired in {fired}")
1280
1281 # Fixed 2026-11-28: the importer reads the line keys strictly before it
1282 # writes anything and refuses (409). The assertion used to accept only
1283 # the fully-landed outcome (3 lines), which no import can reach with the
1284 # ledger unreadable; a refusal that leaves July's two lines alone is the
1285 # other correct answer. What must never happen is a line on file twice.
1286 lines = object_records.read_collection_records("bank_lines", base_dir=data)
1287 net = sum(int(line["amount_cents"]) for line in lines)
1288 if again.get("status") == 409:
1289 assert (len(lines), net) == (2, 150000 - 2500), (again, len(lines), net)
1290 return
1291 assert (len(lines), net) == (3, 150000 - 2500 - 14235), (
1292 f"the import answered {({k: again.get(k) for k in ('status', 'import_status', 'imported', 'duplicates', 'error')})}: "
1293 f"{len(lines)} lines on file, net {net}")
1294
1295
1296def test_an_overlapping_statement_import_skips_lines_already_on_file(tmp_path, monkeypatch):
1297 """The control for the test above, and what correct looks like: with the
1298 ledger readable the overlapping export adds only the one new line."""
1299 data = bank_import_env(tmp_path, monkeypatch)
1300 assert import_csv(JULY).get("imported") == 2
1301 again = import_csv(JULY_AND_ONE_MORE)
1302 assert (again.get("imported"), again.get("duplicates")) == (1, 2), again
1303 lines = object_records.read_collection_records("bank_lines", base_dir=data)
1304 assert (len(lines), sum(int(line["amount_cents"]) for line in lines)) == (3, 133265)
1305
1306
1307SETTING = {"key": "inventory.journal.inventory_account"}
1308
1309
1310def test_the_settings_key_gate_refuses_when_its_read_fails(tmp_path, monkeypatch):
1311 """Driven with the admin token: no rule lets a signed-in user write
1312 app_settings, so that is the only door to this hook (the 403 for ann is
1313 asserted first). A second row for the key is refused with the collection
1314 readable (409) -- the control. Then the hook's own read fails.
1315
1316 Seen today: 201; two rows for inventory.journal.inventory_account, and
1317 every reader takes the first (1300), so the operator's new 1400 does
1318 nothing -- the stale-inventory-account incident the hook's docstring
1319 says it exists to prevent."""
1320 site = build_site(tmp_path, monkeypatch, ["app-settings"])
1321 status, body = site.post("app_settings", "ann", {"id": "s0", **SETTING, "value": "1200"})
1322 must(status == 403, f"a signed-in user reached app_settings: {status} {body}")
1323 ok(site.post("app_settings", "admin", {"id": "s1", **SETTING, "value": "1300"}), "first row")
1324 refused_by_hook(site.post("app_settings", "admin", {"id": "s2", **SETTING, "value": "1400"}),
1325 "duplicate key with a readable collection", status=409,
1326 code="unique_violation")
1327
1328 # The hook that read the collection first is gone: `unique` is checked
1329 # inside the write lock and needs no look-before-write read to fail.
1330 with failing_reads("app_settings", "hook/app_settings.py"):
1331 status, _ = site.post("app_settings", "admin", {"id": "s3", **SETTING, "value": "1400"})
1332 must(status == 409, f"the duplicate was answered {status}")
1333
1334 rows = [row for row in object_records.read_collection_records("app_settings", base_dir=site.data)
1335 if row["key"] == SETTING["key"]]
1336 assert len(rows) == 1, (
1337 f"POST answered {status} while the key check could not read: "
1338 f"{[(row['id'], row['value']) for row in rows]} all claim {SETTING['key']}")
1339
1340
1341def test_a_sale_is_not_stamped_at_standard_cost_when_the_average_cannot_be_read(tmp_path, monkeypatch):
1342 """Standard cost 500; ten units actually bought at 800. A sale with the
1343 ledger readable is stamped 800 -- the control. Then object_stock's read
1344 of stock_moves fails for the next sale. The stamp is a point-in-time
1345 fact (doctrine #1): whatever is written is the cost of that sale for
1346 good.
1347
1348 Seen today: 201 with unit_cost_cents 500 -- cost of sales understated by
1349 300 a unit, which the hook's own comment calls "how gross margin quietly
1350 becomes fiction". Correct is either the true average or a refusal."""
1351 site = stock_site(tmp_path, monkeypatch)
1352 ok(move(site, "m1", to_location_id="shelf", quantity="10", unit_cost_cents="800",
1353 reason="purchase"), "purchase at 800")
1354 control = ok(move(site, "m2", from_location_id="shelf", quantity="1", reason="sale"), "sale")
1355 must(control["unit_cost_cents"] == "800", f"the control sale was stamped {control}")
1356
1357 with failing_reads("stock_moves", "object_stock.py") as fired:
1358 status, _ = move(site, "m3", from_location_id="shelf", quantity="1", reason="sale")
1359 must(fired, "the simulated failure never fired inside object_stock")
1360
1361 stamped = [row["unit_cost_cents"] for row in
1362 object_records.read_collection_records("stock_moves", base_dir=site.data)
1363 if row["id"] == "m3"]
1364 assert stamped in ([], ["800"]), (
1365 f"POST answered {status} while the average could not be read: the sale was "
1366 f"stamped unit_cost_cents {stamped[0]} (true average 800, standard cost 500)")
1367
1368
1369# =============================================================================
1370# 7. dedupe checks that run before the write lock
1371# =============================================================================
1372
1373def billing_site(tmp_path, monkeypatch):
1374 return build_site(tmp_path, monkeypatch,
1375 ["app-views", "app-settings", "app-entities", "app-finance",
1376 "app-invoices", "app-payments", "app-billing"])
1377
1378
1379def test_two_overlapping_retries_of_one_usage_event_are_recorded_once(tmp_path, monkeypatch):
1380 """Serially the second is refused (409, "already recorded ... must not
1381 be billed twice") -- the control, with a different event. Then two
1382 requests for event evt-1 overlap: A's hook has passed, B runs to
1383 completion, A persists.
1384
1385 Seen today: both 201; two usage_events rows for evt-1, quantity 10
1386 each."""
1387 site = billing_site(tmp_path, monkeypatch)
1388 usage = lambda record_id, event: site.post("usage_events", "ann", {
1389 "id": record_id, "event_id": event, "metric": "api_calls", "quantity": "10"})
1390 ok(usage("u0", "evt-0"), "control event")
1391 refused_by_hook(usage("u0b", "evt-0"), "serial retry", status=409,
1392 code="unique_violation")
1393
1394 first, second = overlap_two_creates(monkeypatch, "usage_events",
1395 lambda: usage("u1", "evt-1"), lambda: usage("u2", "evt-1"))
1396
1397 recorded = site.rows("usage_events", event_id="evt-1")
1398 assert len(recorded) == 1, (
1399 f"the overlapping requests answered {first[0]} and {second[0]}: "
1400 f"{len(recorded)} rows for evt-1, "
1401 f"{sum(Decimal(row['quantity']) for row in recorded)} units metered for 10 used")
1402
1403
1404def test_two_overlapping_uploads_of_one_receipt_are_one_scan(tmp_path, monkeypatch):
1405 """Serially the second is refused (409, "already here as scan ...") --
1406 the control. Then two uploads of the same bytes overlap.
1407
1408 Seen today: both 201; two scans with one content_sha256."""
1409 site = build_site(tmp_path, monkeypatch, ["app-views", "app-entities", "app-intake"])
1410 scan = lambda record_id, digest: site.post("scans", "ann", {
1411 "id": record_id, "filename": f"{record_id}.jpg", "content_sha256": digest})
1412 ok(scan("s0", "aaaa"), "control scan")
1413 refused_by_hook(scan("s0b", "aaaa"), "serial duplicate", status=409,
1414 code="unique_violation")
1415
1416 first, second = overlap_two_creates(monkeypatch, "scans",
1417 lambda: scan("s1", "bbbb"), lambda: scan("s2", "bbbb"))
1418
1419 stored = site.rows("scans", content_sha256="bbbb")
1420 assert len(stored) == 1, (
1421 f"the overlapping uploads answered {first[0]} and {second[0]}: "
1422 f"scans {[row['id'] for row in stored]} share one content hash")
1423
1424
1425def test_two_overlapping_posts_of_one_bank_line_land_once(tmp_path, monkeypatch):
1426 """Serial duplicates are refused (see the fail-open test's control).
1427 Here two creates of the same line overlap.
1428
1429 Seen today: both 201; two lines with the same line_hash on one bank
1430 account."""
1431 site = banking_site(tmp_path, monkeypatch)
1432 line = lambda record_id: site.post("bank_lines", "ann", {"id": record_id, **BANK_LINE})
1433
1434 first, second = overlap_two_creates(monkeypatch, "bank_lines",
1435 lambda: line("b1"), lambda: line("b2"))
1436
1437 stored = site.rows("bank_lines")
1438 assert len(stored) == 1, (
1439 f"the overlapping posts answered {first[0]} and {second[0]}: {len(stored)} lines "
1440 f"with line_hash {sorted({row['line_hash'][:12] for row in stored})}")
1441
1442
1443def test_two_overlapping_creates_of_one_setting_key_land_once(tmp_path, monkeypatch):
1444 """Admin token (the only writer of app_settings). Two creates of the
1445 same key overlap.
1446
1447 Seen today: both 201; rows s1=1300 and s2=1400 for one key, readers take
1448 whichever is first in the file."""
1449 site = build_site(tmp_path, monkeypatch, ["app-settings"])
1450 setting = lambda record_id, value: site.post(
1451 "app_settings", "admin", {"id": record_id, **SETTING, "value": value})
1452
1453 first, second = overlap_two_creates(monkeypatch, "app_settings",
1454 lambda: setting("s1", "1300"), lambda: setting("s2", "1400"))
1455
1456 rows = site.rows("app_settings", key=SETTING["key"])
1457 assert len(rows) == 1, (
1458 f"the overlapping creates answered {first[0]} and {second[0]}: "
1459 f"{[(row['id'], row['value']) for row in rows]} all claim {SETTING['key']}")
1460
1461
1462# =============================================================================
1463# 8. approved_at is spelled +00:00 where created_at is spelled Z
1464# =============================================================================
1465
1466def test_an_approval_instant_compares_correctly_whatever_its_spelling(tmp_path, monkeypatch):
1467 """LATENT, not a live bug: hook_time_logs (and hook_expenses, same line)
1468 stamp approved_at with datetime.isoformat() ("+00:00") while created_at
1469 is stamped "Z", and AGENTS.md warns the two do not compare as strings.
1470 Nothing in packages/ or the server compares, sorts or filters on
1471 approved_at by name today (grep), and the one generic comparer a caller
1472 can point at it -- the list API's ordered filters -- parses both sides
1473 (object_permissions._comparable_filter_pair). This pins that parse, so
1474 the test holds before and after the spelling is unified: approved_at is
1475 later than the same record's created_at, and a Z-spelled cutoff sees it
1476 that way even though as raw strings "+00:00" sorts below "Z"."""
1477 site = timers_site(tmp_path, monkeypatch)
1478 row = site.get("time_logs", "t1")
1479 approved = datetime.fromisoformat(row["approved_at"].replace("Z", "+00:00"))
1480 created = datetime.fromisoformat(row["created_at"].replace("Z", "+00:00"))
1481 assert approved > created
1482
1483 listed = lambda query: [r["id"] for r in site.call(
1484 "GET", "/collections/time_logs/records", "ann", query=query)[1]["records"]]
1485 cutoff = row["created_at"] # Z-spelled, strictly earlier
1486 assert listed(f"approved_at.gte={cutoff}") == ["t1"]
1487 assert listed(f"approved_at.lt={cutoff}") == []