Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

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
resolve_dispute.py · 23.6 KB · 531 lines
1"""action_resolve_dispute -- the one door where a dispute and the thing
2that compensates it are written together.
3
4POST {dispute_id, resolution_kind, amount_cents?, note?, wallet_id?,
5 number?, today?}
6
7This is the same argument action_disposition_return makes about returns
8and refunds, and it is the reason this object exists rather than two
9screens. Separating "close the dispute" from "issue the compensation" is
10how they drift: a shop with a resolved queue and no refunds against it,
11or refunds nobody can tie to a claim. Both facts come out of one human
12decision -- "she's right, give her the money" -- so both records come out
13of one call, and the dispute cannot be closed with one half done.
14
15**The refund goes through the EXISTING gate.** hook_refunds already knows
16what a payment can give back (its amount minus prior refunds, never a
17bounced payment), and a second opinion about the same ceiling is a second
18thing to get wrong -- worse, it would quote a customer a different number
19depending on which door their claim came through. So the prospective
20refund is handed to that hook in process and its refusal is surfaced
21VERBATIM, then the record the hook handed back (stamped invoice_id and
22all) is what gets written. A trusted server-side write bypasses hooks by
23design, which is exactly why the hook has to be asked explicitly rather
24than relied on.
25
26**A credit refuses honestly when there is nowhere to put it.** Store
27credit is a wallet entry, wallets are app-billing's, and app-billing is
28not a dependency of this package on purpose: a shop that does not sell
29credit should not be made to install a billing engine to record a
30dispute. When the collection is absent the action says so and names the
31app, rather than inventing a credit nobody can spend or -- worse --
32closing the dispute as though one had been issued.
33
34**A replacement is a real order, confirmed.** Not a draft: the order
35schema's own words are that "a draft is not a commitment", and a
36resolution that points at a document promising nothing is precisely the
37failure hook_disputes exists to prevent. Its lines are copied from the
38original at ZERO price, because the customer already paid on the order
39being argued about and a replacement priced again would double-count
40revenue in every fold that sums order totals. The link back to the
41original is provenance in `notes` plus the dispute row itself, and NOT
42orders.linked_order_id: that field means one specific thing -- the
43drop-ship counterpart -- and action_dropship_order's stock rule reads it.
44A field that means two things is a field a gate cannot read.
45
46**Idempotency is the property this object is judged on.** An already
47resolved dispute answers ok with a note and does nothing: no second
48refund, no second replacement order, no second credit. Belt and braces
49behind that, the refund's reason and the replacement order's notes both
50carry `disputes/{id}`, and a replay finds its own marker. Two mechanisms
51because the failure they guard against is a customer's money going back
52twice, which is the one mistake nobody forgives and nobody notices for a
53month.
54
55The three rules about what a resolution must SAY are hook_disputes', and
56this object holds them by ASKING that hook in process -- twice: once
57before anything is written, for the endings that need no record, and once
58with the finished reference in hand. Trusted server-side writes bypass
59hooks by design, so the rule has to travel with the action; asking the
60hook rather than restating it is what stops one gate growing two
61vocabularies, exactly as the refund ceiling is asked of hook_refunds
62rather than recomputed here.
63"""
64
65import os
66from datetime import date, datetime, timezone
67
68import object_execution
69import object_ids
70import object_records
71import python_object_runtime
72
73ACTOR = "action_resolve_dispute"
74
75RESOLVED = "resolved"
76WITHDRAWN = "withdrawn"
77
78# The schema's own enum, restated only as a list of four values -- the
79# RULES about them live in hook_disputes and are asked for, never copied.
80RESOLUTION_KINDS = ("refund", "replacement", "credit", "no_action")
81NEEDS_A_REASON = "no_action"
82
83
84def _base_dir():
85 return os.environ.get("DBBASIC_DATA_DIR", "data")
86
87
88def _text(value):
89 return str(value if value is not None else "").strip()
90
91
92def _cents(value):
93 try:
94 return int(_text(value) or "0")
95 except ValueError:
96 return 0
97
98
99def _call(object_id, payload, *, method="POST"):
100 """Run another installed object in process. Returns (result, error); a
101 missing object is an error string, never an exception."""
102 try:
103 runtime = python_object_runtime.PythonObjectRuntime()
104 outcome = object_execution.execute_object(
105 runtime,
106 object_execution.ObjectExecutionRequest(
107 object_id, method=method, payload=payload))
108 except Exception as exc:
109 return None, str(exc)[:200]
110 if not outcome.ok:
111 message = getattr(outcome.error, "message", "") if outcome.error else ""
112 return None, _text(message)[:200] or f"{object_id} failed"
113 return outcome.result, ""
114
115
116def _ask_the_gate(record):
117 """Put a prospective dispute row to hook_disputes and hand back its
118 refusal, verbatim, or None.
119
120 Fails CLOSED: a gate that cannot be consulted is not a gate that said
121 yes, so an unreachable hook refuses the close rather than waving it
122 through.
123 """
124 verdict, error = _call("hook_disputes",
125 {"action": "update", "collection": "disputes",
126 "record": record},
127 method="BEFORE_WRITE")
128 if error:
129 return {"status": 503,
130 "error": (f"The dispute gate could not be consulted ({error}), "
131 f"so this dispute has not been closed. The rule about "
132 f"what a resolution must name lives in hook_disputes "
133 f"and this action refuses to decide without it.")}
134 if isinstance(verdict, dict) and verdict.get("error"):
135 return {"status": verdict.get("status", 400),
136 "error": _text(verdict.get("error"))}
137 return None
138
139
140def _rows(collection, base):
141 try:
142 return object_records.read_collection_records(collection, base_dir=base)
143 except Exception:
144 return None
145
146
147def _order_of(base, dispute):
148 order_id = _text(dispute.get("order_id"))
149 if not order_id:
150 return {}
151 try:
152 return object_records.get_collection_record("orders", order_id,
153 base_dir=base)
154 except Exception:
155 return {}
156
157
158def _payment_for(base, dispute, order):
159 """The payment this refund compensates.
160
161 A payment dispute names its own payment and that wins outright -- the
162 customer is arguing about one charge and refunding a different one
163 would be a new problem. Otherwise the order points at an invoice and
164 payments point at the same invoice, which is the join app-shop's
165 checkout leaves behind; the earliest non-bounced payment wins,
166 deterministically. Splitting one refund across several payments is
167 deliberately NOT built here for the same reason app-returns does not
168 build it: it needs a rule about which money goes back first, and
169 inventing that rule inside a disputes action would be picking an
170 accounting policy by accident.
171 """
172 payment_id = _text(dispute.get("payment_id"))
173 if payment_id:
174 try:
175 return object_records.get_collection_record("payments", payment_id,
176 base_dir=base)
177 except Exception:
178 return None
179
180 invoice_id = _text(order.get("invoice_id"))
181 if not invoice_id:
182 return None
183 payments = _rows("payments", base)
184 if payments is None:
185 return None
186 candidates = [row for row in payments
187 if _text(row.get("invoice_id")) == invoice_id
188 and _text(row.get("status") or "received") != "bounced"]
189 candidates.sort(key=lambda row: (_text(row.get("received_on")),
190 _text(row.get("id"))))
191 return candidates[0] if candidates else None
192
193
194def _wallet_for(base, request, dispute, order):
195 """Whose credit this is. Explicit wallet_id wins; otherwise the
196 customer's own wallet, matched on the wallet's owner.
197
198 Deliberately no invention: a shop that sells to guests has no wallet
199 for most of its customers, and issuing credit into a wallet nobody
200 owns would be a number the customer can never spend.
201 """
202 wallets = _rows("wallets", base)
203 if wallets is None:
204 return None, "wallets"
205 wanted = _text(request.get("wallet_id"))
206 if wanted:
207 for row in wallets:
208 if _text(row.get("id")) == wanted:
209 return row, ""
210 return None, "no_such_wallet"
211 keys = {_text(dispute.get("customer_email")),
212 _text(order.get("customer_email")),
213 _text(order.get("customer_id"))}
214 keys.discard("")
215 for row in wallets:
216 if _text(row.get("owner_id")) in keys:
217 return row, ""
218 return None, "no_wallet_for_customer"
219
220
221def _marker(dispute_id):
222 return f"disputes/{dispute_id}"
223
224
225def _already_refunded(base, dispute_id):
226 """Belt and braces behind the status check: a refund carrying this
227 dispute's marker means the money already went back, whatever the
228 dispute row says."""
229 for row in _rows("refunds", base) or []:
230 if _marker(dispute_id) in _text(row.get("reason")):
231 return row
232 return None
233
234
235def _already_replaced(base, dispute_id):
236 for row in _rows("orders", base) or []:
237 if _marker(dispute_id) in _text(row.get("notes")):
238 return row
239 return None
240
241
242def _already_credited(base, dispute_id):
243 for row in _rows("wallet_entries", base) or []:
244 if _marker(dispute_id) in _text(row.get("generated_from")):
245 return row
246 return None
247
248
249def _copy_lines(base, from_order_id, to_order_id, owner):
250 """The goods, again, at no charge.
251
252 Zero price is the decision worth naming: the customer already paid on
253 the order being argued about, so a replacement priced at the catalog
254 rate would show up as a second sale in every fold that sums order
255 totals, and the shop would appear to have earned money it is in fact
256 giving away.
257 """
258 created = []
259 for line in _rows("order_lines", base) or []:
260 if _text(line.get("order_id")) != from_order_id:
261 continue
262 line_id = object_ids.new_uuid4()
263 object_records.create_collection_record(
264 "order_lines",
265 {
266 "id": line_id,
267 "order_id": to_order_id,
268 "product_id": _text(line.get("product_id")),
269 "description": _text(line.get("description")),
270 "quantity": _text(line.get("quantity")) or "1",
271 "unit_price_cents": "0",
272 "line_total_cents": "0",
273 "tax_rate_bps": "0",
274 "line_tax_cents": "0",
275 "owner_id": owner,
276 },
277 base_dir=base, actor=ACTOR)
278 created.append(line_id)
279 return created
280
281
282def POST(request):
283 base = _base_dir()
284 dispute_id = _text(request.get("dispute_id"))
285 if not dispute_id:
286 return {"status": 400, "error": "dispute_id is required"}
287
288 try:
289 dispute = object_records.get_collection_record("disputes", dispute_id,
290 base_dir=base)
291 except Exception:
292 return {"status": 404, "error": f"No such dispute: {dispute_id}"}
293
294 status = _text(dispute.get("status"))
295 if status == RESOLVED:
296 # The single most important behaviour in this object. A retried
297 # request, a double-clicked button, a replayed queue entry: none of
298 # them may send a customer's money back twice or raise a second
299 # replacement order. Observable state, not a lock
300 # (docs/logic-decisions.md #7).
301 return {"ok": True, "dispute_id": dispute_id,
302 "resolution_kind": _text(dispute.get("resolution_kind")),
303 "resolution_ref": _text(dispute.get("resolution_ref")),
304 "refund_id": "", "order_id": "", "wallet_entry_id": "",
305 "note": "this dispute was already resolved; no second refund, "
306 "replacement or credit was issued"}
307
308 if status == WITHDRAWN:
309 return {"status": 409,
310 "error": (f"Dispute {dispute_id} was withdrawn. The customer "
311 f"dropped the claim, and compensating a claim "
312 f"nobody is making would be a payment with no "
313 f"argument behind it -- raise a new dispute if they "
314 f"have come back.")}
315
316 kind = _text(request.get("resolution_kind"))
317 note = _text(request.get("note"))
318 if kind not in RESOLUTION_KINDS:
319 return {"status": 400,
320 "error": (f"Unknown resolution_kind {kind or '(blank)'!r}; "
321 f"expected one of {', '.join(RESOLUTION_KINDS)}.")}
322
323 # The same three rules the hook enforces, asked of the hook's own
324 # checker rather than restated -- trusted server-side writes bypass
325 # hooks, so the rule has to travel with the action, and a second
326 # wording of it would give one gate two vocabularies. The ref is
327 # filled in below once the compensating record exists; only the
328 # kind-and-reason half can be checked this early, which is the half
329 # that must fail BEFORE anything is written.
330 if kind == NEEDS_A_REASON:
331 refusal = _ask_the_gate({"id": dispute_id, "status": RESOLVED,
332 "resolution_kind": kind,
333 "resolution_note": note})
334 if refusal:
335 return refusal
336
337 order = _order_of(base, dispute)
338 owner = (_text(dispute.get("owner_id"))
339 or _text(order.get("owner_id"))
340 or _text((request.get("_identity") or {}).get("user_id")))
341 actor_user = (_text((request.get("_identity") or {}).get("user_id"))
342 or owner)
343 when = _text(request.get("today")) or date.today().isoformat()
344
345 resolution_ref = ""
346 refund_id = ""
347 replacement_id = ""
348 entry_id = ""
349 amount = _cents(request.get("amount_cents"))
350
351 # --- the compensating record, composed BEFORE the dispute is closed ---
352 # Statuses follow facts and never lead them: a dispute marked resolved
353 # while its refund is still being argued about by a gate is exactly the
354 # lie this package exists to prevent.
355 if kind == "refund":
356 existing = _already_refunded(base, dispute_id)
357 if existing is not None:
358 refund_id = _text(existing.get("id"))
359 resolution_ref = f"refunds/{refund_id}"
360 else:
361 if amount <= 0:
362 return {"status": 400,
363 "error": ("A refund of nothing is not a refund: pass "
364 "amount_cents, or resolve this as no_action "
365 "with a reason if no money is going back.")}
366 payment = _payment_for(base, dispute, order)
367 if payment is None:
368 return {"status": 409,
369 "error": ("No payment to refund against. Money can "
370 "only go back the way it came, so a refund "
371 "needs the payment it compensates -- point "
372 "the dispute at a payment_id, or resolve it "
373 "as a credit or a replacement.")}
374 candidate = {
375 "id": object_ids.new_uuid4(),
376 "payment_id": _text(payment.get("id")),
377 "amount_cents": str(amount),
378 "reason": f"{_marker(dispute_id)} {note}".strip()[:300],
379 "refunded_on": when,
380 "owner_id": owner,
381 }
382 # DEFER to the existing ceiling rather than growing a second
383 # opinion about it, and surface its words unchanged so the
384 # customer is quoted the same number whichever door they came
385 # through.
386 verdict, error = _call("hook_refunds",
387 {"action": "create", "collection": "refunds",
388 "record": candidate},
389 method="BEFORE_WRITE")
390 if error:
391 return {"status": 503,
392 "error": (f"The refund gate could not be consulted "
393 f"({error}), so no money is going anywhere "
394 f"and the dispute is still open. Refunds are "
395 f"app-payments' arithmetic and this action "
396 f"refuses to guess at it.")}
397 if isinstance(verdict, dict) and verdict.get("error"):
398 return {"status": verdict.get("status", 409),
399 "error": _text(verdict.get("error")),
400 "refund": _text(verdict.get("error"))}
401 if isinstance(verdict, dict) and isinstance(verdict.get("record"),
402 dict):
403 candidate = verdict["record"]
404 object_records.create_collection_record("refunds", candidate,
405 base_dir=base, actor=ACTOR)
406 refund_id = _text(candidate.get("id"))
407 resolution_ref = f"refunds/{refund_id}"
408
409 elif kind == "replacement":
410 existing = _already_replaced(base, dispute_id)
411 if existing is not None:
412 replacement_id = _text(existing.get("id"))
413 resolution_ref = f"orders/{replacement_id}"
414 else:
415 if not order:
416 return {"status": 409,
417 "error": ("A replacement needs the order it replaces. "
418 "This dispute names no order_id, so there "
419 "are no lines to send again and no customer "
420 "to send them to.")}
421 replacement_id = object_ids.new_uuid4()
422 number = (_text(request.get("number"))
423 or f"{_text(order.get('number'))}-R")
424 object_records.create_collection_record(
425 "orders",
426 {
427 "id": replacement_id,
428 "doc_type": "sale",
429 "number": number,
430 "customer_id": _text(order.get("customer_id")),
431 "customer_name": _text(order.get("customer_name")),
432 "customer_email": _text(order.get("customer_email")),
433 "currency": _text(order.get("currency")) or "USD",
434 # Confirmed, not draft. The order schema's own words are
435 # that a draft is not a commitment, and a resolution
436 # pointing at a document that promises nothing is the
437 # failure hook_disputes exists to prevent.
438 "status": "confirmed",
439 "order_date": when,
440 "ship_to_name": _text(order.get("ship_to_name")),
441 "ship_to_address": _text(order.get("ship_to_address")),
442 "customer_note": _text(order.get("customer_note")),
443 "notes": (f"Generated by {ACTOR} [{_marker(dispute_id)} "
444 f"orders/{order['id']}] -- no-charge replacement"),
445 "owner_id": owner,
446 },
447 base_dir=base, actor=ACTOR)
448 _copy_lines(base, order["id"], replacement_id, owner)
449 resolution_ref = f"orders/{replacement_id}"
450
451 elif kind == "credit":
452 existing = _already_credited(base, dispute_id)
453 if existing is not None:
454 entry_id = _text(existing.get("id"))
455 resolution_ref = f"wallet_entries/{entry_id}"
456 else:
457 if amount <= 0:
458 return {"status": 400,
459 "error": ("A credit of nothing is not a credit: pass "
460 "amount_cents, or resolve this as no_action "
461 "with a reason.")}
462 if _rows("wallet_entries", base) is None:
463 return {"status": 409,
464 "error": ("There is no wallet on this server to credit: "
465 "store credit is a wallet entry and wallets "
466 "come from app-billing, which is not "
467 "installed. Refusing rather than closing this "
468 "dispute as though credit had been issued -- "
469 "refund it, replace it, or say no_action and "
470 "why."),
471 "missing_app": "app-billing"}
472 wallet, problem = _wallet_for(base, request, dispute, order)
473 if wallet is None:
474 return {"status": 409,
475 "error": (f"No wallet to credit ({problem}). A credit "
476 f"has to land somewhere the customer can "
477 f"spend it: pass wallet_id, or open a wallet "
478 f"for this customer first. A credit issued "
479 f"into a wallet nobody owns is a number that "
480 f"never becomes money."),
481 "missing_wallet": problem}
482 entry_id = object_ids.new_uuid4()
483 object_records.create_collection_record(
484 "wallet_entries",
485 {
486 "id": entry_id,
487 "wallet_id": _text(wallet.get("id")),
488 # Positive: credit is money going TO the customer, and
489 # the sign convention is the ledger's, not ours.
490 "amount_minor": str(amount),
491 "kind": "adjustment",
492 "description": note or f"Dispute {dispute_id} resolved as "
493 f"store credit",
494 "reference": _marker(dispute_id),
495 "generated_from": _marker(dispute_id),
496 "owner_id": _text(wallet.get("owner_id")) or owner,
497 },
498 base_dir=base, actor=ACTOR)
499 resolution_ref = f"wallet_entries/{entry_id}"
500
501 # --- the paperwork, last ------------------------------------------------
502 patch = {
503 "status": RESOLVED,
504 "resolution_kind": kind,
505 "resolution_ref": resolution_ref,
506 "resolved_by": actor_user,
507 "resolved_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
508 }
509 if note:
510 patch["resolution_note"] = note
511
512 # The gate, asked one final time with the ref now filled in. It cannot
513 # refuse a resolution this action just composed, and that is exactly
514 # the point: if it ever does, the two have drifted and the dispute
515 # stays open rather than closing over a record nobody can find.
516 refusal = _ask_the_gate({**dispute, **patch})
517 if refusal:
518 return {**refusal,
519 "resolution_ref": resolution_ref,
520 "note": "the compensating record was written but the dispute "
521 "was NOT closed; it is still open for somebody to "
522 "finish"}
523
524 object_records.update_collection_record("disputes", dispute_id, patch,
525 base_dir=base, actor=ACTOR)
526
527 return {"ok": True, "dispute_id": dispute_id, "resolution_kind": kind,
528 "resolution_ref": resolution_ref, "refund_id": refund_id,
529 "order_id": replacement_id, "wallet_entry_id": entry_id,
530 "amount_cents": str(amount) if amount > 0 else "0",
531 "status_of_dispute": RESOLVED, "date": when}