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_pickup_service.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_pickup_service.py · 27.8 KB · 631 lines
1"""Counter service: an instruction on a line, a queue with a clock in it,
2and the message that stops somebody standing there guessing.
3
4Three slices meet in this file and the properties worth holding are the
5seams between them.
6
7**The delta is money, so it is money everywhere.** A modifier that shows
8up in the basket total and not on the invoice is the shop quietly eating
9sixty cents a cup, and nothing in the system would ever say so -- every
10document would be internally consistent and one of them would be wrong.
11So the modifier test walks the whole chain in one go, basket to invoice,
12rather than asserting four separate arithmetics that could each be right
13about a different number.
14
15**The note is NOT money, so it is money nowhere.** It reaches the cook,
16who needs it, and touches no total, which is the other half of the same
17property: the day somebody "helpfully" prices a note is the day an
18invoice stops matching its own lines.
19
20**A ticket is not an invoice.** No prices, ever, by construction and not
21by a flag -- the same rule the packing slip holds, tested the same way.
22
23**A shipping order is untouched by every pickup rule.** That is the
24regression that matters: a warehouse that started printing kitchen
25tickets for parcels would be this slice leaking into the one that was
26already working.
27
28**The ready message queues exactly once.** The dispatcher promises
29at-least-once delivery, so the handler WILL see a ready order again; a
30customer told twice is noise, and a customer told never is the whole
31failure this message exists to prevent.
32"""
33
34import pathlib
35import shutil
36from datetime import datetime, timedelta
37
38from conftest import stage_collection
39
40import object_execution
41import object_ids
42import object_records
43import python_object_runtime
44
45REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
46PACKAGES = REPO_ROOT / "packages"
47SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
48ORDERS_OBJECTS = PACKAGES / "app-orders" / "objects"
49KITCHEN_OBJECTS = PACKAGES / "app-kitchen" / "objects"
50RUNTIME = python_object_runtime.PythonObjectRuntime()
51
52TOKEN = "sess-pickup-1"
53
54
55def setup_env(tmp_path, monkeypatch, *, settings=()):
56 """A data dir with every collection this slice touches, and ONE object
57 root holding three packages' objects -- what an installed server
58 actually looks like, and the only way site_shop reaching action_cart
59 or action_checkout reaching object_cart resolves as it will in
60 production.
61 """
62 data_dir = tmp_path / "data"
63 for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"),
64 ("app-catalog", "products"), ("app-catalog", "locations"),
65 ("app-catalog", "stock_moves"),
66 ("app-orders", "orders"), ("app-orders", "order_lines"),
67 ("app-invoices", "invoices"),
68 ("app-invoices", "invoice_lines"),
69 ("app-email", "email_outbox")):
70 stage_collection(data_dir, pkg, name)
71 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
72 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
73
74 objects_root = tmp_path / "objects"
75 for source in (SHOP_OBJECTS, ORDERS_OBJECTS, KITCHEN_OBJECTS):
76 shutil.copytree(source, objects_root, dirs_exist_ok=True)
77
78 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
79 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
80 return data_dir, objects_root
81
82
83def run(objects_root, object_id, method, payload):
84 return object_execution.execute_object(
85 RUNTIME,
86 object_execution.ObjectExecutionRequest(
87 object_id, method=method, payload=payload),
88 roots=[objects_root]).result
89
90
91# --- fixtures shaped like a small café ---------------------------------------
92
93def product(data_dir, product_id, name, cents=1200, **fields):
94 return object_records.create_collection_record(
95 "products",
96 {"id": product_id, "name": name, "sku": product_id.upper(),
97 "product_type": "physical", "price_cents": str(cents),
98 "currency": "USD", "is_active": "true", "owner_id": "shop", **fields},
99 base_dir=data_dir)
100
101
102def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
103 object_records.create_collection_record(
104 "locations",
105 {"id": to, "name": "Counter", "location_type": "warehouse",
106 "owner_id": "shop"}, base_dir=data_dir)
107 return object_records.create_collection_record(
108 "stock_moves",
109 {"id": object_ids.new_uuid4(), "product_id": product_id,
110 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
111 "occurred_at": "2026-07-01", "owner_id": "shop"},
112 base_dir=data_dir)
113
114
115def cart(objects_root, action="get", **payload):
116 return run(objects_root, "action_cart", "POST",
117 {"session_token": TOKEN, "action": action, **payload})
118
119
120def checkout(objects_root, **payload):
121 return run(objects_root, "action_checkout", "POST",
122 {"session_token": TOKEN, **payload})
123
124
125def when(minutes_from_now):
126 """A promised time as the shop's own naive wall clock -- the
127 convention app-pickup's slot generator writes and every reader of
128 promised_at in this repo shares.
129
130 Half a minute of cushion, away from now in whichever direction the
131 caller asked. The page reports WHOLE minutes elapsed, so a promise
132 written exactly 35 minutes out and read a few milliseconds later is
133 honestly 34; the cushion buys the assertion a stable number without
134 the page having to round up and claim a minute that is not there.
135 """
136 cushion = timedelta(seconds=30 if minutes_from_now >= 0 else -30)
137 return (datetime.now() + timedelta(minutes=minutes_from_now)
138 + cushion).isoformat(timespec="seconds")
139
140
141def pickup_order(data_dir, order_id, *, status="preparing", number="PU-1",
142 promised=None, method="pickup", owner="", email="",
143 name="Ada Lovelace", **fields):
144 record = {"id": order_id, "doc_type": "sale", "number": number,
145 "customer_name": name, "customer_email": email,
146 "currency": "USD", "status": status, "order_date": "2026-07-26",
147 "fulfillment_method": method, "owner_id": owner}
148 if promised is not None:
149 record["promised_at"] = promised
150 record.update({k: str(v) for k, v in fields.items()})
151 return object_records.create_collection_record(
152 "orders", record, base_dir=data_dir, preserve_read_only=True)
153
154
155def order_line(data_dir, line_id, *, order_id, description="Flat White",
156 quantity="1", cents=400, note="", modifier=0):
157 return object_records.create_collection_record(
158 "order_lines",
159 {"id": line_id, "order_id": order_id, "description": description,
160 "quantity": quantity, "unit_price_cents": str(cents),
161 "line_note": note, "modifier_cents": str(modifier),
162 "line_total_cents": str(int(float(quantity)) * (cents + modifier)),
163 "owner_id": "shop"},
164 base_dir=data_dir)
165
166
167def kitchen(objects_root, user_id="dan"):
168 payload = {"_identity": {"user_id": user_id}} if user_id else {}
169 return run(objects_root, "site_kitchen", "GET", payload)["body"]
170
171
172def ticket(objects_root, order_id, user_id="shop"):
173 """As the shop that owns the order (checkout stamps the cart's owner,
174 which for a guest basket is the shop): the ticket asks the permission
175 engine whether the caller may read the order."""
176 return run(objects_root, "site_kitchen_ticket", "GET",
177 {"order_id": order_id, "_identity": {"user_id": user_id}})
178
179
180def fire(objects_root, order_id, action="update"):
181 """One change event, shaped exactly as object_change_dispatch sends
182 them (raw verb in `action`, participle in `event`)."""
183 return run(objects_root, "system_order_email", "EVENT",
184 {"event": f"orders.record.{action}d", "collection": "orders",
185 "record_id": order_id, "action": action})
186
187
188def rows(data_dir, collection):
189 return object_records.read_collection_records(collection,
190 base_dir=data_dir)
191
192
193def outbox(data_dir):
194 return rows(data_dir, "email_outbox")
195
196
197# --- 1. the delta is money, and money is the same number everywhere ----------
198
199def test_a_modifier_reaches_the_basket_the_order_and_the_invoice(
200 tmp_path, monkeypatch):
201 """One test on purpose, walking the whole chain.
202
203 Four separate assertions about four totals can all pass while the
204 totals disagree with each other -- which is precisely the failure
205 mode: every document internally consistent, one of them quietly
206 short. So the chain is walked once, and the last assertion is that
207 the invoice's own lines add up to the invoice.
208 """
209 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
210 product(data_dir, "latte", "Latte", 400, modifiers='{"Oat milk": 60}')
211 stock_in(data_dir, "latte", 20)
212
213 # Two lattes with oat milk: 2 x (400 + 60), because two oat lattes are
214 # two lots of oat milk. The extra is NAMED; its price is the product's.
215 # (A client that also states the right modifier_cents is still served.)
216 basket = cart(objects_root, "add", product_id="latte", quantity="2",
217 line_note="extra hot", modifiers=["oat milk"],
218 modifier_cents="60")
219 assert basket["subtotal_cents"] == 920
220 assert basket["lines"][0]["modifier_cents"] == 60
221 assert basket["lines"][0]["modifiers"] == ["Oat milk"]
222 assert basket["lines"][0]["line_note"] == "extra hot"
223
224 preview = checkout(objects_root, preview="true")
225 assert preview["total_cents"] == 920
226
227 result = checkout(objects_root, customer_email="ada@example.test",
228 customer_name="Ada Lovelace")
229 assert result["ok"] is True
230 assert result["total_cents"] == 920
231
232 order = object_records.get_collection_record("orders", result["order_id"],
233 base_dir=data_dir)
234 assert order["total_cents"] == "920"
235
236 line = rows(data_dir, "order_lines")[0]
237 assert line["modifier_cents"] == "60"
238 # The cook is told what was paid for, ahead of what was typed.
239 assert line["line_note"] == "Oat milk; extra hot"
240 assert line["unit_price_cents"] == "400" # the catalogue price, kept
241 assert line["line_total_cents"] == "920" # with the delta inside it
242
243 invoice = rows(data_dir, "invoices")[0]
244 invoice_line = rows(data_dir, "invoice_lines")[0]
245 # The invoice carries the EFFECTIVE unit price, so the bill is still an
246 # ordinary quantity x price document that multiplies out -- and so a
247 # restatement by invoice_totals could never drop the delta.
248 assert invoice_line["unit_price_cents"] == "460"
249 assert invoice_line["description"] == "Latte (Oat milk +0.60)"
250 assert invoice_line["line_total_cents"] == "920"
251 assert invoice["total_cents"] == "920"
252 assert (sum(int(row["line_total_cents"]) for row in rows(data_dir, "invoice_lines"))
253 == int(invoice["total_cents"]))
254
255
256def test_order_totals_restating_a_line_keeps_the_modifier(tmp_path, monkeypatch):
257 """The fold has to be able to reproduce the number it is restating.
258
259 order_totals recomputes line_total_cents from the line's own columns.
260 If it multiplied the base price alone it would silently replace a
261 correct total with a smaller one every time anybody touched the line,
262 and the shop would be short the delta with nothing to point at.
263 """
264 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
265 pickup_order(data_dir, "ord-mod", number="PU-MOD")
266 order_line(data_dir, "line-mod", order_id="ord-mod", quantity="2",
267 cents=400, modifier=60)
268
269 run(objects_root, "system_order_totals", "EVENT",
270 {"event": "order_lines.record.updated", "collection": "order_lines",
271 "record_id": "line-mod", "action": "update"})
272
273 line = object_records.get_collection_record("order_lines", "line-mod",
274 base_dir=data_dir)
275 assert line["line_total_cents"] == "920"
276 order = object_records.get_collection_record("orders", "ord-mod",
277 base_dir=data_dir)
278 assert order["subtotal_cents"] == "920"
279
280
281def test_two_notes_on_one_product_are_two_lines(tmp_path, monkeypatch):
282 """One burger with no onions and one with are two things to make.
283
284 Merging them on product_id would hand the cook a line of two carrying
285 one instruction, and one of those two customers gets the wrong lunch.
286 """
287 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
288 product(data_dir, "burger", "Burger", 900)
289 stock_in(data_dir, "burger", 20)
290
291 cart(objects_root, "add", product_id="burger", quantity="1",
292 line_note="no onions")
293 basket = cart(objects_root, "add", product_id="burger", quantity="1")
294 assert len(basket["lines"]) == 2
295 assert {line["line_note"] for line in basket["lines"]} == {"no onions", ""}
296
297 # And the ordinary case is untouched: same product, same instruction,
298 # same delta still merges into one line of two.
299 basket = cart(objects_root, "add", product_id="burger", quantity="1",
300 line_note="no onions")
301 assert len(basket["lines"]) == 2
302 noted = [line for line in basket["lines"] if line["line_note"]][0]
303 assert noted["quantity"] == "2"
304
305
306def test_a_shopper_cannot_price_their_own_lunch(tmp_path, monkeypatch):
307 """action_cart is a PUBLIC object, so anything the request can put
308 into money is something a stranger can put into money."""
309 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
310 product(data_dir, "latte", "Latte", 400)
311 stock_in(data_dir, "latte", 20)
312
313 result = cart(objects_root, "add", product_id="latte",
314 modifier_cents="-350")
315 assert result["status"] == 400
316 assert "never take money off" in result["error"]
317 assert rows(data_dir, "cart_items") == []
318
319
320def test_the_shop_page_takes_a_note_and_shows_it_back(tmp_path, monkeypatch):
321 """The box is on the ADD form, because a note belongs to a line.
322 /shop's own `customer_note` is a different field addressed to a
323 different person -- the packer, not the cook -- and one box at the
324 bottom of a checkout cannot say which burger it meant.
325 """
326 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
327 product(data_dir, "burger", "Burger", 900,
328 modifiers='{"Extra cheese": 150}')
329 stock_in(data_dir, "burger", 20)
330
331 body = run(objects_root, "site_shop", "GET",
332 {"_cookies": {"cart": TOKEN}})["body"]
333 assert 'name="line_note"' in body
334 # And no way to type a price: action_cart is public, so a delta input
335 # on a public page is a shopper pricing their own lunch.
336 assert 'name="modifier_cents"' not in body
337
338 cart(objects_root, "add", product_id="burger", quantity="1",
339 line_note="no onions", modifiers="Extra cheese")
340 body = run(objects_root, "site_shop", "GET",
341 {"_cookies": {"cart": TOKEN}})["body"]
342 assert "no onions" in body
343 assert "Extra cheese +1.50 each" in body
344 # The Update button says WHICH line, now that two can share a product.
345 assert 'name="cart_item_id"' in body
346
347
348# --- 2. the note is not money, and reaches the person who needs it ----------
349
350def test_a_line_note_reaches_the_kitchen_ticket_and_never_the_invoice_total(
351 tmp_path, monkeypatch):
352 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
353 product(data_dir, "burger", "Burger", 900)
354 stock_in(data_dir, "burger", 20)
355
356 cart(objects_root, "add", product_id="burger", quantity="2",
357 line_note="no onions, cut in half")
358 result = checkout(objects_root, customer_email="ada@example.test")
359 order_id = result["order_id"]
360
361 # An instruction with no delta must move NO total: 2 x 900, exactly
362 # what the same basket cost before anybody typed anything.
363 assert result["total_cents"] == 1800
364 invoice = rows(data_dir, "invoices")[0]
365 assert invoice["total_cents"] == "1800"
366 invoice_line = rows(data_dir, "invoice_lines")[0]
367 assert invoice_line["line_total_cents"] == "1800"
368 assert "onions" not in invoice_line["description"]
369
370 # And it does reach the cook, under the line it is true of.
371 body = ticket(objects_root, order_id)["body"]
372 assert "no onions, cut in half" in body
373 assert "Burger" in body
374
375
376def test_the_kitchen_ticket_shows_no_prices(tmp_path, monkeypatch):
377 """By construction, not behind a flag -- the packing slip's rule. A
378 cook cannot act on what it cost, and the money conversation already
379 happened with somebody who may not be the person cooking."""
380 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
381 pickup_order(data_dir, "ord-t", number="PU-TICKET", promised=when(20),
382 owner="shop")
383 order_line(data_dir, "line-t", order_id="ord-t", quantity="1",
384 cents=1234, modifier=567, note="extra hot")
385
386 body = ticket(objects_root, "ord-t")["body"]
387 assert "extra hot" in body
388 assert "Flat White" in body
389 for money in ("1234", "12.34", "567", "5.67", "1801", "18.01"):
390 assert money not in body, f"a price ({money}) reached a kitchen ticket"
391
392
393def test_an_unknown_order_is_a_friendly_404_not_a_traceback(tmp_path, monkeypatch):
394 _data_dir, objects_root = setup_env(tmp_path, monkeypatch)
395 page = ticket(objects_root, "no-such-order")
396 assert page["status"] == 404
397 assert "Not found" in page["body"]
398
399
400def test_the_ticket_is_printed_only_for_someone_who_may_read_the_order(
401 tmp_path, monkeypatch):
402 """The page reads storage directly, so it is the only gate in front of
403 the order: it asks the permission engine the question the orders API
404 would. The owner and an admin get the ticket; another signed-in user,
405 and an anonymous call, get the SAME page as a mistyped id -- a guessed
406 id learns nothing."""
407 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
408 pickup_order(data_dir, "ord-t", number="PU-TICKET", promised=when(20),
409 owner="shop", customer_note="ALLERGIC TO NUTS")
410 missing = ticket(objects_root, "no-such-order", user_id="mallory")
411
412 assert "ALLERGIC TO NUTS" in ticket(objects_root, "ord-t")["body"]
413 admin = run(objects_root, "site_kitchen_ticket", "GET",
414 {"order_id": "ord-t",
415 "_identity": {"user_id": "ops", "roles": ["admin"]}})
416 assert "ALLERGIC TO NUTS" in admin["body"]
417
418 for refused in (ticket(objects_root, "ord-t", user_id="mallory"),
419 run(objects_root, "site_kitchen_ticket", "GET",
420 {"order_id": "ord-t"})):
421 assert refused["status"] == 404
422 assert "ALLERGIC TO NUTS" not in refused["body"]
423 assert refused["body"] == missing["body"]
424
425
426# --- 3. the queue, and the clock in it ---------------------------------------
427
428def test_the_queue_sorts_by_promised_time_and_shouts_about_a_late_one(
429 tmp_path, monkeypatch):
430 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
431 pickup_order(data_dir, "ord-late", number="PU-LATE", promised=when(-7),
432 name="Grace Hopper", owner="dan")
433 pickup_order(data_dir, "ord-soon", number="PU-SOON", promised=when(35),
434 name="Ada Lovelace", owner="dan")
435 order_line(data_dir, "line-late", order_id="ord-late",
436 description="Bacon Roll", note="brown sauce")
437 order_line(data_dir, "line-soon", order_id="ord-soon")
438
439 body = kitchen(objects_root)
440 assert "LATE by 7 min" in body
441 assert "in 35 min" in body
442 # Soonest promise first, and the late one is the soonest of all.
443 assert body.index("PU-LATE") < body.index("PU-SOON")
444 # The lines and their notes are on the queue, not only on the ticket:
445 # a cook glancing at the screen is reading the instruction there.
446 assert "brown sauce" in body
447
448
449def test_a_shipping_order_never_appears_on_the_kitchen_queue(
450 tmp_path, monkeypatch):
451 """The regression that matters. A warehouse that started printing
452 kitchen tickets for parcels would be this slice leaking into the one
453 that was already working."""
454 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
455 pickup_order(data_dir, "ord-ship", number="PU-SHIPPED", status="confirmed",
456 method="shipping", promised=when(5))
457 pickup_order(data_dir, "ord-blank", number="PU-NOMETHOD",
458 status="confirmed", method="", promised=when(5))
459 order_line(data_dir, "line-ship", order_id="ord-ship")
460 order_line(data_dir, "line-blank", order_id="ord-blank")
461
462 body = kitchen(objects_root)
463 assert "PU-SHIPPED" not in body
464 assert "PU-NOMETHOD" not in body
465 assert "Nothing is being prepared" in body
466
467
468def test_a_ready_order_has_left_the_queue(tmp_path, monkeypatch):
469 """`ready` is made and on the shelf, and the customer has been told.
470 A queue that still showed it would never empty."""
471 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
472 pickup_order(data_dir, "ord-ready", number="PU-DONE", status="ready",
473 promised=when(-2))
474 order_line(data_dir, "line-ready", order_id="ord-ready")
475 assert "PU-DONE" not in kitchen(objects_root)
476
477
478def test_an_order_with_no_promised_time_sorts_last_and_claims_nothing(
479 tmp_path, monkeypatch):
480 """'We do not know when this was promised' is not a claim to urgency,
481 and must never invent an emergency at the top of the queue."""
482 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
483 pickup_order(data_dir, "ord-none", number="PU-UNSET", owner="dan")
484 pickup_order(data_dir, "ord-soon", number="PU-SOON", promised=when(30),
485 owner="dan")
486 order_line(data_dir, "line-none", order_id="ord-none")
487 order_line(data_dir, "line-soon", order_id="ord-soon")
488
489 body = kitchen(objects_root)
490 assert body.index("PU-SOON") < body.index("PU-UNSET")
491 assert "no promised time" in body
492 assert "LATE" not in body
493
494
495def test_the_queue_shows_only_the_orders_the_caller_may_read(
496 tmp_path, monkeypatch):
497 """The page reads storage directly, so it asks the permission engine
498 what the orders API would answer: the caller's own orders and, for an
499 admin, all of them. An order with NO owner used to be shown to every
500 signed-in account (customer name, note and lines included); the orders
501 API shows it to nobody but an admin."""
502 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
503 for order_id, number, owner in (("ord-mine", "PU-MINE", "dan"),
504 ("ord-eves", "PU-EVES", "eve"),
505 ("ord-nobody", "PU-NOBODY", "")):
506 pickup_order(data_dir, order_id, number=number, promised=when(20),
507 owner=owner, customer_note=f"note for {number}")
508 order_line(data_dir, f"line-{order_id}", order_id=order_id)
509
510 body = kitchen(objects_root, user_id="dan")
511 assert "PU-MINE" in body
512 for hidden in ("PU-EVES", "PU-NOBODY", "note for PU-EVES", "note for PU-NOBODY"):
513 assert hidden not in body, f"dan was shown {hidden}"
514
515 admin = run(objects_root, "site_kitchen", "GET",
516 {"_identity": {"user_id": "ops", "roles": ["admin"]}})["body"]
517 for shown in ("PU-MINE", "PU-EVES", "PU-NOBODY"):
518 assert shown in admin
519
520
521def test_the_queue_asks_a_stranger_to_sign_in(tmp_path, monkeypatch):
522 """A sign-in prompt, not a 403 -- the same shape site_pick_list uses,
523 because the person reading this is staff who have not logged in yet."""
524 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
525 pickup_order(data_dir, "ord-1", number="PU-SECRET", promised=when(10))
526 body = kitchen(objects_root, user_id="")
527 assert "Sign in" in body
528 assert "PU-SECRET" not in body
529
530
531# --- 4. "your order is ready" -------------------------------------------------
532
533def test_the_ready_message_queues_exactly_once_and_a_replay_queues_nothing(
534 tmp_path, monkeypatch):
535 """The dispatcher promises at-least-once delivery, so this handler
536 WILL see the same ready order again."""
537 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
538 pickup_order(data_dir, "ord-r", number="PU-READY", status="ready",
539 email="ada@example.test", promised=when(-1),
540 ready_at="2026-07-26T18:15:00")
541
542 first = fire(objects_root, "ord-r")
543 # `confirmed` rides along on purpose: the confirmation fires anywhere
544 # at or past confirmed, and `ready` is past it. A counter shop that
545 # takes an order and has it made in one burst of writes would
546 # otherwise never send a confirmation at all.
547 assert first["queued"] == ["confirmed", "ready"]
548
549 ready_mail = [row for row in outbox(data_dir)
550 if row["source_object_id"].endswith(":ready")]
551 assert len(ready_mail) == 1
552 assert "ready to collect" in ready_mail[0]["subject"]
553 assert "PU-READY" in ready_mail[0]["text_body"]
554 assert "ready to collect" in ready_mail[0]["text_body"]
555
556 second = fire(objects_root, "ord-r")
557 assert second["queued"] == []
558 assert "ready" in second["skipped_already_sent"]
559 assert len([row for row in outbox(data_dir)
560 if row["source_object_id"].endswith(":ready")]) == 1
561
562
563def test_a_shipping_order_is_never_told_to_come_and_collect(
564 tmp_path, monkeypatch):
565 """'Ready for collection' said to somebody whose parcel is on a van is
566 a customer driving to a shop for nothing."""
567 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
568 pickup_order(data_dir, "ord-s", number="SO-SHIP", status="shipped",
569 method="shipping", email="ada@example.test")
570
571 fire(objects_root, "ord-s")
572 assert [row for row in outbox(data_dir)
573 if row["source_object_id"].endswith(":ready")] == []
574
575
576def test_a_pickup_order_with_no_email_skips_with_a_reason(tmp_path, monkeypatch):
577 """Say so plainly. An operator reading 'no customer_email' knows
578 exactly what to add, whereas silence looks like a working mailer."""
579 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
580 pickup_order(data_dir, "ord-n", number="PU-NOMAIL", status="ready",
581 email="")
582
583 result = fire(objects_root, "ord-n")
584 assert "customer_email" in result["skipped"]
585 assert outbox(data_dir) == []
586
587
588def test_with_no_sms_provider_the_customer_is_still_told_by_email(
589 tmp_path, monkeypatch):
590 """The absence of a connector degrades exactly the way the carrier
591 work degrades: the shop loses nothing, the message still goes, and
592 nothing pretends to have sent a text."""
593 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
594 pickup_order(data_dir, "ord-r", number="PU-READY", status="ready",
595 email="ada@example.test")
596
597 result = fire(objects_root, "ord-r")
598 assert "ready" in result["queued"]
599 assert "no SMS provider configured" in result["sms"]
600 assert len(outbox(data_dir)) == 2 # the confirmation, and this
601
602
603def test_a_named_sms_provider_with_no_adapter_says_so_and_still_emails(
604 tmp_path, monkeypatch):
605 """An operator who pasted a provider name in and heard nothing would
606 reasonably conclude the system was texting people. It is not, and it
607 says which channel actually carried the message."""
608 data_dir, objects_root = setup_env(
609 tmp_path, monkeypatch,
610 settings=(("notify.sms_provider", "twilio"),))
611 pickup_order(data_dir, "ord-r", number="PU-READY", status="ready",
612 email="ada@example.test")
613
614 result = fire(objects_root, "ord-r")
615 assert "ready" in result["queued"]
616 assert "twilio" in result["sms"]
617 assert "no SMS connector is installed" in result["sms"]
618 assert len(outbox(data_dir)) == 2
619
620
621def test_a_manual_sms_shop_is_told_the_counter_does_it_by_hand(
622 tmp_path, monkeypatch):
623 data_dir, objects_root = setup_env(
624 tmp_path, monkeypatch,
625 settings=(("notify.sms_provider", "manual"),))
626 pickup_order(data_dir, "ord-r", number="PU-READY", status="ready",
627 email="ada@example.test")
628
629 result = fire(objects_root, "ord-r")
630 assert "ready" in result["queued"]
631 assert "by hand" in result["sms"]