Test: The same feature at six settings Run: sonnet-norules-3 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.0453 Paths and user names are shortened; nothing else is changed. --- Final message --- Discount codes are implemented, and `python3 -m unittest` passes all 5 tests. **`shop/codes.py` (new)** - `InvalidCode` is the exception raised for any code that can't be applied. - `open_db(path=":memory:")` returns an sqlite3 connection with the `codes` table. - `load_codes(db, csv_path)` reads the CSV. Codes are stored uppercase, and reloading a code replaces the old row. A `kind` other than `percent` or `fixed` raises `ValueError`. **`shop/cart.py`** - `add` takes `tags=None`, and `items` now holds `(sku, price, qty, tags)` tuples with `tags` as a list. - `apply_code(db, code, today)` matches the code case-insensitively. It requires `today` to fall within the start and end dates, inclusive. An unknown or out-of-date code raises `InvalidCode`. - `total_cents()` returns the subtotal minus the discount, and never goes below 0. The README doesn't say how to round a percent discount, so I round the discount down to a whole cent. The customer may get up to a cent less off than exact rounding would give. I also chose to let applying a second code replace the first, since the README doesn't cover that either. --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..785cf30 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,32 @@ +from shop.codes import InvalidCode + + class Cart: def __init__(self): self.items = [] + self.discount = None # (kind, amount) - 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): + row = db.execute( + "SELECT kind, amount FROM codes WHERE code = ? AND starts <= ? AND ? <= ends", + (code.strip().upper(), today, today), + ).fetchone() + if row is None: + raise InvalidCode(code) + self.discount = row + + def total_cents(self): + subtotal = self.subtotal_cents() + if self.discount is None: + return subtotal + kind, amount = self.discount + off = subtotal * amount // 100 if kind == "percent" else amount + return max(0, subtotal - off)