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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
refunds.py · 2.3 KB · 70 lines
| 1 | """Pre-write hook for refunds: the invariant gate and the stamp. |
| 2 | |
| 3 | Two doctrines in one hook (docs/logic-decisions.md): |
| 4 | - #3 money moves: a refund is a compensating record; this gate keeps the |
| 5 | movement honest — amount <= payment.amount minus prior refunds, and no |
| 6 | refunding a bounced payment. Sums refund records directly (authoritative, |
| 7 | never derived values). |
| 8 | - #1 stamp point-in-time facts: invoice_id is copied from the payment at |
| 9 | write time (a transform), never trusted from the client — so invoices can |
| 10 | roll refunds up directly and the pointer can never disagree with the |
| 11 | payment it compensates. |
| 12 | """ |
| 13 | |
| 14 | import os |
| 15 | |
| 16 | import object_records |
| 17 | |
| 18 | |
| 19 | def _base_dir(): |
| 20 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 21 | |
| 22 | |
| 23 | def BEFORE_WRITE(request): |
| 24 | if request.get("action") != "create": |
| 25 | return None |
| 26 | record = dict(request.get("record") or {}) |
| 27 | |
| 28 | try: |
| 29 | amount = int(record.get("amount_cents") or 0) |
| 30 | except ValueError: |
| 31 | return None |
| 32 | if amount <= 0: |
| 33 | return {"error": "Refund amount must be a positive number of cents.", "status": 400} |
| 34 | |
| 35 | payment_id = record.get("payment_id") |
| 36 | if not payment_id: |
| 37 | return None # required + relation validation own this |
| 38 | base = _base_dir() |
| 39 | try: |
| 40 | payment = object_records.get_collection_record("payments", payment_id, base_dir=base) |
| 41 | except Exception: |
| 42 | return None |
| 43 | if (payment.get("status") or "received") == "bounced": |
| 44 | return {"error": "Cannot refund a bounced payment.", "status": 409} |
| 45 | |
| 46 | prior = 0 |
| 47 | for r in object_records.read_collection_records("refunds", base_dir=base): |
| 48 | if r.get("payment_id") == payment_id: |
| 49 | try: |
| 50 | prior += int(r.get("amount_cents") or 0) |
| 51 | except ValueError: |
| 52 | continue |
| 53 | try: |
| 54 | paid = int(payment.get("amount_cents") or 0) |
| 55 | except ValueError: |
| 56 | paid = 0 |
| 57 | refundable = paid - prior |
| 58 | if amount > refundable: |
| 59 | return { |
| 60 | "error": ( |
| 61 | f"Refund of {amount} cents exceeds the refundable " |
| 62 | f"{max(refundable, 0)} cents on payment {payment_id} " |
| 63 | f"({paid} paid, {prior} already refunded)." |
| 64 | ), |
| 65 | "status": 409, |
| 66 | } |
| 67 | |
| 68 | # Stamp: invoice_id always comes from the payment, never the client. |
| 69 | record["invoice_id"] = payment.get("invoice_id", "") |
| 70 | return {"record": record} |