"""Online orders (Xenia Connect) on the site. Orders placed from the QR menu are pulled from the cloud (services/cloud_sync.py order_pull_worker → store_online_orders) and wait for acceptance. The counter POS (plan step 3.3d, in its device scope) and the manager handle them here: GET /api/connect/orders/board the counter's list: new, in progress, finished lately GET /api/connect/orders?status=… active | history (the manager's lists) 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 never waits for the cloud (Rule 8). Paying an online order is the counter's ordinary payment (POST /api/pos/orders/{id}/pay): online orders belong to whoever holds connect_orders.manage (routers/orders.py _can_access_order). Since phase 3S (S.5) an order carries the customer's time (`requested_for`, None = as soon as possible), its delivery area, the delivery fee as its own line (`system_key` "delivery_fee", paid with the items) and the site's price check (`price_diff`, services/online_check.py). """ import logging from typing import Literal, Optional import httpx from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from pydantic import BaseModel, Field from sqlalchemy.orm import Session, selectinload from config import settings from core.access.deps import require from core.errors import XeniaError from core.timeutil import utcnow from database import get_db from models.order import Order, OrderItem from schemas.order import OrderItemOut, OrderOut from services.ws_bus import broadcast_sync logger = logging.getLogger(__name__) router = APIRouter() MANAGE = "connect_orders.manage" # what may follow what (the cloud refuses anything else) TRANSITIONS: dict[str, set[str]] = { "pending_acceptance": {"accepted", "rejected"}, "accepted": {"preparing"}, "preparing": {"ready", "out_for_delivery"}, "ready": {"delivered"}, "out_for_delivery": {"delivered"}, } IN_PROGRESS = ("accepted", "preparing", "ready", "out_for_delivery") FINISHED = ("delivered", "rejected") UNPAID = ("active", "ready") FINISHED_SHOWN = 20 class RejectRequest(BaseModel): reason: Optional[str] = Field(default=None, max_length=300) class StatusUpdateRequest(BaseModel): status: Literal["preparing", "ready", "out_for_delivery", "delivered"] # ── Helpers ─────────────────────────────────────────────────────────────────── def _get_online_order(order_id: int, db: Session) -> Order: order = db.query(Order).filter(Order.id == order_id, Order.source == "online").first() if not order: raise XeniaError("online.not_found", order_id=order_id) return order def _move(order: Order, to: str) -> None: """Refuses a step that doesn't follow (someone else moved the order meanwhile).""" if to not in TRANSITIONS.get(order.online_status or "", set()): raise XeniaError("online.status_changed") order.online_status = to def _cloud_headers() -> dict: return {"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY} async def _mirror_status_to_cloud(cloud_order_id: int, new_status: str, rejection_reason: str = None): """Best-effort push of status update to cloud. Failures are logged, not raised.""" if not settings.CLOUD_URL or not cloud_order_id: return try: body = {"status": new_status} if rejection_reason: body["rejection_reason"] = rejection_reason async with httpx.AsyncClient(timeout=10) as client: resp = await client.patch( f"{settings.CLOUD_URL}/api/orders/{cloud_order_id}/status", headers=_cloud_headers(), json=body, ) resp.raise_for_status() logger.info("Mirrored status %s for cloud order id %d", new_status, cloud_order_id) except Exception as e: logger.warning("Failed to mirror status to cloud for order id %d: %s", cloud_order_id, e) def _changed(background: BackgroundTasks, order: Order, reason: str = None) -> None: background.add_task(_mirror_status_to_cloud, order.online_order_cloud_id, order.online_status, reason) broadcast_sync("online_order_updated", {"order_id": order.id, "status": order.online_status}) def _item_total(i: OrderItem) -> float: return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity def _iso(dt): return None if dt is None else (dt.isoformat() + "Z" if dt.tzinfo is None else dt.isoformat()) def _board_out(order: Order) -> dict: """An online order as the counter lists it: who, what, how much is still to pay.""" items = [i for i in order.items if i.status not in ("cancelled", "closed")] return { "id": order.id, "ref": order.online_order_ref, "status": order.online_status, "type": order.online_order_type, "opened_at": _iso(order.opened_at), "closed_at": _iso(order.closed_at), "customer": { "name": order.online_customer_name, "phone": order.online_customer_phone, "address": order.online_customer_address, "notes": order.online_customer_notes, }, "requested_for": _iso(order.requested_for), # None = as soon as possible (S.5) "area": order.online_delivery_area, "price_diff": OrderOut._diff(order.online_price_diff), "items": [OrderItemOut.model_validate(i).model_dump(mode="json") for i in items], "fee": round(sum(_item_total(i) for i in items if i.system_key == "delivery_fee"), 2), "total": round(sum(_item_total(i) for i in items), 2), "unpaid": round(sum(_item_total(i) for i in items if i.status in UNPAID), 2), } # ── Endpoints ───────────────────────────────────────────────────────────────── @router.get("/orders/board") def online_board(db: Session = Depends(get_db), user=Depends(require(MANAGE))): """The counter's online orders (3.3d): `incoming` waiting for acceptance (oldest first, the next to answer on top), `in_progress` (oldest first) and the last few `finished`.""" q = db.query(Order).filter(Order.source == "online").options(selectinload(Order.items)) incoming = q.filter(Order.online_status == "pending_acceptance").order_by(Order.opened_at.asc()).all() in_progress = q.filter(Order.online_status.in_(IN_PROGRESS)).order_by(Order.opened_at.asc()).all() finished = q.filter(Order.online_status.in_(FINISHED)).order_by(Order.id.desc()).limit(FINISHED_SHOWN).all() return { "incoming": [_board_out(o) for o in incoming], "in_progress": [_board_out(o) for o in in_progress], "finished": [_board_out(o) for o in finished], } @router.get("/orders", response_model=list[OrderOut]) def get_orders_by_status(status: str, db: Session = Depends(get_db), user=Depends(require(MANAGE))): """ ?status=active → accepted | preparing | ready | out_for_delivery, newest first ?status=history → delivered | rejected, newest first, limit 50 """ if status == "active": return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(IN_PROGRESS)) .order_by(Order.opened_at.desc()).all()) if status == "history": return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(FINISHED)) .order_by(Order.opened_at.desc()).limit(50).all()) raise HTTPException(status_code=400, detail=f"Unknown status filter '{status}'. Use 'active' or 'history'.") @router.get("/orders/incoming", response_model=list[OrderOut]) def get_incoming_orders(db: Session = Depends(get_db), user=Depends(require(MANAGE))): """Return all online orders pending acceptance, newest first.""" return (db.query(Order).filter(Order.source == "online", Order.online_status == "pending_acceptance") .order_by(Order.opened_at.desc()).all()) @router.post("/orders/{order_id}/accept", response_model=OrderOut) def accept_order(order_id: int, background: BackgroundTasks, db: Session = Depends(get_db), user=Depends(require(MANAGE))): """Accept: the kitchen gets its tickets and the order shows on the KDS (until now it was kept off both, as it could still be rejected).""" from routers import orders as orders_api from services.printer_service import route_and_print_sync order = _get_online_order(order_id, db) _move(order, "accepted") orders_api._audit(db, order.id, "ONLINE_ACCEPTED", waiter_id=user.id, note=order.online_order_ref) db.commit() unprinted = [i.id for i in order.items if not i.printed and i.status == "active"] if unprinted: route_and_print_sync(order.id, unprinted, db) db.refresh(order) _changed(background, order) broadcast_sync("order_updated", {"order_id": order.id, "table_id": None, "status": order.status, "action": "items_added", "item_ids": unprinted}) broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status}) return order @router.post("/orders/{order_id}/reject", response_model=OrderOut) def reject_order(order_id: int, body: RejectRequest, background: BackgroundTasks, db: Session = Depends(get_db), user=Depends(require(MANAGE))): from routers import orders as orders_api order = _get_online_order(order_id, db) _move(order, "rejected") order.status = "cancelled" order.closed_at, order.closed_by = utcnow(), user.id for item in order.items: if item.status == "active": item.status = "cancelled" orders_api._audit(db, order.id, "ONLINE_REJECTED", waiter_id=user.id, note=body.reason) db.commit() db.refresh(order) _changed(background, order, body.reason) return order @router.post("/orders/{order_id}/status", response_model=OrderOut) def update_order_status(order_id: int, body: StatusUpdateRequest, background: BackgroundTasks, db: Session = Depends(get_db), user=Depends(require(MANAGE))): """The next step. Delivered (or collected) closes the order and takes it off the KDS. The counter takes the payment first (POST /api/pos/orders/{id}/pay); the manager's list can still mark an unpaid order delivered (its items stay unpaid, as before).""" from routers import orders as orders_api order = _get_online_order(order_id, db) _move(order, body.status) if body.status == "delivered": for item in order.items: if item.kds_status != "served": item.kds_status = "served" order.kds_status = "served" if order.status != "closed": order.status = "closed" order.closed_at, order.closed_by = utcnow(), user.id orders_api._audit(db, order.id, f"ONLINE_{body.status.upper()}", waiter_id=user.id) db.commit() db.refresh(order) _changed(background, order) 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)