feat(cloud): table bookings online, with food ordered ahead

Plan phase 3S, step S.6.
- New order types "reservation" (a table only, no items) and "preorder" (a table with food,
  priced at the online_preorder sales point); online_orders.party_size (migration 0005).
- services/ordering.py: the venue's booking settings (ordering.reservations in the snapshot):
  hours (none = any time), time grid, notice, days ahead (≤ 90), party size; res_slots per
  venue day, res_days, res_check (order.service_unavailable, order.party_invalid,
  order.time_invalid). The public menu's ordering summary gains `reservations`
  {enabled, with_food, party_max, days}; GET /api/orders/{site}/reservation-slots?day=.
- Bookings need a phone; a plain booking refuses items (order.items_not_allowed).
- Status steps for bookings: pending_acceptance → accepted | rejected; accepted → delivered
  (arrived) | cancelled (by the venue); ordinary orders unchanged.
- Order app: "Book a table" (people, day, time, optional food at the pre-order prices),
  booking summary at checkout, a booking tracking page (waiting, confirmed, welcome;
  declined / cancelled with the reason). en/el.
- Tests: tests/test_reservations.py (3), order-app logic test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 19:31:21 +02:00
co-authored by Claude Opus 5.5
parent 9ccb47cfd1
commit 3459c80611
14 changed files with 527 additions and 69 deletions
@@ -0,0 +1,24 @@
"""online orders: party_size (reservations online, plan phase 3S, S.6)
Revision ID: 0005_order_party_size
Revises: 0004_order_area_id
Create Date: 2026-11-16 21:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0005_order_party_size'
down_revision = '0004_order_area_id'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('party_size', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('online_orders', schema=None) as batch_op:
batch_op.drop_column('party_size')
+4 -1
View File
@@ -17,7 +17,7 @@ class OnlineOrder(Base):
public_ref = Column(String, nullable=False)
# the customer's tracking page: random, unguessable (S.2; the ref alone was ambiguous across sites)
tracking_token = Column(String, nullable=True)
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | preorder
order_type = Column(String, nullable=False) # dine_in | takeaway | delivery | reservation | preorder (S.6)
# Customer info
customer_name = Column(String, nullable=False)
@@ -28,6 +28,7 @@ class OnlineOrder(Base):
delivery_area = Column(String, nullable=True) # the delivery area's name (S.3)
delivery_area_id = Column(Integer, nullable=True) # the site's area id (S.5: the site checks the fee)
requested_for = Column(DateTime(timezone=True), nullable=True) # the time slot picked (S.4); null = asap
party_size = Column(Integer, nullable=True) # reservations (S.6): how many guests
sales_point = Column(String, nullable=True) # the site's sales point (phase 3S, S.2)
# Order content — JSON array of ordered items
@@ -41,6 +42,8 @@ class OnlineOrder(Base):
# Status lifecycle:
# pending_acceptance → accepted | rejected
# accepted → preparing → ready | out_for_delivery → delivered
# reservations (S.6): pending_acceptance → accepted (confirmed) | rejected;
# accepted → delivered (the guests arrived) | cancelled (by the venue)
status = Column(String, default="pending_acceptance", nullable=False, index=True)
rejection_reason = Column(String, nullable=True)
+53 -20
View File
@@ -1,6 +1,6 @@
import json
import secrets
from datetime import timezone
from datetime import date, timezone
from fastapi import APIRouter, Depends, HTTPException, Header, Request, status
from passlib.context import CryptContext
from sqlalchemy.orm import Session
@@ -38,6 +38,15 @@ _TRANSITIONS: dict[str, set[str]] = {
"ready": {"delivered"},
"out_for_delivery": {"delivered"},
}
# reservations (S.6): confirmed or declined; then the guests arrive, or the venue cancels
_RES_TRANSITIONS: dict[str, set[str]] = {
"pending_acceptance": {"accepted", "rejected"},
"accepted": {"delivered", "cancelled"},
}
def _transitions(order_type: str) -> dict[str, set[str]]:
return _RES_TRANSITIONS if order_type in ordering.RES_TYPES else _TRANSITIONS
def _require_site(
@@ -77,6 +86,17 @@ def order_slots(site_slug: str, db: Session = Depends(get_db)):
return ordering.summary(menu)
@router.get("/{site_slug}/reservation-slots")
def reservation_slots(site_slug: str, day: str, db: Session = Depends(get_db)):
"""The reservation times of one venue day (S.6): ?day=YYYY-MM-DD → {day, slots: [iso]}."""
_site, menu = _site_and_menu(db, site_slug)
try:
wanted = date.fromisoformat(day)
except ValueError:
raise HTTPException(status_code=422, detail={"code": "order.time_invalid", "params": {}})
return {"day": wanted.isoformat(), "slots": [t.isoformat() for t in ordering.res_slots(menu, wanted)]}
@router.post("/{site_slug}/quote")
def quote_order(site_slug: str, body: QuoteRequest, request: Request, db: Session = Depends(get_db)):
"""The cart priced by the cloud from the venue's menu, for the customer apps (phase 3S)."""
@@ -94,17 +114,28 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
_limit(request, "order", ORDER_LIMIT)
site, menu = _site_and_menu(db, site_slug)
items = [i.model_dump() for i in body.items]
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
reservation = body.order_type in ordering.RES_TYPES # S.6: a table, maybe with food
if body.order_type == "reservation":
if items:
raise HTTPException(status_code=422, detail={"code": "order.items_not_allowed", "params": {}})
priced = None
else:
priced = _priced(menu, body.order_type, items, body.area_id, body.postcode)
if reservation:
problem = ordering.res_check(menu, body.order_type, body.requested_for, body.party_size)
elif body.order_type in ("takeaway", "delivery"): # the online ordering app (S.4)
problem = ordering.check(menu, body.order_type, body.requested_for)
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
else:
problem = None
if problem:
raise HTTPException(status_code=409, detail={"code": problem[0], "params": problem[1]})
if (reservation or body.order_type in ("takeaway", "delivery")) and not (body.customer_phone or "").strip():
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone"]}})
if priced is not None:
try:
check_sent(priced, items, body.total)
except CheckoutError as e:
raise HTTPException(status_code=e.status, detail=e.detail())
if body.order_type == "delivery" and not ((body.customer_address or "").strip() and (body.customer_phone or "").strip()):
raise HTTPException(status_code=422, detail={"code": "order.details_missing", "params": {"fields": ["customer_phone", "customer_address"]}})
@@ -121,16 +152,17 @@ def create_order(site_slug: str, body: OnlineOrderCreate, request: Request, db:
customer_address=body.customer_address,
customer_notes=body.customer_notes,
table_label=(body.customer_table or "").strip() or None,
delivery_area=priced.area_name,
delivery_area_id=priced.area_id,
delivery_area=priced.area_name if priced else None,
delivery_area_id=priced.area_id if priced else None,
# stored as UTC: SQLite keeps no time zone (read back naive = UTC, schemas mark it)
requested_for=(body.requested_for.astimezone(timezone.utc).replace(tzinfo=None)
if body.order_type in ("takeaway", "delivery") and body.requested_for else None),
sales_point=priced.sales_point,
items_json=json.dumps([line.out() for line in priced.lines]),
subtotal=priced.subtotal,
delivery_fee=priced.delivery_fee,
total=priced.total,
if (reservation or body.order_type in ("takeaway", "delivery")) and body.requested_for else None),
party_size=body.party_size if reservation else None,
sales_point=priced.sales_point if priced else None,
items_json=json.dumps([line.out() for line in priced.lines] if priced else []),
subtotal=priced.subtotal if priced else 0.0,
delivery_fee=priced.delivery_fee if priced else 0.0,
total=priced.total if priced else 0.0,
status="pending_acceptance",
)
order.tracking_token = secrets.token_urlsafe(12)
@@ -155,6 +187,7 @@ def track_order(token: str, request: Request, db: Session = Depends(get_db)):
lines = []
return OrderStatusOut(public_ref=order.public_ref, status=order.status, rejection_reason=order.rejection_reason,
order_type=order.order_type, requested_for=order.requested_for, created_at=order.created_at,
party_size=order.party_size,
lines=[{"name": x.get("name"), "quantity": x.get("quantity"), "unit_price": x.get("unit_price"),
"options": [o.get("name") for o in x.get("options") or []]} for x in lines],
subtotal=order.subtotal, delivery_fee=order.delivery_fee, total=order.total)
@@ -224,7 +257,7 @@ def update_order_status(
if not order:
raise HTTPException(status_code=404, detail="Order not found")
allowed = _TRANSITIONS.get(order.status, set())
allowed = _transitions(order.order_type).get(order.status, set())
if body.status not in allowed:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+5 -2
View File
@@ -31,8 +31,9 @@ class QuoteRequest(BaseModel):
class OnlineOrderCreate(BaseModel):
order_type: str # dine_in | takeaway | delivery | preorder
order_type: str # dine_in | takeaway | delivery | reservation | preorder
customer_name: str = Field(min_length=1, max_length=100)
party_size: Optional[int] = None # reservations (S.6)
customer_phone: Optional[str] = Field(default=None, max_length=40)
customer_address: Optional[str] = Field(default=None, max_length=500)
customer_notes: Optional[str] = Field(default=None, max_length=1000)
@@ -40,7 +41,7 @@ class OnlineOrderCreate(BaseModel):
area_id: Optional[int] = None # the delivery area picked (S.3)
postcode: Optional[str] = Field(default=None, max_length=20)
requested_for: Optional[datetime] = None # a time slot (S.4); None = as soon as possible
items: list[OrderItemIn] = Field(max_length=100)
items: list[OrderItemIn] = Field(default_factory=list, max_length=100)
# what the customer was shown: compared, never stored as sent
subtotal: Optional[float] = None
delivery_fee: Optional[float] = None
@@ -62,6 +63,7 @@ class OrderStatusOut(BaseModel):
# S.4: what the tracking page shows (all optional: older clients ignore them)
order_type: Optional[str] = None
requested_for: Optional[datetime] = None
party_size: Optional[int] = None # reservations (S.6)
created_at: Optional[datetime] = None
lines: Optional[list] = None
subtotal: Optional[float] = None
@@ -85,6 +87,7 @@ class PendingOrderOut(BaseModel):
delivery_area: Optional[str] = None # the delivery area's name (S.3)
delivery_area_id: Optional[int] = None # the site's area id (S.5)
requested_for: Optional[datetime] = None # when the customer wants it (S.4); None = as soon as possible
party_size: Optional[int] = None # reservations (S.6)
sales_point: Optional[str] = None # the site's sales point (S.2)
items_json: str
subtotal: float
+75 -1
View File
@@ -89,7 +89,8 @@ def summary(snapshot: dict, now: datetime | None = None) -> dict:
open_now = is_open(cfg, local_now)
return {"services": cfg["services"], "open_now": open_now, "asap": bool(cfg["asap"]) and open_now,
"prep_minutes": cfg["prep_minutes"], "timezone": tz.key,
"slots": [t.isoformat() for t in slots(snapshot, now)]}
"slots": [t.isoformat() for t in slots(snapshot, now)],
"reservations": res_summary(snapshot, now)} # S.6
def check(snapshot: dict, service: str, requested_for: datetime | None, now: datetime | None = None):
@@ -109,3 +110,76 @@ def check(snapshot: dict, service: str, requested_for: datetime | None, now: dat
if any(abs((wanted - t).total_seconds()) < 1 for t in slots(snapshot, now)):
return None
return "order.time_invalid", {}
# ── Reservations online (plan phase 3S, step S.6) ─────────────────────────────
# The snapshot's `ordering.reservations` (site routers/fees.py ReservationsBody):
# {enabled, with_food, hours: {"0".."6": [[from, to], ...]}, slot_minutes, days_ahead,
# notice_minutes, party_max, fire_minutes}
# "reservation" = a table only; "preorder" = a table with food ready on arrival (with_food).
# Times: on the slot grid of the venue's day, at least notice_minutes from now, within today +
# days_ahead, inside the hours (none = any time). fire_minutes is the site's (the kitchen).
RES_DEFAULTS = {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
"notice_minutes": 60, "party_max": 10}
RES_TYPES = ("reservation", "preorder")
def res_config(snapshot: dict) -> dict:
cfg = {**RES_DEFAULTS, **((snapshot.get("ordering") or {}).get("reservations") or {})}
cfg["enabled"] = bool(cfg.get("enabled"))
cfg["with_food"] = cfg["enabled"] and bool(cfg.get("with_food"))
cfg["slot_minutes"] = max(5, int(cfg.get("slot_minutes") or 30))
cfg["days_ahead"] = max(0, min(90, int(cfg.get("days_ahead") or 0)))
cfg["notice_minutes"] = max(0, int(cfg.get("notice_minutes") or 0))
cfg["party_max"] = max(1, min(100, int(cfg.get("party_max") or 1)))
return cfg
def res_slots(snapshot: dict, day, now: datetime | None = None) -> list[datetime]:
"""The reservation times on one venue day (a date), aware venue local, in order."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
local_now = (now or datetime.now(timezone.utc)).astimezone(tz)
if day < local_now.date() or day > (local_now + timedelta(days=cfg["days_ahead"])).date():
return []
earliest = local_now + timedelta(minutes=cfg["notice_minutes"])
t = datetime(day.year, day.month, day.day, tzinfo=tz)
out = []
while t.date() == day:
if t >= earliest and is_open(cfg, t):
out.append(t)
t = (t.astimezone(timezone.utc) + timedelta(minutes=cfg["slot_minutes"])).astimezone(tz)
return out
def res_days(snapshot: dict, now: datetime | None = None) -> list[str]:
"""The venue days (ISO dates) with at least one reservation time."""
cfg, tz = res_config(snapshot), venue_tz(snapshot)
if not cfg["enabled"]:
return []
today = (now or datetime.now(timezone.utc)).astimezone(tz).date()
days = (today + timedelta(days=n) for n in range(cfg["days_ahead"] + 1))
return [d.isoformat() for d in days if res_slots(snapshot, d, now)]
def res_summary(snapshot: dict, now: datetime | None = None) -> dict:
cfg = res_config(snapshot)
return {"enabled": cfg["enabled"], "with_food": cfg["with_food"], "party_max": cfg["party_max"],
"days": res_days(snapshot, now)}
def res_check(snapshot: dict, order_type: str, requested_for: datetime | None, party_size, now: datetime | None = None):
"""None if the reservation may be requested, else (code, params)."""
cfg = res_config(snapshot)
if not cfg["enabled"] or (order_type == "preorder" and not cfg["with_food"]):
return "order.service_unavailable", {"service": order_type}
if isinstance(party_size, bool) or not isinstance(party_size, int) or not 1 <= party_size <= cfg["party_max"]:
return "order.party_invalid", {"max": cfg["party_max"]}
if requested_for is None or requested_for.tzinfo is None:
return "order.time_invalid", {}
wanted = requested_for.astimezone(venue_tz(snapshot))
if any(abs((wanted - t).total_seconds()) < 1 for t in res_slots(snapshot, wanted.date(), now)):
return None
return "order.time_invalid", {}
+114
View File
@@ -0,0 +1,114 @@
"""Reservations online (plan phase 3S, step S.6): a table only, or a table with food ready on
arrival; times on the venue's grid, inside its hours, with notice, up to N days ahead; party
size; the venue confirms or declines, then the guests arrive or the venue cancels."""
import json
from datetime import date, datetime, timezone
from zoneinfo import ZoneInfo
from services import ordering
from test_checkout import COLA, ORDERING, _code, _h, _venue
ATH = ZoneInfo("Europe/Athens")
DINNER = {"0": [["19:00", "23:00"]], "6": [["13:00", "16:00"], ["19:00", "23:00"]]} # Mon, Sun
def snap(**res):
return {"timezone": "Europe/Athens", "ordering": {**ORDERING, "reservations": {
"enabled": True, "with_food": True, "hours": DINNER, "slot_minutes": 30, "days_ahead": 14,
"notice_minutes": 120, "party_max": 8, **res}}}
def at(y, mo, d, h, mi):
return datetime(y, mo, d, h, mi, tzinfo=ATH).astimezone(timezone.utc)
def test_times_days_and_checks():
s, now = snap(), at(2026, 11, 15, 18, 10) # Sunday 18:10
sunday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 15), now)]
assert sunday == ["20:30", "21:00", "21:30", "22:00", "22:30"] # 2 h notice; lunch is over
monday = [t.strftime("%H:%M") for t in ordering.res_slots(s, date(2026, 11, 16), now)]
assert monday[0] == "19:00" and monday[-1] == "22:30"
assert ordering.res_slots(s, date(2026, 11, 17), now) == [] # Tuesday: no hours = closed
assert ordering.res_slots(s, date(2026, 11, 30), now) == [] # beyond 14 days
days = ordering.res_days(s, now)
assert days[:3] == ["2026-11-15", "2026-11-16", "2026-11-22"] and "2026-11-17" not in days
ok = at(2026, 11, 16, 20, 0)
assert ordering.res_check(s, "reservation", ok, 4, now) is None
assert ordering.res_check(s, "preorder", ok, 4, now) is None
assert ordering.res_check(s, "reservation", ok, 9, now) == ("order.party_invalid", {"max": 8})
assert ordering.res_check(s, "reservation", ok, 0, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", ok, None, now)[0] == "order.party_invalid"
assert ordering.res_check(s, "reservation", at(2026, 11, 16, 20, 10), 2, now)[0] == "order.time_invalid" # off grid
assert ordering.res_check(s, "reservation", at(2026, 11, 15, 19, 0), 2, now)[0] == "order.time_invalid" # too soon
assert ordering.res_check(s, "reservation", None, 2, now)[0] == "order.time_invalid"
assert ordering.res_check(snap(with_food=False), "preorder", ok, 2, now) == ("order.service_unavailable", {"service": "preorder"})
assert ordering.res_check(snap(enabled=False), "reservation", ok, 2, now)[0] == "order.service_unavailable"
assert ordering.res_summary(snap(enabled=False), now) == {"enabled": False, "with_food": False, "party_max": 8, "days": []}
def _push(client, site, numeric, **res):
menu = client.get(f"/api/menu/{site['site_id']}").json()
hours = {str(d): [["00:00", "23:59"]] for d in range(7)}
snapshot = {"categories": menu["categories"], "timezone": "Europe/Athens",
"ordering": {**ORDERING, "reservations": {"enabled": True, "with_food": True, "hours": hours, "slot_minutes": 30,
"days_ahead": 3, "notice_minutes": 0, "party_max": 6, **res}}}
for cat in snapshot["categories"]:
for p in cat["products"]:
if p["id"] == COLA:
p["sold_at"] = [*p["sold_at"], "online_preorder"]
p["prices"] = {**p["prices"], "online_preorder": 2.6}
r = client.post("/api/menu/sync", headers=_h(site), json={"site_id": numeric, "snapshot_json": json.dumps(snapshot)})
assert r.status_code in (200, 204), r.text
def test_book_a_table_with_and_without_food(client, admin_h):
site, numeric = _venue(client, admin_h)
_push(client, site, numeric)
menu = client.get(f"/api/menu/{site['site_id']}").json()
res = menu["ordering"]["reservations"]
assert res["enabled"] and res["with_food"] and res["party_max"] == 6 and len(res["days"]) == 4
day = res["days"][1]
slots = client.get(f"/api/orders/{site['site_id']}/reservation-slots", params={"day": day}).json()["slots"]
assert len(slots) == 48
when = slots[40] # 20:00 tomorrow
book = lambda **x: client.post(f"/api/orders/{site['site_id']}", json={ # noqa: E731
"order_type": "reservation", "customer_name": "Eleni", "customer_phone": "6977777777", "party_size": 4,
"requested_for": when, "customer_notes": "By the window", **x})
plain = book()
assert plain.status_code == 201, plain.text
assert _code(book(party_size=7)) == "order.party_invalid"
assert _code(book(customer_phone="")) == "order.details_missing"
assert _code(book(items=[{"product_id": COLA, "quantity": 1}])) == "order.items_not_allowed"
assert _code(book(requested_for=None)) == "order.time_invalid"
food = book(order_type="preorder", items=[{"product_id": COLA, "quantity": 2}], total=5.2)
assert food.status_code == 201, food.text
assert food.json()["total"] == 5.2 # the preorder price
assert _code(book(order_type="preorder", items=[])) == "order.empty"
pending = {o["public_ref"]: o for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json()}
p = pending[plain.json()["public_ref"]]
assert (p["order_type"], p["party_size"], p["total"], json.loads(p["items_json"]), p["sales_point"]) == ("reservation", 4, 0.0, [], None)
assert datetime.fromisoformat(p["requested_for"].replace("Z", "+00:00")) == datetime.fromisoformat(when)
f = pending[food.json()["public_ref"]]
assert (f["order_type"], f["sales_point"], f["party_size"]) == ("preorder", "online_preorder", 4)
# the venue confirms, then the guests arrive (or it cancels); the customer's page follows
st = lambda oid, s: client.patch(f"/api/orders/{oid}/status", headers=_h(site), json={"status": s}) # noqa: E731
assert st(p["id"], "preparing").status_code == 422
assert st(p["id"], "accepted").status_code == 204
assert st(p["id"], "delivered").status_code == 204
assert st(f["id"], "accepted").status_code == 204 and st(f["id"], "cancelled").status_code == 204
track = client.get(f"/api/orders/track/{food.json()['tracking_token']}").json()
assert (track["status"], track["order_type"], track["party_size"], track["total"]) == ("cancelled", "preorder", 4, 5.2)
# an ordinary order can't be "cancelled" this way
order = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "takeaway", "customer_name": "M",
"customer_phone": "6900000000", "items": [{"product_id": COLA, "quantity": 1}]})
oid = next(o["id"] for o in client.get(f"/api/orders/pending/{numeric}", headers=_h(site)).json() if o["public_ref"] == order.json()["public_ref"])
st(oid, "accepted")
assert st(oid, "cancelled").status_code == 422
def test_reservations_off_by_default(client, admin_h):
site, _ = _venue(client, admin_h)
assert client.get(f"/api/menu/{site['site_id']}").json()["ordering"]["reservations"]["enabled"] is False
r = client.post(f"/api/orders/{site['site_id']}", json={"order_type": "reservation", "customer_name": "E", "customer_phone": "690000000",
"party_size": 2, "requested_for": datetime.now(timezone.utc).isoformat()})
assert _code(r) == "order.service_unavailable"