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
order_status.py · 19.7 KB · 476 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 rows = object_records.read_collection_records("orders", base_dir=base)
179 except Exception:
180 return None
181 for row in rows:
182 candidate = _text(row.get("portal_token"))
183 if not candidate:
184 continue
185 if hmac.compare_digest(candidate, token):
186 return row
187 return None
188
189
190def _lines_for(base, order_id):
191 """The order's lines, or none at all if order_lines is somehow absent.
192 A receipt with no itemisation is thin; a 500 on the page a customer is
193 trying to read is worse.
194 """
195 try:
196 rows = object_records.read_collection_records("order_lines",
197 base_dir=base)
198 except Exception:
199 return []
200 lines = [row for row in rows if _text(row.get("order_id")) == order_id]
201 lines.sort(key=lambda row: _text(row.get("description")))
202 return lines
203
204
205def _shipments_for(base, order_id):
206 """Outbound parcels for this order, newest-looking last.
207
208 Wrapped because app-shipping is a separate package and app-orders does
209 not depend on it: a shop that never installed shipping still has
210 orders, and its customers still deserve this page.
211 """
212 try:
213 rows = object_records.read_collection_records("shipments",
214 base_dir=base)
215 except Exception:
216 return []
217 return [row for row in rows
218 if _text(row.get("order_id")) == order_id
219 and _text(row.get("direction")) != "inbound"]
220
221
222def _invoice_for(base, order):
223 """The bill for this order, when there is one and it can be found.
224
225 Same posture as the shipments read: app-invoices is another package,
226 and an order with no findable invoice is an order with no pay link,
227 not an error page.
228 """
229 invoice_id = _text(order.get("invoice_id"))
230 if not invoice_id:
231 return None
232 try:
233 return object_records.get_collection_record("invoices", invoice_id,
234 base_dir=base)
235 except Exception:
236 return None
237
238
239def _setting(base, key, default=""):
240 """Duplicated, on purpose, from every other package that reads
241 app_settings: there is no shared settings module in this codebase yet
242 and inventing one for an nth copy is the layer docs/logic-decisions.md
243 #4 says to wait on.
244 """
245 try:
246 for row in object_records.read_collection_records("app_settings",
247 base_dir=base):
248 if row.get("key") == key and _text(row.get("value")):
249 return _text(row["value"])
250 except Exception:
251 pass
252 return default
253
254
255_STYLE = """
256.wrap { max-width: 720px; margin: 0 auto; padding: 2rem 1.25rem; }
257.pagehead { margin-bottom: 1.25rem; }
258.pagehead h1 { margin: 0 0 0.25rem; font-size: 1.4rem; }
259.hint { color: var(--muted, #999); font-size: 0.9rem; }
260.status { border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.9rem 1.1rem; margin: 1.25rem 0; }
261.status .n { font-size: 1.25rem; font-weight: 700; }
262table.lines { width: 100%; border-collapse: collapse; margin: 1rem 0 1.5rem; }
263table.lines th, table.lines td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #38384a); }
264table.lines td.num, table.lines th.num { text-align: right; }
265table.lines tr.total td { font-weight: 700; border-bottom: none; }
266.parcel { border: 1px solid var(--line, #333); border-radius: 8px; padding: 0.8rem 1rem; margin: 0.75rem 0; }
267.doors { margin: 1.5rem 0; }
268.doors a { display: inline-block; margin-right: 1rem; }
269.notfound { text-align: center; padding: 3rem 1rem; }
270"""
271
272
273def _page(body, *, title, status=200):
274 """Deliberately bare: no /nav script, no global search mount, no
275 breadcrumb back into the app. This page is handed to a stranger's
276 inbox; it must not be one click from anything but this one order.
277 """
278 page = {
279 "content_type": "text/html; charset=utf-8",
280 "body": f"""<!doctype html>
281<html lang="en">
282<head>
283<meta charset="utf-8">
284<meta name="viewport" content="width=device-width, initial-scale=1">
285<meta name="referrer" content="no-referrer">
286<title>{_esc(title)}</title>
287<link rel="stylesheet" href="/style">
288<style>{_STYLE}</style>
289</head>
290<body>
291<div class="wrap">
292{body}
293</div>
294</body>
295</html>""",
296 }
297 if status != 200:
298 page["status"] = status
299 return page
300
301
302def _not_found():
303 """One page for every failure: blank token, mistyped token, token for
304 an order that was purged. Saying which would tell somebody probing
305 that they were close.
306 """
307 return _page(
308 '<div class="notfound"><h1>Not found</h1>'
309 '<p class="hint">This tracking link is not valid. It may have been '
310 'mistyped, or copied without its last few characters. Check the link '
311 'in your confirmation email, or contact the shop and they can send '
312 'you a fresh one.</p></div>',
313 title="Not found", status=404)
314
315
316def _business_html(base):
317 """Whatever the operator configured under business.name, and nothing
318 invented when they configured nothing: an unbranded receipt is honest,
319 a fabricated shop name is not.
320 """
321 name = _setting(base, "business.name")
322 return f'<div class="hint">{_esc(name)}</div>' if name else ""
323
324
325def _when(value):
326 """A datetime rendered the way somebody reads a collection time, or
327 "" if it is blank or unparseable.
328
329 Never a raw ISO string on a customer's screen: "2026-07-27T18:00:00"
330 is a machine talking, and the one number this page exists to show a
331 pickup customer is the time they should turn up.
332 """
333 text = _text(value)
334 if not text:
335 return ""
336 try:
337 moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
338 except ValueError:
339 return ""
340 return moment.strftime("%a %d %b, %H:%M")
341
342
343def _status_html(order):
344 raw = _text(order.get("status"))
345 word = CUSTOMER_STATUS.get(raw, FALLBACK_STATUS)
346 # Default is the shipping wording, unchanged for every order that
347 # existed before pickup did -- the overlay only applies when the order
348 # itself says it is being collected.
349 method = _text(order.get("fulfillment_method")) or "shipping"
350 blurb = STATUS_BLURB.get(word, "")
351 if method in PICKUP_METHODS:
352 blurb = PICKUP_BLURB.get(word, blurb)
353 lines = [f'<div class="n">{_esc(word)}</div>']
354 if blurb:
355 lines.append(f'<div class="hint">{_esc(blurb)}</div>')
356 if method in PICKUP_METHODS and raw not in ("collected", "cancelled"):
357 # The promised time, on the one kind of order that has one. A
358 # customer who ordered ahead is not asking "what state is my
359 # order in", they are asking "when do I walk over there".
360 promised = _when(order.get("promised_at"))
361 if promised:
362 lines.append(f'<div class="hint">Ready by {_esc(promised)}</div>')
363 return f'<div class="status">{"".join(lines)}</div>'
364
365
366def _lines_html(order, lines, base):
367 """The receipt itself. Prices included -- see the module docstring."""
368 currency = _text(order.get("currency")) or "USD"
369 total = object_money.format_amount(order.get("total_cents") or 0, currency,
370 base_dir=base)
371 if not lines:
372 # An order whose lines cannot be read still owes the customer the
373 # one number they care about. A "What you ordered" heading over an
374 # empty space reads as "we have lost your order".
375 return (f'<p>Total paid: <strong>{_esc(total)}</strong></p>'
376 '<p class="hint">The itemised list is not available here. '
377 'Your confirmation email has it.</p>')
378 rows = []
379 for line in lines:
380 rows.append(
381 "<tr>"
382 f"<td>{_esc(line.get('description')) or _esc(line.get('product_id'))}</td>"
383 f"<td class=\"num\">{_esc(line.get('quantity')) or '1'}</td>"
384 f"<td class=\"num\">{_esc(object_money.format_amount(line.get('unit_price_cents') or 0, currency, base_dir=base))}</td>"
385 f"<td class=\"num\">{_esc(object_money.format_amount(line.get('line_total_cents') or 0, currency, base_dir=base))}</td>"
386 "</tr>")
387 # The GRAND total, which is what the buyer paid: postage and tax are in
388 # it. Showing the goods subtotal under the word "Total" is how a
389 # receipt ends up disagreeing with a card statement.
390 rows.append('<tr class="total"><td colspan="3">Total</td>'
391 f'<td class="num">{_esc(total)}</td></tr>')
392 return f"""
393<table class="lines">
394<thead><tr><th>Item</th><th class="num">Qty</th>
395<th class="num">Price</th><th class="num">Amount</th></tr></thead>
396<tbody>{''.join(rows)}</tbody>
397</table>"""
398
399
400def _parcels_html(shipments):
401 """Carrier and tracking number when the shipment carries them, and
402 silence when it does not. A "Tracking: (none)" row tells a worried
403 customer nothing except that the shop has a field for it.
404 """
405 blocks = []
406 for shipment in shipments:
407 carrier = _text(shipment.get("carrier"))
408 tracking = _text(shipment.get("tracking_number"))
409 if not carrier and not tracking:
410 continue
411 parts = []
412 if carrier:
413 parts.append(f"<strong>{_esc(carrier)}</strong>")
414 if tracking:
415 parts.append(f"tracking number {_esc(tracking)}")
416 shipped_on = _text(shipment.get("shipped_on"))
417 if shipped_on:
418 parts.append(f"sent {_esc(shipped_on)}")
419 blocks.append(f'<div class="parcel">{" &middot; ".join(parts)}</div>')
420 if not blocks:
421 return ""
422 return "<h2>Your parcel</h2>" + "".join(blocks)
423
424
425def _doors_html(order, invoice, token):
426 """The two links that stay inside this one sale.
427
428 The pay link only appears while money is actually owed: offering "pay
429 now" on an order already paid for is how a shop gets paid twice and
430 spends a fortnight refunding it. The return link only appears once
431 something has physically left, because an order still in the building
432 is changed or cancelled, not returned -- and it carries THIS token, so
433 the guest who never made an account can actually use it.
434 """
435 doors = []
436 if invoice is not None:
437 pay_token = _text(invoice.get("portal_token"))
438 status = _text(invoice.get("status"))
439 if pay_token and status in UNPAID_INVOICE_STATUSES:
440 doors.append(f'<a href="/pay/{_esc(pay_token)}">Pay for this order</a>')
441 if _text(order.get("status")) in RETURNABLE:
442 doors.append(f'<a href="/returns/{_esc(order["id"])}?token={_esc(token)}">'
443 "Start a return</a>")
444 if not doors:
445 return ""
446 return f'<div class="doors">{"".join(doors)}</div>'
447
448
449def GET(request):
450 base = _base_dir()
451 token = _text(request.get("token"))
452 order = _find_order_by_token(base, token)
453 if order is None:
454 return _not_found()
455
456 number = _text(order.get("number")) or order["id"]
457 lines = _lines_for(base, order["id"])
458 shipments = _shipments_for(base, order["id"])
459 invoice = _invoice_for(base, order)
460
461 ordered_on = _text(order.get("order_date"))
462 body = f"""
463<div class="pagehead">
464{_business_html(base)}
465<h1>Order {_esc(number)}</h1>
466<p class="hint">{('Placed ' + _esc(ordered_on)) if ordered_on else 'Thank you for your order'}</p>
467</div>
468{_status_html(order)}
469{_parcels_html(shipments)}
470<h2>What you ordered</h2>
471{_lines_html(order, lines, base)}
472{_doors_html(order, invoice, token)}
473<p class="hint">Keep this link -- it is the only way back to this page, and
474it works for nobody but whoever holds it.</p>
475"""
476 return _page(body, title=f"Order {number}")