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_app_invoices_totals.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_app_invoices_totals.py · 16.2 KB · 384 lines
1"""Behavior tests for packages/app-invoices: the invoice_totals HANDLES
2handler (integer-cents arithmetic, half-up tax per rate group, idempotence,
3delete handling) and the guarded status transitions on invoices.status.
4
5Structural/manifest/permission tests live in tests/test_app_invoices_package.py.
6"""
7
8import os
9from pathlib import Path
10
11import pytest
12
13import object_execution
14import object_packages
15import object_permissions
16import object_record_changes
17import object_records
18import object_schemas
19import python_object_runtime
20
21PACKAGES_ROOT = Path(__file__).resolve().parents[1] / "packages"
22
23
24@pytest.fixture(autouse=True)
25def _objects_dir_is_restored():
26 """_install points DBBASIC_OBJECTS_DIR at this test's object root; put
27 back whatever was there before, after the test."""
28 saved = os.environ.get("DBBASIC_OBJECTS_DIR")
29 yield
30 if saved is None:
31 os.environ.pop("DBBASIC_OBJECTS_DIR", None)
32 else:
33 os.environ["DBBASIC_OBJECTS_DIR"] = saved
34
35
36def _install(tmp_path):
37 """Install app-invoices (+ app-contacts, for the customer_id relation
38 target) into an isolated data dir/object root and return
39 (data_dir, object_root, runtime).
40 """
41 data_dir = tmp_path / "data"
42 object_root = tmp_path / "objects"
43 object_root.mkdir()
44 # conftest's isolated_default_data_dir fixture already points
45 # DBBASIC_DATA_DIR at tmp_path / "data" for this test process; keep
46 # them in sync so invoice_totals.py's own env-based _data_dir()
47 # resolves to the same directory this test writes into.
48 os.environ["DBBASIC_DATA_DIR"] = str(data_dir)
49 # invoice_lines declares a locked check (settled_line) whose object
50 # lives in this package: a line write must be able to find it, and a
51 # declared check that is not installed refuses the write (fails closed).
52 os.environ["DBBASIC_OBJECTS_DIR"] = str(object_root)
53
54 object_packages.install_package(
55 "app-invoices", root=PACKAGES_ROOT, base_dir=data_dir, object_roots=[object_root]
56 )
57 runtime = python_object_runtime.PythonObjectRuntime(base_dir=data_dir)
58 return data_dir, object_root, runtime
59
60
61def _fire(runtime, object_root, record_id, action):
62 return object_execution.execute_object(
63 runtime,
64 object_execution.ObjectExecutionRequest(
65 "system_invoice_totals",
66 method="EVENT",
67 payload={
68 "event": f"invoice_lines.record.{action}",
69 "collection": "invoice_lines",
70 "record_id": record_id,
71 "action": action,
72 },
73 ),
74 roots=[object_root],
75 )
76
77
78def _add_payments_substrate(data_dir, paid_cents=None):
79 """invoices v2 derives amount_paid/balance_due from the payments/refunds
80 collections (app-payments). Give the env those schemas + collections, and
81 optionally one real received payment -- the thing the old test faked by
82 writing amount_paid_cents directly ("simulating a future partial-payment
83 write"; the future arrived)."""
84 import pathlib, shutil
85 packages = pathlib.Path(__file__).resolve().parents[1] / "packages"
86 schema_dir = data_dir / "schemas"
87 from conftest import _stage_locked_check_objects
88 for name in ("payments", "refunds"):
89 shutil.copy(packages / "app-payments" / "schemas" / f"{name}.json",
90 schema_dir / f"{name}.json")
91 # The schemas declare locked checks (the ledger ceilings); a write
92 # to a collection whose check object is missing is refused.
93 _stage_locked_check_objects(data_dir, "app-payments", name)
94 for coll, hdr in (
95 ("payments", "id\tinvoice_id\tamount_cents\tmethod\treceived_on\treference\tnotes\tstatus\trefunded_cents\towner_id\tcreated_at\n"),
96 ("refunds", "id\tpayment_id\tinvoice_id\tamount_cents\treason\trefunded_on\towner_id\tcreated_at\n"),
97 ):
98 d = data_dir / "collections" / coll
99 d.mkdir(parents=True, exist_ok=True)
100 (d / "records.tsv").write_text(hdr)
101 if paid_cents is not None:
102 object_records.create_collection_record(
103 "payments",
104 {"id": "pay_1", "invoice_id": "inv_1", "amount_cents": str(paid_cents),
105 "method": "transfer", "received_on": "2026-07-24", "owner_id": "u1"},
106 base_dir=data_dir)
107
108
109def _make_invoice(data_dir, **overrides):
110 record = {
111 "id": "inv_1",
112 "number": "INV-0001",
113 "customer_name": "Example Consulting LLC",
114 "owner_id": "u1",
115 }
116 record.update(overrides)
117 return object_records.create_collection_record("invoices", record, base_dir=data_dir, actor="test")
118
119
120def _make_line(data_dir, **overrides):
121 record = {
122 "invoice_id": "inv_1",
123 "description": "Line item",
124 "quantity": "1",
125 "unit_price_cents": "100",
126 "owner_id": "u1",
127 }
128 record.update(overrides)
129 return object_records.create_collection_record("invoice_lines", record, base_dir=data_dir, actor="test")
130
131
132def test_line_total_is_quantity_times_unit_price_floored(tmp_path):
133 data_dir, object_root, runtime = _install(tmp_path)
134 _make_invoice(data_dir)
135 _make_line(data_dir, id="il_1", quantity="3", unit_price_cents="1999")
136
137 result = _fire(runtime, object_root, "il_1", "created")
138 assert result.ok is True
139
140 line = object_records.get_collection_record("invoice_lines", "il_1", base_dir=data_dir)
141 assert line["line_total_cents"] == "5997" # 3 * 1999
142
143
144def test_line_tax_uses_basis_points_rounded_half_up(tmp_path):
145 """8.25% (825 bps) of 5997 cents is 494.7525 cents -- 495, half-up.
146 It floored to 494 under 20-invoice-spec.md's 'floor not round', while
147 the cart rounded the same line half-up, so one sale's line tax had two
148 values (finding M18). Decision 2 (owner, 2026-11-30): tax is rounded
149 half-up, once per rate group.
150 """
151 data_dir, object_root, runtime = _install(tmp_path)
152 _make_invoice(data_dir)
153 _make_line(data_dir, id="il_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
154
155 _fire(runtime, object_root, "il_1", "created")
156
157 line = object_records.get_collection_record("invoice_lines", "il_1", base_dir=data_dir)
158 assert line["line_total_cents"] == "5997"
159 assert line["line_tax_cents"] == "495"
160
161
162def test_multi_line_invoice_totals_match_hand_computed_cents(tmp_path):
163 """The worked example this package's report cites:
164
165 Line 1: qty 3, unit_price_cents 1999, tax_rate_bps 825
166 line_total = 3 * 1999 = 5997
167 line_tax = half-up(5997 * 825 / 10000) = 495 (494.7525)
168 Line 2: qty 1, unit_price_cents 5000, tax_rate_bps 0
169 line_total = 5000
170 line_tax = 0
171 subtotal_cents = 5997 + 5000 = 10997
172 tax_cents = 495 + 0 = 495
173 total_cents = 10997 + 495 = 11492
174 amount_paid_cents = 2000 (a real received payment record now --
175 rollup/formula territory, app-payments)
176 balance_due_cents = 11492 - 2000 = 9492
177 """
178 data_dir, object_root, runtime = _install(tmp_path)
179 _make_invoice(data_dir)
180 _add_payments_substrate(data_dir)
181 _make_line(data_dir, id="il_1", description="Consulting hours",
182 quantity="3", unit_price_cents="1999", tax_rate_bps="825")
183 _make_line(data_dir, id="il_2", description="Software license",
184 quantity="1", unit_price_cents="5000", tax_rate_bps="0")
185
186 _fire(runtime, object_root, "il_1", "created")
187 _fire(runtime, object_root, "il_2", "created")
188 # Paid once the invoice says what it is worth: every writer's payment is
189 # checked against its invoice (the ledger's locked check), and an
190 # invoice with no lines and no total is worth nothing yet.
191 object_records.create_collection_record(
192 "payments",
193 {"id": "pay_1", "invoice_id": "inv_1", "amount_cents": "2000",
194 "method": "transfer", "received_on": "2026-07-24", "owner_id": "u1"},
195 base_dir=data_dir)
196
197 invoice = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
198 assert invoice["subtotal_cents"] == "10997"
199 assert invoice["tax_cents"] == "495"
200 assert invoice["total_cents"] == "11492"
201 assert invoice["balance_due_cents"] == "9492"
202
203
204def test_fractional_quantity_uses_decimal_not_float(tmp_path):
205 """2.5 hours at 10000 cents/hr must floor to exactly 25000 cents --
206 Decimal arithmetic, never a bare float multiplication that could
207 introduce binary rounding error.
208 """
209 data_dir, object_root, runtime = _install(tmp_path)
210 _make_invoice(data_dir)
211 _make_line(data_dir, id="il_1", quantity="2.5", unit_price_cents="10000")
212
213 _fire(runtime, object_root, "il_1", "created")
214
215 line = object_records.get_collection_record("invoice_lines", "il_1", base_dir=data_dir)
216 assert line["line_total_cents"] == "25000"
217
218
219def test_recompute_is_idempotent_and_skips_a_no_op_write(tmp_path):
220 data_dir, object_root, runtime = _install(tmp_path)
221 _make_invoice(data_dir)
222 _make_line(data_dir, id="il_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
223
224 first = _fire(runtime, object_root, "il_1", "created")
225 assert first.result["changed"] is True
226
227 changes_before = object_record_changes.list_record_changes(
228 "invoices", record_id="inv_1", base_dir=data_dir
229 )["total"]
230
231 second = _fire(runtime, object_root, "il_1", "updated")
232 assert second.result["changed"] is False
233
234 changes_after = object_record_changes.list_record_changes(
235 "invoices", record_id="inv_1", base_dir=data_dir
236 )["total"]
237 assert changes_after == changes_before # no redundant write/record_change
238
239
240def test_deleting_a_line_recovers_invoice_id_from_record_changes_and_resums(tmp_path):
241 """The deleted line is already gone by the time this handler's
242 post-commit dispatch fires -- it must recover invoice_id from the
243 record_changes log's own 'before' snapshot, not the (now 404) live
244 record.
245 """
246 data_dir, object_root, runtime = _install(tmp_path)
247 _make_invoice(data_dir)
248 _make_line(data_dir, id="il_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
249 _make_line(data_dir, id="il_2", quantity="1", unit_price_cents="5000")
250 _fire(runtime, object_root, "il_1", "created")
251 _fire(runtime, object_root, "il_2", "created")
252
253 invoice = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
254 assert invoice["total_cents"] == "11492"
255
256 object_records.delete_collection_record("invoice_lines", "il_2", base_dir=data_dir, actor="test")
257 result = _fire(runtime, object_root, "il_2", "delete")
258 assert result.ok is True
259 assert result.result["invoice_id"] == "inv_1"
260
261 invoice_after = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
262 assert invoice_after["subtotal_cents"] == "5997"
263 assert invoice_after["tax_cents"] == "495"
264 assert invoice_after["total_cents"] == "6492"
265
266
267def test_deleting_a_line_with_the_real_dispatcher_verb_resums_the_invoice(tmp_path):
268 """object_server's dispatcher passes the RAW change verb ("create" /
269 "update" / "delete") in request["action"] -- only request["event"] uses
270 the past-participle form (see object_change_dispatch's payload-parity
271 note). The handler once compared against "deleted", so a real delete
272 fell through to the live-record lookup, found nothing, and silently
273 skipped the recompute.
274 """
275 data_dir, object_root, runtime = _install(tmp_path)
276 _add_payments_substrate(data_dir) # balance_due derives via payments now
277 _make_invoice(data_dir)
278 _make_line(data_dir, id="il_1", quantity="3", unit_price_cents="1999", tax_rate_bps="825")
279 _make_line(data_dir, id="il_2", quantity="1", unit_price_cents="5000")
280 _fire(runtime, object_root, "il_1", "create")
281 _fire(runtime, object_root, "il_2", "create")
282
283 before = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
284 assert before["total_cents"] == "11492"
285
286 object_records.delete_collection_record("invoice_lines", "il_2", base_dir=data_dir, actor="test")
287 result = _fire(runtime, object_root, "il_2", "delete")
288 assert result.ok is True
289 assert result.result["invoice_id"] == "inv_1"
290
291 after = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
292 assert after["subtotal_cents"] == "5997"
293 assert after["total_cents"] == "6492"
294
295
296def test_zero_lines_leaves_invoice_at_zero_totals(tmp_path):
297 data_dir, object_root, runtime = _install(tmp_path)
298 _add_payments_substrate(data_dir) # balance_due derives via payments now
299 _make_invoice(data_dir)
300
301 invoice = object_records.get_collection_record("invoices", "inv_1", base_dir=data_dir)
302 assert invoice["subtotal_cents"] == "0"
303 assert invoice["total_cents"] == "0"
304 assert invoice["balance_due_cents"] == "0"
305
306
307def test_event_for_an_unrelated_collection_is_a_no_op(tmp_path):
308 data_dir, object_root, runtime = _install(tmp_path)
309 result = object_execution.execute_object(
310 runtime,
311 object_execution.ObjectExecutionRequest(
312 "system_invoice_totals",
313 method="EVENT",
314 payload={"event": "notes.record.created", "collection": "notes",
315 "record_id": "n1", "action": "created"},
316 ),
317 roots=[object_root],
318 )
319 assert result.ok is True
320 assert result.result["skipped"] == "not an invoice_lines event"
321
322
323# -- Guarded status transitions -------------------------------------------
324#
325# Exercised directly against object_records' own guard (the same function
326# update_collection_record calls internally) rather than round-tripping
327# through the full HTTP server for one field's worth of behavior --
328# requires the schema actually installed in a data dir first, since
329# get_schema resolves from base_dir, not from package source.
330
331def test_owner_may_move_draft_to_sent(tmp_path):
332 data_dir, _object_root, _runtime = _install(tmp_path)
333 subject = object_permissions.PermissionSubject(user_id="u1")
334 existing = {"status": "draft", "owner_id": "u1"}
335 updated = {"status": "sent", "owner_id": "u1"}
336
337 object_records._validate_field_transitions(
338 "invoices", existing, updated, base_dir=data_dir, roots=None, subject=subject,
339 ) # no exception == allowed
340
341
342def test_who_moves_the_status_is_the_field_permission_not_a_guard(tmp_path):
343 """app-invoices 0.15.0 dropped the owner_id guards: the owner of a
344 machine-raised invoice is the customer it bills, so "the owner may send
345 it" was "the customer may mark it paid". A move is valid for any writer
346 the status field's permissions let write it (staff over the API; the
347 platform's reactions in process); the guard no longer decides."""
348 data_dir, _object_root, _runtime = _install(tmp_path)
349 subject = object_permissions.PermissionSubject(user_id="staff", roles=("manager",))
350 object_records._validate_field_transitions(
351 "invoices", {"status": "draft", "owner_id": "u1"},
352 {"status": "sent", "owner_id": "u1"}, base_dir=data_dir, roots=None, subject=subject,
353 ) # no exception == allowed
354 status = next(f for f in object_schemas.get_schema("invoices", base_dir=data_dir)["fields"]
355 if f["name"] == "status")
356 assert status["permissions"]["default"] == "read"
357 assert set(status["permissions"]["edit"]) == {"role:manager", "role:admin"}
358
359
360def test_paid_and_void_are_terminal(tmp_path):
361 data_dir, _object_root, _runtime = _install(tmp_path)
362 subject = object_permissions.PermissionSubject(user_id="u1")
363
364 for terminal_status in ("paid", "void"):
365 existing = {"status": terminal_status, "owner_id": "u1"}
366 updated = {"status": "draft", "owner_id": "u1"}
367 with pytest.raises(object_records.InvalidRecordPayloadError):
368 object_records._validate_field_transitions(
369 "invoices", existing, updated, base_dir=data_dir, roots=None, subject=subject,
370 )
371
372
373def test_sent_to_partial_then_partial_to_paid_is_a_legal_path(tmp_path):
374 data_dir, _object_root, _runtime = _install(tmp_path)
375 subject = object_permissions.PermissionSubject(user_id="u1")
376
377 object_records._validate_field_transitions(
378 "invoices", {"status": "sent", "owner_id": "u1"}, {"status": "partial", "owner_id": "u1"},
379 base_dir=data_dir, roots=None, subject=subject,
380 )
381 object_records._validate_field_transitions(
382 "invoices", {"status": "partial", "owner_id": "u1"}, {"status": "paid", "owner_id": "u1"},
383 base_dir=data_dir, roots=None, subject=subject,
384 )