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:
@@ -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'),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
@@ -87,5 +87,9 @@
|
||||
"table_not_yours": "Το {{table}} δεν είναι στις ζώνες σας. Ένας διαχειριστής μπορεί να προσθέσει τη ζώνη στον λογαριασμό σας.",
|
||||
"items_changed": "Κάποια από αυτά πληρώθηκαν ή ακυρώθηκαν στο μεταξύ. Ελέγξτε την παραγγελία και δοκιμάστε ξανά.",
|
||||
"order_unpaid": "Απλήρωτα είδη: {{count}}. Πάρτε την πληρωμή ή ακυρώστε τα πρώτα."
|
||||
},
|
||||
"online": {
|
||||
"not_found": "Η online παραγγελία {{order_id}} δεν βρέθηκε.",
|
||||
"status_changed": "Αυτή η online παραγγελία άλλαξε από άλλη οθόνη στο μεταξύ. Δείτε πού βρίσκεται τώρα."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +241,8 @@
|
||||
"mode": {
|
||||
"label": "Λειτουργία ταμείου",
|
||||
"sale": "Πώληση",
|
||||
"tables": "Τραπέζια"
|
||||
"tables": "Τραπέζια",
|
||||
"online": "Online"
|
||||
},
|
||||
"tables": {
|
||||
"none": "Δεν έχετε τραπέζια",
|
||||
@@ -290,6 +291,64 @@
|
||||
"card": "πληρώθηκε · κάρτα"
|
||||
},
|
||||
"readyItem": "έτοιμο"
|
||||
},
|
||||
"online": {
|
||||
"arrived_one": "Νέα online παραγγελία",
|
||||
"arrived_other": "{{count}} νέες online παραγγελίες",
|
||||
"lists": {
|
||||
"incoming": "Νέες",
|
||||
"in_progress": "Σε εξέλιξη",
|
||||
"finished": "Ολοκληρωμένες"
|
||||
},
|
||||
"empty": {
|
||||
"incoming": "Δεν υπάρχουν νέες online παραγγελίες",
|
||||
"in_progress": "Τίποτα σε εξέλιξη",
|
||||
"finished": "Τίποτα ολοκληρωμένο ακόμη"
|
||||
},
|
||||
"emptyBody": "Οι παραγγελίες από το QR μενού σας εμφανίζονται εδώ αμέσως, με ήχο.",
|
||||
"pick": "Επιλέξτε μια παραγγελία για να τη δείτε",
|
||||
"type": {
|
||||
"delivery": "Διανομή",
|
||||
"dine_in": "Στο κατάστημα"
|
||||
},
|
||||
"status": {
|
||||
"pending_acceptance": "Περιμένει απάντηση",
|
||||
"accepted": "Αποδεκτή",
|
||||
"preparing": "Ετοιμάζεται",
|
||||
"ready": "Έτοιμη",
|
||||
"out_for_delivery": "Σε διανομή",
|
||||
"delivered": "Ολοκληρώθηκε",
|
||||
"rejected": "Απορρίφθηκε"
|
||||
},
|
||||
"waiting_one": "περιμένει {{count}} λεπτό",
|
||||
"waiting_other": "περιμένει {{count}} λεπτά",
|
||||
"accept": "Αποδοχή και αποστολή στην κουζίνα",
|
||||
"reject": "Απόρριψη",
|
||||
"to": {
|
||||
"preparing": "Έναρξη προετοιμασίας",
|
||||
"ready": "Έτοιμη",
|
||||
"out_for_delivery": "Σε διανομή"
|
||||
},
|
||||
"payAnd": {
|
||||
"delivered": "Είσπραξη {{amount}} · παραδόθηκε",
|
||||
"served": "Είσπραξη {{amount}} · σερβιρίστηκε"
|
||||
},
|
||||
"mark": {
|
||||
"delivered": "Παραδόθηκε",
|
||||
"served": "Σερβιρίστηκε"
|
||||
},
|
||||
"rejectTitle": "Απόρριψη αυτής της παραγγελίας;",
|
||||
"rejectBody": "Ο πελάτης βλέπει τον λόγο στη σελίδα της παραγγελίας του.",
|
||||
"reason": "Λόγος",
|
||||
"reasons": {
|
||||
"busy": "Έχουμε πολύ φόρτο αυτή τη στιγμή",
|
||||
"unavailable": "Κάποια είδη δεν είναι διαθέσιμα",
|
||||
"closing": "Κλείνουμε",
|
||||
"area": "Δεν κάνουμε διανομή σε αυτή τη διεύθυνση",
|
||||
"other": "Άλλος λόγος…"
|
||||
},
|
||||
"keep": "Να μείνει",
|
||||
"rejectConfirm": "Απόρριψη παραγγελίας"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,5 +87,9 @@
|
||||
"table_not_yours": "{{table}} isn't in your zones. A manager can add the zone to your account.",
|
||||
"items_changed": "Some of these items were paid or cancelled in the meantime. Check the order and try again.",
|
||||
"order_unpaid": "Items still unpaid: {{count}}. Take the payment or cancel them first."
|
||||
},
|
||||
"online": {
|
||||
"not_found": "Online order {{order_id}} not found.",
|
||||
"status_changed": "This online order was changed on another screen in the meantime. Check where it is now."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +241,8 @@
|
||||
"mode": {
|
||||
"label": "Counter mode",
|
||||
"sale": "Sale",
|
||||
"tables": "Tables"
|
||||
"tables": "Tables",
|
||||
"online": "Online"
|
||||
},
|
||||
"tables": {
|
||||
"none": "No tables for you",
|
||||
@@ -290,6 +291,64 @@
|
||||
"card": "paid · card"
|
||||
},
|
||||
"readyItem": "ready"
|
||||
},
|
||||
"online": {
|
||||
"arrived_one": "New online order",
|
||||
"arrived_other": "{{count}} new online orders",
|
||||
"lists": {
|
||||
"incoming": "New",
|
||||
"in_progress": "In progress",
|
||||
"finished": "Finished"
|
||||
},
|
||||
"empty": {
|
||||
"incoming": "No new online orders",
|
||||
"in_progress": "Nothing in progress",
|
||||
"finished": "Nothing finished yet"
|
||||
},
|
||||
"emptyBody": "Orders from your QR menu show here at once, with a sound.",
|
||||
"pick": "Pick an order to see it",
|
||||
"type": {
|
||||
"delivery": "Delivery",
|
||||
"dine_in": "At the venue"
|
||||
},
|
||||
"status": {
|
||||
"pending_acceptance": "Waiting for an answer",
|
||||
"accepted": "Accepted",
|
||||
"preparing": "Preparing",
|
||||
"ready": "Ready",
|
||||
"out_for_delivery": "Out for delivery",
|
||||
"delivered": "Done",
|
||||
"rejected": "Rejected"
|
||||
},
|
||||
"waiting_one": "waiting {{count}} min",
|
||||
"waiting_other": "waiting {{count}} min",
|
||||
"accept": "Accept and send to the kitchen",
|
||||
"reject": "Reject",
|
||||
"to": {
|
||||
"preparing": "Start preparing",
|
||||
"ready": "Ready",
|
||||
"out_for_delivery": "Out for delivery"
|
||||
},
|
||||
"payAnd": {
|
||||
"delivered": "Take {{amount}} · delivered",
|
||||
"served": "Take {{amount}} · served"
|
||||
},
|
||||
"mark": {
|
||||
"delivered": "Mark as delivered",
|
||||
"served": "Mark as served"
|
||||
},
|
||||
"rejectTitle": "Reject this order?",
|
||||
"rejectBody": "The customer sees the reason on their order page.",
|
||||
"reason": "Reason",
|
||||
"reasons": {
|
||||
"busy": "We're too busy right now",
|
||||
"unavailable": "Some items aren't available",
|
||||
"closing": "We're closing",
|
||||
"area": "We don't deliver to this address",
|
||||
"other": "Other reason…"
|
||||
},
|
||||
"keep": "Keep it",
|
||||
"rejectConfirm": "Reject order"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// One online order at the counter (plan step 3.3d): the right column in Online mode. It shows
|
||||
// the customer (phone, address, their note) and the items, and offers the next step only:
|
||||
// accept (kitchen tickets, KDS) or reject (with a reason the customer sees), start preparing,
|
||||
// ready or out for delivery, then finish: take what's unpaid (the counter's ordinary payment,
|
||||
// cash/card/split with the drawer) and mark it delivered. Someone else's change meanwhile is
|
||||
// refused by the backend and the order shows where it is now.
|
||||
import { useState } from 'react'
|
||||
import { Ban, Banknote, Bike, Check, ChefHat, MapPin, MessageSquare, PackageCheck, Phone, Utensils } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Input } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { nextStep } from './logic/online'
|
||||
import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables'
|
||||
import PaymentDialog from './PaymentDialog'
|
||||
|
||||
const REASONS = ['busy', 'unavailable', 'closing', 'area']
|
||||
const STEP_ICON = { preparing: ChefHat, ready: PackageCheck, out_for_delivery: Bike }
|
||||
|
||||
export default function OnlinePanel({ order, onChanged }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney, formatTime } = useFormat()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [paying, setPaying] = useState(null) // rows being paid
|
||||
const [rejecting, setRejecting] = useState(false)
|
||||
|
||||
if (!order) {
|
||||
return (
|
||||
<aside className="border-l border-line bg-surface flex items-center justify-center p-6" data-testid="online-panel">
|
||||
<EmptyState compact title={t('pos.online.pick')} />
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
const lines = orderLines(order)
|
||||
const sums = orderSums(lines)
|
||||
const step = nextStep(order)
|
||||
const delivery = order.type === 'delivery'
|
||||
const finishWord = delivery ? 'delivered' : 'served'
|
||||
|
||||
const run = async (fn) => {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try { return await fn() } catch (err) { setError(errorMessage(err, t)); onChanged(); return null } finally { setBusy(false) }
|
||||
}
|
||||
const post = (path, body) => client.post(`/api/connect/orders/${order.id}/${path}`, body)
|
||||
const accept = () => run(async () => { await post('accept'); onChanged(null, { list: 'in_progress' }) })
|
||||
const advance = to => run(async () => { await post('status', { status: to }); onChanged() })
|
||||
|
||||
const payRows = lines.filter(l => !l.paid).map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total }))
|
||||
const submitPay = async ({ method, payments, cashGiven }) => (await client.post(`/api/pos/orders/${order.id}/pay`, {
|
||||
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }],
|
||||
cash_given: cashGiven,
|
||||
})).data
|
||||
|
||||
return (
|
||||
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="online-panel" data-order={order.id} data-status={order.status}>
|
||||
<div className="p-3 border-b border-line grid gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex-1 text-title font-semibold">{order.ref}</span>
|
||||
<span className="text-label font-medium text-ink-2 flex items-center gap-1">
|
||||
{delivery ? <Bike size={16} aria-hidden="true" /> : <Utensils size={16} aria-hidden="true" />}
|
||||
{t(`pos.online.type.${delivery ? 'delivery' : 'dine_in'}`)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-caption text-ink-2">{t(`pos.online.status.${order.status}`)} · {formatTime(order.opened_at)}</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<section className="p-3 border-b border-line grid gap-1.5 text-body" data-testid="online-customer">
|
||||
<div className="text-body-lg font-semibold">{order.customer.name}</div>
|
||||
{order.customer.phone && <Detail icon={Phone}>{order.customer.phone}</Detail>}
|
||||
{order.customer.address && <Detail icon={MapPin}>{order.customer.address}</Detail>}
|
||||
{order.customer.notes && (
|
||||
<div className="p-2 rounded-control bg-warning-soft text-warning-ink flex gap-2">
|
||||
<MessageSquare size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span>{order.customer.notes}</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<section data-testid="online-lines">
|
||||
{lines.map(l => (
|
||||
<div key={l.id} className={`px-3 py-2 border-b border-line flex items-start gap-2 ${l.paid ? 'text-ink-3' : 'text-ink'}`} data-testid="online-line">
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="text-body font-medium">{qtyLabel(l.quantity, l.unitType)} {l.name}</span>
|
||||
{(l.options.length > 0 || l.notes) && (
|
||||
<span className="block text-caption text-ink-2">{[...l.options, l.notes && `“${l.notes}”`].filter(Boolean).join(' · ')}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-body text-right">
|
||||
{formatMoney(l.total)}
|
||||
{l.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${l.method === 'card' ? 'card' : 'cash'}`)}</span>}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line p-3 grid gap-2">
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="text-body-lg text-ink-2">{sums.unpaid > 0 ? t('pos.table.due') : t('pos.total')}</span>
|
||||
<span className="text-display font-semibold" data-testid="online-total">{formatMoney(sums.unpaid > 0 ? sums.unpaid : sums.total)}</span>
|
||||
</div>
|
||||
{step?.kind === 'answer' && (
|
||||
<>
|
||||
<Button size="lg" icon={<Check size={20} />} loading={busy} onClick={accept} data-testid="online-accept">{t('pos.online.accept')}</Button>
|
||||
<Button variant="secondary" icon={<Ban size={16} />} disabled={busy} onClick={() => setRejecting(true)} data-testid="online-reject">{t('pos.online.reject')}</Button>
|
||||
</>
|
||||
)}
|
||||
{step?.kind === 'status' && (() => {
|
||||
const Icon = STEP_ICON[step.to]
|
||||
return <Button size="lg" icon={<Icon size={20} />} loading={busy} onClick={() => advance(step.to)} data-testid="online-next">{t(`pos.online.to.${step.to}`)}</Button>
|
||||
})()}
|
||||
{step?.kind === 'finish' && (step.pay ? (
|
||||
<Button size="lg" icon={<Banknote size={20} />} disabled={busy} onClick={() => setPaying(payRows)} data-testid="online-finish">
|
||||
{t(`pos.online.payAnd.${finishWord}`, { amount: formatMoney(sums.unpaid) })}
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="lg" icon={<PackageCheck size={20} />} loading={busy} onClick={() => advance('delivered')} data-testid="online-finish">
|
||||
{t(`pos.online.mark.${finishWord}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{paying && (
|
||||
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
|
||||
onClose={() => setPaying(null)}
|
||||
onPaid={result => {
|
||||
setPaying(null)
|
||||
run(async () => { await post('status', { status: 'delivered' }); onChanged(result) })
|
||||
}} />
|
||||
)}
|
||||
|
||||
{rejecting && <RejectDialog busy={busy} error={error} onClose={() => setRejecting(false)}
|
||||
onReject={reason => run(async () => { await post('reject', { reason }); setRejecting(false); onChanged(null, { clear: true }) })} />}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function Detail({ icon: Icon, children }) {
|
||||
return <div className="flex items-start gap-2 text-ink-2"><Icon size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span className="text-ink">{children}</span></div>
|
||||
}
|
||||
|
||||
function RejectDialog({ busy, error, onClose, onReject }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const [choice, setChoice] = useState(null)
|
||||
const [other, setOther] = useState('')
|
||||
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.online.reasons.${choice}`) : ''
|
||||
return (
|
||||
<Dialog open size="sm" title={t('pos.online.rejectTitle')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('pos.online.keep')}</Button>
|
||||
<Button variant="danger" icon={<Ban size={16} />} loading={busy} disabled={!reason} onClick={() => onReject(reason)} data-testid="reject-confirm">
|
||||
{t('pos.online.rejectConfirm')}
|
||||
</Button>
|
||||
</>}>
|
||||
<div className="grid gap-2">
|
||||
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p>
|
||||
<div className="grid gap-1" role="radiogroup" aria-label={t('pos.online.reason')}>
|
||||
{[...REASONS, 'other'].map(r => (
|
||||
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`reason-${r}`}
|
||||
className={`min-h-[var(--x-control-md)] px-3 rounded-control text-left text-body transition-colors duration-fast
|
||||
${choice === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink hover:bg-surface-3'}`}>
|
||||
{t(`pos.online.reasons.${r}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{choice === 'other' && (
|
||||
<Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} data-testid="reason-text" />
|
||||
)}
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Online orders at the counter (plan step 3.3d): one list at a time (new, in progress,
|
||||
// finished; picked on the left), each order as a card with its reference, delivery or at the
|
||||
// venue, the customer, how long it has waited and what it costs. New orders stand out until
|
||||
// someone answers them. A tap shows the order on the right (OnlinePanel).
|
||||
import { Bike, Clock, Utensils } from 'lucide-react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { EmptyState, Spinner } from '@xenia/ui'
|
||||
import { minutesSince } from './logic/online'
|
||||
|
||||
const LOOK = {
|
||||
pending_acceptance: 'bg-warning-soft border-warning text-warning-ink',
|
||||
accepted: 'bg-info-soft border-info text-info-ink',
|
||||
preparing: 'bg-info-soft border-info text-info-ink',
|
||||
ready: 'bg-success-soft border-success text-success-ink',
|
||||
out_for_delivery: 'bg-success-soft border-success text-success-ink',
|
||||
delivered: 'bg-surface border-line text-ink-2',
|
||||
rejected: 'bg-surface border-line text-ink-3',
|
||||
}
|
||||
|
||||
export default function OnlineView({ data, list, picked, onPick, now }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
if (!data) return <div className="flex-1 flex items-center justify-center"><Spinner /></div>
|
||||
const orders = data[list] ?? []
|
||||
if (!orders.length) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center p-6" data-testid="online-orders">
|
||||
<EmptyState title={t(`pos.online.empty.${list}`)} description={list === 'incoming' ? t('pos.online.emptyBody') : undefined} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(14rem, 1fr))' }}
|
||||
data-testid="online-orders">
|
||||
{orders.map(o => <OrderCard key={o.id} order={o} picked={picked === o.id} onPick={() => onPick(o.id)} now={now} />)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OrderCard({ order, picked, onPick, now }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney, formatTime } = useFormat()
|
||||
const Icon = order.type === 'delivery' ? Bike : Utensils
|
||||
const waiting = order.status === 'pending_acceptance'
|
||||
return (
|
||||
<button type="button" onClick={onPick} aria-pressed={picked} data-testid="online-order" data-order={order.id} data-status={order.status}
|
||||
className={`min-h-32 p-3 rounded-card border-2 shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast
|
||||
${LOOK[order.status] ?? LOOK.delivered} ${picked ? 'ring-2 ring-accent ring-offset-2 ring-offset-canvas' : ''}`}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="flex-1 min-w-0 text-title font-semibold truncate">{order.ref}</span>
|
||||
<Icon size={18} aria-label={t(`pos.online.type.${order.type === 'delivery' ? 'delivery' : 'dine_in'}`)} />
|
||||
</span>
|
||||
<span className="text-body font-medium truncate">{order.customer.name}</span>
|
||||
<span className="text-label font-medium">{t(`pos.online.status.${order.status}`)}</span>
|
||||
<span className="mt-auto flex items-baseline justify-between gap-2">
|
||||
<span className="text-heading font-semibold">{formatMoney(order.total)}</span>
|
||||
<span className="text-label flex items-center gap-1 opacity-80">
|
||||
<Clock size={14} aria-hidden="true" />
|
||||
{waiting ? t('pos.online.waiting', { count: minutesSince(order.opened_at, now) }) : formatTime(order.opened_at)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +1,33 @@
|
||||
// The counter POS screen (plan steps 3.3a–c). Two modes, switched at the top left:
|
||||
// The counter POS screen (plan steps 3.3a–d). Up to three modes, switched at the top left:
|
||||
// - Sale: categories on the left, the product grid with a search, the quick-sale cart on the
|
||||
// right (SaleCart: Charge → payment, 3.3b).
|
||||
// - Tables: the zones on the left and the table list (TablesView); a table opens with the
|
||||
// product grid again and the table's order on the right (TablePanel).
|
||||
// - Online (when online orders are on and the cashier handles them): new / in progress /
|
||||
// finished on the left, the orders (OnlineView) and the picked one (OnlinePanel). A new
|
||||
// order rings (and again every 30 s while one waits for an answer) and shows a notice in any
|
||||
// mode; the mode's badge counts the orders waiting.
|
||||
// A tap adds a product (or opens its choices when it has preferences to pick); the (i) button
|
||||
// checks its price without adding it. Every price is the backend's.
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Globe, Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
|
||||
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
||||
import { useCan } from '@xenia/access'
|
||||
import { EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
|
||||
import { useLiveEvent } from '../../device/context'
|
||||
import { playChime } from './chime'
|
||||
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
|
||||
import { findOnline, ONLINE_LISTS } from './logic/online'
|
||||
import { zoneCounts } from './logic/tables'
|
||||
import OnlinePanel from './OnlinePanel'
|
||||
import OnlineView from './OnlineView'
|
||||
import ProductDialog from './ProductDialog'
|
||||
import SaleCart from './SaleCart'
|
||||
import TablePanel from './TablePanel'
|
||||
import TablesView from './TablesView'
|
||||
import { useMenu, useTables } from './usePos'
|
||||
import { useMenu, useOnline, useTables } from './usePos'
|
||||
|
||||
const REMIND_MS = 30_000
|
||||
|
||||
export default function PosScreen() {
|
||||
const { t } = useTranslation('terminal')
|
||||
@@ -27,7 +38,8 @@ export default function PosScreen() {
|
||||
|
||||
function Counter({ menu, t }) {
|
||||
const { language } = useLanguage()
|
||||
const [mode, setMode] = useState('sale') // sale | tables
|
||||
const { formatMoney } = useFormat()
|
||||
const [mode, setMode] = useState('sale') // sale | tables | online
|
||||
const [tableId, setTableId] = useState(null) // the open table (tables mode)
|
||||
const [zone, setZone] = useState(null)
|
||||
const [category, setCategory] = useState(() => menu.settings.start_category_id ?? null)
|
||||
@@ -38,11 +50,37 @@ function Counter({ menu, t }) {
|
||||
const [dialog, setDialog] = useState(null) // product
|
||||
const tables = useTables()
|
||||
const canDiscount = useCan('ordering.prices.modify')
|
||||
const toast = useToast()
|
||||
const onlineModule = useModule('connect_orders')
|
||||
const handlesOnline = useCan('connect_orders.manage')
|
||||
const onlineOn = onlineModule && handlesOnline
|
||||
const online = useOnline(onlineOn)
|
||||
const [onlineList, setOnlineList] = useState('incoming')
|
||||
const [onlineId, setOnlineId] = useState(null)
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
const [chimes, setChimes] = useState(0)
|
||||
const waiting = online.data?.incoming.length ?? 0
|
||||
|
||||
const ring = () => { playChime(); setChimes(c => c + 1) }
|
||||
useLiveEvent('online_order_received', data => {
|
||||
if (!onlineOn) return
|
||||
ring()
|
||||
if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 }))
|
||||
})
|
||||
// a reminder while an order waits for an answer; the waiting minutes move on too
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
setNow(Date.now())
|
||||
if (waiting > 0) { playChime(); setChimes(c => c + 1) }
|
||||
}, REMIND_MS)
|
||||
return () => clearInterval(id)
|
||||
}, [waiting])
|
||||
|
||||
// a table that left the cashier's list (zone changed) shows the list again
|
||||
const table = tableId != null ? tables.data?.tables.find(x => x.id === tableId) ?? null : null
|
||||
const atTable = mode === 'tables' && table != null
|
||||
const picking = mode === 'tables' && !atTable
|
||||
const onlineOrder = findOnline(online.data, onlineId)
|
||||
const setCart = atTable ? setTableCart : setSaleCart
|
||||
const leaveTable = () => { setTableId(null); setTableCart([]) }
|
||||
|
||||
@@ -59,15 +97,27 @@ function Counter({ menu, t }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" lang={language}>
|
||||
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" data-chimes={chimes} lang={language}>
|
||||
<nav className="border-r border-line bg-surface min-h-0 flex flex-col">
|
||||
<div className="p-2 grid grid-cols-2 gap-1 border-b border-line" role="tablist" aria-label={t('pos.mode.label')}>
|
||||
<div className={`p-2 grid gap-1 border-b border-line ${onlineOn ? 'grid-cols-3' : 'grid-cols-2'}`} role="tablist" aria-label={t('pos.mode.label')}>
|
||||
<ModeButton active={mode === 'sale'} onClick={() => setMode('sale')} icon={ShoppingBag} testId="mode-sale">{t('pos.mode.sale')}</ModeButton>
|
||||
<ModeButton active={mode === 'tables'} onClick={() => { setMode('tables'); leaveTable() }} icon={LayoutGrid} testId="mode-tables"
|
||||
badge={counts.all.busy || null}>{t('pos.mode.tables')}</ModeButton>
|
||||
{onlineOn && (
|
||||
<ModeButton active={mode === 'online'} onClick={() => setMode('online')} icon={Globe} testId="mode-online"
|
||||
badge={waiting || null} alert={waiting > 0}>{t('pos.mode.online')}</ModeButton>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1" data-testid={picking ? 'pos-zones' : 'pos-categories'}>
|
||||
{picking ? (
|
||||
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1"
|
||||
data-testid={mode === 'online' ? 'online-lists' : picking ? 'pos-zones' : 'pos-categories'}>
|
||||
{mode === 'online' ? (
|
||||
ONLINE_LISTS.map(list => (
|
||||
<NavButton key={list} active={onlineList === list} onClick={() => setOnlineList(list)} testId={`online-list-${list}`}
|
||||
tally={list === 'finished' ? null : online.data?.[list].length}>
|
||||
{t(`pos.online.lists.${list}`)}
|
||||
</NavButton>
|
||||
))
|
||||
) : picking ? (
|
||||
<>
|
||||
<NavButton active={zone == null} onClick={() => setZone(null)} count={counts.all}>{t('pos.tables.allZones')}</NavButton>
|
||||
{(tables.data?.groups ?? []).map(g => (
|
||||
@@ -87,7 +137,20 @@ function Counter({ menu, t }) {
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{picking ? (
|
||||
{mode === 'online' ? (
|
||||
<>
|
||||
<main className="flex flex-col min-h-0 min-w-0">
|
||||
<OnlineView data={online.data} list={onlineList} picked={onlineId} onPick={setOnlineId} now={now} />
|
||||
</main>
|
||||
<OnlinePanel key={onlineOrder?.id ?? 'none'} order={onlineOrder}
|
||||
onChanged={(result, move) => {
|
||||
online.reload()
|
||||
if (move?.list) setOnlineList(move.list)
|
||||
if (move?.clear) setOnlineId(null)
|
||||
if (result?.change > 0) toast.success(t('pos.done.toastChange', { change: formatMoney(result.change) }))
|
||||
}} />
|
||||
</>
|
||||
) : picking ? (
|
||||
<main className="col-span-2 flex flex-col min-h-0 min-w-0">
|
||||
<TablesView data={tables.data} zone={zone} onPick={id => { setTableId(id); setTableCart([]) }} />
|
||||
</main>
|
||||
@@ -126,18 +189,18 @@ function Counter({ menu, t }) {
|
||||
)
|
||||
}
|
||||
|
||||
function ModeButton({ active, onClick, icon: Icon, badge, children, testId }) {
|
||||
function ModeButton({ active, onClick, icon: Icon, badge, alert, children, testId }) {
|
||||
return (
|
||||
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId}
|
||||
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId} data-badge={badge ?? 0}
|
||||
className={`relative min-h-[var(--x-control-lg)] rounded-control flex flex-col items-center justify-center gap-0.5 text-label font-semibold transition-colors duration-fast
|
||||
${active ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
|
||||
<Icon size={18} aria-hidden="true" />{children}
|
||||
{badge ? <span className="absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center">{badge}</span> : null}
|
||||
{badge ? <span className={`absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center ${alert ? 'animate-pulse' : ''}`}>{badge}</span> : null}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function NavButton({ active, colour, onClick, children, testId, count }) {
|
||||
function NavButton({ active, colour, onClick, children, testId, count, tally }) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} data-testid={testId} aria-pressed={active}
|
||||
className={`min-h-[var(--x-control-lg)] px-3 rounded-control text-left text-body font-medium flex items-center gap-2 transition-colors duration-fast
|
||||
@@ -145,6 +208,7 @@ function NavButton({ active, colour, onClick, children, testId, count }) {
|
||||
{colour && <span className="size-2.5 rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />}
|
||||
<span className="flex-1 truncate">{children}</span>
|
||||
{count && <span className="text-caption text-ink-3">{count.busy}/{count.total}</span>}
|
||||
{tally != null && <span className="text-caption text-ink-3">{tally}</span>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// The counter's "new online order" sound (plan step 3.3d): a short two-note chime made with
|
||||
// Web Audio, so there is no sound file to ship. Browsers only play sound after the page was
|
||||
// touched; a counter screen always is (the PIN pad), and a failure is silent.
|
||||
let ctx = null
|
||||
|
||||
export function playChime() {
|
||||
try {
|
||||
ctx = ctx ?? new (window.AudioContext || window.webkitAudioContext)()
|
||||
if (ctx.state === 'suspended') ctx.resume()
|
||||
const start = ctx.currentTime + 0.02
|
||||
;[[880, 0], [1320, 0.18]].forEach(([freq, at]) => {
|
||||
const osc = ctx.createOscillator()
|
||||
const gain = ctx.createGain()
|
||||
osc.type = 'sine'
|
||||
osc.frequency.value = freq
|
||||
gain.gain.setValueAtTime(0.0001, start + at)
|
||||
gain.gain.exponentialRampToValueAtTime(0.4, start + at + 0.02)
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, start + at + 0.35)
|
||||
osc.connect(gain).connect(ctx.destination)
|
||||
osc.start(start + at)
|
||||
osc.stop(start + at + 0.4)
|
||||
})
|
||||
} catch { /* no sound on this device */ }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Online orders at the counter (plan step 3.3d): what the list shows and which step comes next.
|
||||
// The orders come from GET /api/connect/orders/board; the steps follow the backend's (and the
|
||||
// cloud's) order: accept or reject → preparing → ready (at the venue) or out for delivery →
|
||||
// delivered. Pure: unit-tested in Node (tests/pos.test.mjs).
|
||||
|
||||
export const ONLINE_LISTS = ['incoming', 'in_progress', 'finished']
|
||||
|
||||
/** The next step of an order: { kind: 'answer' } (accept / reject), { kind: 'status', to },
|
||||
* { kind: 'finish', pay } (take what's unpaid, then delivered) or null (finished). */
|
||||
export function nextStep(order) {
|
||||
switch (order.status) {
|
||||
case 'pending_acceptance': return { kind: 'answer' }
|
||||
case 'accepted': return { kind: 'status', to: 'preparing' }
|
||||
case 'preparing': return { kind: 'status', to: order.type === 'delivery' ? 'out_for_delivery' : 'ready' }
|
||||
case 'ready':
|
||||
case 'out_for_delivery': return { kind: 'finish', pay: order.unpaid > 0.004 }
|
||||
default: return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The order with this id in any of the board's lists (null when gone). */
|
||||
export function findOnline(board, id) {
|
||||
if (!board || id == null) return null
|
||||
for (const list of ONLINE_LISTS) {
|
||||
const hit = (board[list] ?? []).find(o => o.id === id)
|
||||
if (hit) return hit
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Whole minutes since an ISO time (never negative). */
|
||||
export function minutesSince(iso, now = Date.now()) {
|
||||
return Math.max(0, Math.floor((now - Date.parse(iso)) / 60_000))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// The counter POS's server data (plan steps 3.3a, 3.3c): the cashier's session (shift gate),
|
||||
// the menu, the cart priced by the backend, the tables and a table's order. Kept fresh by the
|
||||
// The counter POS's server data (plan steps 3.3a, 3.3c, 3.3d): the cashier's session (shift gate),
|
||||
// the menu, the cart priced by the backend, the tables, a table's order and online orders. Kept fresh by the
|
||||
// live connection, so a waiter's phone and the counter see each other's changes at once.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import client from '../../api/client'
|
||||
@@ -112,3 +112,20 @@ export function useOrder(orderId) {
|
||||
useLiveEvents(TABLE_EVENTS, (_type, data) => { if (data?.order_id === orderId) soon() })
|
||||
return { order, gone, reload: load }
|
||||
}
|
||||
|
||||
const ONLINE_EVENTS = ['online_order_received', 'online_order_updated', 'order_paid', 'order_closed']
|
||||
|
||||
/** GET /api/connect/orders/board: { incoming, in_progress, finished } (null while loading or
|
||||
* when `enabled` is false: the module is off or the cashier doesn't handle online orders). */
|
||||
export function useOnline(enabled) {
|
||||
const [data, setData] = useState(null)
|
||||
const load = useCallback(async () => {
|
||||
if (!enabled) { setData(null); return }
|
||||
try { setData((await client.get('/api/connect/orders/board', quiet)).data) } catch { /* the shell shows offline */ }
|
||||
}, [enabled])
|
||||
const soon = useCoalesced(load)
|
||||
useEffect(() => { load() }, [load])
|
||||
useLiveEvent('ready', load)
|
||||
useLiveEvents(ONLINE_EVENTS, soon)
|
||||
return { data, reload: load }
|
||||
}
|
||||
|
||||
@@ -128,3 +128,23 @@ test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)',
|
||||
assert.equal(qtyLabel(2, 'piece'), '2×')
|
||||
assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
|
||||
})
|
||||
|
||||
test('online orders: the next step and finding an order (3.3d)', async () => {
|
||||
const { findOnline, minutesSince, nextStep } = await import('../src/apps/pos/logic/online.js')
|
||||
assert.deepEqual(nextStep({ status: 'pending_acceptance' }), { kind: 'answer' })
|
||||
assert.deepEqual(nextStep({ status: 'accepted' }), { kind: 'status', to: 'preparing' })
|
||||
assert.deepEqual(nextStep({ status: 'preparing', type: 'delivery' }), { kind: 'status', to: 'out_for_delivery' })
|
||||
assert.deepEqual(nextStep({ status: 'preparing', type: 'dine_in' }), { kind: 'status', to: 'ready' })
|
||||
assert.deepEqual(nextStep({ status: 'out_for_delivery', unpaid: 22 }), { kind: 'finish', pay: true })
|
||||
assert.deepEqual(nextStep({ status: 'ready', unpaid: 0 }), { kind: 'finish', pay: false })
|
||||
assert.equal(nextStep({ status: 'delivered' }), null)
|
||||
assert.equal(nextStep({ status: 'rejected' }), null)
|
||||
const board = { incoming: [{ id: 1 }], in_progress: [{ id: 2 }], finished: [{ id: 3 }] }
|
||||
assert.equal(findOnline(board, 2).id, 2)
|
||||
assert.equal(findOnline(board, 3).id, 3)
|
||||
assert.equal(findOnline(board, 9), null)
|
||||
assert.equal(findOnline(null, 1), null)
|
||||
const at = Date.parse('2026-11-15T10:00:00Z')
|
||||
assert.equal(minutesSince('2026-11-15T09:57:30Z', at), 2)
|
||||
assert.equal(minutesSince('2026-11-15T10:01:00Z', at), 0)
|
||||
})
|
||||
|
||||
+103
-3
@@ -9,7 +9,10 @@
|
||||
// - a customer display (no sign-in) goes straight into its app
|
||||
// - server unreachable → banner → back by itself
|
||||
// - removed from the manager → back to pairing with a notice and a new code
|
||||
// - 3.3a–d: the counter POS (sale, payment, tables with a waiter's phone, online orders
|
||||
// pulled from a fake cloud exactly as from the real one)
|
||||
// node terminal.mjs
|
||||
import http from 'node:http'
|
||||
import net from 'node:net'
|
||||
import path from 'node:path'
|
||||
import { chromium } from 'playwright'
|
||||
@@ -17,7 +20,26 @@ import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs'
|
||||
import { startBackend, startTerminalVite } from './lib/proc.mjs'
|
||||
import { supportLogin } from './lib/support.mjs'
|
||||
|
||||
const backend = await startBackend({ port: 8059, siteId: 'test-site-1' })
|
||||
// A fake cloud for online orders (3.3d): the heartbeat names the site, the order pull hands
|
||||
// over what the test queues, and status changes are recorded (the customer's tracking page).
|
||||
const cloud = { queue: [], synced: [], statuses: [] }
|
||||
const cloudServer = http.createServer((req, res) => {
|
||||
let body = ''
|
||||
req.on('data', c => { body += c })
|
||||
req.on('end', () => {
|
||||
const send = data => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(data)) }
|
||||
const json = () => { try { return JSON.parse(body || '{}') } catch { return {} } }
|
||||
let m
|
||||
if (req.url === '/api/heartbeat/') return send({ site_numeric_id: 7 })
|
||||
if (req.method === 'GET' && req.url === '/api/orders/pending/7') return send(cloud.queue.filter(o => !cloud.synced.includes(o.id)))
|
||||
if ((m = req.url.match(/^\/api\/orders\/(\d+)\/synced$/))) { cloud.synced.push(Number(m[1])); return send({ ok: true }) }
|
||||
if ((m = req.url.match(/^\/api\/orders\/(\d+)\/status$/))) { cloud.statuses.push({ id: Number(m[1]), ...json() }); return send({ ok: true }) }
|
||||
return send({})
|
||||
})
|
||||
})
|
||||
await new Promise(res => cloudServer.listen(0, '127.0.0.1', res))
|
||||
const backend = await startBackend({ port: 8059, siteId: 'test-site-1', cloudUrl: `http://127.0.0.1:${cloudServer.address().port}`,
|
||||
env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1' } })
|
||||
const term = await startTerminalVite({ port: 5187, backendUrl: backend.url })
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
const r = reporter('terminal: pairing, sign-in, app states (paired screens)')
|
||||
@@ -490,10 +512,87 @@ try {
|
||||
const phoneOrder = await api('POST', '/api/orders/', { token: maria, body: { table_id: phoneTable.id } })
|
||||
await api('POST', `/api/orders/${phoneOrder.id}/items`, { token: maria, body: { items: [{ product_id: simple.id, quantity: 2 }] } })
|
||||
r.check('3.3c: a table opened on the phone shows on the counter at once, with what\'s due',
|
||||
await page.waitForFunction(id => document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)?.dataset.state === 'open', phoneTable.id, { timeout: 8000 }).then(() => true).catch(() => false)
|
||||
&& (await page.locator(`[data-testid="pos-table"][data-table="${phoneTable.id}"]`).textContent()).includes((2 * simple.price).toFixed(2)))
|
||||
// (opened, then its items: wait for both, the card shows the order before its items arrive)
|
||||
await page.waitForFunction(([id, due]) => {
|
||||
const card = document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)
|
||||
return card?.dataset.state === 'open' && card.textContent.includes(due)
|
||||
}, [phoneTable.id, (2 * simple.price).toFixed(2)], { timeout: 8000 }).then(() => true).catch(() => false))
|
||||
await page.screenshot({ path: path.join(OUT, 'terminal-pos-tables.png') })
|
||||
phoneWs.close()
|
||||
|
||||
// ── 3.3d: online orders on the POS ──────────────────────────────────────
|
||||
await api('PUT', '/api/platform/modules/connect_menu', { token: boss, body: { enabled: true } })
|
||||
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
|
||||
r.check('3.3d: online orders on → the counter gets an Online mode', await shown(page, 'mode-online', 10_000))
|
||||
const cloudOrder = (id, type, name) => ({
|
||||
id, public_ref: `ORD-${String(id).padStart(4, '0')}`, order_type: type, customer_name: name, customer_phone: '6900000000',
|
||||
customer_address: type === 'delivery' ? 'Main square 3' : null, customer_notes: 'Ring twice', status: 'pending_acceptance',
|
||||
items_json: JSON.stringify([{ product_id: simple.id, name: simple.name, quantity: 2, unit_price: simple.price, options: [] }]),
|
||||
subtotal: 2 * simple.price, delivery_fee: 0, total: 2 * simple.price, created_at: new Date().toISOString(),
|
||||
})
|
||||
const chimesBefore = Number(await page.getByTestId('pos-screen').getAttribute('data-chimes'))
|
||||
cloud.queue.push(cloudOrder(41, 'delivery', 'Nikos Online'))
|
||||
const rang = await page.waitForFunction(n => Number(document.querySelector('[data-testid="pos-screen"]')?.dataset.chimes) > n, chimesBefore, { timeout: 15_000 })
|
||||
.then(() => true).catch(() => false)
|
||||
const badged = await page.waitForFunction(() => document.querySelector('[data-testid="mode-online"]')?.dataset.badge === '1', null, { timeout: 5000 })
|
||||
.then(() => true).catch(() => false)
|
||||
r.check('3.3d: an order placed online reaches the counter at once: it rings, and the badge counts it', rang && badged,
|
||||
`rang ${rang}, badge ${await page.getByTestId('mode-online').getAttribute('data-badge')}`)
|
||||
r.check('3.3d: …the cloud was told it arrived', cloud.synced.includes(41))
|
||||
await page.getByTestId('mode-online').click()
|
||||
const onlineCard = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first()
|
||||
r.check('3.3d: the New list shows it, waiting for an answer', await onlineCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
||||
&& (await onlineCard.textContent()).includes('ORD-0041') && (await onlineCard.textContent()).includes('Nikos Online'))
|
||||
const onlineId = Number(await onlineCard.getAttribute('data-order'))
|
||||
await onlineCard.click()
|
||||
r.check('3.3d: the order shows the customer (phone, address, note) and the items', await shown(page, 'online-panel', 5000)
|
||||
&& (await page.getByTestId('online-customer').textContent()).includes('Main square 3')
|
||||
&& (await page.getByTestId('online-customer').textContent()).includes('Ring twice')
|
||||
&& await page.getByTestId('online-line').count() === 1
|
||||
&& (await page.getByTestId('online-total').textContent()).includes((2 * simple.price).toFixed(2)))
|
||||
await page.screenshot({ path: path.join(OUT, 'terminal-pos-online.png') })
|
||||
const kdsHas = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === onlineId)
|
||||
r.check('3.3d: the kitchen doesn\'t see it before it is accepted', !(await kdsHas()))
|
||||
await page.getByTestId('online-accept').click()
|
||||
await page.waitForFunction(id => document.querySelector(`[data-testid="online-panel"][data-order="${id}"]`)?.dataset.status === 'accepted', onlineId, { timeout: 8000 }).catch(() => {})
|
||||
r.check('3.3d: Accept → accepted, in the In progress list', await page.getByTestId('online-panel').getAttribute('data-status') === 'accepted'
|
||||
&& await page.locator(`[data-testid="online-order"][data-order="${onlineId}"]`).count() === 1)
|
||||
r.check('3.3d: …the kitchen has it now (KDS)', await kdsHas())
|
||||
for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'accepted'); i++) await sleep(100)
|
||||
r.check('3.3d: …and the customer\'s page follows (status sent to the cloud)', cloud.statuses.some(x => x.id === 41 && x.status === 'accepted'))
|
||||
r.check('3.3d: …the badge went back to 0', await page.getByTestId('mode-online').getAttribute('data-badge') === '0')
|
||||
for (const to of ['preparing', 'out_for_delivery']) {
|
||||
await page.getByTestId('online-next').click()
|
||||
await page.waitForFunction(st => document.querySelector('[data-testid="online-panel"]')?.dataset.status === st, to, { timeout: 8000 }).catch(() => {})
|
||||
}
|
||||
r.check('3.3d: Start preparing → Out for delivery', await page.getByTestId('online-panel').getAttribute('data-status') === 'out_for_delivery')
|
||||
const drawerBeforeOnline = drawerBytes.length
|
||||
await page.getByTestId('online-finish').click()
|
||||
await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 })
|
||||
await page.getByTestId('pay-confirm').click()
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid="online-panel"]')?.dataset.status === 'delivered', null, { timeout: 8000 }).catch(() => {})
|
||||
r.check('3.3d: the driver\'s cash taken at the counter → delivered', await page.getByTestId('online-panel').getAttribute('data-status') === 'delivered')
|
||||
for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeOnline; i++) await sleep(100)
|
||||
r.check('3.3d: …the drawer opened and the items are paid', drawerBytes.length > drawerBeforeOnline
|
||||
&& (await api('GET', `/api/orders/${onlineId}`, { token: boss })).items.every(i => i.status === 'paid'))
|
||||
for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'delivered'); i++) await sleep(100)
|
||||
r.check('3.3d: …and the cloud heard every step', ['accepted', 'preparing', 'out_for_delivery', 'delivered']
|
||||
.every(st => cloud.statuses.some(x => x.id === 41 && x.status === st)), JSON.stringify(cloud.statuses))
|
||||
// a second order is rejected with a reason the customer sees
|
||||
await page.getByTestId('online-list-incoming').click()
|
||||
cloud.queue.push(cloudOrder(42, 'dine_in', 'Late Guest'))
|
||||
const secondOnline = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first()
|
||||
await secondOnline.waitFor({ timeout: 15_000 }).catch(() => {})
|
||||
await secondOnline.click()
|
||||
await page.getByTestId('online-reject').click()
|
||||
await page.getByTestId('reason-busy').click()
|
||||
await page.getByTestId('reject-confirm').click()
|
||||
for (let i = 0; i < 50 && !cloud.statuses.some(x => x.id === 42); i++) await sleep(100)
|
||||
const rejected = cloud.statuses.find(x => x.id === 42)
|
||||
r.check('3.3d: Reject with a reason → the customer is told why', rejected?.status === 'rejected' && rejected.rejection_reason?.length > 0,
|
||||
JSON.stringify(rejected))
|
||||
r.check('3.3d: …and it leaves the New list', await page.waitForFunction(() => !document.querySelector('[data-testid="online-order"]'), null, { timeout: 5000 })
|
||||
.then(() => true).catch(() => false))
|
||||
await page.getByTestId('mode-sale').click()
|
||||
drawerServer.close()
|
||||
await page.getByRole('button', { name: 'Sign out' }).click()
|
||||
@@ -528,5 +627,6 @@ try {
|
||||
await browser.close()
|
||||
term.stop()
|
||||
await backend.stop()
|
||||
cloudServer.close()
|
||||
}
|
||||
process.exit(r.done() ? 1 : 0)
|
||||
|
||||
Reference in New Issue
Block a user