Test: The same feature at six settings Run: codexhigh-norules-3 Tool: Codex CLI 0.145.0, model gpt-5.6-sol (Reasoning effort xhigh) 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: 62 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 codes in [shop/codes.py](shop/codes.py) and updated [shop/cart.py](shop/cart.py). Includes case-insensitive codes, inclusive validity dates, percent/fixed discounts, zero-floor totals, CSV loading, and line tags. `python3 -m unittest`: **5 tests passed**. --- Code written (git diff) --- diff --git a/shop/cart.py b/shop/cart.py index d67b0b4..7c17127 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -1,11 +1,49 @@ +from .codes import InvalidCode + + 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)) + line_tags = list(tags) if tags is not None else [] + if self._discount is not None and "discounted" not in line_tags: + line_tags.append("discounted") + self.items.append((sku, unit_price_cents, qty, line_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): + 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 + 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": + total = subtotal - (subtotal * amount // 100) + elif kind == "fixed": + total = subtotal - amount + else: + raise ValueError(f"unknown discount kind: {kind}") + return max(0, total)