From e395d99704c1975366ce85bc28dcbabdd67cce2d Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 18 Nov 2026 10:47:03 +0200 Subject: [PATCH] feat(menu): the menu in English and Greek (platform-v2 step 6.4, D-29) - products.translations / categories.translations (Alembic 0033, core/menu_languages.py: el + en, name / description / quick options by their base name; catalog.translation). Empty = the text as typed; no machine translation (owner). - In the manager's product editor ("In English" / "In Greek", quick extras), the category dialog, and a menu board's Language (signage MenuContent.language). - Customer screens only: cloud snapshot names / descriptions per language (C-2), the menu tablet's EL / EN switch the names (localize), signage boards; tickets, KDS, counter, phones keep the base. - Catalogue bundles carry translations; @xenia/access menuLanguages.js (a backend test compares). - e2e: manager (the other language saved), menu tablet (EN / EL names), QR table (English on the menu, the base name on the kitchen's order, Greek page as typed). Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- local_backend/core/errors.py | 1 + local_backend/core/menu_languages.py | 102 ++++++++++++++++++ .../versions/0033_menu_translations.py | 26 +++++ local_backend/models/product.py | 5 + local_backend/routers/data_transfer.py | 10 +- local_backend/routers/menu_tablet.py | 7 +- local_backend/routers/products.py | 14 ++- local_backend/routers/signage.py | 1 + local_backend/schemas/product.py | 13 +++ local_backend/services/cloud_sync.py | 7 +- local_backend/services/signage_menu.py | 13 ++- local_backend/tests/test_menu_languages.py | 84 +++++++++++++++ .../src/pages/products/CategoryDialog.jsx | 12 ++- .../pages/products/editor/ChoicesPanel.jsx | 9 +- .../src/pages/products/editor/InfoTabs.jsx | 20 +++- .../src/pages/products/editor/formLogic.js | 20 ++++ .../src/pages/signage/MenuEditor.jsx | 6 +- manager_dashboard/tests/products.test.mjs | 10 ++ packages/access/package.json | 3 +- packages/access/src/index.js | 1 + packages/access/src/menuLanguages.js | 11 ++ packages/i18n/locales/el/errors.json | 3 +- packages/i18n/locales/el/manager.json | 17 ++- packages/i18n/locales/en/errors.json | 3 +- packages/i18n/locales/en/manager.json | 17 ++- .../src/apps/menu-tablet/MenuTabletApp.jsx | 7 +- terminal/src/apps/menu-tablet/logic.js | 21 +++- terminal/tests/menu-tablet.test.mjs | 14 ++- tests/e2e/manager.mjs | 3 + tests/e2e/menu_tablet.mjs | 13 ++- tests/e2e/qr_table.mjs | 22 +++- 32 files changed, 459 insertions(+), 38 deletions(-) create mode 100644 local_backend/core/menu_languages.py create mode 100644 local_backend/migrations/versions/0033_menu_translations.py create mode 100644 local_backend/tests/test_menu_languages.py create mode 100644 packages/access/src/menuLanguages.js diff --git a/docs/README.md b/docs/README.md index 10d7797..e17cc76 100644 --- a/docs/README.md +++ b/docs/README.md @@ -68,7 +68,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` | | `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/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`) and the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3; tests compare them), 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 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/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/errors.py b/local_backend/core/errors.py index f3b0cc7..3c60962 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -148,6 +148,7 @@ CODES: dict[str, tuple[int, str]] = { "catalog.unknown_category": (422, "There is no category {category_id}."), "catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."), "catalog.allergen": (422, "Unknown allergen or level: {allergen}."), + "catalog.translation": (422, "The menu can't be translated like that: {what}."), # converted from HTTPException (plan step 6.1) "auth.password_current_required": (400, "Enter your current password to set a new one."), "auth.no_password": (400, "This account has no password yet."), diff --git a/local_backend/core/menu_languages.py b/local_backend/core/menu_languages.py new file mode 100644 index 0000000..b3bfb68 --- /dev/null +++ b/local_backend/core/menu_languages.py @@ -0,0 +1,102 @@ +"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29). + +The menu's languages are English and Greek (fixed for now). A product's own name and +description are its base text, in whatever language the venue typed them (usually the venue's +language). Translations add the other language: + + products.translations {"en": {"name": "…", "description": "…", "quick": {"": "…"}}} + categories.translations {"en": {"name": "…"}} + +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). +""" +from __future__ import annotations + +import json + +MENU_LANGUAGES: tuple[str, ...] = ("el", "en") +PRODUCT_FIELDS = ("name", "description") + + +def _load(value): + if value in (None, "", {}): + return {} + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + return {} + return value if isinstance(value, dict) else {} + + +def _bad(what): + from core.errors import XeniaError + return XeniaError("catalog.translation", what=what) + + +def normalize_product(value) -> dict: + """API input → the stored shape; empty texts dropped; unknown languages or fields refused.""" + data = _load(value) + out = {} + for lang, fields in data.items(): + if lang not in MENU_LANGUAGES or not isinstance(fields, dict): + raise _bad(lang) + clean = {} + for k, v in fields.items(): + if k in PRODUCT_FIELDS: + if v is not None and not isinstance(v, str): + raise _bad(f"{lang}.{k}") + if (v or "").strip(): + clean[k] = v.strip() + elif k == "quick": + if not isinstance(v, dict): + raise _bad(f"{lang}.quick") + quick = {str(base): str(text).strip() for base, text in v.items() if str(text or "").strip()} + if quick: + clean["quick"] = quick + else: + raise _bad(f"{lang}.{k}") + if clean: + out[lang] = clean + return out + + +def normalize_category(value) -> dict: + data = _load(value) + out = {} + for lang, fields in data.items(): + if lang not in MENU_LANGUAGES or not isinstance(fields, dict) or set(fields) - {"name"}: + raise _bad(lang) + if (fields.get("name") or "").strip(): + out[lang] = {"name": fields["name"].strip()} + return out + + +def dump(data: dict) -> str | None: + return json.dumps(data, ensure_ascii=False) if data else None + + +def of(row) -> dict: + """A product's or category's stored translations, read safely.""" + return _load(getattr(row, "translations", None)) + + +def texts(base: str | None, translations: dict, field: str) -> dict: + """{language: text} for every menu language: the translation, else the base text.""" + return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES} + + +def quick_texts(base: str, translations: dict) -> dict: + return {lang: ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES} + + +def product_texts(product, customer: bool = True) -> dict: + """{"names": {lang: …}, "descriptions": {lang: …}} for a customer-facing screen. `customer`: + the customer apps' own name / description (digital_*) are the base when set.""" + tr = of(product) + name = (product.digital_name if customer else None) or product.name + desc = (product.digital_description if customer else None) or product.description + return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "description")} diff --git a/local_backend/migrations/versions/0033_menu_translations.py b/local_backend/migrations/versions/0033_menu_translations.py new file mode 100644 index 0000000..b3b4952 --- /dev/null +++ b/local_backend/migrations/versions/0033_menu_translations.py @@ -0,0 +1,26 @@ +"""The menu in other languages (plan step 6.4, core/menu_languages.py): a product's and a +category's translations as JSON {language: {field: text}}; null = none. + +Revision ID: 0033_menu_translations +Revises: 0032_product_allergens +Create Date: 2026-11-18 15:00:00 +""" +from alembic import op +import sqlalchemy as sa + +revision = '0033_menu_translations' +down_revision = '0032_product_allergens' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + for table in ('products', 'categories'): + with op.batch_alter_table(table, schema=None) as batch_op: + batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True)) + + +def downgrade() -> None: + for table in ('products', 'categories'): + with op.batch_alter_table(table, schema=None) as batch_op: + batch_op.drop_column('translations') diff --git a/local_backend/models/product.py b/local_backend/models/product.py index 30bc768..d4370d4 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -22,6 +22,8 @@ class Category(Base): # Its picture in the media library (plan step 5.2); the library refuses to delete it while set media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True) media = relationship("Media", lazy="joined") + # The menu in other languages (plan step 6.4, core/menu_languages.py): {"en": {"name": "…"}} + translations = Column(Text, nullable=True) @property def image(self): @@ -88,6 +90,9 @@ class Product(Base): tags = Column(Text, nullable=True) # The EU allergens it has (plan step 6.3, core/allergens.py): JSON {key: "contains" | "may_contain"} allergens = Column(Text, nullable=True) + # The menu in other languages (plan step 6.4, core/menu_languages.py): + # {"en": {"name": "…", "description": "…", "quick": {"": "…"}}} + translations = Column(Text, nullable=True) # Fiscal printer (ΦΗΜ) fields fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name) diff --git a/local_backend/routers/data_transfer.py b/local_backend/routers/data_transfer.py index 14d2367..8ba1296 100644 --- a/local_backend/routers/data_transfer.py +++ b/local_backend/routers/data_transfer.py @@ -1,6 +1,6 @@ from core.timeutil import venue_date, utcnow import json -from core import allergens, sales_points +from core import allergens, menu_languages, sales_points from datetime import datetime, timezone from fastapi import APIRouter, Depends from fastapi.responses import JSONResponse @@ -61,6 +61,7 @@ def _serialize_product(p: Product) -> dict: "lifecycle_status": p.lifecycle_status, "sort_order": p.sort_order, "sold_at": sales_points.sold_at(p), "allergens": allergens.of(p), + "translations": menu_languages.of(p), "quick_options": quick_options, "options": options, "ingredients": ingredients, "preference_sets": preference_sets, } @@ -77,6 +78,7 @@ def _serialize_category(cat: Category) -> dict: "name": cat.name, "color": cat.color, "sort_order": cat.sort_order, "parent_name": cat.parent.name if cat.parent else None, "general_sort_order": cat.general_sort_order, "auto_expanded": cat.auto_expanded, + "translations": menu_languages.of(cat), "products": products, } @@ -165,6 +167,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De existing.sort_order = cat_data.get("sort_order", 0) existing.general_sort_order = cat_data.get("general_sort_order", 0) existing.auto_expanded = cat_data.get("auto_expanded", False) + if "translations" in cat_data: # 6.4; older bundles: unchanged + existing.translations = menu_languages.dump(menu_languages.normalize_category(cat_data["translations"])) db.flush() return existing else: @@ -175,6 +179,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De parent_id=parent_id, general_sort_order=cat_data.get("general_sort_order", 0), auto_expanded=cat_data.get("auto_expanded", False), + translations=menu_languages.dump(menu_languages.normalize_category(cat_data.get("translations"))), ) db.add(cat) db.flush() @@ -191,6 +196,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De existing.sold_at = sales_points.dump(prod_data["sold_at"]) if "allergens" in prod_data: # 6.3; older bundles: unchanged existing.allergens = allergens.dump(prod_data["allergens"]) + if "translations" in prod_data: # 6.4 + existing.translations = menu_languages.dump(menu_languages.normalize_product(prod_data["translations"])) db.flush() product = existing else: @@ -202,6 +209,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De sort_order=prod_data.get("sort_order", 0), sold_at=sales_points.dump(prod_data.get("sold_at", sales_points.ALL)), allergens=allergens.dump(prod_data.get("allergens")), + translations=menu_languages.dump(menu_languages.normalize_product(prod_data.get("translations"))), ) db.add(product) db.flush() diff --git a/local_backend/routers/menu_tablet.py b/local_backend/routers/menu_tablet.py index d984077..6cb61ec 100644 --- a/local_backend/routers/menu_tablet.py +++ b/local_backend/routers/menu_tablet.py @@ -26,7 +26,7 @@ import time from fastapi import APIRouter, Depends from sqlalchemy.orm import Session -from core import allergens, sales_points +from core import allergens, menu_languages, sales_points from core.access.deps import require_device from core.errors import XeniaError from database import get_db @@ -112,7 +112,8 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet" ids = in_cat.get(c.id, []) has_sub = any(in_cat.get(x.id) for x in by_parent.get(c.id, [])) if ids or has_sub: - out_cats.append({"id": c.id, "name": c.name, "parent_id": c.parent_id, "depth": depth, "products": ids}) + out_cats.append({"id": c.id, "name": c.name, "names": menu_languages.texts(c.name, menu_languages.of(c), "name"), + "parent_id": c.parent_id, "depth": depth, "products": ids}) used.update(ids) shown = [by_id[i] for i in by_id if i in used] prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {} @@ -124,7 +125,7 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet" "config": cfg, "categories": out_cats, "products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p), - "allergens": allergens.of(p), + "allergens": allergens.of(p), **menu_languages.product_texts(p, customer=False), "price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available), "image": media_store.image_of(p.media)} for p in shown}, } diff --git a/local_backend/routers/products.py b/local_backend/routers/products.py index f8ec76c..3ab7713 100644 --- a/local_backend/routers/products.py +++ b/local_backend/routers/products.py @@ -5,7 +5,7 @@ from pydantic import BaseModel from sqlalchemy.orm import Session from typing import List -from core import allergens, sales_points +from core import allergens, menu_languages, sales_points from database import get_db from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup from models.prep_zone import PrepZone @@ -192,6 +192,7 @@ def create_category(body: CategoryCreate, db: Session = Depends(get_db), user: U parent_id=body.parent_id, general_sort_order=body.general_sort_order, media_id=_picture(db, body.media_id), + translations=menu_languages.dump(menu_languages.normalize_category(body.translations)), ) db.add(cat) db.commit() @@ -267,8 +268,10 @@ def update_category(category_id: int, body: CategoryUpdate, db: Session = Depend cat = db.query(Category).filter(Category.id == category_id).first() if not cat: raise XeniaError("catalog.category_not_found") - for field, value in body.model_dump(exclude_none=True, exclude={"media_id"}).items(): + for field, value in body.model_dump(exclude_none=True, exclude={"media_id", "translations"}).items(): setattr(cat, field, value) + if body.translations is not None: + cat.translations = menu_languages.dump(menu_languages.normalize_category(body.translations)) if "media_id" in body.model_fields_set: cat.media_id = _picture(db, body.media_id) db.commit() @@ -369,13 +372,14 @@ def reorder_products(items: List[ProductReorderItem], db: Session = Depends(get_ @router.post("/", response_model=ProductOut, status_code=status.HTTP_201_CREATED) def create_product(body: ProductCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", - "category_id", "primary_category_id", "category_ids", "allergens"}) + "category_id", "primary_category_id", "category_ids", "allergens", "translations"}) if data.get("sort_order") == 0: data["sort_order"] = db.query(Product).count() if body.cost_breakdown is not None: data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown]) data["tags"] = json.dumps(body.tags) if body.tags is not None else None data["allergens"] = allergens.dump(body.allergens) + data["translations"] = menu_languages.dump(menu_languages.normalize_product(body.translations)) data["sold_at"] = sales_points.dump(body.sold_at) data["media_id"] = _picture(db, body.media_id) product = Product(**data) @@ -433,7 +437,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g scalar_fields = body.model_dump( exclude_none=True, exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups", - "category_id", "primary_category_id", "category_ids", "media_id", "allergens"}, + "category_id", "primary_category_id", "category_ids", "media_id", "allergens", "translations"}, ) if "media_id" in body.model_fields_set: product.media_id = _picture(db, body.media_id) @@ -457,6 +461,8 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g product.tags = None if body.allergens is not None: product.allergens = allergens.dump(body.allergens) + if body.translations is not None: + product.translations = menu_languages.dump(menu_languages.normalize_product(body.translations)) if body.quick_options is not None: _replace_quick_options(db, product, body.quick_options) # Modifier groups must be recreated before items so we have the ID map diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index 512b80c..007a2e2 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -140,6 +140,7 @@ class MenuContent(_Strict): show_descriptions: bool = False badges: Dict[str, Badge] = Field(default_factory=dict) # product id → badge sold_out: Literal["strike", "hide"] = "strike" + language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed # how it's laid out (the player pages through what doesn't fit, 5.5b) columns: int = Field(default=2, ge=1, le=3) page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit diff --git a/local_backend/schemas/product.py b/local_backend/schemas/product.py index 747aea7..3773f25 100644 --- a/local_backend/schemas/product.py +++ b/local_backend/schemas/product.py @@ -4,6 +4,7 @@ from typing import Optional, List, Any, Literal, Dict from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at from core.allergens import of as _allergens_of +from core.menu_languages import of as _menu_tr_of, _load as _menu_tr SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"] @@ -16,6 +17,7 @@ class CategoryCreate(BaseModel): general_sort_order: int = 0 auto_expanded: bool = False media_id: Optional[int] = None # its picture in the media library (5.2) + translations: Dict[str, Dict[str, str]] = {} # 6.4: {"en": {"name": "…"}} class CategoryUpdate(BaseModel): @@ -26,6 +28,7 @@ class CategoryUpdate(BaseModel): general_sort_order: Optional[int] = None auto_expanded: Optional[bool] = None media_id: Optional[int] = None # null clears it (sent explicitly) + translations: Optional[Dict[str, Dict[str, str]]] = None # None = unchanged class CategoryOut(BaseModel): @@ -38,9 +41,15 @@ class CategoryOut(BaseModel): auto_expanded: bool = False media_id: Optional[int] = None image: Optional[dict] = None # {id, name, thumb, card, full} (services/media.image_of) + translations: Dict[str, Dict[str, str]] = {} model_config = {"from_attributes": True} + @field_validator("translations", mode="before") + @classmethod + def _tr(cls, v): + return _menu_tr(v) + class CategoryReparentRequest(BaseModel): parent_id: Optional[int] = None @@ -349,6 +358,8 @@ class ProductBase(BaseModel): tags: Optional[List[str]] = None # The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py allergens: Dict[str, str] = {} + # The menu in other languages (6.4, core/menu_languages.py) + translations: Dict[str, Dict[str, Any]] = {} # Service item flag is_service_item: bool = False # Fiscal printer (ΦΗΜ) @@ -397,6 +408,7 @@ class ProductUpdate(BaseModel): # Tags tags: Optional[List[str]] = None allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none + translations: Optional[Dict[str, Dict[str, Any]]] = None # None = unchanged, {} = none # Service item flag is_service_item: Optional[bool] = None # Fiscal printer (ΦΗΜ) @@ -468,6 +480,7 @@ class ProductOut(ProductBase): 'quick_add_enabled': getattr(data, 'quick_add_enabled', True), 'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []), 'allergens': _allergens_of(data), + 'translations': _menu_tr_of(data), 'is_service_item': bool(getattr(data, 'is_service_item', False)), 'fiscal_name': getattr(data, 'fiscal_name', None), 'fiscal_vat_group_id': getattr(data, 'fiscal_vat_group_id', None), diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index 48bd7b8..cf653af 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -11,7 +11,7 @@ Lock behaviour (unchanged): - cloud sets locked=true → lock_pending while a workday is open, locked once it closes - expiry past grace / site deactivated → likewise never mid-service """ -from core import allergens, sales_points +from core import allergens, menu_languages, sales_points from core.access.queries import holders_filter from core.timeutil import utcnow import asyncio @@ -288,11 +288,14 @@ def menu_snapshot(db) -> tuple[dict, list]: "digital_available": bool(p.digital_available), "digital_image_url": p.digital_image_url, "image_url": p.image_url, - "quick_options": [{"id": o.id, "name": o.name, "price": o.price} for o in p.quick_options], + "quick_options": [{"id": o.id, "name": o.name, "price": o.price, + "names": menu_languages.quick_texts(o.name, menu_languages.of(p))} for o in p.quick_options], "allergens": allergens.of(p), # 6.3: {key: "contains" | "may_contain"} + **menu_languages.product_texts(p), # 6.4: names / descriptions {language: text} }) if product_list: payload_categories.append({"id": cat.id, "name": cat.name, "sort_order": cat.sort_order, + "names": menu_languages.texts(cat.name, menu_languages.of(cat), "name"), "products": product_list}) # delivery areas and fee rules (S.3): the cloud applies them at checkout with the same # engine (services/fees.py); the venue's time zone says what "22:00" and "Saturday" mean diff --git a/local_backend/services/signage_menu.py b/local_backend/services/signage_menu.py index cbb2729..3ce7f70 100644 --- a/local_backend/services/signage_menu.py +++ b/local_backend/services/signage_menu.py @@ -15,7 +15,7 @@ counter's: listed ids first in that order, the rest after them in the catalogue' """ from __future__ import annotations -from core import sales_points +from core import menu_languages, sales_points def _descendants(cats_by_parent: dict, roots: list[int]) -> set[int]: @@ -78,10 +78,15 @@ def resolve(db, content: dict, now=None) -> dict: prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {} badges = {int(k): v for k, v in (content.get("badges") or {}).items() if str(k).isdigit()} + lang = content.get("language") # 6.4: the board's language; None = the base texts + + def text(row, base, field): + return menu_languages.texts(base, menu_languages.of(row), field).get(lang, base) if lang else base + def item(p): image = media_store.image_of(p.media) if content.get("show_photos") else None - return {"id": p.id, "name": p.digital_name or p.name, - "description": (p.digital_description or p.description or None) if content.get("show_descriptions") else None, + return {"id": p.id, "name": text(p, p.digital_name or p.name, "name"), + "description": text(p, p.digital_description or p.description or None, "description") if content.get("show_descriptions") else None, "price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available), "image": image["card"] if image else None, "badge": badges.get(p.id)} @@ -90,7 +95,7 @@ def resolve(db, content: dict, now=None) -> dict: groups: dict = {} for p in products: groups.setdefault(p.primary_category_id, []).append(p) - out = [{"category": {"id": cid, "name": by_id[cid].name} if cid in by_id else None, + out = [{"category": {"id": cid, "name": text(by_id[cid], by_id[cid].name, "name")} if cid in by_id else None, "items": [item(p) for p in sorted(ps, key=prod_key)]} for cid, ps in sorted(groups.items(), key=lambda kv: cat_key(kv[0]))] else: diff --git a/local_backend/tests/test_menu_languages.py b/local_backend/tests/test_menu_languages.py new file mode 100644 index 0000000..6a23fbc --- /dev/null +++ b/local_backend/tests/test_menu_languages.py @@ -0,0 +1,84 @@ +"""The menu in English and Greek (plan step 6.4, owner 2026-11-18): translations of product names, +descriptions, quick options and category names; a missing one shows the base text. Customer +screens use them (cloud menu, menu tablet, signage boards); tickets and staff screens don't.""" +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_menu_tablet import menu, tablet # noqa: F401 (fixtures) + +EN = {"en": {"name": "Pork souvlaki", "description": "On a skewer", "quick": {"Pita": "Pitta bread"}}} + + +def test_translations_are_stored_cleaned_and_validated(client, owner_h, menu): + pid = menu["souvlaki"].id + r = client.put(f"/api/products/{pid}", headers=owner_h, json={"translations": {"en": {"name": " Pork souvlaki ", "description": ""}}}) + assert r.status_code == 200, r.text + assert r.json()["translations"] == {"en": {"name": "Pork souvlaki"}} # trimmed, empty dropped + assert client.put(f"/api/products/{pid}", headers=owner_h, json={"base_price": 4}).json()["translations"]["en"]["name"] == "Pork souvlaki" + for bad in ({"fr": {"name": "x"}}, {"en": {"colour": "x"}}, {"en": {"quick": ["x"]}}): + r = client.put(f"/api/products/{pid}", headers=owner_h, json={"translations": bad}) + assert r.status_code == 422 and err(r) == "catalog.translation", bad + cat = menu["cats"]["grill"] + r = client.put(f"/api/products/categories/{cat}", headers=owner_h, json={"translations": {"en": {"name": "From the grill"}}}) + assert r.status_code == 200 and r.json()["translations"] == {"en": {"name": "From the grill"}} + assert client.put(f"/api/products/categories/{cat}", headers=owner_h, json={"translations": {"en": {"title": "x"}}}).status_code == 422 + + +def test_the_tablet_switches_names_and_falls_back_to_the_base(client, owner_h, menu, tablet): + client.put(f"/api/products/{menu['souvlaki'].id}", headers=owner_h, json={"translations": EN}) + client.put(f"/api/products/categories/{menu['cats']['grill']}", headers=owner_h, json={"translations": {"en": {"name": "Grill (en)"}}}) + data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json() + souv = data["products"][str(menu["souvlaki"].id)] + assert souv["names"] == {"el": "Souvlaki", "en": "Pork souvlaki"} and souv["name"] == "Souvlaki" + assert souv["descriptions"]["en"] == "On a skewer" + steak = data["products"][str(menu["steak"].id)] + assert steak["names"] == {"el": "Steak", "en": "Steak"} # not translated: the base name + grill = next(c for c in data["categories"] if c["id"] == menu["cats"]["grill"]) + assert grill["names"] == {"el": "Grill", "en": "Grill (en)"} + + +def test_the_cloud_menu_carries_names_per_language(client, db, owner_h, menu): + from models.product import ProductQuickOption + db.add(ProductQuickOption(product_id=menu["souvlaki"].id, name="Pita", price=0.5)) + db.commit() + client.put(f"/api/products/{menu['souvlaki'].id}", headers=owner_h, json={"translations": EN}) + from services.cloud_sync import menu_snapshot + snap, _ = menu_snapshot(db) + grill = next(c for c in snap["categories"] if c["id"] == menu["cats"]["grill"]) + souv = next(p for p in grill["products"] if p["id"] == menu["souvlaki"].id) + assert souv["names"] == {"el": "Souvlaki", "en": "Pork souvlaki"} and souv["name"] == "Souvlaki" + assert souv["quick_options"][0]["names"] == {"el": "Pita", "en": "Pitta bread"} + assert grill["names"] == {"el": "Grill", "en": "Grill"} + + +def test_a_board_in_english_and_tickets_stay_in_the_base(client, db, owner_h, menu): + client.put(f"/api/products/{menu['souvlaki'].id}", headers=owner_h, json={"translations": EN}) + from services.signage_menu import resolve + names = lambda lang: [i["name"] for g in resolve(db, {"select": "all", "language": lang})["groups"] for i in g["items"]] # noqa: E731 + assert "Pork souvlaki" in names("en") and "Souvlaki" not in names("en") + assert "Souvlaki" in names(None) and "Souvlaki" in names("el") + # what the staff see (phones, counter): the base name + assert next(p for p in client.get("/api/products/", headers=owner_h).json() if p["id"] == menu["souvlaki"].id)["name"] == "Souvlaki" + + +def test_catalogue_bundle_keeps_translations(client, db, owner_h, menu): + client.put(f"/api/products/{menu['beer'].id}", headers=owner_h, json={"translations": {"en": {"name": "Lager"}}}) + client.put(f"/api/products/categories/{menu['cats']['drinks']}", headers=owner_h, json={"translations": {"en": {"name": "Drinks (en)"}}}) + bundle = client.get("/api/data-transfer/export/catalog", headers=owner_h).json() + client.put(f"/api/products/{menu['beer'].id}", headers=owner_h, json={"translations": {}}) + client.put(f"/api/products/categories/{menu['cats']['drinks']}", headers=owner_h, json={"translations": {}}) + assert client.post("/api/data-transfer/import/catalog", headers=owner_h, json=bundle).status_code < 300 + db.expire_all() + from core.menu_languages import of + from models.product import Category, Product + assert of(db.get(Product, menu["beer"].id)) == {"en": {"name": "Lager"}} + assert of(db.get(Category, menu["cats"]["drinks"])) == {"en": {"name": "Drinks (en)"}} + + + +def test_the_frontend_list_matches_the_backend(): + """packages/access/src/menuLanguages.js keeps the same languages.""" + import re + from pathlib import Path + from core.menu_languages import MENU_LANGUAGES + js = (Path(__file__).resolve().parents[2] / "packages" / "access" / "src" / "menuLanguages.js").read_text(encoding="utf-8") + listed = re.search(r"export const MENU_LANGUAGES = \[([^\]]*)\]", js).group(1) + assert [x.strip().strip("'") for x in listed.split(",") if x.strip()] == list(MENU_LANGUAGES) diff --git a/manager_dashboard/src/pages/products/CategoryDialog.jsx b/manager_dashboard/src/pages/products/CategoryDialog.jsx index d26d9ec..44c6ab5 100644 --- a/manager_dashboard/src/pages/products/CategoryDialog.jsx +++ b/manager_dashboard/src/pages/products/CategoryDialog.jsx @@ -2,6 +2,7 @@ // (top level or under another category). import { useState } from 'react' import { Check } from 'lucide-react' +import { translatedLanguages, useAccess } from '@xenia/access' import { useTranslation } from '@xenia/i18n' import { Button, Dialog, Field, Input, Select, cx } from '@xenia/ui' import MediaField from '../media/MediaField' @@ -13,16 +14,25 @@ export default function CategoryDialog({ category, parentName, saving, onSave, o const [name, setName] = useState(category.name ?? '') const [color, setColor] = useState(category.color ?? CATEGORY_COLOURS[0]) const [image, setImage] = useState(category.image ?? null) + const { venue } = useAccess() + const others = translatedLanguages(venue?.language) + const [tr, setTr] = useState(() => Object.fromEntries(others.map(l => [l, category.translations?.[l]?.name ?? '']))) const sub = !!category.parent_id const title = t(`products.category.${category.id ? 'edit' : 'new'}${sub ? 'Sub' : ''}`) return ( - + }>
setName(e.target.value)} autoFocus data-testid="category-name" /> + {others.map(l => ( + + setTr(s => ({ ...s, [l]: e.target.value }))} placeholder={name} data-testid={`category-name-${l}`} /> + + ))}
{t('products.category.colour')} diff --git a/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx b/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx index 95410ae..b5b9c3e 100644 --- a/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx +++ b/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx @@ -7,6 +7,7 @@ // shared sub-set shown for every choice except those marked to hide it import { useRef, useState } from 'react' import { Heart, Plus, Trash2 } from 'lucide-react' +import { translatedLanguages, useAccess } from '@xenia/access' import { useTranslation } from '@xenia/i18n' import { Button, EmptyState, IconButton, Input, Select, cx } from '@xenia/ui' import { favourites, moveChoice, moveFavourite, moveItem, removeChoice, removeGroup, setSub, toggleFavourite } from './formLogic' @@ -96,8 +97,10 @@ function Favourites({ form, setForm }) { function QuickList({ form, setForm }) { const { t } = useTranslation('manager') + const { venue } = useAccess() + const others = translatedLanguages(venue?.language) const set = (i, k, v) => setForm(f => ({ ...f, quick_options: f.quick_options.map((q, j) => (j === i ? { ...q, [k]: v } : q)) })) - const add = () => setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, is_favorite: false, favorite_sort_order: 0, is_compact: false }] })) + const add = () => setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, is_favorite: false, favorite_sort_order: 0, is_compact: false, tr: {} }] })) return (
@@ -109,6 +112,10 @@ function QuickList({ form, setForm }) { onUp={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, -1) }))} onDown={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, 1) }))} /> setForm(f => toggleFavourite(f, 'quick', i))} /> set(i, 'name', e.target.value)} placeholder={t('products.editor.quickPlaceholder')} /> + {others.map(l => ( + set(i, 'tr', { ...(q.tr ?? {}), [l]: e.target.value })} + placeholder={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} aria-label={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} /> + ))} set(i, 'price', v)} label={t('products.editor.extraCost')} /> set(i, 'allow_multiple', v)}>{t('products.editor.multiple')} set(i, 'is_compact', v)}>{t('products.editor.compact')} diff --git a/manager_dashboard/src/pages/products/editor/InfoTabs.jsx b/manager_dashboard/src/pages/products/editor/InfoTabs.jsx index d659aec..0dc9233 100644 --- a/manager_dashboard/src/pages/products/editor/InfoTabs.jsx +++ b/manager_dashboard/src/pages/products/editor/InfoTabs.jsx @@ -4,18 +4,20 @@ import { useState } from 'react' import { Link } from 'react-router-dom' import { Plus, Trash2, X } from 'lucide-react' -import { SALES_POINTS } from '@xenia/access' +import { SALES_POINTS, translatedLanguages, useAccess } from '@xenia/access' import { useFormat, useTranslation } from '@xenia/i18n' import { Button, Field, IconButton, InfoTip, Input, Select, Switch, Textarea, cx } from '@xenia/ui' import MediaField from '../../media/MediaField' import { costOf } from '../productsLogic' import { AllergensField, CategoriesField } from './Fields' -import { UNITS, WEIGHED, cleanTag } from './formLogic' +import { UNITS, WEIGHED, cleanTag, setTranslation } from './formLogic' import { Check, PriceInput } from './parts' export function InfoTab({ form, set, setForm, categories, prepZones }) { const { t } = useTranslation('manager') + const { venue } = useAccess() const service = form.is_service_item + const others = translatedLanguages(venue?.language) return (
set('is_service_item', v)} label={t('products.editor.serviceItem')} @@ -29,6 +31,20 @@ export function InfoTab({ form, set, setForm, categories, prepZones }) {