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