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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_cart.py · 18.0 KB · 412 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. |
| 30 | |
| 31 | **Availability is decided at checkout, never at add.** Reserving stock |
| 32 | when somebody drops a thing in a basket is how a shop shows "sold out" |
| 33 | for goods nobody bought. |
| 34 | |
| 35 | **Tax and postage are computed here, once.** They are arithmetic on a |
| 36 | sale, so they belong beside the rest of the sale's arithmetic rather |
| 37 | than in the checkout action, the invoice writer and the basket page |
| 38 | separately. `checkout_totals` is the single fold every one of those |
| 39 | callers restates; nothing else is allowed to add up its own version. |
| 40 | """ |
| 41 | |
| 42 | from __future__ import annotations |
| 43 | |
| 44 | from decimal import Decimal, InvalidOperation, ROUND_HALF_UP |
| 45 | from typing import Any |
| 46 | |
| 47 | |
| 48 | def _text(value: Any) -> str: |
| 49 | return str(value if value is not None else "").strip() |
| 50 | |
| 51 | |
| 52 | def _num(value: Any, default: int = 0) -> Decimal: |
| 53 | try: |
| 54 | return Decimal(_text(value) or str(default)) |
| 55 | except (InvalidOperation, TypeError, ValueError): |
| 56 | return Decimal(default) |
| 57 | |
| 58 | |
| 59 | def _int(value: Any, default: int = 0) -> int: |
| 60 | try: |
| 61 | return int(_text(value) or default) |
| 62 | except (TypeError, ValueError): |
| 63 | return default |
| 64 | |
| 65 | |
| 66 | def line_total_cents(quantity: Any, unit_price_cents: Any, |
| 67 | modifier_cents: Any = 0) -> int: |
| 68 | """One line's money, rounded half-up once. |
| 69 | |
| 70 | Fractional quantities are real (1.5 kg, 2.5 hours of setup), so this |
| 71 | is a Decimal multiplication rather than an integer one -- and the |
| 72 | rounding happens here, per line, so the basket total always equals the |
| 73 | sum of the lines a shopper can see. |
| 74 | |
| 75 | `modifier_cents` is the per-line instruction's price delta -- "oat |
| 76 | milk +60c" -- and it is added to the UNIT price rather than to the |
| 77 | line: two oat lattes are two lots of oat milk, and a delta applied |
| 78 | once to a line of six would be a shop giving away five of them. It is |
| 79 | inside this number rather than beside it because every total |
| 80 | downstream (basket, checkout preview, order, invoice) is a sum of |
| 81 | line totals, and money that reaches one of those and not another is |
| 82 | the bug this whole codebase is organised against. |
| 83 | """ |
| 84 | total = _num(quantity) * (_num(unit_price_cents) + _num(modifier_cents)) |
| 85 | if total <= 0: |
| 86 | return 0 |
| 87 | return int(total.to_integral_value(rounding=ROUND_HALF_UP)) |
| 88 | |
| 89 | |
| 90 | def totals(items: list[dict]) -> dict: |
| 91 | """What the basket comes to: {"lines", "subtotal_cents", "count"}. |
| 92 | |
| 93 | Each line carries its instruction (`line_note`) and its delta |
| 94 | (`modifier_cents`) through to every caller, because the callers are |
| 95 | the order writer, the invoice writer and the page -- and a note that |
| 96 | stops here is a note the cook never reads. Both are read with .get: |
| 97 | a basket written before those columns existed is still a basket. |
| 98 | """ |
| 99 | lines = [] |
| 100 | subtotal = 0 |
| 101 | count = Decimal(0) |
| 102 | for item in items: |
| 103 | quantity = _num(item.get("quantity")) |
| 104 | if quantity <= 0: |
| 105 | continue |
| 106 | modifier = _int(item.get("modifier_cents")) |
| 107 | amount = line_total_cents(quantity, item.get("unit_price_cents"), |
| 108 | modifier) |
| 109 | lines.append({ |
| 110 | "cart_item_id": _text(item.get("id")), |
| 111 | "product_id": _text(item.get("product_id")), |
| 112 | "description": _text(item.get("description")), |
| 113 | "quantity": str(quantity), |
| 114 | "unit_price_cents": _int(item.get("unit_price_cents")), |
| 115 | "modifier_cents": modifier, |
| 116 | "line_note": _text(item.get("line_note")), |
| 117 | "line_total_cents": amount, |
| 118 | }) |
| 119 | subtotal += amount |
| 120 | count += quantity |
| 121 | return {"lines": lines, "subtotal_cents": subtotal, "count": str(count)} |
| 122 | |
| 123 | |
| 124 | def tax_cents(taxable_cents: Any, rate_bps: Any) -> int: |
| 125 | """Tax on a taxable base, rounded half-up ONCE. |
| 126 | |
| 127 | Basis points, matching invoice_lines' own convention: 1500 = 15%, |
| 128 | 825 = 8.25%. 0 means the shop charges no tax, which is a real answer |
| 129 | and not a missing setting -- plenty of small sellers genuinely owe |
| 130 | none, and a shop that cannot express that would have to lie. |
| 131 | |
| 132 | Rounded once, on the whole taxable amount, rather than per line. Tax |
| 133 | is owed on a sale, not on each row of it, and rounding each row first |
| 134 | accumulates a cent of error per line that nobody can reconcile: four |
| 135 | fifty-cent lines at 5% are 10c of tax, not the 12c that four |
| 136 | separately-rounded 2.5c lines come to. The single rounding is also |
| 137 | the only version a customer can check with a calculator. |
| 138 | """ |
| 139 | base = _num(taxable_cents) |
| 140 | rate = _num(rate_bps) |
| 141 | if base <= 0 or rate <= 0: |
| 142 | return 0 |
| 143 | return int((base * rate / Decimal(10000)).to_integral_value( |
| 144 | rounding=ROUND_HALF_UP)) |
| 145 | |
| 146 | |
| 147 | def shipping_cents(subtotal_cents: Any, flat_cents: Any, |
| 148 | free_over_cents: Any = 0) -> int: |
| 149 | """What the shop charges to send this basket: flat, or nothing. |
| 150 | |
| 151 | One flat rate, because a real carrier quote needs an address, a |
| 152 | weight and a connector, and a shop that cannot charge postage at all |
| 153 | until that exists is a shop losing money on every parcel today. A |
| 154 | flat rate is honest about being a flat rate; a fake calculated one |
| 155 | would not be. |
| 156 | |
| 157 | `free_over_cents` is the free-shipping threshold, and it is here in |
| 158 | v1 on purpose: it is the one discount every small shop actually |
| 159 | runs. "Free delivery over $50" is a pricing lever, a basket-size |
| 160 | nudge and a thing customers look for by name, and leaving it out |
| 161 | would push every seller into faking it with a discount code. |
| 162 | |
| 163 | flat_cents of 0 means shipping is disabled entirely -- a digital-only |
| 164 | shop charges no postage and must not be made to show a zero line. |
| 165 | """ |
| 166 | flat = _int(flat_cents) |
| 167 | if flat <= 0: |
| 168 | return 0 |
| 169 | threshold = _int(free_over_cents) |
| 170 | if threshold > 0 and _int(subtotal_cents) >= threshold: |
| 171 | return 0 |
| 172 | return flat |
| 173 | |
| 174 | |
| 175 | def checkout_totals(items: list[dict], *, tax_rate_bps: Any = 0, |
| 176 | tax_shipping: bool = False, |
| 177 | shipping_flat_cents: Any = 0, |
| 178 | free_over_cents: Any = 0, |
| 179 | discount_cents: Any = 0, |
| 180 | discount_on: str = "goods", |
| 181 | credit_cents: Any = 0) -> dict: |
| 182 | """The whole bill: {"lines", "subtotal_cents", "shipping_cents", |
| 183 | "tax_cents", "discount_cents", "total_cents", "credit_applied_cents", |
| 184 | "amount_due_cents", "shipping_free", "count"}. |
| 185 | |
| 186 | ONE function, so the arithmetic of a sale exists in exactly one |
| 187 | place. The order, the invoice, the basket page and the preview all |
| 188 | call this and then RESTATE what it said -- none of them may add up |
| 189 | their own version. Money that is computed twice is money that |
| 190 | disagrees with itself eventually, and the disagreement always |
| 191 | surfaces as a customer holding an invoice whose lines do not come to |
| 192 | its total. |
| 193 | |
| 194 | `subtotal_cents` is goods only. Shipping is a separate charge and a |
| 195 | separate invoice LINE, so the invoice total stays the sum of its own |
| 196 | lines plus tax, and a customer can see what the postage cost instead |
| 197 | of finding it baked into a total they cannot check. |
| 198 | |
| 199 | `tax_shipping` decides whether the postage is part of the taxable |
| 200 | base. Jurisdictions genuinely disagree about this -- some tax |
| 201 | delivery on a taxable order, some never do -- so it is a setting the |
| 202 | seller chooses, not a rule this file invents for them. |
| 203 | |
| 204 | `shipping_free` says the threshold was MET rather than that shipping |
| 205 | happens to be zero. The page needs to tell somebody they earned free |
| 206 | delivery, and a bare 0 cannot distinguish "you saved the postage" |
| 207 | from "this shop does not post things". |
| 208 | |
| 209 | **A DISCOUNT COMES OFF THE TAXABLE BASE BEFORE TAX IS COMPUTED.** That |
| 210 | is not a preference; it is what every jurisdiction that levies a sales |
| 211 | or value-added tax actually requires. Tax is owed on the CONSIDERATION |
| 212 | -- what the buyer actually gives up -- and a seller's own price |
| 213 | reduction reduces it. Charging tax on the pre-discount price collects |
| 214 | money from the customer that the shop then either remits on revenue it |
| 215 | never earned or keeps, and both of those are the kind of small |
| 216 | systematic error an audit finds by multiplying one rate by one column. |
| 217 | So the discount is subtracted here, before tax_cents is called, and |
| 218 | never afterwards. |
| 219 | |
| 220 | `discount_on` says which half of the bill the reduction comes off -- |
| 221 | "goods" (a percentage or a fixed amount) or "shipping" (a free-postage |
| 222 | promotion) -- because where a jurisdiction taxes delivery, free |
| 223 | postage must remove that tax too. The discount is CLAMPED to the base |
| 224 | it comes off, so no combination of arguments can produce a negative |
| 225 | total: a shop does not owe money to somebody for shopping. |
| 226 | |
| 227 | `credit_cents` is TENDER, not a price reduction -- a gift card or |
| 228 | store credit -- and it therefore lands AFTER tax and changes no |
| 229 | taxable base at all. A gift card is money the customer already gave |
| 230 | the shop; treating it as a discount would let a shop sell $100 of |
| 231 | goods and remit tax on $60, which is fraud with a rounding error's |
| 232 | face. So `total_cents` stays the value of the SALE (what the order is |
| 233 | worth, what the books see) and `amount_due_cents` is what is left to |
| 234 | pay after the credit is applied. Where no credit is used the two are |
| 235 | identical, which is every existing caller. |
| 236 | """ |
| 237 | summary = totals(items) |
| 238 | subtotal = summary["subtotal_cents"] |
| 239 | postage = shipping_cents(subtotal, shipping_flat_cents, free_over_cents) |
| 240 | |
| 241 | wanted = max(0, _int(discount_cents)) |
| 242 | on_shipping = _text(discount_on).lower() == "shipping" |
| 243 | goods_off = 0 if on_shipping else min(wanted, subtotal) |
| 244 | postage_off = min(wanted, postage) if on_shipping else 0 |
| 245 | discount = goods_off + postage_off |
| 246 | |
| 247 | taxable = (subtotal - goods_off) + ((postage - postage_off) |
| 248 | if tax_shipping else 0) |
| 249 | tax = tax_cents(taxable, tax_rate_bps) |
| 250 | total = subtotal + postage - discount + tax |
| 251 | credit = min(max(0, _int(credit_cents)), total) |
| 252 | return { |
| 253 | "lines": summary["lines"], |
| 254 | "count": summary["count"], |
| 255 | "subtotal_cents": subtotal, |
| 256 | "shipping_cents": postage, |
| 257 | "shipping_free": bool(_int(shipping_flat_cents) > 0 and postage == 0), |
| 258 | "discount_cents": discount, |
| 259 | "discount_on": "shipping" if on_shipping else "goods", |
| 260 | "taxable_cents": taxable, |
| 261 | "tax_cents": tax, |
| 262 | "total_cents": total, |
| 263 | "credit_applied_cents": credit, |
| 264 | "amount_due_cents": total - credit, |
| 265 | } |
| 266 | |
| 267 | |
| 268 | def price_changes(items: list[dict], products: dict[str, dict]) -> list[dict]: |
| 269 | """Lines whose product now costs something else than when it went in. |
| 270 | |
| 271 | Reported, never applied. Silently charging the new price is a |
| 272 | bait-and-switch and silently honouring the old one is an open-ended |
| 273 | liability on anything left in a basket; the only defensible move is to |
| 274 | show the shopper both numbers and let them agree again. |
| 275 | """ |
| 276 | changed = [] |
| 277 | for item in items: |
| 278 | product = products.get(_text(item.get("product_id"))) |
| 279 | if not product: |
| 280 | continue |
| 281 | was = _int(item.get("unit_price_cents")) |
| 282 | now = _int(product.get("price_cents")) |
| 283 | if now and now != was: |
| 284 | changed.append({ |
| 285 | "cart_item_id": _text(item.get("id")), |
| 286 | "product_id": _text(item.get("product_id")), |
| 287 | "description": _text(item.get("description")) |
| 288 | or _text(product.get("name")), |
| 289 | "was_cents": was, |
| 290 | "now_cents": now, |
| 291 | "direction": "up" if now > was else "down", |
| 292 | }) |
| 293 | return changed |
| 294 | |
| 295 | |
| 296 | def availability(items: list[dict], on_hand: dict[str, Any], |
| 297 | *, tracked: set[str] | None = None) -> list[dict]: |
| 298 | """Lines that cannot be filled from stock, with how many are short. |
| 299 | |
| 300 | Only products the shop actually TRACKS are checked. A service, a |
| 301 | digital download or a made-to-order item has no stock level, and |
| 302 | treating "no level recorded" as "none available" would refuse to sell |
| 303 | the very things that are always available. |
| 304 | """ |
| 305 | short = [] |
| 306 | for item in items: |
| 307 | product_id = _text(item.get("product_id")) |
| 308 | if tracked is not None and product_id not in tracked: |
| 309 | continue |
| 310 | if product_id not in on_hand: |
| 311 | continue |
| 312 | wanted = _num(item.get("quantity")) |
| 313 | have = _num(on_hand.get(product_id)) |
| 314 | if wanted > have: |
| 315 | short.append({ |
| 316 | "cart_item_id": _text(item.get("id")), |
| 317 | "product_id": product_id, |
| 318 | "description": _text(item.get("description")), |
| 319 | "wanted": str(wanted), |
| 320 | "available": str(have if have > 0 else 0), |
| 321 | "short_by": str(wanted - have), |
| 322 | }) |
| 323 | return short |
| 324 | |
| 325 | |
| 326 | BACKORDER_POLICIES = ("refuse", "allow", "notify") |
| 327 | |
| 328 | |
| 329 | def backorder_policy(product: dict | None) -> str: |
| 330 | """What this product's seller has said about selling it when the shelf |
| 331 | is empty: "refuse" (the default and today's behaviour), "allow" or |
| 332 | "notify". |
| 333 | |
| 334 | Absent, blank or unreadable means REFUSE. That is the whole safety of |
| 335 | this feature: a catalogue written before the column existed, a product |
| 336 | somebody imported, or a policy typed wrong all behave exactly as the |
| 337 | shop behaved yesterday, and nothing starts selling stock it does not |
| 338 | have because a field was missing. |
| 339 | """ |
| 340 | if not product: |
| 341 | return "refuse" |
| 342 | policy = _text(product.get("backorder_policy")).lower() |
| 343 | return policy if policy in BACKORDER_POLICIES else "refuse" |
| 344 | |
| 345 | |
| 346 | def checkout_blockers(items: list[dict], products: dict[str, dict], |
| 347 | on_hand: dict[str, Any], |
| 348 | *, tracked: set[str] | None = None) -> dict: |
| 349 | """Everything standing between this basket and an order. |
| 350 | |
| 351 | Returns {"empty", "price_changes", "unavailable", "inactive", |
| 352 | "backordered", "notify", "can_checkout"}. Gathered in one pass and ALL |
| 353 | reported together: telling a shopper about one problem, letting them |
| 354 | fix it, then revealing the next is how a checkout gets abandoned. |
| 355 | |
| 356 | **Out of stock is three answers, not one.** Real shops sell the |
| 357 | incoming shipment, and a hard refusal on every empty shelf is a shop |
| 358 | turning away money it could take. The seller decides per product |
| 359 | (products.backorder_policy): |
| 360 | |
| 361 | refuse the line blocks the checkout, exactly as it always has. |
| 362 | The default, so a catalogue that has never heard of this |
| 363 | field behaves identically. |
| 364 | allow the line is ACCEPTED and lands in `backordered`. The order |
| 365 | is placed, the customer is told, and the goods ship when |
| 366 | stock exists -- never before. |
| 367 | notify the line still blocks, and lands in `notify` as well, so |
| 368 | the shop can record the interest and tell somebody when it |
| 369 | is back. Refusing while remembering beats refusing and |
| 370 | forgetting, which is the current behaviour and loses the |
| 371 | customer twice. |
| 372 | |
| 373 | `backordered` does NOT stop the checkout; `notify` and `unavailable` |
| 374 | do. A notify line appears in both lists on purpose: it is a blocker |
| 375 | that also happens to be worth writing down, and a caller that only |
| 376 | read `unavailable` still refuses correctly. |
| 377 | """ |
| 378 | inactive = [] |
| 379 | for item in items: |
| 380 | product = products.get(_text(item.get("product_id"))) |
| 381 | if product is None: |
| 382 | inactive.append({"product_id": _text(item.get("product_id")), |
| 383 | "reason": "no longer in the catalogue"}) |
| 384 | elif _text(product.get("is_active")).lower() in ("false", "0", "no", "off"): |
| 385 | inactive.append({"product_id": _text(item.get("product_id")), |
| 386 | "description": _text(product.get("name")), |
| 387 | "reason": "no longer for sale"}) |
| 388 | |
| 389 | changes = price_changes(items, products) |
| 390 | short = availability(items, on_hand, tracked=tracked) |
| 391 | empty = not [i for i in items if _num(i.get("quantity")) > 0] |
| 392 | |
| 393 | refused, backordered, notify = [], [], [] |
| 394 | for line in short: |
| 395 | policy = backorder_policy(products.get(line["product_id"])) |
| 396 | stamped = {**line, "backorder_policy": policy} |
| 397 | if policy == "allow": |
| 398 | backordered.append(stamped) |
| 399 | continue |
| 400 | refused.append(stamped) |
| 401 | if policy == "notify": |
| 402 | notify.append(stamped) |
| 403 | |
| 404 | return { |
| 405 | "empty": empty, |
| 406 | "price_changes": changes, |
| 407 | "unavailable": refused, |
| 408 | "inactive": inactive, |
| 409 | "backordered": backordered, |
| 410 | "notify": notify, |
| 411 | "can_checkout": not (empty or changes or refused or inactive), |
| 412 | } |