diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py
index 3a7fe0b..48c3b1e 100644
--- a/local_backend/core/errors.py
+++ b/local_backend/core/errors.py
@@ -70,6 +70,10 @@ CODES: dict[str, tuple[int, str]] = {
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
+ "pos.table_not_found": (404, "Table {table_id} not found."),
+ "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."),
"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."),
diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py
index 07d3fa8..d8553fc 100644
--- a/local_backend/routers/orders.py
+++ b/local_backend/routers/orders.py
@@ -508,16 +508,8 @@ def add_items(
if order.source == "online":
order_channel = "online"
# Snapshot existing cart items for condition evaluation
- existing_cart = [
- {
- "product_id": i.product_id,
- "category_id": i.product.primary_category_id if i.product else None,
- "category_ids": i.product.category_ids if i.product else [],
- "quantity": i.quantity,
- "unit_price": i.unit_price,
- }
- for i in order.items if i.status == "active"
- ]
+ from services.pos_cart import order_cart
+ existing_cart = order_cart(order) # the counter's table quote starts from the same (3.3c)
for item_in in body.items:
product = db.query(Product).filter(Product.id == item_in.product_id).first()
@@ -800,6 +792,8 @@ def cancel_item(
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval))
db.commit()
+ broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
+ "action": "items_cancelled", "item_ids": cancelled_ids})
should_print = print_cancellation if is_manager else True
if should_print:
@@ -1197,6 +1191,9 @@ def cancel_items_bulk(
if cancelled_ids:
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=cancelled_ids, note=_approval_note(approval))
db.commit()
+ if cancelled_ids:
+ broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
+ "action": "items_cancelled", "item_ids": cancelled_ids})
should_print = body.print_cancellation if is_manager else True
if should_print and cancelled_ids:
diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py
index 8f7edd1..b547f87 100644
--- a/local_backend/routers/pos.py
+++ b/local_backend/routers/pos.py
@@ -5,6 +5,15 @@ GET /api/pos/menu categories and products to sell, with options and today'
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
POST /api/pos/sales a quick sale (3.3b): order + items + payment(s) in one call, the
cash drawer on cash, the fiscal receipt as for any payment
+GET /api/pos/tables the tables the cashier may serve (their zones, as in the waiter app)
+ with each one's open order: totals, people, flags, ready items (3.3c)
+POST /api/pos/tables/{id}/items send cart lines to a table (opens its order if it has none)
+POST /api/pos/orders/{id}/pay pay chosen items of a table's order (cash/card/split, drawer)
+POST /api/pos/orders/{id}/close close a fully paid order (never writes unpaid items off)
+
+Tables use the waiter app's rules and functions (routers/orders.py): zone access, the person
+assigned to an order, business day, kitchen tickets, shift totals. Cancelling items is the
+waiter's own POST /api/orders/{id}/cancel-items (manager approval when the cashier can't).
Prices are never computed on the screen: the menu's `price` is the pricing engine's answer for
one unit with no options right now (happy hours, price groups), and the cart is priced with
@@ -131,6 +140,7 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
class QuoteBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(default_factory=list, max_length=200)
+ order_id: Optional[int] = None # adding to a table's order: its items count for deals (3.3c)
def _adjustments(db, events) -> list[dict]:
@@ -149,7 +159,11 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
"""The cart priced exactly as the order will be: per line the unit price (base + options,
then price groups/modifiers), its total, what was chosen (names) and any adjustment."""
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
- priced = pos_cart.price_lines(db, lines, body.order_type) if lines else []
+ order_type, existing = body.order_type, None
+ if body.order_id is not None:
+ order = _order_for(db, user, body.order_id)
+ order_type, existing = order.order_type or "here", pos_cart.order_cart(order)
+ priced = pos_cart.price_lines(db, lines, order_type, existing) if lines else []
out = []
for line, (unit, events) in zip(lines, priced):
adj = pos_cart.discount_adjustment(unit, line.discount_pct)
@@ -161,7 +175,7 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi
"entries": [{"name": e["name"], "price": e["price_delta"], "type": e["type"]} for e in line.entries],
"removed": line.removed, "notes": line.notes, "adjustments": _adjustments(db, events),
})
- return {"order_type": body.order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
+ return {"order_type": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)}
@@ -196,42 +210,23 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
shift, the fiscal receipt, auto-close), and open the cash drawer of the screen's receipt
printer when cash was taken. The checks run before anything is written. Discounted lines
need ordering.prices.modify or a manager's approval (D-10)."""
- from core.access.context import authorize, current_device
- from core.modules import device_config
from models.order import OrderItem
- from models.printer import Printer
- from models.shift import WaiterShift
- from models.user import User
from routers import orders as orders_api
- from schemas.order import AddItemsRequest, OrderCreate, OrderItemInput, PayItemsRequest, SelectedOptionInput
- from services.fiscal_service import is_fiscal_enabled
- from services.printer_service import open_cash_drawer
+ from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
- if not isinstance(user, User) or db.query(WaiterShift).filter(
- WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None:
- raise XeniaError("pos.shift_required")
+ _require_shift(db, user)
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
groups = _payment_groups(body, len(lines))
- if any(line.discount_pct for line in lines):
- authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
- if is_fiscal_enabled(db):
- missing = sorted({line.product.name for line in lines if not line.product.fiscal_vat_group_id})
- if missing:
- raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
+ _check_discounts(request, db, user, lines)
+ _check_fiscal(db, {line.product for line in lines})
priced = pos_cart.price_lines(db, lines, body.order_type)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
- if body.cash_given is not None and cash_due and body.cash_given + 0.004 < cash_due:
- raise XeniaError("pos.payment_invalid", reason="cash_short")
+ _check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
- items_in = [OrderItemInput(
- product_id=line.product.id, quantity=line.quantity,
- selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
- removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
- ) for line, adj in zip(lines, adjs)]
- added = orders_api.add_items(order.id, AddItemsRequest(items=items_in), db, user)
+ added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
@@ -239,16 +234,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
paid.append({"method": method, "amount": round(sum(totals[i] for i in idx), 2), "item_ids": res["paid_item_ids"]})
fiscal = res.get("fiscal") or fiscal
- drawer = "none"
- if cash_due > 0:
- dev = current_device(request, db)
- cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
- printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None
- if printer is not None and printer.is_active:
- ok, _ = open_cash_drawer(printer, db, reason=f"order {order.id}")
- drawer = "opened" if ok else "failed"
- orders_api._audit(db, order.id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
- db.commit()
+ drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
return {
@@ -256,3 +242,243 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
}
+
+
+# ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
+
+def _require_shift(db, user):
+ from models.shift import WaiterShift
+ from models.user import User
+ if not isinstance(user, User) or db.query(WaiterShift).filter(
+ WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() is None:
+ raise XeniaError("pos.shift_required")
+
+
+def _check_discounts(request, db, user, lines):
+ from core.access.context import authorize
+ if any(line.discount_pct for line in lines):
+ authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
+
+
+def _check_fiscal(db, products):
+ from services.fiscal_service import is_fiscal_enabled
+ if is_fiscal_enabled(db):
+ missing = sorted({p.name for p in products if p is not None and not p.fiscal_vat_group_id})
+ if missing:
+ raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
+
+
+def _check_cash(cash_given, cash_due):
+ if cash_given is not None and cash_due and cash_given + 0.004 < cash_due:
+ raise XeniaError("pos.payment_invalid", reason="cash_short")
+
+
+def _items_in(lines, adjs):
+ """Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options
+ entries with the database's prices; a discount as the item's price_adjustment)."""
+ from schemas.order import OrderItemInput, SelectedOptionInput
+ return [OrderItemInput(
+ product_id=line.product.id, quantity=line.quantity,
+ selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
+ removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
+ ) for line, adj in zip(lines, adjs)]
+
+
+def _open_drawer(request, db, user, order_id) -> str:
+ """Kick the cash drawer of the screen's receipt printer: opened | failed | none (no printer)."""
+ from core.access.context import current_device
+ from core.modules import device_config
+ from models.printer import Printer
+ from routers import orders as orders_api
+ from services.printer_service import open_cash_drawer
+ dev = current_device(request, db)
+ cfg = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
+ printer = db.get(Printer, cfg["receipt_printer_id"]) if cfg.get("receipt_printer_id") else None
+ if printer is None or not printer.is_active:
+ return "none"
+ ok, _ = open_cash_drawer(printer, db, reason=f"order {order_id}")
+ orders_api._audit(db, order_id, "DRAWER_OPENED" if ok else "DRAWER_FAILED", waiter_id=user.id, note=printer.name)
+ db.commit()
+ return "opened" if ok else "failed"
+
+
+# ── tables (3.3c) ───────────────────────────────────────────────────────────────
+
+ACTIVE = ("open", "partially_paid", "paid")
+UNPAID = ("active", "ready")
+
+
+def _table_name(t) -> str:
+ return t.label or f"T{t.number}"
+
+
+def _item_total(i) -> float:
+ return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity
+
+
+def _in_zones(db, user, table) -> bool:
+ """The waiter app's table rule (routers/tables.py list_tables): managers see every table,
+ staff the tables of their zones (a zone row without a group = every zone)."""
+ from models.user import WaiterZone
+ if holds(user, "core.dashboard.access"):
+ return True
+ zones = db.query(WaiterZone).filter(WaiterZone.waiter_id == user.id).all()
+ return any(z.group_id is None or z.group_id == table.group_id for z in zones)
+
+
+def _order_for(db, user, order_id):
+ """The order, if this cashier may act on it (the waiter app's rule, orders._can_access_order)."""
+ from models.order import Order
+ from routers import orders as orders_api
+ order = db.get(Order, order_id)
+ if order is None:
+ raise XeniaError("order.not_found", order_id=order_id)
+ if not orders_api._can_access_order(order, user, db):
+ raise XeniaError("pos.table_not_yours", table=_table_name(order.table) if order.table else f"#{order_id}")
+ return order
+
+
+@router.get("/tables")
+def pos_tables(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
+ """The tables this cashier may serve and, for each, its open order: totals (all, unpaid),
+ item count, who is on it (and whether it's the cashier), when it opened, ready items
+ (KDS done), flags and a reservation due soon."""
+ from models.flag import TableFlagAssignment, TableFlagDef
+ from models.order import Order
+ from models.table import TableGroup
+ from models.user import User
+ from routers import tables as tables_api
+ visible = tables_api.list_tables(include_inactive=False, db=db, user=user)
+ ids = [t.id for t in visible]
+ orders = {}
+ if ids:
+ orders = {o.table_id: o for o in db.query(Order).filter(Order.table_id.in_(ids), Order.status.in_(ACTIVE))
+ .options(selectinload(Order.items), selectinload(Order.waiters)).all()}
+ people_ids = {w.waiter_id for o in orders.values() for w in o.waiters}
+ people = {u.id: u.nickname or u.full_name or u.username
+ for u in db.query(User).filter(User.id.in_(people_ids)).all()} if people_ids else {}
+ flags: dict[int, list] = {}
+ if ids:
+ rows = (db.query(TableFlagAssignment, TableFlagDef).join(TableFlagDef, TableFlagDef.id == TableFlagAssignment.flag_id)
+ .filter(TableFlagAssignment.table_id.in_(ids), TableFlagDef.is_active.is_(True))
+ .order_by(TableFlagDef.sort_order).all())
+ for a, d in rows:
+ flags.setdefault(a.table_id, []).append({"id": d.id, "name": d.name, "emoji": d.emoji, "color": d.color,
+ "text_color": d.text_color})
+
+ def order_out(o):
+ live = [i for i in o.items if i.status in UNPAID or i.status == "paid"]
+ return {
+ "id": o.id, "status": o.status, "opened_at": _iso(o.opened_at),
+ "total": round(sum(_item_total(i) for i in live), 2),
+ "unpaid": round(sum(_item_total(i) for i in live if i.status in UNPAID), 2),
+ "items": len(live),
+ "ready": sum(1 for i in live if (i.kds_status or "pending") == "done"),
+ "people": [people[w.waiter_id] for w in o.waiters if w.waiter_id in people],
+ "mine": any(w.waiter_id == user.id for w in o.waiters),
+ }
+
+ group_ids = [t.group_id for t in visible if t.group_id is not None]
+ groups = db.query(TableGroup).filter(TableGroup.id.in_(group_ids)).order_by(TableGroup.sort_order).all() if group_ids else []
+ return {
+ "groups": [{"id": g.id, "name": g.name, "color": g.color} for g in groups],
+ "tables": [{
+ "id": t.id, "name": _table_name(t), "number": t.number, "group_id": t.group_id, "seats": t.seat_count,
+ "flags": flags.get(t.id, []),
+ "reservation": ({"guest_name": t.upcoming_reservation.guest_name, "party_size": t.upcoming_reservation.party_size,
+ "reserved_for": _iso(t.upcoming_reservation.reserved_for)} if t.upcoming_reservation else None),
+ "order": order_out(orders[t.id]) if t.id in orders else None,
+ } for t in visible],
+ }
+
+
+class TableItemsBody(BaseModel):
+ lines: List[dict] = Field(min_length=1, max_length=200)
+
+
+@router.post("/tables/{table_id}/items", status_code=201)
+def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: Session = Depends(get_db),
+ user=Depends(require(ACCESS))):
+ """Send cart lines to a table, exactly as the waiter app does: into its open order, or a
+ new one (the cashier is assigned to it). Kitchen tickets, KDS, price events, deals."""
+ from models.order import Order
+ from models.table import Table
+ from routers import orders as orders_api
+ from schemas.order import AddItemsRequest, OrderCreate
+ _require_shift(db, user)
+ table = db.get(Table, table_id)
+ if table is None or not table.is_active:
+ raise XeniaError("pos.table_not_found", table_id=table_id)
+ order = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(ACTIVE)).first()
+ if order is not None:
+ order = _order_for(db, user, order.id)
+ elif not _in_zones(db, user, table):
+ raise XeniaError("pos.table_not_yours", table=_table_name(table))
+ lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
+ _check_discounts(request, db, user, lines)
+ existing = pos_cart.order_cart(order) if order is not None else None
+ priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing)
+ adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
+ if order is None:
+ order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
+ added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
+ return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
+
+
+class ItemsPayment(BaseModel):
+ method: Literal["cash", "card"]
+ item_ids: List[int] = Field(min_length=1, max_length=500)
+
+
+class OrderPayBody(BaseModel):
+ payments: List[ItemsPayment] = Field(min_length=1, max_length=2)
+ cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
+
+
+@router.post("/orders/{order_id}/pay")
+def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Session = Depends(get_db),
+ user=Depends(require(ACCESS))):
+ """Pay chosen items of an order (a table's) through POST /api/orders/{id}/pay, one call per
+ method: the cashier's shift, the fiscal receipt, auto-close. Cash opens the drawer. Items
+ someone else paid or cancelled meanwhile → pos.items_changed, nothing is paid."""
+ from models.order import OrderItem
+ from routers import orders as orders_api
+ from schemas.order import PayItemsRequest
+ _require_shift(db, user)
+ order = _order_for(db, user, order_id)
+ wanted = [i for pay in body.payments for i in pay.item_ids]
+ if len(set(wanted)) != len(wanted) or len({pay.method for pay in body.payments}) != len(body.payments):
+ raise XeniaError("pos.payment_invalid", reason="lines")
+ items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()}
+ if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
+ raise XeniaError("pos.items_changed")
+ _check_fiscal(db, {i.product for i in items.values()})
+ amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments}
+ cash_due = amount.get("cash", 0.0)
+ _check_cash(body.cash_given, cash_due)
+
+ paid, fiscal, res = [], None, {}
+ for pay in body.payments:
+ res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=pay.item_ids, payment_method=pay.method), db, user)
+ paid.append({"method": pay.method, "amount": amount[pay.method], "item_ids": res["paid_item_ids"]})
+ fiscal = res.get("fiscal") or fiscal
+ drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
+ change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
+ return {
+ "order_id": order.id, "status": res.get("status"), "auto_closed": bool(res.get("auto_closed")),
+ "total": round(sum(amount.values()), 2), "payments": paid, "cash_given": body.cash_given, "change": change,
+ "drawer": drawer, "fiscal": fiscal,
+ }
+
+
+@router.post("/orders/{order_id}/close")
+def pos_order_close(order_id: int, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
+ """Close an order once everything on it is paid (or cancelled). Unlike the manager's close,
+ the counter never writes unpaid items off: pos.order_unpaid {count}."""
+ from models.order import OrderItem
+ from routers import orders as orders_api
+ order = _order_for(db, user, order_id)
+ unpaid = db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.status.in_(UNPAID)).count()
+ if unpaid:
+ raise XeniaError("pos.order_unpaid", count=unpaid)
+ return orders_api.close_order(order.id, db, user)
diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py
index 46642f8..55150e5 100644
--- a/local_backend/services/pos_cart.py
+++ b/local_backend/services/pos_cart.py
@@ -197,6 +197,21 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
return out
+def order_cart(order) -> list[dict]:
+ """An order's active items as the pricing engine's cart context (what POST
+ /api/orders/{id}/items starts from, and what a table's quote starts from, 3.3c)."""
+ return [
+ {
+ "product_id": i.product_id,
+ "category_id": i.product.primary_category_id if i.product else None,
+ "category_ids": i.product.category_ids if i.product else [],
+ "quantity": i.quantity,
+ "unit_price": i.unit_price,
+ }
+ for i in order.items if i.status == "active"
+ ]
+
+
def discount_adjustment(unit_price: float, pct) -> float:
"""A line's discount (percent of its unit price) as the order item's price_adjustment
(negative, rounded to cents)."""
diff --git a/local_backend/tests/test_pos_tables.py b/local_backend/tests/test_pos_tables.py
new file mode 100644
index 0000000..c6b3f0a
--- /dev/null
+++ b/local_backend/tests/test_pos_tables.py
@@ -0,0 +1,199 @@
+"""Counter POS: tables at the counter (plan step 3.3c). The counter works on tables with the
+waiter app's rules and functions; these tests prove both sides see and change the same order."""
+import pytest
+
+from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
+from tests.test_pos import burger_line, drawer_printer, menu, on_shift, till # noqa: F401 (fixtures)
+
+
+@pytest.fixture
+def floor(db, till):
+ """Two zones: Terrace (T1, T2) for the cashier and Inside (T3) that isn't theirs."""
+ from models.table import Table, TableGroup
+ from models.user import WaiterZone
+ terrace, inside = TableGroup(name="Terrace", sort_order=1), TableGroup(name="Inside", sort_order=2)
+ db.add_all([terrace, inside])
+ db.flush()
+ t1, t2 = Table(number=1, group_id=terrace.id, seat_count=4), Table(number=2, label="Corner", group_id=terrace.id)
+ t3 = Table(number=3, group_id=inside.id)
+ db.add_all([t1, t2, t3])
+ db.add(WaiterZone(waiter_id=till["cashier"].id, group_id=terrace.id))
+ db.commit()
+ return {"terrace": terrace, "inside": inside, "t1": t1, "t2": t2, "t3": t3}
+
+
+@pytest.fixture
+def phone(db, make_user, login, floor, on_shift):
+ """A waiter on their phone, working the terrace too, with their own shift."""
+ from models.shift import WaiterShift
+ from models.user import WaiterZone
+ maria = make_user(role="waiter", nickname="Maria")
+ db.add(WaiterZone(waiter_id=maria.id, group_id=floor["terrace"].id))
+ db.add(WaiterShift(waiter_id=maria.id, business_day_id=on_shift.business_day_id))
+ db.commit()
+ return {"user": maria, "h": login(maria, "waiter")}
+
+
+@pytest.fixture
+def events(monkeypatch):
+ """Order events broadcast by routers/orders.py (what phones, the KDS and the counter hear)."""
+ import routers.orders as orders
+ got = []
+ real = orders.broadcast_sync
+ monkeypatch.setattr(orders, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data)), real(kind, data, **kw)))
+ return got
+
+
+def tables(client, till):
+ r = client.get("/api/pos/tables", headers=till["h"])
+ assert r.status_code == 200, r.text
+ return {t["name"]: t for t in r.json()["tables"]}, r.json()["groups"]
+
+
+def send(client, till, table, lines):
+ return client.post(f"/api/pos/tables/{table.id}/items", headers=till["h"], json={"lines": lines})
+
+
+def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu):
+ from models.flag import TableFlagAssignment, TableFlagDef
+ flag = TableFlagDef(name="VIP", emoji="⭐", color="#aa0000")
+ db.add(flag)
+ db.flush()
+ db.add(TableFlagAssignment(table_id=floor["t2"].id, flag_id=flag.id))
+ db.commit()
+ by_name, groups = tables(client, till)
+ assert set(by_name) == {"T1", "Corner"} and [g["name"] for g in groups] == ["Terrace"]
+ assert by_name["T1"]["order"] is None and by_name["T1"]["seats"] == 4
+ assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}]
+ # the waiter opens T1 on the phone; the counter sees it with totals and who is on it
+ o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json()
+ client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]})
+ t1 = tables(client, till)[0]["T1"]["order"]
+ assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1
+ assert t1["people"] == ["Maria"] and t1["mine"] is False
+
+
+def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, events):
+ """The done-when of 3.3c at the API level: both sides add to one order and see the other's
+ changes; every change is broadcast."""
+ m = menu
+ r = send(client, till, floor["t1"], [{"product_id": m["coffee"].id}])
+ assert r.status_code == 201, r.text
+ oid = r.json()["order_id"]
+ assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open", "action": "opened"}) in events
+ # the phone sees the counter's order and adds to it
+ seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json()
+ assert [i["product_name"] for i in seen["items"]] == ["Freddo"]
+ assert client.post(f"/api/orders/{oid}/items", headers=phone["h"],
+ json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
+ # the counter adds a burger to the same order (not a second one)
+ assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid
+ t1 = tables(client, till)[0]["T1"]["order"]
+ assert t1["total"] == 16.0 and t1["mine"] is True and t1["people"] == [till["cashier"].full_name]
+ detail = client.get(f"/api/orders/{oid}", headers=till["h"]).json()
+ assert sorted(i["product_name"] for i in detail["items"]) == ["Burger", "Freddo", "Freddo"]
+
+
+def test_quote_for_a_table_counts_its_items(client, db, till, floor, menu, on_shift):
+ """The table's items already on the order count for cart conditions, as in add_items."""
+ import json as _json
+ from models.order import OrderItem
+ from models.pricing import PriceModifier, PriceModifierCondition
+ mod = PriceModifier(name="2nd coffee", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1)
+ db.add(mod)
+ db.flush()
+ db.add(PriceModifierCondition(modifier_id=mod.id, condition_type="min_item_quantity", params=_json.dumps({"min": 2})))
+ db.commit()
+ line = [{"product_id": menu["coffee"].id}]
+ oid = send(client, till, floor["t1"], line).json()["order_id"]
+ assert client.post("/api/pos/quote", headers=till["h"], json={"lines": line}).json()["total"] == 3.0
+ q = client.post("/api/pos/quote", headers=till["h"], json={"order_id": oid, "lines": line}).json()
+ assert q["order_type"] == "here" and q["total"] == 2.7
+ send(client, till, floor["t1"], line)
+ prices = [i.unit_price for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)]
+ assert prices == [3.0, 2.7] # the order charged what the quote said
+
+
+def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_shift, make_user, login):
+ from models.shift import WaiterShift
+ from models.user import WaiterZone
+ assert err(send(client, till, floor["t3"], [{"product_id": menu["coffee"].id}])) == "pos.table_not_yours"
+ # an order inside, opened by someone else, can't be quoted, paid or closed from here
+ nikos = make_user(role="waiter")
+ db.add(WaiterZone(waiter_id=nikos.id, group_id=floor["inside"].id))
+ db.add(WaiterShift(waiter_id=nikos.id, business_day_id=on_shift.business_day_id))
+ db.commit()
+ h = login(nikos, "waiter")
+ o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json()
+ client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]})
+ item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"]
+ assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours"
+ assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"],
+ json={"payments": [{"method": "cash", "item_ids": [item]}]})) == "pos.table_not_yours"
+ assert err(client.post(f"/api/pos/orders/{o['id']}/close", headers=till["h"])) == "pos.table_not_yours"
+ assert err(client.post("/api/pos/tables/999999/items", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]})) == "pos.table_not_found"
+
+
+def test_sending_needs_a_shift_and_checks_lines_first(client, db, till, floor, menu):
+ from models.order import Order
+ assert err(send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}])) == "pos.shift_required"
+ assert db.query(Order).count() == 0
+
+
+def test_pay_some_add_more_pay_the_rest_close(client, db, till, floor, menu, on_shift, drawer_printer, events):
+ from models.order import Order
+ m = menu
+ oid = send(client, till, floor["t1"], [{"product_id": m["coffee"].id, "quantity": 2}, burger_line(m)]).json()["order_id"]
+ items = {i["product_name"]: i["id"] for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"]}
+ # pay the coffees in cash: change, drawer
+ r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
+ json={"payments": [{"method": "cash", "item_ids": [items["Freddo"]]}], "cash_given": 10})
+ assert r.status_code == 200, r.text
+ assert (r.json()["total"], r.json()["change"], r.json()["drawer"], r.json()["status"]) == (6.0, 4.0, "opened", "partially_paid")
+ assert any(k == "order_paid" and d["order_id"] == oid for k, d in events)
+ # paying them again (someone else did) → nothing happens
+ assert err(client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
+ json={"payments": [{"method": "card", "item_ids": [items["Freddo"], items["Burger"]]}]})) == "pos.items_changed"
+ # can't close with the burger unpaid
+ r = client.post(f"/api/pos/orders/{oid}/close", headers=till["h"])
+ assert err(r) == "pos.order_unpaid" and r.json()["error"]["params"] == {"count": 1}
+ # add more, then pay the rest split: burger by card, the new coffee in cash
+ send(client, till, floor["t1"], [{"product_id": m["coffee"].id}])
+ rest = [i for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"] if i["status"] == "active"]
+ burger = next(i["id"] for i in rest if i["product_name"] == "Burger")
+ coffee = next(i["id"] for i in rest if i["product_name"] == "Freddo")
+ r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
+ json={"payments": [{"method": "card", "item_ids": [burger]}, {"method": "cash", "item_ids": [coffee]}]})
+ assert r.status_code == 200 and r.json()["status"] == "paid" and r.json()["change"] is None
+ assert [(p["method"], p["amount"]) for p in r.json()["payments"]] == [("card", 10.0), ("cash", 3.0)]
+ shift = client.get("/api/shifts/my", headers=till["h"]).json()
+ assert (shift["cash_sales"], shift["card_sales"]) == (9.0, 10.0)
+ assert client.post(f"/api/pos/orders/{oid}/close", headers=till["h"]).json() == {"status": "closed"}
+ assert db.get(Order, oid).status == "closed" and tables(client, till)[0]["T1"]["order"] is None
+
+
+def test_pay_checks(client, till, floor, menu, on_shift):
+ oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}]).json()["order_id"]
+ item = client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"][0]["id"]
+ pay = lambda body: client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], json=body) # noqa: E731
+ assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}], "cash_given": 1})) == "pos.payment_invalid"
+ assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}, {"method": "card", "item_ids": [item]}]})) == "pos.payment_invalid"
+ assert err(pay({"payments": [{"method": "cash", "item_ids": [999999]}]})) == "pos.items_changed"
+
+
+def test_cancel_from_the_counter_needs_a_manager_and_is_broadcast(client, db, till, floor, menu, on_shift, pair, make_user, events):
+ from models.order import OrderItem
+ oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}, {"product_id": menu["coffee"].id, "notes": "iced"}]).json()["order_id"]
+ ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)]
+ # a waiter-role cashier can't cancel sent items alone: the manager-approval dialog
+ r = client.post(f"/api/orders/{oid}/cancel-items", headers=till["h"], json={"item_ids": [ids[0]]})
+ assert err(r) == "access.override_possible"
+ # a manager at the counter can; everyone hears about it
+ token, _ = pair("pos_counter", "Till 3")
+ boss = make_user(role="owner")
+ h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
+ r = client.post(f"/api/orders/{oid}/cancel-items", headers=h, json={"item_ids": [ids[0]]})
+ assert r.status_code == 200 and r.json()["cancelled"] == [ids[0]]
+ assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open",
+ "action": "items_cancelled", "item_ids": [ids[0]]}) in events
+ assert tables(client, till)[0]["T1"]["order"]["total"] == 3.0
diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json
index c9e26d6..45e2920 100644
--- a/packages/i18n/locales/el/errors.json
+++ b/packages/i18n/locales/el/errors.json
@@ -82,6 +82,10 @@
"line_invalid": "Η γραμμή {{line}} του καλαθιού δεν μπορεί να πουληθεί όπως επιλέχθηκε ({{reason}}).",
"shift_required": "Ξεκινήστε τη βάρδιά σας πριν πουλήσετε.",
"payment_invalid": "Αυτή η πληρωμή δεν βγαίνει ({{reason}}).",
- "fiscal_vat_missing": "Οι φορολογικές αποδείξεις είναι ενεργές, αλλά αυτά τα προϊόντα δεν έχουν ομάδα ΦΠΑ: {{names}}."
+ "fiscal_vat_missing": "Οι φορολογικές αποδείξεις είναι ενεργές, αλλά αυτά τα προϊόντα δεν έχουν ομάδα ΦΠΑ: {{names}}.",
+ "table_not_found": "Δεν βρέθηκε το τραπέζι {{table_id}}.",
+ "table_not_yours": "Το {{table}} δεν είναι στις ζώνες σας. Ένας διαχειριστής μπορεί να προσθέσει τη ζώνη στον λογαριασμό σας.",
+ "items_changed": "Κάποια από αυτά πληρώθηκαν ή ακυρώθηκαν στο μεταξύ. Ελέγξτε την παραγγελία και δοκιμάστε ξανά.",
+ "order_unpaid": "Απλήρωτα είδη: {{count}}. Πάρτε την πληρωμή ή ακυρώστε τα πρώτα."
}
}
diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json
index f494ca9..24d38c3 100644
--- a/packages/i18n/locales/el/terminal.json
+++ b/packages/i18n/locales/el/terminal.json
@@ -237,6 +237,59 @@
"again": "Τα ίδια ξανά",
"toast": "Πληρώθηκε",
"toastChange": "Πληρώθηκε. Ρέστα: {{change}}"
+ },
+ "mode": {
+ "label": "Λειτουργία ταμείου",
+ "sale": "Πώληση",
+ "tables": "Τραπέζια"
+ },
+ "tables": {
+ "none": "Δεν έχετε τραπέζια",
+ "noneBody": "Βλέπετε τα τραπέζια των ζωνών σας, όπως στην εφαρμογή σερβιτόρου. Ένας διαχειριστής μπορεί να προσθέσει ζώνες στον λογαριασμό σας.",
+ "allZones": "Όλες οι ζώνες",
+ "state": {
+ "free": "Ελεύθερο",
+ "mine": "Δικό σας",
+ "open": "Πιασμένο",
+ "paid": "Πληρωμένο, ανοιχτό"
+ },
+ "ofTotal": "από {{total}}",
+ "since": "από τις {{time}}",
+ "ready_one": "{{count}} έτοιμο",
+ "ready_other": "{{count}} έτοιμα",
+ "reserved": "Κράτηση {{time}} · {{name}} ({{count}})",
+ "noZone": "Χωρίς ζώνη"
+ },
+ "table": {
+ "back": "Πίσω στα τραπέζια",
+ "closedElsewhere": "Το {{table}} έκλεισε από άλλη συσκευή.",
+ "sent": "Στάλθηκε στο {{table}}",
+ "closed": "Το {{table}} έκλεισε",
+ "cancelled_one": "Ακυρώθηκε {{count}} είδος",
+ "cancelled_other": "Ακυρώθηκαν {{count}} είδη",
+ "onOrder": "Στην παραγγελία",
+ "new": "Νέα, δεν έχουν σταλεί",
+ "empty": "Δεν υπάρχει τίποτα ακόμη σε αυτό το τραπέζι",
+ "emptyBody": "Πατήστε προϊόντα για να τα προσθέσετε και μετά στείλτε τα στο τραπέζι.",
+ "newTotal": "Νέα είδη",
+ "send": "Αποστολή στο {{table}}",
+ "due": "Υπόλοιπο",
+ "paySelected": "Πληρωμή επιλεγμένων {{amount}}",
+ "payAll": "Πληρωμή όλων {{amount}}",
+ "cancel": "Ακύρωση επιλεγμένων",
+ "selectAll": "Επιλογή όλων",
+ "selectNone": "Καμία επιλογή",
+ "close": "Κλείσιμο {{table}}",
+ "cancelTitle_one": "Ακύρωση {{count}} είδους;",
+ "cancelTitle_other": "Ακύρωση {{count}} ειδών;",
+ "cancelBody": "Φεύγουν από τον λογαριασμό και η κουζίνα παίρνει δελτίο ακύρωσης. Αν δεν μπορείτε να ακυρώσετε σταλμένα είδη, το εγκρίνει ένας διαχειριστής με το PIN του.",
+ "keep": "Να μείνουν",
+ "cancelConfirm": "Ακύρωση ειδών",
+ "paidBy": {
+ "cash": "πληρώθηκε · μετρητά",
+ "card": "πληρώθηκε · κάρτα"
+ },
+ "readyItem": "έτοιμο"
}
}
}
diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json
index 776f94a..180d224 100644
--- a/packages/i18n/locales/en/errors.json
+++ b/packages/i18n/locales/en/errors.json
@@ -82,6 +82,10 @@
"line_invalid": "Cart line {{line}} can't be sold as chosen ({{reason}}).",
"shift_required": "Start your shift before selling.",
"payment_invalid": "This payment doesn't add up ({{reason}}).",
- "fiscal_vat_missing": "Fiscal receipts are on, but these products have no VAT group: {{names}}."
+ "fiscal_vat_missing": "Fiscal receipts are on, but these products have no VAT group: {{names}}.",
+ "table_not_found": "Table {{table_id}} not found.",
+ "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."
}
}
diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json
index 03231c1..62e2752 100644
--- a/packages/i18n/locales/en/terminal.json
+++ b/packages/i18n/locales/en/terminal.json
@@ -237,6 +237,59 @@
"again": "Same again",
"toast": "Paid",
"toastChange": "Paid. Change: {{change}}"
+ },
+ "mode": {
+ "label": "Counter mode",
+ "sale": "Sale",
+ "tables": "Tables"
+ },
+ "tables": {
+ "none": "No tables for you",
+ "noneBody": "You see the tables of your zones, as in the waiter app. A manager can add zones to your account.",
+ "allZones": "All zones",
+ "state": {
+ "free": "Free",
+ "mine": "Yours",
+ "open": "Taken",
+ "paid": "Paid, not closed"
+ },
+ "ofTotal": "of {{total}}",
+ "since": "since {{time}}",
+ "ready_one": "{{count}} ready",
+ "ready_other": "{{count}} ready",
+ "reserved": "Reserved {{time}} · {{name}} ({{count}})",
+ "noZone": "No zone"
+ },
+ "table": {
+ "back": "Back to the tables",
+ "closedElsewhere": "{{table}} was closed on another device.",
+ "sent": "Sent to {{table}}",
+ "closed": "{{table}} is closed",
+ "cancelled_one": "{{count}} item cancelled",
+ "cancelled_other": "{{count}} items cancelled",
+ "onOrder": "On the order",
+ "new": "New, not sent yet",
+ "empty": "Nothing on this table yet",
+ "emptyBody": "Tap products to add them, then send them to the table.",
+ "newTotal": "New items",
+ "send": "Send to {{table}}",
+ "due": "Still due",
+ "paySelected": "Pay selected {{amount}}",
+ "payAll": "Pay everything {{amount}}",
+ "cancel": "Cancel selected",
+ "selectAll": "Select all",
+ "selectNone": "Select none",
+ "close": "Close {{table}}",
+ "cancelTitle_one": "Cancel {{count}} item?",
+ "cancelTitle_other": "Cancel {{count}} items?",
+ "cancelBody": "They come off the bill and the kitchen gets a cancellation ticket. If you can't cancel sent items, a manager approves it with their PIN.",
+ "keep": "Keep them",
+ "cancelConfirm": "Cancel items",
+ "paidBy": {
+ "cash": "paid · cash",
+ "card": "paid · card"
+ },
+ "readyItem": "ready"
}
}
}
diff --git a/terminal/src/apps/pos/CartLine.jsx b/terminal/src/apps/pos/CartLine.jsx
new file mode 100644
index 0000000..a485d6c
--- /dev/null
+++ b/terminal/src/apps/pos/CartLine.jsx
@@ -0,0 +1,40 @@
+// One cart line at the counter (plan steps 3.3a–c): name, chosen options, quantity buttons,
+// a per-line discount, and the backend's price for it (POST /api/pos/quote).
+import { Minus, Plus } from 'lucide-react'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { IconButton, Select } from '@xenia/ui'
+import { DISCOUNTS, unitOf } from './logic/cart'
+
+export default function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) {
+ const { t } = useTranslation('terminal')
+ const { formatMoney } = useFormat()
+ const unit = product ? unitOf(product) : null
+ const step = unit ? unit.step : 1
+ const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×`
+ return (
+
+ }
+ return (
+
+ )
+}
diff --git a/terminal/src/apps/pos/TablesView.jsx b/terminal/src/apps/pos/TablesView.jsx
new file mode 100644
index 0000000..a880459
--- /dev/null
+++ b/terminal/src/apps/pos/TablesView.jsx
@@ -0,0 +1,93 @@
+// The table list at the counter (plan step 3.3c): the cashier's tables (their zones, as in
+// the waiter app), each with its state, what's still due, who is on it, ready items, flags
+// and a reservation due soon. A tap opens the table: the product grid adds to its order and
+// the right column shows the order (TablePanel). Live: a waiter's change shows at once.
+import { CalendarClock, ChefHat, Users } from 'lucide-react'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { EmptyState, Spinner } from '@xenia/ui'
+import { tableState, tablesIn } from './logic/tables'
+
+const LOOK = {
+ free: 'bg-surface border-line text-ink',
+ mine: 'bg-accent-soft border-accent text-accent-ink',
+ open: 'bg-info-soft border-info text-info-ink',
+ paid: 'bg-success-soft border-success text-success-ink',
+}
+
+export default function TablesView({ data, zone, onPick }) {
+ const { t } = useTranslation('terminal')
+ if (!data) return
+ // all zones: one section per zone (table numbers can repeat between zones)
+ const sections = zone != null
+ ? [{ id: zone, name: null, tables: tablesIn(data.tables, zone) }]
+ : [...data.groups.map(g => ({ id: g.id, name: g.name, tables: tablesIn(data.tables, g.id) })),
+ { id: 'none', name: t('pos.tables.noZone'), tables: data.tables.filter(x => x.group_id == null) }].filter(s => s.tables.length)
+ if (!data.tables.length) {
+ return
+ }
+ return (
+
+ {sections.map(s => (
+
+ {s.name &&
{s.name}
}
+
+ {s.tables.map(table => onPick(table.id)} />)}
+
+
+ ))}
+
+ )
+}
+
+function TableCard({ table, onPick }) {
+ const { t } = useTranslation('terminal')
+ const { formatMoney, formatTime } = useFormat()
+ const state = tableState(table)
+ const o = table.order
+ return (
+
+ )
+}
diff --git a/terminal/src/apps/pos/logic/tables.js b/terminal/src/apps/pos/logic/tables.js
new file mode 100644
index 0000000..1f672cb
--- /dev/null
+++ b/terminal/src/apps/pos/logic/tables.js
@@ -0,0 +1,88 @@
+// Tables at the counter (plan step 3.3c): what the table list and a table's order show.
+// Amounts come from the backend (GET /api/pos/tables, GET /api/orders/{id}); this file only
+// groups, labels and adds up what it was given. Pure: unit-tested in Node (tests/pos.test.mjs).
+
+/** free | mine | open (someone else's) | paid (nothing left to pay). */
+export function tableState(table) {
+ const o = table.order
+ if (!o) return 'free'
+ if (o.items > 0 && o.unpaid <= 0.004) return 'paid'
+ return o.mine ? 'mine' : 'open'
+}
+
+/** Tables of one zone (null = all), in the backend's order. */
+export function tablesIn(tables, groupId) {
+ return groupId == null ? tables : tables.filter(t => t.group_id === groupId)
+}
+
+/** Counts for the zone list: { [groupId|'all']: { total, busy } }. */
+export function zoneCounts(tables) {
+ const out = { all: { total: 0, busy: 0 } }
+ for (const t of tables) {
+ const k = t.group_id ?? 'none'
+ out[k] = out[k] ?? { total: 0, busy: 0 }
+ for (const c of [out.all, out[k]]) {
+ c.total += 1
+ if (t.order) c.busy += 1
+ }
+ }
+ return out
+}
+
+const round2 = n => Math.round(n * 100) / 100
+
+/** The option names stored on an order item (selected_options is JSON text or a list). */
+export function optionNames(selected) {
+ let list = selected
+ if (typeof selected === 'string') {
+ try { list = JSON.parse(selected) } catch { list = [] }
+ }
+ return Array.isArray(list) ? list.map(o => o?.name).filter(Boolean) : []
+}
+
+/** An order's items as the counter lists them (cancelled and written-off ones left out),
+ * unpaid first, each with its total. */
+export function orderLines(order) {
+ if (!order?.items) return []
+ const lines = order.items
+ .filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid')
+ .map(i => ({
+ id: i.id,
+ name: i.product_name ?? i.product?.name ?? '',
+ quantity: i.quantity,
+ unitType: i.unit_type,
+ total: round2((i.unit_price + (i.price_adjustment || 0)) * i.quantity),
+ paid: i.status === 'paid',
+ method: i.payment_method,
+ options: optionNames(i.selected_options),
+ notes: i.notes,
+ kds: i.kds_status ?? 'pending',
+ }))
+ return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)]
+}
+
+/** { total, paid, unpaid, unpaidIds } of the lines. */
+export function orderSums(lines) {
+ const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0))
+ const open = lines.filter(l => !l.paid)
+ return { total: sum(lines), paid: sum(lines.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) }
+}
+
+/** What "Pay" takes: the selected unpaid lines, or every unpaid line when none is selected. */
+export function toPay(lines, selected) {
+ const open = lines.filter(l => !l.paid)
+ const chosen = open.filter(l => selected.includes(l.id))
+ return chosen.length ? chosen : open
+}
+
+/** The dialog's payments (by row index) as POST /api/pos/orders/{id}/pay takes them. */
+export function itemPayments(payments, rows) {
+ return payments.map(p => ({ method: p.method, item_ids: p.lines.map(i => rows[i].id) }))
+}
+
+/** "2×" or "0.5 kg" for an order line. */
+export function qtyLabel(quantity, unitType) {
+ const units = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
+ if (!units[unitType]) return `${quantity}×`
+ return unitType === 'kg' || unitType === 'liter' ? `${Number(quantity).toFixed(1)} ${units[unitType]}` : `${quantity} ${units[unitType]}`
+}
diff --git a/terminal/src/apps/pos/usePos.js b/terminal/src/apps/pos/usePos.js
index 0e6c254..f7b78d3 100644
--- a/terminal/src/apps/pos/usePos.js
+++ b/terminal/src/apps/pos/usePos.js
@@ -1,5 +1,6 @@
-// The counter POS's server data (plan step 3.3a): the cashier's session (shift gate), the
-// menu, and the cart priced by the backend. Kept fresh by the live connection.
+// 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
+// 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'
import { useLiveEvent, useLiveEvents } from '../../device/context'
@@ -40,25 +41,74 @@ export function useMenu() {
return { menu, reload: load }
}
-/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins).
+/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins). With
+ * `orderId` (a table's order) the order's items count for deals, as when it's sent.
* → { quote, pending, error } */
-export function useQuote(lines, orderType) {
+export function useQuote(lines, orderType, orderId = null) {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
- const key = JSON.stringify([lines, orderType])
+ const key = JSON.stringify([lines, orderType, orderId])
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined }
setState(s => ({ ...s, pending: true }))
const id = setTimeout(async () => {
try {
- const { data } = await client.post('/api/pos/quote', { order_type: orderType, lines }, quiet)
+ const { data } = await client.post('/api/pos/quote', { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
if (mine === seq.current) setState({ quote: data, pending: false, error: null })
} catch (err) {
if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err }))
}
}, QUOTE_DELAY_MS)
return () => clearTimeout(id)
- }, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType
+ }, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType + orderId
return state
}
+
+const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated']
+const COALESCE_MS = 150
+
+/** Calls `load` once for a burst of events (a payment sends several). */
+function useCoalesced(load) {
+ const timer = useRef(null)
+ useEffect(() => () => clearTimeout(timer.current), [])
+ return useCallback(() => {
+ clearTimeout(timer.current)
+ timer.current = setTimeout(load, COALESCE_MS)
+ }, [load])
+}
+
+/** GET /api/pos/tables: { groups, tables } (null while loading); live. */
+export function useTables() {
+ const [data, setData] = useState(null)
+ const load = useCallback(async () => {
+ try { setData((await client.get('/api/pos/tables', quiet)).data) } catch { /* the shell shows offline */ }
+ }, [])
+ const soon = useCoalesced(load)
+ useEffect(() => { load() }, [load])
+ useLiveEvent('ready', load)
+ useLiveEvents(TABLE_EVENTS, soon)
+ return { data, reload: load }
+}
+
+/** GET /api/orders/{id} for one order (null id → null); reloads on that order's events.
+ * → { order, gone, reload } (gone: closed or removed meanwhile). */
+export function useOrder(orderId) {
+ const [order, setOrder] = useState(null)
+ const [gone, setGone] = useState(false)
+ const load = useCallback(async () => {
+ if (orderId == null) { setOrder(null); setGone(false); return }
+ try {
+ const { data } = await client.get(`/api/orders/${orderId}`, quiet)
+ setOrder(data)
+ setGone(data.status === 'closed' || data.status === 'cancelled')
+ } catch (err) {
+ if (err?.xenia?.status === 404) setGone(true)
+ }
+ }, [orderId])
+ const soon = useCoalesced(load)
+ useEffect(() => { load() }, [load])
+ useLiveEvent('ready', load)
+ useLiveEvents(TABLE_EVENTS, (_type, data) => { if (data?.order_id === orderId) soon() })
+ return { order, gone, reload: load }
+}
diff --git a/terminal/tests/pos.test.mjs b/terminal/tests/pos.test.mjs
index 526f9ad..d96ff0a 100644
--- a/terminal/tests/pos.test.mjs
+++ b/terminal/tests/pos.test.mjs
@@ -98,3 +98,33 @@ test('paying: quick amounts, change, split parts (3.3b)', async () => {
assert.deepEqual(splitPayments(['card', 'cash', 'cash'], [10, 3, 2.5]),
{ cash: 5.5, card: 10, payments: [{ method: 'card', lines: [0] }, { method: 'cash', lines: [1, 2] }] })
})
+
+test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)', async () => {
+ const { itemPayments, optionNames, orderLines, orderSums, qtyLabel, tableState, tablesIn, toPay, zoneCounts } = await import('../src/apps/pos/logic/tables.js')
+ const free = { id: 1, group_id: 7, order: null }
+ const mine = { id: 2, group_id: 7, order: { items: 2, unpaid: 6, total: 6, mine: true } }
+ const theirs = { id: 3, group_id: 8, order: { items: 1, unpaid: 3, total: 3, mine: false } }
+ const paid = { id: 4, group_id: 8, order: { items: 1, unpaid: 0, total: 3, mine: false } }
+ assert.deepEqual([free, mine, theirs, paid].map(tableState), ['free', 'mine', 'open', 'paid'])
+ assert.deepEqual(tablesIn([free, mine, theirs], 8).map(t => t.id), [3])
+ assert.deepEqual(zoneCounts([free, mine, theirs, paid]), { all: { total: 4, busy: 3 }, 7: { total: 2, busy: 1 }, 8: { total: 2, busy: 2 } })
+ assert.deepEqual(optionNames('[{"name":"Rare"},{"name":"Fries"}]'), ['Rare', 'Fries'])
+ assert.deepEqual(optionNames('not json'), [])
+ const order = { items: [
+ { id: 10, product_name: 'Freddo', quantity: 2, unit_price: 3, price_adjustment: 0, status: 'paid', payment_method: 'cash' },
+ { id: 11, product_name: 'Burger', quantity: 1, unit_price: 10, price_adjustment: -1, status: 'active', selected_options: '[{"name":"Rare"}]' },
+ { id: 12, product_name: 'Old', quantity: 1, unit_price: 5, status: 'cancelled' },
+ { id: 13, product_name: 'Wine', quantity: 0.5, unit_type: 'liter', unit_price: 12, status: 'ready', kds_status: 'done' },
+ ] }
+ const lines = orderLines(order)
+ assert.deepEqual(lines.map(l => [l.id, l.total, l.paid]), [[11, 9, false], [13, 6, false], [10, 6, true]])
+ assert.deepEqual(lines[0].options, ['Rare'])
+ assert.deepEqual(orderSums(lines), { total: 21, paid: 6, unpaid: 15, unpaidIds: [11, 13] })
+ assert.deepEqual(toPay(lines, []).map(l => l.id), [11, 13]) // nothing selected → everything unpaid
+ assert.deepEqual(toPay(lines, [13, 10]).map(l => l.id), [13]) // a paid line can't be chosen
+ const rows = toPay(lines, []).map(l => ({ id: l.id, total: l.total }))
+ assert.deepEqual(itemPayments([{ method: 'card', lines: [1] }, { method: 'cash', lines: [0] }], rows),
+ [{ method: 'card', item_ids: [13] }, { method: 'cash', item_ids: [11] }])
+ assert.equal(qtyLabel(2, 'piece'), '2×')
+ assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
+})
diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs
index 4a65bb8..b3f44d2 100644
--- a/tests/e2e/terminal.mjs
+++ b/tests/e2e/terminal.mjs
@@ -407,6 +407,94 @@ try {
&& (await page.getByTestId('sale-done').textContent()).includes('Card') && !(await page.getByTestId('sale-done').textContent()).includes('Drawer'))
await sleep(300)
r.check('3.3b: …and the drawer stayed shut', drawerBytes.length === drawerBefore)
+
+ // ── 3.3c: tables at the counter, with a waiter's phone on the same table ─
+ // the phone: Maria's live connection (as the waiter app opens it) and her API calls
+ const phoneEvents = []
+ const phoneWs = new WebSocket(`${backend.url.replace(/^http/, 'ws')}/api/ws/connect`)
+ await new Promise(res => {
+ phoneWs.onopen = () => phoneWs.send(JSON.stringify({ cursor: 0, token: maria }))
+ phoneWs.onmessage = e => { const m = JSON.parse(e.data); if (m.type === 'ready') res(); else phoneEvents.push(m) }
+ setTimeout(res, 5000)
+ })
+ const heard = async (pred, ms = 5000) => {
+ for (let i = 0; i < ms / 100; i++) { if (phoneEvents.some(pred)) return true; await sleep(100) }
+ return false
+ }
+ const mariaTables = new Set((await api('GET', '/api/tables/', { token: maria })).map(t => t.id))
+ await page.getByTestId('mode-tables').click()
+ r.check('3.3c: Tables shows the table list', await shown(page, 'pos-tables', 10_000))
+ const counterTables = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/tables')).data.tables)
+ const shared = counterTables.find(t => !t.order && mariaTables.has(t.id))
+ const tableCard = page.locator(`[data-testid="pos-table"][data-table="${shared.id}"]`)
+ r.check('3.3c: …each table with its state (a free one)', await tableCard.getAttribute('data-state') === 'free')
+ await tableCard.click()
+ r.check('3.3c: a table opens with the product grid and its (empty) order', await shown(page, 'table-panel', 5000) && await simpleCard.isVisible())
+ await simpleCard.locator('button').first().click()
+ await page.getByTestId('table-send').waitFor({ timeout: 5000 })
+ await page.waitForFunction(() => !document.querySelector('[data-testid="table-send"]')?.disabled, null, { timeout: 5000 }).catch(() => {})
+ await page.getByTestId('table-send').click()
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 1, null, { timeout: 8000 }).catch(() => {})
+ const tableOrder = Number(await page.getByTestId('table-panel').getAttribute('data-order'))
+ r.check('3.3c: Send opens the table\'s order with the line', tableOrder > 0 && await page.getByTestId('order-line').count() === 1)
+ r.check('3.3c: the phone hears it at once (live)', await heard(m => m.type === 'order_updated' && m.data.order_id === tableOrder && m.data.action === 'items_added'))
+ const onPhone = await api('GET', `/api/orders/${tableOrder}`, { token: maria })
+ r.check('3.3c: …and sees the counter\'s order on that table', onPhone.table_id === shared.id && onPhone.items.length === 1)
+
+ // the phone adds two items → the counter shows them without a reload
+ await api('POST', `/api/orders/${tableOrder}/items`, { token: maria, body: { items: [
+ { product_id: simple.id, quantity: 1, notes: 'from the phone' }, { product_id: simple.id, quantity: 1, notes: 'to cancel' }] } })
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 3, null, { timeout: 8000 }).catch(() => {})
+ r.check('3.3c: the phone adds items → the counter shows them live', await page.getByTestId('order-line').count() === 3
+ && (await page.getByTestId('order-lines').textContent()).includes('from the phone'))
+
+ // cancel one from the counter (the cashier is a manager here: no approval needed)
+ const afterPhone = await api('GET', `/api/orders/${tableOrder}`, { token: maria })
+ const toCancel = afterPhone.items.find(i => i.notes === 'to cancel').id
+ const fromPhone = afterPhone.items.find(i => i.notes === 'from the phone').id
+ await page.locator(`[data-testid="order-line"][data-item="${toCancel}"]`).click()
+ await page.getByTestId('table-cancel').click()
+ await page.getByTestId('cancel-confirm').click()
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 2, null, { timeout: 8000 }).catch(() => {})
+ r.check('3.3c: cancel at the counter takes the item off', await page.getByTestId('order-line').count() === 2)
+ r.check('3.3c: …and the phone hears it', await heard(m => m.type === 'order_updated' && m.data.action === 'items_cancelled' && m.data.item_ids?.includes(toCancel)))
+
+ // pay the phone's item in cash (selected), then the rest by card, then close
+ await page.locator(`[data-testid="order-line"][data-item="${fromPhone}"]`).click()
+ await page.getByTestId('table-pay').click()
+ await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 })
+ r.check('3.3c: Pay takes only the selected item', (await page.getByTestId('pay-confirm').textContent()).includes(simple.price.toFixed(2)))
+ const drawerBeforeTable = drawerBytes.length
+ await page.getByTestId('pay-confirm').click()
+ const paidShown = await shown(page, 'table-paid', 8000)
+ // the order reloads after the payment (live, coalesced): wait for the line to turn paid
+ await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"][data-paid="true"]').length === 1, null, { timeout: 8000 }).catch(() => {})
+ r.check('3.3c: paid some items: the panel says so and the item shows as paid', paidShown
+ && await page.locator('[data-testid="order-line"][data-paid="true"]').count() === 1)
+ for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeTable; i++) await sleep(100)
+ r.check('3.3c: …cash opens the drawer here too', drawerBytes.length > drawerBeforeTable)
+ r.check('3.3c: the phone sees the payment', await heard(m => m.type === 'order_paid' && m.data.order_id === tableOrder)
+ && (await api('GET', `/api/orders/${tableOrder}`, { token: maria })).items.find(i => i.id === fromPhone).status === 'paid')
+ await page.screenshot({ path: path.join(OUT, 'terminal-pos-table.png') })
+ await page.getByTestId('table-pay').click()
+ await page.getByTestId('pay-card').click()
+ await page.getByTestId('pay-confirm').click()
+ r.check('3.3c: everything paid → Close', await shown(page, 'table-close', 8000))
+ await page.getByTestId('table-close').click()
+ r.check('3.3c: closed → back to the list, the table is free again', await shown(page, 'pos-tables', 8000)
+ && await page.waitForFunction(id => document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)?.dataset.state === 'free', shared.id, { timeout: 5000 }).then(() => true).catch(() => false))
+ r.check('3.3c: the phone hears the table close', await heard(m => m.type === 'order_closed' && m.data.order_id === tableOrder))
+
+ // a waiter opens a table on the phone → the counter's list shows it live
+ const phoneTable = counterTables.find(t => !t.order && mariaTables.has(t.id) && t.id !== shared.id)
+ 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)))
+ await page.screenshot({ path: path.join(OUT, 'terminal-pos-tables.png') })
+ phoneWs.close()
+ await page.getByTestId('mode-sale').click()
drawerServer.close()
await page.getByRole('button', { name: 'Sign out' }).click()