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
refunds.py · 19.4 KB · 424 lines
1"""Pre-write hook for refunds: the invariant gate, the stamp, and a refund
2that stays what it was when it was recorded.
3
4Two doctrines in one hook (docs/logic-decisions.md):
5- #3 money moves: a refund is a compensating record; this gate keeps the
6 movement honest -- amount <= payment.amount minus prior refunds, and no
7 refunding a bounced payment. Sums refund records directly (authoritative,
8 never derived values).
9- #1 stamp point-in-time facts: invoice_id is copied from the payment at
10 write time (a transform), never trusted from the client -- so invoices can
11 roll refunds up directly and the pointer can never disagree with the
12 payment it compensates.
13
14Both used to hold on CREATE only, while the owner could PUT and DELETE. A
154000 refund was raised to 25000 on a 10000 payment; a 100 refund was
16edited to -999999, which the invoice rollup read as 999999 more paid; a
17refund was re-pointed at an invoice that was never paid; a full refund
18was deleted and issued again, so 20000 went out against 10000 with one
19record on file. A compensating record that can itself be rewritten
20compensates for nothing, so:
21
22- Somebody who is not an admin may change only `reason`. The amount, the
23 payment, the invoice and the date are the record of money that left.
24 The correction for a refund that should not have been made is a new
25 payment; for one that was too small, another refund.
26- Nobody but an admin may delete a refund (deleting one reopens its
27 headroom). That is the permission rules now (no delete grant, the owner
28 fallback denied), not code here.
29- An admin may do both, through the same gate as a create: positive
30 amount, within the payment minus the OTHER refunds, not against a
31 bounced payment, and invoice_id is whatever the payment says -- an
32 invoice_id that disagrees with the payment is refused, not corrected
33 silently.
34
35This position is the conservative one, taken because the owner had not
36decided otherwise. Loosening it is one edit to _OWNER_EDITABLE.
37
38action_disposition_return and action_resolve_dispute write refunds at the
39storage level and ask this hook first, by calling it with action "create"
40and writing the record it hands back.
41
42**The headroom is decided where the refund lands: LOCKED_CHECK.** A hook
43runs before the write lock, so BEFORE_WRITE's gate is a friendly early
44answer: two refunds submitted at once each read a ledger without the
45other, a refund written below the hook was never asked, and a payment
46bounced or lowered while a refund was in flight was not seen. The schema
47declares LOCKED_CHECK (refunds.json `locked_checks`), which object_records
48calls for every create and every change of amount, payment or invoice --
49whoever the writer, the two actions included -- holding the "ledger" check
50lock every write to payments also takes. It holds the gate's invariants
51against the ledger as it is when the refund lands:
52
53- the payment exists and has not bounced, and the refund fits in what is
54 left of it after the OTHER refunds (checked when a write adds: a create,
55 a raised amount, a move to another payment);
56- invoice_id is the payment's invoice -- a storage-level writer that did
57 not ask this hook to stamp it is refused, not corrected.
58
59A refusal is 409 `check_refused` with the same sentence the gate gives.
60Deleting a refund is not checked: it only gives headroom back (only an
61admin may, by the permission rules). `payment_seq` (v3's per-payment sequence,
62which serialized hooked writers only) is no longer stamped or constrained;
63the column stays so no data is dropped, and a client value is blanked.
64
65Every read fails CLOSED: a collection that cannot be read is a 503, never
66"nothing there".
67"""
68
69import os
70
71import object_collections
72import object_records
73
74SEQ = "payment_seq"
75
76# What the person who recorded a refund may still change. An allow-list,
77# so a field added to the schema later is frozen until somebody decides
78# otherwise.
79_OWNER_EDITABLE = {"reason"}
80
81_MISSING = (object_records.RecordNotFoundError,
82 object_collections.CollectionNotFoundError,
83 object_records.InvalidRecordIdError)
84
85
86def _base_dir():
87 return os.environ.get("DBBASIC_DATA_DIR", "data")
88
89
90def _stored(value):
91 return "" if value is None else str(value)
92
93
94def _is_admin(request):
95 roles = (request.get("subject") or {}).get("roles") or []
96 return "admin" in roles
97
98
99def _rows(collection, field, value, base, *, indexed=False):
100 """The rows of `collection` whose `field` is `value`, read through
101 object_records (so a read that fails raises). `indexed` -- LOCKED_CHECK
102 asks for it, because it runs inside the write lock where every writer
103 waits on it -- uses read_collection_records_where, the same rows
104 without copying every other one."""
105 reader = getattr(object_records, "read_collection_records_where", None) if indexed else None
106 if reader is not None:
107 return reader(collection, field, str(value), base_dir=base)
108 return [row for row in object_records.read_collection_records(collection, base_dir=base)
109 if row.get(field) == value]
110
111
112def _unreadable(what):
113 return {"error": (f"{what} could not be read, so this refund cannot be checked "
114 "against what has already been refunded. Nothing was changed."),
115 "status": 503}
116
117
118def _gate(record, base, *, exclude_id="", missing_is_refusal=False, indexed=False):
119 """The create gate, run over the row as it would be stored. Returns
120 (refusal, None), or (None, the payment's invoice_id). (None, None) when
121 there is nothing to gate (schema validation will report why) -- unless
122 `missing_is_refusal`, which LOCKED_CHECK asks for: it runs after
123 validation, so a payment missing then was deleted since."""
124 try:
125 amount = int(record.get("amount_cents") or 0)
126 except (TypeError, ValueError):
127 amount = 0 if missing_is_refusal else None
128 if amount is None:
129 return None, None # schema validation reports the type error properly
130 # A positive amount is the schema's validation.min, for every writer.
131
132 payment_id = record.get("payment_id")
133 if not payment_id:
134 if missing_is_refusal:
135 return {"error": "A refund names the payment it refunds.", "status": 409}, None
136 return None, None # required + relation validation own this
137 try:
138 payment = object_records.get_collection_record("payments", payment_id, base_dir=base)
139 except _MISSING:
140 if missing_is_refusal:
141 return {"error": (f"Payment {payment_id} no longer exists, so there is nothing to "
142 "refund. Nothing was recorded."), "status": 409}, None
143 return None, None # relation validation owns a missing payment
144 except Exception:
145 return _unreadable("The payment"), None
146 if (payment.get("status") or "received") == "bounced":
147 return {"error": "Cannot refund a bounced payment.", "status": 409}, None
148
149 try:
150 refunds = _rows("refunds", "payment_id", payment_id, base, indexed=indexed)
151 except Exception:
152 return _unreadable("Refunds"), None
153 prior = 0
154 for row in refunds:
155 if exclude_id and row.get("id") == exclude_id:
156 continue
157 try:
158 prior += int(row.get("amount_cents") or 0)
159 except (TypeError, ValueError):
160 # Skipping it would under-count what has gone back and widen
161 # the headroom: the open direction.
162 return {"error": (f"Refund {row.get('id')} on payment {payment_id} has an "
163 "unreadable amount; correct it before refunding more."),
164 "status": 409}, None
165 try:
166 paid = int(payment.get("amount_cents") or 0)
167 except (TypeError, ValueError):
168 paid = 0 # nothing readable was paid: nothing is refundable
169 refundable = paid - prior
170 if amount > refundable:
171 return {
172 "error": (
173 f"Refund of {amount} cents exceeds the refundable "
174 f"{max(refundable, 0)} cents on payment {payment_id} "
175 f"({paid} paid, {prior} already refunded)."
176 ),
177 "status": 409,
178 }, None
179 return None, _stored(payment.get("invoice_id"))
180
181
182def _check_create(request):
183 record = dict(request.get("record") or {})
184 refusal, invoice_id = _gate(record, _base_dir())
185 if refusal:
186 return refusal
187 if invoice_id is None:
188 if not _stored(record.get(SEQ)):
189 return None
190 record[SEQ] = "" # carry no number, never the client's
191 return {"record": record}
192 # Stamp: invoice_id always comes from the payment, never the client.
193 # (v3 also stamped a sequence number here; the column is retired and
194 # a client's value is blanked.)
195 record["invoice_id"] = invoice_id
196 record[SEQ] = ""
197 return {"record": record}
198
199
200def _check_update(request):
201 existing = request.get("existing") or {}
202 record = dict(request.get("record") or {})
203 changes = request.get("changes") or {}
204
205 # A change is a submitted field whose value would differ: a form posts
206 # everything it shows, and sending the amount back unchanged edits
207 # nothing.
208 changed = sorted(name for name in changes
209 if name != "id" and _stored(record.get(name)) != _stored(existing.get(name)))
210 if not changed:
211 return None
212
213 if SEQ in changed and _is_admin(request):
214 return {"error": f"{SEQ} is a retired server-stamped column; it is not edited.",
215 "status": 409}
216
217 if not _is_admin(request):
218 frozen = [name for name in changed if name not in _OWNER_EDITABLE]
219 if frozen:
220 return {"error": (
221 f"A recorded refund is not edited ({', '.join(frozen)}): money moves, "
222 "it does not mutate. If too little was refunded, record another refund; "
223 "if this one should not have been made, record the payment again."),
224 "status": 409}
225 return None
226
227 if not {"amount_cents", "payment_id", "invoice_id"} & set(changed):
228 return None
229
230 refusal, invoice_id = _gate(record, _base_dir(), exclude_id=_stored(existing.get("id")))
231 if refusal:
232 return refusal
233 if invoice_id is None:
234 return None
235 if _stored(record.get("invoice_id")) != invoice_id and "invoice_id" in changed:
236 return {"error": (f"A refund's invoice is its payment's invoice "
237 f"({invoice_id or 'none'}); it cannot be set to "
238 f"{_stored(record.get('invoice_id')) or 'blank'}. "
239 "Re-point the refund at another payment instead."),
240 "status": 409}
241 if _stored(record.get("invoice_id")) == invoice_id:
242 return None
243 # The payment changed, or a stored row's invoice disagrees with its
244 # payment (written before the gate checked it): carry the payment's.
245 record["invoice_id"] = invoice_id
246 return {"record": record}
247
248
249def BEFORE_WRITE(request):
250 action = request.get("action")
251 if action == "create":
252 return _check_create(request)
253 if action == "update":
254 return _check_update(request)
255 return None
256
257
258def LOCKED_CHECK(request):
259 """The refund invariants, decided by object_records inside the write
260 lock and the "ledger" check lock, for every writer (see the module
261 docstring and refunds.json `locked_checks`). Reads only; never asks
262 who is writing.
263
264 `record` is the row as it would be stored, `existing` the row on file
265 (read under the lock; None on create). Returns None or a refusal."""
266 action = request.get("action")
267 if action not in ("create", "update"):
268 return None
269 record = request.get("record") or {}
270 existing = request.get("existing") or {}
271 base = request.get("base_dir") or _base_dir()
272
273 adds = True
274 if action == "update":
275 try:
276 raised = int(record.get("amount_cents") or 0) > int(existing.get("amount_cents") or 0)
277 except (TypeError, ValueError):
278 raised = True
279 adds = raised or _stored(record.get("payment_id")) != _stored(existing.get("payment_id"))
280
281 if adds:
282 refusal, invoice_id = _gate(record, base, exclude_id=_stored(existing.get("id")),
283 missing_is_refusal=True, indexed=True)
284 if refusal:
285 return refusal
286 else:
287 # A refund lowered, or its invoice touched, takes no headroom; what
288 # still has to hold is that it names its payment's invoice.
289 try:
290 payment = object_records.get_collection_record(
291 "payments", _stored(record.get("payment_id")), base_dir=base)
292 except _MISSING:
293 return {"error": (f"Payment {record.get('payment_id')} no longer exists. Nothing "
294 "was changed."), "status": 409}
295 except Exception:
296 return _unreadable("The payment")
297 invoice_id = _stored(payment.get("invoice_id"))
298
299 if _stored(record.get("invoice_id")) != invoice_id:
300 return {"error": (f"A refund's invoice is its payment's invoice ({invoice_id or 'none'}), "
301 f"not {_stored(record.get('invoice_id')) or 'blank'}. Nothing was "
302 "recorded."), "status": 409}
303 return (_line_ceiling(action, record, existing, invoice_id, base)
304 or _goodwill_ceiling(record, existing, base)
305 or _credit_note_ceiling(record, existing, invoice_id, base))
306
307
308def _credit_note_ceiling(record, existing, invoice_id, base):
309 """A refund that returns the money a credit note cancelled (refunds v7,
310 credit_note_id: refunding a sale is a credit note plus a refund, the
311 owner's decision of 2026-11-30) cites a credit note that credits this
312 refund's invoice and is not void, and the refunds citing it never add up
313 to more than the credit note is worth."""
314 credit_note_id = _stored(record.get("credit_note_id")).strip()
315 if not credit_note_id:
316 return None
317 import object_collections
318 try:
319 try:
320 note = object_records.get_collection_record("invoices", credit_note_id, base_dir=base)
321 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
322 note = None
323 given = sum(int(_stored(r.get("amount_cents")) or 0)
324 for r in object_records.read_collection_records("refunds", base_dir=base)
325 if _stored(r.get("credit_note_id")) == credit_note_id
326 and _stored(r.get("id")) != _stored(existing.get("id")))
327 except object_collections.CollectionNotFoundError:
328 note, given = None, 0
329 except Exception:
330 return _unreadable("The credit note this refund returns money for")
331 if (note is None or _stored(note.get("doc_type")) != "credit_note"
332 or _stored(note.get("status")) == "void"):
333 return {"error": f"Credit note {credit_note_id} does not exist. Nothing was recorded.",
334 "status": 409}
335 if _stored(note.get("credits_invoice_id")) != invoice_id:
336 return {"error": (f"Credit note {credit_note_id} credits another invoice, not "
337 f"{invoice_id or 'none'}. Nothing was recorded."), "status": 409}
338 value = int(_stored(note.get("total_cents")) or 0)
339 if given + int(_stored(record.get("amount_cents")) or 0) > value:
340 return {"error": (f"Credit note {credit_note_id} is worth {value}; {given} has already "
341 f"been refunded against it. Nothing was recorded."), "status": 409}
342 return None
343
344
345def _goodwill_ceiling(record, existing, base):
346 """A refund that pays out goodwill (refunds.goodwill_id, app-counter)
347 cites a goodwill record that exists, and the refunds citing it never
348 add up to more than the value a manager approved."""
349 goodwill_id = _stored(record.get("goodwill_id")).strip()
350 if not goodwill_id:
351 return None
352 import object_collections
353 try:
354 try:
355 granted = object_records.get_collection_record("goodwill", goodwill_id, base_dir=base)
356 except (object_records.RecordNotFoundError, object_collections.CollectionNotFoundError):
357 granted = None
358 given = sum(int(_stored(r.get("amount_cents")) or 0)
359 for r in object_records.read_collection_records("refunds", base_dir=base)
360 if _stored(r.get("goodwill_id")) == goodwill_id
361 and _stored(r.get("id")) != _stored(existing.get("id")))
362 except Exception:
363 return _unreadable("The goodwill this refund pays out")
364 if granted is None:
365 return {"error": f"Goodwill {goodwill_id} does not exist. Nothing was recorded.",
366 "status": 409}
367 value = int(_stored(granted.get("value_cents")) or 0)
368 if given + int(_stored(record.get("amount_cents")) or 0) > value:
369 return {"error": (f"That goodwill was approved for {value}; {given} has already been paid "
370 f"out against it. Nothing was recorded."), "status": 409}
371 return None
372
373
374def _line_ceiling(action, record, existing, invoice_id, base):
375 """A refund that cites an order line (refunds v6, the Corner Cup
376 finding: refunds carried no line, only reason text) must cite a line
377 of the order its invoice bills, and with the refunds and credit notes
378 already citing that line must not correct more than was sold. Decided
379 here, inside the ledger lock, so two cashiers refunding the same soup
380 at once cannot both give it back."""
381 line_id = _stored(record.get("order_line_id")).strip()
382 if not line_id:
383 return None
384 if action == "update" and line_id == _stored(existing.get("order_line_id")).strip() \
385 and _stored(record.get("quantity")) == _stored(existing.get("quantity")):
386 return None
387 import object_collections
388 import object_corrections
389
390 def rows(collection):
391 try:
392 return object_records.read_collection_records(collection, base_dir=base)
393 except object_collections.CollectionNotFoundError:
394 return []
395
396 try:
397 line = next((row for row in rows("order_lines") if _stored(row.get("id")) == line_id), None)
398 invoices = rows("invoices")
399 invoice = next((row for row in invoices if _stored(row.get("id")) == invoice_id), None)
400 order = next((row for row in rows("orders")
401 if line and _stored(row.get("id")) == _stored(line.get("order_id"))), None)
402 already = object_corrections.corrected_quantity(
403 line_id, refunds=rows("refunds"), invoices=invoices,
404 invoice_lines=rows("invoice_lines"), exclude_refund_id=_stored(existing.get("id")))
405 except Exception:
406 return _unreadable("The order line this refund cites")
407 if line is None:
408 return {"error": f"Order line {line_id} does not exist. Nothing was recorded.",
409 "status": 409}
410 bills = {_stored(b.get("id")) for b in object_corrections.bills_for_order(order, [invoice] if invoice else [])}
411 if invoice_id not in bills:
412 return {"error": (f"Order line {line_id} is not on the order invoice {invoice_id or 'none'} "
413 f"bills, so this refund cannot cite it. Nothing was recorded."),
414 "status": 409}
415 if _stored(record.get("credit_note_id")).strip():
416 # The credit note this refund pays out already counted these units
417 # against the line (its own line cites it); counting the refund too
418 # would give back one soup and call it two. _credit_note_ceiling
419 # caps the money at the credit note's value.
420 return None
421 refusal = object_corrections.ceiling_refusal(line, record.get("quantity"), already)
422 if refusal:
423 return {"error": refusal + " Nothing was recorded.", "status": 409}
424 return None