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
test_shop_cart.py · 54.8 KB · 1240 lines
| 1 | """The shop: basket, checkout, and a sale that posts itself. |
| 2 | |
| 3 | The cart is the easy part and everybody has one. What is worth testing is |
| 4 | the seam: that a basket is not an order, that a price which moved is |
| 5 | surfaced rather than silently resolved either way, and that stock leaves |
| 6 | the shelf when money arrives and not one moment sooner. |
| 7 | """ |
| 8 | |
| 9 | import pathlib |
| 10 | |
| 11 | from conftest import stage_collection |
| 12 | |
| 13 | import object_cart |
| 14 | import object_execution |
| 15 | import object_ids |
| 16 | import object_records |
| 17 | import python_object_runtime |
| 18 | |
| 19 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 20 | PACKAGES = REPO_ROOT / "packages" |
| 21 | SHOP_OBJECTS = PACKAGES / "app-shop" / "objects" |
| 22 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 23 | |
| 24 | TOKEN = "sess-abc123" |
| 25 | COOKIE = "cart" |
| 26 | |
| 27 | |
| 28 | def setup_env(tmp_path, monkeypatch, *, settings=(), page=False): |
| 29 | data_dir = tmp_path / "data" |
| 30 | for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"), |
| 31 | ("app-catalog", "products"), ("app-catalog", "locations"), |
| 32 | ("app-catalog", "stock_moves"), |
| 33 | ("app-orders", "orders"), ("app-orders", "order_lines"), |
| 34 | ("app-invoices", "invoices"), ("app-invoices", "invoice_lines"), |
| 35 | ("app-payments", "payments")): |
| 36 | stage_collection(data_dir, pkg, name) |
| 37 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 38 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 39 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 40 | if page: |
| 41 | # site_shop calls its siblings by object id with no roots of its |
| 42 | # own, so the page tests need the shop's objects on the search path. |
| 43 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(SHOP_OBJECTS)) |
| 44 | return data_dir |
| 45 | |
| 46 | |
| 47 | def product(data_dir, product_id, name, cents, **fields): |
| 48 | record = {"id": product_id, "name": name, "sku": product_id.upper(), |
| 49 | "product_type": "physical", "price_cents": str(cents), |
| 50 | "currency": "USD", "is_active": "true", "owner_id": "shop"} |
| 51 | record.update({k: str(v) for k, v in fields.items()}) |
| 52 | return object_records.create_collection_record("products", record, |
| 53 | base_dir=data_dir) |
| 54 | |
| 55 | |
| 56 | def location(data_dir, location_id, name, kind="warehouse"): |
| 57 | return object_records.create_collection_record( |
| 58 | "locations", |
| 59 | {"id": location_id, "name": name, "location_type": kind, "owner_id": "shop"}, |
| 60 | base_dir=data_dir) |
| 61 | |
| 62 | |
| 63 | def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"): |
| 64 | return object_records.create_collection_record( |
| 65 | "stock_moves", |
| 66 | {"id": object_ids.new_uuid4(), "product_id": product_id, |
| 67 | "to_location_id": to, "quantity": str(quantity), "reason": "purchase", |
| 68 | "occurred_at": "2026-06-01", "owner_id": "shop"}, |
| 69 | base_dir=data_dir) |
| 70 | |
| 71 | |
| 72 | def cart(action="get", **payload): |
| 73 | return object_execution.execute_object( |
| 74 | RUNTIME, |
| 75 | object_execution.ObjectExecutionRequest( |
| 76 | "action_cart", method="POST", |
| 77 | payload={"session_token": TOKEN, "action": action, **payload}), |
| 78 | roots=[SHOP_OBJECTS]).result |
| 79 | |
| 80 | |
| 81 | def checkout(**payload): |
| 82 | return object_execution.execute_object( |
| 83 | RUNTIME, |
| 84 | object_execution.ObjectExecutionRequest( |
| 85 | "action_checkout", method="POST", |
| 86 | payload={"session_token": TOKEN, **payload}), |
| 87 | roots=[SHOP_OBJECTS]).result |
| 88 | |
| 89 | |
| 90 | def fulfil(payment): |
| 91 | return object_execution.execute_object( |
| 92 | RUNTIME, |
| 93 | object_execution.ObjectExecutionRequest( |
| 94 | "system_shop_fulfillment", method="POST", |
| 95 | payload={"collection": "payments", "record": payment}), |
| 96 | roots=[SHOP_OBJECTS]).result |
| 97 | |
| 98 | |
| 99 | def page(**payload): |
| 100 | """GET the public shop page, the way the site router would call it.""" |
| 101 | payload.setdefault("_cookies", {COOKIE: TOKEN}) |
| 102 | return object_execution.execute_object( |
| 103 | RUNTIME, |
| 104 | object_execution.ObjectExecutionRequest( |
| 105 | "site_shop", method="GET", payload=payload), |
| 106 | roots=[SHOP_OBJECTS]).result |
| 107 | |
| 108 | |
| 109 | def orders(data_dir): |
| 110 | return object_records.read_collection_records("orders", base_dir=data_dir) |
| 111 | |
| 112 | |
| 113 | def moves(data_dir): |
| 114 | return object_records.read_collection_records("stock_moves", base_dir=data_dir) |
| 115 | |
| 116 | |
| 117 | def invoices(data_dir): |
| 118 | return object_records.read_collection_records("invoices", base_dir=data_dir) |
| 119 | |
| 120 | |
| 121 | def invoice_lines(data_dir): |
| 122 | return object_records.read_collection_records("invoice_lines", base_dir=data_dir) |
| 123 | |
| 124 | |
| 125 | # --- the arithmetic ---------------------------------------------------------- |
| 126 | |
| 127 | def test_a_line_rounds_once_and_the_total_is_the_sum_of_the_lines(): |
| 128 | """Fractional quantities are real -- 1.5 kg, 2.5 hours of setup.""" |
| 129 | assert object_cart.line_total_cents("1.5", 333) == 500 # 499.5 -> 500 |
| 130 | summary = object_cart.totals([ |
| 131 | {"id": "a", "quantity": "1.5", "unit_price_cents": "333"}, |
| 132 | {"id": "b", "quantity": "2", "unit_price_cents": "1000"}, |
| 133 | ]) |
| 134 | assert summary["subtotal_cents"] == 2500 |
| 135 | assert sum(line["line_total_cents"] for line in summary["lines"]) == 2500 |
| 136 | |
| 137 | |
| 138 | def test_a_price_that_moved_is_reported_not_applied(): |
| 139 | changes = object_cart.price_changes( |
| 140 | [{"id": "a", "product_id": "p1", "unit_price_cents": "1000"}], |
| 141 | {"p1": {"price_cents": "1200", "name": "Mug"}}) |
| 142 | assert changes[0]["was_cents"] == 1000 and changes[0]["now_cents"] == 1200 |
| 143 | assert changes[0]["direction"] == "up" |
| 144 | |
| 145 | |
| 146 | def test_an_untracked_product_is_always_available(): |
| 147 | """A service or a download has no stock level, and 'no level' must not |
| 148 | read as 'none left' -- that would refuse to sell what never runs out.""" |
| 149 | items = [{"id": "a", "product_id": "svc", "quantity": "3"}] |
| 150 | assert object_cart.availability(items, {}, tracked=set()) == [] |
| 151 | |
| 152 | |
| 153 | def test_every_blocker_is_reported_at_once(): |
| 154 | """Revealing problems one at a time is how a checkout gets abandoned.""" |
| 155 | items = [{"id": "a", "product_id": "p1", "quantity": "5", |
| 156 | "unit_price_cents": "1000", "description": "Mug"}, |
| 157 | {"id": "b", "product_id": "gone", "quantity": "1"}] |
| 158 | blockers = object_cart.checkout_blockers( |
| 159 | items, {"p1": {"price_cents": "1200", "is_active": "true"}}, |
| 160 | {"p1": 2}, tracked={"p1"}) |
| 161 | assert blockers["price_changes"] and blockers["unavailable"] and blockers["inactive"] |
| 162 | assert blockers["can_checkout"] is False |
| 163 | |
| 164 | |
| 165 | # --- the basket --------------------------------------------------------------- |
| 166 | |
| 167 | def test_adding_stamps_the_price_it_had_at_the_time(tmp_path, monkeypatch): |
| 168 | data_dir = setup_env(tmp_path, monkeypatch) |
| 169 | product(data_dir, "p1", "Enamel Mug", 1200) |
| 170 | result = cart("add", product_id="p1", quantity="2") |
| 171 | assert result["subtotal_cents"] == 2400 |
| 172 | |
| 173 | item = object_records.read_collection_records("cart_items", base_dir=data_dir)[0] |
| 174 | assert item["unit_price_cents"] == "1200" |
| 175 | assert item["description"] == "Enamel Mug" |
| 176 | |
| 177 | |
| 178 | def test_adding_the_same_thing_twice_increases_the_quantity(tmp_path, monkeypatch): |
| 179 | data_dir = setup_env(tmp_path, monkeypatch) |
| 180 | product(data_dir, "p1", "Mug", 1000) |
| 181 | cart("add", product_id="p1", quantity="1") |
| 182 | result = cart("add", product_id="p1", quantity="2") |
| 183 | assert result["count"] == "3" |
| 184 | assert len(object_records.read_collection_records("cart_items", base_dir=data_dir)) == 1 |
| 185 | |
| 186 | |
| 187 | def test_setting_a_quantity_to_zero_removes_the_line(tmp_path, monkeypatch): |
| 188 | data_dir = setup_env(tmp_path, monkeypatch) |
| 189 | product(data_dir, "p1", "Mug", 1000) |
| 190 | cart("add", product_id="p1") |
| 191 | result = cart("set", product_id="p1", quantity="0") |
| 192 | assert result["lines"] == [] |
| 193 | |
| 194 | |
| 195 | def test_an_empty_basket_is_an_answer_not_a_404(tmp_path, monkeypatch): |
| 196 | setup_env(tmp_path, monkeypatch) |
| 197 | result = cart("get") |
| 198 | assert result["ok"] and result["lines"] == [] and result["subtotal_cents"] == 0 |
| 199 | |
| 200 | |
| 201 | def test_something_not_for_sale_cannot_go_in_the_basket(tmp_path, monkeypatch): |
| 202 | data_dir = setup_env(tmp_path, monkeypatch) |
| 203 | product(data_dir, "p1", "Retired Mug", 1000, is_active="false") |
| 204 | assert cart("add", product_id="p1")["status"] == 409 |
| 205 | assert cart("add", product_id="nope")["status"] == 404 |
| 206 | |
| 207 | |
| 208 | def test_no_stock_is_touched_by_putting_something_in_a_basket( |
| 209 | tmp_path, monkeypatch): |
| 210 | """Reserving on add is how a shop shows 'sold out' for goods nobody |
| 211 | bought.""" |
| 212 | data_dir = setup_env(tmp_path, monkeypatch) |
| 213 | location(data_dir, "loc-shelf", "Shelf") |
| 214 | product(data_dir, "p1", "Mug", 1000) |
| 215 | stock_in(data_dir, "p1", 5) |
| 216 | cart("add", product_id="p1", quantity="3") |
| 217 | assert len(moves(data_dir)) == 1 # only the purchase |
| 218 | |
| 219 | |
| 220 | # --- checkout ------------------------------------------------------------------- |
| 221 | |
| 222 | def test_checkout_raises_a_draft_order_and_closes_the_basket( |
| 223 | tmp_path, monkeypatch): |
| 224 | data_dir = setup_env(tmp_path, monkeypatch) |
| 225 | location(data_dir, "loc-shelf", "Shelf") |
| 226 | product(data_dir, "p1", "Mug", 1200) |
| 227 | stock_in(data_dir, "p1", 10) |
| 228 | cart("add", product_id="p1", quantity="2") |
| 229 | |
| 230 | result = checkout(customer_email="buyer@example.test", customer_name="Ada") |
| 231 | assert result["ok"] and result["status_of_order"] == "draft" |
| 232 | |
| 233 | order = orders(data_dir)[0] |
| 234 | assert order["total_cents"] == "2400" |
| 235 | assert order["customer_email"] == "buyer@example.test" |
| 236 | assert order["doc_type"] == "sale" |
| 237 | |
| 238 | lines = object_records.read_collection_records("order_lines", base_dir=data_dir) |
| 239 | assert len(lines) == 1 and lines[0]["line_total_cents"] == "2400" |
| 240 | assert len(moves(data_dir)) == 1 # still nothing moved |
| 241 | |
| 242 | |
| 243 | def test_checkout_raises_the_invoice_that_the_buyer_pays(tmp_path, monkeypatch): |
| 244 | """An order with no invoice gives the buyer nothing to pay: the money is |
| 245 | owed and there is no document saying so and no door to walk through. |
| 246 | |
| 247 | It is issued ("sent"), not a draft -- a draft would mean somebody in the |
| 248 | back office has to press a button before the shopper standing at the |
| 249 | counter can hand over money. |
| 250 | """ |
| 251 | data_dir = setup_env(tmp_path, monkeypatch) |
| 252 | product(data_dir, "p1", "Mug", 1200, product_type="service") |
| 253 | cart("add", product_id="p1", quantity="2") |
| 254 | |
| 255 | result = checkout(customer_email="buyer@example.test", customer_name="Ada") |
| 256 | invoice = invoices(data_dir)[0] |
| 257 | assert invoice["status"] == "sent" |
| 258 | assert invoice["total_cents"] == "2400" == orders(data_dir)[0]["total_cents"] |
| 259 | assert invoice["customer_email"] == "buyer@example.test" |
| 260 | assert invoice["number"] == orders(data_dir)[0]["number"] |
| 261 | |
| 262 | # The join system_shop_fulfillment walks backwards from a payment. |
| 263 | assert orders(data_dir)[0]["invoice_id"] == invoice["id"] |
| 264 | assert result["invoice_id"] == invoice["id"] |
| 265 | |
| 266 | # The response has to carry the door: the shopper is here NOW, and the |
| 267 | # portal-link handler mints post-commit and best-effort. |
| 268 | assert invoice["portal_token"] |
| 269 | assert result["pay_path"] == f"/pay/{invoice['portal_token']}" |
| 270 | |
| 271 | |
| 272 | def test_the_invoice_lines_say_what_was_bought(tmp_path, monkeypatch): |
| 273 | """A single opaque total is a bill a customer can only dispute, not |
| 274 | check.""" |
| 275 | data_dir = setup_env(tmp_path, monkeypatch) |
| 276 | product(data_dir, "p1", "Enamel Mug", 1200, product_type="service") |
| 277 | product(data_dir, "p2", "Setup", 2500, product_type="service") |
| 278 | cart("add", product_id="p1", quantity="2") |
| 279 | cart("add", product_id="p2") |
| 280 | checkout(customer_email="buyer@example.test") |
| 281 | |
| 282 | lines = sorted(invoice_lines(data_dir), key=lambda row: row["description"]) |
| 283 | assert [line["description"] for line in lines] == ["Enamel Mug", "Setup"] |
| 284 | assert [line["line_total_cents"] for line in lines] == ["2400", "2500"] |
| 285 | assert lines[0]["quantity"] == "2" |
| 286 | assert lines[0]["unit_price_cents"] == "1200" |
| 287 | assert {line["invoice_id"] for line in lines} == {invoices(data_dir)[0]["id"]} |
| 288 | |
| 289 | |
| 290 | def test_the_invoice_records_the_order_it_came_from(tmp_path, monkeypatch): |
| 291 | """Provenance in notes, the house pattern: invoices carry no |
| 292 | generated_from column, so the marker goes where anyone asking where this |
| 293 | bill came from can find it.""" |
| 294 | data_dir = setup_env(tmp_path, monkeypatch) |
| 295 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 296 | cart("add", product_id="p1") |
| 297 | order_id = checkout(customer_email="buyer@example.test")["order_id"] |
| 298 | assert f"orders/{order_id}" in invoices(data_dir)[0]["notes"] |
| 299 | |
| 300 | |
| 301 | def test_the_due_date_follows_the_billing_setting(tmp_path, monkeypatch): |
| 302 | data_dir = setup_env(tmp_path, monkeypatch, |
| 303 | settings=(("billing.invoice_due_days", "30"),)) |
| 304 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 305 | cart("add", product_id="p1") |
| 306 | checkout(customer_email="buyer@example.test", today="2026-06-15") |
| 307 | invoice = invoices(data_dir)[0] |
| 308 | assert invoice["issue_date"] == "2026-06-15" |
| 309 | assert invoice["due_date"] == "2026-07-15" |
| 310 | |
| 311 | |
| 312 | def test_checking_out_twice_makes_one_order(tmp_path, monkeypatch): |
| 313 | """And one invoice, with the SAME door handed back -- a shopper who |
| 314 | double-clicked needs the link again, not a second bill.""" |
| 315 | data_dir = setup_env(tmp_path, monkeypatch) |
| 316 | product(data_dir, "p1", "Download", 500, product_type="service") |
| 317 | cart("add", product_id="p1") |
| 318 | first = checkout(customer_email="buyer@example.test") |
| 319 | again = checkout(customer_email="buyer@example.test") |
| 320 | assert again["duplicate"] is True |
| 321 | assert again["order_id"] == first["order_id"] |
| 322 | assert again["pay_path"] == first["pay_path"] |
| 323 | assert len(orders(data_dir)) == 1 |
| 324 | assert len(invoices(data_dir)) == 1 |
| 325 | |
| 326 | |
| 327 | def test_a_price_change_stops_checkout_and_shows_both_numbers( |
| 328 | tmp_path, monkeypatch): |
| 329 | """Charging the new price silently is a bait-and-switch; honouring a |
| 330 | three-week-old basket forever is an open-ended liability.""" |
| 331 | data_dir = setup_env(tmp_path, monkeypatch) |
| 332 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 333 | cart("add", product_id="p1") |
| 334 | object_records.update_collection_record( |
| 335 | "products", "p1", {"price_cents": "1400"}, base_dir=data_dir, actor="shop") |
| 336 | |
| 337 | blocked = checkout(customer_email="buyer@example.test") |
| 338 | assert blocked["status"] == 409 |
| 339 | assert blocked["price_changes"][0]["was_cents"] == 1000 |
| 340 | assert blocked["price_changes"][0]["now_cents"] == 1400 |
| 341 | assert orders(data_dir) == [] |
| 342 | |
| 343 | |
| 344 | def test_confirming_the_new_price_orders_at_the_new_price(tmp_path, monkeypatch): |
| 345 | data_dir = setup_env(tmp_path, monkeypatch) |
| 346 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 347 | cart("add", product_id="p1") |
| 348 | object_records.update_collection_record( |
| 349 | "products", "p1", {"price_cents": "1400"}, base_dir=data_dir, actor="shop") |
| 350 | |
| 351 | result = checkout(customer_email="buyer@example.test", confirm_prices="true") |
| 352 | assert result["ok"] and result["total_cents"] == 1400 |
| 353 | assert orders(data_dir)[0]["total_cents"] == "1400" |
| 354 | |
| 355 | |
| 356 | def test_not_enough_stock_stops_checkout_with_the_numbers(tmp_path, monkeypatch): |
| 357 | data_dir = setup_env(tmp_path, monkeypatch) |
| 358 | location(data_dir, "loc-shelf", "Shelf") |
| 359 | product(data_dir, "p1", "Mug", 1000) |
| 360 | stock_in(data_dir, "p1", 2) |
| 361 | cart("add", product_id="p1", quantity="5") |
| 362 | |
| 363 | blocked = checkout(customer_email="buyer@example.test") |
| 364 | assert blocked["status"] == 409 |
| 365 | assert blocked["unavailable"][0]["available"] == "2" |
| 366 | assert blocked["unavailable"][0]["short_by"] == "3" |
| 367 | |
| 368 | |
| 369 | def test_an_emptied_basket_cannot_be_checked_out(tmp_path, monkeypatch): |
| 370 | """A basket somebody filled and then emptied still exists; there is |
| 371 | just nothing in it to sell.""" |
| 372 | data_dir = setup_env(tmp_path, monkeypatch) |
| 373 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 374 | cart("add", product_id="p1") |
| 375 | cart("clear") |
| 376 | assert checkout(customer_email="buyer@example.test")["status"] == 400 |
| 377 | |
| 378 | |
| 379 | def test_checking_out_a_session_with_no_basket_says_so(tmp_path, monkeypatch): |
| 380 | setup_env(tmp_path, monkeypatch) |
| 381 | assert checkout(customer_email="buyer@example.test")["status"] == 404 |
| 382 | |
| 383 | |
| 384 | def test_checkout_needs_somewhere_to_send_the_receipt(tmp_path, monkeypatch): |
| 385 | data_dir = setup_env(tmp_path, monkeypatch) |
| 386 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 387 | cart("add", product_id="p1") |
| 388 | assert checkout()["status"] == 400 |
| 389 | |
| 390 | |
| 391 | def test_preview_prices_the_basket_without_ordering(tmp_path, monkeypatch): |
| 392 | data_dir = setup_env(tmp_path, monkeypatch) |
| 393 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 394 | cart("add", product_id="p1", quantity="2") |
| 395 | result = checkout(preview="true") |
| 396 | assert result["subtotal_cents"] == 2000 and orders(data_dir) == [] |
| 397 | |
| 398 | |
| 399 | # --- money arrives, the sale becomes real ----------------------------------------- |
| 400 | |
| 401 | SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects" |
| 402 | |
| 403 | |
| 404 | def with_shipping(tmp_path, monkeypatch, data_dir): |
| 405 | """Install app-shipping alongside the shop, the way a real box has it. |
| 406 | |
| 407 | Payment no longer writes stock moves itself: it raises a SHIPMENT and |
| 408 | lets app-shipping's system_order_fulfillment move the goods (see |
| 409 | objects/system/shop_fulfillment.py's docstring). Two consequences for a |
| 410 | test: the two shipping collections have to exist, and both packages' |
| 411 | objects have to live under ONE object root, because that is what an |
| 412 | installed server looks like and the only way a sibling call by object id |
| 413 | resolves the way it will in production. |
| 414 | |
| 415 | shutil is imported here rather than at the top of the file to keep this |
| 416 | change contained to the fulfillment tests. |
| 417 | """ |
| 418 | import shutil |
| 419 | |
| 420 | for name in ("shipments", "shipment_lines"): |
| 421 | stage_collection(data_dir, "app-shipping", name) |
| 422 | objects_root = tmp_path / "objects" |
| 423 | for source in (SHOP_OBJECTS, SHIPPING_OBJECTS): |
| 424 | shutil.copytree(source, objects_root, dirs_exist_ok=True) |
| 425 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root)) |
| 426 | return objects_root |
| 427 | |
| 428 | |
| 429 | def shipments(data_dir): |
| 430 | return object_records.read_collection_records("shipments", base_dir=data_dir) |
| 431 | |
| 432 | |
| 433 | def paid_order(data_dir, *, quantity="2"): |
| 434 | """Take an order all the way to a received payment. |
| 435 | |
| 436 | The invoice is the one checkout raised, not a hand-made stand-in: paying |
| 437 | against a fake invoice would let the order/invoice join rot without a |
| 438 | single test noticing. |
| 439 | """ |
| 440 | location(data_dir, "loc-shelf", "Shelf") |
| 441 | location(data_dir, "loc-customer", "Customers", kind="customer") |
| 442 | product(data_dir, "p1", "Mug", 1200) |
| 443 | stock_in(data_dir, "p1", 10) |
| 444 | cart("add", product_id="p1", quantity=quantity) |
| 445 | placed = checkout(customer_email="buyer@example.test", customer_name="Ada") |
| 446 | order_id, invoice_id = placed["order_id"], placed["invoice_id"] |
| 447 | |
| 448 | payment = object_records.create_collection_record( |
| 449 | "payments", |
| 450 | {"id": object_ids.new_uuid4(), "invoice_id": invoice_id, |
| 451 | "amount_cents": "2400", "method": "card", "received_on": "2026-06-15", |
| 452 | "status": "received", "owner_id": "shop"}, |
| 453 | base_dir=data_dir) |
| 454 | return order_id, payment |
| 455 | |
| 456 | |
| 457 | def test_stock_leaves_the_shelf_when_the_money_arrives(tmp_path, monkeypatch): |
| 458 | data_dir = setup_env(tmp_path, monkeypatch, |
| 459 | settings=(("shop.stock_location", "loc-shelf"), |
| 460 | ("shop.customer_location", "loc-customer"))) |
| 461 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 462 | order_id, payment = paid_order(data_dir) |
| 463 | result = fulfil(payment) |
| 464 | assert result["confirmed"] and result["moved"] == 1 |
| 465 | |
| 466 | sale = [m for m in moves(data_dir) if m["reason"] == "sale"][0] |
| 467 | assert sale["quantity"] == "2" |
| 468 | assert sale["from_location_id"] == "loc-shelf" |
| 469 | |
| 470 | # The same chain, now travelling through the shipment noun: there is a |
| 471 | # document saying what went out, and the move is stamped with the line |
| 472 | # it came from rather than with the whole order. |
| 473 | shipment = shipments(data_dir)[0] |
| 474 | assert shipment["order_id"] == order_id and shipment["status"] == "shipped" |
| 475 | assert f"shipments/{shipment['id']}:line/" in sale["reference"] |
| 476 | assert object_records.get_collection_record( |
| 477 | "orders", order_id, base_dir=data_dir)["status"] == "shipped" |
| 478 | |
| 479 | |
| 480 | def test_a_replayed_payment_moves_nothing_twice(tmp_path, monkeypatch): |
| 481 | data_dir = setup_env(tmp_path, monkeypatch, |
| 482 | settings=(("shop.stock_location", "loc-shelf"), |
| 483 | ("shop.customer_location", "loc-customer"))) |
| 484 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 485 | _, payment = paid_order(data_dir) |
| 486 | fulfil(payment) |
| 487 | again = fulfil(payment) |
| 488 | assert again["skipped"] == "order already shipped" |
| 489 | assert len([m for m in moves(data_dir) if m["reason"] == "sale"]) == 1 |
| 490 | assert len(shipments(data_dir)) == 1 # and no second parcel |
| 491 | |
| 492 | |
| 493 | def test_a_payment_for_something_else_is_left_alone(tmp_path, monkeypatch): |
| 494 | data_dir = setup_env(tmp_path, monkeypatch) |
| 495 | object_records.create_collection_record( |
| 496 | "invoices", |
| 497 | {"id": "inv-unrelated", "number": "INV-9", "customer_name": "Someone", |
| 498 | "status": "sent", "issue_date": "2026-06-15", "due_date": "2026-06-29", |
| 499 | "subtotal_cents": "500", "total_cents": "500", "owner_id": "shop"}, |
| 500 | base_dir=data_dir) |
| 501 | payment = object_records.create_collection_record( |
| 502 | "payments", |
| 503 | {"id": object_ids.new_uuid4(), "invoice_id": "inv-unrelated", |
| 504 | "amount_cents": "500", "method": "card", "received_on": "2026-06-15", |
| 505 | "status": "received", "owner_id": "shop"}, |
| 506 | base_dir=data_dir) |
| 507 | assert fulfil(payment)["skipped"] == "no web order for this payment" |
| 508 | |
| 509 | |
| 510 | def test_a_bounced_payment_fulfils_nothing(tmp_path, monkeypatch): |
| 511 | data_dir = setup_env(tmp_path, monkeypatch, |
| 512 | settings=(("shop.stock_location", "loc-shelf"),)) |
| 513 | order_id, payment = paid_order(data_dir) |
| 514 | object_records.update_collection_record( |
| 515 | "payments", payment["id"], {"status": "bounced"}, |
| 516 | base_dir=data_dir, actor="shop") |
| 517 | bounced = object_records.get_collection_record("payments", payment["id"], |
| 518 | base_dir=data_dir) |
| 519 | assert fulfil(bounced)["skipped"] == "payment not received" |
| 520 | assert object_records.get_collection_record( |
| 521 | "orders", order_id, base_dir=data_dir)["status"] == "draft" |
| 522 | |
| 523 | |
| 524 | def test_an_unconfigured_location_still_lets_the_sale_stand(tmp_path, monkeypatch): |
| 525 | """A missing setting must not cost somebody a paid order -- and now it |
| 526 | must not cost them the parcel either: the box still goes out, and the |
| 527 | gap in the ledger is reported rather than swallowed.""" |
| 528 | data_dir = setup_env(tmp_path, monkeypatch) |
| 529 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 530 | order_id, payment = paid_order(data_dir) |
| 531 | result = fulfil(payment) |
| 532 | assert result["confirmed"] and result["moved"] == 0 |
| 533 | assert "stock_location" in result["warning"] |
| 534 | assert shipments(data_dir)[0]["status"] == "shipped" |
| 535 | assert object_records.get_collection_record( |
| 536 | "orders", order_id, base_dir=data_dir)["status"] == "shipped" |
| 537 | |
| 538 | |
| 539 | # --- the page a shopper actually looks at ------------------------------------ |
| 540 | |
| 541 | def test_a_product_card_links_to_the_product(tmp_path, monkeypatch): |
| 542 | """The grid was a dead end: names were bold text, so a shopper could add |
| 543 | a thing to a basket but never find out what it was.""" |
| 544 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 545 | product(data_dir, "p1", "Enamel Mug", 1200) |
| 546 | body = page()["body"] |
| 547 | assert '<a href="/shop/p1">Enamel Mug</a>' in body |
| 548 | |
| 549 | |
| 550 | def test_the_product_page_says_what_it_is_and_offers_to_sell_it( |
| 551 | tmp_path, monkeypatch): |
| 552 | """Name, price and full description in one place, with an add form that |
| 553 | posts to /shop -- the SAME route the cards post to, so there is one way |
| 554 | into a basket rather than two that can drift apart.""" |
| 555 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 556 | product(data_dir, "p1", "Enamel Mug", 1200, |
| 557 | description="Twelve ounces. Chips beautifully.") |
| 558 | body = page(product_id="p1")["body"] |
| 559 | |
| 560 | assert "Enamel Mug" in body |
| 561 | assert "P1" in body # the sku |
| 562 | assert "12.00" in body |
| 563 | assert "Twelve ounces. Chips beautifully." in body |
| 564 | assert '<form method="post" action="/shop"' in body |
| 565 | assert 'name="do" value="add"' in body |
| 566 | assert f'name="session_token" value="{TOKEN}"' in body |
| 567 | assert 'name="product_id" value="p1"' in body |
| 568 | assert '<a href="/shop">Back to shop</a>' in body |
| 569 | |
| 570 | |
| 571 | def test_a_physical_product_says_whether_it_is_there(tmp_path, monkeypatch): |
| 572 | """Low-key, but the question every shopper has. Derived from the stock |
| 573 | ledger, never stored.""" |
| 574 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 575 | location(data_dir, "loc-shelf", "Shelf") |
| 576 | product(data_dir, "p1", "Mug", 1200) |
| 577 | product(data_dir, "p2", "Bowl", 900) |
| 578 | stock_in(data_dir, "p1", 4) |
| 579 | assert "In stock" in page(product_id="p1")["body"] |
| 580 | assert "Out of stock" in page(product_id="p2")["body"] |
| 581 | |
| 582 | |
| 583 | def test_something_that_never_runs_out_says_nothing_about_stock( |
| 584 | tmp_path, monkeypatch): |
| 585 | """An hour of work has no shelf. Saying "Out of stock" about it would |
| 586 | refuse a sale that checkout would happily take.""" |
| 587 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 588 | product(data_dir, "p1", "Setup", 2500, product_type="service") |
| 589 | body = page(product_id="p1")["body"] |
| 590 | assert "In stock" not in body and "Out of stock" not in body |
| 591 | |
| 592 | |
| 593 | def test_an_unknown_product_is_a_friendly_404_not_a_traceback( |
| 594 | tmp_path, monkeypatch): |
| 595 | """A mistyped link is a shopper who is still in the shop.""" |
| 596 | setup_env(tmp_path, monkeypatch, page=True) |
| 597 | result = page(product_id="no-such-thing") |
| 598 | assert result["status"] == 404 |
| 599 | assert result["content_type"].startswith("text/html") |
| 600 | assert "Back to shop" in result["body"] |
| 601 | assert "Traceback" not in result["body"] |
| 602 | |
| 603 | |
| 604 | def test_a_withdrawn_product_reads_the_same_as_a_missing_one( |
| 605 | tmp_path, monkeypatch): |
| 606 | """Distinguishing them would tell a stranger which product ids exist.""" |
| 607 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 608 | product(data_dir, "p1", "Retired Mug", 1000, is_active="false") |
| 609 | assert page(product_id="p1")["status"] == 404 |
| 610 | |
| 611 | |
| 612 | def test_the_page_reuses_the_basket_the_cookie_names(tmp_path, monkeypatch): |
| 613 | """The bug this whole change exists for: a returning shopper's basket |
| 614 | was minted fresh every visit, so nothing ever survived a page load.""" |
| 615 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 616 | product(data_dir, "p1", "Mug", 1200, product_type="service") |
| 617 | cart("add", product_id="p1", quantity="2") |
| 618 | |
| 619 | result = page() |
| 620 | assert "24.00" in result["body"] # the basket total |
| 621 | # A cookie the browser already holds is not re-set on every response. |
| 622 | assert "set_cookie" not in result |
| 623 | |
| 624 | |
| 625 | def test_a_shopper_with_no_cookie_is_given_one(tmp_path, monkeypatch): |
| 626 | """Path-scoped, http-only, SameSite=Lax: it says WHICH basket, never |
| 627 | who, and it is useless anywhere but here.""" |
| 628 | setup_env(tmp_path, monkeypatch, page=True) |
| 629 | result = page(_cookies={}) |
| 630 | cookie = result["set_cookie"] |
| 631 | assert cookie.startswith("cart=") |
| 632 | assert "Path=/" in cookie and "HttpOnly" in cookie |
| 633 | assert "SameSite=Lax" in cookie and "Max-Age=1209600" in cookie |
| 634 | # The old key is gone: the server accepts `set_cookie` and nothing else. |
| 635 | assert "headers" not in result |
| 636 | |
| 637 | |
| 638 | # ============================================================================= |
| 639 | # TAX AND POSTAGE |
| 640 | # |
| 641 | # The shop charged neither, which was a compliance problem and a straight |
| 642 | # money leak: every parcel went out with the delivery paid by the seller. |
| 643 | # What is worth testing here is not that a percentage can be multiplied -- |
| 644 | # it is that the percentage is applied ONCE to the whole sale, that postage |
| 645 | # is a line a customer can read rather than a number welded into a total, |
| 646 | # and that a shop which has configured none of it bills exactly as it did |
| 647 | # before. Absent configuration must look like today, never like a broken |
| 648 | # tax line. |
| 649 | # ============================================================================= |
| 650 | |
| 651 | # --- the arithmetic, with no data directory in sight ------------------------- |
| 652 | |
| 653 | def test_tax_rounds_half_up_once_over_the_whole_sale(): |
| 654 | """Four fifty-cent lines at 5% are 10c of tax, not 12c. |
| 655 | |
| 656 | Rounded per line, 2.5c becomes 3c four times over and the shop |
| 657 | overcharges by 2c that no customer can reconcile against the rate |
| 658 | printed on the bill. Tax is owed on a sale, not on each row of it. |
| 659 | """ |
| 660 | items = [{"id": f"i{n}", "quantity": "1", "unit_price_cents": "50"} |
| 661 | for n in range(4)] |
| 662 | folded = object_cart.checkout_totals(items, tax_rate_bps=500) |
| 663 | assert folded["subtotal_cents"] == 200 |
| 664 | assert folded["tax_cents"] == 10 # 10.0, not 4 x 3 |
| 665 | assert sum(object_cart.tax_cents(50, 500) for _ in range(4)) == 12 |
| 666 | assert folded["total_cents"] == 210 |
| 667 | |
| 668 | |
| 669 | def test_a_rate_of_zero_is_a_real_answer_not_a_missing_setting(): |
| 670 | """Plenty of small sellers owe none, and must be able to say so.""" |
| 671 | assert object_cart.tax_cents(10_000, 0) == 0 |
| 672 | assert object_cart.tax_cents(0, 1500) == 0 |
| 673 | assert object_cart.tax_cents(10_000, 1500) == 1500 # 1500bps = 15% |
| 674 | assert object_cart.tax_cents(1099, 825) == 91 # 90.6675 -> 91 |
| 675 | |
| 676 | |
| 677 | def test_postage_is_flat_until_the_basket_earns_its_way_past_the_threshold(): |
| 678 | """The boundary is AT the threshold, not past it: a shop advertising |
| 679 | 'free over $50' and then charging on a $50 basket has lied on its own |
| 680 | banner.""" |
| 681 | assert object_cart.shipping_cents(4999, 500, 5000) == 500 |
| 682 | assert object_cart.shipping_cents(5000, 500, 5000) == 0 # exactly |
| 683 | assert object_cart.shipping_cents(5001, 500, 5000) == 0 |
| 684 | # No threshold configured: postage is always charged. |
| 685 | assert object_cart.shipping_cents(1_000_000, 500, 0) == 500 |
| 686 | |
| 687 | |
| 688 | def test_a_flat_rate_of_zero_disables_shipping_entirely(): |
| 689 | """A digital-only shop charges no postage and must not be made to show |
| 690 | a zero line for it.""" |
| 691 | assert object_cart.shipping_cents(10_000, 0, 0) == 0 |
| 692 | folded = object_cart.checkout_totals( |
| 693 | [{"id": "a", "quantity": "1", "unit_price_cents": "1000"}], |
| 694 | shipping_flat_cents=0) |
| 695 | assert folded["shipping_cents"] == 0 |
| 696 | assert folded["shipping_free"] is False # not free -- simply not sold |
| 697 | assert folded["total_cents"] == 1000 |
| 698 | |
| 699 | |
| 700 | def test_the_flag_decides_whether_the_postage_itself_is_taxed(): |
| 701 | """Jurisdictions genuinely disagree about this, so the seller chooses.""" |
| 702 | items = [{"id": "a", "quantity": "1", "unit_price_cents": "1000"}] |
| 703 | goods_only = object_cart.checkout_totals( |
| 704 | items, tax_rate_bps=1000, shipping_flat_cents=500, tax_shipping=False) |
| 705 | assert goods_only["tax_cents"] == 100 # 10% of 1000 |
| 706 | assert goods_only["total_cents"] == 1600 |
| 707 | |
| 708 | with_postage = object_cart.checkout_totals( |
| 709 | items, tax_rate_bps=1000, shipping_flat_cents=500, tax_shipping=True) |
| 710 | assert with_postage["tax_cents"] == 150 # 10% of 1500 |
| 711 | assert with_postage["total_cents"] == 1650 |
| 712 | |
| 713 | |
| 714 | def test_free_shipping_is_distinguishable_from_no_shipping(): |
| 715 | """A bare 0 cannot tell 'you saved the postage' from 'this shop does |
| 716 | not post things', and only one of those is worth saying out loud.""" |
| 717 | items = [{"id": "a", "quantity": "1", "unit_price_cents": "5000"}] |
| 718 | earned = object_cart.checkout_totals( |
| 719 | items, shipping_flat_cents=500, free_over_cents=5000) |
| 720 | assert earned["shipping_cents"] == 0 and earned["shipping_free"] is True |
| 721 | never = object_cart.checkout_totals(items, shipping_flat_cents=0) |
| 722 | assert never["shipping_cents"] == 0 and never["shipping_free"] is False |
| 723 | |
| 724 | |
| 725 | # --- what checkout writes down ------------------------------------------------ |
| 726 | |
| 727 | TAXED_AND_POSTED = (("shop.tax_rate_bps", "1000"), |
| 728 | ("shop.shipping_flat_cents", "500")) |
| 729 | |
| 730 | |
| 731 | def sold(data_dir, *, cents=1000, quantity="1", products=1): |
| 732 | """Put something untracked in the basket -- the money is the subject |
| 733 | here, not the shelf.""" |
| 734 | for n in range(products): |
| 735 | product(data_dir, f"p{n}", f"Thing {n}", cents, product_type="service") |
| 736 | cart("add", product_id=f"p{n}", quantity=quantity) |
| 737 | |
| 738 | |
| 739 | def test_checkout_charges_postage_as_a_line_and_tax_as_a_total( |
| 740 | tmp_path, monkeypatch): |
| 741 | """The bill a customer can actually check: every line adds up to the |
| 742 | subtotal, the tax is stated, and the three come to the total.""" |
| 743 | data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED) |
| 744 | sold(data_dir, cents=1000) |
| 745 | result = checkout(customer_email="buyer@example.test") |
| 746 | |
| 747 | assert result["subtotal_cents"] == 1000 |
| 748 | assert result["shipping_cents"] == 500 |
| 749 | assert result["tax_cents"] == 100 # 10% of goods; postage untaxed |
| 750 | assert result["total_cents"] == 1600 # what the payer owes |
| 751 | |
| 752 | lines = sorted(invoice_lines(data_dir), key=lambda row: row["description"]) |
| 753 | assert [line["description"] for line in lines] == ["Shipping", "Thing 0"] |
| 754 | shipping_line = lines[0] |
| 755 | assert shipping_line["quantity"] == "1" |
| 756 | assert shipping_line["unit_price_cents"] == "500" |
| 757 | assert shipping_line["line_total_cents"] == "500" |
| 758 | # Postage is not taxable here, so the line says nothing about tax. |
| 759 | assert not shipping_line["tax_rate_bps"] |
| 760 | |
| 761 | invoice = invoices(data_dir)[0] |
| 762 | assert invoice["subtotal_cents"] == "1500" # goods + postage |
| 763 | assert invoice["tax_cents"] == "100" |
| 764 | assert invoice["total_cents"] == "1600" |
| 765 | # The property that makes a bill checkable rather than disputable. |
| 766 | assert (sum(int(line["line_total_cents"]) for line in lines) |
| 767 | + int(invoice["tax_cents"])) == int(invoice["total_cents"]) |
| 768 | |
| 769 | |
| 770 | def test_the_order_records_the_tax_and_the_grand_total(tmp_path, monkeypatch): |
| 771 | """Subtotal stays goods -- it is defined as the sum of the order's own |
| 772 | lines, and postage is not one of them. Postage on an order is implied |
| 773 | by total - subtotal - tax until orders grows a shipping_cents column; |
| 774 | the itemisation lives on the invoice, where a customer reads it.""" |
| 775 | data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED) |
| 776 | sold(data_dir, cents=1000) |
| 777 | checkout(customer_email="buyer@example.test") |
| 778 | |
| 779 | order = orders(data_dir)[0] |
| 780 | assert order["subtotal_cents"] == "1000" |
| 781 | assert order["tax_cents"] == "100" |
| 782 | assert order["total_cents"] == "1600" |
| 783 | assert (int(order["total_cents"]) - int(order["subtotal_cents"]) |
| 784 | - int(order["tax_cents"])) == 500 |
| 785 | |
| 786 | |
| 787 | def test_taxable_postage_says_so_on_its_own_line(tmp_path, monkeypatch): |
| 788 | """Somebody auditing 'was delivery taxed?' should find the answer on |
| 789 | the line, not reverse-engineer it out of a total.""" |
| 790 | data_dir = setup_env(tmp_path, monkeypatch, settings=( |
| 791 | ("shop.tax_rate_bps", "1000"), ("shop.tax_shipping", "true"), |
| 792 | ("shop.shipping_flat_cents", "500"))) |
| 793 | sold(data_dir, cents=1000) |
| 794 | result = checkout(customer_email="buyer@example.test") |
| 795 | |
| 796 | assert result["tax_cents"] == 150 # 10% of 1000 + 500 |
| 797 | assert result["total_cents"] == 1650 |
| 798 | shipping_line = [l for l in invoice_lines(data_dir) |
| 799 | if l["description"] == "Shipping"][0] |
| 800 | assert shipping_line["tax_rate_bps"] == "1000" |
| 801 | assert shipping_line["line_tax_cents"] == "50" |
| 802 | |
| 803 | |
| 804 | def test_a_basket_over_the_threshold_ships_free_and_is_billed_that_way( |
| 805 | tmp_path, monkeypatch): |
| 806 | data_dir = setup_env(tmp_path, monkeypatch, settings=( |
| 807 | ("shop.shipping_flat_cents", "500"), |
| 808 | ("shop.shipping_free_over_cents", "2000"))) |
| 809 | sold(data_dir, cents=2000) # exactly the threshold |
| 810 | result = checkout(customer_email="buyer@example.test") |
| 811 | |
| 812 | assert result["shipping_cents"] == 0 and result["shipping_free"] is True |
| 813 | assert result["total_cents"] == 2000 |
| 814 | # No postage charged means no postage line: a free-shipping invoice |
| 815 | # with a "Shipping 0.00" row on it invites a question that has no |
| 816 | # answer. |
| 817 | assert [l["description"] for l in invoice_lines(data_dir)] == ["Thing 0"] |
| 818 | |
| 819 | |
| 820 | def test_rounding_once_survives_the_whole_checkout(tmp_path, monkeypatch): |
| 821 | """The same 10c-not-12c case, driven end to end -- because the fold |
| 822 | being right is worth nothing if checkout re-derives tax per line on |
| 823 | its way to the invoice.""" |
| 824 | data_dir = setup_env(tmp_path, monkeypatch, |
| 825 | settings=(("shop.tax_rate_bps", "500"),)) |
| 826 | sold(data_dir, cents=50, products=4) |
| 827 | result = checkout(customer_email="buyer@example.test") |
| 828 | assert result["subtotal_cents"] == 200 |
| 829 | assert result["tax_cents"] == 10 |
| 830 | assert result["total_cents"] == 210 |
| 831 | assert invoices(data_dir)[0]["tax_cents"] == "10" |
| 832 | |
| 833 | |
| 834 | def test_a_shop_that_configures_nothing_bills_exactly_as_it_did( |
| 835 | tmp_path, monkeypatch): |
| 836 | """The regression that matters most: absent configuration must be |
| 837 | invisible. No postage line, no tax, and an invoice line carrying the |
| 838 | same populated fields it carried before any of this existed.""" |
| 839 | data_dir = setup_env(tmp_path, monkeypatch) # no settings at all |
| 840 | sold(data_dir, cents=1200, quantity="2") |
| 841 | result = checkout(customer_email="buyer@example.test") |
| 842 | |
| 843 | assert result["total_cents"] == 2400 == result["subtotal_cents"] |
| 844 | assert result["shipping_cents"] == 0 and result["tax_cents"] == 0 |
| 845 | |
| 846 | lines = invoice_lines(data_dir) |
| 847 | assert len(lines) == 1 # no Shipping row |
| 848 | populated = {k for k, v in lines[0].items() if str(v or "").strip()} |
| 849 | # line_tax_cents is the schema's own default of "0" and was there |
| 850 | # before any of this; tax_rate_bps has no default and stays empty, |
| 851 | # which is what "this line was never taxed" looks like on disk. |
| 852 | assert populated == {"id", "invoice_id", "description", "quantity", |
| 853 | "unit_price_cents", "line_total_cents", "owner_id", |
| 854 | "created_at", "line_tax_cents"} |
| 855 | assert lines[0]["line_tax_cents"] == "0" |
| 856 | assert lines[0]["tax_rate_bps"] == "" |
| 857 | invoice = invoices(data_dir)[0] |
| 858 | assert invoice["subtotal_cents"] == "2400" == invoice["total_cents"] |
| 859 | assert invoice["tax_cents"] == "0" |
| 860 | assert orders(data_dir)[0]["total_cents"] == "2400" |
| 861 | |
| 862 | |
| 863 | def test_preview_shows_the_whole_breakdown_before_anybody_commits( |
| 864 | tmp_path, monkeypatch): |
| 865 | """A preview exists so somebody can see what they are about to owe; a |
| 866 | subtotal alone hides the two numbers they most want to check.""" |
| 867 | data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED) |
| 868 | sold(data_dir, cents=1000) |
| 869 | result = checkout(preview="true") |
| 870 | assert result["subtotal_cents"] == 1000 |
| 871 | assert result["shipping_cents"] == 500 |
| 872 | assert result["tax_cents"] == 100 |
| 873 | assert result["total_cents"] == 1600 |
| 874 | assert orders(data_dir) == [] and invoices(data_dir) == [] |
| 875 | |
| 876 | |
| 877 | # --- what the shopper sees before deciding ------------------------------------- |
| 878 | |
| 879 | def test_the_basket_page_breaks_the_total_down(tmp_path, monkeypatch): |
| 880 | """A shopper who meets a surprise at the last step abandons the |
| 881 | basket. The footer is where postage and tax stop being a surprise.""" |
| 882 | data_dir = setup_env(tmp_path, monkeypatch, settings=TAXED_AND_POSTED, |
| 883 | page=True) |
| 884 | product(data_dir, "p1", "Mug", 1000, product_type="service") |
| 885 | cart("add", product_id="p1") |
| 886 | body = page()["body"] |
| 887 | assert "Subtotal" in body and "10.00" in body |
| 888 | assert "Shipping" in body and "5.00" in body |
| 889 | assert "Tax" in body and "1.00" in body |
| 890 | assert "16.00" in body # the total |
| 891 | |
| 892 | |
| 893 | def test_the_basket_page_says_free_shipping_when_it_is_earned( |
| 894 | tmp_path, monkeypatch): |
| 895 | """The one delighter in a basket. A silent 0.00 reads as a shop that |
| 896 | forgot to charge, not one that gave the shopper something.""" |
| 897 | data_dir = setup_env(tmp_path, monkeypatch, page=True, settings=( |
| 898 | ("shop.shipping_flat_cents", "500"), |
| 899 | ("shop.shipping_free_over_cents", "2000"))) |
| 900 | product(data_dir, "p1", "Mug", 2000, product_type="service") |
| 901 | cart("add", product_id="p1") |
| 902 | body = page()["body"] |
| 903 | assert "Free shipping" in body |
| 904 | assert "Subtotal" in body |
| 905 | |
| 906 | |
| 907 | def test_the_basket_page_is_untouched_when_nothing_is_configured( |
| 908 | tmp_path, monkeypatch): |
| 909 | """Zero-rows are not neutral: 'Shipping 0.00' and 'Tax 0.00' read as a |
| 910 | broken shop rather than one that does not do those things.""" |
| 911 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 912 | product(data_dir, "p1", "Mug", 1200, product_type="service") |
| 913 | cart("add", product_id="p1", quantity="2") |
| 914 | body = page()["body"] |
| 915 | assert "Shipping" not in body and "Subtotal" not in body |
| 916 | assert "24.00" in body |
| 917 | assert '<tfoot><tr><th colspan="3">Total</th>' in body |
| 918 | |
| 919 | |
| 920 | # ============================================================================= |
| 921 | # MERCHANDISING |
| 922 | # |
| 923 | # Categories, variants and the two words a shopper types at checkout. The |
| 924 | # basket did not change to support any of it -- a variant IS a product, so |
| 925 | # every add, price check and stock check here is the same code path it |
| 926 | # always was -- which is exactly why the tests belong beside the basket's: |
| 927 | # what they hold is that the page collapses and groups without the basket |
| 928 | # learning a new noun, and that the one refusal this adds says what to do |
| 929 | # instead. The full variant/image/gift story lives in |
| 930 | # tests/test_merchandising.py; this section is the basket's own view of it. |
| 931 | # ============================================================================= |
| 932 | |
| 933 | def variants(data_dir, *, parent_cents=0): |
| 934 | """A parent that is a heading and one variant that is a real thing.""" |
| 935 | product(data_dir, "tote", "Tote Bag", parent_cents, category="Bags") |
| 936 | product(data_dir, "tote-m", "Tote Bag, medium", 2000, category="Bags", |
| 937 | product_type="service", parent_product_id="tote", |
| 938 | options='{"size": "M", "colour": "navy"}') |
| 939 | |
| 940 | |
| 941 | def test_the_index_groups_by_category_and_never_hides_the_unfiled( |
| 942 | tmp_path, monkeypatch): |
| 943 | """Alphabetical headings, uncategorised last under "Everything else". |
| 944 | Last, not gone: a product nobody got round to filing is still stock |
| 945 | somebody paid for.""" |
| 946 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 947 | product(data_dir, "p1", "Enamel Mug", 1200, category="Kitchen") |
| 948 | product(data_dir, "p2", "Linocut Print", 4000, category="Art") |
| 949 | product(data_dir, "p3", "Odd Thing", 500) |
| 950 | body = page()["body"] |
| 951 | |
| 952 | assert '<h2 class="shop-category">Art</h2>' in body |
| 953 | assert '<h2 class="shop-category">Everything else</h2>' in body |
| 954 | assert body.index("Art</h2>") < body.index("Kitchen</h2>") |
| 955 | assert body.index("Kitchen</h2>") < body.index("Everything else</h2>") |
| 956 | assert "Odd Thing" in body[body.index("Everything else</h2>"):] |
| 957 | |
| 958 | |
| 959 | def test_a_parent_shows_one_card_and_the_basket_refuses_it_by_name( |
| 960 | tmp_path, monkeypatch): |
| 961 | """The card is a doorway, not an Add button: the parent has no price |
| 962 | of its own, so there is nothing to charge and nothing to pick. The |
| 963 | refusal names the options, because a "no" that does not say what to do |
| 964 | instead is a lost sale.""" |
| 965 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 966 | variants(data_dir) |
| 967 | body = page()["body"] |
| 968 | |
| 969 | assert body.count('<div class="shop-card">') == 1 |
| 970 | assert "Tote Bag, medium" not in body # collapsed, not listed |
| 971 | assert "Choose options" in body and "from USD 20.00" in body |
| 972 | assert 'name="do" value="add"' not in body |
| 973 | |
| 974 | refused = cart("add", product_id="tote") |
| 975 | assert refused["status"] == 409 |
| 976 | assert "M / navy" in refused["error"] |
| 977 | assert refused["options"][0]["product_id"] == "tote-m" |
| 978 | |
| 979 | |
| 980 | def test_adding_a_variant_is_an_ordinary_add(tmp_path, monkeypatch): |
| 981 | """The whole argument, in the basket: a product_id went in and a |
| 982 | description came out. Nothing here knows what a variant is.""" |
| 983 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 984 | variants(data_dir) |
| 985 | assert cart("add", product_id="tote-m")["subtotal_cents"] == 2000 |
| 986 | item = object_records.read_collection_records("cart_items", |
| 987 | base_dir=data_dir)[0] |
| 988 | assert item["description"] == "Tote Bag, medium" |
| 989 | |
| 990 | body = page()["body"] |
| 991 | assert "Tote Bag, medium" in body # the basket line |
| 992 | assert "20.00" in body |
| 993 | |
| 994 | |
| 995 | def test_the_checkout_form_carries_the_note_and_the_gift_message( |
| 996 | tmp_path, monkeypatch): |
| 997 | """Straight through the page to action_checkout, which decides where |
| 998 | they land. Both optional, and no gift flag: the packing slip shows no |
| 999 | prices by construction, so every parcel is already gift-safe.""" |
| 1000 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 1001 | product(data_dir, "p1", "Mug", 1200, product_type="service") |
| 1002 | cart("add", product_id="p1") |
| 1003 | assert '<textarea name="customer_note"' in page()["body"] |
| 1004 | |
| 1005 | result = checkout(customer_email="buyer@example.test", |
| 1006 | customer_note="Leave with the neighbour", |
| 1007 | gift_message="Happy birthday, Ada") |
| 1008 | basket = object_records.get_collection_record("carts", result["cart_id"], |
| 1009 | base_dir=data_dir) |
| 1010 | assert basket["customer_note"] == "Leave with the neighbour" |
| 1011 | assert basket["gift_message"] == "Happy birthday, Ada" |
| 1012 | |
| 1013 | |
| 1014 | def test_a_product_with_no_category_and_no_variants_renders_as_it_always_did( |
| 1015 | tmp_path, monkeypatch): |
| 1016 | """The regression guard. Every field this slice added is optional, and |
| 1017 | a shop that sets none of them must not be able to tell it happened -- |
| 1018 | apart from the photograph placeholder, which is the one deliberate |
| 1019 | change to a page that was text-only.""" |
| 1020 | data_dir = setup_env(tmp_path, monkeypatch, page=True) |
| 1021 | product(data_dir, "p1", "Enamel Mug", 1200, product_type="service") |
| 1022 | body = page()["body"] |
| 1023 | |
| 1024 | assert '<a href="/shop/p1">Enamel Mug</a>' in body |
| 1025 | assert "USD 12.00" in body |
| 1026 | assert 'name="product_id" value="p1"' in body |
| 1027 | assert '<h2 class="shop-category">' not in body |
| 1028 | assert '<div class="shop-image placeholder"></div>' in body |
| 1029 | assert cart("add", product_id="p1", quantity="2")["subtotal_cents"] == 2400 |
| 1030 | |
| 1031 | |
| 1032 | # --- money bugs found by walking the live shop ------------------------------- |
| 1033 | # |
| 1034 | # Neither of these was caught by the suite, and the reason is worth |
| 1035 | # recording: the tests exercised objects directly, while the live server |
| 1036 | # runs them through the event dispatcher. The gap between "the object is |
| 1037 | # right" and "the system is right" is exactly where both of these lived. |
| 1038 | |
| 1039 | def test_a_totals_recompute_never_zeroes_tax_it_cannot_see(tmp_path, monkeypatch): |
| 1040 | """The live failure: a customer was quoted 2116 at checkout, and by the |
| 1041 | time the invoice lines had been written the totals handler had restated |
| 1042 | the invoice to 2000 with tax 0 -- because tax is computed once over the |
| 1043 | whole sale and stamped on the DOCUMENT, and that pass only reads lines. |
| 1044 | A fold must not replace a value it cannot reproduce.""" |
| 1045 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1046 | settings=(("shop.tax_rate_bps", "825"), |
| 1047 | ("shop.shipping_flat_cents", "600"))) |
| 1048 | product(data_dir, "p1", "Mug", 1400, product_type="service") |
| 1049 | cart("add", product_id="p1") |
| 1050 | quoted = checkout(customer_email="grace@example.test") |
| 1051 | |
| 1052 | invoice = object_records.get_collection_record( |
| 1053 | "invoices", quoted["invoice_id"], base_dir=data_dir) |
| 1054 | assert int(invoice["total_cents"]) == quoted["total_cents"] |
| 1055 | |
| 1056 | # Now run the recompute the live server runs on every line write. |
| 1057 | object_execution.execute_object( |
| 1058 | RUNTIME, |
| 1059 | object_execution.ObjectExecutionRequest( |
| 1060 | "system_invoice_totals", method="EVENT", |
| 1061 | payload={"collection": "invoice_lines", "action": "created", |
| 1062 | "record_id": ""}), |
| 1063 | roots=[PACKAGES / "app-invoices" / "objects"]) |
| 1064 | |
| 1065 | after = object_records.get_collection_record( |
| 1066 | "invoices", quoted["invoice_id"], base_dir=data_dir) |
| 1067 | assert int(after["total_cents"]) == quoted["total_cents"], ( |
| 1068 | "the recompute silently dropped the tax the customer agreed to") |
| 1069 | assert int(after["tax_cents"]) > 0 |
| 1070 | |
| 1071 | |
| 1072 | def test_a_part_payment_does_not_ship_the_goods(tmp_path, monkeypatch): |
| 1073 | """Goods leave when the BILL is settled, not when money merely |
| 1074 | arrives. Paying 14.00 against a 20.00 invoice used to fulfil the order |
| 1075 | in full while the invoice sat at `partial` saying otherwise.""" |
| 1076 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1077 | settings=(("shop.stock_location", "loc-shelf"), |
| 1078 | ("shop.customer_location", "loc-customer"))) |
| 1079 | order_id, _ = paid_order(data_dir) # pays in full |
| 1080 | order = object_records.get_collection_record("orders", order_id, |
| 1081 | base_dir=data_dir) |
| 1082 | invoice_id = order["invoice_id"] |
| 1083 | |
| 1084 | # A second order, deliberately underpaid. |
| 1085 | cart("add", product_id="p1", quantity="2") |
| 1086 | second = checkout(customer_email="short@example.test") |
| 1087 | part = object_records.create_collection_record( |
| 1088 | "payments", |
| 1089 | {"id": object_ids.new_uuid4(), "invoice_id": second["invoice_id"], |
| 1090 | "amount_cents": "1", "method": "card", "received_on": "2026-07-26", |
| 1091 | "status": "received", "owner_id": "shop"}, |
| 1092 | base_dir=data_dir) |
| 1093 | |
| 1094 | result = fulfil(part) |
| 1095 | assert "not settled" in result["skipped"] |
| 1096 | assert object_records.get_collection_record( |
| 1097 | "orders", second["order_id"], base_dir=data_dir)["status"] == "draft" |
| 1098 | assert invoice_id # the fully paid one is untouched by this test |
| 1099 | |
| 1100 | |
| 1101 | def test_paying_the_balance_later_does_ship(tmp_path, monkeypatch): |
| 1102 | """A deposit followed by the balance must work: the payment that tips |
| 1103 | the invoice to settled is the one that ships.""" |
| 1104 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1105 | settings=(("shop.stock_location", "loc-shelf"), |
| 1106 | ("shop.customer_location", "loc-customer"))) |
| 1107 | location(data_dir, "loc-shelf", "Shelf") |
| 1108 | location(data_dir, "loc-customer", "Customers", kind="customer") |
| 1109 | product(data_dir, "p1", "Mug", 1200) |
| 1110 | stock_in(data_dir, "p1", 10) |
| 1111 | cart("add", product_id="p1", quantity="1") |
| 1112 | order = checkout(customer_email="deposit@example.test") |
| 1113 | total = order["total_cents"] |
| 1114 | |
| 1115 | half = object_records.create_collection_record( |
| 1116 | "payments", |
| 1117 | {"id": object_ids.new_uuid4(), "invoice_id": order["invoice_id"], |
| 1118 | "amount_cents": str(total // 2), "method": "card", |
| 1119 | "received_on": "2026-07-26", "status": "received", "owner_id": "shop"}, |
| 1120 | base_dir=data_dir) |
| 1121 | assert "not settled" in fulfil(half)["skipped"] |
| 1122 | |
| 1123 | rest = object_records.create_collection_record( |
| 1124 | "payments", |
| 1125 | {"id": object_ids.new_uuid4(), "invoice_id": order["invoice_id"], |
| 1126 | "amount_cents": str(total - total // 2), "method": "card", |
| 1127 | "received_on": "2026-07-26", "status": "received", "owner_id": "shop"}, |
| 1128 | base_dir=data_dir) |
| 1129 | assert fulfil(rest)["confirmed"] is True |
| 1130 | |
| 1131 | |
| 1132 | # --- one payment, one shipment ------------------------------------------------- |
| 1133 | |
| 1134 | def test_two_concurrent_deliveries_of_one_payment_ship_once(tmp_path, |
| 1135 | monkeypatch): |
| 1136 | """Goods leaving twice against one payment, reproduced before it was |
| 1137 | fixed: two shipments, FOUR units against an order of two, two sale |
| 1138 | moves. |
| 1139 | |
| 1140 | Nothing in the shipping layer could have stopped it. |
| 1141 | action_create_shipment works out what is unshipped by reading |
| 1142 | shipment_lines, and hook_shipment_lines refuses an over-ship by summing |
| 1143 | them -- but both are check-then-write, and a hook runs BEFORE the write |
| 1144 | lock, so both passes read an empty history and both wrote. Layered |
| 1145 | advisory checks do not compose into an atomic one. |
| 1146 | |
| 1147 | The fix is the one thing on this box that IS atomic: a compare-and-set |
| 1148 | on a single record (63). The claim is the write that moves the order |
| 1149 | out of the shippable set, and the loser finds the row already changed. |
| 1150 | """ |
| 1151 | import threading |
| 1152 | |
| 1153 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1154 | settings=(("shop.stock_location", "loc-shelf"), |
| 1155 | ("shop.customer_location", "loc-customer"))) |
| 1156 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 1157 | order_id, payment = paid_order(data_dir) |
| 1158 | |
| 1159 | out = [] |
| 1160 | threads = [threading.Thread(target=lambda: out.append(fulfil(payment))) |
| 1161 | for _ in range(2)] |
| 1162 | for thread in threads: |
| 1163 | thread.start() |
| 1164 | for thread in threads: |
| 1165 | thread.join() |
| 1166 | |
| 1167 | lines = object_records.read_collection_records("shipment_lines", |
| 1168 | base_dir=data_dir) |
| 1169 | shipments = object_records.read_collection_records("shipments", |
| 1170 | base_dir=data_dir) |
| 1171 | sales = [m for m in moves(data_dir) if m["reason"] == "sale"] |
| 1172 | |
| 1173 | assert len(shipments) == 1, out |
| 1174 | assert sum(float(line["quantity"]) for line in lines) == 2.0 |
| 1175 | assert len(sales) == 1 |
| 1176 | |
| 1177 | # And the loser says so rather than reporting a silent success. |
| 1178 | skipped = [r for r in out if r.get("skipped")] |
| 1179 | assert len(skipped) == 1 |
| 1180 | assert "claimed" in skipped[0]["skipped"] or "handling" in skipped[0]["skipped"] |
| 1181 | |
| 1182 | |
| 1183 | def test_an_order_waiting_on_the_pick_list_is_not_claimed(tmp_path, monkeypatch): |
| 1184 | """With auto_fulfill off the order is supposed to SIT at `confirmed` |
| 1185 | waiting for a person. Claiming it would take it off the very list it |
| 1186 | needs to be on.""" |
| 1187 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1188 | settings=(("shop.stock_location", "loc-shelf"), |
| 1189 | ("shop.customer_location", "loc-customer"), |
| 1190 | ("shop.auto_fulfill", "false"))) |
| 1191 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 1192 | order_id, payment = paid_order(data_dir) |
| 1193 | |
| 1194 | result = fulfil(payment) |
| 1195 | assert result["shipped"] is False |
| 1196 | assert "pick list" in result["note"] |
| 1197 | |
| 1198 | order = object_records.get_collection_record("orders", order_id, |
| 1199 | base_dir=data_dir) |
| 1200 | assert order["status"] == "confirmed" |
| 1201 | |
| 1202 | |
| 1203 | def test_an_already_confirmed_order_is_also_shipped_only_once(tmp_path, |
| 1204 | monkeypatch): |
| 1205 | """The case the draft->confirmed promote cannot cover, and the reason |
| 1206 | the claim exists as a second step. |
| 1207 | |
| 1208 | A deposit followed by a balance payment is the ordinary shape: the |
| 1209 | first payment confirms the order without settling the invoice, and the |
| 1210 | SECOND is the one that tips it to paid and ships. That second event |
| 1211 | finds the order already at `confirmed`, so the promote above is not |
| 1212 | reached and only the claim stands between two concurrent deliveries |
| 1213 | and two shipments. |
| 1214 | """ |
| 1215 | import threading |
| 1216 | |
| 1217 | data_dir = setup_env(tmp_path, monkeypatch, |
| 1218 | settings=(("shop.stock_location", "loc-shelf"), |
| 1219 | ("shop.customer_location", "loc-customer"))) |
| 1220 | with_shipping(tmp_path, monkeypatch, data_dir) |
| 1221 | order_id, payment = paid_order(data_dir) |
| 1222 | |
| 1223 | object_records.update_collection_record( |
| 1224 | "orders", order_id, {"status": "confirmed"}, base_dir=data_dir) |
| 1225 | |
| 1226 | out = [] |
| 1227 | threads = [threading.Thread(target=lambda: out.append(fulfil(payment))) |
| 1228 | for _ in range(2)] |
| 1229 | for thread in threads: |
| 1230 | thread.start() |
| 1231 | for thread in threads: |
| 1232 | thread.join() |
| 1233 | |
| 1234 | shipments = object_records.read_collection_records("shipments", |
| 1235 | base_dir=data_dir) |
| 1236 | lines = object_records.read_collection_records("shipment_lines", |
| 1237 | base_dir=data_dir) |
| 1238 | assert len(shipments) == 1, out |
| 1239 | assert sum(float(line["quantity"]) for line in lines) == 2.0 |
| 1240 | assert len([m for m in moves(data_dir) if m["reason"] == "sale"]) == 1 |