Test: The same feature at six settings Run: sonnet-rules-3 Tool: Claude Code 2.1.302, model Sonnet 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: 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.0466 Paths and user names are shortened; nothing else is changed. --- Final message --- Discount codes are in place and `python3 -m unittest` passes (5 tests). I didn't add tests of my own for the date boundaries, expiry or tagging, so those paths are untested. **`shop/codes.py` (new)** - `InvalidCode`, `open_db(path=":memory:")` and `load_codes(db, csv_path)` are as the README describes. - Codes are stored upper-case and looked up case-insensitively. - A code is valid from its start date through its end date, both included. - An unreadable CSV raises the normal file error. - A `kind` other than `percent` or `fixed` raises `ValueError`. The README doesn't say what to do there, so that's my choice. - Loading a code that already exists replaces the old row. **`shop/cart.py`** - `add` takes `tags=None`, and each item is now `(sku, price, qty, tags)` with `tags` as a list. - `apply_code(db, code, today)` raises `InvalidCode` for an unknown or out-of-date code. It adds the tag "discounted" to every line already in the cart. Lines added after the code is applied are not tagged. - `total_cents()` applies the code to the subtotal and never goes below 0. The README doesn't say how to round a percent discount to whole cents, so I round the discount half up. For example, 10% off 1005 cents takes off 101, which gives 904. --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..35ba198 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,32 @@ +from shop.codes import find_code + + 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 or []))) 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 = find_code(db, code, today) + for tags in (item[3] for item 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 + else: + off = amount + return max(0, subtotal - off)