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