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
order_status.py · 20.7 KB · 489 lines
1"""site_order_status -- "where is my order?", answered without an account.
2GET /orders/track/{token}.
3
4The customer is NOT a user of this system. This shop's default sale is a
5guest checkout: an email address, a card, and no identity afterwards. So
6until now a shopper who paid heard nothing and had nowhere to look --
7every fact about their own purchase lived behind a sign-in wall they had
8no key to. This page is that key, and it is the same shape app-invoices
9already proved for /pay/{token}: a CAPABILITY URL, an unguessable bearer
10token on the order (orders.portal_token, minted by action_checkout and by
11system_order_portal_link), granting exactly "see this one order."
12
13Looked up BY TOKEN ONLY -- never by id. Order ids are UUIDv4 and appear in
14record_changes, in the owner-scoped /collections/orders/records/{id} path,
15in shipment rows and in correlation ids threaded through logs: surfaces an
16operator reasonably expects to stay internal, not things a stranger's
17browser history holds. Keeping the token a separate field means there is
18no enumeration path from a guessed id to somebody's name, address and
19purchase history -- which is exactly the objection site_return_form raised
20when it had to fall back to a sign-in prompt.
21
22hmac.compare_digest for the match: a plain `==` on attacker-controlled
23input leaks how many leading characters matched via how long the compare
24took, which is the side channel a bearer-token scheme exists to close. A
25blank, unknown or mistyped token renders the SAME friendly "not found"
26page at 404 -- never a 403, never a traceback, and never a hint that some
27other token would have worked. A 403 would confirm the token namespace is
28a thing worth attacking; "not found" makes a guess and a typo
29indistinguishable.
30
31**It shows prices, unlike the packing slip.** site_packing_slip carries no
32money by construction, because it goes in the box and the box may be a
33present. This page is the opposite case: it is the buyer's own receipt,
34read by the person who paid, and a receipt with the amounts filed off is
35not a receipt.
36
37**The status is translated, not echoed.** The orders enum is warehouse
38vocabulary -- `partial` is a fact about which shipment lines have left,
39`processing` is a bookkeeping hop, `received` means goods arrived HERE on
40a purchase order. None of that is a sentence to show a person waiting for
41a parcel, and "partial" in particular reads to a customer as "part of my
42money went missing". So there is one mapping, in one place, from the
43internal word to the customer's word, and an unmapped status falls back to
44a plainly honest "Being prepared" rather than leaking the raw enum.
45
46The same argument is why orders v7's pickup ladder gets its own words
47rather than borrowing the parcel ones: a customer collecting a sandwich
48reads "Order received" / "Being prepared" / "Ready for collection" /
49"Collected", and the only reason those needed new enum values at all is
50that "your order has shipped" about something sitting on a counter is a
51sentence written by somebody else's software. A SHIPPING order's wording
52is untouched by every line of that -- the new statuses can only appear on
53an order whose fulfillment_method says it is being collected, and the one
54place this page reads the method (a two-entry blurb overlay and the
55promised time) falls back to exactly what it said before when the field
56is blank or `shipping`.
57
58No nav, no global search, no site chrome beyond the base stylesheet: this
59page is handed to a stranger's inbox and must never be one click from
60somebody else's order or from the sign-in wall of a system they have no
61account on. The two links it DOES offer both stay inside this one sale --
62the invoice's own pay door, and a return carrying this same token.
63"""
64from __future__ import annotations
65
66import hmac
67import html
68import os
69from datetime import datetime
70
71import object_money
72import object_records
73
74DATA_DIR_ENV = "DBBASIC_DATA_DIR"
75ACTOR = "site_order_status"
76
77# The one mapping from warehouse vocabulary to the words a customer
78# understands. `processing` and `partial` share a bucket on purpose:
79# "some of it has left the building" is an internal distinction about
80# shipment lines, and to somebody waiting at home both mean the same thing
81# -- it is being dealt with. `received` is the PURCHASE side's terminal
82# state and can never appear on an order a customer is tracking, so it is
83# deliberately absent rather than mistranslated.
84#
85# preparing/ready/collected are the PICKUP ladder (orders v7). They are
86# separate enum values rather than a reuse of shipped/delivered for
87# exactly the reason this table exists: "your order has shipped" about a
88# sandwich waiting on a counter is a sentence written by somebody else's
89# software. Nothing in this dict changes what a SHIPPING order reads --
90# the three new keys can only ever appear on an order whose
91# fulfillment_method is pickup, delivery or counter, because the objects
92# are what enforce which subset of the enum an order may climb.
93CUSTOMER_STATUS = {
94 "confirmed": "Order received",
95 "partial": "Being prepared",
96 "processing": "Being prepared",
97 "preparing": "Being prepared",
98 "shipped": "On its way",
99 "delivered": "Delivered",
100 "ready": "Ready for collection",
101 "collected": "Collected",
102 "cancelled": "Cancelled",
103}
104
105# What each of those means in a sentence, because a two-word badge answers
106# "what" and never "so what".
107STATUS_BLURB = {
108 "Order received": "We have your order and are getting it ready.",
109 "Being prepared": "Your order is being picked and packed.",
110 "On its way": "Your order has left us and is with the carrier.",
111 "Delivered": "This order has been delivered.",
112 "Ready for collection": "Your order is ready. Come and collect it "
113 "whenever suits.",
114 "Collected": "You collected this order. Thank you.",
115 "Cancelled": "This order was cancelled. If that is a surprise, "
116 "contact the shop.",
117}
118
119# The same words, said the way a person collecting a thing hears them. A
120# pickup order that is "being picked and packed" is being described by a
121# warehouse that is not involved, and a shipping order whose blurb talked
122# about a counter would be the same mistake pointing the other way -- so
123# this is an OVERLAY keyed on fulfillment_method, not an edit to the table
124# above. Only these two lines differ; everything else reads correctly for
125# both, which is why the overlay is two entries rather than a second table.
126PICKUP_BLURB = {
127 "Order received": "We have your order and will have it ready for you.",
128 "Being prepared": "Your order is being made now.",
129}
130
131# Methods where the customer comes to the goods rather than the goods
132# going to the customer. `counter` is in the set because a counter sale
133# collected at once is still collected, not posted. `delivery` is NOT:
134# it is deliberately the thin case in this slice (we drive it, with no
135# dispatch layer), so it reads the shared wording rather than acquiring
136# an overlay nothing has been built to earn yet.
137PICKUP_METHODS = {"pickup", "counter"}
138
139# The customer's word for anything the mapping does not cover -- a draft
140# that somehow acquired a token, or a status added to the enum after this
141# page was written. Never the raw enum value: an unmapped internal word on
142# a customer's screen is a bug that reads as a system talking to itself.
143FALLBACK_STATUS = "Being prepared"
144
145# Goods have reached the customer, so there is something to send back.
146RETURNABLE = {"shipped", "delivered", "partial"}
147
148# An invoice in one of these still wants money. `void` does not -- a
149# cancelled bill must never be offered a pay button.
150UNPAID_INVOICE_STATUSES = {"draft", "sent", "partial", "overdue"}
151
152
153def _base_dir():
154 return os.environ.get(DATA_DIR_ENV, "data")
155
156
157def _text(value):
158 return str(value if value is not None else "").strip()
159
160
161def _esc(value):
162 return html.escape(_text(value))
163
164
165def _find_order_by_token(base, token):
166 """The only lookup this page performs: a full scan matched with a
167 constant-time comparison, never a keyed lookup by id.
168
169 A blank token matches nothing -- without this guard an order that has
170 never had a token minted (stored as "") would "match" a blank incoming
171 token, which turns "no link generated yet" into an accidental open
172 door onto whichever unlinked order happens to be first in the file.
173 """
174 token = _text(token)
175 if not token:
176 return None
177 try:
178 # access: capability link: the order is found by its secret portal_token; its lines, parcels and invoice are the order's own
179 rows = object_records.read_collection_records("orders", base_dir=base)
180 except Exception:
181 return None
182 for row in rows:
183 candidate = _text(row.get("portal_token"))
184 if not candidate:
185 continue
186 if hmac.compare_digest(candidate, token):
187 return row
188 return None
189
190
191def _lines_for(base, order_id):
192 """The order's lines, or none at all if order_lines is somehow absent.
193 A receipt with no itemisation is thin; a 500 on the page a customer is
194 trying to read is worse.
195 """
196 try:
197 # access: capability link: the order is found by its secret portal_token; its lines, parcels and invoice are the order's own
198 rows = object_records.read_collection_records("order_lines",
199 base_dir=base)
200 except Exception:
201 return []
202 lines = [row for row in rows if _text(row.get("order_id")) == order_id]
203 lines.sort(key=lambda row: _text(row.get("description")))
204 return lines
205
206
207def _shipments_for(base, order_id):
208 """Outbound parcels for this order, newest-looking last.
209
210 Wrapped because app-shipping is a separate package and app-orders does
211 not depend on it: a shop that never installed shipping still has
212 orders, and its customers still deserve this page.
213 """
214 try:
215 # access: capability link: the order is found by its secret portal_token; its lines, parcels and invoice are the order's own
216 rows = object_records.read_collection_records("shipments",
217 base_dir=base)
218 except Exception:
219 return []
220 return [row for row in rows
221 if _text(row.get("order_id")) == order_id
222 and _text(row.get("direction")) != "inbound"]
223
224
225def _invoice_for(base, order):
226 """The bill for this order, when there is one and it can be found.
227
228 Same posture as the shipments read: app-invoices is another package,
229 and an order with no findable invoice is an order with no pay link,
230 not an error page.
231
232 "The order's own" invoice is one its owner owns. orders.invoice_id is
233 free text the order's owner may set, so an order pointed at somebody
234 else's invoice put THAT invoice's pay link -- its portal capability,
235 with the customer's name and address behind it -- on this page.
236 """
237 invoice_id = _text(order.get("invoice_id"))
238 if not invoice_id:
239 return None
240 try:
241 # access: capability link: the order is found by its secret portal_token; its lines, parcels and invoice are the order's own
242 invoice = object_records.get_collection_record("invoices", invoice_id,
243 base_dir=base)
244 except Exception:
245 return None
246 if _text(invoice.get("owner_id")) != _text(order.get("owner_id")):
247 return None
248 return invoice
249
250
251def _setting(base, key, default=""):
252 """Duplicated, on purpose, from every other package that reads
253 app_settings: there is no shared settings module in this codebase yet
254 and inventing one for an nth copy is the layer docs/logic-decisions.md
255 #4 says to wait on.
256 """
257 try:
258 # access: box configuration
259 for row in object_records.read_collection_records("app_settings",
260 base_dir=base):
261 if row.get("key") == key and _text(row.get("value")):
262 return _text(row["value"])
263 except Exception:
264 pass
265 return default
266
267
268_STYLE = """
269.wrap { max-width: 720px; margin: 0 auto; padding: 2rem 1.25rem; }
270.pagehead { margin-bottom: 1.25rem; }
271.pagehead h1 { margin: 0 0 0.25rem; font-size: 1.4rem; }
272.hint { color: var(--muted, #999); font-size: 0.9rem; }
273.status { border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.9rem 1.1rem; margin: 1.25rem 0; }
274.status .n { font-size: 1.25rem; font-weight: 700; }
275table.lines { width: 100%; border-collapse: collapse; margin: 1rem 0 1.5rem; }
276table.lines th, table.lines td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
277table.lines td.num, table.lines th.num { text-align: right; }
278table.lines tr.total td { font-weight: 700; border-bottom: none; }
279.parcel { border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.8rem 1rem; margin: 0.75rem 0; }
280.doors { margin: 1.5rem 0; }
281.doors a { display: inline-block; margin-right: 1rem; }
282.notfound { text-align: center; padding: 3rem 1rem; }
283"""
284
285
286def _page(body, *, title, status=200):
287 """Deliberately bare: no /nav script, no global search mount, no
288 breadcrumb back into the app. This page is handed to a stranger's
289 inbox; it must not be one click from anything but this one order.
290 """
291 page = {
292 "content_type": "text/html; charset=utf-8",
293 "body": f"""<!doctype html>
294<html lang="en">
295<head>
296<meta charset="utf-8">
297<meta name="viewport" content="width=device-width, initial-scale=1">
298<meta name="referrer" content="no-referrer">
299<title>{_esc(title)}</title>
300<link rel="stylesheet" href="/style">
301<style>{_STYLE}</style>
302</head>
303<body>
304<div class="wrap">
305{body}
306</div>
307</body>
308</html>""",
309 }
310 if status != 200:
311 page["status"] = status
312 return page
313
314
315def _not_found():
316 """One page for every failure: blank token, mistyped token, token for
317 an order that was purged. Saying which would tell somebody probing
318 that they were close.
319 """
320 return _page(
321 '<div class="notfound"><h1>Not found</h1>'
322 '<p class="hint">This tracking link is not valid. It may have been '
323 'mistyped, or copied without its last few characters. Check the link '
324 'in your confirmation email, or contact the shop and they can send '
325 'you a fresh one.</p></div>',
326 title="Not found", status=404)
327
328
329def _business_html(base):
330 """Whatever the operator configured under business.name, and nothing
331 invented when they configured nothing: an unbranded receipt is honest,
332 a fabricated shop name is not.
333 """
334 name = _setting(base, "business.name")
335 return f'<div class="hint">{_esc(name)}</div>' if name else ""
336
337
338def _when(value):
339 """A datetime rendered the way somebody reads a collection time, or
340 "" if it is blank or unparseable.
341
342 Never a raw ISO string on a customer's screen: "2026-07-27T18:00:00"
343 is a machine talking, and the one number this page exists to show a
344 pickup customer is the time they should turn up.
345 """
346 text = _text(value)
347 if not text:
348 return ""
349 try:
350 moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
351 except ValueError:
352 return ""
353 return moment.strftime("%a %d %b, %H:%M")
354
355
356def _status_html(order):
357 raw = _text(order.get("status"))
358 word = CUSTOMER_STATUS.get(raw, FALLBACK_STATUS)
359 # Default is the shipping wording, unchanged for every order that
360 # existed before pickup did -- the overlay only applies when the order
361 # itself says it is being collected.
362 method = _text(order.get("fulfillment_method")) or "shipping"
363 blurb = STATUS_BLURB.get(word, "")
364 if method in PICKUP_METHODS:
365 blurb = PICKUP_BLURB.get(word, blurb)
366 lines = [f'<div class="n">{_esc(word)}</div>']
367 if blurb:
368 lines.append(f'<div class="hint">{_esc(blurb)}</div>')
369 if method in PICKUP_METHODS and raw not in ("collected", "cancelled"):
370 # The promised time, on the one kind of order that has one. A
371 # customer who ordered ahead is not asking "what state is my
372 # order in", they are asking "when do I walk over there".
373 promised = _when(order.get("promised_at"))
374 if promised:
375 lines.append(f'<div class="hint">Ready by {_esc(promised)}</div>')
376 return f'<div class="status">{"".join(lines)}</div>'
377
378
379def _lines_html(order, lines, base):
380 """The receipt itself. Prices included -- see the module docstring."""
381 currency = _text(order.get("currency")) or "USD"
382 total = object_money.format_amount(order.get("total_cents") or 0, currency,
383 base_dir=base)
384 if not lines:
385 # An order whose lines cannot be read still owes the customer the
386 # one number they care about. A "What you ordered" heading over an
387 # empty space reads as "we have lost your order".
388 return (f'<p>Total paid: <strong>{_esc(total)}</strong></p>'
389 '<p class="hint">The itemised list is not available here. '
390 'Your confirmation email has it.</p>')
391 rows = []
392 for line in lines:
393 rows.append(
394 "<tr>"
395 f"<td>{_esc(line.get('description')) or _esc(line.get('product_id'))}</td>"
396 f"<td class=\"num\">{_esc(line.get('quantity')) or '1'}</td>"
397 f"<td class=\"num\">{_esc(object_money.format_amount(line.get('unit_price_cents') or 0, currency, base_dir=base))}</td>"
398 f"<td class=\"num\">{_esc(object_money.format_amount(line.get('line_total_cents') or 0, currency, base_dir=base))}</td>"
399 "</tr>")
400 # The GRAND total, which is what the buyer paid: postage and tax are in
401 # it. Showing the goods subtotal under the word "Total" is how a
402 # receipt ends up disagreeing with a card statement.
403 rows.append('<tr class="total"><td colspan="3">Total</td>'
404 f'<td class="num">{_esc(total)}</td></tr>')
405 return f"""
406<table class="lines">
407<thead><tr><th>Item</th><th class="num">Qty</th>
408<th class="num">Price</th><th class="num">Amount</th></tr></thead>
409<tbody>{''.join(rows)}</tbody>
410</table>"""
411
412
413def _parcels_html(shipments):
414 """Carrier and tracking number when the shipment carries them, and
415 silence when it does not. A "Tracking: (none)" row tells a worried
416 customer nothing except that the shop has a field for it.
417 """
418 blocks = []
419 for shipment in shipments:
420 carrier = _text(shipment.get("carrier"))
421 tracking = _text(shipment.get("tracking_number"))
422 if not carrier and not tracking:
423 continue
424 parts = []
425 if carrier:
426 parts.append(f"<strong>{_esc(carrier)}</strong>")
427 if tracking:
428 parts.append(f"tracking number {_esc(tracking)}")
429 shipped_on = _text(shipment.get("shipped_on"))
430 if shipped_on:
431 parts.append(f"sent {_esc(shipped_on)}")
432 blocks.append(f'<div class="parcel">{" &middot; ".join(parts)}</div>')
433 if not blocks:
434 return ""
435 return "<h2>Your parcel</h2>" + "".join(blocks)
436
437
438def _doors_html(order, invoice, token):
439 """The two links that stay inside this one sale.
440
441 The pay link only appears while money is actually owed: offering "pay
442 now" on an order already paid for is how a shop gets paid twice and
443 spends a fortnight refunding it. The return link only appears once
444 something has physically left, because an order still in the building
445 is changed or cancelled, not returned -- and it carries THIS token, so
446 the guest who never made an account can actually use it.
447 """
448 doors = []
449 if invoice is not None:
450 pay_token = _text(invoice.get("portal_token"))
451 status = _text(invoice.get("status"))
452 if pay_token and status in UNPAID_INVOICE_STATUSES:
453 doors.append(f'<a href="/pay/{_esc(pay_token)}">Pay for this order</a>')
454 if _text(order.get("status")) in RETURNABLE:
455 doors.append(f'<a href="/returns/{_esc(order["id"])}?token={_esc(token)}">'
456 "Start a return</a>")
457 if not doors:
458 return ""
459 return f'<div class="doors">{"".join(doors)}</div>'
460
461
462def GET(request):
463 base = _base_dir()
464 token = _text(request.get("token"))
465 order = _find_order_by_token(base, token)
466 if order is None:
467 return _not_found()
468
469 number = _text(order.get("number")) or order["id"]
470 lines = _lines_for(base, order["id"])
471 shipments = _shipments_for(base, order["id"])
472 invoice = _invoice_for(base, order)
473
474 ordered_on = _text(order.get("order_date"))
475 body = f"""
476<div class="pagehead">
477{_business_html(base)}
478<h1>Order {_esc(number)}</h1>
479<p class="hint">{('Placed ' + _esc(ordered_on)) if ordered_on else 'Thank you for your order'}</p>
480</div>
481{_status_html(order)}
482{_parcels_html(shipments)}
483<h2>What you ordered</h2>
484{_lines_html(order, lines, base)}
485{_doors_html(order, invoice, token)}
486<p class="hint">Keep this link -- it is the only way back to this page, and
487it works for nobody but whoever holds it.</p>
488"""
489 return _page(body, title=f"Order {number}")