Test: The same feature at six settings Run: sonnet-norules-1 Tool: Claude Code 2.1.302, model Sonnet 5.5 (Default effort) Condition: Only the interface written 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: 14 s Hidden tests passed: 14 of 14 (OK); the project's own tests: OK Cost reported by Claude Code at API list prices: $0.0488 Paths and user names are shortened; nothing else is changed. --- Final message --- Discount codes are implemented, and `python3 -m unittest` passes (5 tests). The README doesn't specify the edge cases, so I chose the behaviors below. **What changed** - **`shop/codes.py`** (new): `InvalidCode`, `open_db`, `load_codes` and a `lookup` helper. A code is valid only if `today` falls within its `starts`–`ends` dates, both ends inclusive. An unknown or out-of-range code raises `InvalidCode`. - **`shop/cart.py`**: - `add` takes `tags` and stores a list. - Items are now 4-tuples. - `apply_code` and `total_cents` are added. **Choices I made where the README is silent** - Codes are case-insensitive. The tests need this (`"save10"` matches `SAVE10`). - Percent discounts round to the nearest cent, with halves rounding up. - A fixed discount can't take the total below zero. - A code with a `kind` other than `percent` or `fixed` makes `load_codes` raise `ValueError`. - Reloading a code that already exists replaces the old row. - Applying a second code replaces the first rather than stacking. I didn't add tests for expiry, the date boundaries or the zero floor. The existing tests don't cover those. --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..8bf32e8 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,29 @@ +from shop.codes import lookup + + 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)) + self.items.append((sku, unit_price_cents, qty, list(tags) if tags else [])) 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): + self.discount = lookup(db, code, today) + + 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 + else: + off = amount + return max(subtotal - off, 0)