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
gift_card_issue.py · 14.2 KB · 340 lines
1"""system_gift_card_issue -- the customer paid for a gift card, so the
2gift card now exists.
3
4HANDLES payment writes. When money settles an invoice raised for an order
5that contained a gift-card product, this opens ONE WALLET PER LINE with a
6bearer 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,
9credited by an ordinary sale and debited at checkout through the gate
10that already refuses to let anybody spend what is not there
11(hook_wallet_entries). Everything a gift-card feature needs -- a balance
12that cannot drift from its movements, a spend check that is authoritative,
13a statement the holder can be shown -- app-billing already had, and
14building a gift_cards table with its own balance column beside it would
15be reconstructing the predecessor's drift bug in a corner nobody watches,
16for money that arrives as a bearer instrument and is therefore the least
17forgiving place to be wrong.
18
19**Selling one is an ordinary product sale.** products.is_gift_card marks
20the catalogue row; nothing else about the sale is special. It has a
21price, it goes in a basket, it is invoiced and it is paid for, and the
22FULFILMENT of it is this handler crediting a wallet rather than a picker
23putting something in a box. The face value is the line total, so a
24customer who buys three $25 cards gets three cards, and a shop that sells
25a card at a discount credits what was actually charged rather than what
26the card claims to be worth. (A shop that wants "pay $45, get $50" prices
27the product at 45 and needs a face-value field; that is a decision for
28whoever 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
31hands to somebody -- three cards on one order are three presents for
32three people, and merging them into one balance makes two of those
33presents impossible to give.
34
35**It waits for the money.** Nothing is credited until the invoice is
36SETTLED, folded from the payments themselves rather than read off the
37invoice's own rollup, for the reason system_shop_fulfillment documents:
38this handler runs ON the write that created the payment, so the invoice
39has not yet been told about the money that triggered it, and trusting the
40rollup would mean the first payment issues nothing and the second issues
41everything.
42
43Placement follows docs/logic-decisions.md #6 -- a REACTION, post-commit,
44best-effort, never blocking the payment. A shop that cannot open a wallet
45must still be able to take the money; the gap is visible and fixable,
46whereas a refused payment is a lost sale.
47
48**Idempotency by provenance** (#7), and it matters more here than almost
49anywhere: a replayed payment event that issued a second card would be the
50shop giving away money. Every credit stamps generated_from with
51`gift_card/{order_line_id}`, and this handler looks for that marker
52before it writes anything. At-least-once delivery therefore credits
53exactly once, with no dedup table.
54
55Looking first is only the fast path. Two deliveries of one payment (this
56handles both payments.record.created and .updated) can overlap: both look,
57both find nothing, and each used to open its own card and credit it -- 10000
58of spendable credit for one 5000 sale. The look-then-write is now backed by
59two schema `unique` keys checked inside the write lock: the wallet carries
60the marker as its own generated_from, so the second delivery's wallet is
61refused and it adopts the first one's; and the ledger refuses a second
62entry with the same marker, so the card is credited once.
63"""
64
65import os
66import secrets
67
68import object_collections
69import object_ids
70import object_records
71
72ACTOR = "system_gift_card_issue"
73
74HANDLES = [
75 "payments.record.created",
76 "payments.record.updated",
77]
78
79MARKER = "gift_card/"
80
81
82def _base_dir():
83 return os.environ.get("DBBASIC_DATA_DIR", "data")
84
85
86def _text(value):
87 return str(value if value is not None else "").strip()
88
89
90def _truthy(value):
91 return _text(value).lower() in ("true", "1", "yes", "on")
92
93
94def _int(value, default=0):
95 try:
96 return int(_text(value) or default)
97 except (TypeError, ValueError):
98 return default
99
100
101def _rows(collection, base):
102 try:
103 return object_records.read_collection_records(collection, base_dir=base)
104 except Exception:
105 return None
106
107
108def _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
122def _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
165def _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
195def _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
210def 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.
340POST = EVENT