diff --git a/docs/README.md b/docs/README.md index 5c7336c..cd72a79 100644 --- a/docs/README.md +++ b/docs/README.md @@ -176,6 +176,8 @@ Routers are mounted from the module manifests (`local_backend/modules//mani **CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17). Use `core.access.deps.require("..")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. A role's defaults are the manifests' plus the venue's changes (`role_permissions`, Settings → Operation → "What each role may do"): create users with `apply_role_template(user, db)`, and a **new key added to a role later must be granted to existing users of that role in its Alembic revision** (keys are copied at creation; see 0024). In endpoints a waiter can reach, check keys with `authorize(request, db, user, key)` (module, device scope, key, manager approval → `access.denied` / `access.override_possible`); the apps read `permissions` and `approvable` from bootstrap (`useAllowed(key)` → `yes` / `approve` / `no`), never a venue switch for what a person may do. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys). + +**Apps never send a price (step 4.4).** Order lines go by id (`services/pos_cart.py`'s line: product, quick add-ons, extras with sub-choices, preferences, removed ingredients) to `POST /api/orders/{id}/items` (the waiter, the manager's ordering tab) or the counter's `/api/pos/*`; the server prices them through `orders.add_priced_items`, the one function that writes order items with prices. A line carrying prices or `selected_options` is refused (`order.line.client_price`), so is the shape before 4.4 (`items` → `order.lines_required`); a by-hand change (`price_adjustment`) needs `ordering.prices.modify` or a manager's approval. Totals before sending come from `POST /api/orders/quote` (the counter: `/api/pos/quote`), the same code; offline an app may show its menu's prices only as an estimate. Apps whose cart keeps the stored `selected_options` shape build lines with `@xenia/api` `wireLine` / `lineFromOptions` (an option no longer on the menu throws `LineError`, never dropped). A preference set left out of a line takes its default, and a set at its free default isn't stored (tickets show only what differs). Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: ` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `.*`) and only reach routes of those modules. A new device app with user logins must declare `.access`. Per-device settings are `ConfigField`s in `DeviceApp.config` (validated by `core/modules/device_config.py`, rendered by the manager's `DeviceConfigFields`), each with texts `modules:.config..label` (+ `.choices.`), never free JSON. Device-only endpoints use `require_device("")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header. Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent). diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 1c17a02..232e2e1 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -75,6 +75,13 @@ CODES: dict[str, tuple[int, str]] = { "pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."), "pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."), "order.not_sold_here": (422, "{name} isn't sold for this kind of order."), + "order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."), + "order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."), + "order.line.option_gone": (422, "{name}: a chosen option doesn't exist any more (line {line}). Remove it and add it again."), + "order.line.choice_missing": (422, "{name}: a required choice is missing (line {line})."), + "order.line.quantity": (422, "{name}: that quantity isn't allowed (line {line})."), + "order.line.price": (422, "{name}: that price change isn't allowed (line {line})."), + "order.line.client_price": (422, "{name}: the app sent its own prices, but prices come from the server (line {line}). Update the app."), "fees.area_not_found": (404, "Delivery area {area_id} not found."), "fees.rule_not_found": (404, "Fee rule {rule_id} not found."), "fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."), diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index 7d07c05..379a85b 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -29,7 +29,7 @@ from services.pricing import ( build_active_price_group_ids, write_price_events, check_waiter_discount_limits, discounts_enabled, _system_round, ) -from pydantic import BaseModel +from pydantic import BaseModel, Field class PrintOrderRequest(BaseModel): printer_id: int @@ -476,13 +476,149 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De return order +# ── lines priced by the server (plan step 4.4) ───────────────────────────────── + +# what an app may not send: prices, and the stored shape that carried them +_CLIENT_PRICE_KEYS = {"selected_options", "removed_ingredients", "unit_price", "price_delta", "extra_cost", "price"} +# pos_cart's reasons → the code the app shows (texts in errors.json, order.line.*) +_LINE_CODES = { + "product_unavailable": "order.line.product_unavailable", + "unknown_quick": "order.line.option_gone", "unknown_option": "order.line.option_gone", + "unknown_choice": "order.line.option_gone", "unknown_sub": "order.line.option_gone", + "unknown_ingredient": "order.line.option_gone", + "choice_required": "order.line.choice_missing", "sub_required": "order.line.choice_missing", + "quantity": "order.line.quantity", "discount": "order.line.price", "price": "order.line.price", + "client_price": "order.line.client_price", "not_sold_here": "order.not_sold_here", +} + + +class AddLinesRequest(BaseModel): + """POST /api/orders/{id}/items: what was chosen, by id (services/pos_cart.py's line, + plus `course_id`, `price_adjustment` (a by-hand change per unit: needs + ordering.prices.modify or a manager's approval) and `is_service_item`).""" + lines: Optional[List[dict]] = Field(default=None, max_length=200) + items: Optional[list] = None # the shape before 4.4: refused (order.lines_required) + order_note: Optional[str] = None + customer_count: Optional[int] = None + + +class QuoteRequest(BaseModel): + lines: List[dict] = Field(default_factory=list, max_length=200) + order_id: Optional[int] = None # adding to an order: its items count, its sales point + order_type: str = "here" # a new order: here | takeaway | delivery + + +def _product_name(db, raw) -> str: + pid = raw.get("product_id") if isinstance(raw, dict) else None + p = db.get(Product, pid) if isinstance(pid, int) and not isinstance(pid, bool) else None + return p.name if p is not None else f"#{pid}" + + +def _resolve_lines(db, raws: list, point: str | None = None) -> tuple[list, list]: + """Each raw line → (pos_cart.Line, its by-hand price change per unit). A refusal names the + product and the line (1-based): order.line.* / order.not_sold_here (checked first, at the + order's sales point).""" + from core.sales_points import is_sold_at + from services import pos_cart + lines, manual = [], [] + for n, raw in enumerate(raws): + raw = raw if isinstance(raw, dict) else {} + pid = raw.get("product_id") + product = db.get(Product, pid) if isinstance(pid, int) and not isinstance(pid, bool) else None + if point is not None and product is not None and product.lifecycle_status == "active" and not is_sold_at(product, point): + raise XeniaError("order.not_sold_here", name=product.name, line=n + 1) + try: + if _CLIENT_PRICE_KEYS & raw.keys(): + raise pos_cart._bad(n, "client_price") + adj = raw.get("price_adjustment") or 0.0 + if isinstance(adj, bool) or not isinstance(adj, (int, float)) or not -10000 <= adj <= 10000: + raise pos_cart._bad(n, "price") + course = raw.get("course_id") + if course is not None and (isinstance(course, bool) or not isinstance(course, int)): + raise pos_cart._bad(n, "unknown_option") + lines.append(pos_cart.resolve_line(db, raw, n)) + manual.append(round(float(adj), 2)) + except XeniaError as e: + if e.code != "pos.line_invalid": + raise + reason = e.params.get("reason") + raise XeniaError(_LINE_CODES.get(reason, "order.line.option_gone"), line=n + 1, + name=_product_name(db, raw), reason=reason) from None + return lines, manual + + +@router.post("/quote") +def quote_lines(body: QuoteRequest, db: Session = Depends(get_db), user: User = Depends(get_current_user)): + """Lines priced exactly as POST /api/orders/{id}/items will price them (the cart's total + before sending, 4.4): into an existing order (its items count for deals, its sales point) + or a new one of `order_type`.""" + from core.sales_points import for_order, of_order + from services import pos_cart + order_type = body.order_type if body.order_type in ("here", "takeaway", "delivery") else "here" + existing, point = None, for_order(order_type) + if body.order_id is not None: + order = db.get(Order, body.order_id) + if order is None: + raise XeniaError("order.not_found", order_id=body.order_id) + if not _can_access_order(order, user, db): + raise HTTPException(status_code=403, detail="Access denied") + existing, order_type, point = pos_cart.order_cart(order), order.order_type or "here", of_order(order) + lines, manual = _resolve_lines(db, body.lines, point) + try: + return pos_cart.quote(db, lines, order_type, existing, point=point, manual=manual) + except XeniaError as e: + if e.code != "pos.line_invalid": + raise + n = e.params.get("line", 0) + raise XeniaError("order.not_sold_here", name=lines[n].product.name if n < len(lines) else "?") from None + + @router.post("/{order_id}/items", response_model=AddItemsResponse) -def add_items( - order_id: int, - body: AddItemsRequest, - db: Session = Depends(get_db), - user: User = Depends(get_current_user), -): +def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Session = Depends(get_db), + user: User = Depends(get_current_user)): + """Add lines to an order; the server prices them (4.4). Apps send what was chosen by id, + never a price: prices or `selected_options` in a line → order.line.client_price, the + shape before 4.4 (`items`) → order.lines_required. A by-hand price change or a discount + needs ordering.prices.modify or a manager's approval (audited).""" + from core.sales_points import of_order + from schemas.order import OrderItemInput, SelectedOptionInput + from services import pos_cart + if body.items is not None or not body.lines: + raise XeniaError("order.lines_required") + order = db.query(Order).filter(Order.id == order_id).first() + if not order: + raise XeniaError("order.not_found", order_id=order_id) + if not _can_access_order(order, user, db): + raise HTTPException(status_code=403, detail="Access denied") + lines, manual = _resolve_lines(db, body.lines, of_order(order)) + approval = None + if any(manual) or any(line.discount_pct for line in lines): + approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items") + discounts = [0.0] * len(lines) + if any(line.discount_pct for line in lines): + priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order)) + discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] + items = [] + for raw, line, hand, disc in zip(body.lines, lines, manual, discounts): + adj = round(hand + disc, 2) + items.append(OrderItemInput( + product_id=line.product.id, quantity=line.quantity, + selected_options=[SelectedOptionInput(**e) for e in line.entries] or None, + removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, + is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"), + )) + result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note, + customer_count=body.customer_count), db, user) + if approval is not None: + _audit(db, order_id, "PRICE_SET_BY_HAND", waiter_id=user.id, note=_approval_note(approval)) + db.commit() + return result + + +def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: User): + """Add items whose options carry the database's prices, built by services/pos_cart.py + from an app's lines (POST /api/orders/{id}/items above, the counter's routers/pos.py). + Never called with what an app sent as is.""" order = db.query(Order).filter(Order.id == order_id).first() if not order: raise XeniaError("order.not_found", order_id=order_id) diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 90a66c3..f2d8285 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -156,17 +156,6 @@ class QuoteBody(BaseModel): order_id: Optional[int] = None # adding to a table's order: its items count for deals (3.3c) -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, @@ -176,19 +165,7 @@ def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(requi if body.order_id is not None: order = _order_for(db, user, body.order_id) order_type, existing = order.order_type or "here", pos_cart.order_cart(order) - priced = pos_cart.price_lines(db, lines, order_type, existing) if lines else [] - out = [] - for line, (unit, events) in zip(lines, priced): - adj = pos_cart.discount_adjustment(unit, line.discount_pct) - 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, - "discount_pct": line.discount_pct, "discount": adj, - "unit_price": round(unit + adj, 2), "total": round((unit + adj) * 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": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)} + return pos_cart.quote(db, lines, order_type, existing) @@ -240,7 +217,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us _check_cash(body.cash_given, cash_due) order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) - added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) + added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()] paid, fiscal = [], None for method, idx in groups: @@ -288,8 +265,8 @@ def _check_cash(cash_given, cash_due): def _items_in(lines, adjs): - """Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options - entries with the database's prices; a discount as the item's price_adjustment).""" + """Resolved lines as orders.add_priced_items takes them (selected_options entries with the + database's prices; a discount as the item's price_adjustment).""" from schemas.order import OrderItemInput, SelectedOptionInput return [OrderItemInput( product_id=line.product.id, quantity=line.quantity, @@ -435,7 +412,7 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)] if order is None: order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user) - added = orders_api.add_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) + added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user) return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])} diff --git a/local_backend/services/pos_cart.py b/local_backend/services/pos_cart.py index 4d4dcb9..f47f7dd 100644 --- a/local_backend/services/pos_cart.py +++ b/local_backend/services/pos_cart.py @@ -1,23 +1,29 @@ -"""The counter POS's cart, priced by the backend (plan step 3.3a, D-26). +"""Order lines priced by the backend: the counter POS (plan step 3.3a, D-26) and, since +step 4.4, the waiter app (POST /api/orders/{id}/items takes these lines). -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. +No app 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 `selected_options` entries an order +item stores (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) through +routers/orders.py::add_priced_items. 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 + options: [{id, qty?, subs?: [name]}], extras; one sub unless multi_select; the + same extra may be listed more than once 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); +Rules (the same as the waiter's options drawer, waiter_pwa OrderDrawer.jsx): +- every preference set needs a choice (one, or one or more for allow_multi_select sets); a set + left out of the line takes its default choice (with the default sub-choices) when it has one; +- a set at its default (default choice, default sub-choices) that costs nothing is not stored: + the ticket shows only what differs from the usual (the waiter app always worked that way); - 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. +- quantities: per-choice qty only on multi-select sets, per-add-on qty only on allow_multiple; + an extra's sub-choice is charged once per extra (qty 2 of "sauce: ketchup" = 2 × both). 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 | discount | not_sold_here @@ -97,6 +103,28 @@ def _sub(subs: list[dict], name, n: int) -> Optional[dict]: return found +def _default_sub(subs: list[dict]) -> Optional[str]: + """The sub-choice selected to start with: the one marked default, else the first.""" + return next((s for s in subs if s.get("is_default")), subs[0])["name"] if subs else None + + +def _usual_pick(choice, shared) -> dict: + """A preference set at its default: the default choice, its default sub-choice and the + set's default shared sub-choice.""" + return {"choices": [{"id": choice.id, "qty": 1, "sub": _default_sub(_subs(choice.sub_choices))}], + "shared": _default_sub(_subs(shared.get("choices"))) if shared and not choice.disables_subset else None} + + +def _same_pick(sel: dict, usual: dict, multi: bool) -> bool: + picks = sel.get("choices") or [] + if len(picks) != 1 or not isinstance(picks[0], dict): + return False + p, u = picks[0], usual["choices"][0] + if p.get("id") != u["id"] or (p.get("qty") or 1) != 1: + return False + return multi or (p.get("sub") == u["sub"] and (usual["shared"] is None or sel.get("shared") == usual["shared"])) + + 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 @@ -136,40 +164,48 @@ def resolve_line(db, raw: dict, n: int) -> Line: "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"}) + line.entries.append({"id": None, "name": s["name"] if qty == 1 else f"{s['name']} x{qty}", + "price_delta": round(float(s.get("extra_cost") or 0.0) * qty, 2), "type": "extra_sub"}) - chosen = {p.get("set_id"): p for p in (raw.get("prefs") or [])} + chosen = {p.get("set_id"): p for p in (raw.get("prefs") or []) if isinstance(p, dict)} for ps in product.preference_sets: + by_id = {c.id: c for c in ps.choices} + shared = _shared(ps.shared_subset) + default = by_id.get(ps.default_choice_id) + usual = _usual_pick(default, shared) if default is not None else None sel = chosen.pop(ps.id, None) + if sel is None and usual is not None: + sel = usual # left out: the set's default (4.4) 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) + entries = [] for pick in picks: - c = by_id.get(pick.get("id")) + c = by_id.get(pick.get("id")) if isinstance(pick, dict) else None 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"}) + 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"}) + 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"}) + 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"}) + entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2), + "type": "pref_sub"}) + at_default = usual is not None and _same_pick(sel, usual, ps.allow_multi_select) + if not (at_default and not any(e["price_delta"] for e in entries)): + line.entries.extend(entries) if chosen: raise _bad(n, "unknown_choice") @@ -242,3 +278,40 @@ def discount_adjustment(unit_price: float, pct) -> float: """A line's discount (percent of its unit price) as the order item's price_adjustment (negative, rounded to cents).""" return -round(unit_price * pct / 100.0, 2) if pct else 0.0 + + +def adjustments(db, events) -> list[dict]: + """A line's price-engine adjustments (happy hour, price groups) as {label, delta}.""" + 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 + + +def quote(db, lines: list[Line], order_type: str, existing_cart: list | None = None, point: str | None = None, + manual: list | None = None) -> dict: + """The lines priced exactly as the order will be: per line the unit price (base + options, + then price groups/modifiers, then a discount or a by-hand price change), its total, what + was chosen (names) and any adjustment. `manual`: each line's by-hand change per unit (the + waiter's price change, 4.4).""" + priced = price_lines(db, lines, order_type, existing_cart, point) if lines else [] + out = [] + for i, (line, (unit, events)) in enumerate(zip(lines, priced)): + adj = discount_adjustment(unit, line.discount_pct) + hand = round(float((manual or [])[i] or 0.0), 2) if manual and i < len(manual) else 0.0 + row = { + "product_id": line.product.id, "name": line.product.name, "quantity": line.quantity, + "base_price": round(line.product.base_price, 2), "extra": line.extra, + "discount_pct": line.discount_pct, "discount": adj, + "unit_price": round(unit + adj + hand, 2), "total": round((unit + adj + hand) * 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), + } + if manual is not None: + row["price_adjustment"] = hand + out.append(row) + return {"order_type": order_type, "lines": out, "total": round(sum(x["total"] for x in out), 2)} diff --git a/local_backend/tests/test_online_site_side.py b/local_backend/tests/test_online_site_side.py index a11304c..d399804 100644 --- a/local_backend/tests/test_online_site_side.py +++ b/local_backend/tests/test_online_site_side.py @@ -65,7 +65,7 @@ def test_the_fee_is_its_own_line_and_never_reaches_the_kitchen(client, db, count assert product.id not in [p["id"] for p in client.get("/api/pos/menu", headers=counter["h"]).json()["products"]] assert client.put(f"/api/products/{product.id}", headers=owner_h, json={"name": "x"}).status_code == 404 assert err(client.post(f"/api/orders/{oid}/items", headers=owner_h, - json={"items": [{"product_id": product.id, "quantity": 1}]})) == "order.not_sold_here" + json={"lines": [{"product_id": product.id, "quantity": 1}]})) == "order.line.product_unavailable" # the board: the time, the area, the fee o = board(client, counter)["incoming"][0] assert (o["requested_for"], o["area"], o["fee"], o["total"], o["price_diff"]) == ("2026-11-16T19:30:00+00:00", "Centre", 2.5, 27.5, None) diff --git a/local_backend/tests/test_order_lines.py b/local_backend/tests/test_order_lines.py new file mode 100644 index 0000000..3929a71 --- /dev/null +++ b/local_backend/tests/test_order_lines.py @@ -0,0 +1,186 @@ +"""Orders priced by the server (plan step 4.4). + +The waiter app sends what was chosen by id (services/pos_cart.py's line) to POST +/api/orders/{id}/items, exactly like the counter; the server prices it. Prices from an app +are refused, a by-hand price change needs ordering.prices.modify or a manager's PIN, and the +cart's total before sending comes from POST /api/orders/quote. +""" +import json + +import pytest + +from conftest import TEST_PIN +from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures) +from tests.test_pos import burger_line, drawer_printer, menu, on_shift, till # noqa: F401 (fixtures) +from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures) + + +@pytest.fixture(autouse=True) +def _no_printing(monkeypatch): + import routers.orders as orders + monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: []) + + +@pytest.fixture +def full(db, menu): + """The test menu's burger plus: a 'Bread' set with a default (the usual costs nothing), a + 'Size' set whose default costs 1.00, and an extra that can be taken more than once.""" + from models.product import ProductOption, ProductPreferenceChoice, ProductPreferenceSet + b = menu["burger"] + bread = ProductPreferenceSet(product_id=b.id, name="Bread") + size = ProductPreferenceSet(product_id=b.id, name="Size") + db.add_all([bread, size]) + db.flush() + brioche = ProductPreferenceChoice(set_id=bread.id, name="Brioche", + sub_choices=json.dumps([{"name": "Toasted", "is_default": True}, {"name": "Soft"}])) + rye = ProductPreferenceChoice(set_id=bread.id, name="Rye", extra_cost=0.3) + double = ProductPreferenceChoice(set_id=size.id, name="Double", extra_cost=1.0) + single = ProductPreferenceChoice(set_id=size.id, name="Single") + db.add_all([brioche, rye, double, single]) + db.flush() + bread.default_choice_id, size.default_choice_id = brioche.id, double.id + pickles = ProductOption(product_id=b.id, name="Pickles", extra_cost=0.4, allow_multiple=True, + sub_choices=json.dumps([{"name": "Sweet", "extra_cost": 0.1}, {"name": "Sour"}])) + db.add(pickles) + db.commit() + return {**menu, "bread": bread, "size": size, "brioche": brioche, "rye": rye, "double": double, "single": single, + "pickles": pickles} + + +def every_kind(m): + """One burger with every kind of choice (the same line from the phone and the counter).""" + b = m["burger"] + return burger_line( + m, quantity=2, notes="no salt", + quick=[{"id": b.quick_options[0].id, "qty": 2}], + options=[{"id": b.options[0].id, "subs": ["BBQ"]}, {"id": m["pickles"].id, "qty": 2, "subs": ["Sweet"]}], + removed=[b.ingredients[0].id], + prefs=[{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Salad"}, + {"set_id": m["bread"].id, "choices": [{"id": m["rye"].id}]}]) + + +def open_order(client, h, table=None, order_type="here"): + r = client.post("/api/orders/", headers=h, json={"table_id": table.id if table else None, "order_type": order_type}) + assert r.status_code == 201, r.text + return r.json()["id"] + + +def items_of(db, order_id): + from models.order import OrderItem + db.expire_all() + return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all() + + +def test_same_price_from_the_phone_and_the_counter(client, db, full, till, phone, floor): + m = full + # 10 + cheese 2×1 + sauce 0.5 + BBQ 0.2 + pickles 2×(0.4 + 0.1) + rare 0 + salad 1 + rye 0.3 + double 1 (default, costs) + want = 10 + 2 + 0.5 + 0.2 + 1.0 + 1.0 + 0.3 + 1.0 + oid = open_order(client, phone["h"], floor["t1"]) + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [every_kind(m)]}) + assert r.status_code == 200, r.text + from_phone = items_of(db, oid)[0] + r = client.post(f"/api/pos/tables/{floor['t2'].id}/items", headers=till["h"], json={"lines": [every_kind(m)]}) + assert r.status_code == 201, r.text + from_counter = items_of(db, r.json()["order_id"])[0] + assert from_phone.unit_price == from_counter.unit_price == pytest.approx(want) + assert from_phone.selected_options == from_counter.selected_options + names = [e["name"] for e in json.loads(from_phone.selected_options)] + # the cheaper default ("Brioche · Toasted") isn't stored; a default that costs ("Double") is + assert names == ["Extra cheese x2", "Sauce", "BBQ", "Pickles x2", "Sweet x2", "Rare", "Salad", "Rye", "Double"] + assert json.loads(from_phone.removed_ingredients) == ["Onion"] and from_phone.notes == "no salt" + # the quote said the same before sending + q = client.post("/api/orders/quote", headers=phone["h"], json={"order_id": oid, "lines": [every_kind(m)]}).json() + assert q["lines"][0]["unit_price"] == pytest.approx(want) and q["total"] == pytest.approx(want * 2) + + +def test_a_set_left_out_takes_its_default(client, db, full, phone, floor): + m = full + oid = open_order(client, phone["h"], floor["t1"]) + line = {"product_id": m["burger"].id, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["well"].id}]}]} + assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [line]}).status_code == 200 + item = items_of(db, oid)[0] + # 10 + well done 0.5 + double 1 (Bread and Size left out: their defaults) + assert item.unit_price == pytest.approx(11.5) + assert [e["name"] for e in json.loads(item.selected_options)] == ["Well done", "Double"] + # a set without a default can't be left out + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{"product_id": m["burger"].id}]}) + assert err(r) == "order.line.choice_missing" and r.json()["error"]["params"]["name"] == "Burger" + + +@pytest.mark.parametrize("tamper", [ + {"selected_options": [{"id": None, "name": "Gold leaf", "price_delta": -9.0, "type": "extra"}]}, + {"unit_price": 0.01}, + {"price_delta": -5}, +]) +def test_prices_from_the_app_are_refused(client, db, full, phone, floor, tamper): + oid = open_order(client, phone["h"], floor["t1"]) + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [{**burger_line(full), **tamper}]}) + assert r.status_code == 422 and err(r) == "order.line.client_price" + assert r.json()["error"]["params"]["line"] == 1 + assert items_of(db, oid) == [] + + +def test_the_old_shape_is_refused(client, db, full, phone, floor): + oid = open_order(client, phone["h"], floor["t1"]) + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], + json={"items": [{"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -3}]}) + assert err(r) == "order.lines_required" and items_of(db, oid) == [] + + +def test_a_price_set_by_hand_needs_the_key_or_a_managers_pin(client, db, full, phone, floor, make_user): + from models.order import OrderAuditLog + oid = open_order(client, phone["h"], floor["t1"]) + line = {"product_id": full["coffee"].id, "quantity": 1, "price_adjustment": -1.0} + url = f"/api/orders/{oid}/items" + r = client.post(url, headers=phone["h"], json={"lines": [line]}) + assert r.status_code == 403 and err(r) == "access.override_possible" + assert r.json()["error"]["params"]["key"] == "ordering.prices.modify" and items_of(db, oid) == [] + boss = make_user(role="owner") + a = client.post("/api/access/override", headers=phone["h"], + json={"key": "ordering.prices.modify", "username": boss.username, "pin": TEST_PIN}) + assert a.status_code == 200, a.text + r = client.post(url, headers=dict(phone["h"], **{"X-Xenia-Override": a.json()["override_token"]}), json={"lines": [line]}) + assert r.status_code == 200, r.text + item = items_of(db, oid)[0] + assert item.unit_price == 3.0 and item.price_adjustment == -1.0 + log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "PRICE_SET_BY_HAND").one() + assert "override #" in log.note + # out of range → refused whoever asks + r = client.post(url, headers=dict(phone["h"]), json={"lines": [{**line, "price_adjustment": 1e9}]}) + assert err(r) == "order.line.price" + + +@pytest.mark.parametrize("bad,code", [ + (lambda m: burger_line(m, options=[{"id": 999999}]), "order.line.option_gone"), + (lambda m: burger_line(m, removed=[999999]), "order.line.option_gone"), + (lambda m: {"product_id": m["gone"].id}, "order.line.product_unavailable"), + (lambda m: {"product_id": m["coffee"].id, "quantity": 0}, "order.line.quantity"), + (lambda m: burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 1.5}]), "order.line.quantity"), +]) +def test_refusals_name_the_product_and_the_line(client, db, full, phone, floor, bad, code): + oid = open_order(client, phone["h"], floor["t1"]) + good = {"product_id": full["coffee"].id, "quantity": 1} + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [good, bad(full)]}) + assert r.status_code == 422 and err(r) == code + assert r.json()["error"]["params"]["line"] == 2 and items_of(db, oid) == [] # nothing half-added + + +def test_quote_for_a_new_order_and_its_sales_point(client, db, full, phone): + from tests.test_sales_points import takeaway_price + takeaway_price(db, full["coffee"], 2.7) + line = {"product_id": full["coffee"].id, "quantity": 2} + here = client.post("/api/orders/quote", headers=phone["h"], json={"lines": [line]}).json() + away = client.post("/api/orders/quote", headers=phone["h"], json={"order_type": "takeaway", "lines": [line]}).json() + assert here["total"] == 6.0 and away["total"] == pytest.approx(5.4) + assert err(client.post("/api/orders/quote", headers=phone["h"], json={"lines": [{**line, "price_delta": 1}]})) == "order.line.client_price" + + +def test_service_items_and_courses_still_work(client, db, full, phone, floor): + oid = open_order(client, phone["h"], floor["t1"]) + r = client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [ + {"product_id": full["cutlery"].id, "quantity": 2, "is_service_item": True}, # priceless: printed, not saved + {"product_id": full["coffee"].id, "quantity": 1, "course_id": 2}, + ]}) + assert r.status_code == 200, r.text + items = items_of(db, oid) + assert [(i.product_id, i.course_id) for i in items] == [(full["coffee"].id, 2)] diff --git a/local_backend/tests/test_pos_tables.py b/local_backend/tests/test_pos_tables.py index c6b3f0a..4097150 100644 --- a/local_backend/tests/test_pos_tables.py +++ b/local_backend/tests/test_pos_tables.py @@ -67,7 +67,7 @@ def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu): assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}] # the waiter opens T1 on the phone; the counter sees it with totals and who is on it o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json() - client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]}) + client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"lines": [{"product_id": menu["coffee"].id, "quantity": 2}]}) t1 = tables(client, till)[0]["T1"]["order"] assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1 assert t1["people"] == ["Maria"] and t1["mine"] is False @@ -85,7 +85,7 @@ def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, e seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json() assert [i["product_name"] for i in seen["items"]] == ["Freddo"] assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], - json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200 + json={"lines": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200 # the counter adds a burger to the same order (not a second one) assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid t1 = tables(client, till)[0]["T1"]["order"] @@ -125,7 +125,7 @@ def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_ db.commit() h = login(nikos, "waiter") o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json() - client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]}) + client.post(f"/api/orders/{o['id']}/items", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "quantity": 1}]}) item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"] assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours" assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"], diff --git a/local_backend/tests/test_sales_points.py b/local_backend/tests/test_sales_points.py index f2c03a3..3ce5a53 100644 --- a/local_backend/tests/test_sales_points.py +++ b/local_backend/tests/test_sales_points.py @@ -85,7 +85,7 @@ def test_waiter_orders_follow_the_sales_point(client, db, make_user, login, menu assert "Burger" in [p["name"] for p in client.get("/api/products/", headers=h).json()] # no filter: as before order = client.post("/api/orders/", headers=h, json={"table_id": None, "order_type": "here"}).json() assert db.get(Order, order["id"]).sales_point == "in_store" - r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"items": [{"product_id": menu["burger"].id, "quantity": 1}]}) + r = client.post(f"/api/orders/{order['id']}/items", headers=h, json={"lines": [{"product_id": menu["burger"].id, "quantity": 1}]}) assert err(r) == "order.not_sold_here" diff --git a/manager_dashboard/src/pages/DesktopOrderingTab.jsx b/manager_dashboard/src/pages/DesktopOrderingTab.jsx index 5316b88..729ca67 100644 --- a/manager_dashboard/src/pages/DesktopOrderingTab.jsx +++ b/manager_dashboard/src/pages/DesktopOrderingTab.jsx @@ -2,6 +2,7 @@ import { useState, useRef, useCallback, useEffect } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import client from '../api/client' +import { LineError, wireLine } from '@xenia/api' import ManagerOrderDrawer from './ManagerOrderDrawer' // ── Constants ───────────────────────────────────────────────────────────────── @@ -494,8 +495,9 @@ export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) { const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId }) activeOrderId = newOrder.id } + // what was chosen, by id: the server prices it (plan step 4.4) const res = await client.post(`/api/orders/${activeOrderId}/items`, { - items: cart.map(({ _key, _drawerState, ...item }) => item), + lines: cart.map(({ _key, _drawerState, ...item }) => wireLine(item, products.find(p => p.id === item.product_id))), order_note: orderNote || null, }) return res.data @@ -514,7 +516,9 @@ export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) { qc.invalidateQueries({ queryKey: ['orders-active'] }) }, onError: (err) => { - toast.error(err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας') + toast.error(err instanceof LineError + ? `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού` + : err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας') }, }) diff --git a/packages/api/src/index.js b/packages/api/src/index.js index 2f69e20..345dc64 100644 --- a/packages/api/src/index.js +++ b/packages/api/src/index.js @@ -5,9 +5,11 @@ // → an axios instance: auth/device headers, err.xenia on every error, manager-override retry // parseError(err) / errorMessage(err, t) / isError(err, code) // createLiveClient({ url, cursor, onEvent, onReady, onDisconnect }) WebSocket + cursor replay +// lineFromOptions / wireLine / estimate order lines: what was chosen, by id; the server prices it (4.4) // // React glue (bootstrap, permissions, the override dialog) lives in @xenia/access. export { createApiClient, DEVICE_HEADER, OVERRIDE_HEADER } from './client.js' export { parseError, errorMessage, isError } from './errors.js' export { createLiveClient, wsUrlFor, INITIAL_RECONNECT_DELAY, MAX_RECONNECT_DELAY } from './live.js' +export { LineError, lineFromOptions, wireLine, estimate } from './lines.js' diff --git a/packages/api/src/lines.js b/packages/api/src/lines.js new file mode 100644 index 0000000..e58aa93 --- /dev/null +++ b/packages/api/src/lines.js @@ -0,0 +1,132 @@ +// Order lines: what POST /api/orders/{id}/items and POST /api/orders/quote take (plan step 4.4). +// +// An app never sends a price. A line says what was chosen, by id (sub-choices by name): +// { product_id, quantity, notes?, course_id?, price_adjustment?, is_service_item?, +// quick: [{id, qty?}], options: [{id, qty?, subs: [name]}], +// prefs: [{set_id, choices: [{id, qty?, sub?}], shared?}], removed: [ingredient_id] } +// and the server prices it (local_backend/services/pos_cart.py; the counter POS builds the +// same lines in terminal/src/apps/pos/logic/cart.js). A preference set left out takes its +// default on the server. +// +// The waiter app and the manager's ordering tab keep their cart in the shape an order item is +// stored in (`selected_options` entries tagged quick | extra | extra_sub | pref | pref_sub, with +// the prices of the menu they have, `removed_ingredients` by name). `lineFromOptions` turns that +// into a line against the product as the menu lists it; the prices in the entries are only used +// for `estimate` (a cart total while offline, shown as an estimate). + +/** An entry that can't be matched to the product any more (an option or ingredient was + * deleted since the item was put in the cart, or "order again" of an old item). */ +export class LineError extends Error { + constructor(product, what) { + super(`${product?.name ?? 'product'}: "${what}" is not on the menu any more`) + this.name = 'LineError' + this.product = product?.name ?? null + this.what = what + } +} + +const QTY = /^(.*) x(\d+)$/ +const splitQty = name => { const m = QTY.exec(name ?? ''); return m ? [m[1], Number(m[2])] : [name ?? '', 1] } +const isSub = (e, type) => !!e && (e.type === type || (!e.type && e.id == null)) +const named = (list, name) => (list ?? []).some(s => s.name === name) + +/** The line for a cart item / stored order item `{selected_options, removed_ingredients}` of + * `product` (the menu's product: quick_options, options, preference_sets, ingredients). */ +export function lineFromOptions(product, item = {}) { + const line = { product_id: product?.id ?? item.product_id } + const opts = item.selected_options ?? [] + const removedNames = item.removed_ingredients ?? [] + if (!product) { + if (opts.length || removedNames.length) throw new LineError(null, opts[0]?.name ?? removedNames[0]) + return line + } + const sets = product.preference_sets ?? [] + const setOf = new Map(sets.flatMap(ps => (ps.choices ?? []).map(c => [c.id, ps]))) + const optById = new Map((product.options ?? []).map(o => [o.id, o])) + const quickById = new Map((product.quick_options ?? []).map(q => [q.id, q])) + const quickByName = new Map((product.quick_options ?? []).map(q => [q.name, q])) + + const quick = new Map() + const options = [] + const prefs = new Map() + for (let i = 0; i < opts.length; i++) { + const o = opts[i] + if (o.type === 'pref' || (!o.type && o.id != null && setOf.has(o.id))) { + const ps = setOf.get(o.id) + const c = ps?.choices.find(x => x.id === o.id) + if (!c) throw new LineError(product, o.name) + const entry = prefs.get(ps.id) ?? { set_id: ps.id, choices: [] } + prefs.set(ps.id, entry) + if (ps.allow_multi_select) { + const [, qty] = splitQty(o.name) + entry.choices.push(qty > 1 ? { id: c.id, qty } : { id: c.id }) + continue + } + const pick = { id: c.id } + if (c.sub_choices?.length && isSub(opts[i + 1], 'pref_sub') && named(c.sub_choices, opts[i + 1].name)) pick.sub = opts[++i].name + const shared = !c.disables_subset ? ps.shared_subset?.choices : null + if (shared?.length && isSub(opts[i + 1], 'pref_sub') && named(shared, opts[i + 1].name)) entry.shared = opts[++i].name + entry.choices = [pick] + } else if (o.type === 'extra' || (!o.type && o.id != null && optById.has(o.id))) { + const opt = optById.get(o.id) + if (!opt) throw new LineError(product, o.name) + const [, qty] = splitQty(o.name) + const subs = [] + while (isSub(opts[i + 1], 'extra_sub') && named(opt.sub_choices, splitQty(opts[i + 1].name)[0])) subs.push(splitQty(opts[++i].name)[0]) + const one = { id: opt.id } + if (qty > 1) one.qty = qty + if (subs.length) one.subs = subs + options.push(one) + } else if (o.type === 'quick' || !o.type) { + const [name, qty] = splitQty(o.name) + const q = (o.id != null && quickById.get(o.id)) || quickByName.get(name) + if (!q) throw new LineError(product, name) + quick.set(q.id, (quick.get(q.id) ?? 0) + qty) + } else { + throw new LineError(product, o.name) + } + } + const ingredients = new Map((product.ingredients ?? []).map(g => [g.name, g.id])) + const removed = removedNames.map(name => { + if (!ingredients.has(name)) throw new LineError(product, name) + return ingredients.get(name) + }) + if (quick.size) line.quick = [...quick].map(([id, qty]) => (qty > 1 ? { id, qty } : { id })) + if (options.length) line.options = options + if (prefs.size) line.prefs = [...prefs.values()] + if (removed.length) line.removed = removed + return line +} + +const cents = n => Math.round(n * 100) / 100 + +/** A cart item as the line the server takes: what was chosen + quantity, note, course, a + * price changed by hand (needs ordering.prices.modify or a manager's PIN), service item. */ +export function wireLine(item, product) { + const line = lineFromOptions(product, item) + line.quantity = item.quantity ?? 1 + if (item.notes?.trim()) line.notes = item.notes.trim() + if (item.course_id != null) line.course_id = item.course_id + if (item.price_adjustment) line.price_adjustment = cents(item.price_adjustment) + if (item.is_service_item) line.is_service_item = true + return line +} + +/** What a cart item will roughly cost from the menu the app has (base price, the options' + * prices, a preference set's default that costs, a price changed by hand). The server's + * price can differ (happy hours, price groups, quantity deals): use POST /api/orders/quote + * when online and show this one as an estimate. */ +export function estimate(item, product) { + if (!product) return 0 + const opts = item.selected_options ?? [] + let unit = product.base_price ?? 0 + for (const o of opts) unit += o.price_delta ?? 0 + const listed = new Set(opts.filter(o => o.type === 'pref').map(o => o.id)) + for (const ps of product.preference_sets ?? []) { + if ((ps.choices ?? []).some(c => listed.has(c.id))) continue + const def = (ps.choices ?? []).find(c => c.id === ps.default_choice_id) + if (def) unit += def.extra_cost ?? 0 + } + unit += item.price_adjustment ?? 0 + return cents(unit * (item.quantity ?? 1)) +} diff --git a/packages/api/tests/lines.test.mjs b/packages/api/tests/lines.test.mjs new file mode 100644 index 0000000..2c0d30c --- /dev/null +++ b/packages/api/tests/lines.test.mjs @@ -0,0 +1,73 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { LineError, estimate, lineFromOptions, wireLine } from '../src/lines.js' + +// the menu's burger as /api/products lists it (local_backend tests/test_order_lines.py `full`) +const burger = { + id: 1, name: 'Burger', base_price: 10, + quick_options: [{ id: 11, name: 'Extra cheese', price: 1, allow_multiple: true }], + options: [ + { id: 21, name: 'Sauce', extra_cost: 0.5, sub_choices: [{ name: 'BBQ', extra_cost: 0.2, is_default: true }, { name: 'Mayo' }] }, + { id: 22, name: 'Pickles', extra_cost: 0.4, allow_multiple: true, sub_choices: [{ name: 'Sweet', extra_cost: 0.1 }, { name: 'Sour' }] }, + ], + ingredients: [{ id: 31, name: 'Onion' }], + preference_sets: [ + { id: 41, name: 'Cooking', default_choice_id: null, + shared_subset: { name: 'Side', choices: [{ name: 'Fries', is_default: true }, { name: 'Salad', extra_cost: 1 }] }, + choices: [{ id: 411, name: 'Rare' }, { id: 412, name: 'Well done', extra_cost: 0.5, disables_subset: true }] }, + { id: 42, name: 'Bread', default_choice_id: 421, + choices: [{ id: 421, name: 'Brioche', sub_choices: [{ name: 'Toasted', is_default: true }, { name: 'Soft' }] }, { id: 422, name: 'Rye', extra_cost: 0.3 }] }, + { id: 43, name: 'Size', default_choice_id: 431, choices: [{ id: 431, name: 'Double', extra_cost: 1 }, { id: 432, name: 'Single' }] }, + ], +} + +const e = (type, id, name, price_delta = 0) => ({ id, name, price_delta, type }) + +test('the waiter drawer\'s cart item becomes a line by id', () => { + const item = { + product_id: 1, quantity: 2, notes: ' no salt ', course_id: 3, + selected_options: [ + e('pref', 411, 'Rare'), e('pref_sub', null, 'Salad', 1), + e('pref', 421, 'Brioche'), e('pref_sub', null, 'Soft'), + e('quick', null, 'Extra cheese', 1), e('quick', null, 'Extra cheese', 1), + e('extra', 21, 'Sauce', 0.5), e('extra_sub', null, 'BBQ', 0.2), + e('extra', 22, 'Pickles', 0.4), e('extra_sub', null, 'Sweet', 0.1), + e('extra', 22, 'Pickles', 0.4), e('extra_sub', null, 'Sweet', 0.1), + ], + removed_ingredients: ['Onion'], + } + assert.deepEqual(wireLine(item, burger), { + product_id: 1, quantity: 2, notes: 'no salt', course_id: 3, + quick: [{ id: 11, qty: 2 }], + options: [{ id: 21, subs: ['BBQ'] }, { id: 22, subs: ['Sweet'] }, { id: 22, subs: ['Sweet'] }], + prefs: [{ set_id: 41, choices: [{ id: 411 }], shared: 'Salad' }, { set_id: 42, choices: [{ id: 421, sub: 'Soft' }] }], + removed: [31], + }) + // the cheaper default isn't listed; the default that costs (Size: Double +1) counts in the estimate + assert.equal(estimate(item, burger), Math.round((10 + 1 + 0 + 2 + 0.7 + 1 + 1) * 2 * 100) / 100) +}) + +test('an item stored by the counter (quantities in the names) — order again', () => { + const stored = { + product_id: 1, quantity: 1, + selected_options: [e('quick', 11, 'Extra cheese x2', 2), e('extra', 22, 'Pickles x2', 0.8), e('extra_sub', null, 'Sweet x2', 0.2), + e('pref', 412, 'Well done', 0.5), e('pref', 431, 'Double', 1)], + } + assert.deepEqual(lineFromOptions(burger, stored), { + product_id: 1, quick: [{ id: 11, qty: 2 }], options: [{ id: 22, qty: 2, subs: ['Sweet'] }], + prefs: [{ set_id: 41, choices: [{ id: 412 }] }, { set_id: 43, choices: [{ id: 431 }] }], + }) +}) + +test('a price changed by hand and a service item travel with the line; nothing else priced', () => { + const line = wireLine({ product_id: 1, quantity: 1, price_adjustment: -1.004, is_service_item: true, unit_price: 0.01, selected_options: [] }, burger) + assert.deepEqual(line, { product_id: 1, quantity: 1, price_adjustment: -1, is_service_item: true }) +}) + +test('what is not on the menu any more is refused, not dropped', () => { + assert.throws(() => lineFromOptions(burger, { selected_options: [e('extra', 99, 'Truffle')] }), LineError) + assert.throws(() => lineFromOptions(burger, { selected_options: [e('quick', null, 'Bacon')] }), LineError) + assert.throws(() => lineFromOptions(burger, { removed_ingredients: ['Tomato'] }), err => err instanceof LineError && err.what === 'Tomato' && err.product === 'Burger') + // a product missing from the menu: fine without options + assert.deepEqual(wireLine({ product_id: 7, quantity: 3 }, undefined), { product_id: 7, quantity: 3 }) +}) diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 564f23f..23497bd 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -62,7 +62,16 @@ }, "order": { "not_found": "Η παραγγελία {{order_id}} δεν βρέθηκε.", - "not_sold_here": "Το {{name}} δεν πωλείται για αυτό το είδος παραγγελίας." + "not_sold_here": "Το {{name}} δεν πωλείται για αυτό το είδος παραγγελίας.", + "lines_required": "Αυτή η εφαρμογή έστειλε την παραγγελία σε παλιά μορφή. Ενημερώστε την εφαρμογή και στείλτε ξανά.", + "line": { + "product_unavailable": "Το «{{name}}» δεν είναι πια διαθέσιμο (γραμμή {{line}}).", + "option_gone": "«{{name}}»: μια επιλογή δεν υπάρχει πια (γραμμή {{line}}). Αφαιρέστε το και προσθέστε το ξανά.", + "choice_missing": "«{{name}}»: λείπει μια υποχρεωτική επιλογή (γραμμή {{line}}).", + "quantity": "«{{name}}»: αυτή η ποσότητα δεν επιτρέπεται (γραμμή {{line}}).", + "price": "«{{name}}»: αυτή η αλλαγή τιμής δεν επιτρέπεται (γραμμή {{line}}).", + "client_price": "«{{name}}»: η εφαρμογή έστειλε δικές της τιμές, ενώ οι τιμές έρχονται από τον server (γραμμή {{line}}). Ενημερώστε την εφαρμογή." + } }, "notification": { "not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε." diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index b22a216..155ba02 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -62,7 +62,16 @@ }, "order": { "not_found": "Order {{order_id}} not found.", - "not_sold_here": "{{name}} isn't sold for this kind of order." + "not_sold_here": "{{name}} isn't sold for this kind of order.", + "lines_required": "This app sent the order in an old format. Update the app and send it again.", + "line": { + "product_unavailable": "{{name}} isn't available any more (line {{line}}).", + "option_gone": "{{name}}: a chosen option doesn't exist any more (line {{line}}). Remove it and add it again.", + "choice_missing": "{{name}}: a required choice is missing (line {{line}}).", + "quantity": "{{name}}: that quantity isn't allowed (line {{line}}).", + "price": "{{name}}: that price change isn't allowed (line {{line}}).", + "client_price": "{{name}}: the app sent its own prices, but prices come from the server (line {{line}}). Update the app." + } }, "notification": { "not_found": "Notification {{notification_id}} not found." diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index d55ebd3..8a7bc4a 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -120,7 +120,7 @@ try { const [p1, p2] = (await api('GET', '/api/products/', { token: boss })).filter(p => p.is_active !== false) await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p1.id], prep_zone_ids: [grill.id] } }) await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p2.id], prep_zone_ids: [bar.id] } }) - await api('POST', `/api/orders/${opened.id}/items`, { token: maria, body: { items: [p1, p2].map(p => ({ product_id: p.id, quantity: 1 })) } }) + await api('POST', `/api/orders/${opened.id}/items`, { token: maria, body: { lines: [p1, p2].map(p => ({ product_id: p.id, quantity: 1 })) } }) await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { prep_zone_id: grill.id, font_scale: 120 } } }) const order = (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === opened.id) const calls = [ @@ -184,7 +184,7 @@ try { const chimes0 = await page.evaluate(() => window.__xeniaChimes || 0) const table2 = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id && t.id !== table.id) const second = await api('POST', '/api/orders/', { token: maria, body: { table_id: table2.id } }) - await api('POST', `/api/orders/${second.id}/items`, { token: maria, body: { items: [{ product_id: p1.id, quantity: 2 }] } }) + await api('POST', `/api/orders/${second.id}/items`, { token: maria, body: { lines: [{ product_id: p1.id, quantity: 2 }] } }) const card2 = page.locator(`[data-testid="kds-card"][data-order="${second.id}"]`) r.check('3.2b: a new order appears by itself (live) and chimes', await card2.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) && await page.evaluate(() => window.__xeniaChimes || 0) > chimes0) @@ -464,7 +464,7 @@ try { r.check('3.3c: …and sees the counter\'s order on that table', onPhone.table_id === shared.id && onPhone.items.length === 1) // the phone adds two items → the counter shows them without a reload - await api('POST', `/api/orders/${tableOrder}/items`, { token: maria, body: { items: [ + await api('POST', `/api/orders/${tableOrder}/items`, { token: maria, body: { lines: [ { product_id: simple.id, quantity: 1, notes: 'from the phone' }, { product_id: simple.id, quantity: 1, notes: 'to cancel' }] } }) await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 3, null, { timeout: 8000 }).catch(() => {}) r.check('3.3c: the phone adds items → the counter shows them live', await page.getByTestId('order-line').count() === 3 @@ -510,7 +510,7 @@ try { // a waiter opens a table on the phone → the counter's list shows it live const phoneTable = counterTables.find(t => !t.order && mariaTables.has(t.id) && t.id !== shared.id) const phoneOrder = await api('POST', '/api/orders/', { token: maria, body: { table_id: phoneTable.id } }) - await api('POST', `/api/orders/${phoneOrder.id}/items`, { token: maria, body: { items: [{ product_id: simple.id, quantity: 2 }] } }) + await api('POST', `/api/orders/${phoneOrder.id}/items`, { token: maria, body: { lines: [{ product_id: simple.id, quantity: 2 }] } }) r.check('3.3c: a table opened on the phone shows on the counter at once, with what\'s due', // (opened, then its items: wait for both, the card shows the order before its items arrive) await page.waitForFunction(([id, due]) => { diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index b99d96f..2e147e5 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -1,6 +1,8 @@ // Waiter app suite (plan phase 4): sign-in v2 on the phone (4.2): each login mode, wrong PIN, // one session per waiter, lock / unlock / idle sign-out, a manager's approval on the phone; -// what a waiter may do from permission keys and the venue's role defaults (4.3). +// what a waiter may do from permission keys and the venue's role defaults (4.3); orders priced +// by the server: the cart's total from a quote, lines sent by id, an offline order priced when +// the phone is back and a refused line shown to the waiter (4.4). // Starts its own backend (:8061) and the venue-mode dev build (:5181), phone-sized Edge. // node waiter.mjs import path from 'node:path' @@ -13,7 +15,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url }) const APP = 'http://localhost:5181' const TOKEN_KEY = 'xenia:dev:token' const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) -const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3)') +const r = reporter('waiter: sign-in v2, lock, approvals (4.2), keys (4.3), server prices (4.4)') const errors = [] let failures = 0 @@ -156,6 +158,92 @@ try { await api('DELETE', `/api/orders/${o3.id}`, { token: boss }).catch(() => {}) await a.goto(`${APP}/tables`) + // ── 4.4: orders priced by the server ──────────────────────────────────────── + const prods = await api('GET', '/api/products/', { token: boss }) + const simple = p => p.quick_add_enabled && p.is_available && !p.is_service_item && p.lifecycle_status === 'active' + && !(p.preference_sets || []).some(ps => ps.default_choice_id == null) + const free = tables.filter(t => ![table.id, t2.id].includes(t.id) && !t.open_order_id && !t.current_order_id) + const [t4, t5] = free + // two products the first category on screen offers with a quick "+" + await a.goto(`${APP}/tables/${t4.id}/add?new=1`) + // the picker opens on favourites (none yet): pick the first category that has a quick "+" + let category = null + for (const c of (await api('GET', '/api/products/categories', { token: boss })).filter(c => !c.parent_id)) { + await a.getByRole('button', { name: c.name, exact: true }).first().click({ timeout: 5000 }).catch(() => {}) + if (await a.locator('[data-testid="product-quick-add"]').first().waitFor({ timeout: 3000 }).then(() => true).catch(() => false)) { category = c.name; break } + } + await a.locator('[data-testid="product-quick-add"]').first().waitFor({ timeout: 5000 }) + .catch(async e => { await a.screenshot({ path: path.join(OUT, 'waiter-add-items.png') }); throw e }) + const onScreen = await a.locator('[data-testid="product-card"]:has([data-testid="product-quick-add"])').evaluateAll(els => els.map(e => e.dataset.name)) + const [plain, other] = prods.filter(p => simple(p) && onScreen.includes(p.name)) + // a price the phone's menu doesn't know (a price modifier): only the server can say it + const mod = await api('POST', '/api/pricing/modifiers', { token: boss, body: { + name: 'e2e 4.4', scope: 'item', item_id: plain.id, action_type: 'set', action_value: 1.2 } }) + const addOn = async (tableId, product, times = 1) => { + if (!(await pathOf(a)).endsWith('/add')) await a.goto(`${APP}/tables/${tableId}/add?new=1`) + await a.getByRole('button', { name: category, exact: true }).first().click({ timeout: 5000 }).catch(() => {}) + const card = a.locator(`[data-testid="product-card"][data-name="${product.name}"]`) + await card.first().waitFor({ timeout: 10_000 }) + for (let i = 0; i < times; i++) await card.getByTestId('product-quick-add').first().click() + } + const total = () => a.getByTestId('cart-total') + await addOn(t4.id, plain, 2) + await a.getByTestId('cart-open').click() + const exact = await waitFor(async () => await total().getAttribute('data-estimated') === 'false', 10_000, 300) + const shownTotal = await total().innerText().catch(() => '') + r.check('4.4: the cart total is the server\'s price (a price the phone\'s menu doesn\'t know)', !!exact && shownTotal.includes('2.40'), shownTotal.replace(/\s+/g, ' ')) + await a.getByRole('button', { name: /^(ΑΠΟΣΤΟΛΗ|ΣΥΝΟΨΗ)/ }).last().click() + if (await shown(a, 'summary-total', 3000)) { + r.check('4.4: the summary shows the same total', (await a.getByTestId('summary-total').innerText()).includes('2.40')) + await a.getByRole('button', { name: /ΑΠΟΣΤΟΛΗ/ }).last().click() + } + const sent = await waitFor(async () => { + const st = await api('GET', `/api/tables/${t4.id}/status`, { token: boss }) + if (!st.active_order_id) return null + const o = await api('GET', `/api/orders/${st.active_order_id}`, { token: boss }) + return o.items.length ? o : null + }, 10_000, 500) + r.check('4.4: sent by id, priced by the server: the order costs what the cart said', + !!sent && sent.items.length === 1 && sent.items[0].quantity === 2 && sent.items[0].unit_price === 1.2, JSON.stringify(sent?.items?.map(i => [i.quantity, i.unit_price]))) + + // offline: the order is queued by id, shown as an estimate, priced when the phone is back; + // a product taken off the menu meanwhile comes back to the waiter as refused + await a.goto(`${APP}/tables/${t5.id}/add?new=1`) + await addOn(t5.id, plain) + await ctxA.setOffline(true) + await a.getByTestId('cart-open').click() + const wentOffline = await waitFor(async () => (await total().innerText().catch(() => '')).includes('χωρίς σύνδεση'), 30_000, 1000) + const est = await total().getAttribute('data-estimated').catch(() => null) + r.check('4.4: offline the cart total is an estimate (≈, the menu prices)', !!wentOffline && est === 'true' + && (await total().innerText()).includes('≈'), `${wentOffline} ${est} ${await total().innerText().catch(() => '')}`) + await a.mouse.click(10, 400) + await sleep(500) + await addOn(t5.id, other) + await a.getByTestId('cart-open').click() + await a.getByRole('button', { name: /^(ΑΠΟΣΤΟΛΗ|ΣΥΝΟΨΗ)/ }).last().click() + if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /ΑΠΟΣΤΟΛΗ/ }).last().click() + await sleep(2000) + await api('PUT', `/api/products/${other.id}`, { token: boss, body: { is_available: false } }) + await ctxA.setOffline(false) + const synced = await waitFor(async () => { + const st = await api('GET', `/api/tables/${t5.id}/status`, { token: boss }) + if (!st.active_order_id) return null + const o = await api('GET', `/api/orders/${st.active_order_id}`, { token: boss }) + return o.items.length ? o : null + }, 40_000, 1000) + r.check('4.4: back online the queued order is priced by the server (not the phone\'s estimate)', + !!synced && synced.items.length === 1 && synced.items[0].product_id === plain.id && synced.items[0].unit_price === 1.2, + JSON.stringify(synced?.items?.map(i => [i.product_id, i.unit_price]))) + const refusedShown = await shown(a, 'refused-lines', 15_000) + const refusedText = await a.getByTestId('refused-lines').innerText().catch(() => '') + r.check('4.4: the line the server refused comes back to the waiter with the reason', refusedShown && refusedText.includes(other.name), refusedText.replace(/\s+/g, ' ').slice(0, 200)) + await a.screenshot({ path: path.join(OUT, 'waiter-refused-lines.png') }) + await a.getByTestId('refused-lines-ok').click().catch(() => {}) + await api('PUT', `/api/products/${other.id}`, { token: boss, body: { is_available: true } }) + await api('DELETE', `/api/pricing/modifiers/${mod.id}`, { token: boss }).catch(() => {}) + for (const o of [sent, synced]) if (o) await api('DELETE', `/api/orders/${o.id}`, { token: boss }).catch(() => {}) + await a.goto(`${APP}/tables`) + // ── Signing out ends the session on the server: the second phone can sign in ─ await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 }) await a.getByRole('button', { name: /Αποσύνδεση/ }).last().click() diff --git a/waiter_pwa/src/App.jsx b/waiter_pwa/src/App.jsx index 097f399..2439f2b 100644 --- a/waiter_pwa/src/App.jsx +++ b/waiter_pwa/src/App.jsx @@ -27,6 +27,7 @@ import OrderLogPage from './pages/OrderLogPage' import { NotificationProvider } from './context/NotificationContext' import { LiveProvider } from './context/LiveContext' import ConnectivityBar from './components/ConnectivityBar' +import RefusedLines from './components/RefusedLines' import AppShell from './components/AppShell' import UpdatePrompt from './components/UpdatePrompt' import InstallAppDialog from './components/InstallAppDialog' @@ -473,6 +474,7 @@ function Routed() { + {/* Native builds ship their UI in the app bundle — no service worker to update */} {deliveryMode() !== 'native' && } diff --git a/waiter_pwa/src/components/ItemOptionsModal.jsx b/waiter_pwa/src/components/ItemOptionsModal.jsx deleted file mode 100644 index f3b3c25..0000000 --- a/waiter_pwa/src/components/ItemOptionsModal.jsx +++ /dev/null @@ -1,521 +0,0 @@ -import { useState, useRef } from 'react' - -// Unit metadata: step, min, quick-preset values, quick ± offset buttons -const UNIT_CONFIG = { - kg: { step: 0.1, min: 0.1, presets: [0.2, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0], offsets: [0.2, 0.5, 1.0], label: 'kg' }, - liter: { step: 0.1, min: 0.1, presets: [0.2, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0], offsets: [0.2, 0.5, 1.0], label: 'L' }, - gram: { step: 10, min: 10, presets: [50, 100, 150, 200, 250, 300, 400, 500], offsets: [50, 100, 200], label: 'g' }, - ml: { step: 5, min: 5, presets: [25, 50, 100, 150, 200, 250, 300, 500], offsets: [25, 50, 100], label: 'mL' }, -} -const DECIMAL_UNITS = new Set(Object.keys(UNIT_CONFIG)) - -function fmtQty(qty, unitCfg) { - if (!unitCfg) return String(qty) - if (unitCfg.label === 'kg' || unitCfg.label === 'L') return Number(qty).toFixed(1) - return String(qty) -} - -export default function ItemOptionsModal({ product, onAdd, onClose }) { - const [selectedOptions, setSelectedOptions] = useState([]) - const [removedIngredients, setRemovedIngredients] = useState([]) - const [notes, setNotes] = useState('') - - const unitCfg = UNIT_CONFIG[product.unit_type] ?? null - const isDecimal = DECIMAL_UNITS.has(product.unit_type) - const [quantity, setQuantity] = useState(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1) - const [qtyInput, setQtyInput] = useState('') - const [editingQty, setEditingQty] = useState(false) - const qtyRef = useRef(null) - - const options = product.options || [] - const ingredients = product.ingredients || [] - const preferenceSets = product.preference_sets || [] - - // selectedPreferences: { [setId]: choice | null } (single-select sets) - const [selectedPreferences, setSelectedPreferences] = useState(() => - Object.fromEntries( - preferenceSets.filter(ps => !ps.allow_multi_select).map(ps => { - const def = ps.default_choice_id != null - ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null - : null - return [ps.id, def] - }) - ) - ) - - // multiPreferences: { [setId]: Array<{choice, qty}> } (multi-select sets) - const [multiPreferences, setMultiPreferences] = useState(() => - Object.fromEntries( - preferenceSets.filter(ps => ps.allow_multi_select).map(ps => { - const def = ps.default_choice_id != null - ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null - : null - return [ps.id, def ? [{ choice: def, qty: 1 }] : []] - }) - ) - ) - - // Per-preference-choice inline sub-choices: { [choiceId]: subChoice | null } - const [selectedSubChoices, setSelectedSubChoices] = useState(() => { - const init = {} - preferenceSets.filter(ps => !ps.allow_multi_select).forEach(ps => { - const def = ps.default_choice_id != null - ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null - : null - if (def && def.sub_choices?.length > 0) { - const subDef = def.sub_choices.find(s => s.is_default) ?? def.sub_choices[0] - init[def.id] = subDef - } - }) - return init - }) - - // Shared-subset selections: { [setId]: subChoice | null } - const [selectedSharedSubs, setSelectedSharedSubs] = useState(() => { - const init = {} - preferenceSets.filter(ps => !ps.allow_multi_select).forEach(ps => { - if (ps.shared_subset?.choices?.length > 0) { - const selectedChoice = ps.default_choice_id != null - ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null - : null - if (!selectedChoice || !selectedChoice.disables_subset) { - const subDef = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0] - init[ps.id] = subDef - } - } - }) - return init - }) - - // Option sub-choices: { [optionId]: subChoice | null } - // Initialise with any option that has a default sub-choice pre-selected — but only - // if the option itself is checked by default (options are all unchecked initially). - const [selectedOptionSubs, setSelectedOptionSubs] = useState({}) - - function selectPreference(setId, choice) { - setSelectedPreferences(prev => ({ ...prev, [setId]: choice })) - if (choice && choice.sub_choices?.length > 0) { - const subDef = choice.sub_choices.find(s => s.is_default) ?? choice.sub_choices[0] - setSelectedSubChoices(prev => ({ ...prev, [choice.id]: subDef })) - } - const ps = preferenceSets.find(p => p.id === setId) - if (ps?.shared_subset?.choices?.length > 0 && !choice?.disables_subset) { - setSelectedSharedSubs(prev => { - if (prev[setId] != null) return prev - const subDef = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0] - return { ...prev, [setId]: subDef } - }) - } - } - - function toggleMultiChoice(setId, choice) { - setMultiPreferences(prev => { - const current = prev[setId] ?? [] - const idx = current.findIndex(e => e.choice.id === choice.id) - if (idx >= 0) return { ...prev, [setId]: current.filter((_, i) => i !== idx) } - return { ...prev, [setId]: [...current, { choice, qty: 1 }] } - }) - } - - function setMultiChoiceQty(setId, choiceId, delta) { - setMultiPreferences(prev => { - const current = prev[setId] ?? [] - return { - ...prev, - [setId]: current.map(e => - e.choice.id === choiceId ? { ...e, qty: Math.max(1, e.qty + delta) } : e - ), - } - }) - } - - function selectSubChoice(parentChoiceId, sub) { - setSelectedSubChoices(prev => ({ ...prev, [parentChoiceId]: sub })) - } - - function selectSharedSub(setId, sub) { - setSelectedSharedSubs(prev => ({ ...prev, [setId]: sub })) - } - - function toggleOption(opt) { - setSelectedOptions(prev => { - const exists = prev.find(o => o.id === opt.id) - if (exists) { - // Deselecting: also clear its sub-choice selection - setSelectedOptionSubs(s => { const n = { ...s }; delete n[opt.id]; return n }) - return prev.filter(o => o.id !== opt.id) - } - // Selecting: pre-select default sub-choice if any - if (opt.sub_choices?.length > 0) { - const subDef = opt.sub_choices.find(s => s.is_default) ?? opt.sub_choices[0] - setSelectedOptionSubs(s => ({ ...s, [opt.id]: subDef })) - } - return [...prev, { id: opt.id, name: opt.name, price_delta: opt.extra_cost ?? 0 }] - }) - } - - function selectOptionSub(optId, sub) { - setSelectedOptionSubs(prev => ({ ...prev, [optId]: sub })) - } - - function toggleIngredient(ing) { - setRemovedIngredients(prev => - prev.includes(ing.name) ? prev.filter(n => n !== ing.name) : [...prev, ing.name] - ) - } - - // Check whether any checked option with sub_choices is missing its sub-choice selection - const optionSubsMissing = selectedOptions.some(o => { - const full = options.find(opt => opt.id === o.id) - return full?.sub_choices?.length > 0 && selectedOptionSubs[o.id] == null - }) - - function isPrefSetComplete(ps) { - if (ps.allow_multi_select) { - return (multiPreferences[ps.id] ?? []).length > 0 - } - const choice = selectedPreferences[ps.id] - if (choice == null) return false - if (choice.sub_choices?.length > 0 && selectedSubChoices[choice.id] == null) return false - if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset && selectedSharedSubs[ps.id] == null) return false - return true - } - - const allPrefsSelected = preferenceSets.every(isPrefSetComplete) - const unselectedPrefs = preferenceSets.filter(ps => !isPrefSetComplete(ps)) - const canAdd = allPrefsSelected && !optionSubsMissing - - const prefExtra = preferenceSets.reduce((s, ps) => { - if (ps.allow_multi_select) { - return s + (multiPreferences[ps.id] ?? []).reduce((acc, { choice, qty }) => acc + (choice.extra_cost ?? 0) * qty, 0) - } - const choice = selectedPreferences[ps.id] - if (!choice) return s - const inlineSub = choice.sub_choices?.length > 0 ? (selectedSubChoices[choice.id] ?? null) : null - const sharedSub = (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) - ? (selectedSharedSubs[ps.id] ?? null) : null - return s + (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0) - }, 0) - const optionExtra = selectedOptions.reduce((s, o) => { - const subExtra = selectedOptionSubs[o.id]?.extra_cost ?? 0 - return s + (o.price_delta ?? 0) + subExtra - }, 0) - const totalPrice = (product.base_price + optionExtra + prefExtra) * quantity - - function handleAdd() { - if (!canAdd) return - const prefChoices = preferenceSets.flatMap(ps => { - if (ps.allow_multi_select) { - return (multiPreferences[ps.id] ?? []).map(({ choice, qty }) => ({ - id: choice.id, - name: qty > 1 ? `${choice.name} x${qty}` : choice.name, - price_delta: (choice.extra_cost ?? 0) * qty, - type: 'pref', - })) - } - const choice = selectedPreferences[ps.id] - if (!choice) return [] - const entries = [{ id: choice.id, name: choice.name, price_delta: choice.extra_cost ?? 0, type: 'pref' }] - const inlineSub = choice.sub_choices?.length > 0 ? (selectedSubChoices[choice.id] ?? null) : null - if (inlineSub) entries.push({ id: null, name: inlineSub.name, price_delta: inlineSub.extra_cost ?? 0, type: 'pref_sub' }) - if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) { - const sharedSub = selectedSharedSubs[ps.id] ?? null - if (sharedSub) entries.push({ id: null, name: sharedSub.name, price_delta: sharedSub.extra_cost ?? 0, type: 'pref_sub' }) - } - return entries - }) - - const optionEntries = selectedOptions.flatMap(o => { - const entries = [{ id: o.id, name: o.name, price_delta: o.price_delta ?? 0, type: 'extra' }] - const sub = selectedOptionSubs[o.id] - if (sub) entries.push({ id: null, name: sub.name, price_delta: sub.extra_cost ?? 0, type: 'extra_sub' }) - return entries - }) - - onAdd({ - product_id: product.id, - quantity, - selected_options: [...optionEntries, ...prefChoices], - removed_ingredients: removedIngredients, - notes, - }) - onClose() - } - - return ( -
-
e.stopPropagation()}> -
-

{product.name}

-

{Number(totalPrice).toFixed(2)} €

- - {/* ── Checkbox options with optional sub-choices ── */} - {options.length > 0 && ( -
-

Επιλογές

- {options.map(opt => { - const isChecked = !!selectedOptions.find(o => o.id === opt.id) - const hasSubs = opt.sub_choices?.length > 0 - const subMissing = isChecked && hasSubs && selectedOptionSubs[opt.id] == null - return ( -
- - {isChecked && hasSubs && ( -
- {subMissing &&

— απαιτείται επιλογή

} - {opt.sub_choices.map((sub, si) => ( - - ))} -
- )} -
- ) - })} -
- )} - - {/* ── Preference sets ── */} - {preferenceSets.map(ps => { - const missing = !isPrefSetComplete(ps) - - if (ps.allow_multi_select) { - const selected = multiPreferences[ps.id] ?? [] - return ( -
-

- {ps.name} - {missing && — επιλέξτε τουλάχιστον μία} -

- {ps.choices.map(ch => { - const entry = selected.find(e => e.choice.id === ch.id) - const isChecked = !!entry - return ( -
-
- - {isChecked && ps.allow_choice_quantity && ( -
- - {entry.qty} - -
- )} -
-
- ) - })} -
- ) - } - - const selectedChoice = selectedPreferences[ps.id] ?? null - const showSharedSubset = ps.shared_subset?.choices?.length > 0 - && selectedChoice != null - && !selectedChoice.disables_subset - const sharedMissing = showSharedSubset && selectedSharedSubs[ps.id] == null - - return ( -
-

- {ps.name} - {missing && — απαιτείται επιλογή} -

- - {ps.choices.map(ch => { - const isSelected = selectedPreferences[ps.id]?.id === ch.id - const hasSubs = ch.sub_choices?.length > 0 - const subMissing = isSelected && hasSubs && selectedSubChoices[ch.id] == null - return ( -
- - {isSelected && hasSubs && ( -
- {subMissing &&

— απαιτείται επιλογή

} - {ch.sub_choices.map((sub, si) => ( - - ))} -
- )} -
- ) - })} - - {showSharedSubset && ( -
-

- {ps.shared_subset.name} - {sharedMissing && — απαιτείται επιλογή} -

- {ps.shared_subset.choices.map((sub, si) => ( - - ))} -
- )} -
- ) - })} - - {/* ── Remove ingredients ── */} - {ingredients.length > 0 && ( -
-

Αφαίρεση υλικών

- {ingredients.map(ing => ( - - ))} -
- )} - -
-

Σημείωση

-