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.
object_cart.py · 31.1 KB · 700 lines
| 1 | """The basket: what somebody intends to buy, before they commit. |
| 2 | |
| 3 | Pure arithmetic and pure decisions, testable without a data directory -- |
| 4 | same posture as object_billing, object_rates and object_money. |
| 5 | |
| 6 | **A basket is not an order.** An order is a commitment: it has a number, |
| 7 | a customer, a books consequence and a place in a sequence somebody |
| 8 | counts. A basket is a browsing artefact that usually gets abandoned. |
| 9 | Modelling one as a draft order fills the order sequence with junk and |
| 10 | makes "how many orders did we take?" unanswerable, which is why carts are |
| 11 | their own collection with their own lifetime. |
| 12 | |
| 13 | **Price is stamped when it goes in, and re-checked at checkout.** A price |
| 14 | that moves while somebody shops must not silently change what they |
| 15 | agreed to; a basket that sat for three weeks must not hold the seller to |
| 16 | a stale price either. So both numbers are kept and the disagreement is |
| 17 | SURFACED rather than resolved in secret -- the same instinct as stamping |
| 18 | a rate at approval, and refusing to let a later change restate it. |
| 19 | |
| 20 | **An instruction is not a product.** A large latte is genuinely its own |
| 21 | product with its own SKU, price and stock, and variants-as-products |
| 22 | already handles that. "No onions" is not a product: it has no SKU, it is |
| 23 | true of one line of one order, and a catalogue row per instruction would |
| 24 | be thousands of dead products nobody can sell. So a line carries |
| 25 | `line_note` and `modifier_cents` -- "oat milk +60c" is the same |
| 26 | instruction with a price delta, which is why the delta lives on the line |
| 27 | rather than in the price book. The delta is money and goes through the |
| 28 | same single fold as everything else; the note is not money and moves no |
| 29 | total anywhere. What a delta COSTS is never the basket's to say: the |
| 30 | product declares its extras and their prices (`declared_modifiers`), a |
| 31 | line names the ones it carries, and the price is looked up -- the basket |
| 32 | is public, and a price a request states is a price a stranger states. |
| 33 | |
| 34 | **Availability is decided at checkout, never at add.** Reserving stock |
| 35 | when somebody drops a thing in a basket is how a shop shows "sold out" |
| 36 | for goods nobody bought. |
| 37 | |
| 38 | **Tax and postage are computed here, once.** They are arithmetic on a |
| 39 | sale, so they belong beside the rest of the sale's arithmetic rather |
| 40 | than in the checkout action, the invoice writer and the basket page |
| 41 | separately. `checkout_totals` is the single fold every one of those |
| 42 | callers restates; nothing else is allowed to add up its own version. |
| 43 | """ |
| 44 | |
| 45 | from __future__ import annotations |
| 46 | |
| 47 | import json |
| 48 | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 49 | from typing import Any |
| 50 | |
| 51 | |
| 52 | def _text(value: Any) -> str: |
| 53 | return str(value if value is not None else "").strip() |
| 54 | |
| 55 | |
| 56 | def _num(value: Any, default: int = 0) -> Decimal: |
| 57 | try: |
| 58 | return Decimal(_text(value) or str(default)) |
| 59 | except (InvalidOperation, TypeError, ValueError): |
| 60 | return Decimal(default) |
| 61 | |
| 62 | |
| 63 | def _int(value: Any, default: int = 0) -> int: |
| 64 | try: |
| 65 | return int(_text(value) or default) |
| 66 | except (TypeError, ValueError): |
| 67 | return default |
| 68 | |
| 69 | |
| 70 | def line_total_cents(quantity: Any, unit_price_cents: Any, |
| 71 | modifier_cents: Any = 0) -> int: |
| 72 | """One line's money, rounded half-up once. |
| 73 | |
| 74 | Fractional quantities are real (1.5 kg, 2.5 hours of setup), so this |
| 75 | is a Decimal multiplication rather than an integer one -- and the |
| 76 | rounding happens here, per line, so the basket total always equals the |
| 77 | sum of the lines a shopper can see. |
| 78 | |
| 79 | `modifier_cents` is the per-line instruction's price delta -- "oat |
| 80 | milk +60c" -- and it is added to the UNIT price rather than to the |
| 81 | line: two oat lattes are two lots of oat milk, and a delta applied |
| 82 | once to a line of six would be a shop giving away five of them. It is |
| 83 | inside this number rather than beside it because every total |
| 84 | downstream (basket, checkout preview, order, invoice) is a sum of |
| 85 | line totals, and money that reaches one of those and not another is |
| 86 | the bug this whole codebase is organised against. |
| 87 | """ |
| 88 | total = _num(quantity) * (_num(unit_price_cents) + _num(modifier_cents)) |
| 89 | if total <= 0: |
| 90 | return 0 |
| 91 | return int(total.to_integral_value(rounding=ROUND_HALF_UP)) |
| 92 | |
| 93 | |
| 94 | def totals(items: list[dict]) -> dict: |
| 95 | """What the basket comes to: {"lines", "subtotal_cents", "count"}. |
| 96 | |
| 97 | Each line carries its instruction (`line_note`) and its delta |
| 98 | (`modifier_cents`) through to every caller, because the callers are |
| 99 | the order writer, the invoice writer and the page -- and a note that |
| 100 | stops here is a note the cook never reads. Both are read with .get: |
| 101 | a basket written before those columns existed is still a basket. |
| 102 | """ |
| 103 | lines = [] |
| 104 | subtotal = 0 |
| 105 | count = Decimal(0) |
| 106 | for item in items: |
| 107 | quantity = _num(item.get("quantity")) |
| 108 | if quantity <= 0: |
| 109 | continue |
| 110 | modifier = _int(item.get("modifier_cents")) |
| 111 | amount = line_total_cents(quantity, item.get("unit_price_cents"), |
| 112 | modifier) |
| 113 | lines.append({ |
| 114 | "cart_item_id": _text(item.get("id")), |
| 115 | "product_id": _text(item.get("product_id")), |
| 116 | "description": _text(item.get("description")), |
| 117 | "quantity": str(quantity), |
| 118 | "unit_price_cents": _int(item.get("unit_price_cents")), |
| 119 | "modifier_cents": modifier, |
| 120 | "line_note": _text(item.get("line_note")), |
| 121 | "line_total_cents": amount, |
| 122 | }) |
| 123 | subtotal += amount |
| 124 | count += quantity |
| 125 | return {"lines": lines, "subtotal_cents": subtotal, "count": str(count)} |
| 126 | |
| 127 | |
| 128 | def tax_cents(taxable_cents: Any, rate_bps: Any) -> int: |
| 129 | """Tax on a taxable base, rounded half-up ONCE. |
| 130 | |
| 131 | Basis points, matching invoice_lines' own convention: 1500 = 15%, |
| 132 | 825 = 8.25%. 0 means the shop charges no tax, which is a real answer |
| 133 | and not a missing setting -- plenty of small sellers genuinely owe |
| 134 | none, and a shop that cannot express that would have to lie. |
| 135 | |
| 136 | Rounded once, on the whole taxable amount, rather than per line. Tax |
| 137 | is owed on a sale, not on each row of it, and rounding each row first |
| 138 | accumulates a cent of error per line that nobody can reconcile: four |
| 139 | fifty-cent lines at 5% are 10c of tax, not the 12c that four |
| 140 | separately-rounded 2.5c lines come to. The single rounding is also |
| 141 | the only version a customer can check with a calculator. |
| 142 | """ |
| 143 | base = _num(taxable_cents) |
| 144 | rate = _num(rate_bps) |
| 145 | if base <= 0 or rate <= 0: |
| 146 | return 0 |
| 147 | return int((base * rate / Decimal(10000)).to_integral_value( |
| 148 | rounding=ROUND_HALF_UP)) |
| 149 | |
| 150 | |
| 151 | def shipping_cents(subtotal_cents: Any, flat_cents: Any, |
| 152 | free_over_cents: Any = 0) -> int: |
| 153 | """What the shop charges to send this basket: flat, or nothing. |
| 154 | |
| 155 | One flat rate, because a real carrier quote needs an address, a |
| 156 | weight and a connector, and a shop that cannot charge postage at all |
| 157 | until that exists is a shop losing money on every parcel today. A |
| 158 | flat rate is honest about being a flat rate; a fake calculated one |
| 159 | would not be. |
| 160 | |
| 161 | `free_over_cents` is the free-shipping threshold, and it is here in |
| 162 | v1 on purpose: it is the one discount every small shop actually |
| 163 | runs. "Free delivery over $50" is a pricing lever, a basket-size |
| 164 | nudge and a thing customers look for by name, and leaving it out |
| 165 | would push every seller into faking it with a discount code. |
| 166 | |
| 167 | flat_cents of 0 means shipping is disabled entirely -- a digital-only |
| 168 | shop charges no postage and must not be made to show a zero line. |
| 169 | """ |
| 170 | flat = _int(flat_cents) |
| 171 | if flat <= 0: |
| 172 | return 0 |
| 173 | threshold = _int(free_over_cents) |
| 174 | if threshold > 0 and _int(subtotal_cents) >= threshold: |
| 175 | return 0 |
| 176 | return flat |
| 177 | |
| 178 | |
| 179 | def checkout_totals(items: list[dict], *, tax_rate_bps: Any = 0, |
| 180 | tax_shipping: bool = False, |
| 181 | shipping_flat_cents: Any = 0, |
| 182 | free_over_cents: Any = 0, |
| 183 | discount_cents: Any = 0, |
| 184 | discount_on: str = "goods", |
| 185 | credit_cents: Any = 0) -> dict: |
| 186 | """The whole bill: {"lines", "subtotal_cents", "shipping_cents", |
| 187 | "tax_cents", "discount_cents", "total_cents", "credit_applied_cents", |
| 188 | "amount_due_cents", "shipping_free", "count"}. |
| 189 | |
| 190 | ONE function, so the arithmetic of a sale exists in exactly one |
| 191 | place. The order, the invoice, the basket page and the preview all |
| 192 | call this and then RESTATE what it said -- none of them may add up |
| 193 | their own version. Money that is computed twice is money that |
| 194 | disagrees with itself eventually, and the disagreement always |
| 195 | surfaces as a customer holding an invoice whose lines do not come to |
| 196 | its total. |
| 197 | |
| 198 | `subtotal_cents` is goods only. Shipping is a separate charge and a |
| 199 | separate invoice LINE, so the invoice total stays the sum of its own |
| 200 | lines plus tax, and a customer can see what the postage cost instead |
| 201 | of finding it baked into a total they cannot check. |
| 202 | |
| 203 | `tax_shipping` decides whether the postage is part of the taxable |
| 204 | base. Jurisdictions genuinely disagree about this -- some tax |
| 205 | delivery on a taxable order, some never do -- so it is a setting the |
| 206 | seller chooses, not a rule this file invents for them. |
| 207 | |
| 208 | `shipping_free` says the threshold was MET rather than that shipping |
| 209 | happens to be zero. The page needs to tell somebody they earned free |
| 210 | delivery, and a bare 0 cannot distinguish "you saved the postage" |
| 211 | from "this shop does not post things". |
| 212 | |
| 213 | **A DISCOUNT COMES OFF THE TAXABLE BASE BEFORE TAX IS COMPUTED.** That |
| 214 | is not a preference; it is what every jurisdiction that levies a sales |
| 215 | or value-added tax actually requires. Tax is owed on the CONSIDERATION |
| 216 | -- what the buyer actually gives up -- and a seller's own price |
| 217 | reduction reduces it. Charging tax on the pre-discount price collects |
| 218 | money from the customer that the shop then either remits on revenue it |
| 219 | never earned or keeps, and both of those are the kind of small |
| 220 | systematic error an audit finds by multiplying one rate by one column. |
| 221 | So the discount is subtracted here, before tax_cents is called, and |
| 222 | never afterwards. |
| 223 | |
| 224 | `discount_on` says which half of the bill the reduction comes off -- |
| 225 | "goods" (a percentage or a fixed amount) or "shipping" (a free-postage |
| 226 | promotion) -- because where a jurisdiction taxes delivery, free |
| 227 | postage must remove that tax too. The discount is CLAMPED to the base |
| 228 | it comes off, so no combination of arguments can produce a negative |
| 229 | total: a shop does not owe money to somebody for shopping. |
| 230 | |
| 231 | `credit_cents` is TENDER, not a price reduction -- a gift card or |
| 232 | store credit -- and it therefore lands AFTER tax and changes no |
| 233 | taxable base at all. A gift card is money the customer already gave |
| 234 | the shop; treating it as a discount would let a shop sell $100 of |
| 235 | goods and remit tax on $60, which is fraud with a rounding error's |
| 236 | face. So `total_cents` stays the value of the SALE (what the order is |
| 237 | worth, what the books see) and `amount_due_cents` is what is left to |
| 238 | pay after the credit is applied. Where no credit is used the two are |
| 239 | identical, which is every existing caller. |
| 240 | """ |
| 241 | summary = totals(items) |
| 242 | subtotal = summary["subtotal_cents"] |
| 243 | postage = shipping_cents(subtotal, shipping_flat_cents, free_over_cents) |
| 244 | |
| 245 | wanted = max(0, _int(discount_cents)) |
| 246 | on_shipping = _text(discount_on).lower() == "shipping" |
| 247 | goods_off = 0 if on_shipping else min(wanted, subtotal) |
| 248 | postage_off = min(wanted, postage) if on_shipping else 0 |
| 249 | discount = goods_off + postage_off |
| 250 | |
| 251 | taxable = (subtotal - goods_off) + ((postage - postage_off) |
| 252 | if tax_shipping else 0) |
| 253 | tax = tax_cents(taxable, tax_rate_bps) |
| 254 | total = subtotal + postage - discount + tax |
| 255 | credit = min(max(0, _int(credit_cents)), total) |
| 256 | return { |
| 257 | "lines": summary["lines"], |
| 258 | "count": summary["count"], |
| 259 | "subtotal_cents": subtotal, |
| 260 | "shipping_cents": postage, |
| 261 | "shipping_free": bool(_int(shipping_flat_cents) > 0 and postage == 0), |
| 262 | "discount_cents": discount, |
| 263 | "discount_on": "shipping" if on_shipping else "goods", |
| 264 | "taxable_cents": taxable, |
| 265 | "tax_cents": tax, |
| 266 | "total_cents": total, |
| 267 | "credit_applied_cents": credit, |
| 268 | "amount_due_cents": total - credit, |
| 269 | } |
| 270 | |
| 271 | |
| 272 | # --- what a public basket may say about money --------------------------------- |
| 273 | # |
| 274 | # action_cart is a PUBLIC object, so every number a request can put on a line |
| 275 | # is a number a stranger can put on a line. The rule these helpers enforce is |
| 276 | # the one the cart_items schema always claimed and the cart never did: the |
| 277 | # request may say WHICH extra and HOW MANY, never what anything costs. |
| 278 | |
| 279 | # A unit that is a count, not a measure. Blank is the ordinary case and means |
| 280 | # "each": a latte is sold in lattes. |
| 281 | COUNTED_UNITS = ("", "each", "ea", "item", "items", "unit", "units", "pc", |
| 282 | "pcs", "piece", "pieces") |
| 283 | |
| 284 | |
| 285 | def declared_modifiers(product: dict | None) -> dict[str, int]: |
| 286 | """The priced extras a product's seller has declared: {label: cents}. |
| 287 | |
| 288 | products.modifiers is a small JSON object -- {"Oat milk": 60, |
| 289 | "Extra shot": 80, "No onions": 0}. Read here so the cart, the checkout |
| 290 | and the page agree about what an extra is and what it costs. |
| 291 | |
| 292 | FAILS CLOSED. Unparseable JSON, a non-object, a negative or |
| 293 | non-integer price all declare NOTHING for that entry rather than |
| 294 | something: a mistyped brace must cost the shop an extra it cannot sell, |
| 295 | never sell one at a price nobody set. A blank label is dropped for the |
| 296 | same reason -- it cannot be chosen by name. |
| 297 | """ |
| 298 | raw = _text((product or {}).get("modifiers")) |
| 299 | if not raw: |
| 300 | return {} |
| 301 | try: |
| 302 | parsed = json.loads(raw) |
| 303 | except (TypeError, ValueError): |
| 304 | return {} |
| 305 | if not isinstance(parsed, dict): |
| 306 | return {} |
| 307 | declared: dict[str, int] = {} |
| 308 | for label, cents in parsed.items(): |
| 309 | name = _text(label) |
| 310 | if not name or isinstance(cents, bool): |
| 311 | continue |
| 312 | try: |
| 313 | amount = int(_text(cents)) |
| 314 | except (TypeError, ValueError): |
| 315 | continue |
| 316 | if amount < 0: |
| 317 | continue |
| 318 | declared[name] = amount |
| 319 | return declared |
| 320 | |
| 321 | |
| 322 | def chosen_modifiers(value: Any) -> list[str]: |
| 323 | """The extras a request names, as a list of labels in the order given. |
| 324 | |
| 325 | A JSON list from an API client, or one comma-separated string from a |
| 326 | form post. Duplicates collapse: "oat milk, oat milk" is one lot of oat |
| 327 | milk, not a way to be charged twice. |
| 328 | """ |
| 329 | if isinstance(value, (list, tuple)): |
| 330 | parts = [_text(part) for part in value] |
| 331 | else: |
| 332 | raw = _text(value) |
| 333 | if raw.startswith("["): |
| 334 | try: |
| 335 | loaded = json.loads(raw) |
| 336 | except (TypeError, ValueError): |
| 337 | loaded = None |
| 338 | if isinstance(loaded, list): |
| 339 | return chosen_modifiers(loaded) |
| 340 | parts = [_text(part) for part in raw.split(",")] |
| 341 | seen: list[str] = [] |
| 342 | for part in parts: |
| 343 | if part and part.casefold() not in [s.casefold() for s in seen]: |
| 344 | seen.append(part) |
| 345 | return seen |
| 346 | |
| 347 | |
| 348 | def price_modifiers(product: dict | None, names: list[str]) -> tuple[list[str], int, list[str]]: |
| 349 | """(labels as the seller spelled them, total cents, unknown names). |
| 350 | |
| 351 | Matching is case-insensitive, and the label handed back is the |
| 352 | SELLER's spelling, so the kitchen ticket reads "Oat milk" whatever the |
| 353 | shopper typed. Any unknown name is returned rather than ignored: an |
| 354 | extra the shop does not offer is a refusal, not a free extra. |
| 355 | """ |
| 356 | declared = declared_modifiers(product) |
| 357 | by_fold = {label.casefold(): label for label in declared} |
| 358 | labels, unknown, total = [], [], 0 |
| 359 | for name in names: |
| 360 | label = by_fold.get(_text(name).casefold()) |
| 361 | if label is None: |
| 362 | unknown.append(_text(name)) |
| 363 | continue |
| 364 | labels.append(label) |
| 365 | total += declared[label] |
| 366 | return labels, total, unknown |
| 367 | |
| 368 | |
| 369 | def note_names_a_priced_extra(note: Any, product: dict | None, |
| 370 | chosen: list[str]) -> str: |
| 371 | """The priced extra a line note asks for by name without choosing it, |
| 372 | or "". |
| 373 | |
| 374 | "oat milk" typed into the note of a latte whose seller charges 60c for |
| 375 | oat milk is the shopper getting it free: the cook reads the note, and |
| 376 | the note is never money. This catches the plain case -- a part of the |
| 377 | note (split on commas, semicolons and new lines) that IS a priced |
| 378 | extra's label, optionally after "with", "add", "plus" or "+" -- and |
| 379 | nothing cleverer. It is a guard against the obvious, not a parser: |
| 380 | "no oat milk" is an instruction and passes, and so would a paraphrase. |
| 381 | """ |
| 382 | declared = {label.casefold(): cents |
| 383 | for label, cents in declared_modifiers(product).items()} |
| 384 | picked = {name.casefold() for name in chosen} |
| 385 | text = _text(note) |
| 386 | for separator in (";", "\n"): |
| 387 | text = text.replace(separator, ",") |
| 388 | for part in text.split(","): |
| 389 | phrase = part.strip().casefold() |
| 390 | for prefix in ("+", "with ", "add ", "plus ", "extra "): |
| 391 | if phrase.startswith(prefix) and phrase[len(prefix):].strip() in declared: |
| 392 | phrase = phrase[len(prefix):].strip() |
| 393 | break |
| 394 | if phrase and declared.get(phrase, 0) > 0 and phrase not in picked: |
| 395 | return next(label for label in declared_modifiers(product) |
| 396 | if label.casefold() == phrase) |
| 397 | return "" |
| 398 | |
| 399 | |
| 400 | def sold_by_measure(product: dict | None) -> bool: |
| 401 | """Does this product sell in fractions -- 1.5 kg, 2.5 hours? |
| 402 | |
| 403 | Only when its seller gave it a unit that is a MEASURE. A blank unit, |
| 404 | or "each", is a count, and a count is whole: 0.001 of a 400c latte |
| 405 | rounds to a 0c line, and the kitchen still makes a whole latte. |
| 406 | """ |
| 407 | return _text((product or {}).get("unit")).casefold() not in COUNTED_UNITS |
| 408 | |
| 409 | |
| 410 | def quantity_problem(quantity: Any, product: dict | None, |
| 411 | unit_price_cents: Any = None) -> str: |
| 412 | """Why this quantity cannot go on a line of this product, or "". |
| 413 | |
| 414 | Finite and positive always. Whole unless the product is sold by |
| 415 | measure. And never so small that the line rounds to nothing while the |
| 416 | product has a price: a line that costs 0 is goods handed over free. |
| 417 | """ |
| 418 | raw = _text(quantity) |
| 419 | try: |
| 420 | amount = Decimal(raw) |
| 421 | except (InvalidOperation, TypeError, ValueError): |
| 422 | return "The quantity must be a number." |
| 423 | if not amount.is_finite() or amount <= 0: |
| 424 | return "The quantity must be a number above zero." |
| 425 | name = _text((product or {}).get("name")) or "This" |
| 426 | if amount != amount.to_integral_value() and not sold_by_measure(product): |
| 427 | return f"{name} is sold in whole numbers, not {raw}." |
| 428 | price = _int((product or {}).get("price_cents") |
| 429 | if unit_price_cents is None else unit_price_cents) |
| 430 | if price > 0 and line_total_cents(amount, price) <= 0: |
| 431 | return f"{raw} is too small a quantity of {name} to charge for." |
| 432 | return "" |
| 433 | |
| 434 | |
| 435 | def line_money_problems(items: list[dict], products: dict[str, dict] |
| 436 | ) -> tuple[list[dict], list[dict]]: |
| 437 | """(modifier price changes, lines that cannot be sold as they stand). |
| 438 | |
| 439 | The basket stamps an extra's price when the line goes in, exactly as |
| 440 | it stamps the product's, and for the same reason: a price that moves |
| 441 | while somebody shops must be SHOWN, not quietly applied. So a line |
| 442 | whose extras now cost something else comes back as a change, in the |
| 443 | same shape price_changes uses, plus `kind: "modifier"`. |
| 444 | |
| 445 | A line is refused outright when its money cannot be reproduced from |
| 446 | what the shop declares: an extra the product no longer offers, a |
| 447 | delta with no declared extra behind it (a basket written before |
| 448 | extras were declared, or one a client priced itself), or a quantity |
| 449 | quantity_problem refuses. Those are not disagreements to confirm -- |
| 450 | there is no shop price to agree to -- so they land beside the |
| 451 | withdrawn products and the shopper removes the line. |
| 452 | """ |
| 453 | changed, refused = [], [] |
| 454 | for item in items: |
| 455 | product_id = _text(item.get("product_id")) |
| 456 | product = products.get(product_id) |
| 457 | if product is None or _num(item.get("quantity")) <= 0: |
| 458 | continue |
| 459 | description = _text(item.get("description")) or _text(product.get("name")) |
| 460 | problem = quantity_problem(item.get("quantity"), product) |
| 461 | if problem: |
| 462 | refused.append({"cart_item_id": _text(item.get("id")), |
| 463 | "product_id": product_id, "description": description, |
| 464 | "reason": problem}) |
| 465 | continue |
| 466 | names = chosen_modifiers(item.get("modifiers")) |
| 467 | labels, live, unknown = price_modifiers(product, names) |
| 468 | stamped = _int(item.get("modifier_cents")) |
| 469 | if unknown: |
| 470 | refused.append({"cart_item_id": _text(item.get("id")), |
| 471 | "product_id": product_id, "description": description, |
| 472 | "reason": f"no longer offered: {', '.join(unknown)}"}) |
| 473 | elif not names and stamped: |
| 474 | refused.append({"cart_item_id": _text(item.get("id")), |
| 475 | "product_id": product_id, "description": description, |
| 476 | "reason": "carries a price for an extra this shop " |
| 477 | "does not offer"}) |
| 478 | elif stamped != live: |
| 479 | changed.append({"cart_item_id": _text(item.get("id")), |
| 480 | "product_id": product_id, "description": description, |
| 481 | "kind": "modifier", "modifiers": labels, |
| 482 | "was_cents": stamped, "now_cents": live, |
| 483 | "direction": "up" if live > stamped else "down"}) |
| 484 | return changed, refused |
| 485 | |
| 486 | |
| 487 | # --- the basket's token ------------------------------------------------------- |
| 488 | # |
| 489 | # A basket is found by its session token and by nothing else, so the token |
| 490 | # is a bearer capability: whoever holds it reads the basket and checks it |
| 491 | # out (and a checked-out basket answers with its order's pay and tracking |
| 492 | # links). It used to be whatever the client sent -- "a" opened a basket on |
| 493 | # "a", and anybody who guessed it read it. The server mints it now. |
| 494 | |
| 495 | # secrets.token_urlsafe(24): 32 characters, 192 bits. |
| 496 | SESSION_TOKEN_BYTES = 24 |
| 497 | # token_urlsafe(16) is 22 characters (128 bits): the shortest a token can be |
| 498 | # and still have been minted at a strength nobody can guess. Baskets opened |
| 499 | # by site_shop before this change carry token_urlsafe(18), 24 characters, |
| 500 | # and keep working. |
| 501 | MIN_SESSION_TOKEN_LENGTH = 22 |
| 502 | _TOKEN_ALPHABET = frozenset( |
| 503 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") |
| 504 | |
| 505 | |
| 506 | def session_token_problem(token: Any) -> str: |
| 507 | """Why this token cannot name a basket for a public caller, or "". |
| 508 | |
| 509 | It must look like something the server minted: URL-safe base64 and at |
| 510 | least MIN_SESSION_TOKEN_LENGTH characters. That alone does not prove |
| 511 | the server minted it -- action_cart also refuses a token no basket has |
| 512 | ever carried -- but it does retire every short, guessable token a |
| 513 | client chose before the server minted them. |
| 514 | """ |
| 515 | text = _text(token) |
| 516 | if len(text) < MIN_SESSION_TOKEN_LENGTH or not set(text) <= _TOKEN_ALPHABET: |
| 517 | return ("That session_token was not issued by this shop. Send the " |
| 518 | "first add without one: the shop mints the token and hands " |
| 519 | "it back to keep.") |
| 520 | return "" |
| 521 | |
| 522 | |
| 523 | def price_changes(items: list[dict], products: dict[str, dict]) -> list[dict]: |
| 524 | """Lines whose product now costs something else than when it went in. |
| 525 | |
| 526 | Reported, never applied. Silently charging the new price is a |
| 527 | bait-and-switch and silently honouring the old one is an open-ended |
| 528 | liability on anything left in a basket; the only defensible move is to |
| 529 | show the shopper both numbers and let them agree again. |
| 530 | """ |
| 531 | changed = [] |
| 532 | for item in items: |
| 533 | product = products.get(_text(item.get("product_id"))) |
| 534 | if not product: |
| 535 | continue |
| 536 | was = _int(item.get("unit_price_cents")) |
| 537 | now = _int(product.get("price_cents")) |
| 538 | if now and now != was: |
| 539 | changed.append({ |
| 540 | "cart_item_id": _text(item.get("id")), |
| 541 | "product_id": _text(item.get("product_id")), |
| 542 | "description": _text(item.get("description")) |
| 543 | or _text(product.get("name")), |
| 544 | "was_cents": was, |
| 545 | "now_cents": now, |
| 546 | "direction": "up" if now > was else "down", |
| 547 | }) |
| 548 | return changed |
| 549 | |
| 550 | |
| 551 | def availability(items: list[dict], on_hand: dict[str, Any], |
| 552 | *, tracked: set[str] | None = None) -> list[dict]: |
| 553 | """Lines that cannot be filled from stock, with how many are short. |
| 554 | |
| 555 | Only products the shop actually TRACKS are checked. A service, a |
| 556 | digital download or a made-to-order item has no stock level, and |
| 557 | treating "no level recorded" as "none available" would refuse to sell |
| 558 | the very things that are always available. |
| 559 | |
| 560 | `on_hand` is what may be PROMISED -- action_checkout passes the level |
| 561 | less what live online orders hold (object_reservations) -- and it is |
| 562 | spent line by line: two lines of one product (a burger with onions and |
| 563 | one without) share one shelf, and each used to be checked against all |
| 564 | of it. `short_by` is never more than the line asked for, however far |
| 565 | below zero the shelf already is: it is what the shop would owe on THIS |
| 566 | line, which is what a backorder records. |
| 567 | """ |
| 568 | short = [] |
| 569 | left: dict[str, Decimal] = {} |
| 570 | for item in items: |
| 571 | product_id = _text(item.get("product_id")) |
| 572 | if tracked is not None and product_id not in tracked: |
| 573 | continue |
| 574 | if product_id not in on_hand: |
| 575 | continue |
| 576 | wanted = _num(item.get("quantity")) |
| 577 | have = left.get(product_id, _num(on_hand.get(product_id))) |
| 578 | left[product_id] = have - wanted |
| 579 | if wanted > have: |
| 580 | have = have if have > 0 else Decimal(0) |
| 581 | short.append({ |
| 582 | "cart_item_id": _text(item.get("id")), |
| 583 | "product_id": product_id, |
| 584 | "description": _text(item.get("description")), |
| 585 | "wanted": str(wanted), |
| 586 | "available": str(have), |
| 587 | "short_by": str(wanted - have), |
| 588 | }) |
| 589 | return short |
| 590 | |
| 591 | |
| 592 | BACKORDER_POLICIES = ("refuse", "allow", "notify") |
| 593 | |
| 594 | |
| 595 | def backorder_policy(product: dict | None) -> str: |
| 596 | """What this product's seller has said about selling it when the shelf |
| 597 | is empty: "refuse" (the default and today's behaviour), "allow" or |
| 598 | "notify". |
| 599 | |
| 600 | Absent, blank or unreadable means REFUSE. That is the whole safety of |
| 601 | this feature: a catalogue written before the column existed, a product |
| 602 | somebody imported, or a policy typed wrong all behave exactly as the |
| 603 | shop behaved yesterday, and nothing starts selling stock it does not |
| 604 | have because a field was missing. |
| 605 | """ |
| 606 | if not product: |
| 607 | return "refuse" |
| 608 | policy = _text(product.get("backorder_policy")).lower() |
| 609 | return policy if policy in BACKORDER_POLICIES else "refuse" |
| 610 | |
| 611 | |
| 612 | def checkout_blockers(items: list[dict], products: dict[str, dict], |
| 613 | on_hand: dict[str, Any], |
| 614 | *, tracked: set[str] | None = None) -> dict: |
| 615 | """Everything standing between this basket and an order. |
| 616 | |
| 617 | Returns {"empty", "price_changes", "unavailable", "inactive", |
| 618 | "backordered", "notify", "can_checkout"}. Gathered in one pass and ALL |
| 619 | reported together: telling a shopper about one problem, letting them |
| 620 | fix it, then revealing the next is how a checkout gets abandoned. |
| 621 | |
| 622 | **Out of stock is three answers, not one.** Real shops sell the |
| 623 | incoming shipment, and a hard refusal on every empty shelf is a shop |
| 624 | turning away money it could take. The seller decides per product |
| 625 | (products.backorder_policy): |
| 626 | |
| 627 | refuse the line blocks the checkout, exactly as it always has. |
| 628 | The default, so a catalogue that has never heard of this |
| 629 | field behaves identically. |
| 630 | allow the line is ACCEPTED and lands in `backordered`. The order |
| 631 | is placed, the customer is told, and the goods ship when |
| 632 | stock exists -- never before. |
| 633 | notify the line still blocks, and lands in `notify` as well, so |
| 634 | the shop can record the interest and tell somebody when it |
| 635 | is back. Refusing while remembering beats refusing and |
| 636 | forgetting, which is the current behaviour and loses the |
| 637 | customer twice. |
| 638 | |
| 639 | `backordered` does NOT stop the checkout; `notify` and `unavailable` |
| 640 | do. A notify line appears in both lists on purpose: it is a blocker |
| 641 | that also happens to be worth writing down, and a caller that only |
| 642 | read `unavailable` still refuses correctly. |
| 643 | """ |
| 644 | inactive = [] |
| 645 | for item in items: |
| 646 | product = products.get(_text(item.get("product_id"))) |
| 647 | if product is None: |
| 648 | inactive.append({"product_id": _text(item.get("product_id")), |
| 649 | "reason": "no longer in the catalogue"}) |
| 650 | elif _text(product.get("is_active")).lower() in ("false", "0", "no", "off"): |
| 651 | inactive.append({"product_id": _text(item.get("product_id")), |
| 652 | "description": _text(product.get("name")), |
| 653 | "reason": "no longer for sale"}) |
| 654 | |
| 655 | # Sold in the shop only, or past the per-order online limit |
| 656 | # (object_reservations.online_refusal): a basket can hold a line that |
| 657 | # was fine when it went in and is not any more, so checkout asks again. |
| 658 | # The limit is per PRODUCT across the basket's lines, not per line. |
| 659 | import object_reservations |
| 660 | wanted_by_product: dict[str, Decimal] = {} |
| 661 | for item in items: |
| 662 | pid = _text(item.get("product_id")) |
| 663 | wanted_by_product[pid] = wanted_by_product.get(pid, Decimal(0)) + _num(item.get("quantity")) |
| 664 | for pid, wanted in wanted_by_product.items(): |
| 665 | product = products.get(pid) |
| 666 | refusal = object_reservations.online_refusal(product, wanted) |
| 667 | if product is not None and refusal and pid not in {row["product_id"] for row in inactive}: |
| 668 | inactive.append({"product_id": pid, |
| 669 | "description": _text(product.get("name")), |
| 670 | "reason": refusal}) |
| 671 | |
| 672 | # Extras and quantities are money too: a changed extra is a price |
| 673 | # change the shopper confirms, an unreproducible one is a line that |
| 674 | # cannot be sold (line_money_problems). |
| 675 | modifier_changed, unsellable = line_money_problems(items, products) |
| 676 | inactive.extend(unsellable) |
| 677 | changes = price_changes(items, products) + modifier_changed |
| 678 | short = availability(items, on_hand, tracked=tracked) |
| 679 | empty = not [i for i in items if _num(i.get("quantity")) > 0] |
| 680 | |
| 681 | refused, backordered, notify = [], [], [] |
| 682 | for line in short: |
| 683 | policy = backorder_policy(products.get(line["product_id"])) |
| 684 | stamped = {**line, "backorder_policy": policy} |
| 685 | if policy == "allow": |
| 686 | backordered.append(stamped) |
| 687 | continue |
| 688 | refused.append(stamped) |
| 689 | if policy == "notify": |
| 690 | notify.append(stamped) |
| 691 | |
| 692 | return { |
| 693 | "empty": empty, |
| 694 | "price_changes": changes, |
| 695 | "unavailable": refused, |
| 696 | "inactive": inactive, |
| 697 | "backordered": backordered, |
| 698 | "notify": notify, |
| 699 | "can_checkout": not (empty or changes or refused or inactive), |
| 700 | } |