Test: The same feature at six settings Run: opus-rules-3 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: 70 s Hidden tests passed: 14 of 14 (OK); the project's own tests: OK Cost reported by Claude Code at API list prices: $0.2594 Paths and user names are shortened; nothing else is changed. --- Final message --- I added discount codes as the README describes, and all 14 tests pass with `python3 -m unittest`. That's the 5 tests that were already there plus 9 new ones in `tests/test_codes.py` for the edge cases. Nothing is committed. **`shop/codes.py`** (new) - `open_db(path=":memory:")` opens an sqlite3 connection and creates the `codes` table. - `load_codes(db, csv_path)`: - A missing or unreadable file raises the usual Python error. - It checks the CSV's columns and every row: the code can't be empty, the kind must be `percent` or `fixed`, the amount must be a whole number of at least 0, the dates must be real dates, and the start can't be after the end. A bad row raises `ValueError` with its line number. - Codes are stored upper-case. - It loads everything in one go, so a file with a bad row loads nothing. - `InvalidCode` is raised for an unknown code and for a date outside its start–end range. Both end days count as valid. **`shop/cart.py`** - `add(..., tags=None)` stores `(sku, unit_price_cents, qty, tags)`. It copies the tags list you pass in, so your own list isn't changed when "discounted" is added. - `apply_code(db, code, today)` checks the code first, so an invalid code leaves the cart unchanged. It then tags every line "discounted", once only, even if you apply a code twice. - `total_cents()` uses whole-cent arithmetic and never goes below 0. The README doesn't settle these, so I chose: - **Rounding:** for percent codes, half a cent goes in the customer's favour. For example, 10% off 5¢ gives 4¢. - **Code not yet started:** raises `InvalidCode`, the same as an expired one. - **Lines added after a code:** they're also tagged "discounted", because the discount applies to the whole subtotal. - **One code per cart:** applying a second code replaces the first rather than adding to it. - **Duplicate codes:** if a CSV has the same code twice (in any case), the last row wins. Reloading a file updates codes already in the database. - **Whole-number amounts:** a percentage like `12.5` is rejected as a bad row. --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..ea92c97 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,40 @@ +from shop.codes import lookup + +DISCOUNTED = "discounted" + + class Cart: def __init__(self): self.items = [] + self.discount = None - 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)) + tags = list(tags or []) + # The discount applies to the whole subtotal, so later lines are discounted too. + if self.discount 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, so an invalid code leaves the cart unchanged. + self.discount = lookup(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": + # Integer math, half a cent rounds in the customer's favour. + off = (subtotal * amount + 50) // 100 + else: + off = amount + return max(0, subtotal - off) diff --git a/tests/test_codes.py b/tests/test_codes.py index 720fa8f..28105f9 100644 --- a/tests/test_codes.py +++ b/tests/test_codes.py @@ -34,3 +34,73 @@ 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): + db = open_db() + path = self.write_csv("code,kind,amount,starts,ends\nsave20,percent,20,2026-01-01,2026-12-31\n") + load_codes(db, path) + self.assertEqual(db.execute("SELECT code FROM codes").fetchall(), [("SAVE20",)]) + c = Cart() + c.add("tea", 1000) + c.apply_code(db, "Save20", "2026-06-01") + self.assertEqual(c.total_cents(), 800) + + def test_first_and_last_day_included(self): + for day in ("2026-01-01", "2026-12-31"): + c = Cart() + c.add("mug", 1200) + c.apply_code(self.db, "FIVE", day) + self.assertEqual(c.total_cents(), 700) + + def test_outside_dates(self): + for day in ("2025-12-31", "2027-01-01"): + with self.assertRaises(InvalidCode): + Cart().apply_code(self.db, "FIVE", day) + + 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("gum", 5) + c.apply_code(self.db, "SAVE10", "2026-06-01") + self.assertEqual(c.total_cents(), 4) + + def test_tags(self): + gift = ["gift"] + c = Cart() + c.add("tea", 1000, 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, "NOPE", "2026-06-01") + self.assertEqual(c.items, [("tea", 1000, 1, [])]) + self.assertEqual(c.total_cents(), 1000) + + def test_unreadable_file(self): + with self.assertRaises(OSError): + load_codes(open_db(), self.path + ".missing") + + def test_bad_row_loads_nothing(self): + db = open_db() + path = self.write_csv(CSV + "BAD,bogus,1,2026-01-01,2026-12-31\n") + with self.assertRaises(ValueError): + load_codes(db, path) + self.assertEqual(db.execute("SELECT COUNT(*) FROM codes").fetchone(), (0,)) + + def write_csv(self, text): + fd, path = tempfile.mkstemp(suffix=".csv") + with os.fdopen(fd, "w") as f: + f.write(text) + self.addCleanup(os.remove, path) + return path