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.
gift_card_issue.py · 14.2 KB · 340 lines
| 1 | """system_gift_card_issue -- the customer paid for a gift card, so the |
| 2 | gift card now exists. |
| 3 | |
| 4 | HANDLES payment writes. When money settles an invoice raised for an order |
| 5 | that contained a gift-card product, this opens ONE WALLET PER LINE with a |
| 6 | bearer code and credits it with what was paid for it. |
| 7 | |
| 8 | **A gift card is not a new kind of thing.** It is a wallet with a code, |
| 9 | credited by an ordinary sale and debited at checkout through the gate |
| 10 | that already refuses to let anybody spend what is not there |
| 11 | (hook_wallet_entries). Everything a gift-card feature needs -- a balance |
| 12 | that cannot drift from its movements, a spend check that is authoritative, |
| 13 | a statement the holder can be shown -- app-billing already had, and |
| 14 | building a gift_cards table with its own balance column beside it would |
| 15 | be reconstructing the predecessor's drift bug in a corner nobody watches, |
| 16 | for money that arrives as a bearer instrument and is therefore the least |
| 17 | forgiving place to be wrong. |
| 18 | |
| 19 | **Selling one is an ordinary product sale.** products.is_gift_card marks |
| 20 | the catalogue row; nothing else about the sale is special. It has a |
| 21 | price, it goes in a basket, it is invoiced and it is paid for, and the |
| 22 | FULFILMENT of it is this handler crediting a wallet rather than a picker |
| 23 | putting something in a box. The face value is the line total, so a |
| 24 | customer who buys three $25 cards gets three cards, and a shop that sells |
| 25 | a card at a discount credits what was actually charged rather than what |
| 26 | the card claims to be worth. (A shop that wants "pay $45, get $50" prices |
| 27 | the product at 45 and needs a face-value field; that is a decision for |
| 28 | whoever has that shop, and it is deliberately not invented here.) |
| 29 | |
| 30 | **One wallet per LINE, not per order.** A gift card is a thing somebody |
| 31 | hands to somebody -- three cards on one order are three presents for |
| 32 | three people, and merging them into one balance makes two of those |
| 33 | presents impossible to give. |
| 34 | |
| 35 | **It waits for the money.** Nothing is credited until the invoice is |
| 36 | SETTLED, folded from the payments themselves rather than read off the |
| 37 | invoice's own rollup, for the reason system_shop_fulfillment documents: |
| 38 | this handler runs ON the write that created the payment, so the invoice |
| 39 | has not yet been told about the money that triggered it, and trusting the |
| 40 | rollup would mean the first payment issues nothing and the second issues |
| 41 | everything. |
| 42 | |
| 43 | Placement follows docs/logic-decisions.md #6 -- a REACTION, post-commit, |
| 44 | best-effort, never blocking the payment. A shop that cannot open a wallet |
| 45 | must still be able to take the money; the gap is visible and fixable, |
| 46 | whereas a refused payment is a lost sale. |
| 47 | |
| 48 | **Idempotency by provenance** (#7), and it matters more here than almost |
| 49 | anywhere: a replayed payment event that issued a second card would be the |
| 50 | shop giving away money. Every credit stamps generated_from with |
| 51 | `gift_card/{order_line_id}`, and this handler looks for that marker |
| 52 | before it writes anything. At-least-once delivery therefore credits |
| 53 | exactly once, with no dedup table. |
| 54 | |
| 55 | Looking first is only the fast path. Two deliveries of one payment (this |
| 56 | handles both payments.record.created and .updated) can overlap: both look, |
| 57 | both find nothing, and each used to open its own card and credit it -- 10000 |
| 58 | of spendable credit for one 5000 sale. The look-then-write is now backed by |
| 59 | two schema `unique` keys checked inside the write lock: the wallet carries |
| 60 | the marker as its own generated_from, so the second delivery's wallet is |
| 61 | refused and it adopts the first one's; and the ledger refuses a second |
| 62 | entry with the same marker, so the card is credited once. |
| 63 | """ |
| 64 | |
| 65 | import os |
| 66 | import secrets |
| 67 | |
| 68 | import object_collections |
| 69 | import object_ids |
| 70 | import object_records |
| 71 | |
| 72 | ACTOR = "system_gift_card_issue" |
| 73 | |
| 74 | HANDLES = [ |
| 75 | "payments.record.created", |
| 76 | "payments.record.updated", |
| 77 | ] |
| 78 | |
| 79 | MARKER = "gift_card/" |
| 80 | |
| 81 | |
| 82 | def _base_dir(): |
| 83 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 84 | |
| 85 | |
| 86 | def _text(value): |
| 87 | return str(value if value is not None else "").strip() |
| 88 | |
| 89 | |
| 90 | def _truthy(value): |
| 91 | return _text(value).lower() in ("true", "1", "yes", "on") |
| 92 | |
| 93 | |
| 94 | def _int(value, default=0): |
| 95 | try: |
| 96 | return int(_text(value) or default) |
| 97 | except (TypeError, ValueError): |
| 98 | return default |
| 99 | |
| 100 | |
| 101 | def _rows(collection, base): |
| 102 | try: |
| 103 | return object_records.read_collection_records(collection, base_dir=base) |
| 104 | except Exception: |
| 105 | return None |
| 106 | |
| 107 | |
| 108 | def _payment_for(request, base): |
| 109 | record = request.get("record") |
| 110 | if isinstance(record, dict) and record.get("id"): |
| 111 | return record |
| 112 | payment_id = _text(request.get("record_id") or request.get("id")) |
| 113 | if not payment_id: |
| 114 | return None |
| 115 | try: |
| 116 | return object_records.get_collection_record("payments", payment_id, |
| 117 | base_dir=base) |
| 118 | except Exception: |
| 119 | return None |
| 120 | |
| 121 | |
| 122 | def _invoice_is_settled(base, invoice_id): |
| 123 | """(True, "") when the bill is fully paid. |
| 124 | |
| 125 | The payments are summed HERE rather than read off the invoice's |
| 126 | amount_paid rollup, for the reason in the module docstring: this runs |
| 127 | on the write that created the payment, so the rollup has not seen it |
| 128 | yet. |
| 129 | """ |
| 130 | if not invoice_id: |
| 131 | return False, "no invoice" |
| 132 | try: |
| 133 | invoice = object_records.get_collection_record("invoices", invoice_id, |
| 134 | base_dir=base) |
| 135 | except Exception: |
| 136 | return False, "invoice unreadable" |
| 137 | total = _int(invoice.get("total_cents")) |
| 138 | if _text(invoice.get("status")) == "paid": |
| 139 | return True, "" |
| 140 | if total <= 0: |
| 141 | return True, "" |
| 142 | |
| 143 | paid = 0 |
| 144 | for row in _rows("payments", base) or []: |
| 145 | if (_text(row.get("invoice_id")) == invoice_id |
| 146 | and _text(row.get("status")) == "received"): |
| 147 | paid += _int(row.get("amount_cents")) |
| 148 | # Unreadable payments already fail safe (nothing paid, nothing issued). |
| 149 | # Unreadable refunds read as "none" and opened a card for money that |
| 150 | # had gone back; not installed is still none. |
| 151 | try: |
| 152 | refunds = object_records.read_collection_records("refunds", base_dir=base) |
| 153 | except object_collections.CollectionNotFoundError: |
| 154 | refunds = [] |
| 155 | except Exception as exc: |
| 156 | return False, f"refunds unreadable ({str(exc)[:120]})" |
| 157 | for row in refunds: |
| 158 | if _text(row.get("invoice_id")) == invoice_id: |
| 159 | paid -= _int(row.get("amount_cents")) |
| 160 | if paid >= total: |
| 161 | return True, "" |
| 162 | return False, f"invoice not settled: {paid} of {total} paid" |
| 163 | |
| 164 | |
| 165 | def _order_for_invoice(base, invoice_id): |
| 166 | """The order this invoice settles: one that names it AND belongs to whoever |
| 167 | owns the invoice. |
| 168 | |
| 169 | orders.invoice_id is a free-text field any order's owner may set, and |
| 170 | this took the first order naming the invoice. An order of somebody |
| 171 | else's, pointed at the shop's invoice, was "the order" when the shop's |
| 172 | customer paid: its lines were read as what had been bought, and a gift |
| 173 | card for its own line opened in its owner's name. Checkout writes the |
| 174 | order and its invoice under one owner, so an order owned by anybody |
| 175 | else is no part of this sale. (Making invoice_id a validated relation |
| 176 | was weighed and not done: every field is re-validated on every write, |
| 177 | so an order whose invoice was deleted could no longer change status.) |
| 178 | An invoice that cannot be read answers None: nothing is issued on a |
| 179 | guess.""" |
| 180 | if not invoice_id: |
| 181 | return None |
| 182 | try: |
| 183 | invoice = object_records.get_collection_record("invoices", invoice_id, |
| 184 | base_dir=base) |
| 185 | except Exception: |
| 186 | return None |
| 187 | owner = _text(invoice.get("owner_id")) |
| 188 | for order in _rows("orders", base) or []: |
| 189 | if (_text(order.get("invoice_id")) == invoice_id |
| 190 | and _text(order.get("owner_id")) == owner): |
| 191 | return order |
| 192 | return None |
| 193 | |
| 194 | |
| 195 | def _new_code(existing): |
| 196 | """A bearer code nobody already holds. |
| 197 | |
| 198 | Long enough not to be guessed off a shop's own order numbers, and |
| 199 | checked against the wallets that exist rather than trusted to be |
| 200 | unique by arithmetic -- hook_wallets refuses a duplicate anyway, and a |
| 201 | handler that produced one would fail the write instead of the card. |
| 202 | """ |
| 203 | for _ in range(8): |
| 204 | code = f"GC-{secrets.token_hex(6).upper()}" |
| 205 | if code not in existing: |
| 206 | return code |
| 207 | return f"GC-{secrets.token_hex(10).upper()}" |
| 208 | |
| 209 | |
| 210 | def EVENT(request): |
| 211 | base = _base_dir() |
| 212 | payment = _payment_for(request, base) |
| 213 | if not payment: |
| 214 | return {"ok": True, "skipped": "no payment in the event"} |
| 215 | if _text(payment.get("status")) != "received": |
| 216 | return {"ok": True, "skipped": "payment not received"} |
| 217 | |
| 218 | invoice_id = _text(payment.get("invoice_id")) |
| 219 | order = _order_for_invoice(base, invoice_id) |
| 220 | if order is None: |
| 221 | # Most payments have nothing to do with gift cards. Saying so |
| 222 | # plainly beats a silent return that looks identical to a bug. |
| 223 | return {"ok": True, "skipped": "no order for this payment"} |
| 224 | |
| 225 | lines = [row for row in (_rows("order_lines", base) or []) |
| 226 | if _text(row.get("order_id")) == _text(order.get("id"))] |
| 227 | products = {} |
| 228 | for line in lines: |
| 229 | product_id = _text(line.get("product_id")) |
| 230 | if not product_id or product_id in products: |
| 231 | continue |
| 232 | try: |
| 233 | products[product_id] = object_records.get_collection_record( |
| 234 | "products", product_id, base_dir=base) |
| 235 | except Exception: |
| 236 | products[product_id] = {} |
| 237 | |
| 238 | sellable = [line for line in lines |
| 239 | if _truthy(products.get(_text(line.get("product_id")), {}) |
| 240 | .get("is_gift_card"))] |
| 241 | if not sellable: |
| 242 | return {"ok": True, "skipped": "no gift card on this order"} |
| 243 | |
| 244 | settled, reason = _invoice_is_settled(base, invoice_id) |
| 245 | if not settled: |
| 246 | # The card is money. It is issued when the money is here, not when |
| 247 | # somebody has promised it. |
| 248 | return {"ok": True, "skipped": reason, "order_id": order["id"]} |
| 249 | |
| 250 | entries = _rows("wallet_entries", base) |
| 251 | if entries is None: |
| 252 | return {"ok": True, "order_id": order["id"], "issued": 0, |
| 253 | "warning": ("this order sold a gift card and there is no " |
| 254 | "wallet ledger on this server to credit; the " |
| 255 | "customer has paid for nothing")} |
| 256 | already = {_text(row.get("generated_from")) for row in entries} |
| 257 | wallets = _rows("wallets", base) or [] |
| 258 | taken = {_text(row.get("code")).upper() for row in wallets if row.get("code")} |
| 259 | |
| 260 | issued = [] |
| 261 | warnings = [] |
| 262 | for line in sellable: |
| 263 | provenance = f"{MARKER}{_text(line.get('id'))}" |
| 264 | if provenance in already: |
| 265 | continue # a replay; the card already exists |
| 266 | amount = _int(line.get("line_total_cents")) |
| 267 | if amount <= 0: |
| 268 | warnings.append(f"order line {_text(line.get('id'))} sold a gift " |
| 269 | f"card worth nothing; no wallet was opened") |
| 270 | continue |
| 271 | code = _new_code(taken) |
| 272 | taken.add(code) |
| 273 | wallet_id = object_ids.new_uuid4() |
| 274 | try: |
| 275 | try: |
| 276 | object_records.create_collection_record( |
| 277 | "wallets", |
| 278 | {"id": wallet_id, |
| 279 | # The SHOP owns the container; the CODE is what spends |
| 280 | # it. A guest who was given this card has no account |
| 281 | # here, and owning it to somebody's email would make |
| 282 | # the present unusable by the person it was for. |
| 283 | "owner_id": _text(order.get("owner_id")), |
| 284 | "kind": "gift_card", |
| 285 | "code": code, |
| 286 | # The claim: wallets declares generated_from unique, so |
| 287 | # of two overlapping deliveries only one opens a card. |
| 288 | "generated_from": provenance, |
| 289 | "is_active": "true"}, |
| 290 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 291 | except object_records.UniqueConstraintError as exc: |
| 292 | if "generated_from" not in exc.fields: |
| 293 | raise |
| 294 | # Another delivery opened this line's card between our read |
| 295 | # and our write. Credit THAT wallet if its credit has not |
| 296 | # landed yet (the entry's own marker decides), never a |
| 297 | # second one. |
| 298 | wallet_id = exc.existing_id |
| 299 | existing = object_records.get_collection_record( |
| 300 | "wallets", wallet_id, base_dir=base) |
| 301 | code = _text(existing.get("code")) |
| 302 | try: |
| 303 | object_records.create_collection_record( |
| 304 | "wallet_entries", |
| 305 | {"id": object_ids.new_uuid4(), |
| 306 | "wallet_id": wallet_id, |
| 307 | # Positive: money arriving, so no balance gate applies; |
| 308 | # the marker below is unique in wallet_entries, checked |
| 309 | # inside the write lock. |
| 310 | "amount_minor": str(amount), |
| 311 | "kind": "topup", |
| 312 | "description": f"Gift card {code} purchased on order " |
| 313 | f"{_text(order.get('number')) or order['id']}", |
| 314 | "reference": f"orders/{order['id']}", |
| 315 | "generated_from": provenance, |
| 316 | "owner_id": _text(order.get("owner_id"))}, |
| 317 | base_dir=base, actor=ACTOR) |
| 318 | except object_records.UniqueConstraintError: |
| 319 | continue # the overlapping delivery credited it |
| 320 | except Exception as exc: |
| 321 | warnings.append(f"gift card for order line {_text(line.get('id'))} " |
| 322 | f"could not be issued: {str(exc)[:120]}") |
| 323 | continue |
| 324 | issued.append({"wallet_id": wallet_id, "code": code, |
| 325 | "amount_minor": amount, |
| 326 | "order_line_id": _text(line.get("id"))}) |
| 327 | |
| 328 | result = {"ok": True, "order_id": order["id"], "issued": len(issued), |
| 329 | "cards": issued} |
| 330 | if warnings: |
| 331 | result["warnings"] = warnings |
| 332 | if not issued and not warnings: |
| 333 | result["note"] = "already issued; a replay credits nothing twice" |
| 334 | return result |
| 335 | |
| 336 | |
| 337 | # EVENT is the verb the change dispatcher calls handlers with; POST stays |
| 338 | # as an alias so an operator can poke the handler by hand over HTTP, the |
| 339 | # same pair system_shop_fulfillment keeps. |
| 340 | POST = EVENT |