askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
checkout.py · 102.8 KB · 2075 lines
| 1 | """action_checkout -- a basket becomes an order AND the bill for it. |
| 2 | |
| 3 | POST {session_token, customer_email, customer_name?, confirm_prices?, |
| 4 | preview?, customer_note?, gift_message?, fulfillment_method?, |
| 5 | pickup_slot_id?, pay_at_pickup?, promo_code?, gift_card_code?} |
| 6 | |
| 7 | This is where browsing turns into a commitment, so it is where every |
| 8 | check happens at once: |
| 9 | |
| 10 | - the products are still for sale, |
| 11 | - the prices still match what the shopper agreed to, |
| 12 | - the stock is there. |
| 13 | |
| 14 | All of them are reported TOGETHER. Telling somebody about one problem, |
| 15 | letting them fix it, then revealing the next is how a checkout gets |
| 16 | abandoned -- and it is the easiest thing in the world to get wrong by |
| 17 | returning on the first failure. |
| 18 | |
| 19 | Price disagreement is a hard stop with both numbers shown, not a silent |
| 20 | resolution in either direction. Accepting the new price on the shopper's |
| 21 | behalf is a bait-and-switch; honouring a three-week-old basket forever is |
| 22 | an open-ended liability. `confirm_prices: true` is the shopper saying yes |
| 23 | to the current prices, having seen them. |
| 24 | |
| 25 | **Stock is HELD here and moved nowhere.** The order is created as a |
| 26 | draft; stock moves and the order confirms when money actually arrives |
| 27 | (system_shop_fulfillment). Decrementing on checkout would make every |
| 28 | abandoned payment a phantom sale -- but checking against on hand alone, |
| 29 | which is what this did until 2026-11-30, made every unpaid order |
| 30 | invisible to the next one: a simulated race sold one unit to two orders |
| 31 | and three to ten, and sequential checkouts did the same. The owner's |
| 32 | decision: "if i order online and drive to the damn store i expect it to |
| 33 | still be there when i arrive". So the order RESERVES (orders.reserves_stock): |
| 34 | the gate judges a basket by what is AVAILABLE -- on hand less what live |
| 35 | online orders hold (object_reservations) -- and the order's lines are the |
| 36 | hold. A hold becomes the stock move when the goods leave, ends when the |
| 37 | order is cancelled, and an unpaid one lapses (object_pickup.hold_lapsed): |
| 38 | after pickup.hold_minutes for a shopper paying online, at the end of the |
| 39 | window plus pickup.grace_minutes for one paying at pickup. |
| 40 | |
| 41 | The race is CLOSED for stock, not pretended away. The gate is a read and |
| 42 | two shoppers can both pass it for the last unit; what stops the second is |
| 43 | the locked check on order_lines (app-orders system_stock_hold), which |
| 44 | object_records runs under the "stock" lock for every writer, so the |
| 45 | second line sees the first. When it refuses, this object deletes the |
| 46 | half-written order, releases the cart and answers 409 with what is left |
| 47 | -- before any invoice, redemption, card debit or slot count exists. |
| 48 | |
| 49 | **The invoice is raised here too, already issued.** An order with no |
| 50 | invoice gives the buyer nothing to pay: the money is owed and there is no |
| 51 | document saying so and no door to walk through. The invoice is created |
| 52 | "sent" rather than "draft" because checkout IS the issuing act -- the |
| 53 | shopper has committed, and a draft would mean somebody in the back office |
| 54 | must press a button before the person standing at the counter can hand |
| 55 | over money. The response carries the pay link for the same reason. |
| 56 | |
| 57 | **The order's own tracking token is minted here too.** This shop's |
| 58 | default sale is a guest checkout -- an email address and no account -- so |
| 59 | this response and the confirmation email are the only two places the |
| 60 | buyer will ever be handed a way back to their own order. Waiting for |
| 61 | system_order_portal_link (a post-commit reaction) would mean returning a |
| 62 | checkout response with no `track_path` in it, which is the one moment the |
| 63 | link is most obviously wanted. The handler tolerates a token that already |
| 64 | exists, so minting it early costs nothing and races with nothing. |
| 65 | |
| 66 | If the invoice cannot be raised, the ORDER STILL STANDS. Losing a sale to |
| 67 | an invoicing hiccup is the expensive failure; an order without an invoice |
| 68 | is visible, and the period biller or an operator can raise one. So only |
| 69 | the invoice block is wrapped -- never the order. |
| 70 | |
| 71 | **Tax and postage are charged here, or the shop is losing money and |
| 72 | breaking the law.** Four settings say how (all absent = a shop that |
| 73 | charges neither, which is exactly what it did before): |
| 74 | |
| 75 | shop.tax_rate_bps basis points, 1500 = 15%; 0 = no tax |
| 76 | shop.tax_shipping is the postage part of the taxable base? |
| 77 | shop.shipping_flat_cents one flat charge; 0 = shipping disabled |
| 78 | shop.shipping_free_over_cents free over this basket size; 0 = never |
| 79 | |
| 80 | The arithmetic itself is object_cart.checkout_totals and nothing here |
| 81 | recomputes any part of it -- this file only writes down what that fold |
| 82 | said. Retrofitting tax later would mean restating invoices that have |
| 83 | already been sent, which is why a flat honest rate now beats a clever |
| 84 | one afterwards. |
| 85 | |
| 86 | **Postage is an invoice LINE, tax is an invoice TOTAL.** The line is |
| 87 | because a customer must be able to see what the delivery cost instead of |
| 88 | finding it welded into a number they cannot check, and because it keeps |
| 89 | the invoice's subtotal the sum of its own lines. The tax is a total |
| 90 | because invoices already carry a tax_cents field that means exactly |
| 91 | this, and inventing a "Sales tax" pseudo-line beside a real field would |
| 92 | give the same money two homes. |
| 93 | |
| 94 | The seam that used to be written down here is closed (decision 2, the |
| 95 | owner's, 2026-11-30). invoice_totals restated a checkout invoice's tax as |
| 96 | the sum of its lines' line_tax_cents, and only the postage line carried |
| 97 | one, so an edited line dropped the tax on the goods (finding M1). Now |
| 98 | EVERY taxable line is stamped with the rate and its share of the tax -- |
| 99 | computed once over the taxable sale and shared out by |
| 100 | object_lines.allocate_tax, the odd cent to the line with the largest |
| 101 | remainder, so the shares add up to exactly the single rounding above and |
| 102 | no cent drifts -- and invoice_totals no longer folds an issued invoice at |
| 103 | all. A discount line carries the rate of what it discounts. |
| 104 | The ORDER records tax_cents, the postage (shipping_cents) and the basket |
| 105 | discount (discount_cents, orders v14), and a total_cents that is subtotal - |
| 106 | discount + shipping + tax; its subtotal stays goods-only. Neither postage |
| 107 | nor the discount is an order line, which is why they are stored: the |
| 108 | order's fold (order_totals) cannot see them otherwise, and used to restate |
| 109 | the order to its goods plus tax (finding M2). Both are stamped through the |
| 110 | schema check, so a shop on an older orders schema still checks out. |
| 111 | invoice. |
| 112 | |
| 113 | **Special instructions and a gift message: two fields, not a subsystem.** |
| 114 | customer_note is what the shopper needs the PACKER to know ("leave it |
| 115 | with the neighbour"), gift_message is what should be printed on the slip. |
| 116 | Both are optional, both are stamped on the cart, and both are stamped on |
| 117 | the ORDER through the same `_has_field` check shipping_cents uses -- the |
| 118 | picker and the packer read the order, and a note that lives only on a |
| 119 | basket is a note nobody in the warehouse ever sees. Until orders declares |
| 120 | those two columns the values stay on the cart rather than being written |
| 121 | into a column that does not exist, and the response says so |
| 122 | (`notes_on_cart_only`) instead of pretending the packer will get them: |
| 123 | the failure that prevents is a birthday message the shopper typed, the |
| 124 | shop charged for, and nobody ever printed. |
| 125 | |
| 126 | **Per-line instructions travel; per-line deltas travel as MONEY.** A |
| 127 | basket line may carry `line_note` ("no onions") and `modifier_cents` |
| 128 | ("oat milk +60c"). The note lands on the order line, where the kitchen |
| 129 | ticket reads it, and touches no total anywhere -- an instruction is not a |
| 130 | term of the sale. The delta is money, so it is inside every total this |
| 131 | file writes: object_cart.checkout_totals already folded it into |
| 132 | line_total_cents, the order line records it alongside the base price, and |
| 133 | the invoice line carries it in its EFFECTIVE unit price so the bill is |
| 134 | still an ordinary quantity x price document that multiplies out. Money |
| 135 | that reaches one total and not another is the failure this whole file is |
| 136 | arranged to prevent, which is why the delta is never a column sitting |
| 137 | beside a total that ignores it. |
| 138 | |
| 139 | **What an extra costs is the shop's, here as in the basket.** A line's |
| 140 | modifier_cents is stamped by action_cart from the prices the product |
| 141 | declares (products.modifiers) for the extras the line names; this file |
| 142 | re-checks it against the live list exactly as it re-checks the unit price |
| 143 | (object_cart.line_money_problems, folded into checkout_blockers). A changed |
| 144 | extra is a price change the shopper confirms; a delta with no declared |
| 145 | extra behind it -- a basket priced by its client before that was refused |
| 146 | -- is a line that cannot be sold. The extras' NAMES go on the order line's |
| 147 | note and the invoice line's description, so the cook makes what was paid |
| 148 | for and the payer can see what the difference was. |
| 149 | |
| 150 | **The clock is the server's.** `today` decides whether a promotion has |
| 151 | started or ended; `now` (below) decides whether a collection time is too |
| 152 | soon. Both used to be read from the request -- and this object is public, |
| 153 | so `today: "2020-07-01"` redeemed a code that ended in 2020. They are |
| 154 | honoured only from an in-process caller (no `_identity`, which the server |
| 155 | sets on every HTTP execution and a client cannot remove), which is how the |
| 156 | tests and the daemon pin a date; a request that came over HTTP gets the |
| 157 | real one. |
| 158 | |
| 159 | There is deliberately no gift FLAG. The packing slip carries no prices by |
| 160 | construction (site_packing_slip), so every parcel is already gift-safe, |
| 161 | and a flag somebody forgets to tick is exactly how a present arrives with |
| 162 | the amount paid stapled to it. The message is about warmth, not secrecy. |
| 163 | |
| 164 | **A collection time is checked here and held by nothing.** |
| 165 | `fulfillment_method` (shipping | pickup | delivery | counter) and |
| 166 | `pickup_slot_id` are the two arguments that turn this into a counter |
| 167 | shop's checkout. When the method is `pickup` the slot must exist, be |
| 168 | open, be in the future, be past the shop's lead time, and have room -- |
| 169 | and every one of those failures is reported ALONGSIDE the price, stock |
| 170 | and availability blockers above, in the same response, never returned |
| 171 | early on its own. That is not a style choice: a shopper told about a |
| 172 | dead slot, who fixes it, and is then told about a price change is a |
| 173 | shopper who has abandoned the basket, and this file is arranged the way |
| 174 | it is precisely to make that impossible. |
| 175 | |
| 176 | A SHIPPING ORDER IS UNTOUCHED BY EVERY LINE OF IT. No method, or |
| 177 | `shipping`, means the gate reads no slots, adds no blockers, and writes |
| 178 | no new field -- orders.fulfillment_method defaults to `shipping`, so an |
| 179 | order raised by a shop that has never heard of pickup is byte-for-byte |
| 180 | the order it was before. That is the regression that matters most here |
| 181 | and it holds by construction rather than by a condition somebody has to |
| 182 | remember. |
| 183 | |
| 184 | **An unpaid booking's hold lapses.** orders_taken is a counter checkout |
| 185 | adds one to, and nothing took one off, so a shopper who checked out and |
| 186 | never paid held their window forever -- one unpaid order filled a café's |
| 187 | 6pm. The gate (and the picker, and the next-free suggestion) now judge a |
| 188 | window by object_pickup's live count: the counter less the bookings whose |
| 189 | order is cancelled, or is still an unpaid draft raised more than |
| 190 | `pickup.hold_minutes` ago (default 30; 0 = holds never lapse). The counter |
| 191 | itself is not written; see object_pickup for why this is a derived count |
| 192 | and not a daemon sweeper, and what it costs. `pay_at_pickup: true` (a |
| 193 | pickup order, in a shop that sets pickup.pay_at_pickup) is the exception: |
| 194 | that shopper is not meant to have paid, so their place and their goods |
| 195 | are held until the window ends plus pickup.grace_minutes. |
| 196 | |
| 197 | **The race is real and is not pretended away.** Two shoppers can both |
| 198 | pass this gate for the last place in a 6pm window (the stock gate used |
| 199 | to share this race; the locked check above closed it for goods, not for |
| 200 | places): the check is a read and there is no lock. It is |
| 201 | accepted deliberately at this scale rather than paid for with a |
| 202 | reservation ledger nobody has needed yet -- the same honest posture |
| 203 | hook_wallet_entries documents for its own check-then-append. Two things |
| 204 | make it survivable. The loser finds out BEFORE PAYING, because the gate |
| 205 | runs before the order and the invoice exist. And the refusal NAMES THE |
| 206 | NEXT FREE SLOT, because "that time is full" sends somebody away while |
| 207 | "that time is full, the next one is 18:30" keeps the sale. When the race |
| 208 | is genuinely lost -- both increments land -- pickup_slots.orders_taken |
| 209 | comes to exceed capacity, and that is visible on the row it happened to, |
| 210 | which is what lets a shop ring somebody instead of finding out when they |
| 211 | turn up. |
| 212 | |
| 213 | The bookability rule is duplicated here rather than imported from |
| 214 | app-pickup's action_pickup_slots, and the duplication is named in both |
| 215 | files: this package cannot execute another package's object as a |
| 216 | function, and a checkout that reached across for it would refuse orders |
| 217 | on a box where the pickup app is installed but its objects are not on |
| 218 | this root. Both read the same setting (`pickup.lead_minutes`) so the |
| 219 | picker and the gate cannot disagree about what "too soon" means. |
| 220 | |
| 221 | **A DISCOUNT IS A PRICE. A GIFT CARD IS TENDER.** Two arguments arrive |
| 222 | here that both make a bill smaller, and everything about how they are |
| 223 | recorded follows from the fact that they are not the same kind of thing. |
| 224 | |
| 225 | `promo_code` reduces what the goods COST. It therefore goes through |
| 226 | object_cart.checkout_totals like every other number on this sale, and it |
| 227 | comes off the taxable base BEFORE tax is computed -- which is not a |
| 228 | preference but what every jurisdiction levying a sales or value-added tax |
| 229 | requires, because tax is owed on the consideration and a seller's own |
| 230 | price reduction reduces it. On the invoice it is a LINE, negative, so the |
| 231 | invoice total stays the sum of its own lines and the customer can see |
| 232 | what came off instead of finding it welded into a number they cannot |
| 233 | check. The terms are STAMPED on the redemption row at the moment of use |
| 234 | (doctrine #1), so a promotion edited next month never restates what |
| 235 | somebody already got, and the arithmetic and the refusals both live in |
| 236 | object_promotions -- pure, tested without a data directory, the same |
| 237 | posture object_rates keeps for rate cards. |
| 238 | |
| 239 | `gift_card_code` reduces what is OWED. A gift card is money the customer |
| 240 | already gave this shop, so it changes no price and no taxable base: the |
| 241 | order's total_cents stays the value of the sale, and the card is applied |
| 242 | after tax as `amount_due_cents`. Treating it as a discount would let a |
| 243 | shop sell $100 of goods and remit tax on $60. The debit is written |
| 244 | against the wallet through the EXISTING hook_wallet_entries gate, ASKED |
| 245 | IN PROCESS -- a trusted server-side write bypasses hooks by design, which |
| 246 | is exactly why the gate has to be consulted explicitly rather than |
| 247 | assumed -- so a card cannot overdraw, and the refusal a customer sees is |
| 248 | the same sentence that gate gives everybody else. The matching payment is |
| 249 | an ordinary payments row, because tender is a payment and this shop |
| 250 | already knows what one of those is. |
| 251 | |
| 252 | **A preview writes NOTHING.** No redemption, no wallet debit, no payment, |
| 253 | no backorder. That is stated here because it is the one property of this |
| 254 | whole block that a refactor could quietly break: a preview exists so |
| 255 | somebody can see what they would owe, and a preview that burned a |
| 256 | single-use code or drained a gift card would be the shop charging people |
| 257 | for looking. The writes all live below the `preview` return, and the |
| 258 | `preview` return is above every one of them. |
| 259 | |
| 260 | **Out of stock is now three answers, not one** -- see |
| 261 | object_cart.checkout_blockers. `refuse` (the default, and every product |
| 262 | that has never heard of the field) blocks exactly as it always has; |
| 263 | `allow` accepts the line, records a backorders row and marks the order |
| 264 | line so the warehouse does not send goods that are not there; `notify` |
| 265 | still refuses but writes down who wanted it. The default is what makes |
| 266 | this safe: a shop that has configured nothing behaves byte-for-byte as it |
| 267 | did before. |
| 268 | |
| 269 | KNOWN GAP, stated rather than hidden: marking the ORDER LINE backordered |
| 270 | needs an order_lines column that app-orders does not declare yet, and |
| 271 | keeping a backordered line out of a shipment needs a condition in |
| 272 | app-shipping's action_create_shipment / system_order_fulfillment. Neither |
| 273 | package is this slice's to change. The stamp here is schema-aware (it |
| 274 | writes the field the day it exists and nothing before), the backorders |
| 275 | ROW carries the fact in the meantime, and tests/test_reorder.py holds |
| 276 | both halves as strict xfails -- the same thing tests/test_dropship.py did |
| 277 | for its two conditions, and for the same reason: a green test over a |
| 278 | shelf that silently ships is worse than a red one. |
| 279 | """ |
| 280 | |
| 281 | import os |
| 282 | import secrets |
| 283 | from datetime import date, datetime, timedelta |
| 284 | |
| 285 | import object_cart |
| 286 | import object_collections |
| 287 | import object_execution |
| 288 | import object_ids |
| 289 | import object_lines |
| 290 | import object_pickup |
| 291 | import object_promotions |
| 292 | import object_records |
| 293 | import object_reservations |
| 294 | import object_schemas |
| 295 | import object_stock |
| 296 | import object_wallet |
| 297 | import python_object_runtime |
| 298 | |
| 299 | ACTOR = "action_checkout" |
| 300 | |
| 301 | DEFAULT_DUE_DAYS = 14 |
| 302 | |
| 303 | |
| 304 | def _base_dir(): |
| 305 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 306 | |
| 307 | |
| 308 | def _text(value): |
| 309 | return str(value if value is not None else "").strip() |
| 310 | |
| 311 | |
| 312 | def _truthy(value): |
| 313 | return _text(value).lower() in ("true", "1", "yes", "on") |
| 314 | |
| 315 | |
| 316 | def _setting(base, key, default): |
| 317 | try: |
| 318 | # access: box configuration |
| 319 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 320 | if row.get("key") == key and _text(row.get("value")): |
| 321 | return _text(row["value"]) |
| 322 | except Exception: |
| 323 | pass |
| 324 | return default |
| 325 | |
| 326 | |
| 327 | def _int(value, default=0): |
| 328 | try: |
| 329 | return int(_text(value) or default) |
| 330 | except (TypeError, ValueError): |
| 331 | return default |
| 332 | |
| 333 | |
| 334 | def _has_field(base, collection, field): |
| 335 | """Does this collection's schema declare `field` yet? |
| 336 | |
| 337 | Asked rather than assumed because orders is due to gain a |
| 338 | shipping_cents column and this file wants to fill it the day it |
| 339 | appears, without a migration and without writing a field that does |
| 340 | not exist into a shop that has not upgraded. Any failure to read the |
| 341 | schema answers "no": a missing column costs an itemisation, a |
| 342 | rejected write would cost the order. |
| 343 | """ |
| 344 | try: |
| 345 | schema = object_schemas.get_schema(collection, base_dir=base) |
| 346 | except Exception: |
| 347 | return False |
| 348 | return any(f.get("name") == field for f in schema.get("fields") or []) |
| 349 | |
| 350 | |
| 351 | def _invoice_description(line, extras=()): |
| 352 | """The line as the payer should read it. |
| 353 | |
| 354 | A latte at 4.00 billed at 4.60 with nothing saying why is the kind of |
| 355 | small unexplained difference that turns into a phone call, so a line |
| 356 | carrying a delta says so in its own description -- and names the |
| 357 | extras it paid for when the line says which. Only when there IS one: |
| 358 | every existing invoice line reads exactly as it did. |
| 359 | """ |
| 360 | description = _text(line.get("description")) |
| 361 | modifier = int(line.get("modifier_cents") or 0) |
| 362 | if not modifier: |
| 363 | return description |
| 364 | named = ", ".join(extras) |
| 365 | return f"{description} ({named + ' ' if named else ''}+{modifier / 100:.2f})" |
| 366 | |
| 367 | |
| 368 | def _kitchen_note(line, extras): |
| 369 | """What the cook reads on the order line: the extras that were paid |
| 370 | for, then whatever the shopper typed. The extras first, because they |
| 371 | are what the money says was ordered; a line with none reads exactly as |
| 372 | it did.""" |
| 373 | note = _text(line.get("line_note")) |
| 374 | if not extras: |
| 375 | return note |
| 376 | return "; ".join([*extras, note] if note else extras) |
| 377 | |
| 378 | |
| 379 | def _in_process(request): |
| 380 | """Is this call from server code rather than over HTTP? |
| 381 | |
| 382 | The server puts `_identity` on every HTTP execution, overwriting |
| 383 | whatever the body said, so its absence means an in-process caller -- |
| 384 | a test, the daemon, another object. Only those may pin the clock; see |
| 385 | the module docstring. |
| 386 | """ |
| 387 | return "_identity" not in request |
| 388 | |
| 389 | |
| 390 | def _tax_and_shipping_settings(base): |
| 391 | """The four numbers that decide what this sale costs beyond the goods. |
| 392 | |
| 393 | All default to 0/off, so a shop that has configured nothing charges |
| 394 | nothing extra and its invoices look exactly as they did yesterday -- |
| 395 | absent configuration must read as "this shop does not do that", never |
| 396 | as a broken tax line. |
| 397 | """ |
| 398 | return { |
| 399 | "tax_rate_bps": _int(_setting(base, "shop.tax_rate_bps", 0)), |
| 400 | "tax_shipping": _truthy(_setting(base, "shop.tax_shipping", "")), |
| 401 | "shipping_flat_cents": _int(_setting(base, "shop.shipping_flat_cents", 0)), |
| 402 | "free_over_cents": _int(_setting(base, "shop.shipping_free_over_cents", 0)), |
| 403 | } |
| 404 | |
| 405 | |
| 406 | def _pay_path_for_order(base, order_id): |
| 407 | """The pay link an already-checked-out order was given, if it has one. |
| 408 | |
| 409 | Everything here is best-effort on purpose: a retry must hand back the |
| 410 | SAME door rather than mint a second invoice, but an order whose invoice |
| 411 | or token cannot be found is still a perfectly good order. The caller |
| 412 | gets no link instead of an error. |
| 413 | """ |
| 414 | try: |
| 415 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 416 | order = object_records.get_collection_record("orders", order_id, base_dir=base) |
| 417 | invoice_id = _text(order.get("invoice_id")) |
| 418 | if not invoice_id: |
| 419 | return "" |
| 420 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 421 | invoice = object_records.get_collection_record("invoices", invoice_id, |
| 422 | base_dir=base) |
| 423 | token = _text(invoice.get("portal_token")) |
| 424 | except Exception: |
| 425 | return "" |
| 426 | return f"/pay/{token}" if token else "" |
| 427 | |
| 428 | |
| 429 | def _track_path_for_order(base, order_id): |
| 430 | """The tracking link an already-checked-out order was given. |
| 431 | |
| 432 | Same best-effort posture as _pay_path_for_order, and for the same |
| 433 | reason: a shopper who double-clicked must get the SAME door back, and |
| 434 | an order whose token cannot be read is still an order. |
| 435 | """ |
| 436 | try: |
| 437 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 438 | order = object_records.get_collection_record("orders", order_id, base_dir=base) |
| 439 | token = _text(order.get("portal_token")) |
| 440 | except Exception: |
| 441 | return "" |
| 442 | return f"/orders/track/{token}" if token else "" |
| 443 | |
| 444 | |
| 445 | def _products(base, product_ids): |
| 446 | out = {} |
| 447 | for product_id in product_ids: |
| 448 | try: |
| 449 | # access: storefront catalog: products and pickup slots are shown to shoppers, by design |
| 450 | row = object_records.get_collection_record( |
| 451 | "products", product_id, base_dir=base) |
| 452 | except Exception: |
| 453 | row = None |
| 454 | if row: |
| 455 | out[product_id] = row |
| 456 | return out |
| 457 | |
| 458 | |
| 459 | def _on_hand(base, products): |
| 460 | """What this basket may be PROMISED, for the products it touches, and |
| 461 | which of them the shop actually tracks. |
| 462 | |
| 463 | Available, not on hand: the level less what live online orders are |
| 464 | holding (object_reservations). On hand alone is how one unit was sold |
| 465 | to two orders and three to ten -- stock moves only when money arrives, |
| 466 | so every unpaid order was invisible to the next one. |
| 467 | |
| 468 | A service or a digital download has no stock level, and treating "no |
| 469 | level recorded" as "none available" would refuse to sell the things |
| 470 | that are always available. |
| 471 | """ |
| 472 | # products.product_type: physical | digital | service | subscription | |
| 473 | # asset. Only the first and last are things that sit on a shelf and |
| 474 | # can run out; a download or an hour of work never does. |
| 475 | tracked = {pid for pid, row in products.items() |
| 476 | if object_reservations.tracked(row)} |
| 477 | levels = {} |
| 478 | for product_id in tracked: |
| 479 | try: |
| 480 | levels[product_id] = object_stock.total_quantity( |
| 481 | product_id, base_dir=base) |
| 482 | except object_collections.CollectionNotFoundError: |
| 483 | continue # no stock ledger installed: not tracked |
| 484 | except Exception as exc: |
| 485 | # Skipping it here is what availability() reads as "not |
| 486 | # tracked", so a basket of five sold against two on the shelf. |
| 487 | raise StockUnreadable(str(exc)[:160]) from exc |
| 488 | if levels: |
| 489 | try: |
| 490 | held = object_reservations.read_holds(base) |
| 491 | except object_reservations.HoldsUnreadable as exc: |
| 492 | raise StockUnreadable(str(exc)[:160]) from exc |
| 493 | levels = {pid: level - held.get(pid, 0) for pid, level in levels.items()} |
| 494 | return levels, tracked |
| 495 | |
| 496 | |
| 497 | class StockUnreadable(Exception): |
| 498 | """A tracked product's level could not be read: an unknown, not |
| 499 | "always available".""" |
| 500 | |
| 501 | |
| 502 | # --- the collection-time gate ------------------------------------------------ |
| 503 | # |
| 504 | # Everything from here to POST is inert for a shipping order: _pickup_gate |
| 505 | # returns before it reads anything at all unless the request names a |
| 506 | # method that is not `shipping`. |
| 507 | |
| 508 | FULFILLMENT_METHODS = ("shipping", "pickup", "delivery", "counter") |
| 509 | |
| 510 | DEFAULT_LEAD_MINUTES = 30 |
| 511 | |
| 512 | |
| 513 | def _moment(value): |
| 514 | """An ISO datetime as naive local wall-clock, or None. |
| 515 | |
| 516 | Same normalisation app-pickup's own objects perform, and for the same |
| 517 | reason: every time in this repo is the shop's own clock, and comparing |
| 518 | one aware value against a naive one raises -- which would turn a |
| 519 | single oddly-typed slot into a checkout that refuses everybody. |
| 520 | """ |
| 521 | text = _text(value) |
| 522 | if not text: |
| 523 | return None |
| 524 | try: |
| 525 | moment = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 526 | except ValueError: |
| 527 | return None |
| 528 | if moment.tzinfo is not None: |
| 529 | moment = moment.astimezone().replace(tzinfo=None) |
| 530 | return moment |
| 531 | |
| 532 | |
| 533 | def _lapsed_holds(base, now, slots=()): |
| 534 | """{slot_id: bookings whose hold has lapsed} -- object_pickup decides; |
| 535 | this only reads. Fails closed: orders, invoices or payments that cannot |
| 536 | be read lapse nothing, so the window looks as full as its counter says. |
| 537 | A box with no payments collection has simply taken no payments. |
| 538 | """ |
| 539 | def rows(collection, *, absent): |
| 540 | try: |
| 541 | # access: pickup capacity: counts which bookings still hold a window; nothing is shown |
| 542 | return object_records.read_collection_records(collection, base_dir=base) |
| 543 | except object_collections.CollectionNotFoundError: |
| 544 | return absent |
| 545 | except Exception: |
| 546 | return None |
| 547 | |
| 548 | orders = rows("orders", absent=[]) |
| 549 | invoices = rows("invoices", absent=[]) |
| 550 | payments = rows("payments", absent=[]) |
| 551 | if orders is None or invoices is None: |
| 552 | return {} |
| 553 | minutes = object_pickup.hold_minutes(_setting(base, "pickup.hold_minutes", "")) |
| 554 | grace = object_pickup.grace_minutes(_setting(base, "pickup.grace_minutes", "")) |
| 555 | return object_pickup.lapsed_holds( |
| 556 | orders, now=now, minutes=minutes, grace=grace, |
| 557 | slot_ends=object_pickup.ends_by_slot(slots), |
| 558 | paid_invoice_ids=object_pickup.paid_invoice_ids(invoices, payments)) |
| 559 | |
| 560 | |
| 561 | def _slot_has_room(slot): |
| 562 | return _int(slot.get("orders_taken"), 0) < _int(slot.get("capacity"), 0) |
| 563 | |
| 564 | |
| 565 | def _next_free_slot(slots, *, earliest, location, exclude_id=""): |
| 566 | """The soonest window somebody could actually be given instead. |
| 567 | |
| 568 | Searched at the SAME location as the one they asked for, because |
| 569 | offering a customer a time at the other branch is not an offer. Ties |
| 570 | are broken by start time and nothing else -- the next free slot is |
| 571 | simply the next one. |
| 572 | """ |
| 573 | candidates = [slot for slot in slots |
| 574 | if _text(slot.get("id")) != exclude_id |
| 575 | and _truthy(slot.get("is_open") or "true") |
| 576 | and _text(slot.get("location_id")) == location |
| 577 | and _slot_has_room(slot)] |
| 578 | dated = [(moment, slot) for moment, slot in |
| 579 | ((_moment(slot.get("starts_at")), slot) for slot in candidates) |
| 580 | if moment is not None and moment >= earliest] |
| 581 | if not dated: |
| 582 | return None |
| 583 | dated.sort(key=lambda pair: pair[0]) |
| 584 | return dated[0][1] |
| 585 | |
| 586 | |
| 587 | def _and_the_next_one(slot): |
| 588 | """The half of a refusal that keeps the sale. |
| 589 | |
| 590 | "That time is full" sends somebody away. "That time is full, the next |
| 591 | one is 18:30" is the same fact with somewhere to go, and it costs one |
| 592 | sentence. |
| 593 | """ |
| 594 | if slot is None: |
| 595 | return (" There is no other free collection time on the board -- " |
| 596 | "contact the shop.") |
| 597 | return f" The next free collection time is {_text(slot.get('starts_at'))}." |
| 598 | |
| 599 | |
| 600 | def _pickup_gate(base, request): |
| 601 | """Everything the collection time can be wrong about, gathered at once. |
| 602 | |
| 603 | Returns {method, slot, problems, next_free}. `problems` is a list of |
| 604 | sentences, and it is a LIST rather than a first-failure return for |
| 605 | exactly the reason the price/stock checks above are: the caller folds |
| 606 | it in with theirs and reports the lot together. |
| 607 | |
| 608 | A blank or `shipping` method returns immediately, having read nothing: |
| 609 | a shop that does not do pickup must not pay a collection scan per |
| 610 | checkout, and more importantly must not be able to acquire a pickup |
| 611 | refusal by accident. |
| 612 | """ |
| 613 | method = _text(request.get("fulfillment_method")).lower() |
| 614 | empty = {"method": "", "slot": None, "problems": [], "next_free": None, |
| 615 | "pay_at_pickup": False} |
| 616 | if _truthy(request.get("pay_at_pickup")): |
| 617 | # Paying at the counter is a promise to turn up at a time, so it |
| 618 | # only exists for an order that has one -- and only in a shop that |
| 619 | # offers it, because such an order holds its goods until its |
| 620 | # window closes (object_pickup.hold_lapsed) rather than for the |
| 621 | # half hour an unpaid online order gets. |
| 622 | if method != "pickup": |
| 623 | return {**empty, "method": method, |
| 624 | "problems": ["Paying at collection is only for collection " |
| 625 | "orders (fulfillment_method pickup)."]} |
| 626 | if not _truthy(_setting(base, "pickup.pay_at_pickup", "")): |
| 627 | return {**empty, "method": method, |
| 628 | "problems": ["This shop takes payment online for collection " |
| 629 | "orders (pickup.pay_at_pickup is off)."]} |
| 630 | empty = {**empty, "pay_at_pickup": True} |
| 631 | if not method or method == "shipping": |
| 632 | return empty |
| 633 | |
| 634 | if method not in FULFILLMENT_METHODS: |
| 635 | return {**empty, "method": method, |
| 636 | "problems": [f"'{method}' is not a way this shop can fulfil an " |
| 637 | f"order. Choose one of: " |
| 638 | f"{', '.join(FULFILLMENT_METHODS)}."]} |
| 639 | |
| 640 | if method != "pickup": |
| 641 | # delivery and counter are stated facts about how this order is |
| 642 | # fulfilled and book nothing: there is no slot board for the van or |
| 643 | # the till, and inventing one here would be a rule nobody asked for. |
| 644 | return {**empty, "method": method} |
| 645 | |
| 646 | slot_id = _text(request.get("pickup_slot_id")) |
| 647 | now = (_moment(request.get("now")) if _in_process(request) else None) \ |
| 648 | or datetime.now() |
| 649 | lead = max(0, _int(_setting(base, "pickup.lead_minutes", ""), |
| 650 | DEFAULT_LEAD_MINUTES)) |
| 651 | earliest = now + timedelta(minutes=lead) |
| 652 | |
| 653 | try: |
| 654 | # access: storefront catalog: products and pickup slots are shown to shoppers, by design |
| 655 | slots = object_records.read_collection_records("pickup_slots", |
| 656 | base_dir=base) |
| 657 | except Exception: |
| 658 | # The pickup app is not installed on this box. Refusing is the only |
| 659 | # honest answer -- the shopper asked for a collection time and this |
| 660 | # shop has no board of them -- and it is a refusal rather than a |
| 661 | # silent downgrade to shipping, because quietly posting somebody |
| 662 | # their lunch is worse than telling them no. |
| 663 | return {**empty, "method": method, |
| 664 | "problems": ["This shop is not taking collection orders " |
| 665 | "(no pickup slots are configured)."]} |
| 666 | # Judged by the live count: a booking whose hold lapsed holds no place. |
| 667 | slots = object_pickup.with_live_count(slots, _lapsed_holds(base, now, slots)) |
| 668 | |
| 669 | if not slot_id: |
| 670 | free = _next_free_slot(slots, earliest=earliest, location="") |
| 671 | return {**empty, "method": method, "next_free": free, |
| 672 | "problems": ["Choose a collection time." + _and_the_next_one(free)]} |
| 673 | |
| 674 | slot = next((row for row in slots if _text(row.get("id")) == slot_id), None) |
| 675 | if slot is None: |
| 676 | free = _next_free_slot(slots, earliest=earliest, location="") |
| 677 | return {**empty, "method": method, "next_free": free, |
| 678 | "problems": ["That collection time is not on the board any " |
| 679 | "more." + _and_the_next_one(free)]} |
| 680 | |
| 681 | location = _text(slot.get("location_id")) |
| 682 | problems = [] |
| 683 | starts = _moment(slot.get("starts_at")) |
| 684 | |
| 685 | if not _truthy(slot.get("is_open") or "true"): |
| 686 | problems.append("The shop is not taking orders for that collection " |
| 687 | "time.") |
| 688 | if starts is None: |
| 689 | problems.append("That collection time cannot be read.") |
| 690 | elif starts <= now: |
| 691 | problems.append(f"That collection time ({_text(slot.get('starts_at'))}) " |
| 692 | f"has already passed.") |
| 693 | elif starts < earliest: |
| 694 | # The one refusal that should be impossible to reach through a |
| 695 | # picker, and is checked anyway: action_pickup_slots never OFFERS a |
| 696 | # slot inside the lead time, so arriving here means the id was |
| 697 | # typed, kept from an old page, or guessed. |
| 698 | problems.append(f"That collection time is too soon -- this shop needs " |
| 699 | f"{lead} minutes' notice.") |
| 700 | if not _slot_has_room(slot): |
| 701 | problems.append(f"That collection time is full: it takes " |
| 702 | f"{_int(slot.get('capacity'), 0)} orders and " |
| 703 | f"{_int(slot.get('orders_taken'), 0)} have been taken.") |
| 704 | |
| 705 | free = None |
| 706 | if problems: |
| 707 | free = _next_free_slot(slots, earliest=earliest, location=location, |
| 708 | exclude_id=slot_id) |
| 709 | problems[-1] += _and_the_next_one(free) |
| 710 | return {"method": method, "slot": slot, "problems": problems, |
| 711 | "next_free": free, "pay_at_pickup": empty["pay_at_pickup"]} |
| 712 | |
| 713 | |
| 714 | # --- the money gates --------------------------------------------------------- |
| 715 | # |
| 716 | # Both are inert unless the request names a code, for the same reason |
| 717 | # _pickup_gate is inert for a shipping order: a shop that runs no |
| 718 | # promotions and sells no gift cards must not pay a collection scan per |
| 719 | # checkout, and must not be able to acquire a refusal by accident. |
| 720 | |
| 721 | |
| 722 | def _rows(base, collection): |
| 723 | try: |
| 724 | # access: gift card: found by its secret code, and only that wallet's own entries are summed |
| 725 | return object_records.read_collection_records(collection, base_dir=base) |
| 726 | except Exception: |
| 727 | return None |
| 728 | |
| 729 | |
| 730 | def _call(object_id, payload, *, method="POST"): |
| 731 | """Run another installed object in process -- the same mechanism |
| 732 | system_shop_fulfillment uses to reach app-shipping, and |
| 733 | action_resolve_dispute uses to reach hook_refunds. |
| 734 | |
| 735 | Returns (result, error). A missing object (the app is simply not |
| 736 | installed) is an error string, never an exception. |
| 737 | """ |
| 738 | try: |
| 739 | runtime = python_object_runtime.PythonObjectRuntime() |
| 740 | outcome = object_execution.execute_object( |
| 741 | runtime, |
| 742 | object_execution.ObjectExecutionRequest( |
| 743 | object_id, method=method, payload=payload)) |
| 744 | except Exception as exc: |
| 745 | return None, str(exc)[:200] |
| 746 | if not outcome.ok: |
| 747 | message = getattr(outcome.error, "message", "") if outcome.error else "" |
| 748 | return None, _text(message)[:200] or f"{object_id} failed" |
| 749 | return outcome.result, "" |
| 750 | |
| 751 | |
| 752 | def _promotion_gate(base, request, subtotal_cents, postage_cents, today): |
| 753 | """Everything a discount code can be wrong about, gathered at once. |
| 754 | |
| 755 | Returns {code, promo, problems, discount_cents, applies_to}. `problems` |
| 756 | is a LIST, from object_promotions.blockers, and it is folded in with |
| 757 | the price, stock and collection-time problems below rather than |
| 758 | returned on its own -- a shopper told their code expired, who fixes |
| 759 | that and is then told the basket is too small, has left. |
| 760 | |
| 761 | No code returns immediately having read nothing. |
| 762 | """ |
| 763 | empty = {"code": "", "promo": None, "problems": [], "discount_cents": 0, |
| 764 | "applies_to": "goods"} |
| 765 | code = object_promotions.normalize_code(request.get("promo_code")) |
| 766 | if not code: |
| 767 | return empty |
| 768 | |
| 769 | promotions = _rows(base, "promotions") |
| 770 | if promotions is None: |
| 771 | # No promotions app on this box. An honest refusal beats silently |
| 772 | # ignoring a code the shopper believes they are getting. |
| 773 | return {**empty, "code": code, |
| 774 | "problems": [f"There is no promotion with the code '{code}'."]} |
| 775 | redemptions = _rows(base, "promotion_redemptions") |
| 776 | if redemptions is None: |
| 777 | # The limits cannot be counted, and a limit that cannot be counted |
| 778 | # has not been met. Refusing is the safe direction: a code honoured |
| 779 | # once too often is money, a code refused once is an email. |
| 780 | return {**empty, "code": code, |
| 781 | "problems": ["That code cannot be checked right now (the " |
| 782 | "redemption log is unreadable)."]} |
| 783 | |
| 784 | promo = object_promotions.resolve(code, promotions, on_date=today) |
| 785 | problems = object_promotions.blockers( |
| 786 | promo, subtotal_cents, _text(request.get("customer_email")), |
| 787 | redemptions, on_date=today, code=code) |
| 788 | if problems: |
| 789 | return {**empty, "code": code, "promo": promo, "problems": problems} |
| 790 | return {"code": code, "promo": promo, "problems": [], |
| 791 | "discount_cents": object_promotions.discount_for( |
| 792 | subtotal_cents, postage_cents, promo), |
| 793 | "applies_to": object_promotions.applies_to(promo)} |
| 794 | |
| 795 | |
| 796 | def _gift_card_gate(base, request): |
| 797 | """The card, its balance, and every reason it cannot be spent. |
| 798 | |
| 799 | Returns {code, wallet, problems, available_cents}. The balance is |
| 800 | SUMMED FROM THE ENTRIES rather than read off wallets.balance_minor, |
| 801 | for the reason hook_wallet_entries states about its own gate: that |
| 802 | number is a rollup, and a decision that leans on a derived value it |
| 803 | could recompute is a decision that authorises a debit against money |
| 804 | which does not exist the moment the rollup goes stale. |
| 805 | |
| 806 | This only decides how much to OFFER. The authoritative refusal comes |
| 807 | from hook_wallet_entries at the moment of the debit, which is asked |
| 808 | in process below -- there is exactly one gate on this ledger and it |
| 809 | is not this function. |
| 810 | """ |
| 811 | empty = {"code": "", "wallet": None, "problems": [], "available_cents": 0} |
| 812 | code = _text(request.get("gift_card_code")).upper() |
| 813 | if not code: |
| 814 | return empty |
| 815 | |
| 816 | wallets = _rows(base, "wallets") |
| 817 | if wallets is None: |
| 818 | return {**empty, "code": code, |
| 819 | "problems": [f"There is no gift card with the code '{code}' " |
| 820 | f"(this shop has no wallets)."]} |
| 821 | wallet = next((row for row in wallets |
| 822 | if _text(row.get("code")).upper() == code), None) |
| 823 | if wallet is None: |
| 824 | return {**empty, "code": code, |
| 825 | "problems": [f"There is no gift card with the code '{code}'."]} |
| 826 | |
| 827 | problems = [] |
| 828 | if not _truthy(wallet.get("is_active") or "true"): |
| 829 | problems.append(f"The gift card {code} is not active.") |
| 830 | |
| 831 | entries = _rows(base, "wallet_entries") |
| 832 | if entries is None: |
| 833 | return {**empty, "code": code, "wallet": wallet, |
| 834 | "problems": problems + [ |
| 835 | f"The balance of gift card {code} cannot be read, so it " |
| 836 | f"cannot be spent right now."]} |
| 837 | balance = sum(_int(row.get("amount_minor")) |
| 838 | for row in entries |
| 839 | if _text(row.get("wallet_id")) == _text(wallet.get("id"))) |
| 840 | if balance <= 0: |
| 841 | problems.append(f"The gift card {code} has nothing left on it.") |
| 842 | |
| 843 | return {"code": code, "wallet": wallet, "problems": problems, |
| 844 | "available_cents": max(0, balance)} |
| 845 | |
| 846 | |
| 847 | def _spend_the_card(base, wallet, amount_cents, *, order_id, invoice_id, |
| 848 | today, owner_id): |
| 849 | """Debit the wallet and record the tender. Returns (applied, error). |
| 850 | |
| 851 | **THE GATE IS ASKED, NOT ASSUMED.** hook_wallet_entries is the one |
| 852 | authority on whether a wallet can afford a debit -- it sums the |
| 853 | entries rather than trusting the balance rollup, and it documents its |
| 854 | own check-then-append race honestly. A trusted server-side write like |
| 855 | this one BYPASSES hooks by design, so the only way to be under that |
| 856 | gate is to ask it in process and surface its refusal verbatim, which |
| 857 | is exactly what action_resolve_dispute does with hook_refunds. A |
| 858 | second opinion written here would be a second ceiling to get wrong, |
| 859 | and would quote a customer a different answer depending on which door |
| 860 | their spend came through. |
| 861 | |
| 862 | Fails CLOSED: a gate that cannot be consulted has not said yes. |
| 863 | |
| 864 | **The order of the two writes, and the compensation.** The debit is |
| 865 | taken first and the payment recorded second, because a payment |
| 866 | against an untouched card is the shop giving away goods. If the |
| 867 | payment cannot be written the debit is REVERSED by a compensating |
| 868 | credit -- the ledger's own correction mechanism, never an edit or a |
| 869 | delete, exactly as refunds correct payments and reversing journals |
| 870 | correct postings. The customer's balance ends where it started and |
| 871 | the checkout says what happened. |
| 872 | """ |
| 873 | wallet_id = _text(wallet.get("id")) |
| 874 | wanted = int(amount_cents) |
| 875 | |
| 876 | def compose(rows): |
| 877 | # Asked again on every attempt, against the rows that attempt read: |
| 878 | # the balance the gate offered was read before the order was |
| 879 | # written, and another checkout may have spent the card since. |
| 880 | amount = min(wanted, object_wallet.balance_of(rows)) |
| 881 | if amount <= 0: |
| 882 | raise object_wallet.Refused( |
| 883 | f"the gift card {_text(wallet.get('code'))} has nothing left on " |
| 884 | f"it (it was spent by another checkout a moment ago), so it was " |
| 885 | f"not charged") |
| 886 | return { |
| 887 | "id": object_ids.new_uuid4(), |
| 888 | # Negative: money leaving. The sign convention is the ledger's. |
| 889 | "amount_minor": str(-amount), |
| 890 | "kind": "debit", |
| 891 | "description": f"Spent at checkout on order {order_id[:8].upper()}", |
| 892 | "reference": f"orders/{order_id}", |
| 893 | # Provenance, so a replayed checkout finds its own marker instead |
| 894 | # of charging the card twice (docs/logic-decisions.md #7) -- and |
| 895 | # wallet_entries declares it unique, so the ledger enforces it. |
| 896 | "generated_from": f"checkout/{order_id}", |
| 897 | "owner_id": _text(wallet.get("owner_id")) or owner_id, |
| 898 | } |
| 899 | |
| 900 | def gate(entry): |
| 901 | verdict, error = _call("hook_wallet_entries", |
| 902 | {"action": "create", "collection": "wallet_entries", |
| 903 | "record": entry}, |
| 904 | method="BEFORE_WRITE") |
| 905 | if error: |
| 906 | return (f"the wallet gate could not be consulted ({error}), so the " |
| 907 | f"gift card was not charged") |
| 908 | if isinstance(verdict, dict) and verdict.get("error"): |
| 909 | return _text(verdict.get("error")) or "the wallet gate refused the charge" |
| 910 | return "" |
| 911 | |
| 912 | # THE CLAIM ON THE BALANCE. object_wallet.append_debit stamps the next |
| 913 | # number in this wallet's spend sequence from the rows compose() summed; |
| 914 | # wallet_entries declares (wallet_id, spend_seq) unique, checked inside |
| 915 | # the write lock. Two checkouts that summed the same rows propose the |
| 916 | # same number and only one lands; the other re-reads and sees the first |
| 917 | # one's debit. That is what makes "the card can afford this" hold under a |
| 918 | # race, which the gate cannot: it runs before the lock, so two debits |
| 919 | # both passed it and a 1000 card paid for two 1000 orders. |
| 920 | try: |
| 921 | stored = object_wallet.append_debit(wallet_id, compose, base_dir=base, |
| 922 | actor=ACTOR, gate=gate) |
| 923 | except object_wallet.Refused as refused: |
| 924 | return 0, refused.message |
| 925 | except object_wallet.Unreadable as exc: |
| 926 | return 0, (f"the gift card's balance cannot be read right now " |
| 927 | f"({str(exc)[:100]}), so it was not charged") |
| 928 | except object_wallet.AlreadyWritten: |
| 929 | # The marker: this order has already charged the card. |
| 930 | return 0, ("this order has already charged the gift card; it was " |
| 931 | "not charged again") |
| 932 | except object_wallet.Contended: |
| 933 | return 0, ("the gift card is being spent by other checkouts right now, " |
| 934 | "so it was not charged; the whole bill is still owed") |
| 935 | except Exception as exc: |
| 936 | return 0, f"the gift card could not be charged: {str(exc)[:120]}" |
| 937 | amount = -_int(stored.get("amount_minor")) |
| 938 | amount_cents = amount |
| 939 | |
| 940 | try: |
| 941 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 942 | object_records.create_collection_record( |
| 943 | "payments", |
| 944 | { |
| 945 | "id": object_ids.new_uuid4(), |
| 946 | "invoice_id": invoice_id, |
| 947 | "amount_cents": str(int(amount_cents)), |
| 948 | # `other` because payments.method has no wallet entry and |
| 949 | # app-payments' enum is not this slice's to widen. The |
| 950 | # reference names the wallet, so what this was is findable |
| 951 | # rather than merely labelled. |
| 952 | "method": "other", |
| 953 | "received_on": today, |
| 954 | "reference": f"wallets/{wallet_id}", |
| 955 | "status": "received", |
| 956 | "notes": (f"Gift card {_text(wallet.get('code'))} redeemed by " |
| 957 | f"{ACTOR} [orders/{order_id}]"), |
| 958 | "owner_id": owner_id, |
| 959 | }, |
| 960 | base_dir=base, actor=ACTOR) |
| 961 | except Exception as exc: |
| 962 | # Put the money back. A compensating entry, never an edit: the |
| 963 | # ledger is append-only and a mistaken charge is corrected by a |
| 964 | # record that says so. |
| 965 | try: |
| 966 | # access: spends the gift card the shopper presented by its secret code |
| 967 | object_records.create_collection_record( |
| 968 | "wallet_entries", |
| 969 | {"id": object_ids.new_uuid4(), |
| 970 | "wallet_id": wallet_id, |
| 971 | "amount_minor": str(int(amount_cents)), |
| 972 | "kind": "adjustment", |
| 973 | "description": ("Reversed: the payment against this order " |
| 974 | "could not be recorded"), |
| 975 | "reference": f"orders/{order_id}", |
| 976 | "generated_from": f"checkout_reversal/{order_id}", |
| 977 | # A credit gives back; it claims nothing, so it takes no |
| 978 | # spend_seq (blank is exempt from the constraint). |
| 979 | "owner_id": _text(wallet.get("owner_id")) or owner_id}, |
| 980 | base_dir=base, actor=ACTOR) |
| 981 | except Exception: |
| 982 | return int(amount_cents), ( |
| 983 | f"the gift card was charged but the payment could not be " |
| 984 | f"recorded ({str(exc)[:100]}) AND the charge could not be " |
| 985 | f"reversed -- this wallet is short and needs a human") |
| 986 | return 0, (f"the payment could not be recorded " |
| 987 | f"({str(exc)[:120]}); the gift card was charged and the " |
| 988 | f"charge has been reversed") |
| 989 | |
| 990 | if amount < wanted: |
| 991 | return amount, (f"only {amount} was left on the gift card when it was " |
| 992 | f"charged, so {wanted - amount} more is owed") |
| 993 | return int(amount_cents), "" |
| 994 | |
| 995 | |
| 996 | def _record_backorders(base, lines, order_id, line_ids, email, today, cart): |
| 997 | """A row per line the shop agreed to owe. Returns what it wrote. |
| 998 | |
| 999 | Best-effort by construction: the sale has already happened by the time |
| 1000 | this runs, and a backorders collection that is absent (a shop still on |
| 1001 | app-catalog 0.6) must cost the warehouse a queue entry rather than |
| 1002 | cost the shopper their order. |
| 1003 | """ |
| 1004 | if not lines: |
| 1005 | return [] |
| 1006 | written = [] |
| 1007 | for line in lines: |
| 1008 | row_id = object_ids.new_uuid4() |
| 1009 | try: |
| 1010 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1011 | object_records.create_collection_record( |
| 1012 | "backorders", |
| 1013 | {"id": row_id, |
| 1014 | "product_id": line["product_id"], |
| 1015 | "kind": "backorder", |
| 1016 | "order_id": order_id, |
| 1017 | "order_line_id": line_ids.get(line["cart_item_id"], ""), |
| 1018 | # What was SHORT, not what was ordered: the rest of the |
| 1019 | # line is ordinary stock that goes out today. |
| 1020 | "quantity": _text(line.get("short_by")), |
| 1021 | "customer_email": email, |
| 1022 | "status": "open", |
| 1023 | "requested_on": today, |
| 1024 | "owner_id": _text(cart.get("owner_id"))}, |
| 1025 | base_dir=base, actor=ACTOR) |
| 1026 | except Exception: |
| 1027 | continue |
| 1028 | written.append({"backorder_id": row_id, |
| 1029 | "product_id": line["product_id"], |
| 1030 | "description": _text(line.get("description")), |
| 1031 | "short_by": _text(line.get("short_by"))}) |
| 1032 | return written |
| 1033 | |
| 1034 | |
| 1035 | def _record_notify_interest(base, lines, products, email, today, cart): |
| 1036 | """Who wanted what the shop just refused to sell them. |
| 1037 | |
| 1038 | Written on the REFUSAL path, which is the only moment this fact |
| 1039 | exists. Refusing while remembering beats refusing and forgetting, |
| 1040 | which is what the shop did before and what loses the same customer |
| 1041 | twice. |
| 1042 | |
| 1043 | Needs an address: a record of interest with no way to reach the |
| 1044 | interested party is a record of nothing, so a checkout with no email |
| 1045 | writes none and the response says so by simply not listing any. |
| 1046 | |
| 1047 | Idempotent on (product, email) while a row is still open, so a shopper |
| 1048 | who presses the button five times is one person waiting, not five. |
| 1049 | """ |
| 1050 | if not lines or not email: |
| 1051 | return [] |
| 1052 | existing = _rows(base, "backorders") |
| 1053 | if existing is None: |
| 1054 | return [] |
| 1055 | already = {(_text(row.get("product_id")), |
| 1056 | _text(row.get("customer_email")).lower()) |
| 1057 | for row in existing |
| 1058 | if _text(row.get("kind")) == "notify" |
| 1059 | and _text(row.get("status")) == "open"} |
| 1060 | |
| 1061 | written = [] |
| 1062 | for line in lines: |
| 1063 | key = (line["product_id"], email.lower()) |
| 1064 | if key in already: |
| 1065 | continue |
| 1066 | already.add(key) |
| 1067 | row_id = object_ids.new_uuid4() |
| 1068 | try: |
| 1069 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1070 | object_records.create_collection_record( |
| 1071 | "backorders", |
| 1072 | {"id": row_id, |
| 1073 | "product_id": line["product_id"], |
| 1074 | "kind": "notify", |
| 1075 | # No order: nothing was sold, which is the whole |
| 1076 | # distinction between this row and a backorder. |
| 1077 | "order_id": "", |
| 1078 | "quantity": _text(line.get("short_by")), |
| 1079 | "customer_email": email, |
| 1080 | "status": "open", |
| 1081 | "requested_on": today, |
| 1082 | "owner_id": _text(cart.get("owner_id"))}, |
| 1083 | base_dir=base, actor=ACTOR) |
| 1084 | except Exception: |
| 1085 | continue |
| 1086 | written.append({"backorder_id": row_id, |
| 1087 | "product_id": line["product_id"], |
| 1088 | "description": _text(line.get("description"))}) |
| 1089 | return written |
| 1090 | |
| 1091 | |
| 1092 | def _slot_refusal(pickup): |
| 1093 | """The pickup half of a 409, shaped so a storefront can render the next |
| 1094 | free time as a button rather than parsing it back out of a sentence.""" |
| 1095 | payload = {"pickup_problems": pickup["problems"]} |
| 1096 | free = pickup.get("next_free") |
| 1097 | if free is not None: |
| 1098 | payload["next_free_slot"] = { |
| 1099 | "id": free["id"], |
| 1100 | "starts_at": _text(free.get("starts_at")), |
| 1101 | "ends_at": _text(free.get("ends_at")), |
| 1102 | "places_left": max(0, _int(free.get("capacity"), 0) |
| 1103 | - _int(free.get("orders_taken"), 0)), |
| 1104 | } |
| 1105 | return payload |
| 1106 | |
| 1107 | |
| 1108 | def _already_checked_out(base, cart): |
| 1109 | """The answer for a cart that already became (or is becoming) an order. |
| 1110 | |
| 1111 | One cart, one order, however many times a browser retries -- and the |
| 1112 | same pay link back each time, because a shopper who double-clicked |
| 1113 | still needs the door, not a second bill. A cart claimed by a submit |
| 1114 | that is still writing its order gets the same answer, without the |
| 1115 | links if they do not exist yet. |
| 1116 | """ |
| 1117 | order_id = _claim_of(cart) |
| 1118 | duplicate = {"ok": True, "duplicate": True, "order_id": order_id, |
| 1119 | "note": "this basket has already been checked out"} |
| 1120 | if _text(cart.get("status")) == "open": |
| 1121 | duplicate["note"] = ("this basket is being checked out by another " |
| 1122 | "request; its order is " + order_id) |
| 1123 | pay_path = _pay_path_for_order(base, order_id) |
| 1124 | if pay_path: |
| 1125 | duplicate["pay_path"] = pay_path |
| 1126 | track_path = _track_path_for_order(base, order_id) |
| 1127 | if track_path: |
| 1128 | duplicate["track_path"] = track_path |
| 1129 | return duplicate |
| 1130 | |
| 1131 | |
| 1132 | def _claim_of(cart): |
| 1133 | """The order a cart became, or the one a submit is writing for it.""" |
| 1134 | return (_text(cart.get("checked_out_order_id")) |
| 1135 | or _text(cart.get("checkout_claim"))) |
| 1136 | |
| 1137 | |
| 1138 | def _latest_claimed(carts, token): |
| 1139 | """The cart a retried submit on this token is about, or None. |
| 1140 | |
| 1141 | A token outlives its first cart: action_cart opens a NEW cart for a |
| 1142 | token whose cart was checked out, so a shopper who buys, keeps browsing |
| 1143 | and buys again holds two carts on one token. This used to answer with |
| 1144 | the FIRST cart on the token that carried a claim -- the older purchase |
| 1145 | -- so the retry of a second checkout (or a click overlapping it) was |
| 1146 | shown, and sent to pay, the order before. A cart still being checked |
| 1147 | out (open, claimed) is the one the browser is on; otherwise the newest |
| 1148 | settled one, by created_at and then by position in the file, which is |
| 1149 | the order the carts were opened in. |
| 1150 | """ |
| 1151 | mine = [(index, cart) for index, cart in enumerate(carts) |
| 1152 | if _text(cart.get("session_token")) == token and _claim_of(cart)] |
| 1153 | in_flight = [pair for pair in mine if _text(pair[1].get("status")) == "open"] |
| 1154 | pool = in_flight or mine |
| 1155 | if not pool: |
| 1156 | return None |
| 1157 | return max(pool, key=lambda pair: (_text(pair[1].get("created_at")), pair[0]))[1] |
| 1158 | |
| 1159 | |
| 1160 | def _claim_the_cart(base, cart, order_id): |
| 1161 | """Claim the cart for this order BEFORE the order exists, as a |
| 1162 | compare-and-set. Returns (claimed_cart, None) or (None, answer). |
| 1163 | |
| 1164 | The stamp used to be the last write, after the order, its lines, the |
| 1165 | redemption and the invoice, and it carried no expected_rev -- so a |
| 1166 | second submit that read the cart while the first was still writing saw |
| 1167 | an open basket and raised a second order and a second invoice (a |
| 1168 | double-click inside that window billed the customer twice). Now the |
| 1169 | first thing written is the claim, and only the submit whose claim lands |
| 1170 | writes anything; the loser is answered with the winner's order. |
| 1171 | |
| 1172 | The claim is its own field, carts.checkout_claim, because |
| 1173 | checked_out_order_id is a relation and cannot name an order that has |
| 1174 | not been written yet; and the status does not move here because |
| 1175 | checked_out is terminal, while a claim has to be releasable if the |
| 1176 | order then cannot be written (_release_the_cart). The status and |
| 1177 | checked_out_order_id are stamped at the end, as before. |
| 1178 | """ |
| 1179 | try: |
| 1180 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1181 | fresh = object_records.get_collection_record("carts", cart["id"], |
| 1182 | base_dir=base) |
| 1183 | except Exception as exc: |
| 1184 | return None, {"status": 503, |
| 1185 | "error": f"The basket cannot be read right now ({str(exc)[:120]}); " |
| 1186 | f"nothing was ordered. Try again in a moment."} |
| 1187 | if _claim_of(fresh) or _text(fresh.get("status")) != "open": |
| 1188 | return None, _already_checked_out(base, fresh) |
| 1189 | try: |
| 1190 | # preserve_read_only: checkout_claim is read_only so no API client |
| 1191 | # can claim (or unclaim) a basket; this is the writer that does. |
| 1192 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1193 | claimed = object_records.update_collection_record( |
| 1194 | "carts", cart["id"], {"checkout_claim": order_id}, |
| 1195 | base_dir=base, actor=ACTOR, preserve_read_only=True, |
| 1196 | expected_rev=object_records.compute_record_rev(fresh)) |
| 1197 | except object_records.VersionConflictError: |
| 1198 | try: |
| 1199 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1200 | fresh = object_records.get_collection_record("carts", cart["id"], |
| 1201 | base_dir=base) |
| 1202 | except Exception: |
| 1203 | fresh = {} |
| 1204 | if _claim_of(fresh): |
| 1205 | return None, _already_checked_out(base, fresh) |
| 1206 | return None, {"status": 409, |
| 1207 | "error": "The basket changed while it was being checked " |
| 1208 | "out. Check it and submit again."} |
| 1209 | return claimed, None |
| 1210 | |
| 1211 | |
| 1212 | def _release_the_cart(base, claimed, order_id): |
| 1213 | """Take a claim back when its order could not be written, so the |
| 1214 | shopper can submit again rather than holding a basket that points at |
| 1215 | an order that does not exist. Only our own claim, and only if nobody |
| 1216 | has changed the cart since; anything else is left for a human.""" |
| 1217 | try: |
| 1218 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1219 | current = object_records.get_collection_record("carts", claimed["id"], |
| 1220 | base_dir=base) |
| 1221 | if (_text(current.get("checkout_claim")) != order_id |
| 1222 | or _text(current.get("checked_out_order_id"))): |
| 1223 | return |
| 1224 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1225 | object_records.update_collection_record( |
| 1226 | "carts", claimed["id"], {"checkout_claim": ""}, |
| 1227 | base_dir=base, actor=ACTOR, preserve_read_only=True, |
| 1228 | expected_rev=object_records.compute_record_rev(current)) |
| 1229 | except Exception: |
| 1230 | pass |
| 1231 | |
| 1232 | |
| 1233 | def _undo_the_order(base, claimed, order_id, line_ids): |
| 1234 | """Take back an order whose hold was refused, before anything else was |
| 1235 | written for it. |
| 1236 | |
| 1237 | Deleted rather than cancelled: nobody was told it exists, it has no |
| 1238 | invoice and no pay link, and a cancelled order would sit in the back |
| 1239 | office as a sale that never happened. The cart's claim is released so |
| 1240 | the shopper can change the basket and submit again. Best-effort, and |
| 1241 | each step on its own: a line that will not delete must not keep the |
| 1242 | cart claimed for good. |
| 1243 | """ |
| 1244 | for line_id in line_ids: |
| 1245 | try: |
| 1246 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1247 | object_records.delete_collection_record( |
| 1248 | "order_lines", line_id, base_dir=base, actor=ACTOR) |
| 1249 | except Exception: |
| 1250 | pass |
| 1251 | try: |
| 1252 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1253 | object_records.delete_collection_record("orders", order_id, |
| 1254 | base_dir=base, actor=ACTOR) |
| 1255 | except Exception: |
| 1256 | pass |
| 1257 | _release_the_cart(base, claimed, order_id) |
| 1258 | |
| 1259 | |
| 1260 | def _lost_the_race(base, items, products, exc): |
| 1261 | """The answer when the locked check refused a line: the same 409 the |
| 1262 | gate gives, read again now that the other order's lines are on file, |
| 1263 | so the shopper is told what is left rather than that something went |
| 1264 | wrong.""" |
| 1265 | status = getattr(exc, "status", 409) |
| 1266 | if status == 503 or not isinstance(exc, object_records.CheckRefusedError): |
| 1267 | return {"status": 503, |
| 1268 | "error": (f"This order could not be placed right now ({str(exc)[:160]}). " |
| 1269 | f"Nothing was ordered; try again in a moment.")} |
| 1270 | try: |
| 1271 | levels, tracked = _on_hand(base, products) |
| 1272 | blockers = object_cart.checkout_blockers(items, products, levels, |
| 1273 | tracked=tracked) |
| 1274 | unavailable, inactive = blockers["unavailable"], blockers["inactive"] |
| 1275 | except Exception: |
| 1276 | unavailable, inactive = [], [] |
| 1277 | return {"status": 409, |
| 1278 | "error": "Some items cannot be ordered right now.", |
| 1279 | "unavailable": unavailable, "inactive": inactive, |
| 1280 | "reserve_error": str(exc)[:300]} |
| 1281 | |
| 1282 | |
| 1283 | def _held_until(base, pickup, slot): |
| 1284 | """When an unpaid hold on this order lapses (object_pickup.hold_lapsed), |
| 1285 | as the shop's wall clock, or "" when it does not.""" |
| 1286 | if pickup.get("pay_at_pickup") and slot is not None: |
| 1287 | ends = _moment(slot.get("ends_at")) or _moment(slot.get("starts_at")) |
| 1288 | if ends is None: |
| 1289 | return "" |
| 1290 | grace = object_pickup.grace_minutes(_setting(base, "pickup.grace_minutes", "")) |
| 1291 | return (ends + timedelta(minutes=grace)).isoformat(timespec="minutes") |
| 1292 | minutes = object_pickup.hold_minutes(_setting(base, "pickup.hold_minutes", "")) |
| 1293 | if minutes <= 0: |
| 1294 | return "" |
| 1295 | return (datetime.now() + timedelta(minutes=minutes)).isoformat(timespec="minutes") |
| 1296 | |
| 1297 | |
| 1298 | def _count_the_slot(base, slot_id): |
| 1299 | """orders_taken + 1, as a compare-and-set. Returns "" or an error. |
| 1300 | |
| 1301 | It used to read, add one and write with no expected_rev, so two orders |
| 1302 | booking one window at the same moment both wrote the same number and |
| 1303 | the slot showed one order where it held two -- the count exists so a |
| 1304 | shop can SEE an oversell, and a lost update hides exactly that. Now a |
| 1305 | write that finds the row changed since it read it reads again and adds |
| 1306 | one to what is there. Still deliberately NOT clamped to capacity (see |
| 1307 | the module docstring): the count says what happened. |
| 1308 | """ |
| 1309 | for _ in range(SLOT_COUNT_ATTEMPTS): |
| 1310 | try: |
| 1311 | # access: storefront catalog: products and pickup slots are shown to shoppers, by design |
| 1312 | current = object_records.get_collection_record( |
| 1313 | "pickup_slots", slot_id, base_dir=base) |
| 1314 | # access: storefront catalog: products and pickup slots are shown to shoppers, by design |
| 1315 | object_records.update_collection_record( |
| 1316 | "pickup_slots", slot_id, |
| 1317 | {"orders_taken": str(_int(current.get("orders_taken"), 0) + 1)}, |
| 1318 | base_dir=base, actor=ACTOR, |
| 1319 | expected_rev=object_records.compute_record_rev(current)) |
| 1320 | return "" |
| 1321 | except object_records.VersionConflictError: |
| 1322 | continue |
| 1323 | except Exception as exc: |
| 1324 | return f"the collection slot's count could not be updated: {str(exc)[:120]}" |
| 1325 | return ("the collection slot's count could not be updated: it kept " |
| 1326 | "changing under this write") |
| 1327 | |
| 1328 | |
| 1329 | SLOT_COUNT_ATTEMPTS = 20 |
| 1330 | |
| 1331 | |
| 1332 | def POST(request): |
| 1333 | base = _base_dir() |
| 1334 | token = _text(request.get("session_token")) |
| 1335 | if not token: |
| 1336 | return {"status": 400, "error": "session_token is required"} |
| 1337 | if not _in_process(request) and object_cart.session_token_problem(token): |
| 1338 | # A short or hand-made token is one somebody could guess, and a |
| 1339 | # guessed token on a checked-out basket would be answered with that |
| 1340 | # order's pay and tracking links (_already_checked_out). The shop |
| 1341 | # mints the token (action_cart); nothing it minted fails this. |
| 1342 | return {"status": 404, "error": "No open basket for this session.", |
| 1343 | "code": "unknown_session_token"} |
| 1344 | |
| 1345 | try: |
| 1346 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1347 | carts = object_records.read_collection_records("carts", base_dir=base) |
| 1348 | except Exception: |
| 1349 | return {"ok": True, "skipped": "shop not installed (carts absent)"} |
| 1350 | |
| 1351 | # An open cart that carries a checkout_claim has been CLAIMED by a |
| 1352 | # submit that is writing its order right now (see _claim_the_cart): it |
| 1353 | # is answered as settled, never checked out again. |
| 1354 | cart = next((c for c in carts if _text(c.get("session_token")) == token |
| 1355 | and _text(c.get("status")) == "open" |
| 1356 | and not _claim_of(c)), None) |
| 1357 | if cart is None: |
| 1358 | settled = _latest_claimed(carts, token) |
| 1359 | if settled: |
| 1360 | return _already_checked_out(base, settled) |
| 1361 | return {"status": 404, "error": "No open basket for this session."} |
| 1362 | |
| 1363 | try: |
| 1364 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1365 | all_items = object_records.read_collection_records("cart_items", base_dir=base) |
| 1366 | except Exception: |
| 1367 | all_items = [] |
| 1368 | items = [i for i in all_items if _text(i.get("cart_id")) == cart["id"]] |
| 1369 | |
| 1370 | products = _products(base, {_text(i.get("product_id")) for i in items}) |
| 1371 | try: |
| 1372 | levels, tracked = _on_hand(base, products) |
| 1373 | except StockUnreadable as exc: |
| 1374 | return {"status": 503, |
| 1375 | "error": (f"The stock levels could not be read right now " |
| 1376 | f"({exc}), so whether this basket can be filled is " |
| 1377 | f"unknown. Nothing was ordered; try again in a " |
| 1378 | f"moment.")} |
| 1379 | blockers = object_cart.checkout_blockers(items, products, levels, tracked=tracked) |
| 1380 | # Gathered HERE, beside the price and stock checks, and reported with |
| 1381 | # them below -- never on its own and never first. For a shipping order |
| 1382 | # this reads nothing and finds nothing; see _pickup_gate. |
| 1383 | pickup = _pickup_gate(base, request) |
| 1384 | |
| 1385 | if blockers["empty"]: |
| 1386 | return {"status": 400, "error": "There is nothing in this basket.", |
| 1387 | **(_slot_refusal(pickup) if pickup["problems"] else {})} |
| 1388 | |
| 1389 | if blockers["price_changes"] and not _truthy(request.get("confirm_prices")): |
| 1390 | return {"status": 409, |
| 1391 | "error": "Some prices changed while this basket was open.", |
| 1392 | "price_changes": blockers["price_changes"], |
| 1393 | "note": "Show both numbers and send confirm_prices=true once " |
| 1394 | "the shopper has agreed to the current ones.", |
| 1395 | **(_slot_refusal(pickup) if pickup["problems"] else {})} |
| 1396 | |
| 1397 | # Prices confirmed: adopt the live ones so the order records what the |
| 1398 | # shopper actually agreed to, not the number they first saw. Moved |
| 1399 | # ABOVE the remaining refusals because the money gates below have to |
| 1400 | # judge a discount code's minimum spend against the basket the shopper |
| 1401 | # is actually agreeing to -- a code checked against a stale subtotal is |
| 1402 | # a code that passes here and fails on the invoice. |
| 1403 | if blockers["price_changes"] and _truthy(request.get("confirm_prices")): |
| 1404 | for item in items: |
| 1405 | product = products.get(_text(item.get("product_id"))) |
| 1406 | if product: |
| 1407 | item["unit_price_cents"] = str(product.get("price_cents") or 0) |
| 1408 | # And the extras' live prices, where those are what moved. |
| 1409 | live_extras = {change["cart_item_id"]: change["now_cents"] |
| 1410 | for change in blockers["price_changes"] |
| 1411 | if change.get("kind") == "modifier"} |
| 1412 | for item in items: |
| 1413 | if _text(item.get("id")) in live_extras: |
| 1414 | item["modifier_cents"] = str(live_extras[_text(item.get("id"))]) |
| 1415 | |
| 1416 | # Which extras each line carries, for the cook's note and the payer's |
| 1417 | # invoice line (see the module docstring). |
| 1418 | extras_of = {_text(item.get("id")): object_cart.chosen_modifiers(item.get("modifiers")) |
| 1419 | for item in items} |
| 1420 | |
| 1421 | # The server's date unless an in-process caller pins one: `today` |
| 1422 | # decides whether a promotion is in force (see the module docstring). |
| 1423 | today = ((_text(request.get("today")) if _in_process(request) else "") |
| 1424 | or date.today().isoformat()) |
| 1425 | charges = _tax_and_shipping_settings(base) |
| 1426 | email = _text(request.get("customer_email")) |
| 1427 | # The sale before any code or card touches it. The promotion's minimum |
| 1428 | # spend is judged on GOODS -- the number a shopper can see on the |
| 1429 | # basket page and check for themselves -- and the free-postage |
| 1430 | # threshold on the same pre-discount subtotal, so "free over $50" means |
| 1431 | # what the banner says rather than what a code left behind. |
| 1432 | quoted = object_cart.checkout_totals(items, **charges) |
| 1433 | promo = _promotion_gate(base, request, quoted["subtotal_cents"], |
| 1434 | quoted["shipping_cents"], today) |
| 1435 | card = _gift_card_gate(base, request) |
| 1436 | money_problems = promo["problems"] + card["problems"] |
| 1437 | |
| 1438 | if (blockers["inactive"] or blockers["unavailable"] or pickup["problems"] |
| 1439 | or money_problems): |
| 1440 | # One 409 carrying everything wrong with this checkout. The |
| 1441 | # sentence changes depending on what is actually broken, because |
| 1442 | # "some items cannot be ordered right now" over a perfectly good |
| 1443 | # basket whose only problem is a full 6pm slot is a message that |
| 1444 | # sends the shopper looking in the wrong place. |
| 1445 | # |
| 1446 | # The code and the card are refused HERE, beside the stock and the |
| 1447 | # slot, and never on their own: a shopper told their code expired, |
| 1448 | # who finds another and is then told an item is out of stock, is a |
| 1449 | # shopper who has left. |
| 1450 | items_wrong = bool(blockers["inactive"] or blockers["unavailable"]) |
| 1451 | if items_wrong and pickup["problems"]: |
| 1452 | error = ("Some items cannot be ordered right now, and the " |
| 1453 | "collection time is no longer available.") |
| 1454 | elif items_wrong: |
| 1455 | error = "Some items cannot be ordered right now." |
| 1456 | elif pickup["problems"]: |
| 1457 | error = " ".join(pickup["problems"]) |
| 1458 | else: |
| 1459 | error = " ".join(money_problems) |
| 1460 | refusal = {"status": 409, |
| 1461 | "error": error, |
| 1462 | "unavailable": blockers["unavailable"], |
| 1463 | "inactive": blockers["inactive"], |
| 1464 | **(_slot_refusal(pickup) if pickup["problems"] else {})} |
| 1465 | if money_problems: |
| 1466 | # Both lists, separately, so a storefront can put each sentence |
| 1467 | # under the box it belongs to instead of next to the basket. |
| 1468 | refusal["money_problems"] = money_problems |
| 1469 | if promo["problems"]: |
| 1470 | refusal["promo_problems"] = promo["problems"] |
| 1471 | if card["problems"]: |
| 1472 | refusal["gift_card_problems"] = card["problems"] |
| 1473 | # Somebody wanted something the shop refused to sell them, and the |
| 1474 | # seller asked to be told about it (products.backorder_policy = |
| 1475 | # notify). Written on the REFUSAL path deliberately: this is the |
| 1476 | # only moment the interest exists, and forgetting it is how the |
| 1477 | # same customer is lost twice. |
| 1478 | # |
| 1479 | # Not on a PREVIEW, though. A preview is a look, and the rule that |
| 1480 | # a preview writes nothing has to hold on the refusal path too or |
| 1481 | # it does not hold at all -- a storefront that quotes the basket |
| 1482 | # before submitting it would otherwise file a waiting list entry |
| 1483 | # for everybody who glanced at an empty shelf. |
| 1484 | if not _truthy(request.get("preview")): |
| 1485 | recorded = _record_notify_interest(base, blockers["notify"], |
| 1486 | products, email, today, cart) |
| 1487 | if recorded: |
| 1488 | refusal["interest_recorded"] = recorded |
| 1489 | return refusal |
| 1490 | |
| 1491 | summary = object_cart.checkout_totals( |
| 1492 | items, **charges, |
| 1493 | # A price reduction: off the taxable base, before tax. |
| 1494 | discount_cents=promo["discount_cents"], |
| 1495 | discount_on=promo["applies_to"], |
| 1496 | # Tender: after tax, changing no price and no taxable base. |
| 1497 | credit_cents=card["available_cents"]) |
| 1498 | |
| 1499 | if _truthy(request.get("preview")): |
| 1500 | # The whole breakdown, because a preview exists so somebody can |
| 1501 | # see what they are about to owe -- a subtotal alone would hide |
| 1502 | # exactly the two numbers this preview was extended to show. |
| 1503 | # |
| 1504 | # AND IT WRITES NOTHING. No redemption row, no wallet debit, no |
| 1505 | # payment, no backorder. A preview that burned a single-use code |
| 1506 | # or drained a gift card would be a shop charging people for |
| 1507 | # looking, and every write in this object is below this return |
| 1508 | # precisely so that stays true. |
| 1509 | quote = {"ok": True, "preview": True, "cart_id": cart["id"], |
| 1510 | "subtotal_cents": summary["subtotal_cents"], |
| 1511 | "shipping_cents": summary["shipping_cents"], |
| 1512 | "shipping_free": summary["shipping_free"], |
| 1513 | "discount_cents": summary["discount_cents"], |
| 1514 | "tax_cents": summary["tax_cents"], |
| 1515 | "total_cents": summary["total_cents"], |
| 1516 | "credit_applied_cents": summary["credit_applied_cents"], |
| 1517 | "amount_due_cents": summary["amount_due_cents"], |
| 1518 | "lines": summary["lines"], |
| 1519 | "price_changes": blockers["price_changes"]} |
| 1520 | if promo["code"]: |
| 1521 | quote["promo_code"] = promo["code"] |
| 1522 | if card["code"]: |
| 1523 | quote["gift_card_code"] = card["code"] |
| 1524 | if blockers["backordered"]: |
| 1525 | quote["backordered"] = blockers["backordered"] |
| 1526 | return quote |
| 1527 | |
| 1528 | if not email: |
| 1529 | return {"status": 400, |
| 1530 | "error": "An email address is needed to send the receipt to."} |
| 1531 | |
| 1532 | order_id = object_ids.new_uuid4() |
| 1533 | # The claim comes first and every write below is behind it: only the |
| 1534 | # submit whose compare-and-set lands raises an order (see |
| 1535 | # _claim_the_cart). Below every refusal and the preview, so a refused or |
| 1536 | # previewed basket is never claimed. |
| 1537 | claimed, answer = _claim_the_cart(base, cart, order_id) |
| 1538 | if answer is not None: |
| 1539 | return answer |
| 1540 | # The order's own capability token, minted HERE and not left to |
| 1541 | # system_order_portal_link, for exactly the reason the invoice's token |
| 1542 | # below is minted here: that handler is a reaction -- post-commit and |
| 1543 | # best-effort -- which is right for an order somebody will email about |
| 1544 | # later and useless to the shopper standing at the counter now. THIS |
| 1545 | # response is what has to carry the door, and the confirmation email |
| 1546 | # composed off the very next write needs a token that already exists. |
| 1547 | # The handler only mints when a token is absent, so one that already |
| 1548 | # exists is something it skips rather than fights over. |
| 1549 | track_token = secrets.token_urlsafe(32) |
| 1550 | order_row = { |
| 1551 | "id": order_id, |
| 1552 | "doc_type": "sale", |
| 1553 | "number": f"WEB-{order_id[:8].upper()}", |
| 1554 | "customer_name": _text(request.get("customer_name")) or email, |
| 1555 | "customer_email": email, |
| 1556 | "currency": _text(cart.get("currency")) or "USD", |
| 1557 | "status": "draft", |
| 1558 | "order_date": today, |
| 1559 | # Subtotal is goods, per the schema's own definition (the sum of |
| 1560 | # the order's lines). Postage is not a line of this order, so it |
| 1561 | # cannot be in its subtotal -- it is in the total, which is what |
| 1562 | # the buyer owes. |
| 1563 | "subtotal_cents": str(summary["subtotal_cents"]), |
| 1564 | "tax_cents": str(summary["tax_cents"]), |
| 1565 | "total_cents": str(summary["total_cents"]), |
| 1566 | "notes": f"Web checkout [carts/{cart['id']}]", |
| 1567 | "owner_id": _text(cart.get("owner_id")), |
| 1568 | } |
| 1569 | if summary["shipping_cents"] and _has_field(base, "orders", "shipping_cents"): |
| 1570 | order_row["shipping_cents"] = str(summary["shipping_cents"]) |
| 1571 | # The basket discount, on the order beside the postage (orders v14), so |
| 1572 | # order_totals' total -- subtotal - discount + shipping + tax -- is what |
| 1573 | # the buyer owes rather than the goods plus tax (finding M2). |
| 1574 | if summary["discount_cents"] and _has_field(base, "orders", "discount_cents"): |
| 1575 | order_row["discount_cents"] = str(summary["discount_cents"]) |
| 1576 | |
| 1577 | # Same schema-aware posture: a shop still on orders v4 has no |
| 1578 | # portal_token column, and writing one would be rejected -- which |
| 1579 | # would cost the shopper the ORDER, not just the link. On such a shop |
| 1580 | # the response simply carries no track_path, which is honest. |
| 1581 | tracks = _has_field(base, "orders", "portal_token") |
| 1582 | if tracks: |
| 1583 | order_row["portal_token"] = track_token |
| 1584 | |
| 1585 | # The two merchandising fields, on the order the moment orders declares |
| 1586 | # them -- see the module docstring. Same schema-aware posture as |
| 1587 | # shipping_cents above: a missing column costs the packer a note (which |
| 1588 | # the cart still holds and this response still reports), a rejected |
| 1589 | # write would cost the shopper their order. |
| 1590 | notes = {"customer_note": _text(request.get("customer_note")), |
| 1591 | "gift_message": _text(request.get("gift_message"))} |
| 1592 | carried_on_cart = [] |
| 1593 | for field, value in notes.items(): |
| 1594 | if not value: |
| 1595 | continue |
| 1596 | if _has_field(base, "orders", field): |
| 1597 | order_row[field] = value |
| 1598 | else: |
| 1599 | carried_on_cart.append(field) |
| 1600 | |
| 1601 | # How this order reaches the customer, and when we said it would be |
| 1602 | # ready. Same schema-aware posture as everything above: a shop still on |
| 1603 | # orders v6 has none of these columns, and writing one would cost the |
| 1604 | # shopper the ORDER rather than the timestamp. |
| 1605 | # |
| 1606 | # requested_at and promised_at are stamped SEPARATELY and deliberately |
| 1607 | # from different places. The promise is the slot's start -- the moment |
| 1608 | # the shop committed to, and the moment the customer will walk in. The |
| 1609 | # request is what they ASKED for, which is the same thing when they |
| 1610 | # simply picked a slot and is genuinely different when a storefront |
| 1611 | # passes the time they originally wanted and could not have. Collapsing |
| 1612 | # them would erase every "you wanted 6:00, we said 6:20", which is the |
| 1613 | # only evidence a shop ever gets that its 6pm is too small. |
| 1614 | slot = pickup["slot"] |
| 1615 | if pickup["method"] and _has_field(base, "orders", "fulfillment_method"): |
| 1616 | order_row["fulfillment_method"] = pickup["method"] |
| 1617 | if slot is not None: |
| 1618 | promised = _text(slot.get("starts_at")) |
| 1619 | requested = _text(request.get("requested_at")) or promised |
| 1620 | if _has_field(base, "orders", "promised_at"): |
| 1621 | order_row["promised_at"] = promised |
| 1622 | if _has_field(base, "orders", "requested_at"): |
| 1623 | order_row["requested_at"] = requested |
| 1624 | # Which window this order took, in the one place this repo puts |
| 1625 | # provenance that has no column of its own -- the same marker |
| 1626 | # pattern the invoice below and app-billing's runner both use. |
| 1627 | # orders needs no pickup_slot_id field for it: promised_at already |
| 1628 | # answers "when", and a second copy of the link would be one more |
| 1629 | # thing that can disagree with the slot's own count. |
| 1630 | order_row["notes"] = (f"{order_row['notes']} " |
| 1631 | f"[pickup_slots/{slot['id']}]") |
| 1632 | |
| 1633 | # THE ORDER RESERVES. Every online order holds what it ordered from |
| 1634 | # this moment (object_reservations): its lines are the hold, and the |
| 1635 | # locked check on order_lines refuses a line the shelf cannot cover. |
| 1636 | # Same schema-aware posture as above -- an app-orders without the |
| 1637 | # column reserves nothing, exactly as before. |
| 1638 | if _has_field(base, "orders", "reserves_stock"): |
| 1639 | order_row["reserves_stock"] = "true" |
| 1640 | if pickup["pay_at_pickup"] and _has_field(base, "orders", "pay_at_pickup"): |
| 1641 | order_row["pay_at_pickup"] = "true" |
| 1642 | |
| 1643 | # portal_token is schema read_only so no client can choose its own; a |
| 1644 | # server-side writer passes preserve_read_only, which is exactly the |
| 1645 | # narrow escape hatch that flag exists for -- the same call the |
| 1646 | # invoice create below already makes. |
| 1647 | try: |
| 1648 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1649 | object_records.create_collection_record( |
| 1650 | "orders", order_row, base_dir=base, actor=ACTOR, |
| 1651 | preserve_read_only=True) |
| 1652 | except Exception: |
| 1653 | # No order exists, so the claim must not stand: a basket pointing |
| 1654 | # at an order that was never written would answer every retry with |
| 1655 | # "already checked out" and sell nothing. |
| 1656 | _release_the_cart(base, claimed, order_id) |
| 1657 | raise |
| 1658 | |
| 1659 | # The redemption, with the TERMS STAMPED ON IT -- written right after the |
| 1660 | # order row and BEFORE its lines, the invoice or any stock effect, |
| 1661 | # because it is where the code's caps are decided. The gate above is a |
| 1662 | # read, so any number of concurrent shoppers pass it; the cap and the |
| 1663 | # per-customer limit are a schema locked check inside this write's lock |
| 1664 | # (app-promotions hook_promotion_redemptions), so exactly the allowed |
| 1665 | # number of redemptions land. The redemption cannot come first (it |
| 1666 | # relates to the order, which must exist), so a refusal here takes back |
| 1667 | # the bare draft order, which has nothing hanging off it yet, and |
| 1668 | # releases the basket's claim: the shopper is told, nothing is billed. |
| 1669 | # Any OTHER failure to record is forgiving as before: a code that |
| 1670 | # cannot be recorded must not cost the shopper the order -- the |
| 1671 | # discount is already in the totals and a missing row undercounts. |
| 1672 | redemption_id = "" |
| 1673 | redemption_error = "" |
| 1674 | if promo["promo"] and summary["discount_cents"]: |
| 1675 | redemption_id = object_ids.new_uuid4() |
| 1676 | try: |
| 1677 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1678 | object_records.create_collection_record( |
| 1679 | "promotion_redemptions", |
| 1680 | { |
| 1681 | "id": redemption_id, |
| 1682 | # Everything object_promotions.terms() hands back is |
| 1683 | # the promotion AS IT WAS: kind, value, minimum and |
| 1684 | # stacking. Editing the promotion next month therefore |
| 1685 | # changes what the next shopper gets and restates |
| 1686 | # nothing anybody has already been given (doctrine #1). |
| 1687 | **object_promotions.terms(promo["promo"]), |
| 1688 | "order_id": order_id, |
| 1689 | "customer_email": email, |
| 1690 | # The money that actually came off, recorded rather |
| 1691 | # than rederivable: a number recomputed later from |
| 1692 | # terms that have since moved is exactly the drift the |
| 1693 | # stamp exists to prevent. |
| 1694 | "discount_cents": str(summary["discount_cents"]), |
| 1695 | "redeemed_at": datetime.now().isoformat(timespec="seconds"), |
| 1696 | "owner_id": _text(cart.get("owner_id")), |
| 1697 | }, |
| 1698 | base_dir=base, actor=ACTOR) |
| 1699 | except object_records.CheckRefusedError as exc: |
| 1700 | try: |
| 1701 | # access: guest checkout: taking back the draft order this very request just created |
| 1702 | object_records.delete_collection_record( |
| 1703 | "orders", order_id, base_dir=base, actor=ACTOR) |
| 1704 | except Exception: |
| 1705 | pass |
| 1706 | _release_the_cart(base, claimed, order_id) |
| 1707 | sentence = str(exc) |
| 1708 | return {"status": exc.status if exc.status in (409, 503) else 409, |
| 1709 | "error": sentence, "money_problems": [sentence], |
| 1710 | "promo_problems": [sentence]} |
| 1711 | except Exception as exc: |
| 1712 | redemption_id = "" |
| 1713 | redemption_error = str(exc)[:200] |
| 1714 | |
| 1715 | # The per-line instruction and its delta, carried straight through -- |
| 1716 | # see the module docstring. Same schema-aware posture as everything |
| 1717 | # else here: an app-orders that predates the columns costs the cook a |
| 1718 | # note, a rejected write would cost the shopper the order. |
| 1719 | line_extras = [field for field in ("line_note", "modifier_cents") |
| 1720 | if _has_field(base, "order_lines", field)] |
| 1721 | # Which lines the shop agreed to owe rather than to hand over today. |
| 1722 | # The MARK belongs on the order line, because the picker and the packer |
| 1723 | # read the order and a fact that lives only on a basket is a fact the |
| 1724 | # warehouse never sees -- but order_lines does not declare the column |
| 1725 | # yet (app-orders is not this slice's to change), so the same |
| 1726 | # schema-aware posture every other field here uses applies: it is |
| 1727 | # written the day it exists, and until then the backorders ROW below |
| 1728 | # carries it. See the module docstring's KNOWN GAP. |
| 1729 | backordered_items = {row["cart_item_id"]: row |
| 1730 | for row in blockers["backordered"]} |
| 1731 | marks_backorders = _has_field(base, "order_lines", "backordered") |
| 1732 | line_ids = {} |
| 1733 | for line in summary["lines"]: |
| 1734 | order_line = { |
| 1735 | "id": object_ids.new_uuid4(), |
| 1736 | "order_id": order_id, |
| 1737 | "product_id": line["product_id"], |
| 1738 | "description": line["description"], |
| 1739 | "quantity": line["quantity"], |
| 1740 | "unit_price_cents": str(line["unit_price_cents"]), |
| 1741 | "line_total_cents": str(line["line_total_cents"]), |
| 1742 | "owner_id": _text(cart.get("owner_id")), |
| 1743 | } |
| 1744 | if "line_note" in line_extras: |
| 1745 | order_line["line_note"] = _kitchen_note( |
| 1746 | line, extras_of.get(line["cart_item_id"])) |
| 1747 | if "modifier_cents" in line_extras: |
| 1748 | order_line["modifier_cents"] = str(line.get("modifier_cents") or 0) |
| 1749 | if marks_backorders and line["cart_item_id"] in backordered_items: |
| 1750 | order_line["backordered"] = "true" |
| 1751 | try: |
| 1752 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1753 | object_records.create_collection_record( |
| 1754 | "order_lines", order_line, base_dir=base, actor=ACTOR) |
| 1755 | except Exception as exc: |
| 1756 | # The hold was refused inside the lock (or the line could not |
| 1757 | # be written at all): another checkout took the goods between |
| 1758 | # the gate's read and this write. Nothing below has happened |
| 1759 | # yet -- no invoice, no redemption, no card, no slot -- so the |
| 1760 | # order is taken back whole and the shopper is told, exactly |
| 1761 | # as if the gate had seen it. |
| 1762 | _undo_the_order(base, claimed, order_id, list(line_ids.values())) |
| 1763 | return _lost_the_race(base, items, products, exc) |
| 1764 | line_ids[line["cart_item_id"]] = order_line["id"] |
| 1765 | |
| 1766 | # The backorders themselves, once the order exists to point at. Written |
| 1767 | # here rather than beside the blockers because a row naming an order id |
| 1768 | # that was never created would be a queue full of ghosts. |
| 1769 | backordered = _record_backorders(base, blockers["backordered"], order_id, |
| 1770 | line_ids, email, today, cart) |
| 1771 | |
| 1772 | # The cart was CLAIMED for this order before anything was written (see |
| 1773 | # _claim_the_cart); this stamp finishes the job -- the terminal status |
| 1774 | # and what the shopper typed. |
| 1775 | stamp = {"status": "checked_out", "checked_out_order_id": order_id, |
| 1776 | "customer_email": email, |
| 1777 | "customer_name": _text(request.get("customer_name"))} |
| 1778 | # Always on the cart, whether or not orders took them: this is where |
| 1779 | # the shopper typed them, and it is the only copy that survives a shop |
| 1780 | # whose orders schema has not caught up yet. |
| 1781 | stamp.update({field: value for field, value in notes.items() if value}) |
| 1782 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1783 | object_records.update_collection_record( |
| 1784 | "carts", cart["id"], stamp, base_dir=base, actor=ACTOR) |
| 1785 | |
| 1786 | # The window's own count, incremented once the order exists. Two |
| 1787 | # shoppers racing for the last place can still both WIN -- the gate |
| 1788 | # above is a read, and that is the documented, accepted race (see the |
| 1789 | # module docstring) -- but neither increment is lost any more: the |
| 1790 | # write is a compare-and-set that re-reads on conflict, so two orders |
| 1791 | # leave the count two higher (_count_the_slot). Deliberately NOT |
| 1792 | # clamped to capacity: clamping would make an oversell invisible, and |
| 1793 | # the whole reason this number is stored on the row is so a shop can |
| 1794 | # SEE that it happened and ring somebody. A slot that cannot be counted |
| 1795 | # never costs a shopper the order they have already placed; it is |
| 1796 | # reported in the response instead of swallowed. |
| 1797 | slot_error = _count_the_slot(base, slot["id"]) if slot is not None else "" |
| 1798 | |
| 1799 | # From here on the sale is already made. Everything below is wrapped so |
| 1800 | # that an invoicing problem costs the shopper a pay link, not the order |
| 1801 | # they just placed -- see the module docstring. |
| 1802 | invoice_id = "" |
| 1803 | pay_path = "" |
| 1804 | invoice_error = "" |
| 1805 | try: |
| 1806 | invoice_id = object_ids.new_uuid4() |
| 1807 | due_days = _int(_setting(base, "billing.invoice_due_days", DEFAULT_DUE_DAYS), |
| 1808 | DEFAULT_DUE_DAYS) |
| 1809 | # The token is minted HERE rather than left to |
| 1810 | # system_invoice_portal_link. That handler is a reaction -- |
| 1811 | # post-commit and best-effort -- which is right for an invoice that |
| 1812 | # will be emailed, and useless to a shopper standing at the counter |
| 1813 | # now: THIS response is what has to carry the door. The handler only |
| 1814 | # mints when a token is absent, so a token that already exists is |
| 1815 | # something it tolerates rather than fights over. |
| 1816 | token = secrets.token_urlsafe(24) |
| 1817 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1818 | object_records.create_collection_record( |
| 1819 | "invoices", |
| 1820 | { |
| 1821 | "id": invoice_id, |
| 1822 | # Same number as the order: one human reference for the |
| 1823 | # whole sale, so "WEB-1A2B3C4D" means one thing to the |
| 1824 | # shopper, the packer and the bookkeeper alike. |
| 1825 | "number": f"WEB-{order_id[:8].upper()}", |
| 1826 | "customer_name": _text(request.get("customer_name")) or email, |
| 1827 | "customer_email": email, |
| 1828 | "currency": _text(cart.get("currency")) or "USD", |
| 1829 | "status": "sent", |
| 1830 | "issue_date": today, |
| 1831 | "due_date": (date.fromisoformat(today) |
| 1832 | + timedelta(days=due_days)).isoformat(), |
| 1833 | # The invoice's subtotal IS the sum of its own lines -- |
| 1834 | # goods plus the postage line below -- and its total is |
| 1835 | # that plus tax. Exactly the arithmetic the schema |
| 1836 | # describes, so invoice_totals restating it one day finds |
| 1837 | # the same numbers rather than an argument. |
| 1838 | "subtotal_cents": str(summary["subtotal_cents"] |
| 1839 | + summary["shipping_cents"] |
| 1840 | - summary["discount_cents"]), |
| 1841 | "tax_cents": str(summary["tax_cents"]), |
| 1842 | "total_cents": str(summary["total_cents"]), |
| 1843 | # Provenance in notes, the house pattern: invoices carry no |
| 1844 | # generated_from column, so the marker goes where it can be |
| 1845 | # found again by anyone asking where this bill came from. |
| 1846 | "notes": f"Generated by {ACTOR} [orders/{order_id}]", |
| 1847 | "source_order_id": order_id, |
| 1848 | "portal_token": token, |
| 1849 | "owner_id": _text(cart.get("owner_id")), |
| 1850 | }, |
| 1851 | # portal_token is schema read_only so no client can choose its |
| 1852 | # own; a server-side writer passes preserve_read_only, which is |
| 1853 | # exactly the narrow escape hatch that flag exists for. |
| 1854 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 1855 | |
| 1856 | # Every line is built first and written after, because each taxable |
| 1857 | # line is STAMPED with the rate and its share of the tax (decision |
| 1858 | # 2, 2026-11-30): the tax is computed once over the taxable sale |
| 1859 | # (object_cart.checkout_totals, one rate, rounded half-up) and |
| 1860 | # shared out by object_lines.allocate_tax -- the odd cent to the |
| 1861 | # line with the largest remainder -- so the lines add up to the |
| 1862 | # invoice and a void, a refund or a credit note can take back |
| 1863 | # exactly what one line carried, at the rate it was sold at. |
| 1864 | rate = charges["tax_rate_bps"] |
| 1865 | invoice_lines = [] |
| 1866 | for line in summary["lines"]: |
| 1867 | # The invoice line's unit price is the EFFECTIVE one -- the |
| 1868 | # catalogue price plus the line's modifier -- so the invoice |
| 1869 | # stays an ordinary quantity x price document that adds up |
| 1870 | # when anybody multiplies it out. The NOTE is not on the |
| 1871 | # invoice at all: it is an instruction to the kitchen, not a |
| 1872 | # term of the sale. |
| 1873 | modifier = int(line.get("modifier_cents") or 0) |
| 1874 | invoice_line = { |
| 1875 | "id": object_ids.new_uuid4(), |
| 1876 | "invoice_id": invoice_id, |
| 1877 | "description": _invoice_description( |
| 1878 | line, extras_of.get(line["cart_item_id"]) or ()), |
| 1879 | "quantity": line["quantity"], |
| 1880 | "unit_price_cents": str(line["unit_price_cents"] + modifier), |
| 1881 | "line_total_cents": str(line["line_total_cents"]), |
| 1882 | "owner_id": _text(cart.get("owner_id")), |
| 1883 | } |
| 1884 | if rate: |
| 1885 | invoice_line["tax_rate_bps"] = str(rate) |
| 1886 | # The order line this bills. Without it the two documents of |
| 1887 | # one sale were linked only by a matching description, so a |
| 1888 | # void or a correction on one could not find the other and |
| 1889 | # they drifted (Corner Cup: a soup edited into a salad on the |
| 1890 | # order and, separately, on the invoice). read_only: no client |
| 1891 | # sets it, this writer does. |
| 1892 | if line_ids.get(line["cart_item_id"]) and _has_field( |
| 1893 | base, "invoice_lines", "order_line_id"): |
| 1894 | invoice_line["order_line_id"] = line_ids[line["cart_item_id"]] |
| 1895 | invoice_lines.append(invoice_line) |
| 1896 | |
| 1897 | if summary["shipping_cents"]: |
| 1898 | # Postage as its own line, only when there is postage to |
| 1899 | # charge: a shop that does not post things must not grow a |
| 1900 | # "Shipping 0.00" row on every bill. Where postage is taxable |
| 1901 | # the line says so -- somebody auditing "was delivery taxed?" |
| 1902 | # finds the answer on the line. |
| 1903 | shipping_line = { |
| 1904 | "id": object_ids.new_uuid4(), |
| 1905 | "invoice_id": invoice_id, |
| 1906 | "description": "Shipping", |
| 1907 | "quantity": "1", |
| 1908 | "unit_price_cents": str(summary["shipping_cents"]), |
| 1909 | "line_total_cents": str(summary["shipping_cents"]), |
| 1910 | "owner_id": _text(cart.get("owner_id")), |
| 1911 | } |
| 1912 | if charges["tax_shipping"] and rate: |
| 1913 | shipping_line["tax_rate_bps"] = str(rate) |
| 1914 | invoice_lines.append(shipping_line) |
| 1915 | |
| 1916 | if summary["discount_cents"]: |
| 1917 | # THE DISCOUNT IS A LINE, and it is negative. Not a field |
| 1918 | # beside the total, and not silently baked into the goods |
| 1919 | # prices: the invoice's subtotal stays the sum of its own |
| 1920 | # lines, so anybody -- a customer, an accountant -- adds the |
| 1921 | # rows up and gets the number printed at the bottom. It |
| 1922 | # carries the rate of what it discounts (the goods, or taxable |
| 1923 | # postage), because a discount comes off the taxable base. |
| 1924 | # |
| 1925 | # It names the CODE, because "Discount -6.00" invites the |
| 1926 | # phone call that "Discount (SPRING20) -6.00" answers. |
| 1927 | discount_line = { |
| 1928 | "id": object_ids.new_uuid4(), |
| 1929 | "invoice_id": invoice_id, |
| 1930 | "description": (f"Discount ({promo['code']})" |
| 1931 | if promo["code"] else "Discount"), |
| 1932 | "quantity": "1", |
| 1933 | "unit_price_cents": str(-summary["discount_cents"]), |
| 1934 | "line_total_cents": str(-summary["discount_cents"]), |
| 1935 | "owner_id": _text(cart.get("owner_id")), |
| 1936 | } |
| 1937 | taxed = (summary["discount_on"] != "shipping") or charges["tax_shipping"] |
| 1938 | if rate and taxed: |
| 1939 | discount_line["tax_rate_bps"] = str(rate) |
| 1940 | invoice_lines.append(discount_line) |
| 1941 | |
| 1942 | shares = object_lines.allocate_tax(invoice_lines) |
| 1943 | if sum(shares) == summary["tax_cents"]: |
| 1944 | for invoice_line, share in zip(invoice_lines, shares): |
| 1945 | if invoice_line.get("tax_rate_bps"): |
| 1946 | invoice_line["line_tax_cents"] = str(share) |
| 1947 | else: |
| 1948 | # Cannot happen with one rate (the group's single rounding IS |
| 1949 | # the checkout's); if it ever does, the document's tax stands |
| 1950 | # and no line claims a share it cannot add up to. |
| 1951 | for invoice_line in invoice_lines: |
| 1952 | invoice_line.pop("tax_rate_bps", None) |
| 1953 | for invoice_line in invoice_lines: |
| 1954 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1955 | object_records.create_collection_record( |
| 1956 | "invoice_lines", invoice_line, |
| 1957 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 1958 | # The stamp is the join system_shop_fulfillment walks backwards: |
| 1959 | # a payment knows its invoice, and this is the only thing that says |
| 1960 | # which order that invoice was for. |
| 1961 | # access: guest checkout: the basket is found by its unguessable session_token; the order and its records are created for it |
| 1962 | object_records.update_collection_record( |
| 1963 | "orders", order_id, {"invoice_id": invoice_id}, |
| 1964 | base_dir=base, actor=ACTOR) |
| 1965 | pay_path = f"/pay/{token}" |
| 1966 | except Exception as exc: |
| 1967 | invoice_error = str(exc)[:200] |
| 1968 | |
| 1969 | # The card is spent LAST, and only against a bill that exists. Tender |
| 1970 | # applied to nothing is money taken off a customer for an invoice |
| 1971 | # nobody raised, so an invoicing failure above means the balance stays |
| 1972 | # where it is and the shopper is told why. |
| 1973 | card_applied = 0 |
| 1974 | card_error = "" |
| 1975 | if card["wallet"] and summary["credit_applied_cents"] and invoice_id: |
| 1976 | card_applied, card_error = _spend_the_card( |
| 1977 | base, card["wallet"], summary["credit_applied_cents"], |
| 1978 | order_id=order_id, invoice_id=invoice_id, today=today, |
| 1979 | owner_id=_text(cart.get("owner_id"))) |
| 1980 | if card["wallet"] and summary["credit_applied_cents"] and not invoice_id: |
| 1981 | card_error = ("the invoice could not be raised, so the gift card was " |
| 1982 | "not charged; its balance is untouched") |
| 1983 | if card_error and not card_applied: |
| 1984 | # The card did not pay, so the customer owes the whole bill. Say so |
| 1985 | # in the totals rather than only in a warning nobody parses. |
| 1986 | summary = {**summary, "credit_applied_cents": 0, |
| 1987 | "amount_due_cents": summary["total_cents"]} |
| 1988 | elif card["wallet"] and card_applied != summary["credit_applied_cents"]: |
| 1989 | # The card paid PART: another checkout spent some of it between the |
| 1990 | # gate's read and this debit. What it did pay is tender; the rest |
| 1991 | # is owed, and the totals say so. |
| 1992 | summary = {**summary, "credit_applied_cents": card_applied, |
| 1993 | "amount_due_cents": summary["total_cents"] - card_applied} |
| 1994 | |
| 1995 | # total_cents is the GRAND total: what the payer owes, including |
| 1996 | # postage and tax. A response whose "total" was the goods subtotal |
| 1997 | # would be the number a payment gets built from, and the shop would |
| 1998 | # quietly collect the wrong amount. |
| 1999 | result = {"ok": True, "order_id": order_id, "cart_id": cart["id"], |
| 2000 | "subtotal_cents": summary["subtotal_cents"], |
| 2001 | "shipping_cents": summary["shipping_cents"], |
| 2002 | "shipping_free": summary["shipping_free"], |
| 2003 | "discount_cents": summary["discount_cents"], |
| 2004 | "tax_cents": summary["tax_cents"], |
| 2005 | "total_cents": summary["total_cents"], |
| 2006 | "credit_applied_cents": summary["credit_applied_cents"], |
| 2007 | "amount_due_cents": summary["amount_due_cents"], |
| 2008 | "lines": len(summary["lines"]), |
| 2009 | "status_of_order": "draft", |
| 2010 | "note": "order raised; stock moves and the order confirms when " |
| 2011 | "payment arrives"} |
| 2012 | if promo["code"]: |
| 2013 | result["promo_code"] = promo["code"] |
| 2014 | if redemption_id: |
| 2015 | result["redemption_id"] = redemption_id |
| 2016 | if redemption_error: |
| 2017 | # Reported, never swallowed: the discount was given and the |
| 2018 | # count of it did not land, so a limit is now one use looser |
| 2019 | # than the shop thinks and somebody has to know. |
| 2020 | result["redemption_error"] = redemption_error |
| 2021 | if card["code"]: |
| 2022 | result["gift_card_code"] = card["code"] |
| 2023 | result["gift_card_applied_cents"] = card_applied |
| 2024 | if card_error: |
| 2025 | result["gift_card_error"] = card_error |
| 2026 | if backordered: |
| 2027 | # Named in the response because the shopper has just bought |
| 2028 | # something that is not in the building, and a confirmation that |
| 2029 | # did not say so is how a parcel becomes a complaint. |
| 2030 | result["backordered"] = backordered |
| 2031 | result["note"] = ("order raised; some lines are backordered and ship " |
| 2032 | "when stock arrives. Stock moves and the order " |
| 2033 | "confirms when payment arrives") |
| 2034 | if pickup["method"]: |
| 2035 | # Only on an order that actually chose a method. A shipping |
| 2036 | # checkout's response is exactly the dict it was before pickup |
| 2037 | # existed -- no empty "fulfillment_method": "shipping" key, no |
| 2038 | # blank promised_at -- because a caller that has never sent these |
| 2039 | # arguments must not have to learn them. |
| 2040 | result["fulfillment_method"] = pickup["method"] |
| 2041 | if slot is not None: |
| 2042 | result["pickup_slot_id"] = slot["id"] |
| 2043 | result["promised_at"] = _text(slot.get("starts_at")) |
| 2044 | if slot_error: |
| 2045 | result["pickup_slot_error"] = slot_error |
| 2046 | if order_row.get("reserves_stock"): |
| 2047 | held_until = _held_until(base, pickup, slot) |
| 2048 | if held_until: |
| 2049 | # Until when the goods are kept for this shopper if nothing |
| 2050 | # is paid -- what somebody about to drive to the shop needs |
| 2051 | # to know. Absent when the hold does not lapse, and on a |
| 2052 | # shipping order, whose response is exactly what it was. |
| 2053 | result["held_until"] = held_until |
| 2054 | if tracks: |
| 2055 | # The customer's own door, alongside the pay link and for the same |
| 2056 | # reason: this shop sells to guests, so the response and the |
| 2057 | # confirmation email are the only two places the buyer will ever |
| 2058 | # be handed a way back to their own order. |
| 2059 | result["track_path"] = f"/orders/track/{track_token}" |
| 2060 | if carried_on_cart: |
| 2061 | # Reported, not swallowed. Somebody has to know that what the |
| 2062 | # shopper typed did not reach the order the packer will read. |
| 2063 | result["notes_on_cart_only"] = carried_on_cart |
| 2064 | if invoice_error: |
| 2065 | # Say what went wrong rather than returning a cheerful ok: somebody |
| 2066 | # has to raise this bill, and they can only do that if the failure |
| 2067 | # was reported instead of swallowed. |
| 2068 | result["invoice_error"] = invoice_error |
| 2069 | result["note"] = ("order raised, but the invoice could not be: " |
| 2070 | f"{invoice_error}. The order stands and the invoice " |
| 2071 | "can be raised again.") |
| 2072 | else: |
| 2073 | result["invoice_id"] = invoice_id |
| 2074 | result["pay_path"] = pay_path |
| 2075 | return result |