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.
payments.py · 18.1 KB · 426 lines
| 1 | """Pre-write hook for payments: the overpayment gate, and a payment that |
| 2 | stays what it was when it was recorded. |
| 3 | |
| 4 | **The ceiling.** A payment may not take an invoice past what it is worth: |
| 5 | received payments minus refunds plus this payment must stay <= the |
| 6 | invoice's ceiling less the credit notes applied to it (invoice_credits: a |
| 7 | credit note cancels debt, so a credited bill owes less). Configurable via app_settings key |
| 8 | `payments.overpayment_policy` ("reject", the default, or "allow" for shops |
| 9 | that keep customer credit balances). That is decided in LOCKED_CHECK below |
| 10 | and nowhere else: this hook no longer answers it early. amount_cents being |
| 11 | positive is the schema's `validation.min` for every writer. |
| 12 | |
| 13 | **What the ceiling is, and why it is not just invoices.total_cents.** That |
| 14 | field is a cache: the invoice_totals handler stamps it from the lines, it |
| 15 | is best-effort and off on a stock install, and it is an ordinary |
| 16 | owner-writable field. A gate that capped against it authorised 10000 |
| 17 | against an invoice whose one line had been cut to 4000 while the handler |
| 18 | was not running, and 999999 against a 4000 invoice whose owner typed the |
| 19 | total. AGENTS.md: a gate must sum the evidence, not read the cache. So: |
| 20 | |
| 21 | - When the invoice HAS lines, the ceiling is the smaller of the stamped |
| 22 | total and what the lines say (subtotal via object_lines, plus tax). A |
| 23 | stale or typed total can only lower it. |
| 24 | - Tax can live on the lines (a rate per line) or on the document |
| 25 | (invoices.tax_cents, computed once at checkout). Which one is |
| 26 | authoritative when both are present is an open decision this hook does |
| 27 | not take: it allows the LARGER of the two, so it can never refuse the |
| 28 | total a customer was actually quoted. The stamped total still bounds it. |
| 29 | - When the invoice has NO lines, the stamped total is the only statement |
| 30 | of what is owed and is the ceiling. (A total that was never stamped |
| 31 | reads 0 and refuses every payment -- closed, as before.) |
| 32 | - A total or tax that does not parse refuses. It used to pass. |
| 33 | |
| 34 | **Recorded money does not change.** The gate above ran on create only, |
| 35 | while the owner could PUT and DELETE: 9000 on a 10000 invoice became |
| 36 | 50000 by an edit; a payment refunded in full was lowered to 100; a |
| 37 | refunded payment was deleted from under its refund. docs/logic-decisions.md |
| 38 | #3 -- money never mutates, it moves -- is now what the hook does: |
| 39 | |
| 40 | - Somebody who is not an admin may change only `status` (the schema's |
| 41 | transitions allow received -> bounced, nothing else) and `notes`. The |
| 42 | amount, the invoice it is against, the date, method and reference are |
| 43 | the record of what happened. A correction is a refund, or a bounce and |
| 44 | a new payment. |
| 45 | - Nobody but an admin may delete a payment. That is the permission rules |
| 46 | now (no delete grant, and the owner fallback denied), not code here. |
| 47 | - An admin may do both, because somebody has to be able to repair a |
| 48 | mistyped ledger -- but through the same invariants: the amount stays |
| 49 | positive, never drops below what has been refunded against it, never |
| 50 | takes its invoice past the ceiling; a payment with refunds cannot be |
| 51 | re-pointed or deleted (delete the refunds first -- deliberately two |
| 52 | acts). Those invariants are LOCKED_CHECK's, for an admin's edit exactly |
| 53 | as for anyone's. |
| 54 | |
| 55 | This position is the conservative one, taken because the owner had not |
| 56 | decided otherwise. Loosening it is one edit to _OWNER_EDITABLE. |
| 57 | |
| 58 | Trusted server-side writers (the Stripe webhook, checkout's gift-card |
| 59 | payment, resolve_bank_line's bounce) go through object_records and do not |
| 60 | reach BEFORE_WRITE: who may do what is a question about a person, and they |
| 61 | are not one. They do meet the ceiling, below. |
| 62 | |
| 63 | **The ceiling is decided where the payment lands: LOCKED_CHECK.** A hook |
| 64 | runs before the write lock, so BEFORE_WRITE's ceiling is a friendly early |
| 65 | answer and nothing more: two payments submitted at once each read a ledger |
| 66 | without the other; a payment written below the hook was never asked; an |
| 67 | invoice line cut while a payment was in flight was not seen. The schema |
| 68 | declares LOCKED_CHECK (payments.json `locked_checks`), and object_records |
| 69 | calls it for every create, every change of amount, invoice or status, and |
| 70 | every delete -- whoever the writer -- holding the "ledger" check lock, which |
| 71 | every write to payments, refunds, invoices, invoice_lines and app_settings |
| 72 | takes. So the ledger it sums is the ledger the payment lands on, and the |
| 73 | invoice it measures is the invoice as it is at that instant. It holds the |
| 74 | same invariants BEFORE_WRITE does, minus the ones about who is asking: |
| 75 | |
| 76 | - a received payment that adds to an invoice (a create, a raised amount, a |
| 77 | move to another invoice, a status back to received) must fit under the |
| 78 | ceiling, computed exactly as above; |
| 79 | - an amount lowered may not go below what has been refunded against it; |
| 80 | - a payment with refunds is not moved to another invoice, or deleted. |
| 81 | |
| 82 | A refusal is 409 `check_refused`; BEFORE_WRITE used to give the same |
| 83 | sentence a little earlier as a 409 `hook_rejected`, and no longer does. `invoice_seq` (v3's per-invoice sequence, which serialized |
| 84 | hooked writers only) is no longer stamped or constrained; the column stays |
| 85 | so no data is dropped, and a client value is blanked on create. |
| 86 | |
| 87 | Every read fails CLOSED: a collection that cannot be read is a 503, never |
| 88 | "nothing there". |
| 89 | """ |
| 90 | |
| 91 | import os |
| 92 | |
| 93 | import object_collections |
| 94 | import object_lines |
| 95 | import object_records |
| 96 | |
| 97 | SEQ = "invoice_seq" |
| 98 | |
| 99 | # What the person who recorded a payment may still change. An allow-list, |
| 100 | # so a field added to the schema later is frozen until somebody decides |
| 101 | # otherwise. |
| 102 | _OWNER_EDITABLE = {"status", "notes"} |
| 103 | |
| 104 | _MISSING = (object_records.RecordNotFoundError, |
| 105 | object_collections.CollectionNotFoundError, |
| 106 | object_records.InvalidRecordIdError) |
| 107 | |
| 108 | |
| 109 | def _base_dir(): |
| 110 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 111 | |
| 112 | |
| 113 | def _text(value): |
| 114 | return str(value if value is not None else "").strip() |
| 115 | |
| 116 | |
| 117 | def _stored(value): |
| 118 | return "" if value is None else str(value) |
| 119 | |
| 120 | |
| 121 | def _is_admin(request): |
| 122 | roles = (request.get("subject") or {}).get("roles") or [] |
| 123 | return "admin" in roles |
| 124 | |
| 125 | |
| 126 | def _setting(key, default): |
| 127 | # Unreadable settings fall back to the default, and the default is |
| 128 | # "reject": the closed direction. |
| 129 | try: |
| 130 | for row in object_records.read_collection_records("app_settings", base_dir=_base_dir()): |
| 131 | if row.get("key") == key and row.get("value"): |
| 132 | return row["value"] |
| 133 | except Exception: |
| 134 | pass |
| 135 | return default |
| 136 | |
| 137 | |
| 138 | def _rows(collection, field, value, base, *, indexed=False): |
| 139 | """The rows of `collection` whose `field` is `value`, read through |
| 140 | object_records (so a read that fails raises). `indexed` -- LOCKED_CHECK |
| 141 | asks for it, because it runs inside the write lock where every writer |
| 142 | waits on it -- uses read_collection_records_where, the same rows |
| 143 | without copying every other one.""" |
| 144 | reader = getattr(object_records, "read_collection_records_where", None) if indexed else None |
| 145 | if reader is not None: |
| 146 | return reader(collection, field, str(value), base_dir=base) |
| 147 | return [row for row in object_records.read_collection_records(collection, base_dir=base) |
| 148 | if row.get(field) == value] |
| 149 | |
| 150 | |
| 151 | def _unreadable(what): |
| 152 | return {"error": (f"{what} could not be read, so this payment cannot be checked " |
| 153 | "against what has already been recorded. Nothing was changed."), |
| 154 | "status": 503} |
| 155 | |
| 156 | |
| 157 | def _cents(value): |
| 158 | """Integer cents, blank reads 0. Raises ValueError on anything else: |
| 159 | the callers decide what an unreadable amount means, and it is never |
| 160 | 'skip this row'.""" |
| 161 | text = _text(value) |
| 162 | return int(text) if text else 0 |
| 163 | |
| 164 | |
| 165 | def _invoice_ceiling(invoice, base, *, indexed=False): |
| 166 | """(ceiling_cents, None) or (None, refusal). See the module docstring.""" |
| 167 | invoice_id = _text(invoice.get("id")) |
| 168 | try: |
| 169 | stamped = _cents(invoice.get("total_cents")) |
| 170 | document_tax = _cents(invoice.get("tax_cents")) |
| 171 | except ValueError: |
| 172 | return None, { |
| 173 | "error": (f"Invoice {invoice_id} has a total or tax that is not a whole number " |
| 174 | f"of cents ({invoice.get('total_cents')!r}, {invoice.get('tax_cents')!r}), " |
| 175 | "so nothing can say what it is worth. Correct the invoice first."), |
| 176 | "status": 409} |
| 177 | |
| 178 | try: |
| 179 | lines = _rows("invoice_lines", "invoice_id", invoice_id, base, indexed=indexed) |
| 180 | except object_collections.CollectionNotFoundError: |
| 181 | lines = [] # no line collection installed: no lines exist |
| 182 | except Exception: |
| 183 | return None, _unreadable("Invoice lines") |
| 184 | if not lines: |
| 185 | return stamped, None |
| 186 | |
| 187 | folded = object_lines.totals(lines) |
| 188 | evidence = folded["subtotal_cents"] + max(folded["tax_cents"], document_tax) |
| 189 | return min(stamped, evidence), None |
| 190 | |
| 191 | |
| 192 | def _refunds_of(payment_id, base, *, indexed=False): |
| 193 | """(how many refunds point at one payment, their cents, None) or |
| 194 | (None, None, refusal).""" |
| 195 | try: |
| 196 | rows = _rows("refunds", "payment_id", payment_id, base, indexed=indexed) |
| 197 | except object_collections.CollectionNotFoundError: |
| 198 | return 0, 0, None |
| 199 | except Exception: |
| 200 | return None, None, _unreadable("Refunds") |
| 201 | count = total = 0 |
| 202 | for row in rows: |
| 203 | count += 1 |
| 204 | try: |
| 205 | total += _cents(row.get("amount_cents")) |
| 206 | except ValueError: |
| 207 | return None, None, { |
| 208 | "error": (f"Refund {row.get('id')} has an unreadable amount; " |
| 209 | "correct it before changing the payment it refunds."), |
| 210 | "status": 409} |
| 211 | return count, total, None |
| 212 | |
| 213 | |
| 214 | def _over_ceiling(invoice_id, amount, base, *, exclude_id="", missing_is_refusal=False, |
| 215 | indexed=False): |
| 216 | """A refusal when `amount` more on this invoice would pass its ceiling, |
| 217 | else None. A missing invoice is None from BEFORE_WRITE (relation |
| 218 | validation owns it) and a refusal from LOCKED_CHECK, which runs after |
| 219 | relation validation and so is looking at an invoice deleted since.""" |
| 220 | try: |
| 221 | invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base) |
| 222 | except _MISSING: |
| 223 | if missing_is_refusal: |
| 224 | return {"error": (f"Invoice {invoice_id} no longer exists, so nothing says what " |
| 225 | "this payment may be. Nothing was recorded."), "status": 409} |
| 226 | return None |
| 227 | except Exception: |
| 228 | return _unreadable("The invoice") |
| 229 | |
| 230 | ceiling, refusal = _invoice_ceiling(invoice, base, indexed=indexed) |
| 231 | if refusal: |
| 232 | return refusal |
| 233 | |
| 234 | try: |
| 235 | payments = _rows("payments", "invoice_id", invoice_id, base, indexed=indexed) |
| 236 | except Exception: |
| 237 | return _unreadable("Payments") |
| 238 | received = 0 |
| 239 | for row in payments: |
| 240 | if exclude_id and row.get("id") == exclude_id: |
| 241 | continue |
| 242 | if (row.get("status") or "received") != "received": |
| 243 | continue |
| 244 | try: |
| 245 | received += _cents(row.get("amount_cents")) |
| 246 | except ValueError: |
| 247 | # Skipping it would under-count what has been received and |
| 248 | # widen the headroom: the open direction. |
| 249 | return {"error": (f"Payment {row.get('id')} on invoice {invoice_id} has an " |
| 250 | "unreadable amount; correct it before recording more."), |
| 251 | "status": 409} |
| 252 | |
| 253 | try: |
| 254 | refunds = _rows("refunds", "invoice_id", invoice_id, base, indexed=indexed) |
| 255 | except object_collections.CollectionNotFoundError: |
| 256 | refunds = [] |
| 257 | except Exception: |
| 258 | return _unreadable("Refunds") |
| 259 | refunded = 0 |
| 260 | for row in refunds: |
| 261 | try: |
| 262 | refunded += _cents(row.get("amount_cents")) |
| 263 | except ValueError: |
| 264 | continue # ignoring a refund only narrows the headroom |
| 265 | |
| 266 | # Credit notes applied to this invoice cancel that much of the debt |
| 267 | # (status follows the money, 2026-11-30): a 950 bill credited 650 owes |
| 268 | # 300, and a payment of 950 against it is an overpayment. Summed from |
| 269 | # the invoice_credits rows -- the evidence -- not the credited_cents |
| 270 | # rollup that caches them. |
| 271 | try: |
| 272 | credits = _rows("invoice_credits", "invoice_id", invoice_id, base, indexed=indexed) |
| 273 | except object_collections.CollectionNotFoundError: |
| 274 | credits = [] |
| 275 | except Exception: |
| 276 | return _unreadable("Credits applied to the invoice") |
| 277 | credited = 0 |
| 278 | for row in credits: |
| 279 | try: |
| 280 | credited += _cents(row.get("amount_cents")) |
| 281 | except ValueError: |
| 282 | return {"error": (f"Credit {row.get('id')} on invoice {invoice_id} has an " |
| 283 | "unreadable amount; correct it before recording more."), |
| 284 | "status": 409} |
| 285 | |
| 286 | remaining = ceiling - credited - (received - refunded) |
| 287 | if amount > remaining: |
| 288 | return { |
| 289 | "error": ( |
| 290 | f"Payment of {amount} cents exceeds the remaining balance of " |
| 291 | f"{max(remaining, 0)} cents on invoice {invoice_id}. " |
| 292 | "(Set app_settings payments.overpayment_policy=allow to permit " |
| 293 | "customer credit balances.)" |
| 294 | ), |
| 295 | "status": 409, |
| 296 | } |
| 297 | return None |
| 298 | |
| 299 | |
| 300 | def _unnumbered(record): |
| 301 | """v3 stamped a sequence number here; nothing does now (LOCKED_CHECK |
| 302 | serializes every writer). A client's number is still blanked, so the |
| 303 | column never carries a value that looks meaningful and is not.""" |
| 304 | if not _stored(record.get(SEQ)): |
| 305 | return None |
| 306 | blanked = dict(record) |
| 307 | blanked[SEQ] = "" |
| 308 | return {"record": blanked} |
| 309 | |
| 310 | |
| 311 | def _ceiling_applies(record): |
| 312 | return ((record.get("status") or "received") == "received" |
| 313 | and bool(record.get("invoice_id")) |
| 314 | and _setting("payments.overpayment_policy", "reject") != "allow") |
| 315 | |
| 316 | |
| 317 | def _check_create(request): |
| 318 | return _unnumbered(request.get("record") or {}) |
| 319 | |
| 320 | |
| 321 | def _changed(record, existing, names): |
| 322 | return sorted(name for name in names |
| 323 | if name != "id" and _stored(record.get(name)) != _stored(existing.get(name))) |
| 324 | |
| 325 | |
| 326 | def _check_update(request): |
| 327 | existing = request.get("existing") or {} |
| 328 | record = request.get("record") or {} |
| 329 | changes = request.get("changes") or {} |
| 330 | |
| 331 | # A change is a submitted field whose value would differ: a form posts |
| 332 | # everything it shows, and sending the amount back unchanged edits |
| 333 | # nothing. |
| 334 | changed = _changed(record, existing, changes) |
| 335 | if not changed: |
| 336 | return None |
| 337 | |
| 338 | if SEQ in changed and _is_admin(request): |
| 339 | return {"error": (f"{SEQ} is a retired server-stamped column; it is not edited."), |
| 340 | "status": 409} |
| 341 | |
| 342 | if not _is_admin(request): |
| 343 | frozen = [name for name in changed if name not in _OWNER_EDITABLE] |
| 344 | if frozen: |
| 345 | return {"error": ( |
| 346 | f"A recorded payment is not edited ({', '.join(frozen)}): money moves, " |
| 347 | "it does not mutate. Record a refund for what should not have been " |
| 348 | "received, or mark this payment bounced and record the right one."), |
| 349 | "status": 409} |
| 350 | return None # status is governed by the schema's transitions |
| 351 | |
| 352 | |
| 353 | def _refunds_block_delete(payment_id, base, *, indexed=False): |
| 354 | refunds, refunded, refusal = _refunds_of(payment_id, base, indexed=indexed) |
| 355 | if refusal: |
| 356 | return refusal |
| 357 | if refunds: |
| 358 | return {"error": (f"Payment {payment_id} has {refunded} cents of refunds pointing at " |
| 359 | "it. Deleting it would leave them refunding nothing; delete the " |
| 360 | "refunds first."), "status": 409} |
| 361 | return None |
| 362 | |
| 363 | |
| 364 | def BEFORE_WRITE(request): |
| 365 | action = request.get("action") |
| 366 | if action == "create": |
| 367 | return _check_create(request) |
| 368 | if action == "update": |
| 369 | return _check_update(request) |
| 370 | return None |
| 371 | |
| 372 | |
| 373 | def LOCKED_CHECK(request): |
| 374 | """The ledger invariants, decided by object_records inside the write |
| 375 | lock and the "ledger" check lock, for every writer (see the module |
| 376 | docstring and payments.json `locked_checks`). Reads only; never asks |
| 377 | who is writing -- these are facts about money, not permissions. |
| 378 | |
| 379 | `record` is the row as it would be stored, `existing` the row on file |
| 380 | (read under the lock; None on create). Returns None or a refusal.""" |
| 381 | action = request.get("action") |
| 382 | record = request.get("record") or {} |
| 383 | existing = request.get("existing") or {} |
| 384 | base = request.get("base_dir") or _base_dir() |
| 385 | payment_id = _text(record.get("id") or existing.get("id")) |
| 386 | |
| 387 | if action == "delete": |
| 388 | return _refunds_block_delete(payment_id, base, indexed=True) |
| 389 | |
| 390 | try: |
| 391 | amount = int(record.get("amount_cents") or 0) |
| 392 | except (TypeError, ValueError): |
| 393 | amount = 0 |
| 394 | # A positive amount is the schema's validation.min (and required), for |
| 395 | # every writer, and this runs after validation; refunds say the same. |
| 396 | |
| 397 | if action == "update": |
| 398 | changed = set(_changed(record, existing, ("amount_cents", "invoice_id", "status"))) |
| 399 | if not changed: |
| 400 | return None |
| 401 | if "amount_cents" in changed or "invoice_id" in changed: |
| 402 | refunds, refunded, refusal = _refunds_of(payment_id, base, indexed=True) |
| 403 | if refusal: |
| 404 | return refusal |
| 405 | if "amount_cents" in changed and amount < refunded: |
| 406 | return {"error": (f"Payment {payment_id} has {refunded} cents refunded against " |
| 407 | f"it and cannot be lowered to {amount}."), "status": 409} |
| 408 | if "invoice_id" in changed and refunds: |
| 409 | return {"error": (f"Payment {payment_id} has refunds, and each is stamped with " |
| 410 | "the invoice it was refunded on. Delete the refunds before " |
| 411 | "moving the payment to another invoice."), "status": 409} |
| 412 | # Only what ADDS to an invoice can pass its ceiling: a lowered |
| 413 | # amount or a bounce never can, and is never refused for it. |
| 414 | try: |
| 415 | before = int(existing.get("amount_cents") or 0) |
| 416 | except (TypeError, ValueError): |
| 417 | before = 0 |
| 418 | was_received = (existing.get("status") or "received") == "received" |
| 419 | adds = ("invoice_id" in changed or not was_received or amount > before) |
| 420 | if not adds: |
| 421 | return None |
| 422 | |
| 423 | if not _ceiling_applies(record): |
| 424 | return None |
| 425 | return _over_ceiling(record.get("invoice_id"), amount, base, exclude_id=payment_id, |
| 426 | missing_is_refusal=True, indexed=True) |