Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
pickup_slots.py · 6.7 KB · 190 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.
27
28**The list is a snapshot, not a hold.** A slot returned here with one
29place left may be taken by somebody else before this customer commits;
30nothing is reserved by asking. That race is checked again at checkout,
31where it is refused with the next free slot named -- see
32action_checkout's own docstring for why this system accepts the race
33rather than building a reservation ledger for it.
34"""
35
36import os
37from datetime import datetime, timedelta
38
39import object_records
40
41ACTOR = "action_pickup_slots"
42
43DEFAULT_LEAD_MINUTES = 30
44
45# A page of times, not a calendar. Somebody choosing when to collect a
46# coffee is choosing among the next few windows; a picker holding six
47# hundred of them is a scroll bar pretending to be a choice. A caller who
48# genuinely wants more says so with `limit`.
49DEFAULT_LIMIT = 48
50MAX_LIMIT = 500
51
52
53def _base_dir():
54 return os.environ.get("DBBASIC_DATA_DIR", "data")
55
56
57def _text(value):
58 return str(value if value is not None else "").strip()
59
60
61def _truthy(value):
62 return _text(value).lower() in ("true", "1", "yes", "on")
63
64
65def _int(value, default=0):
66 try:
67 return int(_text(value) or default)
68 except (TypeError, ValueError):
69 return default
70
71
72def _setting(base, key, default):
73 try:
74 for row in object_records.read_collection_records("app_settings",
75 base_dir=base):
76 if row.get("key") == key and _text(row.get("value")):
77 return _text(row["value"])
78 except Exception:
79 pass
80 return default
81
82
83def _moment(value):
84 """An ISO datetime as NAIVE local wall-clock, or None when it is blank
85 or unparseable.
86
87 None is treated everywhere below as "not bookable": a slot whose start
88 time cannot be read is a slot nobody can be promised, and offering it
89 would put an unparseable string on somebody's order.
90
91 The offset is dropped rather than honoured because every time in this
92 repo is the shop's own clock, and because comparing one aware value to
93 a naive one raises -- which would take a whole picker down over a
94 single imported row.
95 """
96 text = _text(value)
97 if not text:
98 return None
99 try:
100 moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
101 except ValueError:
102 return None
103 if moment.tzinfo is not None:
104 moment = moment.astimezone().replace(tzinfo=None)
105 return moment
106
107
108def lead_minutes(base):
109 """How long the shop needs before it can have anything ready.
110
111 Public because it is the number two objects have to agree on -- this
112 one to decide what to offer, action_checkout to decide what to accept
113 -- and a lead time those two disagreed about would show a customer a
114 slot and then refuse it.
115 """
116 return max(0, _int(_setting(base, "pickup.lead_minutes", ""),
117 DEFAULT_LEAD_MINUTES))
118
119
120def is_bookable(slot, *, now, earliest):
121 """The whole rule, in one place: open, in the future, past the lead
122 time, and with room.
123
124 `earliest` (now + the lead time) is passed in rather than computed
125 here so every slot in one pass is judged against exactly the same
126 edge -- a boundary recomputed per row would let a slot pass or fail
127 depending on how long the loop took to reach it.
128 """
129 starts = _moment(slot.get("starts_at"))
130 if starts is None:
131 return False
132 if not _truthy(slot.get("is_open") or "true"):
133 return False
134 if starts <= now:
135 return False
136 if starts < earliest:
137 return False
138 return _int(slot.get("orders_taken"), 0) < _int(slot.get("capacity"), 0)
139
140
141def _present(slot):
142 capacity = _int(slot.get("capacity"), 0)
143 taken = _int(slot.get("orders_taken"), 0)
144 return {"id": slot["id"],
145 "starts_at": _text(slot.get("starts_at")),
146 "ends_at": _text(slot.get("ends_at")),
147 "capacity": capacity,
148 "orders_taken": taken,
149 "places_left": max(0, capacity - taken),
150 "location_id": _text(slot.get("location_id"))}
151
152
153def _bookable(request):
154 base = _base_dir()
155 now = _moment(request.get("now")) or datetime.now()
156 lead = lead_minutes(base)
157 earliest = now + timedelta(minutes=lead)
158 location = _text(request.get("location_id"))
159 limit = _int(request.get("limit"), DEFAULT_LIMIT)
160 limit = max(1, min(limit or DEFAULT_LIMIT, MAX_LIMIT))
161
162 try:
163 rows = object_records.read_collection_records("pickup_slots",
164 base_dir=base)
165 except Exception:
166 # A box without this app installed has no slots, which is a real
167 # answer to "what can I book?" and not an error page on somebody's
168 # storefront.
169 return {"ok": True, "slots": [], "lead_minutes": lead,
170 "now": now.isoformat(),
171 "note": "pickup not installed (pickup_slots absent)"}
172
173 slots = [row for row in rows
174 if is_bookable(row, now=now, earliest=earliest)
175 and (not location or _text(row.get("location_id")) == location)]
176 slots.sort(key=lambda row: _text(row.get("starts_at")))
177 return {"ok": True,
178 "lead_minutes": lead,
179 "now": now.isoformat(),
180 "earliest_bookable": earliest.isoformat(),
181 "count": len(slots),
182 "slots": [_present(row) for row in slots[:limit]]}
183
184
185def GET(request):
186 return _bookable(request)
187
188
189def POST(request):
190 return _bookable(request)