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
pickup_slots.py · 9.1 KB · 238 lines
1"""action_pickup_slots -- the windows a customer may actually book.
2
3GET|POST {now?, location_id?, limit?} -> {ok, slots: [...], lead_minutes}
4
5This is the one question a storefront asks before it draws a time picker,
6and the answer is deliberately narrow: OPEN, in the FUTURE, past the LEAD
7TIME, and NOT AT CAPACITY. A slot that fails any of those is not returned
8at all -- not returned-with-a-flag, not greyed out with a reason.
9
10**"Can I have a pizza at 3am" is answered by not offering 3am.** A picker
11that shows every window and refuses the impossible ones after the
12customer has chosen a time, typed their name and entered a card is a
13picker that wastes somebody's evening to enforce a rule it knew before
14they started. The lead time (`pickup.lead_minutes`) is the shop saying
15how long it needs; the correct place to spend that knowledge is the list,
16not the refusal.
17
18Both verbs, because both callers are real: a server-rendered storefront
19GETs this while building a page, and a JSON client POSTs it. Neither
20writes anything -- this object only reads -- so there is no CSRF-shaped
21reason to insist on one of them.
22
23`now` is an argument rather than a hidden call to the clock so a test can
24stand at a chosen minute and watch the lead-time edge move, the same
25posture app-billing's runner takes with `today`. In production nothing
26passes it -- and since this object is public, a `now` that arrives over
27HTTP (the request carries `_identity`, which the server sets) is ignored:
28only an in-process caller may move the clock.
29
30**A booking that was never paid stops holding its place.** A window is
31judged by object_pickup's live count -- orders_taken less the bookings
32whose order is cancelled, or is an unpaid draft older than
33`pickup.hold_minutes` -- the same count action_checkout's gate uses, so
34the picker never offers a time the gate would call full or hides one it
35would take. See object_pickup for why that is a derived count and not a
36daemon sweeper.
37
38**The list is a snapshot, not a hold.** A slot returned here with one
39place left may be taken by somebody else before this customer commits;
40nothing is reserved by asking. That race is checked again at checkout,
41where it is refused with the next free slot named -- see
42action_checkout's own docstring for why this system accepts the race
43rather than building a reservation ledger for it.
44"""
45
46import os
47from datetime import datetime, timedelta
48
49import object_collections
50import object_pickup
51import object_records
52
53ACTOR = "action_pickup_slots"
54
55DEFAULT_LEAD_MINUTES = 30
56
57# A page of times, not a calendar. Somebody choosing when to collect a
58# coffee is choosing among the next few windows; a picker holding six
59# hundred of them is a scroll bar pretending to be a choice. A caller who
60# genuinely wants more says so with `limit`.
61DEFAULT_LIMIT = 48
62MAX_LIMIT = 500
63
64
65def _base_dir():
66 return os.environ.get("DBBASIC_DATA_DIR", "data")
67
68
69def _text(value):
70 return str(value if value is not None else "").strip()
71
72
73def _truthy(value):
74 return _text(value).lower() in ("true", "1", "yes", "on")
75
76
77def _int(value, default=0):
78 try:
79 return int(_text(value) or default)
80 except (TypeError, ValueError):
81 return default
82
83
84def _setting(base, key, default):
85 try:
86 # access: box configuration
87 for row in object_records.read_collection_records("app_settings",
88 base_dir=base):
89 if row.get("key") == key and _text(row.get("value")):
90 return _text(row["value"])
91 except Exception:
92 pass
93 return default
94
95
96def _moment(value):
97 """An ISO datetime as NAIVE local wall-clock, or None when it is blank
98 or unparseable.
99
100 None is treated everywhere below as "not bookable": a slot whose start
101 time cannot be read is a slot nobody can be promised, and offering it
102 would put an unparseable string on somebody's order.
103
104 The offset is dropped rather than honoured because every time in this
105 repo is the shop's own clock, and because comparing one aware value to
106 a naive one raises -- which would take a whole picker down over a
107 single imported row.
108 """
109 text = _text(value)
110 if not text:
111 return None
112 try:
113 moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
114 except ValueError:
115 return None
116 if moment.tzinfo is not None:
117 moment = moment.astimezone().replace(tzinfo=None)
118 return moment
119
120
121def lead_minutes(base):
122 """How long the shop needs before it can have anything ready.
123
124 Public because it is the number two objects have to agree on -- this
125 one to decide what to offer, action_checkout to decide what to accept
126 -- and a lead time those two disagreed about would show a customer a
127 slot and then refuse it.
128 """
129 return max(0, _int(_setting(base, "pickup.lead_minutes", ""),
130 DEFAULT_LEAD_MINUTES))
131
132
133def is_bookable(slot, *, now, earliest):
134 """The whole rule, in one place: open, in the future, past the lead
135 time, and with room.
136
137 `earliest` (now + the lead time) is passed in rather than computed
138 here so every slot in one pass is judged against exactly the same
139 edge -- a boundary recomputed per row would let a slot pass or fail
140 depending on how long the loop took to reach it.
141 """
142 starts = _moment(slot.get("starts_at"))
143 if starts is None:
144 return False
145 if not _truthy(slot.get("is_open") or "true"):
146 return False
147 if starts <= now:
148 return False
149 if starts < earliest:
150 return False
151 return _int(slot.get("orders_taken"), 0) < _int(slot.get("capacity"), 0)
152
153
154def _lapsed_holds(base, now, slots=()):
155 """{slot_id: bookings whose hold has lapsed} -- object_pickup decides;
156 this only reads. Fails closed: orders, invoices or payments that cannot
157 be read lapse nothing, so the window looks as full as its counter says.
158 A box with no payments collection has simply taken no payments.
159 """
160 def rows(collection, *, absent):
161 try:
162 # access: pickup capacity: counts which bookings still hold a window; nothing is shown
163 return object_records.read_collection_records(collection, base_dir=base)
164 except object_collections.CollectionNotFoundError:
165 return absent
166 except Exception:
167 return None
168
169 orders = rows("orders", absent=[])
170 invoices = rows("invoices", absent=[])
171 payments = rows("payments", absent=[])
172 if orders is None or invoices is None:
173 return {}
174 minutes = object_pickup.hold_minutes(_setting(base, "pickup.hold_minutes", ""))
175 grace = object_pickup.grace_minutes(_setting(base, "pickup.grace_minutes", ""))
176 return object_pickup.lapsed_holds(
177 orders, now=now, minutes=minutes, grace=grace,
178 slot_ends=object_pickup.ends_by_slot(slots),
179 paid_invoice_ids=object_pickup.paid_invoice_ids(invoices, payments))
180
181
182def _present(slot):
183 capacity = _int(slot.get("capacity"), 0)
184 taken = _int(slot.get("orders_taken"), 0)
185 return {"id": slot["id"],
186 "starts_at": _text(slot.get("starts_at")),
187 "ends_at": _text(slot.get("ends_at")),
188 "capacity": capacity,
189 "orders_taken": taken,
190 "places_left": max(0, capacity - taken),
191 "location_id": _text(slot.get("location_id"))}
192
193
194def _bookable(request):
195 base = _base_dir()
196 # The server's clock: `now` is honoured only from an in-process caller
197 # (no `_identity`, which the server sets on every HTTP execution).
198 now = (_moment(request.get("now")) if "_identity" not in request else None) \
199 or datetime.now()
200 lead = lead_minutes(base)
201 earliest = now + timedelta(minutes=lead)
202 location = _text(request.get("location_id"))
203 limit = _int(request.get("limit"), DEFAULT_LIMIT)
204 limit = max(1, min(limit or DEFAULT_LIMIT, MAX_LIMIT))
205
206 try:
207 # access: storefront catalog: bookable slots are shown to shoppers, by design
208 rows = object_records.read_collection_records("pickup_slots",
209 base_dir=base)
210 except Exception:
211 # A box without this app installed has no slots, which is a real
212 # answer to "what can I book?" and not an error page on somebody's
213 # storefront.
214 return {"ok": True, "slots": [], "lead_minutes": lead,
215 "now": now.isoformat(),
216 "note": "pickup not installed (pickup_slots absent)"}
217
218 # The live count, the same one action_checkout's gate judges by:
219 # a booking whose hold has lapsed (object_pickup) holds no place.
220 rows = object_pickup.with_live_count(rows, _lapsed_holds(base, now, rows))
221 slots = [row for row in rows
222 if is_bookable(row, now=now, earliest=earliest)
223 and (not location or _text(row.get("location_id")) == location)]
224 slots.sort(key=lambda row: _text(row.get("starts_at")))
225 return {"ok": True,
226 "lead_minutes": lead,
227 "now": now.isoformat(),
228 "earliest_bookable": earliest.isoformat(),
229 "count": len(slots),
230 "slots": [_present(row) for row in slots[:limit]]}
231
232
233def GET(request):
234 return _bookable(request)
235
236
237def POST(request):
238 return _bookable(request)