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_shop_cart.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_shop_cart.py · 61.2 KB · 1369 lines
1"""The shop: basket, checkout, and a sale that posts itself.
2
3The cart is the easy part and everybody has one. What is worth testing is
4the seam: that a basket is not an order, that a price which moved is
5surfaced rather than silently resolved either way, and that stock leaves
6the shelf when money arrives and not one moment sooner.
7"""
8
9import pathlib
10
11import pytest
12
13from conftest import stage_collection
14
15import object_cart
16import object_execution
17import object_ids
18import object_records
19import python_object_runtime
20
21REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
22PACKAGES = REPO_ROOT / "packages"
23SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
24RUNTIME = python_object_runtime.PythonObjectRuntime()
25
26TOKEN = "sess-abc123"
27COOKIE = "cart"
28
29
30def setup_env(tmp_path, monkeypatch, *, settings=(), page=False):
31 data_dir = tmp_path / "data"
32 for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"),
33 ("app-catalog", "products"), ("app-catalog", "locations"),
34 ("app-catalog", "stock_moves"),
35 ("app-orders", "orders"), ("app-orders", "order_lines"),
36 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
37 ("app-payments", "payments")):
38 stage_collection(data_dir, pkg, name)
39 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
40 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
41 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
42 if page:
43 # site_shop calls its siblings by object id with no roots of its
44 # own, so the page tests need the shop's objects on the search path.
45 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(SHOP_OBJECTS))
46 return data_dir
47
48
49def product(data_dir, product_id, name, cents, **fields):
50 record = {"id": product_id, "name": name, "sku": product_id.upper(),
51 "product_type": "physical", "price_cents": str(cents),
52 "currency": "USD", "is_active": "true", "owner_id": "shop"}
53 record.update({k: str(v) for k, v in fields.items()})
54 return object_records.create_collection_record("products", record,
55 base_dir=data_dir)
56
57
58def location(data_dir, location_id, name, kind="warehouse"):
59 return object_records.create_collection_record(
60 "locations",
61 {"id": location_id, "name": name, "location_type": kind, "owner_id": "shop"},
62 base_dir=data_dir)
63
64
65def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
66 return object_records.create_collection_record(
67 "stock_moves",
68 {"id": object_ids.new_uuid4(), "product_id": product_id,
69 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
70 "occurred_at": "2026-06-01", "owner_id": "shop"},
71 base_dir=data_dir)
72
73
74def cart(action="get", **payload):
75 return object_execution.execute_object(
76 RUNTIME,
77 object_execution.ObjectExecutionRequest(
78 "action_cart", method="POST",
79 payload={"session_token": TOKEN, "action": action, **payload}),
80 roots=[SHOP_OBJECTS]).result
81
82
83def checkout(**payload):
84 return object_execution.execute_object(
85 RUNTIME,
86 object_execution.ObjectExecutionRequest(
87 "action_checkout", method="POST",
88 payload={"session_token": TOKEN, **payload}),
89 roots=[SHOP_OBJECTS]).result
90
91
92def fulfil(payment):
93 return object_execution.execute_object(
94 RUNTIME,
95 object_execution.ObjectExecutionRequest(
96 "system_shop_fulfillment", method="POST",
97 payload={"collection": "payments", "record": payment}),
98 roots=[SHOP_OBJECTS]).result
99
100
101def page(**payload):
102 """GET the public shop page, the way the site router would call it."""
103 payload.setdefault("_cookies", {COOKIE: TOKEN})
104 return object_execution.execute_object(
105 RUNTIME,
106 object_execution.ObjectExecutionRequest(
107 "site_shop", method="GET", payload=payload),
108 roots=[SHOP_OBJECTS]).result
109
110
111def orders(data_dir):
112 return object_records.read_collection_records("orders", base_dir=data_dir)
113
114
115def moves(data_dir):
116 return object_records.read_collection_records("stock_moves", base_dir=data_dir)
117
118
119def invoices(data_dir):
120 return object_records.read_collection_records("invoices", base_dir=data_dir)
121
122
123def invoice_lines(data_dir):
124 return object_records.read_collection_records("invoice_lines", base_dir=data_dir)
125
126
127# --- the arithmetic ----------------------------------------------------------
128
129def test_a_line_rounds_once_and_the_total_is_the_sum_of_the_lines():
130 """Fractional quantities are real -- 1.5 kg, 2.5 hours of setup."""
131 assert object_cart.line_total_cents("1.5", 333) == 500 # 499.5 -> 500
132 summary = object_cart.totals([
133 {"id": "a", "quantity": "1.5", "unit_price_cents": "333"},
134 {"id": "b", "quantity": "2", "unit_price_cents": "1000"},
135 ])
136 assert summary["subtotal_cents"] == 2500
137 assert sum(line["line_total_cents"] for line in summary["lines"]) == 2500
138
139
140def test_a_price_that_moved_is_reported_not_applied():
141 changes = object_cart.price_changes(
142 [{"id": "a", "product_id": "p1", "unit_price_cents": "1000"}],
143 {"p1": {"price_cents": "1200", "name": "Mug"}})
144 assert changes[0]["was_cents"] == 1000 and changes[0]["now_cents"] == 1200
145 assert changes[0]["direction"] == "up"
146
147
148def test_an_untracked_product_is_always_available():
149 """A service or a download has no stock level, and 'no level' must not
150 read as 'none left' -- that would refuse to sell what never runs out."""
151 items = [{"id": "a", "product_id": "svc", "quantity": "3"}]
152 assert object_cart.availability(items, {}, tracked=set()) == []
153
154
155def test_every_blocker_is_reported_at_once():
156 """Revealing problems one at a time is how a checkout gets abandoned."""
157 items = [{"id": "a", "product_id": "p1", "quantity": "5",
158 "unit_price_cents": "1000", "description": "Mug"},
159 {"id": "b", "product_id": "gone", "quantity": "1"}]
160 blockers = object_cart.checkout_blockers(
161 items, {"p1": {"price_cents": "1200", "is_active": "true"}},
162 {"p1": 2}, tracked={"p1"})
163 assert blockers["price_changes"] and blockers["unavailable"] and blockers["inactive"]
164 assert blockers["can_checkout"] is False
165
166
167# --- the basket ---------------------------------------------------------------
168
169def test_adding_stamps_the_price_it_had_at_the_time(tmp_path, monkeypatch):
170 data_dir = setup_env(tmp_path, monkeypatch)
171 product(data_dir, "p1", "Enamel Mug", 1200)
172 result = cart("add", product_id="p1", quantity="2")
173 assert result["subtotal_cents"] == 2400
174
175 item = object_records.read_collection_records("cart_items", base_dir=data_dir)[0]
176 assert item["unit_price_cents"] == "1200"
177 assert item["description"] == "Enamel Mug"
178
179
180def test_adding_the_same_thing_twice_increases_the_quantity(tmp_path, monkeypatch):
181 data_dir = setup_env(tmp_path, monkeypatch)
182 product(data_dir, "p1", "Mug", 1000)
183 cart("add", product_id="p1", quantity="1")
184 result = cart("add", product_id="p1", quantity="2")
185 assert result["count"] == "3"
186 assert len(object_records.read_collection_records("cart_items", base_dir=data_dir)) == 1
187
188
189def test_setting_a_quantity_to_zero_removes_the_line(tmp_path, monkeypatch):
190 data_dir = setup_env(tmp_path, monkeypatch)
191 product(data_dir, "p1", "Mug", 1000)
192 cart("add", product_id="p1")
193 result = cart("set", product_id="p1", quantity="0")
194 assert result["lines"] == []
195
196
197def test_an_empty_basket_is_an_answer_not_a_404(tmp_path, monkeypatch):
198 setup_env(tmp_path, monkeypatch)
199 result = cart("get")
200 assert result["ok"] and result["lines"] == [] and result["subtotal_cents"] == 0
201
202
203def test_something_not_for_sale_cannot_go_in_the_basket(tmp_path, monkeypatch):
204 data_dir = setup_env(tmp_path, monkeypatch)
205 product(data_dir, "p1", "Retired Mug", 1000, is_active="false")
206 assert cart("add", product_id="p1")["status"] == 409
207 assert cart("add", product_id="nope")["status"] == 404
208
209
210def test_no_stock_is_touched_by_putting_something_in_a_basket(
211 tmp_path, monkeypatch):
212 """Reserving on add is how a shop shows 'sold out' for goods nobody
213 bought."""
214 data_dir = setup_env(tmp_path, monkeypatch)
215 location(data_dir, "loc-shelf", "Shelf")
216 product(data_dir, "p1", "Mug", 1000)
217 stock_in(data_dir, "p1", 5)
218 cart("add", product_id="p1", quantity="3")
219 assert len(moves(data_dir)) == 1 # only the purchase
220
221
222# --- checkout -------------------------------------------------------------------
223
224def test_checkout_raises_a_draft_order_and_closes_the_basket(
225 tmp_path, monkeypatch):
226 data_dir = setup_env(tmp_path, monkeypatch)
227 location(data_dir, "loc-shelf", "Shelf")
228 product(data_dir, "p1", "Mug", 1200)
229 stock_in(data_dir, "p1", 10)
230 cart("add", product_id="p1", quantity="2")
231
232 result = checkout(customer_email="buyer@example.test", customer_name="Ada")
233 assert result["ok"] and result["status_of_order"] == "draft"
234
235 order = orders(data_dir)[0]
236 assert order["total_cents"] == "2400"
237 assert order["customer_email"] == "buyer@example.test"
238 assert order["doc_type"] == "sale"
239
240 lines = object_records.read_collection_records("order_lines", base_dir=data_dir)
241 assert len(lines) == 1 and lines[0]["line_total_cents"] == "2400"
242 assert len(moves(data_dir)) == 1 # still nothing moved
243
244
245def test_checkout_raises_the_invoice_that_the_buyer_pays(tmp_path, monkeypatch):
246 """An order with no invoice gives the buyer nothing to pay: the money is
247 owed and there is no document saying so and no door to walk through.
248
249 It is issued ("sent"), not a draft -- a draft would mean somebody in the
250 back office has to press a button before the shopper standing at the
251 counter can hand over money.
252 """
253 data_dir = setup_env(tmp_path, monkeypatch)
254 product(data_dir, "p1", "Mug", 1200, product_type="service")
255 cart("add", product_id="p1", quantity="2")
256
257 result = checkout(customer_email="buyer@example.test", customer_name="Ada")
258 invoice = invoices(data_dir)[0]
259 assert invoice["status"] == "sent"
260 assert invoice["total_cents"] == "2400" == orders(data_dir)[0]["total_cents"]
261 assert invoice["customer_email"] == "buyer@example.test"
262 assert invoice["number"] == orders(data_dir)[0]["number"]
263
264 # The join system_shop_fulfillment walks backwards from a payment.
265 assert orders(data_dir)[0]["invoice_id"] == invoice["id"]
266 assert result["invoice_id"] == invoice["id"]
267
268 # The response has to carry the door: the shopper is here NOW, and the
269 # portal-link handler mints post-commit and best-effort.
270 assert invoice["portal_token"]
271 assert result["pay_path"] == f"/pay/{invoice['portal_token']}"
272
273
274def test_the_invoice_lines_say_what_was_bought(tmp_path, monkeypatch):
275 """A single opaque total is a bill a customer can only dispute, not
276 check."""
277 data_dir = setup_env(tmp_path, monkeypatch)
278 product(data_dir, "p1", "Enamel Mug", 1200, product_type="service")
279 product(data_dir, "p2", "Setup", 2500, product_type="service")
280 cart("add", product_id="p1", quantity="2")
281 cart("add", product_id="p2")
282 checkout(customer_email="buyer@example.test")
283
284 lines = sorted(invoice_lines(data_dir), key=lambda row: row["description"])
285 assert [line["description"] for line in lines] == ["Enamel Mug", "Setup"]
286 assert [line["line_total_cents"] for line in lines] == ["2400", "2500"]
287 assert lines[0]["quantity"] == "2"
288 assert lines[0]["unit_price_cents"] == "1200"
289 assert {line["invoice_id"] for line in lines} == {invoices(data_dir)[0]["id"]}
290
291
292def test_the_invoice_records_the_order_it_came_from(tmp_path, monkeypatch):
293 """Provenance in notes, the house pattern: invoices carry no
294 generated_from column, so the marker goes where anyone asking where this
295 bill came from can find it."""
296 data_dir = setup_env(tmp_path, monkeypatch)
297 product(data_dir, "p1", "Mug", 1000, product_type="service")
298 cart("add", product_id="p1")
299 order_id = checkout(customer_email="buyer@example.test")["order_id"]
300 assert f"orders/{order_id}" in invoices(data_dir)[0]["notes"]
301
302
303def test_the_due_date_follows_the_billing_setting(tmp_path, monkeypatch):
304 data_dir = setup_env(tmp_path, monkeypatch,
305 settings=(("billing.invoice_due_days", "30"),))
306 product(data_dir, "p1", "Mug", 1000, product_type="service")
307 cart("add", product_id="p1")
308 checkout(customer_email="buyer@example.test", today="2026-06-15")
309 invoice = invoices(data_dir)[0]
310 assert invoice["issue_date"] == "2026-06-15"
311 assert invoice["due_date"] == "2026-07-15"
312
313
314def test_checking_out_twice_makes_one_order(tmp_path, monkeypatch):
315 """And one invoice, with the SAME door handed back -- a shopper who
316 double-clicked needs the link again, not a second bill."""
317 data_dir = setup_env(tmp_path, monkeypatch)
318 product(data_dir, "p1", "Download", 500, product_type="service")
319 cart("add", product_id="p1")
320 first = checkout(customer_email="buyer@example.test")
321 again = checkout(customer_email="buyer@example.test")
322 assert again["duplicate"] is True
323 assert again["order_id"] == first["order_id"]
324 assert again["pay_path"] == first["pay_path"]
325 assert len(orders(data_dir)) == 1
326 assert len(invoices(data_dir)) == 1
327
328
329def test_a_price_change_stops_checkout_and_shows_both_numbers(
330 tmp_path, monkeypatch):
331 """Charging the new price silently is a bait-and-switch; honouring a
332 three-week-old basket forever is an open-ended liability."""
333 data_dir = setup_env(tmp_path, monkeypatch)
334 product(data_dir, "p1", "Mug", 1000, product_type="service")
335 cart("add", product_id="p1")
336 object_records.update_collection_record(
337 "products", "p1", {"price_cents": "1400"}, base_dir=data_dir, actor="shop")
338
339 blocked = checkout(customer_email="buyer@example.test")
340 assert blocked["status"] == 409
341 assert blocked["price_changes"][0]["was_cents"] == 1000
342 assert blocked["price_changes"][0]["now_cents"] == 1400
343 assert orders(data_dir) == []
344
345
346def test_confirming_the_new_price_orders_at_the_new_price(tmp_path, monkeypatch):
347 data_dir = setup_env(tmp_path, monkeypatch)
348 product(data_dir, "p1", "Mug", 1000, product_type="service")
349 cart("add", product_id="p1")
350 object_records.update_collection_record(
351 "products", "p1", {"price_cents": "1400"}, base_dir=data_dir, actor="shop")
352
353 result = checkout(customer_email="buyer@example.test", confirm_prices="true")
354 assert result["ok"] and result["total_cents"] == 1400
355 assert orders(data_dir)[0]["total_cents"] == "1400"
356
357
358def test_not_enough_stock_stops_checkout_with_the_numbers(tmp_path, monkeypatch):
359 data_dir = setup_env(tmp_path, monkeypatch)
360 location(data_dir, "loc-shelf", "Shelf")
361 product(data_dir, "p1", "Mug", 1000)
362 stock_in(data_dir, "p1", 2)
363 cart("add", product_id="p1", quantity="5")
364
365 blocked = checkout(customer_email="buyer@example.test")
366 assert blocked["status"] == 409
367 assert blocked["unavailable"][0]["available"] == "2"
368 assert blocked["unavailable"][0]["short_by"] == "3"
369
370
371def test_an_emptied_basket_cannot_be_checked_out(tmp_path, monkeypatch):
372 """A basket somebody filled and then emptied still exists; there is
373 just nothing in it to sell."""
374 data_dir = setup_env(tmp_path, monkeypatch)
375 product(data_dir, "p1", "Mug", 1000, product_type="service")
376 cart("add", product_id="p1")
377 cart("clear")
378 assert checkout(customer_email="buyer@example.test")["status"] == 400
379
380
381def test_checking_out_a_session_with_no_basket_says_so(tmp_path, monkeypatch):
382 setup_env(tmp_path, monkeypatch)
383 assert checkout(customer_email="buyer@example.test")["status"] == 404
384
385
386def test_checkout_needs_somewhere_to_send_the_receipt(tmp_path, monkeypatch):
387 data_dir = setup_env(tmp_path, monkeypatch)
388 product(data_dir, "p1", "Mug", 1000, product_type="service")
389 cart("add", product_id="p1")
390 assert checkout()["status"] == 400
391
392
393def test_preview_prices_the_basket_without_ordering(tmp_path, monkeypatch):
394 data_dir = setup_env(tmp_path, monkeypatch)
395 product(data_dir, "p1", "Mug", 1000, product_type="service")
396 cart("add", product_id="p1", quantity="2")
397 result = checkout(preview="true")
398 assert result["subtotal_cents"] == 2000 and orders(data_dir) == []
399
400
401# --- money arrives, the sale becomes real -----------------------------------------
402
403SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
404
405
406def test_an_unreadable_stock_ledger_stops_checkout_rather_than_selling_blind(
407 tmp_path, monkeypatch):
408 """A tracked product whose level could not be read was skipped, which
409 availability() reads as "not tracked": two on the shelf, five ordered,
410 and the order went through. Unknown stock is a 503 with nothing
411 ordered, and the same checkout is refused for the real numbers once the
412 ledger reads again."""
413 from test_findings_money_gates import failing_reads
414
415 data_dir = setup_env(tmp_path, monkeypatch)
416 location(data_dir, "loc-shelf", "Shelf")
417 product(data_dir, "p1", "Mug", 1000)
418 stock_in(data_dir, "p1", 2)
419 cart("add", product_id="p1", quantity="5")
420
421 with failing_reads("stock_moves", "object_stock.py") as fired:
422 refused = checkout(customer_email="buyer@example.test")
423 assert fired, "the simulated failure never reached the stock read"
424 assert refused.get("status") == 503, refused
425 assert "stock" in refused["error"]
426 assert orders(data_dir) == []
427
428 assert checkout(customer_email="buyer@example.test")["status"] == 409
429
430
431def test_a_shop_with_no_stock_ledger_installed_still_sells(tmp_path, monkeypatch):
432 """Not installed is a fact: nothing is tracked, so nothing runs out."""
433 import shutil
434
435 data_dir = setup_env(tmp_path, monkeypatch)
436 product(data_dir, "p1", "Mug", 1000)
437 shutil.rmtree(data_dir / "collections" / "stock_moves")
438 (data_dir / "schemas" / "stock_moves.json").unlink()
439 cart("add", product_id="p1", quantity="5")
440 placed = checkout(customer_email="buyer@example.test")
441 assert placed.get("order_id"), placed
442
443
444@pytest.mark.parametrize("unreadable", ["payments", "refunds", "invoices"])
445def test_money_that_cannot_be_counted_ships_nothing(tmp_path, monkeypatch, unreadable):
446 """Unreadable payments, refunds or invoice read as "settled" ("do not
447 hold the goods hostage to a lookup failure"), so a part-paid or
448 refunded order went out of the door. Not knowing whether the bill is
449 paid is not knowing: the order is left as it was, the result says why,
450 and the next payment event ships it once the money can be counted."""
451 from test_findings_money_gates import failing_reads
452
453 data_dir = setup_env(tmp_path, monkeypatch,
454 settings=(("shop.stock_location", "loc-shelf"),
455 ("shop.customer_location", "loc-customer")))
456 stage_collection(data_dir, "app-payments", "refunds")
457 with_shipping(tmp_path, monkeypatch, data_dir)
458 order_id, payment = paid_order(data_dir)
459
460 if unreadable == "invoices":
461 real = object_records.get_collection_record
462
463 def failing(collection, *args, **kwargs):
464 if collection == "invoices":
465 raise OSError("simulated: invoices unreadable")
466 return real(collection, *args, **kwargs)
467
468 monkeypatch.setattr(object_records, "get_collection_record", failing)
469 result = fulfil(payment)
470 monkeypatch.setattr(object_records, "get_collection_record", real)
471 else:
472 with failing_reads(unreadable, "shop_fulfillment.py") as fired:
473 result = fulfil(payment)
474 assert fired, "the simulated failure never reached the handler"
475
476 assert unreadable in result["skipped"], result
477 assert shipments(data_dir) == []
478 assert object_records.get_collection_record(
479 "orders", order_id, base_dir=data_dir)["status"] == "draft"
480
481 again = fulfil(payment)
482 assert again["confirmed"] and again["moved"] == 1
483
484
485def with_shipping(tmp_path, monkeypatch, data_dir):
486 """Install app-shipping alongside the shop, the way a real box has it.
487
488 Payment no longer writes stock moves itself: it raises a SHIPMENT and
489 lets app-shipping's system_order_fulfillment move the goods (see
490 objects/system/shop_fulfillment.py's docstring). Two consequences for a
491 test: the two shipping collections have to exist, and both packages'
492 objects have to live under ONE object root, because that is what an
493 installed server looks like and the only way a sibling call by object id
494 resolves the way it will in production.
495
496 shutil is imported here rather than at the top of the file to keep this
497 change contained to the fulfillment tests.
498 """
499 import shutil
500
501 for name in ("shipments", "shipment_lines"):
502 stage_collection(data_dir, "app-shipping", name)
503 objects_root = tmp_path / "objects"
504 for source in (SHOP_OBJECTS, SHIPPING_OBJECTS):
505 shutil.copytree(source, objects_root, dirs_exist_ok=True)
506 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
507 return objects_root
508
509
510def shipments(data_dir):
511 return object_records.read_collection_records("shipments", base_dir=data_dir)
512
513
514def paid_order(data_dir, *, quantity="2"):
515 """Take an order all the way to a received payment.
516
517 The invoice is the one checkout raised, not a hand-made stand-in: paying
518 against a fake invoice would let the order/invoice join rot without a
519 single test noticing.
520 """
521 location(data_dir, "loc-shelf", "Shelf")
522 location(data_dir, "loc-customer", "Customers", kind="customer")
523 product(data_dir, "p1", "Mug", 1200)
524 stock_in(data_dir, "p1", 10)
525 cart("add", product_id="p1", quantity=quantity)
526 placed = checkout(customer_email="buyer@example.test", customer_name="Ada")
527 order_id, invoice_id = placed["order_id"], placed["invoice_id"]
528
529 payment = object_records.create_collection_record(
530 "payments",
531 {"id": object_ids.new_uuid4(), "invoice_id": invoice_id,
532 "amount_cents": "2400", "method": "card", "received_on": "2026-06-15",
533 "status": "received", "owner_id": "shop"},
534 base_dir=data_dir)
535 return order_id, payment
536
537
538def test_stock_leaves_the_shelf_when_the_money_arrives(tmp_path, monkeypatch):
539 data_dir = setup_env(tmp_path, monkeypatch,
540 settings=(("shop.stock_location", "loc-shelf"),
541 ("shop.customer_location", "loc-customer")))
542 with_shipping(tmp_path, monkeypatch, data_dir)
543 order_id, payment = paid_order(data_dir)
544 result = fulfil(payment)
545 assert result["confirmed"] and result["moved"] == 1
546
547 sale = [m for m in moves(data_dir) if m["reason"] == "sale"][0]
548 assert sale["quantity"] == "2"
549 assert sale["from_location_id"] == "loc-shelf"
550
551 # The same chain, now travelling through the shipment noun: there is a
552 # document saying what went out, and the move is stamped with the line
553 # it came from rather than with the whole order.
554 shipment = shipments(data_dir)[0]
555 assert shipment["order_id"] == order_id and shipment["status"] == "shipped"
556 assert f"shipments/{shipment['id']}:line/" in sale["reference"]
557 assert object_records.get_collection_record(
558 "orders", order_id, base_dir=data_dir)["status"] == "shipped"
559
560
561def test_a_replayed_payment_moves_nothing_twice(tmp_path, monkeypatch):
562 data_dir = setup_env(tmp_path, monkeypatch,
563 settings=(("shop.stock_location", "loc-shelf"),
564 ("shop.customer_location", "loc-customer")))
565 with_shipping(tmp_path, monkeypatch, data_dir)
566 _, payment = paid_order(data_dir)
567 fulfil(payment)
568 again = fulfil(payment)
569 assert again["skipped"] == "order already shipped"
570 assert len([m for m in moves(data_dir) if m["reason"] == "sale"]) == 1
571 assert len(shipments(data_dir)) == 1 # and no second parcel
572
573
574def test_a_payment_for_something_else_is_left_alone(tmp_path, monkeypatch):
575 data_dir = setup_env(tmp_path, monkeypatch)
576 object_records.create_collection_record(
577 "invoices",
578 {"id": "inv-unrelated", "number": "INV-9", "customer_name": "Someone",
579 "status": "sent", "issue_date": "2026-06-15", "due_date": "2026-06-29",
580 "subtotal_cents": "500", "total_cents": "500", "owner_id": "shop"},
581 base_dir=data_dir)
582 payment = object_records.create_collection_record(
583 "payments",
584 {"id": object_ids.new_uuid4(), "invoice_id": "inv-unrelated",
585 "amount_cents": "500", "method": "card", "received_on": "2026-06-15",
586 "status": "received", "owner_id": "shop"},
587 base_dir=data_dir)
588 assert fulfil(payment)["skipped"] == "no web order for this payment"
589
590
591def test_a_bounced_payment_fulfils_nothing(tmp_path, monkeypatch):
592 data_dir = setup_env(tmp_path, monkeypatch,
593 settings=(("shop.stock_location", "loc-shelf"),))
594 order_id, payment = paid_order(data_dir)
595 object_records.update_collection_record(
596 "payments", payment["id"], {"status": "bounced"},
597 base_dir=data_dir, actor="shop")
598 bounced = object_records.get_collection_record("payments", payment["id"],
599 base_dir=data_dir)
600 assert fulfil(bounced)["skipped"] == "payment not received"
601 assert object_records.get_collection_record(
602 "orders", order_id, base_dir=data_dir)["status"] == "draft"
603
604
605def test_an_unconfigured_location_still_lets_the_sale_stand(tmp_path, monkeypatch):
606 """A missing setting must not cost somebody a paid order -- and now it
607 must not cost them the parcel either: the box still goes out, and the
608 gap in the ledger is reported rather than swallowed."""
609 data_dir = setup_env(tmp_path, monkeypatch)
610 with_shipping(tmp_path, monkeypatch, data_dir)
611 order_id, payment = paid_order(data_dir)
612 result = fulfil(payment)
613 assert result["confirmed"] and result["moved"] == 0
614 assert "stock_location" in result["warning"]
615 assert shipments(data_dir)[0]["status"] == "shipped"
616 assert object_records.get_collection_record(
617 "orders", order_id, base_dir=data_dir)["status"] == "shipped"
618
619
620# --- the page a shopper actually looks at ------------------------------------
621
622def test_a_product_card_links_to_the_product(tmp_path, monkeypatch):
623 """The grid was a dead end: names were bold text, so a shopper could add
624 a thing to a basket but never find out what it was."""
625 data_dir = setup_env(tmp_path, monkeypatch, page=True)
626 product(data_dir, "p1", "Enamel Mug", 1200)
627 body = page()["body"]
628 assert '<a href="/shop/p1">Enamel Mug</a>' in body
629
630
631def test_the_product_page_says_what_it_is_and_offers_to_sell_it(
632 tmp_path, monkeypatch):
633 """Name, price and full description in one place, with an add form that
634 posts to /shop -- the SAME route the cards post to, so there is one way
635 into a basket rather than two that can drift apart."""
636 data_dir = setup_env(tmp_path, monkeypatch, page=True)
637 product(data_dir, "p1", "Enamel Mug", 1200,
638 description="Twelve ounces. Chips beautifully.")
639 body = page(product_id="p1")["body"]
640
641 assert "Enamel Mug" in body
642 assert "P1" in body # the sku
643 assert "12.00" in body
644 assert "Twelve ounces. Chips beautifully." in body
645 assert '<form method="post" action="/shop"' in body
646 assert 'name="do" value="add"' in body
647 assert f'name="session_token" value="{TOKEN}"' in body
648 assert 'name="product_id" value="p1"' in body
649 assert '<a href="/shop">Back to shop</a>' in body
650
651
652def test_a_physical_product_says_whether_it_is_there(tmp_path, monkeypatch):
653 """Low-key, but the question every shopper has. Derived from the stock
654 ledger, never stored."""
655 data_dir = setup_env(tmp_path, monkeypatch, page=True)
656 location(data_dir, "loc-shelf", "Shelf")
657 product(data_dir, "p1", "Mug", 1200)
658 product(data_dir, "p2", "Bowl", 900)
659 stock_in(data_dir, "p1", 4)
660 assert "In stock" in page(product_id="p1")["body"]
661 assert "Sold out" in page(product_id="p2")["body"]
662
663
664def test_something_that_never_runs_out_says_nothing_about_stock(
665 tmp_path, monkeypatch):
666 """An hour of work has no shelf. Saying "Out of stock" about it would
667 refuse a sale that checkout would happily take."""
668 data_dir = setup_env(tmp_path, monkeypatch, page=True)
669 product(data_dir, "p1", "Setup", 2500, product_type="service")
670 body = page(product_id="p1")["body"]
671 assert "In stock" not in body and "Sold out" not in body
672
673
674def test_an_unknown_product_is_a_friendly_404_not_a_traceback(
675 tmp_path, monkeypatch):
676 """A mistyped link is a shopper who is still in the shop."""
677 setup_env(tmp_path, monkeypatch, page=True)
678 result = page(product_id="no-such-thing")
679 assert result["status"] == 404
680 assert result["content_type"].startswith("text/html")
681 assert "Back to shop" in result["body"]
682 assert "Traceback" not in result["body"]
683
684
685def test_a_withdrawn_product_reads_the_same_as_a_missing_one(
686 tmp_path, monkeypatch):
687 """Distinguishing them would tell a stranger which product ids exist."""
688 data_dir = setup_env(tmp_path, monkeypatch, page=True)
689 product(data_dir, "p1", "Retired Mug", 1000, is_active="false")
690 assert page(product_id="p1")["status"] == 404
691
692
693def test_the_page_reuses_the_basket_the_cookie_names(tmp_path, monkeypatch):
694 """The bug this whole change exists for: a returning shopper's basket
695 was minted fresh every visit, so nothing ever survived a page load."""
696 data_dir = setup_env(tmp_path, monkeypatch, page=True)
697 product(data_dir, "p1", "Mug", 1200, product_type="service")
698 cart("add", product_id="p1", quantity="2")
699
700 result = page()
701 assert "24.00" in result["body"] # the basket total
702 # A cookie the browser already holds is not re-set on every response.
703 assert "set_cookie" not in result
704
705
706def test_a_shopper_with_no_cookie_is_given_one(tmp_path, monkeypatch):
707 """Path-scoped, http-only, SameSite=Lax: it says WHICH basket, never
708 who, and it is useless anywhere but here. Given when the first thing
709 goes in the basket, carrying the token action_cart minted: a visitor
710 who only looks gets no cookie and writes no basket row."""
711 data_dir = setup_env(tmp_path, monkeypatch, page=True)
712 product(data_dir, "p1", "Mug", 1200, product_type="service")
713 assert "set_cookie" not in page(_cookies={})
714 result = object_execution.execute_object(
715 RUNTIME,
716 object_execution.ObjectExecutionRequest(
717 "site_shop", method="POST",
718 payload={"_cookies": {}, "do": "add", "product_id": "p1",
719 "quantity": "1"}),
720 roots=[SHOP_OBJECTS]).result
721 cookie = result["set_cookie"]
722 assert cookie.startswith("cart=")
723 minted = cookie.split(";")[0][len("cart="):]
724 carts = object_records.read_collection_records("carts", base_dir=data_dir)
725 assert [c["session_token"] for c in carts] == [minted] and len(minted) >= 32
726 assert "Path=/" in cookie and "HttpOnly" in cookie
727 assert "SameSite=Lax" in cookie and "Max-Age=1209600" in cookie
728 # The old key is gone: the server accepts `set_cookie` and nothing else.
729 assert "headers" not in result
730
731
732# =============================================================================
733# TAX AND POSTAGE
734#
735# The shop charged neither, which was a compliance problem and a straight
736# money leak: every parcel went out with the delivery paid by the seller.
737# What is worth testing here is not that a percentage can be multiplied --
738# it is that the percentage is applied ONCE to the whole sale, that postage
739# is a line a customer can read rather than a number welded into a total,
740# and that a shop which has configured none of it bills exactly as it did
741# before. Absent configuration must look like today, never like a broken
742# tax line.
743# =============================================================================
744
745# --- the arithmetic, with no data directory in sight -------------------------
746
747def test_tax_rounds_half_up_once_over_the_whole_sale():
748 """Four fifty-cent lines at 5% are 10c of tax, not 12c.
749
750 Rounded per line, 2.5c becomes 3c four times over and the shop
751 overcharges by 2c that no customer can reconcile against the rate
752 printed on the bill. Tax is owed on a sale, not on each row of it.
753 """
754 items = [{"id": f"i{n}", "quantity": "1", "unit_price_cents": "50"}
755 for n in range(4)]
756 folded = object_cart.checkout_totals(items, tax_rate_bps=500)
757 assert folded["subtotal_cents"] == 200
758 assert folded["tax_cents"] == 10 # 10.0, not 4 x 3
759 assert sum(object_cart.tax_cents(50, 500) for _ in range(4)) == 12
760 assert folded["total_cents"] == 210
761
762
763def test_a_rate_of_zero_is_a_real_answer_not_a_missing_setting():
764 """Plenty of small sellers owe none, and must be able to say so."""
765 assert object_cart.tax_cents(10_000, 0) == 0
766 assert object_cart.tax_cents(0, 1500) == 0
767 assert object_cart.tax_cents(10_000, 1500) == 1500 # 1500bps = 15%
768 assert object_cart.tax_cents(1099, 825) == 91 # 90.6675 -> 91
769
770
771def test_postage_is_flat_until_the_basket_earns_its_way_past_the_threshold():
772 """The boundary is AT the threshold, not past it: a shop advertising
773 'free over $50' and then charging on a $50 basket has lied on its own
774 banner."""
775 assert object_cart.shipping_cents(4999, 500, 5000) == 500
776 assert object_cart.shipping_cents(5000, 500, 5000) == 0 # exactly
777 assert object_cart.shipping_cents(5001, 500, 5000) == 0
778 # No threshold configured: postage is always charged.
779 assert object_cart.shipping_cents(1_000_000, 500, 0) == 500
780
781
782def test_a_flat_rate_of_zero_disables_shipping_entirely():
783 """A digital-only shop charges no postage and must not be made to show
784 a zero line for it."""
785 assert object_cart.shipping_cents(10_000, 0, 0) == 0
786 folded = object_cart.checkout_totals(
787 [{"id": "a", "quantity": "1", "unit_price_cents": "1000"}],
788 shipping_flat_cents=0)
789 assert folded["shipping_cents"] == 0
790 assert folded["shipping_free"] is False # not free -- simply not sold
791 assert folded["total_cents"] == 1000
792
793
794def test_the_flag_decides_whether_the_postage_itself_is_taxed():
795 """Jurisdictions genuinely disagree about this, so the seller chooses."""
796 items = [{"id": "a", "quantity": "1", "unit_price_cents": "1000"}]
797 goods_only = object_cart.checkout_totals(
798 items, tax_rate_bps=1000, shipping_flat_cents=500, tax_shipping=False)
799 assert goods_only["tax_cents"] == 100 # 10% of 1000
800 assert goods_only["total_cents"] == 1600
801
802 with_postage = object_cart.checkout_totals(
803 items, tax_rate_bps=1000, shipping_flat_cents=500, tax_shipping=True)
804 assert with_postage["tax_cents"] == 150 # 10% of 1500
805 assert with_postage["total_cents"] == 1650
806
807
808def test_free_shipping_is_distinguishable_from_no_shipping():
809 """A bare 0 cannot tell 'you saved the postage' from 'this shop does
810 not post things', and only one of those is worth saying out loud."""
811 items = [{"id": "a", "quantity": "1", "unit_price_cents": "5000"}]
812 earned = object_cart.checkout_totals(
813 items, shipping_flat_cents=500, free_over_cents=5000)
814 assert earned["shipping_cents"] == 0 and earned["shipping_free"] is True
815 never = object_cart.checkout_totals(items, shipping_flat_cents=0)
816 assert never["shipping_cents"] == 0 and never["shipping_free"] is False
817
818
819# --- what checkout writes down ------------------------------------------------
820
821TAXED_AND_POSTED = (("shop.tax_rate_bps", "1000"),
822 ("shop.shipping_flat_cents", "500"))
823
824
825def sold(data_dir, *, cents=1000, quantity="1", products=1):
826 """Put something untracked in the basket -- the money is the subject
827 here, not the shelf."""
828 for n in range(products):
829 product(data_dir, f"p{n}", f"Thing {n}", cents, product_type="service")
830 cart("add", product_id=f"p{n}", quantity=quantity)
831
832
833def test_checkout_charges_postage_as_a_line_and_tax_as_a_total(
834 tmp_path, monkeypatch):
835 """The bill a customer can actually check: every line adds up to the
836 subtotal, the tax is stated, and the three come to the total."""
837 data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED)
838 sold(data_dir, cents=1000)
839 result = checkout(customer_email="buyer@example.test")
840
841 assert result["subtotal_cents"] == 1000
842 assert result["shipping_cents"] == 500
843 assert result["tax_cents"] == 100 # 10% of goods; postage untaxed
844 assert result["total_cents"] == 1600 # what the payer owes
845
846 lines = sorted(invoice_lines(data_dir), key=lambda row: row["description"])
847 assert [line["description"] for line in lines] == ["Shipping", "Thing 0"]
848 shipping_line = lines[0]
849 assert shipping_line["quantity"] == "1"
850 assert shipping_line["unit_price_cents"] == "500"
851 assert shipping_line["line_total_cents"] == "500"
852 # Postage is not taxable here, so the line says nothing about tax.
853 assert not shipping_line["tax_rate_bps"]
854
855 invoice = invoices(data_dir)[0]
856 assert invoice["subtotal_cents"] == "1500" # goods + postage
857 assert invoice["tax_cents"] == "100"
858 assert invoice["total_cents"] == "1600"
859 # The property that makes a bill checkable rather than disputable.
860 assert (sum(int(line["line_total_cents"]) for line in lines)
861 + int(invoice["tax_cents"])) == int(invoice["total_cents"])
862
863
864def test_the_order_records_the_tax_and_the_grand_total(tmp_path, monkeypatch):
865 """Subtotal stays goods -- it is defined as the sum of the order's own
866 lines, and postage is not one of them. Postage on an order is implied
867 by total - subtotal - tax until orders grows a shipping_cents column;
868 the itemisation lives on the invoice, where a customer reads it."""
869 data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED)
870 sold(data_dir, cents=1000)
871 checkout(customer_email="buyer@example.test")
872
873 order = orders(data_dir)[0]
874 assert order["subtotal_cents"] == "1000"
875 assert order["tax_cents"] == "100"
876 assert order["total_cents"] == "1600"
877 assert (int(order["total_cents"]) - int(order["subtotal_cents"])
878 - int(order["tax_cents"])) == 500
879
880
881def test_taxable_postage_says_so_on_its_own_line(tmp_path, monkeypatch):
882 """Somebody auditing 'was delivery taxed?' should find the answer on
883 the line, not reverse-engineer it out of a total."""
884 data_dir = setup_env(tmp_path, monkeypatch, settings=(
885 ("shop.tax_rate_bps", "1000"), ("shop.tax_shipping", "true"),
886 ("shop.shipping_flat_cents", "500")))
887 sold(data_dir, cents=1000)
888 result = checkout(customer_email="buyer@example.test")
889
890 assert result["tax_cents"] == 150 # 10% of 1000 + 500
891 assert result["total_cents"] == 1650
892 shipping_line = [l for l in invoice_lines(data_dir)
893 if l["description"] == "Shipping"][0]
894 assert shipping_line["tax_rate_bps"] == "1000"
895 assert shipping_line["line_tax_cents"] == "50"
896
897
898def test_a_basket_over_the_threshold_ships_free_and_is_billed_that_way(
899 tmp_path, monkeypatch):
900 data_dir = setup_env(tmp_path, monkeypatch, settings=(
901 ("shop.shipping_flat_cents", "500"),
902 ("shop.shipping_free_over_cents", "2000")))
903 sold(data_dir, cents=2000) # exactly the threshold
904 result = checkout(customer_email="buyer@example.test")
905
906 assert result["shipping_cents"] == 0 and result["shipping_free"] is True
907 assert result["total_cents"] == 2000
908 # No postage charged means no postage line: a free-shipping invoice
909 # with a "Shipping 0.00" row on it invites a question that has no
910 # answer.
911 assert [l["description"] for l in invoice_lines(data_dir)] == ["Thing 0"]
912
913
914def test_rounding_once_survives_the_whole_checkout(tmp_path, monkeypatch):
915 """The same 10c-not-12c case, driven end to end -- because the fold
916 being right is worth nothing if checkout re-derives tax per line on
917 its way to the invoice."""
918 data_dir = setup_env(tmp_path, monkeypatch,
919 settings=(("shop.tax_rate_bps", "500"),))
920 sold(data_dir, cents=50, products=4)
921 result = checkout(customer_email="buyer@example.test")
922 assert result["subtotal_cents"] == 200
923 assert result["tax_cents"] == 10
924 assert result["total_cents"] == 210
925 assert invoices(data_dir)[0]["tax_cents"] == "10"
926
927
928def test_a_shop_that_configures_nothing_bills_exactly_as_it_did(
929 tmp_path, monkeypatch):
930 """The regression that matters most: absent configuration must be
931 invisible. No postage line, no tax, and an invoice line carrying the
932 same populated fields it carried before any of this existed."""
933 data_dir = setup_env(tmp_path, monkeypatch) # no settings at all
934 sold(data_dir, cents=1200, quantity="2")
935 result = checkout(customer_email="buyer@example.test")
936
937 assert result["total_cents"] == 2400 == result["subtotal_cents"]
938 assert result["shipping_cents"] == 0 and result["tax_cents"] == 0
939
940 lines = invoice_lines(data_dir)
941 assert len(lines) == 1 # no Shipping row
942 populated = {k for k, v in lines[0].items() if str(v or "").strip()}
943 # line_tax_cents is the schema's own default of "0" and was there
944 # before any of this; tax_rate_bps has no default and stays empty,
945 # which is what "this line was never taxed" looks like on disk.
946 # order_line_id is the link to the order line it bills (invoice_lines
947 # v4), which is not money and changes nothing the customer is billed.
948 assert populated == {"id", "invoice_id", "description", "quantity",
949 "unit_price_cents", "line_total_cents", "owner_id",
950 "created_at", "line_tax_cents", "order_line_id"}
951 assert lines[0]["line_tax_cents"] == "0"
952 assert lines[0]["tax_rate_bps"] == ""
953 invoice = invoices(data_dir)[0]
954 assert invoice["subtotal_cents"] == "2400" == invoice["total_cents"]
955 assert invoice["tax_cents"] == "0"
956 assert orders(data_dir)[0]["total_cents"] == "2400"
957
958
959def test_preview_shows_the_whole_breakdown_before_anybody_commits(
960 tmp_path, monkeypatch):
961 """A preview exists so somebody can see what they are about to owe; a
962 subtotal alone hides the two numbers they most want to check."""
963 data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED)
964 sold(data_dir, cents=1000)
965 result = checkout(preview="true")
966 assert result["subtotal_cents"] == 1000
967 assert result["shipping_cents"] == 500
968 assert result["tax_cents"] == 100
969 assert result["total_cents"] == 1600
970 assert orders(data_dir) == [] and invoices(data_dir) == []
971
972
973# --- what the shopper sees before deciding -------------------------------------
974
975def test_the_basket_page_breaks_the_total_down(tmp_path, monkeypatch):
976 """A shopper who meets a surprise at the last step abandons the
977 basket. The footer is where postage and tax stop being a surprise."""
978 data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED,
979 page=True)
980 product(data_dir, "p1", "Mug", 1000, product_type="service")
981 cart("add", product_id="p1")
982 body = page()["body"]
983 assert "Subtotal" in body and "10.00" in body
984 assert "Shipping" in body and "5.00" in body
985 assert "Tax" in body and "1.00" in body
986 assert "16.00" in body # the total
987
988
989def test_the_basket_page_says_free_shipping_when_it_is_earned(
990 tmp_path, monkeypatch):
991 """The one delighter in a basket. A silent 0.00 reads as a shop that
992 forgot to charge, not one that gave the shopper something."""
993 data_dir = setup_env(tmp_path, monkeypatch, page=True, settings=(
994 ("shop.shipping_flat_cents", "500"),
995 ("shop.shipping_free_over_cents", "2000")))
996 product(data_dir, "p1", "Mug", 2000, product_type="service")
997 cart("add", product_id="p1")
998 body = page()["body"]
999 assert "Free shipping" in body
1000 assert "Subtotal" in body
1001
1002
1003def test_the_basket_page_is_untouched_when_nothing_is_configured(
1004 tmp_path, monkeypatch):
1005 """Zero-rows are not neutral: 'Shipping 0.00' and 'Tax 0.00' read as a
1006 broken shop rather than one that does not do those things."""
1007 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1008 product(data_dir, "p1", "Mug", 1200, product_type="service")
1009 cart("add", product_id="p1", quantity="2")
1010 body = page()["body"]
1011 assert "Shipping" not in body and "Subtotal" not in body
1012 assert "24.00" in body
1013 assert '<tfoot><tr><th colspan="3">Total</th>' in body
1014
1015
1016# =============================================================================
1017# MERCHANDISING
1018#
1019# Categories, variants and the two words a shopper types at checkout. The
1020# basket did not change to support any of it -- a variant IS a product, so
1021# every add, price check and stock check here is the same code path it
1022# always was -- which is exactly why the tests belong beside the basket's:
1023# what they hold is that the page collapses and groups without the basket
1024# learning a new noun, and that the one refusal this adds says what to do
1025# instead. The full variant/image/gift story lives in
1026# tests/test_merchandising.py; this section is the basket's own view of it.
1027# =============================================================================
1028
1029def variants(data_dir, *, parent_cents=0):
1030 """A parent that is a heading and one variant that is a real thing."""
1031 product(data_dir, "tote", "Tote Bag", parent_cents, category="Bags")
1032 product(data_dir, "tote-m", "Tote Bag, medium", 2000, category="Bags",
1033 product_type="service", parent_product_id="tote",
1034 options='{"size": "M", "colour": "navy"}')
1035
1036
1037def test_the_index_groups_by_category_and_never_hides_the_unfiled(
1038 tmp_path, monkeypatch):
1039 """Alphabetical headings, uncategorised last under "Everything else".
1040 Last, not gone: a product nobody got round to filing is still stock
1041 somebody paid for."""
1042 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1043 product(data_dir, "p1", "Enamel Mug", 1200, category="Kitchen")
1044 product(data_dir, "p2", "Linocut Print", 4000, category="Art")
1045 product(data_dir, "p3", "Odd Thing", 500)
1046 body = page()["body"]
1047
1048 assert '<h2 class="shop-category">Art</h2>' in body
1049 assert '<h2 class="shop-category">Everything else</h2>' in body
1050 assert body.index("Art</h2>") < body.index("Kitchen</h2>")
1051 assert body.index("Kitchen</h2>") < body.index("Everything else</h2>")
1052 assert "Odd Thing" in body[body.index("Everything else</h2>"):]
1053
1054
1055def test_a_parent_shows_one_card_and_the_basket_refuses_it_by_name(
1056 tmp_path, monkeypatch):
1057 """The card is a doorway, not an Add button: the parent has no price
1058 of its own, so there is nothing to charge and nothing to pick. The
1059 refusal names the options, because a "no" that does not say what to do
1060 instead is a lost sale."""
1061 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1062 variants(data_dir)
1063 body = page()["body"]
1064
1065 assert body.count('<div class="shop-card">') == 1
1066 assert "Tote Bag, medium" not in body # collapsed, not listed
1067 assert "Choose options" in body and "from USD 20.00" in body
1068 assert 'name="do" value="add"' not in body
1069
1070 refused = cart("add", product_id="tote")
1071 assert refused["status"] == 409
1072 assert "M / navy" in refused["error"]
1073 assert refused["options"][0]["product_id"] == "tote-m"
1074
1075
1076def test_adding_a_variant_is_an_ordinary_add(tmp_path, monkeypatch):
1077 """The whole argument, in the basket: a product_id went in and a
1078 description came out. Nothing here knows what a variant is."""
1079 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1080 variants(data_dir)
1081 assert cart("add", product_id="tote-m")["subtotal_cents"] == 2000
1082 item = object_records.read_collection_records("cart_items",
1083 base_dir=data_dir)[0]
1084 assert item["description"] == "Tote Bag, medium"
1085
1086 body = page()["body"]
1087 assert "Tote Bag, medium" in body # the basket line
1088 assert "20.00" in body
1089
1090
1091def test_the_checkout_form_carries_the_note_and_the_gift_message(
1092 tmp_path, monkeypatch):
1093 """Straight through the page to action_checkout, which decides where
1094 they land. Both optional, and no gift flag: the packing slip shows no
1095 prices by construction, so every parcel is already gift-safe."""
1096 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1097 product(data_dir, "p1", "Mug", 1200, product_type="service")
1098 cart("add", product_id="p1")
1099 assert '<textarea name="customer_note"' in page()["body"]
1100
1101 result = checkout(customer_email="buyer@example.test",
1102 customer_note="Leave with the neighbour",
1103 gift_message="Happy birthday, Ada")
1104 basket = object_records.get_collection_record("carts", result["cart_id"],
1105 base_dir=data_dir)
1106 assert basket["customer_note"] == "Leave with the neighbour"
1107 assert basket["gift_message"] == "Happy birthday, Ada"
1108
1109
1110def test_a_product_with_no_category_and_no_variants_renders_as_it_always_did(
1111 tmp_path, monkeypatch):
1112 """The regression guard. Every field this slice added is optional, and
1113 a shop that sets none of them must not be able to tell it happened --
1114 apart from the photograph placeholder, which is the one deliberate
1115 change to a page that was text-only."""
1116 data_dir = setup_env(tmp_path, monkeypatch, page=True)
1117 product(data_dir, "p1", "Enamel Mug", 1200, product_type="service")
1118 body = page()["body"]
1119
1120 assert '<a href="/shop/p1">Enamel Mug</a>' in body
1121 assert "USD 12.00" in body
1122 assert 'name="product_id" value="p1"' in body
1123 assert '<h2 class="shop-category">' not in body
1124 assert '<div class="shop-image placeholder"></div>' in body
1125 assert cart("add", product_id="p1", quantity="2")["subtotal_cents"] == 2400
1126
1127
1128# --- money bugs found by walking the live shop -------------------------------
1129#
1130# Neither of these was caught by the suite, and the reason is worth
1131# recording: the tests exercised objects directly, while the live server
1132# runs them through the event dispatcher. The gap between "the object is
1133# right" and "the system is right" is exactly where both of these lived.
1134
1135def test_a_totals_recompute_never_zeroes_tax_it_cannot_see(tmp_path, monkeypatch):
1136 """The live failure: a customer was quoted 2116 at checkout, and by the
1137 time the invoice lines had been written the totals handler had restated
1138 the invoice to 2000 with tax 0 -- because tax is computed once over the
1139 whole sale and stamped on the DOCUMENT, and that pass only reads lines.
1140 A fold must not replace a value it cannot reproduce."""
1141 data_dir = setup_env(tmp_path, monkeypatch,
1142 settings=(("shop.tax_rate_bps", "825"),
1143 ("shop.shipping_flat_cents", "600")))
1144 product(data_dir, "p1", "Mug", 1400, product_type="service")
1145 cart("add", product_id="p1")
1146 quoted = checkout(customer_email="grace@example.test")
1147
1148 invoice = object_records.get_collection_record(
1149 "invoices", quoted["invoice_id"], base_dir=data_dir)
1150 assert int(invoice["total_cents"]) == quoted["total_cents"]
1151
1152 # Now run the recompute the live server runs on every line write, with
1153 # the payload the dispatcher really sends: the RAW verb in `action`, the
1154 # participle only in `event`, and a real record id. (This test used to
1155 # send action "created" and record_id "", which invoice_totals returns
1156 # on at its first guard -- so it passed whether or not the fold's
1157 # "must not replace a value it cannot reproduce" rule existed.)
1158 lines = [line for line in object_records.read_collection_records(
1159 "invoice_lines", base_dir=data_dir)
1160 if line["invoice_id"] == quoted["invoice_id"]]
1161 assert sorted(line["description"] for line in lines) == ["Mug", "Shipping"]
1162 for line in lines:
1163 ran = object_execution.execute_object(
1164 RUNTIME,
1165 object_execution.ObjectExecutionRequest(
1166 "system_invoice_totals", method="EVENT",
1167 payload={"event": "invoice_lines.record.created",
1168 "collection": "invoice_lines", "action": "create",
1169 "record_id": line["id"]}),
1170 roots=[PACKAGES / "app-invoices" / "objects"])
1171 assert ran.ok, ran.error
1172 # Proof the fold was reached for this line, not skipped at a guard.
1173 assert ran.result.get("invoice_id") == quoted["invoice_id"], ran.result
1174
1175 after = object_records.get_collection_record(
1176 "invoices", quoted["invoice_id"], base_dir=data_dir)
1177 assert int(after["total_cents"]) == quoted["total_cents"], (
1178 "the recompute silently dropped the tax the customer agreed to")
1179 assert int(after["tax_cents"]) > 0
1180
1181
1182def test_a_part_payment_does_not_ship_the_goods(tmp_path, monkeypatch):
1183 """Goods leave when the BILL is settled, not when money merely
1184 arrives. Paying 14.00 against a 20.00 invoice used to fulfil the order
1185 in full while the invoice sat at `partial` saying otherwise."""
1186 data_dir = setup_env(tmp_path, monkeypatch,
1187 settings=(("shop.stock_location", "loc-shelf"),
1188 ("shop.customer_location", "loc-customer")))
1189 order_id, _ = paid_order(data_dir) # pays in full
1190 order = object_records.get_collection_record("orders", order_id,
1191 base_dir=data_dir)
1192 invoice_id = order["invoice_id"]
1193
1194 # A second order, deliberately underpaid.
1195 cart("add", product_id="p1", quantity="2")
1196 second = checkout(customer_email="short@example.test")
1197 part = object_records.create_collection_record(
1198 "payments",
1199 {"id": object_ids.new_uuid4(), "invoice_id": second["invoice_id"],
1200 "amount_cents": "1", "method": "card", "received_on": "2026-07-26",
1201 "status": "received", "owner_id": "shop"},
1202 base_dir=data_dir)
1203
1204 result = fulfil(part)
1205 assert "not settled" in result["skipped"]
1206 assert object_records.get_collection_record(
1207 "orders", second["order_id"], base_dir=data_dir)["status"] == "draft"
1208 assert invoice_id # the fully paid one is untouched by this test
1209
1210
1211def test_paying_the_balance_later_does_ship(tmp_path, monkeypatch):
1212 """A deposit followed by the balance must work: the payment that tips
1213 the invoice to settled is the one that ships."""
1214 data_dir = setup_env(tmp_path, monkeypatch,
1215 settings=(("shop.stock_location", "loc-shelf"),
1216 ("shop.customer_location", "loc-customer")))
1217 location(data_dir, "loc-shelf", "Shelf")
1218 location(data_dir, "loc-customer", "Customers", kind="customer")
1219 product(data_dir, "p1", "Mug", 1200)
1220 stock_in(data_dir, "p1", 10)
1221 cart("add", product_id="p1", quantity="1")
1222 order = checkout(customer_email="deposit@example.test")
1223 total = order["total_cents"]
1224
1225 half = object_records.create_collection_record(
1226 "payments",
1227 {"id": object_ids.new_uuid4(), "invoice_id": order["invoice_id"],
1228 "amount_cents": str(total // 2), "method": "card",
1229 "received_on": "2026-07-26", "status": "received", "owner_id": "shop"},
1230 base_dir=data_dir)
1231 assert "not settled" in fulfil(half)["skipped"]
1232
1233 rest = object_records.create_collection_record(
1234 "payments",
1235 {"id": object_ids.new_uuid4(), "invoice_id": order["invoice_id"],
1236 "amount_cents": str(total - total // 2), "method": "card",
1237 "received_on": "2026-07-26", "status": "received", "owner_id": "shop"},
1238 base_dir=data_dir)
1239 assert fulfil(rest)["confirmed"] is True
1240
1241
1242# --- one payment, one shipment -------------------------------------------------
1243
1244def test_two_concurrent_deliveries_of_one_payment_ship_once(tmp_path,
1245 monkeypatch):
1246 """Goods leaving twice against one payment, reproduced before it was
1247 fixed: two shipments, FOUR units against an order of two, two sale
1248 moves.
1249
1250 Nothing in the shipping layer could have stopped it.
1251 action_create_shipment works out what is unshipped by reading
1252 shipment_lines, and hook_shipment_lines refuses an over-ship by summing
1253 them -- but both are check-then-write, and a hook runs BEFORE the write
1254 lock, so both passes read an empty history and both wrote. Layered
1255 advisory checks do not compose into an atomic one.
1256
1257 The fix is the one thing on this box that IS atomic: a compare-and-set
1258 on a single record (63). The claim is the write that moves the order
1259 out of the shippable set, and the loser finds the row already changed.
1260 """
1261 import threading
1262
1263 data_dir = setup_env(tmp_path, monkeypatch,
1264 settings=(("shop.stock_location", "loc-shelf"),
1265 ("shop.customer_location", "loc-customer")))
1266 with_shipping(tmp_path, monkeypatch, data_dir)
1267 order_id, payment = paid_order(data_dir)
1268
1269 out = []
1270 threads = [threading.Thread(target=lambda: out.append(fulfil(payment)))
1271 for _ in range(2)]
1272 for thread in threads:
1273 thread.start()
1274 for thread in threads:
1275 thread.join()
1276
1277 lines = object_records.read_collection_records("shipment_lines",
1278 base_dir=data_dir)
1279 shipments = object_records.read_collection_records("shipments",
1280 base_dir=data_dir)
1281 sales = [m for m in moves(data_dir) if m["reason"] == "sale"]
1282
1283 assert len(shipments) == 1, out
1284 assert sum(float(line["quantity"]) for line in lines) == 2.0
1285 assert len(sales) == 1
1286
1287 # And the loser says so rather than reporting a silent success.
1288 # There are three honest ways to lose, depending on where the loser
1289 # looked: the winner's compare-and-set landed between the loser's read
1290 # and its own claim ("claimed"), or between the draft->confirmed step
1291 # and the claim ("handling"), or BEFORE the loser read the order at all,
1292 # in which case the loser sees `processing` (or later, `shipped`) and
1293 # stops at the status guard ("order already <status>"). All three are
1294 # refusals made before any write, so the invariants asserted above (one
1295 # shipment, one sale move, quantities shipped once) are what prove the
1296 # loser did nothing; the message only has to say it stood down.
1297 skipped = [r for r in out if r.get("skipped")]
1298 assert len(skipped) == 1
1299 reason = skipped[0]["skipped"]
1300 assert ("claimed" in reason or "handling" in reason
1301 or reason.startswith("order already ")), reason
1302 assert not skipped[0].get("shipped"), skipped[0]
1303 assert not skipped[0].get("shipment_id"), skipped[0]
1304
1305 # Exactly one winner, and it is the one that shipped.
1306 winners = [r for r in out if not r.get("skipped")]
1307 assert len(winners) == 1, out
1308 assert winners[0].get("shipped") is True, out
1309 assert winners[0].get("shipment_id") == shipments[0]["id"], out
1310
1311
1312def test_an_order_waiting_on_the_pick_list_is_not_claimed(tmp_path, monkeypatch):
1313 """With auto_fulfill off the order is supposed to SIT at `confirmed`
1314 waiting for a person. Claiming it would take it off the very list it
1315 needs to be on."""
1316 data_dir = setup_env(tmp_path, monkeypatch,
1317 settings=(("shop.stock_location", "loc-shelf"),
1318 ("shop.customer_location", "loc-customer"),
1319 ("shop.auto_fulfill", "false")))
1320 with_shipping(tmp_path, monkeypatch, data_dir)
1321 order_id, payment = paid_order(data_dir)
1322
1323 result = fulfil(payment)
1324 assert result["shipped"] is False
1325 assert "pick list" in result["note"]
1326
1327 order = object_records.get_collection_record("orders", order_id,
1328 base_dir=data_dir)
1329 assert order["status"] == "confirmed"
1330
1331
1332def test_an_already_confirmed_order_is_also_shipped_only_once(tmp_path,
1333 monkeypatch):
1334 """The case the draft->confirmed promote cannot cover, and the reason
1335 the claim exists as a second step.
1336
1337 A deposit followed by a balance payment is the ordinary shape: the
1338 first payment confirms the order without settling the invoice, and the
1339 SECOND is the one that tips it to paid and ships. That second event
1340 finds the order already at `confirmed`, so the promote above is not
1341 reached and only the claim stands between two concurrent deliveries
1342 and two shipments.
1343 """
1344 import threading
1345
1346 data_dir = setup_env(tmp_path, monkeypatch,
1347 settings=(("shop.stock_location", "loc-shelf"),
1348 ("shop.customer_location", "loc-customer")))
1349 with_shipping(tmp_path, monkeypatch, data_dir)
1350 order_id, payment = paid_order(data_dir)
1351
1352 object_records.update_collection_record(
1353 "orders", order_id, {"status": "confirmed"}, base_dir=data_dir)
1354
1355 out = []
1356 threads = [threading.Thread(target=lambda: out.append(fulfil(payment)))
1357 for _ in range(2)]
1358 for thread in threads:
1359 thread.start()
1360 for thread in threads:
1361 thread.join()
1362
1363 shipments = object_records.read_collection_records("shipments",
1364 base_dir=data_dir)
1365 lines = object_records.read_collection_records("shipment_lines",
1366 base_dir=data_dir)
1367 assert len(shipments) == 1, out
1368 assert sum(float(line["quantity"]) for line in lines) == 2.0
1369 assert len([m for m in moves(data_dir) if m["reason"] == "sale"]) == 1