feat(terminal): counter POS screen with server-priced cart and shift gate (platform-v2 3.3a)

- Backend /api/pos (pos_counter): session (business day, the cashier's own shift,
  self-start, who can open the day), menu (sellable products with every kind of choice,
  no costs; price now from the pricing engine), quote (lines by id → the waiter's
  selected_options entries with DB prices → resolve_price as orders do; pos.line_invalid).
- POS device settings: default order type, start category, receipt printer (new ref
  sources categories / printers, also in the manager's Devices dialogs).
- Terminal apps/pos: shift gate (start shift with drawer cash), categories, search,
  product grid, price check, options dialog, cart priced by the backend.
- Tests: backend test_pos (13), terminal pos.test.mjs, manager refOptions,
  terminal.mjs +10 POS checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 21:55:30 +02:00
co-authored by Claude Opus 5.5
parent b1112b249e
commit 17bee66df1
25 changed files with 1556 additions and 21 deletions
+1
View File
@@ -66,6 +66,7 @@ CODES: dict[str, tuple[int, str]] = {
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"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."),
+9 -1
View File
@@ -14,7 +14,8 @@ Agent notes:
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
- `ref` sources: "prep_zones" (PrepZone ids), "categories" (Category ids), "printers" (active
Printer ids), "devices:<app_key>" (live devices of that app).
- `color` = "#rrggbb" (lower-cased when stored). `after="<key>"` (int fields): the value must be
greater than that field's (stored or default) value, e.g. KDS age thresholds; a stored
config that breaks the order reads back as the defaults of every ordered field (3.2a).
@@ -44,6 +45,13 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source == "categories":
from models.product import Category
return db.get(Category, value) is not None
if source == "printers":
from models.printer import Printer
p = db.get(Printer, value)
return p is not None and bool(p.is_active)
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
+1 -1
View File
@@ -70,7 +70,7 @@ class ConfigField:
choices: tuple = () # enum, or int limited to these values
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
choices_from: Optional[str] = None # ref: "prep_zones" | "categories" | "printers" | "devices:<app_key>"; value = id or None
group: Optional[str] = None # section in the manager's dialogs (3.2a)
after: Optional[str] = None # int: must be greater than this other field (age thresholds)
+16 -3
View File
@@ -1,15 +1,25 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Perm
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
# the terminal from step 3.1c.
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
# A counter screen's settings (plan step 3.3a): the order type a sale starts as, the receipt
# printer whose drawer opens on cash payments (used from 3.3b), and the category the product
# grid opens on (none = all products).
POS_CONFIG = (
ConfigField('default_order_type', 'enum', default='takeaway', choices=('takeaway', 'here')),
ConfigField('start_category_id', 'ref', default=None, choices_from='categories'),
ConfigField('receipt_printer_id', 'ref', default=None, choices_from='printers'),
AUTO_SIGN_OUT,
)
MODULE = Module(
key='pos_counter',
kind='app',
name='Counter POS',
description='A counter terminal for quick orders (coming in phase 3).',
description='A counter terminal for quick sales, tables, price checks and online orders.',
depends=('ordering',),
permissions=(
Perm('pos_counter.access', 'Use the counter POS', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
@@ -18,5 +28,8 @@ MODULE = Module(
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*'),
config=(AUTO_SIGN_OUT,)),
config=POS_CONFIG),
routers=(
Mount('routers.pos', '/api/pos'),
),
)
+160
View File
@@ -0,0 +1,160 @@
"""Counter POS (plan step 3.3a, D-26): what a paired counter screen needs, in its own scope.
GET /api/pos/session the signed-in cashier's shift and the business day (shift gate)
GET /api/pos/menu categories and products to sell, with options and today's price
POST /api/pos/quote a cart priced by the backend (services/pos_cart.py)
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
POST /quote. The menu leaves out what a cashier doesn't need (costs, fiscal fields, digital
menu overrides). Starting a shift uses POST /api/shifts/start (ordering, in the POS scope).
"""
from __future__ import annotations
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, selectinload
from core.access.check import holds
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
from services import pos_cart
router = APIRouter()
ACCESS = "pos_counter.access"
def _iso(dt):
return (dt.isoformat() + "Z") if dt is not None and dt.tzinfo is None else (dt.isoformat() if dt else None)
# ── session (shift gate) ─────────────────────────────────────────────────────
@router.get("/session")
def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""The open business day, the cashier's own open shift, whether they may start one
themselves, and who can open the day (shown when it's closed)."""
from core.access.queries import users_with_key
from models.business_day import BusinessDay
from models.settings import PosSettings
from models.shift import WaiterShift
from models.user import User
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
shift = db.query(WaiterShift).filter(WaiterShift.waiter_id == user.id, WaiterShift.ended_at.is_(None)).first() \
if isinstance(user, User) else None
row = db.get(PosSettings, "shifts.waiter_self_start")
self_start = holds(user, "core.dashboard.access") or (row is not None and row.value == "true")
openers = [u.nickname or u.full_name for u in users_with_key(db, "ordering.business_day.manage").order_by(User.full_name)
if u.role != "superadmin"]
return {
"business_day": {"id": day.id, "business_date": str(day.business_date) if day.business_date else None,
"opened_at": _iso(day.opened_at)} if day else None,
"shift": {"id": shift.id, "started_at": _iso(shift.started_at), "starting_cash": shift.starting_cash} if shift else None,
"self_start": bool(self_start),
"day_openers": openers,
}
# ── menu ────────────────────────────────────────────────────────────────────
def _subs_out(raw):
return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default"))}
for s in pos_cart._subs(raw)]
def _product_out(p, price: float) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"tags": _tags(p.tags),
"primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order,
"quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)}
for q in sorted(p.quick_options, key=lambda q: q.sort_order)],
"options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple),
"multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices)}
for o in p.options],
"prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select),
"shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None),
"choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2),
"disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices)}
for c in ps.choices]}
for ps in p.preference_sets],
"ingredients": [{"id": i.id, "name": i.name} for i in p.ingredients],
}
def _tags(raw):
import json
try:
v = json.loads(raw) if isinstance(raw, str) else (raw or [])
except ValueError:
return []
return [t for t in v if isinstance(t, str)]
@router.get("/menu")
def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""Categories and the products a cashier can sell (available, active, not service
items), each with its price right now for one unit without options (pricing engine)."""
from models.product import Category, Product, ProductPreferenceSet
from core.access.context import current_device
from core.modules import device_config
dev = current_device(request, db)
settings = device_config.effective(device_config.for_app("pos_counter"), dev.config if dev is not None else None, db)
products = (db.query(Product)
.filter(Product.is_available.is_(True), Product.lifecycle_status == "active", Product.is_service_item.is_(False))
.options(selectinload(Product.quick_options), selectinload(Product.options), selectinload(Product.ingredients),
selectinload(Product.preference_sets).selectinload(ProductPreferenceSet.choices),
selectinload(Product.memberships))
.order_by(Product.sort_order, Product.name).all())
lines = [pos_cart.Line(product=p, quantity=1) for p in products]
prices = pos_cart.price_lines(db, lines, settings["default_order_type"]) if lines else []
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
return {
"settings": settings,
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats],
"products": [_product_out(p, unit) for p, (unit, _) in zip(products, prices)],
}
# ── quote ───────────────────────────────────────────────────────────────────
class QuoteBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(default_factory=list, max_length=200)
def _adjustments(db, events) -> list[dict]:
from models.pricing import PriceModifier
out = []
for e in events:
if not e.delta_amount:
continue
m = db.get(PriceModifier, e.modifier_id) if e.modifier_id else None
out.append({"label": m.name if m is not None else e.event_type, "delta": round(e.delta_amount, 2)})
return out
@router.post("/quote")
def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(require(ACCESS))):
"""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 []
out = []
for line, (unit, events) in zip(lines, priced):
out.append({
"product_id": line.product.id, "name": line.product.name, "quantity": line.quantity,
"base_price": round(line.product.base_price, 2), "extra": line.extra,
"unit_price": round(unit, 2), "total": round(unit * line.quantity, 2),
"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)}
+189
View File
@@ -0,0 +1,189 @@
"""The counter POS's cart, priced by the backend (plan step 3.3a, D-26).
The POS never computes a price. It sends what was chosen by id (and sub-choices by name, as
they are stored), and this module turns that into the same `selected_options` entries the
waiter app sends (types quick | extra | extra_sub | pref | pref_sub) with the prices taken
from the database, then runs the pricing engine (services/pricing.py::resolve_price) exactly
as POST /api/orders/{id}/items does. 3.3b sends the same lines to create the order.
A line:
{product_id, quantity, notes?,
quick: [{id, qty?}], quick add-ons (qty only if allow_multiple)
options: [{id, qty?, subs?: [name]}], extras; one sub unless multi_select
prefs: [{set_id, choices: [{id, qty?, sub?: name}], shared?: name}],
removed: [ingredient_id]}
Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx):
- every preference set needs a choice (one, or one or more for allow_multi_select sets);
- a choice/extra with sub-choices needs one of them (the default is pre-selected on screen);
- a set's shared sub-choice applies unless the chosen choice `disables_subset`;
- quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple.
Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of
product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub |
choice_required | sub_required | unknown_ingredient | quantity.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Optional
from core.errors import XeniaError
CHANNELS = {"here": "pos", "takeaway": "takeaway"}
def _subs(raw) -> list[dict]:
if not raw:
return []
try:
data = json.loads(raw) if isinstance(raw, str) else raw
except ValueError:
return []
return [s for s in (data or []) if isinstance(s, dict) and s.get("name")]
def _shared(raw) -> Optional[dict]:
if not raw:
return None
try:
data = json.loads(raw) if isinstance(raw, str) else raw
except ValueError:
return None
return data if isinstance(data, dict) and _subs(data.get("choices")) else None
@dataclass
class Line:
"""A resolved line: what the order item will be."""
product: object
quantity: float
entries: list = field(default_factory=list) # selected_options entries
removed: list = field(default_factory=list) # ingredient names
notes: Optional[str] = None
@property
def extra(self) -> float:
return round(sum(e["price_delta"] for e in self.entries), 2)
def _bad(n: int, reason: str):
return XeniaError("pos.line_invalid", line=n, reason=reason)
def _qty(value, n: int, allowed: bool) -> int:
q = value if value is not None else 1
if isinstance(q, bool) or not isinstance(q, int) or q < 1 or (q > 1 and not allowed) or q > 99:
raise _bad(n, "quantity")
return q
def _sub(subs: list[dict], name, n: int) -> Optional[dict]:
if name is None:
return None
found = next((s for s in subs if s["name"] == name), None)
if found is None:
raise _bad(n, "unknown_sub")
return found
def resolve_line(db, raw: dict, n: int) -> Line:
from models.product import Product
product = db.get(Product, raw.get("product_id")) if isinstance(raw.get("product_id"), int) else None
if product is None or not product.is_available or product.lifecycle_status != "active":
raise _bad(n, "product_unavailable")
quantity = raw.get("quantity", 1)
if isinstance(quantity, bool) or not isinstance(quantity, (int, float)) or quantity <= 0 or quantity > 999:
raise _bad(n, "quantity")
line = Line(product=product, quantity=quantity, notes=(raw.get("notes") or "").strip() or None)
quick = {q.id: q for q in product.quick_options}
for sel in raw.get("quick") or []:
q = quick.get(sel.get("id"))
if q is None:
raise _bad(n, "unknown_quick")
qty = _qty(sel.get("qty"), n, q.allow_multiple)
line.entries.append({"id": q.id, "name": q.name if qty == 1 else f"{q.name} x{qty}",
"price_delta": round((q.price or 0.0) * qty, 2), "type": "quick"})
options = {o.id: o for o in product.options}
for sel in raw.get("options") or []:
o = options.get(sel.get("id"))
if o is None:
raise _bad(n, "unknown_option")
qty = _qty(sel.get("qty"), n, o.allow_multiple)
subs = _subs(o.sub_choices)
names = sel.get("subs") or []
if subs and not names:
raise _bad(n, "sub_required")
if len(names) > 1 and not o.multi_select:
raise _bad(n, "unknown_sub")
line.entries.append({"id": o.id, "name": o.name if qty == 1 else f"{o.name} x{qty}",
"price_delta": round((o.extra_cost or 0.0) * qty, 2), "type": "extra"})
for name in names:
s = _sub(subs, name, n)
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "extra_sub"})
chosen = {p.get("set_id"): p for p in (raw.get("prefs") or [])}
for ps in product.preference_sets:
sel = chosen.pop(ps.id, None)
picks = (sel or {}).get("choices") or []
if not picks or (len(picks) > 1 and not ps.allow_multi_select):
raise _bad(n, "choice_required")
by_id = {c.id: c for c in ps.choices}
shared = _shared(ps.shared_subset)
for pick in picks:
c = by_id.get(pick.get("id"))
if c is None:
raise _bad(n, "unknown_choice")
if ps.allow_multi_select:
qty = _qty(pick.get("qty"), n, True)
line.entries.append({"id": c.id, "name": c.name if qty == 1 else f"{c.name} x{qty}",
"price_delta": round((c.extra_cost or 0.0) * qty, 2), "type": "pref"})
continue
line.entries.append({"id": c.id, "name": c.name, "price_delta": round(c.extra_cost or 0.0, 2), "type": "pref"})
subs = _subs(c.sub_choices)
if subs:
s = _sub(subs, pick.get("sub"), n) if pick.get("sub") is not None else None
if s is None:
raise _bad(n, "sub_required")
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"})
if shared and not c.disables_subset:
s = _sub(_subs(shared.get("choices")), sel.get("shared"), n) if sel.get("shared") is not None else None
if s is None:
raise _bad(n, "sub_required")
line.entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"})
if chosen:
raise _bad(n, "unknown_choice")
ingredients = {i.id: i for i in product.ingredients}
for iid in raw.get("removed") or []:
ing = ingredients.get(iid)
if ing is None:
raise _bad(n, "unknown_ingredient")
line.removed.append(ing.name)
return line
def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | None = None):
"""[(unit_price, [PriceEvent])] for each line, with the same context POST
/api/orders/{id}/items builds: the order's existing items plus this line (the other new
lines of the same batch don't count, as there)."""
from core.timeutil import utcnow
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow()
active = build_active_price_group_ids(db, now)
channel = CHANNELS.get(order_type, "pos")
cart = list(existing_cart or [])
out = []
for line in lines:
p = line.product
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": line.quantity, "unit_price": p.base_price + line.extra}
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events))
return out
+5 -3
View File
@@ -204,9 +204,11 @@ def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
def test_module_catalogue_describes_config(client, owner_h):
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]}
assert mods["pos_counter"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None, "group": None, "after": None}]
pos = {f["key"]: f for f in mods["pos_counter"]["device_app"]["config"]}
assert pos["auto_sign_out_minutes"] == {"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None, "group": None, "after": None}
assert pos["receipt_printer_id"]["choices_from"] == "printers" and pos["start_category_id"]["choices_from"] == "categories"
kds = {f["key"]: f for f in mods["kds"]["device_app"]["config"]}
assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None,
"max": None, "choices_from": "prep_zones", "group": "zone", "after": None}
+145
View File
@@ -0,0 +1,145 @@
"""Counter POS: menu, server-priced cart, shift gate (plan step 3.3a)."""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
@pytest.fixture
def menu(db):
"""A burger with every kind of option, a coffee, an unavailable dish and a service item."""
from models.product import (Category, Product, ProductIngredient, ProductOption, ProductPreferenceChoice,
ProductPreferenceSet, ProductQuickOption)
food, drinks = Category(name="Food", sort_order=1), Category(name="Drinks", sort_order=2)
db.add_all([food, drinks])
db.flush()
burger = Product(name="Burger", base_price=10.0, primary_category_id=food.id, description="Beef, brioche",
tags=json.dumps(["spicy"]), cost_simple=3.5)
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=drinks.id)
gone = Product(name="Old dish", base_price=5.0, primary_category_id=food.id, is_available=False)
cutlery = Product(name="Cutlery", base_price=0.0, primary_category_id=food.id, is_service_item=True)
db.add_all([burger, coffee, gone, cutlery])
db.flush()
db.add(ProductQuickOption(product_id=burger.id, name="Extra cheese", price=1.0, allow_multiple=True))
db.add(ProductOption(product_id=burger.id, name="Sauce", extra_cost=0.5,
sub_choices=json.dumps([{"name": "BBQ", "extra_cost": 0.2, "is_default": True}, {"name": "Mayo"}])))
db.add(ProductIngredient(product_id=burger.id, name="Onion"))
cook = ProductPreferenceSet(product_id=burger.id, name="Cooking",
shared_subset=json.dumps({"name": "Side", "choices": [{"name": "Fries", "is_default": True},
{"name": "Salad", "extra_cost": 1.0}]}))
db.add(cook)
db.flush()
rare = ProductPreferenceChoice(set_id=cook.id, name="Rare")
well = ProductPreferenceChoice(set_id=cook.id, name="Well done", extra_cost=0.5, disables_subset=True)
db.add_all([rare, well])
db.commit()
return {"food": food, "drinks": drinks, "burger": burger, "coffee": coffee, "cook": cook, "rare": rare, "well": well,
"gone": gone, "cutlery": cutlery}
@pytest.fixture
def till(client, pair, make_user):
token, r = pair("pos_counter", "Till")
assert r.status_code == 201, r.text
cashier = make_user(role="waiter")
jwt = terminal_login(client, token, cashier)
return {"h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "cashier": cashier, "id": r.json()["id"]}
def burger_line(m, **extra):
return {"product_id": m["burger"].id, "quantity": 1,
"prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Fries"}], **extra}
def test_menu_lists_what_a_cashier_sells(client, till, menu):
data = client.get("/api/pos/menu", headers=till["h"]).json()
names = [p["name"] for p in data["products"]]
assert "Burger" in names and "Freddo" in names and "Old dish" not in names and "Cutlery" not in names
burger = next(p for p in data["products"] if p["name"] == "Burger")
assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"]
assert "cost_simple" not in burger and "cost_breakdown" not in burger
assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True}
assert burger["prefs"][0]["shared"]["name"] == "Side" and burger["prefs"][0]["choices"][1]["disables_shared"] is True
assert {c["name"] for c in data["categories"]} >= {"Food", "Drinks"}
assert data["settings"]["default_order_type"] == "takeaway"
def test_quote_prices_on_the_server(client, till, menu):
m = menu
line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}],
options=[{"id": m["burger"].options[0].id, "subs": ["BBQ"]}],
removed=[m["burger"].ingredients[0].id], notes="no salt")
r = client.post("/api/pos/quote", headers=till["h"], json={"order_type": "takeaway", "lines": [line, {"product_id": m["coffee"].id, "quantity": 2}]})
assert r.status_code == 200, r.text
burger, coffee = r.json()["lines"]
# 10 + 2×1 cheese + 0.5 sauce + 0.2 BBQ + 0 rare + 0 fries
assert burger["unit_price"] == 12.7 and burger["total"] == 12.7
assert [e["name"] for e in burger["entries"]] == ["Extra cheese x2", "Sauce", "BBQ", "Rare", "Fries"]
assert burger["removed"] == ["Onion"] and burger["notes"] == "no salt"
assert coffee["total"] == 6.0 and r.json()["total"] == 18.7
# well done has no side
r = client.post("/api/pos/quote", headers=till["h"],
json={"lines": [{"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]}]})
assert r.json()["lines"][0]["unit_price"] == 10.5
@pytest.mark.parametrize("bad,reason", [
(lambda m: {"product_id": m["burger"].id}, "choice_required"),
(lambda m: {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}]}]}, "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id}]), "sub_required"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["Ketchup"]}]), "unknown_sub"),
(lambda m: burger_line(m, options=[{"id": m["burger"].options[0].id, "subs": ["BBQ", "Mayo"]}]), "unknown_sub"),
(lambda m: burger_line(m, removed=[999999]), "unknown_ingredient"),
(lambda m: {"product_id": m["gone"].id}, "product_unavailable"),
(lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "quantity"),
])
def test_quote_refuses_what_the_waiter_dialog_refuses(client, till, menu, bad, reason):
r = client.post("/api/pos/quote", headers=till["h"], json={"lines": [bad(menu)]})
assert r.status_code == 422 and r.json()["error"]["code"] == "pos.line_invalid"
assert r.json()["error"]["params"] == {"line": 0, "reason": reason}
def test_quote_applies_price_modifiers_like_orders(client, db, till, menu):
from models.pricing import PriceModifier
db.add(PriceModifier(name="Happy hour", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1))
db.commit()
line = client.post("/api/pos/quote", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]}).json()["lines"][0]
assert line["unit_price"] == 2.7 and line["adjustments"] == [{"label": "Happy hour", "delta": -0.3}]
coffee = next(p for p in client.get("/api/pos/menu", headers=till["h"]).json()["products"] if p["name"] == "Freddo")
assert coffee["price"] == 2.7 and coffee["base_price"] == 3.0
def test_session_shift_gate(client, db, till, make_user):
from models.business_day import BusinessDay
from models.settings import PosSettings
db.query(BusinessDay).filter(BusinessDay.status == "open").update({"status": "closed"})
db.commit()
boss = make_user(role="store_manager", nickname="Eleni")
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is None and s["shift"] is None and "Eleni" in s["day_openers"]
assert client.post("/api/business-day/open", headers=till["h"], json={}).status_code in (401, 403) # not from the till
# the day opens elsewhere; self-start allowed → the cashier starts their own shift
from core.timeutil import utcnow, business_date_of
db.add(BusinessDay(status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id))
row = db.get(PosSettings, "shifts.waiter_self_start")
if row is None:
db.add(PosSettings(key="shifts.waiter_self_start", value="true"))
else:
row.value = "true"
db.commit()
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["business_day"] is not None and s["self_start"] is True and s["shift"] is None
r = client.post("/api/shifts/start", headers=till["h"], json={"starting_cash": 50})
assert r.status_code == 201, r.text
s = client.get("/api/pos/session", headers=till["h"]).json()
assert s["shift"]["starting_cash"] == 50
def test_pos_settings_validate_their_references(client, owner_h, till, menu):
ok = client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"default_order_type": "here", "start_category_id": menu["drinks"].id}})
assert ok.status_code == 200 and ok.json()["config"]["start_category_id"] == menu["drinks"].id
assert err(client.patch(f"/api/devices/{till['id']}", headers=owner_h,
json={"config": {"receipt_printer_id": 999999}})) == "validation.device_config"
assert client.get("/api/pos/menu", headers=till["h"]).json()["settings"]["default_order_type"] == "here"
@@ -9,17 +9,25 @@ import { Field, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client'
import { configGroups, configValue, refOptions } from './devicesLogic'
// Where a `ref` field's choices come from (the device list is passed in)
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers' }
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
const { t } = useTranslation('manager')
const needsZones = fields.some(f => f.choices_from === 'prep_zones')
const [zones, setZones] = useState([])
const sources = [...new Set(fields.map(f => f.choices_from).filter(s => s && REF_URLS[s]))].join(',')
const [lists, setLists] = useState({})
useEffect(() => {
if (!needsZones) return undefined
if (!sources) return undefined
let alive = true
client.get('/api/prep-zones').then(r => { if (alive) setZones(r.data) }).catch(() => {})
for (const s of sources.split(',')) {
client.get(REF_URLS[s]).then(r => { if (alive) setLists(l => ({ ...l, [s]: r.data })) }).catch(() => {})
}
return () => { alive = false }
}, [needsZones])
}, [sources])
const zones = lists.prep_zones ?? []
const categories = lists.categories ?? []
const printers = lists.printers ?? []
if (!fields.length) return null
const base = key => `modules:${appKey}.config.${key}`
@@ -45,7 +53,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
...refOptions(f, { zones, devices, selfId })]} />
...refOptions(f, { zones, categories, printers, devices, selfId })]} />
</Field>
)
}
@@ -85,9 +85,11 @@ export function configGroups(fields = []) {
return out
}
/** Options of a `ref` field: prep zones, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], devices = [], selfId = null } = {}) {
/** Options of a `ref` field: prep zones, categories, printers, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], categories = [], printers = [], devices = [], selfId = null } = {}) {
if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name }))
if (field.choices_from === 'categories') return categories.map(c => ({ value: String(c.id), label: c.name }))
if (field.choices_from === 'printers') return printers.filter(p => p.is_active !== false).map(p => ({ value: String(p.id), label: p.name }))
if (field.choices_from?.startsWith('devices:')) {
const app = field.choices_from.slice('devices:'.length)
return devices.filter(d => !d.revoked_at && d.app_key === app && d.id !== selfId).map(d => ({ value: String(d.id), label: d.name }))
@@ -144,3 +144,9 @@ test('config fields in sections, in the order their groups first appear (3.2a)',
[['zone', ['zone']], ['board', ['w', 's']], ['age', ['c']], [null, ['auto']]])
assert.equal(configValue({ type: 'color' }, '#aabbcc'), '#aabbcc')
})
test('refOptions: categories and active printers (3.3a)', () => {
assert.deepEqual(refOptions({ choices_from: 'categories' }, { categories: [{ id: 3, name: 'Drinks' }] }), [{ value: '3', label: 'Drinks' }])
assert.deepEqual(refOptions({ choices_from: 'printers' }, { printers: [{ id: 1, name: 'Bar', is_active: true }, { id: 2, name: 'Old', is_active: false }] }),
[{ value: '1', label: 'Bar' }])
})
+3
View File
@@ -77,5 +77,8 @@
"item_not_found": "Το είδος {{item_id}} δεν βρέθηκε σε αυτή την παραγγελία.",
"item_claimed": "Ο/Η {{name}} ασχολείται ήδη με αυτό το είδος.",
"claim_needs_staff": "Μόνο μέλος του προσωπικού μπορεί να αναλάβει ένα είδος."
},
"pos": {
"line_invalid": "Η γραμμή {{line}} του καλαθιού δεν μπορεί να πουληθεί όπως επιλέχθηκε ({{reason}})."
}
}
+19 -1
View File
@@ -295,7 +295,7 @@
},
"pos_counter": {
"name": "Ταμείο πάγκου",
"description": "Τερματικό στον πάγκο για γρήγορες παραγγελίες (έρχεται σύντομα).",
"description": "Τερματικό πάγκου για γρήγορες πωλήσεις, τραπέζια, έλεγχο τιμών και online παραγγελίες.",
"limits": {
"devices": "Τερματικά πάγκου"
},
@@ -303,6 +303,24 @@
"access": "Χρήση του ταμείου πάγκου"
},
"config": {
"default_order_type": {
"label": "Οι νέες πωλήσεις ξεκινούν ως",
"hint": "Πακέτο ή για εδώ στον πάγκο (χωρίς τραπέζι).",
"choices": {
"takeaway": "Πακέτο",
"here": "Για εδώ (χωρίς τραπέζι)"
}
},
"start_category_id": {
"label": "Κατηγορία που εμφανίζεται πρώτη",
"hint": "Τα προϊόντα με τα οποία ανοίγει η οθόνη.",
"none": "Όλα τα προϊόντα"
},
"receipt_printer_id": {
"label": "Εκτυπωτής αποδείξεων (συρτάρι)",
"hint": "Το συρτάρι του ανοίγει στις πληρωμές με μετρητά.",
"none": "Κανένας εκτυπωτής"
},
"auto_sign_out_minutes": {
"label": "Αποσύνδεση μετά από",
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
+44
View File
@@ -161,5 +161,49 @@
"taken_by_me": "Το ανέλαβες",
"released": "Το άφησες"
}
},
"pos": {
"allProducts": "Όλα τα προϊόντα",
"search": "Αναζήτηση προϊόντων",
"clearSearch": "Καθαρισμός αναζήτησης",
"noResults": "Τίποτα για «{{query}}»",
"noProducts": "Δεν υπάρχουν προϊόντα εδώ",
"orderType": "Τύπος παραγγελίας",
"type": {
"takeaway": "Πακέτο",
"here": "Για εδώ"
},
"cartEmpty": "Το καλάθι είναι άδειο",
"cartEmptyBody": "Πατήστε ένα προϊόν για να το προσθέσετε. Το κουμπί (i) δείχνει την τιμή του χωρίς να το προσθέσει.",
"total": "Σύνολο",
"clearCart": "Άδειασμα καλαθιού",
"quoteFailed": "Δεν ήταν δυνατή η τιμολόγηση του καλαθιού. Ελέγξτε τις επιλογές και δοκιμάστε ξανά.",
"checkPrice": "Τιμή και στοιχεία: {{name}}",
"less": "Ένα λιγότερο",
"more": "Ένα ακόμη",
"each": "{{price}} το ένα",
"dialog": {
"close": "Κλείσιμο",
"add": "Στο καλάθι",
"pickOne": "επιλέξτε ένα",
"quick": "Προσθήκες",
"extras": "Έξτρα",
"without": "Χωρίς",
"note": "Σημείωση για την κουζίνα",
"quantity": "Ποσότητα",
"missing": "Μένει να επιλέξετε: {{list}}"
},
"gate": {
"dayClosed": "Η ημέρα εργασίας δεν έχει ανοίξει",
"dayOpeners": "Ζητήστε από κάποιον που μπορεί να την ανοίξει: {{names}}.",
"dayOpenersNone": "Κανείς εδώ δεν μπορεί ακόμη να την ανοίξει· ρυθμίστε το στη διαχείριση.",
"noShift": "Δεν έχετε ανοιχτή βάρδια",
"askManager": "Ζητήστε από έναν διαχειριστή να ξεκινήσει τη βάρδιά σας και δοκιμάστε ξανά.",
"startTitle": "Έναρξη βάρδιας",
"startBody": "Τα μετρητά που εισπράττετε σε αυτόν τον πάγκο πάνε στη βάρδιά σας.",
"startingCash": "Μετρητά στο συρτάρι τώρα",
"badAmount": "Γράψτε ένα ποσό, π.χ. 50 ή 50,00",
"start": "Έναρξη βάρδιας"
}
}
}
+3
View File
@@ -77,5 +77,8 @@
"item_not_found": "Item {{item_id}} not found on this order.",
"item_claimed": "{{name}} is already on this item.",
"claim_needs_staff": "Only a staff member can claim an item."
},
"pos": {
"line_invalid": "Cart line {{line}} can't be sold as chosen ({{reason}})."
}
}
+19 -1
View File
@@ -295,7 +295,7 @@
},
"pos_counter": {
"name": "Counter POS",
"description": "A counter terminal for quick orders (coming soon).",
"description": "A counter terminal for quick sales, tables, price checks and online orders.",
"limits": {
"devices": "Counter terminals"
},
@@ -303,6 +303,24 @@
"access": "Use the counter POS"
},
"config": {
"default_order_type": {
"label": "New sales start as",
"hint": "Takeaway or eat in at the counter (no table).",
"choices": {
"takeaway": "Takeaway",
"here": "Eat in (no table)"
}
},
"start_category_id": {
"label": "Category shown first",
"hint": "The products the screen opens on.",
"none": "All products"
},
"receipt_printer_id": {
"label": "Receipt printer (cash drawer)",
"hint": "Its cash drawer opens on cash payments.",
"none": "No printer"
},
"auto_sign_out_minutes": {
"label": "Sign out after",
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
+44
View File
@@ -161,5 +161,49 @@
"taken_by_me": "You're on it",
"released": "Let go"
}
},
"pos": {
"allProducts": "All products",
"search": "Search products",
"clearSearch": "Clear the search",
"noResults": "Nothing matches “{{query}}”",
"noProducts": "No products here",
"orderType": "Order type",
"type": {
"takeaway": "Takeaway",
"here": "Eat in"
},
"cartEmpty": "The cart is empty",
"cartEmptyBody": "Tap a product to add it. The (i) button shows its price without adding it.",
"total": "Total",
"clearCart": "Clear the cart",
"quoteFailed": "Couldn't price the cart. Check the choices and try again.",
"checkPrice": "Price and details of {{name}}",
"less": "One less",
"more": "One more",
"each": "{{price}} each",
"dialog": {
"close": "Close",
"add": "Add to cart",
"pickOne": "choose one",
"quick": "Add-ons",
"extras": "Extras",
"without": "Without",
"note": "Note for the kitchen",
"quantity": "Quantity",
"missing": "Still to choose: {{list}}"
},
"gate": {
"dayClosed": "The business day isn't open",
"dayOpeners": "Ask someone who can open it: {{names}}.",
"dayOpenersNone": "Nobody here can open it yet; set it up in the manager.",
"noShift": "You don't have a shift running",
"askManager": "Ask a manager to start your shift, then try again.",
"startTitle": "Start your shift",
"startBody": "The cash you take at this counter goes to your shift.",
"startingCash": "Cash in the drawer now",
"badAmount": "Enter an amount, e.g. 50 or 50,00",
"start": "Start shift"
}
}
}
+13 -3
View File
@@ -1,6 +1,16 @@
// Placeholder until step 3.3 builds this app (plan phase 3). Lazily loaded (apps/registry.js).
import AppPlaceholder from '../AppPlaceholder'
// The counter POS on a paired screen (plan phase 3.3, D-26). 3.3a: the shift gate, then the
// sale screen (categories, product grid, search, price check, a cart priced by the backend).
// Payment (3.3b), tables (3.3c) and online orders (3.3d) follow. Look: the shared tokens and
// components in the screen's theme.
import PosScreen from './PosScreen'
import ShiftGate from './ShiftGate'
export default function PosApp() {
return <AppPlaceholder appKey="pos_counter" />
return (
<div className="absolute inset-0" data-testid="app-pos_counter">
<ShiftGate>
<PosScreen />
</ShiftGate>
</div>
)
}
+175
View File
@@ -0,0 +1,175 @@
// 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. Paying comes in 3.3b.
import { useMemo, useState } from 'react'
import { Info, Minus, Plus, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import {
addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
} from './logic/cart'
import ProductDialog from './ProductDialog'
import { useMenu, useQuote } from './usePos'
export default function PosScreen() {
const { t } = useTranslation('terminal')
const { menu } = useMenu()
if (!menu) return <div className="absolute inset-0 flex items-center justify-center bg-canvas"><Spinner /></div>
return <Counter menu={menu} key={menu.settings.start_category_id ?? 'all'} t={t} />
}
function Counter({ menu, t }) {
const { formatMoney } = useFormat()
const { language } = useLanguage()
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 [dialog, setDialog] = useState(null) // product
const quote = useQuote(cart, orderType)
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 tap = product => {
if (needsChoices(product)) { setDialog(product); return }
const unit = unitOf(product)
setCart(c => addLine(c, toLine(product, defaultSelection(product), unit ? unit.start : 1)))
}
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>
{/* products */}
<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">
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} />
</div>
{query && <IconButton label={t('pos.clearSearch')} onClick={() => setQuery('')}><X size={18} /></IconButton>}
</div>
<div className="flex-1 overflow-y-auto p-3">
{shown.length === 0 ? (
<EmptyState title={query ? t('pos.noResults', { query }) : t('pos.noProducts')} />
) : (
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid="pos-grid">
{shown.map(p => <ProductCard key={p.id} product={p} onTap={() => tap(p)} onInfo={() => setDialog(p)} />)}
</div>
)}
</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
? <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)}
onQty={q => setCart(c => setLineQty(c, i, q))} />
))}
</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 variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
</div>
</aside>
{dialog && (
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
)}
</div>
)
}
function CategoryButton({ active, colour, onClick, children, testId }) {
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>
</button>
)
}
function ProductCard({ product, onTap, onInfo }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
return (
<div className="relative bg-surface border border-line rounded-card shadow-raised overflow-hidden flex flex-col" data-testid="pos-product" data-product={product.id}>
<button type="button" onClick={onTap} className="flex-1 flex flex-col text-left active:scale-[0.98] transition-transform duration-fast">
{product.image_url
? <img src={product.image_url} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-2" />
: <span className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-heading text-ink-3" aria-hidden="true">{product.name.slice(0, 1)}</span>}
<span className="p-2 grid gap-0.5">
<span className="text-body font-medium text-ink line-clamp-2">{product.name}</span>
<span className="text-label text-ink-2">{formatMoney(product.price)}{unit ? ` / ${unit.label}` : ''}</span>
</span>
</button>
<IconButton label={t('pos.checkPrice', { name: product.name })} size="sm" variant="secondary" onClick={onInfo}
className="absolute top-1.5 right-1.5" data-testid="product-info">
<Info size={16} />
</IconButton>
</div>
)
}
function CartLine({ line, priced, product, onQty }) {
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>}
</div>
</div>
)
}
+191
View File
@@ -0,0 +1,191 @@
// A product on the counter POS (plan step 3.3a): price check and choices in one dialog.
// "Check price" opens it from the product's info button without adding anything; a product
// with preferences to pick opens it on tap. The price shown is the backend's (the menu price,
// then POST /api/pos/quote for what's chosen), never added up here.
import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Stepper } from '@xenia/ui'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
} from './logic/cart'
import { useQuote } from './usePos'
const chip = on => `min-h-[var(--x-control-md)] px-3 rounded-control border-2 text-body text-left flex items-center gap-2 transition-colors duration-fast
${on ? 'border-accent bg-accent-soft text-accent-ink font-medium' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`
function Section({ title, hint, children }) {
return (
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink-2 uppercase tracking-wide">{title}{hint && <span className="ml-2 normal-case font-normal text-warning-ink">{hint}</span>}</h3>
<div className="flex flex-wrap gap-2">{children}</div>
</section>
)
}
function Price({ value }) {
const { formatMoney } = useFormat()
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
}
export default function ProductDialog({ product, orderType, onAdd, onClose }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
const [sel, setSel] = useState(() => defaultSelection(product))
const [qty, setQty] = useState(unit ? unit.start : 1)
const missing = missingChoices(product, sel)
const line = useMemo(() => toLine(product, sel, qty), [product, sel, qty])
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType)
const priced = quote?.lines?.[0]
const add = () => { onAdd(line); onClose() }
return (
<Dialog open onClose={onClose} size="lg" title={product.name} description={product.description || undefined}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('pos.dialog.close')}</Button>
<Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add">
{t('pos.dialog.add')}{priced && !pending ? ` · ${formatMoney(priced.total)}` : ''}
</Button>
</>}>
<div className="grid gap-5" data-testid="product-dialog" data-product={product.id}>
<div className="flex gap-4 items-start">
{product.image_url && <img src={product.image_url} alt="" className="size-28 rounded-card object-cover shrink-0 bg-surface-2" />}
<div className="grid gap-1">
<div className="text-display font-semibold text-ink" data-testid="dialog-price">
{formatMoney(priced ? priced.unit_price : product.price)}
{unit && <span className="text-body text-ink-2"> / {unit.label}</span>}
</div>
{product.price !== product.base_price && !priced && (
<div className="text-label text-ink-3 line-through">{formatMoney(product.base_price)}</div>
)}
{priced?.adjustments?.map(a => (
<div key={a.label} className="text-label text-success-ink">{a.label} {a.delta > 0 ? '+' : ''}{formatMoney(a.delta)}</div>
))}
{product.tags?.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{product.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-full bg-surface-2 text-caption text-ink-2">{tag}</span>)}
</div>
)}
</div>
</div>
{product.prefs.map(ps => {
const picked = sel.prefs[ps.id]?.choices ?? []
const one = !ps.multi && picked[0] ? ps.choices.find(c => c.id === picked[0].id) : null
const need = missing.find(m => m.kind === 'pref' && m.name === ps.name)
return (
<div key={ps.id} className="grid gap-3" data-pref={ps.id}>
<Section title={ps.name} hint={need ? t('pos.dialog.pickOne') : null}>
{ps.choices.map(c => {
const p = picked.find(x => x.id === c.id)
return (
<span key={c.id} className="flex items-center gap-1">
<button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}>
{c.name} <Price value={c.price} />
</button>
{ps.multi && p && (
<Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} />
)}
</span>
)
})}
</Section>
{one?.subs?.length > 0 && (
<Section title={one.name}>
{one.subs.map(s => (
<button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
{ps.shared && one && !one.disables_shared && (
<Section title={ps.shared.name}>
{ps.shared.subs.map(s => (
<button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
</div>
)
})}
{product.quick.length > 0 && (
<Section title={t('pos.dialog.quick')}>
{product.quick.map(q => {
const n = sel.quick[q.id] ?? 0
return (
<span key={q.id} className="flex items-center gap-1">
<button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}>
{q.name} <Price value={q.price} />
</button>
{q.allow_multiple && n > 0 && (
<Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={q.name} />
)}
</span>
)
})}
</Section>
)}
{product.options.length > 0 && (
<Section title={t('pos.dialog.extras')}>
{product.options.map(o => {
const s = sel.options[o.id]
return (
<span key={o.id} className="grid gap-2">
<span className="flex items-center gap-1">
<button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}>
{o.name} <Price value={o.price} />
</button>
{o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={o.name} />}
</span>
{s && o.subs.length > 0 && (
<span className="flex flex-wrap gap-1 pl-3">
{o.subs.map(sub => (
<button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}>
{sub.name} <Price value={sub.price} />
</button>
))}
</span>
)}
</span>
)
})}
</Section>
)}
{product.ingredients.length > 0 && (
<Section title={t('pos.dialog.without')}>
{product.ingredients.map(i => (
<button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}>
{sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{i.name}
</button>
))}
</Section>
)}
<div className="grid sm:grid-cols-[1fr_auto] gap-3 items-end">
<label className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.note')}
<Input value={sel.notes} onChange={e => setSel(s => ({ ...s, notes: e.target.value }))} maxLength={200} />
</label>
<div className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.quantity')}
<Stepper value={qty} min={unit ? unit.step : 1} max={unit ? 999 : 99} step={unit ? unit.step : 1}
format={v => (unit ? `${Number(v).toFixed(unit.step < 1 ? 1 : 0)} ${unit.label}` : String(v))}
onChange={v => setQty(Math.round(v * 1000) / 1000)} label={t('pos.dialog.quantity')} data-testid="dialog-qty" />
</div>
</div>
{missing.length > 0 && (
<p className="text-label text-warning-ink" data-testid="dialog-missing">{t('pos.dialog.missing', { list: missing.map(m => m.name).join(', ') })}</p>
)}
</div>
</Dialog>
)
}
+89
View File
@@ -0,0 +1,89 @@
// Before selling (plan step 3.3a, D-26): the business day must be open, and the cash goes to
// the cashier's own shift. Shows who can open the day when it's closed; starts the cashier's
// shift (with the cash in the drawer) when they may start it themselves, else says to ask a
// manager. Follows live shift/day changes.
import { useState } from 'react'
import { CalendarX2, Clock, Play } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, Input, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { usePosSession } from './usePos'
export default function ShiftGate({ children }) {
const { t } = useTranslation('terminal')
const { session, error, reload } = usePosSession()
if (!session) {
return (
<Centered>
{error ? <EmptyState title={errorMessage(error, t)} action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} /> : <Spinner />}
</Centered>
)
}
if (!session.business_day) {
return (
<Centered testId="pos-day-closed">
<EmptyState icon={<CalendarX2 size={40} />} title={t('pos.gate.dayClosed')}
description={session.day_openers.length
? t('pos.gate.dayOpeners', { names: session.day_openers.join(', ') })
: t('pos.gate.dayOpenersNone')}
action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} />
</Centered>
)
}
if (!session.shift) {
return session.self_start
? <StartShift onStarted={reload} />
: (
<Centered testId="pos-shift-needed">
<EmptyState icon={<Clock size={40} />} title={t('pos.gate.noShift')} description={t('pos.gate.askManager')}
action={<Button variant="secondary" onClick={reload}>{t('common:actions.retry')}</Button>} />
</Centered>
)
}
return children
}
function StartShift({ onStarted }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const [cash, setCash] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const amount = cash.trim() === '' ? 0 : parseNumber(cash, { decimals: 2, allowNegative: false })
const valid = Number.isFinite(amount) && amount >= 0
const start = async e => {
e.preventDefault()
if (!valid || busy) return
setBusy(true)
setError('')
try {
await client.post('/api/shifts/start', { starting_cash: amount })
onStarted()
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(false)
}
}
return (
<Centered testId="pos-start-shift">
<form onSubmit={start} className="bg-surface border border-line rounded-card shadow-raised p-6 grid gap-4 w-full max-w-sm">
<div className="grid gap-1">
<h1 className="text-title font-semibold text-ink">{t('pos.gate.startTitle')}</h1>
<p className="text-label text-ink-2">{t('pos.gate.startBody')}</p>
</div>
<Field label={t('pos.gate.startingCash')} hint={valid && amount > 0 ? formatMoney(amount) : undefined} error={!valid ? t('pos.gate.badAmount') : undefined}>
<Input inputMode="decimal" value={cash} onChange={e => setCash(e.target.value)} placeholder="0" autoFocus data-testid="starting-cash" />
</Field>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<Button type="submit" size="lg" icon={<Play size={18} />} loading={busy} disabled={!valid}>{t('pos.gate.start')}</Button>
</form>
</Centered>
)
}
function Centered({ children, testId }) {
return <div className="absolute inset-0 flex items-center justify-center p-6 bg-canvas" data-testid={testId}>{children}</div>
}
+189
View File
@@ -0,0 +1,189 @@
// The counter POS's menu and cart, without prices (plan step 3.3a). Prices always come from
// the backend: the menu's `price` and POST /api/pos/quote (services/pos_cart.py). This file
// only knows what was chosen; the rules for a complete choice mirror the backend's, so the
// screen can say what's missing before asking. Pure: unit-tested in Node (tests/pos.test.mjs).
// ── menu ────────────────────────────────────────────────────────────────────
/** Lower case, accents and Greek tonos removed: "Φρέντο" matches "φρεντο". */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
/** Products in a category (a product listed in several shows in each), in that category's
* order; categoryId null = all products (each once). */
export function productsIn(products, categoryId) {
if (categoryId == null) return products
const pos = p => p.categories.find(c => c.category_id === categoryId)
return products.filter(pos).sort((a, b) => pos(a).sort_order - pos(b).sort_order || a.name.localeCompare(b.name))
}
/** Search by name (any word order, accents ignored), each product once whatever its
* categories. */
export function searchProducts(products, query) {
const words = fold(query).split(/\s+/).filter(Boolean)
if (!words.length) return []
return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) })
}
/** Categories that have products, in their order (top level first, then by sort order). */
export function categoriesWithProducts(categories, products) {
const used = new Set(products.flatMap(p => p.categories.map(c => c.category_id)))
return categories.filter(c => used.has(c.id))
}
// ── one product's choices ───────────────────────────────────────────────────
const defaultSub = subs => (subs?.length ? (subs.find(s => s.is_default) ?? subs[0]).name : null)
/** The choices a product starts with: default preference choices (+ their default subs and
* the set's default shared sub), nothing else. */
export function defaultSelection(product) {
const prefs = {}
for (const ps of product.prefs ?? []) {
const def = ps.choices.find(c => c.id === ps.default_choice_id)
prefs[ps.id] = def
? { choices: [{ id: def.id, qty: 1, sub: ps.multi ? null : defaultSub(def.subs) }], shared: ps.shared && !def.disables_shared ? defaultSub(ps.shared.subs) : null }
: { choices: [], shared: null }
}
return { quick: {}, options: {}, prefs, removed: [], notes: '' }
}
/** Does the product need the options dialog (a preference to pick)? Otherwise a tap adds it. */
export function needsChoices(product) {
return (product.prefs ?? []).length > 0
}
/** What's still missing: [{ kind: 'pref' | 'sub' | 'option_sub', name }] (empty = complete). */
export function missingChoices(product, sel) {
const out = []
for (const ps of product.prefs ?? []) {
const picked = sel.prefs[ps.id]?.choices ?? []
if (!picked.length) { out.push({ kind: 'pref', name: ps.name }); continue }
if (ps.multi) continue
const c = ps.choices.find(x => x.id === picked[0].id)
if (c?.subs?.length && !picked[0].sub) out.push({ kind: 'sub', name: c.name })
if (ps.shared && c && !c.disables_shared && !sel.prefs[ps.id]?.shared) out.push({ kind: 'sub', name: ps.shared.name })
}
for (const o of product.options ?? []) {
const s = sel.options[o.id]
if (s && o.subs?.length && !(s.subs?.length)) out.push({ kind: 'option_sub', name: o.name })
}
return out
}
/** Pick a single-choice preference (its default sub and the set's shared sub come with it). */
export function pickChoice(product, sel, setId, choiceId) {
const ps = product.prefs.find(p => p.id === setId)
const c = ps.choices.find(x => x.id === choiceId)
const prev = sel.prefs[setId] ?? { choices: [], shared: null }
if (ps.multi) {
const has = prev.choices.some(x => x.id === choiceId)
const choices = has ? prev.choices.filter(x => x.id !== choiceId) : [...prev.choices, { id: choiceId, qty: 1, sub: null }]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices } } }
}
const shared = ps.shared && !c.disables_shared ? (prev.shared ?? defaultSub(ps.shared.subs)) : null
return { ...sel, prefs: { ...sel.prefs, [setId]: { choices: [{ id: choiceId, qty: 1, sub: defaultSub(c.subs) }], shared } } }
}
export function setChoiceQty(sel, setId, choiceId, qty) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map(x => (x.id === choiceId ? { ...x, qty: Math.max(1, qty) } : x)) } } }
}
export function pickChoiceSub(sel, setId, sub) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map((x, i) => (i === 0 ? { ...x, sub } : x)) } } }
}
export function pickShared(sel, setId, shared) {
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...sel.prefs[setId], shared } } }
}
/** Toggle an extra (with its default sub). */
export function toggleOption(product, sel, optionId) {
const options = { ...sel.options }
if (options[optionId]) delete options[optionId]
else {
const o = product.options.find(x => x.id === optionId)
const sub = defaultSub(o.subs)
options[optionId] = { qty: 1, subs: sub ? [sub] : [] }
}
return { ...sel, options }
}
export function pickOptionSub(product, sel, optionId, name) {
const o = product.options.find(x => x.id === optionId)
const cur = sel.options[optionId]?.subs ?? []
const subs = o.multi_select ? (cur.includes(name) ? cur.filter(n => n !== name) : [...cur, name]) : [name]
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], subs } } }
}
export function setOptionQty(sel, optionId, qty) {
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], qty: Math.max(1, qty) } } }
}
/** Quick add-ons: qty 0 removes it. */
export function setQuick(sel, quickId, qty) {
const quick = { ...sel.quick }
if (qty > 0) quick[quickId] = qty
else delete quick[quickId]
return { ...sel, quick }
}
export function toggleRemoved(sel, ingredientId) {
const removed = sel.removed.includes(ingredientId) ? sel.removed.filter(i => i !== ingredientId) : [...sel.removed, ingredientId]
return { ...sel, removed }
}
/** The cart line POST /api/pos/quote (and 3.3b's sale) takes. */
export function toLine(product, sel, quantity) {
const line = { product_id: product.id, quantity }
const quick = Object.entries(sel.quick).map(([id, qty]) => ({ id: Number(id), qty }))
const options = Object.entries(sel.options).map(([id, o]) => ({ id: Number(id), qty: o.qty, subs: o.subs }))
const prefs = Object.entries(sel.prefs).filter(([, p]) => p.choices.length)
.map(([id, p]) => ({ set_id: Number(id), choices: p.choices.map(c => ({ id: c.id, qty: c.qty, sub: c.sub })), shared: p.shared }))
if (quick.length) line.quick = quick
if (options.length) line.options = options
if (prefs.length) line.prefs = prefs
if (sel.removed.length) line.removed = [...sel.removed]
if (sel.notes?.trim()) line.notes = sel.notes.trim()
return line
}
// ── the cart ────────────────────────────────────────────────────────────────
/** Two lines are the same sale when everything but the quantity is the same. */
export function lineKey(line) {
const { quantity, ...rest } = line // eslint-disable-line no-unused-vars
return stable(rest)
}
const stable = v => (Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object' ? `{${Object.keys(v).sort().map(k => `${k}:${stable(v[k])}`).join(',')}}`
: JSON.stringify(v))
/** Add a line; the same product with the same choices adds to its quantity. */
export function addLine(cart, line) {
const key = lineKey(line)
const i = cart.findIndex(l => lineKey(l) === key)
if (i < 0) return [...cart, line]
return cart.map((l, j) => (j === i ? { ...l, quantity: round(l.quantity + line.quantity) } : l))
}
export function setLineQty(cart, index, quantity) {
if (quantity <= 0) return cart.filter((_, i) => i !== index)
return cart.map((l, i) => (i === index ? { ...l, quantity: round(quantity) } : l))
}
const round = n => Math.round(n * 1000) / 1000
// Weighed products (kg, L, g, mL): step and starting amount (the waiter app's)
export const UNITS = {
kg: { step: 0.1, start: 0.5, label: 'kg' },
liter: { step: 0.1, start: 0.5, label: 'L' },
gram: { step: 10, start: 100, label: 'g' },
ml: { step: 5, start: 100, label: 'mL' },
}
export const unitOf = product => UNITS[product.unit_type] ?? null
+64
View File
@@ -0,0 +1,64 @@
// 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.
import { useCallback, useEffect, useRef, useState } from 'react'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
const quiet = { xenia: { noOverride: true } }
const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours)
const QUOTE_DELAY_MS = 120
/** GET /api/pos/session: { business_day, shift, self_start, day_openers } (null while loading). */
export function usePosSession() {
const [session, setSession] = useState(null)
const [error, setError] = useState(null)
const load = useCallback(async () => {
try {
setSession((await client.get('/api/pos/session', quiet)).data)
setError(null)
} catch (err) { setError(err) }
}, [])
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(['shift_changed', 'business_day_changed'], load)
return { session, error, reload: load }
}
/** GET /api/pos/menu: { settings, categories, products } (null while loading). */
export function useMenu() {
const [menu, setMenu] = useState(null)
const load = useCallback(async () => {
try { setMenu((await client.get('/api/pos/menu', quiet)).data) } catch { /* the shell shows offline */ }
}, [])
useEffect(() => { load() }, [load])
useEffect(() => {
const id = setInterval(load, MENU_REFRESH_MS)
return () => clearInterval(id)
}, [load])
useLiveEvent('ready', load)
useLiveEvents(['products_changed', 'device.updated'], load)
return { menu, reload: load }
}
/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins).
* → { quote, pending, error } */
export function useQuote(lines, orderType) {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
const key = JSON.stringify([lines, orderType])
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)
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
return state
}
+89
View File
@@ -0,0 +1,89 @@
// The counter POS's menu and cart logic (plan step 3.3a). No prices here: they come from the
// backend; this checks what's chosen and how the cart groups it.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
addLine, categoriesWithProducts, defaultSelection, fold, lineKey, missingChoices, needsChoices, pickChoice, pickChoiceSub,
pickOptionSub, pickShared, productsIn, searchProducts, setLineQty, setQuick, toLine, toggleOption, toggleRemoved,
} from '../src/apps/pos/logic/cart.js'
const burger = {
id: 1, name: 'Burger', categories: [{ category_id: 10, sort_order: 2 }, { category_id: 20, sort_order: 0 }],
quick: [{ id: 5, name: 'Cheese', allow_multiple: true }],
options: [{ id: 7, name: 'Sauce', multi_select: false, subs: [{ name: 'BBQ', is_default: true }, { name: 'Mayo' }] },
{ id: 8, name: 'Toppings', multi_select: true, subs: [{ name: 'Egg' }, { name: 'Bacon' }] }],
prefs: [{ id: 3, name: 'Cooking', multi: false, default_choice_id: null,
shared: { name: 'Side', subs: [{ name: 'Fries', is_default: true }, { name: 'Salad' }] },
choices: [{ id: 30, name: 'Rare', subs: [] }, { id: 31, name: 'Well done', disables_shared: true, subs: [] },
{ id: 32, name: 'Medium', subs: [{ name: 'pink' }, { name: 'not pink', is_default: true }] }] }],
ingredients: [{ id: 9, name: 'Onion' }],
}
const coffee = { id: 2, name: 'Φρέντο Εσπρέσο', categories: [{ category_id: 20, sort_order: 1 }], quick: [], options: [], prefs: [], ingredients: [] }
test('search ignores accents, case and word order; finds a product once', () => {
assert.equal(fold('Φρέντο'), 'φρεντο')
assert.deepEqual(searchProducts([burger, coffee], 'εσπρεσο φρεντ').map(p => p.id), [2])
assert.deepEqual(searchProducts([burger, coffee], 'bur').map(p => p.id), [1])
assert.deepEqual(searchProducts([burger, coffee], ' '), [])
})
test('categories: a product listed in several shows in each, in that category\'s order', () => {
assert.deepEqual(productsIn([burger, coffee], 20).map(p => p.id), [1, 2])
assert.deepEqual(productsIn([burger, coffee], 10).map(p => p.id), [1])
assert.equal(productsIn([burger, coffee], null).length, 2)
assert.deepEqual(categoriesWithProducts([{ id: 10 }, { id: 20 }, { id: 30 }], [burger, coffee]).map(c => c.id), [10, 20])
})
test('choices: a preference must be picked; subs and shared subs come with their defaults', () => {
assert.equal(needsChoices(burger), true)
assert.equal(needsChoices(coffee), false)
let sel = defaultSelection(burger)
assert.deepEqual(missingChoices(burger, sel), [{ kind: 'pref', name: 'Cooking' }])
sel = pickChoice(burger, sel, 3, 30)
assert.deepEqual(sel.prefs[3], { choices: [{ id: 30, qty: 1, sub: null }], shared: 'Fries' })
assert.deepEqual(missingChoices(burger, sel), [])
sel = pickShared(sel, 3, 'Salad')
sel = pickChoice(burger, sel, 3, 31) // well done: no side
assert.equal(sel.prefs[3].shared, null)
sel = pickChoice(burger, sel, 3, 32) // medium: its default sub, side comes back
assert.deepEqual(sel.prefs[3], { choices: [{ id: 32, qty: 1, sub: 'not pink' }], shared: 'Fries' })
sel = pickChoiceSub(sel, 3, 'pink')
assert.equal(sel.prefs[3].choices[0].sub, 'pink')
})
test('extras, add-ons, without, note → the line the backend prices', () => {
let sel = pickChoice(burger, defaultSelection(burger), 3, 30)
sel = toggleOption(burger, sel, 7) // Sauce with BBQ
sel = pickOptionSub(burger, sel, 7, 'Mayo') // single: replaces
sel = toggleOption(burger, sel, 8) // the first sub comes pre-selected (as on the waiter app)
assert.deepEqual(sel.options[8].subs, ['Egg'])
sel = pickOptionSub(burger, sel, 8, 'Egg') // multi: tapping it again takes it off…
assert.deepEqual(missingChoices(burger, sel), [{ kind: 'option_sub', name: 'Toppings' }])
sel = pickOptionSub(burger, sel, 8, 'Egg')
sel = pickOptionSub(burger, sel, 8, 'Bacon') // …and adds the others
sel = setQuick(sel, 5, 2)
sel = toggleRemoved(sel, 9)
sel = { ...sel, notes: ' no salt ' }
assert.deepEqual(toLine(burger, sel, 1), {
product_id: 1, quantity: 1, quick: [{ id: 5, qty: 2 }],
options: [{ id: 7, qty: 1, subs: ['Mayo'] }, { id: 8, qty: 1, subs: ['Egg', 'Bacon'] }],
prefs: [{ set_id: 3, choices: [{ id: 30, qty: 1, sub: null }], shared: 'Fries' }],
removed: [9], notes: 'no salt',
})
assert.deepEqual(toLine(coffee, defaultSelection(coffee), 2), { product_id: 2, quantity: 2 })
assert.deepEqual(setQuick(sel, 5, 0).quick, {})
})
test('cart: the same choices add up, different choices are separate lines; 0 removes', () => {
const a = { product_id: 2, quantity: 1 }
const b = { product_id: 1, quantity: 1, prefs: [{ set_id: 3, choices: [{ id: 30, qty: 1, sub: null }], shared: 'Fries' }] }
const c = { product_id: 1, quantity: 1, prefs: [{ set_id: 3, choices: [{ id: 31, qty: 1, sub: null }], shared: null }] }
let cart = addLine(addLine(addLine([], a), b), a)
assert.deepEqual(cart.map(l => [l.product_id, l.quantity]), [[2, 2], [1, 1]])
cart = addLine(cart, c)
assert.equal(cart.length, 3)
assert.equal(lineKey({ ...b, quantity: 5 }), lineKey(b))
assert.notEqual(lineKey(b), lineKey(c))
assert.deepEqual(setLineQty(cart, 0, 0).map(l => l.product_id), [1, 1])
assert.equal(setLineQty(cart, 0, 0.30000000000000004)[0].quantity, 0.3)
})
+64
View File
@@ -301,6 +301,70 @@ try {
r.check('moved to Counter POS → signed out, sign-in for the POS',
await page.getByTestId('sign-in-screen').count() === 1 && (await page.getByTestId('sign-in-screen').textContent()).includes('Kitchen'))
// ── 3.3a: the counter POS ────────────────────────────────────────────────
const cats = await api('GET', '/api/products/categories', { token: boss })
const burgerP = await api('POST', '/api/products/', { token: boss, body: {
name: 'E2E Burger', base_price: 10, primary_category_id: cats[0].id, category_ids: [cats[0].id],
preference_sets: [{ name: 'Cooking', choices: [{ name: 'Rare' }, { name: 'Well done', extra_cost: 0.5 }] }],
options: [{ name: 'Sauce', extra_cost: 0.5, sub_choices: [{ name: 'BBQ', extra_cost: 0.2, is_default: true }, { name: 'Mayo' }] }],
quick_options: [{ name: 'Cheese', price: 1, allow_multiple: true }],
ingredients: [{ name: 'Onion' }],
} })
const posMenu = await api('GET', '/api/pos/menu', { token: boss })
const simple = posMenu.products.find(p => !p.prefs.length && p.id !== burgerP.id && p.categories.every(c => c.category_id !== cats[0].id))
await page.locator(`[data-user="${mgr.id}"]`).click()
await page.getByLabel('Password').fill('password')
await page.getByRole('button', { name: 'Sign in' }).click()
r.check('3.3a: the cashier is asked to start their shift (business day open, no shift yet)', await shown(page, 'pos-start-shift', 10_000))
await page.getByTestId('starting-cash').fill('20')
await page.getByRole('button', { name: 'Start shift' }).click()
r.check('3.3a: shift started → the sale screen', await shown(page, 'pos-screen', 10_000))
const posSession = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/session')).data)
r.check('3.3a: the shift is the cashier\'s own, with the starting cash', posSession.shift?.starting_cash === 20, JSON.stringify(posSession.shift))
await page.getByTestId('pos-search').fill('burg e2e')
const burgerCard = page.locator(`[data-testid="pos-product"][data-product="${burgerP.id}"]`)
r.check('3.3a: search finds the product by name (words in any order)', await burgerCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& await page.locator('[data-testid="pos-product"]').count() === 1)
await burgerCard.getByTestId('product-info').click()
r.check('3.3a: price check shows the price without adding it', await shown(page, 'product-dialog', 5000)
&& (await page.getByTestId('dialog-price').textContent()).includes('10.00') && await page.getByTestId('cart-line').count() === 0)
await page.keyboard.press('Escape')
await burgerCard.locator('button').first().click()
await page.getByTestId('product-dialog').waitFor({ timeout: 5000 })
r.check('3.3a: a product with a preference opens its choices; Add waits for the choice',
await page.getByTestId('dialog-add').isDisabled() && await page.getByTestId('dialog-missing').count() === 1)
const set = burgerP.preference_sets[0]
await page.locator(`[data-choice="${set.choices[1].id}"]`).click()
await page.locator(`[data-option="${burgerP.options[0].id}"]`).click()
await page.locator(`[data-quick="${burgerP.quick_options[0].id}"]`).click()
await page.locator(`[data-ingredient="${burgerP.ingredients[0].id}"]`).click()
// 10 + 0.50 well done + 0.50 sauce + 0.20 BBQ + 1 cheese, priced by the backend
await page.waitForFunction(() => document.querySelector('[data-testid="dialog-add"]')?.textContent.includes('12.20'), null, { timeout: 5000 }).catch(() => {})
r.check('3.3a: the price follows the choices (priced by the backend: 12.20)', (await page.getByTestId('dialog-add').textContent()).includes('12.20'),
await page.getByTestId('dialog-add').textContent())
await page.getByTestId('dialog-add').click()
await page.waitForFunction(() => document.querySelector('[data-testid="cart-total"]')?.textContent.includes('12.20'), null, { timeout: 5000 }).catch(() => {})
const line1 = page.getByTestId('cart-line').first()
r.check('3.3a: the cart has the line with its choices and the total', await page.getByTestId('cart-line').count() === 1
&& (await line1.textContent()).includes('Well done') && (await line1.textContent()).includes('Onion')
&& (await page.getByTestId('cart-total').textContent()).includes('12.20'))
await page.getByTestId('pos-search').fill('')
const simpleCat = simple.categories[0].category_id
await page.getByTestId(`category-${simpleCat}`).click()
const simpleCard = page.locator(`[data-testid="pos-product"][data-product="${simple.id}"]`)
r.check('3.3a: a category shows its products', await simpleCard.isVisible() && await burgerCard.count() === 0)
await simpleCard.locator('button').first().click()
await simpleCard.locator('button').first().click()
const expected = (12.2 + 2 * simple.price).toFixed(2)
await page.waitForFunction(x => document.querySelector('[data-testid="cart-total"]')?.textContent.includes(x), expected, { timeout: 5000 }).catch(() => {})
r.check('3.3a: a product without choices is added by a tap; the same one twice adds up', await page.getByTestId('cart-line').count() === 2
&& (await page.getByTestId('line-qty').nth(1).textContent()).includes('2') && (await page.getByTestId('cart-total').textContent()).includes(expected),
`${await page.getByTestId('cart-total').textContent()} vs ${expected}`)
await page.screenshot({ path: path.join(OUT, 'terminal-pos.png') })
await page.getByRole('button', { name: 'Sign out' }).click()
// ── a customer display: no sign-in ───────────────────────────────────────
const cd = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 } })).newPage())
await pairFromManager(cd, boss, { app_key: 'customer_display', name: 'Counter display' })