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