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
kitchen.py · 15.2 KB · 372 lines
1"""site_kitchen -- what has to be made, and by when. GET /kitchen.
2
3A READ, never a table -- the same doctrine as site_pick_list, and this
4page is its sibling. There is no kitchen_queue collection and there must
5never be one: the queue is orders-being-prepared folded live, exactly the
6way the pick list is ordered-minus-shipped and stock levels are folded
7from stock_moves. Storing it would mean two answers to "what is cooking"
8that can disagree, and the stored one is always the one somebody trusts
9at the wrong moment -- here, at the moment a customer is standing at the
10counter.
11
12**Sorted by PROMISED TIME, not grouped by product.** That is the whole
13difference from the pick list, and it is the difference between a
14warehouse and a kitchen. A picker walks the room once, so a pick list
15groups by product and saves the walk. A cook is racing a clock somebody
16else already promised, so the only order that matters is which promise
17comes due next. Grouping a kitchen by product would batch six burgers
18across four orders into one row and lose the one fact the cook is being
19measured on.
20
21**Late is the loudest thing on the page.** An order past its promised
22time is not "due in -4 minutes", it is LATE, in the biggest type here,
23because the customer for that one is already standing there. Sorting
24alone would not do it: the late order sorts first anyway, and a queue
25where the top row looks like every other row is a queue that gets read
26top-down at the same speed whether or not somebody is waiting.
27
28Big type, and print CSS, for the same reason the packing slip has both: a
29cook reads this from a metre away with their hands full, and plenty of
30kitchens will print the queue at the start of a rush rather than keep a
31screen in the splash zone.
32
33**Auto-refresh is a plain <meta refresh>, deliberately.** There is no
34realtime-subscribe precedent to follow on any page in this box --
35site_pick_list and site_stock, the two nearest siblings, both re-read on
36load and nothing else -- so a live subscription here would be this
37package inventing a pattern for itself, on the one screen where a
38half-working one is most expensive. Thirty seconds is well inside the
39resolution of the fact being shown (a promised time is a minute-grained
40promise), it costs one small fold per tick, and it keeps working on a
41tablet whose JavaScript has been asleep in a pocket. The day a page in
42this repo does subscribe, this is one line to change.
43
44Requires a signed-in identity, the same gate site_pick_list and
45site_stock use, and the same SHAPE: a sign-in prompt, not a 403. The
46queue is the orders the permission engine (object_access) lets the caller
47read, the same rows the orders API would list. It used to include every
48order that carried no owner at all, on the reasoning that guest checkout
49leaves owner_id blank; checkout stamps the shop's owner (shop.owner_id,
50default "shop") on a guest basket, and an order nobody owns is shown to
51nobody by the orders API, so the page showed customers' names and notes to
52every signed-in account that asked.
53
54Every pickup field is read with .get. `fulfillment_method` and
55`promised_at` belong to the pickup slice, and this page must be
56installable beside an app-orders that has not gained them yet: on such a
57box no order claims to be a pickup, the queue is honestly empty, and the
58page says which field is missing rather than looking broken.
59"""
60
61import html
62import os
63import urllib.parse
64from datetime import datetime
65
66import object_access
67import object_records
68
69ACTOR = "site_kitchen"
70
71# What a cook is asked to work on: an order that has been committed and is
72# not yet ready to hand over. `draft` is not a commitment, `ready` is
73# already made and waiting on the shelf, `collected` has left, and
74# `cancelled` must never be cooked.
75PREPARING_STATUSES = {"confirmed", "preparing"}
76
77# The one fulfilment method this page is about. `shipping` and `delivery`
78# have a warehouse and a van between them and the customer; `counter` is
79# made and handed over in one motion with nobody waiting on a promise.
80PICKUP_METHOD = "pickup"
81
82# How often the page re-reads itself. See the module docstring.
83REFRESH_SECONDS = 30
84
85
86def _base_dir():
87 return os.environ.get("DBBASIC_DATA_DIR", "data")
88
89
90def _text(value):
91 return str(value if value is not None else "").strip()
92
93
94def _esc(value):
95 return html.escape(_text(value))
96
97
98def _now():
99 return datetime.now()
100
101
102def _parse_when(value):
103 """A promised time as NAIVE local wall-clock, or None when it will not
104 parse.
105
106 Naive local, not UTC, because that is the convention the package that
107 OWNS this field already set: app-pickup's slot generator writes
108 pickup_slots.starts_at as the shop's own clock, checkout stamps it
109 onto promised_at unchanged, and system_pickup_attention reads it back
110 the same way. A kitchen that decided the same string meant UTC would
111 show every order in a shop an hour off the meridian as late by the
112 offset, on the one screen whose entire job is the clock.
113
114 An offset-carrying stamp (hand-typed, or imported) is converted to
115 local and flattened, rather than left aware: comparing an aware
116 datetime to a naive one raises, and one badly-typed order must not
117 take the whole queue down at the start of a rush.
118
119 None is not zero and not "now": an order whose promised time cannot be
120 read is not late and is not on time, it is unscheduled, and it sorts
121 to the BOTTOM rather than screaming at the top of the queue. A blank
122 or hand-typed value must never invent an emergency.
123 """
124 raw = _text(value)
125 if not raw:
126 return None
127 try:
128 when = datetime.fromisoformat(raw.replace("Z", "+00:00"))
129 except ValueError:
130 return None
131 if when.tzinfo is not None:
132 when = when.astimezone().replace(tzinfo=None)
133 return when
134
135
136def _whole_minutes(seconds):
137 """Minutes elapsed, never minutes started.
138
139 Floor of a positive magnitude, so a promise 90 seconds away is "1
140 min" rather than the 2 that rounding up would claim, and one 90
141 seconds overdue is "LATE by 1". Both directions are computed on the
142 magnitude and the SIGN is carried separately: floor-dividing a
143 negative number rounds away from zero, which would report an order
144 seven minutes and one second late as eight -- a page that overstates
145 lateness gets argued with, and a page that gets argued with stops
146 being believed about the ones that matter.
147 """
148 return int(abs(seconds) // 60)
149
150
151def _due_html(when, now):
152 """The clock, in the states that matter.
153
154 LATE is a different sentence rather than a negative number, because a
155 reader scanning a column of "due in" values will read "-4" as "4" at
156 speed, and the one row that must not be misread is that one.
157 """
158 if when is None:
159 return ('<span class="due unscheduled">no promised time</span>',
160 "unscheduled")
161 seconds = (when - now).total_seconds()
162 minutes = _whole_minutes(seconds)
163 if seconds < 0 and minutes:
164 return (f'<span class="due late">LATE by {minutes} min</span>',
165 "late")
166 if minutes == 0:
167 # Inside the minute either way: a promise 40 seconds overdue is
168 # not a crisis and 40 seconds early is not a wait, and both are
169 # the same instruction to the cook.
170 return ('<span class="due now">due now</span>', "now")
171 return (f'<span class="due">in {minutes} min</span>', "soon")
172
173
174def _clock(when):
175 """The promised time itself, HH:MM, beside the countdown.
176
177 Both, not one: the countdown is what a cook acts on and the wall-clock
178 time is what they say out loud to the customer who rings up asking.
179 """
180 return when.strftime("%H:%M") if when is not None else ""
181
182
183def _orders_for(base, identity):
184 """Every pickup order still being made, soonest promise first, among
185 the orders this caller may read.
186
187 A full scan of two collections, the same cost site_pick_list accepts
188 and for the same reason: a shop with a kitchen this size has tens of
189 open orders, not millions.
190 """
191 try:
192 rows = object_records.read_collection_records("orders", base_dir=base)
193 except Exception:
194 return [], {}, False
195 rows = object_access.Access(identity, base_dir=base).visible("orders", rows)
196
197 saw_method = False
198 open_orders = {}
199 for row in rows:
200 if _text(row.get("fulfillment_method")):
201 saw_method = True
202 if _text(row.get("doc_type") or "sale") != "sale":
203 continue
204 if _text(row.get("status")) not in PREPARING_STATUSES:
205 continue
206 if _text(row.get("fulfillment_method")) != PICKUP_METHOD:
207 continue
208 open_orders[row["id"]] = row
209
210 try:
211 # access: lines of the orders the caller may read (Access.visible above)
212 all_lines = object_records.read_collection_records("order_lines",
213 base_dir=base)
214 except Exception:
215 all_lines = []
216 lines = {}
217 for line in all_lines:
218 order_id = _text(line.get("order_id"))
219 if order_id in open_orders:
220 lines.setdefault(order_id, []).append(line)
221 for rows_for_order in lines.values():
222 rows_for_order.sort(key=lambda row: _text(row.get("description")))
223
224 ordered = list(open_orders.values())
225 # Soonest promise first; an order with no readable promised time sorts
226 # last rather than first -- "we do not know when this was promised" is
227 # not a claim to urgency, the same rule the pick list applies to a
228 # missing order date. Sorted on the PARSED instant, not on the string:
229 # two shops an ocean apart write the same moment with different
230 # offsets, and a lexicographic sort would cook them in the wrong order
231 # while looking entirely reasonable.
232 ordered.sort(key=_sort_key)
233 return ordered, lines, saw_method
234
235
236_FOREVER = datetime.max
237
238
239def _sort_key(order):
240 when = _parse_when(order.get("promised_at"))
241 return (when is None, when or _FOREVER,
242 _text(order.get("number")) or order["id"])
243
244
245_STYLE = """
246.kitchen { font-size: 1.15rem; }
247.ticket { border: 2px solid var(--line, #38384a); border-radius: 10px; padding: 0.9rem 1.1rem; margin: 0 0 1.1rem; }
248.ticket.late { border-color: #c33; }
249.ticket header { display: flex; flex-wrap: wrap; gap: 0.6rem 1.2rem; align-items: baseline; margin-bottom: 0.5rem; }
250.ticket .clock { font-size: 2rem; font-weight: 700; line-height: 1; }
251.ticket .who { font-size: 1.2rem; font-weight: 600; }
252.ticket .ref { opacity: 0.6; font-size: 0.9rem; }
253.due { font-size: 1.3rem; font-weight: 600; }
254.due.late { color: #c33; font-size: 1.9rem; text-transform: uppercase; }
255.due.now { font-weight: 700; }
256.due.unscheduled { opacity: 0.6; font-weight: 400; font-size: 1rem; }
257.klines { list-style: none; margin: 0.4rem 0 0; padding: 0; }
258.klines li { padding: 0.25rem 0; border-top: 1px solid var(--line, #38384a); }
259.klines .qty { font-weight: 700; display: inline-block; min-width: 2.2rem; }
260.klines .line-note { display: block; margin-left: 2.2rem; font-style: italic; font-weight: 600; }
261.hint { color: var(--muted, #999); font-size: 0.9rem; }
262@media print {
263 nav, header.app, .noprint, .btn { display: none !important; }
264 body { background: #fff; color: #000; }
265 .ticket { break-inside: avoid; border-color: #666; }
266 .due.late { color: #000; }
267}
268"""
269
270
271def _lines_html(lines):
272 if not lines:
273 return '<p class="hint">This order has no lines.</p>'
274 items = []
275 for line in lines:
276 quantity = _text(line.get("quantity")) or "1"
277 description = (_text(line.get("description"))
278 or _text(line.get("product_id")) or "Item")
279 # The note is the reason this page renders lines at all rather than
280 # a count -- read with .get so an order_lines that predates the
281 # column still cooks.
282 note = _text(line.get("line_note"))
283 note_html = (f'<span class="line-note">{_esc(note)}</span>'
284 if note else "")
285 items.append(f'<li><span class="qty">{_esc(quantity)}&times;</span>'
286 f'{_esc(description)}{note_html}</li>')
287 return f'<ul class="klines">{"".join(items)}</ul>'
288
289
290def _ticket_html(order, lines, now):
291 when = _parse_when(order.get("promised_at"))
292 due, state = _due_html(when, now)
293 number = _text(order.get("number")) or order["id"]
294 who = _text(order.get("customer_name")) or "No name on this order"
295 clock = _clock(when)
296 clock_html = f'<span class="clock">{_esc(clock)}</span>' if clock else ""
297 return f"""
298<article class="ticket {state}">
299<header>
300 {clock_html}
301 {due}
302 <span class="who">{_esc(who)}</span>
303 <span class="ref">{_esc(number)}</span>
304 <span class="ref noprint"><a href="/kitchen/{_esc(urllib.parse.quote(order['id'], safe=''))}/ticket">Ticket</a></span>
305</header>
306{_lines_html(lines)}
307</article>"""
308
309
310def GET(request):
311 identity = request.get("_identity") or {}
312 user_id = _text(identity.get("user_id"))
313
314 if not user_id:
315 body = ('<div class="pagehead"><h1>Kitchen</h1></div>'
316 '<p class="hint"><a href="/login?next=/kitchen">Sign in</a> '
317 'to see what is being made.</p>')
318 refresh = ""
319 else:
320 base = _base_dir()
321 now = _now()
322 orders, lines, saw_method = _orders_for(base, identity)
323 if orders:
324 queue = "".join(_ticket_html(order, lines.get(order["id"], []), now)
325 for order in orders)
326 elif not saw_method:
327 # The honest version of an empty page. A kitchen queue that is
328 # blank because nothing is cooking and one that is blank
329 # because no order on this box has ever said how it is being
330 # fulfilled look identical, and only one of them is somebody's
331 # bug.
332 queue = ('<p class="hint">Nothing is being prepared. No order on '
333 'this server states a <code>fulfillment_method</code> '
334 'yet, so nothing can be a pickup: the queue is empty '
335 'because the shop has not taken a pickup order, not '
336 'because it is missing one.</p>')
337 else:
338 queue = '<p class="hint">Nothing is being prepared right now.</p>'
339
340 body = f"""
341<div class="breadcrumb noprint"><a href="/">Home</a> / Kitchen</div>
342<div class="pagehead"><h1>Kitchen</h1></div>
343<p class="hint noprint">Pickup orders being prepared, soonest promise
344first. This is a read of the order records, never a stored queue, and it
345re-reads itself every {REFRESH_SECONDS} seconds.</p>
346<div class="kitchen">{queue}</div>
347<p class="hint noprint">An order leaves this queue when it is marked
348ready, which is also what tells the customer to come and get it.</p>
349"""
350 refresh = f'<meta http-equiv="refresh" content="{REFRESH_SECONDS}">'
351
352 who = (f"signed in as <strong>{_esc(user_id)}</strong>" if user_id
353 else '<a href="/login?next=/kitchen">sign in</a>')
354 page = f"""<!doctype html>
355<html lang="en">
356<head>
357<meta charset="utf-8">
358<meta name="viewport" content="width=device-width, initial-scale=1">
359{refresh}
360<title>Kitchen</title>
361<link rel="stylesheet" href="/style">
362<style>{_STYLE}</style>
363</head>
364<body>
365<div class="wrap">
366<header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header>
367{body}
368</div>
369<script src="/nav"></script>
370</body>
371</html>"""
372 return {"content_type": "text/html; charset=utf-8", "body": page}