Files
bonaminandClaude Opus 5.5 070c9cf625 feat: tables and orders in the manager on v2 (platform-v2 step 6.9)
- manager: new pages/orders/ (Tables page cards + quick actions, order page with
  lines, multi-select pay/discount/cancel/tab, staff + customer, price changes,
  history, the menu + cart beside it); a free table opens a new order on first
  Send; v1 TablesPage, OrderDetailPage, DesktopOrderingTab, ManagerOrderDrawer
  and PaymentMethodModal removed
- ordering by line id like the phones: GET /api/orders/menu (the counter's
  product shape, in-store prices); the product dialog, cart rules and quote hook
  move to packages/ordering (@xenia/ordering), shared by counter, menu tablet,
  manager
- close follows orders.close_with_unpaid (pay first, or write off after saying
  so) on the order page and the overview's quick view; paying asks cash or card
- a confirmed booking can keep its table ahead (manager, phones, counter):
  POST /api/connect/bookings/{id}/table, reservations create/PATCH; refused with
  reservation.table_kept within 2 h of another booking
- tests: test_manager_ordering.py, online bookings +2, manager orders.test.mjs,
  @xenia/ordering, e2e manager.mjs (take, change, pay-first close, RESERVED)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:58:46 +02:00

236 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 keep_table(db, r, table_id: int | None) -> None:
"""A booking's table ahead (plan step 6.9) or none. Refused when the table is kept for another
booking within two hours of this one (reservation.table_kept)."""
from datetime import timedelta
from core.timeutil import venue_strftime
from models.reservation import Reservation
from models.table import Table
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)
clash = (db.query(Reservation).filter(Reservation.id != r.id, Reservation.table_id == table_id,
Reservation.status.in_(("pending", "requested")),
Reservation.reserved_for > r.reserved_for - timedelta(hours=2),
Reservation.reserved_for < r.reserved_for + timedelta(hours=2)).first())
if clash is not None:
raise XeniaError("reservation.table_kept", name=clash.guest_name, time=venue_strftime(clash.reserved_for, "%H:%M"))
r.table_id = table_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.ws_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