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_corner_cup.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_corner_cup.py · 72.6 KB · 1423 lines
1"""The counter café: what a Haiku simulation of "Corner Cup" found.
2
3A simulated café ran a day of counter and pickup sales through the HTTP API
4and kept getting the same answer from different directions: a sale that has
5been paid for could still be rewritten in place, two documents about the
6same sale drifted apart, and the staff could not see the shop's own orders
7so they all signed in as the owner. Each test here was written against the
8bug first (it failed), through the HTTP API in process
9(scripts/try_package.py's Sandbox, permission enforcement on), the way a
10cashier, a manager and a customer reach the box.
11"""
12
13from __future__ import annotations
14
15from contextlib import contextmanager
16from pathlib import Path
17
18import json
19
20import pytest
21
22import object_records
23from scripts.try_package import Sandbox
24
25ROOT = Path(__file__).resolve().parents[1]
26
27PACKAGES = ["app-shop", "app-pickup", "app-payments", "app-settings",
28 "app-disputes", "app-kitchen", "app-counter", "app-promotions"]
29
30
31def _put(box, collection, **row):
32 row.setdefault("owner_id", "shop")
33 return object_records.create_collection_record(collection, row, base_dir=box.data_dir)
34
35
36def _rows(box, collection):
37 return object_records.read_collection_records(collection, base_dir=box.data_dir)
38
39
40def _get(box, collection, record_id):
41 return object_records.get_collection_record(collection, record_id, base_dir=box.data_dir)
42
43
44def _setting(box, key, value):
45 status, body = box.call("admin", "POST", "/collections/app_settings/records",
46 {"key": key, "value": value})
47 assert status == 201, body
48
49
50def _sell(box, *items, method="counter", email="guest@example.test"):
51 """A guest counter sale through the public basket and checkout.
52 items: (product_id, quantity) pairs. Returns the checkout answer."""
53 status, cart = box.call("anon", "POST", "/objects/action_cart",
54 {"action": "add", "product_id": items[0][0],
55 "quantity": items[0][1]})
56 assert status == 200, cart
57 for product_id, quantity in items[1:]:
58 status, cart = box.call("anon", "POST", "/objects/action_cart",
59 {"action": "add", "product_id": product_id,
60 "quantity": quantity,
61 "session_token": cart["session_token"]})
62 assert status == 200, cart
63 status, out = box.call("anon", "POST", "/objects/action_checkout",
64 {"session_token": cart["session_token"],
65 "customer_email": email, "fulfillment_method": method})
66 assert status == 200, out
67 return out
68
69
70def _lines(box, collection, parent_field, parent_id):
71 return [row for row in _rows(box, collection) if row.get(parent_field) == parent_id]
72
73
74@contextmanager
75def _cafe_box(enforce=True):
76 with Sandbox(PACKAGES, enforce=enforce) as box:
77 box.add_user("cara", roles=["cashier"])
78 box.add_user("lee", roles=["shift_lead"])
79 box.add_user("mo", roles=["manager"])
80 box.add_user("own", roles=["owner"])
81 box.add_user("cust")
82 _setting(box, "shop.auto_fulfill", "false")
83 _put(box, "locations", id="shelf", name="Shelf", location_type="warehouse")
84 _put(box, "locations", id="cust", name="Customers", location_type="customer")
85 _put(box, "products", id="soup", name="Soup", price_cents="650",
86 product_type="physical", is_active="true")
87 _put(box, "products", id="salad", name="Salad", price_cents="500",
88 product_type="physical", is_active="true")
89 _put(box, "products", id="tea", name="Tea", price_cents="300",
90 product_type="physical", is_active="true")
91 for product_id in ("soup", "salad", "tea"):
92 _put(box, "stock_moves", product_id=product_id, to_location_id="shelf",
93 quantity="20", reason="purchase", unit_cost_cents="200")
94 yield box
95
96
97@pytest.fixture()
98def cafe():
99 with _cafe_box() as box:
100 yield box
101
102
103def _pay(box, invoice_id, amount=None, user="mo"):
104 invoice = _get(box, "invoices", invoice_id)
105 status, body = box.call(user, "POST", "/collections/payments/records",
106 {"invoice_id": invoice_id,
107 "amount_cents": amount or invoice["total_cents"],
108 "method": "cash", "received_on": "2026-11-30"})
109 assert status == 201, body
110 return body
111
112
113# --- 1. staff see the shop's sales -------------------------------------------------
114
115
116@pytest.mark.parametrize("user", ["cara", "lee", "mo"])
117def test_staff_read_the_shops_orders_invoices_payments_refunds_and_disputes(cafe, user):
118 """Checkout files a guest sale under the shop's account, and every grant
119 was owner-scoped, so a cashier or manager listing orders saw none: the
120 simulated staff signed in as the owner, and every act was attributed to
121 one login."""
122 sale = _sell(cafe, ("soup", "1"))
123 payment = _pay(cafe, sale["invoice_id"])
124 _put(cafe, "disputes", kind="product", order_id=sale["order_id"],
125 summary="Soup was cold")
126 for collection, wanted in (("orders", sale["order_id"]),
127 ("invoices", sale["invoice_id"]),
128 ("payments", payment["record"]["id"]
129 if "record" in payment else payment["id"])):
130 status, body = cafe.call(user, "GET", f"/collections/{collection}/records")
131 assert status == 200, body
132 assert wanted in {row["id"] for row in body["records"]}, (collection, body)
133 for collection in ("order_lines", "invoice_lines", "refunds", "disputes"):
134 status, body = cafe.call(user, "GET", f"/collections/{collection}/records")
135 assert status == 200, (collection, body)
136 status, body = cafe.call(user, "GET", "/collections/disputes/records")
137 assert [row["summary"] for row in body["records"]] == ["Soup was cold"]
138
139
140def test_a_customer_still_sees_only_their_own_orders(cafe):
141 """The staff grant is by role: a signed-in customer with no role reads
142 nothing of the guest's sale."""
143 _sell(cafe, ("soup", "1"))
144 for collection in ("orders", "invoices", "payments", "disputes"):
145 status, body = cafe.call("cust", "GET", f"/collections/{collection}/records")
146 assert status == 200, body
147 assert body["records"] == [], collection
148
149
150# --- 2. a sold line is not rewritten in place -----------------------------------------
151
152
153def _sale_lines(box, sale):
154 order_line = _lines(box, "order_lines", "order_id", sale["order_id"])[0]
155 invoice_line = _lines(box, "invoice_lines", "invoice_id", sale["invoice_id"])[0]
156 return order_line, invoice_line
157
158
159def test_checkout_links_each_invoice_line_to_the_order_line_it_bills(cafe):
160 sale = _sell(cafe, ("soup", "1"), ("tea", "2"))
161 order_lines = {row["id"]: row for row in _lines(cafe, "order_lines", "order_id", sale["order_id"])}
162 invoice_lines = _lines(cafe, "invoice_lines", "invoice_id", sale["invoice_id"])
163 assert sorted(row["order_line_id"] for row in invoice_lines) == sorted(order_lines)
164
165
166def test_a_paid_order_line_cannot_be_edited_into_another_item(cafe):
167 """Corner Cup turned a paid soup into a salad by editing the order line
168 and, separately, the invoice line; the invoice read paid with 150 due.
169 The shop's own login, a manager and an admin are all refused."""
170 cafe.add_user("shop", roles=["manager"])
171 sale = _sell(cafe, ("soup", "1"))
172 _pay(cafe, sale["invoice_id"])
173 order_line, invoice_line = _sale_lines(cafe, sale)
174 for user in ("shop", "mo", "admin"):
175 status, body = cafe.call(user, "PUT", f"/collections/order_lines/records/{order_line['id']}",
176 {"description": "Salad", "product_id": "salad",
177 "unit_price_cents": "500"})
178 assert status in ((403, 409) if user == "mo" else (409,)), (user, body)
179 if status == 409:
180 assert body["code"] == "check_refused" and "paid" in body["error"]
181 status, body = cafe.call(user, "PUT", f"/collections/invoice_lines/records/{invoice_line['id']}",
182 {"description": "Salad", "unit_price_cents": "500"})
183 assert status in (403, 409), (user, body)
184 status, body = cafe.call("admin", "PUT", f"/collections/invoice_lines/records/{invoice_line['id']}",
185 {"description": "Salad", "unit_price_cents": "500"})
186 assert status == 409, body
187 for collection, row in (("order_lines", order_line), ("invoice_lines", invoice_line)):
188 status, body = cafe.call("admin", "DELETE", f"/collections/{collection}/records/{row['id']}")
189 assert status == 409, (collection, body)
190 invoice = _get(cafe, "invoices", sale["invoice_id"])
191 assert invoice["total_cents"] == "650" and invoice["balance_due_cents"] == "0"
192 assert _get(cafe, "order_lines", order_line["id"])["description"] == "Soup"
193
194
195def test_a_paid_order_takes_no_new_priced_line_but_a_kitchen_note_still_changes(cafe):
196 sale = _sell(cafe, ("soup", "1"))
197 _pay(cafe, sale["invoice_id"])
198 order_line, _ = _sale_lines(cafe, sale)
199 with pytest.raises(object_records.CheckRefusedError):
200 _put(cafe, "order_lines", order_id=sale["order_id"], description="Cookie",
201 quantity="1", unit_price_cents="250")
202 with pytest.raises(object_records.CheckRefusedError):
203 _put(cafe, "invoice_lines", invoice_id=sale["invoice_id"], description="Cookie",
204 quantity="1", unit_price_cents="250")
205 # A zero-priced line (a remake's ticket line) changes nobody's money.
206 _put(cafe, "order_lines", order_id=sale["order_id"], description="Soup (remake)",
207 quantity="1", unit_price_cents="0")
208 object_records.update_collection_record(
209 "order_lines", order_line["id"], {"line_note": "no croutons"}, base_dir=cafe.data_dir)
210
211
212def test_a_paid_line_keeps_its_unit_but_a_partner_reference_still_changes(cafe):
213 """unit_code (app-exchange's units on lines) says what the quantity
214 counts: ten kilograms and ten bags are different sales, so once money
215 has arrived it freezes with the quantity. A partner's id for the line is
216 a reference, not a term of the sale, and stays writable."""
217 sale = _sell(cafe, ("soup", "1"))
218 _pay(cafe, sale["invoice_id"])
219 order_line, invoice_line = _sale_lines(cafe, sale)
220 for collection, row in (("order_lines", order_line), ("invoice_lines", invoice_line)):
221 with pytest.raises(object_records.CheckRefusedError):
222 object_records.update_collection_record(collection, row["id"], {"unit_code": "KGM"},
223 base_dir=cafe.data_dir)
224 object_records.update_collection_record("order_lines", order_line["id"],
225 {"partner_line_id": "their-7"},
226 base_dir=cafe.data_dir)
227
228
229def test_an_invoiced_unpaid_line_is_not_deleted_out_from_under_its_invoice(cafe):
230 """Deleting a line of an unpaid order left the invoice billing it."""
231 cafe.add_user("shop", roles=["manager"])
232 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
233 order_line, _ = _sale_lines(cafe, sale)
234 status, body = cafe.call("shop", "DELETE", f"/collections/order_lines/records/{order_line['id']}")
235 assert status == 409, body
236 assert "void" in body["error"]
237 status, body = cafe.call("shop", "PUT", f"/collections/order_lines/records/{order_line['id']}",
238 {"quantity": "3"})
239 assert status == 409, body
240 assert len(_lines(cafe, "order_lines", "order_id", sale["order_id"])) == 2
241
242
243def test_an_order_nobody_has_invoiced_is_still_edited_freely(cafe):
244 order = _put(cafe, "orders", number="PO-1", customer_name="Mill", doc_type="purchase")
245 line = _put(cafe, "order_lines", order_id=order["id"], description="Flour",
246 quantity="1", unit_price_cents="900")
247 object_records.update_collection_record("order_lines", line["id"], {"quantity": "2"},
248 base_dir=cafe.data_dir)
249 object_records.delete_collection_record("order_lines", line["id"], base_dir=cafe.data_dir)
250
251
252def test_the_line_freeze_checks_are_declared_on_both_line_schemas():
253 """A check object no schema names never runs (AGENTS.md: wired by the
254 schema, not by its name)."""
255 import json
256 for path, obj in (("packages/app-orders/schemas/order_lines.json", "system_line_freeze"),
257 ("packages/app-invoices/schemas/invoice_lines.json",
258 "system_invoice_line_freeze")):
259 schema = json.loads((ROOT / path).read_text())
260 checks = {c["object"]: c for c in schema["locked_checks"]}
261 assert checks[obj]["lock"] == "ledger"
262 assert checks[obj]["on"]["delete"] is True
263
264
265# --- 3. a void takes an item off the order and its invoice together ------------------
266
267
268def _void(box, line_id, reason="customer_error", user="cara", **extra):
269 return box.call(user, "POST", "/objects/action_counter_void",
270 {"order_line_id": line_id, "reason_code": reason, **extra})
271
272
273def _line_of(box, sale, product_id):
274 return next(row for row in _lines(box, "order_lines", "order_id", sale["order_id"])
275 if row["product_id"] == product_id)
276
277
278def test_a_cashier_voids_an_unpaid_item_from_the_order_and_its_invoice_together(cafe):
279 """Corner Cup deleted the tea from an unpaid order and the invoice kept
280 billing it. A void zeroes the order line, records why and who, and
281 restates the order by exactly that line. The issued invoice keeps its
282 total (decision 1, 2026-11-30: an issued invoice's total never
283 changes): a credit note citing the tea is issued and applied, so the
284 invoice owes exactly what the order now says."""
285 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
286 tea = _line_of(cafe, sale, "tea")
287 status, body = _void(cafe, tea["id"], note="changed their mind")
288 assert status == 200, body
289 order_line = _get(cafe, "order_lines", tea["id"])
290 assert order_line["quantity"] == "0" and order_line["line_total_cents"] == "0"
291 assert order_line["void_reason_code"] == "customer_error"
292 assert order_line["voided_by"] == "cara" and order_line["voided_at"]
293 invoice_line = next(row for row in _lines(cafe, "invoice_lines", "invoice_id", sale["invoice_id"])
294 if row["order_line_id"] == tea["id"])
295 assert invoice_line["quantity"] == "1" and invoice_line["line_total_cents"] == "300"
296 [note_id] = body["credit_note_ids"]
297 note = _get(cafe, "invoices", note_id)
298 assert (note["doc_type"], note["credits_invoice_id"], note["total_cents"],
299 note["reason_code"]) == ("credit_note", sale["invoice_id"], "300", "customer_error")
300 [credit_line] = _lines(cafe, "invoice_lines", "invoice_id", note_id)
301 assert credit_line["credits_line_id"] == invoice_line["id"]
302 order = _get(cafe, "orders", sale["order_id"])
303 invoice = _get(cafe, "invoices", sale["invoice_id"])
304 assert order["total_cents"] == "650" and invoice["total_cents"] == "950"
305 assert invoice["balance_due_cents"] == "650" and invoice["status"] == "sent"
306 # Both rows are still there: the history shows what was rung up.
307 assert len(_lines(cafe, "order_lines", "order_id", sale["order_id"])) == 2
308 status, body = _void(cafe, tea["id"])
309 assert status == 409 and "already voided" in body["error"]
310
311
312def test_a_void_needs_a_reason_code_the_shop_lists(cafe):
313 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
314 tea = _line_of(cafe, sale, "tea")
315 for reason in ("", "because", "goodwill"): # goodwill is not a void reason
316 status, body = _void(cafe, tea["id"], reason=reason)
317 assert status == 422, (reason, body)
318 assert "customer_error" in body["error"]
319 # Codes are data: a manager adds one and it can be cited.
320 status, body = cafe.call("mo", "POST", "/collections/correction_reasons/records",
321 {"code": "spilled", "label": "Spilled at the counter",
322 "applies_to": "void,waste"})
323 assert status == 201, body
324 status, body = _void(cafe, tea["id"], reason="spilled")
325 assert status == 200, body
326 status, body = cafe.call("cara", "POST", "/collections/correction_reasons/records",
327 {"code": "whim", "label": "Whim", "applies_to": "void"})
328 assert status == 403, body
329
330
331def test_a_paid_item_is_not_voided(cafe):
332 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
333 _pay(cafe, sale["invoice_id"])
334 status, body = _void(cafe, _line_of(cafe, sale, "tea")["id"])
335 assert status == 409 and "action_counter_correct" in body["error"]
336
337
338def test_the_void_fields_cannot_be_typed_over_the_api(cafe):
339 """read_only: a PUT cannot fake a void (and skip the invoice)."""
340 cafe.add_user("shop", roles=["manager"])
341 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
342 tea = _line_of(cafe, sale, "tea")
343 status, body = cafe.call("shop", "PUT", f"/collections/order_lines/records/{tea['id']}",
344 {"quantity": "0", "line_total_cents": "0",
345 "voided_at": "2026-11-30T10:00:00Z",
346 "void_reason_code": "customer_error"})
347 assert status in (400, 403, 409), body
348 assert _get(cafe, "order_lines", tea["id"])["quantity"] == "1"
349
350
351def test_a_void_takes_off_exactly_the_tax_the_line_was_stamped_with(cafe):
352 """The void used to refuse where the tax was worked out over the whole
353 bill: how much of it was the tea's was not recorded. Decision 2
354 (2026-11-30): checkout stamps the rate and each line's share on the
355 invoice line, so the void takes off exactly that -- 950 at 10% is 95,
356 the soup carrying 65 and the tea 30 -- from the order, and the credit
357 note gives back the tea and its 30."""
358 _setting(cafe, "shop.tax_rate_bps", "1000")
359 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
360 tea = _line_of(cafe, sale, "tea")
361 billed = next(row for row in _lines(cafe, "invoice_lines", "invoice_id", sale["invoice_id"])
362 if row["order_line_id"] == tea["id"])
363 assert (billed["tax_rate_bps"], billed["line_tax_cents"]) == ("1000", "30")
364 status, body = _void(cafe, tea["id"])
365 assert status == 200, body
366 order = _get(cafe, "orders", sale["order_id"])
367 assert (order["subtotal_cents"], order["tax_cents"], order["total_cents"]) == (
368 "650", "65", "715")
369 invoice = _get(cafe, "invoices", sale["invoice_id"])
370 assert (invoice["total_cents"], invoice["balance_due_cents"]) == ("1045", "715")
371 [note_id] = body["credit_note_ids"]
372 note = _get(cafe, "invoices", note_id)
373 assert (note["subtotal_cents"], note["tax_cents"], note["total_cents"]) == ("300", "30", "330")
374
375
376def test_a_void_still_refuses_where_a_basket_discount_was_given(cafe):
377 """How much of a basket discount an item carried, and whether the
378 discount shrinks when the item comes off, is NOT settled by the owner's
379 decisions (docs/logic-decisions.md, "Open: not settled by these decisions"):
380 the void refuses and changes nothing rather than invent it."""
381 _put(cafe, "promotions", id="pr1", code="TEN", kind="percent", value="1000",
382 is_active="true", stacking="never")
383 status, cart = cafe.call("anon", "POST", "/objects/action_cart",
384 {"action": "add", "product_id": "soup", "quantity": "1"})
385 assert status == 200, cart
386 cafe.call("anon", "POST", "/objects/action_cart",
387 {"action": "add", "product_id": "tea", "quantity": "1",
388 "session_token": cart["session_token"]})
389 status, sale = cafe.call("anon", "POST", "/objects/action_checkout",
390 {"session_token": cart["session_token"], "promo_code": "TEN",
391 "customer_email": "g@example.test", "fulfillment_method": "counter"})
392 assert status == 200 and sale["discount_cents"] == 95, sale
393 tea = _line_of(cafe, sale, "tea")
394 before = _get(cafe, "invoices", sale["invoice_id"])
395 status, body = _void(cafe, tea["id"])
396 assert status == 409 and "discount" in body["error"], body
397 assert _get(cafe, "invoices", sale["invoice_id"]) == before
398 assert _get(cafe, "order_lines", tea["id"])["quantity"] == "1"
399
400
401def test_a_customer_cannot_void(cafe):
402 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
403 status, body = _void(cafe, _line_of(cafe, sale, "tea")["id"], user="cust")
404 assert status == 403, body
405
406
407# --- 4. after payment, a correction is a new record citing the item ------------------
408
409
410def _correct(box, line_id, user="cara", **payload):
411 payload.setdefault("quantity", "1")
412 payload.setdefault("reason_code", "wrong_item_by_staff")
413 return box.call(user, "POST", "/objects/action_counter_correct",
414 {"order_line_id": line_id, **payload})
415
416
417def _paid_sale(box, *items, **sell):
418 sale = _sell(box, *items, **sell)
419 status, body = box.call("cara", "POST", "/objects/action_counter_pay",
420 {"order_id": sale["order_id"], "method": "cash"})
421 assert status == 200, body
422 return sale
423
424
425def test_a_cashier_takes_payment_at_the_counter(cafe):
426 """Corner Cup's cashiers had no way to record the money they took
427 except the owner's login. The action takes the open balance and the
428 ledger still refuses a second payment over it."""
429 sale = _sell(cafe, ("soup", "1"))
430 status, body = cafe.call("cara", "POST", "/objects/action_counter_pay",
431 {"order_id": sale["order_id"], "method": "cash"})
432 assert status == 200 and body["amount_cents"] == 650, body
433 assert _get(cafe, "invoices", sale["invoice_id"])["balance_due_cents"] == "0"
434 status, body = cafe.call("cara", "POST", "/objects/action_counter_pay",
435 {"invoice_id": sale["invoice_id"], "amount_cents": "100"})
436 assert status == 409, body
437 status, body = cafe.call("cust", "POST", "/objects/action_counter_pay",
438 {"invoice_id": sale["invoice_id"]})
439 assert status == 403, body
440
441
442def test_a_paid_item_is_refunded_by_a_line_refund_that_cites_it(cafe):
443 """The soup-for-salad case done right: the charge stays as it was, the
444 refund names the item, how many, why and who approved it."""
445 _setting(cafe, "counter.refund_approval_threshold_cents", "1000")
446 sale = _paid_sale(cafe, ("soup", "1"), ("tea", "1"))
447 soup = _line_of(cafe, sale, "soup")
448 status, body = _correct(cafe, soup["id"], note="made salad by mistake")
449 assert status == 200, body
450 refund = _get(cafe, "refunds", body["refund_id"])
451 assert refund["order_line_id"] == soup["id"] and refund["quantity"] == "1"
452 assert refund["amount_cents"] == "650" and refund["reason_code"] == "wrong_item_by_staff"
453 assert refund["invoice_line_id"]
454 assert _get(cafe, "invoice_lines", refund["invoice_line_id"])["order_line_id"] == soup["id"]
455 # The sale itself is untouched: what was charged stays true.
456 assert _get(cafe, "order_lines", soup["id"])["unit_price_cents"] == "650"
457 assert _get(cafe, "invoices", sale["invoice_id"])["total_cents"] == "950"
458 # The same soup cannot be given back twice, by refund or credit note.
459 status, body = _correct(cafe, soup["id"])
460 assert status == 409 and "already corrected" in body["error"], body
461 status, body = _correct(cafe, soup["id"], settle="credit_note")
462 assert status == 409, body
463
464
465@pytest.fixture()
466def follows(monkeypatch):
467 """Reactions on, the way a box running the daemon has them: replay the
468 change log so system_invoice_status sees the storage-level writes the
469 counter actions make. Returns a function that replays until quiet."""
470 import object_change_dispatch
471
472 def replay(box):
473 for _ in range(8):
474 outcome = object_change_dispatch.dispatch_pending(
475 base_dir=box.data_dir, roots=[box.objects_dir])
476 assert outcome["errors"] == 0, outcome["results"]
477 if not outcome["processed"]:
478 return
479 raise AssertionError("change dispatch never went quiet")
480
481 monkeypatch.setenv(object_change_dispatch.ENABLE_ENV, "true")
482 return replay
483
484
485def _money(box, invoice_id):
486 invoice = _get(box, "invoices", invoice_id)
487 return (invoice["status"], invoice["total_cents"], invoice["credited_cents"],
488 invoice["amount_paid_cents"], invoice["balance_due_cents"])
489
490
491def test_refunding_a_paid_item_is_a_credit_note_and_a_refund_so_nothing_is_dunned(cafe, follows):
492 """Decision 1 (2026-11-30): a debt is cancelled only by a credit note,
493 so "refund this soup" is a credit note (the soup is no longer owed) and
494 a refund (the money goes back). The refund alone used to leave the soup
495 owing on a bill the customer had paid, and the aging pass would have
496 dunned them for it. Refund the rest and the invoice reads refunded."""
497 follows(cafe)
498 sale = _paid_sale(cafe, ("soup", "1"), ("tea", "1"))
499 follows(cafe)
500 assert _money(cafe, sale["invoice_id"]) == ("paid", "950", "0", "950", "0")
501 status, body = _correct(cafe, _line_of(cafe, sale, "soup")["id"], user="mo")
502 assert status == 200, body
503 refund = _get(cafe, "refunds", body["refund_id"])
504 assert refund["credit_note_id"] == body["credit_note_id"]
505 note = _get(cafe, "invoices", body["credit_note_id"])
506 assert (note["doc_type"], note["total_cents"]) == ("credit_note", "650")
507 follows(cafe)
508 assert _money(cafe, sale["invoice_id"]) == ("paid", "950", "650", "300", "0")
509 status, body = _correct(cafe, _line_of(cafe, sale, "tea")["id"], user="mo")
510 assert status == 200, body
511 follows(cafe)
512 assert _money(cafe, sale["invoice_id"]) == ("refunded", "950", "950", "0", "0")
513
514
515def test_a_credit_note_on_a_paid_bill_reads_credit_owed_until_the_money_goes_back(cafe, follows):
516 """A counter credit note on a fully paid invoice made balance_due
517 negative and the status still said paid. Status follows the money: the
518 shop owes the customer 300 (credit_owed) until a refund citing the
519 credit note pays it out, and then the bill is simply paid for what was
520 kept."""
521 follows(cafe)
522 sale = _paid_sale(cafe, ("soup", "1"), ("tea", "1"))
523 status, body = _correct(cafe, _line_of(cafe, sale, "tea")["id"], user="mo",
524 settle="credit_note", reason_code="quality")
525 assert status == 200, body
526 follows(cafe)
527 assert _money(cafe, sale["invoice_id"]) == ("credit_owed", "950", "300", "950", "-300")
528 payment = next(p for p in _rows(cafe, "payments") if p["invoice_id"] == sale["invoice_id"])
529 for amount, expected in (("301", 409), ("300", 201)):
530 status, out = cafe.call("mo", "POST", "/collections/refunds/records",
531 {"payment_id": payment["id"], "amount_cents": amount,
532 "refunded_on": "2026-11-30",
533 "credit_note_id": body["credit_note_id"]})
534 assert status == expected, out
535 follows(cafe)
536 assert _money(cafe, sale["invoice_id"]) == ("paid", "950", "300", "650", "0")
537
538
539def test_a_payment_cannot_pay_what_a_credit_note_already_cancelled(cafe):
540 """The overpayment ceiling knew refunds and not credit notes, so a bill
541 of 950 with the tea voided (credited 300) took a payment of 950 and
542 read 300 overpaid."""
543 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
544 status, body = _void(cafe, _line_of(cafe, sale, "tea")["id"])
545 assert status == 200, body
546 status, body = cafe.call("mo", "POST", "/collections/payments/records",
547 {"invoice_id": sale["invoice_id"], "amount_cents": "950",
548 "method": "cash", "received_on": "2026-11-30"})
549 assert status == 409 and "650" in body["error"], body
550 _pay(cafe, sale["invoice_id"], amount="650")
551 assert _get(cafe, "invoices", sale["invoice_id"])["balance_due_cents"] == "0"
552
553
554def test_a_cashier_needs_a_managers_approval_above_the_threshold(cafe):
555 _setting(cafe, "counter.refund_approval_threshold_cents", "500")
556 sale = _paid_sale(cafe, ("soup", "1"))
557 soup = _line_of(cafe, sale, "soup")
558 status, body = _correct(cafe, soup["id"])
559 assert status == 403 and body["approval_required"] is True, body
560 assert _rows(cafe, "refunds") == []
561 # A cashier cannot approve themselves.
562 status, body = cafe.call("cara", "POST", "/collections/counter_approvals/records",
563 {"kind": "refund", "order_line_id": soup["id"],
564 "max_amount_cents": "650"})
565 assert status == 403, body
566 status, approval = cafe.call("lee", "POST", "/collections/counter_approvals/records",
567 {"kind": "refund", "order_line_id": soup["id"],
568 "max_amount_cents": "650", "reason_code": "quality"})
569 assert status == 201, approval
570 approval_id = approval["record"]["id"] if "record" in approval else approval["id"]
571 status, body = _correct(cafe, soup["id"], approval_id=approval_id, reason_code="quality")
572 assert status == 200, body
573 assert body["approved_by"] == "lee"
574 refund = _get(cafe, "refunds", body["refund_id"])
575 assert refund["approved_by"] == "lee" and refund["approval_id"] == approval_id
576 assert _get(cafe, "counter_approvals", approval_id)["used_for"] == f"refunds/{refund['id']}"
577
578
579def test_a_manager_corrects_without_asking_anybody_and_is_named_the_approver(cafe):
580 sale = _paid_sale(cafe, ("soup", "1"))
581 status, body = _correct(cafe, _line_of(cafe, sale, "soup")["id"], user="mo")
582 assert status == 200, body
583 assert _get(cafe, "refunds", body["refund_id"])["approved_by"] == "mo"
584
585
586def test_a_credit_note_names_the_invoice_and_the_item_it_credits(cafe):
587 sale = _paid_sale(cafe, ("tea", "2"))
588 tea = _line_of(cafe, sale, "tea")
589 status, body = _correct(cafe, tea["id"], user="mo", settle="credit_note",
590 reason_code="quality")
591 assert status == 200, body
592 note = _get(cafe, "invoices", body["credit_note_id"])
593 assert note["doc_type"] == "credit_note" and note["credits_invoice_id"] == sale["invoice_id"]
594 assert note["total_cents"] == "300" and note["reason_code"] == "quality"
595 [credit_line] = _lines(cafe, "invoice_lines", "invoice_id", note["id"])
596 assert credit_line["order_line_id"] == tea["id"] and credit_line["line_total_cents"] == "300"
597 # One tea left to correct, and no more.
598 status, body = _correct(cafe, tea["id"], user="mo", quantity="2")
599 assert status == 409, body
600 status, body = _correct(cafe, tea["id"], user="mo", quantity="1")
601 assert status == 200, body
602
603
604def test_an_unpaid_item_is_voided_not_corrected(cafe):
605 sale = _sell(cafe, ("soup", "1"))
606 status, body = _correct(cafe, _line_of(cafe, sale, "soup")["id"], user="mo")
607 assert status == 409 and "void" in body["error"], body
608
609
610def test_a_refund_cannot_cite_an_item_of_another_sale_or_more_than_was_sold(cafe):
611 """The ceiling is the ledger's locked check, so it holds for a
612 manager's refund over the plain records API too."""
613 first = _paid_sale(cafe, ("soup", "1"))
614 second = _paid_sale(cafe, ("tea", "1"))
615 payment = next(p for p in _rows(cafe, "payments") if p["invoice_id"] == first["invoice_id"])
616 tea = _line_of(cafe, second, "tea")
617 status, body = cafe.call("mo", "POST", "/collections/refunds/records",
618 {"payment_id": payment["id"], "amount_cents": "300",
619 "refunded_on": "2026-11-30", "order_line_id": tea["id"],
620 "quantity": "1"})
621 assert status == 409 and "not on the order" in body["error"], body
622 soup = _line_of(cafe, first, "soup")
623 status, body = cafe.call("mo", "POST", "/collections/refunds/records",
624 {"payment_id": payment["id"], "amount_cents": "300",
625 "refunded_on": "2026-11-30", "order_line_id": soup["id"],
626 "quantity": "2"})
627 assert status == 409 and "more than was sold" in body["error"], body
628
629
630# --- 5. counter and pickup sales move stock when handed over ------------------------
631
632
633def _on_hand(box, product_id):
634 import object_stock
635 return object_stock.total_quantity(product_id, base_dir=box.data_dir)
636
637
638def _sales(box):
639 return [m for m in _rows(box, "stock_moves") if m["reason"] == "sale"]
640
641
642def _hand_over(box, sale, user="cara"):
643 return box.call(user, "POST", "/objects/action_counter_hand_over",
644 {"order_id": sale["order_id"]})
645
646
647def test_a_counter_sale_moves_stock_when_it_is_handed_over(cafe):
648 """Corner Cup sold soup all day and the shelf never went down: only a
649 shipment ever moved stock, and a counter sale has none."""
650 _setting(cafe, "shop.stock_location", "shelf")
651 _setting(cafe, "shop.customer_location", "cust")
652 sale = _paid_sale(cafe, ("soup", "2"), ("tea", "1"))
653 assert _on_hand(cafe, "soup") == 20
654 status, body = _hand_over(cafe, sale)
655 assert status == 200, body
656 assert len(body["moved"]) == 2
657 assert _on_hand(cafe, "soup") == 18 and _on_hand(cafe, "tea") == 19
658 order = _get(cafe, "orders", sale["order_id"])
659 assert order["status"] == "collected" and order["collected_at"]
660 move = next(m for m in _sales(cafe) if m["product_id"] == "soup")
661 assert move["unit_cost_cents"] == "200"
662 assert f"orders/{sale['order_id']}:line/" in move["reference"]
663 # Again: nothing more leaves.
664 status, body = _hand_over(cafe, sale)
665 assert status == 200 and body["moved"] == []
666 assert _on_hand(cafe, "soup") == 18
667
668
669def test_a_hand_over_refuses_without_a_stock_location_and_moves_nothing(cafe):
670 sale = _paid_sale(cafe, ("soup", "1"))
671 status, body = _hand_over(cafe, sale)
672 assert status == 409 and "shop.stock_location" in body["error"], body
673 assert _sales(cafe) == []
674 assert _get(cafe, "orders", sale["order_id"])["status"] != "collected"
675
676
677def test_an_unpaid_counter_sale_is_not_handed_over(cafe):
678 _setting(cafe, "shop.stock_location", "shelf")
679 sale = _sell(cafe, ("soup", "1"))
680 status, body = _hand_over(cafe, sale)
681 assert status == 409 and body["owed_cents"] == 650, body
682 assert _sales(cafe) == []
683
684
685def test_a_voided_item_is_not_handed_over(cafe):
686 _setting(cafe, "shop.stock_location", "shelf")
687 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
688 status, body = _void(cafe, _line_of(cafe, sale, "tea")["id"])
689 assert status == 200, body
690 status, body = cafe.call("cara", "POST", "/objects/action_counter_pay",
691 {"order_id": sale["order_id"]})
692 assert status == 200, body
693 status, body = _hand_over(cafe, sale)
694 assert status == 200, body
695 assert [m["product_id"] for m in _sales(cafe)] == ["soup"]
696
697
698def test_a_shipment_after_a_hand_over_does_not_take_the_goods_off_the_shelf_again(cafe):
699 """Two paths to the same fact (the goods left): the shipment handler
700 subtracts what a hand-over already moved for the line."""
701 import object_execution
702 import python_object_runtime
703 _setting(cafe, "shop.stock_location", "shelf")
704 sale = _paid_sale(cafe, ("soup", "2"))
705 assert _hand_over(cafe, sale)[0] == 200
706 soup = _line_of(cafe, sale, "soup")
707 _put(cafe, "shipments", id="late-parcel", order_id=sale["order_id"],
708 direction="outbound", status="open", service="ground", ship_to_name="Guest")
709 _put(cafe, "shipment_lines", id="late-parcel-1", shipment_id="late-parcel",
710 order_line_id=soup["id"], product_id="soup", description="Soup", quantity="2")
711 for step in ("packed", "shipped"):
712 object_records.update_collection_record("shipments", "late-parcel", {"status": step},
713 base_dir=cafe.data_dir)
714 outcome = object_execution.execute_object(
715 python_object_runtime.PythonObjectRuntime(),
716 object_execution.ObjectExecutionRequest(
717 "system_order_fulfillment", method="EVENT",
718 payload={"collection": "shipments", "record_id": "late-parcel",
719 "action": "update"}))
720 assert outcome.ok, outcome
721 assert _on_hand(cafe, "soup") == 18
722 assert len(_sales(cafe)) == 1
723
724
725def test_a_counter_hand_over_is_what_releases_an_online_hold():
726 """The hold an online order keeps is its lines less what moved for
727 them; a hand-over move names the order line, so it counts."""
728 import object_reservations
729 from decimal import Decimal
730 moves = [{"reference": "orders/o1:line/l1 WEB-1", "quantity": "2"},
731 {"reference": "shipments/s1:line/sl1", "quantity": "1"}]
732 shipment_lines = [{"id": "sl1", "order_line_id": "l2", "quantity": "1"}]
733 assert object_reservations.moved_by_line(moves, shipment_lines) == {
734 "l1": Decimal("2"), "l2": Decimal("1")}
735
736
737def test_setting_an_order_collected_moves_its_goods_when_reactions_run(monkeypatch):
738 """The other door: a counter order marked collected over the API, with
739 event handlers on, moves through system_counter_stock (same marker, so
740 the hand-over and the reaction cannot both move it)."""
741 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
742 with Sandbox(PACKAGES) as box:
743 box.add_user("shop", roles=["manager"])
744 _setting(box, "shop.auto_fulfill", "false")
745 _setting(box, "shop.stock_location", "shelf")
746 _put(box, "locations", id="shelf", name="Shelf", location_type="warehouse")
747 _put(box, "products", id="soup", name="Soup", price_cents="650",
748 product_type="physical", is_active="true")
749 _put(box, "stock_moves", product_id="soup", to_location_id="shelf",
750 quantity="5", reason="purchase", unit_cost_cents="200")
751 sale = _sell(box, ("soup", "1"), method="counter")
752 _pay(box, sale["invoice_id"], user="shop")
753 for step in ("confirmed", "preparing", "ready", "collected"):
754 current = _get(box, "orders", sale["order_id"])["status"]
755 if current == step:
756 continue
757 status, body = box.call("shop", "PUT", f"/collections/orders/records/{sale['order_id']}",
758 {"status": step})
759 assert status == 200, (step, body)
760 assert _on_hand(box, "soup") == 4
761
762
763# --- 6. goodwill is not a refund; a remake links three records -----------------------
764
765
766def _goodwill(box, user="lee", **row):
767 row.setdefault("form", "free_item")
768 row.setdefault("value_cents", "300")
769 row.setdefault("reason_code", "goodwill")
770 status, body = box.call(user, "POST", "/collections/goodwill/records", row)
771 return status, (body.get("record", body) if isinstance(body, dict) else body)
772
773
774def test_goodwill_records_a_kindness_without_saying_the_charge_was_wrong(cafe):
775 """'Charged correctly, goodwill given' had no shape except a refund or
776 an edit of the sale, both of which say the price was a mistake."""
777 sale = _paid_sale(cafe, ("soup", "1"))
778 status, given = _goodwill(cafe, order_id=sale["order_id"], customer_email="guest@example.test",
779 note="waited twenty minutes")
780 assert status == 201, given
781 assert given["owner_id"] == "lee" and given["charge_was_correct"] == "true"
782 assert given["customer_wording"] == "This one is on us."
783 # The sale is exactly as charged and nothing was refunded.
784 assert _get(cafe, "invoices", sale["invoice_id"])["total_cents"] == "650"
785 assert _rows(cafe, "refunds") == []
786 # A cashier cannot give goodwill; a reason not for goodwill is refused.
787 assert _goodwill(cafe, user="cara")[0] == 403
788 status, body = _goodwill(cafe, reason_code="wrong_item_by_staff")
789 assert status == 422, body
790 # Not rewritten afterwards by the manager who gave it.
791 status, body = cafe.call("lee", "PUT", f"/collections/goodwill/records/{given['id']}",
792 {"value_cents": "3000"})
793 assert status in (403, 404), body
794
795
796def test_goodwill_paid_as_money_is_a_refund_capped_by_its_value(cafe):
797 sale = _paid_sale(cafe, ("soup", "1"))
798 status, given = _goodwill(cafe, user="mo", form="money_back", value_cents="200",
799 order_id=sale["order_id"])
800 assert status == 201, given
801 payment = next(p for p in _rows(cafe, "payments") if p["invoice_id"] == sale["invoice_id"])
802 refund = {"payment_id": payment["id"], "refunded_on": "2026-11-30",
803 "reason_code": "goodwill", "goodwill_id": given["id"]}
804 status, body = cafe.call("mo", "POST", "/collections/refunds/records",
805 {**refund, "amount_cents": "150"})
806 assert status == 201, body
807 status, body = cafe.call("mo", "POST", "/collections/refunds/records",
808 {**refund, "amount_cents": "100"})
809 assert status == 409 and "approved for 200" in body["error"], body
810
811
812def test_a_remake_links_the_original_line_a_waste_move_and_a_zero_priced_ticket_line(cafe):
813 _setting(cafe, "shop.stock_location", "shelf")
814 sale = _paid_sale(cafe, ("soup", "1"))
815 soup = _line_of(cafe, sale, "soup")
816 status, body = cafe.call("cara", "POST", "/objects/action_counter_remake",
817 {"order_line_id": soup["id"], "reason_code": "quality",
818 "note": "too salty"})
819 assert status == 200, body
820 remake = _get(cafe, "remakes", body["remake_id"])
821 ticket = _get(cafe, "order_lines", remake["remake_line_id"])
822 waste = _get(cafe, "stock_moves", remake["waste_move_id"])
823 assert remake["original_line_id"] == soup["id"] and remake["owner_id"] == "cara"
824 assert ticket["unit_price_cents"] == "0" and ticket["remake_of_line_id"] == soup["id"]
825 assert waste["reason"] == "waste" and waste["quantity"] == "1"
826 assert waste["unit_cost_cents"] == "200"
827 # The bill is untouched, and the shelf goes down by exactly the two
828 # soups the kitchen used once the order is handed over.
829 assert _get(cafe, "invoices", sale["invoice_id"])["total_cents"] == "650"
830 assert _on_hand(cafe, "soup") == 19
831 assert _hand_over(cafe, sale)[0] == 200
832 assert _on_hand(cafe, "soup") == 18
833
834
835def test_a_remake_after_the_hand_over_wastes_the_new_unit_not_a_third(cafe):
836 _setting(cafe, "shop.stock_location", "shelf")
837 sale = _paid_sale(cafe, ("soup", "1"))
838 assert _hand_over(cafe, sale)[0] == 200
839 assert _on_hand(cafe, "soup") == 19
840 soup = _line_of(cafe, sale, "soup")
841 status, body = cafe.call("cara", "POST", "/objects/action_counter_remake",
842 {"order_line_id": soup["id"], "reason_code": "quality"})
843 assert status == 200, body
844 assert body["waste_counts_for_line"] == body["remake_line_id"]
845 assert _on_hand(cafe, "soup") == 18
846 assert _hand_over(cafe, sale)[1].get("moved") == []
847 assert _on_hand(cafe, "soup") == 18
848
849
850# --- 7. books with no chart of accounts refuse loudly -------------------------------
851
852
853def _run(object_id, **payload):
854 import object_execution
855 import python_object_runtime
856 outcome = object_execution.execute_object(
857 python_object_runtime.PythonObjectRuntime(),
858 object_execution.ObjectExecutionRequest(object_id, method="EVENT", payload=payload))
859 assert outcome.ok, outcome
860 return outcome.result
861
862
863@pytest.fixture()
864def books_cafe(monkeypatch):
865 monkeypatch.setenv("DBBASIC_ENABLE_EVENT_HANDLERS", "true")
866 with Sandbox(PACKAGES + ["app-finance"]) as box:
867 box.add_user("mo", roles=["manager"])
868 _put(box, "locations", id="shelf", name="Shelf", location_type="warehouse")
869 _put(box, "products", id="soup", name="Soup", price_cents="650",
870 product_type="physical", is_active="true")
871 _put(box, "stock_moves", product_id="soup", to_location_id="shelf",
872 quantity="20", reason="purchase", unit_cost_cents="200")
873 yield box
874
875
876def test_waste_with_settings_but_no_chart_writes_no_empty_journal(books_cafe):
877 """Corner Cup set the inventory account settings on a box with no chart
878 of accounts: every waste move left an EMPTY draft journal behind (the
879 header landed, the lines were refused) and nothing said so."""
880 box = books_cafe
881 _setting(box, "inventory.journal.inventory_account", "1300")
882 _setting(box, "inventory.journal.shrinkage_account", "5200")
883 box.add_user("shop", roles=["manager"])
884 status, move = box.call("shop", "POST", "/collections/stock_moves/records",
885 {"product_id": "soup", "from_location_id": "shelf",
886 "quantity": "1", "reason": "waste", "unit_cost_cents": "200",
887 "owner_id": "shop"})
888 assert status == 201, move
889 assert _rows(box, "fin_journals") == []
890 move_id = move["record"]["id"] if "record" in move else move["id"]
891 result = _run("system_stock_books", collection="stock_moves", record_id=move_id,
892 action="create")
893 assert result["ok"] is False and sorted(result["missing_accounts"]) == ["1300", "5200"]
894 assert "chart of accounts" in result["error"]
895 assert _rows(box, "fin_journals") == []
896
897
898def test_waste_with_no_account_settings_says_which_settings_it_needs(books_cafe):
899 box = books_cafe
900 move = _put(box, "stock_moves", product_id="soup", from_location_id="shelf",
901 quantity="1", reason="waste", unit_cost_cents="200")
902 result = _run("system_stock_books", collection="stock_moves", record_id=move["id"],
903 action="create")
904 assert result["ok"] is False
905 assert "inventory.journal.inventory_account" in result["needs_settings"]
906 assert "inventory.journal.inventory_account" in result["error"]
907
908
909def test_a_refund_with_no_account_settings_says_which_settings_it_needs(books_cafe):
910 box = books_cafe
911 sale = _sell(box, ("soup", "1"))
912 _pay(box, sale["invoice_id"])
913 payment = _rows(box, "payments")[0]
914 refund = _put(box, "refunds", payment_id=payment["id"], invoice_id=sale["invoice_id"],
915 amount_cents="100", refunded_on="2026-11-30")
916 result = _run("system_books", collection="refunds", record_id=refund["id"], action="create")
917 assert result["ok"] is False
918 assert result["needs_settings"] == ["payments.journal.cash_account",
919 "payments.journal.revenue_account"]
920 assert _rows(box, "fin_journals") == []
921
922
923# --- 8. the waste log ----------------------------------------------------------------
924
925
926def _waste(box, user="cara", **payload):
927 payload.setdefault("reason_code", "quality")
928 return box.call(user, "POST", "/objects/action_counter_waste", payload)
929
930
931def test_waste_by_count_moves_stock_and_says_who_why_and_what_it_cost(cafe):
932 _setting(cafe, "shop.stock_location", "shelf")
933 status, body = _waste(cafe, mode="count", product_id="soup", quantity="3",
934 destination="compost", note="burnt pot")
935 assert status == 200, body
936 row = _get(cafe, "waste_logs", body["waste_log_id"])
937 assert row["owner_id"] == "cara" and row["reason_code"] == "quality"
938 assert row["estimated_cost_cents"] == "600" and row["destination"] == "compost"
939 move = _get(cafe, "stock_moves", row["stock_move_id"])
940 assert move["reason"] == "waste" and move["quantity"] == "3"
941 assert _on_hand(cafe, "soup") == 17
942
943
944def test_waste_by_weight_estimates_a_cost_per_kilo_and_moves_no_stock(cafe):
945 _setting(cafe, "counter.waste_cost_per_kg_cents", "400")
946 _setting(cafe, "counter.waste_cost_per_kg_cents.coffee_grounds", "50")
947 status, body = _waste(cafe, mode="weight", category="peelings", weight_grams="2250",
948 destination="digester")
949 assert status == 200, body
950 row = _get(cafe, "waste_logs", body["waste_log_id"])
951 assert row["estimated_cost_cents"] == "900" and row["cost_per_kg_cents"] == "400"
952 assert not row.get("stock_move_id")
953 status, body = _waste(cafe, mode="weight", category="coffee_grounds", weight_grams="3000")
954 assert body["estimated_cost_cents"] == 150
955 assert [m for m in _rows(cafe, "stock_moves") if m["reason"] == "waste"] == []
956
957
958def test_weight_with_no_cost_per_kilo_is_recorded_without_pretending_it_cost_nothing(cafe):
959 status, body = _waste(cafe, mode="weight", category="peelings", weight_grams="1000")
960 assert status == 200, body
961 assert body["estimated_cost_cents"] is None and "counter.waste_cost_per_kg_cents" in body["warnings"][0]
962 assert not _get(cafe, "waste_logs", body["waste_log_id"]).get("estimated_cost_cents")
963
964
965def test_a_destination_needing_a_licence_is_recorded_and_warned_about_never_judged(cafe):
966 status, body = _waste(cafe, mode="weight", category="scraps", weight_grams="5000",
967 destination="animal_feed", needs_licence="true")
968 assert status == 200, body
969 row = _get(cafe, "waste_logs", body["waste_log_id"])
970 assert row["needs_licence"] == "true" and "none was recorded" in row["licence_warning"]
971 status, body = _waste(cafe, mode="weight", category="scraps", weight_grams="5000",
972 destination="rendering", needs_licence="true",
973 licence_number="ABP-123", licence_expires_on="2020-01-31")
974 row = _get(cafe, "waste_logs", body["waste_log_id"])
975 assert row["licence_number"] == "ABP-123" and "expired on 2020-01-31" in row["licence_warning"]
976 status, body = _waste(cafe, mode="weight", category="scraps", weight_grams="5000",
977 destination="rendering", needs_licence="true",
978 licence_number="ABP-123", licence_expires_on="2099-01-31")
979 assert _get(cafe, "waste_logs", body["waste_log_id"])["licence_warning"] == ""
980
981
982def test_waste_needs_a_waste_reason_a_stock_location_and_staff(cafe):
983 status, body = _waste(cafe, mode="count", product_id="soup", reason_code="goodwill")
984 assert status == 422, body
985 status, body = _waste(cafe, mode="count", product_id="soup")
986 assert status == 409 and "shop.stock_location" in body["error"], body
987 assert _rows(cafe, "waste_logs") == []
988 status, body = _waste(cafe, user="cust", mode="weight", category="x", weight_grams="1")
989 assert status == 403, body
990 status, body = _waste(cafe, mode="weight", category="x", weight_grams="1", destination="river")
991 assert status == 400, body
992
993
994def test_waste_says_when_the_books_will_not_receive_it(books_cafe):
995 box = books_cafe
996 box.add_user("cara", roles=["cashier"])
997 _setting(box, "shop.stock_location", "shelf")
998 status, body = _waste(box, mode="count", product_id="soup", quantity="1")
999 assert status == 200, body
1000 assert "inventory.journal.inventory_account" in body["books_warning"]
1001 _setting(box, "inventory.journal.inventory_account", "1300")
1002 _setting(box, "inventory.journal.shrinkage_account", "5200")
1003 status, body = _waste(box, mode="count", product_id="soup", quantity="1")
1004 assert "has no account" in body["books_warning"]
1005
1006
1007# --- 9. managers read the history, with the reason; complaints per customer ---------
1008
1009
1010def _history(box, user, **payload):
1011 return box.call(user, "POST", "/objects/action_counter_history", payload)
1012
1013
1014def test_a_manager_reads_who_voided_what_and_why_without_the_admin_token(cafe):
1015 """The change log was admin-token only and never said why: Corner
1016 Cup's managers borrowed the owner's login to ask who changed a line."""
1017 sale = _sell(cafe, ("soup", "1"), ("tea", "1"))
1018 tea = _line_of(cafe, sale, "tea")
1019 assert _void(cafe, tea["id"], note="changed their mind")[0] == 200
1020 status, body = _history(cafe, "lee", collection="order_lines", record_id=tea["id"])
1021 assert status == 200, body
1022 [void] = [c for c in body["changes"] if c["action"] == "update"]
1023 assert void["actor"] == "action_counter_void:cara"
1024 assert void["message"] == "void (customer_error): changed their mind"
1025 status, body = _history(cafe, "lee", collection="invoice_lines")
1026 assert any(c["message"].startswith("void (customer_error)") for c in body["changes"])
1027 # A cashier reads the records but not their history; nobody reads the
1028 # history of a collection outside the shop's sales through this door.
1029 assert _history(cafe, "cara", collection="order_lines")[0] == 403
1030 assert _history(cafe, "lee", collection="app_settings")[0] == 400
1031
1032
1033def test_the_history_hides_a_field_the_caller_may_not_read(cafe):
1034 """A shift lead who may open an order but not its customer's name must not
1035 read the name in the history either, nor see that it changed."""
1036 schema_path = cafe.data_dir / "schemas" / "orders.json"
1037 schema = json.loads(schema_path.read_text())
1038 for field in schema["fields"]:
1039 if field["name"] == "customer_name":
1040 field["permissions"] = {"role:shift_lead": "hidden"}
1041 schema_path.write_text(json.dumps(schema))
1042 order = _put(cafe, "orders", number="O-7", customer_name="Mrs Vane")
1043 object_records.update_collection_record(
1044 "orders", order["id"], {"customer_name": "Mrs Vane-Tempest", "number": "O-8"},
1045 base_dir=cafe.data_dir, actor="mo")
1046 assert "customer_name" not in cafe.call("lee", "GET", f"/collections/orders/records/{order['id']}")[1]["record"]
1047 status, body = _history(cafe, "lee", collection="orders", record_id=order["id"])
1048 assert status == 200 and body["changes"]
1049 assert "Vane" not in json.dumps(body)
1050 [update] = [c for c in body["changes"] if c["action"] == "update"]
1051 assert update["changed_fields"] == ["number"]
1052 # the manager's role is not restricted: they read it all
1053 status, body = _history(cafe, "mo", collection="orders", record_id=order["id"])
1054 assert "Vane-Tempest" in json.dumps(body)
1055
1056
1057def test_the_history_is_whole_when_permissions_are_not_enforced():
1058 """The records API serves the same caller every field with enforcement
1059 off, so the history is not narrower."""
1060 with _cafe_box(enforce=False) as box:
1061 schema_path = box.data_dir / "schemas" / "orders.json"
1062 schema = json.loads(schema_path.read_text())
1063 for field in schema["fields"]:
1064 if field["name"] == "customer_name":
1065 field["permissions"] = {"role:shift_lead": "hidden"}
1066 schema_path.write_text(json.dumps(schema))
1067 order = _put(box, "orders", number="O-7", customer_name="Mrs Vane")
1068 status, body = _history(box, "lee", collection="orders", record_id=order["id"])
1069 assert status == 200 and "Mrs Vane" in json.dumps(body)
1070
1071
1072def test_the_history_shows_only_records_the_caller_may_read(cafe):
1073 _put(cafe, "orders", number="PO-9", customer_name="Mill", doc_type="purchase")
1074 cafe.add_user("stranger", roles=["shift_lead"])
1075 status, body = _history(cafe, "stranger", collection="orders")
1076 assert status == 200 and body["changes"] # staff read every order
1077 cafe.add_user("nobody")
1078 status, body = cafe.call("nobody", "POST", "/objects/action_counter_history",
1079 {"collection": "orders"})
1080 assert status == 403, body
1081
1082
1083def test_an_http_write_can_say_why_and_the_history_keeps_it(cafe):
1084 import asyncio
1085 from scripts import try_package
1086 cafe.add_user("shop", roles=["manager"])
1087 sale = _sell(cafe, ("soup", "1"))
1088 soup = _line_of(cafe, sale, "soup")
1089 headers = cafe.headers("shop") + [("x-dbbasic-change-reason", "no croutons, allergy")]
1090 status, _ = asyncio.run(try_package._asgi(
1091 f"/collections/order_lines/records/{soup['id']}", "PUT", "",
1092 b'{"line_note": "no croutons"}', headers))
1093 assert status == 200
1094 status, body = _history(cafe, "mo", collection="order_lines", record_id=soup["id"])
1095 assert body["changes"][0]["message"] == "no croutons, allergy"
1096
1097
1098def test_complaints_per_customer_per_month(cafe):
1099 _setting(cafe, "shop.stock_location", "shelf")
1100 regular = _paid_sale(cafe, ("soup", "1"), ("tea", "1"), email="Reg@Example.test")
1101 other = _paid_sale(cafe, ("tea", "1"), email="once@example.test")
1102 assert _correct(cafe, _line_of(cafe, regular, "soup")["id"], user="mo",
1103 reason_code="quality")[0] == 200
1104 assert cafe.call("cara", "POST", "/objects/action_counter_remake",
1105 {"order_line_id": _line_of(cafe, regular, "tea")["id"],
1106 "reason_code": "quality"})[0] == 200
1107 assert _goodwill(cafe, order_id=regular["order_id"])[0] == 201
1108 _put(cafe, "disputes", kind="product", order_id=other["order_id"],
1109 customer_email="once@example.test", summary="Cold tea")
1110 status, body = cafe.call("mo", "POST", "/objects/action_counter_customer_history", {})
1111 assert status == 200, body
1112 top, second = body["customers"]
1113 assert top["customer"] == "reg@example.test" and top["complaints"] == 3
1114 [month] = top["months"]
1115 assert (month["refunds"], month["refunded_cents"], month["remakes"], month["goodwill"]) == (
1116 1, 650, 1, 1)
1117 assert second == {"customer": "once@example.test", "complaints": 1,
1118 "months": [{**second["months"][0], "disputes": 1, "complaints": 1}]}
1119 status, body = cafe.call("mo", "POST", "/objects/action_counter_customer_history",
1120 {"customer_email": "once@example.test"})
1121 assert [c["customer"] for c in body["customers"]] == ["once@example.test"]
1122 assert cafe.call("cara", "POST", "/objects/action_counter_customer_history", {})[0] == 403
1123
1124
1125# --- 10. the action is the grant, so each action checks its own scope ---------------
1126#
1127# The counter actions write payments, credit notes, refunds and stock moves
1128# pointing at records the caller may only read; that is deliberate (see
1129# counter_pay's docstring and docs/permissions-model.md "Pointing at a record
1130# you may not act on"). So the action, not the relation check, says who it is
1131# for and what it may touch. A reviewer showed on 0.8.0 that it did not:
1132# with enforcement off a plain user ran them, and a cashier paid draft and
1133# void invoices.
1134
1135
1136def _counter_actions():
1137 import json
1138 manifest = json.loads((ROOT / "packages" / "app-counter" / "dbbasic-package.json")
1139 .read_text(encoding="utf-8"))
1140 return sorted(o["id"] for o in manifest["objects"] if o["id"].startswith("action_"))
1141
1142
1143_WRITTEN = ("payments", "refunds", "invoices", "invoice_lines", "order_lines", "orders",
1144 "stock_moves", "waste_logs", "remakes", "counter_approvals")
1145
1146
1147def _snapshot(box):
1148 import object_collections
1149 out = {}
1150 for collection in _WRITTEN:
1151 try:
1152 out[collection] = sorted(
1153 (row["id"], object_records.compute_record_rev(row)) for row in _rows(box, collection))
1154 except object_collections.CollectionNotFoundError:
1155 out[collection] = []
1156 return out
1157
1158
1159def _customer_sale(box):
1160 """A counter sale whose order, lines and invoice a plain user (cust)
1161 owns, as a signed-in customer's own order is: owning them is what let
1162 one void and pay with enforcement off."""
1163 sale = _sell(box, ("soup", "2"), email="cust@example.test")
1164 for collection, rows in (("orders", [_get(box, "orders", sale["order_id"])]),
1165 ("order_lines", _lines(box, "order_lines", "order_id", sale["order_id"])),
1166 ("invoices", [_get(box, "invoices", sale["invoice_id"])])):
1167 for row in rows:
1168 object_records.update_collection_record(collection, row["id"], {"owner_id": "cust"},
1169 base_dir=box.data_dir)
1170 return sale
1171
1172
1173@pytest.mark.parametrize("enforce", [True, False], ids=["enforcement-on", "enforcement-off"])
1174def test_a_plain_user_is_refused_every_counter_action(enforce):
1175 with _cafe_box(enforce) as box:
1176 _setting(box, "shop.stock_location", "shelf")
1177 sale = _customer_sale(box)
1178 line = _lines(box, "order_lines", "order_id", sale["order_id"])[0]
1179 _put(box, "invoices", id="own-bill", number="B-1", total_cents="5000",
1180 status="sent", owner_id="cust", customer_name="Cust")
1181 payloads = {
1182 "action_counter_pay": {"invoice_id": "own-bill", "method": "cash"},
1183 "action_counter_void": {"order_line_id": line["id"], "reason_code": "customer_error"},
1184 "action_counter_correct": {"order_line_id": line["id"], "reason_code": "quality"},
1185 "action_counter_remake": {"order_line_id": line["id"], "reason_code": "quality"},
1186 "action_counter_waste": {"mode": "count", "product_id": "soup", "quantity": "1",
1187 "reason_code": "quality"},
1188 "action_counter_hand_over": {"order_id": sale["order_id"]},
1189 "action_counter_history": {"collection": "orders"},
1190 "action_counter_customer_history": {},
1191 }
1192 # A new action in the package must be added here, with its own check.
1193 assert sorted(payloads) == _counter_actions()
1194 before = _snapshot(box)
1195 for object_id, payload in payloads.items():
1196 status, body = box.call("cust", "POST", f"/objects/{object_id}", payload)
1197 assert status == 403, (object_id, body)
1198 assert _snapshot(box) == before
1199 # Staff still run them whichever way enforcement is set.
1200 status, body = box.call("cara", "POST", "/objects/action_counter_pay",
1201 {"order_id": sale["order_id"]})
1202 assert status == 200 and body["amount_cents"] == 1300, body
1203 status, body = box.call("lee", "POST", "/objects/action_counter_history",
1204 {"collection": "orders"})
1205 assert status == 200, body
1206
1207
1208def test_a_role_the_rules_do_not_name_for_an_action_is_refused_with_enforcement_off():
1209 """The roles come from the installed rules for each action: a cashier
1210 runs the till but does not read the history, enforcement or not."""
1211 with _cafe_box(enforce=False) as box:
1212 assert box.call("cara", "POST", "/objects/action_counter_history",
1213 {"collection": "orders"})[0] == 403
1214 assert box.call("cara", "POST", "/objects/action_counter_customer_history", {})[0] == 403
1215 assert box.call("admin", "POST", "/objects/action_counter_customer_history", {})[0] == 200
1216
1217
1218def test_a_cashier_pays_only_an_issued_bill_with_money_open(cafe):
1219 """0.8.0 skipped the issued filter when it was handed an invoice_id: a
1220 cashier recorded a 500,000 cash payment on a draft, a void and a credit
1221 note. All of them now get the answer a missing id gets, and nothing is
1222 written."""
1223 _put(cafe, "invoices", id="b2b-draft", number="B-1", total_cents="500000",
1224 status="draft", owner_id="mo", customer_name="Big Client")
1225 _put(cafe, "invoices", id="b2b-void", number="B-2", total_cents="500000",
1226 status="void", owner_id="mo", customer_name="Big Client")
1227 _put(cafe, "invoices", id="b2b-credit", number="CN-1", total_cents="500000",
1228 status="sent", doc_type="credit_note", owner_id="mo", customer_name="Big Client")
1229 _put(cafe, "invoices", id="b2b-quote", number="Q-1", total_cents="500000",
1230 status="sent", doc_type="quote", owner_id="mo", customer_name="Big Client")
1231 before = _snapshot(cafe)
1232 status, missing = cafe.call("cara", "POST", "/objects/action_counter_pay",
1233 {"invoice_id": "no-such-bill", "amount_cents": "500000"})
1234 assert status == 404, missing
1235 for invoice_id in ("b2b-draft", "b2b-void", "b2b-credit", "b2b-quote"):
1236 for user in ("cara", "mo"):
1237 assert cafe.call(user, "POST", "/objects/action_counter_pay",
1238 {"invoice_id": invoice_id, "amount_cents": "500000",
1239 "method": "cash"}) == (404, missing), (invoice_id, user)
1240 assert _snapshot(cafe) == before
1241 # A normal sale still takes its payment, and not more than is open.
1242 sale = _sell(cafe, ("soup", "1"))
1243 status, body = cafe.call("cara", "POST", "/objects/action_counter_pay",
1244 {"invoice_id": sale["invoice_id"], "amount_cents": "651"})
1245 assert status == 409, body
1246 status, body = cafe.call("cara", "POST", "/objects/action_counter_pay",
1247 {"invoice_id": sale["invoice_id"]})
1248 assert status == 200 and body["amount_cents"] == 650, body
1249
1250
1251def test_the_owner_role_takes_payment_at_the_counter(cafe):
1252 """The owner role reads invoices and has no update on them, as every
1253 counter role; reading is what the action needs, so the owner pays."""
1254 sale = _sell(cafe, ("soup", "1"))
1255 status, body = cafe.call("own", "POST", "/objects/action_counter_pay",
1256 {"order_id": sale["order_id"], "method": "card"})
1257 assert status == 200 and body["amount_cents"] == 650, body
1258 assert _get(cafe, "invoices", sale["invoice_id"])["balance_due_cents"] == "0"
1259
1260
1261def _plant_blanket_approval(box, **row):
1262 """An approval naming no item, as 0.8.0 accepted and a box upgraded
1263 from it may still hold: written under the old schema, then the schema
1264 put back."""
1265 import json
1266 path = box.data_dir / "schemas" / "counter_approvals.json"
1267 shipped = path.read_text(encoding="utf-8")
1268 old = json.loads(shipped)
1269 for field in old["fields"]:
1270 field.get("validation", {}).pop("required_when", None)
1271 path.write_text(json.dumps(old), encoding="utf-8")
1272 try:
1273 return object_records.create_collection_record(
1274 "counter_approvals", {"kind": "correction", "max_amount_cents": "99999999", **row},
1275 base_dir=box.data_dir)
1276 finally:
1277 path.write_text(shipped, encoding="utf-8")
1278
1279
1280def test_an_approval_names_the_item_it_approves(cafe):
1281 """0.8.0 accepted an approval with no item and a huge limit (201), and
1282 the action honoured it for any item. One is now refused at creation,
1283 and one already on file is not honoured."""
1284 _setting(cafe, "counter.refund_approval_threshold_cents", "0")
1285 sale = _paid_sale(cafe, ("soup", "1"))
1286 soup = _line_of(cafe, sale, "soup")
1287 for kind in ("correction", "refund", "credit_note", "remake", "goodwill"):
1288 status, body = cafe.call("lee", "POST", "/collections/counter_approvals/records",
1289 {"kind": kind, "max_amount_cents": "99999999"})
1290 assert status == 400 and "order_line_id" in str(body), (kind, body)
1291 assert _rows(cafe, "counter_approvals") == []
1292 planted = _plant_blanket_approval(cafe, owner_id="lee")
1293 before = _snapshot(cafe)
1294 status, body = _correct(cafe, soup["id"], approval_id=planted["id"], reason_code="quality")
1295 assert status == 403 and "does not name the item" in body["error"], body
1296 assert _snapshot(cafe) == before
1297 assert not _get(cafe, "counter_approvals", planted["id"]).get("used_at")
1298 # One naming the item still works.
1299 status, approval = cafe.call("lee", "POST", "/collections/counter_approvals/records",
1300 {"kind": "refund", "order_line_id": soup["id"],
1301 "max_amount_cents": "650"})
1302 assert status == 201, approval
1303 approval_id = approval["record"]["id"] if "record" in approval else approval["id"]
1304 status, body = _correct(cafe, soup["id"], approval_id=approval_id, reason_code="quality")
1305 assert status == 200 and body["approved_by"] == "lee", body
1306
1307
1308def _approve_waste(box, user="lee", **row):
1309 status, body = box.call(user, "POST", "/collections/counter_approvals/records",
1310 {"kind": "waste", **row})
1311 return status, (body.get("record", body) if isinstance(body, dict) else body)
1312
1313
1314def test_a_cashier_writes_off_a_few_alone_and_more_with_an_approval(cafe):
1315 """0.8.0 let a cashier write off any quantity alone (19 of 20 soups on
1316 the shelf). Up to counter.waste_approval_quantity (unset: 3, what the
1317 counter bins in an ordinary entry) needs nobody; above it, a waste
1318 approval naming the product, spent once."""
1319 _setting(cafe, "shop.stock_location", "shelf")
1320 status, body = _waste(cafe, mode="count", product_id="soup", quantity="3")
1321 assert status == 200, body
1322 before = _snapshot(cafe)
1323 status, body = _waste(cafe, mode="count", product_id="soup", quantity="4")
1324 assert status == 403 and body["approval_required"] is True, body
1325 assert _snapshot(cafe) == before
1326 # An approval must name the product and how many.
1327 assert _approve_waste(cafe, max_quantity="10")[0] == 400
1328 assert _approve_waste(cafe, product_id="soup")[0] == 400
1329 assert _approve_waste(cafe, user="cara", product_id="soup", max_quantity="10")[0] == 403
1330 status, tea_ok = _approve_waste(cafe, product_id="tea", max_quantity="10")
1331 assert status == 201, tea_ok
1332 status, small = _approve_waste(cafe, product_id="soup", max_quantity="5")
1333 assert status == 201, small
1334 status, approval = _approve_waste(cafe, product_id="soup", max_quantity="10")
1335 assert status == 201, approval
1336 sale = _sell(cafe, ("soup", "1"))
1337 status, refund_ok = cafe.call("lee", "POST", "/collections/counter_approvals/records",
1338 {"kind": "correction", "max_amount_cents": "99999",
1339 "order_line_id": _line_of(cafe, sale, "soup")["id"]})
1340 assert status == 201, refund_ok
1341 refund_ok = refund_ok["record"]
1342 before = _snapshot(cafe)
1343 for wrong in (tea_ok, small, refund_ok):
1344 status, body = _waste(cafe, mode="count", product_id="soup", quantity="10",
1345 approval_id=wrong["id"])
1346 assert status == 403, (wrong, body)
1347 assert _snapshot(cafe) == before
1348 status, body = _waste(cafe, mode="count", product_id="soup", quantity="10",
1349 approval_id=approval["id"])
1350 assert status == 200, body
1351 row = _get(cafe, "waste_logs", body["waste_log_id"])
1352 assert row["approval_id"] == approval["id"] and row["quantity"] == "10"
1353 assert _get(cafe, "counter_approvals", approval["id"])["used_for"] == f"waste_logs/{row['id']}"
1354 status, body = _waste(cafe, mode="count", product_id="soup", quantity="4",
1355 approval_id=approval["id"])
1356 assert status == 403 and "already been used" in body["error"], body
1357 # A shift lead approves their own, as with corrections.
1358 assert _waste(cafe, user="lee", mode="count", product_id="soup", quantity="4")[0] == 200
1359
1360
1361def test_the_waste_limit_is_a_setting_and_fails_closed(cafe):
1362 _setting(cafe, "shop.stock_location", "shelf")
1363 _setting(cafe, "counter.waste_approval_quantity", "1")
1364 assert _waste(cafe, mode="count", product_id="soup", quantity="1")[0] == 200
1365 assert _waste(cafe, mode="count", product_id="soup", quantity="2")[0] == 403
1366 [setting] = [r for r in _rows(cafe, "app_settings")
1367 if r["key"] == "counter.waste_approval_quantity"]
1368 object_records.update_collection_record("app_settings", setting["id"], {"value": "lots"},
1369 base_dir=cafe.data_dir)
1370 assert _waste(cafe, mode="count", product_id="soup", quantity="1")[0] == 403
1371
1372
1373def test_waste_reads_the_product_as_the_action_and_confirms_no_ids():
1374 """0.8.0 read the product unchecked for any signed-in caller, and its
1375 404 named the id, so anybody could confirm which products exist. The
1376 action is the grant: a staff member wastes a product they cannot read
1377 over the record API (no read grant on products was added for this), a
1378 caller who is not staff is refused before any product lookup, and a
1379 missing id gets one answer, the same for every staff role. A deny rule
1380 the box writes for a role on a product still wins."""
1381 import dataclasses
1382 import object_permission_store
1383 import object_permissions
1384 for enforce in (True, False):
1385 with _cafe_box(enforce) as box:
1386 _setting(box, "shop.stock_location", "shelf")
1387 # The till cannot read the catalogue over the record API...
1388 import object_access
1389 till = object_access.Access({"user_id": "cara", "roles": ["cashier"]},
1390 base_dir=box.data_dir)
1391 assert till.get("products", "soup") is None
1392 if enforce:
1393 assert box.call("cara", "GET", "/collections/products/records/soup")[0] in (403, 404)
1394 # ...and still writes off what it binned.
1395 status, body = _waste(box, mode="count", product_id="soup", quantity="1")
1396 assert status == 200, (enforce, body)
1397 before = _snapshot(box)
1398 answers = {}
1399 for user in ("cara", "lee", "mo", "own"):
1400 status, body = _waste(box, user=user, mode="count",
1401 product_id="no-such-product", quantity="1")
1402 assert status == 404 and "no-such-product" not in body["error"], body
1403 answers[user] = body
1404 assert len({repr(b) for b in answers.values()}) == 1, answers
1405 # Not staff: the same 403 for a real product and a missing one.
1406 real = _waste(box, user="cust", mode="count", product_id="soup", quantity="1")
1407 missing = _waste(box, user="cust", mode="count", product_id="no-such-product",
1408 quantity="1")
1409 assert real[0] == 403 and real == missing, (enforce, real, missing)
1410 assert _snapshot(box) == before
1411 # A deny rule naming the cashier for one product wins, and reads
1412 # as a missing product.
1413 policy = object_permission_store.load_policy(box.data_dir)
1414 hidden = object_permissions.rule_from_dict(
1415 {"effect": "deny", "principal": "role:cashier", "actions": ["read"],
1416 "collection": "products", "row_filter": {"id": "tea"},
1417 "reason": "a product the till does not touch"})
1418 object_permission_store.save_policy(
1419 dataclasses.replace(policy, rules=policy.rules + (hidden,)), box.data_dir)
1420 assert _waste(box, mode="count", product_id="tea", quantity="1") == (
1421 404, answers["cara"])
1422 assert _snapshot(box) == before
1423 assert _waste(box, user="lee", mode="count", product_id="tea", quantity="1")[0] == 200