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