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_receiving.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_receiving.py · 29.1 KB · 657 lines
1"""Receipts: the document that says what turned up on the dock.
2
3The properties worth holding here are the ones a shop discovers the hard
4way, and most of them are the mirror of the shipping slice's. You cannot
5receive more than was ordered, and being told so is only useful if the
6refusal carries the numbers. Two deliveries against one purchase order
7derive partial then received, each exactly once, without anybody typing a
8status. A replayed event shelves nothing twice, because events ARE
9replayed (object_change_dispatch promises at-least-once).
10
11The ones that are NOT a mirror are the interesting ones. A rejection is
12not a short delivery: rejected goods physically arrived, so the fact is
13recorded, and no stock move is composed because they never entered stock.
14A line that received nothing has to SAY why, or it is indistinguishable
15from a half-typed row. And a `purchase` move carries unit_cost_cents from
16the price we agreed to pay -- the cost on the way in that valuation
17(and therefore COGS, see test_cogs_on_sale.py) will need and that cannot
18be reconstructed later.
19"""
20
21import pathlib
22import shutil
23
24import pytest
25
26from conftest import stage_collection
27
28import object_execution
29import object_ids
30import object_records
31import python_object_runtime
32
33REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
34PACKAGES = REPO_ROOT / "packages"
35RECEIVING_OBJECTS = PACKAGES / "app-receiving" / "objects"
36RUNTIME = python_object_runtime.PythonObjectRuntime()
37
38
39def setup_env(tmp_path, monkeypatch, *, settings=()):
40 """A data dir with every collection this slice touches, and one object
41 root holding the package's objects -- the shape an installed server
42 actually has (every package installs into the same objects directory).
43 """
44 data_dir = tmp_path / "data"
45 for pkg, name in (("app-receiving", "receipts"),
46 ("app-receiving", "receipt_lines"),
47 ("app-catalog", "products"), ("app-catalog", "locations"),
48 ("app-catalog", "stock_moves"),
49 ("app-orders", "orders"), ("app-orders", "order_lines")):
50 stage_collection(data_dir, pkg, name)
51 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
52 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
53
54 objects_root = tmp_path / "objects"
55 shutil.copytree(RECEIVING_OBJECTS, objects_root, dirs_exist_ok=True)
56
57 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
58 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
59 return data_dir, objects_root
60
61
62def run(objects_root, object_id, method, payload):
63 return object_execution.execute_object(
64 RUNTIME,
65 object_execution.ObjectExecutionRequest(
66 object_id, method=method, payload=payload),
67 roots=[objects_root]).result
68
69
70# --- fixtures shaped like a real shop -----------------------------------------
71
72def product(data_dir, product_id, name, cents=1200):
73 return object_records.create_collection_record(
74 "products",
75 {"id": product_id, "name": name, "sku": product_id.upper(),
76 "product_type": "physical", "price_cents": str(cents),
77 "currency": "USD", "is_active": "true", "owner_id": "shop"},
78 base_dir=data_dir)
79
80
81def location(data_dir, location_id, name, kind="warehouse"):
82 return object_records.create_collection_record(
83 "locations",
84 {"id": location_id, "name": name, "location_type": kind,
85 "owner_id": "shop"},
86 base_dir=data_dir)
87
88
89def purchase_order(data_dir, order_id="po-1", *, status="confirmed",
90 number="PO-0001", doc_type="purchase", owner="shop",
91 **fields):
92 record = {"id": order_id, "doc_type": doc_type, "number": number,
93 "customer_name": "Kiln & Clay Ltd",
94 "customer_email": "sales@kiln.test", "currency": "USD",
95 "status": "draft", "order_date": "2026-07-01", "owner_id": owner}
96 record.update({k: str(v) for k, v in fields.items()})
97 created = object_records.create_collection_record("orders", record,
98 base_dir=data_dir)
99 if status != "draft":
100 # Through the ladder, the way a human would: draft is where every
101 # order starts, purchase or sale.
102 object_records.update_collection_record(
103 "orders", order_id, {"status": "confirmed"},
104 base_dir=data_dir, actor="test")
105 if status != "confirmed":
106 object_records.update_collection_record(
107 "orders", order_id, {"status": status},
108 base_dir=data_dir, actor="test")
109 created = object_records.get_collection_record("orders", order_id,
110 base_dir=data_dir)
111 return created
112
113
114def order_line(data_dir, line_id, order_id="po-1", *, product_id="p1",
115 description="Enamel Mug", quantity="10", cents=450):
116 return object_records.create_collection_record(
117 "order_lines",
118 {"id": line_id, "order_id": order_id, "product_id": product_id,
119 "description": description, "quantity": str(quantity),
120 "unit_price_cents": str(cents),
121 "line_total_cents": str(int(float(quantity) * cents)),
122 "owner_id": "shop"},
123 base_dir=data_dir)
124
125
126def receipts(data_dir):
127 return object_records.read_collection_records("receipts", base_dir=data_dir)
128
129
130def receipt_lines(data_dir):
131 return object_records.read_collection_records("receipt_lines",
132 base_dir=data_dir)
133
134
135def purchases(data_dir):
136 return [move for move in object_records.read_collection_records(
137 "stock_moves", base_dir=data_dir) if move["reason"] == "purchase"]
138
139
140def order_status(data_dir, order_id="po-1"):
141 return object_records.get_collection_record("orders", order_id,
142 base_dir=data_dir)["status"]
143
144
145def receive(objects_root, **payload):
146 """As the shop that owns the purchase order: the action refuses anybody
147 the permission engine would not let update it."""
148 payload.setdefault("_identity", {"user_id": "shop"})
149 return run(objects_root, "action_receive_goods", "POST", payload)
150
151
152def open_receipt(data_dir, receipt_id="rec-open", order_id="po-1", *,
153 lines=()):
154 """A receipt still being counted -- the pallet is on the floor and
155 nobody has signed for it yet.
156
157 Written directly, the way any trusted server-side write is:
158 action_receive_goods signs its own receipts off in the same pass, so
159 `open` is reachable in a test only through the raw path -- which is
160 precisely the path hook_receipt_lines exists to guard.
161 """
162 receipt = object_records.create_collection_record(
163 "receipts",
164 {"id": receipt_id, "order_id": order_id, "status": "open",
165 "received_on": "2026-07-20", "owner_id": "shop"},
166 base_dir=data_dir)
167 for index, (order_line_id, quantity) in enumerate(lines):
168 object_records.create_collection_record(
169 "receipt_lines",
170 {"id": f"{receipt_id}-line-{index}", "receipt_id": receipt_id,
171 "order_line_id": order_line_id, "product_id": "p1",
172 "description": "Enamel Mug", "quantity_expected": str(quantity),
173 "quantity_received": str(quantity), "quantity_rejected": "0",
174 "owner_id": "shop"},
175 base_dir=data_dir)
176 return receipt
177
178
179def hook(objects_root, record, action="create"):
180 return run(objects_root, "hook_receipt_lines", "BEFORE_WRITE",
181 {"action": action, "collection": "receipt_lines",
182 "record": record})
183
184
185def post_receipt(objects_root, receipt_id):
186 """The dispatcher's own payload shape: EVENT verb, record_id, raw action."""
187 return run(objects_root, "system_receipt_posting", "EVENT",
188 {"event": "receipts.record.updated", "collection": "receipts",
189 "record_id": receipt_id, "action": "update"})
190
191
192def stocked_shop(tmp_path, monkeypatch, *, quantity="10", status="confirmed",
193 settings=None, doc_type="purchase"):
194 if settings is None:
195 settings = [("receiving.supplier_location", "loc-supplier"),
196 ("receiving.stock_location", "loc-shelf")]
197 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=settings)
198 location(data_dir, "loc-shelf", "Shelf")
199 location(data_dir, "loc-supplier", "Suppliers", kind="supplier")
200 product(data_dir, "p1", "Enamel Mug")
201 purchase_order(data_dir, status=status, doc_type=doc_type)
202 order_line(data_dir, "po-line-1", quantity=quantity)
203 return data_dir, objects_root
204
205
206# --- the gate ------------------------------------------------------------------
207
208def test_over_receiving_is_refused_with_all_three_numbers(tmp_path, monkeypatch):
209 """"No" is not an answer a receiver can act on. Which of the two
210 deliveries is wrong is only knowable from the numbers."""
211 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
212 first = receive(objects_root, order_id="po-1",
213 lines=[{"order_line_id": "po-line-1",
214 "quantity_received": "8"}])
215 assert first["ok"]
216
217 # A second delivery, still being counted, claiming three more.
218 open_receipt(data_dir)
219 refused = hook(objects_root, {"id": object_ids.new_uuid4(),
220 "receipt_id": "rec-open",
221 "order_line_id": "po-line-1",
222 "quantity_received": "3",
223 "quantity_rejected": "0"})
224 assert refused["status"] == 409
225 assert "ordered 10" in refused["error"]
226 assert "already received 8" in refused["error"]
227 assert "would make 11" in refused["error"]
228
229
230def test_the_action_reports_over_receiving_before_writing_anything(
231 tmp_path, monkeypatch):
232 """The hook guards the generic write path; the action has to guard its
233 own, because trusted server-side writes bypass hooks by design."""
234 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
235 receive(objects_root, order_id="po-1",
236 lines=[{"order_line_id": "po-line-1", "quantity_received": "8"}])
237
238 refused = receive(objects_root, order_id="po-1",
239 lines=[{"order_line_id": "po-line-1",
240 "quantity_received": "3"}])
241 assert refused["status"] == 409
242 assert refused["over_receive"][0] == {
243 "order_line_id": "po-line-1", "description": "Enamel Mug",
244 "ordered": "10", "already_received": "8", "asked_for": "3",
245 "would_make": "11"}
246 assert len(receipts(data_dir)) == 1 # nothing half-written
247
248
249def test_a_settled_receipt_refuses_new_lines(tmp_path, monkeypatch):
250 """A delivery is settled once it has been signed for: a carton found
251 afterwards is a NEW receipt, not a rewrite of what the driver handed
252 over."""
253 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
254 created = receive(objects_root, order_id="po-1",
255 lines=[{"order_line_id": "po-line-1",
256 "quantity_received": "4"}])
257
258 refused = hook(objects_root, {"id": object_ids.new_uuid4(),
259 "receipt_id": created["receipt_id"],
260 "order_line_id": "po-line-1",
261 "quantity_received": "1",
262 "quantity_rejected": "0"})
263 assert refused["status"] == 409
264 assert "already received" in refused["error"]
265 assert "NEW receipt" in refused["error"]
266
267
268def test_a_zero_received_line_with_no_note_is_refused(tmp_path, monkeypatch):
269 """A blank zero is indistinguishable from a row somebody has not
270 finished typing, and the two need opposite answers when the supplier's
271 invoice arrives."""
272 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
273 open_receipt(data_dir)
274
275 refused = hook(objects_root, {"id": object_ids.new_uuid4(),
276 "receipt_id": "rec-open",
277 "order_line_id": "po-line-1",
278 "quantity_received": "0",
279 "quantity_rejected": "0"})
280 assert refused["status"] == 400
281 assert "says nothing about" in refused["error"]
282 assert "short delivery" in refused["error"]
283
284 # The same line WITH a note is exactly the short delivery this system
285 # exists to record, and is allowed through.
286 allowed = hook(objects_root, {"id": object_ids.new_uuid4(),
287 "receipt_id": "rec-open",
288 "order_line_id": "po-line-1",
289 "quantity_received": "0",
290 "quantity_rejected": "0",
291 "discrepancy_note": "nothing on the pallet"})
292 assert allowed is None or allowed == {}
293
294
295def test_a_receipt_line_cannot_be_negative(tmp_path, monkeypatch):
296 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
297 open_receipt(data_dir)
298
299 # `validation.min` 0 on quantity_received / quantity_rejected: the
300 # schema refuses it for every writer, so no hook has to.
301 for field in ("quantity_received", "quantity_rejected"):
302 line = {"id": object_ids.new_uuid4(), "receipt_id": "rec-open",
303 "order_line_id": "po-line-1", "quantity_received": "1",
304 "quantity_rejected": "0"}
305 line[field] = "-1"
306 with pytest.raises(object_records.InvalidRecordPayloadError, match="below min"):
307 object_records.create_collection_record("receipt_lines", line,
308 base_dir=data_dir)
309
310
311def test_lines_of_a_cancelled_receipt_do_not_consume_the_order(
312 tmp_path, monkeypatch):
313 """A receipt raised and then abandoned describes no goods -- being
314 refused for re-checking-in a delivery after voiding a mistyped receipt
315 would be the paperwork punishing the shop for doing the right thing."""
316 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
317 open_receipt(data_dir, lines=[("po-line-1", "10")])
318 object_records.update_collection_record(
319 "receipts", "rec-open", {"status": "cancelled"},
320 base_dir=data_dir, actor="test")
321
322 again = receive(objects_root, order_id="po-1")
323 assert again["ok"] and again["lines"] == 1
324 assert again["receipt_lines"][0]["quantity_received"] == "10"
325
326
327# --- partial receipt is a count, not a flag -------------------------------------
328
329def test_a_short_delivery_records_the_discrepancy_and_leaves_the_po_partial(
330 tmp_path, monkeypatch):
331 """Eight of the ten arrived. The PO is partial, the shortfall is still
332 outstanding, and the note saying why survives on the line."""
333 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
334 created = receive(objects_root, order_id="po-1",
335 supplier_reference="DN-77812",
336 lines=[{"order_line_id": "po-line-1",
337 "quantity_received": "8",
338 "discrepancy_note": "two short, supplier "
339 "back-ordering"}])
340 assert created["still_outstanding"] == "2"
341
342 result = post_receipt(objects_root, created["receipt_id"])
343 assert result["order_status"] == "partial"
344 assert order_status(data_dir) == "partial"
345 assert result["moved"] == 1
346 assert purchases(data_dir)[0]["quantity"] == "8"
347
348 line = receipt_lines(data_dir)[0]
349 assert line["quantity_expected"] == "10"
350 assert line["quantity_received"] == "8"
351 assert "back-ordering" in line["discrepancy_note"]
352 receipt = object_records.get_collection_record(
353 "receipts", created["receipt_id"], base_dir=data_dir)
354 assert receipt["supplier_reference"] == "DN-77812"
355
356
357def test_a_second_receipt_completes_the_purchase_order(tmp_path, monkeypatch):
358 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
359 first = receive(objects_root, order_id="po-1",
360 lines=[{"order_line_id": "po-line-1",
361 "quantity_received": "8"}])
362 result = post_receipt(objects_root, first["receipt_id"])
363 assert result["order_status"] == "partial"
364
365 second = receive(objects_root, order_id="po-1")
366 # The default is everything still outstanding: the remaining two.
367 assert second["receipt_lines"][0]["quantity_received"] == "2"
368 result = post_receipt(objects_root, second["receipt_id"])
369 assert result["order_status"] == "received"
370 assert result["order_status_changed"] is True
371 assert order_status(data_dir) == "received"
372
373 # Derived exactly once each: a second pass over the same facts changes
374 # nothing and says so by NOT reporting a change.
375 again = post_receipt(objects_root, second["receipt_id"])
376 assert again["order_status"] == "received"
377 assert "order_status_changed" not in again
378
379 assert len(purchases(data_dir)) == 2
380 assert sorted(move["quantity"] for move in purchases(data_dir)) == ["2", "8"]
381
382
383def test_a_replayed_received_event_shelves_nothing_twice(tmp_path, monkeypatch):
384 """Events are replayed by design -- the change dispatcher promises
385 at-least-once. The per-line provenance marker is what makes that safe."""
386 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
387 created = receive(objects_root, order_id="po-1")
388 first = post_receipt(objects_root, created["receipt_id"])
389 assert first["moved"] == 1
390
391 again = post_receipt(objects_root, created["receipt_id"])
392 assert again["moved"] == 0
393 assert len(purchases(data_dir)) == 1
394 marker = f"receipts/{created['receipt_id']}:line/"
395 assert marker in purchases(data_dir)[0]["reference"]
396
397
398def test_a_rejected_quantity_is_recorded_and_moves_no_stock(
399 tmp_path, monkeypatch):
400 """Rejected goods arrived and are going back on the van. They never
401 entered stock, so no move is composed -- but the fact is kept, because
402 that is what the argument with the supplier is made of."""
403 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
404 created = receive(objects_root, order_id="po-1",
405 lines=[{"order_line_id": "po-line-1",
406 "quantity_received": "7",
407 "quantity_rejected": "3",
408 "discrepancy_note": "three cartons crushed"}])
409 assert created["rejected"] == "3"
410 post_receipt(objects_root, created["receipt_id"])
411
412 # Seven on the shelf, not ten: the rejection moved nothing.
413 assert len(purchases(data_dir)) == 1
414 assert purchases(data_dir)[0]["quantity"] == "7"
415
416 line = receipt_lines(data_dir)[0]
417 assert line["quantity_rejected"] == "3"
418 assert "crushed" in line["discrepancy_note"]
419 # And the shortfall is still owed: a rejection is not a receipt.
420 assert order_status(data_dir) == "partial"
421
422
423def test_a_wholly_rejected_line_moves_nothing_at_all(tmp_path, monkeypatch):
424 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
425 created = receive(objects_root, order_id="po-1",
426 lines=[{"order_line_id": "po-line-1",
427 "quantity_received": "0",
428 "quantity_rejected": "10",
429 "discrepancy_note": "whole pallet water "
430 "damaged"}])
431 result = post_receipt(objects_root, created["receipt_id"])
432 assert result["moved"] == 0
433 assert purchases(data_dir) == []
434 # Nothing arrived that we kept, so the PO's status is untouched: the
435 # facts say nothing yet, and a machine that knows less than a human
436 # must not drag the row backwards.
437 assert order_status(data_dir) == "confirmed"
438
439
440def test_the_purchase_move_carries_the_price_we_agreed_to_pay(
441 tmp_path, monkeypatch):
442 """unit_cost_cents on the way IN is what FIFO or weighted-average
443 valuation will consume, and it cannot be reconstructed once the
444 supplier's price list moves on (see tests/test_cogs_on_sale.py)."""
445 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
446 created = receive(objects_root, order_id="po-1")
447 post_receipt(objects_root, created["receipt_id"])
448
449 move = purchases(data_dir)[0]
450 assert move["unit_cost_cents"] == "450" # order_line.unit_price_cents
451 assert move["from_location_id"] == "loc-supplier"
452 assert move["to_location_id"] == "loc-shelf"
453 assert "PO-0001" in move["reference"]
454
455
456def test_a_missing_stock_location_still_lets_the_receipt_stand(
457 tmp_path, monkeypatch):
458 """A missing location must not cost somebody the record that goods
459 arrived: the gap is reported, the receipt and the derived status hold."""
460 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, settings=[])
461 created = receive(objects_root, order_id="po-1")
462 result = post_receipt(objects_root, created["receipt_id"])
463
464 assert result["moved"] == 0
465 assert "stock_location" in result["warning"]
466 assert result["order_status"] == "received"
467 assert len(receipts(data_dir)) == 1
468
469
470@pytest.mark.parametrize("unreadable", ["stock_moves", "receipt_lines", "order_lines"])
471def test_an_unreadable_ledger_lands_nothing_and_says_so(tmp_path, monkeypatch, unreadable):
472 """An installed stock_moves that could not be read was taken for "stock
473 not installed; nothing to move", unreadable receipt lines for a receipt
474 with no lines, and unreadable PO lines put the goods on the shelf with
475 no cost (no price to stamp) -- each with nothing saying so. Now nothing
476 lands, the receipt stands, the result says the stock did not move, and
477 the next event for the receipt lands it once, costed."""
478 from test_findings_money_gates import failing_reads
479
480 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
481 created = receive(objects_root, order_id="po-1")
482 for move in purchases(data_dir): # start from an unposted receipt
483 object_records.delete_collection_record("stock_moves", move["id"],
484 base_dir=data_dir)
485 with failing_reads(unreadable, "receipt_posting.py") as fired:
486 result = post_receipt(objects_root, created["receipt_id"])
487 assert fired, "the simulated failure never reached the handler"
488 assert result["moved"] == 0 and purchases(data_dir) == []
489 assert unreadable in result["stock_unreadable"]
490 assert "did not move" in result["warning"]
491 assert len(receipts(data_dir)) == 1
492
493 again = post_receipt(objects_root, created["receipt_id"])
494 assert again["moved"] == 1 and "stock_unreadable" not in again
495 assert purchases(data_dir)[0]["unit_cost_cents"] == "450"
496 assert post_receipt(objects_root, created["receipt_id"])["moved"] == 0
497
498
499def test_the_stock_location_falls_back_to_the_shops_own_setting(
500 tmp_path, monkeypatch):
501 """A one-warehouse shop has already told app-shop where its shelf is and
502 should not have to say it twice."""
503 data_dir, objects_root = stocked_shop(
504 tmp_path, monkeypatch,
505 settings=[("shop.stock_location", "loc-shelf")])
506 created = receive(objects_root, order_id="po-1")
507 result = post_receipt(objects_root, created["receipt_id"])
508
509 assert result["moved"] == 1
510 assert purchases(data_dir)[0]["to_location_id"] == "loc-shelf"
511
512
513def test_a_cancelled_purchase_order_is_never_touched_by_posting(
514 tmp_path, monkeypatch):
515 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
516 created = receive(objects_root, order_id="po-1")
517 object_records.update_collection_record(
518 "orders", "po-1", {"status": "cancelled"},
519 base_dir=data_dir, actor="test")
520
521 result = post_receipt(objects_root, created["receipt_id"])
522 assert result["skipped"] == "order is cancelled"
523 assert purchases(data_dir) == []
524 assert order_status(data_dir) == "cancelled"
525
526
527# --- creating the receipt --------------------------------------------------------
528
529def test_receiving_against_a_sales_order_is_refused_in_words(
530 tmp_path, monkeypatch):
531 """Goods leave on a shipment and arrive on a receipt. Somebody who got
532 here with an SO has a model of the system worth correcting on the
533 spot."""
534 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch,
535 doc_type="sale")
536 refused = receive(objects_root, order_id="po-1")
537 assert refused["status"] == 409
538 assert "sales order" in refused["error"]
539 assert "shipment" in refused["error"]
540 assert receipts(data_dir) == []
541
542
543def test_a_draft_purchase_order_cannot_be_received_against(tmp_path, monkeypatch):
544 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch, status="draft")
545 refused = receive(objects_root, order_id="po-1")
546 assert refused["status"] == 409
547 assert "Commit before you receive" in refused["error"]
548
549
550def test_an_unknown_order_is_a_404(tmp_path, monkeypatch):
551 _, objects_root = stocked_shop(tmp_path, monkeypatch)
552 assert receive(objects_root, order_id="nope")["status"] == 404
553 assert receive(objects_root)["status"] == 400
554
555
556def test_every_blocker_is_reported_at_once(tmp_path, monkeypatch):
557 """Checkout-style: the person doing this is standing up, in the cold,
558 with a driver waiting."""
559 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
560 refused = receive(
561 objects_root, order_id="po-1",
562 lines=[{"order_line_id": "po-line-1", "quantity_received": "99"},
563 {"order_line_id": "no-such-line", "quantity_received": "1"},
564 {"order_line_id": "po-line-1", "quantity_received": "0"},
565 {"order_line_id": "po-line-1", "quantity_received": "-2"}])
566 assert refused["status"] == 409
567 assert refused["over_receive"] and refused["unknown_lines"] == ["no-such-line"]
568 reasons = " ".join(entry["reason"] for entry in refused["bad_quantities"])
569 assert "must say why" in reasons and "negative" in reasons
570 assert receipts(data_dir) == []
571
572
573def test_the_default_receipt_is_everything_still_outstanding(
574 tmp_path, monkeypatch):
575 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
576 order_line(data_dir, "po-line-2", product_id="p1", description="Bowl",
577 quantity="4")
578
579 created = receive(objects_root, order_id="po-1")
580 assert created["lines"] == 2
581 assert {line["quantity_received"] for line in created["receipt_lines"]} == {
582 "10", "4"}
583 assert created["status_of_receipt"] == "received"
584 assert "orders/po-1" in receipts(data_dir)[0]["notes"]
585
586
587def test_a_fully_received_po_answers_ok_with_a_note_not_an_error(
588 tmp_path, monkeypatch):
589 """A double click must not 500, and must not raise an empty receipt."""
590 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
591 first = receive(objects_root, order_id="po-1")
592 post_receipt(objects_root, first["receipt_id"])
593
594 again = receive(objects_root, order_id="po-1")
595 assert again["ok"] is True
596 assert again["receipt_id"] == ""
597 assert "nothing outstanding" in again["note"]
598 assert len(receipts(data_dir)) == 1
599
600
601# --- the paperwork ---------------------------------------------------------------
602
603def sheet(objects_root, order_id="po-1", user_id="shop"):
604 payload = {"order_id": order_id}
605 if user_id:
606 payload["_identity"] = {"user_id": user_id}
607 return run(objects_root, "site_receiving_sheet", "GET", payload)
608
609
610def test_the_receiving_sheet_shows_expected_quantities_and_prior_receipts(
611 tmp_path, monkeypatch):
612 """The dock is where the paperwork actually happens, and a second
613 delivery against a partly-received PO is exactly when a receiver needs
614 to see what already arrived."""
615 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch)
616 body = sheet(objects_root)["body"]
617 assert "Enamel Mug" in body
618 assert "PO-0001" in body
619 assert "Kiln & Clay Ltd" in body
620 assert ">10<" in body # ordered, and expected today
621 assert "No deliveries have been booked in" in body
622 assert "@media print" in body
623
624 created = receive(objects_root, order_id="po-1",
625 supplier_reference="DN-77812", received_on="2026-07-20",
626 lines=[{"order_line_id": "po-line-1",
627 "quantity_received": "8",
628 "quantity_rejected": "1",
629 "discrepancy_note": "one carton crushed"}])
630 post_receipt(objects_root, created["receipt_id"])
631
632 body = sheet(objects_root)["body"]
633 assert "Already received" in body
634 assert "DN-77812" in body and "2026-07-20" in body
635 assert ">2<" in body # still expected today
636 assert ">1<" in body # the rejected column
637
638
639def test_the_receiving_sheet_asks_a_stranger_to_sign_in(tmp_path, monkeypatch):
640 _, objects_root = stocked_shop(tmp_path, monkeypatch)
641 body = sheet(objects_root, user_id="")["body"]
642 assert "Sign in" in body
643 assert "Enamel Mug" not in body
644
645
646def test_the_receiving_sheet_refuses_a_sales_order_and_an_unknown_one(
647 tmp_path, monkeypatch):
648 data_dir, objects_root = stocked_shop(tmp_path, monkeypatch,
649 doc_type="sale")
650 result = sheet(objects_root)
651 assert result["status"] == 404
652 assert "sales order" in result["body"]
653 assert "Traceback" not in result["body"]
654
655 missing = sheet(objects_root, order_id="no-such-order")
656 assert missing["status"] == 404
657 assert "Traceback" not in missing["body"]