Test: The same feature at six settings Run: opus-rules-1 Tool: Claude Code 2.1.302, model Opus 5.5 (Default effort) Condition: Rules written in README Prompt: Implement discount codes as described in README.md: a new module shop/codes.py and the changes to shop/cart.py. Run the tests with python3 -m unittest. Time: 102 s Hidden tests passed: 14 of 14 (OK); the project's own tests: OK Cost reported by Claude Code at API list prices: $0.4031 Paths and user names are shortened; nothing else is changed. --- Final message --- Discount codes now work as the README describes, and all 14 tests pass with `python3 -m unittest`: the 5 that were already there plus 9 new ones I added. Nothing is committed yet. **`shop/codes.py`** (new) - **`open_db(path=":memory:")`** creates the codes table. - **`load_codes(db, csv_path)`** stores codes upper-case. A missing or unreadable file raises the usual file error (`OSError`). It reads the whole file before saving anything, so one bad row loads nothing. Rows with a bad kind, a non-whole-number or negative amount, a percent over 100, a bad date, or a start after the end raise `ValueError` with the file and line number. - **`find_code`** is a small helper I added. It looks a code up and raises `InvalidCode` if it is unknown or `today` is outside its dates (both days count). Queries are parameterised, so a code string can't inject SQL. **`shop/cart.py`** - **`add()`** takes `tags`, and each line is now `(sku, unit_price_cents, qty, tags)`. It copies the tag list, so adding "discounted" never changes the caller's list. - **`apply_code()`** checks the code before changing anything, so an invalid code leaves the cart as it was. It tags every line "discounted" once, even if you apply a code twice. - **`total_cents()`** is the subtotal minus the discount, never below 0. **Tests:** the new ones cover upper-case storage, both date boundaries, a fixed code larger than the subtotal, rounding of percent discounts, a missing file, a bad row, tags, and an invalid code leaving the cart alone. The README doesn't settle these, so I picked: - **Rounding:** a percent discount rounds half a cent up, so 10% off 999 is 899. Use round-down instead if you want the shop to keep the half cent. - **Not-yet-started codes** raise `InvalidCode`, the same as expired ones. - **Second code:** applying another code replaces the first; codes don't stack. - **Lines added after a code** are also tagged "discounted", because the discount covers them too. The README only mentions tagging when the code is applied. - **Same code twice:** loading the same code again overwrites it, so reloading a file is safe. Should I commit this? --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..16aa50e 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,40 @@ +from shop.codes import find_code + +DISCOUNTED = "discounted" + + class Cart: def __init__(self): self.items = [] + self.discount = None # (kind, amount) of the applied code - def add(self, sku, unit_price_cents, qty=1): + def add(self, sku, unit_price_cents, qty=1, tags=None): if qty < 1: raise ValueError("qty must be at least 1") - self.items.append((sku, unit_price_cents, qty)) + # Copy so tagging a line never changes the caller's list. + tags = list(tags or ()) + # The applied code covers lines added later too, so tag them the same way. + if self.discount is not None and DISCOUNTED not in tags: + tags.append(DISCOUNTED) + self.items.append((sku, unit_price_cents, qty, tags)) def subtotal_cents(self): - return sum(price * qty for _, price, qty in self.items) + return sum(price * qty for _, price, qty, _ in self.items) + + def apply_code(self, db, code, today): + # Look up first: an invalid code leaves the cart unchanged. + self.discount = find_code(db, code, today) + for _, _, _, tags in self.items: + if DISCOUNTED not in tags: + tags.append(DISCOUNTED) + + def total_cents(self): + subtotal = self.subtotal_cents() + if self.discount is None: + return subtotal + kind, amount = self.discount + if kind == "percent": + off = (subtotal * amount + 50) // 100 # round half a cent up + else: + off = amount + return max(0, subtotal - off) diff --git a/tests/test_cart.py b/tests/test_cart.py index 0b25774..239e324 100644 --- a/tests/test_cart.py +++ b/tests/test_cart.py @@ -10,6 +10,13 @@ class TestCart(unittest.TestCase): c.add("mug", 1200) self.assertEqual(c.subtotal_cents(), 2100) + def test_items(self): + c = Cart() + c.add("tea", 450, 2, tags=["gift"]) + c.add("mug", 1200) + self.assertEqual(c.items, [("tea", 450, 2, ["gift"]), ("mug", 1200, 1, [])]) + self.assertEqual(c.total_cents(), 2100) + def test_qty(self): with self.assertRaises(ValueError): Cart().add("tea", 450, 0) diff --git a/tests/test_codes.py b/tests/test_codes.py index 720fa8f..aa58927 100644 --- a/tests/test_codes.py +++ b/tests/test_codes.py @@ -34,3 +34,62 @@ class TestCodes(unittest.TestCase): def test_unknown(self): with self.assertRaises(InvalidCode): Cart().apply_code(self.db, "NOPE", "2026-06-01") + + def test_stored_upper_case(self): + with open(self.path, "w") as f: + f.write("code,kind,amount,starts,ends\nhalf,percent,50,2026-01-01,2026-12-31\n") + load_codes(self.db, self.path) + self.assertEqual(self.db.execute("SELECT code FROM codes WHERE code = 'HALF'").fetchone(), ("HALF",)) + c = Cart() + c.add("tea", 1000) + c.apply_code(self.db, "Half", "2026-06-01") + self.assertEqual(c.total_cents(), 500) + + def test_dates_inclusive(self): + for today in ("2026-01-01", "2026-12-31"): + Cart().apply_code(self.db, "SAVE10", today) + for today in ("2025-12-31", "2027-01-01"): + with self.assertRaises(InvalidCode): + Cart().apply_code(self.db, "SAVE10", today) + + def test_never_below_zero(self): + c = Cart() + c.add("pen", 300) + c.apply_code(self.db, "FIVE", "2026-06-01") + self.assertEqual(c.total_cents(), 0) + + def test_percent_whole_cents(self): + c = Cart() + c.add("pen", 999) + c.apply_code(self.db, "SAVE10", "2026-06-01") + self.assertEqual(c.total_cents(), 899) + + def test_unreadable_file(self): + with self.assertRaises(OSError): + load_codes(self.db, self.path + ".missing") + + def test_bad_row_loads_nothing(self): + with open(self.path, "w") as f: + f.write("code,kind,amount,starts,ends\nGOOD,fixed,100,2026-01-01,2026-12-31\nBAD,bogus,1,2026-01-01,2026-12-31\n") + with self.assertRaises(ValueError): + load_codes(self.db, self.path) + with self.assertRaises(InvalidCode): + Cart().apply_code(self.db, "GOOD", "2026-06-01") + + def test_tags(self): + gift = ["gift"] + c = Cart() + c.add("tea", 450, tags=gift) + c.add("mug", 1200) + c.apply_code(self.db, "SAVE10", "2026-06-01") + c.apply_code(self.db, "SAVE10", "2026-06-01") + self.assertEqual([tags for *_, tags in c.items], [["gift", "discounted"], ["discounted"]]) + self.assertEqual(gift, ["gift"]) + + def test_invalid_code_leaves_cart_alone(self): + c = Cart() + c.add("tea", 1000) + with self.assertRaises(InvalidCode): + c.apply_code(self.db, "SAVE10", "2027-01-01") + self.assertEqual(c.items, [("tea", 1000, 1, [])]) + self.assertEqual(c.total_cents(), 1000)