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_returns.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_returns.py · 39.9 KB · 907 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 total = int(float(quantity) * cents)
137 return object_records.create_collection_record(
138 "order_lines",
139 {"id": line_id, "order_id": order_id, "product_id": product_id,
140 "description": description, "quantity": str(quantity),
141 "unit_price_cents": str(cents), "line_total_cents": str(total),
142 "tax_rate_bps": str(tax_bps),
143 "line_tax_cents": str(total * tax_bps // 10000),
144 "owner_id": "shop"},
145 base_dir=data_dir)
146
147
148def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"):
149 return object_records.create_collection_record(
150 "stock_moves",
151 {"id": object_ids.new_uuid4(), "product_id": product_id,
152 "to_location_id": to, "quantity": str(quantity), "reason": "purchase",
153 "occurred_at": "2026-06-01", "owner_id": "shop"},
154 base_dir=data_dir)
155
156
157def paid(data_dir, *, cents=3600, order_id="ord-1", invoice_id="inv-1"):
158 """An order paid for the way app-shop's checkout leaves it: an invoice
159 the order points at, and a received payment against that invoice."""
160 object_records.create_collection_record(
161 "invoices",
162 {"id": invoice_id, "number": "SO-0001", "customer_name": "Ada Lovelace",
163 "customer_email": "ada@example.test", "status": "sent",
164 "issue_date": "2026-07-01", "due_date": "2026-07-15",
165 "subtotal_cents": str(cents), "total_cents": str(cents),
166 "owner_id": "shop"},
167 base_dir=data_dir)
168 object_records.update_collection_record(
169 "orders", order_id, {"invoice_id": invoice_id},
170 base_dir=data_dir, actor="test")
171 return object_records.create_collection_record(
172 "payments",
173 {"id": "pay-1", "invoice_id": invoice_id, "amount_cents": str(cents),
174 "method": "card", "received_on": "2026-07-02", "status": "received",
175 "owner_id": "shop"},
176 base_dir=data_dir)
177
178
179def shipments(data_dir):
180 return object_records.read_collection_records("shipments",
181 base_dir=data_dir)
182
183
184def shipment_lines(data_dir, shipment_id=None):
185 rows = object_records.read_collection_records("shipment_lines",
186 base_dir=data_dir)
187 if shipment_id is None:
188 return rows
189 return [row for row in rows if row["shipment_id"] == shipment_id]
190
191
192def rmas(data_dir):
193 return object_records.read_collection_records("return_authorizations",
194 base_dir=data_dir)
195
196
197def refunds(data_dir):
198 return object_records.read_collection_records("refunds", base_dir=data_dir)
199
200
201def moves(data_dir, reason=None):
202 rows = object_records.read_collection_records("stock_moves",
203 base_dir=data_dir)
204 if reason is None:
205 return rows
206 return [row for row in rows if row["reason"] == reason]
207
208
209def on_shelf(data_dir, product_id="p1", location_id="loc-shelf"):
210 return object_stock.quantity_at_location(product_id, location_id,
211 base_dir=data_dir)
212
213
214def authorize(objects_root, **payload):
215 return run(objects_root, "action_authorize_return", "POST", payload)
216
217
218def disposition(objects_root, **payload):
219 return run(objects_root, "action_disposition_return", "POST", payload)
220
221
222def post_return(objects_root, shipment_id):
223 """The dispatcher's own payload shape: EVENT verb, record_id, raw
224 action."""
225 return run(objects_root, "system_return_posting", "EVENT",
226 {"event": "shipments.record.updated", "collection": "shipments",
227 "record_id": shipment_id, "action": "update"})
228
229
230def outbound_shipment(data_dir, order_id="ord-1", *, lines=(("line-1", "3"),),
231 status="delivered", shipment_id="ship-out"):
232 """A parcel that already went, written directly the way a trusted
233 server-side write is -- this suite is about what comes BACK, and
234 re-proving app-shipping's outbound path here would only couple the two
235 test files together."""
236 object_records.create_collection_record(
237 "shipments",
238 {"id": shipment_id, "order_id": order_id, "direction": "outbound",
239 "status": "open", "service": "ground", "ship_to_name": "Ada Lovelace",
240 "shipped_on": "2026-07-03", "owner_id": "shop"},
241 base_dir=data_dir)
242 for index, (order_line_id, quantity) in enumerate(lines):
243 object_records.create_collection_record(
244 "shipment_lines",
245 {"id": f"{shipment_id}-line-{index}", "shipment_id": shipment_id,
246 "order_line_id": order_line_id, "product_id": "p1",
247 "description": "Enamel Mug", "quantity": str(quantity),
248 "owner_id": "shop"},
249 base_dir=data_dir)
250 for step in ("packed", "shipped", status):
251 current = object_records.get_collection_record(
252 "shipments", shipment_id, base_dir=data_dir)["status"]
253 if step != current:
254 object_records.update_collection_record(
255 "shipments", shipment_id, {"status": step},
256 base_dir=data_dir, actor="test")
257 if step == status:
258 break
259 return object_records.get_collection_record("shipments", shipment_id,
260 base_dir=data_dir)
261
262
263def receive(data_dir, shipment_id):
264 """The parcel lands on our dock: authorized -> received, the walk-in
265 shortcut the inbound ladder allows."""
266 object_records.update_collection_record(
267 "shipments", shipment_id, {"status": "received"},
268 base_dir=data_dir, actor="test")
269
270
271def shop_with_a_return(tmp_path, monkeypatch, *, quantity="3",
272 order_status="delivered", settings=None, tax_bps=0,
273 cents=1200):
274 """A shop that sold three mugs, sent them, and got paid."""
275 if settings is None:
276 settings = [("shop.stock_location", "loc-shelf"),
277 ("shop.customer_location", "loc-customer")]
278 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=settings)
279 location(data_dir, "loc-shelf", "Shelf")
280 location(data_dir, "loc-customer", "Customers", kind="customer")
281 product(data_dir, "p1", "Enamel Mug")
282 stock_in(data_dir, "p1", 20)
283 order(data_dir, status="shipped")
284 order_line(data_dir, "line-1", quantity=quantity, cents=cents,
285 tax_bps=tax_bps)
286 outbound_shipment(data_dir, lines=(("line-1", quantity),),
287 status=order_status)
288 # The sale move the outbound shipment composed: the goods are with the
289 # customer, which is where a return has to come back FROM.
290 object_records.create_collection_record(
291 "stock_moves",
292 {"id": object_ids.new_uuid4(), "product_id": "p1",
293 "from_location_id": "loc-shelf", "to_location_id": "loc-customer",
294 "quantity": str(quantity), "reason": "sale",
295 "reference": "shipments/ship-out:line/ship-out-line-0",
296 "occurred_at": "2026-07-03", "owner_id": "shop"},
297 base_dir=data_dir)
298 paid(data_dir, cents=int(float(quantity) * cents))
299 return data_dir, objects_root
300
301
302def authorized_return(objects_root, **payload):
303 request = {"order_id": "ord-1", "reason": "no_longer_wanted",
304 "lines": [{"order_line_id": "line-1", "quantity": "1"}]}
305 request.update(payload)
306 return authorize(objects_root, **request)
307
308
309# --- the authorization gate -----------------------------------------------------
310
311def test_returning_more_than_was_shipped_is_refused_with_the_numbers(
312 tmp_path, monkeypatch):
313 """A second RMA for the same mug is how two refunds get paid for one
314 sale. "No" is not an answer anybody can act on -- which of the two
315 returns is the wrong one is only knowable from the numbers."""
316 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
317 first = authorized_return(objects_root)
318 assert first["ok"] and first["lines"] == 1
319
320 refused = authorize(objects_root, order_id="ord-1", reason="damaged",
321 lines=[{"order_line_id": "line-1", "quantity": "3"}])
322 assert refused["status"] == 409
323 assert refused["over_return"][0] == {
324 "order_line_id": "line-1", "description": "Enamel Mug",
325 "shipped": "3", "already_authorized": "1", "asked_for": "3",
326 "would_make": "4"}
327 # Nothing half-written: one RMA and one inbound parcel, from the first
328 # call only.
329 assert len(rmas(data_dir)) == 1
330 assert len([row for row in shipments(data_dir)
331 if row["direction"] == "inbound"]) == 1
332
333
334def test_returning_against_an_order_that_never_shipped_is_refused(
335 tmp_path, monkeypatch):
336 """Goods still on our own shelf come off an order by cancelling or
337 amending it -- a different document with different money attached."""
338 data_dir, objects_root = setup_env(
339 tmp_path, monkeypatch,
340 settings=[("shop.stock_location", "loc-shelf"),
341 ("shop.customer_location", "loc-customer")])
342 product(data_dir, "p1", "Enamel Mug")
343 order(data_dir, status="confirmed")
344 order_line(data_dir, "line-1")
345
346 refused = authorized_return(objects_root)
347 assert refused["status"] == 409
348 assert "nothing has left the building" in refused["error"]
349 assert "cannot return what was never sent" in refused["error"]
350 assert rmas(data_dir) == []
351 assert shipments(data_dir) == []
352
353
354def test_a_return_has_to_say_why(tmp_path, monkeypatch):
355 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
356 refused = authorize(objects_root, order_id="ord-1",
357 lines=[{"order_line_id": "line-1", "quantity": "1"}])
358 assert refused["status"] == 409
359 assert "has to say why" in refused["missing_reason"]
360
361 unknown = authorize(objects_root, order_id="ord-1", reason="because",
362 lines=[{"order_line_id": "line-1", "quantity": "1"}])
363 assert "Unknown reason" in unknown["missing_reason"]
364 assert rmas(data_dir) == []
365
366
367def test_every_blocker_is_reported_at_once(tmp_path, monkeypatch):
368 """Whoever is doing this is usually on the phone to the customer."""
369 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
370 refused = authorize(
371 objects_root, order_id="ord-1",
372 lines=[{"order_line_id": "line-1", "quantity": "9"},
373 {"order_line_id": "no-such-line", "quantity": "1"},
374 {"order_line_id": "line-1", "quantity": "0"}])
375 assert refused["status"] == 409
376 assert refused["over_return"] and refused["unknown_lines"] == ["no-such-line"]
377 assert refused["bad_quantities"][0]["order_line_id"] == "line-1"
378 assert refused["missing_reason"]
379 assert rmas(data_dir) == []
380
381
382# --- the RMA is an inbound shipment ---------------------------------------------
383
384def test_an_rma_creates_an_inbound_shipment_carrying_the_lines(
385 tmp_path, monkeypatch):
386 """A return is not a new noun: it is the shipment document with the
387 sign reversed, and the lines live where lines have always lived."""
388 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
389 created = authorized_return(objects_root, reason="damaged",
390 reason_note="handle snapped off",
391 lines=[{"order_line_id": "line-1",
392 "quantity": "2"}],
393 today="2026-07-10", expires_days=14)
394 assert created["ok"]
395
396 parcel = object_records.get_collection_record(
397 "shipments", created["shipment_id"], base_dir=data_dir)
398 assert parcel["direction"] == "inbound"
399 assert parcel["status"] == "authorized"
400 assert parcel["order_id"] == "ord-1"
401 assert parcel["ship_to_name"] == "Ada Lovelace"
402 assert "orders/ord-1" in parcel["notes"]
403
404 lines = shipment_lines(data_dir, created["shipment_id"])
405 assert len(lines) == 1
406 assert lines[0]["order_line_id"] == "line-1"
407 assert lines[0]["quantity"] == "2"
408 assert lines[0]["description"] == "Enamel Mug"
409
410 rma = object_records.get_collection_record(
411 "return_authorizations", created["return_id"], base_dir=data_dir)
412 assert rma["status"] == "authorized"
413 assert rma["shipment_id"] == created["shipment_id"]
414 assert rma["reason"] == "damaged"
415 assert "handle snapped" in rma["reason_note"]
416 assert rma["customer_email"] == "ada@example.test"
417 # An RMA is an offer with a deadline: goods trickling back six months
418 # later against a closed order is how a returns process stops being
419 # auditable. DATA in this slice -- stamped, never enforced.
420 assert rma["expires_on"] == "2026-07-24"
421 assert created["expires_on"] == "2026-07-24"
422
423 # Nothing has moved and nothing has been paid back.
424 assert moves(data_dir, "return") == []
425 assert refunds(data_dir) == []
426
427
428def test_the_original_shipment_is_never_touched(tmp_path, monkeypatch):
429 """A return does not un-ship anything: what left the building on the
430 3rd left the building on the 3rd (docs/logic-decisions.md #3)."""
431 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
432 before = object_records.get_collection_record("shipments", "ship-out",
433 base_dir=data_dir)
434 authorized_return(objects_root, lines=[{"order_line_id": "line-1",
435 "quantity": "3"}])
436 after = object_records.get_collection_record("shipments", "ship-out",
437 base_dir=data_dir)
438 assert after["status"] == before["status"] == "delivered"
439 assert len(shipment_lines(data_dir, "ship-out")) == 1
440 assert shipment_lines(data_dir, "ship-out")[0]["quantity"] == "3"
441
442
443# --- goods arriving is not a decision -------------------------------------------
444
445def test_the_arrival_handler_stamps_the_rma_and_touches_no_money(
446 tmp_path, monkeypatch):
447 """A box on the dock could hold a mug in its wrapping or the same mug
448 in three pieces. The handler keeps the paperwork in step and leaves the
449 judgement to a human."""
450 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
451 created = authorized_return(objects_root)
452
453 early = post_return(objects_root, created["shipment_id"])
454 assert early["skipped"] == "shipment is authorized, not received"
455
456 receive(data_dir, created["shipment_id"])
457 result = post_return(objects_root, created["shipment_id"])
458 assert result["ok"] and result["return_id"] == created["return_id"]
459 assert result["return_status"] == "authorized"
460 assert "nothing financial has happened" in result["note"]
461 assert moves(data_dir, "return") == [] and refunds(data_dir) == []
462
463
464def test_the_arrival_handler_ignores_outbound_parcels(tmp_path, monkeypatch):
465 """Two handlers reacting to the same row is how one undoes the other's
466 work."""
467 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
468 result = post_return(objects_root, "ship-out")
469 assert result["skipped"] == "outbound shipments are not returns"
470
471
472def test_a_parcel_arriving_after_the_deadline_says_so_and_refuses_nothing(
473 tmp_path, monkeypatch):
474 """Expiry is DATA in this slice. A box on the dock is a box on the
475 dock; what the date buys is that whoever chooses restock-or-refund
476 learns they are outside the promise before they choose."""
477 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
478 created = authorized_return(objects_root, today="2020-01-01",
479 expires_days=30)
480 receive(data_dir, created["shipment_id"])
481
482 result = post_return(objects_root, created["shipment_id"])
483 assert result["ok"] is True
484 assert result["past_expiry"] is True
485 assert result["expires_on"] == "2020-01-31"
486 # And the return can still be dispositioned: nothing anywhere refuses a
487 # late parcel, and no pass sweeps stale RMAs to `expired` -- that is
488 # the tracking slice's daemon work, deliberately absent here.
489 done = disposition(objects_root, shipment_id=created["shipment_id"],
490 lines=[{"shipment_line_id": shipment_lines(
491 data_dir, created["shipment_id"])[0]["id"],
492 "disposition": "restock", "quantity": "1"}])
493 assert done["ok"] is True
494
495
496# --- the disposition ------------------------------------------------------------
497
498def dispositioned(objects_root, data_dir, created, *, disposition_kind="restock",
499 quantity="1", **payload):
500 line_id = shipment_lines(data_dir, created["shipment_id"])[0]["id"]
501 request = {"shipment_id": created["shipment_id"],
502 "lines": [{"shipment_line_id": line_id,
503 "disposition": disposition_kind,
504 "quantity": quantity}]}
505 request.update(payload)
506 return disposition(objects_root, **request)
507
508
509def test_dispositioning_a_parcel_that_has_not_arrived_is_refused(
510 tmp_path, monkeypatch):
511 """Deciding what is in a box nobody has opened is a guess."""
512 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
513 created = authorized_return(objects_root)
514
515 refused = dispositioned(objects_root, data_dir, created)
516 assert refused["status"] == 409
517 assert "is authorized, not received" in refused["error"]
518 assert "in transit is a guess" in refused["error"]
519 assert moves(data_dir, "return") == []
520 parcel = object_records.get_collection_record(
521 "shipments", created["shipment_id"], base_dir=data_dir)
522 assert parcel["status"] == "authorized"
523
524
525def test_restock_composes_a_return_move_and_the_shelf_goes_back_up(
526 tmp_path, monkeypatch):
527 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
528 created = authorized_return(objects_root)
529 receive(data_dir, created["shipment_id"])
530 before = on_shelf(data_dir)
531
532 result = dispositioned(objects_root, data_dir, created)
533 assert result["ok"] and result["moved"] == 1
534 assert on_shelf(data_dir) == before + 1
535
536 move = moves(data_dir, "return")[0]
537 assert move["from_location_id"] == "loc-customer"
538 assert move["to_location_id"] == "loc-shelf"
539 assert move["quantity"] == "1"
540 assert f"returns/{created['shipment_id']}:line/" in move["reference"]
541
542 parcel = object_records.get_collection_record(
543 "shipments", created["shipment_id"], base_dir=data_dir)
544 assert parcel["status"] == "dispositioned"
545 rma = object_records.get_collection_record(
546 "return_authorizations", created["return_id"], base_dir=data_dir)
547 assert rma["status"] == "closed"
548
549
550def test_dispose_composes_a_loss_move_and_the_shelf_does_not_go_up(
551 tmp_path, monkeypatch):
552 """Disposal is still a MOVE. Goods that left inventory with no trace is
553 exactly how shrinkage hides, and a loss report that only counts what
554 somebody remembered to write down is guaranteed to be optimistic."""
555 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
556 created = authorized_return(objects_root)
557 receive(data_dir, created["shipment_id"])
558 before = on_shelf(data_dir)
559
560 result = dispositioned(objects_root, data_dir, created,
561 disposition_kind="dispose")
562 assert result["ok"] and result["moved"] == 1
563 assert on_shelf(data_dir) == before # nothing came back to sell
564 assert moves(data_dir, "return") == []
565
566 move = moves(data_dir, "waste")[0]
567 assert move["from_location_id"] == "loc-customer"
568 # The loss shape hook_stock_moves enforces: out of a real location, to
569 # nowhere. Goods leave the system; they are not wasted INTO a shelf.
570 assert move["to_location_id"] == ""
571 assert move["quantity"] == "1"
572
573
574def test_a_damaged_return_is_disposed_of_as_damage_not_waste(
575 tmp_path, monkeypatch):
576 """'This arrived broken' and 'we cannot resell this' are different
577 arguments, and the loss taxonomy exists so the difference survives."""
578 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
579 created = authorized_return(objects_root, reason="damaged")
580 receive(data_dir, created["shipment_id"])
581
582 dispositioned(objects_root, data_dir, created, disposition_kind="dispose")
583 assert moves(data_dir, "waste") == []
584 assert len(moves(data_dir, "damage")) == 1
585
586
587def test_a_replayed_disposition_moves_nothing_twice_and_refunds_nothing_twice(
588 tmp_path, monkeypatch):
589 """The property this whole slice is judged on. Retries, double clicks
590 and replayed queue entries are ordinary; a customer's money going back
591 twice is not."""
592 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
593 created = authorized_return(objects_root)
594 receive(data_dir, created["shipment_id"])
595
596 first = dispositioned(objects_root, data_dir, created, refund="full")
597 assert first["moved"] == 1 and first["refund_id"]
598 assert len(refunds(data_dir)) == 1
599
600 again = dispositioned(objects_root, data_dir, created, refund="full")
601 assert again["ok"] is True
602 assert "already dispositioned" in again["note"]
603 assert again["moved"] == 0 and again["refund_id"] == ""
604 assert again["return_id"] == created["return_id"]
605 assert again["refund_ref"] == first["refund_ref"]
606
607 assert len(moves(data_dir, "return")) == 1
608 assert len(refunds(data_dir)) == 1
609
610
611def test_dispositioning_more_than_came_back_is_refused(tmp_path, monkeypatch):
612 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
613 created = authorized_return(objects_root)
614 receive(data_dir, created["shipment_id"])
615
616 refused = dispositioned(objects_root, data_dir, created, quantity="5")
617 assert refused["status"] == 409
618 assert refused["over_disposition"][0]["came_back"] == "1"
619 assert refused["over_disposition"][0]["asked_for"] == "5"
620 assert moves(data_dir, "return") == []
621
622
623def test_a_disposition_has_to_name_what_each_line_is(tmp_path, monkeypatch):
624 """No default: guessing restock puts damaged goods on the shelf and
625 guessing dispose bins sellable stock."""
626 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
627 created = authorized_return(objects_root)
628 receive(data_dir, created["shipment_id"])
629
630 refused = disposition(objects_root, shipment_id=created["shipment_id"])
631 assert refused["status"] == 409
632 assert "no default" in refused["bad_quantities"][0]["reason"]
633
634
635# --- the money ------------------------------------------------------------------
636
637def test_a_full_refund_pays_back_what_was_paid_for_those_lines(
638 tmp_path, monkeypatch):
639 """The line money plus the tax charged ON that line, computed the way
640 order_totals computed it -- not a number that looks close."""
641 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch,
642 tax_bps=825)
643 created = authorized_return(objects_root)
644 receive(data_dir, created["shipment_id"])
645
646 result = dispositioned(objects_root, data_dir, created, refund="full")
647 assert result["ok"]
648 # One mug at 1200, tax 8.25% floored: 1200 + 99.
649 assert result["refund_cents"] == "1299"
650
651 row = refunds(data_dir)[0]
652 assert row["amount_cents"] == "1299"
653 assert row["payment_id"] == "pay-1"
654 # Stamped by hook_refunds from the payment, never trusted from us.
655 assert row["invoice_id"] == "inv-1"
656 assert row["refunded_on"]
657
658 rma = object_records.get_collection_record(
659 "return_authorizations", created["return_id"], base_dir=data_dir)
660 assert rma["refund_ref"] == f"refunds/{row['id']}"
661 assert result["refund_ref"] == rma["refund_ref"]
662
663
664def test_an_over_large_partial_refund_is_refused_by_the_existing_gate(
665 tmp_path, monkeypatch):
666 """The ceiling is not reimplemented here: app-payments' hook already
667 knows what a payment can give back, and its words are what surfaces --
668 so a customer is quoted the same number whichever door they came
669 through."""
670 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
671 created = authorized_return(objects_root)
672 receive(data_dir, created["shipment_id"])
673
674 refused = dispositioned(objects_root, data_dir, created, refund="partial",
675 refund_cents="99999")
676 assert refused["status"] == 409
677 assert "exceeds the refundable" in refused["refund"]
678 assert "3600" in refused["refund"] # what the payment can give
679 assert "pay-1" in refused["refund"]
680
681 # And nothing happened: no refund, no moves, and the return is still
682 # open for somebody to get right.
683 assert refunds(data_dir) == []
684 assert moves(data_dir, "return") == []
685 parcel = object_records.get_collection_record(
686 "shipments", created["shipment_id"], base_dir=data_dir)
687 assert parcel["status"] == "received"
688
689
690def test_a_partial_refund_within_the_ceiling_is_written(tmp_path, monkeypatch):
691 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
692 created = authorized_return(objects_root)
693 receive(data_dir, created["shipment_id"])
694
695 result = dispositioned(objects_root, data_dir, created, refund="partial",
696 refund_cents="900")
697 assert result["ok"] and result["refund_cents"] == "900"
698 assert refunds(data_dir)[0]["amount_cents"] == "900"
699
700
701def test_refund_none_closes_the_return_silently(tmp_path, monkeypatch):
702 """A restocking-fee-only return, a replacement instead of a refund, a
703 goodwill restock: all ordinary. Warning about them would teach
704 operators to click past warnings."""
705 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
706 created = authorized_return(objects_root)
707 receive(data_dir, created["shipment_id"])
708
709 result = dispositioned(objects_root, data_dir, created)
710 assert result["ok"] and result["moved"] == 1
711 assert result["refund"] == "none"
712 assert result["refund_id"] == "" and result["refund_ref"] == ""
713 assert "warning" not in result and "note" not in result
714 assert refunds(data_dir) == []
715
716 rma = object_records.get_collection_record(
717 "return_authorizations", created["return_id"], base_dir=data_dir)
718 assert rma["status"] == "closed"
719 assert rma["refund_ref"] == ""
720
721
722# --- the page -------------------------------------------------------------------
723
724def form(objects_root, order_id="ord-1", user_id="shop", method="GET", **fields):
725 payload = {"order_id": order_id}
726 if user_id:
727 payload["_identity"] = {"user_id": user_id}
728 if fields:
729 payload["_form"] = fields
730 return run(objects_root, "site_return_form", method, payload)
731
732
733def test_the_return_form_shows_the_shipped_lines(tmp_path, monkeypatch):
734 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
735 body = form(objects_root)["body"]
736 assert "Enamel Mug" in body
737 assert "SO-0001" in body
738 assert ">3<" in body # three of them can come back
739 assert 'name="qty_line-1"' in body
740 assert "No longer wanted" in body
741 # Nothing has been returned yet, so there is no RMA block and no label
742 # placeholder to show.
743 assert "Returns on this order" not in body
744
745
746def test_the_return_form_raises_the_rma_and_shows_it_back(tmp_path, monkeypatch):
747 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
748 result = form(objects_root, method="POST",
749 **{"do": "request", "reason": "damaged",
750 "reason_note": "handle snapped", "qty_line-1": "1"})
751 body = result["body"]
752 assert "authorized" in body
753 assert len(rmas(data_dir)) == 1
754 rma = rmas(data_dir)[0]
755 assert rma["reason"] == "damaged"
756 assert rma["status"] == "authorized"
757 assert "Returns on this order" in body
758 assert "return label will appear here" in body
759 assert "carrier connector" in body
760
761
762def test_the_return_form_surfaces_the_actions_refusal_with_its_numbers(
763 tmp_path, monkeypatch):
764 """Rewording the gate here would guarantee two vocabularies for one
765 rule."""
766 data_dir, objects_root = shop_with_a_return(tmp_path, monkeypatch)
767 result = form(objects_root, method="POST",
768 **{"reason": "damaged", "qty_line-1": "9"})
769 body = result["body"]
770 assert "shipped 3" in body
771 assert "would make 9" in body
772 assert rmas(data_dir) == []
773
774
775def test_the_return_form_turns_away_a_stranger_with_no_credential(
776 tmp_path, monkeypatch):
777 """A visitor with neither a session nor the order's token is offered
778 the two real ways in -- the tracking link from their confirmation
779 email, or sign-in -- and is shown nothing about the order itself.
780 Guests reaching this page WITH a token are tests/test_store_voice.py's
781 subject; this is the case where there is no key at all."""
782 _, objects_root = shop_with_a_return(tmp_path, monkeypatch)
783 body = form(objects_root, user_id="")["body"]
784 assert "tracking link" in body
785 assert "sign in" in body
786 assert "Enamel Mug" not in body
787
788
789def test_the_return_form_is_a_friendly_404_for_an_unknown_order(
790 tmp_path, monkeypatch):
791 _, objects_root = shop_with_a_return(tmp_path, monkeypatch)
792 result = form(objects_root, order_id="no-such-order")
793 assert result["status"] == 404
794 assert "Traceback" not in result["body"]
795
796
797# --- the bench (0.3.0) -------------------------------------------------------
798#
799# The count shipped pointing at /orders: a path this package does not own,
800# serving a list containing none of the rows it counted, because the goods
801# coming back had no page anywhere. The tests below are about the one
802# property that makes a badge worth clicking -- the page it opens has to
803# show what the badge counted -- and about the two choices that follow
804# from it: the index is over SHIPMENTS (an RMA is an intention; the parcel
805# is the thing with a person waiting on it), and it uses `where` rather
806# than `filters` so it renders as the schema's real table instead of a
807# column of raw shipment ids.
808
809import csv # noqa: E402
810import json # noqa: E402
811
812import object_packages # noqa: E402
813
814APP_RETURNS_DIR = PACKAGES / "app-returns"
815
816
817def _returns_seed_rows(name):
818 with open(APP_RETURNS_DIR / "seed" / f"{name}.tsv", newline="") as handle:
819 return list(csv.DictReader(handle, delimiter="\t"))
820
821
822def test_the_bench_lists_the_collection_the_count_actually_reads():
823 """The provider counts inbound shipments, and says in its own docstring
824 that counting return_authorizations would be counting intentions. The
825 page has to agree with it about what a return even is."""
826 provider = (APP_RETURNS_DIR / "objects" / "system" / "return_attention.py").read_text()
827 assert 'object_records.read_collection_records("shipments"' in provider
828
829 rows = [row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench"]
830 assert len(rows) == 1
831 view = rows[0]
832 assert view["route"] == "/returns"
833 blocks = json.loads(view["blocks"])
834 assert len(blocks) == 1
835 block = blocks[0]
836 assert block["kind"] == "list"
837 assert block["collection"] == "shipments"
838
839
840def test_the_bench_is_scoped_with_where_so_it_renders_as_a_real_table():
841 """`filters` would drop the page into the view layer's client-side
842 fallback, which titles each row `title || name || id` -- and a shipment
843 has neither a title nor a name, so every row would read as a raw id.
844 `where` compiles to the server-side narrowing `related` uses and keeps
845 the schema's table, filter bar, search and row cap."""
846 view = next(row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench")
847 block = json.loads(view["blocks"])[0]
848
849 assert block["where"] == {"direction": "inbound"}
850 assert "filters" not in block
851 # The renderer has to actually honour it, or the page silently lists
852 # every outbound parcel too.
853 renderer = (PACKAGES / "app-views" / "objects" / "site" / "view_render.py").read_text()
854 assert "cfg.where = block.where" in renderer
855
856
857def test_the_bench_shows_the_whole_inbound_ladder_not_only_the_undecided():
858 """`received` is what the badge counts, and the bench deliberately shows
859 more than that: a returns bench that hides what is in transit and what
860 was settled yesterday cannot answer either question somebody standing at
861 it asks. The narrowing to `received` is one pick in the filter bar the
862 schema already declares."""
863 view = next(row for row in _returns_seed_rows("views") if row["id"] == "view_returns_bench")
864 block = json.loads(view["blocks"])[0]
865 assert "status" not in block["where"]
866
867 shipments = json.loads((PACKAGES / "app-shipping" / "schemas" / "shipments.json").read_text())
868 assert "status" in shipments["views"]["filter_fields"]
869 assert "received" in next(field for field in shipments["fields"]
870 if field["name"] == "status")["enum"]
871
872
873def test_the_bench_route_points_at_the_generic_renderer_beside_the_return_form():
874 rows = _returns_seed_rows("site_routes")
875 by_id = {row["id"]: row for row in rows}
876
877 assert by_id["route_returns_index"]["pattern"] == "/returns"
878 assert by_id["route_returns_index"]["object_id"] == "site_view_render"
879 # The per-order customer form keeps its own, more specific pattern.
880 assert by_id["route_return_form"]["pattern"] == "/returns/{order_id}"
881
882
883def test_the_package_declares_a_warehouse_door_instead_of_opting_out():
884 manifest = json.loads((APP_RETURNS_DIR / "dbbasic-package.json").read_text())
885 assert "nav_optional" not in manifest
886
887 package = object_packages.get_package("app-returns", root=PACKAGES)
888 entry = package["nav"][0]
889 assert entry["id"] == "returns"
890 assert entry["path"] == "/returns"
891 assert entry["group"] == "Warehouse"
892 assert entry["surface"] == "operator"
893 assert "app-views" in {dep["id"] for dep in package["dependencies"]}
894
895
896def test_the_count_opens_the_bench_and_stays_visible_to_whoever_clears_it():
897 """No nav_id, on purpose. A count bound to a door inherits that door's
898 audience, and this door is filed under the operator tier -- but
899 permissions/rules.json lets ANY signed-in person disposition a parcel,
900 on the stated grounds that the person who opens the box is the person
901 who knows what is in it. Hiding the number from them to keep the menu
902 tidy would undo the reason the queue is counted."""
903 package = object_packages.get_package("app-returns", root=PACKAGES)
904 source = package["attention"][0]
905
906 assert source["path"] == "/returns"
907 assert source["nav_id"] == ""