feat(ordering): orders priced by the server (platform-v2 step 4.4)

The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.

- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
  price_adjustment, is_service_item): sales point checked first, refusals name the
  product and line (order.line.*, order.not_sold_here); prices or selected_options in a
  line -> order.line.client_price, the old `items` shape -> order.lines_required; a
  by-hand price change needs ordering.prices.modify or a manager's approval (audited
  PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
  pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
  isn't stored; a default that costs is charged (the waiter never sent it: fixed);
  an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
  shows the same prices; offline orders queued by id, priced on sync, refused lines
  shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 03:35:03 +02:00
co-authored by Claude Opus 5.5
parent bcf91bf6e9
commit 8e0a786bbc
25 changed files with 1052 additions and 656 deletions
+2
View File
@@ -176,6 +176,8 @@ Routers are mounted from the module manifests (`local_backend/modules/<key>/mani
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17). **CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
Use `core.access.deps.require("<module>.<area>.<action>")` (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). Use `core.access.deps.require("<module>.<area>.<action>")` (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: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.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:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header. Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.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:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; 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). 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).
+7
View File
@@ -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.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."), "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.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.area_not_found": (404, "Delivery area {area_id} not found."),
"fees.rule_not_found": (404, "Fee rule {rule_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."), "fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
+143 -7
View File
@@ -29,7 +29,7 @@ from services.pricing import (
build_active_price_group_ids, write_price_events, build_active_price_group_ids, write_price_events,
check_waiter_discount_limits, discounts_enabled, _system_round, check_waiter_discount_limits, discounts_enabled, _system_round,
) )
from pydantic import BaseModel from pydantic import BaseModel, Field
class PrintOrderRequest(BaseModel): class PrintOrderRequest(BaseModel):
printer_id: int printer_id: int
@@ -476,13 +476,149 @@ def open_order(body: OrderCreate, db: Session = Depends(get_db), user: User = De
return order 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) @router.post("/{order_id}/items", response_model=AddItemsResponse)
def add_items( def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Session = Depends(get_db),
order_id: int, user: User = Depends(get_current_user)):
body: AddItemsRequest, """Add lines to an order; the server prices them (4.4). Apps send what was chosen by id,
db: Session = Depends(get_db), never a price: prices or `selected_options` in a line → order.line.client_price, the
user: User = Depends(get_current_user), 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() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise XeniaError("order.not_found", order_id=order_id) raise XeniaError("order.not_found", order_id=order_id)
+5 -28
View File
@@ -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) 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") @router.post("/quote")
def pos_quote(body: QuoteBody, db: Session = Depends(get_db), user=Depends(require(ACCESS))): 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, """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: if body.order_id is not None:
order = _order_for(db, user, body.order_id) order = _order_for(db, user, body.order_id)
order_type, existing = order.order_type or "here", pos_cart.order_cart(order) 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 [] return pos_cart.quote(db, lines, order_type, existing)
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)}
@@ -240,7 +217,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
_check_cash(body.cash_given, cash_due) _check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) 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()] item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None paid, fiscal = [], None
for method, idx in groups: for method, idx in groups:
@@ -288,8 +265,8 @@ def _check_cash(cash_given, cash_due):
def _items_in(lines, adjs): def _items_in(lines, adjs):
"""Cart lines as POST /api/orders/{id}/items takes them (the waiter's selected_options """Resolved lines as orders.add_priced_items takes them (selected_options entries with the
entries with the database's prices; a discount as the item's price_adjustment).""" database's prices; a discount as the item's price_adjustment)."""
from schemas.order import OrderItemInput, SelectedOptionInput from schemas.order import OrderItemInput, SelectedOptionInput
return [OrderItemInput( return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity, 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)] adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
if order is None: if order is None:
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user) 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", [])} return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
+96 -23
View File
@@ -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 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 same `selected_options` entries the they are stored), and this module turns that into the `selected_options` entries an order
waiter app sends (types quick | extra | extra_sub | pref | pref_sub) with the prices taken 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) exactly from the database, then runs the pricing engine (services/pricing.py::resolve_price) through
as POST /api/orders/{id}/items does. 3.3b sends the same lines to create the order. routers/orders.py::add_priced_items. 3.3b sends the same lines to create the order.
A line: A line:
{product_id, quantity, notes?, {product_id, quantity, notes?,
quick: [{id, qty?}], quick add-ons (qty only if allow_multiple) 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}], prefs: [{set_id, choices: [{id, qty?, sub?: name}], shared?: name}],
removed: [ingredient_id]} removed: [ingredient_id]}
Rules (the same as the waiter's options dialog, waiter_pwa ItemOptionsModal.jsx): 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); - 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 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`; - 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 Anything else → XeniaError("pos.line_invalid", line=n, reason=...), reason one of
product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub | product_unavailable | unknown_quick | unknown_option | unknown_choice | unknown_sub |
choice_required | sub_required | unknown_ingredient | quantity | discount | not_sold_here 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 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: def resolve_line(db, raw: dict, n: int) -> Line:
from models.product import Product from models.product import Product
product = db.get(Product, raw.get("product_id")) if isinstance(raw.get("product_id"), int) else None 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"}) "price_delta": round((o.extra_cost or 0.0) * qty, 2), "type": "extra"})
for name in names: for name in names:
s = _sub(subs, name, n) 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), line.entries.append({"id": None, "name": s["name"] if qty == 1 else f"{s['name']} x{qty}",
"type": "extra_sub"}) "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: 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) 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 [] picks = (sel or {}).get("choices") or []
if not picks or (len(picks) > 1 and not ps.allow_multi_select): if not picks or (len(picks) > 1 and not ps.allow_multi_select):
raise _bad(n, "choice_required") raise _bad(n, "choice_required")
by_id = {c.id: c for c in ps.choices} entries = []
shared = _shared(ps.shared_subset)
for pick in picks: 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: if c is None:
raise _bad(n, "unknown_choice") raise _bad(n, "unknown_choice")
if ps.allow_multi_select: if ps.allow_multi_select:
qty = _qty(pick.get("qty"), n, True) 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}", 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"}) "price_delta": round((c.extra_cost or 0.0) * qty, 2), "type": "pref"})
continue 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) subs = _subs(c.sub_choices)
if subs: if subs:
s = _sub(subs, pick.get("sub"), n) if pick.get("sub") is not None else None s = _sub(subs, pick.get("sub"), n) if pick.get("sub") is not None else None
if s is None: if s is None:
raise _bad(n, "sub_required") 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), entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"}) "type": "pref_sub"})
if shared and not c.disables_subset: 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 s = _sub(_subs(shared.get("choices")), sel.get("shared"), n) if sel.get("shared") is not None else None
if s is None: if s is None:
raise _bad(n, "sub_required") 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), entries.append({"id": None, "name": s["name"], "price_delta": round(float(s.get("extra_cost") or 0.0), 2),
"type": "pref_sub"}) "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: if chosen:
raise _bad(n, "unknown_choice") 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 """A line's discount (percent of its unit price) as the order item's price_adjustment
(negative, rounded to cents).""" (negative, rounded to cents)."""
return -round(unit_price * pct / 100.0, 2) if pct else 0.0 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)}
+1 -1
View File
@@ -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 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 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, 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 # the board: the time, the area, the fee
o = board(client, counter)["incoming"][0] 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) 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)
+186
View File
@@ -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)]
+3 -3
View File
@@ -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}] 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 # 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() 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"] 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["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 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() seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json()
assert [i["product_name"] for i in seen["items"]] == ["Freddo"] assert [i["product_name"] for i in seen["items"]] == ["Freddo"]
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], 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) # 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 assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid
t1 = tables(client, till)[0]["T1"]["order"] 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() db.commit()
h = login(nikos, "waiter") h = login(nikos, "waiter")
o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json() 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"] 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("/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"], assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"],
+1 -1
View File
@@ -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 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() 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" 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" assert err(r) == "order.not_sold_here"
@@ -2,6 +2,7 @@ import { useState, useRef, useCallback, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import client from '../api/client' import client from '../api/client'
import { LineError, wireLine } from '@xenia/api'
import ManagerOrderDrawer from './ManagerOrderDrawer' import ManagerOrderDrawer from './ManagerOrderDrawer'
// ── Constants ───────────────────────────────────────────────────────────────── // ── Constants ─────────────────────────────────────────────────────────────────
@@ -494,8 +495,9 @@ export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) {
const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId }) const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId })
activeOrderId = newOrder.id 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`, { 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, order_note: orderNote || null,
}) })
return res.data return res.data
@@ -514,7 +516,9 @@ export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) {
qc.invalidateQueries({ queryKey: ['orders-active'] }) qc.invalidateQueries({ queryKey: ['orders-active'] })
}, },
onError: (err) => { onError: (err) => {
toast.error(err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας') toast.error(err instanceof LineError
? `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού`
: err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας')
}, },
}) })
+2
View File
@@ -5,9 +5,11 @@
// → an axios instance: auth/device headers, err.xenia on every error, manager-override retry // → an axios instance: auth/device headers, err.xenia on every error, manager-override retry
// parseError(err) / errorMessage(err, t) / isError(err, code) // parseError(err) / errorMessage(err, t) / isError(err, code)
// createLiveClient({ url, cursor, onEvent, onReady, onDisconnect }) WebSocket + cursor replay // 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. // React glue (bootstrap, permissions, the override dialog) lives in @xenia/access.
export { createApiClient, DEVICE_HEADER, OVERRIDE_HEADER } from './client.js' export { createApiClient, DEVICE_HEADER, OVERRIDE_HEADER } from './client.js'
export { parseError, errorMessage, isError } from './errors.js' export { parseError, errorMessage, isError } from './errors.js'
export { createLiveClient, wsUrlFor, INITIAL_RECONNECT_DELAY, MAX_RECONNECT_DELAY } from './live.js' export { createLiveClient, wsUrlFor, INITIAL_RECONNECT_DELAY, MAX_RECONNECT_DELAY } from './live.js'
export { LineError, lineFromOptions, wireLine, estimate } from './lines.js'
+132
View File
@@ -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))
}
+73
View File
@@ -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 })
})
+10 -1
View File
@@ -62,7 +62,16 @@
}, },
"order": { "order": {
"not_found": "Η παραγγελία {{order_id}} δεν βρέθηκε.", "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": { "notification": {
"not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε." "not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε."
+10 -1
View File
@@ -62,7 +62,16 @@
}, },
"order": { "order": {
"not_found": "Order {{order_id}} not found.", "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": { "notification": {
"not_found": "Notification {{notification_id}} not found." "not_found": "Notification {{notification_id}} not found."
+4 -4
View File
@@ -120,7 +120,7 @@ try {
const [p1, p2] = (await api('GET', '/api/products/', { token: boss })).filter(p => p.is_active !== false) 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: [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/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 } } }) 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 order = (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === opened.id)
const calls = [ const calls = [
@@ -184,7 +184,7 @@ try {
const chimes0 = await page.evaluate(() => window.__xeniaChimes || 0) 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 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 } }) 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}"]`) 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) 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) && 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) 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 // 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' }] } }) { 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(() => {}) 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 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 // 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 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 } }) 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', 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) // (opened, then its items: wait for both, the card shows the order before its items arrive)
await page.waitForFunction(([id, due]) => { await page.waitForFunction(([id, due]) => {
+90 -2
View File
@@ -1,6 +1,8 @@
// Waiter app suite (plan phase 4): sign-in v2 on the phone (4.2): each login mode, wrong PIN, // 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; // 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. // Starts its own backend (:8061) and the venue-mode dev build (:5181), phone-sized Edge.
// node waiter.mjs // node waiter.mjs
import path from 'node:path' import path from 'node:path'
@@ -13,7 +15,7 @@ const vite = await startViteNative({ port: 5181, backendUrl: backend.url })
const APP = 'http://localhost:5181' const APP = 'http://localhost:5181'
const TOKEN_KEY = 'xenia:dev:token' const TOKEN_KEY = 'xenia:dev:token'
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) 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 = [] const errors = []
let failures = 0 let failures = 0
@@ -156,6 +158,92 @@ try {
await api('DELETE', `/api/orders/${o3.id}`, { token: boss }).catch(() => {}) await api('DELETE', `/api/orders/${o3.id}`, { token: boss }).catch(() => {})
await a.goto(`${APP}/tables`) 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 ─ // ── 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: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByRole('button', { name: /Αποσύνδεση/ }).last().click() await a.getByRole('button', { name: /Αποσύνδεση/ }).last().click()
+2
View File
@@ -27,6 +27,7 @@ import OrderLogPage from './pages/OrderLogPage'
import { NotificationProvider } from './context/NotificationContext' import { NotificationProvider } from './context/NotificationContext'
import { LiveProvider } from './context/LiveContext' import { LiveProvider } from './context/LiveContext'
import ConnectivityBar from './components/ConnectivityBar' import ConnectivityBar from './components/ConnectivityBar'
import RefusedLines from './components/RefusedLines'
import AppShell from './components/AppShell' import AppShell from './components/AppShell'
import UpdatePrompt from './components/UpdatePrompt' import UpdatePrompt from './components/UpdatePrompt'
import InstallAppDialog from './components/InstallAppDialog' import InstallAppDialog from './components/InstallAppDialog'
@@ -473,6 +474,7 @@ function Routed() {
<LiveProvider> <LiveProvider>
<NotificationProvider> <NotificationProvider>
<ConnectivityBar /> <ConnectivityBar />
<RefusedLines />
{/* Native builds ship their UI in the app bundle — no service worker to update */} {/* Native builds ship their UI in the app bundle — no service worker to update */}
{deliveryMode() !== 'native' && <UpdatePrompt />} {deliveryMode() !== 'native' && <UpdatePrompt />}
<InstallAppDialog /> <InstallAppDialog />
@@ -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 (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
<div className="modal-handle" />
<h2 className="modal-title">{product.name}</h2>
<p className="modal-price">{Number(totalPrice).toFixed(2)} €</p>
{/* ── Checkbox options with optional sub-choices ── */}
{options.length > 0 && (
<section className="modal-section">
<h3>Επιλογές</h3>
{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 (
<div key={opt.id}>
<label className="modal-option">
<input type="checkbox" checked={isChecked} onChange={() => toggleOption(opt)} />
<span>{opt.name}</span>
{(opt.extra_cost ?? 0) !== 0 && (
<span className="option-price">{opt.extra_cost > 0 ? '+' : ''}{Number(opt.extra_cost).toFixed(2)} €</span>
)}
</label>
{isChecked && hasSubs && (
<div style={{
marginLeft: 24, marginTop: 4, marginBottom: 6,
padding: '8px 12px', borderRadius: 8,
borderLeft: `3px solid ${subMissing ? '#ef4444' : '#6366f1'}`,
}}>
{subMissing && <p style={{ fontSize: 12, color: '#ef4444', margin: '0 0 4px' }}>— απαιτείται επιλογή</p>}
{opt.sub_choices.map((sub, si) => (
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
<input type="radio" name={`optsub-${opt.id}`}
checked={selectedOptionSubs[opt.id]?.name === sub.name}
onChange={() => selectOptionSub(opt.id, sub)} />
<span>{sub.name}</span>
{(sub.extra_cost ?? 0) !== 0 && (
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
)}
</label>
))}
</div>
)}
</div>
)
})}
</section>
)}
{/* ── Preference sets ── */}
{preferenceSets.map(ps => {
const missing = !isPrefSetComplete(ps)
if (ps.allow_multi_select) {
const selected = multiPreferences[ps.id] ?? []
return (
<section key={ps.id} className="modal-section"
style={missing ? { border: '1.5px solid #ef4444', borderRadius: 10, padding: '10px 12px' } : {}}>
<h3 style={{ color: missing ? '#ef4444' : undefined }}>
{ps.name}
{missing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— επιλέξτε τουλάχιστον μία</span>}
</h3>
{ps.choices.map(ch => {
const entry = selected.find(e => e.choice.id === ch.id)
const isChecked = !!entry
return (
<div key={ch.id} style={{ marginBottom: 6 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<label className="modal-option" style={{ flex: 1 }}>
<input type="checkbox" checked={isChecked}
onChange={() => toggleMultiChoice(ps.id, ch)} />
<span>{ch.name}</span>
{(ch.extra_cost ?? 0) !== 0 && (
<span className="option-price">{ch.extra_cost > 0 ? '+' : ''}{Number(ch.extra_cost).toFixed(2)} €</span>
)}
</label>
{isChecked && ps.allow_choice_quantity && (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
<button className="qty-btn" style={{ width: 28, height: 28, fontSize: 16 }}
onClick={() => setMultiChoiceQty(ps.id, ch.id, -1)}>−</button>
<span style={{ minWidth: 20, textAlign: 'center', fontWeight: 600, fontSize: 15 }}>{entry.qty}</span>
<button className="qty-btn" style={{ width: 28, height: 28, fontSize: 16 }}
onClick={() => setMultiChoiceQty(ps.id, ch.id, 1)}>+</button>
</div>
)}
</div>
</div>
)
})}
</section>
)
}
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 (
<section key={ps.id} className="modal-section"
style={missing ? { border: '1.5px solid #ef4444', borderRadius: 10, padding: '10px 12px' } : {}}>
<h3 style={{ color: missing ? '#ef4444' : undefined }}>
{ps.name}
{missing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— απαιτείται επιλογή</span>}
</h3>
{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 (
<div key={ch.id}>
<label className="modal-option">
<input type="radio" name={`pref-${ps.id}`} checked={isSelected}
onChange={() => selectPreference(ps.id, ch)} />
<span>{ch.name}</span>
{(ch.extra_cost ?? 0) !== 0 && (
<span className="option-price">{ch.extra_cost > 0 ? '+' : ''}{Number(ch.extra_cost).toFixed(2)} €</span>
)}
</label>
{isSelected && hasSubs && (
<div style={{
marginLeft: 24, marginTop: 4, marginBottom: 6,
padding: '8px 12px', borderRadius: 8,
borderLeft: `3px solid ${subMissing ? '#ef4444' : '#6366f1'}`,
}}>
{subMissing && <p style={{ fontSize: 12, color: '#ef4444', margin: '0 0 4px' }}>— απαιτείται επιλογή</p>}
{ch.sub_choices.map((sub, si) => (
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
<input type="radio" name={`sub-${ch.id}`}
checked={selectedSubChoices[ch.id]?.name === sub.name}
onChange={() => selectSubChoice(ch.id, sub)} />
<span>{sub.name}</span>
{(sub.extra_cost ?? 0) !== 0 && (
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
)}
</label>
))}
</div>
)}
</div>
)
})}
{showSharedSubset && (
<div style={{
marginTop: 8, marginLeft: 8, padding: '8px 12px', borderRadius: 8,
borderLeft: `3px solid ${sharedMissing ? '#ef4444' : '#6366f1'}`,
}}>
<p style={{ fontSize: 13, fontWeight: 600, marginBottom: 6, color: sharedMissing ? '#ef4444' : '#4338ca' }}>
{ps.shared_subset.name}
{sharedMissing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— απαιτείται επιλογή</span>}
</p>
{ps.shared_subset.choices.map((sub, si) => (
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
<input type="radio" name={`shared-${ps.id}`}
checked={selectedSharedSubs[ps.id]?.name === sub.name}
onChange={() => selectSharedSub(ps.id, sub)} />
<span>{sub.name}</span>
{(sub.extra_cost ?? 0) !== 0 && (
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
)}
</label>
))}
</div>
)}
</section>
)
})}
{/* ── Remove ingredients ── */}
{ingredients.length > 0 && (
<section className="modal-section">
<h3>Αφαίρεση υλικών</h3>
{ingredients.map(ing => (
<label key={ing.id} className="modal-option modal-option--remove">
<input type="checkbox" checked={removedIngredients.includes(ing.name)}
onChange={() => toggleIngredient(ing)} />
<span>χωρίς {ing.name}</span>
</label>
))}
</section>
)}
<section className="modal-section">
<h3>Σημείωση</h3>
<textarea className="modal-notes" placeholder="π.χ. χωρίς αλάτι..."
value={notes} onChange={e => setNotes(e.target.value)} rows={2} />
</section>
{isDecimal ? (
<div className="qty-decimal-panel">
{/* Main ‒ / value / + row */}
<div className="modal-qty">
<button className="qty-btn" onClick={() => setQuantity(q => Math.max(unitCfg.min, Math.round((q - unitCfg.step) * 1000) / 1000))}>−</button>
{editingQty ? (
<input
ref={qtyRef}
type="number"
inputMode="decimal"
className="qty-decimal-input"
value={qtyInput}
onChange={e => setQtyInput(e.target.value)}
onBlur={() => {
const v = parseFloat(qtyInput)
if (!isNaN(v) && v >= unitCfg.min) setQuantity(Math.round(v * 1000) / 1000)
setEditingQty(false)
}}
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
autoFocus
/>
) : (
<span className="qty-value" style={{ cursor: 'text', minWidth: 64 }}
onClick={() => { setQtyInput(String(quantity)); setEditingQty(true) }}>
{fmtQty(quantity, unitCfg)}&thinsp;<span style={{ fontSize: 14, fontWeight: 500, opacity: 0.7 }}>{unitCfg.label}</span>
</span>
)}
<button className="qty-btn" onClick={() => setQuantity(q => Math.round((q + unitCfg.step) * 1000) / 1000)}>+</button>
</div>
{/* Quick preset values */}
<div className="qty-presets">
{unitCfg.presets.map(v => (
<button key={v} className={`qty-preset-btn${quantity === v ? ' qty-preset-btn--active' : ''}`}
onClick={() => setQuantity(v)}>
{fmtQty(v, unitCfg)}
</button>
))}
</div>
{/* Quick ± offset buttons */}
<div className="qty-offsets">
{unitCfg.offsets.map(off => (
<button key={`+${off}`} className="qty-offset-btn qty-offset-btn--add"
onClick={() => setQuantity(q => Math.round((q + off) * 1000) / 1000)}>
+{fmtQty(off, unitCfg)}
</button>
))}
</div>
<div className="qty-offsets">
{unitCfg.offsets.map(off => (
<button key={`-${off}`} className="qty-offset-btn qty-offset-btn--sub"
onClick={() => setQuantity(q => Math.max(unitCfg.min, Math.round((q - off) * 1000) / 1000))}>
−{fmtQty(off, unitCfg)}
</button>
))}
</div>
</div>
) : (
<div className="modal-qty">
<button className="qty-btn" onClick={() => setQuantity(q => Math.max(1, q - 1))}>−</button>
<span className="qty-value">{quantity}</span>
<button className="qty-btn" onClick={() => setQuantity(q => q + 1)}>+</button>
</div>
)}
{!allPrefsSelected && (
<p style={{ color: '#ef4444', fontSize: 13, textAlign: 'center', marginTop: 8 }}>
Επιλέξτε: {unselectedPrefs.map(ps => ps.name).join(', ')}
</p>
)}
{optionSubsMissing && (
<p style={{ color: '#ef4444', fontSize: 13, textAlign: 'center', marginTop: 4 }}>
Επιλέξτε υπο-επιλογή για τις επιλεγμένες επιλογές
</p>
)}
<button className="btn btn--primary btn--lg" onClick={handleAdd} disabled={!canAdd}
style={{ width: '100%', marginTop: 16, opacity: canAdd ? 1 : 0.45 }}>
Προσθήκη στην παραγγελία
</button>
</div>
</div>
)
}
+1 -1
View File
@@ -1508,7 +1508,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
<button onClick={() => setQty(q => q + 1)} style={{ width: 52, height: 52, border: 'none', background: 'transparent', fontSize: 22, fontWeight: 500, cursor: 'pointer', color: 'var(--text)' }}>+</button> <button onClick={() => setQty(q => q + 1)} style={{ width: 52, height: 52, border: 'none', background: 'transparent', fontSize: 22, fontWeight: 500, cursor: 'pointer', color: 'var(--text)' }}>+</button>
</div> </div>
)} )}
<button onClick={handleAdd} disabled={!canAdd} style={{ <button data-testid="drawer-add" onClick={handleAdd} disabled={!canAdd} style={{
flex: 1, height: 52, borderRadius: 26, flex: 1, height: 52, borderRadius: 26,
background: canAdd ? 'var(--accent)' : 'var(--bg3)', background: canAdd ? 'var(--accent)' : 'var(--bg3)',
border: 'none', color: canAdd ? 'var(--accent-fg)' : 'var(--muted)', border: 'none', color: canAdd ? 'var(--accent-fg)' : 'var(--muted)',
+12 -10
View File
@@ -21,8 +21,7 @@ function describeOptions(selected_options) {
}).filter(Boolean) }).filter(Boolean)
} }
function CartItemSummaryRow({ item, product, onEdit }) { function CartItemSummaryRow({ item, product, price, estimated, onEdit }) {
const price = (item.unit_price ?? product?.base_price ?? 0) * item.quantity
const opts = describeOptions(item.selected_options) const opts = describeOptions(item.selected_options)
const removed = item.removed_ingredients || [] const removed = item.removed_ingredients || []
@@ -58,7 +57,7 @@ function CartItemSummaryRow({ item, product, onEdit }) {
)} )}
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}> <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(price)}</span> <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{estimated ? '≈ ' : ''}{fmtEUR(price)}</span>
{onEdit && ( {onEdit && (
<button <button
onClick={onEdit} onClick={onEdit}
@@ -73,11 +72,11 @@ function CartItemSummaryRow({ item, product, onEdit }) {
) )
} }
export default function OrderSummaryModal({ cart, products, orderNote, setOrderNote, onSend, onClose, sending }) { // prices / total: the server's (POST /api/orders/quote, plan step 4.4) or, offline, the menu's
// estimate (`estimated`); priceError: a line the server would refuse.
export default function OrderSummaryModal({ cart, products, prices, total, estimated, priceError, orderNote, setOrderNote, onSend, onClose, sending }) {
const [noteEditing, setNoteEditing] = useState(false) const [noteEditing, setNoteEditing] = useState(false)
const total = cart.reduce((s, item) => s + (item.unit_price ?? 0) * item.quantity, 0)
function getProduct(id) { return products.find(p => p.id === id) } function getProduct(id) { return products.find(p => p.id === id) }
return ( return (
@@ -103,7 +102,7 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
}}> }}>
<div> <div>
<div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>Επισκόπηση Παραγγελίας</div> <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>Επισκόπηση Παραγγελίας</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'} · {fmtEUR(total)}</div> <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'} · {estimated ? '≈ ' : ''}{fmtEUR(total)}</div>
</div> </div>
<button <button
onClick={onClose} onClick={onClose}
@@ -116,11 +115,13 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
{/* Item list */} {/* Item list */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 12px 0' }}> <div style={{ flex: 1, overflowY: 'auto', padding: '12px 12px 0' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.map(item => ( {cart.map((item, i) => (
<CartItemSummaryRow <CartItemSummaryRow
key={item._key} key={item._key}
item={item} item={item}
product={getProduct(item.product_id)} product={getProduct(item.product_id)}
price={prices?.[i] ?? 0}
estimated={estimated}
/> />
))} ))}
</div> </div>
@@ -178,9 +179,10 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
{/* Total */} {/* Total */}
<div style={{ marginTop: 12, marginBottom: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 4px', borderTop: '1px solid var(--border)' }}> <div style={{ marginTop: 12, marginBottom: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 4px', borderTop: '1px solid var(--border)' }}>
<span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>Σύνολο</span> <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{estimated ? 'Σύνολο (εκτίμηση)' : 'Σύνολο'}</span>
<span style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(total)}</span> <span data-testid="summary-total" data-estimated={estimated ? 'true' : 'false'} style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{estimated ? '≈ ' : ''}{fmtEUR(total)}</span>
</div> </div>
{priceError && <div style={{ fontSize: 12, color: 'var(--danger)', padding: '0 4px 8px' }}>{priceError}</div>}
</div> </div>
{/* Footer — Send button */} {/* Footer — Send button */}
@@ -190,6 +190,8 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
return ( return (
<div <div
className="product-btn" className="product-btn"
data-testid="product-card"
data-name={product.name}
style={{ position: 'relative' }} style={{ position: 'relative' }}
onClick={handleClick} onClick={handleClick}
{...longPress.handlers} {...longPress.handlers}
@@ -223,6 +225,7 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
alignItems: 'center', justifyContent: 'center', alignItems: 'center', justifyContent: 'center',
}}> }}>
<button <button
data-testid="product-quick-add"
onPointerDown={e => e.stopPropagation()} onPointerDown={e => e.stopPropagation()}
onClick={e => { e.stopPropagation(); onQuickAdd(product) }} onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
style={{ style={{
@@ -0,0 +1,54 @@
import { useEffect, useState } from 'react'
import db from '../db/posdb'
import { clearRefusedLines, refusedLines } from '../services/offlineOrders'
import useAuthStore from '../store/authStore'
// Lines of an order taken offline that the server refused when the phone came back (plan
// step 4.4): a product taken off the menu meanwhile, an option deleted, a price change not
// allowed. They are never dropped silently: this sheet lists them, with the reason, until the
// waiter confirms they've seen them (and dealt with the table).
export default function RefusedLines() {
const token = useAuthStore(s => s.token)
const [lines, setLines] = useState([])
useEffect(() => {
if (!token) return undefined
const load = () => refusedLines().then(async list => {
const named = await Promise.all(list.map(async l => {
const t = l.tableId != null ? await db.pos_tables.get(Number(l.tableId)).catch(() => null) : null
return { ...l, table: t ? (t.label || `T${t.number}`) : null }
}))
setLines(named)
}).catch(() => {})
load()
window.addEventListener('refused-lines', load)
return () => window.removeEventListener('refused-lines', load)
}, [token])
if (!token || lines.length === 0) return null
return (
<div className="modal-overlay" data-testid="refused-lines">
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
<div className="modal-handle" />
<h2 className="modal-title">Δεν στάλθηκαν</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>
Τα παρακάτω πάρθηκαν χωρίς σύνδεση και ο server δεν τα δέχτηκε. Ελέγξτε τα τραπέζια.
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16, maxHeight: '45vh', overflowY: 'auto' }}>
{lines.map((l, i) => (
<div key={i} data-testid="refused-line" style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 12, padding: '10px 12px' }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
{l.product} ×{l.quantity}
{l.table && <span style={{ color: 'var(--muted)', fontWeight: 500 }}> · {l.table}</span>}
</div>
<div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 3 }}>{l.reason}</div>
</div>
))}
</div>
<button className="btn btn--primary" style={{ width: '100%' }} data-testid="refused-lines-ok" onClick={() => clearRefusedLines()}>
Το είδα
</button>
</div>
</div>
)
}
+75 -3
View File
@@ -13,6 +13,11 @@ import useConnectionStore from '../store/connectionStore'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import { queueOfflineOrder } from '../services/offlineOrders' import { queueOfflineOrder } from '../services/offlineOrders'
import { assetUrl } from '../config/server' import { assetUrl } from '../config/server'
import { LineError, estimate, wireLine } from '@xenia/api'
// A cart item whose option is not on the menu any more (4.4: lines go by id)
const lineErrorText = err => `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού. Αφαιρέστε το και προσθέστε το ξανά.`
const money = v => `${Number(v || 0).toFixed(2)} €`
// ─── Global Course Modal ────────────────────────────────────────────────────── // ─── Global Course Modal ──────────────────────────────────────────────────────
@@ -110,6 +115,28 @@ function CustomerCountModal({ value, onChange, onClose }) {
) )
} }
// ─── The cart's total (4.4) ───────────────────────────────────────────────────
// The server's price (POST /api/orders/quote) when online; offline, or until it answers, the
// menu's prices as an estimate. A line the server would refuse shows its reason here.
function CartTotal({ priced, estimatedTotal, offline }) {
const exact = !!priced?.data
return (
<div data-testid="cart-total" data-estimated={exact ? 'false' : 'true'}
style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>
{exact ? 'Σύνολο' : offline ? 'Σύνολο (εκτίμηση, χωρίς σύνδεση)' : 'Σύνολο (εκτίμηση)'}
</span>
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>
{exact ? money(priced.data.total) : `≈ ${money(estimatedTotal)}`}
</span>
</div>
{priced?.error && <div data-testid="cart-total-error" style={{ fontSize: 12, color: 'var(--danger)' }}>{priced.error}</div>}
</div>
)
}
// ───────────────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────────────
const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' } const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
@@ -156,6 +183,7 @@ export default function AddItemsPage() {
const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server
const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer
const quickToastTimer = useRef(null) const quickToastTimer = useRef(null)
const [quote, setQuote] = useState(null) // { key, data, error } — the server's price of the cart (4.4)
useEffect(() => { useEffect(() => {
async function load() { async function load() {
@@ -283,6 +311,34 @@ export default function AddItemsPage() {
setEditItem(null) setEditItem(null)
} }
// The cart as the lines the server prices (4.4): what was chosen, by id — never a price
function cartLines() {
return cart.map(({ _key, _drawerState, ...item }) => wireLine(item, getProduct(item.product_id)))
}
const estimates = cart.map(item => estimate(item, getProduct(item.product_id)))
const estimatedTotal = estimates.reduce((s, v) => s + v, 0)
// The server's price of the cart while it's on screen (debounced); offline → the estimate
const showPrices = (cartOpen || summaryOpen) && cart.length > 0 && !isOffline
const quoteKey = showPrices ? JSON.stringify([orderId, cart.map(({ _key, _drawerState, ...i }) => i)]) : null
useEffect(() => {
if (!quoteKey) return undefined
let lines
try { lines = cartLines() } catch (err) {
const t = setTimeout(() => setQuote({ key: quoteKey, data: null, error: err instanceof LineError ? lineErrorText(err) : String(err) }), 0)
return () => clearTimeout(t)
}
const t = setTimeout(() => {
client.post('/api/orders/quote', {
lines, order_id: orderId ?? undefined, order_type: isStandalone ? orderType : 'here',
}, { noOverride: true })
.then(r => setQuote({ key: quoteKey, data: r.data, error: null }))
.catch(err => setQuote({ key: quoteKey, data: null, error: apiError(err, '') }))
}, 250)
return () => clearTimeout(t)
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps
const priced = quote && quote.key === quoteKey ? quote : null
async function sendOrder() { async function sendOrder() {
if (cart.length === 0) return if (cart.length === 0) return
setSending(true) setSending(true)
@@ -293,12 +349,14 @@ export default function AddItemsPage() {
// ── Offline path (not supported for standalone orders) ──────────────────── // ── Offline path (not supported for standalone orders) ────────────────────
if (isOffline && !isStandalone) { if (isOffline && !isStandalone) {
try { try {
// queued by id; the server prices them when the phone is back (the menu's price is shown as an estimate)
const items = cart.map(({ _key, _drawerState, ...item }) => { const items = cart.map(({ _key, _drawerState, ...item }) => {
const product = products.find(p => p.id === item.product_id) const product = products.find(p => p.id === item.product_id)
return { return {
...item, ...item,
_wire: wireLine(item, product),
_productSnapshot: product ? { name: product.name } : null, _productSnapshot: product ? { name: product.name } : null,
_unitPrice: product?.base_price ?? 0, _unitPrice: estimate({ ...item, quantity: 1 }, product),
_unitType: product?.unit_type ?? null, _unitType: product?.unit_type ?? null,
} }
}) })
@@ -312,7 +370,7 @@ export default function AddItemsPage() {
setTimeout(() => navigate('/tables'), 1200) setTimeout(() => navigate('/tables'), 1200)
} catch (err) { } catch (err) {
console.error('[offline order] save failed:', err) console.error('[offline order] save failed:', err)
setError('Σφάλμα αποθήκευσης offline παραγγελίας') setError(err instanceof LineError ? lineErrorText(err) : 'Σφάλμα αποθήκευσης offline παραγγελίας')
} finally { } finally {
setSending(false) setSending(false)
} }
@@ -321,6 +379,12 @@ export default function AddItemsPage() {
// ── Online path ─────────────────────────────────────────────────────────── // ── Online path ───────────────────────────────────────────────────────────
try { try {
let lines
try { lines = cartLines() } catch (err) {
if (!(err instanceof LineError)) throw err
setError(lineErrorText(err))
return
}
let activeOrderId = orderId let activeOrderId = orderId
if (!activeOrderId) { if (!activeOrderId) {
const orderPayload = isStandalone const orderPayload = isStandalone
@@ -332,7 +396,7 @@ export default function AddItemsPage() {
} }
const res = await client.post(`/api/orders/${activeOrderId}/items`, { const res = await client.post(`/api/orders/${activeOrderId}/items`, {
items: cart.map(({ _key, _drawerState, ...item }) => item), lines,
order_note: orderNote || null, order_note: orderNote || null,
customer_count: customerCount ?? null, customer_count: customerCount ?? null,
}) })
@@ -542,6 +606,7 @@ export default function AddItemsPage() {
{/* Cart button with badge */} {/* Cart button with badge */}
<button <button
className="icon-btn" className="icon-btn"
data-testid="cart-open"
style={{ position: 'relative' }} style={{ position: 'relative' }}
onClick={() => setCartOpen(true)} onClick={() => setCartOpen(true)}
> >
@@ -801,6 +866,9 @@ export default function AddItemsPage() {
{/* Drawer footer */} {/* Drawer footer */}
<div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.length > 0 && (
<CartTotal priced={priced} estimatedTotal={estimatedTotal} offline={isOffline} />
)}
<button <button
className="btn btn--primary btn--lg" className="btn btn--primary btn--lg"
style={{ width: '100%' }} style={{ width: '100%' }}
@@ -831,6 +899,10 @@ export default function AddItemsPage() {
<OrderSummaryModal <OrderSummaryModal
cart={cart} cart={cart}
products={products} products={products}
prices={priced?.data ? priced.data.lines.map(l => l.total) : estimates}
total={priced?.data ? priced.data.total : estimatedTotal}
estimated={!priced?.data}
priceError={priced?.error ?? null}
orderNote={orderNote} orderNote={orderNote}
setOrderNote={setOrderNote} setOrderNote={setOrderNote}
onSend={() => { setSummaryOpen(false); sendOrder() }} onSend={() => { setSummaryOpen(false); sendOrder() }}
+134 -48
View File
@@ -1,5 +1,12 @@
import db from '../db/posdb' import db from '../db/posdb'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors'
// Orders taken offline (plan step 4.4): the cart lines are queued by id (`_wire`, built when
// the order was taken: @xenia/api wireLine) and priced by the server when they reach it; the
// synthetic order shows the menu's price as an estimate until then. A line the server refuses
// is taken out, the rest is sent, and the refused one is kept in `kv.refused_lines` with the
// reason for the waiter to see (components/RefusedLines.jsx), never dropped silently.
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────────
@@ -66,6 +73,7 @@ export async function queueOfflineOrder({ tableId, items, waiterId }) {
quantity: item.quantity, quantity: item.quantity,
unit_price: item._unitPrice || 0, unit_price: item._unitPrice || 0,
unit_type: item._unitType || null, unit_type: item._unitType || null,
_estimated: true,
status: 'active', status: 'active',
kds_status: 'pending', kds_status: 'pending',
selected_options: item.selected_options || [], selected_options: item.selected_options || [],
@@ -238,30 +246,20 @@ async function _flushLegacyOfflineOrders() {
await db.offline_orders.update(entry.localId, { synced: 1 }) await db.offline_orders.update(entry.localId, { synced: 1 })
continue continue
} }
// True legacy record — handle directly // True legacy record (before v0.6.4): it can't be priced by the server (no lines by id)
if (!entry.items.some(i => i._wire)) {
await keepRefused(entry.items.map(i => refusedEntry(i, entry.tableId, entry.uuid, OLD_FORMAT)))
await db.offline_orders.update(entry.localId, { synced: 1 })
await db.pos_orders.delete(`offline_${entry.uuid}`)
continue
}
try { try {
let orderId = null const { orderId } = await sendLines(entry.items, { tableId: entry.tableId, uuid: entry.uuid }, () => tableOrderId(entry.tableId))
try { if (orderId == null) {
const statusRes = await client.get(`/api/tables/${entry.tableId}/status`) await db.offline_orders.update(entry.localId, { synced: 1 })
orderId = statusRes.data.active_order_id ?? null await db.pos_orders.delete(`offline_${entry.uuid}`)
} catch { /* offline */ } continue
if (!orderId) {
const createRes = await client.post('/api/orders/', { table_id: entry.tableId })
orderId = createRes.data?.id
if (!orderId) throw new Error('no order id returned')
} }
await client.post(`/api/orders/${orderId}/items`, {
items: entry.items.map(item => ({
product_id: item.product_id,
quantity: item.quantity,
selected_options: item.selected_options || [],
removed_ingredients: item.removed_ingredients || [],
notes: item.notes || '',
})),
})
const fullRes = await client.get(`/api/orders/${orderId}`) const fullRes = await client.get(`/api/orders/${orderId}`)
await db.offline_orders.update(entry.localId, { synced: 1, serverId: orderId }) await db.offline_orders.update(entry.localId, { synced: 1, serverId: orderId })
await db.pos_orders.delete(`offline_${entry.uuid}`) await db.pos_orders.delete(`offline_${entry.uuid}`)
@@ -295,32 +293,30 @@ async function _flushLegacyOfflinePayments() {
// ── Op handlers ─────────────────────────────────────────────────────────────── // ── Op handlers ───────────────────────────────────────────────────────────────
async function _flushCreateOrder(op, idMap) { async function _flushCreateOrder(op, idMap) {
// Already synced by legacy drain? Check idMap or look for real order const synthetic = await db.pos_orders.get(op.localOrderId)
let orderId = null // queued before 4.4: nothing the server can price → all refused, no empty order opened
try { if (!op.items.some(i => i._wire)) {
const statusRes = await client.get(`/api/tables/${op.tableId}/status`) await keepRefused(op.items.map(i => refusedEntry(i, op.tableId, op.uuid, OLD_FORMAT)))
orderId = statusRes.data.active_order_id ?? null for (const it of synthetic?.items ?? []) idMap[it.id] = REFUSED
} catch { /* offline */ } await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
await db.offline_ops.update(op.localId, { synced: 1 })
if (!orderId) { await db.pos_orders.delete(op.localOrderId)
const createRes = await client.post('/api/orders/', { table_id: op.tableId }) return
orderId = createRes.data?.id
if (!orderId) throw new Error('no order id returned')
} }
// the table's open order (one may have been opened meanwhile), or a new one, once a line
await client.post(`/api/orders/${orderId}/items`, { // is known to be accepted
items: op.items.map(item => ({ const { orderId, sent } = await sendLines(op.items, { tableId: op.tableId, uuid: op.uuid }, () => tableOrderId(op.tableId))
product_id: item.product_id,
quantity: item.quantity,
selected_options: item.selected_options || [],
removed_ingredients: item.removed_ingredients || [],
notes: item.notes || '',
})),
})
// Capture synthetic order item ids BEFORE deleting it // Capture synthetic order item ids BEFORE deleting it
const syntheticOrder = await db.pos_orders.get(op.localOrderId) const allLocalIds = synthetic?.items?.map(i => i.id) ?? []
const syntheticItemIds = syntheticOrder?.items?.map(i => i.id) ?? [] allLocalIds.forEach((id, i) => { if (!sent.includes(i)) idMap[id] = REFUSED })
if (orderId == null) { // every line refused: nothing opened on the table
await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
await db.offline_ops.update(op.localId, { synced: 1 })
await db.pos_orders.delete(op.localOrderId)
return
}
const syntheticItemIds = allLocalIds.filter((_, i) => sent.includes(i))
// Fetch full hydrated order // Fetch full hydrated order
const fullRes = await client.get(`/api/orders/${orderId}`) const fullRes = await client.get(`/api/orders/${orderId}`)
@@ -330,7 +326,7 @@ async function _flushCreateOrder(op, idMap) {
idMap[op.localOrderId] = orderId idMap[op.localOrderId] = orderId
// Map offline item ids → real item ids by position (last N added server items) // Map offline item ids → real item ids by position (last N added server items)
if (syntheticItemIds.length > 0 && serverOrder.items) { if (syntheticItemIds.length > 0 && serverOrder.items && sent.length > 0) {
const addedServerItems = serverOrder.items.slice(-syntheticItemIds.length) const addedServerItems = serverOrder.items.slice(-syntheticItemIds.length)
syntheticItemIds.forEach((localItemId, idx) => { syntheticItemIds.forEach((localItemId, idx) => {
if (addedServerItems[idx]) { if (addedServerItems[idx]) {
@@ -393,14 +389,16 @@ async function _flushPay(op, idMap) {
return return
} }
// Resolve local item ids // Resolve local item ids (items the server refused when the order was sent can't be paid:
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid) // the waiter sees them in the refused list)
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid).filter(id => id !== REFUSED)
const stillLocal = resolvedLocal.filter(id => String(id).startsWith('offline_item_')) const stillLocal = resolvedLocal.filter(id => String(id).startsWith('offline_item_'))
if (stillLocal.length > 0) { if (stillLocal.length > 0) {
throw new Error('offline item ids not yet resolved') throw new Error('offline item ids not yet resolved')
} }
const allIds = [...resolvedLocal, ...(op.realItemIds || [])] const allIds = [...resolvedLocal, ...(op.realItemIds || [])]
if (!allIds.length) { await db.offline_ops.update(op.localId, { synced: 1 }); return }
await client.post(`/api/orders/${realOrderId}/pay-offline`, { await client.post(`/api/orders/${realOrderId}/pay-offline`, {
uuid: op.uuid, uuid: op.uuid,
item_ids: allIds, item_ids: allIds,
@@ -410,6 +408,94 @@ async function _flushPay(op, idMap) {
await db.offline_ops.update(op.localId, { synced: 1 }) await db.offline_ops.update(op.localId, { synced: 1 })
} }
// ── Sending queued lines; refused ones come back to the waiter ──────────────────
const REFUSED_KEY = 'refused_lines'
const REFUSED = 'refused'
const OLD_FORMAT = 'Παλιά μορφή παραγγελίας: προσθέστε το ξανά'
/** Lines the server refused when an offline order was sent: [{ at, tableId, product, quantity, reason }]. */
export async function refusedLines() {
return (await db.kv.get(REFUSED_KEY))?.value ?? []
}
export async function clearRefusedLines() {
await db.kv.put({ key: REFUSED_KEY, value: [] })
window.dispatchEvent(new Event('refused-lines'))
}
async function keepRefused(entries) {
if (!entries.length) return
await db.kv.put({ key: REFUSED_KEY, value: [...(await refusedLines()), ...entries] })
window.dispatchEvent(new Event('refused-lines'))
}
/** The line a refusal names (order.line.*, order.not_sold_here carry `line`, 1-based), or null
* when the error isn't about one line (network, server error, the whole order). */
function refusedLine(err, count) {
const status = err?.response?.status
const line = err?.response?.data?.error?.params?.line
const refusal = status === 400 || status === 404 || status === 409 || status === 422
return refusal && Number.isInteger(line) && line >= 1 && line <= count ? line : null
}
/** Post `pending` lines; a refused line is taken out (with its reason) and the rest posted again. */
async function postLines(pending, refused, ctx, post) {
while (pending.length) {
try {
await post(pending.map(({ item }) => item._wire))
return pending
} catch (err) {
const n = refusedLine(err, pending.length)
if (n == null) throw err
const [{ item }] = pending.splice(n - 1, 1)
refused.push(refusedEntry(item, ctx.tableId, ctx.uuid, apiError(err, 'Ο server δεν το δέχτηκε')))
}
}
return pending
}
/**
* Send queued items, priced by the server. A quote first finds the lines the server refuses
* (so no order is opened for nothing), then `getOrderId()` gives the order and the rest is
* added (a line refused there is taken out too). An item queued before 4.4 (no `_wire`) can't
* be priced and is refused straight away. Network errors throw and the op stays queued (its
* refusals are found again next time). Returns { orderId (null: all refused), sent: [indexes] }.
*/
async function sendLines(items, ctx, getOrderId) {
const refused = items.filter(item => !item._wire).map(item => refusedEntry(item, ctx.tableId, ctx.uuid, OLD_FORMAT))
const opts = { noOverride: true }
let pending = items.map((item, index) => ({ item, index })).filter(({ item }) => item._wire)
pending = await postLines(pending, refused, ctx, lines => client.post('/api/orders/quote', { lines }, opts))
let orderId = null
if (pending.length) {
orderId = await getOrderId()
pending = await postLines(pending, refused, ctx, lines => client.post(`/api/orders/${orderId}/items`, { lines }, opts))
}
await keepRefused(refused)
return { orderId, sent: pending.map(({ index }) => index) }
}
async function tableOrderId(tableId) {
let orderId = null
try {
orderId = (await client.get(`/api/tables/${tableId}/status`)).data.active_order_id ?? null
} catch { /* offline */ }
if (!orderId) {
orderId = (await client.post('/api/orders/', { table_id: tableId })).data?.id
if (!orderId) throw new Error('no order id returned')
}
return orderId
}
function refusedEntry(item, tableId, uuid, reason) {
return {
at: new Date().toISOString(), uuid, tableId,
product: item._productSnapshot?.name ?? `#${item.product_id}`,
quantity: item.quantity, reason,
}
}
// ─── Queue size ─────────────────────────────────────────────────────────────── // ─── Queue size ───────────────────────────────────────────────────────────────
export async function pendingOrderCount() { export async function pendingOrderCount() {