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 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 10:47:03 +02:00
co-authored by Claude Opus 5.5
parent 5048f82a4c
commit e395d99704
32 changed files with 459 additions and 38 deletions
+1
View File
@@ -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."),
+102
View File
@@ -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": {"<quick option's name>": "…"}}}
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")}
@@ -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')
+5
View File
@@ -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": {"<quick option>": "…"}}}
translations = Column(Text, nullable=True)
# Fiscal printer (ΦΗΜ) fields
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
+9 -1
View File
@@ -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()
+4 -3
View File
@@ -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},
}
+10 -4
View File
@@ -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
+1
View File
@@ -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
+13
View File
@@ -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),
+5 -2
View File
@@ -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
+9 -4
View File
@@ -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:
@@ -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)