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_reorder.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_reorder.py · 21.7 KB · 497 lines
1"""Backorders and reorder points: selling what is not on the shelf, and
2noticing before the shelf is empty.
3
4Three claims.
5
6**The default is yesterday.** products.backorder_policy defaults to
7`refuse`, so a catalogue that has never heard of the field -- which is
8every catalogue on every box today -- behaves byte-for-byte as it did.
9That regression is the first test in this file and it is the one that
10makes the rest of the feature safe to ship.
11
12**Refusing while remembering beats refusing and forgetting.** `notify`
13still turns the customer away, and writes down that they came, because
14losing the sale is survivable and losing the customer twice is not.
15
16**The pass suggests; the person decides.** system_reorder_check folds the
17stock ledger and writes a suggestion. It does not raise a purchase order
18and it never will: the fold can see the shelf and cannot see the lead
19time, the case size, the supplier's minimum or the cash in the bank, and
20a machine that orders on its own is how a business ends up with forty
21pallets of the wrong thing.
22
23The two halves that are NOT done are held at the bottom as strict xfails,
24the same way tests/test_dropship.py held its two: each needs one
25condition in a package this slice does not own (app-orders' order_lines
26column, app-shipping's fulfilment gate), and a green test over a shelf
27that silently ships is worse than a red one.
28"""
29
30import pathlib
31import shutil
32
33import pytest
34from conftest import stage_collection
35from test_attention_declared import shipped_count
36
37import object_cart
38import object_execution
39import object_ids
40import object_records
41import python_object_runtime
42
43REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
44PACKAGES = REPO_ROOT / "packages"
45SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
46CATALOG_OBJECTS = PACKAGES / "app-catalog" / "objects"
47SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
48RUNTIME = python_object_runtime.PythonObjectRuntime()
49
50TOKEN = "sess-back"
51TODAY = "2026-06-15"
52
53
54# --- the pure decision, with no data directory in sight -----------------------
55
56def test_a_product_that_has_never_heard_of_the_field_still_refuses():
57 """The whole safety of this feature is in one default. A blank, a
58 missing column and a value typed wrong must all read as `refuse`."""
59 for product in ({}, {"backorder_policy": ""},
60 {"backorder_policy": "yes please"}, None):
61 assert object_cart.backorder_policy(product) == "refuse"
62 assert object_cart.backorder_policy({"backorder_policy": "allow"}) == "allow"
63
64
65def test_out_of_stock_splits_three_ways_and_only_one_of_them_sells():
66 items = [{"id": "a", "product_id": "strict", "quantity": "5"},
67 {"id": "b", "product_id": "loose", "quantity": "5"},
68 {"id": "c", "product_id": "curious", "quantity": "5"}]
69 products = {
70 "strict": {"is_active": "true", "backorder_policy": "refuse"},
71 "loose": {"is_active": "true", "backorder_policy": "allow"},
72 "curious": {"is_active": "true", "backorder_policy": "notify"},
73 }
74 on_hand = {"strict": 1, "loose": 1, "curious": 1}
75 blockers = object_cart.checkout_blockers(
76 items, products, on_hand, tracked=set(products))
77
78 assert [row["product_id"] for row in blockers["unavailable"]] == [
79 "strict", "curious"]
80 assert [row["product_id"] for row in blockers["backordered"]] == ["loose"]
81 assert [row["product_id"] for row in blockers["notify"]] == ["curious"]
82 assert blockers["can_checkout"] is False # two of them still block
83
84 # With only the backorderable line short, the basket goes through.
85 only_loose = object_cart.checkout_blockers(
86 [items[1]], products, on_hand, tracked=set(products))
87 assert only_loose["can_checkout"] is True
88 assert only_loose["backordered"][0]["short_by"] == "4"
89
90
91# --- the shop -----------------------------------------------------------------
92
93def setup_env(tmp_path, monkeypatch, *, with_shipping=False):
94 data_dir = tmp_path / "data"
95 for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"),
96 ("app-catalog", "products"), ("app-catalog", "locations"),
97 ("app-catalog", "stock_moves"),
98 ("app-catalog", "backorders"),
99 ("app-catalog", "reorder_suggestions"),
100 ("app-orders", "orders"), ("app-orders", "order_lines"),
101 ("app-invoices", "invoices"),
102 ("app-invoices", "invoice_lines"),
103 ("app-payments", "payments")):
104 stage_collection(data_dir, pkg, name)
105 if with_shipping:
106 for name in ("shipments", "shipment_lines"):
107 stage_collection(data_dir, "app-shipping", name)
108 stage_collection(data_dir, "app-settings", "app_settings")
109
110 objects_root = tmp_path / "objects"
111 sources = [SHOP_OBJECTS, CATALOG_OBJECTS]
112 if with_shipping:
113 sources.append(SHIPPING_OBJECTS)
114 for source in sources:
115 shutil.copytree(source, objects_root, dirs_exist_ok=True)
116 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
117 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
118 object_records.create_collection_record(
119 "locations",
120 {"id": "loc-shelf", "name": "Shelf", "location_type": "warehouse",
121 "owner_id": "shop"}, base_dir=data_dir)
122 return data_dir, objects_root
123
124
125def product(data_dir, product_id, name, cents, **fields):
126 record = {"id": product_id, "name": name, "sku": product_id.upper(),
127 "product_type": "physical", "price_cents": str(cents),
128 "currency": "USD", "is_active": "true", "owner_id": "shop"}
129 record.update({k: str(v) for k, v in fields.items()})
130 return object_records.create_collection_record("products", record,
131 base_dir=data_dir)
132
133
134def stock_in(data_dir, product_id, quantity):
135 """Put `quantity` on the shelf. Zero writes nothing (a move must move
136 something -- stock_moves.quantity is `exclusive_min: 0`, for every
137 writer), and a negative number is a move OFF the shelf."""
138 if quantity == 0:
139 return None
140 off = quantity < 0
141 return object_records.create_collection_record(
142 "stock_moves",
143 {"id": object_ids.new_uuid4(), "product_id": product_id,
144 "to_location_id": "" if off else "loc-shelf",
145 "from_location_id": "loc-shelf" if off else "",
146 "quantity": str(abs(quantity)),
147 "reason": "sale" if off else "purchase",
148 "occurred_at": "2026-06-01", "owner_id": "shop"},
149 base_dir=data_dir)
150
151
152def run(object_id, payload, objects_root, *, method="POST"):
153 return object_execution.execute_object(
154 RUNTIME,
155 object_execution.ObjectExecutionRequest(object_id, method=method,
156 payload=payload),
157 roots=[objects_root]).result
158
159
160def cart(objects_root, action="get", **payload):
161 return run("action_cart", {"session_token": TOKEN, "action": action,
162 **payload}, objects_root)
163
164
165def checkout(objects_root, **payload):
166 payload.setdefault("today", TODAY)
167 return run("action_checkout", {"session_token": TOKEN, **payload},
168 objects_root)
169
170
171def rows(data_dir, collection):
172 return object_records.read_collection_records(collection, base_dir=data_dir)
173
174
175# --- backorders ---------------------------------------------------------------
176
177def test_refuse_behaves_exactly_as_the_shop_behaved_yesterday(tmp_path, monkeypatch):
178 """The regression that makes the rest of this shippable: a product
179 with no policy set is refused with the same numbers, in the same
180 shape, and writes no backorder row at all."""
181 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
182 product(data_dir, "p1", "Enamel Mug", 1000)
183 stock_in(data_dir, "p1", 1)
184 cart(objects_root, "add", product_id="p1", quantity="3")
185
186 refused = checkout(objects_root, customer_email="ada@example.com")
187 assert refused["status"] == 409
188 assert refused["error"] == "Some items cannot be ordered right now."
189 short = refused["unavailable"][0]
190 assert short["product_id"] == "p1"
191 assert short["wanted"] == "3" and short["available"] == "1"
192 assert short["short_by"] == "2"
193 assert not rows(data_dir, "orders")
194 assert not rows(data_dir, "backorders")
195
196
197def test_allow_takes_the_order_and_marks_what_is_owed(tmp_path, monkeypatch):
198 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
199 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="allow")
200 stock_in(data_dir, "p1", 1)
201 cart(objects_root, "add", product_id="p1", quantity="3")
202
203 placed = checkout(objects_root, customer_email="ada@example.com")
204 assert placed["ok"] is True
205 assert placed["total_cents"] == 3000 # the whole line is sold
206 assert placed["backordered"][0]["short_by"] == "2"
207 assert "backordered" in placed["note"]
208
209 waiting = rows(data_dir, "backorders")
210 assert len(waiting) == 1
211 assert waiting[0]["kind"] == "backorder"
212 assert waiting[0]["quantity"] == "2"
213 assert waiting[0]["status"] == "open"
214 assert waiting[0]["order_id"] == placed["order_id"]
215 assert waiting[0]["customer_email"] == "ada@example.com"
216 assert waiting[0]["requested_on"] == TODAY
217 # The row names the LINE, which is what lets fulfilment leave it behind
218 # while the rest of the order goes out today.
219 line = rows(data_dir, "order_lines")[0]
220 assert waiting[0]["order_line_id"] == line["id"]
221
222
223def test_notify_still_refuses_but_writes_down_who_asked(tmp_path, monkeypatch):
224 """Refusing while remembering beats refusing and forgetting, which is
225 how the same customer is lost twice."""
226 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
227 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="notify")
228 stock_in(data_dir, "p1", 0)
229 cart(objects_root, "add", product_id="p1", quantity="2")
230
231 refused = checkout(objects_root, customer_email="ada@example.com")
232 assert refused["status"] == 409
233 assert refused["unavailable"] # still a refusal
234 assert not rows(data_dir, "orders")
235
236 interest = rows(data_dir, "backorders")
237 assert len(interest) == 1
238 assert interest[0]["kind"] == "notify"
239 assert interest[0]["order_id"] == "" # nothing was sold
240 assert interest[0]["customer_email"] == "ada@example.com"
241 assert refused["interest_recorded"][0]["product_id"] == "p1"
242
243 # And pressing the button five times is one person waiting, not five.
244 checkout(objects_root, customer_email="ada@example.com")
245 checkout(objects_root, customer_email="ADA@example.com")
246 assert len(rows(data_dir, "backorders")) == 1
247
248
249def test_a_preview_of_a_refused_basket_files_no_interest(tmp_path, monkeypatch):
250 """A preview is a look. The rule that a preview writes nothing has to
251 hold on the refusal path too, or a storefront that quotes before it
252 submits files a waiting-list entry for everybody who glanced at an
253 empty shelf."""
254 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
255 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="notify")
256 stock_in(data_dir, "p1", 0)
257 cart(objects_root, "add", product_id="p1", quantity="1")
258
259 quoted = checkout(objects_root, preview="true",
260 customer_email="ada@example.com")
261 assert quoted["status"] == 409
262 assert rows(data_dir, "backorders") == []
263
264
265def test_interest_with_nowhere_to_send_it_is_not_recorded(tmp_path, monkeypatch):
266 """A record of interest with no way to reach the interested party is a
267 record of nothing."""
268 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
269 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="notify")
270 stock_in(data_dir, "p1", 0)
271 cart(objects_root, "add", product_id="p1", quantity="1")
272
273 refused = checkout(objects_root) # no email at all
274 assert refused["status"] == 409
275 assert rows(data_dir, "backorders") == []
276 assert "interest_recorded" not in refused
277
278
279def test_the_backorder_count_is_the_open_ones_and_names_the_longest_wait(tmp_path, monkeypatch):
280 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
281 product(data_dir, "p1", "Mug", 1000)
282 for row_id, status, day in (("b1", "open", "2026-06-01"),
283 ("b2", "open", "2026-06-10"),
284 ("b3", "filled", "2026-01-01")):
285 object_records.create_collection_record(
286 "backorders",
287 {"id": row_id, "product_id": "p1", "kind": "backorder",
288 "quantity": "1", "status": status, "requested_on": day,
289 "owner_id": "shop"}, base_dir=data_dir)
290
291 counted = shipped_count("app-catalog", "backorders_waiting", data_dir)
292 assert counted["count"] == 2
293 assert "oldest waiting" in counted["detail"]
294
295
296# --- reorder points -----------------------------------------------------------
297
298def reorder(objects_root, **payload):
299 payload.setdefault("today", TODAY)
300 return run("system_reorder_check", payload, objects_root)
301
302
303def test_the_pass_suggests_and_never_orders(tmp_path, monkeypatch):
304 """A machine that raises purchase orders on its own is how a business
305 orders forty pallets of the wrong thing."""
306 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
307 product(data_dir, "p1", "Enamel Mug", 1000, reorder_point=5,
308 reorder_quantity=24)
309 stock_in(data_dir, "p1", 3)
310
311 result = reorder(objects_root)
312 assert result["suggested"] == 1
313 assert result["ordered"] == 0
314 assert "never raises a purchase order" in result["note"]
315
316 suggestion = rows(data_dir, "reorder_suggestions")[0]
317 assert suggestion["product_id"] == "p1"
318 assert suggestion["on_hand"] == "3"
319 assert suggestion["reorder_point"] == "5"
320 assert suggestion["suggested_quantity"] == "24"
321 assert suggestion["status"] == "open"
322 assert suggestion["suggested_on"] == TODAY
323
324 # Nothing anywhere that looks like a purchase.
325 assert not rows(data_dir, "orders")
326 assert not rows(data_dir, "stock_moves") or all(
327 row["reason"] == "purchase" and row["id"] != suggestion["id"]
328 for row in rows(data_dir, "stock_moves"))
329
330
331def test_the_threshold_is_at_or_below_and_not_merely_below(tmp_path, monkeypatch):
332 """'Reorder at 5' means five is already the moment. A shop that had to
333 fall to four has been given a number that means something else."""
334 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
335 product(data_dir, "at", "At the line", 1000, reorder_point=5)
336 product(data_dir, "over", "Above it", 1000, reorder_point=5)
337 stock_in(data_dir, "at", 5)
338 stock_in(data_dir, "over", 6)
339
340 reorder(objects_root)
341 assert [row["product_id"] for row in rows(data_dir, "reorder_suggestions")] == ["at"]
342
343
344def test_a_reorder_point_of_zero_is_off_not_reorder_at_zero(tmp_path, monkeypatch):
345 """Most catalogues have a handful of lines anybody actually reorders,
346 and a queue lit up by every service and made-to-order item is a queue
347 nobody reads."""
348 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
349 product(data_dir, "p1", "Never reordered", 1000) # no point set
350 stock_in(data_dir, "p1", 0)
351
352 result = reorder(objects_root)
353 assert result["checked"] == 0
354 assert rows(data_dir, "reorder_suggestions") == []
355
356
357def test_an_inactive_product_is_not_reordered(tmp_path, monkeypatch):
358 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
359 product(data_dir, "p1", "Discontinued", 1000, reorder_point=5,
360 is_active="false")
361 stock_in(data_dir, "p1", 0)
362 reorder(objects_root)
363 assert rows(data_dir, "reorder_suggestions") == []
364
365
366def test_a_second_pass_refreshes_the_open_row_instead_of_adding_another(tmp_path, monkeypatch):
367 """A nightly pass that appended would turn one true fact into ninety
368 within a quarter, which is how a good signal becomes noise."""
369 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
370 product(data_dir, "p1", "Enamel Mug", 1000, reorder_point=5,
371 reorder_quantity=24)
372 stock_in(data_dir, "p1", 3)
373 reorder(objects_root)
374
375 stock_in(data_dir, "p1", -1)
376 second = reorder(objects_root, today="2026-06-16")
377 assert second["suggested"] == 0 and second["refreshed"] == 1
378
379 suggestions = rows(data_dir, "reorder_suggestions")
380 assert len(suggestions) == 1
381 assert suggestions[0]["on_hand"] == "2"
382 assert suggestions[0]["suggested_on"] == "2026-06-16"
383
384
385def test_a_dismissed_suggestion_is_left_alone_and_stops_counting(tmp_path, monkeypatch):
386 """A count nobody can dismiss stays lit forever and teaches people to
387 ignore the band it sits in."""
388 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
389 product(data_dir, "p1", "Enamel Mug", 1000, reorder_point=5)
390 stock_in(data_dir, "p1", 3)
391 reorder(objects_root)
392 suggestion = rows(data_dir, "reorder_suggestions")[0]
393
394 object_records.update_collection_record(
395 "reorder_suggestions", suggestion["id"], {"status": "dismissed"},
396 base_dir=data_dir, actor="operator")
397 assert run("system_reorder_attention", {}, objects_root,
398 method="COUNT")["count"] == 0
399
400 # The next pass raises a fresh one rather than reopening the answered
401 # row: the human said no to what they were shown, not to the question
402 # forever.
403 again = reorder(objects_root, today="2026-06-16")
404 assert again["suggested"] == 1
405 assert {row["status"] for row in rows(data_dir, "reorder_suggestions")} == {
406 "dismissed", "open"}
407
408
409def test_the_reorder_count_keys_on_the_open_rows_and_names_the_worst(tmp_path, monkeypatch):
410 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
411 product(data_dir, "deep", "Very low", 1000, reorder_point=10)
412 product(data_dir, "shallow", "Just under", 1000, reorder_point=5)
413 stock_in(data_dir, "deep", 2)
414 stock_in(data_dir, "shallow", 4)
415 reorder(objects_root)
416
417 counted = run("system_reorder_attention", {}, objects_root, method="COUNT")
418 assert counted["count"] == 2
419 assert counted["detail"] == "one is 8 below its point"
420
421
422def test_the_pass_costs_nothing_on_a_box_with_no_catalogue(tmp_path, monkeypatch):
423 """A pass should not log an error every night about an app nobody
424 installed."""
425 data_dir = tmp_path / "data"
426 (data_dir / "schemas").mkdir(parents=True)
427 objects_root = tmp_path / "objects"
428 shutil.copytree(CATALOG_OBJECTS, objects_root, dirs_exist_ok=True)
429 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
430 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
431
432 assert reorder(objects_root)["suggested"] == 0
433 assert run("system_reorder_attention", {}, objects_root,
434 method="COUNT") == {"count": 0}
435 assert shipped_count("app-catalog", "backorders_waiting", data_dir) == {
436 "count": 0, "detail": ""}
437
438
439# --- the halves that are NOT done, held as specifications ---------------------
440#
441# Each needs one condition in a package this slice does not own, and
442# hacking around a sibling package's handler would be exactly the kind of
443# "make it work by the data" a stock rule cannot afford. Writing the
444# acceptance test first and leaving it red is the honest move -- the same
445# thing tests/test_dropship.py did for its two conditions -- because a
446# green test over a shelf that silently ships is worse than a red one.
447#
448# FOLLOW-UP 1 (app-orders): order_lines needs a `backordered` boolean.
449# action_checkout already stamps it through the same _has_field check it
450# uses for shipping_cents and line_note, so the day the column exists
451# this passes with no change here and no change there.
452#
453# FOLLOW-UP 2 (app-shipping): action_create_shipment defaults to
454# EVERYTHING unshipped, which today includes a line the shop has openly
455# agreed it does not have. It needs to skip lines that are backordered
456# -- readable either from the order_lines column above or from the
457# backorders rows this slice writes -- and system_order_fulfillment must
458# agree, or the shop ships goods that are not in the building and the
459# stock ledger goes negative on a sale nobody could pick.
460
461
462def test_a_backordered_line_is_marked_on_the_order_itself(tmp_path, monkeypatch):
463 """The picker and the packer read the ORDER. A fact that lives only in
464 another app's collection is a fact the warehouse never sees."""
465 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
466 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="allow")
467 stock_in(data_dir, "p1", 1)
468 cart(objects_root, "add", product_id="p1", quantity="3")
469 checkout(objects_root, customer_email="ada@example.com")
470
471 line = rows(data_dir, "order_lines")[0]
472 assert line.get("backordered") == "true"
473
474
475def test_a_backordered_line_does_not_go_in_the_box(tmp_path, monkeypatch):
476 """The whole promise of `allow` is that the sale happens and the goods
477 follow. Shipping the part that does not exist breaks both halves at
478 once: the customer gets a short parcel and the shelf shows minus two."""
479 data_dir, objects_root = setup_env(tmp_path, monkeypatch, with_shipping=True)
480 product(data_dir, "p1", "Enamel Mug", 1000, backorder_policy="allow")
481 stock_in(data_dir, "p1", 1)
482 cart(objects_root, "add", product_id="p1", quantity="3")
483 placed = checkout(objects_root, customer_email="ada@example.com")
484 object_records.update_collection_record(
485 "orders", placed["order_id"], {"status": "confirmed"},
486 base_dir=data_dir, actor="test")
487
488 # An admin packer: the action refuses anybody the permission engine
489 # would not let update the order.
490 shipment = run("action_create_shipment",
491 {"order_id": placed["order_id"], "today": TODAY,
492 "_identity": {"user_id": "warehouse", "roles": ["admin"]}},
493 objects_root)
494 packed = [row for row in rows(data_dir, "shipment_lines")
495 if row["shipment_id"] == shipment.get("shipment_id")]
496 # One on the shelf, two owed: the box holds one.
497 assert [row["quantity"] for row in packed] == ["1"]