feat(backend,terminal): online orders on the counter POS (platform-v2 step 3.3d)

- Counter POS gets an "Online" mode (module on + connect_orders.manage): New / In
  progress / Finished, a chime on arrival (and every 30 s while one waits), badge,
  toast in any mode; the order panel offers only the next step: accept / reject with
  a reason, preparing, ready or out for delivery, then take the payment (shared
  PaymentDialog, drawer, shift) and mark delivered/served.
- connect_orders router on v2 conventions: require(connect_orders.manage), error
  codes online.not_found / online.status_changed, the cloud's step order enforced,
  audit rows, GET /api/connect/orders/board. POS device scope gains connect_orders.*;
  barista and barman get the key by default.
- Fixes: the KDS showed online orders before acceptance; accepting printed no
  kitchen tickets; a pull whose synced mark failed stored the order twice
  (store_online_orders skips known cloud ids); pulled orders lacked the business day
  and delivery type; rejected orders kept active items; delivered sets closed_at/by.
- Online orders belong to holders of connect_orders.manage (_can_access_order), so
  the counter pays them with POST /api/pos/orders/{id}/pay.
- Tests: test_pos_online.py (5), terminal unit +1, terminal.mjs +17 with a fake
  cloud (pull, synced, status mirror); fixed a timing race in a 3.3c check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 05:42:06 +02:00
co-authored by Claude Opus 5.5
parent 988d413d8e
commit d542cf7d34
20 changed files with 1052 additions and 176 deletions
+153 -89
View File
@@ -1,29 +1,63 @@
"""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
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).
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks
from pydantic import BaseModel
from sqlalchemy.orm import Session
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
from schemas.order import OrderOut
from routers.deps import get_current_user, require_manager
from models.user import User
from models.order import Order, OrderItem
from schemas.order import OrderItemOut, OrderOut
from services.sse_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] = None
reason: Optional[str] = Field(default=None, max_length=300)
class StatusUpdateRequest(BaseModel):
status: str # "preparing" | "ready" | "out_for_delivery" | "delivered"
status: Literal["preparing", "ready", "out_for_delivery", "delivered"]
# ── Helpers ───────────────────────────────────────────────────────────────────
@@ -31,10 +65,17 @@ class StatusUpdateRequest(BaseModel):
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 HTTPException(status_code=404, detail="Online order not found")
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}
@@ -61,116 +102,139 @@ async def _mirror_status_to_cloud(cloud_order_id: int, new_status: str, rejectio
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,
},
"items": [OrderItemOut.model_validate(i).model_dump(mode="json") for i in items],
"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: User = Depends(get_current_user),
):
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":
statuses = ["accepted", "preparing", "ready", "out_for_delivery"]
orders = (
db.query(Order)
.filter(Order.source == "online", Order.online_status.in_(statuses))
.order_by(Order.opened_at.desc())
.all()
)
elif status == "history":
statuses = ["delivered", "rejected"]
orders = (
db.query(Order)
.filter(Order.source == "online", Order.online_status.in_(statuses))
.order_by(Order.opened_at.desc())
.limit(50)
.all()
)
else:
raise HTTPException(status_code=400, detail=f"Unknown status filter '{status}'. Use 'active' or 'history'.")
return orders
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: User = Depends(get_current_user),
):
def get_incoming_orders(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
"""Return all online orders pending acceptance, newest first."""
orders = (
db.query(Order)
.filter(Order.source == "online", Order.online_status == "pending_acceptance")
.order_by(Order.opened_at.desc())
.all()
)
return orders
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)
async def accept_order(
order_id: int,
background: BackgroundTasks,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
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)
if order.online_status != "pending_acceptance":
raise HTTPException(status_code=400, detail=f"Order is already '{order.online_status}'")
order.online_status = "accepted"
_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)
background.add_task(_mirror_status_to_cloud, order.online_order_cloud_id, "accepted")
broadcast_sync("online_order_updated", {"order_id": order_id, "status": "accepted"})
_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)
async def reject_order(
order_id: int,
body: RejectRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
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)
if order.online_status != "pending_acceptance":
raise HTTPException(status_code=400, detail=f"Order is already '{order.online_status}'")
order.online_status = "rejected"
_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)
background.add_task(_mirror_status_to_cloud, order.online_order_cloud_id, "rejected", body.reason)
broadcast_sync("online_order_updated", {"order_id": order_id, "status": "rejected"})
_changed(background, order, body.reason)
return order
@router.post("/orders/{order_id}/status", response_model=OrderOut)
async def update_order_status(
order_id: int,
body: StatusUpdateRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
):
allowed = {"preparing", "ready", "out_for_delivery", "delivered"}
if body.status not in allowed:
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'")
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)
order.online_status = body.status
_move(order, body.status)
if body.status == "delivered":
order.status = "closed"
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)
background.add_task(_mirror_status_to_cloud, order.online_order_cloud_id, body.status)
broadcast_sync("online_order_updated", {"order_id": order_id, "status": body.status})
_changed(background, order)
if body.status == "delivered":
broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status})
return order