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
+56 -20
View File
@@ -347,7 +347,7 @@ def _with_table(cloud_order: dict):
return f"Table {table}" + (f" · {notes}" if notes else "")
def store_online_orders(db, orders: list[dict]) -> dict:
def store_online_orders(db, orders: list[dict], booked: list | None = None) -> dict:
"""Store online orders as the cloud hands them over (GET /api/orders/pending/{site}):
one local order each, waiting for acceptance (plan step 3.3d). An order already stored
(an earlier pull whose "synced" mark didn't reach the cloud) isn't stored twice.
@@ -356,11 +356,14 @@ def store_online_orders(db, orders: list[dict]) -> dict:
Phase 3S, S.5: the order keeps the customer's time and delivery area; the cloud's prices
are what the customer pays (items at the cloud's unit prices, the delivery fee as a
system-product line, services/system_products.py), and the site's own engine checks them
(services/online_check.py: a difference is kept on the order and shown, never changed)."""
(services/online_check.py: a difference is kept on the order and shown, never changed).
S.6: table bookings ("reservation", "preorder") become Reservations waiting to be confirmed
(services/online_reservations.py); their ids go into `booked` (new ones) and the map."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.user import User
from services import online_check, system_products
from services import online_check, online_reservations, system_products
# the opener is the first account with the manager dashboard (orders need one)
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
@@ -368,6 +371,18 @@ def store_online_orders(db, orders: list[dict]) -> dict:
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
out = {}
for cloud_order in orders:
if cloud_order.get("order_type") in ("reservation", "preorder"):
seen = online_reservations.known(db, cloud_order["id"])
if seen is not None:
out[cloud_order["id"]] = -seen.id
continue
r = online_reservations.store(db, cloud_order, sales_points.ONLINE_PREORDER)
db.commit()
out[cloud_order["id"]] = r.id
if booked is not None:
booked.append(r.id)
logger.info("Online booking %s pulled as reservation %d", cloud_order["public_ref"], r.id)
continue
known = db.query(Order).filter(Order.source == "online",
Order.online_order_cloud_id == cloud_order["id"]).first()
if known is not None:
@@ -400,21 +415,7 @@ def store_online_orders(db, orders: list[dict]) -> dict:
)
db.add(local_order)
db.flush()
for item in json.loads(cloud_order.get("items_json") or "[]"):
db.add(OrderItem(
order_id=local_order.id,
product_id=item.get("product_id"),
added_by=opener_id,
quantity=item.get("quantity", 1),
unit_price=item.get("unit_price", 0.0),
unit_cost=_cost(db, item.get("product_id")),
# the site's entry shape (services/pos_cart.py: quick add-ons, prices included in unit_price)
selected_options=json.dumps([
{"id": o.get("id"), "name": o.get("name"), "price_delta": o.get("price", 0.0), "type": "quick"}
if isinstance(o, dict) else o for o in item.get("options", [])]),
status="active",
printed=False,
))
add_cloud_items(db, local_order.id, opener_id, json.loads(cloud_order.get("items_json") or "[]"))
fee = round(float(cloud_order.get("delivery_fee") or 0.0), 2)
if fee > 0:
fee_product = system_products.get(db, system_products.DELIVERY_FEE)
@@ -433,6 +434,37 @@ def store_online_orders(db, orders: list[dict]) -> dict:
return out
def add_cloud_items(db, order_id: int, opener_id: int, items: list) -> list:
"""The cloud's lines as order items, at the cloud's prices (what the customer pays)."""
from models.order import OrderItem
out = []
for item in items:
row = OrderItem(
order_id=order_id,
product_id=item.get("product_id"),
added_by=opener_id,
quantity=item.get("quantity", 1),
unit_price=item.get("unit_price", 0.0),
unit_cost=_cost(db, item.get("product_id")),
# the site's entry shape (services/pos_cart.py: quick add-ons, prices included in unit_price)
selected_options=json.dumps([
{"id": o.get("id"), "name": o.get("name"), "price_delta": o.get("price", 0.0), "type": "quick"}
if isinstance(o, dict) else o for o in item.get("options", [])]),
status="active",
printed=False,
)
db.add(row)
out.append(row)
return out
def online_opener_id(db) -> int:
"""Orders need an opener: the first account with the manager dashboard."""
from models.user import User
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
return system_user.id if system_user else 1
def _aware(raw):
"""An ISO time from the cloud → aware UTC (naive = UTC); None for none or garbage."""
if not raw:
@@ -485,8 +517,9 @@ async def _pull_pending_orders():
from services.sse_bus import broadcast_sync
db = SessionLocal()
booked = []
try:
stored = store_online_orders(db, orders)
stored = store_online_orders(db, orders, booked)
except Exception as e:
db.rollback()
logger.error("Failed to process pulled orders: %s", e)
@@ -494,7 +527,10 @@ async def _pull_pending_orders():
finally:
db.close()
new_ids = [local_id for local_id in stored.values() if local_id > 0]
bookings = {o["id"] for o in orders if o.get("order_type") in ("reservation", "preorder")}
new_ids = [local_id for cloud_id, local_id in stored.items() if local_id > 0 and cloud_id not in bookings]
if booked:
broadcast_sync("reservation_requested", {"count": len(booked), "reservation_ids": booked})
if new_ids:
# the counter POS and the manager light up (and ring) at once
broadcast_sync("online_order_received", {"count": len(new_ids), "order_ids": new_ids})
@@ -0,0 +1,216 @@
"""Table bookings from the online ordering app (plan phase 3S, step S.6).
A booking arrives with the online orders pull (services/cloud_sync.store_online_orders) as a
Reservation in status "requested": a table only (cloud type "reservation") or a table with food
ordered ahead ("preorder", its lines at the cloud's prices in `items_json`). The venue:
confirm(db, r) requested → pending (confirmed); the food gets its fire time
decline(db, r, reason) requested → declined (the customer sees the reason)
arrive(db, r, table_id) pending → arrived; the food's order moves to the table
cancel(db, r, status, reason) pending → cancelled | no_show
The food reaches the kitchen at `fire_at` = the booking time − the venue's fire minutes
(Online ordering → Reservations; connect_orders.ordering.reservations.fire_minutes), never at
once: fire_due() (the fire_worker, every FIRE_EVERY seconds, while connect_orders runs) turns
the lines into an order (an online order with no online status, so not on the counter's online
board; on the table once the guests arrive), prints its kitchen tickets and puts it on the KDS.
It needs an open business day; if none is open at fire time it waits for one. Guests who
arrive early get their food fired on arrival.
Every step is mirrored to the cloud so the customer's page follows (cloud statuses:
accepted = confirmed, rejected = declined, delivered = arrived, cancelled).
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
from datetime import timedelta
from core.errors import XeniaError
from core.timeutil import utcnow
logger = logging.getLogger(__name__)
FIRE_EVERY = int(os.environ.get("XENIA_FIRE_CHECK_SECONDS", "20")) # tests run it faster
CLOUD_STATUS = {"pending": "accepted", "declined": "rejected", "arrived": "delivered", "cancelled": "cancelled", "no_show": "cancelled"}
def store(db, cloud_order: dict, point: str):
"""A pulled booking → a Reservation waiting to be confirmed (flushed). Repeats return None."""
from models.reservation import Reservation
from services import online_check
from services.cloud_sync import _aware
if db.query(Reservation).filter(Reservation.online_order_cloud_id == cloud_order["id"]).first() is not None:
return None
items = json.loads(cloud_order.get("items_json") or "[]")
food = cloud_order.get("order_type") == "preorder" and bool(items)
diff = online_check.diff(db, cloud_order, point) if food else None
r = Reservation(
guest_name=cloud_order.get("customer_name") or "?",
party_size=max(1, int(cloud_order.get("party_size") or 1)),
phone=cloud_order.get("customer_phone"),
note=cloud_order.get("customer_notes"),
reserved_for=_aware(cloud_order.get("requested_for")) or utcnow(),
status="requested",
source="online",
online_order_cloud_id=cloud_order["id"],
online_ref=cloud_order.get("public_ref"),
items_json=json.dumps(items) if food else None,
total=round(float(cloud_order.get("total") or 0.0), 2) if food else None,
online_price_diff=json.dumps(diff) if diff else None,
)
db.add(r)
db.flush()
return r
def known(db, cloud_id: int):
from models.reservation import Reservation
return db.query(Reservation).filter(Reservation.online_order_cloud_id == cloud_id).first()
def fire_minutes(db) -> int:
from routers.fees import ordering_settings
return ordering_settings(db)["reservations"]["fire_minutes"]
def _need(r, *statuses):
if r.status not in statuses:
raise XeniaError("reservation.status_changed", current=r.status)
def confirm(db, r) -> None:
_need(r, "requested")
r.status = "pending"
if r.items_json:
r.fire_at = r.reserved_for - timedelta(minutes=fire_minutes(db))
r.updated_at = utcnow()
def decline(db, r, reason: str | None) -> None:
_need(r, "requested")
r.status, r.response_note, r.updated_at = "declined", reason, utcnow()
def cancel(db, r, status: str, reason: str | None) -> None:
_need(r, "pending")
r.status, r.response_note, r.updated_at = status, reason, utcnow()
if r.order is not None:
# the food was already made: the order stays (the venue decides what to charge), the
# items not yet paid can be cancelled from the order as usual
logger.info("Reservation %s cancelled after its food was fired (order %s)", r.id, r.order_id)
def table_busy(db, table_id: int, order_id: int | None = None) -> bool:
from models.order import Order
q = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("open", "partially_paid")))
if order_id is not None:
q = q.filter(Order.id != order_id)
return q.first() is not None
def arrive(db, r, table_id: int | None) -> list:
"""The guests are here: their table (optional), and their food (fired now if it wasn't).
Returns the item ids sent to the kitchen now."""
from models.table import Table
_need(r, "pending")
if table_id is not None:
if db.query(Table).filter(Table.id == table_id, Table.is_active.is_(True)).first() is None:
raise XeniaError("reservation.table_unknown", table_id=table_id)
if table_busy(db, table_id, r.order_id):
raise XeniaError("reservation.table_busy", table_id=table_id)
r.table_id = table_id
r.status, r.updated_at = "arrived", utcnow()
fired = []
if r.items_json and r.order_id is None:
fired = fire(db, r) or []
if r.order is not None and r.table_id is not None:
r.order.table_id = r.table_id
return fired
def fire(db, r) -> list | None:
"""The booking's food → an order for the kitchen (flushed; tickets printed by the caller).
None while no business day is open. Returns the new item ids."""
from models.business_day import BusinessDay
from models.order import Order
from services.cloud_sync import add_cloud_items, online_opener_id
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None:
return None
opener = online_opener_id(db)
note = f"{r.guest_name} · {r.party_size}" + (f" · {r.note}" if r.note else "")
order = Order(
table_id=r.table_id if r.table_id and not table_busy(db, r.table_id) else None,
opened_by=opener, status="open", source="online", order_type="here",
sales_point="online_preorder", business_day_id=day.id,
online_order_ref=r.online_ref, online_order_type="preorder", online_status=None,
online_customer_name=r.guest_name, online_customer_phone=r.phone, online_customer_notes=note,
online_price_diff=r.online_price_diff, requested_for=r.reserved_for, customer_count=r.party_size,
)
db.add(order)
db.flush()
items = add_cloud_items(db, order.id, opener, json.loads(r.items_json or "[]"))
db.flush()
r.order_id = order.id
logger.info("Reservation %s (%s): food fired as order %s", r.id, r.online_ref, order.id)
return [i.id for i in items]
def send_to_kitchen(db, order_id: int, item_ids: list) -> None:
"""Kitchen tickets and the KDS for a fired booking's order (after commit)."""
from services.printer_service import route_and_print_sync
from services.sse_bus import broadcast_sync
if item_ids:
try:
route_and_print_sync(order_id, item_ids, db)
except Exception as e: # a printer problem never undoes the order
logger.error("Reservation food order %s: printing failed: %s", order_id, e)
broadcast_sync("order_updated", {"order_id": order_id, "table_id": None, "status": "open", "action": "items_added", "item_ids": item_ids})
broadcast_sync("kds_order_updated", {"order_id": order_id, "kds_status": "pending"})
def fire_due(db, now=None) -> list[int]:
"""Fire every confirmed booking whose food is due (needs an open business day). Commits.
Returns the new order ids."""
from models.reservation import Reservation
now = now or utcnow()
due = (db.query(Reservation)
.filter(Reservation.status.in_(("pending", "arrived")), Reservation.items_json.isnot(None),
Reservation.order_id.is_(None), Reservation.fire_at.isnot(None), Reservation.fire_at <= now)
.order_by(Reservation.fire_at).all())
out = []
for r in due:
ids = fire(db, r)
if ids is None:
break # no business day open: try again later
db.commit()
send_to_kitchen(db, r.order_id, ids)
out.append(r.order_id)
return out
async def fire_worker():
"""Module worker (connect_orders): fires bookings' food when it's due."""
from database import SessionLocal
def _run():
db = SessionLocal()
try:
fire_due(db)
finally:
db.close()
while True:
try:
await asyncio.to_thread(_run)
except Exception as e:
logger.warning("Reservation fire check failed: %s", e)
await asyncio.sleep(FIRE_EVERY)
def mirror_args(r):
"""(cloud id, cloud status, reason) for status mirroring, or None for a booking not from online."""
if not r.online_order_cloud_id or r.status not in CLOUD_STATUS:
return None
return r.online_order_cloud_id, CLOUD_STATUS[r.status], r.response_note