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.
object_reservations.py · 15.0 KB · 328 lines
| 1 | """Available to promise: on hand less what live online orders are holding. |
| 2 | |
| 3 | **The owner's decision (2026-11-30).** "If I order online and drive to the |
| 4 | damn store I expect it to still be there when I arrive, otherwise the |
| 5 | inventory should have a flag to not allow pick reservations, because |
| 6 | sometimes you'd have a special only upon entry and they have a line inside |
| 7 | the store or outside, or even had people a number ticket so they don't have |
| 8 | line jumpers." So an online order RESERVES: from checkout, what it ordered |
| 9 | is held against the shelf, and the next shopper is promised only what is |
| 10 | left. The flag half is products.in_store_only: goods that are never put in |
| 11 | an online basket nor held for anybody online, because the people in the |
| 12 | shop (queueing, or holding a numbered ticket) come first. `online_refusal` |
| 13 | is the one sentence every door gives for it, and for the optional |
| 14 | products.online_max_per_order. |
| 15 | |
| 16 | **What was wrong.** action_checkout's stock gate summed stock_moves and |
| 17 | subtracted nothing, and stock moves only when money arrives |
| 18 | (system_shop_fulfillment -> a shipment -> system_order_fulfillment). So |
| 19 | every unpaid order was invisible to the next one: a simulated race sold one |
| 20 | unit to two orders and three units to ten -- and not only under a race; |
| 21 | sequential checkouts did it too, since none of them moved anything. |
| 22 | |
| 23 | **There is no reservation ledger, and there must not be one.** The holds |
| 24 | ARE the order lines. An order that reserves (orders.reserves_stock, stamped |
| 25 | by checkout) holds each line's quantity less what has already moved for it: |
| 26 | |
| 27 | held(line) = quantity - moved(line) while the order is live |
| 28 | |
| 29 | `moved(line)` is read off the sale moves themselves -- |
| 30 | system_order_fulfillment stamps each one `shipments/{id}:line/{shipment |
| 31 | line id}`, and the shipment line names its order line -- so the instant |
| 32 | the goods leave the shelf the hold becomes the move, and nothing is counted |
| 33 | twice or not at all. Not "the order says shipped": the status is derived |
| 34 | AFTER the move is written, and a hold released on the status would spend |
| 35 | the gap between the two double-counted, or a move that failed to write |
| 36 | would release a hold the shelf never paid. |
| 37 | |
| 38 | A live order is a sale (not dropship: those goods never touch our shelf) |
| 39 | whose status is one of RESERVING_STATUSES and whose hold has not lapsed. |
| 40 | Lapse is object_pickup.hold_lapsed, the same function that decides whether |
| 41 | the order still holds a pickup place, so a window and a shelf cannot |
| 42 | disagree about whether somebody is coming: |
| 43 | |
| 44 | - cancelled releases at once; |
| 45 | - an unpaid draft paying online lapses after pickup.hold_minutes (default |
| 46 | 30; 0 = never) -- the shopper abandoned the pay link; |
| 47 | - an unpaid draft paying AT PICKUP holds until its window ends plus |
| 48 | pickup.grace_minutes (default 30) -- it is not supposed to have paid yet; |
| 49 | - a paid or confirmed order holds until its goods move; |
| 50 | - shipped, delivered, collected and the rest hold nothing. |
| 51 | |
| 52 | **Derived, not swept**, for object_pickup's reasons (docs/logic-decisions.md |
| 53 | #2 vs #1): a lapsed hold changes no record's meaning -- the order is still a |
| 54 | draft with a live pay link -- so there is no transition to store, only a |
| 55 | count; and a sweeper would make releasing stock depend on a daemon with |
| 56 | croniter installed, which a stock install does not have. The cost, stated: |
| 57 | a shopper who pays after their hold lapsed and after somebody else took the |
| 58 | goods drives the level one under. That is a visible, refundable oversell on |
| 59 | one row, where before it was every order. |
| 60 | |
| 61 | **Back-office orders do not reserve.** Only orders checkout stamps with |
| 62 | reserves_stock count and are gated. An order an operator types is the |
| 63 | operator's own judgement about their own shelf, it was never gated, and |
| 64 | counting every confirmed back-office order (some shops never ship them |
| 65 | through this box) would show "sold out" online for goods on the shelf. |
| 66 | |
| 67 | The atomic half -- check-and-hold under concurrency -- is the locked check |
| 68 | on order_lines (app-orders system_stock_hold.LOCKED_CHECK, lock "stock"): |
| 69 | every write to any collection this fold reads takes that lock, so the |
| 70 | check's read and the line's write are one step for every writer. |
| 71 | |
| 72 | Pure functions first (no I/O, no clock); `read_holds` at the bottom is the |
| 73 | one fold over stored rows that the checkout gate, the locked check and the |
| 74 | storefront all call, so they cannot disagree about what is available -- the |
| 75 | same placement object_stock makes for the level itself. |
| 76 | """ |
| 77 | |
| 78 | from __future__ import annotations |
| 79 | |
| 80 | import re |
| 81 | from datetime import datetime |
| 82 | from decimal import Decimal, InvalidOperation |
| 83 | from pathlib import Path |
| 84 | from typing import Any, Iterable |
| 85 | |
| 86 | import object_pickup |
| 87 | |
| 88 | # An order in one of these, unless its hold lapsed, still owes the shelf |
| 89 | # whatever has not moved for it yet. The rest (shipped, delivered, |
| 90 | # collected, received, cancelled) hold nothing: their goods have left, or |
| 91 | # never will. |
| 92 | RESERVING_STATUSES = frozenset({"draft", "confirmed", "processing", "partial", |
| 93 | "preparing", "ready"}) |
| 94 | |
| 95 | # The product types that sit on a shelf and can run out -- the rule |
| 96 | # action_checkout, site_shop and object_stock's callers already share. |
| 97 | STOCKED_TYPES = ("physical", "asset", "") |
| 98 | |
| 99 | # system_order_fulfillment's per-line provenance marker on a sale move. |
| 100 | _MOVE_MARKER = re.compile(r"shipments/[^:\s]+:line/([^\s\]]+)") |
| 101 | |
| 102 | # app-counter's marker on a move that took an ORDER LINE's goods off the |
| 103 | # shelf with no shipment: a counter or pickup hand-over, or the waste move |
| 104 | # of a remade item (object_corrections.counter_marker). It names the order |
| 105 | # line itself, so the move's own quantity is what moved for that line. |
| 106 | # Corner Cup found counter sales never moved stock at all unless the shop |
| 107 | # had auto_fulfill, shop.stock_location and a shipment; a hand-over is the |
| 108 | # moment the goods leave, and the hold becomes this move the same way it |
| 109 | # becomes a shipment's -- read off the move, never off the status. |
| 110 | _COUNTER_MARKER = re.compile(r"(?<![\w/])orders/[^:\s]+:line/([^\s\]]+)") |
| 111 | |
| 112 | _TRUE = ("true", "1", "yes", "on") |
| 113 | |
| 114 | |
| 115 | def _text(value: Any) -> str: |
| 116 | return str(value if value is not None else "").strip() |
| 117 | |
| 118 | |
| 119 | def _qty(value: Any) -> Decimal: |
| 120 | try: |
| 121 | return Decimal(_text(value) or "0") |
| 122 | except (InvalidOperation, ValueError): |
| 123 | return Decimal("0") |
| 124 | |
| 125 | |
| 126 | def reserves(order: dict) -> bool: |
| 127 | """Does this order hold stock at all (whatever its status)?""" |
| 128 | return (_text(order.get("reserves_stock")).lower() in _TRUE |
| 129 | and _text(order.get("doc_type") or "sale") == "sale" |
| 130 | and _text(order.get("fulfillment_source")) != "dropship") |
| 131 | |
| 132 | |
| 133 | def tracked(product: dict | None) -> bool: |
| 134 | """Is this a thing on a shelf that can run out?""" |
| 135 | return product is not None and _text(product.get("product_type")) in STOCKED_TYPES |
| 136 | |
| 137 | |
| 138 | def in_store_only(product: dict | None) -> bool: |
| 139 | """products.in_store_only: never put in an online basket, never held |
| 140 | for an online order. The counter sells it.""" |
| 141 | return bool(product) and _text(product.get("in_store_only")).lower() in _TRUE |
| 142 | |
| 143 | |
| 144 | def shown_online(product: dict | None) -> bool: |
| 145 | """Does the online shop list this product? Always, unless it is in |
| 146 | store only AND the shop chose not to show it (products.show_online).""" |
| 147 | if not in_store_only(product): |
| 148 | return True |
| 149 | return _text(product.get("show_online") or "true").lower() in _TRUE |
| 150 | |
| 151 | |
| 152 | def online_cap(product: dict | None) -> Decimal | None: |
| 153 | """products.online_max_per_order, or None for no limit (blank or 0).""" |
| 154 | cap = _qty((product or {}).get("online_max_per_order")) |
| 155 | return cap if cap > 0 else None |
| 156 | |
| 157 | |
| 158 | def online_refusal(product: dict | None, wanted: Any) -> str: |
| 159 | """Why an online basket or order cannot take `wanted` of this product, |
| 160 | or "". The one sentence the basket, checkout and the locked check all |
| 161 | give, so a shopper hears the same refusal from every door.""" |
| 162 | if not product: |
| 163 | return "" |
| 164 | name = _text(product.get("name")) or _text(product.get("id")) |
| 165 | if in_store_only(product): |
| 166 | return (f"{name} is sold in the shop only: it cannot be ordered or " |
| 167 | f"reserved online. Come in to buy it.") |
| 168 | cap = online_cap(product) |
| 169 | if cap is not None and _qty(wanted) > cap: |
| 170 | return (f"{name} is limited to {format(cap.normalize(), 'f')} per " |
| 171 | f"online order.") |
| 172 | return "" |
| 173 | |
| 174 | |
| 175 | DEFAULT_LOW_STOCK = 3 |
| 176 | |
| 177 | |
| 178 | def promise(available: Any, *, low: int = DEFAULT_LOW_STOCK) -> dict: |
| 179 | """What a storefront may say about a shelf: {"state", "left"}. |
| 180 | |
| 181 | `state` is "sold_out" (nothing can be promised), "low" (1..low left, |
| 182 | and `left` says how many) or "in_stock" (`left` is None). Said from |
| 183 | AVAILABLE, never on hand: a page that says "3 in stock" while three |
| 184 | unpaid orders hold them sends a shopper into a refusal at checkout. |
| 185 | |
| 186 | And never more than that. The number is shown only when it is small |
| 187 | (shop.low_stock_threshold, default 3; 0 = never a number), because it |
| 188 | is the one thing other customers' orders leak into this page: an exact |
| 189 | count on every product page would let anybody watch it fall and read |
| 190 | off what the shop is selling, and to whom by timing. Nothing about |
| 191 | WHICH orders hold what is ever returned. |
| 192 | """ |
| 193 | left = _qty(available) |
| 194 | if left <= 0: |
| 195 | return {"state": "sold_out", "left": 0} |
| 196 | if low > 0 and left <= low: |
| 197 | whole = int(left) if left == left.to_integral_value() else left |
| 198 | return {"state": "low", "left": whole} |
| 199 | return {"state": "in_stock", "left": None} |
| 200 | |
| 201 | |
| 202 | def low_stock_threshold(base_dir: Path | str) -> int: |
| 203 | """shop.low_stock_threshold as a whole number; blank or unreadable is |
| 204 | the default, negative is 0.""" |
| 205 | rows = _rows("app_settings", base_dir, required=False) or [] |
| 206 | for row in rows: |
| 207 | if _text(row.get("key")) == "shop.low_stock_threshold" and _text(row.get("value")): |
| 208 | try: |
| 209 | return max(0, int(_text(row.get("value")))) |
| 210 | except ValueError: |
| 211 | break |
| 212 | return DEFAULT_LOW_STOCK |
| 213 | |
| 214 | |
| 215 | def moved_by_line(moves: Iterable[dict], shipment_lines: Iterable[dict]) -> dict[str, Decimal]: |
| 216 | """{order_line_id: quantity whose move off the shelf has been written}: |
| 217 | shipment lines whose sale move carries their marker, plus moves that |
| 218 | name the order line directly (a counter hand-over, a remake's waste).""" |
| 219 | moved_lines = set() |
| 220 | out: dict[str, Decimal] = {} |
| 221 | for move in moves: |
| 222 | reference = _text(move.get("reference")) |
| 223 | for match in _MOVE_MARKER.finditer(reference): |
| 224 | moved_lines.add(match.group(1)) |
| 225 | for match in _COUNTER_MARKER.finditer(reference): |
| 226 | key = match.group(1) |
| 227 | out[key] = out.get(key, Decimal("0")) + _qty(move.get("quantity")) |
| 228 | for line in shipment_lines: |
| 229 | if _text(line.get("id")) in moved_lines and _text(line.get("order_line_id")): |
| 230 | key = _text(line.get("order_line_id")) |
| 231 | out[key] = out.get(key, Decimal("0")) + _qty(line.get("quantity")) |
| 232 | return out |
| 233 | |
| 234 | |
| 235 | def live(order: dict, *, paid_invoice_ids: set[str] | None, now: datetime, |
| 236 | minutes: int, grace: int, slot_ends: dict[str, Any] | None) -> bool: |
| 237 | """Does this order hold its goods right now?""" |
| 238 | if not reserves(order): |
| 239 | return False |
| 240 | if _text(order.get("status") or "draft").lower() not in RESERVING_STATUSES: |
| 241 | return False |
| 242 | return not object_pickup.hold_lapsed( |
| 243 | order, paid_invoice_ids=paid_invoice_ids, now=now, minutes=minutes, |
| 244 | grace=grace, slot_ends=slot_ends) |
| 245 | |
| 246 | |
| 247 | def held_by_product(orders: Iterable[dict], order_lines: Iterable[dict], *, |
| 248 | moved: dict[str, Decimal], paid_invoice_ids: set[str] | None, |
| 249 | now: datetime, minutes: int, grace: int, |
| 250 | slot_ends: dict[str, Any] | None = None, |
| 251 | exclude_line_ids: Iterable[str] = ()) -> dict[str, Decimal]: |
| 252 | """{product_id: quantity live orders are holding}. Never negative per |
| 253 | line: a line that moved more than it ordered holds nothing, it does not |
| 254 | give stock back.""" |
| 255 | holding = {_text(order.get("id")) for order in orders |
| 256 | if live(order, paid_invoice_ids=paid_invoice_ids, now=now, |
| 257 | minutes=minutes, grace=grace, slot_ends=slot_ends)} |
| 258 | skip = {_text(line_id) for line_id in exclude_line_ids} |
| 259 | held: dict[str, Decimal] = {} |
| 260 | for line in order_lines: |
| 261 | line_id = _text(line.get("id")) |
| 262 | product_id = _text(line.get("product_id")) |
| 263 | if (not product_id or line_id in skip |
| 264 | or _text(line.get("order_id")) not in holding): |
| 265 | continue |
| 266 | rest = _qty(line.get("quantity")) - moved.get(line_id, Decimal("0")) |
| 267 | if rest > 0: |
| 268 | held[product_id] = held.get(product_id, Decimal("0")) + rest |
| 269 | return held |
| 270 | |
| 271 | |
| 272 | # --- the one fold over stored rows --------------------------------------------- |
| 273 | |
| 274 | |
| 275 | class HoldsUnreadable(Exception): |
| 276 | """Orders or their lines could not be read: what is held is unknown, |
| 277 | which is not "nothing is held".""" |
| 278 | |
| 279 | |
| 280 | def _rows(collection: str, base_dir: Path | str, *, required: bool): |
| 281 | import object_collections |
| 282 | import object_records |
| 283 | try: |
| 284 | return object_records.read_collection_records(collection, base_dir=base_dir) |
| 285 | except (object_collections.CollectionNotFoundError, LookupError): |
| 286 | return [] # not installed: a fact, not a failure |
| 287 | except Exception as exc: |
| 288 | if required: |
| 289 | raise HoldsUnreadable(f"{collection}: {str(exc)[:120]}") from exc |
| 290 | return None |
| 291 | |
| 292 | |
| 293 | def settings(base_dir: Path | str) -> tuple[int, int]: |
| 294 | """(pickup.hold_minutes, pickup.grace_minutes) as minutes.""" |
| 295 | rows = _rows("app_settings", base_dir, required=False) or [] |
| 296 | values = {_text(row.get("key")): _text(row.get("value")) for row in rows} |
| 297 | return (object_pickup.hold_minutes(values.get("pickup.hold_minutes", "")), |
| 298 | object_pickup.grace_minutes(values.get("pickup.grace_minutes", ""))) |
| 299 | |
| 300 | |
| 301 | def read_holds(base_dir: Path | str, *, now: datetime | None = None, |
| 302 | exclude_line_ids: Iterable[str] = ()) -> dict[str, Decimal]: |
| 303 | """{product_id: held} from the stored rows. |
| 304 | |
| 305 | Raises HoldsUnreadable when orders, lines or the stock log cannot be |
| 306 | read (a gate must refuse, a page must say nothing). Payments or |
| 307 | invoices that cannot be read lapse nothing (object_pickup's fail-closed |
| 308 | rule: a shelf that looks emptier than it is costs a sale, one that |
| 309 | looks fuller costs the customer who drove there). |
| 310 | """ |
| 311 | now = now or datetime.now().astimezone() |
| 312 | orders = _rows("orders", base_dir, required=True) |
| 313 | lines = _rows("order_lines", base_dir, required=True) |
| 314 | if not orders or not lines: |
| 315 | return {} |
| 316 | moves = _rows("stock_moves", base_dir, required=True) |
| 317 | shipment_lines = _rows("shipment_lines", base_dir, required=True) |
| 318 | invoices = _rows("invoices", base_dir, required=False) |
| 319 | payments = _rows("payments", base_dir, required=False) |
| 320 | paid = (None if invoices is None or payments is None |
| 321 | else object_pickup.paid_invoice_ids(invoices, payments)) |
| 322 | slots = _rows("pickup_slots", base_dir, required=False) or [] |
| 323 | minutes, grace = settings(base_dir) |
| 324 | return held_by_product( |
| 325 | orders, lines, moved=moved_by_line(moves, shipment_lines), |
| 326 | paid_invoice_ids=paid, now=now, minutes=minutes, grace=grace, |
| 327 | slot_ends=object_pickup.ends_by_slot(slots), |
| 328 | exclude_line_ids=exclude_line_ids) |