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_dropship.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, 18 minutes ago History
test_dropship.py · 28.9 KB · 650 lines
1"""Drop-shipping: the composition test the whole fulfillment build was
2measured against.
3
4plan/fulfillment-logistics-spec.md set it in as many words -- "a sale
5order flagged `fulfillment: dropship` produces a linked PURCHASE order to
6the vendor carrying the customer's ship-to; receiving is skipped (goods
7never touch our shelf); margin is already a read because both orders
8carry money. If the shipment model can't express this cleanly, the model
9is wrong."
10
11The model expresses it, and it does so with no new collection anywhere,
12because the decision made in orders v1 -- sale and purchase orders share
13one schema -- turns out to have already modelled a drop-ship as two rows
14pointing at each other. That is what the first half of this file asserts:
15one PO, confirmed, carrying the customer's ship-to onto the vendor's
16document, linked both ways, refusing a second PO and refusing an order
17whose goods have already come off our shelf.
18
19**The stock rule is the test that matters**, and it has two halves that
20this file deliberately reports differently, because they are in different
21states and pretending otherwise would be the dishonest kind of green.
22
23The half that is done: the drop-ship flow itself moves no stock. No
24handler fires, no move is composed, and the shelf is provably unchanged
25from end to end.
26
27The half that is NOT: app-shipping's system_order_fulfillment composes a
28`sale` move for every shipment line the moment a shipment reaches
29`shipped`, and it does not look at fulfillment_source -- so the vendor's
30dispatch, recorded as a shipment against the sale order the way the spec
31describes, would decrement a shelf that never held the goods. The order
32carries the fact the handler needs; the handler does not read it. That is
33one condition in a package the disputes/drop-ship slice does not own, so
34it is a STRICT XFAIL here rather than a hack in a package that is not
35ours -- the same posture tests/test_cogs_on_sale.py takes toward the
36missing COGS journal. The day somebody adds the condition, the acceptance
37test is already written and this file goes red if the fix does not match
38what was specified.
39"""
40
41import pathlib
42import shutil
43
44import pytest
45from conftest import stage_collection
46
47import object_execution
48import object_ids
49import object_records
50import object_stock
51import python_object_runtime
52
53REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
54PACKAGES = REPO_ROOT / "packages"
55ORDERS_OBJECTS = PACKAGES / "app-orders" / "objects"
56SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
57RECEIVING_OBJECTS = PACKAGES / "app-receiving" / "objects"
58RUNTIME = python_object_runtime.PythonObjectRuntime()
59
60
61def setup_env(tmp_path, monkeypatch, *, settings=()):
62 """A data dir with every collection this slice touches, and ONE object
63 root holding app-orders' objects beside app-shipping's and
64 app-receiving's.
65
66 The merged root is what an installed server actually looks like, and
67 it is the only way the two gap tests at the bottom can fire the REAL
68 handlers rather than a description of them.
69 """
70 data_dir = tmp_path / "data"
71 for pkg, name in (("app-orders", "orders"), ("app-orders", "order_lines"),
72 ("app-catalog", "products"), ("app-catalog", "locations"),
73 ("app-catalog", "stock_moves"),
74 ("app-contacts", "contacts"),
75 ("app-shipping", "shipments"),
76 ("app-shipping", "shipment_lines"),
77 ("app-receiving", "receipts"),
78 ("app-receiving", "receipt_lines")):
79 stage_collection(data_dir, pkg, name)
80 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
81 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
82
83 objects_root = tmp_path / "objects"
84 for source in (ORDERS_OBJECTS, SHIPPING_OBJECTS, RECEIVING_OBJECTS):
85 shutil.copytree(source, objects_root, dirs_exist_ok=True)
86
87 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
88 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
89 return data_dir, objects_root
90
91
92def run(objects_root, object_id, method, payload):
93 return object_execution.execute_object(
94 RUNTIME,
95 object_execution.ObjectExecutionRequest(
96 object_id, method=method, payload=payload),
97 roots=[objects_root]).result
98
99
100# --- fixtures shaped like a real shop -----------------------------------------
101
102def product(data_dir, product_id="p1", name="Enamel Mug", cents=1200,
103 cost_cents=None):
104 record = {"id": product_id, "name": name, "sku": product_id.upper(),
105 "product_type": "physical", "price_cents": str(cents),
106 "currency": "USD", "is_active": "true", "owner_id": "shop"}
107 if cost_cents is not None:
108 record["cost_cents"] = str(cost_cents)
109 return object_records.create_collection_record("products", record,
110 base_dir=data_dir)
111
112
113def location(data_dir, location_id, name, kind="warehouse"):
114 return object_records.create_collection_record(
115 "locations",
116 {"id": location_id, "name": name, "location_type": kind,
117 "owner_id": "shop"},
118 base_dir=data_dir)
119
120
121def vendor(data_dir, vendor_id="ven-1"):
122 """A supplier filed as a contact. full_name is COMPUTED on contacts,
123 so it is not written here -- the name the purchase order carries is
124 whatever app-contacts derives, which is the point of asking the
125 collection rather than stamping a string."""
126 return object_records.create_collection_record(
127 "contacts",
128 {"id": vendor_id, "first_name": "Kiln & Clay", "last_name": "Ltd",
129 "email": "sales@kiln.test", "owner_id": "shop"},
130 base_dir=data_dir)
131
132
133def order(data_dir, order_id="ord-1", *, status="confirmed", number="SO-0001",
134 owner="shop", **fields):
135 record = {"id": order_id, "doc_type": "sale", "number": number,
136 "customer_name": "Ada Lovelace",
137 "customer_email": "ada@example.test", "currency": "USD",
138 "status": "draft", "order_date": "2026-07-01", "owner_id": owner}
139 record.update({k: str(v) for k, v in fields.items()})
140 object_records.create_collection_record("orders", record,
141 base_dir=data_dir)
142 # Through the ladder, the way a human would: draft is where every order
143 # starts.
144 for step in ("confirmed", status):
145 current = object_records.get_collection_record(
146 "orders", order_id, base_dir=data_dir)["status"]
147 if step not in ("draft", current):
148 object_records.update_collection_record(
149 "orders", order_id, {"status": step},
150 base_dir=data_dir, actor="test")
151 return object_records.get_collection_record("orders", order_id,
152 base_dir=data_dir)
153
154
155def order_line(data_dir, line_id, order_id="ord-1", *, product_id="p1",
156 description="Enamel Mug", quantity="3", cents=1200):
157 total = int(float(quantity) * cents)
158 return object_records.create_collection_record(
159 "order_lines",
160 {"id": line_id, "order_id": order_id, "product_id": product_id,
161 "description": description, "quantity": str(quantity),
162 "unit_price_cents": str(cents), "line_total_cents": str(total),
163 "tax_rate_bps": "0", "line_tax_cents": "0", "owner_id": "shop"},
164 base_dir=data_dir)
165
166
167def stock_in(data_dir, product_id="p1", quantity=20, *, to="loc-shelf"):
168 return object_records.create_collection_record(
169 "stock_moves",
170 {"id": object_ids.new_uuid4(), "product_id": product_id,
171 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
172 "occurred_at": "2026-06-01", "owner_id": "shop"},
173 base_dir=data_dir)
174
175
176def moves(data_dir, reason=None):
177 rows = object_records.read_collection_records("stock_moves",
178 base_dir=data_dir)
179 if reason is None:
180 return rows
181 return [row for row in rows if row["reason"] == reason]
182
183
184def on_shelf(data_dir, product_id="p1", location_id="loc-shelf"):
185 return object_stock.quantity_at_location(product_id, location_id,
186 base_dir=data_dir)
187
188
189def orders_of(data_dir, doc_type=None):
190 rows = object_records.read_collection_records("orders", base_dir=data_dir)
191 if doc_type is None:
192 return rows
193 return [row for row in rows if row["doc_type"] == doc_type]
194
195
196def lines_of(data_dir, order_id):
197 return [row for row in object_records.read_collection_records(
198 "order_lines", base_dir=data_dir) if row["order_id"] == order_id]
199
200
201def dropship(objects_root, **payload):
202 # As the shop that owns the order: the action refuses anybody the
203 # permission engine would not let update it.
204 request = {"order_id": "ord-1", "vendor_id": "ven-1",
205 "_identity": {"user_id": "shop"}}
206 request.update(payload)
207 return run(objects_root, "action_dropship_order", "POST", request)
208
209
210def margin(objects_root, order_id="ord-1", user_id="shop"):
211 return run(objects_root, "site_dropship_margin", "GET",
212 {"order_id": order_id, "_identity": {"user_id": user_id}})
213
214
215def shop_that_can_dropship(tmp_path, monkeypatch, *, cost_cents=None,
216 address="12 Analytical Way\nLondon"):
217 """A shop with stock on the shelf and one confirmed sale order for
218 three mugs, with somewhere for a parcel to go."""
219 data_dir, objects_root = setup_env(
220 tmp_path, monkeypatch,
221 settings=[("shop.stock_location", "loc-shelf"),
222 ("shop.customer_location", "loc-customer")])
223 location(data_dir, "loc-shelf", "Shelf")
224 location(data_dir, "loc-customer", "Customers", kind="customer")
225 product(data_dir, cost_cents=cost_cents)
226 stock_in(data_dir)
227 vendor(data_dir)
228 order(data_dir, ship_to_address=address)
229 order_line(data_dir, "line-1")
230 return data_dir, objects_root
231
232
233# --- one sale order spawns exactly one purchase order --------------------------
234
235def test_a_dropship_order_spawns_one_po_carrying_the_customers_address(
236 tmp_path, monkeypatch):
237 """The whole shape in one assertion block: the vendor is the
238 counterparty, the customer is the destination, and this is the only
239 place in the repo where those are different people."""
240 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
241 result = dropship(objects_root, vendor_price_cents="700",
242 today="2026-07-20")
243 assert result["ok"] is True
244 assert result["lines"] == 1
245
246 purchases = orders_of(data_dir, "purchase")
247 assert len(purchases) == 1
248 po = purchases[0]
249 assert po["id"] == result["purchase_order_id"]
250 assert po["number"] == "PO-SO-0001"
251 # Confirmed, not draft: the operator choosing a vendor IS the
252 # commitment to buy, and a drop-ship PO in draft is a customer waiting
253 # on a parcel nobody ordered.
254 assert po["status"] == "confirmed"
255 assert po["fulfillment_source"] == "dropship"
256 assert po["vendor_id"] == "ven-1"
257 # The counterparty is the vendor, named the way every other PO in this
258 # repo names its supplier.
259 assert po["customer_name"] == "Kiln & Clay Ltd"
260 # ...and the goods go somewhere else entirely.
261 assert po["ship_to_name"] == "Ada Lovelace"
262 assert po["ship_to_address"] == "12 Analytical Way\nLondon"
263 assert "orders/ord-1" in po["notes"]
264
265 po_lines = lines_of(data_dir, po["id"])
266 assert len(po_lines) == 1
267 assert po_lines[0]["description"] == "Enamel Mug"
268 assert po_lines[0]["quantity"] == "3"
269 assert po_lines[0]["unit_price_cents"] == "700"
270 assert po_lines[0]["line_total_cents"] == "2100"
271
272 # Linked both ways, so either end answers on its own and no handler
273 # ever has to join to find out what it is looking at.
274 sale = object_records.get_collection_record("orders", "ord-1",
275 base_dir=data_dir)
276 assert sale["fulfillment_source"] == "dropship"
277 assert sale["linked_order_id"] == po["id"]
278 assert sale["vendor_id"] == "ven-1"
279 assert po["linked_order_id"] == "ord-1"
280
281
282def test_drop_shipping_the_same_order_twice_is_refused_with_the_po_that_exists(
283 tmp_path, monkeypatch):
284 """A duplicate PO is a duplicate commitment to buy, with a supplier on
285 the other end who will happily send the goods twice."""
286 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
287 first = dropship(objects_root, vendor_price_cents="700")
288 assert first["ok"]
289
290 refused = dropship(objects_root, vendor_price_cents="700")
291 assert refused["status"] == 409
292 assert "already drop-shipped" in refused["already_linked"]
293 assert "PO-SO-0001" in refused["already_linked"]
294 assert len(orders_of(data_dir, "purchase")) == 1
295
296
297def test_a_purchase_order_cannot_itself_be_drop_shipped(tmp_path, monkeypatch):
298 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
299 order(data_dir, "po-9", doc_type="purchase", number="PO-9",
300 customer_name="Kiln & Clay Ltd")
301 order_line(data_dir, "po-9-line", order_id="po-9")
302
303 refused = dropship(objects_root, order_id="po-9")
304 assert refused["status"] == 409
305 assert "That is a purchase order" in refused["wrong_document"]
306
307
308def test_every_blocker_is_reported_at_once(tmp_path, monkeypatch):
309 """Whoever is doing this is usually choosing between two vendors with
310 a customer waiting; revealing one problem at a time is how a screen
311 gets abandoned."""
312 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
313 object_records.update_collection_record(
314 "orders", "ord-1", {"status": "cancelled"},
315 base_dir=data_dir, actor="test")
316
317 refused = dropship(objects_root, order_id="ord-1", vendor_id="")
318 assert refused["status"] == 409
319 assert "cancelled" in refused["order_status"]
320 assert "has to name who is shipping it" in refused["missing_vendor"]
321 assert orders_of(data_dir, "purchase") == []
322
323
324# --- you cannot drop-ship what you already picked ------------------------------
325
326def picked_from_stock(data_dir, order_id="ord-1", shipment_id="ship-1"):
327 """A parcel packed and sent from our own shelf, with the `sale` move
328 system_order_fulfillment composes for it. Written directly, the way a
329 trusted server-side write is: this file is about what happens NEXT."""
330 object_records.create_collection_record(
331 "shipments",
332 {"id": shipment_id, "order_id": order_id, "direction": "outbound",
333 "status": "open", "service": "ground", "ship_to_name": "Ada Lovelace",
334 "shipped_on": "2026-07-05", "owner_id": "shop"},
335 base_dir=data_dir)
336 object_records.create_collection_record(
337 "shipment_lines",
338 {"id": f"{shipment_id}-line-0", "shipment_id": shipment_id,
339 "order_line_id": "line-1", "product_id": "p1",
340 "description": "Enamel Mug", "quantity": "3", "owner_id": "shop"},
341 base_dir=data_dir)
342 object_records.create_collection_record(
343 "stock_moves",
344 {"id": object_ids.new_uuid4(), "product_id": "p1",
345 "from_location_id": "loc-shelf", "to_location_id": "loc-customer",
346 "quantity": "3", "reason": "sale",
347 "reference": f"shipments/{shipment_id}:line/{shipment_id}-line-0 SO-0001",
348 "occurred_at": "2026-07-05", "owner_id": "shop"},
349 base_dir=data_dir)
350
351
352def test_drop_shipping_an_order_with_stock_movement_is_refused(
353 tmp_path, monkeypatch):
354 """The goods left our shelf, so the sale is ours to fulfill. Raising a
355 PO now would buy a second set of the same units, and the refusal names
356 the moves so somebody can see whether they picked the wrong order or
357 the wrong day."""
358 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
359 picked_from_stock(data_dir)
360
361 refused = dropship(objects_root, vendor_price_cents="700")
362 assert refused["status"] == 409
363 assert len(refused["stock_moved"]) == 1
364 moved = refused["stock_moved"][0]
365 assert moved["product_id"] == "p1"
366 assert moved["quantity"] == "3"
367 assert moved["reason"] == "sale"
368 assert "shipments/ship-1:" in moved["reference"]
369 assert refused["shipments"] == ["ship-1"]
370
371 # Nothing half-written, and the sale order still says what it is.
372 assert orders_of(data_dir, "purchase") == []
373 assert object_records.get_collection_record(
374 "orders", "ord-1", base_dir=data_dir)["fulfillment_source"] == "stock"
375
376
377@pytest.mark.parametrize("unreadable", ["shipments", "stock_moves", "order_lines"])
378def test_drop_shipping_refuses_when_the_history_it_decides_from_cannot_be_read(
379 tmp_path, monkeypatch, unreadable):
380 """An unreadable shipments or stock ledger read as "nothing moved", so
381 an order whose goods had already left our shelf was drop-shipped and
382 the same units were bought a second time. A history that cannot be
383 read is an unknown: 503, nothing written, and the claim released so
384 the next try can go ahead. (Unreadable order lines used to be the 409
385 "this order has no lines", which sent somebody looking at the order.)"""
386 from test_findings_money_gates import failing_reads
387
388 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
389 picked_from_stock(data_dir)
390
391 with failing_reads(unreadable, "dropship_order.py") as fired:
392 refused = dropship(objects_root, vendor_price_cents="700")
393 assert fired, "the simulated failure never reached the action"
394 assert refused.get("status") == 503, refused
395 assert unreadable in refused["error"]
396 assert orders_of(data_dir, "purchase") == []
397 sale = object_records.get_collection_record("orders", "ord-1", base_dir=data_dir)
398 assert sale["fulfillment_source"] == "stock"
399 assert sale["action_claim"] == ""
400
401 # Readable again, the same request sees the moves and refuses for them.
402 again = dropship(objects_root, vendor_price_cents="700")
403 assert again["status"] == 409 and len(again["stock_moved"]) == 1
404
405
406def test_an_order_with_no_shipments_collection_installed_has_moved_nothing(
407 tmp_path, monkeypatch):
408 """Not installed is a fact, not an unknown: no shipment exists, so
409 nothing has left the shelf for one."""
410 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
411 shutil.rmtree(data_dir / "collections" / "shipments")
412 shutil.rmtree(data_dir / "collections" / "shipment_lines")
413 for name in ("shipments", "shipment_lines"):
414 (data_dir / "schemas" / f"{name}.json").unlink()
415
416 result = dropship(objects_root, vendor_price_cents="700")
417 assert result.get("ok") is True, result
418
419
420# --- THE composition test: a drop-ship order moves no stock --------------------
421
422def test_a_dropship_order_moves_no_stock_end_to_end(tmp_path, monkeypatch):
423 """The property the whole slice is judged on, asserted over the shelf
424 itself rather than over a handler's return value.
425
426 Twenty mugs on the shelf before, twenty after: not one move composed
427 anywhere, no receipt raised, and the purchase order still sitting at
428 confirmed because nothing on this server creates a receipt on its own.
429 That last clause is why receiving is skipped BY CONSTRUCTION rather
430 than by a gate -- system_receipt_posting only ever reacts to a
431 `receipts` row a human raised.
432 """
433 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
434 before = on_shelf(data_dir)
435 assert before == 20
436 moves_before = len(moves(data_dir))
437
438 result = dropship(objects_root, vendor_price_cents="700")
439 assert result["ok"] is True
440 assert "never touch our shelf" in result["note"]
441
442 assert on_shelf(data_dir) == before
443 assert len(moves(data_dir)) == moves_before
444 assert moves(data_dir, "sale") == []
445 # The one purchase move is the shelf being stocked in the fixture; the
446 # drop-ship added none of its own.
447 assert len(moves(data_dir, "purchase")) == 1
448
449 # No receipt exists, so system_receipt_posting has nothing to react to
450 # and the PO stays where the action put it.
451 assert object_records.read_collection_records(
452 "receipts", base_dir=data_dir) == []
453 po = orders_of(data_dir, "purchase")[0]
454 assert po["status"] == "confirmed"
455
456 # And firing the receiving handler anyway -- the replay case -- finds
457 # no receipt and moves nothing.
458 replayed = run(objects_root, "system_receipt_posting", "EVENT",
459 {"event": "receipts.record.updated",
460 "collection": "receipts", "record_id": "no-such-receipt",
461 "action": "update"})
462 assert replayed["ok"] is True
463 assert on_shelf(data_dir) == before
464
465
466# --- margin is a read over the two orders --------------------------------------
467
468def test_margin_reads_from_the_two_linked_orders(tmp_path, monkeypatch):
469 """The spec's claim was that margin needs no stored field because both
470 orders carry money. This is that claim, checked: revenue off the sale
471 order, cost off the purchase order, and object_billing.margin doing
472 the arithmetic rather than a second implementation of it."""
473 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
474 dropship(objects_root, vendor_price_cents="700")
475
476 read = margin(objects_root)
477 assert read["margin"] == {"revenue_minor": 3600, "cost_minor": 2100,
478 "gross_minor": 1500, "gross_pct": 41.67}
479 assert read["currency"] == "USD"
480 # Folded from the lines, because system_order_totals is a post-commit
481 # reaction that has not run in this test -- and a margin quoted off a
482 # total that simply has not landed yet would be a confident wrong
483 # answer at exactly the wrong moment.
484 assert read["revenue_source"] == "folded"
485 assert read["cost_source"] == "folded"
486 assert "36.00 USD" in read["body"]
487 assert "21.00 USD" in read["body"]
488 assert "15.00 USD" in read["body"]
489
490
491def test_margin_opens_from_either_end_of_the_pair(tmp_path, monkeypatch):
492 """A link written both ways is a link you never have to search for."""
493 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
494 created = dropship(objects_root, vendor_price_cents="700")
495
496 from_sale = margin(objects_root, "ord-1")
497 from_po = margin(objects_root, created["purchase_order_id"])
498 assert from_sale["margin"] == from_po["margin"]
499 assert from_po["sale_order_id"] == "ord-1"
500
501
502def test_margin_prefers_the_stamped_total_when_the_handler_has_run(
503 tmp_path, monkeypatch):
504 """The document's own number wins when it exists: that is what a human
505 sees on the order itself, and a page that quietly disagreed with the
506 order it is about would be worse than no page."""
507 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
508 created = dropship(objects_root, vendor_price_cents="700")
509 for order_id, total in (("ord-1", "4000"),
510 (created["purchase_order_id"], "2500")):
511 object_records.update_collection_record(
512 "orders", order_id,
513 {"subtotal_cents": total, "total_cents": total},
514 base_dir=data_dir, actor="test")
515
516 read = margin(objects_root)
517 assert read["revenue_source"] == "stamped"
518 assert read["margin"]["revenue_minor"] == 4000
519 assert read["margin"]["cost_minor"] == 2500
520 assert read["margin"]["gross_minor"] == 1500
521
522
523def test_a_missing_vendor_price_is_warned_about_rather_than_smoothed_over(
524 tmp_path, monkeypatch):
525 """A cost of zero reads as 100% margin and a cost copied from the sale
526 price reads as none. Both are lies; saying the number is missing is
527 not."""
528 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
529 result = dropship(objects_root)
530 assert result["ok"] is True
531 assert result["unpriced_lines"] == ["line-1"]
532 assert "no vendor price" in result["warning"]
533
534 read = margin(objects_root)
535 assert read["margin"]["cost_minor"] == 0
536 assert read["margin"]["gross_pct"] == 100.0
537 assert "reads as pure profit and is not" in read["body"]
538
539
540def test_the_products_recorded_cost_is_used_before_giving_up(tmp_path,
541 monkeypatch):
542 """A price we already wrote down is a fact; zero is not."""
543 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch,
544 cost_cents=650)
545 result = dropship(objects_root)
546 assert result["ok"] is True
547 assert "warning" not in result
548 po_lines = lines_of(data_dir, result["purchase_order_id"])
549 assert po_lines[0]["unit_price_cents"] == "650"
550
551
552def test_margin_on_an_ordinary_order_says_what_is_missing_instead_of_zero(
553 tmp_path, monkeypatch):
554 """An order fulfilled from our own shelf has no vendor cost to set
555 against it -- that needs inventory valuation, which this server does
556 not do yet. Saying so beats printing a margin of 100%."""
557 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
558 read = margin(objects_root)
559 assert read["status"] == 409
560 assert "not part of a drop-ship pair" in read["body"]
561
562
563def test_margin_is_not_a_number_for_visitors(tmp_path, monkeypatch):
564 """The page is addressed by an internal order id; public execute would
565 make it an enumeration oracle for the whole margin book."""
566 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
567 dropship(objects_root, vendor_price_cents="700")
568 body = margin(objects_root, user_id="")["body"]
569 assert "Please sign in" in body
570 assert "36.00" not in body
571
572
573# --- the halves that are NOT done, held as specifications ----------------------
574#
575# Both were written first as strict xfails, because each needed one
576# condition in a package the drop-ship slice did not own, and hacking
577# around a sibling package's handler would have been exactly the kind of
578# "make it work by the data" a stock rule cannot afford. Writing the
579# acceptance test first and leaving it red is the honest move: a green
580# test over a shelf that silently decrements is worse than a red one.
581#
582# Both conditions have since been added -- app-shipping's fulfilment
583# handler and app-receiving's check-in action each now read the order's
584# fulfillment_source -- so these are ordinary passing tests. The history
585# is left here because it is the argument for why they exist at all.
586
587def shipped_by_the_vendor(data_dir, shipment_id="ship-ds"):
588 """The vendor's dispatch, recorded the way plan/fulfillment-logistics-
589 spec.md describes it: a shipment against the sale order.
590
591 NOTE: the spec asks for `source: vendor` on that shipment, and
592 app-shipping's shipments schema has no `source` field -- a second,
593 smaller follow-up in the same package, named here so it is not
594 rediscovered.
595 """
596 object_records.create_collection_record(
597 "shipments",
598 {"id": shipment_id, "order_id": "ord-1", "direction": "outbound",
599 "status": "open", "service": "ground", "carrier": "Vendor",
600 "ship_to_name": "Ada Lovelace", "owner_id": "shop"},
601 base_dir=data_dir)
602 object_records.create_collection_record(
603 "shipment_lines",
604 {"id": f"{shipment_id}-line-0", "shipment_id": shipment_id,
605 "order_line_id": "line-1", "product_id": "p1",
606 "description": "Enamel Mug", "quantity": "3", "owner_id": "shop"},
607 base_dir=data_dir)
608 for step in ("packed", "shipped"):
609 object_records.update_collection_record(
610 "shipments", shipment_id, {"status": step},
611 base_dir=data_dir, actor="test")
612 return shipment_id
613
614
615def test_the_vendors_dispatch_must_not_move_our_stock(tmp_path, monkeypatch):
616 """The specification for the missing condition, written as the
617 acceptance test whoever adds it already has."""
618 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
619 dropship(objects_root, vendor_price_cents="700")
620 before = on_shelf(data_dir)
621
622 shipment_id = shipped_by_the_vendor(data_dir)
623 result = run(objects_root, "system_order_fulfillment", "EVENT",
624 {"event": "shipments.record.updated",
625 "collection": "shipments", "record_id": shipment_id,
626 "action": "update"})
627
628 assert result["moved"] == 0
629 assert moves(data_dir, "sale") == []
630 assert on_shelf(data_dir) == before
631
632
633def test_receiving_against_a_dropship_po_is_refused(tmp_path, monkeypatch):
634 """The second specification. Weaker than the first -- it takes a
635 deliberate human mistake to trigger, where the shipping gap fires on
636 its own -- but the same one-line fix in the same shape."""
637 data_dir, objects_root = shop_that_can_dropship(tmp_path, monkeypatch)
638 created = dropship(objects_root, vendor_price_cents="700")
639 po_line = lines_of(data_dir, created["purchase_order_id"])[0]
640 before = on_shelf(data_dir)
641
642 result = run(objects_root, "action_receive_goods", "POST",
643 {"order_id": created["purchase_order_id"],
644 "_identity": {"user_id": "shop"}, # the PO's owner
645 "lines": [{"order_line_id": po_line["id"],
646 "quantity_received": "3"}]})
647
648 assert result.get("status") == 409
649 assert "drop-ship" in result.get("error", "")
650 assert on_shelf(data_dir) == before