diff --git a/docs/README.md b/docs/README.md index 16a99f6..eff18d6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) | | `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/access/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (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 `` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | +| `packages/access/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (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 `` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | | `packages/i18n/` | Translations (`locales//.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/`. | diff --git a/local_backend/core/menu_languages.py b/local_backend/core/menu_languages.py index 1ac63a6..5a917b5 100644 --- a/local_backend/core/menu_languages.py +++ b/local_backend/core/menu_languages.py @@ -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 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, -order app, menu tablet, signage menu boards). Tickets, the kitchen display, the counter and the -waiters' phones keep the base text (the staff's). +order app, menu tablet, signage menu boards), and since 6R.L the waiters' phones and the counter +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 diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 4aeb7ca..bc97f8d 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -76,16 +76,28 @@ def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))): # ── 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): - 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)] def _product_out(p, price: float, prices: dict | None = None) -> dict: shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731 from core import allergens, sales_points + from core.menu_languages import of as product_tr return { "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()}, "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", @@ -95,18 +107,19 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict: "primary_category_id": p.primary_category_id, "categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships], "sort_order": p.sort_order, - "quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)} + "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)], "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], - "prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select), - "shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None), + "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"], "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), - "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 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"]) cats = db.query(Category).order_by(Category.sort_order, Category.name).all() from services import price_changes, split_bills + from core.menu_languages import of as product_tr return { # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount "settings": {**settings, "price_change": price_changes.mode(db), # 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)}, - "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], "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)], diff --git a/local_backend/tests/test_pos.py b/local_backend/tests/test_pos.py index f1f2fa6..787487d 100644 --- a/local_backend/tests/test_pos.py +++ b/local_backend/tests/test_pos.py @@ -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") assert burger["price"] == 10.0 and burger["description"] == "Beef, brioche" and burger["tags"] == ["spicy"] assert "cost_simple" not in burger and "cost_breakdown" not in burger - assert burger["options"][0]["subs"][0] == {"name": "BBQ", "price": 0.2, "is_default": True} + assert burger["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 {c["name"] for c in data["categories"]} >= {"Food", "Drinks"} 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): m = menu line = burger_line(m, quick=[{"id": m["burger"].quick_options[0].id, "qty": 2}], diff --git a/packages/access/src/index.js b/packages/access/src/index.js index 3e3c607..9fb37d9 100644 --- a/packages/access/src/index.js +++ b/packages/access/src/index.js @@ -8,6 +8,7 @@ // useAllowed('ordering.orders.cancel') → 'yes' | 'approve' (a manager's PIN) | 'no' (4.3) // · // +// 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) // 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 { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js' 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) diff --git a/packages/access/src/menuLanguages.js b/packages/access/src/menuLanguages.js index b8c3c11..1138171 100644 --- a/packages/access/src/menuLanguages.js +++ b/packages/access/src/menuLanguages.js @@ -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). */ export const shownText = (texts, venueLanguage, 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 +} diff --git a/packages/access/src/useMenuText.js b/packages/access/src/useMenuText.js new file mode 100644 index 0000000..249b15b --- /dev/null +++ b/packages/access/src/useMenuText.js @@ -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]) +} diff --git a/packages/access/tests/menuText.test.mjs b/packages/access/tests/menuText.test.mjs new file mode 100644 index 0000000..13a3049 --- /dev/null +++ b/packages/access/tests/menuText.test.mjs @@ -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, '')) +}) diff --git a/packages/ordering/src/ProductDialog.jsx b/packages/ordering/src/ProductDialog.jsx index 71b78e4..f72d0d8 100644 --- a/packages/ordering/src/ProductDialog.jsx +++ b/packages/ordering/src/ProductDialog.jsx @@ -3,6 +3,8 @@ // 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. // `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 { Minus, Plus } from 'lucide-react' 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 // 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 { formatMoney } = useFormat() const unit = unitOf(product) @@ -47,7 +51,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) const add = () => { onAdd(line); onClose() } return ( - {ps.multi && p && ( - setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} /> + setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={text(c)} /> )} ) })} {one?.subs?.length > 0 && ( -
+
{one.subs.map(s => ( ))}
)} {ps.shared && one && !one.disables_shared && ( -
+
{ps.shared.subs.map(s => ( ))}
@@ -128,10 +132,10 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) return ( {q.allow_multiple && n > 0 && ( - setSel(s => setQuick(s, q.id, v))} label={q.name} /> + setSel(s => setQuick(s, q.id, v))} label={text(q)} /> )} ) @@ -147,15 +151,15 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) - {o.allow_multiple && s && setSel(x => setOptionQty(x, o.id, v))} label={o.name} />} + {o.allow_multiple && s && setSel(x => setOptionQty(x, o.id, v))} label={text(o)} />} {s && o.subs.length > 0 && ( {o.subs.map(sub => ( ))} @@ -170,7 +174,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel })
{product.ingredients.map(i => ( ))}
@@ -189,7 +193,7 @@ export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) {missing.length > 0 && ( -

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

+

{t('ordering.dialog.missing', { list: missing.map(m => (text.choice ? text.choice(product, m.name) : m.name)).join(', ') })}

)}
diff --git a/packages/ordering/src/cart.js b/packages/ordering/src/cart.js index 1ed54e7..6bf1692 100644 --- a/packages/ordering/src/cart.js +++ b/packages/ordering/src/cart.js @@ -23,7 +23,9 @@ export function productsIn(products, categoryId) { export function searchProducts(products, query) { const words = fold(query).split(/\s+/).filter(Boolean) if (!words.length) return [] - return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) }) + // 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). */ diff --git a/packages/ordering/tests/cart.test.mjs b/packages/ordering/tests/cart.test.mjs index e679973..96f0f6b 100644 --- a/packages/ordering/tests/cart.test.mjs +++ b/packages/ordering/tests/cart.test.mjs @@ -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.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), []) +}) diff --git a/terminal/src/apps/pos/CartLine.jsx b/terminal/src/apps/pos/CartLine.jsx index 7784d83..4eebb9c 100644 --- a/terminal/src/apps/pos/CartLine.jsx +++ b/terminal/src/apps/pos/CartLine.jsx @@ -3,24 +3,26 @@ import { Minus, Plus } from 'lucide-react' import { useFormat, useTranslation } from '@xenia/i18n' import { IconButton, Select } from '@xenia/ui' +import { useMenuText } from '@xenia/access' import { DISCOUNTS, unitOf } from './logic/cart' export default function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) { const { t } = useTranslation('terminal') 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 step = unit ? unit.step : 1 const qtyText = unit ? `${Number(line.quantity).toFixed(step < 1 ? 1 : 0)} ${unit.label}` : `${line.quantity}×` return (
- {product?.name ?? priced?.name} + {product ? mt(product) : priced?.name} {priced ? formatMoney(priced.total) : '…'}
{priced && (priced.entries.length > 0 || priced.removed.length > 0 || priced.notes) && (
- {priced.entries.map((e, i) => + {e.name}{e.price ? ` (${formatMoney(e.price)})` : ''})} - {priced.removed.map(n => − {n})} + {priced.entries.map((e, i) => + {mt.choice(product, e.name)}{e.price ? ` (${formatMoney(e.price)})` : ''})} + {priced.removed.map(n => − {mt.choice(product, n)})} {priced.notes && “{priced.notes}”}
)} diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index d507a44..6c01e12 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -14,7 +14,7 @@ import { useEffect, useMemo, useState } from 'react' import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react' 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 { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui' import { useLiveEvent } from '../../device/context' @@ -51,6 +51,7 @@ export default function PosScreen() { function Counter({ menu, t }) { const { t: tc } = useTranslation('common') const { language } = useLanguage() + const mt = useMenuText() // 6R.L: menu names in the cashier's language (display only) const { formatMoney } = useFormat() const [mode, setMode] = useState('sale') // sale | tables | online | receipts const [tableId, setTableId] = useState(null) // the open table (tables mode) @@ -181,7 +182,7 @@ function Counter({ menu, t }) { { setCategory(null); setQuery('') }}>{t('pos.allProducts')} {categories.map(c => ( { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}> - {c.name} + {mt(c)} ))} @@ -266,7 +267,7 @@ function Counter({ menu, t }) { )} {dialog && ( - setDialog(null)} + setDialog(null)} text={mt} onAdd={line => setCart(c => addLine(c, line))} /> )}
@@ -299,6 +300,8 @@ function NavButton({ active, colour, onClick, children, testId, count, tally }) function ProductCard({ product, onTap, onInfo }) { const { t } = useTranslation('terminal') + const mt = useMenuText() // 6R.L: the cashier's language, display only + const name = mt(product) const { formatMoney } = useFormat() const unit = unitOf(product) return ( @@ -306,13 +309,13 @@ function ProductCard({ product, onTap, onInfo }) { - diff --git a/terminal/src/apps/pos/SaleCart.jsx b/terminal/src/apps/pos/SaleCart.jsx index ff95605..e267853 100644 --- a/terminal/src/apps/pos/SaleCart.jsx +++ b/terminal/src/apps/pos/SaleCart.jsx @@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from 'react' import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react' import { useFormat, useTranslation } from '@xenia/i18n' import { Button, EmptyState, useToast } from '@xenia/ui' +import { useMenuText } from '@xenia/access' import client from '../../api/client' import CartLine from './CartLine' 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 }) { const { t } = useTranslation('terminal') + const mt = useMenuText() // 6R.L: the cashier's language (the customer display keeps the venue's) const { formatMoney } = useFormat() const toast = useToast() const [paying, setPaying] = useState(false) @@ -79,7 +81,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, {paying && quote.quote && ( ({ 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)} onPaid={result => { setPaying(false) diff --git a/terminal/src/apps/pos/TablePanel.jsx b/terminal/src/apps/pos/TablePanel.jsx index 5a55911..8d03349 100644 --- a/terminal/src/apps/pos/TablePanel.jsx +++ b/terminal/src/apps/pos/TablePanel.jsx @@ -7,6 +7,7 @@ import { useEffect, useState } from 'react' import { ArrowLeft, Ban, Banknote, Check, CheckCircle2, Lock, Send, Trash2 } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' +import { useMenuText } from '@xenia/access' import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xenia/ui' import client from '../../api/client' import CartLine from './CartLine' @@ -31,7 +32,13 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on const [lastPay, setLastPay] = useState(null) 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 state = tableState(table) const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length diff --git a/terminal/src/apps/pos/logic/tables.js b/terminal/src/apps/pos/logic/tables.js index ec8f39d..6476130 100644 --- a/terminal/src/apps/pos/logic/tables.js +++ b/terminal/src/apps/pos/logic/tables.js @@ -49,6 +49,7 @@ export function orderLines(order) { .filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid' || i.status === 'split') .map(i => ({ 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 ?? '', quantity: i.quantity, unitType: i.unit_type, diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 2a904f4..14e25cd 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -377,6 +377,36 @@ try { 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)) + // ── 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') 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) diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 90dec81..680ce24 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -596,6 +596,68 @@ try { await a.getByRole('button', { name: /Dark theme/ }).click() 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 // says why; an order queued offline on the first phone goes out after it signs in again ── { diff --git a/waiter_pwa/src/components/OrderDrawer.jsx b/waiter_pwa/src/components/OrderDrawer.jsx index 401f30a..17faa0c 100644 --- a/waiter_pwa/src/components/OrderDrawer.jsx +++ b/waiter_pwa/src/components/OrderDrawer.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useRef } from 'react' -import { useCan } from '@xenia/access' +import { useCan, useMenuText } from '@xenia/access' import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import { assetUrl } from '../config/server' import { money } from '../i18n' @@ -155,6 +155,7 @@ function Row({ selected, onClick, children, right, left, style = {} }) { function QuickOptionRow({ opt, quickState, setQuickState, compact }) { 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 selected = qty > 0 const toggleSingle = () => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 })) @@ -176,7 +177,7 @@ function QuickOptionRow({ opt, quickState, setQuickState, compact }) { ) : null} > -
{opt.name}
+
{mt(opt)}
{opt.price > 0 &&
+{money(opt.price)}{opt.allow_multiple ? ` ${t('drawer.each')}` : ''}
} ) @@ -186,6 +187,7 @@ function QuickOptionRow({ opt, quickState, setQuickState, compact }) { function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra, compact }) { 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 selected = !!sel const open = expandedExtra === opt.id @@ -249,7 +251,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx } style={compact ? { minHeight: 48 } : {}} > -
{opt.name}
+
{mt(opt)}
{(opt.extra_cost ?? 0) !== 0 ? `+${money(opt.extra_cost)}` : t('drawer.included')} {subLabel && · {subLabel}} @@ -272,7 +274,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx left={} style={sub.is_compact ? { minHeight: 44 } : {}}>
-
{sub.name}
+
{mt(sub)}
{(sub.extra_cost ?? 0) !== 0 &&
+{money(sub.extra_cost)}
}
@@ -309,7 +311,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx style={sub.is_compact ? { minHeight: 44 } : {}}>
- {sub.name} + {mt(sub)} {subQty > 1 && ×{subQty}}
{(sub.extra_cost ?? 0) !== 0 &&
+{money(sub.extra_cost)}{sub.allow_multiple ? ` ${t('drawer.each')}` : ''}
} @@ -328,6 +330,7 @@ function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setEx function IngredientRow({ ing, removedState, setRemovedState, compact }) { 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] return ( }> -
{ing.name}
+
{mt(ing)}
) } @@ -355,6 +358,7 @@ function IngredientRow({ ing, removedState, setRemovedState, compact }) { function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { 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 complete = selChoice != null && !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null) @@ -374,7 +378,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu return (
-
{ps.name}
+
{mt(ps)}
{!complete &&
{t('drawer.required')}
}
@@ -388,7 +392,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu selectPref(ch)} left={} style={ch.is_compact ? { minHeight: 48 } : {}} right={(ch.extra_cost ?? 0) !== 0 ?
{ch.extra_cost > 0 ? '+' : ''}{money(ch.extra_cost)}
: null}> -
{ch.name}
+
{mt(ch)}
{isSel && hasSubs && ( @@ -401,7 +405,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={} style={sub.is_compact ? { minHeight: 44 } : {}} right={(sub.extra_cost ?? 0) !== 0 ?
+{money(sub.extra_cost)}
: null}> -
{sub.name}
+
{mt(sub)}
) @@ -414,7 +418,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu {showShared && (
-
{ps.shared_subset.name}
+
{mt(ps.shared_subset)}
{ps.shared_subset.choices.map((sub, si) => { const subSel = sharedSubs[ps.id]?.name === sub.name @@ -423,7 +427,7 @@ function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSu setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={} style={sub.is_compact ? { minHeight: 44 } : {}} right={(sub.extra_cost ?? 0) !== 0 ?
+{money(sub.extra_cost)}
: null}> -
{sub.name}
+
{mt(sub)}
) @@ -549,6 +553,7 @@ function partitionByGroup(items, modifierGroups) { function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) { 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 [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(extraGroups.map(g => [g.id, true]))) const options = product.options || [] @@ -579,7 +584,7 @@ function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExp const isCollapsed = collapsedGroups[group.id] ?? true return (
- toggleGroup(group.id)} colorIdx={gi} /> + toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{items.map(renderOption)} @@ -596,6 +601,7 @@ function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExp function IngredientsTab({ product, removedState, setRemovedState }) { 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 [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(ingGroups.map(g => [g.id, true]))) const ingredients = product.ingredients || [] @@ -626,7 +632,7 @@ function IngredientsTab({ product, removedState, setRemovedState }) { const isCollapsed = collapsedGroups[group.id] ?? true return (
- toggleGroup(group.id)} colorIdx={gi} /> + toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{items.map(renderIng)} @@ -643,6 +649,7 @@ function IngredientsTab({ product, removedState, setRemovedState }) { function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) { 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 [collapsedGroups, setCollapsedGroups] = useState(() => Object.fromEntries(prefGroups.map(g => [g.id, true]))) const preferenceSets = product.preference_sets || [] @@ -675,7 +682,7 @@ function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedS const isCollapsed = collapsedGroups[group.id] ?? true return (
- toggleGroup(group.id)} colorIdx={gi} /> + toggleGroup(group.id)} colorIdx={gi} /> {!isCollapsed && (
{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 }) { 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) // 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. @@ -1208,8 +1216,8 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt && (!sharedSub || sharedSub.name === defaultSharedSub?.name) if (isFullyDefault) { price += delta; return } - const value = `${choice.name}${inlineSub ? ` · ${inlineSub.name}` : ''}${sharedSub ? ` · ${sharedSub.name}` : ''}` - lines.push({ group: 'prefs', label: ps.name, value, qty: 1, price: delta, detail: null }) + const value = `${mt(choice)}${inlineSub ? ` · ${mt(inlineSub)}` : ''}${sharedSub ? ` · ${mt(sharedSub)}` : ''}` + lines.push({ group: 'prefs', label: mt(ps), value, qty: 1, price: delta, detail: null }) price += delta }) @@ -1217,7 +1225,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt const q = quickState[opt.id] || 0 if (q === 0) return 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 }) @@ -1231,19 +1239,19 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt if (!subQty || subQty < 1) return const sub = opt.sub_choices.find(s => s.name === subName) 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 }) } else { const sub = opt.sub_choices?.find(s => s.name === sel.subName) 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 } }) 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 } @@ -1449,7 +1457,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt style={{ width: 48, height: 48, borderRadius: 12, objectFit: 'cover', flexShrink: 0 }} /> )}
-
{product.name}
+
{mt(product)}
{priceAdj !== 0 ? <>{money(product.base_price)} → {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 tabColor = isAlert ? 'var(--x-danger)' : active ? 'var(--x-warning)' : 'var(--muted)' return ( - ) })} @@ -670,7 +674,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd: onClick={() => toggleSub(key)} > {accentColor && } - {section.name} + {mt(section)} {sectionProducts.length} selectCategory(cat.id)} > - {cat.name} + {mt(cat)} ) })} @@ -773,7 +777,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd: const taggedProducts = activeTag ? products.filter(p => (p.tags || []).includes(activeTag)) : [] const byCategory = taggedProducts.reduce((acc, p) => { 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] = [] acc[key].push(p) return acc @@ -826,7 +830,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd: cursor: 'pointer', textAlign: 'left', }} > - {p.name} + {mt(p)} {money(p.base_price)} ))} diff --git a/waiter_pwa/src/components/QuantityModal.jsx b/waiter_pwa/src/components/QuantityModal.jsx index 91c7264..de88a01 100644 --- a/waiter_pwa/src/components/QuantityModal.jsx +++ b/waiter_pwa/src/components/QuantityModal.jsx @@ -3,10 +3,12 @@ // asks whether to send a cancellation (yes while the kitchen hasn't finished it). import { useState } from 'react' import { useTranslation } from '@xenia/i18n' +import { useMenuNames } from '../hooks/useMenuNames' import { cancelByDefault, lowestQuantity } from '../logic/lines' export default function QuantityModal({ item, mode, error, busy, onSave, onClose }) { const { t } = useTranslation('waiter') + const names = useMenuNames() // 6R.L const now = item.quantity const [qty, setQty] = useState(now) const [ticket, setTicket] = useState(() => cancelByDefault(item)) @@ -19,7 +21,7 @@ export default function QuantityModal({ item, mode, error, busy, onSave, onClose
e.stopPropagation()} data-testid="quantity-sheet">

{t('quantity.title')}

-

{item.product_name || item.product?.name}

+

{names.lineName(item, item.product_name || item.product?.name)}

{t('quantity.now')}
diff --git a/waiter_pwa/src/hooks/useMenuNames.js b/waiter_pwa/src/hooks/useMenuNames.js new file mode 100644 index 0000000..11c1c81 --- /dev/null +++ b/waiter_pwa/src/hooks/useMenuNames.js @@ -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]) +} diff --git a/waiter_pwa/src/hooks/useProductCache.js b/waiter_pwa/src/hooks/useProductCache.js index e3d5834..ab81e44 100644 --- a/waiter_pwa/src/hooks/useProductCache.js +++ b/waiter_pwa/src/hooks/useProductCache.js @@ -6,7 +6,7 @@ import { warmPhotos } from '../services/photoCache' export const PRODUCTS_KEY = ['products'] -async function fetchAndCacheProducts() { +export async function fetchAndCacheProducts() { const [prodRes, catRes] = await Promise.all([ client.get('/api/products/', { params: { sold_at: 'in_store,in_store_takeaway' } }), // phase 3S client.get('/api/products/categories'), diff --git a/waiter_pwa/src/pages/AddItemsPage.jsx b/waiter_pwa/src/pages/AddItemsPage.jsx index 2e3e4b4..e81d8d3 100644 --- a/waiter_pwa/src/pages/AddItemsPage.jsx +++ b/waiter_pwa/src/pages/AddItemsPage.jsx @@ -16,6 +16,7 @@ import { assetUrl } from '../config/server' import { money } from '../i18n' import { LineError, estimate, wireLine } from '@xenia/api' import { useTranslation } from '@xenia/i18n' +import { useMenuText } from '@xenia/access' import { fade } from '../logic/colour' import SeatsHint from '../components/SeatsHint' @@ -156,6 +157,7 @@ function fmtDraftQty(qty, unitType) { export default function AddItemsPage() { 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 isStandalone = !!orderType // true when on /standalone/:orderType/add const [searchParams] = useSearchParams() @@ -434,6 +436,7 @@ export default function AddItemsPage() { // Returns structured sections for the expanded cart view function buildItemSections(item, product) { const sections = [] + const c = name => mt.choice(product, name) // 6R.L: shown in the waiter's language if (item.selected_options?.length) { const prefIds = new Set( @@ -442,7 +445,7 @@ export default function AddItemsPage() { // Build a map: prefChoiceId → preference set name const prefSetByChoiceId = {} ;(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 extraIds = new Set((product?.options || []).map(o => o.id)) @@ -462,7 +465,7 @@ export default function AddItemsPage() { const setName = prefSetByChoiceId[o.id] ?? '' let subName = null if (i + 1 < opts.length && opts[i + 1].id == null) { - subName = opts[i + 1].name + subName = c(opts[i + 1].name) i += 2 } else { i++ @@ -471,15 +474,15 @@ export default function AddItemsPage() { const existing = prefGroups.find(g => g.setName === setName) if (existing) { // 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 { - 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)) { // Collect sub immediately following let subName = null if (i + 1 < opts.length && opts[i + 1].id == null) { - subName = opts[i + 1].name + subName = c(opts[i + 1].name) i += 2 } else { i++ @@ -487,9 +490,9 @@ export default function AddItemsPage() { // Merge duplicates const existing = extraGroups.find(g => g.id === o.id && g.subName === subName) 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)) { - quickLines.push(o) + quickLines.push({ ...o, name: c(o.name) }) i++ } else { i++ @@ -510,7 +513,7 @@ export default function AddItemsPage() { } 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) { @@ -523,14 +526,15 @@ export default function AddItemsPage() { // Simple flat summary for the collapsed one-liner function buildItemSummary(item) { const lines = [] + const c = name => mt.choice(getProduct(item.product_id), name) // 6R.L if (item.selected_options?.length) { item.selected_options.forEach(o => { if (o.price_delta && o.price_delta !== 0) - lines.push(`${o.name} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`) - else lines.push(o.name) + lines.push(`${c(o.name)} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`) + 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) return lines } @@ -682,7 +686,7 @@ export default function AddItemsPage() { const p = getProduct(item.product_id) return (
- {p?.name ?? `#${item.product_id}`} + {p ? mt(p) : `#${item.product_id}`} {fmtDraftQty(item.quantity, p?.unit_type)}
) @@ -1167,7 +1171,8 @@ function DealOfferModal({ offer, _products, onAccept, onDismiss }) { function QuickAddToast({ product, count }) { 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 (
{product.name}
+ }}>{mt(product)}
{t('add.inCart')}
{/* Count badge */} @@ -1243,6 +1248,7 @@ function SectionIcon({ type }) { function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) { const { t } = useTranslation('waiter') + const mt = useMenuText() const [expanded, setExpanded] = useState(false) const hasDetails = sections.length > 0 @@ -1261,7 +1267,7 @@ function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onC {/* Name */}
- {product?.name ?? `#${item.product_id}`} + {product ? mt(product) : `#${item.product_id}`}
{!expanded && hasDetails && (
@@ -1380,14 +1386,13 @@ function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onC function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) { const { t } = useTranslation('waiter') + const mt = useMenuText() // 6R.L: shown in the waiter's language, found by either const [drawerProduct, setDrawerProduct] = useState(null) const activeProducts = products.filter(p => p.lifecycle_status !== 'archived') const results = query.trim().length === 0 ? [] - : activeProducts.filter(p => - p.name.toLowerCase().includes(query.trim().toLowerCase()) - ) + : activeProducts.filter(p => mt.matches(p, query.trim().toLowerCase())) function openProduct(p) { // 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 })}

) : 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 (