Plan phase 3S, step S.5. - Pull: an online order keeps the customer's time (orders.requested_for, None = as soon as possible) and delivery area; quick options are stored in the site's entry shape; items get their cost snapshot. - The delivery fee is its own order line: a system product (products.system_key "delivery_fee", lifecycle "system", sold nowhere; services/system_products.py), created on first use in the venue's language with the VAT group most products use. Added printed and served, so kitchen tickets and the KDS never see it; paid at the counter with the items, counted in the shift, on the fiscal receipt with its VAT group. Never listed in the catalogue (products list, export, edit endpoints → 404) and never added by hand. - Price check (services/online_check.py): each line priced as the snapshot prices it, at the order's time, and the fee through the same engine with the site's rules and the cloud's area id; differences kept on orders.online_price_diff and shown. The customer pays what the cloud charged. - Counter: time chip (or as soon as possible), area, fee line, price warning; takeaway is its own kind (was shown as "at the venue") and finishes as "collected". KDS cards show the online reference and the time; kitchen tickets print the reference, the type and the time. - Manager: Online ordering → "The fee on the receipt" (name, VAT group; PUT /api/connect/fees/fee-product, fees.vat_group_unknown); the online orders page shows the time, area and price warning. - Migration 0019. Tests: tests/test_online_site_side.py (6), terminal unit test, e2e (terminal: fee, time, warning, paid in full; manager: fee line settings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
11 KiB
Python
249 lines
11 KiB
Python
"""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).
|
|
|
|
Since phase 3S (S.5) an order carries the customer's time (`requested_for`, None = as soon as
|
|
possible), its delivery area, the delivery fee as its own line (`system_key` "delivery_fee",
|
|
paid with the items) and the site's price check (`price_diff`, services/online_check.py).
|
|
"""
|
|
import logging
|
|
from typing import Literal, Optional
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
from sqlalchemy.orm import Session, selectinload
|
|
|
|
from config import settings
|
|
from core.access.deps import require
|
|
from core.errors import XeniaError
|
|
from core.timeutil import utcnow
|
|
from database import get_db
|
|
from models.order import Order, OrderItem
|
|
from schemas.order import OrderItemOut, OrderOut
|
|
from services.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] = Field(default=None, max_length=300)
|
|
|
|
|
|
class StatusUpdateRequest(BaseModel):
|
|
status: Literal["preparing", "ready", "out_for_delivery", "delivered"]
|
|
|
|
|
|
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
|
|
def _get_online_order(order_id: int, db: Session) -> Order:
|
|
order = db.query(Order).filter(Order.id == order_id, Order.source == "online").first()
|
|
if not order:
|
|
raise XeniaError("online.not_found", order_id=order_id)
|
|
return order
|
|
|
|
|
|
def _move(order: Order, to: str) -> None:
|
|
"""Refuses a step that doesn't follow (someone else moved the order meanwhile)."""
|
|
if to not in TRANSITIONS.get(order.online_status or "", set()):
|
|
raise XeniaError("online.status_changed")
|
|
order.online_status = to
|
|
|
|
|
|
def _cloud_headers() -> dict:
|
|
return {"X-Site-ID": settings.SITE_ID, "X-Site-Key": settings.SITE_KEY}
|
|
|
|
|
|
async def _mirror_status_to_cloud(cloud_order_id: int, new_status: str, rejection_reason: str = None):
|
|
"""Best-effort push of status update to cloud. Failures are logged, not raised."""
|
|
if not settings.CLOUD_URL or not cloud_order_id:
|
|
return
|
|
try:
|
|
body = {"status": new_status}
|
|
if rejection_reason:
|
|
body["rejection_reason"] = rejection_reason
|
|
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
resp = await client.patch(
|
|
f"{settings.CLOUD_URL}/api/orders/{cloud_order_id}/status",
|
|
headers=_cloud_headers(),
|
|
json=body,
|
|
)
|
|
resp.raise_for_status()
|
|
logger.info("Mirrored status %s for cloud order id %d", new_status, cloud_order_id)
|
|
|
|
except Exception as e:
|
|
logger.warning("Failed to mirror status to cloud for order id %d: %s", cloud_order_id, e)
|
|
|
|
|
|
def _changed(background: BackgroundTasks, order: Order, reason: str = None) -> None:
|
|
background.add_task(_mirror_status_to_cloud, order.online_order_cloud_id, order.online_status, reason)
|
|
broadcast_sync("online_order_updated", {"order_id": order.id, "status": order.online_status})
|
|
|
|
|
|
def _item_total(i: OrderItem) -> float:
|
|
return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity
|
|
|
|
|
|
def _iso(dt):
|
|
return None if dt is None else (dt.isoformat() + "Z" if dt.tzinfo is None else dt.isoformat())
|
|
|
|
|
|
def _board_out(order: Order) -> dict:
|
|
"""An online order as the counter lists it: who, what, how much is still to pay."""
|
|
items = [i for i in order.items if i.status not in ("cancelled", "closed")]
|
|
return {
|
|
"id": order.id,
|
|
"ref": order.online_order_ref,
|
|
"status": order.online_status,
|
|
"type": order.online_order_type,
|
|
"opened_at": _iso(order.opened_at),
|
|
"closed_at": _iso(order.closed_at),
|
|
"customer": {
|
|
"name": order.online_customer_name, "phone": order.online_customer_phone,
|
|
"address": order.online_customer_address, "notes": order.online_customer_notes,
|
|
},
|
|
"requested_for": _iso(order.requested_for), # None = as soon as possible (S.5)
|
|
"area": order.online_delivery_area,
|
|
"price_diff": OrderOut._diff(order.online_price_diff),
|
|
"items": [OrderItemOut.model_validate(i).model_dump(mode="json") for i in items],
|
|
"fee": round(sum(_item_total(i) for i in items if i.system_key == "delivery_fee"), 2),
|
|
"total": round(sum(_item_total(i) for i in items), 2),
|
|
"unpaid": round(sum(_item_total(i) for i in items if i.status in UNPAID), 2),
|
|
}
|
|
|
|
|
|
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
|
|
|
@router.get("/orders/board")
|
|
def online_board(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
|
"""The counter's online orders (3.3d): `incoming` waiting for acceptance (oldest first, the
|
|
next to answer on top), `in_progress` (oldest first) and the last few `finished`."""
|
|
q = db.query(Order).filter(Order.source == "online").options(selectinload(Order.items))
|
|
incoming = q.filter(Order.online_status == "pending_acceptance").order_by(Order.opened_at.asc()).all()
|
|
in_progress = q.filter(Order.online_status.in_(IN_PROGRESS)).order_by(Order.opened_at.asc()).all()
|
|
finished = q.filter(Order.online_status.in_(FINISHED)).order_by(Order.id.desc()).limit(FINISHED_SHOWN).all()
|
|
return {
|
|
"incoming": [_board_out(o) for o in incoming],
|
|
"in_progress": [_board_out(o) for o in in_progress],
|
|
"finished": [_board_out(o) for o in finished],
|
|
}
|
|
|
|
|
|
@router.get("/orders", response_model=list[OrderOut])
|
|
def get_orders_by_status(status: str, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
|
"""
|
|
?status=active → accepted | preparing | ready | out_for_delivery, newest first
|
|
?status=history → delivered | rejected, newest first, limit 50
|
|
"""
|
|
if status == "active":
|
|
return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(IN_PROGRESS))
|
|
.order_by(Order.opened_at.desc()).all())
|
|
if status == "history":
|
|
return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(FINISHED))
|
|
.order_by(Order.opened_at.desc()).limit(50).all())
|
|
raise HTTPException(status_code=400, detail=f"Unknown status filter '{status}'. Use 'active' or 'history'.")
|
|
|
|
|
|
@router.get("/orders/incoming", response_model=list[OrderOut])
|
|
def get_incoming_orders(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
|
"""Return all online orders pending acceptance, newest first."""
|
|
return (db.query(Order).filter(Order.source == "online", Order.online_status == "pending_acceptance")
|
|
.order_by(Order.opened_at.desc()).all())
|
|
|
|
|
|
@router.post("/orders/{order_id}/accept", response_model=OrderOut)
|
|
def accept_order(order_id: int, background: BackgroundTasks, db: Session = Depends(get_db),
|
|
user=Depends(require(MANAGE))):
|
|
"""Accept: the kitchen gets its tickets and the order shows on the KDS (until now it was
|
|
kept off both, as it could still be rejected)."""
|
|
from routers import orders as orders_api
|
|
from services.printer_service import route_and_print_sync
|
|
order = _get_online_order(order_id, db)
|
|
_move(order, "accepted")
|
|
orders_api._audit(db, order.id, "ONLINE_ACCEPTED", waiter_id=user.id, note=order.online_order_ref)
|
|
db.commit()
|
|
unprinted = [i.id for i in order.items if not i.printed and i.status == "active"]
|
|
if unprinted:
|
|
route_and_print_sync(order.id, unprinted, db)
|
|
db.refresh(order)
|
|
_changed(background, order)
|
|
broadcast_sync("order_updated", {"order_id": order.id, "table_id": None, "status": order.status, "action": "items_added",
|
|
"item_ids": unprinted})
|
|
broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status})
|
|
return order
|
|
|
|
|
|
@router.post("/orders/{order_id}/reject", response_model=OrderOut)
|
|
def reject_order(order_id: int, body: RejectRequest, background: BackgroundTasks, db: Session = Depends(get_db),
|
|
user=Depends(require(MANAGE))):
|
|
from routers import orders as orders_api
|
|
order = _get_online_order(order_id, db)
|
|
_move(order, "rejected")
|
|
order.status = "cancelled"
|
|
order.closed_at, order.closed_by = utcnow(), user.id
|
|
for item in order.items:
|
|
if item.status == "active":
|
|
item.status = "cancelled"
|
|
orders_api._audit(db, order.id, "ONLINE_REJECTED", waiter_id=user.id, note=body.reason)
|
|
db.commit()
|
|
db.refresh(order)
|
|
_changed(background, order, body.reason)
|
|
return order
|
|
|
|
|
|
@router.post("/orders/{order_id}/status", response_model=OrderOut)
|
|
def update_order_status(order_id: int, body: StatusUpdateRequest, background: BackgroundTasks,
|
|
db: Session = Depends(get_db), user=Depends(require(MANAGE))):
|
|
"""The next step. Delivered (or collected) closes the order and takes it off the KDS. The
|
|
counter takes the payment first (POST /api/pos/orders/{id}/pay); the manager's list can
|
|
still mark an unpaid order delivered (its items stay unpaid, as before)."""
|
|
from routers import orders as orders_api
|
|
order = _get_online_order(order_id, db)
|
|
_move(order, body.status)
|
|
if body.status == "delivered":
|
|
for item in order.items:
|
|
if item.kds_status != "served":
|
|
item.kds_status = "served"
|
|
order.kds_status = "served"
|
|
if order.status != "closed":
|
|
order.status = "closed"
|
|
order.closed_at, order.closed_by = utcnow(), user.id
|
|
orders_api._audit(db, order.id, f"ONLINE_{body.status.upper()}", waiter_id=user.id)
|
|
db.commit()
|
|
db.refresh(order)
|
|
_changed(background, order)
|
|
if body.status == "delivered":
|
|
broadcast_sync("kds_order_updated", {"order_id": order.id, "kds_status": order.kds_status})
|
|
return order
|