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.
shop_fulfillment.py · 18.2 KB · 406 lines
| 1 | """system_shop_fulfillment -- money arrived, so the sale is real and the |
| 2 | box goes out. |
| 3 | |
| 4 | HANDLES payment writes. When a payment lands against an invoice raised for |
| 5 | a web order, this confirms the order and -- unless the shop has taken over |
| 6 | its own packing bench -- ships it. |
| 7 | |
| 8 | The ordering is still the whole point. Checkout decrements nothing: an |
| 9 | order that is never paid for must not have consumed stock, or every |
| 10 | abandoned card leaves a phantom sale behind and the shop shows "sold out" |
| 11 | for goods sitting on the shelf. Stock moves when money moves. |
| 12 | |
| 13 | **What changed, and why this object got smaller.** It used to write the |
| 14 | stock moves itself, one per order line, at payment. That was right while |
| 15 | an order could only be fulfilled all at once; it became wrong the moment |
| 16 | shipments existed, because "the goods left" is a fact about a BOX, not |
| 17 | about a payment, and two objects claiming the same fact is how a system |
| 18 | learns to disagree with itself. So the old behavior now travels through |
| 19 | the shipment noun: this handler creates a shipment for everything |
| 20 | unshipped and marks it packed, then shipped, and app-shipping's |
| 21 | system_order_fulfillment does what it always does when a shipment leaves |
| 22 | -- one sale move per line, idempotent per line, order status derived. |
| 23 | Nothing about the zero-touch shop's experience changes; there is simply a |
| 24 | document now saying what went out, and a packing slip to put in the box. |
| 25 | |
| 26 | **shop.auto_fulfill (default TRUE)** is the seam. A shop with no warehouse |
| 27 | wants payment to mean shipped and never wants to see a pick list; a shop |
| 28 | that picks and packs sets it false, and this handler then confirms the |
| 29 | order and stops, leaving the shipment to action_create_shipment and a |
| 30 | human with a trolley. Defaulting true is what keeps the proven chain |
| 31 | working for every existing installation without anybody configuring |
| 32 | anything. |
| 33 | |
| 34 | Placement follows docs/logic-decisions.md #6 -- a REACTION (post-commit, |
| 35 | best-effort, never blocks the payment). A shop that cannot record a |
| 36 | shipment must still be able to take the money; the discrepancy is visible |
| 37 | and fixable, whereas a refused payment is a lost sale nobody can recover. |
| 38 | Every failure below therefore lands in the RESULT, not in an exception: |
| 39 | no shipping app installed, no stock app installed, no configured |
| 40 | locations -- the order still confirms and the response says what did not |
| 41 | happen. |
| 42 | |
| 43 | Idempotency by provenance (#7): the shipment carries "orders/{id}" in its |
| 44 | notes and, more usefully, the remaining-quantity arithmetic in |
| 45 | action_create_shipment means a replayed payment finds nothing left to ship |
| 46 | and returns ok with a note rather than raising a second empty parcel. The |
| 47 | stock moves are stamped per shipment line by system_order_fulfillment, so |
| 48 | a replay moves nothing twice there either. The books entry is handled by |
| 49 | app-payments' system_books, unchanged -- this object deliberately does not |
| 50 | post anything itself. |
| 51 | """ |
| 52 | |
| 53 | import os |
| 54 | |
| 55 | import object_collections |
| 56 | import object_execution |
| 57 | import object_records |
| 58 | import python_object_runtime |
| 59 | |
| 60 | HANDLES = [ |
| 61 | "payments.record.created", |
| 62 | "payments.record.updated", |
| 63 | ] |
| 64 | |
| 65 | ACTOR = "system_shop_fulfillment" |
| 66 | |
| 67 | |
| 68 | def _base_dir(): |
| 69 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 70 | |
| 71 | |
| 72 | def _text(value): |
| 73 | return str(value if value is not None else "").strip() |
| 74 | |
| 75 | |
| 76 | def _truthy(value, default): |
| 77 | text = _text(value).lower() |
| 78 | if not text: |
| 79 | return default |
| 80 | return text in ("true", "1", "yes", "on") |
| 81 | |
| 82 | |
| 83 | def _setting(base, key, default=""): |
| 84 | try: |
| 85 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 86 | if row.get("key") == key and _text(row.get("value")): |
| 87 | return _text(row["value"]) |
| 88 | except Exception: |
| 89 | pass |
| 90 | return default |
| 91 | |
| 92 | |
| 93 | def _payment_for(request, base): |
| 94 | record = request.get("record") |
| 95 | if isinstance(record, dict) and record.get("id"): |
| 96 | return record |
| 97 | payment_id = _text(request.get("record_id") or request.get("id")) |
| 98 | if not payment_id: |
| 99 | return None |
| 100 | try: |
| 101 | return object_records.get_collection_record("payments", payment_id, |
| 102 | base_dir=base) |
| 103 | except Exception: |
| 104 | return None |
| 105 | |
| 106 | |
| 107 | def _invoice_is_settled(base, invoice_id): |
| 108 | """(True, "") when the bill is fully paid, else (False, why). |
| 109 | |
| 110 | Trusts the invoice's own status where it is decisive, and falls back |
| 111 | to comparing what has been paid against the total -- because a shop |
| 112 | with app-payments' status handler absent would otherwise never ship |
| 113 | anything, and "your money arrived and nothing happened" is a worse |
| 114 | failure than shipping a shade early. |
| 115 | |
| 116 | A bill, payments or refunds that cannot be READ are a different case: |
| 117 | whether the money is there is unknown, and this used to answer |
| 118 | "settled" ("do not hold the goods hostage to a lookup failure"), so a |
| 119 | part-paid or refunded order went out of the door. Goods that have left |
| 120 | cannot be called back; a held order is retried by the next payment |
| 121 | event. Not installed (no invoices or refunds app) is still a fact. |
| 122 | """ |
| 123 | if not invoice_id: |
| 124 | return True, "" # nothing to settle; not a web order's bill |
| 125 | try: |
| 126 | invoice = object_records.get_collection_record( |
| 127 | "invoices", invoice_id, base_dir=base) |
| 128 | except (object_collections.CollectionNotFoundError, |
| 129 | object_records.RecordNotFoundError): |
| 130 | return True, "" # no bill to hold the goods to |
| 131 | except Exception as exc: |
| 132 | return False, (f"invoices unreadable ({str(exc)[:120]}); whether the " |
| 133 | f"bill is paid is unknown, so nothing shipped") |
| 134 | if _text(invoice.get("status")) in ("paid", "void"): |
| 135 | return True, "" |
| 136 | total = _int(invoice.get("total_cents")) |
| 137 | if not total: |
| 138 | return True, "" |
| 139 | |
| 140 | # Sum the payments HERE rather than trusting invoice.amount_paid_cents. |
| 141 | # That field is derived by a rollup, and this handler runs ON the write |
| 142 | # that just created the payment -- so at this instant the invoice has |
| 143 | # not been told about the money that triggered us. Reading it would |
| 144 | # mean the first payment never ships anything and the SECOND one ships |
| 145 | # everything, which is a bug that only appears for customers who pay |
| 146 | # in instalments. |
| 147 | paid = 0 |
| 148 | try: |
| 149 | for row in object_records.read_collection_records("payments", base_dir=base): |
| 150 | if (_text(row.get("invoice_id")) == invoice_id |
| 151 | and _text(row.get("status")) == "received"): |
| 152 | paid += _int(row.get("amount_cents")) |
| 153 | except Exception as exc: |
| 154 | return False, (f"payments unreadable ({str(exc)[:120]}); whether the " |
| 155 | f"bill is paid is unknown, so nothing shipped") |
| 156 | try: |
| 157 | for row in object_records.read_collection_records("refunds", base_dir=base): |
| 158 | if _text(row.get("invoice_id")) == invoice_id: |
| 159 | paid -= _int(row.get("amount_cents")) |
| 160 | except object_collections.CollectionNotFoundError: |
| 161 | pass # no refunds app installed is not a refund |
| 162 | except Exception as exc: |
| 163 | return False, (f"refunds unreadable ({str(exc)[:120]}); whether the " |
| 164 | f"bill is paid is unknown, so nothing shipped") |
| 165 | |
| 166 | if paid >= total: |
| 167 | return True, "" |
| 168 | return False, f"invoice not settled: {paid} of {total} paid" |
| 169 | |
| 170 | |
| 171 | def _int(value): |
| 172 | try: |
| 173 | return int(_text(value) or 0) |
| 174 | except (TypeError, ValueError): |
| 175 | return 0 |
| 176 | |
| 177 | |
| 178 | def _order_for_invoice(base, invoice_id): |
| 179 | """The order this invoice settles: one that names it AND belongs to whoever |
| 180 | owns the invoice. |
| 181 | |
| 182 | orders.invoice_id is a free-text field any order's owner may set, and |
| 183 | this took the first order naming the invoice. An order of somebody |
| 184 | else's, pointed at the shop's invoice, was "the order" when the shop's |
| 185 | customer paid, and was the one confirmed and shipped. Checkout writes |
| 186 | the order and its invoice under one owner, so an order owned by anybody |
| 187 | else is no part of this sale. When there is no invoice to own it |
| 188 | (none on file, or none installed) the first order naming the id is |
| 189 | still taken, as before: there is no sale of anybody else's to take. |
| 190 | When the invoice cannot be READ the same is done, and |
| 191 | _invoice_is_settled then holds the goods and says why.""" |
| 192 | if not invoice_id: |
| 193 | return None |
| 194 | try: |
| 195 | orders = object_records.read_collection_records("orders", base_dir=base) |
| 196 | except Exception: |
| 197 | return None |
| 198 | try: |
| 199 | owner = _text(object_records.get_collection_record( |
| 200 | "invoices", invoice_id, base_dir=base).get("owner_id")) |
| 201 | except Exception: |
| 202 | owner = None |
| 203 | for order in orders: |
| 204 | if (_text(order.get("invoice_id")) == invoice_id |
| 205 | and (owner is None or _text(order.get("owner_id")) == owner)): |
| 206 | return order |
| 207 | return None |
| 208 | |
| 209 | |
| 210 | def _call(object_id, payload, *, method="POST"): |
| 211 | """Run another installed object in process, the same way site_shop calls |
| 212 | its siblings: this package owns the payment-to-order join and nothing |
| 213 | about boxes, so it asks the object that does. |
| 214 | |
| 215 | Returns (result, error). A missing object -- app-shipping simply not |
| 216 | installed -- is an error string, never an exception: see the module |
| 217 | docstring's posture about what a failure here is allowed to cost. |
| 218 | """ |
| 219 | try: |
| 220 | runtime = python_object_runtime.PythonObjectRuntime() |
| 221 | outcome = object_execution.execute_object( |
| 222 | runtime, |
| 223 | object_execution.ObjectExecutionRequest( |
| 224 | object_id, method=method, payload=payload)) |
| 225 | except Exception as exc: |
| 226 | return None, str(exc)[:200] |
| 227 | if not outcome.ok: |
| 228 | message = getattr(outcome.error, "message", "") if outcome.error else "" |
| 229 | return None, _text(message)[:200] or f"{object_id} failed" |
| 230 | return outcome.result, "" |
| 231 | |
| 232 | |
| 233 | def _ship_everything(base, order): |
| 234 | """Create a shipment for everything still unshipped and send it. |
| 235 | |
| 236 | packed then shipped as two separate updates, deliberately: the schema's |
| 237 | transition ladder is open -> packed -> shipped, and a handler that |
| 238 | jumped straight to shipped would either be refused or would force the |
| 239 | ladder to be loosened for everybody, which would let a real packing |
| 240 | bench skip the step that means "somebody actually put this in a box". |
| 241 | """ |
| 242 | # action_create_shipment asks the permission engine whether its caller |
| 243 | # may update the order, and an in-process call with no identity is |
| 244 | # anonymous (object_access). This handler reacts to money that has |
| 245 | # already arrived for the shop's own order, so it says so explicitly |
| 246 | # rather than getting authority by omission. |
| 247 | created, error = _call("action_create_shipment", { |
| 248 | "order_id": order["id"], |
| 249 | "_identity": {"user_id": ACTOR, "roles": ["admin"]}}) |
| 250 | if error: |
| 251 | return {"shipped": False, "warning": |
| 252 | f"no shipment was created ({error}); the order still stands"} |
| 253 | if not isinstance(created, dict) or not created.get("ok"): |
| 254 | detail = _text((created or {}).get("error")) or "unknown reason" |
| 255 | return {"shipped": False, |
| 256 | "warning": f"no shipment was created ({detail}); the order still stands"} |
| 257 | |
| 258 | shipment_id = _text(created.get("shipment_id")) |
| 259 | if not shipment_id: |
| 260 | # Nothing left to ship: a replayed payment, or an order somebody |
| 261 | # already packed by hand. Idempotent, and not a failure. |
| 262 | return {"shipped": False, "note": _text(created.get("note"))} |
| 263 | |
| 264 | for status in ("packed", "shipped"): |
| 265 | try: |
| 266 | object_records.update_collection_record( |
| 267 | "shipments", shipment_id, {"status": status}, |
| 268 | base_dir=base, actor=ACTOR) |
| 269 | except Exception as exc: |
| 270 | return {"shipped": False, "shipment_id": shipment_id, |
| 271 | "warning": (f"shipment {shipment_id} could not move to " |
| 272 | f"{status}: {str(exc)[:120]}")} |
| 273 | |
| 274 | # Fire the fulfillment handler in process rather than waiting for the |
| 275 | # change-log dispatcher: this write came from a handler, not from an |
| 276 | # HTTP request, so nothing dispatched it, and the stock move has to |
| 277 | # happen now for exactly the reason it always did -- the goods have |
| 278 | # gone. The handler is idempotent per line, so the dispatcher's later |
| 279 | # at-least-once redelivery moves nothing twice. |
| 280 | result, error = _call("system_order_fulfillment", |
| 281 | {"collection": "shipments", "record_id": shipment_id}, |
| 282 | method="EVENT") |
| 283 | out = {"shipped": True, "shipment_id": shipment_id, |
| 284 | "lines": created.get("lines", 0), |
| 285 | "slip_path": created.get("slip_path", "")} |
| 286 | if error: |
| 287 | out["warning"] = (f"the shipment went out but its stock move did not " |
| 288 | f"({error}); the goods left the shelf without the " |
| 289 | f"ledger saying so") |
| 290 | return out |
| 291 | if isinstance(result, dict): |
| 292 | out["moved"] = result.get("moved", 0) |
| 293 | if result.get("warning"): |
| 294 | out["warning"] = result["warning"] |
| 295 | if result.get("order_status"): |
| 296 | out["order_status"] = result["order_status"] |
| 297 | return out |
| 298 | |
| 299 | |
| 300 | def EVENT(request): |
| 301 | base = _base_dir() |
| 302 | payment = _payment_for(request, base) |
| 303 | if not payment: |
| 304 | return {"ok": True, "skipped": "no payment in the event"} |
| 305 | if _text(payment.get("status")) != "received": |
| 306 | return {"ok": True, "skipped": "payment not received"} |
| 307 | |
| 308 | order = _order_for_invoice(base, _text(payment.get("invoice_id"))) |
| 309 | if order is None: |
| 310 | # Most payments are not for web orders. Saying so plainly beats a |
| 311 | # silent return that looks identical to a bug. |
| 312 | return {"ok": True, "skipped": "no web order for this payment"} |
| 313 | |
| 314 | # Goods leave when the BILL is settled, not when money merely arrives. |
| 315 | # |
| 316 | # This checked only that a payment existed and was received, so any |
| 317 | # amount shipped the order: a 14.00 payment against a 20.00 invoice |
| 318 | # fulfilled it in full, and the invoice was left sitting at `partial` |
| 319 | # saying so. Found by paying the wrong amount by hand on the live shop. |
| 320 | # |
| 321 | # The invoice already knows the answer -- system_invoice_status folds |
| 322 | # payments and refunds and flips it to paid or partial -- so this asks |
| 323 | # the document rather than doing its own arithmetic on one payment, |
| 324 | # which is also what makes a deposit followed by a balance work: the |
| 325 | # second payment is what tips it to paid, and that is the event that |
| 326 | # ships. |
| 327 | settled, reason = _invoice_is_settled(base, _text(payment.get("invoice_id"))) |
| 328 | if not settled: |
| 329 | return {"ok": True, "skipped": reason, "order_id": order["id"]} |
| 330 | if _text(order.get("status")) not in ("draft", "confirmed"): |
| 331 | return {"ok": True, "skipped": f"order already {_text(order.get('status'))}"} |
| 332 | |
| 333 | if _text(order.get("status")) == "draft": |
| 334 | try: |
| 335 | object_records.update_collection_record( |
| 336 | "orders", order["id"], {"status": "confirmed"}, |
| 337 | base_dir=base, actor=ACTOR, |
| 338 | expected_rev=object_records.compute_record_rev(order)) |
| 339 | except object_records.VersionConflictError: |
| 340 | return {"ok": True, "order_id": order["id"], |
| 341 | "skipped": "another pass is already handling this order"} |
| 342 | order = object_records.get_collection_record("orders", order["id"], |
| 343 | base_dir=base) |
| 344 | |
| 345 | result = {"ok": True, "order_id": order["id"], "confirmed": True} |
| 346 | |
| 347 | if not _truthy(_setting(base, "shop.auto_fulfill"), True): |
| 348 | # A shop with a packing bench: the order is confirmed and appears on |
| 349 | # the pick list, and a human decides what goes in which box. |
| 350 | # Deliberately NOT claimed below -- the order is supposed to sit at |
| 351 | # `confirmed` waiting for a person, and claiming it would take it |
| 352 | # off the very list it needs to be on. |
| 353 | result["note"] = ("shop.auto_fulfill is off; this order is confirmed " |
| 354 | "and waiting on the pick list") |
| 355 | result["shipped"] = False |
| 356 | return result |
| 357 | |
| 358 | # CLAIM THE ORDER BEFORE SHIPPING ANYTHING. |
| 359 | # |
| 360 | # Two concurrent deliveries of the same payment event -- the change |
| 361 | # dispatcher is at-least-once, and an operator can POST this handler by |
| 362 | # hand -- both read the order as `confirmed`, both walked past the guard |
| 363 | # above, and both shipped it. Reproduced reliably, three times in three: |
| 364 | # two shipments, FOUR units against an order of two, two sale moves. The |
| 365 | # goods left the shelf twice. |
| 366 | # |
| 367 | # Nothing below could have stopped it. action_create_shipment computes |
| 368 | # what is unshipped by reading shipment_lines, and hook_shipment_lines |
| 369 | # refuses an over-ship by summing them -- but both are check-then-write |
| 370 | # and a hook runs BEFORE the write lock, so under real concurrency both |
| 371 | # passes read an empty history and both wrote. Layered advisory checks |
| 372 | # do not compose into an atomic one. |
| 373 | # |
| 374 | # The only thing on this box that IS atomic is a compare-and-set on a |
| 375 | # single record: expected_rev, compared inside the write lock (63, |
| 376 | # plan/vocabulary/63-concurrency-spec.md). So the claim is the write |
| 377 | # that moves the order out of the shippable set, and the loser finds the |
| 378 | # row already changed. |
| 379 | # |
| 380 | # THE TRADE, stated because it is a real one: the ladder has no |
| 381 | # processing -> confirmed step, so an order whose shipment then FAILS |
| 382 | # stays at `processing` rather than falling back to `confirmed` for a |
| 383 | # redelivered event to retry. That is deliberate. A stuck order is |
| 384 | # visible on the pick list and a person ships it; a double shipment is |
| 385 | # goods out of the door against one payment, and no one finds out until |
| 386 | # the stock count. |
| 387 | try: |
| 388 | object_records.update_collection_record( |
| 389 | "orders", order["id"], {"status": "processing"}, |
| 390 | base_dir=base, actor=ACTOR, |
| 391 | expected_rev=object_records.compute_record_rev(order)) |
| 392 | except object_records.VersionConflictError: |
| 393 | result["shipped"] = False |
| 394 | result["skipped"] = "another pass claimed this order first" |
| 395 | return result |
| 396 | |
| 397 | result.update(_ship_everything(base, order)) |
| 398 | return result |
| 399 | |
| 400 | |
| 401 | # EVENT is the verb the change dispatcher calls handlers with (see |
| 402 | # object_change_dispatch); it went unnoticed here because in-process tests |
| 403 | # invoked POST directly and the dispatcher's method-not-supported error |
| 404 | # only surfaced on the live box. POST stays as an alias so an operator can |
| 405 | # poke the handler by hand over HTTP. |
| 406 | POST = EVENT |