Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/tests/test_pickup_slots.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_pickup_slots.py · 29.1 KB · 687 lines
1"""Pickup: the slot board, the gate that books it, and the promised time.
2
3Everything about the MONEY was already built and almost nothing about the
4TIME was, so these are the properties a shop discovers the hard way once
5it starts promising people a moment rather than a parcel.
6
7A window that is full, in the past, inside the shop's lead time, or
8closed is NEVER OFFERED -- "can I have a pizza at 3am" has to be answered
9by the picker not showing 3am, not by a refusal after the card is typed
10in. Every one of those is also refused if the id is asked for directly,
11because a picker is a courtesy and a gate is a gate. A refusal names the
12next free window, because "that time is full" sends somebody away and
13"that time is full, the next one is 18:30" keeps the sale. The generator
14is idempotent, because it runs every night forever and the second run
15must create nothing. And a SHIPPING order is untouched by the whole of
16it, which is the regression that matters most: an order raised by a shop
17that has never heard of pickup has to be the order it was yesterday.
18"""
19
20import json
21import pathlib
22import shutil
23from datetime import datetime, timedelta
24
25from conftest import stage_collection
26
27import object_execution
28import object_packages
29import object_records
30import object_schemas
31import python_object_runtime
32
33REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
34PACKAGES = REPO_ROOT / "packages"
35PICKUP_OBJECTS = PACKAGES / "app-pickup" / "objects"
36SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
37ORDERS_OBJECTS = PACKAGES / "app-orders" / "objects"
38RUNTIME = python_object_runtime.PythonObjectRuntime()
39
40TOKEN = "sess-pickup-1"
41
42# One fixed minute to stand at, so "too soon" and "already passed" are
43# properties of the arithmetic rather than of how long the test took to
44# run. Every slot below is placed relative to it.
45NOW = datetime(2026, 7, 27, 12, 0, 0)
46
47
48def at(minutes):
49 """A slot start `minutes` from NOW, as the ISO string a row holds."""
50 return (NOW + timedelta(minutes=minutes)).isoformat()
51
52
53def setup_env(tmp_path, monkeypatch, *, settings=()):
54 """A data dir with every collection this slice touches, and ONE object
55 root holding all three packages' objects -- which is what an installed
56 server actually looks like, since every package installs into the same
57 objects directory.
58 """
59 data_dir = tmp_path / "data"
60 for pkg, name in (("app-pickup", "pickup_slots"),
61 ("app-shop", "carts"), ("app-shop", "cart_items"),
62 ("app-catalog", "products"), ("app-catalog", "locations"),
63 ("app-catalog", "stock_moves"),
64 ("app-orders", "orders"), ("app-orders", "order_lines"),
65 ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"),
66 ("app-payments", "payments")):
67 stage_collection(data_dir, pkg, name)
68 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
69 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
70
71 objects_root = tmp_path / "objects"
72 for source in (PICKUP_OBJECTS, SHOP_OBJECTS, ORDERS_OBJECTS):
73 shutil.copytree(source, objects_root, dirs_exist_ok=True)
74
75 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
76 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
77 return data_dir, objects_root
78
79
80def uninstall_pickup(data_dir):
81 """A box that never installed this app: no schema and no records file.
82
83 The schema has to go too. A collection whose schema is still declared
84 reads as an empty one rather than an absent one, which is exactly the
85 distinction every "not installed" branch in this package turns on.
86 """
87 shutil.rmtree(data_dir / "collections" / "pickup_slots")
88 (data_dir / "schemas" / "pickup_slots.json").unlink()
89
90
91def run(objects_root, object_id, method, payload):
92 return object_execution.execute_object(
93 RUNTIME,
94 object_execution.ObjectExecutionRequest(
95 object_id, method=method, payload=payload),
96 roots=[objects_root]).result
97
98
99# --- fixtures shaped like a small counter shop ---------------------------------
100
101def slot(data_dir, slot_id, *, starts_in=60, minutes=15, capacity=2,
102 taken=0, is_open="true", location=""):
103 return object_records.create_collection_record(
104 "pickup_slots",
105 {"id": slot_id,
106 "starts_at": at(starts_in),
107 "ends_at": at(starts_in + minutes),
108 "capacity": str(capacity),
109 "orders_taken": str(taken),
110 "is_open": is_open,
111 "location_id": location,
112 "owner_id": ""},
113 base_dir=data_dir)
114
115
116def product(data_dir, product_id="p1", name="Flat White", cents=350):
117 return object_records.create_collection_record(
118 "products",
119 {"id": product_id, "name": name, "sku": product_id.upper(),
120 # service: nothing on a shelf to run out of, so the stock gate is
121 # silent and every blocker in these tests is a pickup blocker.
122 "product_type": "service", "price_cents": str(cents),
123 "currency": "USD", "is_active": "true", "owner_id": "shop"},
124 base_dir=data_dir)
125
126
127def add_to_cart(objects_root, quantity="1", product_id="p1"):
128 return run(objects_root, "action_cart", "POST",
129 {"session_token": TOKEN, "action": "add",
130 "product_id": product_id, "quantity": quantity})
131
132
133def checkout(objects_root, **payload):
134 payload.setdefault("session_token", TOKEN)
135 payload.setdefault("customer_email", "buyer@example.test")
136 return run(objects_root, "action_checkout", "POST", payload)
137
138
139def bookable(objects_root, **payload):
140 payload.setdefault("now", NOW.isoformat())
141 return run(objects_root, "action_pickup_slots", "GET", payload)
142
143
144def offered_ids(objects_root, **payload):
145 return {row["id"] for row in bookable(objects_root, **payload)["slots"]}
146
147
148def slots(data_dir):
149 return object_records.read_collection_records("pickup_slots",
150 base_dir=data_dir)
151
152
153def orders(data_dir):
154 return object_records.read_collection_records("orders", base_dir=data_dir)
155
156
157def one_slot(data_dir, slot_id):
158 return object_records.get_collection_record("pickup_slots", slot_id,
159 base_dir=data_dir)
160
161
162# --- what a picker may offer ----------------------------------------------------
163
164def test_a_full_slot_is_never_offered_and_is_refused_by_name(tmp_path, monkeypatch):
165 """The refusal carries BOTH numbers and the next free time. "Sorry"
166 sends a customer away; "sorry, 18:30 is free" keeps the sale."""
167 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
168 slot(data_dir, "full", starts_in=60, capacity=2, taken=2)
169 slot(data_dir, "next", starts_in=120, capacity=2, taken=0)
170 product(data_dir)
171 add_to_cart(objects_root)
172
173 assert offered_ids(objects_root) == {"next"}
174
175 blocked = checkout(objects_root, fulfillment_method="pickup",
176 pickup_slot_id="full", now=NOW.isoformat())
177 assert blocked["status"] == 409
178 problem = " ".join(blocked["pickup_problems"])
179 assert "takes 2 orders and 2 have been taken" in problem
180 assert at(120) in problem
181 assert blocked["next_free_slot"]["id"] == "next"
182 # Refused BEFORE anything was committed: this is the whole point of
183 # checking here rather than after the card.
184 assert orders(data_dir) == []
185 assert one_slot(data_dir, "full")["orders_taken"] == "2"
186
187
188def test_a_slot_inside_the_lead_time_is_never_offered_and_is_refused(
189 tmp_path, monkeypatch):
190 """A shop that needs 45 minutes' notice must not show a window 20
191 minutes away -- and must still refuse it when the id is typed."""
192 data_dir, objects_root = setup_env(
193 tmp_path, monkeypatch, settings=(("pickup.lead_minutes", "45"),))
194 slot(data_dir, "too_soon", starts_in=20)
195 slot(data_dir, "fine", starts_in=90)
196 product(data_dir)
197 add_to_cart(objects_root)
198
199 assert offered_ids(objects_root) == {"fine"}
200
201 blocked = checkout(objects_root, fulfillment_method="pickup",
202 pickup_slot_id="too_soon", now=NOW.isoformat())
203 assert blocked["status"] == 409
204 problem = " ".join(blocked["pickup_problems"])
205 assert "45 minutes' notice" in problem
206 assert blocked["next_free_slot"]["id"] == "fine"
207 assert orders(data_dir) == []
208
209
210def test_a_slot_in_the_past_is_never_offered_and_is_refused(tmp_path, monkeypatch):
211 data_dir, objects_root = setup_env(
212 tmp_path, monkeypatch, settings=(("pickup.lead_minutes", "0"),))
213 slot(data_dir, "gone", starts_in=-60)
214 slot(data_dir, "later", starts_in=60)
215 product(data_dir)
216 add_to_cart(objects_root)
217
218 assert offered_ids(objects_root) == {"later"}
219
220 blocked = checkout(objects_root, fulfillment_method="pickup",
221 pickup_slot_id="gone", now=NOW.isoformat())
222 assert blocked["status"] == 409
223 assert "has already passed" in " ".join(blocked["pickup_problems"])
224 assert blocked["next_free_slot"]["id"] == "later"
225 assert orders(data_dir) == []
226
227
228def test_a_closed_slot_is_never_offered_and_is_refused(tmp_path, monkeypatch):
229 """`is_open=false` and `capacity=0` are different sentences: the shop
230 is shut then, versus that window is full. Both refuse; only one of
231 them is about how many orders exist."""
232 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
233 slot(data_dir, "shut", starts_in=60, is_open="false")
234 slot(data_dir, "open", starts_in=180)
235 product(data_dir)
236 add_to_cart(objects_root)
237
238 assert offered_ids(objects_root) == {"open"}
239
240 blocked = checkout(objects_root, fulfillment_method="pickup",
241 pickup_slot_id="shut", now=NOW.isoformat())
242 assert blocked["status"] == 409
243 assert "not taking orders" in " ".join(blocked["pickup_problems"])
244 assert blocked["next_free_slot"]["id"] == "open"
245 assert orders(data_dir) == []
246
247
248def test_a_slot_problem_is_reported_alongside_the_price_blockers(
249 tmp_path, monkeypatch):
250 """Never returned early on its own. Telling somebody about the slot,
251 letting them fix it, then revealing the price change is how a
252 checkout gets abandoned."""
253 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
254 slot(data_dir, "full", starts_in=60, capacity=1, taken=1)
255 product(data_dir)
256 add_to_cart(objects_root)
257 object_records.update_collection_record(
258 "products", "p1", {"price_cents": "500"}, base_dir=data_dir, actor="shop")
259
260 blocked = checkout(objects_root, fulfillment_method="pickup",
261 pickup_slot_id="full", now=NOW.isoformat())
262 assert blocked["status"] == 409
263 # Both facts, one response.
264 assert blocked["price_changes"][0]["now_cents"] == 500
265 assert blocked["pickup_problems"]
266
267
268# --- booking one ------------------------------------------------------------------
269
270def test_a_pickup_checkout_stamps_the_method_and_the_promise_and_takes_a_place(
271 tmp_path, monkeypatch):
272 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
273 slot(data_dir, "six", starts_in=60, capacity=4)
274 product(data_dir)
275 add_to_cart(objects_root)
276
277 result = checkout(objects_root, fulfillment_method="pickup",
278 pickup_slot_id="six", now=NOW.isoformat())
279 assert result["ok"] is True
280 assert result["fulfillment_method"] == "pickup"
281 assert result["pickup_slot_id"] == "six"
282 assert result["promised_at"] == at(60)
283
284 order = orders(data_dir)[0]
285 assert order["fulfillment_method"] == "pickup"
286 assert order["promised_at"] == at(60)
287 # requested_at defaults to the slot the shopper chose, and stays its
288 # own field so a storefront that knows what they actually wanted can
289 # say so instead of overwriting the promise.
290 assert order["requested_at"] == at(60)
291 assert order["ready_at"] == "" and order["collected_at"] == ""
292 assert "[pickup_slots/six]" in order["notes"]
293
294 assert one_slot(data_dir, "six")["orders_taken"] == "1"
295
296
297def test_a_stated_requested_time_is_kept_apart_from_the_promise(
298 tmp_path, monkeypatch):
299 """"You wanted 6:00, we said 6:20" is the fact that makes every
300 capacity failure visible; one field holding whichever was written last
301 would hide all of them."""
302 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
303 slot(data_dir, "later", starts_in=80)
304 product(data_dir)
305 add_to_cart(objects_root)
306
307 checkout(objects_root, fulfillment_method="pickup", pickup_slot_id="later",
308 requested_at=at(60), now=NOW.isoformat())
309 order = orders(data_dir)[0]
310 assert order["requested_at"] == at(60)
311 assert order["promised_at"] == at(80)
312
313
314def test_two_shoppers_racing_for_the_last_place_are_told_before_they_pay(
315 tmp_path, monkeypatch):
316 """The race is not pretended away. What is promised is that the loser
317 finds out at checkout, with the next free time named, rather than
318 after handing over money."""
319 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
320 slot(data_dir, "last", starts_in=60, capacity=1)
321 slot(data_dir, "spare", starts_in=120, capacity=1)
322 product(data_dir)
323
324 add_to_cart(objects_root)
325 first = checkout(objects_root, fulfillment_method="pickup",
326 pickup_slot_id="last", now=NOW.isoformat())
327 assert first["ok"] is True
328
329 # A second shopper, a second basket, the same window.
330 run(objects_root, "action_cart", "POST",
331 {"session_token": "sess-pickup-2", "action": "add", "product_id": "p1"})
332 second = run(objects_root, "action_checkout", "POST",
333 {"session_token": "sess-pickup-2",
334 "customer_email": "other@example.test",
335 "fulfillment_method": "pickup", "pickup_slot_id": "last",
336 "now": NOW.isoformat()})
337 assert second["status"] == 409
338 assert second["next_free_slot"]["id"] == "spare"
339 # One order, not two, and no invoice raised for the loser.
340 assert len(orders(data_dir)) == 1
341
342
343# --- the regression that matters most ---------------------------------------------
344
345def test_a_shipping_checkout_is_exactly_what_it_was(tmp_path, monkeypatch):
346 """No pickup argument, no pickup read, no pickup key in the response,
347 no slot touched, and no blocker added -- even with a full slot board
348 sitting right there for it to trip over."""
349 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
350 slot(data_dir, "full", starts_in=60, capacity=1, taken=1)
351 slot(data_dir, "shut", starts_in=90, is_open="false")
352 product(data_dir)
353 add_to_cart(objects_root)
354
355 result = checkout(objects_root, today="2026-07-27")
356 assert result["ok"] is True
357 # No pickup key of any kind. The three money-layer totals are always
358 # present and always zero here: discount_cents, credit_applied_cents
359 # and an amount_due_cents that equals the total are what "this shop
360 # runs no promotions and took no gift card" looks like, and a response
361 # that omitted them would make a storefront ask whether the shop had
362 # them rather than read the number.
363 assert set(result) == {
364 "ok", "order_id", "cart_id", "subtotal_cents", "shipping_cents",
365 "shipping_free", "tax_cents", "total_cents", "lines",
366 "status_of_order", "note", "track_path", "invoice_id", "pay_path",
367 "discount_cents", "credit_applied_cents", "amount_due_cents",
368 }
369 assert result["discount_cents"] == 0
370 assert result["credit_applied_cents"] == 0
371 assert result["amount_due_cents"] == result["total_cents"]
372
373 order = orders(data_dir)[0]
374 # `shipping` arrives from the schema default, not from this file: the
375 # order is the row it would have been before v7 existed.
376 assert order["fulfillment_method"] == "shipping"
377 assert order["requested_at"] == "" and order["promised_at"] == ""
378 assert order["notes"] == f"Web checkout [carts/{result['cart_id']}]"
379 assert [(row["id"], row["orders_taken"]) for row in slots(data_dir)] == [
380 ("full", "1"), ("shut", "0")]
381
382
383def test_an_unknown_fulfilment_method_is_refused_rather_than_silently_shipped(
384 tmp_path, monkeypatch):
385 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
386 product(data_dir)
387 add_to_cart(objects_root)
388
389 blocked = checkout(objects_root, fulfillment_method="teleport")
390 assert blocked["status"] == 409
391 assert "teleport" in blocked["error"]
392 assert orders(data_dir) == []
393
394
395def test_delivery_and_counter_state_a_method_and_book_no_slot(
396 tmp_path, monkeypatch):
397 """There is no slot board for the van or the till, and inventing one
398 would be a rule nobody asked for."""
399 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
400 product(data_dir)
401 add_to_cart(objects_root)
402
403 result = checkout(objects_root, fulfillment_method="counter")
404 assert result["ok"] is True
405 assert result["fulfillment_method"] == "counter"
406 assert "pickup_slot_id" not in result
407 order = orders(data_dir)[0]
408 assert order["fulfillment_method"] == "counter"
409 assert order["promised_at"] == ""
410
411
412# --- the generator ------------------------------------------------------------------
413
414def generate(objects_root, **payload):
415 payload.setdefault("today", "2026-07-27")
416 return run(objects_root, "system_slot_generator", "POST", payload)
417
418
419GENERATOR_SETTINGS = (("pickup.open_time", "09:00"),
420 ("pickup.close_time", "12:00"),
421 ("pickup.slot_minutes", "30"),
422 ("pickup.capacity_per_slot", "3"),
423 ("pickup.days_ahead", "2"))
424
425
426def test_the_generator_builds_the_board_the_settings_describe(
427 tmp_path, monkeypatch):
428 """09:00-12:00 in half hours is six windows, and days_ahead=2 means
429 today plus two -- today included, because a shop that installs this
430 at eight in the morning must be able to take lunch orders today."""
431 data_dir, objects_root = setup_env(tmp_path, monkeypatch,
432 settings=GENERATOR_SETTINGS)
433 result = generate(objects_root)
434 assert result["created"] == 18
435 assert [day["created"] for day in result["days"]] == [6, 6, 6]
436
437 rows = sorted(slots(data_dir), key=lambda row: row["starts_at"])
438 assert rows[0]["starts_at"] == "2026-07-27T09:00:00"
439 assert rows[0]["ends_at"] == "2026-07-27T09:30:00"
440 assert rows[0]["capacity"] == "3"
441 assert rows[0]["orders_taken"] == "0"
442 assert rows[0]["is_open"] == "true"
443 # The last window ENDS at closing time; a half-length one would be a
444 # promise made by arithmetic rather than by anybody who works there.
445 assert rows[5]["starts_at"] == "2026-07-27T11:30:00"
446 assert rows[5]["ends_at"] == "2026-07-27T12:00:00"
447
448
449def test_the_generator_is_idempotent_across_two_runs(tmp_path, monkeypatch):
450 """It runs every night forever. The second run must create nothing --
451 idempotent by the row's own natural key, (starts_at, location)."""
452 data_dir, objects_root = setup_env(tmp_path, monkeypatch,
453 settings=GENERATOR_SETTINGS)
454 generate(objects_root)
455 before = {row["id"] for row in slots(data_dir)}
456
457 again = generate(objects_root)
458 assert again["created"] == 0
459 assert again["already_there"] == 18
460 assert {row["id"] for row in slots(data_dir)} == before
461
462
463def test_the_generator_never_restates_a_slot_somebody_edited(
464 tmp_path, monkeypatch):
465 """A slot an operator closed or resized is a decision. A nightly pass
466 that put it back would overwrite them every single night."""
467 data_dir, objects_root = setup_env(tmp_path, monkeypatch,
468 settings=GENERATOR_SETTINGS)
469 generate(objects_root)
470 nine = next(row for row in slots(data_dir)
471 if row["starts_at"] == "2026-07-27T09:00:00")
472 object_records.update_collection_record(
473 "pickup_slots", nine["id"], {"is_open": "false", "capacity": "1"},
474 base_dir=data_dir, actor="operator")
475
476 generate(objects_root)
477 kept = object_records.get_collection_record("pickup_slots", nine["id"],
478 base_dir=data_dir)
479 assert kept["is_open"] == "false" and kept["capacity"] == "1"
480 assert len(slots(data_dir)) == 18
481
482
483def test_the_generator_says_so_on_a_box_without_the_pickup_app(
484 tmp_path, monkeypatch):
485 """Not an exception every night on a shop that never wanted pickup."""
486 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
487 uninstall_pickup(data_dir)
488 result = generate(objects_root)
489 assert result["ok"] is True and "pickup not installed" in result["skipped"]
490
491
492# --- the hook -----------------------------------------------------------------------
493
494def hook(objects_root, record, action="create"):
495 return run(objects_root, "hook_pickup_slots", "BEFORE_WRITE",
496 {"collection": "pickup_slots", "action": action,
497 "record": record, "existing": None, "changes": record})
498
499
500def test_the_hook_refuses_more_orders_than_the_slot_can_hold_with_the_numbers(
501 tmp_path, monkeypatch):
502 """A gate that only says "no" leaves whoever is fixing the slot
503 guessing which of the two figures is the wrong one."""
504 _data_dir, objects_root = setup_env(tmp_path, monkeypatch)
505 refused = hook(objects_root, {"id": "s1", "starts_at": at(60),
506 "capacity": "2", "orders_taken": "5"},
507 action="update")
508 assert refused["status"] == 409
509 assert "capacity 2" in refused["error"]
510 assert "orders taken 5" in refused["error"]
511
512
513def test_the_hook_refuses_a_negative_capacity_and_allows_zero(
514 tmp_path, monkeypatch):
515 """Zero is a real statement -- this window exists and is full -- and
516 is a different one from is_open=false."""
517 _data_dir, objects_root = setup_env(tmp_path, monkeypatch)
518 refused = hook(objects_root, {"id": "s1", "starts_at": at(60),
519 "capacity": "-1", "orders_taken": "0"})
520 assert refused["status"] == 400
521 assert "-1" in refused["error"]
522
523 assert hook(objects_root, {"id": "s2", "starts_at": at(60),
524 "capacity": "0", "orders_taken": "0"}) is None
525
526
527# --- the band and the customer's page -------------------------------------------------
528
529# Every rung between draft and the status a test wants, because orders'
530# transitions are guarded and there is no shortcut through them.
531LADDER = {
532 "draft": ["draft"],
533 "confirmed": ["confirmed"],
534 "preparing": ["confirmed", "preparing"],
535 "ready": ["confirmed", "preparing", "ready"],
536 "collected": ["confirmed", "preparing", "ready", "collected"],
537 "shipped": ["confirmed", "shipped"],
538 "delivered": ["confirmed", "shipped", "delivered"],
539}
540
541
542def order_row(data_dir, order_id, *, status="confirmed", method="pickup",
543 promised=None, token=""):
544 record = {"id": order_id, "doc_type": "sale", "number": order_id.upper(),
545 "customer_name": "Ada Lovelace",
546 "customer_email": "ada@example.test", "currency": "USD",
547 "status": "draft", "order_date": "2026-07-27",
548 "fulfillment_method": method, "owner_id": "shop"}
549 if promised is not None:
550 record["promised_at"] = promised
551 if token:
552 record["portal_token"] = token
553 object_records.create_collection_record("orders", record, base_dir=data_dir,
554 actor="test", preserve_read_only=True)
555 # Up the ladder a rung at a time, the way a human would: the schema's
556 # own transitions are what make `collected` reachable only through
557 # `ready`, and a test that jumped straight there would be exercising a
558 # move the server refuses.
559 for rung in LADDER.get(status, [status]):
560 if rung == "draft":
561 continue
562 object_records.update_collection_record(
563 "orders", order_id, {"status": rung}, base_dir=data_dir, actor="test")
564 return object_records.get_collection_record("orders", order_id,
565 base_dir=data_dir)
566
567
568def test_an_order_past_its_promised_time_and_not_ready_needs_a_human(
569 tmp_path, monkeypatch):
570 """Late is a fact about a time that passed, so the count keys on
571 promised_at -- which is why a shipping order can never appear in it."""
572 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
573 past = (datetime.now() - timedelta(minutes=25)).isoformat()
574 future = (datetime.now() + timedelta(minutes=25)).isoformat()
575
576 order_row(data_dir, "late", promised=past)
577 order_row(data_dir, "soon", promised=future)
578 order_row(data_dir, "done", status="ready", promised=past)
579 order_row(data_dir, "parcel", method="shipping")
580
581 count = run(objects_root, "system_pickup_attention", "COUNT", {})
582 assert count["count"] == 1
583 assert "past its promised time" in count["detail"]
584
585
586def test_the_band_is_silent_when_nothing_is_late(tmp_path, monkeypatch):
587 """A count that reads zero is rendered nowhere; a band that is always
588 lit is a band nobody reads."""
589 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
590 order_row(data_dir, "soon",
591 promised=(datetime.now() + timedelta(hours=2)).isoformat())
592 assert run(objects_root, "system_pickup_attention", "COUNT", {}) == {"count": 0}
593
594
595def track(objects_root, token):
596 return run(objects_root, "site_order_status", "GET", {"token": token})["body"]
597
598
599def test_the_customer_reads_ready_for_collection_on_a_pickup_order(
600 tmp_path, monkeypatch):
601 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
602 order_row(data_dir, "pick", status="ready", token="tok-pickup",
603 promised="2026-07-27T18:00:00")
604
605 page = track(objects_root, "tok-pickup")
606 assert "Ready for collection" in page
607 assert "Ready by" in page
608 # Never the warehouse's word for it.
609 assert "On its way" not in page
610 assert "shipped" not in page
611
612
613def test_a_shipping_order_still_reads_on_its_way(tmp_path, monkeypatch):
614 """The regression beside the feature: adding the pickup vocabulary
615 must not change one word a parcel customer sees."""
616 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
617 order_row(data_dir, "parcel", status="shipped", method="shipping",
618 token="tok-shipping")
619
620 page = track(objects_root, "tok-shipping")
621 assert "On its way" in page
622 assert "Your order has left us and is with the carrier." in page
623 assert "Ready for collection" not in page
624 assert "Ready by" not in page
625
626
627def test_the_pickup_ladder_reads_in_the_customers_words_at_every_rung(
628 tmp_path, monkeypatch):
629 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
630 expected = {"confirmed": "Order received", "preparing": "Being prepared",
631 "ready": "Ready for collection", "collected": "Collected"}
632 for index, (status, word) in enumerate(expected.items()):
633 order_row(data_dir, f"p{index}", status=status, token=f"tok-{index}")
634 assert word in track(objects_root, f"tok-{index}"), status
635
636
637# --- the package itself -----------------------------------------------------------------
638
639def test_the_package_installs_on_a_bare_box(tmp_path):
640 """Structural, and worth its two lines: a package whose dry run is not
641 clean is a package nobody can ship, however well its objects behave
642 under a test harness that copies them into place by hand."""
643 object_root = tmp_path / "objects"
644 object_root.mkdir()
645 plan = object_packages.dry_run_package(
646 "app-pickup", root=PACKAGES, base_dir=tmp_path / "data",
647 object_roots=[object_root])
648 assert plan["safe_to_install"] is True
649 assert plan["warnings"] == []
650
651 object_packages.install_package(
652 "app-pickup", root=PACKAGES, base_dir=tmp_path / "data",
653 object_roots=[object_root])
654 schema = object_schemas.get_schema("pickup_slots",
655 base_dir=tmp_path / "data")
656 assert schema["name"] == "pickup_slots"
657 # The gate is declared on the collection, not merely shipped beside it:
658 # a hook nothing points at is a hook that never runs.
659 assert schema["hooks"]["before_write"] == "hook_pickup_slots"
660
661
662def test_capacity_is_counted_in_orders_and_the_schema_says_why():
663 """The load-bearing decision in this package, asserted so a later
664 refactor to "items" has to argue with a test rather than a comment."""
665 schema = json.loads(
666 (PACKAGES / "app-pickup" / "schemas" / "pickup_slots.json").read_text())
667 by_name = {field["name"]: field for field in schema["fields"]}
668 assert by_name["capacity"]["type"] == "integer"
669 assert "orders" in by_name["capacity"]["label"].lower()
670 assert "ORDERS, NOT ITEMS" in schema["description"].upper()
671 # orders_taken is maintained by the checkout gate, so it is kept out of
672 # the default form for the same reason the stamped totals are on
673 # orders: a number a person types over is a number that stops being a
674 # record of what happened.
675 assert "orders_taken" not in schema["forms"]["default"]["fields"]
676
677
678# --- the object ids a fresh box must be able to find ------------------------------------
679
680def test_an_empty_box_offers_no_slots_rather_than_an_error_page(
681 tmp_path, monkeypatch):
682 """A storefront on a box without the pickup app gets an empty picker,
683 not a traceback where its time buttons should be."""
684 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
685 uninstall_pickup(data_dir)
686 answer = bookable(objects_root)
687 assert answer["ok"] is True and answer["slots"] == []