feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival

Plan phase 3S, step S.6.
- Pull: "reservation" / "preorder" orders become Reservations waiting for an answer
  (status "requested"; services/online_reservations.py), with the food ordered ahead kept on
  the booking (items_json at the cloud's prices, the site's price check) — no order yet.
  Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total,
  online_price_diff, fire_at, order_id, response_note).
- Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker
  (connect_orders, every 20 s) turns the food into an order at that time (needs an open
  business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival
  fires at once. Seating moves the order to the table (refused if the table has an open
  order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud.
- Found: the KDS filter dropped every online order without an online status (SQL NULL in
  NOT(a AND b)) — made NULL-safe.
- Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm,
  decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel,
  no-show); the Online badge and chime count booking requests.
- Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice,
  days ahead, party size, fire minutes); the dashboard's reservations card confirms /
  declines online requests; the reservations router delegates online bookings' status steps.
- Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app
  (book with food → the venue confirms), terminal (request → confirm → the two dishes reach
  the KDS at the fire time, not before → seated), manager (booking settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 19:31:44 +02:00
co-authored by Claude Opus 5.5
parent 0ca700279a
commit 70c8f2bb57
33 changed files with 1402 additions and 105 deletions
+128
View File
@@ -10,6 +10,8 @@ GET /api/connect/orders/incoming waiting for acceptance
POST /api/connect/orders/{id}/accept → kitchen tickets and the KDS
POST /api/connect/orders/{id}/reject
POST /api/connect/orders/{id}/status preparing | ready | out_for_delivery | delivered
GET /api/connect/bookings table bookings: requested, upcoming (S.6)
POST /api/connect/bookings/{id}/confirm | decline | arrive | cancel
The steps follow the cloud's (cloud_backend/routers/orders.py _TRANSITIONS), and every change
is mirrored to the cloud in the background so the customer's tracking page follows; the site
@@ -246,3 +248,129 @@ def update_order_status(order_id: int, body: StatusUpdateRequest, background: Ba
if body.status == "delivered":
broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status})
return order
# ── Table bookings from the online ordering app (phase 3S, S.6) ───────────────
# services/online_reservations.py has the rules; here the counter (and the manager) list them,
# confirm or decline, seat the guests (their food moves to the table) or cancel.
class BookingAnswer(BaseModel):
reason: Optional[str] = Field(default=None, max_length=300)
class ArriveRequest(BaseModel):
table_id: Optional[int] = None
class CancelRequest(BaseModel):
status: Literal["cancelled", "no_show"] = "cancelled"
reason: Optional[str] = Field(default=None, max_length=300)
def _booking_lines(r) -> list:
import json
try:
lines = json.loads(r.items_json or "[]")
except ValueError:
lines = []
return [{"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 [] if isinstance(o, dict)]} for x in lines]
def booking_out(r) -> dict:
return {
"id": r.id, "ref": r.online_ref, "status": r.status, "source": r.source,
"guest_name": r.guest_name, "party_size": r.party_size, "phone": r.phone, "note": r.note,
"reserved_for": _iso(r.reserved_for),
"table_id": r.table_id, "table_label": (r.table.label or f"T{r.table.number}") if r.table else None,
"lines": _booking_lines(r), "total": r.total, "price_diff": OrderOut._diff(r.online_price_diff),
"fire_at": _iso(r.fire_at), "order_id": r.order_id, "response_note": r.response_note,
}
def _booking(db, reservation_id: int):
from models.reservation import Reservation
r = db.get(Reservation, reservation_id)
if r is None:
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
return r
def _booking_changed(background: BackgroundTasks, r) -> None:
from services.online_reservations import mirror_args
args = mirror_args(r)
if args:
background.add_task(_mirror_status_to_cloud, *args)
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status})
@router.get("/bookings")
def list_bookings(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""The counter's bookings: `requested` (online, waiting for an answer, soonest first) and
`upcoming` (confirmed, from 4 hours ago on, soonest first; any source)."""
from datetime import timedelta
from models.reservation import Reservation
q = db.query(Reservation)
requested = q.filter(Reservation.status == "requested").order_by(Reservation.reserved_for).all()
upcoming = (q.filter(Reservation.status == "pending", Reservation.reserved_for >= utcnow() - timedelta(hours=4))
.order_by(Reservation.reserved_for).limit(100).all())
return {"requested": [booking_out(r) for r in requested], "upcoming": [booking_out(r) for r in upcoming]}
@router.post("/bookings/{reservation_id}/confirm")
def confirm_booking(reservation_id: int, background: BackgroundTasks, db: Session = Depends(get_db),
user=Depends(require(MANAGE))):
"""Confirm: the customer is told; food ordered ahead goes to the kitchen at its fire time
(at once if that time has passed and the day is open)."""
from routers import orders as orders_api
from services import online_reservations as svc
r = _booking(db, reservation_id)
svc.confirm(db, r)
db.commit()
svc.fire_due(db)
db.refresh(r)
if r.order_id:
orders_api._audit(db, r.order_id, "ONLINE_ACCEPTED", waiter_id=user.id, note=r.online_ref)
db.commit()
_booking_changed(background, r)
return booking_out(r)
@router.post("/bookings/{reservation_id}/decline")
def decline_booking(reservation_id: int, body: BookingAnswer, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
from services import online_reservations as svc
r = _booking(db, reservation_id)
svc.decline(db, r, body.reason)
db.commit()
_booking_changed(background, r)
return booking_out(r)
@router.post("/bookings/{reservation_id}/arrive")
def arrive_booking(reservation_id: int, body: ArriveRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""The guests are here: seat them (optional table); their food's order moves to the table
(and goes to the kitchen now if it hadn't yet)."""
from services import online_reservations as svc
r = _booking(db, reservation_id)
fired = svc.arrive(db, r, body.table_id)
db.commit()
if fired:
svc.send_to_kitchen(db, r.order_id, fired)
elif r.order_id:
broadcast_sync("order_updated", {"order_id": r.order_id, "table_id": r.table_id, "status": "open", "action": "moved"})
db.refresh(r)
_booking_changed(background, r)
return booking_out(r)
@router.post("/bookings/{reservation_id}/cancel")
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
from services import online_reservations as svc
r = _booking(db, reservation_id)
svc.cancel(db, r, body.status, body.reason)
db.commit()
_booking_changed(background, r)
return booking_out(r)
+38 -14
View File
@@ -75,6 +75,42 @@ def fees_payload(db) -> dict:
return {"areas": [area_out(a) for a in areas], "rules": [rule_out(r) for r in rules]}
def _clean_hours(v):
out = {}
for day, ranges in (v or {}).items():
if str(day) not in {str(d) for d in range(7)}:
raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)")
if not isinstance(ranges, list) or len(ranges) > 4:
raise ValueError("at most 4 time ranges a day")
clean = []
for r in ranges:
if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]:
raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different")
clean.append([r[0], r[1]])
if clean:
out[str(day)] = sorted(clean)
return out
class ReservationsBody(BaseModel):
"""Table bookings online (plan phase 3S, S.6): a table only, or with food ordered ahead
(`with_food`). The cloud enforces hours, the time grid, notice, days ahead and party size;
`fire_minutes` is the site's: the kitchen gets pre-ordered food that long before arrival."""
enabled: bool = False
with_food: bool = False
hours: dict = Field(default_factory=dict) # like OrderingBody.hours; none = any time
slot_minutes: int = Field(default=30, ge=5, le=120)
days_ahead: int = Field(default=30, ge=0, le=90)
notice_minutes: int = Field(default=60, ge=0, le=7 * 24 * 60) # the earliest booking from now
party_max: int = Field(default=10, ge=1, le=100)
fire_minutes: int = Field(default=20, ge=0, le=240)
@field_validator("hours")
@classmethod
def _hours(cls, v):
return _clean_hours(v)
class OrderingBody(BaseModel):
"""What the online ordering app offers and when (plan phase 3S, S.4). The cloud enforces
it at checkout. hours: {"0".."6" (Mon..Sun): [["HH:MM", "HH:MM"], ...]}; no hours at all =
@@ -86,6 +122,7 @@ class OrderingBody(BaseModel):
slot_minutes: int = Field(default=15, ge=5, le=120) # the times offered, every N minutes
days_ahead: int = Field(default=0, ge=0, le=7) # 0 = today only
asap: bool = True # "as soon as possible" offered while open
reservations: ReservationsBody = Field(default_factory=ReservationsBody) # S.6
@field_validator("services")
@classmethod
@@ -95,20 +132,7 @@ class OrderingBody(BaseModel):
@field_validator("hours")
@classmethod
def _hours(cls, v):
out = {}
for day, ranges in (v or {}).items():
if str(day) not in {str(d) for d in range(7)}:
raise ValueError("hours are keyed 0 (Monday) to 6 (Sunday)")
if not isinstance(ranges, list) or len(ranges) > 4:
raise ValueError("at most 4 time ranges a day")
clean = []
for r in ranges:
if not (isinstance(r, (list, tuple)) and len(r) == 2 and all(isinstance(x, str) and HHMM.match(x) for x in r)) or r[0] == r[1]:
raise ValueError("a time range is [\"HH:MM\", \"HH:MM\"], start and end different")
clean.append([r[0], r[1]])
if clean:
out[str(day)] = sorted(clean)
return out
return _clean_hours(v)
class AreaBody(BaseModel):
+2 -1
View File
@@ -314,7 +314,8 @@ def kds_orders(
db.query(Order)
.filter(Order.status.in_(["open", "partially_paid", "paid"]))
# an online order waits for the counter to accept it (3.3d); before that it may still be rejected
.filter(~((Order.source == "online") & (Order.online_status == "pending_acceptance")))
# (NULL-safe: a booking's food order has no online status, S.6)
.filter((Order.source != "online") | Order.online_status.is_(None) | (Order.online_status != "pending_acceptance"))
.options(
joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.ingredients),
joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.options),
+21 -4
View File
@@ -1,5 +1,5 @@
from core.timeutil import utcnow, venue_day_window
from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime, timezone
@@ -77,14 +77,14 @@ def list_reservations(
q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end)
if tab == "upcoming":
# pending + no_show (actionable), ordered soonest first
q = q.filter(Reservation.status.in_(["pending", "no_show"]))
# requested (online, to confirm, S.6) + pending + no_show (actionable), soonest first
q = q.filter(Reservation.status.in_(["requested", "pending", "no_show"]))
q = q.order_by(Reservation.reserved_for.asc())
elif tab == "history":
# arrived, cancelled, plus no_show/pending that are clearly in the past
now = utcnow()
q = q.filter(
(Reservation.status.in_(["arrived", "cancelled"])) |
(Reservation.status.in_(["arrived", "cancelled", "declined"])) |
(
Reservation.status.in_(["no_show", "pending"]) &
(Reservation.reserved_for < now)
@@ -143,6 +143,7 @@ def update_reservation(
def update_reservation_status(
reservation_id: int,
body: ReservationStatusUpdate,
background: BackgroundTasks,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
@@ -153,6 +154,22 @@ def update_reservation_status(
if not r:
raise HTTPException(status_code=404, detail="Reservation not found")
if r.online_order_cloud_id and r.status in ("requested", "pending") and body.status in ("arrived", "cancelled", "no_show"):
# an online booking (phase 3S, S.6): the same steps as the counter's, and the customer's page follows
from routers.connect_orders import _booking_changed
from services import online_reservations as svc
if body.status == "arrived":
fired = svc.arrive(db, r, r.table_id)
db.commit()
if fired:
svc.send_to_kitchen(db, r.order_id, fired)
else:
svc.cancel(db, r, body.status, None)
db.commit()
db.refresh(r)
_booking_changed(background, r)
return _enrich(r)
r.status = body.status
r.updated_at = utcnow()
db.commit()