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_store_voice.py · 35.5 KB · 827 lines
| 1 | """Store voice: the shop finally answers the customer. |
| 2 | |
| 3 | Before this slice a shopper paid and heard nothing, then had nowhere to |
| 4 | look. Both halves of that silence were the same missing thing -- a |
| 5 | capability token on the ORDER -- and the properties worth holding here |
| 6 | are the ones that make such a token safe to hand to a stranger and the |
| 7 | ones that make an automatic email safe to send. |
| 8 | |
| 9 | On the token: it is minted where the shopper can actually be handed it |
| 10 | (the checkout response) AND durably by a reaction, because a link that |
| 11 | only exists on the happy path is a link the awkward cases never get. It |
| 12 | is never rewritten once it exists, because by then it is in somebody's |
| 13 | inbox. It resolves BY TOKEN ONLY, so a guessed order id opens nothing, |
| 14 | and every failure -- blank, wrong, unknown -- renders one identical |
| 15 | friendly 404 rather than an oracle telling somebody they were close. |
| 16 | |
| 17 | On the page: it speaks the customer's language. The orders enum is |
| 18 | warehouse vocabulary, and `partial` on a customer's screen reads as "part |
| 19 | of my money went missing". The tests below assert both directions -- that |
| 20 | the human words appear AND that the internal ones do not -- because a |
| 21 | mapping that is merely present is not the same as a mapping that is used. |
| 22 | |
| 23 | On the email: it is queued, never sent, and queued exactly once. The |
| 24 | change dispatcher promises at-least-once delivery, so the handler WILL |
| 25 | see the same order twice; a customer receiving two confirmations is a |
| 26 | support ticket, and receiving two refund notices is a phone call about |
| 27 | money. The replay tests are therefore the point of this file, not a |
| 28 | footnote to it. |
| 29 | """ |
| 30 | |
| 31 | import pathlib |
| 32 | import shutil |
| 33 | |
| 34 | from conftest import stage_collection |
| 35 | |
| 36 | import object_execution |
| 37 | import object_ids |
| 38 | import object_records |
| 39 | import python_object_runtime |
| 40 | |
| 41 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 42 | PACKAGES = REPO_ROOT / "packages" |
| 43 | ORDERS_OBJECTS = PACKAGES / "app-orders" / "objects" |
| 44 | SHOP_OBJECTS = PACKAGES / "app-shop" / "objects" |
| 45 | RETURNS_OBJECTS = PACKAGES / "app-returns" / "objects" |
| 46 | SHIPPING_OBJECTS = PACKAGES / "app-shipping" / "objects" |
| 47 | PAYMENTS_OBJECTS = PACKAGES / "app-payments" / "objects" |
| 48 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 49 | |
| 50 | TRACK_PREFIX = "/orders/track/" |
| 51 | |
| 52 | |
| 53 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 54 | """A data dir with every collection this slice touches, and ONE object |
| 55 | root holding every package's objects. |
| 56 | |
| 57 | The merged root is what an installed server actually looks like, and |
| 58 | it is the only way objects that call a sibling by id resolve the way |
| 59 | they will in production -- site_return_form hands everything to |
| 60 | action_authorize_return, and the store-voice objects read collections |
| 61 | owned by four other packages. |
| 62 | """ |
| 63 | data_dir = tmp_path / "data" |
| 64 | for pkg, name in (("app-orders", "orders"), ("app-orders", "order_lines"), |
| 65 | ("app-shop", "carts"), ("app-shop", "cart_items"), |
| 66 | ("app-catalog", "products"), ("app-catalog", "locations"), |
| 67 | ("app-catalog", "stock_moves"), |
| 68 | ("app-invoices", "invoices"), |
| 69 | ("app-invoices", "invoice_lines"), |
| 70 | ("app-shipping", "shipments"), |
| 71 | ("app-shipping", "shipment_lines"), |
| 72 | ("app-payments", "payments"), ("app-payments", "refunds"), |
| 73 | ("app-returns", "return_authorizations"), |
| 74 | ("app-email", "email_outbox")): |
| 75 | stage_collection(data_dir, pkg, name) |
| 76 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 77 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 78 | |
| 79 | objects_root = tmp_path / "objects" |
| 80 | for source in (ORDERS_OBJECTS, SHOP_OBJECTS, RETURNS_OBJECTS, |
| 81 | SHIPPING_OBJECTS, PAYMENTS_OBJECTS): |
| 82 | shutil.copytree(source, objects_root, dirs_exist_ok=True) |
| 83 | |
| 84 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 85 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root)) |
| 86 | return data_dir, objects_root |
| 87 | |
| 88 | |
| 89 | def run(objects_root, object_id, method, payload): |
| 90 | return object_execution.execute_object( |
| 91 | RUNTIME, |
| 92 | object_execution.ObjectExecutionRequest( |
| 93 | object_id, method=method, payload=payload), |
| 94 | roots=[objects_root]).result |
| 95 | |
| 96 | |
| 97 | # --- fixtures shaped like a real shop ---------------------------------------- |
| 98 | |
| 99 | def product(data_dir, product_id, name, cents=1200): |
| 100 | return object_records.create_collection_record( |
| 101 | "products", |
| 102 | {"id": product_id, "name": name, "sku": product_id.upper(), |
| 103 | "product_type": "physical", "price_cents": str(cents), |
| 104 | "currency": "USD", "is_active": "true", "owner_id": "shop"}, |
| 105 | base_dir=data_dir) |
| 106 | |
| 107 | |
| 108 | def location(data_dir, location_id="loc-shelf", name="Shelf", |
| 109 | kind="warehouse"): |
| 110 | return object_records.create_collection_record( |
| 111 | "locations", |
| 112 | {"id": location_id, "name": name, "location_type": kind, |
| 113 | "owner_id": "shop"}, |
| 114 | base_dir=data_dir) |
| 115 | |
| 116 | |
| 117 | def stock_in(data_dir, product_id, quantity, *, to="loc-shelf"): |
| 118 | """Goods on the shelf. Checkout refuses to sell what is not there, so |
| 119 | a store-voice test that never stocks anything is testing the oversell |
| 120 | gate by accident.""" |
| 121 | return object_records.create_collection_record( |
| 122 | "stock_moves", |
| 123 | {"id": object_ids.new_uuid4(), "product_id": product_id, |
| 124 | "to_location_id": to, "quantity": str(quantity), "reason": "purchase", |
| 125 | "occurred_at": "2026-06-01", "owner_id": "shop"}, |
| 126 | base_dir=data_dir) |
| 127 | |
| 128 | |
| 129 | def order(data_dir, order_id="ord-1", *, status="confirmed", number="SO-0001", |
| 130 | email="ada@example.test", **fields): |
| 131 | record = {"id": order_id, "doc_type": "sale", "number": number, |
| 132 | "customer_name": "Ada Lovelace", "customer_email": email, |
| 133 | "currency": "USD", "status": status, "order_date": "2026-07-01", |
| 134 | "subtotal_cents": "2400", "total_cents": "2400", |
| 135 | "owner_id": "shop"} |
| 136 | record.update({k: str(v) for k, v in fields.items()}) |
| 137 | # preserve_read_only because portal_token is schema read_only -- the |
| 138 | # same escape hatch every server-side writer of it uses. |
| 139 | return object_records.create_collection_record( |
| 140 | "orders", record, base_dir=data_dir, preserve_read_only=True) |
| 141 | |
| 142 | |
| 143 | def order_line(data_dir, line_id="line-1", *, order_id="ord-1", |
| 144 | description="Enamel Mug", quantity="2", cents=1200): |
| 145 | return object_records.create_collection_record( |
| 146 | "order_lines", |
| 147 | {"id": line_id, "order_id": order_id, |
| 148 | "description": description, "quantity": quantity, |
| 149 | "unit_price_cents": str(cents), |
| 150 | "line_total_cents": str(int(cents) * int(float(quantity))), |
| 151 | "owner_id": "shop"}, |
| 152 | base_dir=data_dir) |
| 153 | |
| 154 | |
| 155 | def invoice(data_dir, invoice_id="inv-1", *, order_id="ord-1", status="sent", |
| 156 | token="invoice-token-xyz"): |
| 157 | return object_records.create_collection_record( |
| 158 | "invoices", |
| 159 | {"id": invoice_id, "number": "SO-0001", "customer_name": "Ada Lovelace", |
| 160 | "customer_email": "ada@example.test", "currency": "USD", |
| 161 | "status": status, "issue_date": "2026-07-01", "due_date": "2026-07-15", |
| 162 | "total_cents": "2400", |
| 163 | "source_order_id": order_id, "portal_token": token, |
| 164 | "owner_id": "shop"}, |
| 165 | base_dir=data_dir, preserve_read_only=True) |
| 166 | |
| 167 | |
| 168 | def shipment(data_dir, shipment_id="shp-1", *, order_id="ord-1", |
| 169 | status="shipped", carrier="Royal Mail", |
| 170 | tracking="RM123456789GB"): |
| 171 | return object_records.create_collection_record( |
| 172 | "shipments", |
| 173 | {"id": shipment_id, "order_id": order_id, "direction": "outbound", |
| 174 | "status": status, "carrier": carrier, "tracking_number": tracking, |
| 175 | "shipped_on": "2026-07-03", "owner_id": "shop"}, |
| 176 | base_dir=data_dir) |
| 177 | |
| 178 | |
| 179 | def payment(data_dir, payment_id="pay-1", *, invoice_id="inv-1", cents=2400): |
| 180 | """The money that arrived. Only here because refunds.payment_id is a |
| 181 | validated relation -- a refund with no payment behind it is not a |
| 182 | thing this system will let you write, and rightly.""" |
| 183 | return object_records.create_collection_record( |
| 184 | "payments", |
| 185 | {"id": payment_id, "invoice_id": invoice_id, "amount_cents": str(cents), |
| 186 | "method": "card", "received_on": "2026-07-02", "status": "received", |
| 187 | "owner_id": "shop"}, |
| 188 | base_dir=data_dir) |
| 189 | |
| 190 | |
| 191 | def refund(data_dir, refund_id="ref-1", *, invoice_id="inv-1", cents=1200, |
| 192 | reason="Arrived damaged"): |
| 193 | """Written straight into the collection rather than through |
| 194 | hook_refunds: this file is about what the shop SAYS when a refund |
| 195 | exists, and app-payments' own tests already own the question of when |
| 196 | one may. The hook's stamp (invoice_id from the payment) is supplied |
| 197 | directly for the same reason.""" |
| 198 | return object_records.create_collection_record( |
| 199 | "refunds", |
| 200 | {"id": refund_id, "payment_id": "pay-1", "invoice_id": invoice_id, |
| 201 | "amount_cents": str(cents), "reason": reason, |
| 202 | "refunded_on": "2026-07-05", "owner_id": "shop"}, |
| 203 | base_dir=data_dir) |
| 204 | |
| 205 | |
| 206 | def fire(objects_root, object_id, collection, record_id, action="update"): |
| 207 | """One change event, shaped exactly as object_change_dispatch sends |
| 208 | them (raw verb in `action`, participle in `event`).""" |
| 209 | return run(objects_root, object_id, "EVENT", |
| 210 | {"event": f"{collection}.record.{action}d", |
| 211 | "collection": collection, "record_id": record_id, |
| 212 | "action": action}) |
| 213 | |
| 214 | |
| 215 | def orders_row(data_dir, order_id="ord-1"): |
| 216 | return object_records.get_collection_record("orders", order_id, |
| 217 | base_dir=data_dir) |
| 218 | |
| 219 | |
| 220 | def outbox(data_dir): |
| 221 | return object_records.read_collection_records("email_outbox", |
| 222 | base_dir=data_dir) |
| 223 | |
| 224 | |
| 225 | def track(objects_root, token): |
| 226 | return run(objects_root, "site_order_status", "GET", {"token": token}) |
| 227 | |
| 228 | |
| 229 | # --- 1. the token is minted where the shopper can be handed it --------------- |
| 230 | |
| 231 | def test_checkout_mints_the_orders_token_and_returns_the_link(tmp_path, monkeypatch): |
| 232 | """The shopper is standing there. A reaction handler runs post-commit |
| 233 | and cannot put anything in this response, so checkout mints the token |
| 234 | itself -- exactly as it already does for the invoice's pay link.""" |
| 235 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 236 | product(data_dir, "mug", "Enamel Mug", 1200) |
| 237 | location(data_dir) |
| 238 | stock_in(data_dir, "mug", 5) |
| 239 | run(objects_root, "action_cart", "POST", |
| 240 | {"session_token": "sess-1", "action": "add", "product_id": "mug", |
| 241 | "quantity": "2"}) |
| 242 | |
| 243 | result = run(objects_root, "action_checkout", "POST", |
| 244 | {"session_token": "sess-1", "customer_email": "ada@example.test", |
| 245 | "customer_name": "Ada Lovelace"}) |
| 246 | assert result["ok"] is True |
| 247 | assert result["track_path"].startswith(TRACK_PREFIX) |
| 248 | |
| 249 | token = result["track_path"][len(TRACK_PREFIX):] |
| 250 | assert len(token) >= 20 # a guessable token is not a token |
| 251 | stored = orders_row(data_dir, result["order_id"])["portal_token"] |
| 252 | assert stored == token |
| 253 | |
| 254 | # The pay link the shop already handed over is untouched: this slice |
| 255 | # rides alongside it, it does not replace it. |
| 256 | assert result["pay_path"].startswith("/pay/") |
| 257 | |
| 258 | |
| 259 | def test_a_retried_checkout_hands_back_the_same_tracking_link(tmp_path, monkeypatch): |
| 260 | """A double-clicked submit button must not mint a second door onto a |
| 261 | sale that already has one.""" |
| 262 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 263 | product(data_dir, "mug", "Enamel Mug", 1200) |
| 264 | location(data_dir) |
| 265 | stock_in(data_dir, "mug", 5) |
| 266 | run(objects_root, "action_cart", "POST", |
| 267 | {"session_token": "sess-1", "action": "add", "product_id": "mug"}) |
| 268 | first = run(objects_root, "action_checkout", "POST", |
| 269 | {"session_token": "sess-1", "customer_email": "ada@example.test"}) |
| 270 | |
| 271 | again = run(objects_root, "action_checkout", "POST", |
| 272 | {"session_token": "sess-1", "customer_email": "ada@example.test"}) |
| 273 | assert again["duplicate"] is True |
| 274 | assert again["track_path"] == first["track_path"] |
| 275 | |
| 276 | |
| 277 | def test_the_reaction_mints_for_an_order_that_lacks_one(tmp_path, monkeypatch): |
| 278 | """The durable path: an order raised anywhere but the web checkout -- |
| 279 | by hand, by an importer -- still gets its door.""" |
| 280 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 281 | order(data_dir, status="confirmed") |
| 282 | assert orders_row(data_dir)["portal_token"] == "" |
| 283 | |
| 284 | result = fire(objects_root, "system_order_portal_link", "orders", "ord-1") |
| 285 | assert result["minted"] is True |
| 286 | assert orders_row(data_dir)["portal_token"] |
| 287 | |
| 288 | |
| 289 | def test_the_reaction_skips_an_order_that_already_has_one(tmp_path, monkeypatch): |
| 290 | """Skipped, not rotated. The dispatcher replays by design, and by the |
| 291 | time a second event arrives the link is usually already in a |
| 292 | customer's inbox -- rewriting it would break a link the shop sent.""" |
| 293 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 294 | order(data_dir, status="confirmed", portal_token="already-minted-token") |
| 295 | |
| 296 | result = fire(objects_root, "system_order_portal_link", "orders", "ord-1") |
| 297 | assert result.get("minted") is not True |
| 298 | assert result["skipped"] == "already has a link" |
| 299 | assert orders_row(data_dir)["portal_token"] == "already-minted-token" |
| 300 | |
| 301 | |
| 302 | def test_a_draft_order_gets_no_door(tmp_path, monkeypatch): |
| 303 | """A draft is not a commitment. A tracking URL for something nobody |
| 304 | has paid for is a link waiting to be forwarded.""" |
| 305 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 306 | order(data_dir, status="draft") |
| 307 | |
| 308 | result = fire(objects_root, "system_order_portal_link", "orders", "ord-1") |
| 309 | assert result["skipped"] == "still a draft" |
| 310 | assert orders_row(data_dir)["portal_token"] == "" |
| 311 | |
| 312 | |
| 313 | def test_portal_token_is_read_only_and_off_every_generic_surface(): |
| 314 | """A capability URL a client could choose is not a capability, and a |
| 315 | bearer token that turns up in a list response has already leaked.""" |
| 316 | import json |
| 317 | schema = json.loads( |
| 318 | (PACKAGES / "app-orders" / "schemas" / "orders.json").read_text()) |
| 319 | by_name = {f["name"]: f for f in schema["fields"]} |
| 320 | assert by_name["portal_token"]["read_only"] is True |
| 321 | assert "portal_token" not in schema["forms"]["default"]["fields"] |
| 322 | assert "portal_token" not in schema["views"]["list_fields"] |
| 323 | assert "portal_token" not in schema["search"]["fields"] |
| 324 | |
| 325 | |
| 326 | # --- 2. the tracking page ---------------------------------------------------- |
| 327 | |
| 328 | def test_the_tracking_page_renders_the_customers_own_receipt(tmp_path, monkeypatch): |
| 329 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 330 | order(data_dir, status="confirmed", portal_token="track-me") |
| 331 | order_line(data_dir) |
| 332 | |
| 333 | page = track(objects_root, "track-me") |
| 334 | assert page.get("status", 200) == 200 |
| 335 | body = page["body"] |
| 336 | assert "SO-0001" in body # order number |
| 337 | assert "2026-07-01" in body # order date |
| 338 | assert "Enamel Mug" in body # what was bought |
| 339 | assert "24.00 USD" in body # and what it cost -- this IS |
| 340 | assert "12.00 USD" in body # the receipt, unlike the slip |
| 341 | |
| 342 | |
| 343 | def test_an_unknown_token_is_a_friendly_404_that_leaks_nothing(tmp_path, monkeypatch): |
| 344 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 345 | order(data_dir, status="confirmed", portal_token="track-me") |
| 346 | order_line(data_dir) |
| 347 | |
| 348 | page = track(objects_root, "not-the-right-token") |
| 349 | assert page["status"] == 404 |
| 350 | body = page["body"] |
| 351 | assert "Traceback" not in body |
| 352 | # Never the real order, never a 403 (which would confirm the token |
| 353 | # namespace is worth attacking), never a hint that another value works. |
| 354 | assert "SO-0001" not in body and "Enamel Mug" not in body |
| 355 | assert "403" not in str(page) |
| 356 | assert "track-me" not in body |
| 357 | |
| 358 | |
| 359 | def test_a_blank_token_never_matches_an_order_that_has_none(tmp_path, monkeypatch): |
| 360 | """Without the guard, "no link minted yet" would be an open door onto |
| 361 | whichever unlinked order happens to be first in the file.""" |
| 362 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 363 | order(data_dir, status="confirmed") # portal_token left blank |
| 364 | |
| 365 | assert track(objects_root, "")["status"] == 404 |
| 366 | |
| 367 | |
| 368 | def test_an_order_id_opens_nothing(tmp_path, monkeypatch): |
| 369 | """There is no enumeration path from a guessed id: the page resolves |
| 370 | by token and only by token.""" |
| 371 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 372 | order(data_dir, status="confirmed", portal_token="track-me") |
| 373 | |
| 374 | assert track(objects_root, "ord-1")["status"] == 404 |
| 375 | |
| 376 | |
| 377 | STATUS_WORDS = (("confirmed", "Order received"), |
| 378 | ("processing", "Being prepared"), |
| 379 | ("partial", "Being prepared"), |
| 380 | ("shipped", "On its way"), |
| 381 | ("delivered", "Delivered"), |
| 382 | ("cancelled", "Cancelled")) |
| 383 | |
| 384 | |
| 385 | def test_the_status_is_shown_in_customer_words_not_warehouse_words(tmp_path, monkeypatch): |
| 386 | """Both directions. A mapping that is present but unused is not a |
| 387 | mapping, and `partial` on a customer's screen reads as "part of my |
| 388 | money went missing". |
| 389 | |
| 390 | One order per status rather than one order walked through them: the |
| 391 | schema's transition table guards the moves, and this test is about |
| 392 | what a customer READS, not about which moves are legal. |
| 393 | """ |
| 394 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 395 | for index, (raw, _customer) in enumerate(STATUS_WORDS): |
| 396 | order(data_dir, f"ord-{index}", status=raw, number=f"SO-{index}", |
| 397 | portal_token=f"token-{index}") |
| 398 | |
| 399 | for index, (raw, customer) in enumerate(STATUS_WORDS): |
| 400 | body = track(objects_root, f"token-{index}")["body"] |
| 401 | assert customer in body, f"{raw} should read as {customer!r}" |
| 402 | # The warehouse-only words, none of which is ordinary English a |
| 403 | # customer sentence would use by accident. ("received" is excluded |
| 404 | # only because "Order received" legitimately contains it.) |
| 405 | for internal in ("partial", "processing", "confirmed", "draft"): |
| 406 | assert internal not in body, ( |
| 407 | f"internal word {internal!r} reached the customer on a " |
| 408 | f"{raw} order") |
| 409 | |
| 410 | |
| 411 | def test_the_tracking_number_appears_when_a_shipment_carries_one(tmp_path, monkeypatch): |
| 412 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 413 | order(data_dir, status="shipped", portal_token="track-me") |
| 414 | order_line(data_dir) |
| 415 | shipment(data_dir) |
| 416 | |
| 417 | body = track(objects_root, "track-me")["body"] |
| 418 | assert "Royal Mail" in body |
| 419 | assert "RM123456789GB" in body |
| 420 | |
| 421 | |
| 422 | def test_a_shipment_with_no_tracking_says_nothing_rather_than_nothing_useful( |
| 423 | tmp_path, monkeypatch): |
| 424 | """"Tracking: (none)" tells a worried customer only that the shop has |
| 425 | a field for it.""" |
| 426 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 427 | order(data_dir, status="shipped", portal_token="track-me") |
| 428 | shipment(data_dir, carrier="", tracking="") |
| 429 | |
| 430 | body = track(objects_root, "track-me")["body"] |
| 431 | assert "Your parcel" not in body |
| 432 | assert "On its way" in body # the status still speaks |
| 433 | |
| 434 | |
| 435 | def test_the_pay_link_shows_while_money_is_owed_and_not_after(tmp_path, monkeypatch): |
| 436 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 437 | order(data_dir, status="confirmed", portal_token="track-me", |
| 438 | invoice_id="inv-1") |
| 439 | invoice(data_dir, status="sent") |
| 440 | assert "/pay/invoice-token-xyz" in track(objects_root, "track-me")["body"] |
| 441 | |
| 442 | object_records.update_collection_record( |
| 443 | "invoices", "inv-1", {"status": "paid"}, base_dir=data_dir, |
| 444 | actor="test") |
| 445 | # Offering "pay now" on a settled order is how a shop gets paid twice |
| 446 | # and spends a fortnight refunding it. |
| 447 | assert "/pay/invoice-token-xyz" not in track(objects_root, "track-me")["body"] |
| 448 | |
| 449 | |
| 450 | def test_the_return_link_appears_once_something_has_left_the_building( |
| 451 | tmp_path, monkeypatch): |
| 452 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 453 | order(data_dir, status="confirmed", portal_token="track-me") |
| 454 | assert "/returns/ord-1" not in track(objects_root, "track-me")["body"] |
| 455 | |
| 456 | object_records.update_collection_record( |
| 457 | "orders", "ord-1", {"status": "shipped"}, base_dir=data_dir, |
| 458 | actor="test") |
| 459 | body = track(objects_root, "track-me")["body"] |
| 460 | # Carrying the token, because the guest it is for has no account. |
| 461 | assert "/returns/ord-1?token=track-me" in body |
| 462 | |
| 463 | |
| 464 | def test_the_tracking_page_is_not_a_door_into_the_app(tmp_path, monkeypatch): |
| 465 | """Handed to a stranger's inbox: it must not be one click from |
| 466 | somebody else's order or from a sign-in wall.""" |
| 467 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 468 | order(data_dir, status="confirmed", portal_token="track-me") |
| 469 | |
| 470 | body = track(objects_root, "track-me")["body"] |
| 471 | assert "/nav" not in body |
| 472 | assert "/login" not in body |
| 473 | assert 'href="/orders"' not in body |
| 474 | |
| 475 | |
| 476 | # --- 3. the three emails ----------------------------------------------------- |
| 477 | |
| 478 | def kinds(data_dir): |
| 479 | return sorted(row["subject"] for row in outbox(data_dir)) |
| 480 | |
| 481 | |
| 482 | def test_confirmation_queues_once_and_a_replay_queues_nothing(tmp_path, monkeypatch): |
| 483 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, |
| 484 | settings=(("portal.base_url", |
| 485 | "https://shop.example.test"),)) |
| 486 | order(data_dir, status="confirmed", portal_token="track-me", |
| 487 | invoice_id="inv-1") |
| 488 | order_line(data_dir) |
| 489 | invoice(data_dir, status="sent") |
| 490 | |
| 491 | result = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 492 | assert result["queued"] == ["confirmed"] |
| 493 | mails = outbox(data_dir) |
| 494 | assert len(mails) == 1 |
| 495 | mail = mails[0] |
| 496 | assert mail["to"] == "ada@example.test" |
| 497 | assert "SO-0001" in mail["subject"] |
| 498 | assert "Enamel Mug" in mail["text_body"] |
| 499 | assert "24.00 USD" in mail["text_body"] |
| 500 | assert "https://shop.example.test/orders/track/track-me" in mail["text_body"] |
| 501 | assert "https://shop.example.test/pay/invoice-token-xyz" in mail["text_body"] |
| 502 | assert mail["status"] == "queued" |
| 503 | |
| 504 | # The dispatcher is at-least-once by design. Twice is a support ticket. |
| 505 | replay = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 506 | assert replay["queued"] == [] |
| 507 | assert replay["skipped_already_sent"] == ["confirmed"] |
| 508 | assert len(outbox(data_dir)) == 1 |
| 509 | |
| 510 | |
| 511 | def test_the_shipped_note_carries_carrier_and_tracking_and_queues_once( |
| 512 | tmp_path, monkeypatch): |
| 513 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, |
| 514 | settings=(("portal.base_url", |
| 515 | "https://shop.example.test"),)) |
| 516 | order(data_dir, status="shipped", portal_token="track-me") |
| 517 | order_line(data_dir) |
| 518 | shipment(data_dir) |
| 519 | |
| 520 | result = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 521 | # Reaching `shipped` also means the confirmation was owed and never |
| 522 | # sent -- the zero-touch shop confirms and ships in one burst, and a |
| 523 | # buyer who never heard from the shop because their order moved too |
| 524 | # fast is exactly the silence this slice ends. |
| 525 | assert sorted(result["queued"]) == ["confirmed", "shipped"] |
| 526 | |
| 527 | shipped = next(row for row in outbox(data_dir) |
| 528 | if "has shipped" in row["subject"]) |
| 529 | assert "Royal Mail" in shipped["text_body"] |
| 530 | assert "RM123456789GB" in shipped["text_body"] |
| 531 | assert "https://shop.example.test/orders/track/track-me" in shipped["text_body"] |
| 532 | |
| 533 | replay = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 534 | assert replay["queued"] == [] |
| 535 | assert len(outbox(data_dir)) == 2 |
| 536 | |
| 537 | |
| 538 | def test_the_refund_note_names_the_amount_and_the_order_and_queues_once( |
| 539 | tmp_path, monkeypatch): |
| 540 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 541 | order(data_dir, status="delivered", portal_token="track-me", |
| 542 | invoice_id="inv-1") |
| 543 | invoice(data_dir, status="paid") |
| 544 | payment(data_dir) |
| 545 | refund(data_dir, cents=1200) |
| 546 | |
| 547 | result = fire(objects_root, "system_order_email", "refunds", "ref-1", |
| 548 | action="create") |
| 549 | assert result["queued"] == ["refunded"] |
| 550 | mail = outbox(data_dir)[0] |
| 551 | assert mail["to"] == "ada@example.test" |
| 552 | assert "SO-0001" in mail["subject"] |
| 553 | assert "12.00 USD" in mail["text_body"] |
| 554 | assert "SO-0001" in mail["text_body"] |
| 555 | |
| 556 | replay = fire(objects_root, "system_order_email", "refunds", "ref-1", |
| 557 | action="create") |
| 558 | assert replay["queued"] == [] |
| 559 | assert len(outbox(data_dir)) == 1 |
| 560 | |
| 561 | |
| 562 | def test_a_second_refund_on_one_order_gets_its_own_message(tmp_path, monkeypatch): |
| 563 | """The marker carries the refund's id, not just the order's: two |
| 564 | refunds are two facts, and a customer told about the first but not the |
| 565 | second is a phone call about money.""" |
| 566 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 567 | order(data_dir, status="delivered", portal_token="track-me", |
| 568 | invoice_id="inv-1") |
| 569 | invoice(data_dir, status="paid") |
| 570 | payment(data_dir) |
| 571 | refund(data_dir, "ref-1", cents=1200) |
| 572 | refund(data_dir, "ref-2", cents=600) |
| 573 | |
| 574 | fire(objects_root, "system_order_email", "refunds", "ref-1", action="create") |
| 575 | fire(objects_root, "system_order_email", "refunds", "ref-2", action="create") |
| 576 | bodies = [row["text_body"] for row in outbox(data_dir)] |
| 577 | assert len(bodies) == 2 |
| 578 | assert any("12.00 USD" in body for body in bodies) |
| 579 | assert any("6.00 USD" in body for body in bodies) |
| 580 | |
| 581 | |
| 582 | def test_the_idempotency_marker_lives_on_the_outbox_row(tmp_path, monkeypatch): |
| 583 | """The claim being recorded is "this message exists", so it is |
| 584 | recorded on the message. A stamped flag elsewhere is a second record |
| 585 | that can disagree with the first.""" |
| 586 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 587 | order(data_dir, status="confirmed", portal_token="track-me") |
| 588 | |
| 589 | fire(objects_root, "system_order_email", "orders", "ord-1") |
| 590 | assert outbox(data_dir)[0]["source_object_id"] == ( |
| 591 | "system_order_email:orders/ord-1:confirmed") |
| 592 | |
| 593 | |
| 594 | def test_an_order_with_no_customer_email_is_skipped_with_a_reason( |
| 595 | tmp_path, monkeypatch): |
| 596 | """Never a crash, never a message addressed to "". An operator reading |
| 597 | the reason knows exactly what to add; silence looks like a working |
| 598 | mailer.""" |
| 599 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 600 | order(data_dir, status="confirmed", portal_token="track-me", email="") |
| 601 | |
| 602 | result = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 603 | assert result["ok"] is True |
| 604 | assert result["skipped"] == "no customer_email on the order" |
| 605 | assert outbox(data_dir) == [] |
| 606 | |
| 607 | |
| 608 | def test_no_base_url_sends_the_words_without_a_dead_link(tmp_path, monkeypatch): |
| 609 | """A relative URL in an email is a link that does nothing in every |
| 610 | mail client there is. Honest text beats a guaranteed 404.""" |
| 611 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) # no base_url |
| 612 | order(data_dir, status="confirmed", portal_token="track-me") |
| 613 | |
| 614 | fire(objects_root, "system_order_email", "orders", "ord-1") |
| 615 | body = outbox(data_dir)[0]["text_body"] |
| 616 | assert "http" not in body |
| 617 | assert "/orders/track/" not in body |
| 618 | assert "SO-0001" in body # the message still says something |
| 619 | |
| 620 | |
| 621 | def test_no_smtp_configured_still_queues_and_does_not_error(tmp_path, monkeypatch): |
| 622 | """The daemon already logs "queuing only" when there is no transport. |
| 623 | The shop's voice is recorded even where it cannot yet be heard.""" |
| 624 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 625 | monkeypatch.delenv("DBBASIC_SMTP_MODE", raising=False) |
| 626 | order(data_dir, status="confirmed", portal_token="track-me") |
| 627 | |
| 628 | result = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 629 | assert result["ok"] is True |
| 630 | assert outbox(data_dir)[0]["status"] == "queued" |
| 631 | |
| 632 | |
| 633 | def test_a_draft_order_says_nothing_at_all(tmp_path, monkeypatch): |
| 634 | """Nobody has paid, nothing has been promised, and an email about a |
| 635 | draft is a message about something that may never exist.""" |
| 636 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 637 | order(data_dir, status="draft", portal_token="track-me") |
| 638 | |
| 639 | result = fire(objects_root, "system_order_email", "orders", "ord-1") |
| 640 | assert result["queued"] == [] |
| 641 | assert outbox(data_dir) == [] |
| 642 | |
| 643 | |
| 644 | # --- 4. the return a guest can finally start --------------------------------- |
| 645 | |
| 646 | def return_form(objects_root, *, order_id="ord-1", token=None, user_id=None, |
| 647 | method="GET", **fields): |
| 648 | payload = {"order_id": order_id} |
| 649 | if token is not None: |
| 650 | payload["token"] = token |
| 651 | if user_id: |
| 652 | payload["_identity"] = {"user_id": user_id} |
| 653 | if fields: |
| 654 | payload["_form"] = fields |
| 655 | return run(objects_root, "site_return_form", method, payload) |
| 656 | |
| 657 | |
| 658 | def shop_that_shipped(data_dir): |
| 659 | """An order whose goods actually left, so there is something to send |
| 660 | back -- the return form folds shipped-minus-claimed live.""" |
| 661 | product(data_dir, "mug", "Enamel Mug", 1200) |
| 662 | order(data_dir, status="shipped", portal_token="track-me") |
| 663 | order_line(data_dir, quantity="2") |
| 664 | shipment(data_dir) |
| 665 | object_records.create_collection_record( |
| 666 | "shipment_lines", |
| 667 | {"id": "sl-1", "shipment_id": "shp-1", "order_line_id": "line-1", |
| 668 | "product_id": "mug", "quantity": "2", "owner_id": "shop"}, |
| 669 | base_dir=data_dir) |
| 670 | |
| 671 | |
| 672 | def test_a_guest_with_the_order_token_can_open_the_return_form(tmp_path, monkeypatch): |
| 673 | """The whole point. A guest checkout is the default sale here, so a |
| 674 | returns flow that requires an account is a returns flow nobody can |
| 675 | use.""" |
| 676 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 677 | shop_that_shipped(data_dir) |
| 678 | |
| 679 | body = return_form(objects_root, token="track-me")["body"] |
| 680 | assert "Enamel Mug" in body |
| 681 | assert 'name="qty_line-1"' in body |
| 682 | # The token rides through the POST, or the submit button would bounce |
| 683 | # the very visitor the GET just let in. |
| 684 | assert 'name="token" value="track-me"' in body |
| 685 | |
| 686 | |
| 687 | def test_a_guest_with_a_wrong_token_is_refused_without_being_told_why( |
| 688 | tmp_path, monkeypatch): |
| 689 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 690 | shop_that_shipped(data_dir) |
| 691 | |
| 692 | page = return_form(objects_root, token="wrong-token") |
| 693 | body = page["body"] |
| 694 | assert "Enamel Mug" not in body |
| 695 | assert "tracking link" in body |
| 696 | assert page.get("status", 200) == 200 # never a 404 that says "close" |
| 697 | |
| 698 | # A real order with a wrong token and an order that does not exist are |
| 699 | # indistinguishable, so a guessed id never confirms itself. Only the |
| 700 | # sign-in link's `next=` differs, because it echoes the URL asked for. |
| 701 | unknown = return_form(objects_root, order_id="no-such-order", |
| 702 | token="wrong-token") |
| 703 | assert unknown.get("status", 200) == 200 |
| 704 | assert (unknown["body"].replace("no-such-order", "ord-1") == body) |
| 705 | |
| 706 | |
| 707 | def test_a_guest_token_for_another_order_opens_nothing(tmp_path, monkeypatch): |
| 708 | """The token is checked against THIS order, not against any order.""" |
| 709 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 710 | shop_that_shipped(data_dir) |
| 711 | order(data_dir, "ord-2", status="shipped", number="SO-0002", |
| 712 | portal_token="someone-elses-token") |
| 713 | |
| 714 | body = return_form(objects_root, order_id="ord-1", |
| 715 | token="someone-elses-token")["body"] |
| 716 | assert "Enamel Mug" not in body |
| 717 | |
| 718 | |
| 719 | def test_a_guest_can_actually_submit_the_return(tmp_path, monkeypatch): |
| 720 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 721 | shop_that_shipped(data_dir) |
| 722 | |
| 723 | body = return_form(objects_root, token="track-me", method="POST", |
| 724 | **{"reason": "damaged", "qty_line-1": "1"})["body"] |
| 725 | assert "authorized" in body |
| 726 | rmas = object_records.read_collection_records("return_authorizations", |
| 727 | base_dir=data_dir) |
| 728 | assert len(rmas) == 1 |
| 729 | assert rmas[0]["order_id"] == "ord-1" |
| 730 | |
| 731 | |
| 732 | def test_the_signed_in_path_still_works(tmp_path, monkeypatch): |
| 733 | """Staff raise returns at the counter the way they always have; the |
| 734 | token is an addition, not a replacement.""" |
| 735 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 736 | shop_that_shipped(data_dir) |
| 737 | |
| 738 | body = return_form(objects_root, user_id="shop")["body"] |
| 739 | assert "Enamel Mug" in body |
| 740 | assert 'name="qty_line-1"' in body |
| 741 | # No token was used, so none is carried -- a signed-in session does |
| 742 | # not need one and putting one in the HTML would leak it to a shared |
| 743 | # screen. |
| 744 | assert 'name="token"' not in body |
| 745 | |
| 746 | |
| 747 | def test_the_tracking_pages_return_link_actually_opens_the_form( |
| 748 | tmp_path, monkeypatch): |
| 749 | """End to end, because a link that renders and does not work is the |
| 750 | exact failure this slice exists to remove.""" |
| 751 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 752 | shop_that_shipped(data_dir) |
| 753 | |
| 754 | page = track(objects_root, "track-me")["body"] |
| 755 | assert "/returns/ord-1?token=track-me" in page |
| 756 | |
| 757 | href = "/returns/ord-1?token=track-me" |
| 758 | order_id, query = href[len("/returns/"):].split("?", 1) |
| 759 | token = query.split("=", 1)[1] |
| 760 | body = return_form(objects_root, order_id=order_id, token=token)["body"] |
| 761 | assert "Enamel Mug" in body |
| 762 | |
| 763 | |
| 764 | # --- 5. the package says what it ships --------------------------------------- |
| 765 | |
| 766 | def _rows(package_id, collection): |
| 767 | import csv |
| 768 | path = PACKAGES / package_id / "seed" / f"{collection}.tsv" |
| 769 | with path.open(newline="", encoding="utf-8") as handle: |
| 770 | return list(csv.DictReader(handle, delimiter="\t")) |
| 771 | |
| 772 | |
| 773 | def test_the_tracking_route_is_seeded_and_cannot_shadow_the_order_permalink(): |
| 774 | """Three segments against the permalink's two, so they can never match |
| 775 | the same path -- but the priority is lower anyway, because a route |
| 776 | named `track` sitting where an order id goes is exactly the collision |
| 777 | worth being explicit about.""" |
| 778 | routes = {row["pattern"]: row for row in _rows("app-orders", "site_routes")} |
| 779 | track_route = routes["/orders/track/{token}"] |
| 780 | assert track_route["object_id"] == "site_order_status" |
| 781 | assert int(track_route["priority"]) < int(routes["/orders/{order_id}"]["priority"]) |
| 782 | |
| 783 | |
| 784 | def test_the_tracking_page_is_public_and_the_orders_collection_is_not(): |
| 785 | """Public EXECUTE on the page object, never public READ on the |
| 786 | collection -- the same split app-invoices uses for its portal.""" |
| 787 | import json |
| 788 | import object_permissions |
| 789 | payload = json.loads( |
| 790 | (PACKAGES / "app-orders" / "permissions" / "rules.json").read_text()) |
| 791 | policy = object_permissions.policy_from_dict( |
| 792 | {"access_mode": "role_based", "rules": payload["rules"]}) |
| 793 | |
| 794 | page = object_permissions.check_permission( |
| 795 | None, object_permissions.EXECUTE, policy=policy, |
| 796 | object_id="site_order_status") |
| 797 | assert page.allowed is True |
| 798 | |
| 799 | collection = object_permissions.check_permission( |
| 800 | None, object_permissions.READ, policy=policy, collection="orders", |
| 801 | record={"owner_id": "shop", "portal_token": "track-me"}) |
| 802 | assert collection.allowed is False |
| 803 | |
| 804 | |
| 805 | def test_the_return_form_is_public_now_because_a_guest_shop_needs_it_to_be(): |
| 806 | import json |
| 807 | import object_permissions |
| 808 | payload = json.loads( |
| 809 | (PACKAGES / "app-returns" / "permissions" / "rules.json").read_text()) |
| 810 | policy = object_permissions.policy_from_dict( |
| 811 | {"access_mode": "role_based", "rules": payload["rules"]}) |
| 812 | |
| 813 | decision = object_permissions.check_permission( |
| 814 | None, object_permissions.EXECUTE, policy=policy, |
| 815 | object_id="site_return_form") |
| 816 | assert decision.allowed is True |
| 817 | |
| 818 | |
| 819 | def test_an_order_with_no_readable_lines_still_shows_the_total(tmp_path, monkeypatch): |
| 820 | """A "What you ordered" heading over an empty space reads as "we have |
| 821 | lost your order". The one number the customer cares about survives.""" |
| 822 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 823 | order(data_dir, status="confirmed", portal_token="track-me") # no lines |
| 824 | |
| 825 | body = track(objects_root, "track-me")["body"] |
| 826 | assert "24.00 USD" in body |
| 827 | assert "Total paid" in body |