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
order_email.py · 28.9 KB · 683 lines
1"""system_order_email -- the shop finally says something back.
2
3Until this handler existed a customer paid and heard silence. Every piece
4of the machinery was already here -- object_email.enqueue writes a row,
5the daemon's process_email_outbox pass drains it -- and nothing in the
6whole server ever composed a message to a buyer. This composes four, and
7each one is sent by a TRANSITION rather than a button:
8
9 order confirmed -- what they bought, the total, the tracking link, and
10 the pay link if the bill is still open
11 shipped -- the carrier and tracking number if the parcel has
12 them, and the tracking link
13 ready -- a PICKUP order is made and waiting to be collected
14 refunded -- how much went back, and which order it came off
15
16A button would be a fourth thing somebody has to remember on a busy
17Friday, and the whole complaint this slice answers is that the shop was
18already forgetting. A transition cannot be forgotten: the fact that
19causes the email IS the email's trigger.
20
21**It queues; it never sends.** enqueue() is a plain local write of one
22`queued` row. Nothing here opens a socket. A slow SMTP server would
23otherwise add its timeout to the write that triggered it -- an order
24confirmation would make taking the money slower, and a broken relay would
25make it fail. The daemon owns delivery, retries and backoff, and it
26already logs "outbound mail is queuing only" when no transport is
27configured. So on a server with no SMTP at all, every message still lands
28in the outbox, inspectable, and nothing errors: the shop's voice is
29recorded even where it cannot yet be heard.
30
31Placement is doctrine #6: a REACTION, post-commit, best-effort, never a
32gate. It cannot fail the write that confirmed the order or recorded the
33refund. Every failure lands in the result rather than an exception.
34
35**Idempotency by provenance (#7), on the OUTBOX ROW.** The change
36dispatcher promises at-least-once delivery, so this handler will see the
37same order again -- and the confirmed email's trigger is `status is
38confirmed`, a state the order SITS in, not an edge it crosses, so every
39later write to a confirmed order re-fires it. Each message therefore
40carries a marker in its outbox row's source_object_id:
41
42 system_order_email:orders/{order_id}:confirmed
43 system_order_email:orders/{order_id}:shipped
44 system_order_email:orders/{order_id}:ready
45 system_order_email:orders/{order_id}:refunded/{refund_id}
46
47and the handler refuses to compose one whose marker it can already find.
48
49The marker lives on the outbox row rather than on a stamped field on the
50order, and the choice is not arbitrary. The outbox row IS the message: the
51claim being recorded is "this message exists", and putting that claim
52anywhere else means two records that can disagree -- an order stamped
53`confirmation_sent` whose message was never actually written is a customer
54who will never be told, and nothing will ever notice. It also matches the
55house pattern exactly (system_order_fulfillment stamps
56`shipments/{id}:line/{id}` into stock_moves.reference and scans for it).
57And it is the only option that gets refunds right: a second refund on one
58order is a second fact that deserves a second email, so the refund's own
59id is part of its marker, while an order-level `refund_email_sent` flag
60would silence it. The honest cost: a compaction that discarded delivered
61outbox rows would let a replay re-send. Nothing prunes the outbox today
62(object_daemon.process_email_outbox only updates rows), and the day
63something does, its retention window is the thing to argue about -- which
64is a better place for the argument than a stamped boolean nobody can
65audit.
66
67**"Your order is ready" is the one of the four that is not a courtesy.**
68A confirmation is reassurance and a shipping note is a convenience: in
69both cases the customer is at home and can wait. A pickup customer cannot.
70Without this message they stand at a counter guessing, or they turn up
71twenty minutes early and hover, or they do not turn up at all and the food
72goes cold on a shelf -- and the whole promise of ordering ahead is that
73you do not have to stand there. That is why it is a TRANSITION and not a
74button: on a busy Friday the button is the first thing that gets forgotten,
75and the fact that causes the message IS the message's trigger.
76
77It fires only for a PICKUP order. `fulfillment_method` decides -- read
78with .get, so a box whose orders schema predates the pickup slice simply
79never sends it -- because "ready for collection" is a lie to somebody
80whose parcel is going in a van, and there is nowhere for a shipping
81customer to come and get it.
82
83**SMS is the honest channel, and it is a CONNECTOR boundary, not an
84adapter written here.** A person walking back from the car park reads a
85text; they do not check email. So the channel is named in a setting,
86`notify.sms_provider`, defaulting to `none`, and it degrades EXACTLY the
87way the carrier work degrades: with nothing configured the message still
88goes -- by email -- the result says which channel carried it, and nothing
89pretends to have sent a text. `manual` means the counter phones them, and
90says so. Any other value names a provider that is not installed on this
91box, which is reported rather than silently ignored: an operator who
92pasted a provider name in and got silence would reasonably conclude the
93system was texting people.
94
95What is deliberately NOT written here is a Twilio-shaped adapter. Nothing
96in this repo can test one, an untested integration against a paid API is
97the worst kind of confident wrong answer, and the second half of the
98argument is bigger than the first: orders carries no customer_phone at
99all, so even a perfect adapter would have no number to send to. Adding
100that column is the pickup slice's business, not this handler's. What an
101SMS connector must provide when it exists is one function shaped like
102app-shipping's carrier interface -- send(to, text, *, base_dir) answering
103in the connector vocabulary ({"ok": True} / {"skip": True, "reason"} /
104{"ok": False, "error", "permanent"}) -- and the choice of channel stays
105here while the credentials stay over there.
106
107**Degrading honestly.** No customer_email on the order: skipped, with the
108reason in the result, never a crash and never a message sent to "". No
109portal.base_url configured: the mail goes out with no links rather than
110with guaranteed-404 ones, exactly as system_invoice_aging's dunning mail
111already does. No shipments collection, no invoices collection: those are
112other packages, app-orders depends on neither, and their absence costs a
113line of detail rather than the message.
114
115Plain text only. An HTML alternative is supported by the outbox
116(html_body) and deliberately unused: these are four short paragraphs a
117person reads, every mail client on earth renders text, and a templating
118layer is the kind of thing that gets built once and then owns every
119future change to a sentence.
120"""
121
122import os
123import secrets
124
125import object_email
126import object_money
127import object_records
128
129HANDLES = [
130 "orders.record.created",
131 "orders.record.updated",
132 "refunds.record.created",
133]
134
135ACTOR = "system_order_email"
136
137# The confirmation fires anywhere at or past `confirmed`, not only on the
138# exact value. The zero-touch shop (app-shop's auto_fulfill) confirms and
139# ships a paid order in one burst of writes, so an order can be `shipped`
140# by the time this handler first sees it -- and a buyer who never got a
141# confirmation because their order moved too fast is exactly the silence
142# this slice exists to end. The marker makes the wider net safe.
143# The pickup rungs are in the set for the same reason and not by
144# accident: `preparing`, `ready` and `collected` are all past `confirmed`,
145# and a counter shop that takes an order and starts making it in one burst
146# of writes would otherwise never send a confirmation at all.
147CONFIRMED_ONWARD = {"confirmed", "processing", "partial", "shipped",
148 "delivered", "preparing", "ready", "collected"}
149
150# Same reasoning for the shipping note: `delivered` is downstream of
151# `shipped`, and an order that jumped straight to it still needs the
152# "it is on its way" mail somebody may be waiting for.
153SHIPPED_ONWARD = {"shipped", "delivered"}
154
155# And the same wider net for the pickup note. `collected` is downstream of
156# `ready`, so an order that jumped straight to it never got told -- which
157# on the counter path is usually a walk-in the shop served in one motion,
158# and the mail then reads as a receipt for a collection that happened
159# rather than a summons. Harmless where it is redundant; the failure the
160# other way round is somebody never told their food was waiting, which is
161# the entire reason this message exists. Same net as CONFIRMED_ONWARD, and
162# the marker makes the wider net safe.
163READY_ONWARD = {"ready", "collected"}
164
165# The one fulfilment method a "come and get it" message is true of. A
166# shipping order has a van; a `counter` sale was handed over as it was
167# made. Absent (an app-orders that predates the pickup slice) is not
168# pickup, so nothing is sent and nothing breaks.
169PICKUP_METHOD = "pickup"
170
171# The channel setting and the two values that mean "no adapter here". See
172# the module docstring: absent must degrade to email, never to silence.
173SMS_PROVIDER_SETTING = "notify.sms_provider"
174SMS_NOT_CONFIGURED = ("none", "")
175SMS_MANUAL = "manual"
176
177# An invoice in one of these still wants money, so the confirmation
178# carries the pay door. `void` and `paid` do not.
179UNPAID_INVOICE_STATUSES = {"draft", "sent", "partial", "overdue"}
180
181KIND_CONFIRMED = "confirmed"
182KIND_SHIPPED = "shipped"
183KIND_READY = "ready"
184
185
186def _base_dir():
187 return os.environ.get("DBBASIC_DATA_DIR", "data")
188
189
190def _text(value):
191 return str(value if value is not None else "").strip()
192
193
194def _setting(base, key, default=""):
195 """Duplicated on purpose, like every other package that reads
196 app_settings -- see docs/logic-decisions.md #4."""
197 try:
198 for row in object_records.read_collection_records("app_settings",
199 base_dir=base):
200 if row.get("key") == key and _text(row.get("value")):
201 return _text(row["value"])
202 except Exception:
203 pass
204 return default
205
206
207def _marker(order_id, kind):
208 return f"{ACTOR}:orders/{order_id}:{kind}"
209
210
211def _sent_markers(base):
212 """Every message this handler has already composed, or None when the
213 outbox cannot be read at all.
214
215 None is a REFUSAL, not an empty set. The two ways to be wrong here are
216 not symmetric: a message this pass skips will be composed by the next
217 event on the same record (and there is always a next event, because
218 the dispatcher replays), whereas a message sent twice is already in
219 somebody's inbox and cannot be taken back. When in doubt, stay quiet
220 -- and say WHICH doubt, so "app-email is not installed" never
221 masquerades as "already told them".
222
223 Read once per invocation rather than once per message: the outbox is
224 append-storage and grows, and scanning it three times to compose three
225 mails is the kind of quiet waste that only shows up at volume.
226 """
227 try:
228 rows = object_records.read_collection_records(
229 object_email.OUTBOX_COLLECTION, base_dir=base)
230 except Exception:
231 return None
232 return {_text(row.get("source_object_id")) for row in rows}
233
234
235def _base_url(base):
236 """The public origin this shop's links are built from, or "" when the
237 operator has not configured one. Never a bare path: a relative URL in
238 an email is a link that does nothing in every mail client there is, so
239 an unconfigured deployment sends the text without the link rather than
240 with a broken one.
241 """
242 return _setting(base, "portal.base_url").rstrip("/")
243
244
245def _ensure_track_token(base, order):
246 """The order's portal_token, minted here if it has none yet.
247
248 system_order_portal_link mints it too, but handlers run in sorted
249 object-id order, so on a hand-entered order this handler composed the
250 confirmation BEFORE that one ran: the mail went out without the
251 tracking link, and its sent marker then blocked a corrected resend, so
252 the customer never got the door at all. Minting here is the same act
253 portal_link performs (a fresh token_urlsafe(32), written with
254 preserve_read_only, never rotating one that exists), done as a
255 compare-and-set so a token another writer minted a moment ago is
256 adopted rather than overwritten -- it may already be in an inbox.
257 Draft orders get nothing, for portal_link's reason."""
258 token = _text(order.get("portal_token"))
259 if token or (_text(order.get("status")) or "draft") == "draft" or not order.get("id"):
260 return token
261 current = order
262 for _attempt in range(2):
263 try:
264 object_records.update_collection_record(
265 "orders", order["id"], {"portal_token": secrets.token_urlsafe(32)},
266 base_dir=base, actor=ACTOR, preserve_read_only=True,
267 expected_rev=object_records.compute_record_rev(current))
268 except Exception:
269 pass # a concurrent writer won, or our copy was stale: re-read
270 current = _order(base, order["id"]) or {}
271 token = _text(current.get("portal_token"))
272 if token:
273 order["portal_token"] = token
274 return token
275 return ""
276
277
278def _track_link(base, order):
279 origin = _base_url(base)
280 if not origin:
281 return ""
282 token = _ensure_track_token(base, order)
283 if not token:
284 return ""
285 return f"{origin}/orders/track/{token}"
286
287
288def _pay_link(base, invoice):
289 if invoice is None:
290 return ""
291 token = _text(invoice.get("portal_token"))
292 origin = _base_url(base)
293 if not token or not origin:
294 return ""
295 if _text(invoice.get("status")) not in UNPAID_INVOICE_STATUSES:
296 return ""
297 return f"{origin}/pay/{token}"
298
299
300def _order(base, order_id):
301 if not order_id:
302 return None
303 try:
304 return object_records.get_collection_record("orders", order_id,
305 base_dir=base)
306 except Exception:
307 return None
308
309
310def _invoice_for(base, order):
311 invoice_id = _text(order.get("invoice_id"))
312 if not invoice_id:
313 return None
314 try:
315 return object_records.get_collection_record("invoices", invoice_id,
316 base_dir=base)
317 except Exception:
318 return None
319
320
321def _lines_for(base, order_id):
322 try:
323 rows = object_records.read_collection_records("order_lines",
324 base_dir=base)
325 except Exception:
326 return []
327 lines = [row for row in rows if _text(row.get("order_id")) == order_id]
328 lines.sort(key=lambda row: _text(row.get("description")))
329 return lines
330
331
332def _money(base, cents, currency):
333 """Whole currency units, never raw minor units. "1200" in a customer's
334 email is a bill for twelve hundred of something -- and the one place a
335 formatting failure must not become a traceback is the message that
336 tells somebody their money moved."""
337 try:
338 return object_money.format_amount(cents or 0, currency or "USD",
339 base_dir=base)
340 except Exception:
341 return f"{cents or 0} (minor units)"
342
343
344def _shipment_with_tracking(base, order_id):
345 """The outbound parcel worth naming: the one that actually carries a
346 carrier or a tracking number. Returns None when shipping is not
347 installed, when nothing has been dispatched, or when the parcel simply
348 has no tracking -- all three of which are "say it shipped, say no more"
349 rather than an error.
350 """
351 try:
352 rows = object_records.read_collection_records("shipments",
353 base_dir=base)
354 except Exception:
355 return None
356 best = None
357 for row in rows:
358 if _text(row.get("order_id")) != order_id:
359 continue
360 if _text(row.get("direction")) == "inbound":
361 continue
362 if _text(row.get("carrier")) or _text(row.get("tracking_number")):
363 best = row
364 return best
365
366
367def _queue(base, *, to, subject, body, marker):
368 """One outbox row, or a reason it could not be written. Wrapped whole:
369 the outbox belongs to another package (app-email) and a shop that
370 never installed it must still be able to take orders."""
371 try:
372 object_email.enqueue(to, subject, body, base_dir=base,
373 source_object_id=marker)
374 except Exception as exc:
375 return str(exc)[:200]
376 return ""
377
378
379# --- the three messages ------------------------------------------------------
380
381def _confirmation_body(base, order, lines, invoice):
382 currency = _text(order.get("currency")) or "USD"
383 number = _text(order.get("number")) or order["id"]
384 parts = [f"Hello {_text(order.get('customer_name')) or 'there'},", "",
385 f"Thank you -- we have your order {number}.", ""]
386 for line in lines:
387 description = (_text(line.get("description"))
388 or _text(line.get("product_id")) or "Item")
389 quantity = _text(line.get("quantity")) or "1"
390 amount = _money(base, line.get("line_total_cents"), currency)
391 parts.append(f" {quantity} x {description} -- {amount}")
392 if lines:
393 parts.append("")
394 parts.append(f"Total: {_money(base, order.get('total_cents'), currency)}")
395
396 track = _track_link(base, order)
397 if track:
398 parts += ["", f"Follow your order here: {track}"]
399 pay = _pay_link(base, invoice)
400 if pay:
401 # Only when money is genuinely still owed -- see _pay_link. A "pay
402 # now" line on a paid order is how a shop gets paid twice.
403 parts += ["", f"There is still a balance to settle: {pay}"]
404 parts += ["", "We will email you again when it ships.", ""]
405 return "\n".join(parts)
406
407
408def _shipped_body(base, order, shipment):
409 number = _text(order.get("number")) or order["id"]
410 parts = [f"Hello {_text(order.get('customer_name')) or 'there'},", "",
411 f"Your order {number} is on its way.", ""]
412 if shipment is not None:
413 carrier = _text(shipment.get("carrier"))
414 tracking = _text(shipment.get("tracking_number"))
415 if carrier:
416 parts.append(f"Carrier: {carrier}")
417 if tracking:
418 parts.append(f"Tracking number: {tracking}")
419 if carrier or tracking:
420 parts.append("")
421 track = _track_link(base, order)
422 if track:
423 parts += [f"Track it here: {track}", ""]
424 return "\n".join(parts)
425
426
427def _ready_body(base, order):
428 """Come and get it -- and say WHERE and BY WHEN if the order knows.
429
430 Short on purpose. This is the message most likely to be read on a
431 phone, one-handed, walking; anything below the first two lines will
432 not be read at all, so the two lines carry the whole fact.
433 """
434 number = _text(order.get("number")) or order["id"]
435 parts = [f"Hello {_text(order.get('customer_name')) or 'there'},", "",
436 f"Your order {number} is ready to collect.", ""]
437 # Both read with .get: they belong to the pickup slice, and this
438 # message must compose on a box whose orders schema has not got them.
439 ready_at = _text(order.get("ready_at"))
440 if ready_at:
441 parts += [f"Ready since: {ready_at}", ""]
442 track = _track_link(base, order)
443 if track:
444 parts += [f"Your order: {track}", ""]
445 parts += ["See you shortly.", ""]
446 return "\n".join(parts)
447
448
449def _sms_channel(base):
450 """(provider, note) -- what would carry a text, and what actually will.
451
452 Never raises and never blocks the mail. The channel is a SETTING here
453 and the credentials are a connector's problem elsewhere, exactly as
454 carrier.provider works: a shop with nothing configured must lose
455 nothing, so the email goes either way and this only decides what the
456 result gets to claim.
457 """
458 provider = _setting(base, SMS_PROVIDER_SETTING, "none").lower()
459 if provider in SMS_NOT_CONFIGURED:
460 return "none", ("no SMS provider configured; the customer was told "
461 "by email")
462 if provider == SMS_MANUAL:
463 return SMS_MANUAL, ("notify.sms_provider is manual: the email went, "
464 "and the counter texts or phones by hand")
465 # A provider was named and there is no adapter on this box to answer to
466 # it. Said out loud rather than swallowed: an operator who pasted a
467 # name in and heard nothing would reasonably assume texts were going
468 # out, and the customer would be the one who found out otherwise.
469 return provider, (f"notify.sms_provider names '{provider}', but no SMS "
470 "connector is installed on this server; the customer "
471 "was told by email")
472
473
474def _refund_body(base, order, refund):
475 number = _text(order.get("number")) or order["id"]
476 currency = _text(order.get("currency")) or "USD"
477 amount = _money(base, refund.get("amount_cents"), currency)
478 parts = [f"Hello {_text(order.get('customer_name')) or 'there'},", "",
479 f"We have refunded {amount} against your order {number}.", ""]
480 reason = _text(refund.get("reason"))
481 if reason:
482 parts += [f"Reason: {reason}", ""]
483 parts += ["Depending on your bank, it can take a few days to appear on "
484 "your statement.", ""]
485 track = _track_link(base, order)
486 if track:
487 parts += [f"Your order: {track}", ""]
488 return "\n".join(parts)
489
490
491# --- triggers ----------------------------------------------------------------
492
493def _on_order(base, order_id):
494 order = _order(base, order_id)
495 if order is None:
496 return {"ok": True, "skipped": "order gone"}
497
498 to = _text(order.get("customer_email"))
499 if not to:
500 # A guest checkout always types one; an order raised by hand in the
501 # back office may not have. Say so plainly -- an operator reading
502 # "no customer_email" knows exactly what to add, whereas silence
503 # looks like a working mailer.
504 return {"ok": True, "skipped": "no customer_email on the order",
505 "order_id": order_id}
506
507 sent = _sent_markers(base)
508 if sent is None:
509 return {"ok": True, "skipped": "outbox unreadable; nothing composed",
510 "order_id": order_id}
511
512 status = _text(order.get("status"))
513 number = _text(order.get("number")) or order_id
514 queued, skipped, errors = [], [], {}
515
516 if status in CONFIRMED_ONWARD:
517 marker = _marker(order_id, KIND_CONFIRMED)
518 if marker in sent:
519 skipped.append(KIND_CONFIRMED)
520 else:
521 error = _queue(
522 base, to=to,
523 subject=f"Your order {number} is confirmed",
524 body=_confirmation_body(base, order, _lines_for(base, order_id),
525 _invoice_for(base, order)),
526 marker=marker)
527 (queued.append(KIND_CONFIRMED) if not error
528 else errors.setdefault(KIND_CONFIRMED, error))
529
530 if status in SHIPPED_ONWARD:
531 marker = _marker(order_id, KIND_SHIPPED)
532 if marker in sent:
533 skipped.append(KIND_SHIPPED)
534 else:
535 error = _queue(
536 base, to=to,
537 subject=f"Your order {number} has shipped",
538 body=_shipped_body(base, order,
539 _shipment_with_tracking(base, order_id)),
540 marker=marker)
541 (queued.append(KIND_SHIPPED) if not error
542 else errors.setdefault(KIND_SHIPPED, error))
543
544 # The pickup note. Gated on fulfillment_method, not only on status:
545 # "ready for collection" said to somebody whose parcel is on a van is
546 # a customer driving to a shop for nothing. Read with .get, so an
547 # app-orders that predates the pickup slice simply never matches.
548 sms_note = ""
549 if (status in READY_ONWARD
550 and _text(order.get("fulfillment_method")) == PICKUP_METHOD):
551 marker = _marker(order_id, KIND_READY)
552 if marker in sent:
553 skipped.append(KIND_READY)
554 else:
555 _provider, sms_note = _sms_channel(base)
556 error = _queue(
557 base, to=to,
558 subject=f"Your order {number} is ready to collect",
559 body=_ready_body(base, order),
560 marker=marker)
561 (queued.append(KIND_READY) if not error
562 else errors.setdefault(KIND_READY, error))
563
564 result = {"ok": True, "order_id": order_id, "queued": queued,
565 "skipped_already_sent": skipped}
566 if sms_note:
567 # Reported, not swallowed: which channel actually carried the one
568 # message that a customer is standing somewhere waiting for is
569 # exactly the thing an operator needs to be able to check.
570 result["sms"] = sms_note
571 if errors:
572 result["errors"] = errors
573 return result
574
575
576def _order_for_refund(base, refund):
577 """Walk a refund back to the order it came off.
578
579 refunds.invoice_id is stamped by app-payments' hook_refunds from the
580 payment, and app-shop's checkout stamps invoices.source_order_id, so
581 the chain is refund -> invoice -> order. The fallback scan on
582 orders.invoice_id catches an invoice raised before source_order_id
583 existed, or one converted from an order the other way round -- a
584 refund whose order cannot be found is a message not sent, never a
585 crash.
586 """
587 invoice_id = _text(refund.get("invoice_id"))
588 if not invoice_id:
589 return None
590 try:
591 invoice = object_records.get_collection_record("invoices", invoice_id,
592 base_dir=base)
593 except Exception:
594 invoice = None
595 if invoice is not None and _text(invoice.get("source_order_id")):
596 order = _order(base, _text(invoice.get("source_order_id")))
597 if order is not None:
598 return order
599 try:
600 rows = object_records.read_collection_records("orders", base_dir=base)
601 except Exception:
602 return None
603 for row in rows:
604 if _text(row.get("invoice_id")) == invoice_id:
605 return row
606 return None
607
608
609def _on_refund(base, refund_id):
610 try:
611 refund = object_records.get_collection_record("refunds", refund_id,
612 base_dir=base)
613 except Exception:
614 return {"ok": True, "skipped": "refund gone"}
615
616 order = _order_for_refund(base, refund)
617 if order is None:
618 return {"ok": True, "skipped": "no order behind this refund",
619 "refund_id": refund_id}
620
621 to = _text(order.get("customer_email"))
622 if not to:
623 return {"ok": True, "skipped": "no customer_email on the order",
624 "refund_id": refund_id, "order_id": order["id"]}
625
626 # The refund's own id is in the marker: two refunds against one order
627 # are two separate facts, and a customer told about the first but not
628 # the second is a support ticket.
629 marker = _marker(order["id"], f"refunded/{refund_id}")
630 sent = _sent_markers(base)
631 if sent is None:
632 return {"ok": True, "skipped": "outbox unreadable; nothing composed",
633 "order_id": order["id"], "refund_id": refund_id}
634 if marker in sent:
635 return {"ok": True, "order_id": order["id"], "refund_id": refund_id,
636 "queued": [], "skipped_already_sent": ["refunded"]}
637
638 number = _text(order.get("number")) or order["id"]
639 error = _queue(base, to=to,
640 subject=f"A refund on your order {number}",
641 body=_refund_body(base, order, refund),
642 marker=marker)
643 result = {"ok": True, "order_id": order["id"], "refund_id": refund_id,
644 "queued": [] if error else ["refunded"],
645 "skipped_already_sent": []}
646 if error:
647 result["errors"] = {"refunded": error}
648 return result
649
650
651def EVENT(request):
652 # The dispatcher's payload carries the RAW verb ("create"/"update");
653 # the event NAME uses the participle. Accept both.
654 action = _text(request.get("action"))
655 action = {"create": "created", "update": "updated",
656 "delete": "deleted"}.get(action, action)
657 if action not in ("created", "updated"):
658 return {"ok": True, "skipped": "not a create or update"}
659
660 record_id = _text(request.get("record_id") or request.get("id"))
661 if not record_id:
662 return {"ok": True, "skipped": "no record id"}
663
664 collection = _text(request.get("collection"))
665 if not collection:
666 # An operator poking this by hand over HTTP: infer from what they
667 # named rather than refusing on a technicality.
668 collection = "refunds" if _text(request.get("refund_id")) else "orders"
669
670 base = _base_dir()
671 if collection == "refunds":
672 return _on_refund(base, record_id)
673 if collection == "orders":
674 return _on_order(base, record_id)
675 return {"ok": True, "skipped": f"nothing to say about {collection}"}
676
677
678# EVENT is the verb the change dispatcher calls handlers with (see
679# object_change_dispatch); POST stays as an alias so an operator can poke
680# the handler by hand over HTTP. The alias is not decoration -- a handler
681# shipped with only POST silently matched nothing in production once, and
682# every handler in this house has carried both ever since.
683POST = EVENT