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_shipping.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, 18 minutes ago History
test_shipping.py · 45.0 KB · 993 lines
1"""Shipments: the document that says what physically moved.
2
3The properties worth holding here are the ones a shop discovers the hard
4way. You cannot ship more than was ordered, and being told so is only
5useful if the refusal carries the numbers. Two shipments against one order
6derive partial then shipped, each exactly once, without anybody typing a
7status. A replayed event moves no stock twice, because events ARE replayed
8(object_change_dispatch promises at-least-once). A packing slip carries no
9prices, ever, which is what makes every parcel gift-safe with no flag to
10forget. And the zero-touch shop keeps working: payment still ships the
11order and still moves the stock -- it just travels through the shipment
12noun now.
13"""
14
15import pathlib
16import re
17import shutil
18import sys
19
20import pytest
21
22from conftest import stage_collection
23
24import object_execution
25import object_ids
26import object_records
27import python_object_runtime
28
29REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
30PACKAGES = REPO_ROOT / "packages"
31SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
32SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
33RUNTIME = python_object_runtime.PythonObjectRuntime()
34
35TOKEN = "sess-ship-1"
36
37
38def setup_env(tmp_path, monkeypatch, *, settings=()):
39 """A data dir with every collection this slice touches, and ONE object
40 root holding both packages' objects.
41
42 The merged root is not a convenience: it is what an installed server
43 actually looks like (every package installs into the same objects
44 directory), and it is the only way an object that calls a sibling by id
45 -- system_shop_fulfillment reaching action_create_shipment -- resolves
46 the way it will in production.
47 """
48 data_dir = tmp_path / "data"
49 for pkg, name in (("app-shipping", "shipments"),
50 ("app-shipping", "shipment_lines"),
51 ("app-shop", "carts"), ("app-shop", "cart_items"),
52 ("app-catalog", "products"), ("app-catalog", "locations"),
53 ("app-catalog", "stock_moves"),
54 ("app-orders", "orders"), ("app-orders", "order_lines"),
55 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
56 ("app-payments", "payments")):
57 stage_collection(data_dir, pkg, name)
58 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
59 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
60
61 objects_root = tmp_path / "objects"
62 for source in (SHIPPING_OBJECTS, SHOP_OBJECTS):
63 shutil.copytree(source, objects_root, dirs_exist_ok=True)
64
65 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
66 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
67 return data_dir, objects_root
68
69
70def run(objects_root, object_id, method, payload):
71 return object_execution.execute_object(
72 RUNTIME,
73 object_execution.ObjectExecutionRequest(
74 object_id, method=method, payload=payload),
75 roots=[objects_root]).result
76
77
78# --- fixtures shaped like a real shop -----------------------------------------
79
80def product(data_dir, product_id, name, cents=1200):
81 return object_records.create_collection_record(
82 "products",
83 {"id": product_id, "name": name, "sku": product_id.upper(),
84 "product_type": "physical", "price_cents": str(cents),
85 "currency": "USD", "is_active": "true", "owner_id": "shop"},
86 base_dir=data_dir)
87
88
89def location(data_dir, location_id, name, kind="warehouse"):
90 return object_records.create_collection_record(
91 "locations",
92 {"id": location_id, "name": name, "location_type": kind, "owner_id": "shop"},
93 base_dir=data_dir)
94
95
96def order(data_dir, order_id="ord-1", *, status="confirmed", number="SO-0001",
97 owner="shop", **fields):
98 record = {"id": order_id, "doc_type": "sale", "number": number,
99 "customer_name": "Ada Lovelace",
100 "customer_email": "ada@example.test", "currency": "USD",
101 "status": "draft", "order_date": "2026-07-01", "owner_id": owner}
102 record.update({k: str(v) for k, v in fields.items()})
103 created = object_records.create_collection_record("orders", record,
104 base_dir=data_dir)
105 if status != "draft":
106 # Through the ladder, the way a human would: draft is where every
107 # order starts.
108 object_records.update_collection_record(
109 "orders", order_id, {"status": "confirmed"},
110 base_dir=data_dir, actor="test")
111 if status != "confirmed":
112 object_records.update_collection_record(
113 "orders", order_id, {"status": status},
114 base_dir=data_dir, actor="test")
115 created = object_records.get_collection_record("orders", order_id,
116 base_dir=data_dir)
117 return created
118
119
120def order_line(data_dir, line_id, order_id="ord-1", *, product_id="p1",
121 description="Enamel Mug", quantity="3", cents=1200):
122 return object_records.create_collection_record(
123 "order_lines",
124 {"id": line_id, "order_id": order_id, "product_id": product_id,
125 "description": description, "quantity": str(quantity),
126 "unit_price_cents": str(cents),
127 "line_total_cents": str(int(float(quantity) * cents)),
128 "owner_id": "shop"},
129 base_dir=data_dir)
130
131
132def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
133 return object_records.create_collection_record(
134 "stock_moves",
135 {"id": object_ids.new_uuid4(), "product_id": product_id,
136 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
137 "occurred_at": "2026-06-01", "owner_id": "shop"},
138 base_dir=data_dir)
139
140
141def shipments(data_dir):
142 return object_records.read_collection_records("shipments", base_dir=data_dir)
143
144
145def shipment_lines(data_dir):
146 return object_records.read_collection_records("shipment_lines",
147 base_dir=data_dir)
148
149
150def sales(data_dir):
151 return [move for move in object_records.read_collection_records(
152 "stock_moves", base_dir=data_dir) if move["reason"] == "sale"]
153
154
155def order_status(data_dir, order_id="ord-1"):
156 return object_records.get_collection_record("orders", order_id,
157 base_dir=data_dir)["status"]
158
159
160def create_shipment(objects_root, **payload):
161 """As the shop that owns the order: the action refuses anybody the
162 permission engine would not let update it."""
163 payload.setdefault("_identity", {"user_id": "shop"})
164 return run(objects_root, "action_create_shipment", "POST", payload)
165
166
167def hook(objects_root, record, action="create"):
168 return run(objects_root, "hook_shipment_lines", "BEFORE_WRITE",
169 {"action": action, "collection": "shipment_lines", "record": record})
170
171
172def fulfil_shipment(objects_root, shipment_id, *, today=None):
173 """The dispatcher's own payload shape: EVENT verb, record_id, raw action.
174
175 `today` is the same optional stamp every other pass in this house takes
176 -- the handler dates the handover with it, so a test can put parcels on
177 a named day instead of on whatever day it is being run.
178 """
179 payload = {"event": "shipments.record.updated", "collection": "shipments",
180 "record_id": shipment_id, "action": "update"}
181 if today:
182 payload["today"] = today
183 return run(objects_root, "system_order_fulfillment", "EVENT", payload)
184
185
186def ship(data_dir, objects_root, shipment_id, *, today=None):
187 """Take a shipment out of the door the way a packer would, then let the
188 handler react to it."""
189 for status in ("packed", "shipped"):
190 object_records.update_collection_record(
191 "shipments", shipment_id, {"status": status},
192 base_dir=data_dir, actor="test")
193 return fulfil_shipment(objects_root, shipment_id, today=today)
194
195
196def stocked_shop(tmp_path, monkeypatch, *, quantity="3", auto=None,
197 status="confirmed"):
198 settings = [("shop.stock_location", "loc-shelf"),
199 ("shop.customer_location", "loc-customer")]
200 if auto is not None:
201 settings.append(("shop.auto_fulfill", auto))
202 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=settings)
203 location(data_dir, "loc-shelf", "Shelf")
204 location(data_dir, "loc-customer", "Customers", kind="customer")
205 product(data_dir, "p1", "Enamel Mug")
206 stock_in(data_dir, "p1", 20)
207 order(data_dir, status=status)
208 order_line(data_dir, "line-1", quantity=quantity)
209 return data_dir, objects_root
210
211
212# --- the gate ------------------------------------------------------------------
213
214def test_over_shipping_is_refused_with_all_three_numbers(tmp_path, monkeypatch):
215 """"No" is not an answer a packer can act on. Which of the two shipments
216 is wrong is only knowable from the numbers."""
217 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
218 first = create_shipment(objects_root, order_id="ord-1",
219 lines=[{"order_line_id": "line-1", "quantity": "2"}])
220 assert first["ok"]
221
222 refused = hook(objects_root, {"id": object_ids.new_uuid4(),
223 "shipment_id": first["shipment_id"],
224 "order_line_id": "line-1", "quantity": "2"})
225 assert refused["status"] == 409
226 assert "ordered 3" in refused["error"]
227 assert "already on shipments 2" in refused["error"]
228 assert "would make 4" in refused["error"]
229
230
231def test_the_action_reports_over_shipping_before_writing_anything(
232 tmp_path, monkeypatch):
233 """The hook guards the generic write path; the action has to guard its
234 own, because trusted server-side writes bypass hooks by design."""
235 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
236 create_shipment(objects_root, order_id="ord-1",
237 lines=[{"order_line_id": "line-1", "quantity": "2"}])
238
239 refused = create_shipment(objects_root, order_id="ord-1",
240 lines=[{"order_line_id": "line-1", "quantity": "2"}])
241 assert refused["status"] == 409
242 assert refused["over_ship"][0] == {
243 "order_line_id": "line-1", "description": "Enamel Mug",
244 "ordered": "3", "already_on_shipments": "2", "asked_for": "2",
245 "would_make": "4"}
246 assert len(shipments(data_dir)) == 1 # nothing half-written
247
248
249def test_a_shipped_shipment_refuses_new_lines(tmp_path, monkeypatch):
250 """A manifest is settled once it leaves the dock: a forgotten item is a
251 NEW shipment, not a rewrite of what the courier already took."""
252 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
253 created = create_shipment(objects_root, order_id="ord-1",
254 lines=[{"order_line_id": "line-1", "quantity": "1"}])
255 ship(data_dir, objects_root, created["shipment_id"])
256
257 refused = hook(objects_root, {"id": object_ids.new_uuid4(),
258 "shipment_id": created["shipment_id"],
259 "order_line_id": "line-1", "quantity": "1"})
260 assert refused["status"] == 409
261 assert "already shipped" in refused["error"]
262
263
264def test_a_shipment_line_must_ship_something(tmp_path, monkeypatch):
265 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
266 created = create_shipment(objects_root, order_id="ord-1",
267 lines=[{"order_line_id": "line-1", "quantity": "1"}])
268 # The schema's `exclusive_min: 0` on quantity (no longer the hook's), so
269 # the action and an import meet it as well as the HTTP write path.
270 for quantity in ("0", "-1"):
271 with pytest.raises(object_records.InvalidRecordPayloadError):
272 object_records.create_collection_record(
273 "shipment_lines",
274 {"id": object_ids.new_uuid4(), "shipment_id": created["shipment_id"],
275 "order_line_id": "line-1", "quantity": quantity},
276 base_dir=data_dir)
277 line_id = object_records.read_collection_records("shipment_lines", base_dir=data_dir)[0]["id"]
278 for quantity in ("0", ""):
279 with pytest.raises(object_records.InvalidRecordPayloadError):
280 object_records.update_collection_record(
281 "shipment_lines", line_id, {"quantity": quantity}, base_dir=data_dir)
282 with pytest.raises(object_records.InvalidRecordPayloadError,
283 match="'quantity' must be greater than 0"):
284 object_records.create_collection_record(
285 "shipment_lines",
286 {"id": object_ids.new_uuid4(), "shipment_id": created["shipment_id"],
287 "order_line_id": "line-1", "quantity": "0"},
288 base_dir=data_dir)
289 assert len(object_records.read_collection_records(
290 "shipment_lines", base_dir=data_dir)) == 1
291
292
293def test_lines_of_a_lost_shipment_do_not_consume_the_order(tmp_path, monkeypatch):
294 """The goods never arrived, so the order still owes them -- being refused
295 for re-sending a lost parcel would be the paperwork punishing the shop
296 for doing the right thing."""
297 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
298 created = create_shipment(objects_root, order_id="ord-1")
299 ship(data_dir, objects_root, created["shipment_id"])
300 object_records.update_collection_record(
301 "shipments", created["shipment_id"], {"status": "lost"},
302 base_dir=data_dir, actor="test")
303
304 again = create_shipment(objects_root, order_id="ord-1")
305 assert again["ok"] and again["lines"] == 1
306 assert again["shipment_lines"][0]["quantity"] == "3"
307
308
309# --- partial fulfillment is a count, not a flag ---------------------------------
310
311def test_two_shipments_derive_partial_then_shipped_exactly_once_each(
312 tmp_path, monkeypatch):
313 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
314
315 first = create_shipment(objects_root, order_id="ord-1",
316 lines=[{"order_line_id": "line-1", "quantity": "2"}])
317 result = ship(data_dir, objects_root, first["shipment_id"])
318 assert result["order_status"] == "partial"
319 assert order_status(data_dir) == "partial"
320 assert result["moved"] == 1
321
322 second = create_shipment(objects_root, order_id="ord-1")
323 assert second["shipment_lines"][0]["quantity"] == "1" # the remainder
324 result = ship(data_dir, objects_root, second["shipment_id"])
325 assert result["order_status"] == "shipped"
326 assert order_status(data_dir) == "shipped"
327
328 assert len(sales(data_dir)) == 2
329 assert sorted(move["quantity"] for move in sales(data_dir)) == ["1", "2"]
330
331
332def test_a_replayed_shipped_event_moves_nothing_twice(tmp_path, monkeypatch):
333 """Events are replayed by design -- the change dispatcher promises
334 at-least-once. The per-line provenance marker is what makes that safe."""
335 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
336 created = create_shipment(objects_root, order_id="ord-1")
337 first = ship(data_dir, objects_root, created["shipment_id"])
338 assert first["moved"] == 1
339
340 again = fulfil_shipment(objects_root, created["shipment_id"])
341 assert again["moved"] == 0
342 assert len(sales(data_dir)) == 1
343 marker = f"shipments/{created['shipment_id']}:line/"
344 assert marker in sales(data_dir)[0]["reference"]
345
346
347def test_every_shipment_delivered_makes_the_order_delivered(tmp_path, monkeypatch):
348 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
349 created = create_shipment(objects_root, order_id="ord-1")
350 ship(data_dir, objects_root, created["shipment_id"])
351 object_records.update_collection_record(
352 "shipments", created["shipment_id"], {"status": "delivered"},
353 base_dir=data_dir, actor="test")
354
355 result = fulfil_shipment(objects_root, created["shipment_id"])
356 assert result["order_status"] == "delivered"
357 assert len(sales(data_dir)) == 1 # delivery moves nothing new
358
359
360def test_a_cancelled_order_is_never_touched_by_fulfillment(tmp_path, monkeypatch):
361 """Fulfillment must not resurrect an order somebody called off -- a
362 parcel sent against it is a mistake to reverse, not a status to derive."""
363 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
364 created = create_shipment(objects_root, order_id="ord-1")
365 object_records.update_collection_record(
366 "orders", "ord-1", {"status": "cancelled"}, base_dir=data_dir, actor="test")
367
368 result = ship(data_dir, objects_root, created["shipment_id"])
369 assert result["skipped"] == "order is cancelled"
370 assert sales(data_dir) == []
371 assert order_status(data_dir) == "cancelled"
372
373
374def test_a_missing_stock_location_still_lets_the_parcel_go(tmp_path, monkeypatch):
375 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
376 product(data_dir, "p1", "Enamel Mug")
377 order(data_dir)
378 order_line(data_dir, "line-1")
379
380 created = create_shipment(objects_root, order_id="ord-1")
381 result = ship(data_dir, objects_root, created["shipment_id"])
382 assert result["moved"] == 0
383 assert "shop.stock_location" in result["warning"]
384 assert result["order_status"] == "shipped" # the box still went out
385
386
387def test_a_sale_whose_average_cost_cannot_be_read_ships_uncosted_and_says_so(
388 tmp_path, monkeypatch):
389 """The goods were bought at 800; the product's typed-in standard cost is
390 500. With the locations unreadable the average cannot be computed, and
391 the handler stamped the sale at 500 -- a planning figure written down
392 as the cost of goods for good, with nothing to show it was a guess
393 (hook_stock_moves refuses exactly this; a reaction cannot refuse a
394 parcel that has left). Now the parcel still ships and the move is still
395 written, but with no cost, a marker in its reference, and a warning in
396 the handler's result: an honest gap somebody can find and book, rather
397 than a wrong number nobody will look at again."""
398 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
399 object_records.update_collection_record(
400 "products", "p1", {"cost_cents": "500"}, base_dir=data_dir, actor="test")
401 object_records.create_collection_record(
402 "stock_moves",
403 {"id": "bought", "product_id": "p1", "to_location_id": "loc-shelf",
404 "quantity": "5", "unit_cost_cents": "800", "reason": "purchase",
405 "occurred_at": "2026-06-02", "owner_id": "shop"},
406 base_dir=data_dir)
407 created = create_shipment(objects_root, order_id="ord-1")
408
409 real = object_records.read_collection_records
410
411 def failing(collection, *args, **kwargs):
412 if collection == "locations" and sys._getframe(1).f_code.co_filename.endswith(
413 "object_stock.py"):
414 raise OSError("simulated: locations unreadable")
415 return real(collection, *args, **kwargs)
416
417 monkeypatch.setattr(object_records, "read_collection_records", failing)
418 result = ship(data_dir, objects_root, created["shipment_id"])
419 monkeypatch.setattr(object_records, "read_collection_records", real)
420
421 assert result["moved"] == 1
422 assert result["order_status"] == "shipped" # the box still went out
423 [sale] = sales(data_dir)
424 assert sale["unit_cost_cents"] == "" # not the standard 500
425 assert "[uncosted: its cost could not be read]" in sale["reference"]
426 assert f"shipments/{created['shipment_id']}:line/" in sale["reference"]
427 assert "could not be costed" in result["warning"]
428 assert sale["id"] in result["uncosted_moves"]
429
430
431def test_a_sale_whose_product_cannot_be_read_is_marked_uncosted_too(tmp_path, monkeypatch):
432 """No priced stock sends the cost to the product's standard cost; a
433 product that cannot be READ is the same unknown as an unreadable
434 average, and used to leave the move silently costless."""
435 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
436 created = create_shipment(objects_root, order_id="ord-1")
437 real = object_records.get_collection_record
438
439 def failing(collection, *args, **kwargs):
440 if collection == "products" and sys._getframe(1).f_code.co_filename.endswith(
441 "order_fulfillment.py"):
442 raise OSError("simulated: products unreadable")
443 return real(collection, *args, **kwargs)
444
445 monkeypatch.setattr(object_records, "get_collection_record", failing)
446 result = ship(data_dir, objects_root, created["shipment_id"])
447 monkeypatch.setattr(object_records, "get_collection_record", real)
448
449 [sale] = sales(data_dir)
450 assert sale["unit_cost_cents"] == ""
451 assert "[uncosted:" in sale["reference"]
452 assert result["uncosted_moves"] == [sale["id"]]
453 assert result["order_status"] == "shipped"
454
455
456def test_a_sale_with_no_priced_stock_still_falls_back_to_the_standard_cost(
457 tmp_path, monkeypatch):
458 """No priced acquisitions is a known answer, not an unknown: the
459 standard cost is the honest fallback there, as hook_stock_moves has it."""
460 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
461 object_records.update_collection_record(
462 "products", "p1", {"cost_cents": "500"}, base_dir=data_dir, actor="test")
463 created = create_shipment(objects_root, order_id="ord-1")
464 result = ship(data_dir, objects_root, created["shipment_id"])
465 [sale] = sales(data_dir)
466 assert sale["unit_cost_cents"] == "500"
467 assert "uncosted" not in sale["reference"] and "warning" not in result
468
469
470@pytest.mark.parametrize("unreadable", ["stock_moves", "shipment_lines"])
471def test_an_unreadable_stock_ledger_ships_without_a_move_and_says_so(
472 tmp_path, monkeypatch, unreadable):
473 """An installed stock_moves (or shipment_lines) that could not be read
474 was taken for "stock not installed; nothing to move": the parcel left,
475 the shelf never got lighter, and the result said that was expected.
476 Without the ledger the per-line provenance markers cannot be checked,
477 so writing a move could take the same goods off the shelf twice on a
478 replay; the parcel still ships, nothing is moved, and the result says
479 the stock did NOT move and why. The order keeps the status it had
480 rather than being derived from lines that could not be read. Once the
481 ledger reads again, the next event for the shipment moves the goods
482 exactly once."""
483 from test_findings_money_gates import failing_reads
484
485 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
486 created = create_shipment(objects_root, order_id="ord-1")
487 with failing_reads(unreadable, "order_fulfillment.py") as fired:
488 result = ship(data_dir, objects_root, created["shipment_id"])
489 assert fired, "the simulated failure never reached the handler"
490 assert result["moved"] == 0
491 assert sales(data_dir) == []
492 assert unreadable in result["stock_unreadable"]
493 assert "not installed" not in result.get("warning", "")
494 assert "did not move" in result["warning"]
495 assert object_records.get_collection_record(
496 "shipments", created["shipment_id"], base_dir=data_dir)["status"] == "shipped"
497 assert order_status(data_dir) != "processing"
498
499 again = fulfil_shipment(objects_root, created["shipment_id"])
500 assert again["moved"] == 1 and "stock_unreadable" not in again
501 assert len(sales(data_dir)) == 1
502 assert fulfil_shipment(objects_root, created["shipment_id"])["moved"] == 0
503 assert order_status(data_dir) == "shipped"
504
505
506def test_no_stock_ledger_installed_still_moves_nothing_quietly(tmp_path, monkeypatch):
507 """Not installed is a fact (a shop of services has no shelf)."""
508 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
509 created = create_shipment(objects_root, order_id="ord-1")
510 shutil.rmtree(data_dir / "collections" / "stock_moves")
511 (data_dir / "schemas" / "stock_moves.json").unlink()
512 result = ship(data_dir, objects_root, created["shipment_id"])
513 assert result["moved"] == 0 and "stock_unreadable" not in result
514 assert result["order_status"] == "shipped"
515
516
517# --- creating the shipment ------------------------------------------------------
518
519def test_the_default_shipment_is_everything_still_unshipped(tmp_path, monkeypatch):
520 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
521 order_line(data_dir, "line-2", product_id="p1", description="Bowl",
522 quantity="1")
523
524 created = create_shipment(objects_root, order_id="ord-1")
525 assert created["lines"] == 2
526 assert {line["quantity"] for line in created["shipment_lines"]} == {"3", "1"}
527 assert created["status_of_shipment"] == "open"
528
529
530def test_the_address_is_stamped_when_the_box_is_made(tmp_path, monkeypatch):
531 """An address is what it was when the box left; re-reading the customer
532 record later would rewrite where last month's parcel went."""
533 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
534 created = create_shipment(objects_root, order_id="ord-1")
535 shipment = object_records.get_collection_record(
536 "shipments", created["shipment_id"], base_dir=data_dir)
537 assert shipment["ship_to_name"] == "Ada Lovelace"
538 assert "orders/ord-1" in shipment["notes"]
539
540 object_records.update_collection_record(
541 "orders", "ord-1", {"customer_name": "Ada Byron"},
542 base_dir=data_dir, actor="test")
543 unchanged = object_records.get_collection_record(
544 "shipments", created["shipment_id"], base_dir=data_dir)
545 assert unchanged["ship_to_name"] == "Ada Lovelace"
546
547
548def test_a_fully_shipped_order_answers_ok_with_a_note_not_an_error(
549 tmp_path, monkeypatch):
550 """A double click must not 500, and must not raise an empty parcel."""
551 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
552 first = create_shipment(objects_root, order_id="ord-1")
553 ship(data_dir, objects_root, first["shipment_id"])
554
555 again = create_shipment(objects_root, order_id="ord-1")
556 assert again["ok"] is True
557 assert again["shipment_id"] == ""
558 assert "nothing left to ship" in again["note"]
559 assert len(shipments(data_dir)) == 1
560
561
562def test_a_draft_order_cannot_be_packed(tmp_path, monkeypatch):
563 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, status="draft")
564 refused = create_shipment(objects_root, order_id="ord-1")
565 assert refused["status"] == 409
566 assert "Commit before you pack" in refused["error"]
567
568
569def test_an_unknown_order_is_a_404(tmp_path, monkeypatch):
570 _, objects_root = stocked_shop(tmp_path, monkeypatch)
571 assert create_shipment(objects_root, order_id="nope")["status"] == 404
572 assert create_shipment(objects_root)["status"] == 400
573
574
575def test_every_blocker_is_reported_at_once(tmp_path, monkeypatch):
576 """Checkout-style: revealing problems one at a time is how a warehouse
577 screen gets abandoned in favour of a spreadsheet."""
578 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
579 refused = create_shipment(
580 objects_root, order_id="ord-1",
581 lines=[{"order_line_id": "line-1", "quantity": "9"},
582 {"order_line_id": "no-such-line", "quantity": "1"},
583 {"order_line_id": "line-1", "quantity": "0"}])
584 assert refused["status"] == 409
585 assert refused["over_ship"] and refused["unknown_lines"] == ["no-such-line"]
586 assert refused["bad_quantities"][0]["order_line_id"] == "line-1"
587 assert shipments(data_dir) == []
588
589
590# --- the paperwork --------------------------------------------------------------
591
592def slip(objects_root, shipment_id, user_id="shop"):
593 payload = {"shipment_id": shipment_id}
594 if user_id:
595 payload["_identity"] = {"user_id": user_id}
596 return run(objects_root, "site_packing_slip", "GET", payload)
597
598
599def test_the_packing_slip_says_what_is_in_the_box_and_never_what_it_cost(
600 tmp_path, monkeypatch):
601 """Pricelessness by construction is what makes every parcel gift-safe --
602 a flag somebody forgets to tick is how a present arrives with the
603 amount paid stapled to it."""
604 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
605 created = create_shipment(objects_root, order_id="ord-1",
606 lines=[{"order_line_id": "line-1", "quantity": "2"}])
607 body = slip(objects_root, created["shipment_id"])["body"]
608
609 assert "Enamel Mug" in body
610 assert ">2<" in body # the quantity cell
611 assert "SO-0001" in body
612 assert "Ada Lovelace" in body
613
614 # The page prints the shipment's random uuid ("shipment 1abc...-..."); a
615 # uuid is hex, so "1200" turns up in one about once in 2000 pages. Blank
616 # the ids out so only the words and numbers a packer reads are checked --
617 # a price in any cell would still be caught.
618 visible = re.sub(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-"
619 r"[0-9a-f]{12}", "<id>", body)
620 assert "<id>" in visible # the blanking really ran
621 assert "$" not in visible
622 assert "1200" not in visible and "12.00" not in visible
623 assert "unit_price" not in visible and "_cents" not in visible
624 assert "@media print" in body
625
626
627def test_the_slip_prints_the_note_and_the_gift_message_when_they_exist(
628 tmp_path, monkeypatch):
629 """Read with .get: the merchandising slice that adds these two fields to
630 orders has not landed, and a slip that crashed on an older order would
631 be a page breaking itself while waiting for a feature."""
632 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
633 created = create_shipment(objects_root, order_id="ord-1")
634 assert "Gift message" not in slip(objects_root, created["shipment_id"])["body"]
635
636 object_records.update_collection_record(
637 "orders", "ord-1",
638 {"customer_note": "Leave with the neighbour",
639 "gift_message": "Happy birthday, Ada"},
640 base_dir=data_dir, actor="test")
641 body = slip(objects_root, created["shipment_id"])["body"]
642 assert "Leave with the neighbour" in body
643 assert "Happy birthday, Ada" in body
644 assert "$" not in body
645
646
647def test_the_packing_slip_is_for_someone_who_may_read_the_shipment(
648 tmp_path, monkeypatch):
649 """The slip reads storage directly: it is the only gate in front of a
650 shipment's recipient, address and its order's notes. The owner and an
651 admin get it; another signed-in user and an anonymous call get the SAME
652 page as a mistyped id, so a guessed id learns nothing."""
653 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
654 created = create_shipment(objects_root, order_id="ord-1")
655 shipment_id = created["shipment_id"]
656 object_records.update_collection_record(
657 "orders", "ord-1", {"customer_note": "Leave with the neighbour"},
658 base_dir=data_dir, actor="test")
659 missing = slip(objects_root, "no-such-shipment", user_id="mallory")
660
661 assert "Ada Lovelace" in slip(objects_root, shipment_id)["body"]
662 admin = run(objects_root, "site_packing_slip", "GET",
663 {"shipment_id": shipment_id,
664 "_identity": {"user_id": "ops", "roles": ["admin"]}})
665 assert "Ada Lovelace" in admin["body"]
666
667 for refused in (slip(objects_root, shipment_id, user_id="mallory"),
668 slip(objects_root, shipment_id, user_id="")):
669 assert refused["status"] == 404
670 assert "Ada Lovelace" not in refused["body"]
671 assert "neighbour" not in refused["body"]
672 assert refused["body"] == missing["body"]
673
674
675def test_an_unknown_shipment_is_a_friendly_404_not_a_traceback(
676 tmp_path, monkeypatch):
677 _, objects_root = stocked_shop(tmp_path, monkeypatch)
678 result = slip(objects_root, "no-such-shipment")
679 assert result["status"] == 404
680 assert result["content_type"].startswith("text/html")
681 assert "Traceback" not in result["body"]
682
683
684def pick_list(objects_root, user_id="shop"):
685 payload = {"_identity": {"user_id": user_id}} if user_id else {}
686 return run(objects_root, "site_pick_list", "GET", payload)
687
688
689def test_the_pick_list_groups_two_orders_into_one_walk_to_the_shelf(
690 tmp_path, monkeypatch):
691 """A picker walks the room once: two orders wanting mugs is one trip
692 carrying five, not two trips."""
693 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
694 order(data_dir, "ord-2", number="SO-0002", order_date="2026-06-20")
695 order_line(data_dir, "line-2", order_id="ord-2", quantity="2")
696
697 body = pick_list(objects_root)["body"]
698 assert body.count("Enamel Mug") == 1
699 assert ">5<" in body # 3 + 2, one row
700 assert "SO-0001" in body and "SO-0002" in body
701 # Oldest first: SO-0002 was placed in June, so its date leads the row.
702 assert "2026-06-20" in body
703
704
705def test_what_is_already_on_a_shipment_leaves_the_pick_list(tmp_path, monkeypatch):
706 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
707 create_shipment(objects_root, order_id="ord-1",
708 lines=[{"order_line_id": "line-1", "quantity": "2"}])
709 body = pick_list(objects_root)["body"]
710 assert ">1<" in body # only the remainder is left
711
712 create_shipment(objects_root, order_id="ord-1")
713 assert "Nothing is waiting to be picked" in pick_list(objects_root)["body"]
714
715
716def test_the_pick_list_folds_only_the_orders_the_caller_may_read(
717 tmp_path, monkeypatch):
718 """The page reads storage directly, so it asks the permission engine
719 what the orders API would answer. An order with NO owner used to be
720 folded in for every signed-in account (its number and quantities on
721 another person's pick list); the orders API shows it to nobody but an
722 admin, and a second user's order is theirs alone."""
723 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
724 product(data_dir, "p2", "Secret Teapot")
725 product(data_dir, "p3", "Nobody Kettle")
726 order(data_dir, "ord-eve", number="SO-EVE", owner="eve")
727 order_line(data_dir, "line-eve", order_id="ord-eve", product_id="p2",
728 description="Secret Teapot")
729 order(data_dir, "ord-nobody", number="SO-NOBODY", owner="")
730 order_line(data_dir, "line-nobody", order_id="ord-nobody", product_id="p3",
731 description="Nobody Kettle")
732
733 mine = pick_list(objects_root, user_id="shop")["body"]
734 assert "SO-0001" in mine and "Enamel Mug" in mine
735 for hidden in ("SO-EVE", "Secret Teapot", "SO-NOBODY", "Nobody Kettle"):
736 assert hidden not in mine, f"shop was shown {hidden}"
737
738 admin = run(objects_root, "site_pick_list", "GET",
739 {"_identity": {"user_id": "ops", "roles": ["admin"]}})["body"]
740 for shown in ("SO-0001", "SO-EVE", "SO-NOBODY"):
741 assert shown in admin
742
743
744def test_the_pick_list_asks_a_stranger_to_sign_in(tmp_path, monkeypatch):
745 _, objects_root = stocked_shop(tmp_path, monkeypatch)
746 body = pick_list(objects_root, user_id="")["body"]
747 assert "Sign in" in body
748 assert "Enamel Mug" not in body
749
750
751# --- the manifest: what the driver signs for ------------------------------------
752
753def manifest(objects_root, user_id="shop", **params):
754 payload = {"_identity": {"user_id": user_id}} if user_id else {}
755 payload.update(params)
756 return run(objects_root, "site_manifest", "GET", payload)
757
758
759def hand_over(data_dir, objects_root, *, carrier, tracking, on, quantity="1"):
760 """One parcel, out of the door on a named day with a named carrier."""
761 created = create_shipment(objects_root, order_id="ord-1", carrier=carrier,
762 lines=[{"order_line_id": "line-1",
763 "quantity": quantity}])
764 object_records.update_collection_record(
765 "shipments", created["shipment_id"], {"tracking_number": tracking},
766 base_dir=data_dir, actor="test")
767 ship(data_dir, objects_root, created["shipment_id"], today=on)
768 return created["shipment_id"]
769
770
771def test_the_handover_date_is_stamped_when_the_shipment_reaches_shipped(
772 tmp_path, monkeypatch):
773 """Nothing wrote shipped_on before the carrier slice needed it, so every
774 shipment the shop's own automation raised had a blank one -- and a
775 manifest keyed on it would have printed an empty page for a real
776 morning's work."""
777 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
778 created = create_shipment(objects_root, order_id="ord-1")
779 assert object_records.get_collection_record(
780 "shipments", created["shipment_id"], base_dir=data_dir)["shipped_on"] == ""
781
782 ship(data_dir, objects_root, created["shipment_id"], today="2026-07-24")
783 assert object_records.get_collection_record(
784 "shipments", created["shipment_id"],
785 base_dir=data_dir)["shipped_on"] == "2026-07-24"
786
787
788def test_a_date_somebody_typed_is_never_overwritten(tmp_path, monkeypatch):
789 """An operator backdating a parcel knows something the handler does
790 not."""
791 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
792 created = create_shipment(objects_root, order_id="ord-1")
793 object_records.update_collection_record(
794 "shipments", created["shipment_id"], {"shipped_on": "2026-07-01"},
795 base_dir=data_dir, actor="operator")
796
797 ship(data_dir, objects_root, created["shipment_id"], today="2026-07-24")
798 assert object_records.get_collection_record(
799 "shipments", created["shipment_id"],
800 base_dir=data_dir)["shipped_on"] == "2026-07-01"
801
802
803def test_the_manifest_lists_one_day_for_one_carrier_and_nothing_else(
804 tmp_path, monkeypatch):
805 """A driver signs for the pile in front of them: yesterday's parcels and
806 the other carrier's parcels are not that pile."""
807 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
808 hand_over(data_dir, objects_root, carrier="Van Lines", tracking="TRK-A",
809 on="2026-07-24")
810 hand_over(data_dir, objects_root, carrier="Post Office", tracking="TRK-B",
811 on="2026-07-24")
812 hand_over(data_dir, objects_root, carrier="Van Lines", tracking="TRK-C",
813 on="2026-07-23")
814
815 body = manifest(objects_root, date="2026-07-24", carrier="Van Lines")["body"]
816 assert "TRK-A" in body
817 assert "TRK-B" not in body and "TRK-C" not in body
818 assert "1 parcel" in body
819 assert "SO-0001" in body and "Ada Lovelace" in body and "ground" in body
820
821
822def test_the_manifest_lists_only_the_shipments_the_caller_may_read(
823 tmp_path, monkeypatch):
824 """The page reads storage directly, so it asks the permission engine
825 what the shipments API would answer. A shipment with NO owner used to be
826 listed for every signed-in account (recipient, tracking number); the API
827 shows it to nobody but an admin, and a second user's shipment is theirs."""
828 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
829 mine = hand_over(data_dir, objects_root, carrier="Van Lines",
830 tracking="TRK-MINE", on="2026-07-24")
831 for tracking, owner in (("TRK-EVES", "eve"), ("TRK-NOBODY", "")):
832 shipment = hand_over(data_dir, objects_root, carrier="Van Lines",
833 tracking=tracking, on="2026-07-24")
834 object_records.update_collection_record(
835 "shipments", shipment, {"owner_id": owner},
836 base_dir=data_dir, actor="test")
837
838 body = manifest(objects_root, date="2026-07-24")["body"]
839 assert "TRK-MINE" in body
840 assert "TRK-EVES" not in body and "TRK-NOBODY" not in body
841 assert "1 parcel" in body
842
843 admin = run(objects_root, "site_manifest", "GET",
844 {"date": "2026-07-24",
845 "_identity": {"user_id": "ops", "roles": ["admin"]}})["body"]
846 for shown in ("TRK-MINE", "TRK-EVES", "TRK-NOBODY"):
847 assert shown in admin
848
849
850def test_a_parcel_still_on_the_bench_is_on_no_manifest(tmp_path, monkeypatch):
851 """A manifest joins at `shipped`, which is when the handover date is
852 stamped: a packed box nobody has handed over has been handed to
853 nobody."""
854 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
855 created = create_shipment(objects_root, order_id="ord-1", carrier="Van Lines")
856 object_records.update_collection_record(
857 "shipments", created["shipment_id"], {"tracking_number": "TRK-BENCH"},
858 base_dir=data_dir, actor="test")
859
860 body = manifest(objects_root, date="2026-07-24")["body"]
861 assert "TRK-BENCH" not in body
862 assert "Nothing was handed over" in body
863
864
865def test_each_carrier_gets_its_own_pile_and_its_own_signature(
866 tmp_path, monkeypatch):
867 """Two carriers collecting from one dock take two piles, and one list
868 mixing them is a list neither driver can sign."""
869 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
870 hand_over(data_dir, objects_root, carrier="Van Lines", tracking="TRK-A",
871 on="2026-07-24")
872 hand_over(data_dir, objects_root, carrier="Post Office", tracking="TRK-B",
873 on="2026-07-24")
874
875 body = manifest(objects_root, date="2026-07-24")["body"]
876 assert "Van Lines" in body and "Post Office" in body
877 assert body.count("Signature") == 2
878 assert "2 carriers" in body and "2 parcels" in body
879
880
881def test_the_manifest_prints_and_never_says_what_anything_cost(
882 tmp_path, monkeypatch):
883 """This document goes to a third party. A carrier who can read the value
884 of every parcel in the van has been handed a theft list."""
885 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
886 hand_over(data_dir, objects_root, carrier="Van Lines", tracking="TRK-A",
887 on="2026-07-24")
888
889 body = manifest(objects_root, date="2026-07-24")["body"]
890 assert "$" not in body
891 assert "1200" not in body and "12.00" not in body
892 assert "_cents" not in body
893 assert "@media print" in body
894 # A fold, not a form: nothing on the page changes anything.
895 assert "<form" not in body and "<button" not in body
896 # No weight column, because no row carries a weight -- shipments
897 # declares no such field, and a column of blanks on a signed document is
898 # worse than no column.
899 assert "Weight" not in body
900
901
902def test_the_manifest_asks_a_stranger_to_sign_in(tmp_path, monkeypatch):
903 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
904 hand_over(data_dir, objects_root, carrier="Van Lines", tracking="TRK-A",
905 on="2026-07-24")
906
907 body = manifest(objects_root, user_id="", date="2026-07-24")["body"]
908 assert "Sign in" in body
909 assert "TRK-A" not in body
910
911
912def test_a_date_nobody_can_read_prints_today_and_says_so(tmp_path, monkeypatch):
913 """Somebody is standing at a dock holding parcels; the page's job is to
914 print."""
915 _, objects_root = stocked_shop(tmp_path, monkeypatch)
916 body = manifest(objects_root, date="last tuesday")["body"]
917 assert "not a date this page can read" in body
918 assert "Traceback" not in body
919
920
921# --- the shop's zero-touch path, through the new noun ---------------------------
922
923def paid_web_order(data_dir, objects_root):
924 """An order paid for the way app-shop's checkout leaves it: an invoice
925 the order points at, and a received payment against that invoice."""
926 object_records.create_collection_record(
927 "invoices",
928 {"id": "inv-1", "number": "SO-0001", "customer_name": "Ada Lovelace",
929 "customer_email": "ada@example.test", "status": "sent",
930 "issue_date": "2026-07-01", "due_date": "2026-07-15",
931 "subtotal_cents": "3600", "total_cents": "3600", "owner_id": "shop"},
932 base_dir=data_dir)
933 object_records.update_collection_record(
934 "orders", "ord-1", {"invoice_id": "inv-1"},
935 base_dir=data_dir, actor="test")
936 return object_records.create_collection_record(
937 "payments",
938 {"id": object_ids.new_uuid4(), "invoice_id": "inv-1",
939 "amount_cents": "3600", "method": "card", "received_on": "2026-07-02",
940 "status": "received", "owner_id": "shop"},
941 base_dir=data_dir)
942
943
944def fulfil_payment(objects_root, payment):
945 return run(objects_root, "system_shop_fulfillment", "EVENT",
946 {"collection": "payments", "record": payment})
947
948
949def test_auto_fulfill_ships_the_whole_order_and_moves_the_stock(
950 tmp_path, monkeypatch):
951 """The proven chain, unchanged from a shopper's point of view -- there
952 is simply a document now saying what went out."""
953 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, status="draft")
954 payment = paid_web_order(data_dir, objects_root)
955
956 result = fulfil_payment(objects_root, payment)
957 assert result["confirmed"] and result["shipped"] is True
958 assert result["moved"] == 1
959
960 shipment = shipments(data_dir)[0]
961 assert shipment["status"] == "shipped"
962 assert shipment["order_id"] == "ord-1"
963 assert len(shipment_lines(data_dir)) == 1
964 assert sales(data_dir)[0]["quantity"] == "3"
965 assert sales(data_dir)[0]["from_location_id"] == "loc-shelf"
966 assert order_status(data_dir) == "shipped"
967
968
969def test_auto_fulfill_off_confirms_the_order_and_ships_nothing(
970 tmp_path, monkeypatch):
971 """A shop with a packing bench: the order lands on the pick list and a
972 human decides what goes in which box."""
973 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, auto="false",
974 status="draft")
975 payment = paid_web_order(data_dir, objects_root)
976
977 result = fulfil_payment(objects_root, payment)
978 assert result["confirmed"] and result["shipped"] is False
979 assert "auto_fulfill is off" in result["note"]
980 assert shipments(data_dir) == [] and sales(data_dir) == []
981 assert order_status(data_dir) == "confirmed"
982 assert "Enamel Mug" in pick_list(objects_root)["body"]
983
984
985def test_a_replayed_payment_raises_no_second_parcel(tmp_path, monkeypatch):
986 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, status="draft")
987 payment = paid_web_order(data_dir, objects_root)
988 fulfil_payment(objects_root, payment)
989
990 again = fulfil_payment(objects_root, payment)
991 assert again["skipped"] == "order already shipped"
992 assert len(shipments(data_dir)) == 1
993 assert len(sales(data_dir)) == 1