Test: The same feature at six settings Run: codex-rules-2 Tool: Codex CLI 0.145.0, model gpt-5.6-sol (Built-in default reasoning) 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: 29 s Hidden tests passed: 14 of 14 (OK); the project's own tests: OK Cost: Codex on a ChatGPT plan reports tokens, not a price Paths and user names are shortened; nothing else is changed. --- Final message --- Implemented discount code support: - Added `shop/codes.py` with `InvalidCode`, SQLite setup, and CSV loading. - Updated `Cart` with tags, code application, date validation, and discounted totals. - Codes are case-insensitive; date bounds are inclusive. - Totals never fall below zero. Verification: ```text Ran 5 tests in 0.002s OK ``` --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..cd53d73 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,40 @@ 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 is not None 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): + from .codes import InvalidCode + + row = db.execute( + "SELECT kind, amount, starts, ends FROM codes WHERE code = ?", + (code.upper(),), + ).fetchone() + if row is None or not row[2] <= today <= row[3]: + raise InvalidCode(code) + + self._discount = (row[0], row[1]) + for item in self.items: + tags = item[3] + 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": + discount = subtotal * amount // 100 + else: + discount = amount + return max(0, subtotal - discount)