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_returns.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_returns.py · 45.8 KB · 1026 lines
1"""Returns: the document that says goods may come back, and what happened
2when they did.
3
4The properties worth holding here are the ones a shop discovers the
5expensive way. You cannot return what never left, and you cannot return
6more than was shipped -- being told so is only useful if the refusal
7carries the numbers, exactly as the over-ship gate does. Goods arriving
8and goods being JUDGED are two different events: the parcel landing moves
9no stock and no money, because a box on the dock could hold a mug in its
10wrapping or the same mug in three pieces, and a human decides which.
11
12Then the three that cost real money if they are wrong. Disposal composes
13a stock move like restock does -- a different reason and no destination,
14but a MOVE -- because goods leaving inventory with no trace is how
15shrinkage hides. A refund is capped by app-payments' existing gate rather
16than by a second opinion grown here, and the refusal that comes back is
17the gate's own words. And a dispositioned return that is dispositioned
18again moves nothing and refunds nothing: retries, double clicks and
19replayed queue entries are ordinary, and a customer's money going back
20twice is not.
21
22EXPIRY IS DATA IN THIS SLICE, deliberately. expires_on is stamped when the
23return is authorized and system_return_posting says `past_expiry` when the
24goods land after it, so the person choosing restock-or-refund knows they
25are outside the promise before they choose -- but nothing refuses a late
26parcel and no pass sweeps stale RMAs to `expired`. Time-driven work
27belongs with the tracking poll (plan/fulfillment-logistics-spec.md item
284). The tests below assert the stamp and the flag, and nothing more,
29because there is deliberately nothing more.
30"""
31
32import pathlib
33import shutil
34
35from conftest import stage_collection
36
37import object_execution
38import object_ids
39import object_records
40import object_stock
41import python_object_runtime
42
43REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
44PACKAGES = REPO_ROOT / "packages"
45RETURNS_OBJECTS = PACKAGES / "app-returns" / "objects"
46SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects"
47PAYMENTS_OBJECTS = PACKAGES / "app-payments" / "objects"
48RUNTIME = python_object_runtime.PythonObjectRuntime()
49
50
51def setup_env(tmp_path, monkeypatch, *, settings=()):
52 """A data dir with every collection this slice touches, and ONE object
53 root holding all three packages' objects.
54
55 The merged root is not a convenience: it is what an installed server
56 actually looks like, and it is the only way the objects that call a
57 sibling by id resolve the way they will in production --
58 action_disposition_return asks app-payments' hook_refunds what a
59 payment can give back rather than deciding for itself, and
60 site_return_form hands everything to action_authorize_return.
61 """
62 data_dir = tmp_path / "data"
63 for pkg, name in (("app-returns", "return_authorizations"),
64 ("app-shipping", "shipments"),
65 ("app-shipping", "shipment_lines"),
66 ("app-catalog", "products"), ("app-catalog", "locations"),
67 ("app-catalog", "stock_moves"),
68 ("app-orders", "orders"), ("app-orders", "order_lines"),
69 ("app-invoices", "invoices"),
70 ("app-payments", "payments"),
71 ("app-payments", "refunds")):
72 stage_collection(data_dir, pkg, name)
73 rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings))
74 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
75
76 objects_root = tmp_path / "objects"
77 for source in (RETURNS_OBJECTS, SHIPPING_OBJECTS, PAYMENTS_OBJECTS):
78 shutil.copytree(source, objects_root, dirs_exist_ok=True)
79
80 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
81 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
82 return data_dir, objects_root
83
84
85def run(objects_root, object_id, method, payload):
86 return object_execution.execute_object(
87 RUNTIME,
88 object_execution.ObjectExecutionRequest(
89 object_id, method=method, payload=payload),
90 roots=[objects_root]).result
91
92
93# --- fixtures shaped like a real shop -----------------------------------------
94
95def product(data_dir, product_id, name, cents=1200):
96 return object_records.create_collection_record(
97 "products",
98 {"id": product_id, "name": name, "sku": product_id.upper(),
99 "product_type": "physical", "price_cents": str(cents),
100 "currency": "USD", "is_active": "true", "owner_id": "shop"},
101 base_dir=data_dir)
102
103
104def location(data_dir, location_id, name, kind="warehouse"):
105 return object_records.create_collection_record(
106 "locations",
107 {"id": location_id, "name": name, "location_type": kind,
108 "owner_id": "shop"},
109 base_dir=data_dir)
110
111
112def order(data_dir, order_id="ord-1", *, status="confirmed", number="SO-0001",
113 owner="shop", **fields):
114 record = {"id": order_id, "doc_type": "sale", "number": number,
115 "customer_name": "Ada Lovelace",
116 "customer_email": "ada@example.test", "currency": "USD",
117 "status": "draft", "order_date": "2026-07-01", "owner_id": owner}
118 record.update({k: str(v) for k, v in fields.items()})
119 object_records.create_collection_record("orders", record,
120 base_dir=data_dir)
121 # Through the ladder, the way a human would: draft is where every order
122 # starts.
123 for step in ("confirmed", status):
124 current = object_records.get_collection_record(
125 "orders", order_id, base_dir=data_dir)["status"]
126 if step not in ("draft", current):
127 object_records.update_collection_record(
128 "orders", order_id, {"status": step},
129 base_dir=data_dir, actor="test")
130 return object_records.get_collection_record("orders", order_id,
131 base_dir=data_dir)
132
133
134def order_line(data_dir, line_id, order_id="ord-1", *, product_id="p1",
135 description="Enamel Mug", quantity="3", cents=1200, tax_bps=0,
136 **extra):
137 total = int(float(quantity) * cents)
138 record = {"id": line_id, "order_id": order_id, "product_id": product_id,
139 "description": description, "quantity": str(quantity),
140 "unit_price_cents": str(cents), "line_total_cents": str(total),
141 "tax_rate_bps": str(tax_bps),
142 "line_tax_cents": str(total * tax_bps // 10000),
143 "owner_id": "shop"}
144 record.update({k: str(v) for k, v in extra.items()})
145 return object_records.create_collection_record(
146 "order_lines", record, base_dir=data_dir)
147
148
149def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
150 return object_records.create_collection_record(
151 "stock_moves",
152 {"id": object_ids.new_uuid4(), "product_id": product_id,
153 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
154 "occurred_at": "2026-06-01", "owner_id": "shop"},
155 base_dir=data_dir)
156
157
158def paid(data_dir, *, cents=3600, order_id="ord-1", invoice_id="inv-1"):
159 """An order paid for the way app-shop's checkout leaves it: an invoice
160 the order points at, and a received payment against that invoice."""
161 object_records.create_collection_record(
162 "invoices",
163 {"id": invoice_id, "number": "SO-0001", "customer_name": "Ada Lovelace",
164 "customer_email": "ada@example.test", "status": "sent",
165 "issue_date": "2026-07-01", "due_date": "2026-07-15",
166 "subtotal_cents": str(cents), "total_cents": str(cents),
167 "owner_id": "shop"},
168 base_dir=data_dir)
169 object_records.update_collection_record(
170 "orders", order_id, {"invoice_id": invoice_id},
171 base_dir=data_dir, actor="test")
172 return object_records.create_collection_record(
173 "payments",
174 {"id": "pay-1", "invoice_id": invoice_id, "amount_cents": str(cents),
175 "method": "card", "received_on": "2026-07-02", "status": "received",
176 "owner_id": "shop"},
177 base_dir=data_dir)
178
179
180def shipments(data_dir):
181 return object_records.read_collection_records("shipments",
182 base_dir=data_dir)
183
184
185def shipment_lines(data_dir, shipment_id=None):
186 rows = object_records.read_collection_records("shipment_lines",
187 base_dir=data_dir)
188 if shipment_id is None:
189 return rows
190 return [row for row in rows if row["shipment_id"] == shipment_id]
191
192
193def rmas(data_dir):
194 return object_records.read_collection_records("return_authorizations",
195 base_dir=data_dir)
196
197
198def refunds(data_dir):
199 return object_records.read_collection_records("refunds", base_dir=data_dir)
200
201
202def moves(data_dir, reason=None):
203 rows = object_records.read_collection_records("stock_moves",
204 base_dir=data_dir)
205 if reason is None:
206 return rows
207 return [row for row in rows if row["reason"] == reason]
208
209
210def on_shelf(data_dir, product_id="p1", location_id="loc-shelf"):
211 return object_stock.quantity_at_location(product_id, location_id,
212 base_dir=data_dir)
213
214
215def authorize(objects_root, **payload):
216 """As the shop that owns the order: the action refuses anybody the
217 permission engine would not let update it (or who lacks its token)."""
218 payload.setdefault("_identity", {"user_id": "shop"})
219 return run(objects_root, "action_authorize_return", "POST", payload)
220
221
222def disposition(objects_root, **payload):
223 """As the shop that owns the return: the action refuses anybody the
224 permission engine would not let update the inbound shipment."""
225 payload.setdefault("_identity", {"user_id": "shop"})
226 return run(objects_root, "action_disposition_return", "POST", payload)
227
228
229def post_return(objects_root, shipment_id):
230 """The dispatcher's own payload shape: EVENT verb, record_id, raw
231 action."""
232 return run(objects_root, "system_return_posting", "EVENT",
233 {"event": "shipments.record.updated", "collection": "shipments",
234 "record_id": shipment_id, "action": "update"})
235
236
237def outbound_shipment(data_dir, order_id="ord-1", *, lines=(("line-1", "3"),),
238 status="delivered", shipment_id="ship-out"):
239 """A parcel that already went, written directly the way a trusted
240 server-side write is -- this suite is about what comes BACK, and
241 re-proving app-shipping's outbound path here would only couple the two
242 test files together."""
243 object_records.create_collection_record(
244 "shipments",
245 {"id": shipment_id, "order_id": order_id, "direction": "outbound",
246 "status": "open", "service": "ground", "ship_to_name": "Ada Lovelace",
247 "shipped_on": "2026-07-03", "owner_id": "shop"},
248 base_dir=data_dir)
249 for index, (order_line_id, quantity) in enumerate(lines):
250 object_records.create_collection_record(
251 "shipment_lines",
252 {"id": f"{shipment_id}-line-{index}", "shipment_id": shipment_id,
253 "order_line_id": order_line_id, "product_id": "p1",
254 "description": "Enamel Mug", "quantity": str(quantity),
255 "owner_id": "shop"},
256 base_dir=data_dir)
257 for step in ("packed", "shipped", status):
258 current = object_records.get_collection_record(
259 "shipments", shipment_id, base_dir=data_dir)["status"]
260 if step != current:
261 object_records.update_collection_record(
262 "shipments", shipment_id, {"status": step},
263 base_dir=data_dir, actor="test")
264 if step == status:
265 break
266 return object_records.get_collection_record("shipments", shipment_id,
267 base_dir=data_dir)
268
269
270def receive(data_dir, shipment_id):
271 """The parcel lands on our dock: authorized -> received, the walk-in
272 shortcut the inbound ladder allows."""
273 object_records.update_collection_record(
274 "shipments", shipment_id, {"status": "received"},
275 base_dir=data_dir, actor="test")
276
277
278def shop_with_a_return(tmp_path, monkeypatch, *, quantity="3",
279 order_status="delivered", settings=None, tax_bps=0,
280 cents=1200, line_fields=None, paid_cents=None):
281 """A shop that sold three mugs, sent them, and got paid.
282
283 line_fields: extra order-line fields (a discount, a modifier), and
284 paid_cents what the customer paid for them. Both are set BEFORE the
285 payment: a paid line is frozen (object_corrections), so a test cannot
286 reshape the sale after the money arrived any more than a cashier can."""
287 if settings is None:
288 settings = [("shop.stock_location", "loc-shelf"),
289 ("shop.customer_location", "loc-customer")]
290 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=settings)
291 location(data_dir, "loc-shelf", "Shelf")
292 location(data_dir, "loc-customer", "Customers", kind="customer")
293 product(data_dir, "p1", "Enamel Mug")
294 stock_in(data_dir, "p1", 20)
295 order(data_dir, status="shipped")
296 order_line(data_dir, "line-1", quantity=quantity, cents=cents,
297 tax_bps=tax_bps, **(line_fields or {}))
298 outbound_shipment(data_dir, lines=(("line-1", quantity),),
299 status=order_status)
300 # The sale move the outbound shipment composed: the goods are with the
301 # customer, which is where a return has to come back FROM.
302 object_records.create_collection_record(
303 "stock_moves",
304 {"id": object_ids.new_uuid4(), "product_id": "p1",
305 "from_location_id": "loc-shelf", "to_location_id": "loc-customer",
306 "quantity": str(quantity), "reason": "sale",
307 "reference": "shipments/ship-out:line/ship-out-line-0",
308 "occurred_at": "2026-07-03", "owner_id": "shop"},
309 base_dir=data_dir)
310 paid(data_dir, cents=paid_cents or int(float(quantity) * cents))
311 return data_dir, objects_root
312
313
314def authorized_return(objects_root, **payload):
315 request = {"order_id": "ord-1", "reason": "no_longer_wanted",
316 "lines": [{"order_line_id": "line-1", "quantity": "1"}]}
317 request.update(payload)
318 return authorize(objects_root, **request)
319
320
321# --- the authorization gate -----------------------------------------------------
322
323def test_returning_more_than_was_shipped_is_refused_with_the_numbers(
324 tmp_path, monkeypatch):
325 """A second RMA for the same mug is how two refunds get paid for one
326 sale. "No" is not an answer anybody can act on -- which of the two
327 returns is the wrong one is only knowable from the numbers."""
328 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
329 first = authorized_return(objects_root)
330 assert first["ok"] and first["lines"] == 1
331
332 refused = authorize(objects_root, order_id="ord-1", reason="damaged",
333 lines=[{"order_line_id": "line-1", "quantity": "3"}])
334 assert refused["status"] == 409
335 assert refused["over_return"][0] == {
336 "order_line_id": "line-1", "description": "Enamel Mug",
337 "shipped": "3", "already_authorized": "1", "asked_for": "3",
338 "would_make": "4"}
339 # Nothing half-written: one RMA and one inbound parcel, from the first
340 # call only.
341 assert len(rmas(data_dir)) == 1
342 assert len([row for row in shipments(data_dir)
343 if row["direction"] == "inbound"]) == 1
344
345
346import pytest # noqa: E402
347
348
349@pytest.mark.parametrize("collection", ["shipments", "shipment_lines", "order_lines"])
350def test_an_unreadable_history_refuses_the_return_with_503(
351 tmp_path, monkeypatch, collection):
352 """An unreadable history is an unknown, not "nothing shipped". Read as
353 empty it refused with a 409 telling the person on the phone that this
354 order shipped nothing (or has no such line), which is false, and the
355 next thing they do is raise the return by hand. Found failing open in
356 the 2026-11-28 review; it failed closed, but with the wrong words."""
357 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
358 real = object_records.read_collection_records
359
360 def failing(name, *a, **k):
361 if name == collection:
362 raise OSError(f"{name} unreadable")
363 return real(name, *a, **k)
364
365 monkeypatch.setattr(object_records, "read_collection_records", failing)
366 result = authorized_return(objects_root)
367 monkeypatch.setattr(object_records, "read_collection_records", real)
368
369 assert result["status"] == 503, result
370 assert f"{collection} unreadable" in result["error"]
371 assert rmas(data_dir) == []
372 assert [s for s in shipments(data_dir) if s["direction"] == "inbound"] == []
373 assert authorized_return(objects_root)["ok"] # readable again: normal
374
375
376def test_returning_against_an_order_that_never_shipped_is_refused(
377 tmp_path, monkeypatch):
378 """Goods still on our own shelf come off an order by cancelling or
379 amending it -- a different document with different money attached."""
380 data_dir, objects_root = setup_env(
381 tmp_path, monkeypatch,
382 settings=[("shop.stock_location", "loc-shelf"),
383 ("shop.customer_location", "loc-customer")])
384 product(data_dir, "p1", "Enamel Mug")
385 order(data_dir, status="confirmed")
386 order_line(data_dir, "line-1")
387
388 refused = authorized_return(objects_root)
389 assert refused["status"] == 409
390 assert "nothing has left the building" in refused["error"]
391 assert "cannot return what was never sent" in refused["error"]
392 assert rmas(data_dir) == []
393 assert shipments(data_dir) == []
394
395
396def test_a_return_has_to_say_why(tmp_path, monkeypatch):
397 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
398 refused = authorize(objects_root, order_id="ord-1",
399 lines=[{"order_line_id": "line-1", "quantity": "1"}])
400 assert refused["status"] == 409
401 assert "has to say why" in refused["missing_reason"]
402
403 unknown = authorize(objects_root, order_id="ord-1", reason="because",
404 lines=[{"order_line_id": "line-1", "quantity": "1"}])
405 assert "Unknown reason" in unknown["missing_reason"]
406 assert rmas(data_dir) == []
407
408
409def test_every_blocker_is_reported_at_once(tmp_path, monkeypatch):
410 """Whoever is doing this is usually on the phone to the customer."""
411 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
412 refused = authorize(
413 objects_root, order_id="ord-1",
414 lines=[{"order_line_id": "line-1", "quantity": "9"},
415 {"order_line_id": "no-such-line", "quantity": "1"},
416 {"order_line_id": "line-1", "quantity": "0"}])
417 assert refused["status"] == 409
418 assert refused["over_return"] and refused["unknown_lines"] == ["no-such-line"]
419 assert refused["bad_quantities"][0]["order_line_id"] == "line-1"
420 assert refused["missing_reason"]
421 assert rmas(data_dir) == []
422
423
424# --- the RMA is an inbound shipment ---------------------------------------------
425
426def test_an_rma_creates_an_inbound_shipment_carrying_the_lines(
427 tmp_path, monkeypatch):
428 """A return is not a new noun: it is the shipment document with the
429 sign reversed, and the lines live where lines have always lived."""
430 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
431 created = authorized_return(objects_root, reason="damaged",
432 reason_note="handle snapped off",
433 lines=[{"order_line_id": "line-1",
434 "quantity": "2"}],
435 today="2026-07-10", expires_days=14)
436 assert created["ok"]
437
438 parcel = object_records.get_collection_record(
439 "shipments", created["shipment_id"], base_dir=data_dir)
440 assert parcel["direction"] == "inbound"
441 assert parcel["status"] == "authorized"
442 assert parcel["order_id"] == "ord-1"
443 assert parcel["ship_to_name"] == "Ada Lovelace"
444 assert "orders/ord-1" in parcel["notes"]
445
446 lines = shipment_lines(data_dir, created["shipment_id"])
447 assert len(lines) == 1
448 assert lines[0]["order_line_id"] == "line-1"
449 assert lines[0]["quantity"] == "2"
450 assert lines[0]["description"] == "Enamel Mug"
451
452 rma = object_records.get_collection_record(
453 "return_authorizations", created["return_id"], base_dir=data_dir)
454 assert rma["status"] == "authorized"
455 assert rma["shipment_id"] == created["shipment_id"]
456 assert rma["reason"] == "damaged"
457 assert "handle snapped" in rma["reason_note"]
458 assert rma["customer_email"] == "ada@example.test"
459 # An RMA is an offer with a deadline: goods trickling back six months
460 # later against a closed order is how a returns process stops being
461 # auditable. DATA in this slice -- stamped, never enforced.
462 assert rma["expires_on"] == "2026-07-24"
463 assert created["expires_on"] == "2026-07-24"
464
465 # Nothing has moved and nothing has been paid back.
466 assert moves(data_dir, "return") == []
467 assert refunds(data_dir) == []
468
469
470def test_the_original_shipment_is_never_touched(tmp_path, monkeypatch):
471 """A return does not un-ship anything: what left the building on the
472 3rd left the building on the 3rd (docs/logic-decisions.md #3)."""
473 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
474 before = object_records.get_collection_record("shipments", "ship-out",
475 base_dir=data_dir)
476 authorized_return(objects_root, lines=[{"order_line_id": "line-1",
477 "quantity": "3"}])
478 after = object_records.get_collection_record("shipments", "ship-out",
479 base_dir=data_dir)
480 assert after["status"] == before["status"] == "delivered"
481 assert len(shipment_lines(data_dir, "ship-out")) == 1
482 assert shipment_lines(data_dir, "ship-out")[0]["quantity"] == "3"
483
484
485# --- goods arriving is not a decision -------------------------------------------
486
487def test_the_arrival_handler_stamps_the_rma_and_touches_no_money(
488 tmp_path, monkeypatch):
489 """A box on the dock could hold a mug in its wrapping or the same mug
490 in three pieces. The handler keeps the paperwork in step and leaves the
491 judgement to a human."""
492 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
493 created = authorized_return(objects_root)
494
495 early = post_return(objects_root, created["shipment_id"])
496 assert early["skipped"] == "shipment is authorized, not received"
497
498 receive(data_dir, created["shipment_id"])
499 result = post_return(objects_root, created["shipment_id"])
500 assert result["ok"] and result["return_id"] == created["return_id"]
501 assert result["return_status"] == "authorized"
502 assert "nothing financial has happened" in result["note"]
503 assert moves(data_dir, "return") == [] and refunds(data_dir) == []
504
505
506def test_the_arrival_handler_ignores_outbound_parcels(tmp_path, monkeypatch):
507 """Two handlers reacting to the same row is how one undoes the other's
508 work."""
509 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
510 result = post_return(objects_root, "ship-out")
511 assert result["skipped"] == "outbound shipments are not returns"
512
513
514def test_a_parcel_arriving_after_the_deadline_says_so_and_refuses_nothing(
515 tmp_path, monkeypatch):
516 """Expiry is DATA in this slice. A box on the dock is a box on the
517 dock; what the date buys is that whoever chooses restock-or-refund
518 learns they are outside the promise before they choose."""
519 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
520 created = authorized_return(objects_root, today="2020-01-01",
521 expires_days=30)
522 receive(data_dir, created["shipment_id"])
523
524 result = post_return(objects_root, created["shipment_id"])
525 assert result["ok"] is True
526 assert result["past_expiry"] is True
527 assert result["expires_on"] == "2020-01-31"
528 # And the return can still be dispositioned: nothing anywhere refuses a
529 # late parcel, and no pass sweeps stale RMAs to `expired` -- that is
530 # the tracking slice's daemon work, deliberately absent here.
531 done = disposition(objects_root, shipment_id=created["shipment_id"],
532 lines=[{"shipment_line_id": shipment_lines(
533 data_dir, created["shipment_id"])[0]["id"],
534 "disposition": "restock", "quantity": "1"}])
535 assert done["ok"] is True
536
537
538# --- the disposition ------------------------------------------------------------
539
540def dispositioned(objects_root, data_dir, created, *, disposition_kind="restock",
541 quantity="1", **payload):
542 line_id = shipment_lines(data_dir, created["shipment_id"])[0]["id"]
543 request = {"shipment_id": created["shipment_id"],
544 "lines": [{"shipment_line_id": line_id,
545 "disposition": disposition_kind,
546 "quantity": quantity}]}
547 request.update(payload)
548 return disposition(objects_root, **request)
549
550
551def test_dispositioning_a_parcel_that_has_not_arrived_is_refused(
552 tmp_path, monkeypatch):
553 """Deciding what is in a box nobody has opened is a guess."""
554 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
555 created = authorized_return(objects_root)
556
557 refused = dispositioned(objects_root, data_dir, created)
558 assert refused["status"] == 409
559 assert "is authorized, not received" in refused["error"]
560 assert "in transit is a guess" in refused["error"]
561 assert moves(data_dir, "return") == []
562 parcel = object_records.get_collection_record(
563 "shipments", created["shipment_id"], base_dir=data_dir)
564 assert parcel["status"] == "authorized"
565
566
567def test_restock_composes_a_return_move_and_the_shelf_goes_back_up(
568 tmp_path, monkeypatch):
569 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
570 created = authorized_return(objects_root)
571 receive(data_dir, created["shipment_id"])
572 before = on_shelf(data_dir)
573
574 result = dispositioned(objects_root, data_dir, created)
575 assert result["ok"] and result["moved"] == 1
576 assert on_shelf(data_dir) == before + 1
577
578 move = moves(data_dir, "return")[0]
579 assert move["from_location_id"] == "loc-customer"
580 assert move["to_location_id"] == "loc-shelf"
581 assert move["quantity"] == "1"
582 assert f"returns/{created['shipment_id']}:line/" in move["reference"]
583
584 parcel = object_records.get_collection_record(
585 "shipments", created["shipment_id"], base_dir=data_dir)
586 assert parcel["status"] == "dispositioned"
587 rma = object_records.get_collection_record(
588 "return_authorizations", created["return_id"], base_dir=data_dir)
589 assert rma["status"] == "closed"
590
591
592def test_dispose_composes_a_loss_move_and_the_shelf_does_not_go_up(
593 tmp_path, monkeypatch):
594 """Disposal is still a MOVE. Goods that left inventory with no trace is
595 exactly how shrinkage hides, and a loss report that only counts what
596 somebody remembered to write down is guaranteed to be optimistic."""
597 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
598 created = authorized_return(objects_root)
599 receive(data_dir, created["shipment_id"])
600 before = on_shelf(data_dir)
601
602 result = dispositioned(objects_root, data_dir, created,
603 disposition_kind="dispose")
604 assert result["ok"] and result["moved"] == 1
605 assert on_shelf(data_dir) == before # nothing came back to sell
606 assert moves(data_dir, "return") == []
607
608 move = moves(data_dir, "waste")[0]
609 assert move["from_location_id"] == "loc-customer"
610 # The loss shape hook_stock_moves enforces: out of a real location, to
611 # nowhere. Goods leave the system; they are not wasted INTO a shelf.
612 assert move["to_location_id"] == ""
613 assert move["quantity"] == "1"
614
615
616def test_a_damaged_return_is_disposed_of_as_damage_not_waste(
617 tmp_path, monkeypatch):
618 """'This arrived broken' and 'we cannot resell this' are different
619 arguments, and the loss taxonomy exists so the difference survives."""
620 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
621 created = authorized_return(objects_root, reason="damaged")
622 receive(data_dir, created["shipment_id"])
623
624 dispositioned(objects_root, data_dir, created, disposition_kind="dispose")
625 assert moves(data_dir, "waste") == []
626 assert len(moves(data_dir, "damage")) == 1
627
628
629def test_a_replayed_disposition_moves_nothing_twice_and_refunds_nothing_twice(
630 tmp_path, monkeypatch):
631 """The property this whole slice is judged on. Retries, double clicks
632 and replayed queue entries are ordinary; a customer's money going back
633 twice is not."""
634 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
635 created = authorized_return(objects_root)
636 receive(data_dir, created["shipment_id"])
637
638 first = dispositioned(objects_root, data_dir, created, refund="full")
639 assert first["moved"] == 1 and first["refund_id"]
640 assert len(refunds(data_dir)) == 1
641
642 again = dispositioned(objects_root, data_dir, created, refund="full")
643 assert again["ok"] is True
644 assert "already dispositioned" in again["note"]
645 assert again["moved"] == 0 and again["refund_id"] == ""
646 assert again["return_id"] == created["return_id"]
647 assert again["refund_ref"] == first["refund_ref"]
648
649 assert len(moves(data_dir, "return")) == 1
650 assert len(refunds(data_dir)) == 1
651
652
653def test_dispositioning_more_than_came_back_is_refused(tmp_path, monkeypatch):
654 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
655 created = authorized_return(objects_root)
656 receive(data_dir, created["shipment_id"])
657
658 refused = dispositioned(objects_root, data_dir, created, quantity="5")
659 assert refused["status"] == 409
660 assert refused["over_disposition"][0]["came_back"] == "1"
661 assert refused["over_disposition"][0]["asked_for"] == "5"
662 assert moves(data_dir, "return") == []
663
664
665def test_a_disposition_has_to_name_what_each_line_is(tmp_path, monkeypatch):
666 """No default: guessing restock puts damaged goods on the shelf and
667 guessing dispose bins sellable stock."""
668 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
669 created = authorized_return(objects_root)
670 receive(data_dir, created["shipment_id"])
671
672 refused = disposition(objects_root, shipment_id=created["shipment_id"])
673 assert refused["status"] == 409
674 assert "no default" in refused["bad_quantities"][0]["reason"]
675
676
677# --- the money ------------------------------------------------------------------
678
679def test_a_full_refund_pays_back_what_was_paid_for_those_lines(
680 tmp_path, monkeypatch):
681 """The line money plus the tax charged ON that line, computed the way
682 order_totals computed it -- not a number that looks close."""
683 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch,
684 tax_bps=825)
685 created = authorized_return(objects_root)
686 receive(data_dir, created["shipment_id"])
687
688 result = dispositioned(objects_root, data_dir, created, refund="full")
689 assert result["ok"]
690 # One mug at 1200, tax 8.25% floored: 1200 + 99.
691 assert result["refund_cents"] == "1299"
692
693 row = refunds(data_dir)[0]
694 assert row["amount_cents"] == "1299"
695 assert row["payment_id"] == "pay-1"
696 # Stamped by hook_refunds from the payment, never trusted from us.
697 assert row["invoice_id"] == "inv-1"
698 assert row["refunded_on"]
699
700 rma = object_records.get_collection_record(
701 "return_authorizations", created["return_id"], base_dir=data_dir)
702 assert rma["refund_ref"] == f"refunds/{row['id']}"
703 assert result["refund_ref"] == rma["refund_ref"]
704
705
706def test_an_over_large_partial_refund_is_refused_by_the_existing_gate(
707 tmp_path, monkeypatch):
708 """The ceiling is not reimplemented here: app-payments' hook already
709 knows what a payment can give back, and its words are what surfaces --
710 so a customer is quoted the same number whichever door they came
711 through."""
712 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
713 created = authorized_return(objects_root)
714 receive(data_dir, created["shipment_id"])
715
716 refused = dispositioned(objects_root, data_dir, created, refund="partial",
717 refund_cents="99999")
718 assert refused["status"] == 409
719 assert "exceeds the refundable" in refused["refund"]
720 assert "3600" in refused["refund"] # what the payment can give
721 assert "pay-1" in refused["refund"]
722
723 # And nothing happened: no refund, no moves, and the return is still
724 # open for somebody to get right.
725 assert refunds(data_dir) == []
726 assert moves(data_dir, "return") == []
727 parcel = object_records.get_collection_record(
728 "shipments", created["shipment_id"], base_dir=data_dir)
729 assert parcel["status"] == "received"
730
731
732def test_a_partial_refund_within_the_ceiling_is_written(tmp_path, monkeypatch):
733 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
734 created = authorized_return(objects_root)
735 receive(data_dir, created["shipment_id"])
736
737 result = dispositioned(objects_root, data_dir, created, refund="partial",
738 refund_cents="900")
739 assert result["ok"] and result["refund_cents"] == "900"
740 assert refunds(data_dir)[0]["amount_cents"] == "900"
741
742
743def test_refund_none_closes_the_return_silently(tmp_path, monkeypatch):
744 """A restocking-fee-only return, a replacement instead of a refund, a
745 goodwill restock: all ordinary. Warning about them would teach
746 operators to click past warnings."""
747 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
748 created = authorized_return(objects_root)
749 receive(data_dir, created["shipment_id"])
750
751 result = dispositioned(objects_root, data_dir, created)
752 assert result["ok"] and result["moved"] == 1
753 assert result["refund"] == "none"
754 assert result["refund_id"] == "" and result["refund_ref"] == ""
755 assert "warning" not in result and "note" not in result
756 assert refunds(data_dir) == []
757
758 rma = object_records.get_collection_record(
759 "return_authorizations", created["return_id"], base_dir=data_dir)
760 assert rma["status"] == "closed"
761 assert rma["refund_ref"] == ""
762
763
764# --- the page -------------------------------------------------------------------
765
766def form(objects_root, order_id="ord-1", user_id="shop", method="GET", **fields):
767 payload = {"order_id": order_id}
768 if user_id:
769 payload["_identity"] = {"user_id": user_id}
770 if fields:
771 payload["_form"] = fields
772 return run(objects_root, "site_return_form", method, payload)
773
774
775def test_the_return_form_shows_the_shipped_lines(tmp_path, monkeypatch):
776 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
777 body = form(objects_root)["body"]
778 assert "Enamel Mug" in body
779 assert "SO-0001" in body
780 assert ">3<" in body # three of them can come back
781 assert 'name="qty_line-1"' in body
782 assert "No longer wanted" in body
783 # Nothing has been returned yet, so there is no RMA block and no label
784 # placeholder to show.
785 assert "Returns on this order" not in body
786
787
788def test_the_return_form_raises_the_rma_and_shows_it_back(tmp_path, monkeypatch):
789 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
790 result = form(objects_root, method="POST",
791 **{"do": "request", "reason": "damaged",
792 "reason_note": "handle snapped", "qty_line-1": "1"})
793 body = result["body"]
794 assert "authorized" in body
795 assert len(rmas(data_dir)) == 1
796 rma = rmas(data_dir)[0]
797 assert rma["reason"] == "damaged"
798 assert rma["status"] == "authorized"
799 assert "Returns on this order" in body
800 assert "return label will appear here" in body
801 assert "carrier connector" in body
802
803
804def test_the_return_form_surfaces_the_actions_refusal_with_its_numbers(
805 tmp_path, monkeypatch):
806 """Rewording the gate here would guarantee two vocabularies for one
807 rule."""
808 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
809 result = form(objects_root, method="POST",
810 **{"reason": "damaged", "qty_line-1": "9"})
811 body = result["body"]
812 assert "shipped 3" in body
813 assert "would make 9" in body
814 assert rmas(data_dir) == []
815
816
817def test_the_return_form_turns_away_a_stranger_with_no_credential(
818 tmp_path, monkeypatch):
819 """A visitor with neither a session nor the order's token is offered
820 the two real ways in -- the tracking link from their confirmation
821 email, or sign-in -- and is shown nothing about the order itself.
822 Guests reaching this page WITH a token are tests/test_store_voice.py's
823 subject; this is the case where there is no key at all."""
824 _, objects_root = shop_with_a_return(tmp_path, monkeypatch)
825 body = form(objects_root, user_id="")["body"]
826 assert "tracking link" in body
827 assert "sign in" in body
828 assert "Enamel Mug" not in body
829
830
831def test_the_return_form_is_a_friendly_404_for_an_unknown_order(
832 tmp_path, monkeypatch):
833 _, objects_root = shop_with_a_return(tmp_path, monkeypatch)
834 result = form(objects_root, order_id="no-such-order")
835 assert result["status"] == 404
836 assert "Traceback" not in result["body"]
837
838
839# --- the bench (0.3.0) -------------------------------------------------------
840#
841# The count shipped pointing at /orders: a path this package does not own,
842# serving a list containing none of the rows it counted, because the goods
843# coming back had no page anywhere. The tests below are about the one
844# property that makes a badge worth clicking -- the page it opens has to
845# show what the badge counted -- and about the two choices that follow
846# from it: the index is over SHIPMENTS (an RMA is an intention; the parcel
847# is the thing with a person waiting on it), and it uses `where` rather
848# than `filters` so it renders as the schema's real table instead of a
849# column of raw shipment ids.
850
851import csv # noqa: E402
852import json # noqa: E402
853
854import object_packages # noqa: E402
855
856APP_RETURNS_DIR = PACKAGES / "app-returns"
857
858
859def _returns_seed_rows(name):
860 with open(APP_RETURNS_DIR / "seed" / f"{name}.tsv", newline="") as handle:
861 return list(csv.DictReader(handle, delimiter="\t"))
862
863
864def test_the_bench_lists_the_collection_the_count_actually_reads():
865 """The count is of inbound shipments that have ARRIVED (the box is
866 here), not of return_authorizations, which would be counting
867 intentions. The page has to agree with it about what a return even is."""
868 manifest = json.loads((APP_RETURNS_DIR / "dbbasic-package.json").read_text())
869 [entry] = [e for e in manifest["attention"] if e["id"] == "returns_to_disposition"]
870 assert entry["collection"] == "shipments"
871 assert entry["where"] == {"direction": "inbound", "status": "received"}
872
873 rows = [row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench"]
874 assert len(rows) == 1
875 view = rows[0]
876 assert view["route"] == "/returns"
877 blocks = json.loads(view["blocks"])
878 assert len(blocks) == 1
879 block = blocks[0]
880 assert block["kind"] == "list"
881 assert block["collection"] == "shipments"
882
883
884def test_the_bench_is_scoped_with_where_so_it_renders_as_a_real_table():
885 """`filters` would drop the page into the view layer's client-side
886 fallback, which titles each row `title || name || id` -- and a shipment
887 has neither a title nor a name, so every row would read as a raw id.
888 `where` compiles to the server-side narrowing `related` uses and keeps
889 the schema's table, filter bar, search and row cap."""
890 view = next(row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench")
891 block = json.loads(view["blocks"])[0]
892
893 assert block["where"] == {"direction": "inbound"}
894 assert "filters" not in block
895 # The renderer has to actually honour it, or the page silently lists
896 # every outbound parcel too.
897 renderer = (PACKAGES / "app-views" / "objects" / "site" / "view_render.py").read_text()
898 assert "cfg.where = block.where" in renderer
899
900
901def test_the_bench_shows_the_whole_inbound_ladder_not_only_the_undecided():
902 """`received` is what the badge counts, and the bench deliberately shows
903 more than that: a returns bench that hides what is in transit and what
904 was settled yesterday cannot answer either question somebody standing at
905 it asks. The narrowing to `received` is one pick in the filter bar the
906 schema already declares."""
907 view = next(row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench")
908 block = json.loads(view["blocks"])[0]
909 assert "status" not in block["where"]
910
911 shipments = json.loads((PACKAGES / "app-shipping" / "schemas" / "shipments.json").read_text())
912 assert "status" in shipments["views"]["filter_fields"]
913 assert "received" in next(field for field in shipments["fields"]
914 if field["name"] == "status")["enum"]
915
916
917def test_the_bench_route_points_at_the_generic_renderer_beside_the_return_form():
918 rows = _returns_seed_rows("site_routes")
919 by_id = {row["id"]: row for row in rows}
920
921 assert by_id["route_returns_index"]["pattern"] == "/returns"
922 assert by_id["route_returns_index"]["object_id"] == "site_view_render"
923 # The per-order customer form keeps its own, more specific pattern.
924 assert by_id["route_return_form"]["pattern"] == "/returns/{order_id}"
925
926
927def test_the_package_declares_a_warehouse_door_instead_of_opting_out():
928 manifest = json.loads((APP_RETURNS_DIR / "dbbasic-package.json").read_text())
929 assert "nav_optional" not in manifest
930
931 package = object_packages.get_package("app-returns", root=PACKAGES)
932 entry = package["nav"][0]
933 assert entry["id"] == "returns"
934 assert entry["path"] == "/returns"
935 assert entry["group"] == "Warehouse"
936 assert entry["surface"] == "operator"
937 assert "app-views" in {dep["id"] for dep in package["dependencies"]}
938
939
940def test_the_count_opens_the_bench_and_stays_visible_to_whoever_clears_it():
941 """No nav_id, on purpose. A count bound to a door inherits that door's
942 audience, and this door is filed under the operator tier -- but
943 permissions/rules.json lets ANY signed-in person disposition a parcel,
944 on the stated grounds that the person who opens the box is the person
945 who knows what is in it. Hiding the number from them to keep the menu
946 tidy would undo the reason the queue is counted."""
947 package = object_packages.get_package("app-returns", root=PACKAGES)
948 source = package["attention"][0]
949
950 assert source["path"] == "/returns"
951 assert source["nav_id"] == ""
952
953
954# --- whose money: the parcel is the caller's, the order may not be ---------------
955#
956# action_disposition_return asked only whether the caller may update the
957# PARCEL. An inbound shipment is its writer's own row, and its order_id, its
958# lines' product_id and the order's invoice_id were whatever the writer typed.
959# So mallory raised a parcel of her own naming the shop's order, dispositioned
960# it, and the refund came off the shop's payment while stock moved on the
961# shop's product.
962
963def _mallorys_parcel(data_dir, order_id="ord-1", product_id="p1"):
964 object_records.create_collection_record(
965 "shipments",
966 {"id": "ship-m", "order_id": order_id, "direction": "inbound",
967 "status": "authorized", "owner_id": "mallory"},
968 base_dir=data_dir)
969 object_records.create_collection_record(
970 "shipment_lines",
971 {"id": "ship-m-line", "shipment_id": "ship-m", "order_line_id": "line-1",
972 "product_id": product_id, "description": "Enamel Mug", "quantity": "1",
973 "owner_id": "mallory"},
974 base_dir=data_dir)
975 receive(data_dir, "ship-m")
976
977
978def _dispose_as_mallory(objects_root, **payload):
979 return disposition(objects_root, shipment_id="ship-m", _identity={"user_id": "mallory"},
980 lines=[{"shipment_line_id": "ship-m-line", "disposition": "dispose",
981 "quantity": "1"}], **payload)
982
983
984def test_a_parcel_naming_somebody_elses_order_refunds_nothing_and_moves_nothing(
985 tmp_path, monkeypatch):
986 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
987 _mallorys_parcel(data_dir)
988 before = len(moves(data_dir))
989 refused = _dispose_as_mallory(objects_root, refund="partial", refund_cents="900")
990 assert refused["status"] == 409
991 assert any("product p1" in item["reason"] for item in refused["bad_quantities"])
992 assert refunds(data_dir) == []
993 assert len(moves(data_dir)) == before
994
995
996def test_a_parcel_naming_somebody_elses_order_finds_no_payment_to_refund(
997 tmp_path, monkeypatch):
998 """With goods of her own in the box, so only the order and its money are
999 in question."""
1000 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
1001 object_records.create_collection_record(
1002 "products", {"id": "p-m", "name": "Her mug", "sku": "PM", "product_type": "physical",
1003 "price_cents": "1200", "currency": "USD", "is_active": "true",
1004 "owner_id": "mallory"}, base_dir=data_dir)
1005 _mallorys_parcel(data_dir, product_id="p-m")
1006 refused = _dispose_as_mallory(objects_root, refund="partial", refund_cents="900")
1007 assert refused["status"] == 409
1008 assert "No payment" in refused["refund"]
1009 assert refunds(data_dir) == []
1010
1011
1012def test_a_parcel_on_an_order_whose_invoice_is_somebody_elses_refunds_nothing(
1013 tmp_path, monkeypatch):
1014 """orders.invoice_id is not a relation: mallory's own order can name the
1015 shop's invoice, and the refund path joins payments on it."""
1016 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
1017 order(data_dir, "ord-m", owner="mallory", number="SO-M", invoice_id="inv-1")
1018 object_records.create_collection_record(
1019 "products", {"id": "p-m", "name": "Her mug", "sku": "PM", "product_type": "physical",
1020 "price_cents": "1200", "currency": "USD", "is_active": "true",
1021 "owner_id": "mallory"}, base_dir=data_dir)
1022 _mallorys_parcel(data_dir, order_id="ord-m", product_id="p-m")
1023 refused = _dispose_as_mallory(objects_root, refund="partial", refund_cents="900")
1024 assert refused["status"] == 409
1025 assert "No payment" in refused["refund"]
1026 assert refunds(data_dir) == []