feat: staff apps show the menu in the reader's language (plan 6R.L)

The waiters' phones and the counter show categories, products and every
choice (quick options, extras and sub-choices, preferences, shared sets,
ingredients, groups) in the signed-in person's language, falling back to
the stored text. Display only: carts, lines, tickets and the kitchen keep
the venue's text (ids, sub-choices by stored name). In the venue's own
language nothing changes.

- @xenia/access: menuText / useMenuText (mt, mt.choice, mt.line, mt.matches)
- /api/pos/menu carries translations for products, categories and choices
- shared ProductDialog takes a text() prop (the counter passes useMenuText)
- search finds a product by its name in any language (counter, waiter)
- waiter: useMenuNames for sent lines; picker, drawer, cart, summary,
  table lines, quantity / price history, favourites setup
- counter: categories, cards, dialog, cart lines, table lines, payment rows
- tests: access menuText, ordering search, test_pos per-language,
  e2e waiter.mjs and terminal.mjs 6R.L blocks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 20:18:10 +02:00
co-authored by Claude Opus 5.5
parent f107deca8c
commit 0840247768
29 changed files with 518 additions and 123 deletions
+1 -1
View File
@@ -80,7 +80,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) | | `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) |
| `routers/identity.py`; manager `pages/Settings/sections/IdentitySettings.jsx`, `shell/useIdentity.js`, `shell/VenueIdentity.jsx` | The venue's identity (6R.14): `GET/PUT /api/identity` = `venue.name` + the JSON setting `venue.identity` (slogan, up to 12 named colours, logos main / light / dark / icon as media ids — registered usage `identity` —, guest Wi-Fi, contact details). Signage gets it in `_venue()` (`identity`, plus the venue's `timezone`) and every screen is told on a change. The manager reads it once (`useIdentity`) and `VenueIdentity` feeds `VenueColoursProvider` (`@xenia/ui`): every `ColourField` offers the venue's colours first. `wifiQr()` (`@xenia/signage/logic`) writes the join-the-network QR text. **In every app (6R.20):** bootstrap `venue.identity` = {colour (the first), slogan, logo, logo_light, logo_dark, icon}; `venue.theme = identity` → `applyVenueTheme('identity', colour)` (`@xenia/ui/venueAccent.js`: accent tokens for light and dark from one colour, readable foregrounds) in the waiter app and every terminal screen (else the terminal keeps its own accent); a customer display look's `brand: identity` (its accent and the identity's logo when the look has none); a signage logo widget without a picture shows the main logo (kept on the TV) | | `routers/identity.py`; manager `pages/Settings/sections/IdentitySettings.jsx`, `shell/useIdentity.js`, `shell/VenueIdentity.jsx` | The venue's identity (6R.14): `GET/PUT /api/identity` = `venue.name` + the JSON setting `venue.identity` (slogan, up to 12 named colours, logos main / light / dark / icon as media ids — registered usage `identity` —, guest Wi-Fi, contact details). Signage gets it in `_venue()` (`identity`, plus the venue's `timezone`) and every screen is told on a change. The manager reads it once (`useIdentity`) and `VenueIdentity` feeds `VenueColoursProvider` (`@xenia/ui`): every `ColourField` offers the venue's colours first. `wifiQr()` (`@xenia/signage/logic`) writes the join-the-network QR text. **In every app (6R.20):** bootstrap `venue.identity` = {colour (the first), slogan, logo, logo_light, logo_dark, icon}; `venue.theme = identity` → `applyVenueTheme('identity', colour)` (`@xenia/ui/venueAccent.js`: accent tokens for light and dark from one colour, readable foregrounds) in the waiter app and every terminal screen (else the terminal keeps its own accent); a customer display look's `brand: identity` (its accent and the identity's logo when the look has none); a signage logo widget without a picture shows the main logo (kept on the TV) |
| `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it | | `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3) and the menu's languages (`menuLanguages.js` = `core/menu_languages.py`, 6.4: el + en; a product's own name is its base text, translations in `products.translations` / `categories.translations` are for customer screens only; tests compare the lists), and `<Allergens>` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | | `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3) and the menu's languages (`menuLanguages.js` = `core/menu_languages.py`, 6.4: el + en; a product's own name is its base text, translations in `products.translations` / `categories.translations` are for customer screens; since 6R.L also the staff apps' **display**: `useMenuText()` → `mt(item)`, `mt.choice(product, storedName)`, `mt.line(product, storedName)`, unchanged when the reader's language is the venue's; carts, lines and tickets keep the stored names and ids; tests compare the lists), and `<Allergens>` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests |
| `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) | | `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) |
| `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. | | `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. |
+4 -2
View File
@@ -27,8 +27,10 @@ language). Translations add the other language:
Quick options are kept by their base name (they are recreated on every product save, so ids Quick options are kept by their base name (they are recreated on every product save, so ids
change). A missing translation shows the base text, whatever its language — never Latin letters, change). A missing translation shows the base text, whatever its language — never Latin letters,
never a machine translation (owner). Who sees translations: the customer-facing screens (QR menu, never a machine translation (owner). Who sees translations: the customer-facing screens (QR menu,
order app, menu tablet, signage menu boards). Tickets, the kitchen display, the counter and the order app, menu tablet, signage menu boards), and since 6R.L the waiters' phones and the counter
waiters' phones keep the base text (the staff's). show menu names in the staff member's language, for display only (`@xenia/access` useMenuText;
`routers/pos.py` sends every text per language). Order lines, tickets and the kitchen display keep
the base text (the venue's): apps send ids, and sub-choices by their stored name.
""" """
from __future__ import annotations from __future__ import annotations
+23 -8
View File
@@ -76,16 +76,28 @@ def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
# ── menu ──────────────────────────────────────────────────────────────────── # ── menu ────────────────────────────────────────────────────────────────────
def _tr(x) -> dict:
"""A choice's names per language {lang: text} (6R.L: the counter shows them in the cashier's
language; display only, lines keep ids and the venue's names). A row or a sub-choice's dict."""
from core.menu_languages import _load, names_of
if isinstance(x, dict):
return {k: v for k, v in _load(x.get("translations")).items() if isinstance(v, str)}
return names_of(x)
def _subs_out(raw): def _subs_out(raw):
return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default"))} return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default")),
"translations": _tr(s)}
for s in pos_cart._subs(raw)] for s in pos_cart._subs(raw)]
def _product_out(p, price: float, prices: dict | None = None) -> dict: def _product_out(p, price: float, prices: dict | None = None) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731 shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
from core import allergens, sales_points from core import allergens, sales_points
from core.menu_languages import of as product_tr
return { return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url, "id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"translations": product_tr(p), # 6R.L: {lang: {name, description}}; every choice below has its own
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()}, "price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON], "sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece", "base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
@@ -95,18 +107,19 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict:
"primary_category_id": p.primary_category_id, "primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships], "categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order, "sort_order": p.sort_order,
"quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)} "quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple),
"translations": _tr(q)}
for q in sorted(p.quick_options, key=lambda q: q.sort_order)], for q in sorted(p.quick_options, key=lambda q: q.sort_order)],
"options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple), "options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple),
"multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices)} "multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices), "translations": _tr(o)}
for o in p.options], for o in p.options],
"prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select), "prefs": [{"id": ps.id, "name": ps.name, "translations": _tr(ps), "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select),
"shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None), "shared": ({"name": shared(ps)["name"], "translations": _tr(shared(ps)), "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None),
"choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2), "choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2),
"disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices)} "disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices), "translations": _tr(c)}
for c in ps.choices]} for c in ps.choices]}
for ps in p.preference_sets], for ps in p.preference_sets],
"ingredients": [{"id": i.id, "name": i.name} for i in p.ingredients], "ingredients": [{"id": i.id, "name": i.name, "translations": _tr(i)} for i in p.ingredients],
} }
@@ -142,12 +155,14 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
default = pos_cart.point_for(settings["default_order_type"]) default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all() cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
from services import price_changes, split_bills from services import price_changes, split_bills
from core.menu_languages import of as product_tr
return { return {
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
"settings": {**settings, "price_change": price_changes.mode(db), "settings": {**settings, "price_change": price_changes.mode(db),
# 6F.6: splitting a bill by amount (the level and the most equal parts) # 6F.6: splitting a bill by amount (the level and the most equal parts)
"split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)}, "split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)},
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order} "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order,
"translations": product_tr(c)}
for c in cats], for c in cats],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON}) "products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
for i, p in enumerate(products)], for i, p in enumerate(products)],
+29 -1
View File
@@ -59,12 +59,40 @@ def test_menu_lists_what_a_cashier_sells(client, till, menu):
burger = next(p for p in data["products"] if p["name"] == "Burger") burger = next(p for p in data["products"] if p["name"] == "Burger")
assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"] assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"]
assert "cost_simple" not in burger and "cost_breakdown" not in burger assert "cost_simple" not in burger and "cost_breakdown" not in burger
assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True} assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True, "translations": {}}
assert burger["prefs"][0]["shared"]["name"] == "Side" and burger["prefs"][0]["choices"][1]["disables_shared"] is True assert burger["prefs"][0]["shared"]["name"] == "Side" and burger["prefs"][0]["choices"][1]["disables_shared"] is True
assert {c["name"] for c in data["categories"]} >= {"Food", "Drinks"} assert {c["name"] for c in data["categories"]} >= {"Food", "Drinks"}
assert data["settings"]["default_order_type"] == "takeaway" assert data["settings"]["default_order_type"] == "takeaway"
def test_menu_carries_every_name_per_language_lines_keep_the_venues(client, db, till, menu, on_shift):
"""6R.L: the counter gets each text per language to show in the cashier's language; what it
sends is ids (and sub-choices by their stored name), so the order keeps the venue's text."""
from models.order import OrderItem
m = menu
m["burger"].translations = json.dumps({"el": {"name": "Μπέργκερ", "description": "Μοσχάρι"}, "en": {"name": "Burger"}})
m["food"].translations = json.dumps({"el": {"name": "Φαγητό"}})
m["rare"].translations = json.dumps({"el": "Λίγο ψημένο"})
m["cook"].translations = json.dumps({"el": "Ψήσιμο"})
m["cook"].shared_subset = json.dumps({"name": "Side", "translations": {"el": "Συνοδευτικό"},
"choices": [{"name": "Fries", "is_default": True, "translations": {"el": "Πατάτες"}},
{"name": "Salad", "extra_cost": 1.0}]})
db.commit()
data = client.get("/api/pos/menu", headers=till["h"]).json()
burger = next(p for p in data["products"] if p["id"] == m["burger"].id)
assert burger["translations"]["el"] == {"name": "Μπέργκερ", "description": "Μοσχάρι"}
pref = burger["prefs"][0]
assert pref["translations"] == {"el": "Ψήσιμο"} and pref["shared"]["translations"] == {"el": "Συνοδευτικό"}
assert pref["shared"]["subs"][0]["translations"] == {"el": "Πατάτες"} and pref["shared"]["subs"][1]["translations"] == {}
assert next(c for c in pref["choices"] if c["id"] == m["rare"].id)["translations"] == {"el": "Λίγο ψημένο"}
assert next(c for c in data["categories"] if c["id"] == m["food"].id)["translations"] == {"el": {"name": "Φαγητό"}}
assert burger["quick"][0]["translations"] == {} and burger["ingredients"][0]["translations"] == {}
r = sale(client, till, [burger_line(m)], [{"method": "cash"}], cash_given=20)
assert r.status_code == 201, r.text
item = db.query(OrderItem).filter(OrderItem.order_id == r.json()["order_id"]).one()
assert [o["name"] for o in json.loads(item.selected_options)] == ["Rare", "Fries"] # the stored names, not a translation
def test_quote_prices_on_the_server(client, till, menu): def test_quote_prices_on_the_server(client, till, menu):
m = menu m = menu
line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}], line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}],
+3 -1
View File
@@ -8,6 +8,7 @@
// useAllowed('ordering.orders.cancel') → 'yes' | 'approve' (a manager's PIN) | 'no' (4.3) // useAllowed('ordering.orders.cancel') → 'yes' | 'approve' (a manager's PIN) | 'no' (4.3)
// <Can perm="…" fallback={…}> · <RequireModule module="…"> // <Can perm="…" fallback={…}> · <RequireModule module="…">
// //
// useMenuText() → mt(item) / mt.choice(product, name) menu names in the reader's language (6R.L)
// SALES_POINTS, IN_PERSON, DIGITAL where an order is sold (phase 3S) // SALES_POINTS, IN_PERSON, DIGITAL where an order is sold (phase 3S)
// ALLERGENS, allergenList, setAllergen the 14 EU allergens (6.3) // ALLERGENS, allergenList, setAllergen the 14 EU allergens (6.3)
// //
@@ -20,4 +21,5 @@ export { OverrideHost } from './OverrideHost.jsx'
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js' export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js' export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js'
export { Allergens } from './Allergens.jsx' export { Allergens } from './Allergens.jsx'
export { DEFAULT_LANGUAGE, MENU_LANGUAGES, inLanguage, shownText, slotOf, translatedLanguages } from './menuLanguages.js' export { DEFAULT_LANGUAGE, MENU_LANGUAGES, inLanguage, shownText, slotOf, translatedLanguages, ownText, choiceTexts, menuText } from './menuLanguages.js'
export { useMenuText } from './useMenuText.js' // 6R.L: staff apps in the reader's language (display only)
+70
View File
@@ -24,3 +24,73 @@ const filled = v => (typeof v === 'string' && v.trim() ? v.trim() : '')
* that has one, else `fallback` (the row's stored text, for items never given a language). */ * that has one, else `fallback` (the row's stored text, for items never given a language). */
export const shownText = (texts, venueLanguage, fallback = '') => export const shownText = (texts, venueLanguage, fallback = '') =>
filled(texts?.[venueLanguage]) || MENU_LANGUAGES.map(l => filled(texts?.[l])).find(Boolean) || filled(fallback) filled(texts?.[venueLanguage]) || MENU_LANGUAGES.map(l => filled(texts?.[l])).find(Boolean) || filled(fallback)
// ── Staff apps in the device's language (plan 6R.L, owner 2026-11-21) ───────────────────────
// The waiters' phones and the counter show menu names in the reader's language (the user's,
// else the device's, else the venue's), falling back to the shown text. **Display only:** the
// rows keep their `name` (the venue's text), carts and lines are built from it and from ids, so
// order lines and tickets keep the venue's text whatever the phone shows. When the reader's
// language is the venue's, every text is exactly the stored one (nothing changes).
//
// `translations` shapes (as the backend sends them): a product / category
// {lang: {name, description}}, a choice / ingredient / group / sub-choice {lang: text}.
/** An item's own text in `lang` (no fallback): '' when it has none. */
export function ownText(item, lang, field = 'name') {
const v = item?.translations?.[lang]
if (typeof v === 'string') return field === 'name' ? filled(v) : ''
return filled(v?.[field])
}
/** base name → its text in `lang`, for every choice inside a product (quick options, extras and
* their sub-choices, ingredients, preferences, their choices, sub-choices and shared set,
* groups), whatever the app's menu shape. Lines and carts keep choices by these base names. */
export function choiceTexts(product, lang) {
const out = new Map()
const seen = new Set()
const walk = v => {
if (!v || typeof v !== 'object' || seen.has(v)) return
seen.add(v)
if (Array.isArray(v)) { v.forEach(walk); return }
if (v !== product && typeof v.name === 'string' && v.translations) {
const text = ownText(v, lang)
if (text && !out.has(v.name)) out.set(v.name, text)
}
for (const [k, x] of Object.entries(v)) if (k !== 'translations' && k !== 'image') walk(x)
}
walk(product)
return out
}
const QTY_SUFFIX = /^(.*) x(\d+)$/
/** The menu-text function for a reader: `mt(item, field?)` the item's text (product, category,
* choice…), `mt.choice(product, name)` a choice kept by its base name (a cart entry, a sent
* line's option, a removed ingredient; "name x2" keeps its count), `mt.same` true when nothing
* is translated (the reader's language is the venue's, or not a menu language), `mt.line(product,
* stored)` an ordered line's name. */
export function menuText(lang, venueLanguage) {
const same = !lang || lang === venueLanguage || !MENU_LANGUAGES.includes(lang)
const cache = new WeakMap()
const mt = (item, field = 'name') => {
if (!item) return ''
const stored = item[field] ?? ''
return same ? stored : (ownText(item, lang, field) || stored)
}
mt.choice = (product, name) => {
if (same || !product || !name) return name
let map = cache.get(product)
if (!map) { map = choiceTexts(product, lang); cache.set(product, map) }
if (map.has(name)) return map.get(name)
const m = QTY_SUFFIX.exec(name)
return m && map.has(m[1]) ? `${map.get(m[1])} x${m[2]}` : name
}
/** A line already ordered: its product's text in the reader's language, else the name it was
* ordered under (`stored`: the line's own record, kept when there is no translation). */
mt.line = (product, stored) => (same || !product ? stored : (ownText(product, lang) || stored))
/** Search: does the item's text in either language contain `q` (lower case)? */
mt.matches = (item, q) => !q || [item?.name, ...MENU_LANGUAGES.map(l => ownText(item, l))].some(s => s && s.toLowerCase().includes(q))
mt.same = same
mt.lang = lang
return mt
}
+13
View File
@@ -0,0 +1,13 @@
// The menu-text function for the signed-in reader (plan 6R.L): their language (user, else device,
// else venue: what the app's texts are in) against the venue's. See menuText in menuLanguages.js.
import { useMemo } from 'react'
import { useLanguage } from '@xenia/i18n'
import { useAccess } from './hooks.js'
import { menuText } from './menuLanguages.js'
export function useMenuText() {
const { venue } = useAccess()
const { language } = useLanguage()
const venueLanguage = venue?.language
return useMemo(() => menuText(language, venueLanguage), [language, venueLanguage])
}
+77
View File
@@ -0,0 +1,77 @@
// Staff apps in the device's language (plan 6R.L): display only, the venue's text kept underneath.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { choiceTexts, menuText } from '../src/menuLanguages.js'
const pita = {
id: 1, name: 'Πίτα γύρος', description: 'Με τζατζίκι',
translations: { el: { name: 'Πίτα γύρος' }, en: { name: 'Gyros pita' } }, // no English description
quick_options: [{ id: 5, name: 'Χωρίς κρεμμύδι', translations: { en: 'No onion' } }],
options: [{ id: 7, name: 'Πατάτες', translations: { el: 'Πατάτες', en: 'Fries' },
sub_choices: [{ name: 'Λίγες', translations: { en: 'A few' } }, { name: 'Πολλές' }] }],
ingredients: [{ id: 9, name: 'Ντομάτα', translations: { en: 'Tomato' } }],
preference_sets: [{ id: 3, name: 'Κρέας', translations: { en: 'Meat' },
choices: [{ id: 30, name: 'Χοιρινό', translations: { en: 'Pork' } }],
shared_subset: { name: 'Ψήσιμο', translations: { en: 'Cooking' }, choices: [{ name: 'Καλοψημένο', translations: { en: 'Well done' } }] } }],
image: { id: 4, name: 'photo.jpg' },
}
test('an English phone at a Greek venue sees English, Greek where there is none', () => {
const mt = menuText('en', 'el')
assert.equal(mt.same, false)
assert.equal(mt(pita), 'Gyros pita')
assert.equal(mt(pita, 'description'), 'Με τζατζίκι')
assert.equal(mt(pita.options[0]), 'Fries')
assert.equal(mt(pita.options[0].sub_choices[1]), 'Πολλές')
assert.equal(mt({ name: 'Ορεκτικά', translations: { en: { name: 'Starters' } } }), 'Starters')
})
test('a phone in the venue language shows the stored text, untouched', () => {
const mt = menuText('el', 'el')
assert.equal(mt.same, true)
assert.equal(mt(pita), 'Πίτα γύρος')
assert.equal(mt({ name: 'Only English', translations: { en: { name: 'Only English' } } }), 'Only English')
assert.equal(mt.choice(pita, 'Πατάτες'), 'Πατάτες')
})
test('a language that is not a menu language changes nothing', () => {
assert.equal(menuText('de', 'el').same, true)
assert.equal(menuText(undefined, 'el').same, true)
})
test('choices kept by their base name are shown translated; counts kept', () => {
const mt = menuText('en', 'el')
assert.equal(mt.choice(pita, 'Χωρίς κρεμμύδι'), 'No onion')
assert.equal(mt.choice(pita, 'Χωρίς κρεμμύδι x2'), 'No onion x2')
assert.equal(mt.choice(pita, 'Λίγες'), 'A few')
assert.equal(mt.choice(pita, 'Ντομάτα'), 'Tomato')
assert.equal(mt.choice(pita, 'Χοιρινό'), 'Pork')
assert.equal(mt.choice(pita, 'Καλοψημένο'), 'Well done')
assert.equal(mt.choice(pita, 'Πολλές'), 'Πολλές') // no English: the base text
assert.equal(mt.choice(pita, 'Unknown'), 'Unknown')
assert.equal(mt.choice(null, 'Λίγες'), 'Λίγες')
})
test('the counter menu shape (quick / options.subs / prefs.shared) is walked too', () => {
const counter = { id: 1, name: 'Καφές', translations: {}, prefs: [{ id: 1, name: 'Ζάχαρη', translations: { en: 'Sugar' },
choices: [{ id: 2, name: 'Γλυκός', translations: { en: 'Sweet' }, subs: [] }],
shared: { name: 'Γάλα', translations: { en: 'Milk' }, subs: [{ name: 'Φρέσκο', translations: { en: 'Fresh' } }] } }] }
const map = choiceTexts(counter, 'en')
assert.deepEqual([...map], [['Ζάχαρη', 'Sugar'], ['Γλυκός', 'Sweet'], ['Γάλα', 'Milk'], ['Φρέσκο', 'Fresh']])
assert.equal(choiceTexts(pita, 'en').has('photo.jpg'), false)
})
test('an ordered line: the product translation, else the name it was ordered under', () => {
assert.equal(menuText('en', 'el').line(pita, 'Πίτα γύρος (παλιά)'), 'Gyros pita')
assert.equal(menuText('en', 'el').line({ name: 'Νέο', translations: {} }, 'Παλιό'), 'Παλιό')
assert.equal(menuText('en', 'el').line(undefined, 'Παλιό'), 'Παλιό')
assert.equal(menuText('el', 'el').line(pita, 'Πίτα γύρος (παλιά)'), 'Πίτα γύρος (παλιά)')
})
test('search finds an item by either language', () => {
const mt = menuText('en', 'el')
assert.ok(mt.matches(pita, 'gyros'))
assert.ok(mt.matches(pita, 'γύρος'))
assert.ok(!mt.matches(pita, 'burger'))
assert.ok(mt.matches(pita, ''))
})
+20 -16
View File
@@ -3,6 +3,8 @@
// product with preferences to pick opens it on tap. The price shown is the backend's (the menu // product with preferences to pick opens it on tap. The price shown is the backend's (the menu
// price, then the app's quote endpoint through `fetchQuote(lines)`), never added up here. // price, then the app's quote endpoint through `fetchQuote(lines)`), never added up here.
// `product` is the counter's product shape (routers/pos._product_out). // `product` is the counter's product shape (routers/pos._product_out).
// `text` (6R.L): how a name is shown, `text(item, field?)` (the counter passes `useMenuText()`, the
// cashier's language); display only: choices are still picked and sent by id / stored name.
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react' import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
@@ -33,7 +35,9 @@ function Price({ value }) {
// fetchQuote(lines) → the server's quote ({lines, total}); each app its endpoint (the menu tablet's // fetchQuote(lines) → the server's quote ({lines, total}); each app its endpoint (the menu tablet's
// has in-store prices and no discounts, 6.6) // has in-store prices and no discounts, 6.6)
export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) { const asStored = (item, field = 'name') => item?.[field] ?? ''
export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel, text = asStored }) {
const { t } = useTranslation('common') const { t } = useTranslation('common')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const unit = unitOf(product) const unit = unitOf(product)
@@ -47,7 +51,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
const add = () => { onAdd(line); onClose() } const add = () => { onAdd(line); onClose() }
return ( return (
<Dialog open onClose={onClose} size="lg" title={product.name} description={product.description || undefined} <Dialog open onClose={onClose} size="lg" title={text(product)} description={text(product, 'description') || undefined}
footer={<> footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('ordering.dialog.close')}</Button> <Button variant="secondary" size="lg" onClick={onClose}>{t('ordering.dialog.close')}</Button>
<Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add"> <Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add">
@@ -84,35 +88,35 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
const need = missing.find(m => m.kind === 'pref' && m.name === ps.name) const need = missing.find(m => m.kind === 'pref' && m.name === ps.name)
return ( return (
<div key={ps.id} className="grid gap-3" data-pref={ps.id}> <div key={ps.id} className="grid gap-3" data-pref={ps.id}>
<Section title={ps.name} hint={need ? t('ordering.dialog.pickOne') : null}> <Section title={text(ps)} hint={need ? t('ordering.dialog.pickOne') : null}>
{ps.choices.map(c => { {ps.choices.map(c => {
const p = picked.find(x => x.id === c.id) const p = picked.find(x => x.id === c.id)
return ( return (
<span key={c.id} className="flex items-center gap-1"> <span key={c.id} className="flex items-center gap-1">
<button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}> <button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}>
{c.name} <Price value={c.price} /> {text(c)} <Price value={c.price} />
</button> </button>
{ps.multi && p && ( {ps.multi && p && (
<Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} /> <Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={text(c)} />
)} )}
</span> </span>
) )
})} })}
</Section> </Section>
{one?.subs?.length > 0 && ( {one?.subs?.length > 0 && (
<Section title={one.name}> <Section title={text(one)}>
{one.subs.map(s => ( {one.subs.map(s => (
<button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}> <button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}>
{s.name} <Price value={s.price} /> {text(s)} <Price value={s.price} />
</button> </button>
))} ))}
</Section> </Section>
)} )}
{ps.shared && one && !one.disables_shared && ( {ps.shared && one && !one.disables_shared && (
<Section title={ps.shared.name}> <Section title={text(ps.shared)}>
{ps.shared.subs.map(s => ( {ps.shared.subs.map(s => (
<button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}> <button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}>
{s.name} <Price value={s.price} /> {text(s)} <Price value={s.price} />
</button> </button>
))} ))}
</Section> </Section>
@@ -128,10 +132,10 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
return ( return (
<span key={q.id} className="flex items-center gap-1"> <span key={q.id} className="flex items-center gap-1">
<button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}> <button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}>
{q.name} <Price value={q.price} /> {text(q)} <Price value={q.price} />
</button> </button>
{q.allow_multiple && n > 0 && ( {q.allow_multiple && n > 0 && (
<Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={q.name} /> <Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={text(q)} />
)} )}
</span> </span>
) )
@@ -147,15 +151,15 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
<span key={o.id} className="grid gap-2"> <span key={o.id} className="grid gap-2">
<span className="flex items-center gap-1"> <span className="flex items-center gap-1">
<button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}> <button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}>
{o.name} <Price value={o.price} /> {text(o)} <Price value={o.price} />
</button> </button>
{o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={o.name} />} {o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={text(o)} />}
</span> </span>
{s && o.subs.length > 0 && ( {s && o.subs.length > 0 && (
<span className="flex flex-wrap gap-1 pl-3"> <span className="flex flex-wrap gap-1 pl-3">
{o.subs.map(sub => ( {o.subs.map(sub => (
<button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}> <button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}>
{sub.name} <Price value={sub.price} /> {text(sub)} <Price value={sub.price} />
</button> </button>
))} ))}
</span> </span>
@@ -170,7 +174,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
<Section title={t('ordering.dialog.without')}> <Section title={t('ordering.dialog.without')}>
{product.ingredients.map(i => ( {product.ingredients.map(i => (
<button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}> <button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}>
{sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{i.name} {sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{text(i)}
</button> </button>
))} ))}
</Section> </Section>
@@ -189,7 +193,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
</div> </div>
</div> </div>
{missing.length > 0 && ( {missing.length > 0 && (
<p className="text-label text-warning-ink" data-testid="dialog-missing">{t('ordering.dialog.missing', { list: missing.map(m => m.name).join(', ') })}</p> <p className="text-label text-warning-ink" data-testid="dialog-missing">{t('ordering.dialog.missing', { list: missing.map(m => (text.choice ? text.choice(product, m.name) : m.name)).join(', ') })}</p>
)} )}
</div> </div>
</Dialog> </Dialog>
+3 -1
View File
@@ -23,7 +23,9 @@ export function productsIn(products, categoryId) {
export function searchProducts(products, query) { export function searchProducts(products, query) {
const words = fold(query).split(/\s+/).filter(Boolean) const words = fold(query).split(/\s+/).filter(Boolean)
if (!words.length) return [] if (!words.length) return []
return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) }) // the stored name or its text in any language (6R.L: a cashier may type in theirs)
const texts = p => [p.name, ...Object.values(p.translations ?? {}).map(v => (typeof v === 'string' ? v : v?.name))].filter(Boolean).map(fold)
return products.filter(p => { const all = texts(p); return words.every(w => all.some(name => name.includes(w))) })
} }
/** Categories that have products, in their order (top level first, then by sort order). */ /** Categories that have products, in their order (top level first, then by sort order). */
+12
View File
@@ -21,3 +21,15 @@ test('a product with a preference to pick needs the dialog; the line holds ids o
assert.equal('unit_price' in line, false) assert.equal('unit_price' in line, false)
assert.deepEqual(line.removed, [9]) assert.deepEqual(line.removed, [9])
}) })
test('search: the stored name or its text in any language (6R.L)', async () => {
const { searchProducts } = await import('../src/cart.js')
const list = [
{ id: 1, name: 'Πίτα γύρος', translations: { el: { name: 'Πίτα γύρος' }, en: { name: 'Gyros pita' } } },
{ id: 2, name: 'Freddo', translations: {} },
]
assert.deepEqual(searchProducts(list, 'gyros').map(p => p.id), [1])
assert.deepEqual(searchProducts(list, 'γυρος πιτα').map(p => p.id), [1])
assert.deepEqual(searchProducts(list, 'fred').map(p => p.id), [2])
assert.deepEqual(searchProducts(list, 'gyros fred').map(p => p.id), [])
})
+5 -3
View File
@@ -3,24 +3,26 @@
import { Minus, Plus } from 'lucide-react' import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { IconButton, Select } from '@xenia/ui' import { IconButton, Select } from '@xenia/ui'
import { useMenuText } from '@xenia/access'
import { DISCOUNTS, unitOf } from './logic/cart' import { DISCOUNTS, unitOf } from './logic/cart'
export default function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) { export default function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const mt = useMenuText() // 6R.L: names in the cashier's language; the line keeps ids
const unit = product ? unitOf(product) : null const unit = product ? unitOf(product) : null
const step = unit ? unit.step : 1 const step = unit ? unit.step : 1
const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×` const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×`
return ( return (
<div className="px-3 py-2 border-b border-line grid gap-1" data-testid="cart-line" data-product={line.product_id}> <div className="px-3 py-2 border-b border-line grid gap-1" data-testid="cart-line" data-product={line.product_id}>
<div className="flex items-start gap-2"> <div className="flex items-start gap-2">
<span className="flex-1 min-w-0 text-body font-medium text-ink">{product?.name ?? priced?.name}</span> <span className="flex-1 min-w-0 text-body font-medium text-ink">{product ? mt(product) : priced?.name}</span>
<span className="text-body text-ink" data-testid="line-total">{priced ? formatMoney(priced.total) : '…'}</span> <span className="text-body text-ink" data-testid="line-total">{priced ? formatMoney(priced.total) : '…'}</span>
</div> </div>
{priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && ( {priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && (
<div className="text-label text-ink-2 grid"> <div className="text-label text-ink-2 grid">
{priced.entries.map((e, i) => <span key={i}>+ {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''}</span>)} {priced.entries.map((e, i) => <span key={i}>+ {mt.choice(product, e.name)}{e.price ? ` (${formatMoney(e.price)})` : ''}</span>)}
{priced.removed.map(n => <span key={n} className="text-danger-ink">− {n}</span>)} {priced.removed.map(n => <span key={n} className="text-danger-ink">− {mt.choice(product, n)}</span>)}
{priced.notes && <span className="italic">“{priced.notes}”</span>} {priced.notes && <span className="italic">“{priced.notes}”</span>}
</div> </div>
)} )}
+9 -6
View File
@@ -14,7 +14,7 @@
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react' import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n' import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useAllowed, useCan, useModule } from '@xenia/access' import { useAllowed, useCan, useMenuText, useModule } from '@xenia/access'
import { splitChoices as splitChoicesOf } from '@xenia/ordering/split' import { splitChoices as splitChoicesOf } from '@xenia/ordering/split'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui' import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
import { useLiveEvent } from '../../device/context' import { useLiveEvent } from '../../device/context'
@@ -51,6 +51,7 @@ export default function PosScreen() {
function Counter({ menu, t }) { function Counter({ menu, t }) {
const { t: tc } = useTranslation('common') const { t: tc } = useTranslation('common')
const { language } = useLanguage() const { language } = useLanguage()
const mt = useMenuText() // 6R.L: menu names in the cashier's language (display only)
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const [mode, setMode] = useState('sale') // sale | tables | online | receipts const [mode, setMode] = useState('sale') // sale | tables | online | receipts
const [tableId, setTableId] = useState(null) // the open table (tables mode) const [tableId, setTableId] = useState(null) // the open table (tables mode)
@@ -181,7 +182,7 @@ function Counter({ menu, t }) {
<NavButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</NavButton> <NavButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</NavButton>
{categories.map(c => ( {categories.map(c => (
<NavButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}> <NavButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name} {mt(c)}
</NavButton> </NavButton>
))} ))}
</> </>
@@ -266,7 +267,7 @@ function Counter({ menu, t }) {
)} )}
{dialog && ( {dialog && (
<ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)} <ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)} text={mt}
onAdd={line => setCart(c => addLine(c, line))} /> onAdd={line => setCart(c => addLine(c, line))} />
)} )}
</div> </div>
@@ -299,6 +300,8 @@ function NavButton({ active, colour, onClick, children, testId, count, tally })
function ProductCard({ product, onTap, onInfo }) { function ProductCard({ product, onTap, onInfo }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const mt = useMenuText() // 6R.L: the cashier's language, display only
const name = mt(product)
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const unit = unitOf(product) const unit = unitOf(product)
return ( return (
@@ -306,13 +309,13 @@ function ProductCard({ product, onTap, onInfo }) {
<button type="button" onClick={onTap} className="flex-1 flex flex-col text-left active:scale-[0.98] transition-transform duration-fast"> <button type="button" onClick={onTap} className="flex-1 flex flex-col text-left active:scale-[0.98] transition-transform duration-fast">
{product.image_url {product.image_url
? <img src={product.image_url} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-2" /> ? <img src={product.image_url} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-2" />
: <span className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-heading text-ink-3" aria-hidden="true">{product.name.slice(0, 1)}</span>} : <span className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-heading text-ink-3" aria-hidden="true">{name.slice(0, 1)}</span>}
<span className="p-2 grid gap-0.5"> <span className="p-2 grid gap-0.5">
<span className="text-body font-medium text-ink line-clamp-2">{product.name}</span> <span className="text-body font-medium text-ink line-clamp-2">{name}</span>
<span className="text-label text-ink-2">{formatMoney(product.price)}{unit ? ` / ${unit.label}` : ''}</span> <span className="text-label text-ink-2">{formatMoney(product.price)}{unit ? ` / ${unit.label}` : ''}</span>
</span> </span>
</button> </button>
<IconButton label={t('pos.checkPrice', { name: product.name })} size="sm" variant="secondary" onClick={onInfo} <IconButton label={t('pos.checkPrice', { name })} size="sm" variant="secondary" onClick={onInfo}
className="absolute top-1.5 right-1.5" data-testid="product-info"> className="absolute top-1.5 right-1.5" data-testid="product-info">
<Info size={16} /> <Info size={16} />
</IconButton> </IconButton>
+3 -1
View File
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from 'react'
import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react' import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, useToast } from '@xenia/ui' import { Button, EmptyState, useToast } from '@xenia/ui'
import { useMenuText } from '@xenia/access'
import client from '../../api/client' import client from '../../api/client'
import CartLine from './CartLine' import CartLine from './CartLine'
import { setLineQty } from './logic/cart' import { setLineQty } from './logic/cart'
@@ -13,6 +14,7 @@ import { useDisplay, useQuote } from './usePos'
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount, amountSplit = null }) { export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount, amountSplit = null }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
const mt = useMenuText() // 6R.L: the cashier's language (the customer display keeps the venue's)
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const toast = useToast() const toast = useToast()
const [paying, setPaying] = useState(false) const [paying, setPaying] = useState(false)
@@ -79,7 +81,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
{paying && quote.quote && ( {paying && quote.quote && (
<PaymentDialog total={quote.quote.total} submit={submit} amountSplit={amountSplit} <PaymentDialog total={quote.quote.total} submit={submit} amountSplit={amountSplit}
rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))} rows={cart.map((l, i) => ({ label: `${l.quantity}× ${mt(byId.get(l.product_id))}`, total: quote.quote.lines[i].total }))}
onClose={() => setPaying(false)} onClose={() => setPaying(false)}
onPaid={result => { onPaid={result => {
setPaying(false) setPaying(false)
+8 -1
View File
@@ -7,6 +7,7 @@ import { useEffect, useState } from 'react'
import { ArrowLeft, Ban, Banknote, Check, CheckCircle2, Lock, Send, Trash2 } from 'lucide-react' import { ArrowLeft, Ban, Banknote, Check, CheckCircle2, Lock, Send, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { useMenuText } from '@xenia/access'
import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xenia/ui' import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import CartLine from './CartLine' import CartLine from './CartLine'
@@ -31,7 +32,13 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on
const [lastPay, setLastPay] = useState(null) const [lastPay, setLastPay] = useState(null)
const [error, setError] = useState('') const [error, setError] = useState('')
const lines = orderLines(order) const mt = useMenuText()
// 6R.L: shown in the cashier's language (the product's and its choices' texts); display only
const lines = orderLines(order).map(l => {
if (mt.same || l.system) return l
const p = byId.get(l.productId)
return { ...l, name: mt.line(p, l.name), options: l.options.map(o => mt.choice(p, o)) }
})
const sums = orderSums(lines) const sums = orderSums(lines)
const state = tableState(table) const state = tableState(table)
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
+1
View File
@@ -49,6 +49,7 @@ export function orderLines(order) {
.filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid' || i.status === 'split') .filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid' || i.status === 'split')
.map(i => ({ .map(i => ({
id: i.id, id: i.id,
productId: i.product_id, // 6R.L: the menu's product, for its name in the cashier's language
name: i.product_name ?? i.product?.name ?? '', name: i.product_name ?? i.product?.name ?? '',
quantity: i.quantity, quantity: i.quantity,
unitType: i.unit_type, unitType: i.unit_type,
+30
View File
@@ -377,6 +377,36 @@ try {
const posSession = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/session')).data) const posSession = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/session')).data)
r.check('3.3a: the shift is the cashier\'s own, with the starting cash', posSession.shift?.starting_cash === 20, JSON.stringify(posSession.shift)) r.check('3.3a: the shift is the cashier\'s own, with the starting cash', posSession.shift?.starting_cash === 20, JSON.stringify(posSession.shift))
// ── 6R.L: the counter in the cashier's language (display only): the manager switches to Greek ──
{
const tr = await api('PUT', `/api/products/${burgerP.id}`, { token: boss, body: {
translations: { en: { name: 'E2E Burger' }, el: { name: 'Μπέργκερ E2E' } },
preference_sets: burgerP.preference_sets.map(ps => ({ ...ps, translations: { el: 'Ψήσιμο' },
choices: ps.choices.map(c => ({ ...c, translations: c.name === 'Well done' ? { el: 'Καλοψημένο' } : {} })) })),
} })
Object.assign(burgerP, tr) // the choices are recreated: new ids for the checks below
await page.evaluate(async () => window.__xeniaClient.patch('/api/auth/me', { language: 'el' }))
await page.reload()
await shown(page, 'pos-screen', 15_000)
await page.getByTestId('pos-search').fill('burg e2e')
const card = page.locator(`[data-testid="pos-product"][data-product="${burgerP.id}"]`)
const cardOk = await card.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
r.check('6R.L: a cashier in Greek sees the dish in Greek (found by its English name too)', cardOk && (await card.innerText()).includes('Μπέργκερ E2E'), cardOk ? await card.innerText() : 'not found')
await page.getByTestId('pos-search').fill('μπεργκ')
r.check('6R.L: …and by its Greek name', await card.waitFor({ timeout: 5000 }).then(() => true).catch(() => false))
if (cardOk) {
await card.getByTestId('product-info').click()
const dialogText = await page.getByTestId('product-dialog').innerText({ timeout: 5000 }).catch(() => '')
r.check('6R.L: the choices in Greek where they have it, as they are where not', dialogText.includes('Ψήσιμο') && dialogText.includes('Καλοψημένο')
&& dialogText.includes('Rare') && !dialogText.includes('Well done'), dialogText.replace(/\s+/g, ' ').slice(0, 200))
await page.keyboard.press('Escape')
}
await page.getByTestId('pos-search').fill('')
await page.evaluate(async () => window.__xeniaClient.patch('/api/auth/me', { language: '' }))
await page.reload()
await shown(page, 'pos-screen', 15_000)
}
await page.getByTestId('pos-search').fill('burg e2e') await page.getByTestId('pos-search').fill('burg e2e')
const burgerCard = page.locator(`[data-testid="pos-product"][data-product="${burgerP.id}"]`) const burgerCard = page.locator(`[data-testid="pos-product"][data-product="${burgerP.id}"]`)
r.check('3.3a: search finds the product by name (words in any order)', await burgerCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) r.check('3.3a: search finds the product by name (words in any order)', await burgerCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
+62
View File
@@ -596,6 +596,68 @@ try {
await a.getByRole('button', { name: /Dark theme/ }).click() await a.getByRole('button', { name: /Dark theme/ }).click()
await a.reload() await a.reload()
// ── 6R.L: the phone shows the menu in the waiter's language (display only); the line, and so
// the ticket, keeps the venue's text. The venue is English here; Maria switches to Greek. ──
{
const cat = await api('POST', '/api/products/categories', { token: boss, body: {
name: 'EN-6RL Cat', sort_order: 99, translations: { en: { name: 'EN-6RL Cat' }, el: { name: 'ΕΛ-6RL Κατηγορία' } } } })
const dish = await api('POST', '/api/products/', { token: boss, body: {
name: 'EN-6RL Dish', base_price: 4, primary_category_id: cat.id, quick_add_enabled: false,
translations: { en: { name: 'EN-6RL Dish' }, el: { name: 'ΕΛ-6RL Πιάτο' } },
quick_options: [{ name: 'EN-6RL extra', price: 0.5, translations: { en: 'EN-6RL extra', el: 'ΕΛ-6RL έξτρα' } },
{ name: 'EN-6RL only', translations: { en: 'EN-6RL only' } }], // no Greek: shown as it is
ingredients: [{ name: 'EN-6RL onion', translations: { en: 'EN-6RL onion', el: 'ΕΛ-6RL κρεμμύδι' } }] } })
const tl = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id)
await a.goto(`${APP}/tables`)
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByTestId('menu-language-el').click()
await waitFor(async () => (await navText()).includes('Τραπέζια'), 8000, 300)
await a.goto(`${APP}/tables/${tl.id}/add?new=1`)
await a.getByRole('button', { name: 'ΕΛ-6RL Κατηγορία', exact: true }).first().click({ timeout: 15_000 }).catch(() => {})
const card = a.locator('[data-testid="product-card"][data-name="EN-6RL Dish"]').first()
const cardShown = await card.waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)
const cardText = cardShown ? await card.innerText() : ''
r.check('6R.L: a phone in Greek at an English venue: the category and the dish in Greek', cardShown && cardText.includes('ΕΛ-6RL Πιάτο') && !cardText.includes('EN-6RL'), cardText.replace(/\s+/g, ' '))
if (cardShown) {
await card.click()
await a.getByTestId('drawer-tab-quick').click({ timeout: 5000 }).catch(() => {})
const drawerText = await waitFor(async () => { const x = await a.locator('body').innerText(); return x.includes('ΕΛ-6RL έξτρα') && x }, 5000, 300) || ''
r.check('6R.L: the choices in Greek, one without a Greek name as it is', drawerText.includes('ΕΛ-6RL έξτρα') && drawerText.includes('EN-6RL only') && !drawerText.includes('EN-6RL extra'),
drawerText.replace(/\s+/g, ' ').slice(0, 300))
await a.getByText('ΕΛ-6RL έξτρα', { exact: true }).first().click()
await a.getByTestId('drawer-tab-ingredients').click({ timeout: 5000 }).catch(() => {})
await a.getByText('ΕΛ-6RL κρεμμύδι', { exact: true }).first().click({ timeout: 5000 }).catch(() => {})
await a.screenshot({ path: path.join(OUT, 'waiter-6rl-drawer.png') })
await a.getByTestId('drawer-add').click()
await a.getByTestId('cart-open').click()
await a.getByRole('button', { name: /^(SEND|SUMMARY|ΑΠΟΣΤΟΛΗ|ΣΥΝΟΨΗ)/ }).last().click()
if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /SEND|ΑΠΟΣΤΟΛΗ/ }).last().click()
}
const sentL = await waitFor(async () => {
const st = await api('GET', `/api/tables/${tl.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)
const line = sentL?.items?.[0]
const opts = line ? JSON.parse(line.selected_options || '[]').map(o => o.name) : []
const removedL = line ? JSON.parse(line.removed_ingredients || '[]') : []
r.check('6R.L: the sent line keeps the venue\'s text (what the ticket prints), not the phone\'s',
line?.product_name === 'EN-6RL Dish' && opts.includes('EN-6RL extra') && removedL.includes('EN-6RL onion'),
JSON.stringify([line?.product_name, opts, removedL]))
await a.goto(`${APP}/tables/${tl.id}`)
const tableText = await waitFor(async () => { const x = await a.locator('body').innerText(); return x.includes('ΕΛ-6RL Πιάτο') && x }, 10_000, 500) || ''
r.check('6R.L: the table\'s sent line shows in Greek on this phone', tableText.includes('ΕΛ-6RL Πιάτο') && !tableText.includes('EN-6RL Dish'), tableText.replace(/\s+/g, ' ').slice(0, 300))
await a.screenshot({ path: path.join(OUT, 'waiter-6rl-table.png') })
await a.goto(`${APP}/tables`)
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByTestId('menu-language-en').click()
await waitFor(async () => (await navText()).includes('Tables'), 8000, 300)
if (sentL) await api('DELETE', `/api/orders/${sentL.id}`, { token: boss }).catch(() => {})
await api('DELETE', `/api/products/${dish.id}`, { token: boss }).catch(() => {})
await api('DELETE', `/api/products/categories/${cat.id}`, { token: boss }).catch(() => {})
}
// ── 6F.7: "ask" (the default): the second phone asks; Continue signs the first one out and it // ── 6F.7: "ask" (the default): the second phone asks; Continue signs the first one out and it
// says why; an order queued offline on the first phone goes out after it signs in again ── // says why; an order queued offline on the first phone goes out after it signs in again ──
{ {
+30 -22
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react' import { useState, useEffect, useRef } from 'react'
import { useCan } from '@xenia/access' import { useCan, useMenuText } from '@xenia/access'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server' import { assetUrl } from '../config/server'
import { money } from '../i18n' import { money } from '../i18n'
@@ -155,6 +155,7 @@ function Row({ selected, onClick, children, right, left, style = {} }) {
function QuickOptionRow({ opt, quickState, setQuickState, compact }) { function QuickOptionRow({ opt, quickState, setQuickState, compact }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const qty = quickState[opt.id] || 0 const qty = quickState[opt.id] || 0
const selected = qty > 0 const selected = qty > 0
const toggleSingle = () => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 })) const toggleSingle = () => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))
@@ -176,7 +177,7 @@ function QuickOptionRow({ opt, quickState, setQuickState, compact }) {
</div> </div>
) : null} ) : null}
> >
<div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{opt.name}</div> <div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(opt)}</div>
{opt.price > 0 && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>+{money(opt.price)}{opt.allow_multiple ? ` ${t('drawer.each')}` : ''}</div>} {opt.price > 0 && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>+{money(opt.price)}{opt.allow_multiple ? ` ${t('drawer.each')}` : ''}</div>}
</Row> </Row>
) )
@@ -186,6 +187,7 @@ function QuickOptionRow({ opt, quickState, setQuickState, compact }) {
function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra, compact }) { function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra, compact }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const sel = extrasState[opt.id] const sel = extrasState[opt.id]
const selected = !!sel const selected = !!sel
const open = expandedExtra === opt.id const open = expandedExtra === opt.id
@@ -249,7 +251,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx
} }
style={compact ? { minHeight: 48 } : {}} style={compact ? { minHeight: 48 } : {}}
> >
<div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{opt.name}</div> <div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(opt)}</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}> <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
{(opt.extra_cost ?? 0) !== 0 ? `+${money(opt.extra_cost)}` : t('drawer.included')} {(opt.extra_cost ?? 0) !== 0 ? `+${money(opt.extra_cost)}` : t('drawer.included')}
{subLabel && <span style={{ color: 'var(--x-warning)', fontWeight: 600 }}> · {subLabel}</span>} {subLabel && <span style={{ color: 'var(--x-warning)', fontWeight: 600 }}> · {subLabel}</span>}
@@ -272,7 +274,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx
left={<RadioDot selected={isSel} />} left={<RadioDot selected={isSel} />}
style={sub.is_compact ? { minHeight: 44 } : {}}> style={sub.is_compact ? { minHeight: 44 } : {}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub.name}</div> <div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(sub)}</div>
{(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0, marginLeft: 6 }}>+{money(sub.extra_cost)}</div>} {(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0, marginLeft: 6 }}>+{money(sub.extra_cost)}</div>}
</div> </div>
</Row> </Row>
@@ -309,7 +311,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx
style={sub.is_compact ? { minHeight: 44 } : {}}> style={sub.is_compact ? { minHeight: 44 } : {}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', minWidth: 0 }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', minWidth: 0 }}>
<div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{sub.name} {mt(sub)}
{subQty > 1 && <span style={{ color: 'var(--muted)', marginLeft: 6, fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>×{subQty}</span>} {subQty > 1 && <span style={{ color: 'var(--muted)', marginLeft: 6, fontSize: 12, fontVariantNumeric: 'tabular-nums' }}>×{subQty}</span>}
</div> </div>
{(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0, marginLeft: 6 }}>+{money(sub.extra_cost)}{sub.allow_multiple ? ` ${t('drawer.each')}` : ''}</div>} {(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0, marginLeft: 6 }}>+{money(sub.extra_cost)}{sub.allow_multiple ? ` ${t('drawer.each')}` : ''}</div>}
@@ -328,6 +330,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx
function IngredientRow({ ing, removedState, setRemovedState, compact }) { function IngredientRow({ ing, removedState, setRemovedState, compact }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const removed = !!removedState[ing.id] const removed = !!removedState[ing.id]
return ( return (
<Row selected={false} <Row selected={false}
@@ -346,7 +349,7 @@ function IngredientRow({ ing, removedState, setRemovedState, compact }) {
{removed ? t('drawer.removed') : t('drawer.remove')} {removed ? t('drawer.removed') : t('drawer.remove')}
</div> </div>
}> }>
<div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: removed ? 'var(--muted)' : 'var(--text)', textDecoration: removed ? 'line-through' : 'none', transition: 'all 120ms', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ing.name}</div> <div style={{ fontSize: compact ? 13 : 15, fontWeight: 500, color: removed ? 'var(--muted)' : 'var(--text)', textDecoration: removed ? 'line-through' : 'none', transition: 'all 120ms', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(ing)}</div>
</Row> </Row>
) )
} }
@@ -355,6 +358,7 @@ function IngredientRow({ ing, removedState, setRemovedState, compact }) {
function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const selChoice = prefs[ps.id] ?? null const selChoice = prefs[ps.id] ?? null
const complete = selChoice != null const complete = selChoice != null
&& !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null) && !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null)
@@ -374,7 +378,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu
return ( return (
<div> <div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '0 2px 10px' }}> <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '0 2px 10px' }}>
<div style={{ fontSize: 14, fontWeight: 700, color: complete ? 'var(--text)' : 'var(--x-danger)' }}>{ps.name}</div> <div style={{ fontSize: 14, fontWeight: 700, color: complete ? 'var(--text)' : 'var(--x-danger)' }}>{mt(ps)}</div>
{!complete && <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--x-danger)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{t('drawer.required')}</div>} {!complete && <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--x-danger)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{t('drawer.required')}</div>}
</div> </div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}> <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
@@ -388,7 +392,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu
<Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />} <Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />}
style={ch.is_compact ? { minHeight: 48 } : {}} style={ch.is_compact ? { minHeight: 48 } : {}}
right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: ch.is_compact ? 12 : 14, fontWeight: 500, color: 'var(--muted)', flexShrink: 0 }}>{ch.extra_cost > 0 ? '+' : ''}{money(ch.extra_cost)}</div> : null}> right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: ch.is_compact ? 12 : 14, fontWeight: 500, color: 'var(--muted)', flexShrink: 0 }}>{ch.extra_cost > 0 ? '+' : ''}{money(ch.extra_cost)}</div> : null}>
<div style={{ fontSize: ch.is_compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ch.name}</div> <div style={{ fontSize: ch.is_compact ? 13 : 15, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(ch)}</div>
</Row> </Row>
{isSel && hasSubs && ( {isSel && hasSubs && (
@@ -401,7 +405,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu
<Row selected={subSel} onClick={() => setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={<RadioDot selected={subSel} />} <Row selected={subSel} onClick={() => setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={<RadioDot selected={subSel} />}
style={sub.is_compact ? { minHeight: 44 } : {}} style={sub.is_compact ? { minHeight: 44 } : {}}
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>+{money(sub.extra_cost)}</div> : null}> right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>+{money(sub.extra_cost)}</div> : null}>
<div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub.name}</div> <div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(sub)}</div>
</Row> </Row>
</div> </div>
) )
@@ -414,7 +418,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu
{showShared && ( {showShared && (
<div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 14, borderLeft: '2px solid rgb(var(--x-warning-rgb) / 0.3)', width: '100%' }}> <div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 14, borderLeft: '2px solid rgb(var(--x-warning-rgb) / 0.3)', width: '100%' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 6px' }}>{ps.shared_subset.name}</div> <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 6px' }}>{mt(ps.shared_subset)}</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}> <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{ps.shared_subset.choices.map((sub, si) => { {ps.shared_subset.choices.map((sub, si) => {
const subSel = sharedSubs[ps.id]?.name === sub.name const subSel = sharedSubs[ps.id]?.name === sub.name
@@ -423,7 +427,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu
<Row selected={subSel} onClick={() => setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={<RadioDot selected={subSel} />} <Row selected={subSel} onClick={() => setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={<RadioDot selected={subSel} />}
style={sub.is_compact ? { minHeight: 44 } : {}} style={sub.is_compact ? { minHeight: 44 } : {}}
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>+{money(sub.extra_cost)}</div> : null}> right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>+{money(sub.extra_cost)}</div> : null}>
<div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub.name}</div> <div style={{ fontSize: sub.is_compact ? 12 : 14, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mt(sub)}</div>
</Row> </Row>
</div> </div>
) )
@@ -549,6 +553,7 @@ function partitionByGroup(items, modifierGroups) {
function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) { function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const extraGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'option') const extraGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'option')
const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(extraGroups.map(g => [g.id, true]))) const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(extraGroups.map(g => [g.id, true])))
const options = product.options || [] const options = product.options || []
@@ -579,7 +584,7 @@ function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExp
const isCollapsed = collapsedGroups[group.id] ?? true const isCollapsed = collapsedGroups[group.id] ?? true
return ( return (
<div key={group.id} style={{ marginBottom: 12 }}> <div key={group.id} style={{ marginBottom: 12 }}>
<PWAGroupHeader name={group.name} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} /> <PWAGroupHeader name={mt(group)} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} />
{!isCollapsed && ( {!isCollapsed && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}> <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{items.map(renderOption)} {items.map(renderOption)}
@@ -596,6 +601,7 @@ function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExp
function IngredientsTab({ product, removedState, setRemovedState }) { function IngredientsTab({ product, removedState, setRemovedState }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const ingGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'ingredient') const ingGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'ingredient')
const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(ingGroups.map(g => [g.id, true]))) const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(ingGroups.map(g => [g.id, true])))
const ingredients = product.ingredients || [] const ingredients = product.ingredients || []
@@ -626,7 +632,7 @@ function IngredientsTab({ product, removedState, setRemovedState }) {
const isCollapsed = collapsedGroups[group.id] ?? true const isCollapsed = collapsedGroups[group.id] ?? true
return ( return (
<div key={group.id} style={{ marginBottom: 12 }}> <div key={group.id} style={{ marginBottom: 12 }}>
<PWAGroupHeader name={group.name} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} /> <PWAGroupHeader name={mt(group)} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} />
{!isCollapsed && ( {!isCollapsed && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}> <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{items.map(renderIng)} {items.map(renderIng)}
@@ -643,6 +649,7 @@ function IngredientsTab({ product, removedState, setRemovedState }) {
function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const prefGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'preference') const prefGroups = (product.modifier_groups || []).filter(g => g.modifier_type === 'preference')
const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(prefGroups.map(g => [g.id, true]))) const [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(prefGroups.map(g => [g.id, true])))
const preferenceSets = product.preference_sets || [] const preferenceSets = product.preference_sets || []
@@ -675,7 +682,7 @@ function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedS
const isCollapsed = collapsedGroups[group.id] ?? true const isCollapsed = collapsedGroups[group.id] ?? true
return ( return (
<div key={group.id} style={{ marginBottom: 16 }}> <div key={group.id} style={{ marginBottom: 16 }}>
<PWAGroupHeader name={group.name} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} /> <PWAGroupHeader name={mt(group)} collapsed={isCollapsed} onToggle={() => toggleGroup(group.id)} colorIdx={gi} />
{!isCollapsed && ( {!isCollapsed && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
{items.map(renderPrefSet)} {items.map(renderPrefSet)}
@@ -1071,6 +1078,7 @@ const FALLBACK_QUICK_NOTES = ['drawer.notes.noSalt', 'drawer.notes.quick', 'draw
export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialState, courses, quickNotes }) { export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialState, courses, quickNotes }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; state and lines keep ids / stored names
const itemFavorites = useWaiterFavoritesStore(s => s.itemFavorites) const itemFavorites = useWaiterFavoritesStore(s => s.itemFavorites)
// A price set before sending needs the key itself (plan 4.3); the manager-approval path for // A price set before sending needs the key itself (plan 4.3); the manager-approval path for
// it comes with server-priced orders (4.4). After sending, the item's actions offer it. // it comes with server-priced orders (4.4). After sending, the item's actions offer it.
@@ -1208,8 +1216,8 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
&& (!sharedSub || sharedSub.name === defaultSharedSub?.name) && (!sharedSub || sharedSub.name === defaultSharedSub?.name)
if (isFullyDefault) { price += delta; return } if (isFullyDefault) { price += delta; return }
const value = `${choice.name}${inlineSub ? ` · ${inlineSub.name}` : ''}${sharedSub ? ` · ${sharedSub.name}` : ''}` const value = `${mt(choice)}${inlineSub ? ` · ${mt(inlineSub)}` : ''}${sharedSub ? ` · ${mt(sharedSub)}` : ''}`
lines.push({ group: 'prefs', label: ps.name, value, qty: 1, price: delta, detail: null }) lines.push({ group: 'prefs', label: mt(ps), value, qty: 1, price: delta, detail: null })
price += delta price += delta
}) })
@@ -1217,7 +1225,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
const q = quickState[opt.id] || 0 const q = quickState[opt.id] || 0
if (q === 0) return if (q === 0) return
const linePrice = opt.price * q const linePrice = opt.price * q
lines.push({ group: 'quick', label: opt.name, qty: q, price: linePrice, detail: null }) lines.push({ group: 'quick', label: mt(opt), qty: q, price: linePrice, detail: null })
price += linePrice price += linePrice
}) })
@@ -1231,19 +1239,19 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
if (!subQty || subQty < 1) return if (!subQty || subQty < 1) return
const sub = opt.sub_choices.find(s => s.name === subName) const sub = opt.sub_choices.find(s => s.name === subName)
const linePrice = ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * subQty const linePrice = ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * subQty
lines.push({ group: 'extras', label: opt.name, qty: subQty, price: linePrice, subName, detail: null }) lines.push({ group: 'extras', label: mt(opt), qty: subQty, price: linePrice, subName: sub ? mt(sub) : subName, detail: null })
price += linePrice price += linePrice
}) })
} else { } else {
const sub = opt.sub_choices?.find(s => s.name === sel.subName) const sub = opt.sub_choices?.find(s => s.name === sel.subName)
const linePrice = ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty const linePrice = ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty
lines.push({ group: 'extras', label: opt.name, qty: sel.qty, price: linePrice, subName: sub?.name ?? null, detail: null }) lines.push({ group: 'extras', label: mt(opt), qty: sel.qty, price: linePrice, subName: sub ? mt(sub) : null, detail: null })
price += linePrice price += linePrice
} }
}) })
ingredients.forEach(ing => { ingredients.forEach(ing => {
if (removedState[ing.id]) lines.push({ group: 'removed', label: ing.name, qty: 1, price: 0, detail: null }) if (removedState[ing.id]) lines.push({ group: 'removed', label: mt(ing), qty: 1, price: 0, detail: null })
}) })
return { summaryLines: lines, totalPrice: (price + priceAdj) * qty } return { summaryLines: lines, totalPrice: (price + priceAdj) * qty }
@@ -1449,7 +1457,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
style={{ width: 48, height: 48, borderRadius: 12, objectFit: 'cover', flexShrink: 0 }} /> style={{ width: 48, height: 48, borderRadius: 12, objectFit: 'cover', flexShrink: 0 }} />
)} )}
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2 }}>{product.name}</div> <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2 }}>{mt(product)}</div>
<div style={{ fontSize: 13, color: priceAdj !== 0 ? 'var(--x-warning)' : 'var(--muted)', marginTop: 2 }}> <div style={{ fontSize: 13, color: priceAdj !== 0 ? 'var(--x-warning)' : 'var(--muted)', marginTop: 2 }}>
{priceAdj !== 0 {priceAdj !== 0
? <><span style={{ textDecoration: 'line-through', opacity: 0.5 }}>{money(product.base_price)}</span> → {money(product.base_price + priceAdj)}</> ? <><span style={{ textDecoration: 'line-through', opacity: 0.5 }}>{money(product.base_price)}</span> → {money(product.base_price + priceAdj)}</>
@@ -1471,7 +1479,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
const isAlert = (tb.id === 'prefs' && prefsTabAlert) || (tb.id === 'favorites' && favTabAlert) const isAlert = (tb.id === 'prefs' && prefsTabAlert) || (tb.id === 'favorites' && favTabAlert)
const tabColor = isAlert ? 'var(--x-danger)' : active ? 'var(--x-warning)' : 'var(--muted)' const tabColor = isAlert ? 'var(--x-danger)' : active ? 'var(--x-warning)' : 'var(--muted)'
return ( return (
<button key={tb.id} ref={el => { tabButtonRefs.current[tb.id] = el }} onClick={() => setActiveTab(tb.id)} style={{ <button key={tb.id} ref={el => { tabButtonRefs.current[tb.id] = el }} onClick={() => setActiveTab(tb.id)} data-testid={`drawer-tab-${tb.id}`} style={{
padding: '12px 6px', padding: '12px 6px',
background: 'none', border: 'none', background: 'none', border: 'none',
borderBottom: `2px solid ${active ? 'var(--x-warning)' : isAlert ? 'var(--x-danger)' : 'transparent'}`, borderBottom: `2px solid ${active ? 'var(--x-warning)' : isAlert ? 'var(--x-danger)' : 'transparent'}`,
+12 -9
View File
@@ -2,6 +2,7 @@ import { useRef, useState } from 'react'
import useTableViewStore from '../store/tableViewStore' import useTableViewStore from '../store/tableViewStore'
import { money } from '../i18n' import { money } from '../i18n'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { useMenuNames } from '../hooks/useMenuNames'
import { fade } from '../logic/colour' import { fade } from '../logic/colour'
import OneMore from './OneMore' import OneMore from './OneMore'
import { canOneMore } from '../logic/lines' import { canOneMore } from '../logic/lines'
@@ -57,7 +58,8 @@ function ExpandArrow({ expanded, onClick }) {
// ── Parse selected_options into grouped sections ────────────────────────────── // ── Parse selected_options into grouped sections ──────────────────────────────
function buildSections(item) { // `c(name)`: a choice's name as shown (6R.L: the waiter's language; the stored name by default)
function buildSections(item, c = name => name) {
const sections = [] const sections = []
const opts = (() => { const opts = (() => {
try { return item.selected_options ? JSON.parse(item.selected_options) : [] } catch { return [] } try { return item.selected_options ? JSON.parse(item.selected_options) : [] } catch { return [] }
@@ -80,25 +82,25 @@ function buildSections(item) {
if (consumedAsSubAtIndex.has(i)) { i++; continue } if (consumedAsSubAtIndex.has(i)) { i++; continue }
if (o.id == null) { if (o.id == null) {
const existing = quickLines.find(x => x.name === o.name) const existing = quickLines.find(x => x.name === c(o.name))
if (existing) existing._qty = (existing._qty || 1) + 1 if (existing) existing._qty = (existing._qty || 1) + 1
else quickLines.push({ name: o.name, _qty: 1 }) else quickLines.push({ name: c(o.name), _qty: 1 })
i++ i++
continue continue
} }
let subName = null let subName = null
if (i + 1 < opts.length && opts[i + 1].id == null) { if (i + 1 < opts.length && opts[i + 1].id == null) {
subName = opts[i + 1].name subName = c(opts[i + 1].name)
consumedAsSubAtIndex.add(i + 1) consumedAsSubAtIndex.add(i + 1)
} }
if (idCount[o.id] > 1) { if (idCount[o.id] > 1) {
const existing = extraGroups.find(g => g.id === o.id && g.subName === subName) const existing = extraGroups.find(g => g.id === o.id && g.subName === subName)
if (existing) existing.qty++ if (existing) existing.qty++
else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 }) else extraGroups.push({ id: o.id, name: c(o.name), subName, qty: 1 })
} else { } else {
const value = subName ? `${o.name} · ${subName}` : o.name const value = subName ? `${c(o.name)} · ${subName}` : c(o.name)
prefGroups.push({ setName: null, values: [value] }) prefGroups.push({ setName: null, values: [value] })
} }
i++ i++
@@ -107,7 +109,7 @@ function buildSections(item) {
if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups }) if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups })
if (quickLines.length > 0) sections.push({ type: 'quick', lines: quickLines }) if (quickLines.length > 0) sections.push({ type: 'quick', lines: quickLines })
if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups }) if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups })
if (removed.length > 0) sections.push({ type: 'removed', lines: removed.map(n => ({ name: n })) }) if (removed.length > 0) sections.push({ type: 'removed', lines: removed.map(n => ({ name: c(n) })) })
if (item.notes) sections.push({ type: 'note', lines: [{ name: item.notes }] }) if (item.notes) sections.push({ type: 'note', lines: [{ name: item.notes }] })
return sections return sections
@@ -331,7 +333,8 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
const isServed = effectiveKds === 'served' const isServed = effectiveKds === 'served'
const kdsColor = !isCancelled && !isServed ? KDS_COLORS[effectiveKds] : null const kdsColor = !isCancelled && !isServed ? KDS_COLORS[effectiveKds] : null
const sections = buildSections(item) const names = useMenuNames() // 6R.L: the waiter's language, display only
const sections = buildSections(item, n => names.choiceName(item, n))
const hasDetails = sections.length > 0 const hasDetails = sections.length > 0
const [expanded, setExpanded] = useState(false) const [expanded, setExpanded] = useState(false)
@@ -404,7 +407,7 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
].filter(Boolean).join(' ')} ].filter(Boolean).join(' ')}
style={nameColor ? { color: nameColor } : undefined} style={nameColor ? { color: nameColor } : undefined}
> >
{(isPart(item) ? item.product_name : item.product?.name) || `#${item.product_id}`} {(isPart(item) ? item.product_name : names.lineName(item, item.product?.name)) || `#${item.product_id}`}
{isSettled(item) && ( {isSettled(item) && (
<span data-testid="item-settled" title={t('split.settledHint')} <span data-testid="item-settled" title={t('split.settledHint')}
style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle', style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle',
@@ -1,6 +1,7 @@
import { useState } from 'react' import { useState } from 'react'
import { money } from '../i18n' import { money } from '../i18n'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { useMenuText } from '@xenia/access'
const _UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' } const _UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
function fmtQty(qty, unitType) { function fmtQty(qty, unitType) {
@@ -12,10 +13,10 @@ function fmtQty(qty, unitType) {
const fmtEUR = money const fmtEUR = money
// Flatten selected_options into readable lines // Flatten selected_options into readable lines
function describeOptions(selected_options) { function describeOptions(selected_options, c = name => name) { // c: the name as shown (6R.L)
if (!selected_options?.length) return [] if (!selected_options?.length) return []
return selected_options.map(o => { return selected_options.map(o => {
let s = o.name || '' let s = o.name ? c(o.name) : ''
if (o.price_delta && Math.abs(o.price_delta) > 0.001) { if (o.price_delta && Math.abs(o.price_delta) > 0.001) {
s += ` (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})` s += ` (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`
} }
@@ -25,8 +26,9 @@ function describeOptions(selected_options) {
function CartItemSummaryRow({ item, product, price, estimated, onEdit }) { function CartItemSummaryRow({ item, product, price, estimated, onEdit }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const opts = describeOptions(item.selected_options) const mt = useMenuText() // 6R.L: the waiter's language, display only
const removed = item.removed_ingredients || [] const opts = describeOptions(item.selected_options, n => mt.choice(product, n))
const removed = (item.removed_ingredients || []).map(n => mt.choice(product, n))
return ( return (
<div style={{ <div style={{
@@ -36,7 +38,7 @@ function CartItemSummaryRow({ item, product, price, estimated, onEdit }) {
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}> <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{product?.name ?? `#${item.product_id}`}</span> <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{product ? mt(product) : `#${item.product_id}`}</span>
<span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 500 }}>{fmtQty(item.quantity, item.unit_type)}</span> <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 500 }}>{fmtQty(item.quantity, item.unit_type)}</span>
</div> </div>
{opts.length > 0 && ( {opts.length > 0 && (
+3 -1
View File
@@ -3,11 +3,13 @@
// manager who approved it, why. GET /api/orders/{id}/price-changes. // manager who approved it, why. GET /api/orders/{id}/price-changes.
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { useMenuNames } from '../hooks/useMenuNames'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors' import { apiError } from '../api/errors'
export default function PriceHistory({ orderId, item, onClose }) { export default function PriceHistory({ orderId, item, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L
const { formatDateTime, formatMoney } = useFormat() const { formatDateTime, formatMoney } = useFormat()
const [rows, setRows] = useState(null) const [rows, setRows] = useState(null)
const [error, setError] = useState('') const [error, setError] = useState('')
@@ -23,7 +25,7 @@ export default function PriceHistory({ orderId, item, onClose }) {
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="price-history"> <div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="price-history">
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title">{t('price.history')}</h2> <h2 className="modal-title">{t('price.history')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{item.product_name || item.product?.name}</p> <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{names.lineName(item, item.product_name || item.product?.name)}</p>
{error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center' }}>{error}</p>} {error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center' }}>{error}</p>}
{!error && rows === null && <p style={{ textAlign: 'center', color: 'var(--muted)' }}>…</p>} {!error && rows === null && <p style={{ textAlign: 'center', color: 'var(--muted)' }}>…</p>}
{rows?.length === 0 && <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>{t('price.historyNone')}</p>} {rows?.length === 0 && <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>{t('price.historyNone')}</p>}
+16 -12
View File
@@ -5,7 +5,7 @@ import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server' import { assetUrl } from '../config/server'
import { money } from '../i18n' import { money } from '../i18n'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Allergens } from '@xenia/access' import { Allergens, useMenuText } from '@xenia/access'
const FAV_CAT_ID = '__favorites__' const FAV_CAT_ID = '__favorites__'
const SVC_CAT_ID = '__service__' const SVC_CAT_ID = '__service__'
@@ -76,7 +76,8 @@ function ProductDetailModal({ product, onClose }) {
return () => window.removeEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey)
}, [onClose]) }, [onClose])
const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() const mt = useMenuText() // 6R.L: names in the waiter's language (display only)
const initials = mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return ( return (
<> <>
@@ -132,7 +133,7 @@ function ProductDetailModal({ product, onClose }) {
{/* Info */} {/* Info */}
<div style={{ padding: '18px 20px 24px' }}> <div style={{ padding: '18px 20px 24px' }}>
<div style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', lineHeight: 1.2, marginBottom: 6 }}> <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', lineHeight: 1.2, marginBottom: 6 }}>
{product.name} {mt(product)}
</div> </div>
<div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent, var(--x-warning))', marginBottom: product.description ? 14 : 0 }}> <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent, var(--x-warning))', marginBottom: product.description ? 14 : 0 }}>
{money(product.base_price)} {money(product.base_price)}
@@ -142,7 +143,7 @@ function ProductDetailModal({ product, onClose }) {
fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, fontSize: 14, color: 'var(--muted)', lineHeight: 1.6,
borderTop: '1px solid var(--border)', paddingTop: 12, borderTop: '1px solid var(--border)', paddingTop: 12,
}}> }}>
{product.description} {mt(product, 'description')}
</div> </div>
)} )}
<Allergens allergens={product.allergens} style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 12 }} /> <Allergens allergens={product.allergens} style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 12 }} />
@@ -189,6 +190,7 @@ function useLongPress(callback, delay = 2000) {
// ── Product card ────────────────────────────────────────────────────────────── // ── Product card ──────────────────────────────────────────────────────────────
function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) { function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
const mt = useMenuText()
const canQuickAdd = productAllowsQuickAdd(product) const canQuickAdd = productAllowsQuickAdd(product)
const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product]) const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product])
@@ -214,13 +216,13 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
{product.image_url {product.image_url
? <img src={assetUrl(product.image_url)} alt="" className="product-btn__img" /> ? <img src={assetUrl(product.image_url)} alt="" className="product-btn__img" />
: <span className="product-btn__initials"> : <span className="product-btn__initials">
{product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()} {mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
</span> </span>
} }
</div> </div>
</div> </div>
<div className="product-btn__info"> <div className="product-btn__info">
<span className="product-btn__name">{product.name}</span> <span className="product-btn__name">{mt(product)}</span>
{product.tags?.length > 0 && ( {product.tags?.length > 0 && (
<div className="product-btn__tags"> <div className="product-btn__tags">
{product.tags.map(tag => ( {product.tags.map(tag => (
@@ -263,6 +265,7 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
// ── Service Item Card ───────────────────────────────────────────────────────── // ── Service Item Card ─────────────────────────────────────────────────────────
function ServiceItemCard({ product, customerCount, onAdd }) { function ServiceItemCard({ product, customerCount, onAdd }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText()
const [qty, setQty] = useState(0) const [qty, setQty] = useState(0)
function dec() { setQty(q => Math.max(0, q - 1)) } function dec() { setQty(q => Math.max(0, q - 1)) }
@@ -290,7 +293,7 @@ function ServiceItemCard({ product, customerCount, onAdd }) {
{/* Top row: name + price */} {/* Top row: name + price */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2, flex: 1, minWidth: 0 }}> <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', lineHeight: 1.2, flex: 1, minWidth: 0 }}>
{product.name} {mt(product)}
</span> </span>
<span style={{ fontSize: 13, fontWeight: 600, color: hasPrice ? 'var(--x-warning)' : 'var(--muted)', flexShrink: 0 }}> <span style={{ fontSize: 13, fontWeight: 600, color: hasPrice ? 'var(--x-warning)' : 'var(--muted)', flexShrink: 0 }}>
{hasPrice ? money(product.base_price) : t('picker.noCharge')} {hasPrice ? money(product.base_price) : t('picker.noCharge')}
@@ -438,6 +441,7 @@ function buildSections(parent, subcategories, directProducts) {
export default function ProductPicker({ categories, products, onAdd, onQuickAdd: onQuickAddProp, viewAllOpen, setViewAllOpen, customerCount, courses = [], globalCourseId = null, quickNotes }) { export default function ProductPicker({ categories, products, onAdd, onQuickAdd: onQuickAddProp, viewAllOpen, setViewAllOpen, customerCount, courses = [], globalCourseId = null, quickNotes }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: categories and products in the waiter's language
const navigate = useNavigate() const navigate = useNavigate()
const favorites = useWaiterFavoritesStore(s => s.favorites) const favorites = useWaiterFavoritesStore(s => s.favorites)
@@ -575,7 +579,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
style={{ background: bg, color, border: isActive && cat.color ? `2px solid ${cat.color}` : undefined }} style={{ background: bg, color, border: isActive && cat.color ? `2px solid ${cat.color}` : undefined }}
onClick={() => selectCategory(cat.id)} onClick={() => selectCategory(cat.id)}
> >
{cat.name} {mt(cat)}
</button> </button>
) )
})} })}
@@ -670,7 +674,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
onClick={() => toggleSub(key)} onClick={() => toggleSub(key)}
> >
{accentColor && <span className="subcat-header__pill" style={{ background: accentColor }} />} {accentColor && <span className="subcat-header__pill" style={{ background: accentColor }} />}
<span className="subcat-header__name">{section.name}</span> <span className="subcat-header__name">{mt(section)}</span>
<span className="subcat-header__count">{sectionProducts.length}</span> <span className="subcat-header__count">{sectionProducts.length}</span>
<svg <svg
className="subcat-header__chevron" className="subcat-header__chevron"
@@ -761,7 +765,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
onClick={() => selectCategory(cat.id)} onClick={() => selectCategory(cat.id)}
> >
<span className="cat-all-tile__overlay" style={{ background: overlay }} /> <span className="cat-all-tile__overlay" style={{ background: overlay }} />
<span className="cat-all-tile__name">{cat.name}</span> <span className="cat-all-tile__name">{mt(cat)}</span>
</button> </button>
) )
})} })}
@@ -773,7 +777,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
const taggedProducts = activeTag ? products.filter(p => (p.tags || []).includes(activeTag)) : [] const taggedProducts = activeTag ? products.filter(p => (p.tags || []).includes(activeTag)) : []
const byCategory = taggedProducts.reduce((acc, p) => { const byCategory = taggedProducts.reduce((acc, p) => {
const cat = categories.find(c => c.id === p.category_id) const cat = categories.find(c => c.id === p.category_id)
const key = cat?.name || t('picker.noCategory') const key = (cat && mt(cat)) || t('picker.noCategory')
if (!acc[key]) acc[key] = [] if (!acc[key]) acc[key] = []
acc[key].push(p) acc[key].push(p)
return acc return acc
@@ -826,7 +830,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
cursor: 'pointer', textAlign: 'left', cursor: 'pointer', textAlign: 'left',
}} }}
> >
<span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{p.name}</span> <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{mt(p)}</span>
<span style={{ fontSize: 13, color: 'var(--muted)' }}>{money(p.base_price)}</span> <span style={{ fontSize: 13, color: 'var(--muted)' }}>{money(p.base_price)}</span>
</button> </button>
))} ))}
+3 -1
View File
@@ -3,10 +3,12 @@
// asks whether to send a cancellation (yes while the kitchen hasn't finished it). // asks whether to send a cancellation (yes while the kitchen hasn't finished it).
import { useState } from 'react' import { useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { useMenuNames } from '../hooks/useMenuNames'
import { cancelByDefault, lowestQuantity } from '../logic/lines' import { cancelByDefault, lowestQuantity } from '../logic/lines'
export default function QuantityModal({ item, mode, error, busy, onSave, onClose }) { export default function QuantityModal({ item, mode, error, busy, onSave, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L
const now = item.quantity const now = item.quantity
const [qty, setQty] = useState(now) const [qty, setQty] = useState(now)
const [ticket, setTicket] = useState(() => cancelByDefault(item)) const [ticket, setTicket] = useState(() => cancelByDefault(item))
@@ -19,7 +21,7 @@ export default function QuantityModal({ item, mode, error, busy, onSave, onClose
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="quantity-sheet"> <div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="quantity-sheet">
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title">{t('quantity.title')}</h2> <h2 className="modal-title">{t('quantity.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{item.product_name || item.product?.name}</p> <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{names.lineName(item, item.product_name || item.product?.name)}</p>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginBottom: 6 }}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginBottom: 6 }}>
<div style={{ textAlign: 'center' }}> <div style={{ textAlign: 'center' }}>
<div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>{t('quantity.now')}</div> <div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>{t('quantity.now')}</div>
+24
View File
@@ -0,0 +1,24 @@
// Menu names in the waiter's language (plan 6R.L) for what is already ordered: the sent lines of
// a table, the move / quantity dialogs. `mt` is @xenia/access's useMenuText(); `productOf(id)`
// finds the menu's product (the products the app already keeps, never fetched here), so a line
// shows its product's and its choices' text in the waiter's language. Display only: the lines,
// the tickets and the kitchen keep the venue's text. In the venue's own language nothing changes.
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useMenuText } from '@xenia/access'
import { PRODUCTS_KEY, fetchAndCacheProducts } from './useProductCache'
export function useMenuNames() {
const mt = useMenuText()
// reads the cache the menu snapshot fills (LiveContext, AddItemsPage); never fetches itself
const { data } = useQuery({ queryKey: PRODUCTS_KEY, queryFn: fetchAndCacheProducts, enabled: false })
const byId = useMemo(() => new Map((data?.products ?? []).map(p => [p.id, p])), [data])
return useMemo(() => {
const productOf = id => byId.get(id)
/** A sent order line's product name: the menu's text in the waiter's language, else `stored`. */
const lineName = (item, stored) => mt.line(productOf(item?.product_id), stored)
/** A sent line's choice (kept by its stored name) in the waiter's language. */
const choiceName = (item, name) => mt.choice(productOf(item?.product_id), name)
return { mt, productOf, lineName, choiceName }
}, [mt, byId])
}
+1 -1
View File
@@ -6,7 +6,7 @@ import { warmPhotos } from '../services/photoCache'
export const PRODUCTS_KEY = ['products'] export const PRODUCTS_KEY = ['products']
async function fetchAndCacheProducts() { export async function fetchAndCacheProducts() {
const [prodRes, catRes] = await Promise.all([ const [prodRes, catRes] = await Promise.all([
client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S
client.get('/api/products/categories'), client.get('/api/products/categories'),
+25 -20
View File
@@ -16,6 +16,7 @@ import { assetUrl } from '../config/server'
import { money } from '../i18n' import { money } from '../i18n'
import { LineError, estimate, wireLine } from '@xenia/api' import { LineError, estimate, wireLine } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { useMenuText } from '@xenia/access'
import { fade } from '../logic/colour' import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint' import SeatsHint from '../components/SeatsHint'
@@ -156,6 +157,7 @@ function fmtDraftQty(qty, unitType) {
export default function AddItemsPage() { export default function AddItemsPage() {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language; the cart keeps ids and stored names
const { tableId, orderType } = useParams() const { tableId, orderType } = useParams()
const isStandalone = !!orderType // true when on /standalone/:orderType/add const isStandalone = !!orderType // true when on /standalone/:orderType/add
const [searchParams] = useSearchParams() const [searchParams] = useSearchParams()
@@ -434,6 +436,7 @@ export default function AddItemsPage() {
// Returns structured sections for the expanded cart view // Returns structured sections for the expanded cart view
function buildItemSections(item, product) { function buildItemSections(item, product) {
const sections = [] const sections = []
const c = name => mt.choice(product, name) // 6R.L: shown in the waiter's language
if (item.selected_options?.length) { if (item.selected_options?.length) {
const prefIds = new Set( const prefIds = new Set(
@@ -442,7 +445,7 @@ export default function AddItemsPage() {
// Build a map: prefChoiceId → preference set name // Build a map: prefChoiceId → preference set name
const prefSetByChoiceId = {} const prefSetByChoiceId = {}
;(product?.preference_sets || []).forEach(ps => { ;(product?.preference_sets || []).forEach(ps => {
ps.choices.forEach(c => { prefSetByChoiceId[c.id] = ps.name }) ps.choices.forEach(ch => { prefSetByChoiceId[ch.id] = mt(ps) })
}) })
const quickNames = new Set((product?.quick_options || []).map(o => o.name)) const quickNames = new Set((product?.quick_options || []).map(o => o.name))
const extraIds = new Set((product?.options || []).map(o => o.id)) const extraIds = new Set((product?.options || []).map(o => o.id))
@@ -462,7 +465,7 @@ export default function AddItemsPage() {
const setName = prefSetByChoiceId[o.id] ?? '' const setName = prefSetByChoiceId[o.id] ?? ''
let subName = null let subName = null
if (i + 1 < opts.length && opts[i + 1].id == null) { if (i + 1 < opts.length && opts[i + 1].id == null) {
subName = opts[i + 1].name subName = c(opts[i + 1].name)
i += 2 i += 2
} else { } else {
i++ i++
@@ -471,15 +474,15 @@ export default function AddItemsPage() {
const existing = prefGroups.find(g => g.setName === setName) const existing = prefGroups.find(g => g.setName === setName)
if (existing) { if (existing) {
// multiple choices from same set (shouldn't normally happen, but handle gracefully) // multiple choices from same set (shouldn't normally happen, but handle gracefully)
existing.values.push(subName ? `${o.name} · ${subName}` : o.name) existing.values.push(subName ? `${c(o.name)} · ${subName}` : c(o.name))
} else { } else {
prefGroups.push({ setName, values: [subName ? `${o.name} · ${subName}` : o.name] }) prefGroups.push({ setName, values: [subName ? `${c(o.name)} · ${subName}` : c(o.name)] })
} }
} else if (o.id != null && extraIds.has(o.id)) { } else if (o.id != null && extraIds.has(o.id)) {
// Collect sub immediately following // Collect sub immediately following
let subName = null let subName = null
if (i + 1 < opts.length && opts[i + 1].id == null) { if (i + 1 < opts.length && opts[i + 1].id == null) {
subName = opts[i + 1].name subName = c(opts[i + 1].name)
i += 2 i += 2
} else { } else {
i++ i++
@@ -487,9 +490,9 @@ export default function AddItemsPage() {
// Merge duplicates // Merge duplicates
const existing = extraGroups.find(g => g.id === o.id && g.subName === subName) const existing = extraGroups.find(g => g.id === o.id && g.subName === subName)
if (existing) existing.qty++ if (existing) existing.qty++
else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 }) else extraGroups.push({ id: o.id, name: c(o.name), subName, qty: 1 })
} else if (quickNames.has(o.name)) { } else if (quickNames.has(o.name)) {
quickLines.push(o) quickLines.push({ ...o, name: c(o.name) })
i++ i++
} else { } else {
i++ i++
@@ -510,7 +513,7 @@ export default function AddItemsPage() {
} }
if (item.removed_ingredients?.length) { if (item.removed_ingredients?.length) {
sections.push({ type: 'removed', lines: item.removed_ingredients.map(n => ({ name: n })) }) sections.push({ type: 'removed', lines: item.removed_ingredients.map(n => ({ name: c(n) })) })
} }
if (item.notes) { if (item.notes) {
@@ -523,14 +526,15 @@ export default function AddItemsPage() {
// Simple flat summary for the collapsed one-liner // Simple flat summary for the collapsed one-liner
function buildItemSummary(item) { function buildItemSummary(item) {
const lines = [] const lines = []
const c = name => mt.choice(getProduct(item.product_id), name) // 6R.L
if (item.selected_options?.length) { if (item.selected_options?.length) {
item.selected_options.forEach(o => { item.selected_options.forEach(o => {
if (o.price_delta && o.price_delta !== 0) if (o.price_delta && o.price_delta !== 0)
lines.push(`${o.name} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`) lines.push(`${c(o.name)} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`)
else lines.push(o.name) else lines.push(c(o.name))
}) })
} }
if (item.removed_ingredients?.length) lines.push(t('add.withoutList', { names: item.removed_ingredients.join(', ') })) if (item.removed_ingredients?.length) lines.push(t('add.withoutList', { names: item.removed_ingredients.map(c).join(', ') }))
if (item.notes) lines.push(item.notes) if (item.notes) lines.push(item.notes)
return lines return lines
} }
@@ -682,7 +686,7 @@ export default function AddItemsPage() {
const p = getProduct(item.product_id) const p = getProduct(item.product_id)
return ( return (
<div key={item._key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}> <div key={item._key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 12, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{p?.name ?? `#${item.product_id}`}</span> <span style={{ fontSize: 12, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{p ? mt(p) : `#${item.product_id}`}</span>
<span style={{ fontSize: 12, fontWeight: 700, color: 'var(--x-warning)', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, p?.unit_type)}</span> <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--x-warning)', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, p?.unit_type)}</span>
</div> </div>
) )
@@ -1167,7 +1171,8 @@ function DealOfferModal({ offer, _products, onAccept, onDismiss }) {
function QuickAddToast({ product, count }) { function QuickAddToast({ product, count }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() const mt = useMenuText()
const initials = mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return ( return (
<div style={{ <div style={{
position: 'fixed', top: 62, left: '50%', position: 'fixed', top: 62, left: '50%',
@@ -1199,7 +1204,7 @@ function QuickAddToast({ product, count }) {
<div style={{ <div style={{
fontSize: 13, fontWeight: 600, color: 'var(--text)', fontSize: 13, fontWeight: 600, color: 'var(--text)',
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{product.name}</div> }}>{mt(product)}</div>
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>{t('add.inCart')}</div> <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>{t('add.inCart')}</div>
</div> </div>
{/* Count badge */} {/* Count badge */}
@@ -1243,6 +1248,7 @@ function SectionIcon({ type }) {
function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) { function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText()
const [expanded, setExpanded] = useState(false) const [expanded, setExpanded] = useState(false)
const hasDetails = sections.length > 0 const hasDetails = sections.length > 0
@@ -1261,7 +1267,7 @@ function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onC
{/* Name */} {/* Name */}
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product?.name ?? `#${item.product_id}`} {product ? mt(product) : `#${item.product_id}`}
</div> </div>
{!expanded && hasDetails && ( {!expanded && hasDetails && (
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
@@ -1380,14 +1386,13 @@ function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onC
function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) { function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: shown in the waiter's language, found by either
const [drawerProduct, setDrawerProduct] = useState(null) const [drawerProduct, setDrawerProduct] = useState(null)
const activeProducts = products.filter(p => p.lifecycle_status !== 'archived') const activeProducts = products.filter(p => p.lifecycle_status !== 'archived')
const results = query.trim().length === 0 const results = query.trim().length === 0
? [] ? []
: activeProducts.filter(p => : activeProducts.filter(p => mt.matches(p, query.trim().toLowerCase()))
p.name.toLowerCase().includes(query.trim().toLowerCase())
)
function openProduct(p) { function openProduct(p) {
// Blur the input first so the keyboard dismisses, then open the drawer // Blur the input first so the keyboard dismisses, then open the drawer
@@ -1425,7 +1430,7 @@ function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [],
{t('add.search.none', { query })} {t('add.search.none', { query })}
</p> </p>
) : results.map(p => { ) : results.map(p => {
const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() const initials = mt(p).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return ( return (
<button <button
key={p.id} key={p.id}
@@ -1450,7 +1455,7 @@ function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [],
</div> </div>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{p.name} {mt(p)}
</div> </div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}> <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
{money(p.base_price)} {money(p.base_price)}
+13 -6
View File
@@ -5,6 +5,7 @@ import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server' import { assetUrl } from '../config/server'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { money } from '../i18n' import { money } from '../i18n'
import { useMenuText } from '@xenia/access'
// ── Heart icon ──────────────────────────────────────────────────────────────── // ── Heart icon ────────────────────────────────────────────────────────────────
function Heart({ filled, size = 22 }) { function Heart({ filled, size = 22 }) {
@@ -17,6 +18,7 @@ function Heart({ filled, size = 22 }) {
// ── Thumb (product image or initials) ───────────────────────────────────────── // ── Thumb (product image or initials) ─────────────────────────────────────────
function Thumb({ product, size = 42, radius = 10 }) { function Thumb({ product, size = 42, radius = 10 }) {
const mt = useMenuText() // 6R.L: names in the waiter's language
return ( return (
<div style={{ <div style={{
width: size, height: size, borderRadius: radius, flexShrink: 0, width: size, height: size, borderRadius: radius, flexShrink: 0,
@@ -26,7 +28,7 @@ function Thumb({ product, size = 42, radius = 10 }) {
{product.image_url {product.image_url
? <img src={assetUrl(product.image_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> ? <img src={assetUrl(product.image_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: Math.round(size * 0.33), fontWeight: 700, color: 'var(--muted)' }}> : <span style={{ fontSize: Math.round(size * 0.33), fontWeight: 700, color: 'var(--muted)' }}>
{product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()} {mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()}
</span> </span>
} }
</div> </div>
@@ -38,6 +40,7 @@ function Thumb({ product, size = 42, radius = 10 }) {
// The waiter picks which items appear in that product's Favorites tab. // The waiter picks which items appear in that product's Favorites tab.
function AttrSection({ title, items, favIds, onToggle }) { function AttrSection({ title, items, favIds, onToggle }) {
const mt = useMenuText() // 6R.L: names in the waiter's language
if (!items || items.length === 0) return null if (!items || items.length === 0) return null
return ( return (
<div style={{ marginBottom: 20 }}> <div style={{ marginBottom: 20 }}>
@@ -65,7 +68,7 @@ function AttrSection({ title, items, favIds, onToggle }) {
> >
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.name} {mt(item)}
</div> </div>
{item.extra_cost != null && item.extra_cost !== 0 && ( {item.extra_cost != null && item.extra_cost !== 0 && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>+{money(item.extra_cost)}</div> <div style={{ fontSize: 12, color: 'var(--muted)' }}>+{money(item.extra_cost)}</div>
@@ -90,6 +93,7 @@ function AttrSection({ title, items, favIds, onToggle }) {
function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) { function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language
// Local state: { quick: id[], ingredients: id[], options: id[], prefs: id[] } // Local state: { quick: id[], ingredients: id[], options: id[], prefs: id[] }
// Start from waiter overrides if they exist, otherwise seed from manager's is_favorite flags // Start from waiter overrides if they exist, otherwise seed from manager's is_favorite flags
function seedFromManager() { function seedFromManager() {
@@ -164,7 +168,7 @@ function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
<Thumb product={product} size={38} radius={9} /> <Thumb product={product} size={38} radius={9} />
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name} {mt(product)}
</div> </div>
<div style={{ fontSize: 12, color: 'var(--muted)' }}> <div style={{ fontSize: 12, color: 'var(--muted)' }}>
{waiterAttrFavs ? t('favSetup.personalOn') : t('favSetup.managerDefaults')} {waiterAttrFavs ? t('favSetup.personalOn') : t('favSetup.managerDefaults')}
@@ -257,6 +261,7 @@ function ItemFavoritesModal({ product, waiterAttrFavs, onSave, onClose }) {
// ── Product row (ALL tab) ───────────────────────────────────────────────────── // ── Product row (ALL tab) ─────────────────────────────────────────────────────
function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs }) { function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const hasAttrs = ( const hasAttrs = (
(product.quick_options || []).length > 0 || (product.quick_options || []).length > 0 ||
@@ -279,7 +284,7 @@ function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs
> >
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name} {mt(product)}
</div> </div>
{hasAttrOverride && ( {hasAttrOverride && (
<Heart filled size={12} /> <Heart filled size={12} />
@@ -304,6 +309,7 @@ function ProductRow({ product, isFav, hasAttrOverride, onToggleFav, onEditAttrs
// ── Draggable favorites list (pointer-events — works on touch + mouse) ───────── // ── Draggable favorites list (pointer-events — works on touch + mouse) ─────────
function FavoritesList({ items, products, onReorder }) { function FavoritesList({ items, products, onReorder }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language
const [dragging, setDragging] = useState(null) const [dragging, setDragging] = useState(null)
const [dropIndex, setDropIndex] = useState(null) const [dropIndex, setDropIndex] = useState(null)
const containerRef = useRef(null) const containerRef = useRef(null)
@@ -405,7 +411,7 @@ function FavoritesList({ items, products, onReorder }) {
<Thumb product={product} size={38} radius={9} /> <Thumb product={product} size={38} radius={9} />
<span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product.name} {mt(product)}
</span> </span>
<span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>{money(product.base_price)}</span> <span style={{ fontSize: 12, color: 'var(--muted)', flexShrink: 0 }}>{money(product.base_price)}</span>
@@ -424,6 +430,7 @@ function FavoritesList({ items, products, onReorder }) {
// ── Main page ───────────────────────────────────────────────────────────────── // ── Main page ─────────────────────────────────────────────────────────────────
export default function FavoritesSetupPage() { export default function FavoritesSetupPage() {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: names in the waiter's language
const navigate = useNavigate() const navigate = useNavigate()
const { products, categories } = useProductCache() const { products, categories } = useProductCache()
const { favorites, toggleFavorite, reorderFavorites, itemFavorites, setItemFavorites } = useWaiterFavoritesStore() const { favorites, toggleFavorite, reorderFavorites, itemFavorites, setItemFavorites } = useWaiterFavoritesStore()
@@ -482,7 +489,7 @@ export default function FavoritesSetupPage() {
background: 'var(--bg2)', borderBottom: '1px solid var(--border)', background: 'var(--bg2)', borderBottom: '1px solid var(--border)',
position: 'sticky', top: 0, zIndex: 1, position: 'sticky', top: 0, zIndex: 1,
}}> }}>
{cat.name} {mt(cat)}
</div> </div>
{allProds.map(p => ( {allProds.map(p => (
<ProductRow <ProductRow
+11 -5
View File
@@ -16,6 +16,7 @@ import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../co
import usePaymentSettingsStore from '../store/paymentSettingsStore' import usePaymentSettingsStore from '../store/paymentSettingsStore'
import useTableViewStore from '../store/tableViewStore' import useTableViewStore from '../store/tableViewStore'
import { parseNumber, useTranslation } from '@xenia/i18n' import { parseNumber, useTranslation } from '@xenia/i18n'
import { useMenuNames } from '../hooks/useMenuNames'
import PriceReason from '../components/PriceReason' import PriceReason from '../components/PriceReason'
import { priceReasonText } from '../logic/priceRules' import { priceReasonText } from '../logic/priceRules'
import PriceHistory from '../components/PriceHistory' import PriceHistory from '../components/PriceHistory'
@@ -93,6 +94,7 @@ function mergeItems(items, mode) {
function SplitModal({ item, onConfirm, onClose }) { function SplitModal({ item, onConfirm, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L: the waiter's language, display only
const [splitQty, setSplitQty] = useState(1) const [splitQty, setSplitQty] = useState(1)
const max = item.quantity - 1 const max = item.quantity - 1
@@ -102,7 +104,7 @@ function SplitModal({ item, onConfirm, onClose }) {
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title">{t('detail.split.title')}</h2> <h2 className="modal-title">{t('detail.split.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--x-ink-2)', fontSize: 14, marginBottom: 4 }}> <p style={{ textAlign: 'center', color: 'var(--x-ink-2)', fontSize: 14, marginBottom: 4 }}>
{item.product?.name} ×{item.quantity} {names.lineName(item, item.product?.name)} ×{item.quantity}
</p> </p>
<p style={{ textAlign: 'center', color: 'var(--x-ink-2)', fontSize: 13, marginBottom: 16 }}> <p style={{ textAlign: 'center', color: 'var(--x-ink-2)', fontSize: 13, marginBottom: 16 }}>
{t('detail.split.howMany')} {t('detail.split.howMany')}
@@ -134,6 +136,7 @@ function SplitModal({ item, onConfirm, onClose }) {
function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) { function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L: the waiter's language, display only
const [reason, setReason] = useState({ choice: '', other: '' }) // 6F.3 const [reason, setReason] = useState({ choice: '', other: '' }) // 6F.3
const [tried, setTried] = useState(false) const [tried, setTried] = useState(false)
const basePrice = item.unit_price ?? 0 const basePrice = item.unit_price ?? 0
@@ -173,7 +176,7 @@ function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) {
<div className="modal-handle" /> <div className="modal-handle" />
<h2 className="modal-title">{t('detail.price.title')}</h2> <h2 className="modal-title">{t('detail.price.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}> <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}>
{item.product?.name} {names.lineName(item, item.product?.name)}
</p> </p>
{/* Current effective price — tap to type */} {/* Current effective price — tap to type */}
@@ -276,10 +279,11 @@ function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) {
function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, movedLine, onMoveHistory, canChangeQty, onChangeQty, onClose }) { function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, movedLine, onMoveHistory, canChangeQty, onChangeQty, onClose }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L: the waiter's language, display only
const { items, singleStacked, multiSelect } = target const { items, singleStacked, multiSelect } = target
const label = multiSelect const label = multiSelect
? t('detail.selected', { count: items.length }) ? t('detail.selected', { count: items.length })
: items[0]?.product?.name || `#${items[0]?.product_id}` : names.lineName(items[0], items[0]?.product?.name) || `#${items[0]?.product_id}`
const actionRows = [ const actionRows = [
// 6F.5: correct how many there are, without sending it to the kitchen again // 6F.5: correct how many there are, without sending it to the kitchen again
@@ -464,6 +468,7 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance
function ApplyDiscountModal({ order, _waiterId, onClose, onApplied }) { function ApplyDiscountModal({ order, _waiterId, onClose, onApplied }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L: the waiter's language, display only
const activeItems = (order?.items ?? []).filter(i => i.status === 'active') const activeItems = (order?.items ?? []).filter(i => i.status === 'active')
const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id)) const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id))
const [pct, setPct] = useState(10) const [pct, setPct] = useState(10)
@@ -544,7 +549,7 @@ function ApplyDiscountModal({ order, _waiterId, onClose, onApplied }) {
</div> </div>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}> <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.product?.name ?? `#${item.product_id}`} {names.lineName(item, item.product?.name) ?? `#${item.product_id}`}
</div> </div>
<div style={{ fontSize: 11, color: 'var(--muted)' }}>×{item.quantity} · {fmtPrice(eff)}</div> <div style={{ fontSize: 11, color: 'var(--muted)' }}>×{item.quantity} · {fmtPrice(eff)}</div>
</div> </div>
@@ -1154,6 +1159,7 @@ function CustomerCountModal({ value, seats, onChange, onClose }) {
export default function TableDetailPage() { export default function TableDetailPage() {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const names = useMenuNames() // 6R.L: the waiter's language, display only
const { tableId, orderId: standaloneOrderId } = useParams() const { tableId, orderId: standaloneOrderId } = useParams()
const isStandalone = !!standaloneOrderId const isStandalone = !!standaloneOrderId
const [searchParams, setSearchParams] = useSearchParams() const [searchParams, setSearchParams] = useSearchParams()
@@ -2338,7 +2344,7 @@ export default function TableDetailPage() {
onMoveHistory={() => { onMoveHistory={() => {
const item = itemActionTarget.items[0] const item = itemActionTarget.items[0]
setItemActionTarget(null) setItemActionTarget(null)
setMoveSheet({ title: t('moves.lineTitle'), subtitle: item.product_name || item.product?.name, moves: moves.items[item.id] ?? [], itemId: item.id }) setMoveSheet({ title: t('moves.lineTitle'), subtitle: names.lineName(item, item.product_name || item.product?.name), moves: moves.items[item.id] ?? [], itemId: item.id })
}} }}
onPriceHistory={() => { onPriceHistory={() => {
const item = itemActionTarget.items[0] const item = itemActionTarget.items[0]