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