Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
gift_card_issue.py · 11.0 KB · 282 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"""
55
56import os
57import secrets
58
59import object_ids
60import object_records
61
62ACTOR = "system_gift_card_issue"
63
64HANDLES = [
65 "payments.record.created",
66 "payments.record.updated",
67]
68
69MARKER = "gift_card/"
70
71
72def _base_dir():
73 return os.environ.get("DBBASIC_DATA_DIR", "data")
74
75
76def _text(value):
77 return str(value if value is not None else "").strip()
78
79
80def _truthy(value):
81 return _text(value).lower() in ("true", "1", "yes", "on")
82
83
84def _int(value, default=0):
85 try:
86 return int(_text(value) or default)
87 except (TypeError, ValueError):
88 return default
89
90
91def _rows(collection, base):
92 try:
93 return object_records.read_collection_records(collection, base_dir=base)
94 except Exception:
95 return None
96
97
98def _payment_for(request, base):
99 record = request.get("record")
100 if isinstance(record, dict) and record.get("id"):
101 return record
102 payment_id = _text(request.get("record_id") or request.get("id"))
103 if not payment_id:
104 return None
105 try:
106 return object_records.get_collection_record("payments", payment_id,
107 base_dir=base)
108 except Exception:
109 return None
110
111
112def _invoice_is_settled(base, invoice_id):
113 """(True, "") when the bill is fully paid.
114
115 The payments are summed HERE rather than read off the invoice's
116 amount_paid rollup, for the reason in the module docstring: this runs
117 on the write that created the payment, so the rollup has not seen it
118 yet.
119 """
120 if not invoice_id:
121 return False, "no invoice"
122 try:
123 invoice = object_records.get_collection_record("invoices", invoice_id,
124 base_dir=base)
125 except Exception:
126 return False, "invoice unreadable"
127 total = _int(invoice.get("total_cents"))
128 if _text(invoice.get("status")) == "paid":
129 return True, ""
130 if total <= 0:
131 return True, ""
132
133 paid = 0
134 for row in _rows("payments", base) or []:
135 if (_text(row.get("invoice_id")) == invoice_id
136 and _text(row.get("status")) == "received"):
137 paid += _int(row.get("amount_cents"))
138 for row in _rows("refunds", base) or []:
139 if _text(row.get("invoice_id")) == invoice_id:
140 paid -= _int(row.get("amount_cents"))
141 if paid >= total:
142 return True, ""
143 return False, f"invoice not settled: {paid} of {total} paid"
144
145
146def _order_for_invoice(base, invoice_id):
147 if not invoice_id:
148 return None
149 for order in _rows("orders", base) or []:
150 if _text(order.get("invoice_id")) == invoice_id:
151 return order
152 return None
153
154
155def _new_code(existing):
156 """A bearer code nobody already holds.
157
158 Long enough not to be guessed off a shop's own order numbers, and
159 checked against the wallets that exist rather than trusted to be
160 unique by arithmetic -- hook_wallets refuses a duplicate anyway, and a
161 handler that produced one would fail the write instead of the card.
162 """
163 for _ in range(8):
164 code = f"GC-{secrets.token_hex(6).upper()}"
165 if code not in existing:
166 return code
167 return f"GC-{secrets.token_hex(10).upper()}"
168
169
170def EVENT(request):
171 base = _base_dir()
172 payment = _payment_for(request, base)
173 if not payment:
174 return {"ok": True, "skipped": "no payment in the event"}
175 if _text(payment.get("status")) != "received":
176 return {"ok": True, "skipped": "payment not received"}
177
178 invoice_id = _text(payment.get("invoice_id"))
179 order = _order_for_invoice(base, invoice_id)
180 if order is None:
181 # Most payments have nothing to do with gift cards. Saying so
182 # plainly beats a silent return that looks identical to a bug.
183 return {"ok": True, "skipped": "no order for this payment"}
184
185 lines = [row for row in (_rows("order_lines", base) or [])
186 if _text(row.get("order_id")) == _text(order.get("id"))]
187 products = {}
188 for line in lines:
189 product_id = _text(line.get("product_id"))
190 if not product_id or product_id in products:
191 continue
192 try:
193 products[product_id] = object_records.get_collection_record(
194 "products", product_id, base_dir=base)
195 except Exception:
196 products[product_id] = {}
197
198 sellable = [line for line in lines
199 if _truthy(products.get(_text(line.get("product_id")), {})
200 .get("is_gift_card"))]
201 if not sellable:
202 return {"ok": True, "skipped": "no gift card on this order"}
203
204 settled, reason = _invoice_is_settled(base, invoice_id)
205 if not settled:
206 # The card is money. It is issued when the money is here, not when
207 # somebody has promised it.
208 return {"ok": True, "skipped": reason, "order_id": order["id"]}
209
210 entries = _rows("wallet_entries", base)
211 if entries is None:
212 return {"ok": True, "order_id": order["id"], "issued": 0,
213 "warning": ("this order sold a gift card and there is no "
214 "wallet ledger on this server to credit; the "
215 "customer has paid for nothing")}
216 already = {_text(row.get("generated_from")) for row in entries}
217 wallets = _rows("wallets", base) or []
218 taken = {_text(row.get("code")).upper() for row in wallets if row.get("code")}
219
220 issued = []
221 warnings = []
222 for line in sellable:
223 provenance = f"{MARKER}{_text(line.get('id'))}"
224 if provenance in already:
225 continue # a replay; the card already exists
226 amount = _int(line.get("line_total_cents"))
227 if amount <= 0:
228 warnings.append(f"order line {_text(line.get('id'))} sold a gift "
229 f"card worth nothing; no wallet was opened")
230 continue
231 code = _new_code(taken)
232 taken.add(code)
233 wallet_id = object_ids.new_uuid4()
234 try:
235 object_records.create_collection_record(
236 "wallets",
237 {"id": wallet_id,
238 # The SHOP owns the container; the CODE is what spends it.
239 # A guest who was given this card has no account here, and
240 # owning it to somebody's email would make the present
241 # unusable by the person it was for.
242 "owner_id": _text(order.get("owner_id")),
243 "kind": "gift_card",
244 "code": code,
245 "is_active": "true"},
246 base_dir=base, actor=ACTOR)
247 object_records.create_collection_record(
248 "wallet_entries",
249 {"id": object_ids.new_uuid4(),
250 "wallet_id": wallet_id,
251 # Positive: money arriving. Credits are never gated by
252 # hook_wallet_entries, which is why this write needs no
253 # permission from it.
254 "amount_minor": str(amount),
255 "kind": "topup",
256 "description": f"Gift card {code} purchased on order "
257 f"{_text(order.get('number')) or order['id']}",
258 "reference": f"orders/{order['id']}",
259 "generated_from": provenance,
260 "owner_id": _text(order.get("owner_id"))},
261 base_dir=base, actor=ACTOR)
262 except Exception as exc:
263 warnings.append(f"gift card for order line {_text(line.get('id'))} "
264 f"could not be issued: {str(exc)[:120]}")
265 continue
266 issued.append({"wallet_id": wallet_id, "code": code,
267 "amount_minor": amount,
268 "order_line_id": _text(line.get("id"))})
269
270 result = {"ok": True, "order_id": order["id"], "issued": len(issued),
271 "cards": issued}
272 if warnings:
273 result["warnings"] = warnings
274 if not issued and not warnings:
275 result["note"] = "already issued; a replay credits nothing twice"
276 return result
277
278
279# EVENT is the verb the change dispatcher calls handlers with; POST stays
280# as an alias so an operator can poke the handler by hand over HTTP, the
281# same pair system_shop_fulfillment keeps.
282POST = EVENT