diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index f435bf0..b883cc9 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), diff --git a/local_backend/core/modules/device_config.py b/local_backend/core/modules/device_config.py index 2762bfe..50c3cf5 100644 --- a/local_backend/core/modules/device_config.py +++ b/local_backend/core/modules/device_config.py @@ -14,7 +14,8 @@ Agent notes: field needs its label in packages/i18n/locales/{en,el}/modules.json (`.config..label`, plus `.choices.` per choice); test_module_texts fails otherwise. The manager renders the fields generically (DeviceConfigFields.jsx). -- `ref` sources: "prep_zones" (PrepZone ids), "devices:" (live devices of that app). +- `ref` sources: "prep_zones" (PrepZone ids), "categories" (Category ids), "printers" (active + Printer ids), "devices:" (live devices of that app). - `color` = "#rrggbb" (lower-cased when stored). `after=""` (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) diff --git a/local_backend/core/modules/model.py b/local_backend/core/modules/model.py index 9117421..992ce71 100644 --- a/local_backend/core/modules/model.py +++ b/local_backend/core/modules/model.py @@ -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:"; value = id or None + choices_from: Optional[str] = None # ref: "prep_zones" | "categories" | "printers" | "devices:"; 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) diff --git a/local_backend/modules/pos_counter/manifest.py b/local_backend/modules/pos_counter/manifest.py index ad21662..8a4d0d9 100644 --- a/local_backend/modules/pos_counter/manifest.py +++ b/local_backend/modules/pos_counter/manifest.py @@ -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'), + ), ) diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py new file mode 100644 index 0000000..6bebac8 --- /dev/null +++ b/local_backend/routers/pos.py @@ -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)} diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py new file mode 100644 index 0000000..1a22f75 --- /dev/null +++ b/local_backend/services/pos_cart.py @@ -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 diff --git a/local_backend/tests/test_live.py b/local_backend/tests/test_live.py index ac9ed64..ba32b2e 100644 --- a/local_backend/tests/test_live.py +++ b/local_backend/tests/test_live.py @@ -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} diff --git a/local_backend/tests/test_pos.py b/local_backend/tests/test_pos.py new file mode 100644 index 0000000..d358f72 --- /dev/null +++ b/local_backend/tests/test_pos.py @@ -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" diff --git a/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx b/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx index bc1bb15..87c7def 100644 --- a/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx +++ b/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx @@ -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 setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} /> + + {query && setQuery('')}>} + +
+ {shown.length === 0 ? ( + + ) : ( +
+ {shown.map(p => tap(p)} onInfo={() => setDialog(p)} />)} +
+ )} +
+ + + {/* cart */} + + + {dialog && ( + setDialog(null)} + onAdd={line => setCart(c => addLine(c, line))} /> + )} + + ) +} + +function CategoryButton({ active, colour, onClick, children, testId }) { + return ( + + ) +} + +function ProductCard({ product, onTap, onInfo }) { + const { t } = useTranslation('terminal') + const { formatMoney } = useFormat() + const unit = unitOf(product) + return ( +
+ + + + +
+ ) +} + +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 ( +
+
+ {product?.name ?? priced?.name} + {priced ? formatMoney(priced.total) : '…'} +
+ {priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && ( +
+ {priced.entries.map((e, i) => + {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''})} + {priced.removed.map(n => − {n})} + {priced.notes && “{priced.notes}”} +
+ )} +
+ onQty(line.quantity - step)}> + {qtyText} + onQty(line.quantity + step)}> + {priced && line.quantity !== 1 && {t('pos.each', { price: formatMoney(priced.unit_price) })}} +
+
+ ) +} diff --git a/terminal/src/apps/pos/ProductDialog.jsx b/terminal/src/apps/pos/ProductDialog.jsx new file mode 100644 index 0000000..7e9b08f --- /dev/null +++ b/terminal/src/apps/pos/ProductDialog.jsx @@ -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 ( +
+

{title}{hint && {hint}}

+
{children}
+
+ ) +} + +function Price({ value }) { + const { formatMoney } = useFormat() + return value ? {value > 0 ? '+' : ''}{formatMoney(value)} : 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 ( + + + + }> +
+
+ {product.image_url && } +
+
+ {formatMoney(priced ? priced.unit_price : product.price)} + {unit && / {unit.label}} +
+ {product.price !== product.base_price && !priced && ( +
{formatMoney(product.base_price)}
+ )} + {priced?.adjustments?.map(a => ( +
{a.label} {a.delta > 0 ? '+' : ''}{formatMoney(a.delta)}
+ ))} + {product.tags?.length > 0 && ( +
+ {product.tags.map(tag => {tag})} +
+ )} +
+
+ + {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 ( +
+
+ {ps.choices.map(c => { + const p = picked.find(x => x.id === c.id) + return ( + + + {ps.multi && p && ( + setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} /> + )} + + ) + })} +
+ {one?.subs?.length > 0 && ( +
+ {one.subs.map(s => ( + + ))} +
+ )} + {ps.shared && one && !one.disables_shared && ( +
+ {ps.shared.subs.map(s => ( + + ))} +
+ )} +
+ ) + })} + + {product.quick.length > 0 && ( +
+ {product.quick.map(q => { + const n = sel.quick[q.id] ?? 0 + return ( + + + {q.allow_multiple && n > 0 && ( + setSel(s => setQuick(s, q.id, v))} label={q.name} /> + )} + + ) + })} +
+ )} + + {product.options.length > 0 && ( +
+ {product.options.map(o => { + const s = sel.options[o.id] + return ( + + + + {o.allow_multiple && s && setSel(x => setOptionQty(x, o.id, v))} label={o.name} />} + + {s && o.subs.length > 0 && ( + + {o.subs.map(sub => ( + + ))} + + )} + + ) + })} +
+ )} + + {product.ingredients.length > 0 && ( +
+ {product.ingredients.map(i => ( + + ))} +
+ )} + +
+ +
+ {t('pos.dialog.quantity')} + (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" /> +
+
+ {missing.length > 0 && ( +

{t('pos.dialog.missing', { list: missing.map(m => m.name).join(', ') })}

+ )} +
+
+ ) +} diff --git a/terminal/src/apps/pos/ShiftGate.jsx b/terminal/src/apps/pos/ShiftGate.jsx new file mode 100644 index 0000000..8580007 --- /dev/null +++ b/terminal/src/apps/pos/ShiftGate.jsx @@ -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 ( + + {error ? {t('common:actions.retry')}} /> : } + + ) + } + if (!session.business_day) { + return ( + + } title={t('pos.gate.dayClosed')} + description={session.day_openers.length + ? t('pos.gate.dayOpeners', { names: session.day_openers.join(', ') }) + : t('pos.gate.dayOpenersNone')} + action={} /> + + ) + } + if (!session.shift) { + return session.self_start + ? + : ( + + } title={t('pos.gate.noShift')} description={t('pos.gate.askManager')} + action={} /> + + ) + } + 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 ( + +
+
+

{t('pos.gate.startTitle')}

+

{t('pos.gate.startBody')}

+
+ 0 ? formatMoney(amount) : undefined} error={!valid ? t('pos.gate.badAmount') : undefined}> + setCash(e.target.value)} placeholder="0" autoFocus data-testid="starting-cash" /> + + {error &&

{error}

} + +
+
+ ) +} + +function Centered({ children, testId }) { + return
{children}
+} diff --git a/terminal/src/apps/pos/logic/cart.js b/terminal/src/apps/pos/logic/cart.js new file mode 100644 index 0000000..3511d50 --- /dev/null +++ b/terminal/src/apps/pos/logic/cart.js @@ -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 diff --git a/terminal/src/apps/pos/usePos.js b/terminal/src/apps/pos/usePos.js new file mode 100644 index 0000000..0e6c254 --- /dev/null +++ b/terminal/src/apps/pos/usePos.js @@ -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 +} diff --git a/terminal/tests/pos.test.mjs b/terminal/tests/pos.test.mjs new file mode 100644 index 0000000..9274cde --- /dev/null +++ b/terminal/tests/pos.test.mjs @@ -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) +}) diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 4e577ed..4ef7471 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -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' })