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_promotions.py · 33.8 KB · 748 lines
| 1 | """Promotions, gift cards and store credit: the money that comes OFF a |
| 2 | sale, and the money that PAYS for one. |
| 3 | |
| 4 | Two claims carry this file, and they are different claims about |
| 5 | different kinds of thing. |
| 6 | |
| 7 | A DISCOUNT IS A PRICE. It changes what the goods cost, so it comes off |
| 8 | the taxable base before tax is computed -- what every jurisdiction that |
| 9 | levies a sales or value-added tax actually requires -- it lands on the |
| 10 | invoice as a LINE so the total stays the sum of its own lines, and its |
| 11 | terms are STAMPED on the redemption at use so that editing the promotion |
| 12 | next month cannot restate what somebody already got. |
| 13 | |
| 14 | A GIFT CARD IS TENDER. It is money the customer already gave this shop, |
| 15 | so it changes no price and no taxable base; it goes through the wallet |
| 16 | gate that already exists (hook_wallet_entries, which sums the entries |
| 17 | rather than trusting the rollup), it cannot overdraw, and -- the property |
| 18 | most easily broken by a refactor -- a PREVIEW SPENDS NOTHING. |
| 19 | """ |
| 20 | |
| 21 | import pathlib |
| 22 | import shutil |
| 23 | |
| 24 | import pytest |
| 25 | from conftest import stage_collection |
| 26 | |
| 27 | import object_cart |
| 28 | import object_execution |
| 29 | import object_ids |
| 30 | import object_promotions |
| 31 | import object_records |
| 32 | import python_object_runtime |
| 33 | |
| 34 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 35 | PACKAGES = REPO_ROOT / "packages" |
| 36 | SHOP_OBJECTS = PACKAGES / "app-shop" / "objects" |
| 37 | BILLING_OBJECTS = PACKAGES / "app-billing" / "objects" |
| 38 | PROMO_OBJECTS = PACKAGES / "app-promotions" / "objects" |
| 39 | RUNTIME = python_object_runtime.PythonObjectRuntime() |
| 40 | |
| 41 | TOKEN = "sess-promo" |
| 42 | TODAY = "2026-06-15" |
| 43 | |
| 44 | |
| 45 | # --- the pure fold, with no data directory in sight --------------------------- |
| 46 | |
| 47 | def promo(**fields): |
| 48 | row = {"id": "pr1", "code": "SPRING20", "kind": "percent", "value": "2000", |
| 49 | "is_active": "true", "stacking": "never"} |
| 50 | row.update({k: str(v) for k, v in fields.items()}) |
| 51 | return row |
| 52 | |
| 53 | |
| 54 | def test_a_percentage_comes_off_before_the_tax_is_computed(): |
| 55 | """Not a preference -- tax is owed on the consideration, and a |
| 56 | seller's own price reduction reduces it. Charging tax on the |
| 57 | pre-discount price collects money the shop then remits on revenue it |
| 58 | never earned, which is the kind of systematic error an audit finds by |
| 59 | multiplying one rate by one column.""" |
| 60 | items = [{"id": "a", "quantity": "1", "unit_price_cents": "10000"}] |
| 61 | folded = object_cart.checkout_totals(items, tax_rate_bps=1000, |
| 62 | discount_cents=2000) |
| 63 | assert folded["subtotal_cents"] == 10000 |
| 64 | assert folded["discount_cents"] == 2000 |
| 65 | assert folded["taxable_cents"] == 8000 |
| 66 | assert folded["tax_cents"] == 800 # 10% of 8000, not of 10000 |
| 67 | assert folded["total_cents"] == 8800 |
| 68 | |
| 69 | undiscounted = object_cart.checkout_totals(items, tax_rate_bps=1000) |
| 70 | assert undiscounted["tax_cents"] == 1000 # and the shop would keep 200 |
| 71 | |
| 72 | |
| 73 | def test_the_discount_is_rounded_once_over_the_whole_basket(): |
| 74 | """Rounded per line, the cents of error accumulate into a number no |
| 75 | customer can reconcile against the percentage on their receipt.""" |
| 76 | # 15% of 333 is 49.95 -- three separately rounded lines come to 150, |
| 77 | # the single rounding to 150 as well, but the base matters: 15% of 999 |
| 78 | # is 149.85 -> 150, and per-line 50+50+50 = 150 only by luck. The |
| 79 | # honest check is that the fold rounds the WHOLE base once. |
| 80 | assert object_promotions.discount_for(999, 0, promo(value=1500)) == 150 |
| 81 | assert object_promotions.discount_for(1099, 0, promo(value=825)) == 91 |
| 82 | |
| 83 | |
| 84 | def test_a_fixed_discount_bigger_than_the_basket_cannot_make_a_negative_total(): |
| 85 | """A shop does not owe money to somebody for shopping, and a negative |
| 86 | total would propagate into an invoice, a payment and eventually a |
| 87 | refund of money nobody paid.""" |
| 88 | big = promo(kind="fixed", value=5000) |
| 89 | assert object_promotions.discount_for(3000, 500, big) == 3000 # clamped |
| 90 | |
| 91 | folded = object_cart.checkout_totals( |
| 92 | [{"id": "a", "quantity": "1", "unit_price_cents": "3000"}], |
| 93 | tax_rate_bps=1000, shipping_flat_cents=500, discount_cents=5000) |
| 94 | assert folded["discount_cents"] == 3000 |
| 95 | assert folded["taxable_cents"] == 0 |
| 96 | assert folded["tax_cents"] == 0 |
| 97 | assert folded["total_cents"] == 500 # the postage, and no less |
| 98 | assert folded["total_cents"] >= 0 |
| 99 | |
| 100 | |
| 101 | def test_free_shipping_comes_off_the_postage_and_its_tax_with_it(): |
| 102 | """Where a jurisdiction taxes delivery, free postage must remove that |
| 103 | tax too -- otherwise the shop charges tax on a charge it waived.""" |
| 104 | items = [{"id": "a", "quantity": "1", "unit_price_cents": "5000"}] |
| 105 | post = promo(kind="free_shipping", value=0) |
| 106 | assert object_promotions.applies_to(post) == "shipping" |
| 107 | assert object_promotions.discount_for(5000, 700, post) == 700 |
| 108 | |
| 109 | folded = object_cart.checkout_totals( |
| 110 | items, tax_rate_bps=1000, tax_shipping=True, shipping_flat_cents=700, |
| 111 | discount_cents=700, discount_on="shipping") |
| 112 | assert folded["discount_cents"] == 700 |
| 113 | assert folded["taxable_cents"] == 5000 # goods only; postage waived |
| 114 | assert folded["tax_cents"] == 500 |
| 115 | assert folded["total_cents"] == 5500 |
| 116 | |
| 117 | |
| 118 | def test_every_blocker_is_reported_together_and_never_just_the_first(): |
| 119 | """A shopper told their code expired, who finds another and is then |
| 120 | told the basket is too small, is a shopper who has left.""" |
| 121 | exhausted = promo(id="pr9", code="DEAD", is_active="false", |
| 122 | starts_on="2026-07-01", ends_on="2026-05-01", |
| 123 | minimum_spend_cents=10000, max_redemptions=1, |
| 124 | per_customer_limit=1) |
| 125 | redemptions = [{"promotion_id": "pr9", "customer_email": "Ada@Example.com"}] |
| 126 | reasons = object_promotions.blockers( |
| 127 | exhausted, 500, "ada@example.com", redemptions, on_date=TODAY, |
| 128 | code="DEAD") |
| 129 | joined = " ".join(reasons) |
| 130 | assert len(reasons) == 6, reasons |
| 131 | assert "not active" in joined |
| 132 | assert "does not start until 2026-07-01" in joined |
| 133 | assert "ended on 2026-05-01" in joined |
| 134 | assert "at least 100.00" in joined and "this one is 5.00" in joined |
| 135 | assert "used 1 times and its limit is 1" in joined |
| 136 | assert "already been used 1 times by ada@example.com" in joined |
| 137 | |
| 138 | |
| 139 | def test_an_expired_or_unstarted_code_is_refused_with_its_date(): |
| 140 | """'That code has expired' starts a support ticket. 'That code ended |
| 141 | on the 30th of June' ends the conversation.""" |
| 142 | ended = object_promotions.blockers( |
| 143 | promo(ends_on="2026-06-30"), 5000, "", [], on_date="2026-07-01", |
| 144 | code="SPRING20") |
| 145 | assert ended == ["The code SPRING20 ended on 2026-06-30."] |
| 146 | |
| 147 | early = object_promotions.blockers( |
| 148 | promo(starts_on="2026-07-01"), 5000, "", [], on_date=TODAY, |
| 149 | code="SPRING20") |
| 150 | assert early == ["The code SPRING20 does not start until 2026-07-01."] |
| 151 | |
| 152 | |
| 153 | def test_a_code_at_its_limit_is_refused_with_both_numbers(): |
| 154 | used = [{"promotion_id": "pr1", "customer_email": f"{n}@x.com"} |
| 155 | for n in range(3)] |
| 156 | assert object_promotions.blockers( |
| 157 | promo(max_redemptions=3), 5000, "new@x.com", used, on_date=TODAY) == [ |
| 158 | "The code SPRING20 has been used 3 times and its limit is 3."] |
| 159 | # One under, and it works. |
| 160 | assert object_promotions.blockers( |
| 161 | promo(max_redemptions=4), 5000, "new@x.com", used, on_date=TODAY) == [] |
| 162 | |
| 163 | |
| 164 | def test_the_per_customer_limit_counts_one_person_not_everybody(): |
| 165 | used = [{"promotion_id": "pr1", "customer_email": "ada@example.com"}, |
| 166 | {"promotion_id": "pr1", "customer_email": "grace@example.com"}] |
| 167 | limited = promo(per_customer_limit=1) |
| 168 | assert object_promotions.blockers(limited, 5000, "ada@example.com", used, |
| 169 | on_date=TODAY) |
| 170 | assert object_promotions.blockers(limited, 5000, "alan@example.com", used, |
| 171 | on_date=TODAY) == [] |
| 172 | |
| 173 | |
| 174 | def test_the_per_customer_limit_survives_a_capital_letter(): |
| 175 | """The same address with a shift key is the same person, and a limit |
| 176 | that a capital letter walks around is not a limit.""" |
| 177 | used = [{"promotion_id": "pr1", "customer_email": "Ada@Example.COM"}] |
| 178 | assert object_promotions.blockers(promo(per_customer_limit=1), 5000, |
| 179 | "ada@example.com", used, on_date=TODAY) |
| 180 | |
| 181 | |
| 182 | def test_the_count_of_redemptions_is_a_fold_and_not_the_stored_counter(): |
| 183 | """promotions.redemptions_used is a rollup. A gate that read it would |
| 184 | authorise the 1001st use of a 1000-use code the moment it went stale |
| 185 | -- the identical argument hook_wallet_entries makes about summing the |
| 186 | ledger instead of trusting wallets.balance_minor.""" |
| 187 | lying = promo(max_redemptions=2, redemptions_used=0) |
| 188 | really_used = [{"promotion_id": "pr1", "customer_email": "a@x.com"}, |
| 189 | {"promotion_id": "pr1", "customer_email": "b@x.com"}] |
| 190 | assert object_promotions.blockers(lying, 5000, "c@x.com", really_used, |
| 191 | on_date=TODAY) |
| 192 | |
| 193 | |
| 194 | def test_resolution_never_looks_forward(): |
| 195 | """Two rows share a code -- a campaign re-run on new terms. The answer |
| 196 | is the newest one that had ALREADY STARTED, exactly as object_rates |
| 197 | picks a rate card.""" |
| 198 | rows = [promo(id="old", value=1000, starts_on="2026-01-01"), |
| 199 | promo(id="new", value=3000, starts_on="2026-09-01")] |
| 200 | assert object_promotions.resolve("spring20", rows, on_date=TODAY)["id"] == "old" |
| 201 | assert object_promotions.resolve("SPRING20", rows, |
| 202 | on_date="2026-09-02")["id"] == "new" |
| 203 | |
| 204 | |
| 205 | def test_a_code_nobody_has_started_yet_still_resolves_so_it_can_be_dated(): |
| 206 | """Returning None would leave the refusal only able to say 'no such |
| 207 | code', which sends somebody to support instead of to a calendar.""" |
| 208 | rows = [promo(id="future", starts_on="2026-09-01")] |
| 209 | found = object_promotions.resolve("SPRING20", rows, on_date=TODAY) |
| 210 | assert found["id"] == "future" |
| 211 | assert object_promotions.blockers(found, 5000, "", [], on_date=TODAY, |
| 212 | code="SPRING20") == [ |
| 213 | "The code SPRING20 does not start until 2026-09-01."] |
| 214 | |
| 215 | |
| 216 | def test_an_unknown_code_is_one_sentence_and_names_what_was_typed(): |
| 217 | assert object_promotions.resolve("NOPE", [promo()], on_date=TODAY) is None |
| 218 | assert object_promotions.blockers(None, 5000, "", [], on_date=TODAY, |
| 219 | code="nope") == [ |
| 220 | "There is no promotion with the code 'NOPE'."] |
| 221 | |
| 222 | |
| 223 | def test_a_code_that_never_stacks_says_so_with_the_company_it_refused(): |
| 224 | assert object_promotions.blockers(promo(stacking="never"), 5000, "", [], |
| 225 | on_date=TODAY, others=["FREESHIP"]) == [ |
| 226 | "The code SPRING20 cannot be combined with FREESHIP."] |
| 227 | assert object_promotions.blockers(promo(stacking="with_others"), 5000, "", |
| 228 | [], on_date=TODAY, |
| 229 | others=["FREESHIP"]) == [] |
| 230 | |
| 231 | |
| 232 | def test_the_terms_that_get_stamped_are_the_ones_that_applied(): |
| 233 | stamped = object_promotions.terms(promo(minimum_spend_cents=1000)) |
| 234 | assert stamped == {"promotion_id": "pr1", "code_used": "SPRING20", |
| 235 | "kind": "percent", "value": "2000", |
| 236 | "minimum_spend_cents": "1000", "stacking": "never"} |
| 237 | |
| 238 | |
| 239 | def test_a_gift_card_is_tender_and_changes_no_taxable_base(): |
| 240 | """Treating a card as a discount would let a shop sell $100 of goods |
| 241 | and remit tax on $60.""" |
| 242 | items = [{"id": "a", "quantity": "1", "unit_price_cents": "10000"}] |
| 243 | folded = object_cart.checkout_totals(items, tax_rate_bps=1000, |
| 244 | credit_cents=4000) |
| 245 | assert folded["taxable_cents"] == 10000 |
| 246 | assert folded["tax_cents"] == 1000 |
| 247 | assert folded["total_cents"] == 11000 # the sale is still the sale |
| 248 | assert folded["credit_applied_cents"] == 4000 |
| 249 | assert folded["amount_due_cents"] == 7000 |
| 250 | |
| 251 | |
| 252 | def test_a_card_worth_more_than_the_bill_pays_the_bill_and_no_more(): |
| 253 | folded = object_cart.checkout_totals( |
| 254 | [{"id": "a", "quantity": "1", "unit_price_cents": "1000"}], |
| 255 | credit_cents=999999) |
| 256 | assert folded["credit_applied_cents"] == 1000 |
| 257 | assert folded["amount_due_cents"] == 0 |
| 258 | |
| 259 | |
| 260 | def test_the_fold_is_unchanged_for_every_caller_that_passes_no_code(): |
| 261 | """The regression that matters most: a shop that has never heard of |
| 262 | promotions or gift cards gets byte-for-byte the arithmetic it had.""" |
| 263 | items = [{"id": "a", "quantity": "2", "unit_price_cents": "1000"}] |
| 264 | folded = object_cart.checkout_totals(items, tax_rate_bps=1000, |
| 265 | shipping_flat_cents=500) |
| 266 | assert folded["discount_cents"] == 0 |
| 267 | assert folded["tax_cents"] == 200 |
| 268 | assert folded["total_cents"] == 2700 |
| 269 | assert folded["credit_applied_cents"] == 0 |
| 270 | assert folded["amount_due_cents"] == folded["total_cents"] |
| 271 | |
| 272 | |
| 273 | # --- the shop, with a data directory ----------------------------------------- |
| 274 | |
| 275 | def setup_env(tmp_path, monkeypatch, *, settings=()): |
| 276 | """A shop that can take a code and a card: app-shop's objects and |
| 277 | app-billing's, on one root, the way a real box has them -- checkout |
| 278 | asks hook_wallet_entries in process, and a trusted server-side write |
| 279 | bypasses hooks by design, so the gate has to be REACHABLE or it is |
| 280 | not a gate.""" |
| 281 | data_dir = tmp_path / "data" |
| 282 | for pkg, name in (("app-shop", "carts"), ("app-shop", "cart_items"), |
| 283 | ("app-catalog", "products"), ("app-catalog", "locations"), |
| 284 | ("app-catalog", "stock_moves"), |
| 285 | ("app-catalog", "backorders"), |
| 286 | ("app-orders", "orders"), ("app-orders", "order_lines"), |
| 287 | ("app-invoices", "invoices"), |
| 288 | ("app-invoices", "invoice_lines"), |
| 289 | ("app-payments", "payments"), |
| 290 | ("app-billing", "wallets"), |
| 291 | ("app-billing", "wallet_entries"), |
| 292 | ("app-promotions", "promotions"), |
| 293 | ("app-promotions", "promotion_redemptions")): |
| 294 | stage_collection(data_dir, pkg, name) |
| 295 | rows = "".join(f"s{i}\t{k}\t{v}\t\n" for i, (k, v) in enumerate(settings)) |
| 296 | stage_collection(data_dir, "app-settings", "app_settings", rows=rows) |
| 297 | |
| 298 | objects_root = tmp_path / "objects" |
| 299 | for source in (SHOP_OBJECTS, BILLING_OBJECTS, PROMO_OBJECTS): |
| 300 | shutil.copytree(source, objects_root, dirs_exist_ok=True) |
| 301 | monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir)) |
| 302 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root)) |
| 303 | object_records.create_collection_record( |
| 304 | "locations", |
| 305 | {"id": "loc-shelf", "name": "Shelf", "location_type": "warehouse", |
| 306 | "owner_id": "shop"}, base_dir=data_dir) |
| 307 | return data_dir, objects_root |
| 308 | |
| 309 | |
| 310 | def product(data_dir, product_id, name, cents, **fields): |
| 311 | record = {"id": product_id, "name": name, "sku": product_id.upper(), |
| 312 | "product_type": "physical", "price_cents": str(cents), |
| 313 | "currency": "USD", "is_active": "true", "owner_id": "shop"} |
| 314 | record.update({k: str(v) for k, v in fields.items()}) |
| 315 | return object_records.create_collection_record("products", record, |
| 316 | base_dir=data_dir) |
| 317 | |
| 318 | |
| 319 | def stock_in(data_dir, product_id, quantity): |
| 320 | return object_records.create_collection_record( |
| 321 | "stock_moves", |
| 322 | {"id": object_ids.new_uuid4(), "product_id": product_id, |
| 323 | "to_location_id": "loc-shelf", "quantity": str(quantity), |
| 324 | "reason": "purchase", "occurred_at": "2026-06-01", "owner_id": "shop"}, |
| 325 | base_dir=data_dir) |
| 326 | |
| 327 | |
| 328 | def promotion(data_dir, **fields): |
| 329 | record = {"id": "pr1", "code": "SPRING20", "kind": "percent", |
| 330 | "value": "2000", "is_active": "true", "stacking": "never", |
| 331 | "owner_id": "shop"} |
| 332 | record.update({k: str(v) for k, v in fields.items()}) |
| 333 | return object_records.create_collection_record("promotions", record, |
| 334 | base_dir=data_dir) |
| 335 | |
| 336 | |
| 337 | def wallet(data_dir, wallet_id="gc1", code="GC-TEST", kind="gift_card", |
| 338 | **fields): |
| 339 | record = {"id": wallet_id, "owner_id": "shop", "kind": kind, "code": code, |
| 340 | "is_active": "true"} |
| 341 | record.update({k: str(v) for k, v in fields.items()}) |
| 342 | return object_records.create_collection_record("wallets", record, |
| 343 | base_dir=data_dir) |
| 344 | |
| 345 | |
| 346 | def credit(data_dir, wallet_id, amount, *, kind="topup"): |
| 347 | return object_records.create_collection_record( |
| 348 | "wallet_entries", |
| 349 | {"id": object_ids.new_uuid4(), "wallet_id": wallet_id, |
| 350 | "amount_minor": str(amount), "kind": kind, "owner_id": "shop"}, |
| 351 | base_dir=data_dir) |
| 352 | |
| 353 | |
| 354 | def run(object_id, payload, objects_root, *, method="POST"): |
| 355 | return object_execution.execute_object( |
| 356 | RUNTIME, |
| 357 | object_execution.ObjectExecutionRequest(object_id, method=method, |
| 358 | payload=payload), |
| 359 | roots=[objects_root]).result |
| 360 | |
| 361 | |
| 362 | def cart(objects_root, action="get", **payload): |
| 363 | return run("action_cart", {"session_token": TOKEN, "action": action, |
| 364 | **payload}, objects_root) |
| 365 | |
| 366 | |
| 367 | def checkout(objects_root, **payload): |
| 368 | payload.setdefault("today", TODAY) |
| 369 | return run("action_checkout", {"session_token": TOKEN, **payload}, |
| 370 | objects_root) |
| 371 | |
| 372 | |
| 373 | def basket_of(objects_root, data_dir, cents=10000, quantity=1): |
| 374 | product(data_dir, "p1", "Enamel Mug", cents) |
| 375 | stock_in(data_dir, "p1", 10) |
| 376 | cart(objects_root, "add", product_id="p1", quantity=str(quantity)) |
| 377 | |
| 378 | |
| 379 | def rows(data_dir, collection): |
| 380 | return object_records.read_collection_records(collection, base_dir=data_dir) |
| 381 | |
| 382 | |
| 383 | TAXED = (("shop.tax_rate_bps", "1000"),) |
| 384 | |
| 385 | |
| 386 | def test_a_percentage_at_checkout_is_taxed_after_the_discount(tmp_path, monkeypatch): |
| 387 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED) |
| 388 | basket_of(objects_root, data_dir) |
| 389 | promotion(data_dir) |
| 390 | |
| 391 | placed = checkout(objects_root, customer_email="ada@example.com", |
| 392 | promo_code="spring20") |
| 393 | assert placed["ok"] is True |
| 394 | assert placed["subtotal_cents"] == 10000 |
| 395 | assert placed["discount_cents"] == 2000 |
| 396 | assert placed["tax_cents"] == 800 |
| 397 | assert placed["total_cents"] == 8800 |
| 398 | |
| 399 | |
| 400 | def test_the_invoice_total_is_still_the_sum_of_its_own_lines(tmp_path, monkeypatch): |
| 401 | """The discount is a LINE, negative -- not a field beside the total. |
| 402 | Anybody who adds the rows up gets the number at the bottom.""" |
| 403 | data_dir, objects_root = setup_env( |
| 404 | tmp_path, monkeypatch, |
| 405 | settings=TAXED + (("shop.shipping_flat_cents", "500"),)) |
| 406 | basket_of(objects_root, data_dir) |
| 407 | promotion(data_dir) |
| 408 | |
| 409 | checkout(objects_root, customer_email="ada@example.com", |
| 410 | promo_code="SPRING20") |
| 411 | invoice = rows(data_dir, "invoices")[0] |
| 412 | lines = rows(data_dir, "invoice_lines") |
| 413 | |
| 414 | discount = [line for line in lines if "Discount" in line["description"]] |
| 415 | assert len(discount) == 1 |
| 416 | assert discount[0]["line_total_cents"] == "-2000" |
| 417 | assert "SPRING20" in discount[0]["description"] |
| 418 | |
| 419 | assert (sum(int(line["line_total_cents"]) for line in lines) |
| 420 | == int(invoice["subtotal_cents"]) == 8500) |
| 421 | assert (int(invoice["subtotal_cents"]) + int(invoice["tax_cents"]) |
| 422 | == int(invoice["total_cents"]) == 9300) |
| 423 | |
| 424 | |
| 425 | def test_a_fixed_code_larger_than_the_basket_leaves_a_bill_of_zero(tmp_path, monkeypatch): |
| 426 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 427 | basket_of(objects_root, data_dir, cents=1500) |
| 428 | promotion(data_dir, kind="fixed", value=99999, code="TAKEITALL") |
| 429 | |
| 430 | placed = checkout(objects_root, customer_email="ada@example.com", |
| 431 | promo_code="TAKEITALL") |
| 432 | assert placed["discount_cents"] == 1500 |
| 433 | assert placed["total_cents"] == 0 |
| 434 | invoice = rows(data_dir, "invoices")[0] |
| 435 | assert int(invoice["total_cents"]) == 0 |
| 436 | |
| 437 | |
| 438 | def test_a_bad_code_is_refused_beside_the_stock_problem_not_before_it(tmp_path, monkeypatch): |
| 439 | """One 409 carrying everything. Revealing the code problem first, then |
| 440 | the stock problem after they fix it, is how a checkout is abandoned.""" |
| 441 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 442 | product(data_dir, "p1", "Mug", 1000) |
| 443 | stock_in(data_dir, "p1", 1) |
| 444 | cart(objects_root, "add", product_id="p1", quantity="5") |
| 445 | promotion(data_dir, ends_on="2026-01-01") |
| 446 | |
| 447 | refused = checkout(objects_root, customer_email="ada@example.com", |
| 448 | promo_code="SPRING20") |
| 449 | assert refused["status"] == 409 |
| 450 | assert refused["unavailable"] # the stock problem |
| 451 | assert refused["promo_problems"] == [ |
| 452 | "The code SPRING20 ended on 2026-01-01."] # and the code problem |
| 453 | assert refused["money_problems"] == refused["promo_problems"] |
| 454 | assert not rows(data_dir, "orders") |
| 455 | |
| 456 | |
| 457 | def test_the_terms_stamped_at_redemption_survive_a_later_edit(tmp_path, monkeypatch): |
| 458 | """The whole reason the stamp exists. A shop that doubles SPRING20 |
| 459 | next month must not silently restate the receipt somebody is already |
| 460 | holding.""" |
| 461 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 462 | basket_of(objects_root, data_dir) |
| 463 | promotion(data_dir, value=1000) |
| 464 | |
| 465 | checkout(objects_root, customer_email="ada@example.com", |
| 466 | promo_code="SPRING20") |
| 467 | redemption = rows(data_dir, "promotion_redemptions")[0] |
| 468 | assert redemption["value"] == "1000" |
| 469 | assert redemption["kind"] == "percent" |
| 470 | assert redemption["code_used"] == "SPRING20" |
| 471 | assert redemption["discount_cents"] == "1000" |
| 472 | assert redemption["customer_email"] == "ada@example.com" |
| 473 | |
| 474 | object_records.update_collection_record( |
| 475 | "promotions", "pr1", {"value": "5000", "kind": "fixed"}, |
| 476 | base_dir=data_dir, actor="operator") |
| 477 | after = rows(data_dir, "promotion_redemptions")[0] |
| 478 | assert after["value"] == "1000" |
| 479 | assert after["kind"] == "percent" |
| 480 | assert after["discount_cents"] == "1000" |
| 481 | |
| 482 | |
| 483 | def test_a_used_code_counts_against_its_limit_for_the_next_shopper(tmp_path, monkeypatch): |
| 484 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 485 | basket_of(objects_root, data_dir) |
| 486 | promotion(data_dir, max_redemptions=1) |
| 487 | assert checkout(objects_root, customer_email="ada@example.com", |
| 488 | promo_code="SPRING20")["ok"] is True |
| 489 | |
| 490 | # A second shopper, a second basket, the same code. |
| 491 | object_records.create_collection_record( |
| 492 | "carts", {"id": "c2", "session_token": "sess-two", "status": "open", |
| 493 | "currency": "USD", "owner_id": "shop"}, base_dir=data_dir) |
| 494 | object_records.create_collection_record( |
| 495 | "cart_items", {"id": "ci2", "cart_id": "c2", "product_id": "p1", |
| 496 | "description": "Enamel Mug", "quantity": "1", |
| 497 | "unit_price_cents": "10000", "owner_id": "shop"}, |
| 498 | base_dir=data_dir) |
| 499 | refused = run("action_checkout", |
| 500 | {"session_token": "sess-two", "today": TODAY, |
| 501 | "customer_email": "grace@example.com", |
| 502 | "promo_code": "SPRING20"}, objects_root) |
| 503 | assert refused["status"] == 409 |
| 504 | assert "has been used 1 times and its limit is 1" in refused["error"] |
| 505 | |
| 506 | |
| 507 | def test_a_preview_writes_no_redemption_and_no_wallet_entry(tmp_path, monkeypatch): |
| 508 | """A preview that burned a single-use code or drained a gift card |
| 509 | would be a shop charging people for looking.""" |
| 510 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 511 | basket_of(objects_root, data_dir) |
| 512 | promotion(data_dir, max_redemptions=1) |
| 513 | wallet(data_dir) |
| 514 | credit(data_dir, "gc1", 5000) |
| 515 | |
| 516 | quoted = checkout(objects_root, preview="true", promo_code="SPRING20", |
| 517 | gift_card_code="gc-test", |
| 518 | customer_email="ada@example.com") |
| 519 | assert quoted["preview"] is True |
| 520 | assert quoted["discount_cents"] == 2000 |
| 521 | assert quoted["credit_applied_cents"] == 5000 |
| 522 | assert quoted["amount_due_cents"] == 3000 |
| 523 | |
| 524 | assert rows(data_dir, "promotion_redemptions") == [] |
| 525 | assert [row for row in rows(data_dir, "wallet_entries") |
| 526 | if int(row["amount_minor"]) < 0] == [] |
| 527 | assert rows(data_dir, "payments") == [] |
| 528 | assert rows(data_dir, "orders") == [] |
| 529 | |
| 530 | |
| 531 | def test_a_gift_card_pays_part_of_the_bill_and_is_debited_once(tmp_path, monkeypatch): |
| 532 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED) |
| 533 | basket_of(objects_root, data_dir) |
| 534 | wallet(data_dir) |
| 535 | credit(data_dir, "gc1", 4000) |
| 536 | |
| 537 | placed = checkout(objects_root, customer_email="ada@example.com", |
| 538 | gift_card_code="GC-TEST") |
| 539 | assert placed["ok"] is True |
| 540 | assert placed["total_cents"] == 11000 # the sale, taxed in full |
| 541 | assert placed["credit_applied_cents"] == 4000 |
| 542 | assert placed["amount_due_cents"] == 7000 |
| 543 | assert placed["gift_card_applied_cents"] == 4000 |
| 544 | |
| 545 | debits = [row for row in rows(data_dir, "wallet_entries") |
| 546 | if int(row["amount_minor"]) < 0] |
| 547 | assert len(debits) == 1 |
| 548 | assert debits[0]["amount_minor"] == "-4000" |
| 549 | assert debits[0]["generated_from"].startswith("checkout/") |
| 550 | # The balance is the entries, and they now come to nothing. |
| 551 | assert object_records.get_collection_record( |
| 552 | "wallets", "gc1", base_dir=data_dir)["balance_minor"] == "0" |
| 553 | |
| 554 | # Tender is a payment, so the bill knows it was partly settled. |
| 555 | payment = rows(data_dir, "payments")[0] |
| 556 | assert payment["amount_cents"] == "4000" |
| 557 | assert payment["invoice_id"] == placed["invoice_id"] |
| 558 | assert payment["reference"] == "wallets/gc1" |
| 559 | |
| 560 | |
| 561 | def test_a_card_cannot_overdraw_because_the_existing_gate_says_so(tmp_path, monkeypatch): |
| 562 | """The ceiling is hook_wallet_entries', asked in process. A second |
| 563 | opinion written into checkout would be a second thing to get wrong, |
| 564 | and would quote a customer a different number depending on which door |
| 565 | their spend came through.""" |
| 566 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 567 | basket_of(objects_root, data_dir, cents=10000) |
| 568 | wallet(data_dir) |
| 569 | credit(data_dir, "gc1", 2500) |
| 570 | |
| 571 | placed = checkout(objects_root, customer_email="ada@example.com", |
| 572 | gift_card_code="GC-TEST") |
| 573 | assert placed["gift_card_applied_cents"] == 2500 |
| 574 | assert placed["amount_due_cents"] == 7500 |
| 575 | |
| 576 | balance = sum(int(row["amount_minor"]) |
| 577 | for row in rows(data_dir, "wallet_entries") |
| 578 | if row["wallet_id"] == "gc1") |
| 579 | assert balance == 0 # spent, never overdrawn |
| 580 | |
| 581 | # And the gate itself refuses a debit past the floor, in its own words. |
| 582 | verdict = run("hook_wallet_entries", |
| 583 | {"action": "create", "collection": "wallet_entries", |
| 584 | "record": {"id": "x", "wallet_id": "gc1", |
| 585 | "amount_minor": "-1", "kind": "debit"}}, |
| 586 | objects_root, method="BEFORE_WRITE") |
| 587 | assert verdict["status"] == 402 |
| 588 | |
| 589 | |
| 590 | def test_an_empty_card_is_refused_with_the_other_problems(tmp_path, monkeypatch): |
| 591 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 592 | basket_of(objects_root, data_dir) |
| 593 | wallet(data_dir) # no entries at all |
| 594 | |
| 595 | refused = checkout(objects_root, customer_email="ada@example.com", |
| 596 | gift_card_code="GC-TEST") |
| 597 | assert refused["status"] == 409 |
| 598 | assert refused["gift_card_problems"] == [ |
| 599 | "The gift card GC-TEST has nothing left on it."] |
| 600 | assert not rows(data_dir, "orders") |
| 601 | |
| 602 | |
| 603 | def test_an_unknown_card_names_the_code_and_places_no_order(tmp_path, monkeypatch): |
| 604 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 605 | basket_of(objects_root, data_dir) |
| 606 | |
| 607 | refused = checkout(objects_root, customer_email="ada@example.com", |
| 608 | gift_card_code="GC-NOPE") |
| 609 | assert refused["status"] == 409 |
| 610 | assert "There is no gift card with the code 'GC-NOPE'." in refused["error"] |
| 611 | assert not rows(data_dir, "orders") |
| 612 | |
| 613 | |
| 614 | def test_store_credit_spends_through_exactly_the_same_gate(tmp_path, monkeypatch): |
| 615 | """Store credit is a wallet issued by a refund or a dispute rather |
| 616 | than bought -- action_resolve_dispute already writes into this same |
| 617 | ledger. Given a code so a guest can reach it, it redeems by the same |
| 618 | path a gift card does, because it IS the same path.""" |
| 619 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 620 | basket_of(objects_root, data_dir, cents=3000) |
| 621 | wallet(data_dir, wallet_id="sc1", code="SC-ADA", kind="store_credit") |
| 622 | # The shape action_resolve_dispute writes: positive, kind adjustment. |
| 623 | credit(data_dir, "sc1", 3000, kind="adjustment") |
| 624 | |
| 625 | placed = checkout(objects_root, customer_email="ada@example.com", |
| 626 | gift_card_code="SC-ADA") |
| 627 | assert placed["amount_due_cents"] == 0 |
| 628 | debits = [row for row in rows(data_dir, "wallet_entries") |
| 629 | if int(row["amount_minor"]) < 0] |
| 630 | assert len(debits) == 1 and debits[0]["wallet_id"] == "sc1" |
| 631 | |
| 632 | |
| 633 | def test_a_checkout_that_names_no_code_and_no_card_is_the_one_it_was(tmp_path, monkeypatch): |
| 634 | """The regression that matters: a shop running none of this reads no |
| 635 | promotions, no wallets, and gets the same response body it always |
| 636 | did.""" |
| 637 | data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED) |
| 638 | basket_of(objects_root, data_dir) |
| 639 | |
| 640 | placed = checkout(objects_root, customer_email="ada@example.com") |
| 641 | assert placed["ok"] is True |
| 642 | assert placed["total_cents"] == 11000 |
| 643 | assert placed["discount_cents"] == 0 |
| 644 | assert placed["credit_applied_cents"] == 0 |
| 645 | assert placed["amount_due_cents"] == placed["total_cents"] |
| 646 | assert "promo_code" not in placed and "gift_card_code" not in placed |
| 647 | assert rows(data_dir, "promotion_redemptions") == [] |
| 648 | assert rows(data_dir, "payments") == [] |
| 649 | lines = rows(data_dir, "invoice_lines") |
| 650 | assert not [line for line in lines if "Discount" in line["description"]] |
| 651 | |
| 652 | |
| 653 | # --- issuing a card, and the code that names it ------------------------------- |
| 654 | |
| 655 | def test_buying_a_gift_card_credits_a_wallet_when_the_money_settles(tmp_path, monkeypatch): |
| 656 | """An ordinary product sale whose fulfilment credits a wallet instead |
| 657 | of putting something in a box.""" |
| 658 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 659 | product(data_dir, "gc", "Gift Card $50", 5000, is_gift_card="true", |
| 660 | product_type="digital") |
| 661 | cart(objects_root, "add", product_id="gc", quantity="1") |
| 662 | placed = checkout(objects_root, customer_email="ada@example.com") |
| 663 | |
| 664 | payment = {"id": "pay1", "invoice_id": placed["invoice_id"], |
| 665 | "amount_cents": "5000", "method": "card", |
| 666 | "received_on": TODAY, "status": "received", "owner_id": "shop"} |
| 667 | object_records.create_collection_record("payments", payment, |
| 668 | base_dir=data_dir) |
| 669 | issued = run("system_gift_card_issue", |
| 670 | {"collection": "payments", "record": payment}, objects_root) |
| 671 | assert issued["issued"] == 1 |
| 672 | card = issued["cards"][0] |
| 673 | assert card["amount_minor"] == 5000 |
| 674 | assert card["code"].startswith("GC-") |
| 675 | |
| 676 | opened = object_records.get_collection_record("wallets", card["wallet_id"], |
| 677 | base_dir=data_dir) |
| 678 | assert opened["kind"] == "gift_card" |
| 679 | assert opened["balance_minor"] == "5000" |
| 680 | |
| 681 | # And a replayed payment event issues nothing twice: at-least-once |
| 682 | # delivery must not be the shop giving away money. |
| 683 | again = run("system_gift_card_issue", |
| 684 | {"collection": "payments", "record": payment}, objects_root) |
| 685 | assert again["issued"] == 0 |
| 686 | assert len([row for row in rows(data_dir, "wallets") |
| 687 | if row["kind"] == "gift_card"]) == 1 |
| 688 | |
| 689 | |
| 690 | def test_a_card_is_not_issued_before_the_bill_is_settled(tmp_path, monkeypatch): |
| 691 | """A card is money. It is issued when the money is here, not when |
| 692 | somebody has promised it.""" |
| 693 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 694 | product(data_dir, "gc", "Gift Card $50", 5000, is_gift_card="true", |
| 695 | product_type="digital") |
| 696 | cart(objects_root, "add", product_id="gc", quantity="1") |
| 697 | placed = checkout(objects_root, customer_email="ada@example.com") |
| 698 | |
| 699 | part = {"id": "pay1", "invoice_id": placed["invoice_id"], |
| 700 | "amount_cents": "1000", "method": "card", "received_on": TODAY, |
| 701 | "status": "received", "owner_id": "shop"} |
| 702 | object_records.create_collection_record("payments", part, base_dir=data_dir) |
| 703 | outcome = run("system_gift_card_issue", |
| 704 | {"collection": "payments", "record": part}, objects_root) |
| 705 | assert "not settled" in outcome["skipped"] |
| 706 | assert not [row for row in rows(data_dir, "wallets") |
| 707 | if row["kind"] == "gift_card"] |
| 708 | |
| 709 | |
| 710 | def test_two_cards_cannot_share_a_code(tmp_path, monkeypatch): |
| 711 | """A gift card is spent by whoever holds its code, so two cards with |
| 712 | one code is one customer spending another's money.""" |
| 713 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 714 | wallet(data_dir, wallet_id="gc1", code="GC-SAME") |
| 715 | |
| 716 | refusal = run("hook_wallets", |
| 717 | {"action": "create", "collection": "wallets", |
| 718 | "record": {"id": "gc2", "code": "gc-same", |
| 719 | "kind": "gift_card", "owner_id": "shop"}}, |
| 720 | objects_root, method="BEFORE_WRITE") |
| 721 | assert refusal["status"] == 409 |
| 722 | assert "already carries the code GC-SAME" in refusal["error"] |
| 723 | |
| 724 | # A wallet with no code collides with nothing, and there are many. |
| 725 | assert run("hook_wallets", |
| 726 | {"action": "create", "collection": "wallets", |
| 727 | "record": {"id": "w9", "owner_id": "dan"}}, |
| 728 | objects_root, method="BEFORE_WRITE") is None |
| 729 | |
| 730 | |
| 731 | # --- the public quote --------------------------------------------------------- |
| 732 | |
| 733 | def test_the_basket_page_can_ask_without_spending_the_code(tmp_path, monkeypatch): |
| 734 | data_dir, objects_root = setup_env(tmp_path, monkeypatch) |
| 735 | promotion(data_dir, max_redemptions=1) |
| 736 | |
| 737 | quote = run("action_check_promotion", |
| 738 | {"code": "spring20", "subtotal_cents": "10000", |
| 739 | "today": TODAY}, objects_root) |
| 740 | assert quote["applies"] is True |
| 741 | assert quote["discount_cents"] == 2000 |
| 742 | assert rows(data_dir, "promotion_redemptions") == [] |
| 743 | |
| 744 | refused = run("action_check_promotion", |
| 745 | {"code": "nope", "subtotal_cents": "10000", "today": TODAY}, |
| 746 | objects_root) |
| 747 | assert refused["status"] == 409 |
| 748 | assert refused["problems"] == ["There is no promotion with the code 'NOPE'."] |