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})