Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_promotions.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_promotions.py · 34.7 KB · 767 lines
1"""Promotions, gift cards and store credit: the money that comes OFF a
2sale, and the money that PAYS for one.
3
4Two claims carry this file, and they are different claims about
5different kinds of thing.
6
7A DISCOUNT IS A PRICE. It changes what the goods cost, so it comes off
8the taxable base before tax is computed -- what every jurisdiction that
9levies a sales or value-added tax actually requires -- it lands on the
10invoice as a LINE so the total stays the sum of its own lines, and its
11terms are STAMPED on the redemption at use so that editing the promotion
12next month cannot restate what somebody already got.
13
14A GIFT CARD IS TENDER. It is money the customer already gave this shop,
15so it changes no price and no taxable base; it goes through the wallet
16gate that already exists (hook_wallet_entries, which sums the entries
17rather than trusting the rollup), it cannot overdraw, and -- the property
18most easily broken by a refactor -- a PREVIEW SPENDS NOTHING.
19"""
20
21import pathlib
22import shutil
23
24import pytest
25from conftest import stage_collection
26
27import object_cart
28import object_execution
29import object_ids
30import object_promotions
31import object_records
32import python_object_runtime
33
34REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
35PACKAGES = REPO_ROOT / "packages"
36SHOP_OBJECTS = PACKAGES / "app-shop" / "objects"
37BILLING_OBJECTS = PACKAGES / "app-billing" / "objects"
38PROMO_OBJECTS = PACKAGES / "app-promotions" / "objects"
39RUNTIME = python_object_runtime.PythonObjectRuntime()
40
41TOKEN = "sess-promo"
42TODAY = "2026-06-15"
43
44
45# --- the pure fold, with no data directory in sight ---------------------------
46
47def 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
54def 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
73def 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
84def 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
101def 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
118def 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
139def 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
153def 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
164def 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
174def 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
182def 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
194def 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
205def 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
216def 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
223def 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
232def 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
239def 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
252def 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
260def 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
275def 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
310def 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
319def 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
328def 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
337def 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
346def 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
354def 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
362def cart(objects_root, action="get", **payload):
363 return run("action_cart", {"session_token": TOKEN, "action": action,
364 **payload}, objects_root)
365
366
367def checkout(objects_root, **payload):
368 payload.setdefault("today", TODAY)
369 return run("action_checkout", {"session_token": TOKEN, **payload},
370 objects_root)
371
372
373def cart_items_for(data_dir, cart_id, token, item_id, product_id="p1", cents=10000):
374 """An extra open basket holding one unit of a product."""
375 object_records.create_collection_record(
376 "carts", {"id": cart_id, "session_token": token, "status": "open",
377 "currency": "USD", "owner_id": "shop"}, base_dir=data_dir)
378 object_records.create_collection_record(
379 "cart_items", {"id": item_id, "cart_id": cart_id, "product_id": product_id,
380 "description": "Enamel Mug", "quantity": "1",
381 "unit_price_cents": str(cents), "owner_id": "shop"},
382 base_dir=data_dir)
383
384
385def checkout_as(objects_root, token, email, **payload):
386 payload.setdefault("today", TODAY)
387 return run("action_checkout",
388 {"session_token": token, "customer_email": email, **payload},
389 objects_root)
390
391
392def basket_of(objects_root, data_dir, cents=10000, quantity=1):
393 product(data_dir, "p1", "Enamel Mug", cents)
394 stock_in(data_dir, "p1", 10)
395 cart(objects_root, "add", product_id="p1", quantity=str(quantity))
396
397
398def rows(data_dir, collection):
399 return object_records.read_collection_records(collection, base_dir=data_dir)
400
401
402TAXED = (("shop.tax_rate_bps", "1000"),)
403
404
405def test_a_percentage_at_checkout_is_taxed_after_the_discount(tmp_path, monkeypatch):
406 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED)
407 basket_of(objects_root, data_dir)
408 promotion(data_dir)
409
410 placed = checkout(objects_root, customer_email="ada@example.com",
411 promo_code="spring20")
412 assert placed["ok"] is True
413 assert placed["subtotal_cents"] == 10000
414 assert placed["discount_cents"] == 2000
415 assert placed["tax_cents"] == 800
416 assert placed["total_cents"] == 8800
417
418
419def test_the_invoice_total_is_still_the_sum_of_its_own_lines(tmp_path, monkeypatch):
420 """The discount is a LINE, negative -- not a field beside the total.
421 Anybody who adds the rows up gets the number at the bottom."""
422 data_dir, objects_root = setup_env(
423 tmp_path, monkeypatch,
424 settings=TAXED + (("shop.shipping_flat_cents", "500"),))
425 basket_of(objects_root, data_dir)
426 promotion(data_dir)
427
428 checkout(objects_root, customer_email="ada@example.com",
429 promo_code="SPRING20")
430 invoice = rows(data_dir, "invoices")[0]
431 lines = rows(data_dir, "invoice_lines")
432
433 discount = [line for line in lines if "Discount" in line["description"]]
434 assert len(discount) == 1
435 assert discount[0]["line_total_cents"] == "-2000"
436 assert "SPRING20" in discount[0]["description"]
437
438 assert (sum(int(line["line_total_cents"]) for line in lines)
439 == int(invoice["subtotal_cents"]) == 8500)
440 assert (int(invoice["subtotal_cents"]) + int(invoice["tax_cents"])
441 == int(invoice["total_cents"]) == 9300)
442
443
444def test_a_fixed_code_larger_than_the_basket_leaves_a_bill_of_zero(tmp_path, monkeypatch):
445 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
446 basket_of(objects_root, data_dir, cents=1500)
447 promotion(data_dir, kind="fixed", value=99999, code="TAKEITALL")
448
449 placed = checkout(objects_root, customer_email="ada@example.com",
450 promo_code="TAKEITALL")
451 assert placed["discount_cents"] == 1500
452 assert placed["total_cents"] == 0
453 invoice = rows(data_dir, "invoices")[0]
454 assert int(invoice["total_cents"]) == 0
455
456
457def test_a_bad_code_is_refused_beside_the_stock_problem_not_before_it(tmp_path, monkeypatch):
458 """One 409 carrying everything. Revealing the code problem first, then
459 the stock problem after they fix it, is how a checkout is abandoned."""
460 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
461 product(data_dir, "p1", "Mug", 1000)
462 stock_in(data_dir, "p1", 1)
463 cart(objects_root, "add", product_id="p1", quantity="5")
464 promotion(data_dir, ends_on="2026-01-01")
465
466 refused = checkout(objects_root, customer_email="ada@example.com",
467 promo_code="SPRING20")
468 assert refused["status"] == 409
469 assert refused["unavailable"] # the stock problem
470 assert refused["promo_problems"] == [
471 "The code SPRING20 ended on 2026-01-01."] # and the code problem
472 assert refused["money_problems"] == refused["promo_problems"]
473 assert not rows(data_dir, "orders")
474
475
476def test_the_terms_stamped_at_redemption_survive_a_later_edit(tmp_path, monkeypatch):
477 """The whole reason the stamp exists. A shop that doubles SPRING20
478 next month must not silently restate the receipt somebody is already
479 holding."""
480 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
481 basket_of(objects_root, data_dir)
482 promotion(data_dir, value=1000)
483
484 checkout(objects_root, customer_email="ada@example.com",
485 promo_code="SPRING20")
486 redemption = rows(data_dir, "promotion_redemptions")[0]
487 assert redemption["value"] == "1000"
488 assert redemption["kind"] == "percent"
489 assert redemption["code_used"] == "SPRING20"
490 assert redemption["discount_cents"] == "1000"
491 assert redemption["customer_email"] == "ada@example.com"
492
493 object_records.update_collection_record(
494 "promotions", "pr1", {"value": "5000", "kind": "fixed"},
495 base_dir=data_dir, actor="operator")
496 after = rows(data_dir, "promotion_redemptions")[0]
497 assert after["value"] == "1000"
498 assert after["kind"] == "percent"
499 assert after["discount_cents"] == "1000"
500
501
502def test_a_used_code_counts_against_its_limit_for_the_next_shopper(tmp_path, monkeypatch):
503 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
504 basket_of(objects_root, data_dir)
505 promotion(data_dir, max_redemptions=1)
506 assert checkout(objects_root, customer_email="ada@example.com",
507 promo_code="SPRING20")["ok"] is True
508
509 # A second shopper, a second basket, the same code.
510 object_records.create_collection_record(
511 "carts", {"id": "c2", "session_token": "sess-two", "status": "open",
512 "currency": "USD", "owner_id": "shop"}, base_dir=data_dir)
513 object_records.create_collection_record(
514 "cart_items", {"id": "ci2", "cart_id": "c2", "product_id": "p1",
515 "description": "Enamel Mug", "quantity": "1",
516 "unit_price_cents": "10000", "owner_id": "shop"},
517 base_dir=data_dir)
518 refused = run("action_checkout",
519 {"session_token": "sess-two", "today": TODAY,
520 "customer_email": "grace@example.com",
521 "promo_code": "SPRING20"}, objects_root)
522 assert refused["status"] == 409
523 assert "has been used 1 times and its limit is 1" in refused["error"]
524
525
526def test_a_preview_writes_no_redemption_and_no_wallet_entry(tmp_path, monkeypatch):
527 """A preview that burned a single-use code or drained a gift card
528 would be a shop charging people for looking."""
529 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
530 basket_of(objects_root, data_dir)
531 promotion(data_dir, max_redemptions=1)
532 wallet(data_dir)
533 credit(data_dir, "gc1", 5000)
534
535 quoted = checkout(objects_root, preview="true", promo_code="SPRING20",
536 gift_card_code="gc-test",
537 customer_email="ada@example.com")
538 assert quoted["preview"] is True
539 assert quoted["discount_cents"] == 2000
540 assert quoted["credit_applied_cents"] == 5000
541 assert quoted["amount_due_cents"] == 3000
542
543 assert rows(data_dir, "promotion_redemptions") == []
544 assert [row for row in rows(data_dir, "wallet_entries")
545 if int(row["amount_minor"]) < 0] == []
546 assert rows(data_dir, "payments") == []
547 assert rows(data_dir, "orders") == []
548
549
550def test_a_gift_card_pays_part_of_the_bill_and_is_debited_once(tmp_path, monkeypatch):
551 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED)
552 basket_of(objects_root, data_dir)
553 wallet(data_dir)
554 credit(data_dir, "gc1", 4000)
555
556 placed = checkout(objects_root, customer_email="ada@example.com",
557 gift_card_code="GC-TEST")
558 assert placed["ok"] is True
559 assert placed["total_cents"] == 11000 # the sale, taxed in full
560 assert placed["credit_applied_cents"] == 4000
561 assert placed["amount_due_cents"] == 7000
562 assert placed["gift_card_applied_cents"] == 4000
563
564 debits = [row for row in rows(data_dir, "wallet_entries")
565 if int(row["amount_minor"]) < 0]
566 assert len(debits) == 1
567 assert debits[0]["amount_minor"] == "-4000"
568 assert debits[0]["generated_from"].startswith("checkout/")
569 # The balance is the entries, and they now come to nothing.
570 assert object_records.get_collection_record(
571 "wallets", "gc1", base_dir=data_dir)["balance_minor"] == "0"
572
573 # Tender is a payment, so the bill knows it was partly settled.
574 payment = rows(data_dir, "payments")[0]
575 assert payment["amount_cents"] == "4000"
576 assert payment["invoice_id"] == placed["invoice_id"]
577 assert payment["reference"] == "wallets/gc1"
578
579
580def test_a_card_cannot_overdraw_because_the_existing_gate_says_so(tmp_path, monkeypatch):
581 """The ceiling is hook_wallet_entries', asked in process. A second
582 opinion written into checkout would be a second thing to get wrong,
583 and would quote a customer a different number depending on which door
584 their spend came through."""
585 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
586 basket_of(objects_root, data_dir, cents=10000)
587 wallet(data_dir)
588 credit(data_dir, "gc1", 2500)
589
590 placed = checkout(objects_root, customer_email="ada@example.com",
591 gift_card_code="GC-TEST")
592 assert placed["gift_card_applied_cents"] == 2500
593 assert placed["amount_due_cents"] == 7500
594
595 balance = sum(int(row["amount_minor"])
596 for row in rows(data_dir, "wallet_entries")
597 if row["wallet_id"] == "gc1")
598 assert balance == 0 # spent, never overdrawn
599
600 # And the gate itself refuses a debit past the floor, in its own words.
601 verdict = run("hook_wallet_entries",
602 {"action": "create", "collection": "wallet_entries",
603 "record": {"id": "x", "wallet_id": "gc1",
604 "amount_minor": "-1", "kind": "debit"}},
605 objects_root, method="BEFORE_WRITE")
606 assert verdict["status"] == 402
607
608
609def test_an_empty_card_is_refused_with_the_other_problems(tmp_path, monkeypatch):
610 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
611 basket_of(objects_root, data_dir)
612 wallet(data_dir) # no entries at all
613
614 refused = checkout(objects_root, customer_email="ada@example.com",
615 gift_card_code="GC-TEST")
616 assert refused["status"] == 409
617 assert refused["gift_card_problems"] == [
618 "The gift card GC-TEST has nothing left on it."]
619 assert not rows(data_dir, "orders")
620
621
622def test_an_unknown_card_names_the_code_and_places_no_order(tmp_path, monkeypatch):
623 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
624 basket_of(objects_root, data_dir)
625
626 refused = checkout(objects_root, customer_email="ada@example.com",
627 gift_card_code="GC-NOPE")
628 assert refused["status"] == 409
629 assert "There is no gift card with the code 'GC-NOPE'." in refused["error"]
630 assert not rows(data_dir, "orders")
631
632
633def test_store_credit_spends_through_exactly_the_same_gate(tmp_path, monkeypatch):
634 """Store credit is a wallet issued by a refund or a dispute rather
635 than bought -- action_resolve_dispute already writes into this same
636 ledger. Given a code so a guest can reach it, it redeems by the same
637 path a gift card does, because it IS the same path."""
638 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
639 basket_of(objects_root, data_dir, cents=3000)
640 wallet(data_dir, wallet_id="sc1", code="SC-ADA", kind="store_credit")
641 # The shape action_resolve_dispute writes: positive, kind adjustment.
642 credit(data_dir, "sc1", 3000, kind="adjustment")
643
644 placed = checkout(objects_root, customer_email="ada@example.com",
645 gift_card_code="SC-ADA")
646 assert placed["amount_due_cents"] == 0
647 debits = [row for row in rows(data_dir, "wallet_entries")
648 if int(row["amount_minor"]) < 0]
649 assert len(debits) == 1 and debits[0]["wallet_id"] == "sc1"
650
651
652def test_a_checkout_that_names_no_code_and_no_card_is_the_one_it_was(tmp_path, monkeypatch):
653 """The regression that matters: a shop running none of this reads no
654 promotions, no wallets, and gets the same response body it always
655 did."""
656 data_dir, objects_root = setup_env(tmp_path, monkeypatch, settings=TAXED)
657 basket_of(objects_root, data_dir)
658
659 placed = checkout(objects_root, customer_email="ada@example.com")
660 assert placed["ok"] is True
661 assert placed["total_cents"] == 11000
662 assert placed["discount_cents"] == 0
663 assert placed["credit_applied_cents"] == 0
664 assert placed["amount_due_cents"] == placed["total_cents"]
665 assert "promo_code" not in placed and "gift_card_code" not in placed
666 assert rows(data_dir, "promotion_redemptions") == []
667 assert rows(data_dir, "payments") == []
668 lines = rows(data_dir, "invoice_lines")
669 assert not [line for line in lines if "Discount" in line["description"]]
670
671
672# --- issuing a card, and the code that names it -------------------------------
673
674def test_buying_a_gift_card_credits_a_wallet_when_the_money_settles(tmp_path, monkeypatch):
675 """An ordinary product sale whose fulfilment credits a wallet instead
676 of putting something in a box."""
677 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
678 product(data_dir, "gc", "Gift Card $50", 5000, is_gift_card="true",
679 product_type="digital")
680 cart(objects_root, "add", product_id="gc", quantity="1")
681 placed = checkout(objects_root, customer_email="ada@example.com")
682
683 payment = {"id": "pay1", "invoice_id": placed["invoice_id"],
684 "amount_cents": "5000", "method": "card",
685 "received_on": TODAY, "status": "received", "owner_id": "shop"}
686 object_records.create_collection_record("payments", payment,
687 base_dir=data_dir)
688 issued = run("system_gift_card_issue",
689 {"collection": "payments", "record": payment}, objects_root)
690 assert issued["issued"] == 1
691 card = issued["cards"][0]
692 assert card["amount_minor"] == 5000
693 assert card["code"].startswith("GC-")
694
695 opened = object_records.get_collection_record("wallets", card["wallet_id"],
696 base_dir=data_dir)
697 assert opened["kind"] == "gift_card"
698 assert opened["balance_minor"] == "5000"
699
700 # And a replayed payment event issues nothing twice: at-least-once
701 # delivery must not be the shop giving away money.
702 again = run("system_gift_card_issue",
703 {"collection": "payments", "record": payment}, objects_root)
704 assert again["issued"] == 0
705 assert len([row for row in rows(data_dir, "wallets")
706 if row["kind"] == "gift_card"]) == 1
707
708
709def test_a_card_is_not_issued_before_the_bill_is_settled(tmp_path, monkeypatch):
710 """A card is money. It is issued when the money is here, not when
711 somebody has promised it."""
712 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
713 product(data_dir, "gc", "Gift Card $50", 5000, is_gift_card="true",
714 product_type="digital")
715 cart(objects_root, "add", product_id="gc", quantity="1")
716 placed = checkout(objects_root, customer_email="ada@example.com")
717
718 part = {"id": "pay1", "invoice_id": placed["invoice_id"],
719 "amount_cents": "1000", "method": "card", "received_on": TODAY,
720 "status": "received", "owner_id": "shop"}
721 object_records.create_collection_record("payments", part, base_dir=data_dir)
722 outcome = run("system_gift_card_issue",
723 {"collection": "payments", "record": part}, objects_root)
724 assert "not settled" in outcome["skipped"]
725 assert not [row for row in rows(data_dir, "wallets")
726 if row["kind"] == "gift_card"]
727
728
729def test_two_cards_cannot_share_a_code(tmp_path, monkeypatch):
730 """A gift card is spent by whoever holds its code, so two cards with
731 one code is one customer spending another's money."""
732 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
733 wallet(data_dir, wallet_id="gc1", code="GC-SAME")
734
735 # The schema's `unique` on code (without case, blank exempt) refuses it
736 # inside the write lock, for every writer; there is no hook any more.
737 with pytest.raises(object_records.UniqueConstraintError) as refusal:
738 object_records.create_collection_record(
739 "wallets", {"id": "gc2", "code": "gc-same", "kind": "gift_card",
740 "owner_id": "shop"}, base_dir=data_dir)
741 assert "carries that gift-card code" in str(refusal.value)
742
743 # A wallet with no code collides with nothing, and there are many.
744 object_records.create_collection_record(
745 "wallets", {"id": "w8", "owner_id": "dan"}, base_dir=data_dir)
746 object_records.create_collection_record(
747 "wallets", {"id": "w9", "owner_id": "dan"}, base_dir=data_dir)
748
749
750# --- the public quote ---------------------------------------------------------
751
752def test_the_basket_page_can_ask_without_spending_the_code(tmp_path, monkeypatch):
753 data_dir, objects_root = setup_env(tmp_path, monkeypatch)
754 promotion(data_dir, max_redemptions=1)
755
756 quote = run("action_check_promotion",
757 {"code": "spring20", "subtotal_cents": "10000",
758 "today": TODAY}, objects_root)
759 assert quote["applies"] is True
760 assert quote["discount_cents"] == 2000
761 assert rows(data_dir, "promotion_redemptions") == []
762
763 refused = run("action_check_promotion",
764 {"code": "nope", "subtotal_cents": "10000", "today": TODAY},
765 objects_root)
766 assert refused["status"] == 409
767 assert refused["problems"] == ["There is no promotion with the code 'NOPE'."]