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