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
+4
View File
@@ -85,6 +85,10 @@ CODES: dict[str, tuple[int, str]] = {
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
"online.not_found": (404, "Online order {order_id} not found."),
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
@@ -0,0 +1,38 @@
"""reservations: online bookings with food ordered ahead (plan phase 3S, S.6)
Revision ID: 0020_online_reservations
Revises: 0019_online_order_site_side
Create Date: 2026-11-16 21:30:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0020_online_reservations'
down_revision = '0019_online_order_site_side'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('reservations', schema=None) as batch_op:
batch_op.add_column(sa.Column('online_order_cloud_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('online_ref', sa.String(), nullable=True))
batch_op.add_column(sa.Column('items_json', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('total', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('online_price_diff', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('fire_at', UTCDateTime(), nullable=True))
batch_op.add_column(sa.Column('order_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('response_note', sa.Text(), nullable=True))
batch_op.create_index(batch_op.f('ix_reservations_online_order_cloud_id'), ['online_order_cloud_id'], unique=False)
batch_op.create_foreign_key('fk_reservations_order_id_orders', 'orders', ['order_id'], ['id'])
def downgrade() -> None:
with op.batch_alter_table('reservations', schema=None) as batch_op:
batch_op.drop_constraint('fk_reservations_order_id_orders', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_reservations_online_order_cloud_id'))
for c in ('response_note', 'order_id', 'fire_at', 'online_price_diff', 'total', 'items_json', 'online_ref', 'online_order_cloud_id'):
batch_op.drop_column(c)
+15 -2
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, ForeignKey, Text
from sqlalchemy import Column, Float, Integer, String, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from database import Base
@@ -22,7 +22,8 @@ class Reservation(Base):
# Optional table assignment (assignable/editable later)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
# Lifecycle: pending | arrived | cancelled | no_show
# Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show;
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
status = Column(String, nullable=False, default="pending")
# Source: manager_app | waiter_app | online
@@ -34,9 +35,21 @@ class Reservation(Base):
# For future online reservations: cloud-side customer identifier
online_customer_id = Column(String, nullable=True)
# Online bookings (phase 3S, S.6): the cloud's order (status mirrored to the customer's page)
online_order_cloud_id = Column(Integer, nullable=True, index=True)
online_ref = Column(String, nullable=True) # "ORD-0042"
# food ordered ahead: the cloud's lines (its prices) until the kitchen gets them, then the order
items_json = Column(Text, nullable=True) # JSON list as the cloud sent it; NULL = a table only
total = Column(Float, nullable=True)
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched
fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) # created at fire time
response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it)
created_at = Column(UTCDateTime, default=utcnow)
updated_at = Column(UTCDateTime, default=utcnow,
onupdate=utcnow)
table = relationship("Table", foreign_keys=[table_id])
order = relationship("Order", foreign_keys=[order_id])
created_by = relationship("User", foreign_keys=[created_by_user_id])
@@ -18,5 +18,6 @@ MODULE = Module(
Mount('routers.fees', '/api/connect/fees'),
Mount('routers.connect_orders', '/api/connect'),
),
workers=('services.cloud_sync:order_pull_worker',),
# S.6: bookings' food goes to the kitchen at its fire time
workers=('services.cloud_sync:order_pull_worker', 'services.online_reservations:fire_worker'),
)
+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()
+6
View File
@@ -60,6 +60,12 @@ class ReservationOut(BaseModel):
created_at: datetime
updated_at: datetime
# online bookings (phase 3S, S.6)
online_ref: Optional[str] = None
total: Optional[float] = None
order_id: Optional[int] = None
fire_at: Optional[datetime] = None
# Denormalized for convenience
table_label: Optional[str] = None
created_by_name: Optional[str] = None
+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
+5 -3
View File
@@ -190,9 +190,11 @@ def test_supervisor_starts_and_stops_workers(monkeypatch):
started, after = asyncio.run(scenario())
assert started == ["connect_menu:services.cloud_sync:menu_push_worker",
"connect_orders:services.cloud_sync:order_pull_worker"]
assert after == ["connect_orders:services.cloud_sync:order_pull_worker"]
assert calls == ["run", "run"]
"connect_orders:services.cloud_sync:order_pull_worker",
"connect_orders:services.online_reservations:fire_worker"] # S.6
assert after == ["connect_orders:services.cloud_sync:order_pull_worker",
"connect_orders:services.online_reservations:fire_worker"]
assert calls == ["run", "run", "run"]
def test_worker_specs_resolve_to_coroutines():
+202
View File
@@ -0,0 +1,202 @@
"""Table bookings from the online ordering app (plan phase 3S, step S.6): a booking arrives as a
reservation to confirm or decline; food ordered ahead reaches the kitchen at its fire time (the
booking time − the venue's fire minutes), not at once; the guests are seated and their food
moves to the table; every step is mirrored to the cloud."""
import json
from datetime import timedelta
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import drawer_printer, menu, till # noqa: F401 (fixtures)
from tests.test_pos_online import cloud, counter, kds_ids # noqa: F401 (fixtures)
def book(db, menu, cloud_id=701, *, minutes=120, food=True, party=4):
"""A booking as the cloud hands it over."""
from core.timeutil import utcnow
from services.cloud_sync import store_online_orders
booked = []
lines = [{"product_id": menu["burger"].id, "name": "Burger", "quantity": 2, "unit_price": 10.0, "options": []},
{"product_id": menu["coffee"].id, "name": "Freddo", "quantity": 1, "unit_price": 3.0, "options": []}] if food else []
order = {
"id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": "preorder" if food else "reservation",
"sales_point": "online_preorder" if food else None, "customer_name": "Eleni", "customer_phone": "6977777777",
"customer_notes": "By the window", "party_size": party, "status": "pending_acceptance",
"requested_for": (utcnow() + timedelta(minutes=minutes)).isoformat(), "created_at": utcnow().isoformat(),
"items_json": json.dumps(lines), "subtotal": 23.0 if food else 0.0, "delivery_fee": 0.0, "total": 23.0 if food else 0.0,
}
stored = store_online_orders(db, [order], booked)
return stored[cloud_id], booked
@pytest.fixture
def fire_in(db):
"""The venue's fire minutes (Online ordering → Reservations)."""
from models.settings import PosSettings
def _set(minutes):
value = json.dumps({"reservations": {"enabled": True, "with_food": True, "fire_minutes": minutes}})
row = db.get(PosSettings, "connect_orders.ordering")
if row is None:
db.add(PosSettings(key="connect_orders.ordering", value=value))
else:
row.value = value
db.commit()
return _set
def bookings(client, counter):
r = client.get("/api/connect/bookings", headers=counter["h"])
assert r.status_code == 200, r.text
return r.json()
def test_a_booking_with_food_reaches_the_kitchen_at_its_fire_time(client, db, counter, menu, owner_h, cloud, fire_in):
from core.timeutil import utcnow
from models.order import Order
from models.reservation import Reservation
from services import online_reservations as svc
fire_in(30)
rid, booked = book(db, menu)
assert booked == [rid]
r = db.get(Reservation, rid)
assert (r.status, r.source, r.party_size, r.online_ref, r.total, r.order_id) == ("requested", "online", 4, "ORD-0701", 23.0, None)
assert book(db, menu)[0] == -rid # a repeated pull stores it once
b = bookings(client, counter)
assert [x["id"] for x in b["requested"]] == [rid] and b["upcoming"] == []
x = b["requested"][0]
assert [(line["name"], line["quantity"]) for line in x["lines"]] == [("Burger", 2), ("Freddo", 1)] and x["price_diff"] is None
# confirmed two hours ahead: the kitchen doesn't get anything yet
c = client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"])
assert c.status_code == 200, c.text
assert c.json()["status"] == "pending" and c.json()["order_id"] is None
db.refresh(r)
assert abs((r.fire_at - (r.reserved_for - timedelta(minutes=30))).total_seconds()) < 1
assert cloud["mirror"] == [(701, "accepted", None)] and cloud["printed"] == []
assert svc.fire_due(db) == []
assert err(client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"])) == "reservation.status_changed"
# fire time: the order is made, printed, and on the KDS
fired = svc.fire_due(db, now=r.fire_at + timedelta(seconds=1))
db.refresh(r)
assert fired == [r.order_id]
order = db.get(Order, r.order_id)
assert (order.source, order.online_status, order.online_order_ref, order.sales_point, order.customer_count) == \
("online", None, "ORD-0701", "online_preorder", 4)
assert [(i.product_name, i.quantity, i.unit_price) for i in order.items] == [("Burger", 2, 10.0), ("Freddo", 1, 3.0)]
assert cloud["printed"] == [(order.id, sorted(i.id for i in order.items))]
assert order.id in kds_ids(client, owner_h)
assert svc.fire_due(db, now=utcnow() + timedelta(days=1)) == [] # once
# not on the counter's online board (it's a booking's food, not an order to answer)
board = client.get("/api/connect/orders/board", headers=counter["h"]).json()
assert order.id not in [o["id"] for lst in board.values() for o in lst]
def test_seated_the_food_moves_to_the_table(client, db, counter, menu, cloud, fire_in, owner_h):
from models.order import Order
from models.reservation import Reservation
from models.table import Table
fire_in(15)
t5 = Table(number=5, label="T5", is_active=True)
t6 = Table(number=6, label="T6", is_active=True)
db.add_all([t5, t6])
db.commit()
busy = Order(table_id=t6.id, opened_by=counter["user"].id, status="open", business_day_id=counter["day"].id)
db.add(busy)
db.commit()
rid, _ = book(db, menu, cloud_id=702)
h = counter["h"]
assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={})) == "reservation.status_changed" # not confirmed
client.post(f"/api/connect/bookings/{rid}/confirm", headers=h)
assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": t6.id})) == "reservation.table_busy"
assert err(client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": 9999})) == "reservation.table_unknown"
# early: the food goes to the kitchen now, on table 5
a = client.post(f"/api/connect/bookings/{rid}/arrive", headers=h, json={"table_id": t5.id})
assert a.status_code == 200, a.text
assert a.json()["status"] == "arrived" and a.json()["table_label"] == "T5" and a.json()["order_id"]
order = db.get(Order, a.json()["order_id"])
assert order.table_id == t5.id and len(cloud["printed"]) == 1
assert [m[1] for m in cloud["mirror"]] == ["accepted", "delivered"]
assert db.get(Reservation, rid).status == "arrived"
def test_fired_before_arrival_then_seated(client, db, counter, menu, cloud, fire_in):
from models.order import Order
from models.table import Table
from services import online_reservations as svc
fire_in(60)
t7 = Table(number=7, label="T7", is_active=True)
db.add(t7)
db.commit()
rid, _ = book(db, menu, cloud_id=703, minutes=30) # due in 30 min, fire 60 before → at once
c = client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"]).json()
assert c["order_id"] and len(cloud["printed"]) == 1 # confirmed late: fired right away
order_id = c["order_id"]
assert db.get(Order, order_id).table_id is None
a = client.post(f"/api/connect/bookings/{rid}/arrive", headers=counter["h"], json={"table_id": t7.id}).json()
db.expire_all()
assert a["order_id"] == order_id and db.get(Order, order_id).table_id == t7.id and len(cloud["printed"]) == 1
assert svc.fire_due(db) == []
def test_no_business_day_the_food_waits(client, db, counter, menu, cloud, fire_in):
from models.business_day import BusinessDay
from models.reservation import Reservation
from services import online_reservations as svc
fire_in(0)
rid, _ = book(db, menu, cloud_id=704, minutes=1)
client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"])
db.expire_all()
r = db.get(Reservation, rid)
counter["day"].status = "closed"
db.commit()
later = r.fire_at + timedelta(minutes=5)
assert svc.fire_due(db, now=later) == [] and db.get(Reservation, rid).order_id is None
db.add(BusinessDay(status="open", opened_at=later, business_date=counter["day"].business_date, opened_by_id=counter["user"].id))
db.commit()
assert len(svc.fire_due(db, now=later)) == 1
def test_a_table_only_decline_and_cancel(client, db, counter, menu, cloud):
from models.reservation import Reservation
rid, _ = book(db, menu, cloud_id=705, food=False, party=2)
r = db.get(Reservation, rid)
assert r.items_json is None and r.total is None
d = client.post(f"/api/connect/bookings/{rid}/decline", headers=counter["h"], json={"reason": "Fully booked"})
assert d.json()["status"] == "declined" and d.json()["response_note"] == "Fully booked"
assert cloud["mirror"] == [(705, "rejected", "Fully booked")]
assert bookings(client, counter)["requested"] == []
rid2, _ = book(db, menu, cloud_id=706, food=False)
client.post(f"/api/connect/bookings/{rid2}/confirm", headers=counter["h"])
assert [x["id"] for x in bookings(client, counter)["upcoming"]] == [rid2]
x = client.post(f"/api/connect/bookings/{rid2}/cancel", headers=counter["h"], json={"status": "no_show"}).json()
assert x["status"] == "no_show" and cloud["mirror"][-1] == (706, "cancelled", None)
assert x["order_id"] is None
def test_the_manager_card_steps_are_mirrored(client, db, owner_h, menu, cloud, counter):
rid, _ = book(db, menu, cloud_id=707, food=False)
assert rid in [r["id"] for r in client.get("/api/reservations/?tab=upcoming", headers=owner_h).json()]
client.post(f"/api/connect/bookings/{rid}/confirm", headers=owner_h)
r = client.patch(f"/api/reservations/{rid}/status", headers=owner_h, json={"status": "arrived"})
assert r.status_code == 200, r.text
assert r.json()["status"] == "arrived" and cloud["mirror"][-1] == (707, "delivered", None)
def test_bookings_need_the_key(client, pair, make_user):
token, _ = pair("pos_counter", "Other till")
jwt = terminal_login(client, token, make_user(role="waiter"))
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}
assert err(client.get("/api/connect/bookings", headers=h)) == "access.denied"
def test_reservation_settings(client, owner_h):
body = client.get("/api/connect/fees/ordering", headers=owner_h).json()
assert body["reservations"] == {"enabled": False, "with_food": False, "hours": {}, "slot_minutes": 30, "days_ahead": 30,
"notice_minutes": 60, "party_max": 10, "fire_minutes": 20}
body["reservations"].update(enabled=True, with_food=True, hours={"4": [["19:00", "23:30"]]}, party_max=8, fire_minutes=25)
r = client.put("/api/connect/fees/ordering", headers=owner_h, json=body)
assert r.status_code == 200, r.text
assert r.json()["reservations"]["hours"] == {"4": [["19:00", "23:30"]]} and r.json()["reservations"]["fire_minutes"] == 25
body["reservations"]["party_max"] = 0
assert client.put("/api/connect/fees/ordering", headers=owner_h, json=body).status_code == 422