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
cart.py · 14.6 KB · 358 lines
| 1 | """action_cart -- the basket verbs: get, add, set, remove, clear. |
| 2 | |
| 3 | POST {session_token, action, product_id?, quantity?, line_note?, |
| 4 | modifier_cents?, cart_item_id?} |
| 5 | |
| 6 | One object rather than five, because these are the same operation with a |
| 7 | different argument and splitting them would mean five copies of "find or |
| 8 | make this session's basket". The verb is data, which is the same reason |
| 9 | the scheduler's tasks are data. |
| 10 | |
| 11 | No stock is touched here and no price is refreshed here. Adding to a |
| 12 | basket is not a commitment: reserving stock on add is how a shop shows |
| 13 | "sold out" for goods nobody bought, and quietly repricing a basket is how |
| 14 | a shopper is charged something they never agreed to. Both are decided at |
| 15 | checkout, where a person is looking. |
| 16 | |
| 17 | One thing IS refused here, and it is a merchandising rule rather than a |
| 18 | stock one: a product that has variants and no price of its own is a |
| 19 | display heading, not a thing. "Tote bag" is what somebody is looking for; |
| 20 | "Tote bag, medium, navy" is what they can actually be sent, and it is a |
| 21 | products row of its own with its own SKU, price and stock level (see |
| 22 | products.json's own description on why a variant IS a product). Adding |
| 23 | the heading would put a line with no price on an order nobody can pick, |
| 24 | so it is refused HERE, in the object that owns the rule, and the refusal |
| 25 | names the options -- a "no" that does not say what to do instead is a |
| 26 | lost sale. site_shop mirrors the same rule when it decides whether to |
| 27 | draw an Add button, so the page never offers what this would refuse. |
| 28 | |
| 29 | **An instruction is not a product, and it makes its own line.** A large |
| 30 | latte is genuinely its own product with its own SKU, price and stock, and |
| 31 | variants-as-products above already handles that correctly. "No onions" is |
| 32 | not a product: it has no SKU, it is true of one line of one order, and a |
| 33 | catalogue row per instruction would be thousands of dead products. So a |
| 34 | line carries `line_note` and `modifier_cents` ("oat milk +60c" is the |
| 35 | same instruction with a price delta, which is why the delta lives on the |
| 36 | line rather than in the price book), and two adds of the same product |
| 37 | with DIFFERENT instructions are two lines rather than a quantity of two. |
| 38 | That is not a nicety: one burger with no onions and one with is two |
| 39 | things to make, and merging them on product_id alone would send the cook |
| 40 | a line they cannot follow. Same product, same instruction, same delta |
| 41 | still merges, so a shop that never types a note sees exactly the basket |
| 42 | it saw before. |
| 43 | |
| 44 | `set` and `remove` take an optional `cart_item_id` to say WHICH line, |
| 45 | because product_id stopped being unique the moment two lines could share |
| 46 | one. Without it they fall back to the first line for that product -- |
| 47 | today's behaviour, kept so every existing caller still works -- and |
| 48 | site_shop always sends the id, so the page is never the caller guessing. |
| 49 | |
| 50 | **A negative modifier is refused.** action_cart is a PUBLIC object (a |
| 51 | basket must not require an account), so anything the request can put into |
| 52 | money is something a stranger can put into money, and "-500" would be a |
| 53 | shopper pricing their own lunch. A genuine discount is a pricing decision |
| 54 | that belongs in the price book or in a variant with its own price, never |
| 55 | in a field the buyer fills in. When a modifier PICKER eventually exists, |
| 56 | its prices must be looked up server-side from whatever lists them -- the |
| 57 | request may say which modifier, never what it costs. |
| 58 | """ |
| 59 | |
| 60 | import json |
| 61 | import os |
| 62 | |
| 63 | import object_cart |
| 64 | import object_ids |
| 65 | import object_records |
| 66 | |
| 67 | ACTOR = "action_cart" |
| 68 | |
| 69 | ACTIONS = ("get", "add", "set", "remove", "clear") |
| 70 | |
| 71 | INACTIVE = ("false", "0", "no", "off") |
| 72 | |
| 73 | |
| 74 | def _base_dir(): |
| 75 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 76 | |
| 77 | |
| 78 | def _text(value): |
| 79 | return str(value if value is not None else "").strip() |
| 80 | |
| 81 | |
| 82 | def _shop_owner(base): |
| 83 | """Whose shop this is -- the owner stamped on anonymous baskets. |
| 84 | |
| 85 | A cart always belongs to somebody so that permissions have something |
| 86 | to filter on; before anyone signs in, that somebody is the shop. |
| 87 | """ |
| 88 | try: |
| 89 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 90 | if row.get("key") == "shop.owner_id" and _text(row.get("value")): |
| 91 | return _text(row["value"]) |
| 92 | except Exception: |
| 93 | pass |
| 94 | return "shop" |
| 95 | |
| 96 | |
| 97 | def _price_cents(product): |
| 98 | try: |
| 99 | return int(_text(product.get("price_cents")) or 0) |
| 100 | except (TypeError, ValueError): |
| 101 | return 0 |
| 102 | |
| 103 | |
| 104 | def _options(product): |
| 105 | """The option map a variant declares, or {} for anything that is not |
| 106 | one. |
| 107 | |
| 108 | Parsed here as well as in site_shop rather than shared through a |
| 109 | module: it is six lines, and a page and an action reaching for the |
| 110 | same import across an object boundary is a coupling neither of them |
| 111 | needs. Bad JSON is {} -- a mistyped brace must not decide whether a |
| 112 | product can be sold. |
| 113 | """ |
| 114 | raw = _text(product.get("options")) |
| 115 | if not raw: |
| 116 | return {} |
| 117 | try: |
| 118 | parsed = json.loads(raw) |
| 119 | except (TypeError, ValueError): |
| 120 | return {} |
| 121 | return ({str(key): str(value) for key, value in parsed.items()} |
| 122 | if isinstance(parsed, dict) else {}) |
| 123 | |
| 124 | |
| 125 | def _variants_of(base, product_id): |
| 126 | """The variants that display under this product and are still on sale. |
| 127 | |
| 128 | Read fresh every time. This is the gate that decides whether a row is |
| 129 | a thing or a heading, and a stale answer either sells a heading or |
| 130 | refuses a real product. |
| 131 | """ |
| 132 | try: |
| 133 | rows = object_records.read_collection_records("products", base_dir=base) |
| 134 | except Exception: |
| 135 | return [] |
| 136 | return [row for row in rows |
| 137 | if _text(row.get("parent_product_id")) == product_id |
| 138 | and _text(row.get("id")) != product_id |
| 139 | and _text(row.get("is_active")).lower() not in INACTIVE] |
| 140 | |
| 141 | |
| 142 | def _modifier_cents(value): |
| 143 | """The line's price delta, or None when it is not a whole number of |
| 144 | minor units. None is a REFUSAL upstream, not a zero: silently reading |
| 145 | "sixty pence" as no charge is the shop giving the oat milk away.""" |
| 146 | raw = _text(value) |
| 147 | if not raw: |
| 148 | return 0 |
| 149 | try: |
| 150 | return int(raw) |
| 151 | except (TypeError, ValueError): |
| 152 | return None |
| 153 | |
| 154 | |
| 155 | def _same_line(item, product_id, note, modifier): |
| 156 | """Is this basket line the same THING as what is being added? |
| 157 | |
| 158 | Product, instruction and delta all three. Two burgers where one has no |
| 159 | onions are two lines, because they are two things to make. |
| 160 | """ |
| 161 | return (_text(item.get("product_id")) == product_id |
| 162 | and _text(item.get("line_note")) == note |
| 163 | and _modifier_cents(item.get("modifier_cents")) == modifier) |
| 164 | |
| 165 | |
| 166 | def _find_cart(base, token): |
| 167 | try: |
| 168 | rows = object_records.read_collection_records("carts", base_dir=base) |
| 169 | except Exception: |
| 170 | return None, "shop not installed (carts absent)" |
| 171 | for row in rows: |
| 172 | if _text(row.get("session_token")) == token and _text(row.get("status")) == "open": |
| 173 | return row, "" |
| 174 | return None, "" |
| 175 | |
| 176 | |
| 177 | def _items_of(base, cart_id): |
| 178 | try: |
| 179 | rows = object_records.read_collection_records("cart_items", base_dir=base) |
| 180 | except Exception: |
| 181 | return [] |
| 182 | return [row for row in rows if _text(row.get("cart_id")) == cart_id] |
| 183 | |
| 184 | |
| 185 | def _state(base, cart, items): |
| 186 | summary = object_cart.totals(items) |
| 187 | return {"ok": True, "cart_id": cart["id"], |
| 188 | "session_token": _text(cart.get("session_token")), |
| 189 | "status": _text(cart.get("status")), **summary} |
| 190 | |
| 191 | |
| 192 | def POST(request): |
| 193 | base = _base_dir() |
| 194 | token = _text(request.get("session_token")) |
| 195 | action = _text(request.get("action")) or "get" |
| 196 | if not token: |
| 197 | return {"status": 400, "error": "session_token is required"} |
| 198 | if action not in ACTIONS: |
| 199 | return {"status": 400, |
| 200 | "error": f"action must be one of {', '.join(ACTIONS)}"} |
| 201 | |
| 202 | cart, problem = _find_cart(base, token) |
| 203 | if problem: |
| 204 | return {"ok": True, "skipped": problem} |
| 205 | |
| 206 | if cart is None: |
| 207 | if action in ("get", "remove", "clear"): |
| 208 | # Nothing to look at and nothing to remove: an empty basket is |
| 209 | # a perfectly good answer, not a 404. |
| 210 | return {"ok": True, "cart_id": "", "session_token": token, |
| 211 | "status": "open", "lines": [], "subtotal_cents": 0, "count": "0"} |
| 212 | cart = object_records.create_collection_record( |
| 213 | "carts", |
| 214 | {"id": object_ids.new_uuid4(), "session_token": token, "status": "open", |
| 215 | "currency": "USD", "owner_id": _shop_owner(base)}, |
| 216 | base_dir=base, actor=ACTOR) |
| 217 | |
| 218 | items = _items_of(base, cart["id"]) |
| 219 | |
| 220 | if action == "get": |
| 221 | return _state(base, cart, items) |
| 222 | |
| 223 | if action == "clear": |
| 224 | for item in items: |
| 225 | object_records.delete_collection_record( |
| 226 | "cart_items", item["id"], base_dir=base, actor=ACTOR) |
| 227 | return _state(base, cart, []) |
| 228 | |
| 229 | product_id = _text(request.get("product_id")) |
| 230 | cart_item_id = _text(request.get("cart_item_id")) |
| 231 | if not product_id and not cart_item_id: |
| 232 | return {"status": 400, |
| 233 | "error": "product_id (or cart_item_id) is required for this action"} |
| 234 | |
| 235 | note = _text(request.get("line_note")) |
| 236 | modifier = _modifier_cents(request.get("modifier_cents")) |
| 237 | if modifier is None: |
| 238 | return {"status": 400, |
| 239 | "error": "modifier_cents must be a whole number of minor " |
| 240 | "units -- 60 for sixty cents, not \"0.60\"."} |
| 241 | if modifier < 0: |
| 242 | # See the module docstring: this object is public, so a negative |
| 243 | # delta is a stranger pricing their own lunch. A real discount is a |
| 244 | # price-book decision, not something the buyer types. |
| 245 | return {"status": 400, |
| 246 | "error": "A modifier can add to a line's price, never take " |
| 247 | "money off it. A discount is a price the shop sets, " |
| 248 | "not one the basket asks for."} |
| 249 | |
| 250 | if action == "add": |
| 251 | # Product, instruction and delta: same three, same line. |
| 252 | existing = next((i for i in items |
| 253 | if _same_line(i, product_id, note, modifier)), None) |
| 254 | elif cart_item_id: |
| 255 | existing = next((i for i in items |
| 256 | if _text(i.get("id")) == cart_item_id), None) |
| 257 | else: |
| 258 | existing = next((i for i in items |
| 259 | if _text(i.get("product_id")) == product_id), None) |
| 260 | if not product_id and existing is not None: |
| 261 | # Addressed purely by line id: the line already knows what it is. |
| 262 | product_id = _text(existing.get("product_id")) |
| 263 | if not product_id: |
| 264 | return {"status": 400, |
| 265 | "error": "No line with that cart_item_id is in this basket."} |
| 266 | |
| 267 | if action == "remove": |
| 268 | if existing: |
| 269 | object_records.delete_collection_record( |
| 270 | "cart_items", existing["id"], base_dir=base, actor=ACTOR) |
| 271 | items = [i for i in items if i["id"] != existing["id"]] |
| 272 | return _state(base, cart, items) |
| 273 | |
| 274 | try: |
| 275 | product = object_records.get_collection_record( |
| 276 | "products", product_id, base_dir=base) |
| 277 | except Exception: |
| 278 | product = None |
| 279 | if not product: |
| 280 | return {"status": 404, "error": f"No such product: {product_id}"} |
| 281 | if _text(product.get("is_active")).lower() in INACTIVE: |
| 282 | return {"status": 409, |
| 283 | "error": f"{_text(product.get('name')) or product_id} is not for sale."} |
| 284 | |
| 285 | variants = _variants_of(base, product_id) |
| 286 | if variants and _price_cents(product) <= 0: |
| 287 | name = _text(product.get("name")) or product_id |
| 288 | # Name the options in the sentence AND hand back the ids: the |
| 289 | # sentence is for the shopper reading a page, the list is for an |
| 290 | # API client or an agent that has to pick one without scraping |
| 291 | # prose. Both, because this refusal is the whole of the guidance |
| 292 | # either of them gets. |
| 293 | choices = [{"product_id": _text(variant.get("id")), |
| 294 | "label": " / ".join( |
| 295 | value for value in _options(variant).values() if value) |
| 296 | or _text(variant.get("name")), |
| 297 | "price_cents": str(_price_cents(variant))} |
| 298 | for variant in variants] |
| 299 | # "Choose a size" beats "choose an option" when the seller has said |
| 300 | # what the axis is called -- it is their word for it, and reading |
| 301 | # it back is the difference between a form and a conversation. |
| 302 | axes = [] |
| 303 | for variant in variants: |
| 304 | for key in _options(variant): |
| 305 | if key not in axes: |
| 306 | axes.append(key) |
| 307 | what = " and ".join(axes) if axes else "option" |
| 308 | listed = ", ".join(choice["label"] for choice in choices) |
| 309 | return {"status": 409, |
| 310 | "error": f"{name} comes in more than one {what}. " |
| 311 | f"Choose one: {listed}.", |
| 312 | "product_id": product_id, |
| 313 | "options": choices} |
| 314 | |
| 315 | wanted = object_cart._num(request.get("quantity"), 1) |
| 316 | if action == "add" and existing: |
| 317 | wanted = object_cart._num(existing.get("quantity")) + wanted |
| 318 | if wanted <= 0: |
| 319 | if existing: |
| 320 | object_records.delete_collection_record( |
| 321 | "cart_items", existing["id"], base_dir=base, actor=ACTOR) |
| 322 | items = [i for i in items if i["id"] != existing["id"]] |
| 323 | return _state(base, cart, items) |
| 324 | |
| 325 | if existing: |
| 326 | changes = {"quantity": str(wanted)} |
| 327 | # On `set`, a stated instruction or delta EDITS the line -- somebody |
| 328 | # correcting "no onions" to "extra onions" is changing this line, |
| 329 | # not buying a different thing. Only what was actually stated: an |
| 330 | # ordinary quantity update must not silently wipe a note the |
| 331 | # shopper typed a minute ago. |
| 332 | if "line_note" in request: |
| 333 | changes["line_note"] = note |
| 334 | if "modifier_cents" in request: |
| 335 | changes["modifier_cents"] = str(modifier) |
| 336 | object_records.update_collection_record( |
| 337 | "cart_items", existing["id"], changes, |
| 338 | base_dir=base, actor=ACTOR) |
| 339 | for item in items: |
| 340 | if item["id"] == existing["id"]: |
| 341 | item.update(changes) |
| 342 | else: |
| 343 | item = object_records.create_collection_record( |
| 344 | "cart_items", |
| 345 | {"id": object_ids.new_uuid4(), "cart_id": cart["id"], |
| 346 | "product_id": product_id, |
| 347 | "description": _text(product.get("name")) or product_id, |
| 348 | "quantity": str(wanted), |
| 349 | # Stamped now; compared, never silently replaced, at checkout. |
| 350 | "unit_price_cents": str(product.get("price_cents") or 0), |
| 351 | # What was asked for on this line, and what asking cost. |
| 352 | "line_note": note, |
| 353 | "modifier_cents": str(modifier), |
| 354 | "owner_id": _text(cart.get("owner_id"))}, |
| 355 | base_dir=base, actor=ACTOR) |
| 356 | items.append(item) |
| 357 | |
| 358 | return _state(base, cart, items) |