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_disputes.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_disputes.py · 29.8 KB · 666 lines
1"""Disputes: a customer said something went wrong, and what we did about
2it has to be checkable.
3
4Every property in this file is about one failure, and it is the failure
5nobody inside the shop can see: a dispute marked `resolved` with nothing
6behind it. The row looks finished, the queue count goes down, the badge
7turns green, and the only person who knows the money never moved is the
8customer still waiting. So the gate is tested from both doors -- the
9generic write path a form uses (hook_disputes) and the action that also
10composes the compensating record -- because trusted server-side writes
11bypass hooks by design, and a rule that only holds on one of the two
12doors is a rule with a door left open.
13
14The three that cost real money if they are wrong. A refund defers to
15app-payments' existing ceiling and surfaces that gate's refusal in its
16own words, so a customer is quoted the same number whichever door their
17claim came through. A credit refuses honestly on a server with no wallet
18app rather than closing the dispute as though credit had been issued --
19"we cannot do that here" is a fine answer and "sorted!" is not. And a
20dispute resolved twice refunds once: retries, double clicks and replayed
21queue entries are ordinary, and a customer's money going back twice is
22not.
23"""
24
25import csv
26import json
27import pathlib
28import shutil
29
30from conftest import stage_collection
31
32import object_execution
33import object_packages
34import object_records
35import python_object_runtime
36
37REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
38PACKAGES = REPO_ROOT / "packages"
39APP_DISPUTES_DIR = PACKAGES / "app-disputes"
40DISPUTES_OBJECTS = APP_DISPUTES_DIR / "objects"
41PAYMENTS_OBJECTS = PACKAGES / "app-payments" / "objects"
42RUNTIME = python_object_runtime.PythonObjectRuntime()
43
44
45def setup_env(tmp_path, monkeypatch, *, wallets=True):
46 """A data dir with every collection this slice touches, and ONE object
47 root holding both packages' objects.
48
49 The merged root is not a convenience: action_resolve_dispute asks
50 app-payments' hook_refunds what a payment can give back rather than
51 deciding for itself, and asks its own hook_disputes what a resolution
52 must name, so both have to resolve by id the way they will in
53 production.
54
55 `wallets=False` stages a server with no app-billing at all -- no
56 wallets, no wallet_entries -- which is the ordinary case for a shop
57 that does not sell store credit and the case the credit path has to
58 refuse honestly in.
59 """
60 data_dir = tmp_path / "data"
61 staged = [("app-disputes", "disputes"),
62 ("app-orders", "orders"), ("app-orders", "order_lines"),
63 ("app-catalog", "products"),
64 ("app-shipping", "shipments"),
65 ("app-invoices", "invoices"),
66 ("app-payments", "payments"), ("app-payments", "refunds")]
67 if wallets:
68 staged += [("app-billing", "wallets"), ("app-billing", "wallet_entries")]
69 for pkg, name in staged:
70 stage_collection(data_dir, pkg, name)
71
72 objects_root = tmp_path / "objects"
73 for source in (DISPUTES_OBJECTS, PAYMENTS_OBJECTS):
74 shutil.copytree(source, objects_root, dirs_exist_ok=True)
75
76 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
77 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
78 return data_dir, objects_root
79
80
81def run(objects_root, object_id, method, payload):
82 return object_execution.execute_object(
83 RUNTIME,
84 object_execution.ObjectExecutionRequest(
85 object_id, method=method, payload=payload),
86 roots=[objects_root]).result
87
88
89# --- fixtures shaped like a real shop -----------------------------------------
90
91def product(data_dir, product_id="p1", name="Enamel Mug", cents=1200):
92 return object_records.create_collection_record(
93 "products",
94 {"id": product_id, "name": name, "sku": product_id.upper(),
95 "product_type": "physical", "price_cents": str(cents),
96 "currency": "USD", "is_active": "true", "owner_id": "shop"},
97 base_dir=data_dir)
98
99
100def order(data_dir, order_id="ord-1", *, status="delivered", number="SO-0001",
101 owner="shop", **fields):
102 record = {"id": order_id, "doc_type": "sale", "number": number,
103 "customer_name": "Ada Lovelace",
104 "customer_email": "ada@example.test", "currency": "USD",
105 "status": "draft", "order_date": "2026-07-01", "owner_id": owner}
106 record.update({k: str(v) for k, v in fields.items()})
107 object_records.create_collection_record("orders", record,
108 base_dir=data_dir)
109 for step in ("confirmed", "shipped", status):
110 current = object_records.get_collection_record(
111 "orders", order_id, base_dir=data_dir)["status"]
112 if step not in ("draft", current):
113 object_records.update_collection_record(
114 "orders", order_id, {"status": step},
115 base_dir=data_dir, actor="test")
116 if step == status:
117 break
118 return object_records.get_collection_record("orders", order_id,
119 base_dir=data_dir)
120
121
122def order_line(data_dir, line_id, order_id="ord-1", *, product_id="p1",
123 description="Enamel Mug", quantity="3", cents=1200):
124 total = int(float(quantity) * cents)
125 return object_records.create_collection_record(
126 "order_lines",
127 {"id": line_id, "order_id": order_id, "product_id": product_id,
128 "description": description, "quantity": str(quantity),
129 "unit_price_cents": str(cents), "line_total_cents": str(total),
130 "tax_rate_bps": "0", "line_tax_cents": "0", "owner_id": "shop"},
131 base_dir=data_dir)
132
133
134def paid(data_dir, *, cents=3600, order_id="ord-1", invoice_id="inv-1"):
135 """An order paid for the way app-shop's checkout leaves it."""
136 object_records.create_collection_record(
137 "invoices",
138 {"id": invoice_id, "number": "SO-0001", "customer_name": "Ada Lovelace",
139 "customer_email": "ada@example.test", "status": "sent",
140 "issue_date": "2026-07-01", "due_date": "2026-07-15",
141 "subtotal_cents": str(cents), "total_cents": str(cents),
142 "owner_id": "shop"},
143 base_dir=data_dir)
144 object_records.update_collection_record(
145 "orders", order_id, {"invoice_id": invoice_id},
146 base_dir=data_dir, actor="test")
147 return object_records.create_collection_record(
148 "payments",
149 {"id": "pay-1", "invoice_id": invoice_id, "amount_cents": str(cents),
150 "method": "card", "received_on": "2026-07-02", "status": "received",
151 "owner_id": "shop"},
152 base_dir=data_dir)
153
154
155def dispute(data_dir, dispute_id="dis-1", *, kind="delivery", status="open",
156 **fields):
157 record = {"id": dispute_id, "kind": kind, "order_id": "ord-1",
158 "customer_email": "ada@example.test",
159 "summary": "Parcel never arrived", "status": status,
160 "opened_by": "shop", "owner_id": "shop"}
161 record.update({k: str(v) for k, v in fields.items()})
162 return object_records.create_collection_record("disputes", record,
163 base_dir=data_dir)
164
165
166def wallet(data_dir, wallet_id="wal-1", owner="ada@example.test"):
167 return object_records.create_collection_record(
168 "wallets",
169 # balance_minor is a rollup over the entries and refuses to be
170 # written, which is the point of app-billing's ledger: the entries
171 # ARE the balance.
172 {"id": wallet_id, "owner_id": owner, "is_active": "true"},
173 base_dir=data_dir)
174
175
176def disputes(data_dir):
177 return object_records.read_collection_records("disputes", base_dir=data_dir)
178
179
180def refunds(data_dir):
181 return object_records.read_collection_records("refunds", base_dir=data_dir)
182
183
184def orders(data_dir):
185 return object_records.read_collection_records("orders", base_dir=data_dir)
186
187
188def entries(data_dir):
189 return object_records.read_collection_records("wallet_entries",
190 base_dir=data_dir)
191
192
193def gate(objects_root, record, action="update"):
194 """The generic HTTP write path's door: what a form posting straight at
195 the collection would hit."""
196 return run(objects_root, "hook_disputes", "BEFORE_WRITE",
197 {"action": action, "collection": "disputes", "record": record})
198
199
200def resolve(objects_root, **payload):
201 return run(objects_root, "action_resolve_dispute", "POST", payload)
202
203
204def shop_with_a_dispute(tmp_path, monkeypatch, *, cents=3600, wallets=True,
205 **dispute_fields):
206 data_dir, objects_root = setup_env(tmp_path, monkeypatch, wallets=wallets)
207 product(data_dir)
208 order(data_dir)
209 order_line(data_dir, "line-1")
210 paid(data_dir, cents=cents)
211 dispute(data_dir, **dispute_fields)
212 return data_dir, objects_root
213
214
215# --- the gate: a dispute cannot be resolved without a resolution ----------------
216
217def test_resolving_with_no_resolution_at_all_is_refused(tmp_path, monkeypatch):
218 """The load-bearing rule, at the door a form would come through. A
219 dispute closed with nothing behind it is how a customer gets told it
220 is sorted when nothing happened."""
221 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
222 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
223 "summary": "Parcel never arrived"})
224 assert refused["status"] == 400
225 assert "dis-1" in refused["error"]
226 assert "resolution_kind" in refused["error"]
227 assert "told it is sorted when nothing happened" in refused["error"]
228
229
230def test_a_dispute_that_is_not_being_resolved_is_none_of_the_gates_business(
231 tmp_path, monkeypatch):
232 """The gate is on the ENDING. Every other status is somebody's work in
233 progress, and a hook with opinions about all of them would be a hook
234 people route around."""
235 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
236 for status in ("open", "investigating", "withdrawn"):
237 assert gate(objects_root, {"id": "dis-1", "status": status}) is None
238
239
240def test_no_action_needs_a_reason(tmp_path, monkeypatch):
241 """A legitimate ending -- plenty of claims are not ours to compensate --
242 but a bare no_action is indistinguishable from a queue somebody
243 cleared to make the number go down."""
244 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
245 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
246 "resolution_kind": "no_action"})
247 assert refused["status"] == 400
248 assert "no reason" in refused["error"]
249 assert "resolution_note" in refused["error"]
250
251 allowed = gate(objects_root, {"id": "dis-1", "status": "resolved",
252 "resolution_kind": "no_action",
253 "resolution_note": "Claimed 40 days after "
254 "delivery, outside the "
255 "30-day window."})
256 assert allowed is None
257
258
259def test_a_compensating_resolution_must_name_a_reference(tmp_path, monkeypatch):
260 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
261 for kind, collection in (("refund", "refunds"),
262 ("replacement", "orders"),
263 ("credit", "wallet_entries")):
264 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
265 "resolution_kind": kind})
266 assert refused["status"] == 400, kind
267 assert f"{collection}/{{id}}" in refused["error"], kind
268
269
270def test_a_reference_into_the_wrong_collection_is_refused_by_name(
271 tmp_path, monkeypatch):
272 """refunds hold money that went back, orders hold goods that will go
273 out, wallet_entries hold credit somebody can spend. A refund pointing
274 at an order is a story about something that did not happen."""
275 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
276 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
277 "resolution_kind": "refund",
278 "resolution_ref": "orders/ord-1"})
279 assert refused["status"] == 409
280 assert "says refund but points at orders/ord-1" in refused["error"]
281 assert "A refund resolution lives in refunds" in refused["error"]
282
283
284def test_a_reference_that_resolves_to_nothing_is_refused(tmp_path, monkeypatch):
285 """A plausible-looking pointer at nothing is strictly worse than a
286 blank one: a blank field is visibly unfinished and 'refunds/abc123'
287 reads as done."""
288 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
289 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
290 "resolution_kind": "refund",
291 "resolution_ref": "refunds/never-existed"})
292 assert refused["status"] == 409
293 assert "names no record in refunds" in refused["error"]
294
295
296def test_a_reference_that_resolves_is_allowed_through(tmp_path, monkeypatch):
297 """The gate has to say yes to a real one, or it is not a gate, it is a
298 wall."""
299 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
300 object_records.create_collection_record(
301 "refunds",
302 {"id": "ref-1", "payment_id": "pay-1", "invoice_id": "inv-1",
303 "amount_cents": "1200", "refunded_on": "2026-07-20",
304 "owner_id": "shop"},
305 base_dir=data_dir)
306 assert gate(objects_root, {"id": "dis-1", "status": "resolved",
307 "resolution_kind": "refund",
308 "resolution_ref": "refunds/ref-1"}) is None
309
310
311def test_a_bare_id_is_not_a_reference(tmp_path, monkeypatch):
312 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
313 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
314 "resolution_kind": "refund",
315 "resolution_ref": "ref-1"})
316 assert refused["status"] == 400
317 assert "is not a reference" in refused["error"]
318
319
320def test_the_credit_gate_names_the_missing_app_rather_than_shrugging(
321 tmp_path, monkeypatch):
322 """On a server with no app-billing there is no wallet_entries
323 collection at all, and 'credit' is not a resolution this shop can
324 carry out. Saying which app is missing is the difference between a
325 refusal somebody can act on and one they can only be annoyed by."""
326 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch,
327 wallets=False)
328 refused = gate(objects_root, {"id": "dis-1", "status": "resolved",
329 "resolution_kind": "credit",
330 "resolution_ref": "wallet_entries/x"})
331 assert refused["status"] == 409
332 assert "no wallet_entries collection on this server" in refused["error"]
333 assert "app-billing" in refused["error"]
334
335
336# --- the action: the one place a dispute and its compensation compose ----------
337
338def test_resolving_with_a_refund_writes_the_refund_and_closes_the_dispute(
339 tmp_path, monkeypatch):
340 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
341 result = resolve(objects_root, dispute_id="dis-1",
342 resolution_kind="refund", amount_cents="1200",
343 note="Carrier lost it", today="2026-07-20")
344 assert result["ok"] is True
345 assert result["resolution_kind"] == "refund"
346 assert result["refund_id"]
347 assert result["resolution_ref"] == f"refunds/{result['refund_id']}"
348
349 row = refunds(data_dir)[0]
350 assert row["amount_cents"] == "1200"
351 assert row["payment_id"] == "pay-1"
352 # Stamped by hook_refunds from the payment, never trusted from us --
353 # which is the proof the refund really went through that gate.
354 assert row["invoice_id"] == "inv-1"
355 assert "disputes/dis-1" in row["reason"]
356
357 closed = object_records.get_collection_record("disputes", "dis-1",
358 base_dir=data_dir)
359 assert closed["status"] == "resolved"
360 assert closed["resolution_ref"] == result["resolution_ref"]
361 assert closed["resolution_note"] == "Carrier lost it"
362 assert closed["resolved_at"]
363
364
365def test_a_refund_resolution_defers_to_the_existing_ceiling_and_says_its_words(
366 tmp_path, monkeypatch):
367 """The ceiling is not reimplemented here: app-payments' hook already
368 knows what a payment can give back, and its words are what surfaces --
369 so a customer is quoted the same number whether they came through a
370 return or a dispute."""
371 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
372 refused = resolve(objects_root, dispute_id="dis-1",
373 resolution_kind="refund", amount_cents="99999")
374 assert refused["status"] == 409
375 assert "exceeds the refundable" in refused["error"]
376 assert "3600" in refused["error"] # what the payment can give
377 assert "pay-1" in refused["error"]
378
379 # And nothing happened: no refund, and the dispute is still open for
380 # somebody to get right.
381 assert refunds(data_dir) == []
382 assert object_records.get_collection_record(
383 "disputes", "dis-1", base_dir=data_dir)["status"] == "open"
384
385
386def test_resolving_twice_refunds_once(tmp_path, monkeypatch):
387 """The most important test in the slice. Retries, double clicks and
388 replayed queue entries are ordinary; a customer's money going back
389 twice is not."""
390 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
391 first = resolve(objects_root, dispute_id="dis-1",
392 resolution_kind="refund", amount_cents="1200")
393 assert first["ok"] and first["refund_id"]
394 assert len(refunds(data_dir)) == 1
395
396 again = resolve(objects_root, dispute_id="dis-1",
397 resolution_kind="refund", amount_cents="1200")
398 assert again["ok"] is True
399 assert "already resolved" in again["note"]
400 assert again["refund_id"] == ""
401 assert again["resolution_ref"] == first["resolution_ref"]
402 assert len(refunds(data_dir)) == 1
403
404 # Even asked for a different ending, and even for one that would have
405 # composed a different record: the dispute is over.
406 third = resolve(objects_root, dispute_id="dis-1",
407 resolution_kind="replacement")
408 assert third["ok"] is True and "already resolved" in third["note"]
409 assert len(refunds(data_dir)) == 1
410 assert len(orders(data_dir)) == 1
411
412
413def test_no_action_through_the_action_still_needs_a_reason(tmp_path, monkeypatch):
414 """The action does not restate the rule -- it asks hook_disputes -- so
415 the refusal a caller sees here is word for word the one the generic
416 write path gives."""
417 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
418 refused = resolve(objects_root, dispute_id="dis-1",
419 resolution_kind="no_action")
420 assert refused["status"] == 400
421 assert "resolution_note" in refused["error"]
422 assert object_records.get_collection_record(
423 "disputes", "dis-1", base_dir=data_dir)["status"] == "open"
424
425 done = resolve(objects_root, dispute_id="dis-1",
426 resolution_kind="no_action",
427 note="Tracking shows delivered and signed for by the "
428 "customer's neighbour.")
429 assert done["ok"] is True
430 assert done["resolution_ref"] == ""
431 closed = object_records.get_collection_record("disputes", "dis-1",
432 base_dir=data_dir)
433 assert closed["status"] == "resolved"
434 assert closed["resolution_kind"] == "no_action"
435 assert "neighbour" in closed["resolution_note"]
436 assert refunds(data_dir) == []
437
438
439def test_a_credit_with_no_wallet_app_refuses_honestly(tmp_path, monkeypatch):
440 """Store credit is a wallet entry and wallets are app-billing's, which
441 is deliberately not a dependency of this package. A shop that does not
442 sell credit should hear 'we cannot do that here', not have a dispute
443 closed as though credit had been issued."""
444 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch,
445 wallets=False)
446 refused = resolve(objects_root, dispute_id="dis-1",
447 resolution_kind="credit", amount_cents="1200")
448 assert refused["status"] == 409
449 assert refused["missing_app"] == "app-billing"
450 assert "app-billing" in refused["error"]
451 assert "not installed" in refused["error"]
452 assert object_records.get_collection_record(
453 "disputes", "dis-1", base_dir=data_dir)["status"] == "open"
454
455
456def test_a_credit_with_a_wallet_writes_one_entry_the_customer_can_spend(
457 tmp_path, monkeypatch):
458 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
459 wallet(data_dir)
460 result = resolve(objects_root, dispute_id="dis-1",
461 resolution_kind="credit", amount_cents="500",
462 note="Goodwill for the delay")
463 assert result["ok"] is True
464 assert result["resolution_ref"] == f"wallet_entries/{result['wallet_entry_id']}"
465
466 row = entries(data_dir)[0]
467 assert row["wallet_id"] == "wal-1"
468 # Positive: credit is money going TO the customer, and the sign
469 # convention is the ledger's rather than ours.
470 assert row["amount_minor"] == "500"
471 assert row["generated_from"] == "disputes/dis-1"
472 assert refunds(data_dir) == []
473
474
475def test_a_credit_with_nowhere_to_land_refuses_rather_than_inventing_a_wallet(
476 tmp_path, monkeypatch):
477 """A shop that sells to guests has no wallet for most of its
478 customers, and a credit issued into a wallet nobody owns is a number
479 that never becomes money."""
480 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
481 refused = resolve(objects_root, dispute_id="dis-1",
482 resolution_kind="credit", amount_cents="500")
483 assert refused["status"] == 409
484 assert refused["missing_wallet"] == "no_wallet_for_customer"
485 assert entries(data_dir) == []
486
487
488def test_a_replacement_raises_a_confirmed_no_charge_order_that_references_the_original(
489 tmp_path, monkeypatch):
490 """Confirmed, not draft: the order schema's own words are that a draft
491 is not a commitment, and a resolution pointing at a document that
492 promises nothing is exactly what the gate exists to prevent. Zero
493 price, because the customer already paid on the order being argued
494 about."""
495 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
496 result = resolve(objects_root, dispute_id="dis-1",
497 resolution_kind="replacement", today="2026-07-20")
498 assert result["ok"] is True
499 replacement = object_records.get_collection_record(
500 "orders", result["order_id"], base_dir=data_dir)
501
502 assert replacement["doc_type"] == "sale"
503 assert replacement["number"] == "SO-0001-R"
504 assert replacement["status"] == "confirmed"
505 assert replacement["customer_email"] == "ada@example.test"
506 assert "disputes/dis-1" in replacement["notes"]
507 assert "orders/ord-1" in replacement["notes"]
508 # NOT linked_order_id: that field means the drop-ship counterpart and
509 # nothing else, because action_dropship_order's stock rule reads it.
510 assert replacement["linked_order_id"] == ""
511
512 lines = [row for row in object_records.read_collection_records(
513 "order_lines", base_dir=data_dir)
514 if row["order_id"] == result["order_id"]]
515 assert len(lines) == 1
516 assert lines[0]["description"] == "Enamel Mug"
517 assert lines[0]["quantity"] == "3"
518 assert lines[0]["unit_price_cents"] == "0"
519 assert lines[0]["line_total_cents"] == "0"
520
521 closed = object_records.get_collection_record("disputes", "dis-1",
522 base_dir=data_dir)
523 assert closed["resolution_ref"] == f"orders/{result['order_id']}"
524
525
526def test_a_withdrawn_dispute_is_not_something_to_compensate(tmp_path,
527 monkeypatch):
528 """The customer dropped it. Paying out on a claim nobody is making is
529 a payment with no argument behind it -- and filing withdrawals under
530 resolved would salt every 'what did we pay out' report with claims
531 that cost nothing."""
532 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch,
533 status="withdrawn")
534 refused = resolve(objects_root, dispute_id="dis-1",
535 resolution_kind="refund", amount_cents="1200")
536 assert refused["status"] == 409
537 assert "withdrawn" in refused["error"]
538 assert refunds(data_dir) == []
539
540
541def test_an_unknown_resolution_kind_is_refused_before_anything_is_written(
542 tmp_path, monkeypatch):
543 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
544 refused = resolve(objects_root, dispute_id="dis-1",
545 resolution_kind="apology", amount_cents="1200")
546 assert refused["status"] == 400
547 assert "Unknown resolution_kind" in refused["error"]
548 assert refunds(data_dir) == []
549
550
551def test_an_unknown_dispute_is_a_friendly_404(tmp_path, monkeypatch):
552 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
553 refused = resolve(objects_root, dispute_id="nope",
554 resolution_kind="no_action", note="x")
555 assert refused["status"] == 404
556 assert "No such dispute" in refused["error"]
557
558
559# --- the queue and the door ----------------------------------------------------
560
561def test_open_disputes_surface_as_attention_and_investigating_ones_do_not(
562 tmp_path, monkeypatch):
563 """The number exists to find the claims nobody has picked up. A count
564 that also included work in progress could never reach zero, which is
565 how a badge stops meaning anything."""
566 data_dir, objects_root = shop_with_a_dispute(tmp_path, monkeypatch)
567 dispute(data_dir, "dis-2", kind="payment", summary="Charged twice")
568 dispute(data_dir, "dis-3", kind="product", summary="Wrong size",
569 status="open")
570 object_records.update_collection_record(
571 "disputes", "dis-3", {"status": "investigating"},
572 base_dir=data_dir, actor="test")
573
574 counted = run(objects_root, "system_dispute_attention", "COUNT", {})
575 assert counted["count"] == 2
576
577 resolve(objects_root, dispute_id="dis-1", resolution_kind="no_action",
578 note="Delivered and signed for.")
579 assert run(objects_root, "system_dispute_attention", "COUNT",
580 {})["count"] == 1
581
582
583def test_the_count_has_no_opinion_on_a_server_with_no_disputes_collection(
584 tmp_path, monkeypatch):
585 """A missing collection reads as zero -- a server with no disputes app
586 has no disputes -- rather than raising and parking a stale number in
587 the rollup."""
588 data_dir = tmp_path / "data"
589 stage_collection(data_dir, "app-orders", "orders")
590 objects_root = tmp_path / "objects"
591 shutil.copytree(DISPUTES_OBJECTS, objects_root, dirs_exist_ok=True)
592 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
593 assert run(objects_root, "system_dispute_attention", "COUNT",
594 {}) == {"count": 0}
595
596
597def _seed_rows(name):
598 with open(APP_DISPUTES_DIR / "seed" / f"{name}.tsv", newline="") as handle:
599 return list(csv.DictReader(handle, delimiter="\t"))
600
601
602def test_the_bench_lists_the_collection_the_count_actually_reads():
603 """A badge that disagrees with the page it opens is worse than no
604 badge. The provider counts disputes, so the index is over disputes."""
605 provider = (DISPUTES_OBJECTS / "system" / "dispute_attention.py").read_text()
606 assert 'object_records.read_collection_records("disputes"' in provider
607
608 view = next(row for row in _seed_rows("views")
609 if row["id"] == "view_disputes_bench")
610 assert view["route"] == "/disputes"
611 blocks = json.loads(view["blocks"])
612 assert len(blocks) == 1
613 assert blocks[0]["kind"] == "list"
614 assert blocks[0]["collection"] == "disputes"
615
616
617def test_the_bench_shows_the_whole_ladder_not_only_the_untouched():
618 """`open` is what the badge counts, and the bench deliberately shows
619 more: somebody standing at it needs to see what is in flight and what
620 was settled yesterday. The narrowing is one pick in the filter bar the
621 schema already declares."""
622 view = next(row for row in _seed_rows("views")
623 if row["id"] == "view_disputes_bench")
624 assert "where" not in json.loads(view["blocks"])[0]
625
626 schema = json.loads(
627 (APP_DISPUTES_DIR / "schemas" / "disputes.json").read_text())
628 assert "status" in schema["views"]["filter_fields"]
629
630
631def test_the_count_opens_a_door_this_package_actually_serves():
632 """The sweep in tests/test_attention_paths.py holds this for every
633 package; asserted here too because a count nobody can open is a
634 notification, and this is the package that just added one."""
635 package = object_packages.get_package("app-disputes", root=PACKAGES)
636 source = package["attention"][0]
637 assert source["path"] == "/disputes"
638 assert "?" not in source["path"]
639
640 route = next(row for row in _seed_rows("site_routes")
641 if row["pattern"] == "/disputes")
642 assert route["object_id"] == "site_view_render"
643
644 door = package["nav"][0]
645 assert door["path"] == "/disputes"
646 assert door["group"] == "Commerce"
647
648
649def test_the_gate_is_declared_on_the_collection_not_only_written():
650 """A hook object nobody wired up is a docstring. The schema's
651 `hooks.before_write` is what makes the generic write path run it."""
652 schema = json.loads(
653 (APP_DISPUTES_DIR / "schemas" / "disputes.json").read_text())
654 assert schema["hooks"]["before_write"] == "hook_disputes"
655
656
657def test_the_review_freeze_is_named_as_a_decision_rather_than_forgotten():
658 """plan/fulfillment-logistics-spec.md wants a disputed order's review
659 window frozen. There is no reviews system on this server, so the field
660 would be a column of blanks -- the doctrine is written down instead of
661 guessed at in code, and this test is what stops that being an
662 accident."""
663 schema = json.loads(
664 (APP_DISPUTES_DIR / "schemas" / "disputes.json").read_text())
665 assert "review" in schema["description"].lower()
666 assert "no reviews system exists" in schema["description"]