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
+2
View File
@@ -74,6 +74,8 @@ CODES: dict[str, tuple[int, str]] = {
"pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."),
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"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."),
"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."),
@@ -8,7 +8,7 @@ MODULE = Module(
description='Orders placed from the QR menu, pulled from the cloud.',
depends=('ordering', 'connect_menu'),
permissions=(
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager')),
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager', 'barista', 'barman')),
),
routers=(
Mount('routers.connect_orders', '/api/connect'),
@@ -27,7 +27,7 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*'),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*', 'connect_orders.*'),
config=POS_CONFIG),
routers=(
Mount('routers.pos', '/api/pos'),
+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
+2
View File
@@ -310,6 +310,8 @@ def kds_orders(
open_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")))
.options(
joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.ingredients),
joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.options),
+3
View File
@@ -77,6 +77,9 @@ def _can_access_order(order: Order, user: User, db: Session) -> bool:
Standalone orders (table_id=None) are accessible to all waiters with any zone assignment."""
if holds(user, "core.dashboard.access"):
return True
# Online orders (no table): whoever handles online orders (the counter, 3.3d)
if order.source == "online" and holds(user, "connect_orders.manage"):
return True
# Whoever the order is assigned to may act on it (e.g. a cashier's own counter sale, 3.3b)
if any(ow.waiter_id == user.id for ow in order.waiters):
return True
+73 -62
View File
@@ -327,6 +327,61 @@ async def _push_menu_snapshot():
logger.warning("Menu snapshot push failed: %s", e)
def store_online_orders(db, orders: list[dict]) -> 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.
Returns {cloud id: local order id}; a repeated order maps to minus its local id."""
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.user import User
# 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()
opener_id = system_user.id if system_user else 1
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
out = {}
for cloud_order in orders:
known = db.query(Order).filter(Order.source == "online",
Order.online_order_cloud_id == cloud_order["id"]).first()
if known is not None:
out[cloud_order["id"]] = -known.id
continue
local_order = Order(
table_id=None,
opened_by=opener_id,
status="open",
source="online",
order_type="delivery" if cloud_order.get("order_type") == "delivery" else "here",
business_day_id=day.id if day else None,
online_order_ref=cloud_order["public_ref"],
online_order_cloud_id=cloud_order["id"],
online_status="pending_acceptance",
online_customer_name=cloud_order.get("customer_name"),
online_customer_phone=cloud_order.get("customer_phone"),
online_customer_address=cloud_order.get("customer_address"),
online_customer_notes=cloud_order.get("customer_notes"),
online_order_type=cloud_order.get("order_type"),
)
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),
selected_options=json.dumps(item.get("options", [])),
status="active",
printed=False,
))
db.commit()
out[cloud_order["id"]] = local_order.id
logger.info("Online order %s pulled and created as local order %d", cloud_order["public_ref"], local_order.id)
return out
async def _pull_pending_orders():
"""Fetch online orders from cloud that haven't been synced to local yet."""
if not settings.SITE_ID or not settings.CLOUD_URL:
@@ -349,75 +404,31 @@ async def _pull_pending_orders():
return
from database import SessionLocal
from models.order import Order, OrderItem
from models.product import Product
from services.sse_bus import broadcast_sync
db = SessionLocal()
try:
# Use a system user id=1 (first manager/sysadmin) as the opener
from models.user import User
system_user = db.query(User).filter(holders_filter("core.dashboard.access")).first()
opener_id = system_user.id if system_user else 1
for cloud_order in orders:
# Create local Order row — no table_id for online orders
local_order = Order(
table_id=None,
opened_by=opener_id,
status="open",
source="online",
online_order_ref=cloud_order["public_ref"],
online_order_cloud_id=cloud_order["id"],
online_status="pending_acceptance",
online_customer_name=cloud_order.get("customer_name"),
online_customer_phone=cloud_order.get("customer_phone"),
online_customer_address=cloud_order.get("customer_address"),
online_customer_notes=cloud_order.get("customer_notes"),
online_order_type=cloud_order.get("order_type"),
)
db.add(local_order)
db.flush() # get local_order.id
# Create OrderItem rows
items = json.loads(cloud_order.get("items_json", "[]"))
for item in items:
product = db.query(Product).filter(
Product.id == item.get("product_id")
).first()
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),
selected_options=json.dumps(item.get("options", [])),
status="active",
printed=False,
))
db.commit()
# Mark synced on cloud
async with httpx.AsyncClient(timeout=10) as client:
await client.post(
f"{settings.CLOUD_URL}/api/orders/{cloud_order['id']}/synced",
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
json={"local_order_id": local_order.id},
)
logger.info("Online order %s pulled and created as local order %d",
cloud_order["public_ref"], local_order.id)
db.close()
# Broadcast SSE so the manager dashboard lights up
broadcast_sync("online_order_received", {"count": len(orders)})
stored = store_online_orders(db, orders)
except Exception as e:
db.rollback()
db.close()
logger.error("Failed to process pulled orders: %s", e)
return
finally:
db.close()
new_ids = [local_id for local_id in stored.values() if local_id > 0]
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})
# Mark synced on the cloud (also orders stored by an earlier pull whose mark failed)
async with httpx.AsyncClient(timeout=10) as client:
for cloud_id, local_id in stored.items():
await client.post(
f"{settings.CLOUD_URL}/api/orders/{cloud_id}/synced",
headers={"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY},
json={"local_order_id": abs(local_id)},
)
except Exception as e:
logger.warning("Order pull failed: %s", e)
+170
View File
@@ -0,0 +1,170 @@
"""Counter POS: online orders (plan step 3.3d). An order pulled from the cloud waits for the
counter, which accepts (kitchen tickets, KDS) or rejects it, moves it along, takes the payment
and finishes it; every change is broadcast and mirrored to the cloud."""
import json
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)
@pytest.fixture
def counter(client, db, pair, make_user):
"""A counter screen with a barista (the role accepts online orders by default) on shift."""
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.shift import WaiterShift
token, r = pair("pos_counter", "Counter")
assert r.status_code == 201, r.text
barista = make_user(role="barista", nickname="Eleni")
jwt = terminal_login(client, token, barista)
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if day is None:
day = BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()),
opened_by_id=make_user(role="owner").id)
db.add(day)
db.flush()
shift = WaiterShift(waiter_id=barista.id, business_day_id=day.id, starting_cash=20)
db.add(shift)
db.commit()
return {"h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "user": barista, "id": r.json()["id"],
"shift": shift, "day": day}
@pytest.fixture
def cloud(monkeypatch):
"""What reaches the cloud (status mirroring) and what the kitchen printers get."""
import routers.connect_orders as co
import services.printer_service as ps
got = {"mirror": [], "printed": [], "events": []}
async def mirror(cloud_id, status, reason=None):
got["mirror"].append((cloud_id, status, reason))
monkeypatch.setattr(co, "_mirror_status_to_cloud", mirror)
monkeypatch.setattr(ps, "route_and_print_sync", lambda order_id, ids, db, **kw: (got["printed"].append((order_id, sorted(ids))), [])[1])
real = co.broadcast_sync
monkeypatch.setattr(co, "broadcast_sync", lambda kind, data, **kw: (got["events"].append((kind, data)), real(kind, data, **kw)))
return got
def pulled(db, menu, cloud_id=501, order_type="delivery", **extra):
"""Store an order exactly as the cloud pull does (services/cloud_sync.py)."""
from services.cloud_sync import store_online_orders
order = {
"id": cloud_id, "public_ref": f"ORD-{cloud_id:04d}", "order_type": order_type,
"customer_name": "Nikos", "customer_phone": "6900000000", "customer_address": "Main square 3",
"customer_notes": "Ring twice", "status": "pending_acceptance",
"items_json": json.dumps([
{"product_id": menu["burger"].id, "name": "Burger", "quantity": 2, "unit_price": 9.5, "options": []},
{"product_id": menu["coffee"].id, "name": "Freddo", "quantity": 1, "unit_price": 3.0, "options": []},
]),
"subtotal": 22.0, "delivery_fee": 0.0, "total": 22.0, **extra,
}
return store_online_orders(db, [order])[cloud_id]
def board(client, counter):
r = client.get("/api/connect/orders/board", headers=counter["h"])
assert r.status_code == 200, r.text
return r.json()
def kds_ids(client, owner_h):
return {o["id"] for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"]}
def test_a_pulled_order_waits_for_the_counter(client, db, counter, menu, owner_h):
from models.order import Order
oid = pulled(db, menu)
order = db.get(Order, oid)
assert order.online_status == "pending_acceptance" and order.order_type == "delivery"
assert order.business_day_id == counter["day"].id
assert [(i.product_name, i.quantity, i.unit_price) for i in order.items] == [("Burger", 2, 9.5), ("Freddo", 1, 3.0)]
# a second pull of the same order (its "synced" mark got lost) doesn't store it twice
assert pulled(db, menu) == -oid
assert db.query(Order).filter(Order.online_order_cloud_id == 501).count() == 1
b = board(client, counter)
assert [o["id"] for o in b["incoming"]] == [oid] and b["in_progress"] == []
o = b["incoming"][0]
assert o["ref"] == "ORD-0501" and o["type"] == "delivery" and o["total"] == 22.0 and o["unpaid"] == 22.0
assert o["customer"] == {"name": "Nikos", "phone": "6900000000", "address": "Main square 3", "notes": "Ring twice"}
assert [i["product_name"] for i in o["items"]] == ["Burger", "Freddo"]
# the kitchen doesn't see it yet: it may still be rejected
assert oid not in kds_ids(client, owner_h)
def test_online_orders_need_the_key(client, pair, make_user, menu, db):
token, _ = pair("pos_counter", "Other till")
jwt = terminal_login(client, token, make_user(role="waiter")) # no connect_orders.manage
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}
oid = pulled(db, menu)
assert err(client.get("/api/connect/orders/board", headers=h)) == "access.denied"
assert err(client.post(f"/api/connect/orders/{oid}/accept", headers=h)) == "access.denied"
def test_accept_sends_it_to_the_kitchen(client, db, counter, menu, owner_h, cloud):
oid = pulled(db, menu)
r = client.post(f"/api/connect/orders/{oid}/accept", headers=counter["h"])
assert r.status_code == 200, r.text
assert r.json()["online_status"] == "accepted"
items = sorted(i["id"] for i in r.json()["items"])
assert cloud["printed"] == [(oid, items)] # kitchen tickets
assert oid in kds_ids(client, owner_h) # and the KDS
assert cloud["mirror"] == [(501, "accepted", None)] # the customer's page follows
assert ("online_order_updated", {"order_id": oid, "status": "accepted"}) in cloud["events"]
assert ("order_updated", {"order_id": oid, "table_id": None, "status": "open", "action": "items_added", "item_ids": items}) in cloud["events"]
b = board(client, counter)
assert b["incoming"] == [] and [o["id"] for o in b["in_progress"]] == [oid]
# accepted on another screen meanwhile → refused, nothing printed again
again = client.post(f"/api/connect/orders/{oid}/accept", headers=counter["h"])
assert again.status_code == 409 and err(again) == "online.status_changed"
assert len(cloud["printed"]) == 1
def test_delivery_paid_at_the_counter_and_finished(client, db, counter, menu, owner_h, cloud, drawer_printer):
from models.order import Order
from models.printer import Printer
printer = db.query(Printer).filter(Printer.name == "Counter receipt").one() # drawer_printer's
assert client.patch(f"/api/devices/{counter['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": printer.id}}).status_code == 200
oid = pulled(db, menu)
h = counter["h"]
step = lambda s: client.post(f"/api/connect/orders/{oid}/status", headers=h, json={"status": s}) # noqa: E731
assert err(step("preparing")) == "online.status_changed" # not accepted yet
client.post(f"/api/connect/orders/{oid}/accept", headers=h)
assert err(step("ready")) == "online.status_changed" # one step at a time
assert step("preparing").json()["online_status"] == "preparing"
assert step("out_for_delivery").json()["online_status"] == "out_for_delivery"
assert step("nonsense").status_code == 422
# the driver brings the cash: the counter's ordinary payment (drawer, the barista's shift)
o = board(client, counter)["in_progress"][0]
ids = [i["id"] for i in o["items"]]
paid = client.post(f"/api/pos/orders/{oid}/pay", headers=h, json={"payments": [{"method": "cash", "item_ids": ids}], "cash_given": 30})
assert paid.status_code == 200, paid.text
assert paid.json()["total"] == 22.0 and paid.json()["change"] == 8.0 and paid.json()["drawer"] == "opened"
db.expire_all()
assert all(i.paid_in_shift_id == counter["shift"].id for i in db.get(Order, oid).items)
assert len(drawer_printer) == 1 # the drawer kick
done = step("delivered")
assert done.status_code == 200 and done.json()["online_status"] == "delivered" and done.json()["status"] == "closed"
assert oid not in kds_ids(client, owner_h)
b = board(client, counter)
assert b["in_progress"] == [] and b["finished"][0]["id"] == oid and b["finished"][0]["unpaid"] == 0
assert [m[1] for m in cloud["mirror"]] == ["accepted", "preparing", "out_for_delivery", "delivered"]
def test_reject_tells_the_customer_why(client, db, counter, menu, owner_h, cloud):
from models.order import Order
oid = pulled(db, menu, order_type="dine_in")
assert db.get(Order, oid).order_type == "here"
r = client.post(f"/api/connect/orders/{oid}/reject", headers=counter["h"], json={"reason": "Kitchen closed"})
assert r.status_code == 200, r.text
assert r.json()["online_status"] == "rejected" and r.json()["status"] == "cancelled"
assert {i["status"] for i in r.json()["items"]} == {"cancelled"}
assert cloud["mirror"] == [(501, "rejected", "Kitchen closed")] and cloud["printed"] == []
assert oid not in kds_ids(client, owner_h)
b = board(client, counter)
assert b["incoming"] == [] and b["finished"][0]["status"] == "rejected" and b["finished"][0]["total"] == 0
assert err(client.post(f"/api/connect/orders/{oid}/accept", headers=counter["h"])) == "online.status_changed"
assert err(client.post("/api/connect/orders/99999/accept", headers=counter["h"])) == "online.not_found"