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
shop.py · 39.8 KB · 915 lines
1"""/shop -- browse, basket, checkout, on one public page.
2
3Deliberately one page and deliberately server-rendered. Every step a
4shopper takes is a form POST that comes back as HTML, so the whole flow
5works with no JavaScript at all: no framework, no client-side cart state
6to drift out of sync with the server's, and nothing to go wrong on a
7phone with one bar of signal in a shop doorway.
8
9The basket is identified by a `cart` cookie holding an opaque session
10token. It is not an identity and it is not a cross-site key -- it says
11WHICH basket, never who. Nothing here reads or sets anything else: the
12server hands routed objects every cookie EXCEPT the identity session, and
13accepts exactly one response header back, `set_cookie`.
14
15**The token is action_cart's to mint, not this page's.** This page used to
16mint its own token for a visitor with no cookie and pass along whatever a
17cookie or a form said, which made the token whatever the client chose. It
18now forwards its request's `_identity` to action_cart and action_checkout,
19so they hold it to the public rule, sends the first add with no token, and
20sets the cookie from the token action_cart hands back. So a visitor who
21only looks gets no cookie and no basket row; one whose cookie names a
22basket this shop never opened is treated as a new visitor, and the cookie
23is replaced on their first add.
24
25A product also has a page of its own at /shop/{product_id} -- a grid of
26cards is a list of names and prices, and nobody buys a thing they cannot
27read about first. Its add-to-basket form posts to /shop, the same index
28the cards post to, so there is one basket path and not two.
29
30**A variant IS a product**, and this page is the only place that has to
31know it. A size or a colour is its own products row -- own SKU, own
32price, own stock level -- carrying parent_product_id (which card it
33displays under) and options ({"size": "M", "colour": "navy"}). Stock
34moves, pricing, checkout, fulfillment and the books all key on
35product_id today, so variants-as-products means every one of those keeps
36working with ZERO changes, and "how many medium navy totes are left?" is
37the same question as any other stock question. The alternative -- a
38variants table hanging under one product -- is the model that gives
39every integration a products-vs-variants split personality and two ids
40for one sellable thing. The cost lands here and nowhere else: the index
41collapses children under one card, and the product page renders a picker
42whose radios post the CHILD's product_id into the same add form every
43other card uses.
44
45**A note belongs to a LINE, so the box is on the add form.** "No onions"
46is true of one burger, not of an order, and a single box at the bottom of
47the checkout cannot say which line it meant -- that is what
48`customer_note` already is, and it is addressed to the packer. A line
49note is addressed to the cook. Two adds of one product with different
50notes come back as two basket lines, because they are two things to make,
51and the basket prints the note and any price delta under the line so the
52shopper can check both before they commit. The page renders no input for
53the delta itself: see _add_form.
54
55Categories are one flat text field, grouped into <h2> headings in
56alphabetical order, with the uncategorised last under "Everything else".
57Never hidden: a product nobody got round to filing must still be
58sellable, and a shop that quietly refused to show its own stock over a
59blank field would be losing sales it could not even see.
60
61All the actual decisions live in action_cart and action_checkout; this
62object only renders them and passes the token along. That split is what
63lets the same flow be driven by an API client, an agent over MCP, or a
64different front end, without the rules living in a template.
65"""
66
67import html
68import json
69import os
70import urllib.parse
71
72import object_execution
73import object_records
74import object_reservations
75import python_object_runtime
76
77try:
78 import object_stock
79except ImportError: # no stock app installed: the page says nothing at all
80 object_stock = None
81
82COOKIE = "cart"
83
84# The product types that sit on a shelf and can run out, same rule
85# action_checkout applies. A download or an hour of work never does, and
86# saying "Out of stock" about one would refuse a sale that checkout would
87# happily take.
88STOCKED_TYPES = ("physical", "asset", "")
89
90# Where product photographs already live: http_api_contract.USER_FILES_PATH,
91# the endpoint app-files has served since it existed. Not a shop-specific
92# image route -- inventing one would mean a second way to read the same
93# bytes, with its own permission story to get wrong.
94FILES_PATH = "/api/files"
95
96# The heading for products nobody has categorised. Last on the page and
97# never hidden: a blank field is a filing omission, not a decision to stop
98# selling something.
99UNCATEGORISED = "Everything else"
100
101# What an in-store-only product offers instead of an Add button
102# (products.in_store_only): the owner's special "only upon entry", where the
103# people in the shop -- queueing, or holding a numbered ticket -- come first.
104# action_cart refuses it whatever a page offers; this only makes the page
105# say so before anybody tries.
106IN_STORE_ONLY = ('<p class="stock in-store-only"><strong>In store only</strong>'
107 ' &mdash; come in to buy it; it cannot be ordered or reserved '
108 'online.</p>')
109
110_STYLE = """
111.shop-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 1rem; margin: 1rem 0 2rem; }
112.shop-card { border: 1px solid var(--line, #38384a); border-radius: 8px; padding: 0.9rem; display: flex; flex-direction: column; gap: 0.4rem; }
113.shop-card .price { font-size: 1.15rem; font-weight: 600; }
114.shop-card .sku { font-size: 0.8rem; opacity: 0.65; }
115.shop-category { font-size: 1rem; margin: 1.8rem 0 0.2rem; opacity: 0.85; }
116.shop-image { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 6px; }
117.shop-image.placeholder { background: var(--line, #38384a); opacity: 0.3; }
118.shop-detail .shop-image { max-width: 22rem; margin-bottom: 0.8rem; border-radius: 8px; }
119.options { border: 0; margin: 0.8rem 0; padding: 0; display: flex; flex-direction: column; gap: 0.35rem; }
120.options legend { padding: 0; font-weight: 600; }
121.option { display: block; }
122.option.out { opacity: 0.6; }
123.checkout textarea { width: 100%; max-width: 32rem; }
124.cart-table { width: 100%; border-collapse: collapse; margin: 0.5rem 0 1rem; }
125.cart-table th, .cart-table td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
126.cart-table td.num, .cart-table th.num { text-align: right; }
127.notice { border-left: 3px solid #c88; padding: 0.5rem 0.8rem; margin: 0.8rem 0; }
128.notice.ok { border-left-color: #6a6; }
129.shop-form { display: inline; }
130.qty { width: 4rem; }
131.note { width: 11rem; max-width: 100%; }
132.line-note { display: block; font-size: 0.85rem; opacity: 0.75; font-style: italic; }
133.line-modifier { display: block; font-size: 0.85rem; opacity: 0.75; }
134.shop-detail .price { font-size: 1.4rem; font-weight: 600; margin: 0.4rem 0; }
135.shop-detail .description { white-space: pre-wrap; margin: 1rem 0; max-width: 42rem; }
136.shop-detail .stock { font-size: 0.9rem; opacity: 0.7; }
137"""
138
139
140def _esc(value):
141 return html.escape(str(value if value is not None else ""), quote=True)
142
143
144def _base_dir():
145 return os.environ.get("DBBASIC_DATA_DIR", object_records.DEFAULT_DATA_DIR)
146
147
148def _money(cents):
149 try:
150 return f"{int(cents) / 100:,.2f}"
151 except (TypeError, ValueError):
152 return "0.00"
153
154
155def _call(object_id, payload, request=None):
156 """Run a sibling object in-process.
157
158 The page owns no rules of its own: it asks the objects that do. It
159 forwards the visitor's `_identity` with the request, as an object that
160 relays a request must (object_access), so the sibling knows this came
161 over HTTP and holds it to the public rules.
162 """
163 if request is not None and "_identity" in request:
164 payload = {**payload, "_identity": request["_identity"]}
165 runtime = python_object_runtime.PythonObjectRuntime()
166 result = object_execution.execute_object(
167 runtime,
168 object_execution.ObjectExecutionRequest(
169 object_id, method="POST", payload=payload))
170 return result.result if result.ok else {"error": "That did not work."}
171
172
173def _token(request):
174 """The basket token the visitor holds, or "" for none yet.
175
176 Never minted here: action_cart mints it on the first add (see the
177 module docstring)."""
178 cookies = request.get("_cookies") or {}
179 token = str(cookies.get(COOKIE) or "").strip()
180 if token:
181 return token, False
182 form = request.get("_form") or request
183 return str(form.get("session_token") or "").strip(), False
184
185
186def _products(base):
187 try:
188 # access: storefront catalog: the shop page shows live products to anyone, by design
189 rows = object_records.read_collection_records("products", base_dir=base)
190 except Exception:
191 return []
192 # An in-store-only product the shop chose not to show online
193 # (products.show_online) is not on this page at all, and its own page
194 # answers like a missing one; one it does show is marked and offers no
195 # Add button (_card).
196 live = [row for row in rows
197 if str(row.get("is_active") or "").lower() not in ("false", "0", "no", "off")
198 and object_reservations.shown_online(row)]
199 return sorted(live, key=lambda row: str(row.get("name") or ""))
200
201
202def _find_product(products, product_id):
203 """One product, or None when it is missing OR withdrawn from sale.
204
205 Withdrawn and missing answer the same way on purpose: a public page that
206 distinguished them would tell a stranger which ids exist.
207
208 Takes the already-read list rather than re-reading the collection: the
209 detail page needs the whole catalogue anyway, to find this product's
210 variants and its parent.
211 """
212 wanted = str(product_id or "").strip()
213 if not wanted:
214 return None
215 for row in products:
216 if str(row.get("id") or "") == wanted:
217 return row
218 return None
219
220
221def _detail_path(product_id):
222 return "/shop/" + urllib.parse.quote(str(product_id or ""), safe="")
223
224
225def _price_cents(product):
226 try:
227 return int(str(product.get("price_cents") or "0").strip() or 0)
228 except (TypeError, ValueError):
229 return 0
230
231
232def _options(product):
233 """The option map a variant declares, or {} for anything that is not one.
234
235 Bad JSON is {} rather than an error. A mistyped brace in one product's
236 options must not take that product off the shelf, and there is nobody
237 on this page who could fix it anyway.
238 """
239 raw = str(product.get("options") or "").strip()
240 if not raw:
241 return {}
242 try:
243 parsed = json.loads(raw)
244 except (TypeError, ValueError):
245 return {}
246 if not isinstance(parsed, dict):
247 return {}
248 # Insertion order is the SELLER's order -- "size" then "colour" reads
249 # the way a label is written -- so it is kept rather than sorted.
250 return {str(key): str(value) for key, value in parsed.items()}
251
252
253def _option_label(product):
254 """"M / navy" -- one line naming which variant this is.
255
256 Falls back to the product's own name so a row with no options (a
257 parent that is also sellable on its own) still has something to be
258 called in a picker.
259 """
260 values = [value for value in _options(product).values() if value]
261 return " / ".join(values) or str(product.get("name") or "")
262
263
264def _children_by_parent(products):
265 """Variants grouped under the product they display beneath.
266
267 Only parents that are themselves on sale count. A child whose parent
268 is withdrawn or missing would otherwise be collapsed under a card that
269 is not on the page at all -- a product nobody can see and nobody can
270 buy -- so it falls back to being its own card, which is exactly what
271 it was before anybody set the field.
272 """
273 live = {str(row.get("id") or "") for row in products}
274 groups = {}
275 for row in products:
276 parent = str(row.get("parent_product_id") or "").strip()
277 if parent and parent in live and parent != str(row.get("id") or ""):
278 groups.setdefault(parent, []).append(row)
279 return groups
280
281
282def _sellable(product, children):
283 """Can this row go in a basket on its own?
284
285 A parent WITH children and no price of its own is a display heading,
286 not a thing: "Tote bag" at 0.00 is not what anybody is buying, and
287 selling it would be charging nothing for a parcel nobody can pick. A
288 parent that does carry a price is a real base product that happens to
289 have variants too, and stays sellable.
290
291 action_cart is the authority and refuses the sale there; this mirrors
292 the rule so the page never offers a button that would be refused --
293 the same posture as _availability, for the same reason.
294 """
295 return not (children and _price_cents(product) <= 0)
296
297
298def _image(product):
299 """The product photograph, or an honest blank.
300
301 The catalogue stores a file id, never bytes, and the bytes come back
302 from the endpoint app-files already serves. A missing photograph is a
303 plain block rather than an <img> pointed at nothing: a broken-image
304 icon reads as a shop whose pages do not work, which is worse than a
305 product nobody has photographed yet.
306 """
307 file_id = str(product.get("image_file_id") or "").strip()
308 if not file_id:
309 return '<div class="shop-image placeholder"></div>'
310 src = FILES_PATH + "/" + urllib.parse.quote(file_id, safe="")
311 return (f'<img class="shop-image" src="{_esc(src)}" '
312 f'alt="{_esc(product.get("name"))}" loading="lazy">')
313
314
315def _add_form(product, token):
316 """The one way anything enters a basket: a POST to /shop.
317
318 The detail page uses this form too, so a product page is a different
319 VIEW of the shop and not a second checkout path to keep in step.
320
321 The note box is here rather than at checkout because it belongs to a
322 LINE: "no onions" is true of one burger, and a single box at the
323 bottom of the order cannot say which. action_cart makes a differing
324 note its own line, so two burgers ordered differently stay two things
325 to make.
326
327 There is deliberately NO price-delta input. This page is public and
328 action_cart is a public object, so an input that sets money is a
329 shopper pricing their own lunch; the delta arrives from an API caller
330 today, and the day a modifier picker exists it must price itself from
331 the server's own list rather than from the form.
332 """
333 return f"""
334<form method="post" action="/shop" class="shop-form">
335 <input type="hidden" name="do" value="add">
336 <input type="hidden" name="session_token" value="{_esc(token)}">
337 <input type="hidden" name="product_id" value="{_esc(product.get('id'))}">
338 <input class="qty" type="number" name="quantity" value="1" min="1" step="1">
339 <input class="note" type="text" name="line_note" maxlength="300"
340 placeholder="No onions, extra hot...">
341 <button type="submit">Add</button>
342</form>"""
343
344
345def _card(product, children, token):
346 """One card. A parent with variants gets ONE, not one per size.
347
348 A grid with Small, Medium and Large as three separate tiles is a grid
349 nobody can read: the shopper is looking for a tote bag, not for the
350 medium. When the parent is only a heading (variants priced, parent
351 not) the card shows the cheapest child's price as a "from" and offers
352 the only thing that is actually possible -- go and choose -- because a
353 disabled Add button is a dead control that teaches a shopper the shop
354 is broken.
355 """
356 currency = _esc(product.get("currency") or "USD")
357 if object_reservations.in_store_only(product):
358 price = f"{currency} {_money(product.get('price_cents'))}"
359 action = IN_STORE_ONLY
360 elif _sellable(product, children):
361 price = f"{currency} {_money(product.get('price_cents'))}"
362 action = _add_form(product, token)
363 else:
364 price = f"from {currency} {_money(min(_price_cents(c) for c in children))}"
365 action = (f'<a href="{_esc(_detail_path(product.get("id")))}">'
366 f'Choose options</a>')
367 return f"""
368<div class="shop-card">
369 <a href="{_esc(_detail_path(product.get('id')))}">{_image(product)}</a>
370 <div><strong><a href="{_esc(_detail_path(product.get('id')))}">{_esc(product.get('name'))}</a></strong></div>
371 <div class="sku">{_esc(product.get('sku') or '')}</div>
372 <div class="price">{price}</div>
373 {action}
374</div>"""
375
376
377def _grid(products, groups, token):
378 cards = [_card(product, groups.get(str(product.get("id") or ""), []), token)
379 for product in products]
380 return f'<div class="shop-grid">{"".join(cards)}</div>'
381
382
383def _product_cards(products, token):
384 """The catalogue, collapsed by variant and grouped by category.
385
386 A shop that has categorised nothing gets EXACTLY the grid it had
387 before any of this: it is not a shop with one category called
388 "Everything else", it is a shop that does not use categories, and a
389 heading over the whole page would be furniture pretending to be
390 information. Headings appear the moment somebody actually fills the
391 field in.
392 """
393 if not products:
394 return ('<p class="hint">Nothing is for sale yet. Add products in '
395 '<a href="/products">the catalogue</a>.</p>')
396
397 groups = _children_by_parent(products)
398 collapsed = {str(child.get("id") or "")
399 for children in groups.values() for child in children}
400 top = [row for row in products if str(row.get("id") or "") not in collapsed]
401
402 buckets = {}
403 for product in top:
404 buckets.setdefault(str(product.get("category") or "").strip(),
405 []).append(product)
406 named = sorted((key for key in buckets if key), key=str.lower)
407 if not named:
408 return _grid(top, groups, token)
409
410 sections = [f'<h2 class="shop-category">{_esc(name)}</h2>'
411 f'{_grid(buckets[name], groups, token)}' for name in named]
412 if buckets.get(""):
413 # Last, and never hidden. A product nobody got round to filing is
414 # still stock somebody paid for, and a shop that dropped it off the
415 # page would be refusing sales it could not even see it was losing.
416 sections.append(f'<h2 class="shop-category">{UNCATEGORISED}</h2>'
417 f'{_grid(buckets[""], groups, token)}')
418 return "".join(sections)
419
420
421def _stock_state(base, product):
422 """What may be promised, or None when nothing in this shop counts this
423 thing.
424
425 None is the point. None is not "out": a service, a
426 download, or a server with no stock app installed has no shelf, and
427 collapsing that into False would refuse to sell the things that never
428 run out. It is the same tracked-type rule action_checkout applies, so
429 the page cannot promise what checkout would refuse -- nor refuse what
430 checkout would happily take.
431
432 The answer is object_reservations.promise -- {"state", "left"} -- from
433 what is AVAILABLE: on hand less what live online orders hold. On hand
434 alone said "In stock" about a mug three unpaid orders were already
435 holding, and checkout then refused the shopper it had just invited.
436 """
437 if object_stock is None:
438 return None
439 if str(product.get("product_type") or "") not in STOCKED_TYPES:
440 return None
441 try:
442 on_hand = object_stock.total_quantity(product.get("id"), base_dir=base)
443 held = object_reservations.read_holds(base).get(str(product.get("id")), 0)
444 return object_reservations.promise(
445 on_hand - held, low=object_reservations.low_stock_threshold(base))
446 except Exception:
447 # A shelf that cannot be counted says nothing, rather than a number
448 # it cannot stand behind; checkout still decides.
449 return None
450
451
452STOCK_WORDS = {"sold_out": "Sold out", "in_stock": "In stock"}
453
454
455def _stock_words(promised):
456 if promised["state"] == "low":
457 return f"Only {promised['left']} left"
458 return STOCK_WORDS[promised["state"]]
459
460
461def _availability(base, product):
462 """One low-key line: in stock, only N left, sold out, or nothing at all.
463
464 Silence is the right answer more often than it looks -- see
465 _stock_state. Where stock IS counted, zero means zero: checkout
466 refuses that sale, and a page that promised otherwise would be sending
467 shoppers into a wall. A number only when it is small: see
468 object_reservations.promise for why an exact count is not shown.
469 """
470 promised = _stock_state(base, product)
471 if promised is None:
472 return ""
473 return f'<p class="stock">{_stock_words(promised)}</p>'
474
475
476def _preview(token, request=None):
477 """What this basket would actually cost, asked of action_checkout.
478
479 The page owns no arithmetic: postage and tax are decided by the same
480 object that will charge them, so the footer a shopper reads and the
481 invoice they get cannot disagree. A preview writes nothing.
482
483 None when the preview cannot be had -- an empty basket, a price that
484 moved, something out of stock. Those all have their own notice
485 already, and a basket that still shows its plain total is a better
486 answer than one whose totals vanish.
487 """
488 result = _call("action_checkout", {"session_token": token, "preview": "true"},
489 request)
490 if isinstance(result, dict) and result.get("preview"):
491 return result
492 return None
493
494
495def _totals_rows(cart, preview):
496 """The footer under the basket: today's one Total, or the breakdown.
497
498 A shop charging neither tax nor postage sees EXACTLY what it saw
499 before -- one Total row. Zero-rows are not neutral: "Shipping 0.00"
500 and "Tax 0.00" read as a broken shop, not a shop that does not do
501 those things.
502 """
503 if preview is None:
504 return (f'<tr><th colspan="3">Total</th>'
505 f'<th class="num">{_money(cart.get("subtotal_cents"))}</th></tr>')
506
507 shipping = int(preview.get("shipping_cents") or 0)
508 free = bool(preview.get("shipping_free"))
509 tax = int(preview.get("tax_cents") or 0)
510 if not shipping and not free and not tax:
511 return (f'<tr><th colspan="3">Total</th>'
512 f'<th class="num">{_money(preview.get("subtotal_cents"))}</th></tr>')
513
514 rows = [f'<tr><td colspan="3">Subtotal</td>'
515 f'<td class="num">{_money(preview.get("subtotal_cents"))}</td></tr>']
516 if shipping or free:
517 # Say it. Earning free delivery is the one moment in a basket
518 # that a shopper is pleased about, and a silent 0.00 throws it
519 # away -- it reads as a shop that forgot to charge rather than
520 # one that gave them something.
521 amount = ('<strong>Free shipping</strong>' if free
522 else _money(shipping))
523 rows.append(f'<tr><td colspan="3">Shipping</td>'
524 f'<td class="num">{amount}</td></tr>')
525 if tax:
526 rows.append(f'<tr><td colspan="3">Tax</td>'
527 f'<td class="num">{_money(tax)}</td></tr>')
528 rows.append(f'<tr><th colspan="3">Total</th>'
529 f'<th class="num">{_money(preview.get("total_cents"))}</th></tr>')
530 return "".join(rows)
531
532
533def _line_extras(line):
534 """The instruction under a basket line, and what it cost.
535
536 Both are shown, and shown apart, because they answer different
537 questions: the note is what the shopper asked for and is the thing
538 they will check before ordering, while the delta is why the price is
539 not the one on the card. A delta with no explanation beside it is the
540 small unexplained difference that becomes a phone call.
541 """
542 note = str(line.get("line_note") or "").strip()
543 modifier = int(line.get("modifier_cents") or 0)
544 blocks = ""
545 if note:
546 blocks += f'<span class="line-note">{_esc(note)}</span>'
547 if modifier:
548 named = ', '.join(line.get('modifiers') or [])
549 blocks += (f'<span class="line-modifier">'
550 f'{_esc(named + " ") if named else ""}+{_money(modifier)} each'
551 f'</span>')
552 return blocks
553
554
555def _line_stock(line):
556 """The "Only 2 left" or "Sold out" under a basket line, from what
557 action_cart says can still be promised; nothing when there is plenty,
558 or when the thing is not counted at all."""
559 promised = line.get("stock")
560 if not isinstance(promised, dict) or promised.get("state") not in ("low", "sold_out"):
561 return ""
562 return f'<span class="line-stock">{_esc(_stock_words(promised))}</span>'
563
564
565def _cart_table(cart, token, preview=None):
566 lines = cart.get("lines") or []
567 if not lines:
568 return '<p class="hint">Your basket is empty.</p>'
569 rows = []
570 for line in lines:
571 # cart_item_id, not just product_id: two lines can now share a
572 # product (one burger with no onions, one without), and an Update
573 # button that could only say WHICH PRODUCT would edit whichever
574 # line happened to be first.
575 rows.append(f"""
576<tr>
577 <td>{_esc(line['description'])}{_line_extras(line)}{_line_stock(line)}</td>
578 <td class="num">
579 <form method="post" action="/shop" class="shop-form">
580 <input type="hidden" name="do" value="set">
581 <input type="hidden" name="session_token" value="{_esc(token)}">
582 <input type="hidden" name="product_id" value="{_esc(line['product_id'])}">
583 <input type="hidden" name="cart_item_id" value="{_esc(line.get('cart_item_id'))}">
584 <input class="qty" type="number" name="quantity" value="{_esc(line['quantity'])}" min="0" step="any">
585 <button type="submit">Update</button>
586 </form>
587 </td>
588 <td class="num">{_money(line['unit_price_cents'])}</td>
589 <td class="num">{_money(line['line_total_cents'])}</td>
590</tr>""")
591 return f"""
592<table class="cart-table">
593<thead><tr><th>Item</th><th class="num">Qty</th><th class="num">Each</th><th class="num">Total</th></tr></thead>
594<tbody>{''.join(rows)}</tbody>
595<tfoot>{_totals_rows(cart, preview)}</tfoot>
596</table>"""
597
598
599def _checkout_form(token):
600 """Two optional textareas, and no gift FLAG anywhere near them.
601
602 The packing slip carries no prices by construction, so every parcel
603 this shop sends is already gift-safe -- a tickbox would only be one
604 more thing to forget, and forgetting it is how a present arrives with
605 the amount paid stapled to it. The placeholder says so out loud,
606 because a shopper who does not know that will not risk the message.
607 """
608 return f"""
609<form method="post" action="/shop" class="checkout">
610 <input type="hidden" name="do" value="checkout">
611 <input type="hidden" name="session_token" value="{_esc(token)}">
612 <p><label>Name<br><input type="text" name="customer_name"></label></p>
613 <p><label>Email<br><input type="email" name="customer_email" required></label></p>
614 <p><label>Special instructions (optional)<br>
615 <textarea name="customer_note" rows="2"
616 placeholder="Anything the packer needs to know"></textarea></label></p>
617 <p><label>Gift message (optional)<br>
618 <textarea name="gift_message" rows="2"
619 placeholder="Printed on the packing slip, which never shows prices"></textarea></label></p>
620 <p><button type="submit">Place order</button></p>
621</form>"""
622
623
624def _notice(result):
625 """Turn an object's refusal into something a shopper can act on."""
626 if not isinstance(result, dict):
627 return ""
628 if result.get("order_id") and not result.get("error"):
629 # The pay link is the most useful thing on the page at this moment,
630 # so it gets its own line rather than being buried in a sentence: a
631 # shopper who has just committed should not have to wait for an
632 # email to find out how to pay.
633 pay = ""
634 if result.get("pay_path"):
635 pay = (f'<p><strong><a href="{_esc(result["pay_path"])}">Pay now'
636 f'</a></strong></p>')
637 return (f'<div class="notice ok"><strong>Order placed.</strong> '
638 f'Reference {_esc(str(result["order_id"])[:8].upper())}. '
639 f'A receipt is on its way to you.{pay}</div>')
640 error = result.get("error")
641 if not error:
642 return ""
643 detail = []
644 for change in result.get("price_changes") or []:
645 detail.append(f"{_esc(change['description'])}: was {_money(change['was_cents'])}, "
646 f"now {_money(change['now_cents'])}")
647 for short in result.get("unavailable") or []:
648 detail.append(f"{_esc(short['description'])}: {_esc(short['available'])} left, "
649 f"you asked for {_esc(short['wanted'])}")
650 for gone in result.get("inactive") or []:
651 detail.append(f"{_esc(gone.get('description') or gone.get('product_id'))}: "
652 f"{_esc(gone['reason'])}")
653 extra = ("<ul><li>" + "</li><li>".join(detail) + "</li></ul>") if detail else ""
654 confirm = ""
655 if result.get("price_changes"):
656 confirm = ('<p>These are the current prices. Place the order again to '
657 'accept them.</p>')
658 return f'<div class="notice"><strong>{_esc(error)}</strong>{extra}{confirm}</div>'
659
660
661def _response(title, body, token, fresh, status=200):
662 """One shell for every page this object serves -- index, product, 404.
663
664 A shopper who mistypes a product id is still in the shop, so the not-
665 found page is the same page furniture with a different sentence in it,
666 never a traceback and never a bare JSON error.
667 """
668 html_page = f"""<!doctype html>
669<html lang="en">
670<head>
671<meta charset="utf-8">
672<meta name="viewport" content="width=device-width, initial-scale=1">
673<title>{_esc(title)}</title>
674<link rel="stylesheet" href="/style">
675<style>{_STYLE}</style>
676</head>
677<body>
678<div class="wrap">
679<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
680{body}
681</div>
682</body>
683</html>"""
684
685 response = {"status": status, "content_type": "text/html; charset=utf-8",
686 "body": html_page}
687 if fresh:
688 # Path-scoped, http-only, SameSite=Lax: it identifies a basket and is
689 # useless anywhere else. `set_cookie` is the single response header
690 # the server accepts from an object -- see _object_set_cookie_headers.
691 # A fresh EMPTY token expires the cookie: the basket was checked out
692 # or never existed, and the next add mints a new one.
693 response["set_cookie"] = (
694 f"{COOKIE}={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=1209600"
695 if token else
696 f"{COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0")
697 return response
698
699
700def _render(token, cart, products, notice, fresh, preview=None):
701 body = f"""
702<div class="breadcrumb"><a href="/">Home</a> / Shop</div>
703<div class="pagehead"><h1>Shop</h1></div>
704{notice}
705{_product_cards(products, token)}
706<h2 style="font-size:1rem">Your basket</h2>
707{_cart_table(cart, token, preview)}
708{_checkout_form(token) if (cart.get('lines') or []) else ''}
709<p class="hint">Prices are confirmed when you order. Your order holds its items
710for you from the moment you place it.</p>"""
711 return _response("Shop", body, token, fresh)
712
713
714def _picker(base, product, children, token):
715 """Choose a variant: plain radios in the same add form as everywhere.
716
717 This is where variants-as-products pays for itself. The radio's value
718 is a product_id, the form posts to /shop with do=add like every card
719 on the index, and action_cart, checkout, the stock ledger and the
720 books never learn that a "variant" is a word anybody uses.
721
722 Out-of-stock children are SHOWN and disabled, never dropped. Hiding
723 the medium is how a shopper concludes this shop does not sell their
724 size and goes to one that does; saying "Out of stock" tells them to
725 come back, and it is also simply true.
726
727 Nothing is pre-selected. A default that quietly ships the small
728 because it sorted first is a wrong parcel, a return and a refund; a
729 form that insists on being answered is a second of the shopper's time.
730 The parent itself appears as a choice only when it is sellable in its
731 own right -- otherwise it is a heading, not a thing to buy.
732 """
733 choices = ([product] if _sellable(product, children) else []) + list(children)
734 rows = []
735 for choice in choices:
736 label = _esc(_option_label(choice))
737 value = _esc(choice.get("id"))
738 if object_reservations.in_store_only(choice):
739 rows.append(f'<label class="option out"><input type="radio" '
740 f'name="product_id" value="{value}" disabled> {label} '
741 f'&mdash; In store only</label>')
742 elif (promised := _stock_state(base, choice)) and promised["state"] == "sold_out":
743 rows.append(f'<label class="option out"><input type="radio" '
744 f'name="product_id" value="{value}" disabled> {label} '
745 f'&mdash; Sold out</label>')
746 else:
747 money = (f'{_esc(choice.get("currency") or "USD")} '
748 f'{_money(choice.get("price_cents"))}')
749 few = (f' ({_stock_words(promised)})'
750 if promised and promised["state"] == "low" else "")
751 rows.append(f'<label class="option"><input type="radio" '
752 f'name="product_id" value="{value}" required> {label} '
753 f'&mdash; {money}{few}</label>')
754 return f"""
755<form method="post" action="/shop" class="shop-form">
756 <input type="hidden" name="do" value="add">
757 <input type="hidden" name="session_token" value="{_esc(token)}">
758 <fieldset class="options"><legend>Choose an option</legend>
759 {"".join(rows)}
760 </fieldset>
761 <input class="qty" type="number" name="quantity" value="1" min="1" step="1">
762 <input class="note" type="text" name="line_note" maxlength="300"
763 placeholder="No onions, extra hot...">
764 <button type="submit">Add</button>
765</form>"""
766
767
768def _variant_of(parent, product):
769 """The line on a child's page that says what it is and where it came
770 from.
771
772 A shopper who landed on the medium from a search result needs the way
773 back to the other sizes, or the only size this shop appears to sell is
774 the one Google happened to index.
775 """
776 options = _options(product)
777 named = ", ".join(f"{key}: {value}" for key, value in options.items())
778 said = f'<p class="options-said">{_esc(named)}</p>' if named else ""
779 return (f'{said}<p><a href="{_esc(_detail_path(parent.get("id")))}">'
780 f'All options of {_esc(parent.get("name"))}</a></p>')
781
782
783def _render_detail(base, product, children, parent, token, fresh):
784 description = product.get("description") or ""
785 unit = f" / {_esc(product.get('unit'))}" if product.get("unit") else ""
786 currency = _esc(product.get("currency") or "USD")
787 if _sellable(product, children):
788 price = f"{currency} {_money(product.get('price_cents'))}{unit}"
789 else:
790 # A heading has no price of its own, and printing 0.00 would be a
791 # number the shopper cannot buy anything at.
792 price = f"from {currency} {_money(min(_price_cents(c) for c in children))}"
793 # Availability belongs to a thing that can be added; for a parent the
794 # answer is per-variant and lives on each radio, where the choice is.
795 stock = "" if children else _availability(base, product)
796 if object_reservations.in_store_only(product) and not children:
797 stock, buy = "", IN_STORE_ONLY
798 else:
799 buy = (_picker(base, product, children, token) if children
800 else _add_form(product, token))
801 body = f"""
802<div class="breadcrumb"><a href="/">Home</a> / <a href="/shop">Shop</a> /
803{_esc(product.get('name'))}</div>
804<div class="pagehead"><h1>{_esc(product.get('name'))}</h1></div>
805<div class="shop-detail">
806 {_image(product)}
807 <div class="sku">{_esc(product.get('sku') or '')}</div>
808 <div class="price">{price}</div>
809 {stock}
810 <div class="description">{_esc(description)}</div>
811 {buy}
812 {_variant_of(parent, product) if parent is not None else ''}
813</div>
814<p><a href="/shop">Back to shop</a></p>"""
815 return _response(str(product.get("name") or "Product"), body, token, fresh)
816
817
818def _render_missing(token, fresh):
819 body = """
820<div class="breadcrumb"><a href="/">Home</a> / <a href="/shop">Shop</a></div>
821<div class="pagehead"><h1>Not for sale</h1></div>
822<p>We could not find that. It may have sold out for good, or the link may
823have a typo in it.</p>
824<p><a href="/shop">Back to shop</a></p>"""
825 return _response("Not for sale", body, token, fresh, status=404)
826
827
828def _detail(request, product_id):
829 base = _base_dir()
830 token, fresh = _token(request)
831 products = _products(base)
832 product = _find_product(products, product_id)
833 if product is None:
834 return _render_missing(token, fresh)
835 children = _children_by_parent(products).get(str(product.get("id") or ""), [])
836 # A parent that is withdrawn or missing is the same as no parent at
837 # all: the child is a product in its own right and its page must still
838 # sell it, rather than pointing at a card that is not on the shop.
839 parent = _find_product(products, product.get("parent_product_id"))
840 if parent is not None and str(parent.get("id") or "") == str(product.get("id") or ""):
841 parent = None
842 return _render_detail(base, product, children, parent, token, fresh)
843
844
845def _handle(request):
846 base = _base_dir()
847 token, fresh = _token(request)
848 form = request.get("_form") or request
849 do = str(form.get("do") or "").strip()
850 notice = ""
851
852 if do in ("add", "set", "remove", "clear"):
853 payload = {"session_token": token, "action": do,
854 "product_id": form.get("product_id"),
855 "quantity": form.get("quantity")}
856 if do == "add":
857 # Only on add. Passing an absent note on `set` would tell
858 # action_cart to blank a note the shopper typed, which is
859 # what "stated" versus "omitted" means over there.
860 payload["line_note"] = form.get("line_note")
861 # The extras by NAME, if a form offers them; action_cart prices
862 # them from the product. Never a price from the page.
863 if form.get("modifiers"):
864 payload["modifiers"] = form.get("modifiers")
865 if form.get("cart_item_id"):
866 payload["cart_item_id"] = form.get("cart_item_id")
867 if not token:
868 payload.pop("session_token")
869 result = _call("action_cart", payload, request)
870 if result.get("code") == "unknown_session_token" and do == "add":
871 # The cookie names a basket this shop never opened: start one.
872 payload.pop("session_token", None)
873 result = _call("action_cart", payload, request)
874 minted = str(result.get("session_token") or "")
875 if minted and minted != token:
876 token, fresh = minted, True
877 notice = _notice(result)
878 elif do == "checkout":
879 result = _call("action_checkout", {
880 "session_token": token,
881 "customer_email": form.get("customer_email"),
882 "customer_name": form.get("customer_name"),
883 # Two optional fields, straight through: the page decides
884 # nothing about them, action_checkout decides where they land.
885 "customer_note": form.get("customer_note"),
886 "gift_message": form.get("gift_message"),
887 # A second attempt after seeing the new prices IS the shopper
888 # agreeing to them, which is why this is not a hidden default.
889 "confirm_prices": form.get("confirm_prices")}, request)
890 notice = _notice(result)
891 if result.get("order_id"):
892 # A fresh basket: the cookie is expired, and the next add mints.
893 token, fresh = "", True
894
895 cart = (_call("action_cart", {"session_token": token, "action": "get"}, request)
896 if token else {})
897 cart = cart if isinstance(cart, dict) else {}
898 # Only ask what it costs when there is something to cost. A preview
899 # of an empty basket is a 404 the page would only throw away.
900 preview = _preview(token, request) if (cart.get("lines") or []) else None
901 return _render(token, cart, _products(base), notice, fresh, preview)
902
903
904def GET(request):
905 # /shop/{product_id} arrives as a top-level route capture. POST is
906 # deliberately NOT routed here: every basket change posts to /shop, so
907 # there is one add path and the detail page is only ever a view.
908 product_id = str(request.get("product_id") or "").strip()
909 if product_id:
910 return _detail(request, product_id)
911 return _handle(request)
912
913
914def POST(request):
915 return _handle(request)