feat(backend,terminal): tables at the counter, shared live with the waiter phones (platform-v2 3.3c)

- POS: GET /api/pos/tables (the cashier's zones as in the waiter app, each open order's
  totals, people, ready items, flags, reservation), POST /api/pos/tables/{id}/items (into
  the table's order or a new one via orders.open_order + add_items), POST
  /api/pos/orders/{id}/pay (chosen items, cash/card/split, drawer on cash), POST
  /api/pos/orders/{id}/close (only when nothing is unpaid). Quote takes order_id so the
  order's items count for cart conditions (shared pos_cart.order_cart, used by add_items).
- New codes pos.table_not_found, pos.table_not_yours, pos.items_changed, pos.order_unpaid.
- Fix: item cancels (DELETE item, cancel-items) now broadcast order_updated, so phones and
  kitchen screens see them at once.
- Terminal: Sale | Tables switch, zone list, table cards by zone, TablePanel (order lines,
  new lines, send, pay selected/all, cancel with approval, close), generic PaymentDialog.
- Tests: test_pos_tables.py (8), terminal unit, terminal.mjs +17 with a live phone socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 02:15:54 +02:00
co-authored by Claude Opus 5.5
parent bff82a332a
commit 988d413d8e
19 changed files with 1452 additions and 218 deletions
+4
View File
@@ -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."),
+7 -10
View File
@@ -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:
+263 -37
View File
@@ -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)
+15
View File
@@ -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)."""
+199
View File
@@ -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
+5 -1
View File
@@ -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}}. Πάρτε την πληρωμή ή ακυρώστε τα πρώτα."
}
}
+53
View File
@@ -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": "έτοιμο"
}
}
}
+5 -1
View File
@@ -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."
}
}
+53
View File
@@ -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"
}
}
}
+40
View File
@@ -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 (
<div className="px-3 py-2 border-b border-line grid gap-1" data-testid="cart-line" data-product={line.product_id}>
<div className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-body font-medium text-ink">{product?.name ?? priced?.name}</span>
<span className="text-body text-ink" data-testid="line-total">{priced ? formatMoney(priced.total) : '…'}</span>
</div>
{priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && (
<div className="text-label text-ink-2 grid">
{priced.entries.map((e, i) => <span key={i}>+ {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''}</span>)}
{priced.removed.map(n => <span key={n} className="text-danger-ink">− {n}</span>)}
{priced.notes && <span className="italic">“{priced.notes}”</span>}
</div>
)}
<div className="flex items-center gap-2">
<IconButton size="sm" variant="secondary" label={t('pos.less')} onClick={() => onQty(line.quantity - step)}><Minus size={16} /></IconButton>
<span className="min-w-12 text-center text-body font-semibold" data-testid="line-qty">{qtyText}</span>
<IconButton size="sm" variant="secondary" label={t('pos.more')} onClick={() => onQty(line.quantity + step)}><Plus size={16} /></IconButton>
{priced && line.quantity !== 1 && <span className="text-caption text-ink-3">{t('pos.each', { price: formatMoney(priced.unit_price) })}</span>}
<span className="flex-1" />
<Select size="sm" value={String(line.discount_pct ?? 0)} onChange={e => onDiscount(Number(e.target.value))} aria-label={t('pos.discount')}
title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36"
options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />
</div>
{priced?.discount ? <span className="text-label text-success-ink">{t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })}</span> : null}
</div>
)
}
+14 -17
View File
@@ -1,26 +1,26 @@
// Taking the payment at the counter (plan step 3.3b, D-26): cash (amount given → change,
// Taking a payment at the counter (plan steps 3.3b, 3.3c, D-26): cash (amount given → change,
// quick amounts), card (typed on the card terminal, recorded as card), or split between them
// by line. One call does the whole sale (POST /api/pos/sales): order, kitchen tickets,
// payment(s) on the cashier's shift, fiscal receipt, cash drawer. Cash with the exact amount
// is pre-selected: Charge → Cash → Take = three taps.
// by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick
// sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay,
// rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps.
import { useState } from 'react'
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input } from '@xenia/ui'
import client from '../../api/client'
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
export default function PaymentDialog({ cart, quote, orderType, names, onPaid, onClose }) {
/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split', rowMethods, payments, cashGiven })
* → the result passed to onPaid. `payments` are by row index (splitPayments). */
export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const total = quote.total
const totals = quote.lines.map(l => l.total)
const totals = rows.map(r => r.total)
const [method, setMethod] = useState('cash')
const [split, setSplit] = useState(() => cart.map(() => 'card'))
const [split, setSplit] = useState(() => rows.map(() => 'card'))
const parts = splitPayments(split, totals)
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0
const [givenText, setGivenText] = useState('') // empty = the exact amount
@@ -34,12 +34,9 @@ export default function PaymentDialog({ cart, quote, orderType, names, onPaid, o
if (busy || short) return
setBusy(true)
setError('')
const payments = method === 'split' ? parts.payments : [{ method }]
const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }]
try {
const { data } = await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments, cash_given: cashDue > 0 ? (given ?? cashDue) : null,
})
onPaid(data)
onPaid(await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null }))
} catch (err) {
setError(errorMessage(err, t))
} finally {
@@ -68,10 +65,10 @@ export default function PaymentDialog({ cart, quote, orderType, names, onPaid, o
</div>
{method === 'split' && (
<div className="grid gap-1" data-testid="split-lines">
{cart.map((line, i) => (
<div className="grid gap-1 max-h-72 overflow-y-auto" data-testid="split-lines">
{rows.map((row, i) => (
<div key={i} className="flex items-center gap-2 py-1 border-b border-line">
<span className="flex-1 min-w-0 text-body text-ink truncate">{line.quantity}× {names[i]}</span>
<span className="flex-1 min-w-0 text-body text-ink truncate">{row.label}</span>
<span className="text-body text-ink-2">{formatMoney(totals[i])}</span>
<span className="flex gap-1">
{['cash', 'card'].map(m => (
+79 -129
View File
@@ -1,19 +1,22 @@
// The counter POS screen (plan step 3.3a): categories on the left, the product grid with a
// search on top, the cart on the right. 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: the menu's and the cart's quote. Charge → PaymentDialog (3.3b); after a sale
// the cart shows what happened and "Same again".
// The counter POS screen (plan steps 3.3a–c). Two 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).
// 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 { Banknote, Info, Minus, Plus, Repeat, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan } from '@xenia/access'
import { Button, EmptyState, IconButton, Input, Select, Spinner, useToast } from '@xenia/ui'
import {
DISCOUNTS, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
} from './logic/cart'
import PaymentDialog from './PaymentDialog'
import { EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
import { zoneCounts } from './logic/tables'
import ProductDialog from './ProductDialog'
import { useMenu, useQuote } from './usePos'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useTables } from './usePos'
export default function PosScreen() {
const { t } = useTranslation('terminal')
@@ -23,24 +26,31 @@ export default function PosScreen() {
}
function Counter({ menu, t }) {
const { formatMoney } = useFormat()
const { language } = useLanguage()
const [mode, setMode] = useState('sale') // sale | tables
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)
const [query, setQuery] = useState('')
const [orderType, setOrderType] = useState(menu.settings.default_order_type)
const [cart, setCart] = useState([])
const [saleCart, setSaleCart] = useState([])
const [tableCart, setTableCart] = useState([])
const [dialog, setDialog] = useState(null) // product
const [paying, setPaying] = useState(false)
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
const quote = useQuote(cart, orderType)
const toast = useToast()
const tables = useTables()
const canDiscount = useCan('ordering.prices.modify')
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
// 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 setCart = atTable ? setTableCart : setSaleCart
const leaveTable = () => { setTableId(null); setTableCart([]) }
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
const shown = useMemo(() => (query.trim() ? searchProducts(menu.products, query) : productsIn(menu.products, category)),
[menu.products, query, category])
const counts = useMemo(() => zoneCounts(tables.data?.tables ?? []), [tables.data])
const tap = product => {
if (needsChoices(product)) { setDialog(product); return }
@@ -50,17 +60,39 @@ 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}>
{/* categories */}
<nav className="border-r border-line bg-surface overflow-y-auto p-2 grid content-start gap-1" data-testid="pos-categories">
<CategoryButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</CategoryButton>
{categories.map(c => (
<CategoryButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name}
</CategoryButton>
<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')}>
<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>
</div>
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1" data-testid={picking ? 'pos-zones' : 'pos-categories'}>
{picking ? (
<>
<NavButton active={zone == null} onClick={() => setZone(null)} count={counts.all}>{t('pos.tables.allZones')}</NavButton>
{(tables.data?.groups ?? []).map(g => (
<NavButton key={g.id} colour={g.color} active={zone === g.id} onClick={() => setZone(g.id)} count={counts[g.id]} testId={`zone-${g.id}`}>{g.name}</NavButton>
))}
</>
) : (
<>
<NavButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</NavButton>
{categories.map(c => (
<NavButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name}
</NavButton>
))}
</>
)}
</div>
</nav>
{/* products */}
{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>
) : (
<>
<main className="flex flex-col min-h-0 min-w-0">
<div className="p-3 border-b border-line bg-surface flex items-center gap-2">
<div className="relative flex-1">
@@ -79,69 +111,40 @@ function Counter({ menu, t }) {
)}
</div>
</main>
{/* cart */}
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="pos-cart">
<div className="p-3 border-b border-line grid grid-cols-2 gap-1" role="radiogroup" aria-label={t('pos.orderType')}>
{[['takeaway', ShoppingBag], ['here', Utensils]].map(([type, Icon]) => (
<button key={type} type="button" role="radio" aria-checked={orderType === type} onClick={() => setOrderType(type)} data-testid={`type-${type}`}
className={`min-h-[var(--x-control-md)] rounded-control flex items-center justify-center gap-2 text-body font-medium transition-colors duration-fast
${orderType === type ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={16} />{t(`pos.type.${type}`)}
</button>
))}
</div>
<div className="flex-1 overflow-y-auto">
{cart.length === 0 && lastSale && <SaleDone sale={lastSale} onAgain={() => { setCart(lastSale.lines); setOrderType(lastSale.orderType); setLastSale(null) }} />}
{cart.length === 0
? !lastSale && <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
: cart.map((line, i) => (
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
onQty={q => setCart(c => setLineQty(c, i, q))}
onDiscount={pct => setCart(c => c.map((l, j) => (j === i ? { ...l, discount_pct: pct || undefined } : l)))} />
))}
</div>
<div className="border-t border-line p-3 grid gap-3">
{quote.error && <p role="alert" className="text-label text-danger-ink">{t('pos.quoteFailed')}</p>}
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.total')}</span>
<span className={`text-display font-semibold ${quote.pending ? 'opacity-50' : ''}`} data-testid="cart-total">
{formatMoney(quote.quote?.total ?? 0)}
</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={!ready} onClick={() => setPaying(true)} data-testid="charge">
{t('pos.charge', { total: formatMoney(quote.quote?.total ?? 0) })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
</aside>
{paying && quote.quote && (
<PaymentDialog cart={cart} quote={quote.quote} orderType={orderType} names={cart.map(l => byId.get(l.product_id)?.name ?? '')}
onClose={() => setPaying(false)}
onPaid={result => {
setPaying(false)
setLastSale({ lines: cart, orderType, result })
setCart([])
toast.success(result.change != null ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
}} />
{atTable
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount}
onBack={leaveTable} onTablesChanged={tables.reload} />
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} />}
</>
)}
{dialog && (
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
<ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
)}
</div>
)
}
function CategoryButton({ active, colour, onClick, children, testId }) {
function ModeButton({ active, onClick, icon: Icon, badge, children, testId }) {
return (
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId}
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}
</button>
)
}
function NavButton({ active, colour, onClick, children, testId, count }) {
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
${active ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2'}`}>
{colour && <span className="size-2.5 rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />}
<span className="truncate">{children}</span>
<span className="flex-1 truncate">{children}</span>
{count && <span className="text-caption text-ink-3">{count.busy}/{count.total}</span>}
</button>
)
}
@@ -168,56 +171,3 @@ function ProductCard({ product, onTap, onInfo }) {
</div>
)
}
function SaleDone({ sale, onAgain }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const r = sale.result
return (
<div className="m-3 p-4 rounded-card bg-success-soft text-success-ink grid gap-2" data-testid="sale-done" data-order={r.order_id}>
<div className="text-title font-semibold">{t('pos.done.paid', { total: formatMoney(r.total) })}</div>
{r.change != null && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
<div className="text-label">
{r.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
{r.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
{r.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
{r.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
</div>
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
</div>
)
}
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 (
<div className="px-3 py-2 border-b border-line grid gap-1" data-testid="cart-line" data-product={line.product_id}>
<div className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-body font-medium text-ink">{product?.name ?? priced?.name}</span>
<span className="text-body text-ink" data-testid="line-total">{priced ? formatMoney(priced.total) : '…'}</span>
</div>
{priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && (
<div className="text-label text-ink-2 grid">
{priced.entries.map((e, i) => <span key={i}>+ {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''}</span>)}
{priced.removed.map(n => <span key={n} className="text-danger-ink">− {n}</span>)}
{priced.notes && <span className="italic">“{priced.notes}”</span>}
</div>
)}
<div className="flex items-center gap-2">
<IconButton size="sm" variant="secondary" label={t('pos.less')} onClick={() => onQty(line.quantity - step)}><Minus size={16} /></IconButton>
<span className="min-w-12 text-center text-body font-semibold" data-testid="line-qty">{qtyText}</span>
<IconButton size="sm" variant="secondary" label={t('pos.more')} onClick={() => onQty(line.quantity + step)}><Plus size={16} /></IconButton>
{priced && line.quantity !== 1 && <span className="text-caption text-ink-3">{t('pos.each', { price: formatMoney(priced.unit_price) })}</span>}
<span className="flex-1" />
<Select size="sm" value={String(line.discount_pct ?? 0)} onChange={e => onDiscount(Number(e.target.value))} aria-label={t('pos.discount')}
title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36"
options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />
</div>
{priced?.discount ? <span className="text-label text-success-ink">{t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })}</span> : null}
</div>
)
}
+102
View File
@@ -0,0 +1,102 @@
// The quick-sale cart (plan steps 3.3a–b): order type, the lines priced by the backend,
// Charge → PaymentDialog (POST /api/pos/sales); after a sale it shows what happened and
// "Same again".
import { useState } from 'react'
import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, useToast } from '@xenia/ui'
import client from '../../api/client'
import CartLine from './CartLine'
import { setLineQty } from './logic/cart'
import PaymentDialog from './PaymentDialog'
import { useQuote } from './usePos'
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const toast = useToast()
const [paying, setPaying] = useState(false)
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
const quote = useQuote(cart, orderType)
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven,
})).data
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="pos-cart">
<div className="p-3 border-b border-line grid grid-cols-2 gap-1" role="radiogroup" aria-label={t('pos.orderType')}>
{[['takeaway', ShoppingBag], ['here', Utensils]].map(([type, Icon]) => (
<button key={type} type="button" role="radio" aria-checked={orderType === type} onClick={() => setOrderType(type)} data-testid={`type-${type}`}
className={`min-h-[var(--x-control-md)] rounded-control flex items-center justify-center gap-2 text-body font-medium transition-colors duration-fast
${orderType === type ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={16} />{t(`pos.type.${type}`)}
</button>
))}
</div>
<div className="flex-1 overflow-y-auto">
{cart.length === 0 && lastSale && <SaleDone sale={lastSale} onAgain={() => { setCart(lastSale.lines); setOrderType(lastSale.orderType); setLastSale(null) }} />}
{cart.length === 0
? !lastSale && <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
: cart.map((line, i) => (
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
onQty={q => setCart(c => setLineQty(c, i, q))}
onDiscount={pct => setCart(c => c.map((l, j) => (j === i ? { ...l, discount_pct: pct || undefined } : l)))} />
))}
</div>
<div className="border-t border-line p-3 grid gap-3">
{quote.error && <p role="alert" className="text-label text-danger-ink">{t('pos.quoteFailed')}</p>}
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.total')}</span>
<span className={`text-display font-semibold ${quote.pending ? 'opacity-50' : ''}`} data-testid="cart-total">
{formatMoney(quote.quote?.total ?? 0)}
</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={!ready} onClick={() => setPaying(true)} data-testid="charge">
{t('pos.charge', { total: formatMoney(quote.quote?.total ?? 0) })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
{paying && quote.quote && (
<PaymentDialog total={quote.quote.total} submit={submit}
rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))}
onClose={() => setPaying(false)}
onPaid={result => {
setPaying(false)
setLastSale({ lines: cart, orderType, result })
setCart([])
toast.success(result.change > 0 ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
}} />
)}
</aside>
)
}
export function PaidSummary({ result }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
return (
<div className="text-label">
{result.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
{result.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
{result.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
{result.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
</div>
)
}
function SaleDone({ sale, onAgain }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const r = sale.result
return (
<div className="m-3 p-4 rounded-card bg-success-soft text-success-ink grid gap-2" data-testid="sale-done" data-order={r.order_id}>
<div className="text-title font-semibold">{t('pos.done.paid', { total: formatMoney(r.total) })}</div>
{r.change > 0 && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
<PaidSummary result={r} />
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
</div>
)
}
+241
View File
@@ -0,0 +1,241 @@
// A table at the counter (plan step 3.3c): the right column while a table is open. It shows
// what's on the table's order (the waiter app's order, live), new lines from the product grid
// (priced with the order's items counted, as when sent), and the actions: send to the table,
// pay some or all items (cash/card/split, drawer), cancel sent items (a manager approves when
// the cashier can't: the shared approval dialog), close once everything is paid.
import { useEffect, useState } from 'react'
import { ArrowLeft, Ban, Banknote, Check, CheckCircle2, Lock, Send, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xenia/ui'
import client from '../../api/client'
import CartLine from './CartLine'
import { setLineQty } from './logic/cart'
import { itemPayments, orderLines, orderSums, qtyLabel, tableState, toPay } from './logic/tables'
import PaymentDialog from './PaymentDialog'
import { PaidSummary } from './SaleCart'
import { useOrder, useQuote } from './usePos'
export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const toast = useToast()
const orderId = table.order?.id ?? null
const { order, gone, reload } = useOrder(orderId)
const quote = useQuote(cart, 'here', orderId)
const [picked, setPicked] = useState([])
const [busy, setBusy] = useState(false)
const [paying, setPaying] = useState(null) // rows being paid
const [cancelling, setCancelling] = useState(false)
const [lastPay, setLastPay] = useState(null)
const [error, setError] = useState('')
const lines = orderLines(order)
const sums = orderSums(lines)
const state = tableState(table)
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
// only items still unpaid stay selected (a phone may pay or cancel meanwhile)
const selected = picked.filter(id => sums.unpaidIds.includes(id))
const setSelected = setPicked
const chosen = toPay(lines, selected)
useEffect(() => {
if (gone && orderId != null) { toast.info(t('pos.table.closedElsewhere', { table: table.name })); onBack() }
}, [gone]) // eslint-disable-line react-hooks/exhaustive-deps -- once, when the order goes
const run = async (fn) => {
setBusy(true)
setError('')
try { return await fn() } catch (err) { setError(errorMessage(err, t)); return null } finally { setBusy(false) }
}
const send = () => run(async () => {
await client.post(`/api/pos/tables/${table.id}/items`, { lines: cart })
setCart([])
setLastPay(null)
toast.success(t('pos.table.sent', { table: table.name }))
onTablesChanged()
reload()
})
const close = () => run(async () => {
await client.post(`/api/pos/orders/${orderId}/close`)
toast.success(t('pos.table.closed', { table: table.name }))
onTablesChanged()
onBack()
})
const cancel = () => run(async () => {
const ids = lines.filter(l => !l.paid && selected.includes(l.id)).map(l => l.id)
await client.post(`/api/orders/${orderId}/cancel-items`, { item_ids: ids, print_cancellation: true })
setCancelling(false)
setSelected([])
toast.success(t('pos.table.cancelled', { count: ids.length }))
reload()
})
const payRows = chosen.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/${orderId}/pay`, {
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }],
cash_given: cashGiven,
})).data
const toggle = id => setSelected(sel => (sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]))
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="table-panel" data-table={table.id} data-order={orderId ?? ''}>
<div className="p-3 border-b border-line flex items-center gap-2">
<IconButton label={t('pos.table.back')} variant="secondary" onClick={onBack} data-testid="table-back"><ArrowLeft size={18} /></IconButton>
<div className="flex-1 min-w-0">
<div className="text-title font-semibold truncate">{table.name}</div>
<div className="text-caption text-ink-2 truncate">
{table.order
? `${table.order.people.join(', ')} · ${t('pos.tables.since', { time: formatTime(table.order.opened_at) })}`
: t('pos.tables.state.free')}
</div>
</div>
</div>
<div className="flex-1 overflow-y-auto">
{orderId != null && !order && <div className="p-6 flex justify-center"><Spinner /></div>}
{lastPay && cart.length === 0 && (
<div className="m-3 p-3 rounded-card bg-success-soft text-success-ink grid gap-1" data-testid="table-paid">
<div className="text-body-lg font-semibold">{t('pos.done.paid', { total: formatMoney(lastPay.total) })}</div>
{lastPay.change > 0 && <div className="text-heading font-semibold" data-testid="table-change">{t('pos.pay.change', { amount: formatMoney(lastPay.change) })}</div>}
<PaidSummary result={lastPay} />
</div>
)}
{lines.length > 0 && (
<section data-testid="order-lines">
<h3 className="px-3 pt-3 pb-1 text-label font-semibold text-ink-2 flex justify-between">
<span>{t('pos.table.onOrder')}</span><span>{formatMoney(sums.total)}</span>
</h3>
{lines.map(l => (
<OrderLine key={l.id} line={l} selected={selected.includes(l.id)} onToggle={() => toggle(l.id)} />
))}
</section>
)}
{cart.length > 0 && (
<section data-testid="new-lines">
<h3 className="px-3 pt-3 pb-1 text-label font-semibold text-accent-ink">{t('pos.table.new')}</h3>
{cart.map((line, i) => (
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
onQty={q => setCart(c => setLineQty(c, i, q))}
onDiscount={pct => setCart(c => c.map((x, j) => (j === i ? { ...x, discount_pct: pct || undefined } : x)))} />
))}
</section>
)}
{lines.length === 0 && cart.length === 0 && (orderId == null || order) && (
<EmptyState compact title={t('pos.table.empty')} description={t('pos.table.emptyBody')} />
)}
</div>
<div className="border-t border-line p-3 grid gap-2">
{(error || quote.error) && <p role="alert" className="text-label text-danger-ink">{error || t('pos.quoteFailed')}</p>}
{cart.length > 0 ? (
<>
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.table.newTotal')}</span>
<span className={`text-heading font-semibold ${quote.pending ? 'opacity-50' : ''}`} data-testid="cart-total">{formatMoney(quote.quote?.total ?? 0)}</span>
</div>
<Button size="lg" icon={<Send size={18} />} disabled={!ready} loading={busy} onClick={send} data-testid="table-send">
{t('pos.table.send', { table: table.name })}
</Button>
<Button variant="secondary" icon={<Trash2 size={16} />} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</>
) : sums.unpaid > 0 ? (
<>
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{t('pos.table.due')}</span>
<span className="text-display font-semibold" data-testid="table-due-total">{formatMoney(sums.unpaid)}</span>
</div>
<Button size="lg" icon={<Banknote size={20} />} disabled={busy} onClick={() => setPaying(payRows)} data-testid="table-pay">
{selected.length ? t('pos.table.paySelected', { amount: formatMoney(orderSums(chosen).total) }) : t('pos.table.payAll', { amount: formatMoney(sums.unpaid) })}
</Button>
<div className="grid grid-cols-2 gap-2">
<Button variant="secondary" icon={<Ban size={16} />} disabled={!selected.length || busy} onClick={() => setCancelling(true)} data-testid="table-cancel">
{t('pos.table.cancel')}
</Button>
<Button variant="secondary" icon={<Check size={16} />} disabled={busy}
onClick={() => setSelected(selected.length ? [] : sums.unpaidIds)}>
{selected.length ? t('pos.table.selectNone') : t('pos.table.selectAll')}
</Button>
</div>
</>
) : orderId != null && order && state === 'paid' ? (
<Button size="lg" icon={<Lock size={18} />} loading={busy} onClick={close} data-testid="table-close">
{t('pos.table.close', { table: table.name })}
</Button>
) : null}
</div>
{paying && (
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
onClose={() => setPaying(null)}
onPaid={result => {
setPaying(null)
setSelected([])
setLastPay(result)
toast.success(result.change > 0 ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
onTablesChanged()
if (result.auto_closed) onBack()
else reload()
}} />
)}
{cancelling && (
<Dialog open size="sm" title={t('pos.table.cancelTitle', { count: selected.length })} onClose={busy ? undefined : () => setCancelling(false)}
footer={<>
<Button variant="secondary" onClick={() => setCancelling(false)} disabled={busy}>{t('pos.table.keep')}</Button>
<Button variant="danger" icon={<Ban size={16} />} loading={busy} onClick={cancel} data-testid="cancel-confirm">{t('pos.table.cancelConfirm')}</Button>
</>}>
<div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.table.cancelBody')}</p>
<ul className="text-body text-ink grid gap-0.5">
{lines.filter(l => selected.includes(l.id)).map(l => <li key={l.id}>{qtyLabel(l.quantity, l.unitType)} {l.name}</li>)}
</ul>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)}
</aside>
)
}
function OrderLine({ line, selected, onToggle }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const body = (
<>
<span className="flex items-start gap-2">
{!line.paid && (
<span aria-hidden="true" className={`mt-0.5 size-5 shrink-0 rounded-control border-2 flex items-center justify-center
${selected ? 'bg-accent border-accent text-accent-fg' : 'border-line-strong'}`}>
{selected && <Check size={14} />}
</span>
)}
{line.paid && <CheckCircle2 size={18} className="mt-0.5 shrink-0 text-success-ink" aria-hidden="true" />}
<span className="flex-1 min-w-0">
<span className="text-body font-medium">{qtyLabel(line.quantity, line.unitType)} {line.name}</span>
{(line.options.length > 0 || line.notes) && (
<span className="block text-caption text-ink-2 truncate">{[...line.options, line.notes && `“${line.notes}”`].filter(Boolean).join(' · ')}</span>
)}
</span>
<span className="text-body text-right">
{formatMoney(line.total)}
{line.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>}
{!line.paid && line.kds === 'done' && <span className="block text-caption text-success-ink">{t('pos.table.readyItem')}</span>}
</span>
</span>
</>
)
if (line.paid) {
return <div className="px-3 py-2 border-b border-line text-ink-3" data-testid="order-line" data-item={line.id} data-paid="true">{body}</div>
}
return (
<button type="button" onClick={onToggle} aria-pressed={selected} data-testid="order-line" data-item={line.id} data-paid="false"
className={`w-full text-left px-3 py-2 border-b border-line transition-colors duration-fast ${selected ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2'}`}>
{body}
</button>
)
}
+93
View File
@@ -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 <div className="flex-1 flex items-center justify-center"><Spinner /></div>
// 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 <div className="flex-1 flex items-center justify-center p-6"><EmptyState title={t('pos.tables.none')} description={t('pos.tables.noneBody')} /></div>
}
return (
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-4" data-testid="pos-tables">
{sections.map(s => (
<section key={s.id} className="grid gap-2">
{s.name && <h2 className="text-label font-semibold text-ink-2">{s.name}</h2>}
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(11rem, 1fr))' }}>
{s.tables.map(table => <TableCard key={table.id} table={table} onPick={() => onPick(table.id)} />)}
</div>
</section>
))}
</div>
)
}
function TableCard({ table, onPick }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const state = tableState(table)
const o = table.order
return (
<button type="button" onClick={onPick} data-testid="pos-table" data-table={table.id} data-state={state}
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[state]}`}>
<span className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-title font-semibold truncate">{table.name}</span>
{table.seats ? <span className="text-label opacity-70 flex items-center gap-1"><Users size={14} aria-hidden="true" />{table.seats}</span> : null}
</span>
<span className="text-label font-medium" data-testid="table-state">
{state === 'open' ? (o.people.join(', ') || t('pos.tables.state.open')) : t(`pos.tables.state.${state}`)}
</span>
{o && (
<>
<span className="text-heading font-semibold" data-testid="table-due">
{state === 'paid' ? formatMoney(o.total) : formatMoney(o.unpaid)}
</span>
<span className="text-caption opacity-80">
{o.unpaid < o.total - 0.004 && state !== 'paid' ? `${t('pos.tables.ofTotal', { total: formatMoney(o.total) })} · ` : ''}
{t('pos.tables.since', { time: formatTime(o.opened_at) })}
</span>
{o.ready > 0 && (
<span className="self-start px-2 py-0.5 rounded-control bg-success text-success-fg text-caption font-semibold flex items-center gap-1" data-testid="table-ready">
<ChefHat size={12} aria-hidden="true" />{t('pos.tables.ready', { count: o.ready })}
</span>
)}
</>
)}
{!o && table.reservation && (
<span className="text-caption text-warning-ink flex items-center gap-1">
<CalendarClock size={12} aria-hidden="true" />
{t('pos.tables.reserved', { time: formatTime(table.reservation.reserved_for), name: table.reservation.guest_name, count: table.reservation.party_size })}
</span>
)}
{table.flags.length > 0 && (
<span className="flex flex-wrap gap-1 mt-auto pt-1">
{table.flags.map(f => (
// flag colours are the venue's own data (manager → flags), like category colours
<span key={f.id} title={f.name}
className={`px-1.5 py-0.5 rounded-control text-caption font-medium ${f.color ? 'text-accent-fg' : 'bg-surface-2 text-ink'}`}
style={{ background: f.color || undefined, color: f.text_color || undefined }}>
{f.emoji ? `${f.emoji} ` : ''}{f.name}
</span>
))}
</span>
)}
</button>
)
}
+88
View File
@@ -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]}`
}
+57 -7
View File
@@ -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 }
}
+30
View File
@@ -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')
})
+88
View File
@@ -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()