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_pickup.py · 10.5 KB · 243 lines
| 1 | """Which bookings still hold a pickup slot: pure, no I/O, no clock. |
| 2 | |
| 3 | A pickup slot's `orders_taken` is a COUNTER: action_checkout adds one as |
| 4 | each order books the window, and nothing ever took one off. So an order |
| 5 | raised at checkout and never paid -- the shopper closed the tab at the pay |
| 6 | link -- held its place for good, and a café's 6pm filled up with people |
| 7 | who were never coming. A simulated café run found it: one unpaid checkout |
| 8 | and the window refused every later shopper. |
| 9 | |
| 10 | **A hold lapses; the count is derived, not edited.** What a window has |
| 11 | room for is `orders_taken` minus the bookings whose hold has lapsed, and a |
| 12 | booking's hold lapses when its order is |
| 13 | |
| 14 | - still a `draft` -- the shop has not confirmed it, which is what the |
| 15 | payment does (system_shop_fulfillment) -- AND nothing has been paid |
| 16 | against its invoice (a received payment, or an invoice already paid or |
| 17 | part-paid), AND it was raised more than `pickup.hold_minutes` ago; or |
| 18 | - `cancelled`, which never gave its place back either. |
| 19 | |
| 20 | The stored counter is left alone. It is still the record of every booking |
| 21 | the window took -- including the ones somebody types in by hand for a |
| 22 | phone order, which no order row explains -- and the races test in |
| 23 | tests/test_commerce_action_races.py still holds on it. What changed is |
| 24 | what the gate and the picker SUBTRACT from it, in one function both of |
| 25 | them call, so they cannot disagree about whether 6pm is full. |
| 26 | |
| 27 | Why derived and not a sweeper. docs/logic-decisions.md #2 puts |
| 28 | time-driven STATE in the daemon, and a sweeper that decremented the |
| 29 | counter and stamped the order would be that. It was rejected here because |
| 30 | nothing about the order changes meaning when its hold lapses -- it is |
| 31 | still a draft order with a live pay link, and a shopper who pays at minute |
| 32 | 45 has a perfectly good order -- so there is no transition to store, only |
| 33 | a count to derive (#1: totals, balances, COUNTS). And a sweeper would make |
| 34 | the release depend on the daemon running with croniter installed, which a |
| 35 | stock install does not have: a café whose holds never released because a |
| 36 | scheduler was off is the bug this fixes. The cost, stated: a shopper who |
| 37 | pays AFTER their hold lapsed and after somebody else took the place puts |
| 38 | the window one over capacity. That is the same visible oversell the |
| 39 | documented checkout race already produces, on the row it happened to. |
| 40 | |
| 41 | **The same rule holds the goods.** Since 2026-11-30 an online order also |
| 42 | holds its lines against the shelf (object_reservations), and whether it |
| 43 | still does is `hold_lapsed` here -- one function for the window and the |
| 44 | shelf, so a shopper is never told their 6pm is gone while their basket is |
| 45 | still kept, or the reverse. It adds one case: an order that PAYS AT PICKUP |
| 46 | (orders.pay_at_pickup) is not supposed to have paid yet, so its age means |
| 47 | nothing; it holds until its window ends plus `pickup.grace_minutes`. |
| 48 | |
| 49 | Fails closed: an order whose age cannot be read, or a box whose payments |
| 50 | cannot be read, keeps every hold (the caller passes paid=None) -- a window |
| 51 | that looks fuller than it is costs a sale, one that looks emptier than it |
| 52 | is costs a kitchen. |
| 53 | """ |
| 54 | |
| 55 | from __future__ import annotations |
| 56 | |
| 57 | import re |
| 58 | from datetime import datetime, timedelta, timezone |
| 59 | from typing import Any, Iterable |
| 60 | |
| 61 | DEFAULT_HOLD_MINUTES = 30 |
| 62 | |
| 63 | # pickup.grace_minutes: a pay-at-pickup order keeps its hold this long |
| 64 | # after its window closes (see hold_lapsed). |
| 65 | DEFAULT_GRACE_MINUTES = 30 |
| 66 | |
| 67 | # The provenance marker action_checkout writes into an order's notes for |
| 68 | # the window it booked: orders carry no pickup_slot_id column, and promised_at |
| 69 | # alone cannot tell two windows that start together at two counters apart. |
| 70 | _MARKER = re.compile(r"\[pickup_slots/([^\]\s]+)\]") |
| 71 | |
| 72 | # Order statuses that hold no place whatever their age. |
| 73 | RELEASED_STATUSES = ("cancelled",) |
| 74 | |
| 75 | |
| 76 | def _text(value: Any) -> str: |
| 77 | return str(value if value is not None else "").strip() |
| 78 | |
| 79 | |
| 80 | def hold_minutes(value: Any) -> int: |
| 81 | """`pickup.hold_minutes` as a number of minutes. |
| 82 | |
| 83 | Blank or unreadable is the default. 0 (or less) means holds never |
| 84 | lapse, which is how the shop behaved before -- a real choice for a |
| 85 | shop that takes payment at the counter, not a broken setting. |
| 86 | """ |
| 87 | try: |
| 88 | return int(_text(value)) |
| 89 | except (TypeError, ValueError): |
| 90 | return DEFAULT_HOLD_MINUTES |
| 91 | |
| 92 | |
| 93 | def slot_of(order: dict) -> str: |
| 94 | """The slot an order booked, from its provenance marker, or "".""" |
| 95 | match = _MARKER.search(_text(order.get("notes"))) |
| 96 | return match.group(1) if match else "" |
| 97 | |
| 98 | |
| 99 | def _utc(value: Any) -> datetime | None: |
| 100 | """A stored timestamp as an aware UTC datetime, or None. |
| 101 | |
| 102 | Parsed, never compared as text: created_at is written as ...Z by the |
| 103 | record store, and "+00:00" and "Z" spellings of one instant do not |
| 104 | sort together (AGENTS.md). A naive value is the shop's wall clock. |
| 105 | """ |
| 106 | text = _text(value) |
| 107 | if not text: |
| 108 | return None |
| 109 | try: |
| 110 | moment = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 111 | except ValueError: |
| 112 | return None |
| 113 | if moment.tzinfo is None: |
| 114 | moment = moment.astimezone() |
| 115 | return moment.astimezone(timezone.utc) |
| 116 | |
| 117 | |
| 118 | def grace_minutes(value: Any) -> int: |
| 119 | """`pickup.grace_minutes`: how long after its window CLOSES a |
| 120 | pay-at-pickup order still holds its goods and its place. Blank or |
| 121 | unreadable is the default; a negative number reads as 0 (the hold ends |
| 122 | with the window).""" |
| 123 | try: |
| 124 | return max(0, int(_text(value))) |
| 125 | except (TypeError, ValueError): |
| 126 | return DEFAULT_GRACE_MINUTES |
| 127 | |
| 128 | |
| 129 | def pays_at_pickup(order: dict) -> bool: |
| 130 | return _text(order.get("pay_at_pickup")).lower() in ("true", "1", "yes", "on") |
| 131 | |
| 132 | |
| 133 | def hold_lapsed(order: dict, *, paid_invoice_ids: set[str] | None, |
| 134 | now: datetime, minutes: int, |
| 135 | grace: int = DEFAULT_GRACE_MINUTES, |
| 136 | slot_ends: dict[str, Any] | None = None) -> bool: |
| 137 | """Has this order stopped holding what it booked -- its pickup place, |
| 138 | and (object_reservations) its goods? The ONE rule both ask, so a window |
| 139 | and a shelf cannot disagree about whether an order is still coming. |
| 140 | |
| 141 | - `cancelled`: lapsed, always. |
| 142 | - anything but `draft`: holding. Confirmation is the payment |
| 143 | (system_shop_fulfillment), so a confirmed order is paid for. |
| 144 | - a draft something has been paid against: holding. |
| 145 | - an unpaid draft that pays ONLINE: lapsed once it is older than |
| 146 | `minutes` (pickup.hold_minutes; 0 = never). The shopper is at a pay |
| 147 | link, and a pay link nobody opens for half an hour is a closed tab. |
| 148 | - an unpaid draft that PAYS AT PICKUP (orders.pay_at_pickup): holding |
| 149 | until its window ends plus `grace` (pickup.grace_minutes). Its money |
| 150 | is not supposed to arrive before the shopper does -- "if I order |
| 151 | online and drive to the store I expect it to still be there when I |
| 152 | arrive" -- so the clock that matters is the window it promised, not |
| 153 | its age. The window's end is the slot's `ends_at` (slot_ends, by |
| 154 | slot id), else the order's own promised_at. |
| 155 | |
| 156 | Fails closed: payments that cannot be read (paid_invoice_ids None), an |
| 157 | age or a window that cannot be read, all keep the hold. |
| 158 | """ |
| 159 | status = _text(order.get("status")).lower() |
| 160 | if status in RELEASED_STATUSES: |
| 161 | return True |
| 162 | if status != "draft" or paid_invoice_ids is None: |
| 163 | return False |
| 164 | if _text(order.get("invoice_id")) and _text(order.get("invoice_id")) in paid_invoice_ids: |
| 165 | return False |
| 166 | now_utc = _utc(now.isoformat()) or datetime.now(timezone.utc) |
| 167 | if pays_at_pickup(order): |
| 168 | ends = _utc((slot_ends or {}).get(slot_of(order))) or _utc(order.get("promised_at")) |
| 169 | if ends is None: |
| 170 | return False |
| 171 | return now_utc > ends + timedelta(minutes=max(0, grace)) |
| 172 | if minutes <= 0: |
| 173 | return False |
| 174 | raised = _utc(order.get("created_at")) |
| 175 | if raised is None: |
| 176 | return False |
| 177 | return now_utc - raised >= timedelta(minutes=minutes) |
| 178 | |
| 179 | |
| 180 | def lapsed_holds(orders: Iterable[dict], *, paid_invoice_ids: set[str] | None, |
| 181 | now: datetime, minutes: int, |
| 182 | grace: int = DEFAULT_GRACE_MINUTES, |
| 183 | slot_ends: dict[str, Any] | None = None) -> dict[str, int]: |
| 184 | """{slot_id: how many of its bookings no longer hold a place}. |
| 185 | |
| 186 | `paid_invoice_ids` is every invoice something has been paid against; |
| 187 | None means the payments could not be read, and then no unpaid draft |
| 188 | lapses (fail closed). `now` is aware or naive local; it is compared as |
| 189 | UTC. Each order is judged by hold_lapsed. |
| 190 | """ |
| 191 | lapsed: dict[str, int] = {} |
| 192 | for order in orders: |
| 193 | slot_id = slot_of(order) |
| 194 | if not slot_id: |
| 195 | continue |
| 196 | if hold_lapsed(order, paid_invoice_ids=paid_invoice_ids, now=now, |
| 197 | minutes=minutes, grace=grace, slot_ends=slot_ends): |
| 198 | lapsed[slot_id] = lapsed.get(slot_id, 0) + 1 |
| 199 | return lapsed |
| 200 | |
| 201 | |
| 202 | def ends_by_slot(slots: Iterable[dict] | None) -> dict[str, str]: |
| 203 | """{slot_id: ends_at} for hold_lapsed's pay-at-pickup rule.""" |
| 204 | return {_text(slot.get("id")): _text(slot.get("ends_at")) |
| 205 | for slot in slots or () if _text(slot.get("id"))} |
| 206 | |
| 207 | |
| 208 | def paid_invoice_ids(invoices: Iterable[dict] | None, |
| 209 | payments: Iterable[dict] | None) -> set[str] | None: |
| 210 | """The invoices something has been paid against, or None if unknown. |
| 211 | |
| 212 | The payment rows are the evidence and are summed first (AGENTS.md: a |
| 213 | gate sums the evidence rather than reading the cache); an invoice whose |
| 214 | own status already says paid or part-paid counts too, so a payment |
| 215 | recorded somewhere this does not read still keeps its order's place. |
| 216 | """ |
| 217 | if payments is None: |
| 218 | return None |
| 219 | paid = {_text(row.get("invoice_id")) for row in payments |
| 220 | if _text(row.get("status") or "received") == "received" |
| 221 | and _text(row.get("invoice_id"))} |
| 222 | for invoice in invoices or (): |
| 223 | if _text(invoice.get("status")) in ("paid", "partial"): |
| 224 | paid.add(_text(invoice.get("id"))) |
| 225 | return paid |
| 226 | |
| 227 | |
| 228 | def orders_holding(slot: dict, lapsed: dict[str, int]) -> int: |
| 229 | """How many orders this window is really holding: the stored count less |
| 230 | its lapsed bookings, never below zero.""" |
| 231 | try: |
| 232 | taken = int(_text(slot.get("orders_taken")) or 0) |
| 233 | except ValueError: |
| 234 | taken = 0 |
| 235 | return max(0, taken - lapsed.get(_text(slot.get("id")), 0)) |
| 236 | |
| 237 | |
| 238 | def with_live_count(slots: Iterable[dict], lapsed: dict[str, int]) -> list[dict]: |
| 239 | """Copies of these slots whose orders_taken is the live count, for a |
| 240 | gate or a picker to judge by. Copies, never the rows themselves: the |
| 241 | stored counter is not written here.""" |
| 242 | return [{**slot, "orders_taken": str(orders_holding(slot, lapsed))} |
| 243 | for slot in slots] |