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

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
resolve_dispute.py · 47.5 KB · 1009 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 credit lands in the customer's wallet, and only theirs.** The
35customer is the order's customer, or the dispute's customer_email when
36it names no order; a wallet is theirs when its owner is that email or
37the one active user carrying it, it is a balance or store_credit wallet
38(never a gift card, which belongs to the shop and to whoever holds its
39code), and it is active. A body wallet_id only picks among those. It
40used to select ANY wallet, so whoever resolved a real complaint could
41send the customer's credit to their own wallet, a friend's or a gift
42card, and an unknown id answered differently from somebody else's, so
43the door also said which wallet ids exist. Every id that is not the
44customer's now gets the one answer a customer with no wallet gets, and
45writes nothing; only an admin may name another wallet.
46
47**A replacement is a real order, confirmed.** Not a draft: the order
48schema's own words are that "a draft is not a commitment", and a
49resolution that points at a document promising nothing is precisely the
50failure hook_disputes exists to prevent. Its lines are copied from the
51original at ZERO price, because the customer already paid on the order
52being argued about and a replacement priced again would double-count
53revenue in every fold that sums order totals. The link back to the
54original is provenance in `notes` plus the dispute row itself, and NOT
55orders.linked_order_id: that field means one specific thing -- the
56drop-ship counterpart -- and action_dropship_order's stock rule reads it.
57A field that means two things is a field a gate cannot read.
58
59**Idempotency is the property this object is judged on.** An already
60resolved dispute answers ok with a note and does nothing: no second
61refund, no second replacement order, no second credit. Belt and braces
62behind that, the refund's reason and the replacement order's notes both
63carry `disputes/{id}`, and a replay finds its own marker. Two mechanisms
64because the failure they guard against is a customer's money going back
65twice, which is the one mistake nobody forgives and nobody notices for a
66month. Neither of them holds against two requests that overlap: both find
67the dispute open and no marker, and both refund. So before composing
68anything the action CLAIMS the dispute (disputes.resolution_claim, a
69compare-and-set), and a request that finds a live claim is refused with
70409 `in_progress`; the claim is released whenever the request ends without
71closing the dispute, and one older than ten minutes is taken over.
72
73**A credit has a ceiling.** What the customer paid for the thing argued
74about (the dispute's payment, or the received payments on the order's
75invoice), less refunds against those payments and credits other disputes
76about the same order already issued -- money received, the same unit the
77refund ceiling is measured in, and never more than the order's own total.
78It used to have none: a 36.00 order could be resolved with 999,999.00 of
79spendable credit. An admin may go over it deliberately (`over_ceiling:
80true`), nobody by typo.
81
82**The action is the grant for the payout, so it checks its own scope.**
83Who: staff by role (object_corrections.staff_refusal); update on the
84dispute (its owner, or a manager or owner for any dispute); and for a
85refund, replacement or credit a ROLE that may update every dispute
86(object_corrections.role_grants), never just owning the row. What from:
87_scope reads the order as the caller (staff roles read every order), then
88checks under this action's authority that the order's bill and payments
89are the order's own account's and that a payment the dispute names is on
90that order. It used to ask for update on the order and its payments
91instead, which no shipped role holds on orders, so nobody but an admin
92could pay out a dispute about a shop order -- and the fix is not to give
93managers a general right to edit orders.
94
95The three rules about what a resolution must SAY are hook_disputes', and
96this object holds them by ASKING that hook in process -- twice: once
97before anything is written, for the endings that need no record, and once
98with the finished reference in hand. Trusted server-side writes bypass
99hooks by design, so the rule has to travel with the action; asking the
100hook rather than restating it is what stops one gate growing two
101vocabularies, exactly as the refund ceiling is asked of hook_refunds
102rather than recomputed here.
103"""
104
105import os
106from datetime import date, datetime, timedelta, timezone
107
108import object_access
109import object_collections
110import object_corrections
111import object_execution
112import object_identity
113import object_ids
114import object_money
115import object_records
116import python_object_runtime
117
118ACTOR = "action_resolve_dispute"
119
120RESOLVED = "resolved"
121WITHDRAWN = "withdrawn"
122
123# The schema's own enum, restated only as a list of four values -- the
124# RULES about them live in hook_disputes and are asked for, never copied.
125RESOLUTION_KINDS = ("refund", "replacement", "credit", "no_action")
126NEEDS_A_REASON = "no_action"
127# The endings that give something away. Only a role that may update EVERY
128# dispute (role:manager, role:owner in this package's rules) or an admin
129# may choose one; owning the dispute is not enough.
130PAYOUT_KINDS = ("refund", "replacement", "credit")
131
132
133def _base_dir():
134 return os.environ.get("DBBASIC_DATA_DIR", "data")
135
136
137def _text(value):
138 return str(value if value is not None else "").strip()
139
140
141def _cents(value):
142 try:
143 return int(_text(value) or "0")
144 except ValueError:
145 return 0
146
147
148def _call(object_id, payload, *, method="POST"):
149 """Run another installed object in process. Returns (result, error); a
150 missing object is an error string, never an exception."""
151 try:
152 runtime = python_object_runtime.PythonObjectRuntime()
153 outcome = object_execution.execute_object(
154 runtime,
155 object_execution.ObjectExecutionRequest(
156 object_id, method=method, payload=payload))
157 except Exception as exc:
158 return None, str(exc)[:200]
159 if not outcome.ok:
160 message = getattr(outcome.error, "message", "") if outcome.error else ""
161 return None, _text(message)[:200] or f"{object_id} failed"
162 return outcome.result, ""
163
164
165def _ask_the_gate(record):
166 """Put a prospective dispute row to hook_disputes and hand back its
167 refusal, verbatim, or None.
168
169 Fails CLOSED: a gate that cannot be consulted is not a gate that said
170 yes, so an unreachable hook refuses the close rather than waving it
171 through.
172 """
173 verdict, error = _call("hook_disputes",
174 {"action": "update", "collection": "disputes",
175 "record": record},
176 method="BEFORE_WRITE")
177 if error:
178 return {"status": 503,
179 "error": (f"The dispute gate could not be consulted ({error}), "
180 f"so this dispute has not been closed. The rule about "
181 f"what a resolution must name lives in hook_disputes "
182 f"and this action refuses to decide without it.")}
183 if isinstance(verdict, dict) and verdict.get("error"):
184 return {"status": verdict.get("status", 400),
185 "error": _text(verdict.get("error"))}
186 return None
187
188
189def _rows(collection, base):
190 try:
191 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
192 return object_records.read_collection_records(collection, base_dir=base)
193 except Exception:
194 return None
195
196
197def _int_or_none(value):
198 try:
199 return int(_text(value))
200 except ValueError:
201 return None
202
203
204def _mismatch(what):
205 return {"status": 409, "code": "order_mismatch",
206 "error": (f"{what}, so nothing was issued and the dispute is still "
207 f"open. A dispute pays out only from its own order and "
208 f"that order's own bill and payments.")}
209
210
211def _no_order():
212 return {"status": 409, "code": "order_not_found",
213 "error": ("This dispute's order cannot be found, so there is "
214 "nothing to pay out from; nothing was issued and the "
215 "dispute is still open.")}
216
217
218def _scope(base, access, dispute):
219 """What a payout may come out of, read under this action's own checks.
220
221 Returns (order, payments, refusal). ``payments`` are the payments the
222 compensation may be measured against or refunded from.
223
224 The action is the grant (docs/package-authoring.md, "An action that is
225 the grant"): a manager resolves a dispute about a shop order without any
226 right to edit orders or the orders' bills, so this checks for itself
227 what that update right used to stand in for:
228
229 - the order is one the caller may READ (staff roles read every order;
230 a deny rule the box wrote for them still wins), read as the caller;
231 - the order and its bill are one account's: the bill the order names
232 belongs to the order's owner and, when it says which order it bills,
233 to this order -- orders.invoice_id is not a validated pointer, so an
234 order of one account could name another's bill;
235 - a payment counts only if it is on that bill and owned like it;
236 - a payment the dispute names must be one of those when the dispute
237 names an order, and one the caller may read when it names none.
238
239 A refused or missing record gets one answer, without the id.
240 """
241 payment_id = _text(dispute.get("payment_id"))
242 order = {}
243 payments = []
244 if _text(dispute.get("order_id")):
245 order = access.get("orders", _text(dispute.get("order_id")))
246 if order is None:
247 return {}, [], _no_order()
248 account = _text(order.get("owner_id"))
249 invoice_id = _text(order.get("invoice_id"))
250 if invoice_id:
251 try:
252 # access: the order's own bill, read under this action's authority after the staff and payout checks; its owner is compared with the order's below
253 invoice = object_records.get_collection_record(
254 "invoices", invoice_id, base_dir=base)
255 except (object_records.RecordNotFoundError,
256 object_records.InvalidRecordIdError,
257 object_collections.CollectionNotFoundError):
258 invoice = {}
259 except Exception as exc:
260 raise Unreadable(f"invoices: {str(exc)[:120]}") from exc
261 if invoice:
262 if _text(invoice.get("owner_id")) != account:
263 return {}, [], _mismatch(
264 "This dispute's order and the bill it names belong to "
265 "different accounts")
266 source = _text(invoice.get("source_order_id"))
267 if source and source != _text(order.get("id")):
268 return {}, [], _mismatch(
269 "The bill this dispute's order names is another "
270 "order's bill")
271 payments = [row for row in _history(base, "payments")
272 if _text(row.get("invoice_id")) == invoice_id
273 and _text(row.get("owner_id")) == account
274 and access.can("read", "payments", row)]
275 if payment_id:
276 named = [row for row in payments if _text(row.get("id")) == payment_id]
277 if not named:
278 return {}, [], _mismatch(
279 "The payment this dispute names is not a payment on its "
280 "order")
281 payments = named
282 elif payment_id:
283 payment = access.get("payments", payment_id)
284 payments = [payment] if payment is not None else []
285 return order, payments, None
286
287
288def _payment_for(dispute, payments):
289 """The payment this refund compensates.
290
291 A payment dispute names its own payment and that wins outright (_scope
292 has already narrowed ``payments`` to it) -- the customer is arguing
293 about one charge and refunding a different one would be a new problem.
294 Otherwise the earliest non-bounced payment on the order's bill wins,
295 deterministically. Splitting one refund across several payments is
296 deliberately NOT built here for the same reason app-returns does not
297 build it: it needs a rule about which money goes back first, and
298 inventing that rule inside a disputes action would be picking an
299 accounting policy by accident.
300 """
301 candidates = [row for row in payments
302 if _text(row.get("status") or "received") != "bounced"]
303 candidates.sort(key=lambda row: (_text(row.get("received_on")),
304 _text(row.get("id"))))
305 return candidates[0] if candidates else None
306
307
308# Kinds a credit may land in as "the customer's wallet". A gift card is
309# not: its owner_id is the shop that sold it and it is spent by whoever
310# holds the code (wallets.json), so it belongs to no customer.
311CUSTOMER_WALLET_KINDS = ("store_credit", "balance")
312
313
314def _customer_keys(base, dispute, order):
315 """The owner_ids a wallet of this dispute's customer can carry.
316
317 WHO the customer is: the order's customer when the dispute names an
318 order, and the dispute's customer_email only when it names none. The
319 dispute's field is plain editable text, so it never outranks the
320 order. A dispute that names an order the resolver may not act on
321 (`order` came back empty) has a customer nobody here can see, and gets
322 no keys at all rather than falling back to the editable field.
323
324 HOW a wallet is keyed to them: wallets are owned by a user id (the
325 wallets rules filter on $user_id; action_run_template opens and spends
326 the caller's own), while app-shop's checkout stamps an order with only
327 the email the buyer typed -- no customer_id, and orders.customer_id is
328 a contacts row, not a user. So the email is resolved to the ONE active
329 user carrying it (signup verifies the address before a user is
330 active); none, or more than one, resolves to nobody. A wallet keyed by
331 the email itself still matches, compared without case.
332 """
333 if _text(dispute.get("order_id")):
334 email = _text(order.get("customer_email"))
335 else:
336 email = _text(dispute.get("customer_email"))
337 if not email:
338 return set()
339 keys = {email.casefold()}
340 try:
341 users = object_identity.find_users_by_email(email, base_dir=base)
342 except Exception:
343 users = []
344 active = [user for user in users
345 if _text(user.get("status")) == object_identity.ACTIVE_STATUS
346 and _text(user.get("user_id"))]
347 if len(active) == 1:
348 keys.add(_text(active[0]["user_id"]).casefold())
349 return keys
350
351
352def _is_customers_wallet(row, keys):
353 return (bool(keys)
354 and _text(row.get("owner_id")).casefold() in keys
355 and (_text(row.get("kind")) or "balance") in CUSTOMER_WALLET_KINDS
356 and _truthy(row.get("is_active") or "true"))
357
358
359def _wallet_for(base, request, access, dispute, order):
360 """Whose credit this is: a wallet of the dispute's customer.
361
362 A body wallet_id only CHOOSES among that customer's wallets. Any other
363 id -- somebody else's wallet, a gift card, an inactive wallet, an id
364 that does not exist -- gets exactly the answer a customer with no
365 wallet gets, so the action cannot be used to send a customer's credit
366 elsewhere or to learn which wallet ids exist. Only an admin may name
367 another wallet (it still has to exist).
368
369 Without a wallet_id: the customer's store_credit wallet first, then
370 their balance wallet. Deliberately no invention: a shop that sells to
371 guests has no wallet for most of its customers, and issuing credit
372 into a wallet nobody owns would be a number the customer can never
373 spend.
374 """
375 wallets = _rows("wallets", base)
376 if wallets is None:
377 return None, "wallets"
378 keys = _customer_keys(base, dispute, order)
379 theirs = [row for row in wallets if _is_customers_wallet(row, keys)]
380 wanted = _text(request.get("wallet_id"))
381 if wanted:
382 pool = wallets if access.is_admin else theirs
383 for row in pool:
384 if _text(row.get("id")) == wanted:
385 return row, ""
386 return None, "no_wallet_for_customer"
387 theirs.sort(key=lambda row: CUSTOMER_WALLET_KINDS.index(
388 _text(row.get("kind")) or "balance"))
389 if theirs:
390 return theirs[0], ""
391 return None, "no_wallet_for_customer"
392
393
394def _code(value):
395 """A currency or denomination code; blank is the server default, the
396 convention the schemas state (a wallet's blank denomination is USD)."""
397 return _text(value).upper() or object_money.DEFAULT_CODE
398
399
400def _dispute_currency(base, dispute, order):
401 """The currency the amount_cents of this dispute is in: the order's,
402 or, for a dispute that names only a payment, its invoice's."""
403 if order:
404 return _code(order.get("currency"))
405 invoice_id = ""
406 payment_id = _text(dispute.get("payment_id"))
407 if payment_id:
408 for row in _history(base, "payments"):
409 if _text(row.get("id")) == payment_id:
410 invoice_id = _text(row.get("invoice_id"))
411 break
412 currency = ""
413 if invoice_id:
414 for row in _history(base, "invoices"):
415 if _text(row.get("id")) == invoice_id:
416 currency = row.get("currency")
417 break
418 return _code(currency)
419
420
421def _currency_mismatch(base, dispute, order, wallet):
422 """A refusal when the wallet holds a different denomination than the
423 amount is in, else None. wallet_entries.amount_minor is in the wallet's
424 own minor unit, so crediting 500 USD cents into a wallet of another
425 denomination would be a different amount of money (the ledger never
426 adds across denominations, object_money.same_denomination); there is no
427 rate here to convert at, so it fails closed."""
428 money = _dispute_currency(base, dispute, order)
429 denomination_id = _text(wallet.get("denomination_id"))
430 held = _code("")
431 if denomination_id:
432 # The field is a pointer at a denominations row; its code is the
433 # currency. A pointer that cannot be followed is a wallet whose
434 # currency is unknown, which is not a match.
435 try:
436 # access: the wallet's own denomination, after the wallet was chosen as the customer's own above
437 held = _code(object_records.get_collection_record(
438 object_money.DENOMINATIONS_COLLECTION, denomination_id,
439 base_dir=base).get("code"))
440 except Exception:
441 held = f"an unreadable denomination ({denomination_id})"
442 if money == held:
443 return None
444 return {"status": 409, "code": "currency_mismatch",
445 "error": (f"This dispute is in {money} but the wallet holds {held}. "
446 f"A credit is issued in the dispute's own currency, so "
447 f"nothing was issued and the dispute is still open: pick "
448 f"a wallet held in {money}, or refund it instead.")}
449
450
451def _marker(dispute_id):
452 return f"disputes/{dispute_id}"
453
454
455def _already_refunded(base, dispute_id):
456 """Belt and braces behind the status check: a refund carrying this
457 dispute's marker means the money already went back, whatever the
458 dispute row says.
459
460 This and its two siblings read strictly (_history): an unreadable
461 history used to read as "not yet", so a retry after a crash between
462 the compensation and the close sent a second replacement."""
463 for row in _history(base, "refunds"):
464 if _marker(dispute_id) in _text(row.get("reason")):
465 return row
466 return None
467
468
469def _already_replaced(base, dispute_id):
470 for row in _history(base, "orders"):
471 if _marker(dispute_id) in _text(row.get("notes")):
472 return row
473 return None
474
475
476def _already_credited(base, dispute_id):
477 for row in _history(base, "wallet_entries"):
478 if _marker(dispute_id) in _text(row.get("generated_from")):
479 return row
480 return None
481
482
483def _copy_lines(base, lines, from_order_id, to_order_id, owner):
484 """The goods, again, at no charge.
485
486 Zero price is the decision worth naming: the customer already paid on
487 the order being argued about, so a replacement priced at the catalog
488 rate would show up as a second sale in every fold that sums order
489 totals, and the shop would appear to have earned money it is in fact
490 giving away.
491 """
492 created = []
493 for line in lines:
494 if _text(line.get("order_id")) != from_order_id:
495 continue
496 line_id = object_ids.new_uuid4()
497 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
498 object_records.create_collection_record(
499 "order_lines",
500 {
501 "id": line_id,
502 "order_id": to_order_id,
503 "product_id": _text(line.get("product_id")),
504 "description": _text(line.get("description")),
505 "quantity": _text(line.get("quantity")) or "1",
506 "unit_price_cents": "0",
507 "line_total_cents": "0",
508 "tax_rate_bps": "0",
509 "line_tax_cents": "0",
510 "owner_id": owner,
511 },
512 base_dir=base, actor=ACTOR)
513 created.append(line_id)
514 return created
515
516
517def POST(request):
518 base = _base_dir()
519 dispute_id = _text(request.get("dispute_id"))
520 if not dispute_id:
521 return {"status": 400, "error": "dispute_id is required"}
522
523 # The action is the grant: it credits wallets and refunds payments the
524 # caller may not touch over the record API, so it asks for itself that
525 # the caller is staff (a role the installed execute rules name for this
526 # action, or an admin) instead of leaning on a rule that is only asked
527 # with enforcement on. Before the lookup, so a customer learns nothing
528 # about any dispute, their own included.
529 access = object_access.Access(request.get("_identity"), base_dir=base)
530 staff = object_corrections.staff_refusal(access, "action_resolve_dispute",
531 doing="resolve a dispute")
532 if staff:
533 return staff
534
535 try:
536 dispute = object_records.get_collection_record("disputes", dispute_id,
537 base_dir=base)
538 except Exception:
539 return {"status": 404, "error": f"No such dispute: {dispute_id}"}
540 # Only someone the disputes API would let UPDATE this dispute may
541 # resolve it. Every write below is a trusted server-side write, so this
542 # object is the only gate -- it used to let any signed-in user close
543 # (and compensate) anyone's dispute (bug-reports/2026-11-28-06-14-26).
544 # Asked first, before even the already-resolved answer, which carries
545 # the resolution; refused reads exactly like missing. Under the
546 # shipped rules that is the dispute's owner, or role:manager or
547 # role:owner for any dispute.
548 if not access.can("update", "disputes", dispute):
549 return {"status": 404, "error": f"No such dispute: {dispute_id}"}
550
551 status = _text(dispute.get("status"))
552 if status == RESOLVED:
553 # The single most important behaviour in this object. A retried
554 # request, a double-clicked button, a replayed queue entry: none of
555 # them may send a customer's money back twice or raise a second
556 # replacement order. Observable state -- and, for two requests that
557 # overlap, the claim below (docs/logic-decisions.md #7).
558 return _already_resolved(dispute_id, dispute)
559
560 if status == WITHDRAWN:
561 return {"status": 409,
562 "error": (f"Dispute {dispute_id} was withdrawn. The customer "
563 f"dropped the claim, and compensating a claim "
564 f"nobody is making would be a payment with no "
565 f"argument behind it -- raise a new dispute if they "
566 f"have come back.")}
567
568 kind = _text(request.get("resolution_kind"))
569 note = _text(request.get("note"))
570 if kind not in RESOLUTION_KINDS:
571 return {"status": 400,
572 "error": (f"Unknown resolution_kind {kind or '(blank)'!r}; "
573 f"expected one of {', '.join(RESOLUTION_KINDS)}.")}
574
575 # Who may GIVE something away. Updating the dispute is enough to close
576 # it as no_action; a refund, replacement or credit also needs a ROLE
577 # that may update every dispute (role:manager and role:owner in this
578 # package's rules) or an admin. A cashier holds update only on the
579 # disputes they opened, through the registered owner-row grant, which
580 # role_grants does not count. This, not a right to edit orders or
581 # payments, is the payout authority: what it pays out from is read and
582 # checked by _scope under this action's own authority.
583 if kind in PAYOUT_KINDS and not object_corrections.role_grants(
584 access, "update", collection="disputes", record=dispute):
585 return {"status": 403, "code": "payout_needs_manager",
586 "error": ("Only a manager or the owner may resolve a dispute "
587 "with a refund, a replacement or store credit. You "
588 "can close it as no_action with a reason, or ask a "
589 "manager to settle it.")}
590
591 # The same three rules the hook enforces, asked of the hook's own
592 # checker rather than restated -- trusted server-side writes bypass
593 # hooks, so the rule has to travel with the action, and a second
594 # wording of it would give one gate two vocabularies. The ref is
595 # filled in below once the compensating record exists; only the
596 # kind-and-reason half can be checked this early, which is the half
597 # that must fail BEFORE anything is written.
598 if kind == NEEDS_A_REASON:
599 refusal = _ask_the_gate({"id": dispute_id, "status": RESOLVED,
600 "resolution_kind": kind,
601 "resolution_note": note})
602 if refusal:
603 return refusal
604
605 # THE CLAIM, before anything is composed. Without it two overlapping
606 # resolutions (a double click) both found no refund marker and both
607 # refunded, each inside the payment's ceiling, so the ceiling passed
608 # both. Only the request whose compare-and-set lands composes anything;
609 # it is released whenever this request ends without closing the
610 # dispute, so a refused amount can simply be tried again.
611 claim, answer = _claim_the_dispute(base, dispute)
612 if answer is not None:
613 return answer
614 try:
615 result = _compose_and_close(base, request, access, dispute, kind, note,
616 claim)
617 except Unreadable as exc:
618 _release_the_claim(base, dispute_id, claim)
619 return {"status": 503,
620 "error": (f"What this dispute has already been given cannot be "
621 f"read right now ({exc}), so nothing was issued and "
622 f"the dispute is still open. Try again in a moment.")}
623 except Exception:
624 _release_the_claim(base, dispute_id, claim)
625 raise
626 if not result.get("ok"):
627 _release_the_claim(base, dispute_id, claim)
628 return result
629
630
631def _already_resolved(dispute_id, dispute):
632 return {"ok": True, "dispute_id": dispute_id,
633 "resolution_kind": _text(dispute.get("resolution_kind")),
634 "resolution_ref": _text(dispute.get("resolution_ref")),
635 "refund_id": "", "order_id": "", "wallet_entry_id": "",
636 "note": "this dispute was already resolved; no second refund, "
637 "replacement or credit was issued"}
638
639
640CLAIM_TTL = timedelta(minutes=10)
641
642
643def _claim_is_live(claim):
644 """A claim younger than CLAIM_TTL belongs to a request that may still be
645 running. An older one is a request that died; it may be taken over,
646 and the compensation markers then find what it had already written."""
647 try:
648 stamped = datetime.fromisoformat(claim.split(" ", 1)[1])
649 except (IndexError, ValueError):
650 return True # unreadable: assume somebody holds it
651 return datetime.now(timezone.utc) - stamped < CLAIM_TTL
652
653
654def _in_progress(dispute_id):
655 return {"status": 409, "code": "in_progress", "dispute_id": dispute_id,
656 "error": (f"Dispute {dispute_id} is being resolved by another "
657 f"request right now. Reload it in a moment: nothing was "
658 f"written by this one.")}
659
660
661def _claim_the_dispute(base, dispute):
662 """Returns (claim, None) or ("", answer)."""
663 dispute_id = _text(dispute.get("id"))
664 held = _text(dispute.get("resolution_claim"))
665 if held and _claim_is_live(held):
666 return "", _in_progress(dispute_id)
667 claim = (f"{object_ids.new_uuid4()} "
668 f"{datetime.now(timezone.utc).isoformat(timespec='seconds')}")
669 try:
670 object_records.update_collection_record(
671 "disputes", dispute_id, {"resolution_claim": claim},
672 base_dir=base, actor=ACTOR, preserve_read_only=True,
673 expected_rev=object_records.compute_record_rev(dispute))
674 except object_records.VersionConflictError:
675 try:
676 fresh = object_records.get_collection_record("disputes", dispute_id,
677 base_dir=base)
678 except Exception:
679 fresh = {}
680 if _text(fresh.get("status")) == RESOLVED:
681 return "", _already_resolved(dispute_id, fresh)
682 return "", _in_progress(dispute_id)
683 return claim, None
684
685
686def _release_the_claim(base, dispute_id, claim):
687 """Clear OUR claim (never somebody else's) when this request ends
688 without closing the dispute."""
689 try:
690 current = object_records.get_collection_record("disputes", dispute_id,
691 base_dir=base)
692 if _text(current.get("resolution_claim")) != claim:
693 return
694 object_records.update_collection_record(
695 "disputes", dispute_id, {"resolution_claim": ""},
696 base_dir=base, actor=ACTOR, preserve_read_only=True,
697 expected_rev=object_records.compute_record_rev(current))
698 except Exception:
699 pass
700
701
702def _history(base, collection):
703 """Rows of `collection`: [] when it is not installed, Unreadable for any
704 other failure -- a ceiling computed from an unread history is not a
705 ceiling."""
706 try:
707 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
708 return object_records.read_collection_records(collection, base_dir=base)
709 except object_collections.CollectionNotFoundError:
710 return []
711 except Exception as exc:
712 raise Unreadable(f"{collection}: {str(exc)[:120]}") from exc
713
714
715class Unreadable(Exception):
716 pass
717
718
719def _credit_ceiling(base, dispute, order, payments):
720 """The most store credit this dispute may issue: what the customer
721 actually paid for the thing argued about, minus what has already gone
722 back for it -- refunds against those payments, and credits issued by
723 other disputes about the same order or payment.
724
725 The credit path used to have no ceiling at all (a 36.00 order was
726 "resolved" with 999,999.00 of spendable credit). Measured in money
727 RECEIVED, on purpose: the money is what a credit compensates, it is
728 what the refund path's ceiling is measured in (hook_refunds). An order
729 nobody has paid for has a ceiling of zero: it is corrected by amending
730 its invoice, not by handing out credit. And never more than the order's
731 own total, when it states one: money received over the total (a double
732 payment) is the payment's to refund, not the dispute's to credit.
733
734 Only the payments _scope let through count: a ceiling measured in
735 somebody else's money let a dispute about their payment credit the
736 resolver's own wallet.
737 """
738 dispute_id = _text(dispute.get("id"))
739 payment_id = _text(dispute.get("payment_id"))
740 paid_with = [row for row in payments
741 if _text(row.get("status") or "received") == "received"]
742 payment_ids = {_text(row.get("id")) for row in paid_with}
743 paid = sum(_cents(row.get("amount_cents")) for row in paid_with)
744 total = _int_or_none(order.get("total_cents")) if order else None
745 if total is not None and total > 0:
746 paid = min(paid, total)
747
748 refunded = sum(_cents(row.get("amount_cents"))
749 for row in _history(base, "refunds")
750 if _text(row.get("payment_id")) in payment_ids)
751
752 order_id = _text(dispute.get("order_id"))
753 siblings = {_text(row.get("id")) for row in _history(base, "disputes")
754 if _text(row.get("id")) != dispute_id
755 and ((order_id and _text(row.get("order_id")) == order_id)
756 or (payment_id and _text(row.get("payment_id")) == payment_id))}
757 markers = {_marker(other) for other in siblings}
758 credited = sum(_cents(row.get("amount_minor"))
759 for row in _history(base, "wallet_entries")
760 if _text(row.get("generated_from")) in markers
761 and _cents(row.get("amount_minor")) > 0)
762 return max(0, paid - refunded - credited), {
763 "paid_cents": paid, "refunded_cents": refunded,
764 "credited_by_other_disputes_cents": credited}
765
766
767def _truthy(value):
768 return _text(value).lower() in ("true", "1", "yes", "on")
769
770
771def _compose_and_close(base, request, access, dispute, kind, note, claim):
772 dispute_id = _text(dispute.get("id"))
773 order, payments = {}, []
774 if kind in PAYOUT_KINDS:
775 order, payments, refusal = _scope(base, access, dispute)
776 if refusal:
777 return refusal
778 owner = (_text(order.get("owner_id"))
779 or _text(dispute.get("owner_id"))
780 or _text(order.get("owner_id"))
781 or _text((request.get("_identity") or {}).get("user_id")))
782 actor_user = (_text((request.get("_identity") or {}).get("user_id"))
783 or owner)
784 when = _text(request.get("today")) or date.today().isoformat()
785
786 resolution_ref = ""
787 refund_id = ""
788 replacement_id = ""
789 entry_id = ""
790 amount = _cents(request.get("amount_cents"))
791
792 # --- the compensating record, composed BEFORE the dispute is closed ---
793 # Statuses follow facts and never lead them: a dispute marked resolved
794 # while its refund is still being argued about by a gate is exactly the
795 # lie this package exists to prevent.
796 if kind == "refund":
797 existing = _already_refunded(base, dispute_id)
798 if existing is not None:
799 refund_id = _text(existing.get("id"))
800 resolution_ref = f"refunds/{refund_id}"
801 else:
802 if amount <= 0:
803 return {"status": 400,
804 "error": ("A refund of nothing is not a refund: pass "
805 "amount_cents, or resolve this as no_action "
806 "with a reason if no money is going back.")}
807 payment = _payment_for(dispute, payments)
808 if payment is None:
809 return {"status": 409,
810 "error": ("No payment to refund against. Money can "
811 "only go back the way it came, so a refund "
812 "needs the payment it compensates -- point "
813 "the dispute at a payment_id, or resolve it "
814 "as a credit or a replacement.")}
815 candidate = {
816 "id": object_ids.new_uuid4(),
817 "payment_id": _text(payment.get("id")),
818 "amount_cents": str(amount),
819 "reason": f"{_marker(dispute_id)} {note}".strip()[:300],
820 "refunded_on": when,
821 # The money's account, not whoever typed the dispute.
822 "owner_id": _text(payment.get("owner_id")) or owner,
823 }
824 # DEFER to the existing ceiling rather than growing a second
825 # opinion about it, and surface its words unchanged so the
826 # customer is quoted the same number whichever door they came
827 # through.
828 verdict, error = _call("hook_refunds",
829 {"action": "create", "collection": "refunds",
830 "record": candidate},
831 method="BEFORE_WRITE")
832 if error:
833 return {"status": 503,
834 "error": (f"The refund gate could not be consulted "
835 f"({error}), so no money is going anywhere "
836 f"and the dispute is still open. Refunds are "
837 f"app-payments' arithmetic and this action "
838 f"refuses to guess at it.")}
839 if isinstance(verdict, dict) and verdict.get("error"):
840 return {"status": verdict.get("status", 409),
841 "error": _text(verdict.get("error")),
842 "refund": _text(verdict.get("error"))}
843 if isinstance(verdict, dict) and isinstance(verdict.get("record"),
844 dict):
845 candidate = verdict["record"]
846 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
847 object_records.create_collection_record("refunds", candidate,
848 base_dir=base, actor=ACTOR)
849 refund_id = _text(candidate.get("id"))
850 resolution_ref = f"refunds/{refund_id}"
851
852 elif kind == "replacement":
853 existing = _already_replaced(base, dispute_id)
854 if existing is not None:
855 replacement_id = _text(existing.get("id"))
856 resolution_ref = f"orders/{replacement_id}"
857 else:
858 if not order:
859 return {"status": 409,
860 "error": ("A replacement needs the order it replaces. "
861 "This dispute names no order_id, so there "
862 "are no lines to send again and no customer "
863 "to send them to.")}
864 # Read before the replacement order exists: an unreadable
865 # order_lines used to make a replacement with no lines at all.
866 lines = _history(base, "order_lines")
867 replacement_id = object_ids.new_uuid4()
868 number = (_text(request.get("number"))
869 or f"{_text(order.get('number'))}-R")
870 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
871 object_records.create_collection_record(
872 "orders",
873 {
874 "id": replacement_id,
875 "doc_type": "sale",
876 "number": number,
877 "customer_id": _text(order.get("customer_id")),
878 "customer_name": _text(order.get("customer_name")),
879 "customer_email": _text(order.get("customer_email")),
880 "currency": _text(order.get("currency")) or "USD",
881 # Confirmed, not draft. The order schema's own words are
882 # that a draft is not a commitment, and a resolution
883 # pointing at a document that promises nothing is the
884 # failure hook_disputes exists to prevent.
885 "status": "confirmed",
886 "order_date": when,
887 "ship_to_name": _text(order.get("ship_to_name")),
888 "ship_to_address": _text(order.get("ship_to_address")),
889 "customer_note": _text(order.get("customer_note")),
890 "notes": (f"Generated by {ACTOR} [{_marker(dispute_id)} "
891 f"orders/{order['id']}] -- no-charge replacement"),
892 "owner_id": owner,
893 },
894 base_dir=base, actor=ACTOR)
895 _copy_lines(base, lines, order["id"], replacement_id, owner)
896 resolution_ref = f"orders/{replacement_id}"
897
898 elif kind == "credit":
899 existing = _already_credited(base, dispute_id)
900 if existing is not None:
901 entry_id = _text(existing.get("id"))
902 resolution_ref = f"wallet_entries/{entry_id}"
903 else:
904 if amount <= 0:
905 return {"status": 400,
906 "error": ("A credit of nothing is not a credit: pass "
907 "amount_cents, or resolve this as no_action "
908 "with a reason.")}
909 if _rows("wallet_entries", base) is None:
910 return {"status": 409,
911 "error": ("There is no wallet on this server to credit: "
912 "store credit is a wallet entry and wallets "
913 "come from app-billing, which is not "
914 "installed. Refusing rather than closing this "
915 "dispute as though credit had been issued -- "
916 "refund it, replace it, or say no_action and "
917 "why."),
918 "missing_app": "app-billing"}
919 try:
920 ceiling, basis = _credit_ceiling(base, dispute, order, payments)
921 except Unreadable as exc:
922 return {"status": 503,
923 "error": (f"What was paid and already given back for "
924 f"this dispute cannot be read right now "
925 f"({exc}), so no credit was issued and the "
926 f"dispute is still open.")}
927 if amount > ceiling and not (access.is_admin
928 and _truthy(request.get("over_ceiling"))):
929 # An admin may knowingly give more than was paid (goodwill),
930 # but has to say so; nobody does it by typo.
931 return {"status": 409, "code": "credit_over_ceiling",
932 "ceiling_cents": str(ceiling), **{
933 key: str(value) for key, value in basis.items()},
934 "error": (f"A credit of {amount} is more than this "
935 f"dispute can give back: {ceiling} (paid "
936 f"{basis['paid_cents']}, less refunds and "
937 f"other disputes' credits). Nothing was "
938 f"issued; the dispute is still open.")}
939 wallet, problem = _wallet_for(base, request, access, dispute, order)
940 if wallet is None:
941 return {"status": 409,
942 "error": (f"No wallet to credit ({problem}). A credit "
943 f"has to land somewhere the customer can "
944 f"spend it: pass the id of one of the "
945 f"customer's own wallets, or open a wallet "
946 f"for this customer first. A credit issued "
947 f"into a wallet nobody owns is a number that "
948 f"never becomes money."),
949 "missing_wallet": problem}
950 mismatch = _currency_mismatch(base, dispute, order, wallet)
951 if mismatch:
952 return mismatch
953 entry_id = object_ids.new_uuid4()
954 # access: the dispute's own order, payment, wallet and compensation, after Access.can on the dispute above
955 object_records.create_collection_record(
956 "wallet_entries",
957 {
958 "id": entry_id,
959 "wallet_id": _text(wallet.get("id")),
960 # Positive: credit is money going TO the customer, and
961 # the sign convention is the ledger's, not ours.
962 "amount_minor": str(amount),
963 "kind": "adjustment",
964 "description": note or f"Dispute {dispute_id} resolved as "
965 f"store credit",
966 "reference": _marker(dispute_id),
967 "generated_from": _marker(dispute_id),
968 "owner_id": _text(wallet.get("owner_id")) or owner,
969 },
970 base_dir=base, actor=ACTOR)
971 resolution_ref = f"wallet_entries/{entry_id}"
972
973 # --- the paperwork, last ------------------------------------------------
974 patch = {
975 "status": RESOLVED,
976 "resolution_kind": kind,
977 "resolution_ref": resolution_ref,
978 "resolved_by": actor_user,
979 "resolved_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
980 }
981 if note:
982 patch["resolution_note"] = note
983 # Asked of the gate without the claim, which is this action's
984 # bookkeeping and not part of the resolution.
985 gate_patch = dict(patch)
986
987 # The gate, asked one final time with the ref now filled in. It cannot
988 # refuse a resolution this action just composed, and that is exactly
989 # the point: if it ever does, the two have drifted and the dispute
990 # stays open rather than closing over a record nobody can find.
991 refusal = _ask_the_gate({**dispute, **gate_patch})
992 if refusal:
993 return {**refusal,
994 "resolution_ref": resolution_ref,
995 "note": "the compensating record was written but the dispute "
996 "was NOT closed; it is still open for somebody to "
997 "finish"}
998
999 # Closed and unclaimed in one write: `resolved` is now the guard.
1000 patch["resolution_claim"] = ""
1001 object_records.update_collection_record("disputes", dispute_id, patch,
1002 base_dir=base, actor=ACTOR,
1003 preserve_read_only=True)
1004
1005 return {"ok": True, "dispute_id": dispute_id, "resolution_kind": kind,
1006 "resolution_ref": resolution_ref, "refund_id": refund_id,
1007 "order_id": replacement_id, "wallet_entry_id": entry_id,
1008 "amount_cents": str(amount) if amount > 0 else "0",
1009 "status_of_dispute": RESOLVED, "date": when}