Here's everything in the starter repo, so you can look around before you download it. Click a file to open it.
README.md 139 lines
# Crumb & Co. production planner
Crumb & Co.'s central kitchen bakes for its two shops and for cafés and hotels around town. Every
evening the kitchen office runs this planner over the next few days' orders. It works out how many
batches of each recipe the kitchen makes on each day, what ingredients they take, and the sheets
everyone works from. You've joined the team that looks after it, and there are three tickets waiting.
## 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's tests: `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.
- `tests/test_stage1.py` to `tests/test_stage3.py` go with stages 1 to 3, and
`tests/test_change_request.py` with the change request after stage 2. Each fails until that part is done.
- There are hidden tests too, like the ones an interviewer runs after you say you're done. In the browser
workspace, choose "Hidden tests" in the Run menu. Locally, download `hidden-tests.zip` from the problem
page and unzip it where you unzipped the starter. It adds a `hidden_tests` folder next to `tests`. Then,
from this folder, run `python3 -m unittest discover -s hidden_tests`.
## Time box and rules
90 minutes. Do the stages in order, with the change request after stage 2.
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 `bakehouse/`, but don't edit the tests or the data files.
## The codebase
| File | What it does |
|---|---|
| `bakehouse/units.py` | Quantities: `parse_quantity`, `parse_amount`, `format_quantity` |
| `bakehouse/models.py` | Dataclasses: `Ingredient`, `Recipe`, `Order`, `Lot`, `Pick`, `Shortage`, `Allocation` |
| `bakehouse/recipes.py` | `RecipeBook`: looking things up, checking the recipes, and the order to plan them in |
| `bakehouse/schedule.py` | `KitchenCalendar`: which days the kitchen is open, and which day to make something |
| `bakehouse/orders.py` | `OrderBook`: which orders the kitchen bakes for |
| `bakehouse/loaders.py` | Reads the CSV files in `data/` |
| `bakehouse/planning.py` | `build_plan`: the batches and ingredients for each day |
| `bakehouse/stock.py` | The store room: `on_hand`, and `allocate`, which isn't written yet |
| `bakehouse/reports.py` | Production sheets, the delivery list, store room labels, pick lists |
| `bakehouse/costing.py` | What a batch, and one of each product, costs in ingredients |
| `bakehouse/cli.py` | The command line: `python3 -m bakehouse plan 2027-03-02 2027-03-07` |
| `data/` | The recipe book (`ingredients.csv`, `recipes.csv`, `components.csv`), the orders for the week of 2 March 2027, the store room (`stock.csv`), ingredient prices (`prices.csv`) and the holidays (`closed.csv`) |
| `CHANGELOG.md` | What changed recently |
## How the plan works
- **Quantities.** Inside the planner every quantity is a whole number of grams, millilitres or "each".
The data files can say "1.25 kg" or "0.5 l"; the loaders convert them.
- **Recipes.** Each recipe makes a fixed amount per batch (48 croissants, 6 kg of laminated dough), and the
kitchen only makes whole batches. A recipe's components are ingredients or other recipes: croissants are
made from laminated dough, which is made from flour, butter, milk and so on.
- **When things are made.** A product is made `lead_days` before it's delivered. Anything that goes into
a recipe is made its own `lead_days` before the day that recipe is made, and so on down. The kitchen is
closed on Mondays and on the days in `closed.csv`: anything that would be made on a closed day is made
on the last open day before it.
- **Batches.** On each day, the kitchen makes enough batches of each recipe to cover everything that
needs it that day, rounded up once for the day.
- **Orders.** `orders.csv` has one row for each line of an order. When a customer changes an order, every
line of it is written again under the next version number, and the newest version replaces the older
ones completely: its lines, its delivery date, and whether it's cancelled. A cancellation is a version
with status `cancelled` and no lines.
## Stage 1: PLAN-231, Friday's prep list wants too much butter
> From: Rosa (head baker)
>
> Friday's prep list asks for 53.85 kg of butter. I worked it out by hand from Saturday's orders and it
> should be about 38 kg. Saturday's own sheet is off too: it says 30 batches of croissants, and we've
> never needed more than 20. The only thing that's changed on our side is that Marco rewrote the
> laminated dough recipe in kilos last week (1.75 kg of butter instead of 1750 g), so I'd start with how
> the planner reads kilos. The rest of the week looks right.
`python3 -m bakehouse plan 2027-03-02 2027-03-07` prints the week's production sheets.
## Stage 2: PLAN-238, pick lists
> From: Sam (kitchen manager)
>
> The plan says what we need but not where it comes from. Every morning someone goes through the store
> room working out which butter to take, and every week something goes past its use-by while a fresher
> case gets opened. The pick list and the shortage report are already written; they just need
> something to tell them what to pick.
Write `allocate(plan, lots)` in `bakehouse/stock.py`. It returns an `Allocation` (in `models.py`): a list
of `Pick`s and a list of `Shortage`s.
- Go through the plan's days in order, and on each day its ingredients in order of their code.
- A lot can be used on a day if it has come in by then (`received` on or before the day) and the day isn't
after its `use_by` date. A lot with no `use_by` doesn't go off.
- Use the lot that goes off first: the earliest `use_by`, with lots that don't go off last. If two lots
tie, the one that came in first, then the lowest `lot_id`.
- Take what the day needs from each lot in turn, with one `Pick` for each lot you take from. Whatever's
left in a lot is there for later days.
- Whatever the lots can't cover is a `Shortage` for that day and ingredient.
- List the picks and shortages in the order they happen.
- Don't change the lots you're given: the office runs what-if plans against the same stock.
`python3 -m bakehouse picks 2027-03-02 2027-03-07` prints the pick lists and the shortage report.
## Change request: opened containers
> From: Sam (kitchen manager)
>
> We had the food safety inspector in this morning, and there are two things we have to change before
> tonight's run. Anything that's been opened gets used first. And milk, cream, berries and yeast have to
> be used within a few days of opening, whatever the use-by says. The store room has been filling in the
> `opened_on` column in stock.csv for a couple of weeks, so it's all there.
This is the requirements changing partway through, the way an interviewer often does once your first
version works. Fit it into your stage 2 code rather than bolting it on.
- `Lot` gets `opened_on`: the day it was opened, or `None` if it hasn't been. It comes from the
`opened_on` column in `stock.csv`. A stock file without that column still loads, with nothing opened.
- An ingredient's `opened_shelf_days` (already in `ingredients.csv`) is how long it keeps once opened: an
opened lot can be used up to and including `opened_on` plus that many days, or until its `use_by` if
that's sooner. Milk opened on 1 March with 3 days can be used until 4 March. Ingredients without
`opened_shelf_days` keep until their `use_by`, opened or not.
- Opened lots are used before unopened ones. Within each group the order is as before: the lot that goes
off first (counting the days since it was opened), then the one that came in first, then `lot_id`.
- A lot the plan takes from is open from that day on.
## Stage 3: PLAN-252, plan December in one go
> From: Priya (operations)
>
> December is our busiest month, and we want to plan all of it in one run so the buyers can see the
> month's shortages up front. We tried it on a copy of last December (about 20,000 orders, plus the
> changes and cancellations) and it took the best part of a minute. In December the office reruns the
> plan every time a big order changes, so it needs to come back in a second or two. Nothing in the plan
> can change, though: the same batches, picks and shortages, in the same order.
`tests/test_stage3.py` builds a December like that and plans it from start to finish. It gives up as
soon as it can tell the run is too slow, so you don't have to wait a minute for it to fail.
CHANGELOG.md 33 lines
# Changelog
## 2027-02-26
- Recipes: Marco rewrote the laminated dough recipe in kilos (1.75 kg of butter instead of 1750 g). The
loaders already read kilos, so no code changed.
## 2027-02-22
- PLAN-219: orders can be changed after they're placed. `orders.csv` has a `version` column: a changed
order is written out again under the next version number, and a cancellation is a version with status
`cancelled`. `OrderBook.current()` keeps the newest version of each order.
## 2027-02-15
- `stock.csv` has an `opened_on` column, which the store room fills in when a container is opened. The
planner doesn't use it yet.
## 2027-02-08
- PLAN-238, started: `reports.pick_list`, `reports.shortage_report` and the `picks` command. They need
`stock.allocate`, which isn't written yet.
## 2027-01-18
- `closed.csv`: the days the kitchen is closed besides Mondays.
- Store room labels say how long an ingredient keeps once it's opened (`opened_shelf_days` in
`ingredients.csv`).
## 2026-11-30
- PLAN-204: batches are rounded up once per day across everything that needs a recipe, instead of once
per order.
bakehouse/__init__.py 1 line
"""Crumb & Co.'s production planner: what the central kitchen has to make, and when."""
bakehouse/__main__.py 5 lines
import sys
from .cli import main
sys.exit(main())
bakehouse/cli.py 68 lines
"""The command line the kitchen office uses. From the repo's folder:
python3 -m bakehouse plan 2027-03-02 2027-03-07 production sheets for those deliveries
python3 -m bakehouse deliveries 2027-03-06 the van's list for one day
python3 -m bakehouse picks 2027-03-02 2027-03-07 pick lists and shortages for those deliveries
python3 -m bakehouse labels store room labels for every lot
python3 -m bakehouse costs what each product costs to make
Add --data FOLDER to read the data files from somewhere other than data/.
"""
import argparse
from datetime import date
from .costing import costing_sheet
from .errors import PlannerError
from .loaders import load_kitchen
from .orders import OrderBook
from .planning import build_plan
from .reports import delivery_list, pick_list, production_sheet, shortage_report, store_room_label
from .stock import allocate
def _date(text):
try:
return date.fromisoformat(text)
except ValueError:
raise argparse.ArgumentTypeError(f"not a date (YYYY-MM-DD): {text!r}") from None
def _parser():
parser = argparse.ArgumentParser(prog="python3 -m bakehouse", description="Crumb & Co.'s production planner")
parser.add_argument("--data", default="data", help="the folder with the data files (default: data)")
commands = parser.add_subparsers(dest="command", required=True)
for name, help_text in (("plan", "production sheets for a range of delivery days"),
("picks", "pick lists and shortages for a range of delivery days")):
command = commands.add_parser(name, help=help_text)
command.add_argument("first", type=_date, help="first delivery day, YYYY-MM-DD")
command.add_argument("last", type=_date, nargs="?", help="last delivery day (default: the first)")
deliveries = commands.add_parser("deliveries", help="the delivery list for one day")
deliveries.add_argument("day", type=_date)
commands.add_parser("labels", help="store room labels for every lot")
commands.add_parser("costs", help="what each product costs to make")
return parser
def main(argv=None, out=print):
args = _parser().parse_args(argv)
try:
kitchen = load_kitchen(args.data)
if args.command == "costs":
out(costing_sheet(kitchen.book, kitchen.prices))
elif args.command == "labels":
out("\n\n".join(store_room_label(lot, kitchen.book) for lot in kitchen.stock))
elif args.command == "deliveries":
out(delivery_list(OrderBook(kitchen.orders), kitchen.book, args.day))
else:
plan = build_plan(kitchen.book, kitchen.orders, kitchen.calendar, args.first, args.last or args.first)
if args.command == "plan":
out("\n\n".join(production_sheet(plan, day) for day in plan.days()) or "Nothing to make.")
else:
allocation = allocate(plan, kitchen.stock)
sheets = [pick_list(allocation, kitchen.book, day) for day in plan.days()]
out("\n\n".join(sheets + [shortage_report(allocation, kitchen.book)]))
except PlannerError as error:
out(f"error: {error}")
return 1
return 0
bakehouse/costing.py 49 lines
"""What things cost to make, for the finance team's margins sheet.
The buyers' price list (data/prices.csv) prices each ingredient per kilo, per litre or each. Costs
are worked out exactly (as fractions of a penny) and only rounded, to the nearest penny, for people.
A recipe's cost is for an ideal batch: it doesn't count what's left over from rounding up to whole
batches on the day.
"""
from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction
from .errors import DataError
def batch_cost(book, prices, code):
"""What one batch of a recipe costs, in pence, as a Fraction. `prices` is pence per base unit
(per gram, millilitre or each) for each ingredient, as load_prices gives it."""
total = Fraction(0)
for component in book.recipe(code).components:
if book.is_recipe(component.code):
sub_recipe = book.recipe(component.code)
total += batch_cost(book, prices, sub_recipe.code) * component.amount / sub_recipe.batch_yield
else:
if component.code not in prices:
raise DataError(f"there's no price for {component.code!r}")
total += prices[component.code] * component.amount
return total
def unit_cost(book, prices, code):
"""What one of something costs to make (one croissant, one gram of dough), in pence."""
recipe = book.recipe(code)
return batch_cost(book, prices, code) / recipe.batch_yield
def format_pence(pence):
"""Fraction(1234, 3) -> '£4.11'. Rounds to the nearest penny, halves up."""
rounded = (Decimal(pence.numerator) / Decimal(pence.denominator)).quantize(Decimal(1), rounding=ROUND_HALF_UP)
pounds, pennies = divmod(int(rounded), 100)
return f"£{pounds:,}.{pennies:02d}"
def costing_sheet(book, prices):
"""Each product and what one costs to make, most expensive first."""
products = sorted(book.products(), key=lambda recipe: (-unit_cost(book, prices, recipe.code), recipe.name))
lines = ["What one of each product costs to make"]
for recipe in products:
lines.append(f" {recipe.name:<28}{format_pence(unit_cost(book, prices, recipe.code))}")
return "\n".join(lines)
bakehouse/errors.py 6 lines
class PlannerError(Exception):
"""Something the planner can't do."""
class DataError(PlannerError):
"""A data file has something the planner can't use. The message says which file and line."""
bakehouse/loaders.py 226 lines
"""Reading the data files in data/. Each loader takes the file's text, so the tests can hand
them a few lines instead of a file.
Errors say which file and line they come from, because the people who fix them are the ones
who edit the spreadsheets these files are exported from.
"""
import csv
import io
import os
from dataclasses import dataclass
from datetime import date
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from .errors import DataError
from .models import Component, Ingredient, Lot, Order, OrderLine, Recipe
from .recipes import RecipeBook
from .schedule import KitchenCalendar
from .units import BASE_UNITS, UNITS, parse_amount, parse_quantity
INGREDIENT_COLUMNS = ("code", "name", "unit", "opened_shelf_days")
RECIPE_COLUMNS = ("code", "name", "makes", "lead_days", "sellable")
COMPONENT_COLUMNS = ("recipe", "component", "amount")
ORDER_COLUMNS = ("order_id", "version", "status", "customer", "delivery_date", "product", "quantity")
STOCK_COLUMNS = ("lot_id", "ingredient", "quantity", "received", "use_by")
CLOSED_COLUMNS = ("date", "reason")
PRICE_COLUMNS = ("ingredient", "price", "per")
ORDER_STATUSES = ("open", "cancelled")
def _rows(text, columns, filename):
"""(line number, row) for each row of a CSV file, with every value stripped. Extra columns
are fine; missing ones aren't."""
reader = csv.DictReader(io.StringIO(text))
found = [name.strip() for name in reader.fieldnames or ()]
missing = [name for name in columns if name not in found]
if missing:
raise DataError(f"{filename}: missing column(s) {', '.join(missing)}")
reader.fieldnames = found
for row in reader:
values = {name: (row.get(name) or "").strip() for name in found}
if not any(values.values()):
continue # a blank line
yield reader.line_num, values
def _date(text, where):
try:
return date.fromisoformat(text)
except ValueError:
raise DataError(f"{where}: not a date (YYYY-MM-DD): {text!r}") from None
def _optional_date(text, where):
return _date(text, where) if text else None
def _whole_number(text, where, smallest=0):
try:
number = int(text)
except ValueError:
raise DataError(f"{where}: not a whole number: {text!r}") from None
if number < smallest:
raise DataError(f"{where}: {number} is less than {smallest}")
return number
def _amount(text, unit, where):
try:
return parse_amount(text, unit)
except DataError as error:
raise DataError(f"{where}: {error}") from None
# ----------------------------------------------------------------------
# the recipe book
def load_ingredients(text, filename="ingredients.csv"):
ingredients = []
for line_no, row in _rows(text, INGREDIENT_COLUMNS, filename):
where = f"{filename} line {line_no}"
if row["unit"] not in BASE_UNITS:
raise DataError(f"{where}: unit has to be one of {', '.join(BASE_UNITS)}, not {row['unit']!r}")
shelf_days = _whole_number(row["opened_shelf_days"], where, smallest=1) if row["opened_shelf_days"] else None
ingredients.append(Ingredient(row["code"], row["name"], row["unit"], shelf_days))
return ingredients
def load_recipe_book(ingredients_text, recipes_text, components_text):
"""ingredients.csv, recipes.csv and components.csv -> a checked RecipeBook."""
ingredients = load_ingredients(ingredients_text)
units = {ingredient.code: ingredient.unit for ingredient in ingredients}
headers = []
for line_no, row in _rows(recipes_text, RECIPE_COLUMNS, "recipes.csv"):
where = f"recipes.csv line {line_no}"
try:
batch_yield, unit = parse_quantity(row["makes"])
except DataError as error:
raise DataError(f"{where}: {error}") from None
if row["sellable"] not in ("yes", "no"):
raise DataError(f"{where}: sellable has to be yes or no, not {row['sellable']!r}")
headers.append((row["code"], row["name"], batch_yield, unit,
_whole_number(row["lead_days"], where), row["sellable"] == "yes"))
units.setdefault(row["code"], unit)
components = {code: [] for code, *_ in headers}
for line_no, row in _rows(components_text, COMPONENT_COLUMNS, "components.csv"):
where = f"components.csv line {line_no}"
if row["recipe"] not in components:
raise DataError(f"{where}: no recipe {row['recipe']!r} in recipes.csv")
if row["component"] not in units:
raise DataError(f"{where}: {row['component']!r} isn't an ingredient or a recipe")
amount = _amount(row["amount"], units[row["component"]], where)
components[row["recipe"]].append(Component(row["component"], amount))
recipes = [Recipe(code, name, batch_yield, unit, lead_days, tuple(components[code]), sellable)
for code, name, batch_yield, unit, lead_days, sellable in headers]
return RecipeBook(ingredients, recipes)
# ----------------------------------------------------------------------
# orders
def load_orders(text, filename="orders.csv"):
"""orders.csv -> one Order for each version of each order.
Each row is one line of one version of an order. When a customer changes an order, every
line of it is written again under the next version number. A cancellation is a version with
status "cancelled" and no lines."""
drafts = {} # order id -> what we know about the order so far
for line_no, row in _rows(text, ORDER_COLUMNS, filename):
where = f"{filename} line {line_no}"
version = _whole_number(row["version"], where, smallest=1)
status = row["status"] or "open"
if status not in ORDER_STATUSES:
raise DataError(f"{where}: status has to be open or cancelled, not {status!r}")
if row["order_id"] not in drafts:
drafts[row["order_id"]] = (version, row["customer"], _date(row["delivery_date"], where), status == "cancelled", [])
if row["product"]:
if status == "cancelled":
raise DataError(f"{where}: a cancelled order can't have lines")
quantity = _whole_number(row["quantity"], where, smallest=1)
drafts[row["order_id"]][4].append(OrderLine(row["product"], quantity))
return [Order(order_id, version, customer, delivery_date, tuple(lines), cancelled)
for order_id, (version, customer, delivery_date, cancelled, lines) in drafts.items()]
# ----------------------------------------------------------------------
# the store room and the calendar
def load_stock(text, book, filename="stock.csv"):
"""stock.csv -> a Lot for each row. Quantities can be in any unit that fits the
ingredient ("12.5 kg" of butter); they're stored in its base unit."""
lots, seen = [], set()
for line_no, row in _rows(text, STOCK_COLUMNS, filename):
where = f"{filename} line {line_no}"
if row["lot_id"] in seen:
raise DataError(f"{where}: lot {row['lot_id']} is listed twice")
seen.add(row["lot_id"])
try:
ingredient = book.ingredient(row["ingredient"])
except DataError as error:
raise DataError(f"{where}: {error}") from None
lots.append(Lot(
lot_id=row["lot_id"],
ingredient=ingredient.code,
quantity=_amount(row["quantity"], ingredient.unit, where),
received=_date(row["received"], where),
use_by=_optional_date(row["use_by"], where),
))
return lots
def load_prices(text, book, filename="prices.csv"):
"""prices.csv -> {ingredient code: pence per base unit, as a Fraction}. Prices are in pounds,
per kg, per l or each: butter at 8.40 per kg is 21/25 of a penny per gram."""
prices = {}
for line_no, row in _rows(text, PRICE_COLUMNS, filename):
where = f"{filename} line {line_no}"
try:
ingredient = book.ingredient(row["ingredient"])
except DataError as error:
raise DataError(f"{where}: {error}") from None
if row["per"] not in UNITS or UNITS[row["per"]][0] != ingredient.unit:
raise DataError(f"{where}: {ingredient.name} is in {ingredient.unit}, so it can't be priced per {row['per']!r}")
try:
pounds = Decimal(row["price"])
except InvalidOperation:
raise DataError(f"{where}: not a price: {row['price']!r}") from None
_, factor = UNITS[row["per"]]
prices[ingredient.code] = Fraction(pounds * 100) / factor
return prices
def load_closed_days(text, filename="closed.csv"):
return {_date(row["date"], f"{filename} line {line_no}") for line_no, row in _rows(text, CLOSED_COLUMNS, filename)}
@dataclass
class Kitchen:
"""Everything in a data folder."""
book: RecipeBook
orders: list
stock: list
calendar: KitchenCalendar
prices: dict
def load_kitchen(folder):
def read(name):
with open(os.path.join(folder, name), encoding="utf-8") as f:
return f.read()
book = load_recipe_book(read("ingredients.csv"), read("recipes.csv"), read("components.csv"))
return Kitchen(
book=book,
orders=load_orders(read("orders.csv")),
stock=load_stock(read("stock.csv"), book),
calendar=KitchenCalendar(holidays=load_closed_days(read("closed.csv"))),
prices=load_prices(read("prices.csv"), book),
)
bakehouse/models.py 95 lines
"""The planner's data. Every quantity is a whole number of base units (see units.py)."""
from dataclasses import dataclass, field
from datetime import date
@dataclass(frozen=True)
class Ingredient:
"""Something the kitchen buys and keeps in the store room."""
code: str
name: str
unit: str # g, ml or each
# How many days an opened container stays good for, if that's shorter than its use-by
# date. None for things that keep (flour, sugar). The store room labels print it.
opened_shelf_days: int | None = None
@dataclass(frozen=True)
class Component:
"""One line of a recipe: how much of an ingredient, or of another recipe, one batch uses."""
code: str
amount: int
@dataclass(frozen=True)
class Recipe:
"""Something the kitchen makes, in whole batches.
Products (sellable=True) are what customers order. The rest, like laminated dough or pastry
cream, are only made to go into other recipes."""
code: str
name: str
batch_yield: int # how much one batch makes, in `unit`
unit: str # g, ml or each
lead_days: int # made this many days before it's needed
components: tuple = () # of Component
sellable: bool = False
@dataclass(frozen=True)
class OrderLine:
product: str
quantity: int
@dataclass(frozen=True)
class Order:
"""One version of an order. When a customer changes an order, the new version replaces the
old one completely: its lines, its delivery date, and whether it's cancelled."""
order_id: str
version: int
customer: str
delivery_date: date
lines: tuple = () # of OrderLine
cancelled: bool = False
@dataclass
class Lot:
"""One delivery of one ingredient, as the store room records it."""
lot_id: str
ingredient: str
quantity: int
received: date
use_by: date | None = None # None if it doesn't go off
@dataclass(frozen=True)
class Pick:
"""Take `quantity` of an ingredient from a lot, for the prep on `day`."""
day: date
ingredient: str
lot_id: str
quantity: int
@dataclass(frozen=True)
class Shortage:
"""What the store room can't cover for the prep on `day`."""
day: date
ingredient: str
quantity: int
@dataclass
class Allocation:
picks: list = field(default_factory=list)
shortages: list = field(default_factory=list)
bakehouse/orders.py 38 lines
"""The order book: every version of every order, and which of them the kitchen bakes for."""
from collections import Counter
class OrderBook:
def __init__(self, orders):
self._orders = list(orders)
def __len__(self):
return len(self._orders)
def current(self):
"""The newest version of each order, leaving out the ones whose newest version is a
cancellation. Sorted by order id."""
live = []
for order in self._orders:
replaced = any(other.order_id == order.order_id and other.version > order.version
for other in self._orders)
if not replaced and not order.cancelled:
live.append(order)
live.sort(key=lambda order: order.order_id)
return live
def for_delivery(self, first_day, last_day):
"""The current orders delivered from first_day to last_day, inclusive."""
return [order for order in self.current() if first_day <= order.delivery_date <= last_day]
def delivered_on(self, day):
return self.for_delivery(day, day)
def totals(self, first_day, last_day):
"""How many of each product the current orders want, from first_day to last_day."""
totals = Counter()
for order in self.for_delivery(first_day, last_day):
for line in order.lines:
totals[line.product] += line.quantity
return dict(sorted(totals.items()))
bakehouse/planning.py 72 lines
"""The production plan: how many batches of each recipe the kitchen makes on each day, and the
ingredients that takes.
A product is made `lead_days` before it's delivered. Whatever goes into a recipe (laminated
dough, pastry cream) is made `lead_days` before the day that recipe is made, and so on down.
Anything that would be made on a day the kitchen is closed is made on the open day before.
Batches are whole: on each day, the kitchen makes enough batches of each recipe to cover
everything that needs it that day, rounded up once for the day.
"""
from collections import defaultdict
from dataclasses import dataclass
from .errors import PlannerError
from .orders import OrderBook
from .units import ceil_div
@dataclass
class Plan:
book: object # the RecipeBook it was planned from
first_delivery: object # the deliveries it covers, inclusive
last_delivery: object
batches: dict # (day, recipe code) -> batches to make that day
needs: dict # (day, ingredient code) -> how much the day's batches use, in base units
def days(self):
"""Every day with something to make, in order."""
return sorted({day for day, _ in self.batches} | {day for day, _ in self.needs})
def batches_on(self, day):
return {code: count for (when, code), count in sorted(self.batches.items()) if when == day}
def needs_on(self, day):
return {code: amount for (when, code), amount in sorted(self.needs.items()) if when == day}
def total_needed(self, ingredient):
return sum(amount for (_, code), amount in self.needs.items() if code == ingredient)
def build_plan(book, orders, calendar, first_delivery, last_delivery):
"""Plan everything the current orders need delivered from first_delivery to last_delivery.
`orders` is every version of every order (an OrderBook works out which ones count)."""
if last_delivery < first_delivery:
raise PlannerError("the last delivery day is before the first")
demand = defaultdict(int) # (day, recipe code) -> how much is needed that day, in the recipe's unit
for order in OrderBook(orders).for_delivery(first_delivery, last_delivery):
for line in order.lines:
recipe = book.recipe(line.product)
if not recipe.sellable:
raise PlannerError(f"order {order.order_id} asks for {recipe.name}, which isn't for sale")
demand[calendar.make_day(order.delivery_date, recipe.lead_days), recipe.code] += line.quantity
batches, needs = {}, defaultdict(int)
# Parents first, so that by the time we get to a recipe, everything that uses it has
# added its demand, and each day's batches are rounded up once.
for code in book.parents_first():
recipe = book.recipe(code)
for day in sorted(day for day, what in demand if what == code):
count = ceil_div(demand[day, code], recipe.batch_yield)
batches[day, code] = count
for component in recipe.components:
amount = component.amount * count
if book.is_recipe(component.code):
sub_recipe = book.recipe(component.code)
demand[calendar.make_day(day, sub_recipe.lead_days), sub_recipe.code] += amount
else:
needs[day, component.code] += amount
return Plan(book, first_delivery, last_delivery, batches, dict(needs))
bakehouse/recipes.py 124 lines
"""The recipe book: every ingredient and recipe the kitchen knows, checked for mistakes."""
from .errors import DataError
class RecipeBook:
def __init__(self, ingredients, recipes):
self._ingredients = {}
for ingredient in ingredients:
if ingredient.code in self._ingredients:
raise DataError(f"ingredient {ingredient.code!r} is listed twice")
self._ingredients[ingredient.code] = ingredient
self._recipes = {}
for recipe in recipes:
if recipe.code in self._recipes or recipe.code in self._ingredients:
raise DataError(f"{recipe.code!r} is listed twice")
self._recipes[recipe.code] = recipe
self._check_components()
self._order = self._parents_first()
# ------------------------------------------------------------------
# looking things up
def ingredient(self, code):
try:
return self._ingredients[code]
except KeyError:
raise DataError(f"no ingredient {code!r}") from None
def recipe(self, code):
try:
return self._recipes[code]
except KeyError:
raise DataError(f"no recipe {code!r}") from None
def is_recipe(self, code):
return code in self._recipes
def ingredients(self):
return sorted(self._ingredients.values(), key=lambda ingredient: ingredient.code)
def recipes(self):
return sorted(self._recipes.values(), key=lambda recipe: recipe.code)
def products(self):
"""What customers can order."""
return [recipe for recipe in self.recipes() if recipe.sellable]
def unit_of(self, code):
if code in self._recipes:
return self._recipes[code].unit
return self.ingredient(code).unit
def name_of(self, code):
if code in self._recipes:
return self._recipes[code].name
return self.ingredient(code).name
def parents_first(self):
"""Every recipe, each one before any recipe it uses. Ties go alphabetically, so the
order is the same every time."""
return list(self._order)
def uses(self, code):
"""The recipes that have `code` as a component, alphabetically."""
return sorted(recipe.code for recipe in self._recipes.values()
if any(component.code == code for component in recipe.components))
def raw_ingredients(self, code):
"""Every ingredient that goes into a recipe, however deep, alphabetically."""
found, stack, seen = set(), [code], set()
while stack:
current = stack.pop()
if current in seen:
continue
seen.add(current)
for component in self.recipe(current).components:
if component.code in self._recipes:
stack.append(component.code)
else:
found.add(component.code)
return sorted(found)
# ------------------------------------------------------------------
# checks
def _check_components(self):
for recipe in self._recipes.values():
if recipe.batch_yield <= 0:
raise DataError(f"recipe {recipe.code!r} makes nothing")
if recipe.lead_days < 0:
raise DataError(f"recipe {recipe.code!r} has a negative lead time")
seen = set()
for component in recipe.components:
if component.code not in self._recipes and component.code not in self._ingredients:
raise DataError(f"recipe {recipe.code!r} uses {component.code!r}, which isn't an ingredient or a recipe")
if component.code in seen:
raise DataError(f"recipe {recipe.code!r} lists {component.code!r} twice")
if component.amount <= 0:
raise DataError(f"recipe {recipe.code!r} uses no {component.code!r}")
seen.add(component.code)
def _parents_first(self):
"""Kahn's algorithm, on the graph where each recipe points at the recipes it uses."""
waiting_on = {code: 0 for code in self._recipes} # how many recipes use it and aren't placed yet
for recipe in self._recipes.values():
for component in recipe.components:
if component.code in self._recipes:
waiting_on[component.code] += 1
ready = sorted(code for code, count in waiting_on.items() if count == 0)
order = []
while ready:
code = ready.pop(0)
order.append(code)
for component in self._recipes[code].components:
if component.code in self._recipes:
waiting_on[component.code] -= 1
if waiting_on[component.code] == 0:
ready.append(component.code)
ready.sort()
if len(order) != len(self._recipes):
stuck = sorted(code for code in self._recipes if code not in order)
raise DataError(f"these recipes go round in a circle: {', '.join(stuck)}")
return order
bakehouse/reports.py 102 lines
"""What people read: the kitchen's production sheets, the delivery list, store room labels,
and the pick lists and shortages from an allocation."""
from .units import format_quantity
def _day(day):
return f"{day:%a} {day.day} {day:%b %Y}"
def _table(rows, widths):
lines = []
for row in rows:
cells = [str(cell).ljust(width) if i < len(row) - 1 else str(cell)
for i, (cell, width) in enumerate(zip(row, widths))]
lines.append(" " + "".join(cells).rstrip())
return lines
def production_sheet(plan, day):
"""The kitchen's sheet for one day: what to make, and what the store room sends up for it."""
book = plan.book
lines = [f"Production for {_day(day)}"]
batches = plan.batches_on(day)
if not batches:
return "\n".join(lines + [" Nothing to make."])
lines.append("")
rows = [("Make", "Batches", "Makes")]
for code, count in sorted(batches.items(), key=lambda item: book.name_of(item[0])):
recipe = book.recipe(code)
rows.append((recipe.name, count, format_quantity(count * recipe.batch_yield, recipe.unit)))
lines += _table(rows, (28, 10, 12))
lines.append("")
rows = [("Ingredient", "Amount")]
for code, amount in sorted(plan.needs_on(day).items(), key=lambda item: book.name_of(item[0])):
ingredient = book.ingredient(code)
rows.append((ingredient.name, format_quantity(amount, ingredient.unit)))
lines += _table(rows, (28, 12))
return "\n".join(lines)
def delivery_list(order_book, book, day):
"""The van's list for one day: each current order and what's in it."""
lines = [f"Deliveries for {_day(day)}"]
orders = sorted(order_book.delivered_on(day), key=lambda order: (order.customer, order.order_id))
if not orders:
return "\n".join(lines + [" No deliveries."])
for order in orders:
lines.append(f" {order.customer} (order {order.order_id}, version {order.version})")
for line in order.lines:
lines.append(f" {line.quantity:>5} x {book.name_of(line.product)}")
return "\n".join(lines)
def store_room_label(lot, book):
"""The sticker that goes on a lot when it comes in."""
ingredient = book.ingredient(lot.ingredient)
lines = [
f"{ingredient.name.upper()} lot {lot.lot_id}",
f"{format_quantity(lot.quantity, ingredient.unit)}, received {lot.received:%d/%m/%Y}",
f"Use by {lot.use_by:%d/%m/%Y}" if lot.use_by else "No use-by date",
]
if ingredient.opened_shelf_days:
days = ingredient.opened_shelf_days
lines.append(f"Once opened, use within {days} day{'s' if days != 1 else ''}")
return "\n".join(lines)
def pick_list(allocation, book, day):
"""What the store room sends up for one day's prep, lot by lot."""
lines = [f"Pick list for {_day(day)}"]
picks = [pick for pick in allocation.picks if pick.day == day]
if not picks:
lines.append(" Nothing to pick.")
rows = [("Ingredient", "Lot", "Amount")] if picks else []
for pick in picks:
ingredient = book.ingredient(pick.ingredient)
rows.append((ingredient.name, pick.lot_id, format_quantity(pick.quantity, ingredient.unit)))
lines += _table(rows, (24, 12, 12))
short = [shortage for shortage in allocation.shortages if shortage.day == day]
if short:
lines.append("")
lines.append(" SHORT:")
for shortage in short:
ingredient = book.ingredient(shortage.ingredient)
lines.append(f" {ingredient.name}: {format_quantity(shortage.quantity, ingredient.unit)}")
return "\n".join(lines)
def shortage_report(allocation, book):
"""Everything the store room can't cover, for whoever does the ordering."""
if not allocation.shortages:
return "No shortages."
lines = ["Shortages"]
rows = [("Day", "Ingredient", "Short by")]
for shortage in allocation.shortages:
ingredient = book.ingredient(shortage.ingredient)
rows.append((_day(shortage.day), ingredient.name, format_quantity(shortage.quantity, ingredient.unit)))
lines += _table(rows, (18, 24, 12))
return "\n".join(lines)
bakehouse/schedule.py 39 lines
"""When the kitchen works. It's closed one day a week and on holidays, and anything that would
be made on a closed day is made on the last open day before it."""
from datetime import timedelta
from .errors import PlannerError
MONDAY = 0
DAY = timedelta(days=1)
class KitchenCalendar:
def __init__(self, closed_weekdays=(MONDAY,), holidays=()):
self.closed_weekdays = frozenset(closed_weekdays) # 0 is Monday, as in date.weekday()
self.holidays = frozenset(holidays)
if len(self.closed_weekdays) >= 7:
raise PlannerError("the kitchen has to be open at least one day a week")
def is_open(self, day):
return day.weekday() not in self.closed_weekdays and day not in self.holidays
def make_day(self, needed_on, lead_days):
"""The day to make something that's needed on `needed_on` and is made `lead_days` before
it's needed. If the kitchen is closed that day, it's the open day before."""
day = needed_on - lead_days * DAY
for _ in range(400):
if self.is_open(day):
return day
day -= DAY
raise PlannerError(f"no open day in the year before {needed_on}")
def open_days(self, start, end):
"""The days from start to end, inclusive, that the kitchen is open."""
days, day = [], start
while day <= end:
if self.is_open(day):
days.append(day)
day += DAY
return days
bakehouse/stock.py 18 lines
"""The store room: what's on the shelves, and which lots the plan takes its ingredients from."""
from collections import defaultdict
def on_hand(lots, day):
"""How much of each ingredient is in the store room and still good on `day`, by code."""
totals = defaultdict(int)
for lot in lots:
if lot.received <= day and (lot.use_by is None or day <= lot.use_by):
totals[lot.ingredient] += lot.quantity
return dict(sorted(totals.items()))
def allocate(plan, lots):
"""Which lots each day's prep takes its ingredients from, and what the store room can't
cover, as an Allocation. PLAN-238: not written yet. The README has what it should do."""
raise NotImplementedError("allocate isn't written yet (PLAN-238)")
bakehouse/units.py 82 lines
"""Quantities, as the recipe sheets, the stock file and the reports write them.
Inside the planner every quantity is a whole number of base units: grams for anything that's
weighed, millilitres for anything measured by volume, and "each" for anything that's counted
(eggs, croissants). The data files can use bigger units and decimals ("1.25 kg", "0.5 l");
`parse_quantity` turns those into base units, and `format_quantity` turns them back for people.
"""
from decimal import Decimal, InvalidOperation
from .errors import DataError
BASE_UNITS = ("g", "ml", "each")
# what each unit in the data files means, in base units
UNITS = {
"g": ("g", 1),
"kg": ("g", 1000),
"ml": ("ml", 1),
"l": ("ml", 1000),
"each": ("each", 1),
}
# the unit format_quantity switches to for big amounts
BIGGER_UNIT = {"g": "kg", "ml": "l"}
def parse_quantity(text):
"""'1.25 kg' -> (1250, 'g'). '6 each' -> (6, 'each').
Raises DataError for a unit it doesn't know, a negative amount, or an amount that isn't a
whole number of base units ('0.5 g')."""
parts = text.split()
if len(parts) != 2:
raise DataError(f"not a quantity: {text!r} (expected an amount and a unit, like '250 g')")
number, unit = parts
unit = unit.lower()
if unit not in UNITS:
raise DataError(f"unknown unit {unit!r} in {text!r}")
try:
value = Decimal(number)
except InvalidOperation:
raise DataError(f"not a number: {number!r} in {text!r}") from None
base_unit, factor = UNITS[unit]
amount = value * factor
if amount < 0:
raise DataError(f"negative quantity: {text!r}")
if amount != amount.to_integral_value():
raise DataError(f"{text!r} isn't a whole number of {base_unit}")
return int(amount), base_unit
def parse_amount(text, unit):
"""A quantity that has to be in `unit` (a base unit). '1.5 kg' with 'g' -> 1500.
A bare number is taken to be in `unit` already: '12' with 'each' -> 12."""
text = text.strip()
if text and " " not in text:
text = f"{text} {unit}"
amount, base_unit = parse_quantity(text)
if base_unit != unit:
raise DataError(f"{text!r} is in {base_unit}, but it has to be in {unit}")
return amount
def format_quantity(amount, unit):
"""For people: 1250 g -> '1.25 kg', 800 g -> '800 g', 2000 ml -> '2 l', 12 each -> '12'."""
if unit == "each":
return f"{amount:,}"
if unit not in BIGGER_UNIT:
raise ValueError(f"not a base unit: {unit!r}")
if abs(amount) < 1000:
return f"{amount:,} {unit}"
whole, rest = divmod(abs(amount), 1000)
sign = "-" if amount < 0 else ""
decimals = f"{rest:03d}".rstrip("0")
number = f"{whole:,}" + (f".{decimals}" if decimals else "")
return f"{sign}{number} {BIGGER_UNIT[unit]}"
def ceil_div(numerator, denominator):
"""The smallest whole number n with n * denominator >= numerator (both positive)."""
return -(-numerator // denominator)
data/closed.csv 6 lines
date,reason
2027-03-26,Good Friday
2027-03-29,Easter Monday
2027-12-25,Christmas Day
2027-12-26,Boxing Day
2028-01-01,New Year's Day
data/components.csv 54 lines
recipe,component,amount
almond-croissant,laminated-dough,1800 g
almond-croissant,frangipane,960 g
almond-croissant,almonds,120 g
celebration-cake,sponge,1500 g
celebration-cake,cream,400 ml
celebration-cake,berries,300 g
celebration-cake,sugar,150 g
choux-paste,butter,400 g
choux-paste,flour,500 g
choux-paste,eggs,18
choux-paste,milk,900 ml
choux-paste,salt,10 g
choux-paste,sugar,20 g
croissant,laminated-dough,3600 g
eclair,choux-paste,1600 g
eclair,pastry-cream,1600 g
eclair,chocolate,400 g
eclair,cream,200 ml
frangipane,almonds,700 g
frangipane,butter,600 g
frangipane,sugar,600 g
frangipane,eggs,10
frangipane,flour,120 g
fruit-tart,sweet-pastry,1500 g
fruit-tart,pastry-cream,1800 g
fruit-tart,berries,1200 g
laminated-dough,flour,3000 g
laminated-dough,butter,1.75 kg
laminated-dough,milk,1200 ml
laminated-dough,sugar,330 g
laminated-dough,yeast,66 g
laminated-dough,salt,60 g
levain,flour,2000 g
pain-au-chocolat,laminated-dough,3360 g
pain-au-chocolat,chocolate,960 g
pastry-cream,milk,2000 ml
pastry-cream,cream,500 ml
pastry-cream,eggs,16
pastry-cream,sugar,450 g
pastry-cream,flour,180 g
pastry-cream,vanilla,15 ml
sourdough-loaf,levain,4800 g
sourdough-loaf,flour,12000 g
sourdough-loaf,salt,280 g
sponge,eggs,30
sponge,sugar,900 g
sponge,flour,900 g
sponge,butter,300 g
sweet-pastry,flour,1250 g
sweet-pastry,butter,750 g
sweet-pastry,sugar,400 g
sweet-pastry,eggs,5
sweet-pastry,salt,5 g
data/ingredients.csv 13 lines
code,name,unit,opened_shelf_days
almonds,Ground almonds,g,
berries,Mixed berries,g,2
butter,Butter,g,
chocolate,Dark chocolate,g,
cream,Double cream,ml,3
eggs,Eggs,each,
flour,Flour,g,
milk,Whole milk,ml,3
salt,Salt,g,
sugar,Caster sugar,g,
vanilla,Vanilla extract,ml,
yeast,Fresh yeast,g,14
data/orders.csv 93 lines
order_id,version,status,customer,delivery_date,product,quantity
W-4101,1,open,Crumb & Co. Market St,2027-03-02,croissant,96
W-4101,1,open,Crumb & Co. Market St,2027-03-02,pain-au-chocolat,48
W-4101,1,open,Crumb & Co. Market St,2027-03-02,almond-croissant,24
W-4101,1,open,Crumb & Co. Market St,2027-03-02,sourdough-loaf,48
W-4101,1,open,Crumb & Co. Market St,2027-03-02,eclair,40
W-4101,1,open,Crumb & Co. Market St,2027-03-02,fruit-tart,12
W-4102,1,open,Crumb & Co. Station Rd,2027-03-02,croissant,144
W-4102,1,open,Crumb & Co. Station Rd,2027-03-02,pain-au-chocolat,48
W-4102,1,open,Crumb & Co. Station Rd,2027-03-02,sourdough-loaf,24
W-4102,1,open,Crumb & Co. Station Rd,2027-03-02,eclair,40
W-4103,1,open,Hilltop Hotel,2027-03-02,croissant,120
W-4103,1,open,Hilltop Hotel,2027-03-02,sourdough-loaf,24
W-4104,1,open,Bean There Cafe,2027-03-02,croissant,96
W-4104,1,open,Bean There Cafe,2027-03-02,pain-au-chocolat,48
W-4105,1,open,Crumb & Co. Market St,2027-03-03,croissant,96
W-4105,1,open,Crumb & Co. Market St,2027-03-03,pain-au-chocolat,48
W-4105,1,open,Crumb & Co. Market St,2027-03-03,almond-croissant,24
W-4105,1,open,Crumb & Co. Market St,2027-03-03,sourdough-loaf,48
W-4105,1,open,Crumb & Co. Market St,2027-03-03,eclair,40
W-4105,1,open,Crumb & Co. Market St,2027-03-03,fruit-tart,12
W-4106,1,open,Crumb & Co. Station Rd,2027-03-03,croissant,144
W-4106,1,open,Crumb & Co. Station Rd,2027-03-03,pain-au-chocolat,48
W-4106,1,open,Crumb & Co. Station Rd,2027-03-03,sourdough-loaf,24
W-4106,1,open,Crumb & Co. Station Rd,2027-03-03,eclair,40
W-4107,1,open,Hilltop Hotel,2027-03-03,croissant,120
W-4107,1,open,Hilltop Hotel,2027-03-03,sourdough-loaf,24
W-4108,1,open,Ivy's Deli,2027-03-03,sourdough-loaf,48
W-4108,1,open,Ivy's Deli,2027-03-03,fruit-tart,12
W-4109,1,open,Bean There Cafe,2027-03-03,croissant,96
W-4109,1,open,Bean There Cafe,2027-03-03,pain-au-chocolat,48
W-4110,1,open,Crumb & Co. Market St,2027-03-04,croissant,96
W-4110,1,open,Crumb & Co. Market St,2027-03-04,pain-au-chocolat,48
W-4110,1,open,Crumb & Co. Market St,2027-03-04,almond-croissant,24
W-4110,1,open,Crumb & Co. Market St,2027-03-04,sourdough-loaf,48
W-4110,1,open,Crumb & Co. Market St,2027-03-04,eclair,40
W-4110,1,open,Crumb & Co. Market St,2027-03-04,fruit-tart,12
W-4111,1,open,Crumb & Co. Station Rd,2027-03-04,croissant,144
W-4111,1,open,Crumb & Co. Station Rd,2027-03-04,pain-au-chocolat,48
W-4111,1,open,Crumb & Co. Station Rd,2027-03-04,sourdough-loaf,24
W-4111,1,open,Crumb & Co. Station Rd,2027-03-04,eclair,40
W-4112,1,open,Hilltop Hotel,2027-03-04,croissant,120
W-4112,1,open,Hilltop Hotel,2027-03-04,sourdough-loaf,24
W-4113,1,open,Bean There Cafe,2027-03-04,croissant,96
W-4113,1,open,Bean There Cafe,2027-03-04,pain-au-chocolat,48
W-4114,1,open,Crumb & Co. Market St,2027-03-05,croissant,96
W-4114,1,open,Crumb & Co. Market St,2027-03-05,pain-au-chocolat,48
W-4114,1,open,Crumb & Co. Market St,2027-03-05,almond-croissant,24
W-4114,1,open,Crumb & Co. Market St,2027-03-05,sourdough-loaf,48
W-4114,1,open,Crumb & Co. Market St,2027-03-05,eclair,40
W-4114,1,open,Crumb & Co. Market St,2027-03-05,fruit-tart,12
W-4115,1,open,Crumb & Co. Station Rd,2027-03-05,croissant,144
W-4115,1,open,Crumb & Co. Station Rd,2027-03-05,pain-au-chocolat,48
W-4115,1,open,Crumb & Co. Station Rd,2027-03-05,sourdough-loaf,24
W-4115,1,open,Crumb & Co. Station Rd,2027-03-05,eclair,40
W-4116,1,open,Hilltop Hotel,2027-03-05,croissant,120
W-4116,1,open,Hilltop Hotel,2027-03-05,sourdough-loaf,24
W-4117,1,open,Ivy's Deli,2027-03-05,sourdough-loaf,48
W-4117,1,open,Ivy's Deli,2027-03-05,fruit-tart,12
W-4118,1,open,Bean There Cafe,2027-03-05,croissant,96
W-4118,1,open,Bean There Cafe,2027-03-05,pain-au-chocolat,48
W-4119,1,open,Crumb & Co. Market St,2027-03-06,croissant,144
W-4119,1,open,Crumb & Co. Market St,2027-03-06,pain-au-chocolat,96
W-4119,1,open,Crumb & Co. Market St,2027-03-06,almond-croissant,48
W-4119,1,open,Crumb & Co. Market St,2027-03-06,sourdough-loaf,72
W-4119,1,open,Crumb & Co. Market St,2027-03-06,eclair,80
W-4119,1,open,Crumb & Co. Market St,2027-03-06,fruit-tart,24
W-4120,1,open,Crumb & Co. Station Rd,2027-03-06,croissant,144
W-4120,1,open,Crumb & Co. Station Rd,2027-03-06,pain-au-chocolat,48
W-4120,1,open,Crumb & Co. Station Rd,2027-03-06,sourdough-loaf,24
W-4120,1,open,Crumb & Co. Station Rd,2027-03-06,eclair,40
W-4121,1,open,Hilltop Hotel,2027-03-06,croissant,120
W-4121,1,open,Hilltop Hotel,2027-03-06,sourdough-loaf,24
W-4122,1,open,Northside Sports Club,2027-03-06,eclair,80
W-4122,1,open,Northside Sports Club,2027-03-06,fruit-tart,24
W-4123,1,open,Bean There Cafe,2027-03-06,croissant,480
W-4123,1,open,Bean There Cafe,2027-03-06,pain-au-chocolat,240
W-4123,2,open,Bean There Cafe,2027-03-06,croissant,528
W-4123,2,open,Bean There Cafe,2027-03-06,pain-au-chocolat,288
W-4123,2,open,Bean There Cafe,2027-03-06,almond-croissant,48
W-4124,1,open,Crumb & Co. Market St,2027-03-07,croissant,144
W-4124,1,open,Crumb & Co. Market St,2027-03-07,pain-au-chocolat,96
W-4124,1,open,Crumb & Co. Market St,2027-03-07,almond-croissant,48
W-4124,1,open,Crumb & Co. Market St,2027-03-07,sourdough-loaf,72
W-4124,1,open,Crumb & Co. Market St,2027-03-07,eclair,80
W-4124,1,open,Crumb & Co. Market St,2027-03-07,fruit-tart,24
W-4125,1,open,Crumb & Co. Station Rd,2027-03-07,croissant,144
W-4125,1,open,Crumb & Co. Station Rd,2027-03-07,pain-au-chocolat,48
W-4125,1,open,Crumb & Co. Station Rd,2027-03-07,sourdough-loaf,24
W-4125,1,open,Crumb & Co. Station Rd,2027-03-07,eclair,40
W-4126,1,open,Hilltop Hotel,2027-03-07,croissant,120
W-4126,1,open,Hilltop Hotel,2027-03-07,sourdough-loaf,24
W-4127,1,open,Pemberton wedding,2027-03-07,celebration-cake,3
data/prices.csv 13 lines
ingredient,price,per
almonds,12.60,kg
berries,9.80,kg
butter,8.40,kg
chocolate,11.20,kg
cream,4.10,l
eggs,0.28,each
flour,0.92,kg
milk,1.15,l
salt,0.60,kg
sugar,1.30,kg
vanilla,95.00,l
yeast,4.80,kg
data/recipes.csv 15 lines
code,name,makes,lead_days,sellable
almond-croissant,Almond croissant,24 each,0,yes
celebration-cake,Celebration cake,1 each,1,yes
choux-paste,Choux paste,2.4 kg,0,no
croissant,Croissant,48 each,0,yes
eclair,Chocolate eclair,40 each,0,yes
frangipane,Frangipane,2.4 kg,1,no
fruit-tart,Fruit tart,12 each,0,yes
laminated-dough,Laminated dough,6 kg,1,no
levain,Levain,4 kg,1,no
pain-au-chocolat,Pain au chocolat,48 each,0,yes
pastry-cream,Pastry cream,3 kg,1,no
sourdough-loaf,Sourdough loaf,24 each,0,yes
sponge,Sponge,3 kg,1,no
sweet-pastry,Sweet pastry,2.5 kg,1,no
data/stock.csv 29 lines
lot_id,ingredient,quantity,received,use_by,opened_on
A-0201,almonds,5 kg,2027-02-01,2027-05-01,2027-02-20
A-0225,almonds,10 kg,2027-02-25,2027-06-01,
BE-0301,berries,8 kg,2027-03-01,2027-03-05,
BE-0304,berries,8 kg,2027-03-04,2027-03-08,
B-0219,butter,25 kg,2027-02-19,2027-03-20,2027-02-26
B-0226,butter,50 kg,2027-02-26,2027-03-27,
B-0303,butter,40 kg,2027-03-03,2027-04-02,
CH-0210,chocolate,20 kg,2027-02-10,2027-08-01,2027-02-23
CH-0302,chocolate,15 kg,2027-03-02,2027-09-01,
C-0224,cream,5 l,2027-02-24,2027-03-01,2027-02-26
C-0226,cream,10 l,2027-02-26,2027-03-06,
C-0303,cream,10 l,2027-03-03,2027-03-12,
E-0225,eggs,360,2027-02-25,2027-03-18,
E-0301,eggs,720,2027-03-01,2027-03-25,
F-0210,flour,18 kg,2027-02-10,,2027-02-24
F-0222,flour,300 kg,2027-02-22,,
F-0301,flour,350 kg,2027-03-01,,
M-0225,milk,20 l,2027-02-25,2027-03-02,2027-02-26
M-0226,milk,40 l,2027-02-26,2027-03-04,
M-0302,milk,40 l,2027-03-02,2027-03-08,
M-0304,milk,30 l,2027-03-04,2027-03-10,
SA-0115,salt,10 kg,2027-01-15,,2027-02-01
SA-0226,salt,10 kg,2027-02-26,,
S-0201,sugar,50 kg,2027-02-01,,
S-0220,sugar,10 kg,2027-02-20,,2027-02-22
V-0110,vanilla,1 l,2027-01-10,,2027-01-10
Y-0222,yeast,2 kg,2027-02-22,2027-03-08,2027-02-22
Y-0301,yeast,2 kg,2027-03-01,2027-03-15,
tests/test_change_request.py 54 lines
"""Change request: opened containers, after the food safety inspection."""
import unittest
from datetime import date
from bakehouse.loaders import load_stock
from bakehouse.models import Ingredient, Lot, Pick, Shortage
from bakehouse.planning import Plan
from bakehouse.recipes import RecipeBook
from bakehouse.stock import allocate
TUE, WED, THU = date(2027, 3, 2), date(2027, 3, 3), date(2027, 3, 4)
BOOK = RecipeBook([Ingredient("butter", "Butter", "g"), Ingredient("milk", "Whole milk", "ml", opened_shelf_days=3)], [])
def a_plan(needs):
return Plan(BOOK, TUE, THU, {}, dict(needs))
class TestOpenedLots(unittest.TestCase):
def test_the_stock_file_says_when_a_lot_was_opened(self):
[opened, unopened] = load_stock(
"lot_id,ingredient,quantity,received,use_by,opened_on\n"
"M-1,milk,20 l,2027-02-25,2027-03-06,2027-02-28\n"
"M-2,milk,40 l,2027-02-26,2027-03-08,\n",
BOOK,
)
self.assertEqual(opened.opened_on, date(2027, 2, 28))
self.assertIsNone(unopened.opened_on)
def test_an_opened_lot_goes_first(self):
lots = [Lot("B-1", "butter", 25_000, date(2027, 2, 19), date(2027, 3, 10)),
Lot("B-2", "butter", 25_000, date(2027, 2, 26), date(2027, 3, 20), opened_on=date(2027, 3, 1))]
allocation = allocate(a_plan({(WED, "butter"): 3_000}), lots)
self.assertEqual(allocation.picks, [Pick(WED, "butter", "B-2", 3_000)])
def test_opened_milk_only_lasts_three_days(self):
lots = [Lot("M-1", "milk", 20_000, date(2027, 2, 25), date(2027, 3, 10), opened_on=date(2027, 2, 27)),
Lot("M-2", "milk", 40_000, date(2027, 2, 26), date(2027, 3, 12))]
allocation = allocate(a_plan({(TUE, "milk"): 5_000, (WED, "milk"): 5_000}), lots)
# opened on Saturday 27 February, so it's good until Tuesday 2 March
self.assertEqual(allocation.picks, [Pick(TUE, "milk", "M-1", 5_000), Pick(WED, "milk", "M-2", 5_000)])
self.assertEqual(allocation.shortages, [])
def test_when_opened_milk_runs_out_its_unopened_milk_or_nothing(self):
lots = [Lot("M-1", "milk", 2_000, date(2027, 2, 25), date(2027, 3, 10), opened_on=date(2027, 3, 1))]
allocation = allocate(a_plan({(WED, "milk"): 5_000}), lots)
self.assertEqual(allocation.picks, [Pick(WED, "milk", "M-1", 2_000)])
self.assertEqual(allocation.shortages, [Shortage(WED, "milk", 3_000)])
if __name__ == "__main__":
unittest.main()
tests/test_existing.py 263 lines
"""What already works. These pass before you change anything; keep them passing."""
import os
import unittest
from datetime import date
from fractions import Fraction
from bakehouse.cli import main
from bakehouse.costing import format_pence, unit_cost
from bakehouse.errors import DataError, PlannerError
from bakehouse.loaders import load_kitchen, load_orders, load_prices, load_recipe_book, load_stock
from bakehouse.models import Component, Ingredient, Order, OrderLine, Recipe
from bakehouse.orders import OrderBook
from bakehouse.planning import build_plan
from bakehouse.recipes import RecipeBook
from bakehouse.reports import delivery_list, production_sheet, store_room_label
from bakehouse.schedule import KitchenCalendar
from bakehouse.units import format_quantity, parse_amount, parse_quantity
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
TUE, WED, THU, FRI, SAT, SUN = (date(2027, 3, day) for day in range(2, 8))
MON = date(2027, 3, 1)
def a_small_book():
"""Dough is made the day before; croissants and rolls both use it."""
return RecipeBook(
[Ingredient("butter", "Butter", "g"), Ingredient("flour", "Flour", "g"),
Ingredient("milk", "Milk", "ml", opened_shelf_days=3)],
[Recipe("dough", "Dough", 5000, "g", 1, (Component("flour", 3000), Component("butter", 1500), Component("milk", 500))),
Recipe("croissant", "Croissant", 50, "each", 0, (Component("dough", 4000),), sellable=True),
Recipe("roll", "Roll", 20, "each", 0, (Component("dough", 1000), Component("milk", 100)), sellable=True)],
)
def an_order(order_id, day, *lines, version=1, cancelled=False, customer="Hilltop Hotel"):
return Order(order_id, version, customer, day, tuple(OrderLine(product, quantity) for product, quantity in lines), cancelled)
class TestUnits(unittest.TestCase):
def test_parse_quantity_turns_everything_into_base_units(self):
self.assertEqual(parse_quantity("1.25 kg"), (1250, "g"))
self.assertEqual(parse_quantity("800 g"), (800, "g"))
self.assertEqual(parse_quantity("0.5 l"), (500, "ml"))
self.assertEqual(parse_quantity("12 each"), (12, "each"))
self.assertEqual(parse_quantity("3 KG"), (3000, "g"))
def test_parse_quantity_rejects_what_it_cant_read(self):
for text in ("0.5 g", "3 cups", "-1 kg", "kg", "1.5", "a lot kg"):
with self.subTest(text=text), self.assertRaises(DataError):
parse_quantity(text)
def test_parse_amount_checks_the_unit(self):
self.assertEqual(parse_amount("1.5 kg", "g"), 1500)
self.assertEqual(parse_amount("12", "each"), 12)
with self.assertRaises(DataError):
parse_amount("1 l", "g")
def test_format_quantity(self):
self.assertEqual(format_quantity(1250, "g"), "1.25 kg")
self.assertEqual(format_quantity(800, "g"), "800 g")
self.assertEqual(format_quantity(2000, "ml"), "2 l")
self.assertEqual(format_quantity(1_500_000, "g"), "1,500 kg")
self.assertEqual(format_quantity(12, "each"), "12")
class TestRecipeBook(unittest.TestCase):
def test_parents_come_before_what_they_use(self):
self.assertEqual(a_small_book().parents_first(), ["croissant", "roll", "dough"])
def test_a_recipe_that_uses_itself_is_refused(self):
with self.assertRaises(DataError) as caught:
RecipeBook([Ingredient("flour", "Flour", "g")],
[Recipe("a", "A", 10, "g", 0, (Component("b", 5),)),
Recipe("b", "B", 10, "g", 0, (Component("a", 5),))])
self.assertIn("a, b", str(caught.exception))
def test_an_unknown_component_is_refused(self):
with self.assertRaises(DataError):
RecipeBook([], [Recipe("a", "A", 10, "g", 0, (Component("sprinkles", 5),))])
def test_raw_ingredients(self):
self.assertEqual(a_small_book().raw_ingredients("roll"), ["butter", "flour", "milk"])
def test_the_real_recipe_book_loads(self):
book = load_kitchen(DATA).book
self.assertEqual(len(book.recipes()), 14)
self.assertEqual([recipe.code for recipe in book.products()],
["almond-croissant", "celebration-cake", "croissant", "eclair", "fruit-tart",
"pain-au-chocolat", "sourdough-loaf"])
dough = book.recipe("laminated-dough")
self.assertEqual((dough.batch_yield, dough.unit, dough.lead_days), (6000, "g", 1))
self.assertIn(Component("butter", 1750), dough.components)
self.assertEqual(book.uses("pastry-cream"), ["eclair", "fruit-tart"])
class TestLoaders(unittest.TestCase):
def test_orders(self):
orders = load_orders(
"order_id,version,status,customer,delivery_date,product,quantity\n"
"W-1,1,open,Ivy's Deli,2027-03-03,sourdough-loaf,48\n"
"W-1,1,open,Ivy's Deli,2027-03-03,fruit-tart,12\n"
"W-2,1,cancelled,Hilltop Hotel,2027-03-04,,\n"
)
self.assertEqual(orders, [
Order("W-1", 1, "Ivy's Deli", WED, (OrderLine("sourdough-loaf", 48), OrderLine("fruit-tart", 12))),
Order("W-2", 1, "Hilltop Hotel", THU, (), cancelled=True),
])
def test_a_bad_row_says_where_it_is(self):
with self.assertRaises(DataError) as caught:
load_orders("order_id,version,status,customer,delivery_date,product,quantity\n"
"W-1,1,open,Ivy's Deli,3 March,sourdough-loaf,48\n")
self.assertIn("orders.csv line 2", str(caught.exception))
def test_stock(self):
[butter, flour] = load_stock(
"lot_id,ingredient,quantity,received,use_by\n"
"B-1,butter,12.5 kg,2027-02-26,2027-03-27\n"
"F-1,flour,200 kg,2027-02-22,\n",
load_kitchen(DATA).book,
)
self.assertEqual((butter.lot_id, butter.quantity, butter.received, butter.use_by),
("B-1", 12_500, date(2027, 2, 26), date(2027, 3, 27)))
self.assertEqual((flour.quantity, flour.use_by), (200_000, None))
def test_a_missing_column(self):
with self.assertRaises(DataError) as caught:
load_recipe_book("code,name\n", "", "")
self.assertIn("unit", str(caught.exception))
class TestCalendar(unittest.TestCase):
def test_the_day_before_a_monday_is_the_sunday_before(self):
calendar = KitchenCalendar()
self.assertEqual(calendar.make_day(TUE, 1), date(2027, 2, 28))
self.assertEqual(calendar.make_day(WED, 1), TUE)
self.assertEqual(calendar.make_day(MON, 0), date(2027, 2, 28))
def test_holidays(self):
calendar = KitchenCalendar(holidays={THU})
self.assertEqual(calendar.make_day(FRI, 1), WED)
self.assertEqual(calendar.open_days(MON, SUN), [TUE, WED, FRI, SAT, SUN])
class TestOrderBook(unittest.TestCase):
def test_the_newest_version_of_each_order_counts(self):
orders = OrderBook([
an_order("W-2", SAT, ("croissant", 100)),
an_order("W-1", FRI, ("croissant", 50)),
an_order("W-2", SAT, ("croissant", 150), version=2),
an_order("W-3", SAT, ("roll", 40)),
an_order("W-3", SAT, version=2, cancelled=True),
])
self.assertEqual([(order.order_id, order.version) for order in orders.current()], [("W-1", 1), ("W-2", 2)])
self.assertEqual([order.order_id for order in orders.for_delivery(SAT, SUN)], ["W-2"])
self.assertEqual(orders.totals(FRI, SAT), {"croissant": 200})
class TestPlanning(unittest.TestCase):
def test_batches_are_rounded_up_once_a_day_for_everything_that_needs_them(self):
orders = [an_order("W-1", WED, ("croissant", 60), ("roll", 30)), an_order("W-2", WED, ("croissant", 30))]
plan = build_plan(a_small_book(), orders, KitchenCalendar(), WED, WED)
self.assertEqual(plan.days(), [TUE, WED])
self.assertEqual(plan.batches_on(WED), {"croissant": 2, "roll": 2})
# 2 batches of croissants and 2 of rolls take 8 kg + 2 kg of dough: 2 batches of dough, made the day before
self.assertEqual(plan.batches_on(TUE), {"dough": 2})
self.assertEqual(plan.needs_on(TUE), {"butter": 3000, "flour": 6000, "milk": 1000})
self.assertEqual(plan.needs_on(WED), {"milk": 200})
def test_dough_for_tuesday_is_made_on_sunday(self):
plan = build_plan(a_small_book(), [an_order("W-1", TUE, ("croissant", 10))], KitchenCalendar(), TUE, TUE)
self.assertEqual(plan.batches, {(TUE, "croissant"): 1, (date(2027, 2, 28), "dough"): 1})
def test_only_the_days_asked_for(self):
orders = [an_order("W-1", WED, ("roll", 20)), an_order("W-2", THU, ("roll", 20))]
plan = build_plan(a_small_book(), orders, KitchenCalendar(), THU, SUN)
self.assertEqual(plan.batches, {(THU, "roll"): 1, (WED, "dough"): 1})
def test_dough_isnt_for_sale(self):
with self.assertRaises(PlannerError):
build_plan(a_small_book(), [an_order("W-1", WED, ("dough", 1))], KitchenCalendar(), WED, WED)
def test_the_sample_week_up_to_thursday(self):
kitchen = load_kitchen(DATA)
plan = build_plan(kitchen.book, kitchen.orders, kitchen.calendar, TUE, SUN)
self.assertEqual(plan.days(), [date(2027, 2, 28), TUE, WED, THU, FRI, SAT, SUN])
self.assertEqual(plan.batches_on(TUE)["croissant"], 10)
self.assertEqual(plan.batches_on(date(2027, 2, 28))["laminated-dough"], 8)
self.assertEqual(plan.needs_on(WED)["butter"], 16_150)
self.assertEqual(plan.needs_on(THU)["eggs"], 104)
class TestReports(unittest.TestCase):
def test_production_sheet(self):
plan = build_plan(a_small_book(), [an_order("W-1", WED, ("croissant", 60), ("roll", 30))], KitchenCalendar(), WED, WED)
self.assertEqual(production_sheet(plan, TUE), "\n".join([
"Production for Tue 2 Mar 2027",
"",
" Make Batches Makes",
" Dough 2 10 kg",
"",
" Ingredient Amount",
" Butter 3 kg",
" Flour 6 kg",
" Milk 1 l",
]))
def test_delivery_list(self):
orders = OrderBook([an_order("W-1", WED, ("croissant", 60), ("roll", 30), customer="Ivy's Deli")])
self.assertEqual(delivery_list(orders, a_small_book(), WED), "\n".join([
"Deliveries for Wed 3 Mar 2027",
" Ivy's Deli (order W-1, version 1)",
" 60 x Croissant",
" 30 x Roll",
]))
def test_store_room_label(self):
[lot] = load_stock("lot_id,ingredient,quantity,received,use_by\nM-1,milk,20 l,2027-02-25,2027-03-02\n", a_small_book())
self.assertEqual(store_room_label(lot, a_small_book()),
"MILK lot M-1\n20 l, received 25/02/2027\nUse by 02/03/2027\nOnce opened, use within 3 days")
class TestCosting(unittest.TestCase):
def test_what_a_croissant_costs(self):
kitchen = load_kitchen(DATA)
# 3.6 kg of laminated dough, at what 6 kg of it costs: 3 kg of flour at 92p a kilo, 1.75 kg of
# butter at £8.40, 1.2 l of milk at £1.15, 330 g of sugar at £1.30, 66 g of yeast at £4.80 and
# 60 g of salt at 60p. That's £19.6218, so a croissant (one 48th of 3.6 kg) costs 24.53p.
self.assertEqual(unit_cost(kitchen.book, kitchen.prices, "croissant"), Fraction(196_218, 100) * 3_600 / 6_000 / 48)
self.assertEqual(format_pence(unit_cost(kitchen.book, kitchen.prices, "croissant")), "£0.25")
def test_format_pence(self):
self.assertEqual(format_pence(Fraction(1234, 3)), "£4.11")
self.assertEqual(format_pence(Fraction(25, 2)), "£0.13")
self.assertEqual(format_pence(Fraction(123_456)), "£1,234.56")
def test_prices_have_to_fit_the_ingredient(self):
with self.assertRaises(DataError):
load_prices("ingredient,price,per\nmilk,1.15,kg\n", a_small_book())
class TestCommandLine(unittest.TestCase):
def test_plan(self):
printed = []
self.assertEqual(main(["--data", DATA, "plan", "2027-03-02"], out=printed.append), 0)
self.assertTrue(printed[0].startswith("Production for Sun 28 Feb 2027\n"))
self.assertIn("Production for Tue 2 Mar 2027", printed[0])
def test_costs(self):
printed = []
self.assertEqual(main(["--data", DATA, "costs"], out=printed.append), 0)
self.assertIn(" Croissant £0.25", printed[0])
def test_a_missing_data_folder(self):
printed = []
with self.assertRaises(OSError):
main(["--data", os.path.join(DATA, "nowhere"), "plan", "2027-03-02"], out=printed.append)
if __name__ == "__main__":
unittest.main()
tests/test_stage1.py 40 lines
"""Stage 1 (PLAN-231): Friday's prep list asks for far too much butter."""
import os
import unittest
from datetime import date
from bakehouse.loaders import load_kitchen, load_orders
from bakehouse.planning import build_plan
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
TUE, FRI, SAT, SUN = date(2027, 3, 2), date(2027, 3, 5), date(2027, 3, 6), date(2027, 3, 7)
class TestTheSampleWeek(unittest.TestCase):
def setUp(self):
kitchen = load_kitchen(DATA)
self.plan = build_plan(kitchen.book, kitchen.orders, kitchen.calendar, TUE, SUN)
def test_fridays_butter(self):
self.assertEqual(self.plan.needs_on(FRI)["butter"], 38_100)
def test_saturdays_croissants(self):
self.assertEqual(self.plan.batches_on(SAT)["croissant"], 20)
class TestAChangedOrder(unittest.TestCase):
def test_it_counts_once(self):
kitchen = load_kitchen(DATA)
orders = load_orders(
"order_id,version,status,customer,delivery_date,product,quantity\n"
"W-1,1,open,Bean There Cafe,2027-03-06,croissant,96\n"
"W-1,2,open,Bean There Cafe,2027-03-06,croissant,144\n"
)
plan = build_plan(kitchen.book, orders, kitchen.calendar, SAT, SAT)
self.assertEqual(plan.batches_on(SAT), {"croissant": 3})
if __name__ == "__main__":
unittest.main()
tests/test_stage2.py 68 lines
"""Stage 2 (PLAN-238): pick lists. Which lots each day's prep uses, and what's short."""
import os
import unittest
from datetime import date
from bakehouse.cli import main
from bakehouse.models import Allocation, Ingredient, Lot, Pick, Shortage
from bakehouse.planning import Plan
from bakehouse.recipes import RecipeBook
from bakehouse.stock import allocate
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
TUE, WED, THU = date(2027, 3, 2), date(2027, 3, 3), date(2027, 3, 4)
BOOK = RecipeBook([Ingredient("butter", "Butter", "g"), Ingredient("flour", "Flour", "g"),
Ingredient("sugar", "Caster sugar", "g")], [])
def a_plan(needs):
"""A plan that needs {(day, ingredient): amount}. (Batches don't matter here.)"""
return Plan(BOOK, TUE, THU, {}, dict(needs))
class TestAllocate(unittest.TestCase):
def test_the_lot_that_goes_off_first_is_used_first(self):
lots = [Lot("B-2", "butter", 25_000, date(2027, 2, 26), date(2027, 3, 20)),
Lot("B-1", "butter", 25_000, date(2027, 2, 19), date(2027, 3, 10))]
allocation = allocate(a_plan({(WED, "butter"): 3_000}), lots)
self.assertEqual(allocation, Allocation(picks=[Pick(WED, "butter", "B-1", 3_000)], shortages=[]))
def test_when_a_lot_runs_out_the_next_one_takes_over(self):
lots = [Lot("B-1", "butter", 2_000, date(2027, 2, 19), date(2027, 3, 10)),
Lot("B-2", "butter", 25_000, date(2027, 2, 26), date(2027, 3, 20))]
allocation = allocate(a_plan({(WED, "butter"): 3_000}), lots)
self.assertEqual(allocation.picks, [Pick(WED, "butter", "B-1", 2_000), Pick(WED, "butter", "B-2", 1_000)])
def test_whats_left_of_a_lot_is_there_the_next_day(self):
lots = [Lot("B-1", "butter", 4_000, date(2027, 2, 19), date(2027, 3, 10)),
Lot("B-2", "butter", 25_000, date(2027, 2, 26), date(2027, 3, 20))]
allocation = allocate(a_plan({(WED, "butter"): 3_000, (THU, "butter"): 3_000}), lots)
self.assertEqual(allocation.picks, [Pick(WED, "butter", "B-1", 3_000),
Pick(THU, "butter", "B-1", 1_000), Pick(THU, "butter", "B-2", 2_000)])
def test_a_lot_past_its_use_by_isnt_used(self):
lots = [Lot("B-1", "butter", 25_000, date(2027, 2, 1), date(2027, 3, 2)),
Lot("B-2", "butter", 25_000, date(2027, 2, 26), date(2027, 3, 20))]
allocation = allocate(a_plan({(WED, "butter"): 3_000}), lots)
self.assertEqual(allocation.picks, [Pick(WED, "butter", "B-2", 3_000)])
def test_what_the_store_room_cant_cover_is_short(self):
lots = [Lot("S-1", "sugar", 6_000, date(2027, 2, 1))]
allocation = allocate(a_plan({(WED, "sugar"): 10_000}), lots)
self.assertEqual(allocation, Allocation(picks=[Pick(WED, "sugar", "S-1", 6_000)],
shortages=[Shortage(WED, "sugar", 4_000)]))
class TestTheCommandLine(unittest.TestCase):
def test_picks(self):
printed = []
self.assertEqual(main(["--data", DATA, "picks", "2027-03-02"], out=printed.append), 0)
self.assertTrue(printed[0].startswith("Pick list for Sun 28 Feb 2027\n"))
self.assertIn("Butter B-0219 15.35 kg", printed[0])
if __name__ == "__main__":
unittest.main()
tests/test_stage3.py 117 lines
"""Stage 3 (PLAN-252): plan all of December in one go."""
import os
import random
import unittest
from dataclasses import fields
from datetime import date, timedelta
from bakehouse.loaders import load_kitchen
from bakehouse.models import Ingredient, Lot, Order, OrderLine, Pick, Shortage
from bakehouse.planning import build_plan
from bakehouse.recipes import RecipeBook
from bakehouse.stock import allocate
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
DECEMBER = [date(2027, 12, 1) + timedelta(days=n) for n in range(31)]
class TookTooLong(Exception):
pass
def metered(things, field, reads_each):
"""Stand-ins for `things` (all the same kind of dataclass) that count how many times anything
reads `field`. They work like the real thing, copies included, but past the limit they give up,
so you don't wait a minute to find out."""
meter = {"reads": 0, "limit": reads_each * len(things)}
real = type(things[0])
class Metered(real):
def __getattribute__(self, name):
if name == field:
meter["reads"] += 1
if meter["reads"] > meter["limit"]:
raise TookTooLong(f"more than {meter['limit']:,} reads of .{name}: far too many for one month's orders")
return super().__getattribute__(name)
Metered.__name__ = Metered.__qualname__ = real.__name__
return [Metered(**{f.name: getattr(thing, f.name) for f in fields(thing)}) for thing in things]
def december():
"""The recipe book, December's orders and the store room.
20,000 orders from 400 customers, in no particular order. About 2,000 were changed after
they were placed, some of them to another day, and about 500 were cancelled. The store room
has what's left from November and a delivery of each ingredient every few days.
(December's numbers don't depend on the change request: no lot is open yet, nothing goes off
once it's opened, and each delivery of an ingredient goes off later than the one before.)"""
kitchen = load_kitchen(DATA)
book = RecipeBook([Ingredient(i.code, i.name, i.unit) for i in kitchen.book.ingredients()], kitchen.book.recipes())
products = [recipe.code for recipe in book.products()]
rng = random.Random(252)
orders = []
for n in range(20_000):
order_id = f"D-{n:05d}"
day = rng.choice(DECEMBER)
lines = tuple(OrderLine(product, rng.randint(1, 3) if product == "celebration-cake" else rng.choice((6, 12, 24, 48)))
for product in rng.sample(products, rng.randint(1, 3)))
orders.append(Order(order_id, 1, f"Customer {n % 400}", day, lines))
change = rng.random()
if change < 0.07:
orders.append(Order(order_id, 2, f"Customer {n % 400}", day, tuple(OrderLine(line.product, line.quantity * 2) for line in lines)))
elif change < 0.10:
orders.append(Order(order_id, 2, f"Customer {n % 400}", rng.choice(DECEMBER), lines))
elif change < 0.125:
orders.append(Order(order_id, 2, f"Customer {n % 400}", day, (), cancelled=True))
elif change < 0.13:
orders.append(Order(order_id, 2, f"Customer {n % 400}", day, (), cancelled=True))
orders.append(Order(order_id, 3, f"Customer {n % 400}", day, lines[:1]))
rng.shuffle(orders)
# (shelf life in days, or None; days between deliveries; lots per delivery; size of each lot)
deliveries = {
"almonds": (180, 7, 2, 250_000), "berries": (4, 2, 6, 160_000), "butter": (30, 3, 12, 105_000),
"chocolate": (240, 7, 4, 240_000), "cream": (10, 2, 6, 110_000), "eggs": (21, 3, 8, 4_320),
"flour": (None, 2, 30, 250_000), "milk": (7, 2, 15, 95_000), "salt": (None, 14, 4, 225_000),
"sugar": (None, 7, 10, 390_000), "vanilla": (None, 28, 2, 60_000), "yeast": (14, 7, 4, 19_000),
}
lots = []
for code, (shelf_life, every, count, size) in deliveries.items():
received, number = date(2027, 11, 22), 0
while received <= date(2027, 12, 31):
for _ in range(count):
number += 1
use_by = received + timedelta(days=shelf_life) if shelf_life else None
lots.append(Lot(f"{code[:3].upper()}-{number:04d}", code, size, received, use_by))
received += timedelta(days=every)
rng.shuffle(lots)
return book, orders, kitchen.calendar, lots
class TestDecember(unittest.TestCase):
def test_the_whole_month(self):
book, orders, calendar, lots = december()
plan = build_plan(book, metered(orders, "order_id", 50), calendar, DECEMBER[0], DECEMBER[-1])
allocation = allocate(plan, lots)
self.assertEqual(len(plan.days()), 27)
self.assertEqual(sum(count for (_, code), count in plan.batches.items() if code == "croissant"), 2_843)
self.assertEqual(plan.total_needed("butter"), 17_766_100)
self.assertEqual(len(allocation.picks), 1_534)
self.assertEqual(allocation.picks[0], Pick(date(2027, 11, 28), "butter", "BUT-0001", 58_800))
self.assertEqual(allocation.shortages, [
Shortage(date(2027, 12, 18), "butter", 199_900),
Shortage(date(2027, 12, 19), "berries", 528_300),
Shortage(date(2027, 12, 23), "butter", 1_424_400),
Shortage(date(2027, 12, 23), "milk", 281_800),
Shortage(date(2027, 12, 24), "berries", 900_000),
Shortage(date(2027, 12, 24), "butter", 674_800),
])
if __name__ == "__main__":
unittest.main()