Bakery Order Service
Pick up four tickets in a working bakery order service: fix a stock bug, add coupon codes, make the dashboard queries scale, then add cancellations. Practice reading, debugging and extending code you didn't write, with an AI assistant at your side.
Quick start
- Download the starter repo and unzip it.
- Open the folder in your editor, with any AI assistant you like.
-
Run the tests from the repo's folder:
python3 -m unittest discover -s tests. The tests for the stages you haven't done yet fail. - Set a timer for 75 minutes and work through the stages in order.
Stages
- Stage 1: Fix BUG-112, stock goes missing after rejected orders
- Stage 2: Add coupon codes (percent or fixed, minimum, expiry, redemption limit)
- Stage 3: Make the dashboard queries scale without scanning every order
- Stage 4 (stretch): Cancel orders, releasing stock and coupon uses
What it practices
- reading unfamiliar code
- debugging across modules
- extending a codebase without breaking it
- money in integer cents and rounding rules
- indexes and running aggregates
- verifying AI-written code
Similar to
- Meta AI-enabled coding round
- Stripe integration round
The scenario
You've just joined the team behind Crumb & Co., a small bakery's order service. It's a working Python codebase of seven modules (about 500 lines): products and customers, pricing with bulk discounts and a loyalty programme, stock reservation, order placement, and an in-memory repository that backs the shop's dashboard. Your job is to pick up four tickets: fix a bug, add a feature, make the reporting queries scale, and (as a stretch) add cancellations.
This is the "existing codebase" format: the code already works, and most of the job is understanding it well enough to change it safely. It's close to Meta's AI-enabled coding round (a multi-file project you debug and extend with an AI assistant at your side) and to the integration and bug-finding rounds at companies like Stripe, where you work inside code you didn't write.
Time box: 60-75 minutes. In a real interview the stages are often revealed one at a time. They're all listed here, but do them in order: each one builds on the last.
- Stage 1: fix BUG-112, "stock goes missing after rejected orders." When an order is rejected (say, because one item is no longer on the menu), stock for the other items still goes down. Done when a rejected order never changes stock, and successful orders still reserve it.
- Stage 2: add coupon codes. Percent-off or fixed-amount coupons with a minimum subtotal, an expiry date and an optional redemption limit, at most one per order. Done when the coupon is applied after bulk discounts and before the loyalty discount, percentages round down, a coupon can never make a total negative, and an invalid coupon rejects the order without changing anything.
- Stage 3: make the dashboard queries scale. "This customer's orders" and "best sellers between two dates" both scan every order ever placed. Done when they return exactly the same results but only touch the orders they need: O(k) for a customer with k orders, and proportional to the date range (plus a binary search) for best sellers. The tests count which stored orders each query touches, so a scan fails however fast it is.
- Stage 4 (stretch): cancel an order. Done when cancelling releases the stock, gives back the coupon use, refuses to cancel twice, and the cancelled order drops out of best sellers straight away, without bringing back the full scan.
The README in the download has the full rules for each stage, and the tests are the acceptance criteria:
test_existing.py passes from the start, and each test_stageN.py passes when that
stage is done. Run them with python3 -m unittest discover -s tests.
How to work this problem with an AI assistant
Spend the first 5-10 minutes reading, not prompting. Run the tests, then read
orders.py top to bottom: place_order is the spine of the codebase, and every
stage touches it. Then follow each call it makes into pricing.py, inventory.py
and repository.py. Skim models.py and errors.py for the vocabulary.
A good AI-assisted interview still starts with you knowing where things live.
Give the assistant the whole code path, not one file. If you paste only
inventory.py into a chat and ask why stock goes missing, you'll probably get a confident, wrong answer
about locking or negative stock. If you use an agent that can read the repo, point it at the path
explicitly. Good first prompts for this codebase:
-
"Trace
OrderService.place_orderfor a silver-tier customer ordering 4 croissants and 1 pumpkin pie (which is off the menu). List every function that runs, in order, and every change to inventory or the repository before the exception is raised." -
"Before writing any code: where should a coupon discount slot into
PricingEngine.quote, given the README's order of operations? What new fields and errors are needed, and which existing tests might be affected?" -
"What's the time complexity of
orders_for_customerandbest_sellersnow? Propose indexes that are maintained inadd(), and explain how they handle orders that arrive out of time order and orders that are already cancelled."
Verify everything the assistant writes. For each stage:
- Run that stage's tests and
test_existing.pyafter every change. Never let the assistant edit the tests to make them pass. - Work one example by hand (a coupon on a discounted order, say) and check the numbers match.
- Ask "what other inputs take this code path?" A fix for the reported case often misses its neighbours.
- Read every line of the diff and be ready to explain it. In the real round, the interviewer will ask why.
Self-check rubric
Here's what interviewers in AI-allowed rounds tend to look for. Be honest with yourself about which column you were in.
| Area | Strong signals | Weak signals |
|---|---|---|
| Understanding the codebase | Can sketch the path through place_order from memory. Spots that validation is spread across modules. Explains the bug in terms of the order of operations. |
Starts prompting before reading. Can't say which module a change belongs in. Treats each file in isolation. |
| Correctness | Fixes the cause, so every rejection path leaves stock alone. Gets the coupon order, rounding and caps right. Indexes give identical results, including edge cases (end of day, ties, cancelled history). | Fixes only the reported case. Clamps the total at zero instead of capping the coupon. Index that drops orders placed late on the end date. |
| Tests and verification | Runs the tests after each change, reads failures carefully, checks one example by hand, and asks what the tests don't cover. | Runs the tests once at the end. Accepts "all tests pass" without reading the diff. Edits tests to make them pass. |
| Code quality | Small, well-placed changes that match the existing style. Pricing stays side-effect free. The coupon rules live in one place. Indexes are documented with their complexity. | Copy-pasted validation in several places. Huge AI-generated rewrites of working code. Dead code left behind. |
| Use of AI | Gives the assistant the right context and constraints, asks for a plan before code, challenges its answers, and catches its mistakes. | Pastes the bug report and accepts the first patch. Can't explain the code the AI wrote. Lets it "fix" tests. |
| Communication | Narrates the plan, states assumptions (for example, "valid through the end of the expiry day"), and flags trade-offs like extra work on every write. | Works silently, or narrates only what the AI is doing. Doesn't mention trade-offs or what's left undone. |
Walkthrough
Show the walkthrough (spoilers)
Stage 1: stock goes missing after rejected orders
Root cause. place_order reserves stock first and prices the order second.
_reserve_stock really is all-or-nothing, but only for OutOfStockError raised
during reservation. Two other checks live in PricingEngine._price_line, which runs
after the stock is already reserved: "this product is off the menu"
(ProductUnavailableError) and "too many celebration cakes" (InvalidQuantityError).
When either fires, nothing puts the stock back. You only see this by reading
orders.py and pricing.py together.
Fix. Pricing has no side effects, so do every check that can reject the order before touching stock:
customer = self._customers.get(customer_id)
quantities = self._collect_quantities(items)
quote = self._pricing.quote(customer, quantities) # can reject; changes nothing
self._reserve_stock(quantities) # all-or-nothing
order = Order(...)
try:
self._repository.add(order)
except Exception:
self._release_stock(quantities.items())
raise
Pitfalls. Widening the except in _reserve_stock doesn't help: the
error is raised after that try block has finished. Checking on_menu inside the
reservation loop still leaks the lines reserved before the bad one, and misses the per-order limit.
Releasing in a finally block undoes successful orders too. And "release every line on any
error" puts back stock that was never reserved when the out-of-stock line fails, so stock goes up.
The stage 1 tests catch all four.
Weak prompt: "Stock goes down when orders fail. Fix inventory.py."
Strong prompt: "Here are orders.py, pricing.py and inventory.py. An order of 4 croissants
and a discontinued pumpkin pie is rejected, but croissant stock drops by 4. Trace the calls in
place_order and list every way an order can be rejected after stock is reserved. Then propose
the smallest change that makes all of them leave stock untouched."
Stage 2: coupon codes
Design. Keep three concerns apart. A small CouponBook (new
coupons.py) looks codes up (case-insensitive), checks expiry and the redemption limit, and
counts redemptions. PricingEngine.quote takes an optional coupon and works out the discount,
because the minimum and the percentage both depend on the subtotal after bulk discounts.
place_order looks the coupon up, prices, reserves, stores, and only then records the redemption.
def coupon_discount(coupon: Coupon, amount_cents: int) -> int:
if coupon.kind is CouponKind.PERCENT:
return percent_of(amount_cents, coupon.value) # rounds down
return min(coupon.value, amount_cents) # never below zero
# in PricingEngine.quote
after_items = subtotal - item_discounts
coupon_off = 0
if coupon is not None:
if after_items < coupon.min_subtotal_cents:
raise InvalidCouponError(...)
coupon_off = coupon_discount(coupon, after_items)
after_coupon = after_items - coupon_off
loyalty = percent_of(after_coupon, customer.loyalty_tier.percent_off)
total = after_coupon - loyalty
Pitfalls (all of them are things assistants plausibly write):
- Applying the loyalty discount before the coupon. With a percent coupon the total can come out the same, but the breakdown is wrong, and with a fixed coupon the total is wrong too.
- Checking the minimum against the gross subtotal, before bulk discounts.
- Expiring the coupon at midnight at the start of
expires_on. - Using
round(amount * pct / 100). That's a float, and Python rounds half to even, so 10% of 1975 gives 198 instead of 197. - Clamping the total at zero instead of capping the coupon, so the recorded discount is bigger than the order and the breakdown doesn't add up.
- Counting the redemption before the order succeeds, so an out-of-stock order uses up a one-time coupon.
Weak prompt: "Add coupon support to the order service."
Strong prompt: "Add coupons per the README's stage 2 rules (pasted below). First give me a
plan: where each rule is checked, the order of discounts, how a failed order avoids using up a redemption.
Don't write code until I've agreed the plan. Percentages must use the existing percent_of."
Stage 3: make the dashboard queries scale
Design. Do the work once, at write time, so reads are cheap:
-
For
orders_for_customer, a hash map from customer id to a sorted list of(placed_at, order_id).bisect.insortkeeps it sorted even when orders arrive out of time order, and ties fall back to the id. A query is O(k). -
For
best_sellers, a running aggregate: day toCounterof units per SKU, for placed orders only, plus a sorted list of the days that have sales. A query uses binary search to find the days in range and adds up only those counters. It never looks at an individual order.
def add(self, order: Order) -> None:
...
insort(self._by_customer.setdefault(order.customer_id, []), (order.placed_at, order.id))
if order.status is OrderStatus.PLACED:
self._count_units(order, +1)
def best_sellers(self, start: date, end: date, limit: int = 10):
if start > end:
return []
first = bisect_left(self._days, start)
last = bisect_right(self._days, end)
units = Counter()
for day in self._days[first:last]:
units.update(self._units_by_day[day])
return sorted(units.items(), key=lambda item: (-item[1], item[0]))[:limit]
A list of all orders sorted by time, searched with bisect, is also fine: it touches only the
orders in range. In a real database these are an index on (customer_id, placed_at) and a daily
rollup table. The trade-off to mention is that every write now does a little more work, and the aggregate has
to be kept consistent with the orders.
Pitfalls. Building the index lazily on the first query is still a full scan, just a
hidden one. When bisecting on datetimes, using midnight at the start of end as the upper bound
drops every order placed later that day. Counting cancelled orders imported from history.
Counter.most_common breaks ties by insertion order, not by SKU. And looping over every day of
history is still a scan, just a smaller one.
Weak prompt: "Make the repository faster."
Strong prompt: "Both queries in repository.py are O(n) in all orders. Design indexes
maintained in add() so orders_for_customer is O(k) and best_sellers
depends only on the date range. Results must be identical to the current code, including ties, the
inclusive end date and already-cancelled orders. Give the complexity of each operation before writing code."
Stage 4 (stretch): cancelling orders
Design. The stage 3 aggregate is derived state now: setting
order.status directly would leave best sellers wrong. So the repository owns the status change
and updates the aggregate in the same method, and the service handles stock and coupons. Check
"already cancelled" before any side effect.
# repository
def mark_cancelled(self, order_id: str) -> Order:
order = self.get(order_id)
if order.status is OrderStatus.CANCELLED:
raise OrderAlreadyCancelledError(order_id)
order.status = OrderStatus.CANCELLED
self._count_units(order, -1)
return order
# service
def cancel_order(self, order_id: str) -> Order:
order = self._repository.mark_cancelled(order_id)
self._release_stock((line.sku, line.quantity) for line in order.lines)
if order.coupon_code is not None:
self._coupons.unredeem(order.coupon_code)
return order
Pitfalls. Mutating the status behind the index's back. Releasing stock before the double-cancel check, so a second cancel adds stock that doesn't exist. Deleting the order instead of marking it, so it vanishes from the customer's history. Forgetting to give the coupon use back.
Weak prompt: "Add a cancel_order method."
Strong prompt: "Add cancel_order. Before coding, list every piece of state
that was changed when the order was placed (stock, coupon redemptions, the repository's indexes and
aggregates) and how each one gets reversed. Cancelling twice must change nothing."
Files in the starter repo
Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.
README.md 97 lines
# Crumb & Co. order service
Crumb & Co. is a small neighbourhood bakery. This is the order service behind its website and till: it
prices orders (bulk discounts and a loyalty programme), reserves stock from the day's bake, and stores
orders for the shop dashboard. You've just joined the team and you're picking up the next few tickets.
## Running the tests
Python 3.10 or newer, standard library only (nothing to install). From this folder:
python3 -m unittest discover -s tests
To run one stage: `python3 -m unittest discover -s tests -p "test_stage1.py"`
`tests/test_existing.py` covers behaviour that already works. It passes now; keep it passing.
Each `tests/test_stageN.py` fails until you finish that stage.
## Time box and rules
60-75 minutes. Do the stages in order. Stages 1-3 are the core; stage 4 is a stretch.
Use any editor and any AI assistant you like. In a real AI-allowed interview you'd be expected to explain
and verify everything the AI writes, so practice that too.
Change or add anything under `bakery/`, but don't edit the tests.
## The codebase
| Module | What it does |
|---|---|
| `bakery/models.py` | Dataclasses: `Product`, `Customer`, `LineItem`, `Order`, `Coupon` |
| `bakery/errors.py` | `OrderError` and its subclasses (the errors a customer sees) |
| `bakery/catalog.py` | The menu (`Catalog`) and the `CustomerDirectory` |
| `bakery/inventory.py` | Stock on hand: `reserve`, `release`, `restock` |
| `bakery/pricing.py` | `PricingEngine.quote`: line totals, bulk discounts, loyalty discount |
| `bakery/repository.py` | `InMemoryOrderRepository`: storage plus the dashboard queries |
| `bakery/orders.py` | `OrderService.place_order`: validate, reserve stock, price, store |
All money is integer cents. Percentages round down to a whole cent.
## Stage 1: BUG-112, stock goes missing after rejected orders
> From: Marta (shop manager)
>
> Since we took the pumpkin pie off the menu, our croissant count keeps drifting. This morning a customer
> tried to order 4 croissants and a pumpkin pie. The site correctly said the pie isn't available any more,
> and no order was created, but our croissant stock went from 20 to 16, and the 3 pies we still have in the
> back now show as 2. I think it happens with other rejected orders too, not just the pie.
Fix it so that a rejected order never changes stock. Successful orders must still reserve stock.
## Stage 2: coupon codes
Marketing wants coupon codes. The `Coupon` model already exists in `bakery/models.py`, but nothing uses it yet.
- `OrderService.add_coupon(coupon)` registers a coupon. Codes are unique, ignoring case: a duplicate raises `ValueError`.
- `OrderService.place_order(..., coupon_code=None)` takes at most one code. Codes match ignoring case and
surrounding spaces (`" spring10 "` uses `SPRING10`). A string with two codes in it is just an unknown code.
- Pricing order: bulk discounts first, then the coupon on the subtotal after bulk discounts, then the loyalty
discount on what's left after the coupon.
- `PERCENT` coupons take `value`% of that amount, rounded down to a whole cent.
- `FIXED` coupons take `value` cents, but never more than the amount they apply to: a coupon can't make a
total negative.
- Reject the order with a new `InvalidCouponError` (in `bakery/errors.py`, a subclass of `OrderError`) if the
code is unknown, the coupon has expired (it's valid through the end of the `expires_on` day, compared with
`placed_at`), the subtotal after bulk discounts is below `min_subtotal_cents`, or the coupon has already
been used `max_redemptions` times.
- A rejected order changes nothing: no stock reserved, no coupon use counted, nothing stored.
- `Order` gets two new fields: `coupon_code` (the code as it was registered, or `None`) and
`coupon_discount_cents` (0 without a coupon). It must always hold that
`subtotal - item discount - coupon discount - loyalty discount == total`.
- `OrderService.coupon_redemptions(code)` returns how many placed orders used that coupon.
## Stage 3: make the dashboard queries scale
The dashboard is getting slow. `orders_for_customer` and `best_sellers` in `bakery/repository.py` look at
every order ever placed, on every call. Make them cheap enough for years of history:
- `orders_for_customer(customer_id)`: O(k) for a customer with k orders (O(k log k) is fine).
- `best_sellers(start, end, limit)`: proportional to what's in the date range, plus a binary search, not to
the whole history (no loop over every order, or over every day ever).
- Keep your indexes up to date in `add()`, not lazily at query time. Orders can arrive out of time order
(phone orders get back-entered later), and imported history can include orders that are already cancelled.
- The results mustn't change. `test_existing.py` pins the current behaviour: oldest first with ties broken by
order id; an inclusive date range; ties broken by SKU; cancelled orders don't count as sales.
The stage 3 tests store 4,000 orders and record which ones the repository touches while it answers a
query. Touching every order fails, however quick it is.
## Stage 4 (stretch): cancelling orders
- `OrderService.cancel_order(order_id)` returns the cancelled order: its status is `CANCELLED`, every line's
stock is released, and its coupon use is given back (so a one-use coupon can be used again).
- An unknown id raises `OrderNotFoundError`. Cancelling an order that's already cancelled raises an
`OrderError` (for example a new `OrderAlreadyCancelledError`) and changes nothing.
- Cancelled orders stay in `orders_for_customer` (with their new status) but drop out of `best_sellers`
straight away, without bringing back the full scan.
bakery/__init__.py 13 lines
"""Order service for Crumb & Co., a small neighbourhood bakery.
Modules:
models products, customers, orders, coupons (plain dataclasses)
errors exceptions shown to customers when an order is rejected
catalog the menu (products) and the customer directory
inventory stock on hand, and reserving/releasing it
pricing line totals, bulk discounts and loyalty discounts
repository in-memory order storage and reporting queries
orders OrderService: validate, price, reserve and store an order
All money is integer cents.
"""
bakery/catalog.py 54 lines
"""The menu (products by SKU) and the customer directory."""
from __future__ import annotations
from dataclasses import replace
from typing import Iterable
from bakery.errors import UnknownCustomerError, UnknownProductError
from bakery.models import Customer, Product
class Catalog:
"""Every product the bakery has ever sold, including discontinued ones.
Discontinued products stay in the catalog (old orders refer to them) but
have on_menu=False.
"""
def __init__(self, products: Iterable[Product] = ()) -> None:
self._products: dict[str, Product] = {}
for product in products:
self.add(product)
def add(self, product: Product) -> None:
if product.price_cents < 0:
raise ValueError(f"{product.sku}: price can't be negative")
self._products[product.sku] = product
def get(self, sku: str) -> Product:
try:
return self._products[sku]
except KeyError:
raise UnknownProductError(f"no product with SKU {sku!r}") from None
def discontinue(self, sku: str) -> None:
"""Take a product off the menu. It stays in the catalog for old orders."""
self._products[sku] = replace(self.get(sku), on_menu=False)
def menu(self) -> list[Product]:
return [p for p in self._products.values() if p.on_menu]
class CustomerDirectory:
def __init__(self, customers: Iterable[Customer] = ()) -> None:
self._customers: dict[str, Customer] = {c.id: c for c in customers}
def add(self, customer: Customer) -> None:
self._customers[customer.id] = customer
def get(self, customer_id: str) -> Customer:
try:
return self._customers[customer_id]
except KeyError:
raise UnknownCustomerError(f"no customer with id {customer_id!r}") from None
bakery/errors.py 43 lines
"""Exceptions raised when an order can't be placed.
Everything a customer might see subclasses OrderError, so the web layer can
catch OrderError and show the message.
"""
from __future__ import annotations
class OrderError(Exception):
"""Base class for order problems we report back to the customer."""
class UnknownCustomerError(OrderError):
pass
class UnknownProductError(OrderError):
pass
class ProductUnavailableError(OrderError):
"""The product exists but is no longer on the menu."""
class InvalidQuantityError(OrderError):
pass
class EmptyOrderError(OrderError):
pass
class OutOfStockError(OrderError):
def __init__(self, sku: str, requested: int, available: int) -> None:
super().__init__(f"only {available} of {sku} left (asked for {requested})")
self.sku = sku
self.requested = requested
self.available = available
class OrderNotFoundError(OrderError):
pass
bakery/inventory.py 48 lines
"""Stock on hand.
Placing an order reserves stock straight away (the bakery bakes to a fixed
plan, so stock is the number of items still available to sell today).
"""
from __future__ import annotations
from typing import Mapping
from bakery.errors import OutOfStockError
class Inventory:
def __init__(self, stock: Mapping[str, int] | None = None) -> None:
self._on_hand: dict[str, int] = {}
for sku, quantity in (stock or {}).items():
self.restock(sku, quantity)
def on_hand(self, sku: str) -> int:
return self._on_hand.get(sku, 0)
def restock(self, sku: str, quantity: int) -> None:
if quantity < 0:
raise ValueError("can't restock a negative quantity")
self._on_hand[sku] = self.on_hand(sku) + quantity
def reserve(self, sku: str, quantity: int) -> None:
"""Take `quantity` of `sku` out of stock, or raise OutOfStockError and change nothing."""
if quantity <= 0:
raise ValueError("can only reserve a positive quantity")
available = self.on_hand(sku)
if available < quantity:
raise OutOfStockError(sku, requested=quantity, available=available)
self._on_hand[sku] = available - quantity
def release(self, sku: str, quantity: int) -> None:
"""Put previously reserved stock back."""
if quantity <= 0:
raise ValueError("can only release a positive quantity")
self._on_hand[sku] = self.on_hand(sku) + quantity
def snapshot(self) -> dict[str, int]:
return dict(self._on_hand)
def low_stock(self, threshold: int) -> list[str]:
"""SKUs with fewer than `threshold` items left, for the morning bake plan."""
return sorted(sku for sku, qty in self._on_hand.items() if qty < threshold)
bakery/models.py 130 lines
"""Domain models for the bakery order service.
Money is always an integer number of cents. Never use floats for money.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from enum import Enum
class LoyaltyTier(Enum):
"""Loyalty programme tiers. The value is the percent off the order."""
NONE = 0
SILVER = 5
GOLD = 10
@property
def percent_off(self) -> int:
return self.value
@dataclass(frozen=True)
class BulkDiscount:
"""Percent off a line when the customer buys at least `min_quantity` of one product."""
min_quantity: int
percent_off: int
@dataclass(frozen=True)
class Product:
sku: str
name: str
price_cents: int
category: str = "pastry"
on_menu: bool = True
bulk_discount: BulkDiscount | None = None
# Celebration cakes need notice, so the kitchen caps how many go in one order.
max_per_order: int | None = None
@dataclass(frozen=True)
class Customer:
id: str
name: str
loyalty_tier: LoyaltyTier = LoyaltyTier.NONE
@dataclass(frozen=True)
class LineItem:
"""One product in an order, after duplicate SKUs have been merged."""
sku: str
name: str
quantity: int
unit_price_cents: int
discount_cents: int = 0
@property
def gross_cents(self) -> int:
return self.unit_price_cents * self.quantity
@property
def net_cents(self) -> int:
return self.gross_cents - self.discount_cents
class OrderStatus(Enum):
PLACED = "placed"
CANCELLED = "cancelled"
@dataclass
class Order:
"""A stored order.
subtotal_cents is before any discounts, and
total = subtotal - item discounts - loyalty discount.
"""
id: str
customer_id: str
placed_at: datetime
lines: tuple[LineItem, ...]
subtotal_cents: int
item_discount_cents: int
loyalty_discount_cents: int
total_cents: int
status: OrderStatus = OrderStatus.PLACED
@property
def units(self) -> int:
return sum(line.quantity for line in self.lines)
class CouponKind(Enum):
PERCENT = "percent"
FIXED = "fixed"
@dataclass(frozen=True)
class Coupon:
"""A coupon code from the marketing team.
Not wired into pricing or ordering yet (see README, stage 2).
value is a percent (1-100) for PERCENT coupons and an amount in cents for
FIXED coupons. A coupon is valid through the end of the `expires_on` day.
max_redemptions=None means unlimited.
"""
code: str
kind: CouponKind
value: int
expires_on: date
min_subtotal_cents: int = 0
max_redemptions: int | None = None
def __post_init__(self) -> None:
if not self.code.strip():
raise ValueError("coupon code can't be blank")
if self.kind is CouponKind.PERCENT and not 1 <= self.value <= 100:
raise ValueError("percent coupons must be between 1 and 100")
if self.kind is CouponKind.FIXED and self.value <= 0:
raise ValueError("fixed coupons must be worth at least 1 cent")
if self.max_redemptions is not None and self.max_redemptions < 1:
raise ValueError("max_redemptions must be at least 1 (or None)")
bakery/orders.py 87 lines
"""Placing orders: validate, reserve stock, price, store."""
from __future__ import annotations
import itertools
from datetime import datetime
from typing import Iterable
from bakery.catalog import Catalog, CustomerDirectory
from bakery.errors import EmptyOrderError, InvalidQuantityError, OutOfStockError
from bakery.inventory import Inventory
from bakery.models import Order
from bakery.pricing import PricingEngine
from bakery.repository import InMemoryOrderRepository
class OrderService:
def __init__(
self,
catalog: Catalog,
customers: CustomerDirectory,
inventory: Inventory,
repository: InMemoryOrderRepository,
) -> None:
self._catalog = catalog
self._customers = customers
self._inventory = inventory
self._repository = repository
self._pricing = PricingEngine(catalog)
self._order_numbers = itertools.count(1)
def place_order(
self,
customer_id: str,
items: Iterable[tuple[str, int]],
*,
placed_at: datetime,
) -> Order:
"""Place an order for `items`, a list of (sku, quantity) pairs.
Either the whole order goes through, or it raises an OrderError.
"""
customer = self._customers.get(customer_id)
quantities = self._collect_quantities(items)
self._reserve_stock(quantities)
quote = self._pricing.quote(customer, quantities)
order = Order(
id=self._next_order_id(),
customer_id=customer.id,
placed_at=placed_at,
lines=quote.lines,
subtotal_cents=quote.subtotal_cents,
item_discount_cents=quote.item_discount_cents,
loyalty_discount_cents=quote.loyalty_discount_cents,
total_cents=quote.total_cents,
)
self._repository.add(order)
return order
def _collect_quantities(self, items: Iterable[tuple[str, int]]) -> dict[str, int]:
"""Check each requested line and merge repeated SKUs (keeping first-seen order)."""
quantities: dict[str, int] = {}
for sku, quantity in items:
if quantity <= 0:
raise InvalidQuantityError(f"quantity for {sku} must be at least 1")
self._catalog.get(sku) # raises UnknownProductError for typos
quantities[sku] = quantities.get(sku, 0) + quantity
if not quantities:
raise EmptyOrderError("an order needs at least one item")
return quantities
def _reserve_stock(self, quantities: dict[str, int]) -> None:
"""Reserve every line, or none of them."""
reserved: list[tuple[str, int]] = []
try:
for sku, quantity in quantities.items():
self._inventory.reserve(sku, quantity)
reserved.append((sku, quantity))
except OutOfStockError:
for sku, quantity in reserved:
self._inventory.release(sku, quantity)
raise
def _next_order_id(self) -> str:
return f"ord-{next(self._order_numbers):05d}"
bakery/pricing.py 73 lines
"""Pricing: line totals, bulk (per-item) discounts and the loyalty discount.
Order of operations, as agreed with the owner:
1. gross line totals (unit price x quantity)
2. bulk discounts, per line
3. the loyalty discount, on what's left after the bulk discounts
Percentages always round down to a whole cent (the bakery keeps the fraction).
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Mapping
from bakery.catalog import Catalog
from bakery.errors import InvalidQuantityError, ProductUnavailableError
from bakery.models import Customer, LineItem
def percent_of(amount_cents: int, percent: int) -> int:
"""`percent`% of `amount_cents`, rounded down to a whole cent."""
return amount_cents * percent // 100
@dataclass(frozen=True)
class Quote:
lines: tuple[LineItem, ...]
subtotal_cents: int
item_discount_cents: int
loyalty_discount_cents: int
total_cents: int
class PricingEngine:
def __init__(self, catalog: Catalog) -> None:
self._catalog = catalog
def quote(self, customer: Customer, quantities: Mapping[str, int]) -> Quote:
"""Price an order. `quantities` maps SKU -> quantity, in the order the customer listed them."""
lines = tuple(self._price_line(sku, qty) for sku, qty in quantities.items())
subtotal = sum(line.gross_cents for line in lines)
item_discounts = sum(line.discount_cents for line in lines)
after_items = subtotal - item_discounts
loyalty = percent_of(after_items, customer.loyalty_tier.percent_off)
return Quote(
lines=lines,
subtotal_cents=subtotal,
item_discount_cents=item_discounts,
loyalty_discount_cents=loyalty,
total_cents=after_items - loyalty,
)
def _price_line(self, sku: str, quantity: int) -> LineItem:
product = self._catalog.get(sku)
if not product.on_menu:
raise ProductUnavailableError(f"{product.name} is no longer on the menu")
if product.max_per_order is not None and quantity > product.max_per_order:
raise InvalidQuantityError(
f"we can only take {product.max_per_order} {product.name} per order"
)
gross = product.price_cents * quantity
discount = 0
bulk = product.bulk_discount
if bulk is not None and quantity >= bulk.min_quantity:
discount = percent_of(gross, bulk.percent_off)
return LineItem(
sku=sku,
name=product.name,
quantity=quantity,
unit_price_cents=product.price_cents,
discount_cents=discount,
)
bakery/repository.py 55 lines
"""In-memory order storage, standing in for the real database.
The reporting queries here back the shop dashboard ("this customer's
orders", "what sold best last week").
"""
from __future__ import annotations
from collections import Counter
from datetime import date
from bakery.errors import OrderNotFoundError
from bakery.models import Order, OrderStatus
class InMemoryOrderRepository:
def __init__(self) -> None:
self._orders: dict[str, Order] = {}
def __len__(self) -> int:
return len(self._orders)
def add(self, order: Order) -> None:
if order.id in self._orders:
raise ValueError(f"order {order.id} already exists")
self._orders[order.id] = order
def get(self, order_id: str) -> Order:
try:
return self._orders[order_id]
except KeyError:
raise OrderNotFoundError(f"no order with id {order_id!r}") from None
def orders_for_customer(self, customer_id: str) -> list[Order]:
"""All of a customer's orders (any status), oldest first, ties broken by order id."""
matches = [o for o in self._orders.values() if o.customer_id == customer_id]
matches.sort(key=lambda o: (o.placed_at, o.id))
return matches
def best_sellers(self, start: date, end: date, limit: int = 10) -> list[tuple[str, int]]:
"""Top SKUs by units sold in PLACED orders from `start` to `end`, inclusive.
Returns (sku, units) pairs, most units first, ties broken by SKU.
"""
if start > end:
return []
units: Counter[str] = Counter()
for order in self._orders.values():
if order.status is not OrderStatus.PLACED:
continue
if start <= order.placed_at.date() <= end:
for line in order.lines:
units[line.sku] += line.quantity
ranked = sorted(units.items(), key=lambda item: (-item[1], item[0]))
return ranked[:limit]
tests/test_existing.py 248 lines
"""Behaviour that already works. Keep these passing while you change things."""
import unittest
from datetime import date, datetime
from bakery.catalog import Catalog, CustomerDirectory
from bakery.errors import (
EmptyOrderError,
InvalidQuantityError,
OrderError,
OrderNotFoundError,
OutOfStockError,
ProductUnavailableError,
UnknownCustomerError,
UnknownProductError,
)
from bakery.inventory import Inventory
from bakery.models import (
BulkDiscount,
Customer,
LineItem,
LoyaltyTier,
Order,
OrderStatus,
Product,
)
from bakery.orders import OrderService
from bakery.pricing import percent_of
from bakery.repository import InMemoryOrderRepository
PRODUCTS = [
Product("croissant", "Butter croissant", 375),
Product("cupcake", "Vanilla cupcake", 350, bulk_discount=BulkDiscount(6, 15)),
Product("sourdough", "Sourdough loaf", 800, category="bread"),
Product("macaron", "Pistachio macaron", 250, bulk_discount=BulkDiscount(12, 20)),
Product("brownie", "Fudge brownie", 300),
Product("pumpkin-pie", "Pumpkin pie", 2400, category="pie", on_menu=False),
Product("celebration-cake", "Celebration cake", 4500, category="cake", max_per_order=2),
]
CUSTOMERS = [
Customer("ana", "Ana"),
Customer("ben", "Ben", LoyaltyTier.SILVER),
Customer("gia", "Gia", LoyaltyTier.GOLD),
]
STOCK = {
"croissant": 20,
"cupcake": 24,
"sourdough": 10,
"macaron": 36,
"brownie": 15,
"pumpkin-pie": 3,
"celebration-cake": 4,
}
MORNING = datetime(2026, 4, 10, 9, 30)
class OrderServiceTestCase(unittest.TestCase):
def setUp(self):
self.catalog = Catalog(PRODUCTS)
self.inventory = Inventory(STOCK)
self.repo = InMemoryOrderRepository()
self.service = OrderService(
self.catalog, CustomerDirectory(CUSTOMERS), self.inventory, self.repo
)
def place(self, customer_id, items, placed_at=MORNING):
return self.service.place_order(customer_id, items, placed_at=placed_at)
class TestPlacingOrders(OrderServiceTestCase):
def test_simple_order_is_priced_stored_and_reserved(self):
order = self.place("ana", [("croissant", 2), ("sourdough", 1)])
self.assertEqual(order.id, "ord-00001")
self.assertEqual([line.sku for line in order.lines], ["croissant", "sourdough"])
self.assertEqual(order.subtotal_cents, 1550)
self.assertEqual(order.item_discount_cents, 0)
self.assertEqual(order.loyalty_discount_cents, 0)
self.assertEqual(order.total_cents, 1550)
self.assertEqual(order.status, OrderStatus.PLACED)
self.assertIs(self.repo.get(order.id), order)
self.assertEqual(self.inventory.on_hand("croissant"), 18)
self.assertEqual(self.inventory.on_hand("sourdough"), 9)
def test_order_ids_increase(self):
first = self.place("ana", [("brownie", 1)])
second = self.place("ben", [("brownie", 1)])
self.assertEqual((first.id, second.id), ("ord-00001", "ord-00002"))
def test_bulk_discount_applies_at_minimum_quantity(self):
order = self.place("ana", [("cupcake", 6)])
self.assertEqual(order.subtotal_cents, 2100)
self.assertEqual(order.item_discount_cents, 315)
self.assertEqual(order.total_cents, 1785)
def test_no_bulk_discount_below_minimum(self):
order = self.place("ana", [("cupcake", 5)])
self.assertEqual(order.item_discount_cents, 0)
self.assertEqual(order.total_cents, 1750)
def test_repeated_skus_are_merged_before_discounts(self):
order = self.place("ana", [("cupcake", 3), ("croissant", 1), ("cupcake", 3)])
self.assertEqual([(l.sku, l.quantity) for l in order.lines], [("cupcake", 6), ("croissant", 1)])
self.assertEqual(order.item_discount_cents, 315)
self.assertEqual(self.inventory.on_hand("cupcake"), 18)
def test_loyalty_discount_is_on_the_amount_after_item_discounts(self):
order = self.place("ben", [("cupcake", 6), ("sourdough", 1)])
self.assertEqual(order.subtotal_cents, 2900)
self.assertEqual(order.item_discount_cents, 315)
self.assertEqual(order.loyalty_discount_cents, 129) # 5% of 2585, rounded down
self.assertEqual(order.total_cents, 2456)
def test_loyalty_discount_rounds_down(self):
order = self.place("gia", [("croissant", 1)])
self.assertEqual(order.loyalty_discount_cents, 37)
self.assertEqual(order.total_cents, 338)
def test_line_items_record_prices(self):
order = self.place("ana", [("macaron", 12)])
(line,) = order.lines
self.assertEqual(line, LineItem("macaron", "Pistachio macaron", 12, 250, 600))
self.assertEqual(line.net_cents, 2400)
self.assertEqual(order.units, 12)
class TestRejectedOrders(OrderServiceTestCase):
def test_out_of_stock_rejects_the_whole_order(self):
with self.assertRaises(OutOfStockError) as caught:
self.place("ana", [("croissant", 5), ("sourdough", 11)])
self.assertEqual(caught.exception.available, 10)
self.assertEqual(self.inventory.snapshot(), STOCK)
self.assertEqual(len(self.repo), 0)
def test_unknown_product(self):
with self.assertRaises(UnknownProductError):
self.place("ana", [("croissant", 1), ("croisant", 1)])
self.assertEqual(self.inventory.snapshot(), STOCK)
def test_bad_quantities_and_empty_orders(self):
with self.assertRaises(InvalidQuantityError):
self.place("ana", [("croissant", 0)])
with self.assertRaises(EmptyOrderError):
self.place("ana", [])
self.assertEqual(len(self.repo), 0)
def test_unknown_customer(self):
with self.assertRaises(UnknownCustomerError):
self.place("zed", [("croissant", 1)])
def test_discontinued_products_are_rejected(self):
with self.assertRaises(ProductUnavailableError):
self.place("ana", [("pumpkin-pie", 1)])
self.assertEqual(len(self.repo), 0)
def test_per_order_limit(self):
with self.assertRaises(InvalidQuantityError):
self.place("ana", [("celebration-cake", 3)])
self.assertEqual(len(self.repo), 0)
def test_up_to_the_per_order_limit_is_fine(self):
order = self.place("ana", [("celebration-cake", 2)])
self.assertEqual(order.total_cents, 9000)
def test_all_customer_facing_errors_are_order_errors(self):
for error in (OutOfStockError, UnknownProductError, ProductUnavailableError,
InvalidQuantityError, EmptyOrderError, UnknownCustomerError):
self.assertTrue(issubclass(error, OrderError), error)
def stored_order(order_id, customer_id, placed_at, lines, status=OrderStatus.PLACED):
line_items = tuple(LineItem(sku, sku, qty, 100) for sku, qty in lines)
total = sum(line.gross_cents for line in line_items)
return Order(
id=order_id,
customer_id=customer_id,
placed_at=placed_at,
lines=line_items,
subtotal_cents=total,
item_discount_cents=0,
loyalty_discount_cents=0,
total_cents=total,
status=status,
)
class TestRepository(unittest.TestCase):
def setUp(self):
self.repo = InMemoryOrderRepository()
# Added out of time order on purpose: phone orders get back-entered.
self.repo.add(stored_order("o-3", "ana", datetime(2026, 3, 9, 8, 0), [("cupcake", 2)]))
self.repo.add(stored_order("o-1", "ana", datetime(2026, 3, 2, 16, 45), [("croissant", 3)]))
self.repo.add(stored_order("o-2", "ben", datetime(2026, 3, 3, 12, 0), [("croissant", 1), ("cupcake", 4)]))
self.repo.add(stored_order("o-5", "ana", datetime(2026, 3, 9, 8, 0), [("brownie", 1)]))
self.repo.add(stored_order("o-4", "gia", datetime(2026, 3, 8, 23, 59, 59), [("brownie", 4)]))
self.repo.add(stored_order("o-6", "gia", datetime(2026, 3, 4, 10, 0), [("sourdough", 9)],
status=OrderStatus.CANCELLED))
def test_get_and_missing_orders(self):
self.assertEqual(self.repo.get("o-2").customer_id, "ben")
with self.assertRaises(OrderNotFoundError):
self.repo.get("nope")
with self.assertRaises(ValueError):
self.repo.add(stored_order("o-2", "ben", datetime(2026, 3, 3), [("brownie", 1)]))
def test_orders_for_customer_oldest_first_ties_by_id(self):
self.assertEqual([o.id for o in self.repo.orders_for_customer("ana")], ["o-1", "o-3", "o-5"])
self.assertEqual([o.id for o in self.repo.orders_for_customer("gia")], ["o-6", "o-4"])
self.assertEqual(self.repo.orders_for_customer("nobody"), [])
def test_best_sellers_inclusive_range_skips_cancelled(self):
# o-4 at 23:59:59 on the 8th counts; o-6 is cancelled; three-way tie, so by SKU.
self.assertEqual(self.repo.best_sellers(date(2026, 3, 2), date(2026, 3, 8)),
[("brownie", 4), ("croissant", 4), ("cupcake", 4)])
self.assertEqual(self.repo.best_sellers(date(2026, 3, 9), date(2026, 3, 9)),
[("cupcake", 2), ("brownie", 1)])
def test_best_sellers_limit_and_empty_ranges(self):
self.assertEqual(self.repo.best_sellers(date(2026, 3, 1), date(2026, 3, 31), limit=2),
[("cupcake", 6), ("brownie", 5)])
self.assertEqual(self.repo.best_sellers(date(2026, 4, 1), date(2026, 4, 30)), [])
self.assertEqual(self.repo.best_sellers(date(2026, 3, 9), date(2026, 3, 1)), [])
class TestBuildingBlocks(unittest.TestCase):
def test_percent_of_rounds_down(self):
self.assertEqual(percent_of(1975, 10), 197)
self.assertEqual(percent_of(999, 5), 49)
self.assertEqual(percent_of(0, 50), 0)
def test_inventory(self):
inventory = Inventory({"brownie": 2})
inventory.reserve("brownie", 2)
with self.assertRaises(OutOfStockError):
inventory.reserve("brownie", 1)
inventory.release("brownie", 1)
inventory.restock("cupcake", 5)
self.assertEqual(inventory.snapshot(), {"brownie": 1, "cupcake": 5})
self.assertEqual(inventory.low_stock(3), ["brownie"])
def test_discontinue_keeps_product_in_catalog(self):
catalog = Catalog(PRODUCTS)
catalog.discontinue("brownie")
self.assertFalse(catalog.get("brownie").on_menu)
self.assertNotIn("brownie", [p.sku for p in catalog.menu()])
if __name__ == "__main__":
unittest.main()
tests/test_stage1.py 99 lines
"""Stage 1: BUG-112, stock goes missing after rejected orders (see README)."""
import unittest
from datetime import datetime
from bakery.catalog import Catalog, CustomerDirectory
from bakery.errors import InvalidQuantityError, OutOfStockError, ProductUnavailableError
from bakery.inventory import Inventory
from bakery.models import BulkDiscount, Customer, LoyaltyTier, Product
from bakery.orders import OrderService
from bakery.repository import InMemoryOrderRepository
PRODUCTS = [
Product("croissant", "Butter croissant", 375),
Product("cupcake", "Vanilla cupcake", 350, bulk_discount=BulkDiscount(6, 15)),
Product("sourdough", "Sourdough loaf", 800, category="bread"),
Product("brownie", "Fudge brownie", 300),
Product("pumpkin-pie", "Pumpkin pie", 2400, category="pie", on_menu=False),
Product("celebration-cake", "Celebration cake", 4500, category="cake", max_per_order=2),
]
CUSTOMERS = [Customer("ana", "Ana"), Customer("ben", "Ben", LoyaltyTier.SILVER)]
STOCK = {
"croissant": 20,
"cupcake": 24,
"sourdough": 10,
"brownie": 15,
"pumpkin-pie": 3,
"celebration-cake": 4,
}
MORNING = datetime(2026, 12, 2, 9, 30)
class TestRejectedOrdersLeaveStockAlone(unittest.TestCase):
def setUp(self):
self.inventory = Inventory(STOCK)
self.repo = InMemoryOrderRepository()
self.service = OrderService(
Catalog(PRODUCTS), CustomerDirectory(CUSTOMERS), self.inventory, self.repo
)
def place(self, customer_id, items):
return self.service.place_order(customer_id, items, placed_at=MORNING)
def assert_stock_untouched(self):
self.assertEqual(self.inventory.snapshot(), STOCK)
self.assertEqual(len(self.repo), 0)
def test_the_reported_case_croissants_and_a_discontinued_pie(self):
with self.assertRaises(ProductUnavailableError):
self.place("ana", [("croissant", 4), ("pumpkin-pie", 1)])
self.assertEqual(self.inventory.on_hand("croissant"), 20)
self.assertEqual(self.inventory.on_hand("pumpkin-pie"), 3)
self.assert_stock_untouched()
def test_discontinued_item_listed_first(self):
with self.assertRaises(ProductUnavailableError):
self.place("ben", [("pumpkin-pie", 1), ("croissant", 4), ("cupcake", 6)])
self.assert_stock_untouched()
def test_over_the_per_order_limit(self):
with self.assertRaises(InvalidQuantityError):
self.place("ana", [("croissant", 2), ("sourdough", 1), ("celebration-cake", 3)])
self.assert_stock_untouched()
def test_next_customer_can_buy_everything_after_a_rejection(self):
with self.assertRaises(ProductUnavailableError):
self.place("ana", [("croissant", 4), ("pumpkin-pie", 1)])
order = self.place("ben", [("croissant", 20)])
self.assertEqual(order.units, 20)
self.assertEqual(self.inventory.on_hand("croissant"), 0)
def test_out_of_stock_still_rolls_back_without_inflating_stock(self):
with self.assertRaises(OutOfStockError):
self.place("ana", [("croissant", 4), ("sourdough", 11), ("brownie", 2)])
self.assert_stock_untouched()
def test_successful_orders_still_reserve_stock(self):
self.place("ana", [("croissant", 4), ("cupcake", 6)])
self.place("ben", [("croissant", 1), ("celebration-cake", 2)])
self.assertEqual(self.inventory.on_hand("croissant"), 15)
self.assertEqual(self.inventory.on_hand("cupcake"), 18)
self.assertEqual(self.inventory.on_hand("celebration-cake"), 2)
self.assertEqual(len(self.repo), 2)
def test_mix_of_rejections_then_success(self):
for bad in (
[("croissant", 3), ("pumpkin-pie", 2)],
[("brownie", 5), ("celebration-cake", 9)],
[("cupcake", 6), ("sourdough", 50)],
):
with self.assertRaises((ProductUnavailableError, InvalidQuantityError, OutOfStockError)):
self.place("ana", bad)
self.assert_stock_untouched()
order = self.place("ana", [("brownie", 15), ("cupcake", 24)])
self.assertEqual(order.units, 39)
if __name__ == "__main__":
unittest.main()
tests/test_stage2.py 174 lines
"""Stage 2: coupon codes (see README for the rules)."""
import unittest
from datetime import date, datetime
import bakery.errors as errors
from bakery.catalog import Catalog, CustomerDirectory
from bakery.inventory import Inventory
from bakery.models import BulkDiscount, Coupon, CouponKind, Customer, LoyaltyTier, Product
from bakery.orders import OrderService
from bakery.repository import InMemoryOrderRepository
PRODUCTS = [
Product("croissant", "Butter croissant", 375),
Product("cupcake", "Vanilla cupcake", 350, bulk_discount=BulkDiscount(6, 15)),
Product("sourdough", "Sourdough loaf", 800, category="bread"),
Product("macaron", "Pistachio macaron", 250, bulk_discount=BulkDiscount(12, 20)),
Product("brownie", "Fudge brownie", 300),
Product("pumpkin-pie", "Pumpkin pie", 2400, category="pie", on_menu=False),
]
CUSTOMERS = [
Customer("ana", "Ana"),
Customer("ben", "Ben", LoyaltyTier.SILVER),
Customer("gia", "Gia", LoyaltyTier.GOLD),
]
STOCK = {"croissant": 20, "cupcake": 24, "sourdough": 10, "macaron": 36, "brownie": 15, "pumpkin-pie": 3}
COUPONS = [
Coupon("SPRING10", CouponKind.PERCENT, 10, expires_on=date(2026, 4, 30), min_subtotal_cents=2000),
Coupon("FIVEOFF", CouponKind.FIXED, 500, expires_on=date(2026, 12, 31)),
Coupon("BIGTREAT", CouponKind.FIXED, 2000, expires_on=date(2026, 12, 31)),
Coupon("TEN", CouponKind.PERCENT, 10, expires_on=date(2026, 12, 31)),
Coupon("ONCE", CouponKind.PERCENT, 20, expires_on=date(2026, 12, 31), max_redemptions=1),
]
APRIL = datetime(2026, 4, 10, 9, 30)
class CouponTestCase(unittest.TestCase):
def setUp(self):
self.inventory = Inventory(STOCK)
self.repo = InMemoryOrderRepository()
self.service = OrderService(
Catalog(PRODUCTS), CustomerDirectory(CUSTOMERS), self.inventory, self.repo
)
for coupon in COUPONS:
self.service.add_coupon(coupon)
def place(self, customer_id, items, coupon_code=None, placed_at=APRIL):
order = self.service.place_order(
customer_id, items, placed_at=placed_at, coupon_code=coupon_code
)
self.assert_adds_up(order)
return order
def assert_adds_up(self, order):
self.assertGreaterEqual(order.total_cents, 0)
self.assertGreaterEqual(order.coupon_discount_cents, 0)
self.assertEqual(
order.subtotal_cents
- order.item_discount_cents
- order.coupon_discount_cents
- order.loyalty_discount_cents,
order.total_cents,
)
def assert_rejected(self, customer_id, items, coupon_code, placed_at=APRIL):
before = self.inventory.snapshot()
orders_before = len(self.repo)
with self.assertRaises(errors.InvalidCouponError):
self.service.place_order(customer_id, items, placed_at=placed_at, coupon_code=coupon_code)
self.assertEqual(self.inventory.snapshot(), before, "a rejected coupon must not touch stock")
self.assertEqual(len(self.repo), orders_before)
class TestCouponPricing(CouponTestCase):
def test_percent_coupon_comes_after_item_discounts_and_before_loyalty(self):
order = self.place("ben", [("cupcake", 6), ("sourdough", 1)], "SPRING10")
self.assertEqual(order.subtotal_cents, 2900)
self.assertEqual(order.item_discount_cents, 315)
self.assertEqual(order.coupon_discount_cents, 258) # 10% of 2585, rounded down
self.assertEqual(order.loyalty_discount_cents, 116) # 5% of 2327, rounded down
self.assertEqual(order.total_cents, 2211)
self.assertEqual(order.coupon_code, "SPRING10")
def test_fixed_coupon_then_loyalty(self):
order = self.place("gia", [("croissant", 4), ("sourdough", 2)], "FIVEOFF")
self.assertEqual(order.coupon_discount_cents, 500)
self.assertEqual(order.loyalty_discount_cents, 260)
self.assertEqual(order.total_cents, 2340)
def test_percent_coupon_rounds_down(self):
order = self.place("ana", [("croissant", 1), ("sourdough", 1), ("brownie", 1), ("macaron", 2)], "TEN")
self.assertEqual(order.coupon_discount_cents, 197) # 10% of 1975
self.assertEqual(order.total_cents, 1778)
def test_fixed_coupon_never_makes_the_total_negative(self):
small = self.place("gia", [("croissant", 1)], "BIGTREAT")
self.assertEqual(small.coupon_discount_cents, 375)
self.assertEqual(small.loyalty_discount_cents, 0)
self.assertEqual(small.total_cents, 0)
discounted = self.place("ana", [("cupcake", 6)], "BIGTREAT")
self.assertEqual(discounted.coupon_discount_cents, 1785)
self.assertEqual(discounted.total_cents, 0)
def test_codes_ignore_case_and_surrounding_spaces(self):
order = self.place("ana", [("sourdough", 2), ("brownie", 2)], " spring10 ")
self.assertEqual(order.coupon_code, "SPRING10")
self.assertEqual(order.coupon_discount_cents, 220)
self.assertEqual(order.total_cents, 1980)
def test_orders_without_a_coupon_are_unchanged(self):
order = self.place("ben", [("cupcake", 6), ("sourdough", 1)])
self.assertIsNone(order.coupon_code)
self.assertEqual(order.coupon_discount_cents, 0)
self.assertEqual(order.loyalty_discount_cents, 129)
self.assertEqual(order.total_cents, 2456)
class TestCouponRules(CouponTestCase):
def test_unknown_code(self):
self.assert_rejected("ana", [("sourdough", 3)], "SPRING11")
def test_only_one_coupon_per_order(self):
self.assert_rejected("ana", [("sourdough", 3)], "SPRING10 FIVEOFF")
self.assert_rejected("ana", [("sourdough", 3)], "SPRING10,FIVEOFF")
def test_valid_through_the_end_of_the_expiry_day(self):
order = self.place("ana", [("sourdough", 3)], "SPRING10", placed_at=datetime(2026, 4, 30, 23, 59))
self.assertEqual(order.coupon_discount_cents, 240)
self.assert_rejected("ana", [("sourdough", 3)], "SPRING10", placed_at=datetime(2026, 5, 1, 0, 0))
def test_minimum_is_checked_after_item_discounts(self):
# 6 cupcakes are 2100 before the bulk discount but 1785 after it.
self.assert_rejected("ana", [("cupcake", 6)], "SPRING10")
exactly = self.place("ana", [("sourdough", 1), ("brownie", 4)], "SPRING10")
self.assertEqual(exactly.coupon_discount_cents, 200)
self.assertEqual(exactly.total_cents, 1800)
def test_max_redemptions(self):
first = self.place("ana", [("brownie", 2)], "ONCE")
self.assertEqual(first.coupon_discount_cents, 120)
self.assertEqual(self.service.coupon_redemptions("ONCE"), 1)
self.assert_rejected("ben", [("brownie", 2)], "once")
self.assertEqual(self.service.coupon_redemptions("ONCE"), 1)
def test_failed_orders_do_not_use_up_a_coupon(self):
with self.assertRaises(errors.OutOfStockError):
self.service.place_order("ana", [("brownie", 1), ("sourdough", 11)], placed_at=APRIL,
coupon_code="ONCE")
with self.assertRaises(errors.ProductUnavailableError):
self.service.place_order("ana", [("brownie", 1), ("pumpkin-pie", 1)], placed_at=APRIL,
coupon_code="ONCE")
self.assertEqual(self.inventory.snapshot(), STOCK)
self.assertEqual(self.service.coupon_redemptions("ONCE"), 0)
order = self.place("ben", [("brownie", 1)], "ONCE")
self.assertEqual(order.coupon_discount_cents, 60)
def test_redemptions_are_counted_per_coupon(self):
self.place("ana", [("sourdough", 3)], "SPRING10")
self.place("ben", [("sourdough", 3)], "spring10")
self.place("gia", [("brownie", 1)], "FIVEOFF")
self.assertEqual(self.service.coupon_redemptions("SPRING10"), 2)
self.assertEqual(self.service.coupon_redemptions("FIVEOFF"), 1)
self.assertEqual(self.service.coupon_redemptions("TEN"), 0)
def test_duplicate_codes_are_refused(self):
with self.assertRaises(ValueError):
self.service.add_coupon(Coupon("spring10", CouponKind.FIXED, 100, expires_on=date(2026, 6, 1)))
def test_invalid_coupon_error_is_an_order_error(self):
self.assertTrue(issubclass(errors.InvalidCouponError, errors.OrderError))
if __name__ == "__main__":
unittest.main()
tests/test_stage3.py 256 lines
"""Stage 3: reporting queries that don't scan every order.
These tests store a few thousand orders, then record which stored orders
the repository touches while it answers a query: reading an Order's
attributes, or comparing its customer id, timestamp or date, counts as
touching that order. A full scan touches every order. An index or a running
aggregate only touches the orders in the answer, plus a few dozen for
binary searches. No timing is involved, so the results are deterministic.
"""
import random
import unittest
from collections import Counter
from datetime import date, datetime, timedelta
from bakery.models import LineItem, Order, OrderStatus
from bakery.repository import InMemoryOrderRepository
SKUS = [
"baguette", "brownie", "cinnamon-roll", "croissant", "cupcake", "eclair",
"lemon-tart", "macaron", "muffin", "pain-au-chocolat", "scone", "sourdough",
]
FIRST_DAY = date(2026, 1, 1)
SLACK = 40 # room for binary searches and dictionary lookups
class _Touched:
recording = False
orders = set()
TOUCHED = _Touched()
def touch(order_id):
if TOUCHED.recording:
TOUCHED.orders.add(order_id)
class TrackedOrder(Order):
"""An Order that records when its attributes are read."""
def __getattribute__(self, name):
if TOUCHED.recording and not name.startswith("__"):
TOUCHED.orders.add(object.__getattribute__(self, "id"))
return object.__getattribute__(self, name)
def _tracked_comparisons(base):
def compare(op):
def method(self, other):
touch(self.owner)
return getattr(base, op)(self, other)
return method
return {op: compare(op) for op in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__")}
TrackedStr = type("TrackedStr", (str,), {**_tracked_comparisons(str), "__hash__": str.__hash__})
TrackedDate = type("TrackedDate", (date,), {**_tracked_comparisons(date), "__hash__": date.__hash__})
def _tracked_date(self):
day = TrackedDate(self.year, self.month, self.day)
day.owner = self.owner
return day
TrackedDatetime = type(
"TrackedDatetime", (datetime,),
{**_tracked_comparisons(datetime), "__hash__": datetime.__hash__, "date": _tracked_date},
)
def touched_by(query):
"""Run `query` and return (its result, how many distinct stored orders it touched)."""
TOUCHED.orders = set()
TOUCHED.recording = True
try:
result = query()
finally:
TOUCHED.recording = False
return result, len(TOUCHED.orders)
def make_order(order_id, customer_id, placed_at, lines, status=OrderStatus.PLACED):
items = tuple(LineItem(sku, sku, qty, 300) for sku, qty in lines)
total = sum(item.gross_cents for item in items)
stamp = TrackedDatetime(*placed_at.timetuple()[:6])
stamp.owner = order_id
customer = TrackedStr(customer_id)
customer.owner = order_id
return TrackedOrder(
id=order_id,
customer_id=customer,
placed_at=stamp,
lines=items,
subtotal_cents=total,
item_discount_cents=0,
loyalty_discount_cents=0,
total_cents=total,
status=status,
)
def generate_orders(count, seed, id_prefix="ord"):
"""Orders spread over 200 days, in random (not time) order."""
rng = random.Random(seed)
orders = []
for n in range(count):
day = FIRST_DAY + timedelta(days=rng.randrange(200))
placed_at = datetime(day.year, day.month, day.day) + timedelta(minutes=rng.randrange(6 * 60, 20 * 60))
lines = [(sku, rng.randint(1, 6)) for sku in rng.sample(SKUS, rng.randint(1, 3))]
status = OrderStatus.CANCELLED if rng.random() < 0.05 else OrderStatus.PLACED
orders.append(make_order(f"{id_prefix}-{n:05d}", f"cust-{rng.randrange(150):03d}", placed_at, lines, status))
return orders
ORDERS = generate_orders(4000, seed=2026)
LATE_ORDERS = generate_orders(400, seed=7, id_prefix="late")
def expected_for_customer(orders, customer_id):
matches = [o for o in orders if o.customer_id == customer_id]
return [o.id for o in sorted(matches, key=lambda o: (o.placed_at, o.id))]
def expected_best_sellers(orders, start, end, limit):
units = Counter()
for order in orders:
if order.status is OrderStatus.PLACED and start <= order.placed_at.date() <= end:
for line in order.lines:
units[line.sku] += line.quantity
return sorted(units.items(), key=lambda item: (-item[1], item[0]))[:limit]
def in_range(orders, start, end):
return sum(1 for o in orders if start <= o.placed_at.date() <= end)
class ScaleTestCase(unittest.TestCase):
def setUp(self):
self.repo = InMemoryOrderRepository()
for order in ORDERS:
self.repo.add(order)
self.stored = list(ORDERS)
def add(self, order):
self.repo.add(order)
self.stored.append(order)
def assert_not_a_scan(self, touched, needed, query):
self.assertLessEqual(
touched, needed + SLACK,
f"{query} touched {touched} of the {len(self.stored)} stored orders, but only "
f"{needed} are in the answer. That's a scan: use an index kept up to date in add().",
)
class TestOrdersForCustomer(ScaleTestCase):
def test_results_match_a_full_scan(self):
for customer_id in ("cust-000", "cust-017", "cust-149", "cust-150", "nobody"):
with self.subTest(customer_id=customer_id):
got = self.repo.orders_for_customer(customer_id)
self.assertEqual([o.id for o in got], expected_for_customer(self.stored, customer_id))
def test_only_touches_that_customers_orders(self):
for customer_id in ("cust-003", "cust-088"):
expected = expected_for_customer(self.stored, customer_id)
result, touched = touched_by(lambda: self.repo.orders_for_customer(customer_id))
self.assertEqual([o.id for o in result], expected)
self.assert_not_a_scan(touched, len(expected), "orders_for_customer")
def test_unknown_customer_is_cheap(self):
result, touched = touched_by(lambda: self.repo.orders_for_customer("nobody"))
self.assertEqual(result, [])
self.assert_not_a_scan(touched, 0, "orders_for_customer")
def test_same_timestamp_is_ordered_by_id(self):
when = datetime(2026, 2, 14, 9, 0)
self.add(make_order("tie-2", "cust-tie", when, [("eclair", 1)]))
self.add(make_order("tie-1", "cust-tie", when, [("eclair", 2)]))
self.add(make_order("tie-0", "cust-tie", when + timedelta(seconds=1), [("eclair", 3)]))
self.assertEqual([o.id for o in self.repo.orders_for_customer("cust-tie")], ["tie-1", "tie-2", "tie-0"])
class TestBestSellers(ScaleTestCase):
RANGES = [
(date(2026, 1, 1), date(2026, 1, 1), 10),
(date(2026, 2, 2), date(2026, 2, 8), 10),
(date(2026, 3, 1), date(2026, 3, 31), 5),
(date(2025, 6, 1), date(2027, 1, 1), 12),
(date(2026, 7, 19), date(2026, 7, 19), 3),
(date(2026, 7, 20), date(2026, 8, 30), 10),
(date(2025, 1, 1), date(2025, 12, 31), 10),
(date(2026, 5, 2), date(2026, 5, 1), 10),
]
def test_results_match_a_full_scan(self):
for start, end, limit in self.RANGES:
with self.subTest(start=start, end=end, limit=limit):
self.assertEqual(
self.repo.best_sellers(start, end, limit),
expected_best_sellers(self.stored, start, end, limit),
)
def test_default_limit_is_ten(self):
start, end = date(2026, 4, 1), date(2026, 4, 30)
self.assertEqual(self.repo.best_sellers(start, end), expected_best_sellers(self.stored, start, end, 10))
def test_a_short_range_only_touches_orders_in_it(self):
for start, end in ((date(2026, 2, 2), date(2026, 2, 8)), (date(2026, 6, 10), date(2026, 6, 10))):
result, touched = touched_by(lambda: self.repo.best_sellers(start, end, 10))
self.assertEqual(result, expected_best_sellers(self.stored, start, end, 10))
self.assert_not_a_scan(touched, in_range(self.stored, start, end), "best_sellers")
def test_an_empty_range_is_cheap(self):
result, touched = touched_by(lambda: self.repo.best_sellers(date(2026, 8, 1), date(2026, 8, 31)))
self.assertEqual(result, [])
self.assert_not_a_scan(touched, 0, "best_sellers")
def test_end_date_includes_the_whole_last_day(self):
self.add(make_order("edge-1", "cust-edge", datetime(2026, 9, 30, 23, 59, 59), [("baguette", 50)]))
self.add(make_order("edge-2", "cust-edge", datetime(2026, 10, 1, 0, 0, 0), [("scone", 60)]))
self.add(make_order("edge-3", "cust-edge", datetime(2026, 9, 29, 0, 0, 0), [("muffin", 40)]))
self.assertEqual(self.repo.best_sellers(date(2026, 9, 29), date(2026, 9, 30)),
[("baguette", 50), ("muffin", 40)])
self.assertEqual(self.repo.best_sellers(date(2026, 10, 1), date(2026, 10, 1)), [("scone", 60)])
class TestIndexesStayCurrent(ScaleTestCase):
def test_orders_added_after_a_query_are_included(self):
start, end = date(2026, 3, 1), date(2026, 3, 14)
self.repo.best_sellers(start, end)
self.repo.orders_for_customer("cust-042")
for order in LATE_ORDERS:
self.add(order)
expected = expected_for_customer(self.stored, "cust-042")
result, touched = touched_by(lambda: self.repo.orders_for_customer("cust-042"))
self.assertEqual([o.id for o in result], expected)
self.assert_not_a_scan(touched, len(expected), "orders_for_customer")
result, touched = touched_by(lambda: self.repo.best_sellers(start, end))
self.assertEqual(result, expected_best_sellers(self.stored, start, end, 10))
self.assert_not_a_scan(touched, in_range(self.stored, start, end), "best_sellers")
def test_cancelled_orders_added_from_history_are_skipped(self):
day = datetime(2026, 11, 20, 10, 0)
self.add(make_order("hist-1", "cust-hist", day, [("eclair", 30)], status=OrderStatus.CANCELLED))
self.add(make_order("hist-2", "cust-hist", day, [("scone", 3)]))
self.assertEqual(self.repo.best_sellers(day.date(), day.date()), [("scone", 3)])
self.assertEqual([o.id for o in self.repo.orders_for_customer("cust-hist")], ["hist-1", "hist-2"])
if __name__ == "__main__":
unittest.main()
tests/test_stage4.py 98 lines
"""Stage 4 (stretch): cancelling an order."""
import unittest
from datetime import date, datetime
import bakery.errors as errors
from bakery.catalog import Catalog, CustomerDirectory
from bakery.inventory import Inventory
from bakery.models import BulkDiscount, Coupon, CouponKind, Customer, LoyaltyTier, OrderStatus, Product
from bakery.orders import OrderService
from bakery.repository import InMemoryOrderRepository
PRODUCTS = [
Product("croissant", "Butter croissant", 375),
Product("cupcake", "Vanilla cupcake", 350, bulk_discount=BulkDiscount(6, 15)),
Product("sourdough", "Sourdough loaf", 800, category="bread"),
Product("brownie", "Fudge brownie", 300),
]
CUSTOMERS = [Customer("ana", "Ana"), Customer("ben", "Ben", LoyaltyTier.SILVER)]
STOCK = {"croissant": 20, "cupcake": 24, "sourdough": 10, "brownie": 15}
MONDAY = datetime(2026, 6, 1, 9, 0)
TUESDAY = datetime(2026, 6, 2, 9, 0)
class TestCancellingOrders(unittest.TestCase):
def setUp(self):
self.inventory = Inventory(STOCK)
self.repo = InMemoryOrderRepository()
self.service = OrderService(
Catalog(PRODUCTS), CustomerDirectory(CUSTOMERS), self.inventory, self.repo
)
self.service.add_coupon(
Coupon("ONCE", CouponKind.FIXED, 200, expires_on=date(2026, 12, 31), max_redemptions=1)
)
def place(self, customer_id, items, placed_at=MONDAY, coupon_code=None):
return self.service.place_order(customer_id, items, placed_at=placed_at, coupon_code=coupon_code)
def test_cancelling_releases_stock_and_marks_the_order(self):
order = self.place("ana", [("croissant", 4), ("sourdough", 1)])
self.place("ben", [("croissant", 2)])
cancelled = self.service.cancel_order(order.id)
self.assertEqual(cancelled.id, order.id)
self.assertEqual(cancelled.status, OrderStatus.CANCELLED)
self.assertEqual(self.repo.get(order.id).status, OrderStatus.CANCELLED)
self.assertEqual(self.inventory.on_hand("croissant"), 18)
self.assertEqual(self.inventory.on_hand("sourdough"), 10)
def test_cancelled_orders_stay_in_the_customers_history(self):
first = self.place("ana", [("brownie", 1)], placed_at=MONDAY)
second = self.place("ana", [("brownie", 2)], placed_at=TUESDAY)
self.service.cancel_order(first.id)
history = self.repo.orders_for_customer("ana")
self.assertEqual([o.id for o in history], [first.id, second.id])
self.assertEqual([o.status for o in history], [OrderStatus.CANCELLED, OrderStatus.PLACED])
def test_cancelled_orders_stop_counting_as_sales(self):
keep = self.place("ana", [("cupcake", 6), ("brownie", 2)], placed_at=MONDAY)
drop = self.place("ben", [("croissant", 9), ("brownie", 1)], placed_at=MONDAY)
self.place("ben", [("sourdough", 3)], placed_at=TUESDAY)
week = (date(2026, 6, 1), date(2026, 6, 7))
self.assertEqual(self.repo.best_sellers(*week),
[("croissant", 9), ("cupcake", 6), ("brownie", 3), ("sourdough", 3)])
self.service.cancel_order(drop.id)
self.assertEqual(self.repo.best_sellers(*week),
[("cupcake", 6), ("sourdough", 3), ("brownie", 2)])
self.assertEqual(self.repo.best_sellers(date(2026, 6, 1), date(2026, 6, 1)),
[("cupcake", 6), ("brownie", 2)])
self.assertEqual(keep.status, OrderStatus.PLACED)
def test_cancelling_gives_back_the_coupon(self):
order = self.place("ana", [("brownie", 2)], coupon_code="ONCE")
self.assertEqual(self.service.coupon_redemptions("ONCE"), 1)
with self.assertRaises(errors.InvalidCouponError):
self.place("ben", [("brownie", 2)], coupon_code="ONCE")
self.service.cancel_order(order.id)
self.assertEqual(self.service.coupon_redemptions("ONCE"), 0)
again = self.place("ben", [("brownie", 2)], coupon_code="ONCE")
self.assertEqual(again.coupon_discount_cents, 200)
self.assertEqual(self.service.coupon_redemptions("ONCE"), 1)
def test_cancelling_twice_is_refused_and_changes_nothing(self):
order = self.place("ana", [("croissant", 5)], coupon_code="ONCE")
self.place("ben", [("croissant", 1)])
self.service.cancel_order(order.id)
with self.assertRaises(errors.OrderError):
self.service.cancel_order(order.id)
self.assertEqual(self.inventory.on_hand("croissant"), 19)
self.assertEqual(self.service.coupon_redemptions("ONCE"), 0)
self.assertEqual(self.repo.best_sellers(date(2026, 6, 1), date(2026, 6, 1)), [("croissant", 1)])
def test_unknown_order(self):
with self.assertRaises(errors.OrderNotFoundError):
self.service.cancel_order("ord-99999")
if __name__ == "__main__":
unittest.main()
Download the starter repo. Done, or out of time? Download the reference solution (spoilers) and compare it with yours.
More AI coding interview practice
- Delivery Scheduler Bug Squash: Four bug reports, written as symptoms, in a small cake delivery scheduler. Find and fix each root cause, and practice not accepting an AI's plausible-but-wrong fix.
- Cake Database (Progressive Build): Build the bakery's in-memory order database in four levels, from set/get to TTLs and backup/restore. The design you pick in level 1 decides how painful level 4 is.
- All practice problems, and how to use AI well in a coding interview
- AI-assisted coding interviews: how they work and how to prepare
- CoderPad interviews
- The CodeSignal General Coding Assessment (GCA)
- HackerRank tests
- Karat interviews
- Coding interview tips
Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026
Interview Cake