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.
cart.py · 27.6 KB · 597 lines
| 1 | """action_cart -- the basket verbs: get, add, set, remove, clear. |
| 2 | |
| 3 | POST {session_token?, action, product_id?, quantity?, line_note?, |
| 4 | modifiers?, modifier_cents?, cart_item_id?} |
| 5 | |
| 6 | **The server mints the session token.** A basket is found by its token |
| 7 | and by nothing else, so the token is a bearer capability: whoever holds it |
| 8 | reads the basket, edits it and checks it out, and a basket that has been |
| 9 | checked out answers with its order's pay and tracking links. It used to be |
| 10 | whatever the client sent -- "a" opened a basket on "a", and a second caller |
| 11 | sending "a" read it. Now an `add` with no session_token opens a basket on |
| 12 | `secrets.token_urlsafe(24)` and the response carries it (`session_token`) |
| 13 | for the client to keep and send back. A request over HTTP (it carries |
| 14 | `_identity`, which the server sets and a client cannot remove) is refused |
| 15 | a token shorter than object_cart.MIN_SESSION_TOKEN_LENGTH or outside the |
| 16 | URL-safe alphabet, and an `add` on a token no basket has ever carried, so |
| 17 | a client cannot choose one; `get`, `remove` and `clear` on an unknown |
| 18 | token answer with an empty basket, which reveals nothing. An in-process |
| 19 | caller -- a test, another object -- is server code and may still name its |
| 20 | own token. site_shop forwards its request's `_identity`, so the public |
| 21 | page is held to the HTTP rule and takes the token this object mints. |
| 22 | |
| 23 | One object rather than five, because these are the same operation with a |
| 24 | different argument and splitting them would mean five copies of "find or |
| 25 | make this session's basket". The verb is data, which is the same reason |
| 26 | the scheduler's tasks are data. |
| 27 | |
| 28 | No stock is touched here and no price is refreshed here. Adding to a |
| 29 | basket is not a commitment: reserving stock on add is how a shop shows |
| 30 | "sold out" for goods nobody bought, and quietly repricing a basket is how |
| 31 | a shopper is charged something they never agreed to. Both are decided at |
| 32 | checkout, where a person is looking. |
| 33 | |
| 34 | One thing IS refused here, and it is a merchandising rule rather than a |
| 35 | stock one: a product that has variants and no price of its own is a |
| 36 | display heading, not a thing. "Tote bag" is what somebody is looking for; |
| 37 | "Tote bag, medium, navy" is what they can actually be sent, and it is a |
| 38 | products row of its own with its own SKU, price and stock level (see |
| 39 | products.json's own description on why a variant IS a product). Adding |
| 40 | the heading would put a line with no price on an order nobody can pick, |
| 41 | so it is refused HERE, in the object that owns the rule, and the refusal |
| 42 | names the options -- a "no" that does not say what to do instead is a |
| 43 | lost sale. site_shop mirrors the same rule when it decides whether to |
| 44 | draw an Add button, so the page never offers what this would refuse. |
| 45 | |
| 46 | **In store only is refused here too** (products.in_store_only): the owner |
| 47 | wanted a flag "to not allow pick reservations, because sometimes you'd |
| 48 | have a special only upon entry", where the people queueing in the shop -- |
| 49 | or holding a numbered ticket -- must not be overtaken by somebody's phone. |
| 50 | Such a product never enters an online basket; the counter sells it from |
| 51 | the back office, which this object never sees. So does the optional |
| 52 | products.online_max_per_order, counted across the basket's lines of that |
| 53 | product. The sentence is object_reservations.online_refusal, the same one |
| 54 | checkout and the locked check give. |
| 55 | |
| 56 | **An instruction is not a product, and it makes its own line.** A large |
| 57 | latte is genuinely its own product with its own SKU, price and stock, and |
| 58 | variants-as-products above already handles that correctly. "No onions" is |
| 59 | not a product: it has no SKU, it is true of one line of one order, and a |
| 60 | catalogue row per instruction would be thousands of dead products. So a |
| 61 | line carries `line_note` and `modifier_cents` ("oat milk +60c" is the |
| 62 | same instruction with a price delta, which is why the delta lives on the |
| 63 | line rather than in the price book), and two adds of the same product |
| 64 | with DIFFERENT instructions are two lines rather than a quantity of two. |
| 65 | That is not a nicety: one burger with no onions and one with is two |
| 66 | things to make, and merging them on product_id alone would send the cook |
| 67 | a line they cannot follow. Same product, same instruction, same delta |
| 68 | still merges, so a shop that never types a note sees exactly the basket |
| 69 | it saw before. |
| 70 | |
| 71 | `set` and `remove` take an optional `cart_item_id` to say WHICH line, |
| 72 | because product_id stopped being unique the moment two lines could share |
| 73 | one. Without it they fall back to the first line for that product -- |
| 74 | today's behaviour, kept so every existing caller still works -- and |
| 75 | site_shop always sends the id, so the page is never the caller guessing. |
| 76 | |
| 77 | **A negative modifier is refused.** action_cart is a PUBLIC object (a |
| 78 | basket must not require an account), so anything the request can put into |
| 79 | money is something a stranger can put into money, and "-500" would be a |
| 80 | shopper pricing their own lunch. A genuine discount is a pricing decision |
| 81 | that belongs in the price book or in a variant with its own price, never |
| 82 | in a field the buyer fills in. |
| 83 | |
| 84 | **The request says which extra, never what it costs.** The paragraph above |
| 85 | used to end "when a modifier picker eventually exists, its prices must be |
| 86 | looked up server-side", and until then the request's own `modifier_cents` |
| 87 | was trusted as long as it was not negative -- so a latte with |
| 88 | `line_note: "oat milk", modifier_cents: 0` went through checkout at the |
| 89 | plain price, and the cook, who reads the note, made the oat latte. A café |
| 90 | run found it. Now the product declares its extras and their prices |
| 91 | (products.modifiers, {"Oat milk": 60}), the request names them |
| 92 | (`modifiers: ["Oat milk"]`, or "Oat milk, Extra shot" from a form), and the |
| 93 | line's modifier_cents is the sum this object looks up. A request that |
| 94 | still sends modifier_cents is refused unless it is exactly that sum, so an |
| 95 | older client that sent the right number keeps working and one that sent |
| 96 | its own number is told the shop's. An unknown extra is refused with the |
| 97 | list of real ones. A note that simply IS a priced extra's label ("oat |
| 98 | milk", "+ extra shot") is refused too, because the note reaches the cook |
| 99 | and is never money; it is a guard against the obvious case, not a parser. |
| 100 | |
| 101 | **A quantity is money as well.** 0.001 of a 400c latte rounded to a 0c |
| 102 | line and checked out as a free order, with a whole latte on the ticket. |
| 103 | A quantity must be finite and above zero, whole unless the product is |
| 104 | sold by measure (a unit such as kg or hour, object_cart.sold_by_measure), |
| 105 | and never so small that a priced line rounds to nothing. |
| 106 | """ |
| 107 | |
| 108 | import json |
| 109 | import os |
| 110 | import secrets |
| 111 | |
| 112 | import object_cart |
| 113 | import object_ids |
| 114 | import object_records |
| 115 | import object_reservations |
| 116 | |
| 117 | ACTOR = "action_cart" |
| 118 | |
| 119 | ACTIONS = ("get", "add", "set", "remove", "clear") |
| 120 | |
| 121 | INACTIVE = ("false", "0", "no", "off") |
| 122 | |
| 123 | # order_lines.line_note's max_length, which the extras and the note share. |
| 124 | NOTE_LIMIT = 300 |
| 125 | |
| 126 | |
| 127 | def _base_dir(): |
| 128 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 129 | |
| 130 | |
| 131 | def _text(value): |
| 132 | return str(value if value is not None else "").strip() |
| 133 | |
| 134 | |
| 135 | def _shop_owner(base): |
| 136 | """Whose shop this is -- the owner stamped on anonymous baskets. |
| 137 | |
| 138 | A cart always belongs to somebody so that permissions have something |
| 139 | to filter on; before anyone signs in, that somebody is the shop. |
| 140 | """ |
| 141 | try: |
| 142 | # access: box configuration |
| 143 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 144 | if row.get("key") == "shop.owner_id" and _text(row.get("value")): |
| 145 | return _text(row["value"]) |
| 146 | except Exception: |
| 147 | pass |
| 148 | return "shop" |
| 149 | |
| 150 | |
| 151 | def _price_cents(product): |
| 152 | try: |
| 153 | return int(_text(product.get("price_cents")) or 0) |
| 154 | except (TypeError, ValueError): |
| 155 | return 0 |
| 156 | |
| 157 | |
| 158 | def _options(product): |
| 159 | """The option map a variant declares, or {} for anything that is not |
| 160 | one. |
| 161 | |
| 162 | Parsed here as well as in site_shop rather than shared through a |
| 163 | module: it is six lines, and a page and an action reaching for the |
| 164 | same import across an object boundary is a coupling neither of them |
| 165 | needs. Bad JSON is {} -- a mistyped brace must not decide whether a |
| 166 | product can be sold. |
| 167 | """ |
| 168 | raw = _text(product.get("options")) |
| 169 | if not raw: |
| 170 | return {} |
| 171 | try: |
| 172 | parsed = json.loads(raw) |
| 173 | except (TypeError, ValueError): |
| 174 | return {} |
| 175 | return ({str(key): str(value) for key, value in parsed.items()} |
| 176 | if isinstance(parsed, dict) else {}) |
| 177 | |
| 178 | |
| 179 | def _variants_of(base, product_id): |
| 180 | """The variants that display under this product and are still on sale. |
| 181 | |
| 182 | Read fresh every time. This is the gate that decides whether a row is |
| 183 | a thing or a heading, and a stale answer either sells a heading or |
| 184 | refuses a real product. |
| 185 | """ |
| 186 | try: |
| 187 | # access: storefront catalog: the shop page shows live products to anyone, by design |
| 188 | rows = object_records.read_collection_records("products", base_dir=base) |
| 189 | except Exception: |
| 190 | return [] |
| 191 | return [row for row in rows |
| 192 | if _text(row.get("parent_product_id")) == product_id |
| 193 | and _text(row.get("id")) != product_id |
| 194 | and _text(row.get("is_active")).lower() not in INACTIVE] |
| 195 | |
| 196 | |
| 197 | def _modifier_cents(value): |
| 198 | """The line's price delta, or None when it is not a whole number of |
| 199 | minor units. None is a REFUSAL upstream, not a zero: silently reading |
| 200 | "sixty pence" as no charge is the shop giving the oat milk away.""" |
| 201 | raw = _text(value) |
| 202 | if not raw: |
| 203 | return 0 |
| 204 | try: |
| 205 | return int(raw) |
| 206 | except (TypeError, ValueError): |
| 207 | return None |
| 208 | |
| 209 | |
| 210 | def _extras_key(labels): |
| 211 | return sorted(label.casefold() for label in labels) |
| 212 | |
| 213 | |
| 214 | def _same_line(item, product_id, note, labels): |
| 215 | """Is this basket line the same THING as what is being added? |
| 216 | |
| 217 | Product, instruction and extras all three. Two burgers where one has no |
| 218 | onions are two lines, because they are two things to make. |
| 219 | """ |
| 220 | return (_text(item.get("product_id")) == product_id |
| 221 | and _text(item.get("line_note")) == note |
| 222 | and _extras_key(object_cart.chosen_modifiers(item.get("modifiers"))) |
| 223 | == _extras_key(labels)) |
| 224 | |
| 225 | |
| 226 | def _offered(product): |
| 227 | """The extras a refusal names, so a "no" says what to send instead.""" |
| 228 | declared = object_cart.declared_modifiers(product) |
| 229 | if not declared: |
| 230 | return "this product takes no priced extras" |
| 231 | return "this product offers " + ", ".join( |
| 232 | f"{label} ({cents / 100:.2f})" for label, cents in declared.items()) |
| 233 | |
| 234 | |
| 235 | def _find_cart(base, token): |
| 236 | try: |
| 237 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 238 | rows = object_records.read_collection_records("carts", base_dir=base) |
| 239 | except Exception: |
| 240 | return None, "shop not installed (carts absent)" |
| 241 | for row in rows: |
| 242 | if _text(row.get("session_token")) == token and _text(row.get("status")) == "open": |
| 243 | return row, "" |
| 244 | return None, "" |
| 245 | |
| 246 | |
| 247 | def _token_known(base, token): |
| 248 | """Has any basket, open or long since checked out, carried this token? |
| 249 | |
| 250 | The proof a token was minted here: this object is the only thing that |
| 251 | writes carts, and it opens one only on a token it minted (or that an |
| 252 | in-process caller named).""" |
| 253 | try: |
| 254 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 255 | rows = object_records.read_collection_records("carts", base_dir=base) |
| 256 | except Exception: |
| 257 | return False |
| 258 | return any(_text(row.get("session_token")) == token for row in rows) |
| 259 | |
| 260 | |
| 261 | def _items_of(base, cart_id): |
| 262 | try: |
| 263 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 264 | rows = object_records.read_collection_records("cart_items", base_dir=base) |
| 265 | except Exception: |
| 266 | return [] |
| 267 | return [row for row in rows if _text(row.get("cart_id")) == cart_id] |
| 268 | |
| 269 | |
| 270 | def _promised(base, product_ids): |
| 271 | """{product_id: object_reservations.promise(...)} for the tracked |
| 272 | products among these -- AVAILABLE (on hand less what live online orders |
| 273 | hold), never on hand, and never anything about whose orders those are. |
| 274 | A product or a shelf that cannot be read is simply left out: the basket |
| 275 | is a view, and checkout is where the answer is enforced.""" |
| 276 | import object_stock |
| 277 | out = {} |
| 278 | if not product_ids: |
| 279 | return out |
| 280 | try: |
| 281 | held = object_reservations.read_holds(base) |
| 282 | low = object_reservations.low_stock_threshold(base) |
| 283 | except Exception: |
| 284 | return out |
| 285 | for product_id in product_ids: |
| 286 | try: |
| 287 | # access: storefront catalog: the shop page shows live products to anyone, by design |
| 288 | product = object_records.get_collection_record("products", product_id, |
| 289 | base_dir=base) |
| 290 | if not object_reservations.tracked(product): |
| 291 | continue |
| 292 | on_hand = object_stock.total_quantity(product_id, base_dir=base) |
| 293 | except Exception: |
| 294 | continue |
| 295 | out[product_id] = object_reservations.promise( |
| 296 | on_hand - held.get(product_id, 0), low=low) |
| 297 | return out |
| 298 | |
| 299 | |
| 300 | def _state(base, cart, items): |
| 301 | summary = object_cart.totals(items) |
| 302 | # The extras each line carries, by name, beside the money they cost -- |
| 303 | # only on lines that have any, so a basket without extras reads exactly |
| 304 | # as it always has. |
| 305 | extras = {_text(item.get("id")): object_cart.chosen_modifiers(item.get("modifiers")) |
| 306 | for item in items} |
| 307 | for line in summary["lines"]: |
| 308 | if extras.get(line["cart_item_id"]): |
| 309 | line["modifiers"] = extras[line["cart_item_id"]] |
| 310 | # What the shelf can still promise for each line's product, so a basket |
| 311 | # says "only 2 left" or "sold out" before checkout has to refuse it. |
| 312 | promised = _promised(base, {_text(item.get("product_id")) for item in items}) |
| 313 | for line in summary["lines"]: |
| 314 | if line.get("product_id") in promised: |
| 315 | line["stock"] = promised[line["product_id"]] |
| 316 | return {"ok": True, "cart_id": cart["id"], |
| 317 | "session_token": _text(cart.get("session_token")), |
| 318 | "status": _text(cart.get("status")), **summary} |
| 319 | |
| 320 | |
| 321 | def POST(request): |
| 322 | base = _base_dir() |
| 323 | token = _text(request.get("session_token")) |
| 324 | action = _text(request.get("action")) or "get" |
| 325 | if action not in ACTIONS: |
| 326 | return {"status": 400, |
| 327 | "error": f"action must be one of {', '.join(ACTIONS)}"} |
| 328 | over_http = "_identity" in request |
| 329 | minted = False |
| 330 | if not token: |
| 331 | if action != "add": |
| 332 | # No basket yet, and nothing to look at: an empty basket, with |
| 333 | # no token, because none is minted until something goes in. |
| 334 | return {"ok": True, "cart_id": "", "session_token": "", |
| 335 | "status": "open", "lines": [], "subtotal_cents": 0, |
| 336 | "count": "0"} |
| 337 | token, minted = secrets.token_urlsafe(object_cart.SESSION_TOKEN_BYTES), True |
| 338 | elif over_http: |
| 339 | refused = object_cart.session_token_problem(token) |
| 340 | if refused: |
| 341 | return {"status": 400, "error": refused, |
| 342 | "code": "unknown_session_token"} |
| 343 | |
| 344 | cart, problem = _find_cart(base, token) |
| 345 | if problem: |
| 346 | return {"ok": True, "skipped": problem} |
| 347 | |
| 348 | if cart is None: |
| 349 | if action in ("get", "remove", "clear"): |
| 350 | # Nothing to look at and nothing to remove: an empty basket is |
| 351 | # a perfectly good answer, not a 404. |
| 352 | return {"ok": True, "cart_id": "", "session_token": token, |
| 353 | "status": "open", "lines": [], "subtotal_cents": 0, "count": "0"} |
| 354 | if over_http and not minted and not _token_known(base, token): |
| 355 | # A token no basket has carried was chosen by the client, not |
| 356 | # minted here -- see the module docstring. |
| 357 | return {"status": 404, |
| 358 | "error": object_cart.session_token_problem(""), |
| 359 | "code": "unknown_session_token"} |
| 360 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 361 | cart = object_records.create_collection_record( |
| 362 | "carts", |
| 363 | {"id": object_ids.new_uuid4(), "session_token": token, "status": "open", |
| 364 | "currency": "USD", "owner_id": _shop_owner(base)}, |
| 365 | base_dir=base, actor=ACTOR) |
| 366 | |
| 367 | items = _items_of(base, cart["id"]) |
| 368 | |
| 369 | if action == "get": |
| 370 | return _state(base, cart, items) |
| 371 | |
| 372 | if action == "clear": |
| 373 | for item in items: |
| 374 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 375 | object_records.delete_collection_record( |
| 376 | "cart_items", item["id"], base_dir=base, actor=ACTOR) |
| 377 | return _state(base, cart, []) |
| 378 | |
| 379 | product_id = _text(request.get("product_id")) |
| 380 | cart_item_id = _text(request.get("cart_item_id")) |
| 381 | if not product_id and not cart_item_id: |
| 382 | return {"status": 400, |
| 383 | "error": "product_id (or cart_item_id) is required for this action"} |
| 384 | |
| 385 | note = _text(request.get("line_note")) |
| 386 | modifier = _modifier_cents(request.get("modifier_cents")) |
| 387 | if modifier is None: |
| 388 | return {"status": 400, |
| 389 | "error": "modifier_cents must be a whole number of minor " |
| 390 | "units -- 60 for sixty cents, not \"0.60\"."} |
| 391 | if modifier < 0: |
| 392 | # See the module docstring: this object is public, so a negative |
| 393 | # delta is a stranger pricing their own lunch. A real discount is a |
| 394 | # price-book decision, not something the buyer types. |
| 395 | return {"status": 400, |
| 396 | "error": "A modifier can add to a line's price, never take " |
| 397 | "money off it. A discount is a price the shop sets, " |
| 398 | "not one the basket asks for."} |
| 399 | |
| 400 | if action == "add": |
| 401 | existing = None # found below, once the extras are priced |
| 402 | elif cart_item_id: |
| 403 | existing = next((i for i in items |
| 404 | if _text(i.get("id")) == cart_item_id), None) |
| 405 | else: |
| 406 | existing = next((i for i in items |
| 407 | if _text(i.get("product_id")) == product_id), None) |
| 408 | if not product_id and existing is not None: |
| 409 | # Addressed purely by line id: the line already knows what it is. |
| 410 | product_id = _text(existing.get("product_id")) |
| 411 | if not product_id: |
| 412 | return {"status": 400, |
| 413 | "error": "No line with that cart_item_id is in this basket."} |
| 414 | |
| 415 | if action == "remove": |
| 416 | if existing: |
| 417 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 418 | object_records.delete_collection_record( |
| 419 | "cart_items", existing["id"], base_dir=base, actor=ACTOR) |
| 420 | items = [i for i in items if i["id"] != existing["id"]] |
| 421 | return _state(base, cart, items) |
| 422 | |
| 423 | try: |
| 424 | # access: storefront catalog: the shop page shows live products to anyone, by design |
| 425 | product = object_records.get_collection_record( |
| 426 | "products", product_id, base_dir=base) |
| 427 | except Exception: |
| 428 | product = None |
| 429 | if not product: |
| 430 | return {"status": 404, "error": f"No such product: {product_id}"} |
| 431 | if _text(product.get("is_active")).lower() in INACTIVE: |
| 432 | return {"status": 409, |
| 433 | "error": f"{_text(product.get('name')) or product_id} is not for sale."} |
| 434 | if object_reservations.in_store_only(product): |
| 435 | # Sold to the people in the shop, never put in an online basket -- |
| 436 | # the special that exists only upon entry (products.in_store_only). |
| 437 | # Refused HERE, where the shopper is looking, and again at checkout |
| 438 | # and by the locked check, for a basket filled before the flag was |
| 439 | # set and for any other writer. |
| 440 | return {"status": 409, "code": "in_store_only", |
| 441 | "error": object_reservations.online_refusal(product, 1)} |
| 442 | |
| 443 | variants = _variants_of(base, product_id) |
| 444 | if variants and _price_cents(product) <= 0: |
| 445 | name = _text(product.get("name")) or product_id |
| 446 | # Name the options in the sentence AND hand back the ids: the |
| 447 | # sentence is for the shopper reading a page, the list is for an |
| 448 | # API client or an agent that has to pick one without scraping |
| 449 | # prose. Both, because this refusal is the whole of the guidance |
| 450 | # either of them gets. |
| 451 | choices = [{"product_id": _text(variant.get("id")), |
| 452 | "label": " / ".join( |
| 453 | value for value in _options(variant).values() if value) |
| 454 | or _text(variant.get("name")), |
| 455 | "price_cents": str(_price_cents(variant))} |
| 456 | for variant in variants] |
| 457 | # "Choose a size" beats "choose an option" when the seller has said |
| 458 | # what the axis is called -- it is their word for it, and reading |
| 459 | # it back is the difference between a form and a conversation. |
| 460 | axes = [] |
| 461 | for variant in variants: |
| 462 | for key in _options(variant): |
| 463 | if key not in axes: |
| 464 | axes.append(key) |
| 465 | what = " and ".join(axes) if axes else "option" |
| 466 | listed = ", ".join(choice["label"] for choice in choices) |
| 467 | return {"status": 409, |
| 468 | "error": f"{name} comes in more than one {what}. " |
| 469 | f"Choose one: {listed}.", |
| 470 | "product_id": product_id, |
| 471 | "options": choices} |
| 472 | |
| 473 | asked_quantity = object_cart._num(request.get("quantity"), 1) |
| 474 | if not asked_quantity.is_finite(): |
| 475 | return {"status": 400, "error": "The quantity must be a number."} |
| 476 | if action == "set" and asked_quantity <= 0: |
| 477 | # Setting a line to nothing removes it: nothing about its extras or |
| 478 | # its note can stop a shopper taking a thing OUT of a basket. |
| 479 | if existing: |
| 480 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 481 | object_records.delete_collection_record( |
| 482 | "cart_items", existing["id"], base_dir=base, actor=ACTOR) |
| 483 | items = [i for i in items if i["id"] != existing["id"]] |
| 484 | return _state(base, cart, items) |
| 485 | |
| 486 | # THE EXTRAS, PRICED HERE. The request names them; what they cost is |
| 487 | # what the product declares (see the module docstring). On `set` an |
| 488 | # unstated list keeps the line's own. |
| 489 | if action == "add" or "modifiers" in request or existing is None: |
| 490 | names = object_cart.chosen_modifiers(request.get("modifiers")) |
| 491 | else: |
| 492 | names = object_cart.chosen_modifiers(existing.get("modifiers")) |
| 493 | labels, modifier_price, unknown = object_cart.price_modifiers(product, names) |
| 494 | if unknown: |
| 495 | return {"status": 400, |
| 496 | "error": f"{_text(product.get('name')) or product_id} has no extra " |
| 497 | f"called {', '.join(unknown)}; {_offered(product)}.", |
| 498 | "modifiers": object_cart.declared_modifiers(product)} |
| 499 | if (_text(request.get("modifier_cents")) |
| 500 | and modifier != modifier_price): |
| 501 | return {"status": 400, |
| 502 | "error": f"An extra's price is the shop's, not the basket's: " |
| 503 | f"name the extra in `modifiers` and it is priced for " |
| 504 | f"you ({modifier_price} for what this line names; " |
| 505 | f"{_offered(product)}).", |
| 506 | "modifier_cents": modifier_price, |
| 507 | "modifiers": object_cart.declared_modifiers(product)} |
| 508 | modifier = modifier_price |
| 509 | stated_note = (note if (action == "add" or "line_note" in request) |
| 510 | else _text((existing or {}).get("line_note"))) |
| 511 | asked = object_cart.note_names_a_priced_extra(stated_note, product, labels) |
| 512 | if asked: |
| 513 | cents = object_cart.declared_modifiers(product)[asked] |
| 514 | return {"status": 400, |
| 515 | "error": f"{asked} is an extra this shop charges " |
| 516 | f"{cents / 100:.2f} for: choose it in `modifiers` " |
| 517 | f"rather than writing it in the note.", |
| 518 | "modifiers": object_cart.declared_modifiers(product)} |
| 519 | |
| 520 | if len("; ".join([*labels, stated_note] if stated_note else labels)) > NOTE_LIMIT: |
| 521 | # The extras and the note travel to the order line together |
| 522 | # (action_checkout's _kitchen_note), and order_lines.line_note holds |
| 523 | # 300 characters: refused here, where the shopper can shorten it, |
| 524 | # rather than at checkout with the order half written. |
| 525 | return {"status": 400, |
| 526 | "error": f"The extras and the note on this line come to more " |
| 527 | f"than {NOTE_LIMIT} characters; shorten the note."} |
| 528 | |
| 529 | if action == "add": |
| 530 | # Product, instruction and extras: same three, same line. |
| 531 | existing = next((i for i in items |
| 532 | if _same_line(i, product_id, note, labels)), None) |
| 533 | |
| 534 | wanted = asked_quantity |
| 535 | if action == "add" and existing: |
| 536 | wanted = object_cart._num(existing.get("quantity")) + wanted |
| 537 | if wanted > 0: |
| 538 | problem = object_cart.quantity_problem(wanted, product) |
| 539 | if problem: |
| 540 | return {"status": 400, "error": problem} |
| 541 | # The per-order online limit counts every line of this product in |
| 542 | # the basket, not just this one (products.online_max_per_order). |
| 543 | others = sum((object_cart._num(i.get("quantity")) for i in items |
| 544 | if _text(i.get("product_id")) == product_id |
| 545 | and (existing is None or i.get("id") != existing.get("id"))), |
| 546 | object_cart._num(0)) |
| 547 | limit = object_reservations.online_refusal(product, wanted + others) |
| 548 | if limit: |
| 549 | return {"status": 409, "code": "online_limit", "error": limit} |
| 550 | if wanted <= 0: |
| 551 | if existing: |
| 552 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 553 | object_records.delete_collection_record( |
| 554 | "cart_items", existing["id"], base_dir=base, actor=ACTOR) |
| 555 | items = [i for i in items if i["id"] != existing["id"]] |
| 556 | return _state(base, cart, items) |
| 557 | |
| 558 | if existing: |
| 559 | changes = {"quantity": str(wanted)} |
| 560 | # On `set`, a stated instruction or delta EDITS the line -- somebody |
| 561 | # correcting "no onions" to "extra onions" is changing this line, |
| 562 | # not buying a different thing. Only what was actually stated: an |
| 563 | # ordinary quantity update must not silently wipe a note the |
| 564 | # shopper typed a minute ago. |
| 565 | if "line_note" in request: |
| 566 | changes["line_note"] = note |
| 567 | if "modifier_cents" in request or "modifiers" in request: |
| 568 | changes["modifier_cents"] = str(modifier) |
| 569 | changes["modifiers"] = json.dumps(labels) if labels else "" |
| 570 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 571 | object_records.update_collection_record( |
| 572 | "cart_items", existing["id"], changes, |
| 573 | base_dir=base, actor=ACTOR) |
| 574 | for item in items: |
| 575 | if item["id"] == existing["id"]: |
| 576 | item.update(changes) |
| 577 | else: |
| 578 | # access: guest basket: found by its unguessable session_token; its items are the basket's own |
| 579 | item = object_records.create_collection_record( |
| 580 | "cart_items", |
| 581 | {"id": object_ids.new_uuid4(), "cart_id": cart["id"], |
| 582 | "product_id": product_id, |
| 583 | "description": _text(product.get("name")) or product_id, |
| 584 | "quantity": str(wanted), |
| 585 | # Stamped now; compared, never silently replaced, at checkout. |
| 586 | "unit_price_cents": str(product.get("price_cents") or 0), |
| 587 | # What was asked for on this line, and what asking cost. |
| 588 | "line_note": note, |
| 589 | "modifier_cents": str(modifier), |
| 590 | # Which extras, so checkout can re-price them and the cook is |
| 591 | # told what was paid for. |
| 592 | "modifiers": json.dumps(labels) if labels else "", |
| 593 | "owner_id": _text(cart.get("owner_id"))}, |
| 594 | base_dir=base, actor=ACTOR) |
| 595 | items.append(item) |
| 596 | |
| 597 | return _state(base, cart, items) |