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
checkout.py · 73.3 KB · 1540 lines
1"""action_checkout -- a basket becomes an order AND the bill for it.
2
3POST {session_token, customer_email, customer_name?, confirm_prices?,
4 preview?, customer_note?, gift_message?}
5
6This is where browsing turns into a commitment, so it is where every
7check happens at once:
8
9- the products are still for sale,
10- the prices still match what the shopper agreed to,
11- the stock is there.
12
13All of them are reported TOGETHER. Telling somebody about one problem,
14letting them fix it, then revealing the next is how a checkout gets
15abandoned -- and it is the easiest thing in the world to get wrong by
16returning on the first failure.
17
18Price disagreement is a hard stop with both numbers shown, not a silent
19resolution in either direction. Accepting the new price on the shopper's
20behalf is a bait-and-switch; honouring a three-week-old basket forever is
21an open-ended liability. `confirm_prices: true` is the shopper saying yes
22to the current prices, having seen them.
23
24**Stock is checked here and moved nowhere.** The order is created as a
25draft; stock moves and the order confirms when money actually arrives
26(system_shop_fulfillment). Decrementing on checkout would make every
27abandoned payment a phantom sale.
28
29The oversell race is real and is not pretended away: two shoppers can
30both pass this gate for the last unit. That is accepted deliberately at
31this scale -- it surfaces at the stock move, which is visible and
32refundable -- rather than paid for with a reservation ledger nobody has
33needed yet. The same honest posture as hook_wallet_entries' documented
34check-then-append race.
35
36**The invoice is raised here too, already issued.** An order with no
37invoice gives the buyer nothing to pay: the money is owed and there is no
38document saying so and no door to walk through. The invoice is created
39"sent" rather than "draft" because checkout IS the issuing act -- the
40shopper has committed, and a draft would mean somebody in the back office
41must press a button before the person standing at the counter can hand
42over money. The response carries the pay link for the same reason.
43
44**The order's own tracking token is minted here too.** This shop's
45default sale is a guest checkout -- an email address and no account -- so
46this response and the confirmation email are the only two places the
47buyer will ever be handed a way back to their own order. Waiting for
48system_order_portal_link (a post-commit reaction) would mean returning a
49checkout response with no `track_path` in it, which is the one moment the
50link is most obviously wanted. The handler tolerates a token that already
51exists, so minting it early costs nothing and races with nothing.
52
53If the invoice cannot be raised, the ORDER STILL STANDS. Losing a sale to
54an invoicing hiccup is the expensive failure; an order without an invoice
55is visible, and the period biller or an operator can raise one. So only
56the invoice block is wrapped -- never the order.
57
58**Tax and postage are charged here, or the shop is losing money and
59breaking the law.** Four settings say how (all absent = a shop that
60charges neither, which is exactly what it did before):
61
62 shop.tax_rate_bps basis points, 1500 = 15%; 0 = no tax
63 shop.tax_shipping is the postage part of the taxable base?
64 shop.shipping_flat_cents one flat charge; 0 = shipping disabled
65 shop.shipping_free_over_cents free over this basket size; 0 = never
66
67The arithmetic itself is object_cart.checkout_totals and nothing here
68recomputes any part of it -- this file only writes down what that fold
69said. Retrofitting tax later would mean restating invoices that have
70already been sent, which is why a flat honest rate now beats a clever
71one afterwards.
72
73**Postage is an invoice LINE, tax is an invoice TOTAL.** The line is
74because a customer must be able to see what the delivery cost instead of
75finding it welded into a number they cannot check, and because it keeps
76the invoice's subtotal the sum of its own lines. The tax is a total
77because invoices already carry a tax_cents field that means exactly
78this, and inventing a "Sales tax" pseudo-line beside a real field would
79give the same money two homes.
80
81One seam is left open rather than papered over. invoice_totals, if an
82operator ever turns DBBASIC_ENABLE_EVENT_HANDLERS on AND somebody edits
83a line of one of these invoices through the API, restates tax as the sum
84of the lines' own line_tax_cents -- and only the postage line carries
85one, so such a restatement would drop the tax on the goods. Nothing
86this file writes triggers that today (checkout writes through
87object_records directly, which never reaches the dispatcher), and the
88flag is off everywhere. The honest fixes are a decision for whoever owns
89invoice_totals -- either it learns to leave an invoice-level tax alone,
90or every taxable line carries its own rate -- and the second one costs a
91cent of per-line rounding drift, which is exactly the error the single
92rounding above exists to avoid. Written down here so the next person
93finds it before a customer does.
94
95The ORDER records tax_cents and a total_cents that includes both, but
96its subtotal stays goods-only -- so postage on an order is currently
97implied by total - subtotal - tax rather than stated. That is a known
98gap: orders has no shipping_cents column yet. The moment one exists this
99file stamps it (it checks the schema rather than assuming), and until
100then the itemisation lives where a customer actually reads it, on the
101invoice.
102
103**Special instructions and a gift message: two fields, not a subsystem.**
104customer_note is what the shopper needs the PACKER to know ("leave it
105with the neighbour"), gift_message is what should be printed on the slip.
106Both are optional, both are stamped on the cart, and both are stamped on
107the ORDER through the same `_has_field` check shipping_cents uses -- the
108picker and the packer read the order, and a note that lives only on a
109basket is a note nobody in the warehouse ever sees. Until orders declares
110those two columns the values stay on the cart rather than being written
111into a column that does not exist, and the response says so
112(`notes_on_cart_only`) instead of pretending the packer will get them:
113the failure that prevents is a birthday message the shopper typed, the
114shop charged for, and nobody ever printed.
115
116**Per-line instructions travel; per-line deltas travel as MONEY.** A
117basket line may carry `line_note` ("no onions") and `modifier_cents`
118("oat milk +60c"). The note lands on the order line, where the kitchen
119ticket reads it, and touches no total anywhere -- an instruction is not a
120term of the sale. The delta is money, so it is inside every total this
121file writes: object_cart.checkout_totals already folded it into
122line_total_cents, the order line records it alongside the base price, and
123the invoice line carries it in its EFFECTIVE unit price so the bill is
124still an ordinary quantity x price document that multiplies out. Money
125that reaches one total and not another is the failure this whole file is
126arranged to prevent, which is why the delta is never a column sitting
127beside a total that ignores it.
128
129There is deliberately no gift FLAG. The packing slip carries no prices by
130construction (site_packing_slip), so every parcel is already gift-safe,
131and a flag somebody forgets to tick is exactly how a present arrives with
132the amount paid stapled to it. The message is about warmth, not secrecy.
133
134**A collection time is checked here and held by nothing.**
135`fulfillment_method` (shipping | pickup | delivery | counter) and
136`pickup_slot_id` are the two arguments that turn this into a counter
137shop's checkout. When the method is `pickup` the slot must exist, be
138open, be in the future, be past the shop's lead time, and have room --
139and every one of those failures is reported ALONGSIDE the price, stock
140and availability blockers above, in the same response, never returned
141early on its own. That is not a style choice: a shopper told about a
142dead slot, who fixes it, and is then told about a price change is a
143shopper who has abandoned the basket, and this file is arranged the way
144it is precisely to make that impossible.
145
146A SHIPPING ORDER IS UNTOUCHED BY EVERY LINE OF IT. No method, or
147`shipping`, means the gate reads no slots, adds no blockers, and writes
148no new field -- orders.fulfillment_method defaults to `shipping`, so an
149order raised by a shop that has never heard of pickup is byte-for-byte
150the order it was before. That is the regression that matters most here
151and it holds by construction rather than by a condition somebody has to
152remember.
153
154**The race is real and is not pretended away.** Two shoppers can both
155pass this gate for the last place in a 6pm window, exactly as two can
156both pass the stock gate for the last unit, and for the same reason: the
157check is a read, nothing is reserved, and there is no lock. It is
158accepted deliberately at this scale rather than paid for with a
159reservation ledger nobody has needed yet -- the same honest posture
160hook_wallet_entries documents for its own check-then-append. Two things
161make it survivable. The loser finds out BEFORE PAYING, because the gate
162runs before the order and the invoice exist. And the refusal NAMES THE
163NEXT FREE SLOT, because "that time is full" sends somebody away while
164"that time is full, the next one is 18:30" keeps the sale. When the race
165is genuinely lost -- both increments land -- pickup_slots.orders_taken
166comes to exceed capacity, and that is visible on the row it happened to,
167which is what lets a shop ring somebody instead of finding out when they
168turn up.
169
170The bookability rule is duplicated here rather than imported from
171app-pickup's action_pickup_slots, and the duplication is named in both
172files: this package cannot execute another package's object as a
173function, and a checkout that reached across for it would refuse orders
174on a box where the pickup app is installed but its objects are not on
175this root. Both read the same setting (`pickup.lead_minutes`) so the
176picker and the gate cannot disagree about what "too soon" means.
177
178**A DISCOUNT IS A PRICE. A GIFT CARD IS TENDER.** Two arguments arrive
179here that both make a bill smaller, and everything about how they are
180recorded follows from the fact that they are not the same kind of thing.
181
182`promo_code` reduces what the goods COST. It therefore goes through
183object_cart.checkout_totals like every other number on this sale, and it
184comes off the taxable base BEFORE tax is computed -- which is not a
185preference but what every jurisdiction levying a sales or value-added tax
186requires, because tax is owed on the consideration and a seller's own
187price reduction reduces it. On the invoice it is a LINE, negative, so the
188invoice total stays the sum of its own lines and the customer can see
189what came off instead of finding it welded into a number they cannot
190check. The terms are STAMPED on the redemption row at the moment of use
191(doctrine #1), so a promotion edited next month never restates what
192somebody already got, and the arithmetic and the refusals both live in
193object_promotions -- pure, tested without a data directory, the same
194posture object_rates keeps for rate cards.
195
196`gift_card_code` reduces what is OWED. A gift card is money the customer
197already gave this shop, so it changes no price and no taxable base: the
198order's total_cents stays the value of the sale, and the card is applied
199after tax as `amount_due_cents`. Treating it as a discount would let a
200shop sell $100 of goods and remit tax on $60. The debit is written
201against the wallet through the EXISTING hook_wallet_entries gate, ASKED
202IN PROCESS -- a trusted server-side write bypasses hooks by design, which
203is exactly why the gate has to be consulted explicitly rather than
204assumed -- so a card cannot overdraw, and the refusal a customer sees is
205the same sentence that gate gives everybody else. The matching payment is
206an ordinary payments row, because tender is a payment and this shop
207already knows what one of those is.
208
209**A preview writes NOTHING.** No redemption, no wallet debit, no payment,
210no backorder. That is stated here because it is the one property of this
211whole block that a refactor could quietly break: a preview exists so
212somebody can see what they would owe, and a preview that burned a
213single-use code or drained a gift card would be the shop charging people
214for looking. The writes all live below the `preview` return, and the
215`preview` return is above every one of them.
216
217**Out of stock is now three answers, not one** -- see
218object_cart.checkout_blockers. `refuse` (the default, and every product
219that has never heard of the field) blocks exactly as it always has;
220`allow` accepts the line, records a backorders row and marks the order
221line so the warehouse does not send goods that are not there; `notify`
222still refuses but writes down who wanted it. The default is what makes
223this safe: a shop that has configured nothing behaves byte-for-byte as it
224did before.
225
226KNOWN GAP, stated rather than hidden: marking the ORDER LINE backordered
227needs an order_lines column that app-orders does not declare yet, and
228keeping a backordered line out of a shipment needs a condition in
229app-shipping's action_create_shipment / system_order_fulfillment. Neither
230package is this slice's to change. The stamp here is schema-aware (it
231writes the field the day it exists and nothing before), the backorders
232ROW carries the fact in the meantime, and tests/test_reorder.py holds
233both halves as strict xfails -- the same thing tests/test_dropship.py did
234for its two conditions, and for the same reason: a green test over a
235shelf that silently ships is worse than a red one.
236"""
237
238import os
239import secrets
240from datetime import date, datetime, timedelta
241
242import object_cart
243import object_execution
244import object_ids
245import object_promotions
246import object_records
247import object_schemas
248import object_stock
249import python_object_runtime
250
251ACTOR = "action_checkout"
252
253DEFAULT_DUE_DAYS = 14
254
255
256def _base_dir():
257 return os.environ.get("DBBASIC_DATA_DIR", "data")
258
259
260def _text(value):
261 return str(value if value is not None else "").strip()
262
263
264def _truthy(value):
265 return _text(value).lower() in ("true", "1", "yes", "on")
266
267
268def _setting(base, key, default):
269 try:
270 for row in object_records.read_collection_records("app_settings", base_dir=base):
271 if row.get("key") == key and _text(row.get("value")):
272 return _text(row["value"])
273 except Exception:
274 pass
275 return default
276
277
278def _int(value, default=0):
279 try:
280 return int(_text(value) or default)
281 except (TypeError, ValueError):
282 return default
283
284
285def _has_field(base, collection, field):
286 """Does this collection's schema declare `field` yet?
287
288 Asked rather than assumed because orders is due to gain a
289 shipping_cents column and this file wants to fill it the day it
290 appears, without a migration and without writing a field that does
291 not exist into a shop that has not upgraded. Any failure to read the
292 schema answers "no": a missing column costs an itemisation, a
293 rejected write would cost the order.
294 """
295 try:
296 schema = object_schemas.get_schema(collection, base_dir=base)
297 except Exception:
298 return False
299 return any(f.get("name") == field for f in schema.get("fields") or [])
300
301
302def _invoice_description(line):
303 """The line as the payer should read it.
304
305 A latte at 4.00 billed at 4.60 with nothing saying why is the kind of
306 small unexplained difference that turns into a phone call, so a line
307 carrying a delta says so in its own description. Only when there IS
308 one: every existing invoice line reads exactly as it did.
309 """
310 description = _text(line.get("description"))
311 modifier = int(line.get("modifier_cents") or 0)
312 if not modifier:
313 return description
314 return f"{description} (+{modifier / 100:.2f})"
315
316
317def _tax_and_shipping_settings(base):
318 """The four numbers that decide what this sale costs beyond the goods.
319
320 All default to 0/off, so a shop that has configured nothing charges
321 nothing extra and its invoices look exactly as they did yesterday --
322 absent configuration must read as "this shop does not do that", never
323 as a broken tax line.
324 """
325 return {
326 "tax_rate_bps": _int(_setting(base, "shop.tax_rate_bps", 0)),
327 "tax_shipping": _truthy(_setting(base, "shop.tax_shipping", "")),
328 "shipping_flat_cents": _int(_setting(base, "shop.shipping_flat_cents", 0)),
329 "free_over_cents": _int(_setting(base, "shop.shipping_free_over_cents", 0)),
330 }
331
332
333def _pay_path_for_order(base, order_id):
334 """The pay link an already-checked-out order was given, if it has one.
335
336 Everything here is best-effort on purpose: a retry must hand back the
337 SAME door rather than mint a second invoice, but an order whose invoice
338 or token cannot be found is still a perfectly good order. The caller
339 gets no link instead of an error.
340 """
341 try:
342 order = object_records.get_collection_record("orders", order_id, base_dir=base)
343 invoice_id = _text(order.get("invoice_id"))
344 if not invoice_id:
345 return ""
346 invoice = object_records.get_collection_record("invoices", invoice_id,
347 base_dir=base)
348 token = _text(invoice.get("portal_token"))
349 except Exception:
350 return ""
351 return f"/pay/{token}" if token else ""
352
353
354def _track_path_for_order(base, order_id):
355 """The tracking link an already-checked-out order was given.
356
357 Same best-effort posture as _pay_path_for_order, and for the same
358 reason: a shopper who double-clicked must get the SAME door back, and
359 an order whose token cannot be read is still an order.
360 """
361 try:
362 order = object_records.get_collection_record("orders", order_id, base_dir=base)
363 token = _text(order.get("portal_token"))
364 except Exception:
365 return ""
366 return f"/orders/track/{token}" if token else ""
367
368
369def _products(base, product_ids):
370 out = {}
371 for product_id in product_ids:
372 try:
373 row = object_records.get_collection_record(
374 "products", product_id, base_dir=base)
375 except Exception:
376 row = None
377 if row:
378 out[product_id] = row
379 return out
380
381
382def _on_hand(base, products):
383 """Levels for the products this basket touches, and which of them the
384 shop actually tracks.
385
386 A service or a digital download has no stock level, and treating "no
387 level recorded" as "none available" would refuse to sell the things
388 that are always available.
389 """
390 # products.product_type: physical | digital | service | subscription |
391 # asset. Only the first and last are things that sit on a shelf and
392 # can run out; a download or an hour of work never does.
393 tracked = {pid for pid, row in products.items()
394 if _text(row.get("product_type")) in ("physical", "asset", "")}
395 levels = {}
396 for product_id in tracked:
397 try:
398 levels[product_id] = object_stock.total_quantity(
399 product_id, base_dir=base)
400 except Exception:
401 continue
402 return levels, tracked
403
404
405# --- the collection-time gate ------------------------------------------------
406#
407# Everything from here to POST is inert for a shipping order: _pickup_gate
408# returns before it reads anything at all unless the request names a
409# method that is not `shipping`.
410
411FULFILLMENT_METHODS = ("shipping", "pickup", "delivery", "counter")
412
413DEFAULT_LEAD_MINUTES = 30
414
415
416def _moment(value):
417 """An ISO datetime as naive local wall-clock, or None.
418
419 Same normalisation app-pickup's own objects perform, and for the same
420 reason: every time in this repo is the shop's own clock, and comparing
421 one aware value against a naive one raises -- which would turn a
422 single oddly-typed slot into a checkout that refuses everybody.
423 """
424 text = _text(value)
425 if not text:
426 return None
427 try:
428 moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
429 except ValueError:
430 return None
431 if moment.tzinfo is not None:
432 moment = moment.astimezone().replace(tzinfo=None)
433 return moment
434
435
436def _slot_has_room(slot):
437 return _int(slot.get("orders_taken"), 0) < _int(slot.get("capacity"), 0)
438
439
440def _next_free_slot(slots, *, earliest, location, exclude_id=""):
441 """The soonest window somebody could actually be given instead.
442
443 Searched at the SAME location as the one they asked for, because
444 offering a customer a time at the other branch is not an offer. Ties
445 are broken by start time and nothing else -- the next free slot is
446 simply the next one.
447 """
448 candidates = [slot for slot in slots
449 if _text(slot.get("id")) != exclude_id
450 and _truthy(slot.get("is_open") or "true")
451 and _text(slot.get("location_id")) == location
452 and _slot_has_room(slot)]
453 dated = [(moment, slot) for moment, slot in
454 ((_moment(slot.get("starts_at")), slot) for slot in candidates)
455 if moment is not None and moment >= earliest]
456 if not dated:
457 return None
458 dated.sort(key=lambda pair: pair[0])
459 return dated[0][1]
460
461
462def _and_the_next_one(slot):
463 """The half of a refusal that keeps the sale.
464
465 "That time is full" sends somebody away. "That time is full, the next
466 one is 18:30" is the same fact with somewhere to go, and it costs one
467 sentence.
468 """
469 if slot is None:
470 return (" There is no other free collection time on the board -- "
471 "contact the shop.")
472 return f" The next free collection time is {_text(slot.get('starts_at'))}."
473
474
475def _pickup_gate(base, request):
476 """Everything the collection time can be wrong about, gathered at once.
477
478 Returns {method, slot, problems, next_free}. `problems` is a list of
479 sentences, and it is a LIST rather than a first-failure return for
480 exactly the reason the price/stock checks above are: the caller folds
481 it in with theirs and reports the lot together.
482
483 A blank or `shipping` method returns immediately, having read nothing:
484 a shop that does not do pickup must not pay a collection scan per
485 checkout, and more importantly must not be able to acquire a pickup
486 refusal by accident.
487 """
488 method = _text(request.get("fulfillment_method")).lower()
489 empty = {"method": "", "slot": None, "problems": [], "next_free": None}
490 if not method or method == "shipping":
491 return empty
492
493 if method not in FULFILLMENT_METHODS:
494 return {**empty, "method": method,
495 "problems": [f"'{method}' is not a way this shop can fulfil an "
496 f"order. Choose one of: "
497 f"{', '.join(FULFILLMENT_METHODS)}."]}
498
499 if method != "pickup":
500 # delivery and counter are stated facts about how this order is
501 # fulfilled and book nothing: there is no slot board for the van or
502 # the till, and inventing one here would be a rule nobody asked for.
503 return {**empty, "method": method}
504
505 slot_id = _text(request.get("pickup_slot_id"))
506 now = _moment(request.get("now")) or datetime.now()
507 lead = max(0, _int(_setting(base, "pickup.lead_minutes", ""),
508 DEFAULT_LEAD_MINUTES))
509 earliest = now + timedelta(minutes=lead)
510
511 try:
512 slots = object_records.read_collection_records("pickup_slots",
513 base_dir=base)
514 except Exception:
515 # The pickup app is not installed on this box. Refusing is the only
516 # honest answer -- the shopper asked for a collection time and this
517 # shop has no board of them -- and it is a refusal rather than a
518 # silent downgrade to shipping, because quietly posting somebody
519 # their lunch is worse than telling them no.
520 return {**empty, "method": method,
521 "problems": ["This shop is not taking collection orders "
522 "(no pickup slots are configured)."]}
523
524 if not slot_id:
525 free = _next_free_slot(slots, earliest=earliest, location="")
526 return {**empty, "method": method, "next_free": free,
527 "problems": ["Choose a collection time." + _and_the_next_one(free)]}
528
529 slot = next((row for row in slots if _text(row.get("id")) == slot_id), None)
530 if slot is None:
531 free = _next_free_slot(slots, earliest=earliest, location="")
532 return {**empty, "method": method, "next_free": free,
533 "problems": ["That collection time is not on the board any "
534 "more." + _and_the_next_one(free)]}
535
536 location = _text(slot.get("location_id"))
537 problems = []
538 starts = _moment(slot.get("starts_at"))
539
540 if not _truthy(slot.get("is_open") or "true"):
541 problems.append("The shop is not taking orders for that collection "
542 "time.")
543 if starts is None:
544 problems.append("That collection time cannot be read.")
545 elif starts <= now:
546 problems.append(f"That collection time ({_text(slot.get('starts_at'))}) "
547 f"has already passed.")
548 elif starts < earliest:
549 # The one refusal that should be impossible to reach through a
550 # picker, and is checked anyway: action_pickup_slots never OFFERS a
551 # slot inside the lead time, so arriving here means the id was
552 # typed, kept from an old page, or guessed.
553 problems.append(f"That collection time is too soon -- this shop needs "
554 f"{lead} minutes' notice.")
555 if not _slot_has_room(slot):
556 problems.append(f"That collection time is full: it takes "
557 f"{_int(slot.get('capacity'), 0)} orders and "
558 f"{_int(slot.get('orders_taken'), 0)} have been taken.")
559
560 free = None
561 if problems:
562 free = _next_free_slot(slots, earliest=earliest, location=location,
563 exclude_id=slot_id)
564 problems[-1] += _and_the_next_one(free)
565 return {"method": method, "slot": slot, "problems": problems,
566 "next_free": free}
567
568
569# --- the money gates ---------------------------------------------------------
570#
571# Both are inert unless the request names a code, for the same reason
572# _pickup_gate is inert for a shipping order: a shop that runs no
573# promotions and sells no gift cards must not pay a collection scan per
574# checkout, and must not be able to acquire a refusal by accident.
575
576
577def _rows(base, collection):
578 try:
579 return object_records.read_collection_records(collection, base_dir=base)
580 except Exception:
581 return None
582
583
584def _call(object_id, payload, *, method="POST"):
585 """Run another installed object in process -- the same mechanism
586 system_shop_fulfillment uses to reach app-shipping, and
587 action_resolve_dispute uses to reach hook_refunds.
588
589 Returns (result, error). A missing object (the app is simply not
590 installed) is an error string, never an exception.
591 """
592 try:
593 runtime = python_object_runtime.PythonObjectRuntime()
594 outcome = object_execution.execute_object(
595 runtime,
596 object_execution.ObjectExecutionRequest(
597 object_id, method=method, payload=payload))
598 except Exception as exc:
599 return None, str(exc)[:200]
600 if not outcome.ok:
601 message = getattr(outcome.error, "message", "") if outcome.error else ""
602 return None, _text(message)[:200] or f"{object_id} failed"
603 return outcome.result, ""
604
605
606def _promotion_gate(base, request, subtotal_cents, postage_cents, today):
607 """Everything a discount code can be wrong about, gathered at once.
608
609 Returns {code, promo, problems, discount_cents, applies_to}. `problems`
610 is a LIST, from object_promotions.blockers, and it is folded in with
611 the price, stock and collection-time problems below rather than
612 returned on its own -- a shopper told their code expired, who fixes
613 that and is then told the basket is too small, has left.
614
615 No code returns immediately having read nothing.
616 """
617 empty = {"code": "", "promo": None, "problems": [], "discount_cents": 0,
618 "applies_to": "goods"}
619 code = object_promotions.normalize_code(request.get("promo_code"))
620 if not code:
621 return empty
622
623 promotions = _rows(base, "promotions")
624 if promotions is None:
625 # No promotions app on this box. An honest refusal beats silently
626 # ignoring a code the shopper believes they are getting.
627 return {**empty, "code": code,
628 "problems": [f"There is no promotion with the code '{code}'."]}
629 redemptions = _rows(base, "promotion_redemptions")
630 if redemptions is None:
631 # The limits cannot be counted, and a limit that cannot be counted
632 # has not been met. Refusing is the safe direction: a code honoured
633 # once too often is money, a code refused once is an email.
634 return {**empty, "code": code,
635 "problems": ["That code cannot be checked right now (the "
636 "redemption log is unreadable)."]}
637
638 promo = object_promotions.resolve(code, promotions, on_date=today)
639 problems = object_promotions.blockers(
640 promo, subtotal_cents, _text(request.get("customer_email")),
641 redemptions, on_date=today, code=code)
642 if problems:
643 return {**empty, "code": code, "promo": promo, "problems": problems}
644 return {"code": code, "promo": promo, "problems": [],
645 "discount_cents": object_promotions.discount_for(
646 subtotal_cents, postage_cents, promo),
647 "applies_to": object_promotions.applies_to(promo)}
648
649
650def _gift_card_gate(base, request):
651 """The card, its balance, and every reason it cannot be spent.
652
653 Returns {code, wallet, problems, available_cents}. The balance is
654 SUMMED FROM THE ENTRIES rather than read off wallets.balance_minor,
655 for the reason hook_wallet_entries states about its own gate: that
656 number is a rollup, and a decision that leans on a derived value it
657 could recompute is a decision that authorises a debit against money
658 which does not exist the moment the rollup goes stale.
659
660 This only decides how much to OFFER. The authoritative refusal comes
661 from hook_wallet_entries at the moment of the debit, which is asked
662 in process below -- there is exactly one gate on this ledger and it
663 is not this function.
664 """
665 empty = {"code": "", "wallet": None, "problems": [], "available_cents": 0}
666 code = _text(request.get("gift_card_code")).upper()
667 if not code:
668 return empty
669
670 wallets = _rows(base, "wallets")
671 if wallets is None:
672 return {**empty, "code": code,
673 "problems": [f"There is no gift card with the code '{code}' "
674 f"(this shop has no wallets)."]}
675 wallet = next((row for row in wallets
676 if _text(row.get("code")).upper() == code), None)
677 if wallet is None:
678 return {**empty, "code": code,
679 "problems": [f"There is no gift card with the code '{code}'."]}
680
681 problems = []
682 if not _truthy(wallet.get("is_active") or "true"):
683 problems.append(f"The gift card {code} is not active.")
684
685 entries = _rows(base, "wallet_entries")
686 if entries is None:
687 return {**empty, "code": code, "wallet": wallet,
688 "problems": problems + [
689 f"The balance of gift card {code} cannot be read, so it "
690 f"cannot be spent right now."]}
691 balance = sum(_int(row.get("amount_minor"))
692 for row in entries
693 if _text(row.get("wallet_id")) == _text(wallet.get("id")))
694 if balance <= 0:
695 problems.append(f"The gift card {code} has nothing left on it.")
696
697 return {"code": code, "wallet": wallet, "problems": problems,
698 "available_cents": max(0, balance)}
699
700
701def _spend_the_card(base, wallet, amount_cents, *, order_id, invoice_id,
702 today, owner_id):
703 """Debit the wallet and record the tender. Returns (applied, error).
704
705 **THE GATE IS ASKED, NOT ASSUMED.** hook_wallet_entries is the one
706 authority on whether a wallet can afford a debit -- it sums the
707 entries rather than trusting the balance rollup, and it documents its
708 own check-then-append race honestly. A trusted server-side write like
709 this one BYPASSES hooks by design, so the only way to be under that
710 gate is to ask it in process and surface its refusal verbatim, which
711 is exactly what action_resolve_dispute does with hook_refunds. A
712 second opinion written here would be a second ceiling to get wrong,
713 and would quote a customer a different answer depending on which door
714 their spend came through.
715
716 Fails CLOSED: a gate that cannot be consulted has not said yes.
717
718 **The order of the two writes, and the compensation.** The debit is
719 taken first and the payment recorded second, because a payment
720 against an untouched card is the shop giving away goods. If the
721 payment cannot be written the debit is REVERSED by a compensating
722 credit -- the ledger's own correction mechanism, never an edit or a
723 delete, exactly as refunds correct payments and reversing journals
724 correct postings. The customer's balance ends where it started and
725 the checkout says what happened.
726 """
727 wallet_id = _text(wallet.get("id"))
728 entry = {
729 "id": object_ids.new_uuid4(),
730 "wallet_id": wallet_id,
731 # Negative: money leaving. The sign convention is the ledger's.
732 "amount_minor": str(-int(amount_cents)),
733 "kind": "debit",
734 "description": f"Spent at checkout on order {order_id[:8].upper()}",
735 "reference": f"orders/{order_id}",
736 # Provenance, so a replayed checkout finds its own marker instead
737 # of charging the card twice (docs/logic-decisions.md #7).
738 "generated_from": f"checkout/{order_id}",
739 "owner_id": _text(wallet.get("owner_id")) or owner_id,
740 }
741
742 verdict, error = _call("hook_wallet_entries",
743 {"action": "create", "collection": "wallet_entries",
744 "record": entry},
745 method="BEFORE_WRITE")
746 if error:
747 return 0, (f"the wallet gate could not be consulted ({error}), so the "
748 f"gift card was not charged")
749 if isinstance(verdict, dict) and verdict.get("error"):
750 return 0, _text(verdict.get("error"))
751
752 try:
753 object_records.create_collection_record(
754 "wallet_entries", entry, base_dir=base, actor=ACTOR)
755 except Exception as exc:
756 return 0, f"the gift card could not be charged: {str(exc)[:120]}"
757
758 try:
759 object_records.create_collection_record(
760 "payments",
761 {
762 "id": object_ids.new_uuid4(),
763 "invoice_id": invoice_id,
764 "amount_cents": str(int(amount_cents)),
765 # `other` because payments.method has no wallet entry and
766 # app-payments' enum is not this slice's to widen. The
767 # reference names the wallet, so what this was is findable
768 # rather than merely labelled.
769 "method": "other",
770 "received_on": today,
771 "reference": f"wallets/{wallet_id}",
772 "status": "received",
773 "notes": (f"Gift card {_text(wallet.get('code'))} redeemed by "
774 f"{ACTOR} [orders/{order_id}]"),
775 "owner_id": owner_id,
776 },
777 base_dir=base, actor=ACTOR)
778 except Exception as exc:
779 # Put the money back. A compensating entry, never an edit: the
780 # ledger is append-only and a mistaken charge is corrected by a
781 # record that says so.
782 try:
783 object_records.create_collection_record(
784 "wallet_entries",
785 {"id": object_ids.new_uuid4(),
786 "wallet_id": wallet_id,
787 "amount_minor": str(int(amount_cents)),
788 "kind": "adjustment",
789 "description": ("Reversed: the payment against this order "
790 "could not be recorded"),
791 "reference": f"orders/{order_id}",
792 "generated_from": f"checkout_reversal/{order_id}",
793 "owner_id": _text(wallet.get("owner_id")) or owner_id},
794 base_dir=base, actor=ACTOR)
795 except Exception:
796 return int(amount_cents), (
797 f"the gift card was charged but the payment could not be "
798 f"recorded ({str(exc)[:100]}) AND the charge could not be "
799 f"reversed -- this wallet is short and needs a human")
800 return 0, (f"the payment could not be recorded "
801 f"({str(exc)[:120]}); the gift card was charged and the "
802 f"charge has been reversed")
803
804 return int(amount_cents), ""
805
806
807def _record_backorders(base, lines, order_id, line_ids, email, today, cart):
808 """A row per line the shop agreed to owe. Returns what it wrote.
809
810 Best-effort by construction: the sale has already happened by the time
811 this runs, and a backorders collection that is absent (a shop still on
812 app-catalog 0.6) must cost the warehouse a queue entry rather than
813 cost the shopper their order.
814 """
815 if not lines:
816 return []
817 written = []
818 for line in lines:
819 row_id = object_ids.new_uuid4()
820 try:
821 object_records.create_collection_record(
822 "backorders",
823 {"id": row_id,
824 "product_id": line["product_id"],
825 "kind": "backorder",
826 "order_id": order_id,
827 "order_line_id": line_ids.get(line["cart_item_id"], ""),
828 # What was SHORT, not what was ordered: the rest of the
829 # line is ordinary stock that goes out today.
830 "quantity": _text(line.get("short_by")),
831 "customer_email": email,
832 "status": "open",
833 "requested_on": today,
834 "owner_id": _text(cart.get("owner_id"))},
835 base_dir=base, actor=ACTOR)
836 except Exception:
837 continue
838 written.append({"backorder_id": row_id,
839 "product_id": line["product_id"],
840 "description": _text(line.get("description")),
841 "short_by": _text(line.get("short_by"))})
842 return written
843
844
845def _record_notify_interest(base, lines, products, email, today, cart):
846 """Who wanted what the shop just refused to sell them.
847
848 Written on the REFUSAL path, which is the only moment this fact
849 exists. Refusing while remembering beats refusing and forgetting,
850 which is what the shop did before and what loses the same customer
851 twice.
852
853 Needs an address: a record of interest with no way to reach the
854 interested party is a record of nothing, so a checkout with no email
855 writes none and the response says so by simply not listing any.
856
857 Idempotent on (product, email) while a row is still open, so a shopper
858 who presses the button five times is one person waiting, not five.
859 """
860 if not lines or not email:
861 return []
862 existing = _rows(base, "backorders")
863 if existing is None:
864 return []
865 already = {(_text(row.get("product_id")),
866 _text(row.get("customer_email")).lower())
867 for row in existing
868 if _text(row.get("kind")) == "notify"
869 and _text(row.get("status")) == "open"}
870
871 written = []
872 for line in lines:
873 key = (line["product_id"], email.lower())
874 if key in already:
875 continue
876 already.add(key)
877 row_id = object_ids.new_uuid4()
878 try:
879 object_records.create_collection_record(
880 "backorders",
881 {"id": row_id,
882 "product_id": line["product_id"],
883 "kind": "notify",
884 # No order: nothing was sold, which is the whole
885 # distinction between this row and a backorder.
886 "order_id": "",
887 "quantity": _text(line.get("short_by")),
888 "customer_email": email,
889 "status": "open",
890 "requested_on": today,
891 "owner_id": _text(cart.get("owner_id"))},
892 base_dir=base, actor=ACTOR)
893 except Exception:
894 continue
895 written.append({"backorder_id": row_id,
896 "product_id": line["product_id"],
897 "description": _text(line.get("description"))})
898 return written
899
900
901def _slot_refusal(pickup):
902 """The pickup half of a 409, shaped so a storefront can render the next
903 free time as a button rather than parsing it back out of a sentence."""
904 payload = {"pickup_problems": pickup["problems"]}
905 free = pickup.get("next_free")
906 if free is not None:
907 payload["next_free_slot"] = {
908 "id": free["id"],
909 "starts_at": _text(free.get("starts_at")),
910 "ends_at": _text(free.get("ends_at")),
911 "places_left": max(0, _int(free.get("capacity"), 0)
912 - _int(free.get("orders_taken"), 0)),
913 }
914 return payload
915
916
917def POST(request):
918 base = _base_dir()
919 token = _text(request.get("session_token"))
920 if not token:
921 return {"status": 400, "error": "session_token is required"}
922
923 try:
924 carts = object_records.read_collection_records("carts", base_dir=base)
925 except Exception:
926 return {"ok": True, "skipped": "shop not installed (carts absent)"}
927
928 cart = next((c for c in carts if _text(c.get("session_token")) == token
929 and _text(c.get("status")) == "open"), None)
930 if cart is None:
931 settled = next((c for c in carts
932 if _text(c.get("session_token")) == token
933 and _text(c.get("checked_out_order_id"))), None)
934 if settled:
935 # One cart, one order, however many times a browser retries --
936 # and the same pay link back each time, because a shopper who
937 # double-clicked still needs the door, not a second bill.
938 order_id = _text(settled["checked_out_order_id"])
939 duplicate = {"ok": True, "duplicate": True, "order_id": order_id,
940 "note": "this basket has already been checked out"}
941 pay_path = _pay_path_for_order(base, order_id)
942 if pay_path:
943 duplicate["pay_path"] = pay_path
944 track_path = _track_path_for_order(base, order_id)
945 if track_path:
946 duplicate["track_path"] = track_path
947 return duplicate
948 return {"status": 404, "error": "No open basket for this session."}
949
950 try:
951 all_items = object_records.read_collection_records("cart_items", base_dir=base)
952 except Exception:
953 all_items = []
954 items = [i for i in all_items if _text(i.get("cart_id")) == cart["id"]]
955
956 products = _products(base, {_text(i.get("product_id")) for i in items})
957 levels, tracked = _on_hand(base, products)
958 blockers = object_cart.checkout_blockers(items, products, levels, tracked=tracked)
959 # Gathered HERE, beside the price and stock checks, and reported with
960 # them below -- never on its own and never first. For a shipping order
961 # this reads nothing and finds nothing; see _pickup_gate.
962 pickup = _pickup_gate(base, request)
963
964 if blockers["empty"]:
965 return {"status": 400, "error": "There is nothing in this basket.",
966 **(_slot_refusal(pickup) if pickup["problems"] else {})}
967
968 if blockers["price_changes"] and not _truthy(request.get("confirm_prices")):
969 return {"status": 409,
970 "error": "Some prices changed while this basket was open.",
971 "price_changes": blockers["price_changes"],
972 "note": "Show both numbers and send confirm_prices=true once "
973 "the shopper has agreed to the current ones.",
974 **(_slot_refusal(pickup) if pickup["problems"] else {})}
975
976 # Prices confirmed: adopt the live ones so the order records what the
977 # shopper actually agreed to, not the number they first saw. Moved
978 # ABOVE the remaining refusals because the money gates below have to
979 # judge a discount code's minimum spend against the basket the shopper
980 # is actually agreeing to -- a code checked against a stale subtotal is
981 # a code that passes here and fails on the invoice.
982 if blockers["price_changes"] and _truthy(request.get("confirm_prices")):
983 for item in items:
984 product = products.get(_text(item.get("product_id")))
985 if product:
986 item["unit_price_cents"] = str(product.get("price_cents") or 0)
987
988 today = _text(request.get("today")) or date.today().isoformat()
989 charges = _tax_and_shipping_settings(base)
990 email = _text(request.get("customer_email"))
991 # The sale before any code or card touches it. The promotion's minimum
992 # spend is judged on GOODS -- the number a shopper can see on the
993 # basket page and check for themselves -- and the free-postage
994 # threshold on the same pre-discount subtotal, so "free over $50" means
995 # what the banner says rather than what a code left behind.
996 quoted = object_cart.checkout_totals(items, **charges)
997 promo = _promotion_gate(base, request, quoted["subtotal_cents"],
998 quoted["shipping_cents"], today)
999 card = _gift_card_gate(base, request)
1000 money_problems = promo["problems"] + card["problems"]
1001
1002 if (blockers["inactive"] or blockers["unavailable"] or pickup["problems"]
1003 or money_problems):
1004 # One 409 carrying everything wrong with this checkout. The
1005 # sentence changes depending on what is actually broken, because
1006 # "some items cannot be ordered right now" over a perfectly good
1007 # basket whose only problem is a full 6pm slot is a message that
1008 # sends the shopper looking in the wrong place.
1009 #
1010 # The code and the card are refused HERE, beside the stock and the
1011 # slot, and never on their own: a shopper told their code expired,
1012 # who finds another and is then told an item is out of stock, is a
1013 # shopper who has left.
1014 items_wrong = bool(blockers["inactive"] or blockers["unavailable"])
1015 if items_wrong and pickup["problems"]:
1016 error = ("Some items cannot be ordered right now, and the "
1017 "collection time is no longer available.")
1018 elif items_wrong:
1019 error = "Some items cannot be ordered right now."
1020 elif pickup["problems"]:
1021 error = " ".join(pickup["problems"])
1022 else:
1023 error = " ".join(money_problems)
1024 refusal = {"status": 409,
1025 "error": error,
1026 "unavailable": blockers["unavailable"],
1027 "inactive": blockers["inactive"],
1028 **(_slot_refusal(pickup) if pickup["problems"] else {})}
1029 if money_problems:
1030 # Both lists, separately, so a storefront can put each sentence
1031 # under the box it belongs to instead of next to the basket.
1032 refusal["money_problems"] = money_problems
1033 if promo["problems"]:
1034 refusal["promo_problems"] = promo["problems"]
1035 if card["problems"]:
1036 refusal["gift_card_problems"] = card["problems"]
1037 # Somebody wanted something the shop refused to sell them, and the
1038 # seller asked to be told about it (products.backorder_policy =
1039 # notify). Written on the REFUSAL path deliberately: this is the
1040 # only moment the interest exists, and forgetting it is how the
1041 # same customer is lost twice.
1042 #
1043 # Not on a PREVIEW, though. A preview is a look, and the rule that
1044 # a preview writes nothing has to hold on the refusal path too or
1045 # it does not hold at all -- a storefront that quotes the basket
1046 # before submitting it would otherwise file a waiting list entry
1047 # for everybody who glanced at an empty shelf.
1048 if not _truthy(request.get("preview")):
1049 recorded = _record_notify_interest(base, blockers["notify"],
1050 products, email, today, cart)
1051 if recorded:
1052 refusal["interest_recorded"] = recorded
1053 return refusal
1054
1055 summary = object_cart.checkout_totals(
1056 items, **charges,
1057 # A price reduction: off the taxable base, before tax.
1058 discount_cents=promo["discount_cents"],
1059 discount_on=promo["applies_to"],
1060 # Tender: after tax, changing no price and no taxable base.
1061 credit_cents=card["available_cents"])
1062
1063 if _truthy(request.get("preview")):
1064 # The whole breakdown, because a preview exists so somebody can
1065 # see what they are about to owe -- a subtotal alone would hide
1066 # exactly the two numbers this preview was extended to show.
1067 #
1068 # AND IT WRITES NOTHING. No redemption row, no wallet debit, no
1069 # payment, no backorder. A preview that burned a single-use code
1070 # or drained a gift card would be a shop charging people for
1071 # looking, and every write in this object is below this return
1072 # precisely so that stays true.
1073 quote = {"ok": True, "preview": True, "cart_id": cart["id"],
1074 "subtotal_cents": summary["subtotal_cents"],
1075 "shipping_cents": summary["shipping_cents"],
1076 "shipping_free": summary["shipping_free"],
1077 "discount_cents": summary["discount_cents"],
1078 "tax_cents": summary["tax_cents"],
1079 "total_cents": summary["total_cents"],
1080 "credit_applied_cents": summary["credit_applied_cents"],
1081 "amount_due_cents": summary["amount_due_cents"],
1082 "lines": summary["lines"],
1083 "price_changes": blockers["price_changes"]}
1084 if promo["code"]:
1085 quote["promo_code"] = promo["code"]
1086 if card["code"]:
1087 quote["gift_card_code"] = card["code"]
1088 if blockers["backordered"]:
1089 quote["backordered"] = blockers["backordered"]
1090 return quote
1091
1092 if not email:
1093 return {"status": 400,
1094 "error": "An email address is needed to send the receipt to."}
1095
1096 order_id = object_ids.new_uuid4()
1097 # The order's own capability token, minted HERE and not left to
1098 # system_order_portal_link, for exactly the reason the invoice's token
1099 # below is minted here: that handler is a reaction -- post-commit and
1100 # best-effort -- which is right for an order somebody will email about
1101 # later and useless to the shopper standing at the counter now. THIS
1102 # response is what has to carry the door, and the confirmation email
1103 # composed off the very next write needs a token that already exists.
1104 # The handler only mints when a token is absent, so one that already
1105 # exists is something it skips rather than fights over.
1106 track_token = secrets.token_urlsafe(32)
1107 order_row = {
1108 "id": order_id,
1109 "doc_type": "sale",
1110 "number": f"WEB-{order_id[:8].upper()}",
1111 "customer_name": _text(request.get("customer_name")) or email,
1112 "customer_email": email,
1113 "currency": _text(cart.get("currency")) or "USD",
1114 "status": "draft",
1115 "order_date": today,
1116 # Subtotal is goods, per the schema's own definition (the sum of
1117 # the order's lines). Postage is not a line of this order, so it
1118 # cannot be in its subtotal -- it is in the total, which is what
1119 # the buyer owes.
1120 "subtotal_cents": str(summary["subtotal_cents"]),
1121 "tax_cents": str(summary["tax_cents"]),
1122 "total_cents": str(summary["total_cents"]),
1123 "notes": f"Web checkout [carts/{cart['id']}]",
1124 "owner_id": _text(cart.get("owner_id")),
1125 }
1126 if summary["shipping_cents"] and _has_field(base, "orders", "shipping_cents"):
1127 order_row["shipping_cents"] = str(summary["shipping_cents"])
1128
1129 # Same schema-aware posture: a shop still on orders v4 has no
1130 # portal_token column, and writing one would be rejected -- which
1131 # would cost the shopper the ORDER, not just the link. On such a shop
1132 # the response simply carries no track_path, which is honest.
1133 tracks = _has_field(base, "orders", "portal_token")
1134 if tracks:
1135 order_row["portal_token"] = track_token
1136
1137 # The two merchandising fields, on the order the moment orders declares
1138 # them -- see the module docstring. Same schema-aware posture as
1139 # shipping_cents above: a missing column costs the packer a note (which
1140 # the cart still holds and this response still reports), a rejected
1141 # write would cost the shopper their order.
1142 notes = {"customer_note": _text(request.get("customer_note")),
1143 "gift_message": _text(request.get("gift_message"))}
1144 carried_on_cart = []
1145 for field, value in notes.items():
1146 if not value:
1147 continue
1148 if _has_field(base, "orders", field):
1149 order_row[field] = value
1150 else:
1151 carried_on_cart.append(field)
1152
1153 # How this order reaches the customer, and when we said it would be
1154 # ready. Same schema-aware posture as everything above: a shop still on
1155 # orders v6 has none of these columns, and writing one would cost the
1156 # shopper the ORDER rather than the timestamp.
1157 #
1158 # requested_at and promised_at are stamped SEPARATELY and deliberately
1159 # from different places. The promise is the slot's start -- the moment
1160 # the shop committed to, and the moment the customer will walk in. The
1161 # request is what they ASKED for, which is the same thing when they
1162 # simply picked a slot and is genuinely different when a storefront
1163 # passes the time they originally wanted and could not have. Collapsing
1164 # them would erase every "you wanted 6:00, we said 6:20", which is the
1165 # only evidence a shop ever gets that its 6pm is too small.
1166 slot = pickup["slot"]
1167 if pickup["method"] and _has_field(base, "orders", "fulfillment_method"):
1168 order_row["fulfillment_method"] = pickup["method"]
1169 if slot is not None:
1170 promised = _text(slot.get("starts_at"))
1171 requested = _text(request.get("requested_at")) or promised
1172 if _has_field(base, "orders", "promised_at"):
1173 order_row["promised_at"] = promised
1174 if _has_field(base, "orders", "requested_at"):
1175 order_row["requested_at"] = requested
1176 # Which window this order took, in the one place this repo puts
1177 # provenance that has no column of its own -- the same marker
1178 # pattern the invoice below and app-billing's runner both use.
1179 # orders needs no pickup_slot_id field for it: promised_at already
1180 # answers "when", and a second copy of the link would be one more
1181 # thing that can disagree with the slot's own count.
1182 order_row["notes"] = (f"{order_row['notes']} "
1183 f"[pickup_slots/{slot['id']}]")
1184
1185 # portal_token is schema read_only so no client can choose its own; a
1186 # server-side writer passes preserve_read_only, which is exactly the
1187 # narrow escape hatch that flag exists for -- the same call the
1188 # invoice create below already makes.
1189 object_records.create_collection_record(
1190 "orders", order_row, base_dir=base, actor=ACTOR,
1191 preserve_read_only=True)
1192
1193 # The per-line instruction and its delta, carried straight through --
1194 # see the module docstring. Same schema-aware posture as everything
1195 # else here: an app-orders that predates the columns costs the cook a
1196 # note, a rejected write would cost the shopper the order.
1197 line_extras = [field for field in ("line_note", "modifier_cents")
1198 if _has_field(base, "order_lines", field)]
1199 # Which lines the shop agreed to owe rather than to hand over today.
1200 # The MARK belongs on the order line, because the picker and the packer
1201 # read the order and a fact that lives only on a basket is a fact the
1202 # warehouse never sees -- but order_lines does not declare the column
1203 # yet (app-orders is not this slice's to change), so the same
1204 # schema-aware posture every other field here uses applies: it is
1205 # written the day it exists, and until then the backorders ROW below
1206 # carries it. See the module docstring's KNOWN GAP.
1207 backordered_items = {row["cart_item_id"]: row
1208 for row in blockers["backordered"]}
1209 marks_backorders = _has_field(base, "order_lines", "backordered")
1210 line_ids = {}
1211 for line in summary["lines"]:
1212 order_line = {
1213 "id": object_ids.new_uuid4(),
1214 "order_id": order_id,
1215 "product_id": line["product_id"],
1216 "description": line["description"],
1217 "quantity": line["quantity"],
1218 "unit_price_cents": str(line["unit_price_cents"]),
1219 "line_total_cents": str(line["line_total_cents"]),
1220 "owner_id": _text(cart.get("owner_id")),
1221 }
1222 if "line_note" in line_extras:
1223 order_line["line_note"] = _text(line.get("line_note"))
1224 if "modifier_cents" in line_extras:
1225 order_line["modifier_cents"] = str(line.get("modifier_cents") or 0)
1226 if marks_backorders and line["cart_item_id"] in backordered_items:
1227 order_line["backordered"] = "true"
1228 object_records.create_collection_record(
1229 "order_lines", order_line, base_dir=base, actor=ACTOR)
1230 line_ids[line["cart_item_id"]] = order_line["id"]
1231
1232 # The backorders themselves, once the order exists to point at. Written
1233 # here rather than beside the blockers because a row naming an order id
1234 # that was never created would be a queue full of ghosts.
1235 backordered = _record_backorders(base, blockers["backordered"], order_id,
1236 line_ids, email, today, cart)
1237
1238 # The redemption, with the TERMS STAMPED ON IT. Written once the order
1239 # exists, because a redemption naming an order that was never created
1240 # is a used-up code against nothing. Wrapped, because a code that
1241 # cannot be recorded must not cost the shopper the order they just
1242 # placed -- the discount is already in the totals above, and a missing
1243 # redemption row is visible (and its absence undercounts, which is the
1244 # forgiving direction) where a lost order is not.
1245 redemption_id = ""
1246 redemption_error = ""
1247 if promo["promo"] and summary["discount_cents"]:
1248 redemption_id = object_ids.new_uuid4()
1249 try:
1250 object_records.create_collection_record(
1251 "promotion_redemptions",
1252 {
1253 "id": redemption_id,
1254 # Everything object_promotions.terms() hands back is
1255 # the promotion AS IT WAS: kind, value, minimum and
1256 # stacking. Editing the promotion next month therefore
1257 # changes what the next shopper gets and restates
1258 # nothing anybody has already been given (doctrine #1).
1259 **object_promotions.terms(promo["promo"]),
1260 "order_id": order_id,
1261 "customer_email": email,
1262 # The money that actually came off, recorded rather
1263 # than rederivable: a number recomputed later from
1264 # terms that have since moved is exactly the drift the
1265 # stamp exists to prevent.
1266 "discount_cents": str(summary["discount_cents"]),
1267 "redeemed_at": datetime.now().isoformat(timespec="seconds"),
1268 "owner_id": _text(cart.get("owner_id")),
1269 },
1270 base_dir=base, actor=ACTOR)
1271 except Exception as exc:
1272 redemption_id = ""
1273 redemption_error = str(exc)[:200]
1274
1275 # Stamp the cart BEFORE anything else can retry: the stamp is what
1276 # makes a second click a no-op rather than a second order.
1277 stamp = {"status": "checked_out", "checked_out_order_id": order_id,
1278 "customer_email": email,
1279 "customer_name": _text(request.get("customer_name"))}
1280 # Always on the cart, whether or not orders took them: this is where
1281 # the shopper typed them, and it is the only copy that survives a shop
1282 # whose orders schema has not caught up yet.
1283 stamp.update({field: value for field, value in notes.items() if value})
1284 object_records.update_collection_record(
1285 "carts", cart["id"], stamp, base_dir=base, actor=ACTOR)
1286
1287 # The window's own count, incremented once the order exists. Read,
1288 # add one, write -- with no lock, because there is none to take here,
1289 # and this is the exact point at which two shoppers racing for the
1290 # last place both win: each read 3 of 4 and each writes 4, or worse,
1291 # each writes 5. That is the documented, accepted race (see the module
1292 # docstring), and the write is deliberately NOT clamped to capacity:
1293 # clamping would make an oversell invisible, and the whole reason this
1294 # number is stored on the row is so a shop can SEE that it happened
1295 # and ring somebody. Wrapped, because a slot that cannot be counted
1296 # must never cost a shopper the order they have already placed.
1297 if slot is not None:
1298 try:
1299 current = object_records.get_collection_record(
1300 "pickup_slots", slot["id"], base_dir=base)
1301 object_records.update_collection_record(
1302 "pickup_slots", slot["id"],
1303 {"orders_taken": str(_int(current.get("orders_taken"), 0) + 1)},
1304 base_dir=base, actor=ACTOR)
1305 except Exception:
1306 pass
1307
1308 # From here on the sale is already made. Everything below is wrapped so
1309 # that an invoicing problem costs the shopper a pay link, not the order
1310 # they just placed -- see the module docstring.
1311 invoice_id = ""
1312 pay_path = ""
1313 invoice_error = ""
1314 try:
1315 invoice_id = object_ids.new_uuid4()
1316 due_days = _int(_setting(base, "billing.invoice_due_days", DEFAULT_DUE_DAYS),
1317 DEFAULT_DUE_DAYS)
1318 # The token is minted HERE rather than left to
1319 # system_invoice_portal_link. That handler is a reaction --
1320 # post-commit and best-effort -- which is right for an invoice that
1321 # will be emailed, and useless to a shopper standing at the counter
1322 # now: THIS response is what has to carry the door. The handler only
1323 # mints when a token is absent, so a token that already exists is
1324 # something it tolerates rather than fights over.
1325 token = secrets.token_urlsafe(24)
1326 object_records.create_collection_record(
1327 "invoices",
1328 {
1329 "id": invoice_id,
1330 # Same number as the order: one human reference for the
1331 # whole sale, so "WEB-1A2B3C4D" means one thing to the
1332 # shopper, the packer and the bookkeeper alike.
1333 "number": f"WEB-{order_id[:8].upper()}",
1334 "customer_name": _text(request.get("customer_name")) or email,
1335 "customer_email": email,
1336 "currency": _text(cart.get("currency")) or "USD",
1337 "status": "sent",
1338 "issue_date": today,
1339 "due_date": (date.fromisoformat(today)
1340 + timedelta(days=due_days)).isoformat(),
1341 # The invoice's subtotal IS the sum of its own lines --
1342 # goods plus the postage line below -- and its total is
1343 # that plus tax. Exactly the arithmetic the schema
1344 # describes, so invoice_totals restating it one day finds
1345 # the same numbers rather than an argument.
1346 "subtotal_cents": str(summary["subtotal_cents"]
1347 + summary["shipping_cents"]
1348 - summary["discount_cents"]),
1349 "tax_cents": str(summary["tax_cents"]),
1350 "total_cents": str(summary["total_cents"]),
1351 # Provenance in notes, the house pattern: invoices carry no
1352 # generated_from column, so the marker goes where it can be
1353 # found again by anyone asking where this bill came from.
1354 "notes": f"Generated by {ACTOR} [orders/{order_id}]",
1355 "source_order_id": order_id,
1356 "portal_token": token,
1357 "owner_id": _text(cart.get("owner_id")),
1358 },
1359 # portal_token is schema read_only so no client can choose its
1360 # own; a server-side writer passes preserve_read_only, which is
1361 # exactly the narrow escape hatch that flag exists for.
1362 base_dir=base, actor=ACTOR, preserve_read_only=True)
1363
1364 for line in summary["lines"]:
1365 # The invoice line's unit price is the EFFECTIVE one -- the
1366 # catalogue price plus the line's modifier -- so the invoice
1367 # stays an ordinary quantity x price document that adds up
1368 # when anybody, or invoice_totals, multiplies it out. Carrying
1369 # the delta as a separate column here instead would mean the
1370 # one restatement this file already documents (invoice_totals
1371 # recomputing a line) would quietly drop it, and the customer
1372 # would be billed less than the shop is about to make. The
1373 # NOTE is not on the invoice at all: it is an instruction to
1374 # the kitchen, not a term of the sale.
1375 modifier = int(line.get("modifier_cents") or 0)
1376 object_records.create_collection_record(
1377 "invoice_lines",
1378 {
1379 "id": object_ids.new_uuid4(),
1380 "invoice_id": invoice_id,
1381 "description": _invoice_description(line),
1382 "quantity": line["quantity"],
1383 "unit_price_cents": str(line["unit_price_cents"] + modifier),
1384 "line_total_cents": str(line["line_total_cents"]),
1385 "owner_id": _text(cart.get("owner_id")),
1386 },
1387 base_dir=base, actor=ACTOR)
1388
1389 if summary["shipping_cents"]:
1390 # Postage as its own line, only when there is postage to
1391 # charge: a shop that does not post things must not grow a
1392 # "Shipping 0.00" row on every bill.
1393 shipping_line = {
1394 "id": object_ids.new_uuid4(),
1395 "invoice_id": invoice_id,
1396 "description": "Shipping",
1397 "quantity": "1",
1398 "unit_price_cents": str(summary["shipping_cents"]),
1399 "line_total_cents": str(summary["shipping_cents"]),
1400 "owner_id": _text(cart.get("owner_id")),
1401 }
1402 if charges["tax_shipping"] and charges["tax_rate_bps"]:
1403 # Where postage is taxable, the line says so and carries
1404 # its own share -- somebody auditing "was delivery taxed?"
1405 # should find the answer on the line, not have to
1406 # reverse-engineer it out of the invoice total.
1407 shipping_line["tax_rate_bps"] = str(charges["tax_rate_bps"])
1408 shipping_line["line_tax_cents"] = str(object_cart.tax_cents(
1409 summary["shipping_cents"], charges["tax_rate_bps"]))
1410 object_records.create_collection_record(
1411 "invoice_lines", shipping_line, base_dir=base, actor=ACTOR)
1412
1413 if summary["discount_cents"]:
1414 # THE DISCOUNT IS A LINE, and it is negative. Not a field
1415 # beside the total, and not silently baked into the goods
1416 # prices: the invoice's subtotal stays the sum of its own
1417 # lines, so anybody -- a customer, an accountant,
1418 # invoice_totals recomputing it one day -- adds the rows up
1419 # and gets the number printed at the bottom. Baking it into
1420 # the unit prices instead would leave a bill nobody can
1421 # reconcile against the code the shopper was given, and a
1422 # field beside the total would be money with two homes.
1423 #
1424 # It names the CODE, because "Discount -6.00" invites the
1425 # phone call that "Discount (SPRING20) -6.00" answers.
1426 object_records.create_collection_record(
1427 "invoice_lines",
1428 {
1429 "id": object_ids.new_uuid4(),
1430 "invoice_id": invoice_id,
1431 "description": (f"Discount ({promo['code']})"
1432 if promo["code"] else "Discount"),
1433 "quantity": "1",
1434 "unit_price_cents": str(-summary["discount_cents"]),
1435 "line_total_cents": str(-summary["discount_cents"]),
1436 "owner_id": _text(cart.get("owner_id")),
1437 },
1438 base_dir=base, actor=ACTOR)
1439
1440 # The stamp is the join system_shop_fulfillment walks backwards:
1441 # a payment knows its invoice, and this is the only thing that says
1442 # which order that invoice was for.
1443 object_records.update_collection_record(
1444 "orders", order_id, {"invoice_id": invoice_id},
1445 base_dir=base, actor=ACTOR)
1446 pay_path = f"/pay/{token}"
1447 except Exception as exc:
1448 invoice_error = str(exc)[:200]
1449
1450 # The card is spent LAST, and only against a bill that exists. Tender
1451 # applied to nothing is money taken off a customer for an invoice
1452 # nobody raised, so an invoicing failure above means the balance stays
1453 # where it is and the shopper is told why.
1454 card_applied = 0
1455 card_error = ""
1456 if card["wallet"] and summary["credit_applied_cents"] and invoice_id:
1457 card_applied, card_error = _spend_the_card(
1458 base, card["wallet"], summary["credit_applied_cents"],
1459 order_id=order_id, invoice_id=invoice_id, today=today,
1460 owner_id=_text(cart.get("owner_id")))
1461 if card["wallet"] and summary["credit_applied_cents"] and not invoice_id:
1462 card_error = ("the invoice could not be raised, so the gift card was "
1463 "not charged; its balance is untouched")
1464 if card_error and not card_applied:
1465 # The card did not pay, so the customer owes the whole bill. Say so
1466 # in the totals rather than only in a warning nobody parses.
1467 summary = {**summary, "credit_applied_cents": 0,
1468 "amount_due_cents": summary["total_cents"]}
1469
1470 # total_cents is the GRAND total: what the payer owes, including
1471 # postage and tax. A response whose "total" was the goods subtotal
1472 # would be the number a payment gets built from, and the shop would
1473 # quietly collect the wrong amount.
1474 result = {"ok": True, "order_id": order_id, "cart_id": cart["id"],
1475 "subtotal_cents": summary["subtotal_cents"],
1476 "shipping_cents": summary["shipping_cents"],
1477 "shipping_free": summary["shipping_free"],
1478 "discount_cents": summary["discount_cents"],
1479 "tax_cents": summary["tax_cents"],
1480 "total_cents": summary["total_cents"],
1481 "credit_applied_cents": summary["credit_applied_cents"],
1482 "amount_due_cents": summary["amount_due_cents"],
1483 "lines": len(summary["lines"]),
1484 "status_of_order": "draft",
1485 "note": "order raised; stock moves and the order confirms when "
1486 "payment arrives"}
1487 if promo["code"]:
1488 result["promo_code"] = promo["code"]
1489 if redemption_id:
1490 result["redemption_id"] = redemption_id
1491 if redemption_error:
1492 # Reported, never swallowed: the discount was given and the
1493 # count of it did not land, so a limit is now one use looser
1494 # than the shop thinks and somebody has to know.
1495 result["redemption_error"] = redemption_error
1496 if card["code"]:
1497 result["gift_card_code"] = card["code"]
1498 result["gift_card_applied_cents"] = card_applied
1499 if card_error:
1500 result["gift_card_error"] = card_error
1501 if backordered:
1502 # Named in the response because the shopper has just bought
1503 # something that is not in the building, and a confirmation that
1504 # did not say so is how a parcel becomes a complaint.
1505 result["backordered"] = backordered
1506 result["note"] = ("order raised; some lines are backordered and ship "
1507 "when stock arrives. Stock moves and the order "
1508 "confirms when payment arrives")
1509 if pickup["method"]:
1510 # Only on an order that actually chose a method. A shipping
1511 # checkout's response is exactly the dict it was before pickup
1512 # existed -- no empty "fulfillment_method": "shipping" key, no
1513 # blank promised_at -- because a caller that has never sent these
1514 # arguments must not have to learn them.
1515 result["fulfillment_method"] = pickup["method"]
1516 if slot is not None:
1517 result["pickup_slot_id"] = slot["id"]
1518 result["promised_at"] = _text(slot.get("starts_at"))
1519 if tracks:
1520 # The customer's own door, alongside the pay link and for the same
1521 # reason: this shop sells to guests, so the response and the
1522 # confirmation email are the only two places the buyer will ever
1523 # be handed a way back to their own order.
1524 result["track_path"] = f"/orders/track/{track_token}"
1525 if carried_on_cart:
1526 # Reported, not swallowed. Somebody has to know that what the
1527 # shopper typed did not reach the order the packer will read.
1528 result["notes_on_cart_only"] = carried_on_cart
1529 if invoice_error:
1530 # Say what went wrong rather than returning a cheerful ok: somebody
1531 # has to raise this bill, and they can only do that if the failure
1532 # was reported instead of swallowed.
1533 result["invoice_error"] = invoice_error
1534 result["note"] = ("order raised, but the invoice could not be: "
1535 f"{invoice_error}. The order stands and the invoice "
1536 "can be raised again.")
1537 else:
1538 result["invoice_id"] = invoice_id
1539 result["pay_path"] = pay_path
1540 return result