feat(products): every menu text per language, the editor's language picker, service item dialog
- Alembic 0042: a `translations` column on every choice (groups, quick options, extras, ingredients, preference sets and choices; sub-choices and shared sub-sets in their JSON); the texts typed so far become the text in their language (Greek letters → el, else the venue's); the product's old quick map moves onto the quick options. API, catalogue bundle and the cloud's quick option names carry them; names are checked before anything is replaced. - Editor: a language picker beside the close button (Default = the venue's language, plus every menu language) drives every name and description, left and right; an empty language shows what is used instead as its placeholder. The shown name is the venue language's, else any (never mixed). - Choices: one name field; the shared controls at one height (heart red when on, several / compact… chips coloured when on, delete red on hover); "+ Preference" at the right end of the tab strip; preference groups made inside a preference. - Categories: the shared dropdown to add one; the category dialog per language. - The service item switch is gone: "New service item" opens its own small dialog. - UI: Dialog headerEnd; a toned toggle keeps its colour while pressed. - Tests: backend (choice names, migration 0042), access, editor logic, e2e. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,21 @@
|
||||
"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29).
|
||||
"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29; every text per
|
||||
language, owner 2026-11-21).
|
||||
|
||||
Since 2026-11-21 (Alembic 0042) every text of the menu is kept **per language**, the venue's own
|
||||
language included: a product's name and description, a category's name, and every choice's name
|
||||
(quick options, ingredients, extras and their sub-choices, preference sets, their choices,
|
||||
sub-choices and shared sub-set, choice groups). The editor's "Default" is the venue's language
|
||||
(`venue.language`). The row's own `name` / `description` is the text shown when a language has
|
||||
none: the venue language's, else the first language that has one. So when the venue changes its
|
||||
language, the new language starts empty ("Default" is empty) but the item keeps showing its only
|
||||
text everywhere; languages are never mixed.
|
||||
|
||||
products.translations {"el": {"name": "…", "description": "…"}, "en": {…}}
|
||||
categories.translations {"el": {"name": "…"}, …}
|
||||
a choice's translations {"el": "…", "en": "…"} (the rows' column; sub-choices inside their JSON)
|
||||
|
||||
Before 0042 the base text had no language and quick options were translated on the product
|
||||
(`"quick": {"<quick option's name>": "…"}`); 0042 moved those onto the quick options.
|
||||
|
||||
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
|
||||
@@ -89,8 +106,11 @@ def texts(base: str | None, translations: dict, field: str) -> dict:
|
||||
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 quick_texts(base: str, translations: dict, own: dict | None = None) -> dict:
|
||||
"""A quick option's texts: its own translations (since 0042), else the product's old
|
||||
`quick` map, else the base text."""
|
||||
own = own or {}
|
||||
return {lang: own.get(lang) or ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES}
|
||||
|
||||
|
||||
def product_texts(product, customer: bool = True) -> dict:
|
||||
@@ -100,3 +120,28 @@ def product_texts(product, customer: bool = True) -> dict:
|
||||
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")}
|
||||
|
||||
|
||||
def normalize_names(value) -> dict:
|
||||
"""A choice's translations {language: text}: API input → stored; empty texts dropped."""
|
||||
data = _load(value)
|
||||
out = {}
|
||||
for lang, text in data.items():
|
||||
if text is not None and not isinstance(text, str):
|
||||
raise _bad(str(lang))
|
||||
if not (text or "").strip():
|
||||
continue # empty: nothing to keep, whatever the language
|
||||
if lang not in MENU_LANGUAGES:
|
||||
raise _bad(str(lang))
|
||||
out[lang] = text.strip()
|
||||
return out
|
||||
|
||||
|
||||
def names_of(row) -> dict:
|
||||
"""A choice row's translations {language: text}, read safely."""
|
||||
return {k: v for k, v in _load(getattr(row, "translations", None)).items() if isinstance(v, str)}
|
||||
|
||||
|
||||
def name_texts(base: str, names: dict) -> dict:
|
||||
"""{language: text} of a choice for every menu language: its own, else the base text."""
|
||||
return {lang: names.get(lang) or base for lang in MENU_LANGUAGES}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Every menu text per language (owner 2026-11-21, core/menu_languages.py).
|
||||
|
||||
- Every choice gets its own `translations` {language: text}: choice groups, quick options,
|
||||
extras, ingredients, preference sets and their choices (sub-choices and a set's shared
|
||||
sub-set keep theirs inside their JSON).
|
||||
- The texts typed so far had no language: they become the text **in their language**: Greek
|
||||
letters → "el", else the venue's language (`venue.language`, default "en"). A language that
|
||||
already had a translation keeps it.
|
||||
- The product's old `"quick": {"<quick option's name>": "…"}` translations move onto the quick
|
||||
options.
|
||||
|
||||
Revision ID: 0042_menu_texts_per_language
|
||||
Revises: 0041_floor_item_color
|
||||
Create Date: 2026-11-21 12:00:00
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0042_menu_texts_per_language'
|
||||
down_revision = '0041_floor_item_color'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
CHOICE_TABLES = ('product_modifier_groups', 'product_quick_options', 'product_options', 'product_ingredients',
|
||||
'product_preference_sets', 'product_preference_choices')
|
||||
GREEK = re.compile('[Ͱ-Ͽἀ-]')
|
||||
LANGS = ('el', 'en')
|
||||
|
||||
|
||||
def _load(v):
|
||||
if not v:
|
||||
return {}
|
||||
try:
|
||||
d = json.loads(v)
|
||||
except ValueError:
|
||||
return {}
|
||||
return d if isinstance(d, (dict, list)) else {}
|
||||
|
||||
|
||||
def _dump(d):
|
||||
return json.dumps(d, ensure_ascii=False) if d else None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
for table in CHOICE_TABLES:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
|
||||
|
||||
bind = op.get_bind()
|
||||
row = bind.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'venue.language'")).first()
|
||||
venue = (row[0] if row else None) or 'en'
|
||||
venue = venue if venue in LANGS else 'en'
|
||||
|
||||
def lang_of(text):
|
||||
return 'el' if GREEK.search(text or '') else venue
|
||||
|
||||
def names(text, current=None):
|
||||
out = dict(current or {})
|
||||
if (text or '').strip():
|
||||
out.setdefault(lang_of(text), text.strip())
|
||||
return out
|
||||
|
||||
def subs(raw):
|
||||
"""Sub-choices (a JSON list of dicts) with their names per language."""
|
||||
data = _load(raw)
|
||||
if not isinstance(data, list) or not data:
|
||||
return raw
|
||||
for s in data:
|
||||
if isinstance(s, dict):
|
||||
s['translations'] = names(s.get('name'), s.get('translations') if isinstance(s.get('translations'), dict) else None)
|
||||
return json.dumps(data, ensure_ascii=False)
|
||||
|
||||
# products: name / description in their language; the quick options' translations move out
|
||||
quick_moved = {}
|
||||
for pid, name, desc, tr in bind.execute(sa.text("SELECT id, name, description, translations FROM products")).fetchall():
|
||||
data = _load(tr)
|
||||
data = data if isinstance(data, dict) else {}
|
||||
for lang, fields in list(data.items()):
|
||||
if not isinstance(fields, dict):
|
||||
data.pop(lang)
|
||||
continue
|
||||
for base, text in (fields.pop('quick', None) or {}).items():
|
||||
quick_moved.setdefault(pid, {}).setdefault(base, {})[lang] = text
|
||||
for field, text in (('name', name), ('description', desc)):
|
||||
if (text or '').strip():
|
||||
data.setdefault(lang_of(text), {}).setdefault(field, text.strip())
|
||||
data = {k: v for k, v in data.items() if v}
|
||||
bind.execute(sa.text("UPDATE products SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': pid})
|
||||
|
||||
for cid, name, tr in bind.execute(sa.text("SELECT id, name, translations FROM categories")).fetchall():
|
||||
data = _load(tr)
|
||||
data = data if isinstance(data, dict) else {}
|
||||
if (name or '').strip():
|
||||
data.setdefault(lang_of(name), {}).setdefault('name', name.strip())
|
||||
bind.execute(sa.text("UPDATE categories SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': cid})
|
||||
|
||||
for qid, pid, name in bind.execute(sa.text("SELECT id, product_id, name FROM product_quick_options")).fetchall():
|
||||
bind.execute(sa.text("UPDATE product_quick_options SET translations = :t WHERE id = :id"),
|
||||
{'t': _dump(names(name, quick_moved.get(pid, {}).get(name))), 'id': qid})
|
||||
for table in ('product_modifier_groups', 'product_ingredients'):
|
||||
for rid, name in bind.execute(sa.text(f"SELECT id, name FROM {table}")).fetchall():
|
||||
bind.execute(sa.text(f"UPDATE {table} SET translations = :t WHERE id = :id"), {'t': _dump(names(name)), 'id': rid})
|
||||
for table in ('product_options', 'product_preference_choices'):
|
||||
for rid, name, sub in bind.execute(sa.text(f"SELECT id, name, sub_choices FROM {table}")).fetchall():
|
||||
bind.execute(sa.text(f"UPDATE {table} SET translations = :t, sub_choices = :s WHERE id = :id"),
|
||||
{'t': _dump(names(name)), 's': subs(sub), 'id': rid})
|
||||
for rid, name, shared in bind.execute(sa.text("SELECT id, name, shared_subset FROM product_preference_sets")).fetchall():
|
||||
data = _load(shared)
|
||||
if isinstance(data, dict) and data:
|
||||
data['translations'] = names(data.get('name'))
|
||||
data['choices'] = json.loads(subs(json.dumps(data.get('choices') or [])) or '[]')
|
||||
shared = json.dumps(data, ensure_ascii=False)
|
||||
bind.execute(sa.text("UPDATE product_preference_sets SET translations = :t, shared_subset = :s WHERE id = :id"),
|
||||
{'t': _dump(names(name)), 's': shared, 'id': rid})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in CHOICE_TABLES:
|
||||
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||
batch_op.drop_column('translations')
|
||||
@@ -140,6 +140,8 @@ class ProductModifierGroup(Base):
|
||||
modifier_type = Column(String, nullable=False)
|
||||
name = Column(String, nullable=False)
|
||||
sort_order = Column(Integer, default=0, nullable=False)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
product = relationship("Product", back_populates="modifier_groups")
|
||||
|
||||
@@ -162,6 +164,8 @@ class ProductOption(Base):
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Optional group/folder this option belongs to
|
||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
product = relationship("Product", back_populates="options")
|
||||
|
||||
@@ -178,6 +182,8 @@ class ProductQuickOption(Base):
|
||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||
favorite_sort_order = Column(Integer, default=0, nullable=False)
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
product = relationship("Product", back_populates="quick_options")
|
||||
|
||||
@@ -195,6 +201,8 @@ class ProductIngredient(Base):
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Optional group/folder this ingredient belongs to
|
||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
product = relationship("Product", back_populates="ingredients")
|
||||
|
||||
@@ -217,6 +225,8 @@ class ProductPreferenceSet(Base):
|
||||
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
||||
# When True, each selected choice can have a quantity (x2, x3, …)
|
||||
allow_choice_quantity = Column(Boolean, default=False, nullable=False)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
product = relationship("Product", back_populates="preference_sets")
|
||||
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
|
||||
@@ -236,6 +246,8 @@ class ProductPreferenceChoice(Base):
|
||||
disables_subset = Column(Boolean, default=False, nullable=False)
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||
translations = Column(Text, nullable=True)
|
||||
|
||||
set = relationship("ProductPreferenceSet", back_populates="choices")
|
||||
|
||||
|
||||
@@ -22,11 +22,17 @@ EXPORT_VERSION = 1 # tables bundle
|
||||
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23)
|
||||
|
||||
|
||||
def _names(value):
|
||||
"""A choice's names per language from a bundle (0042), stored cleaned."""
|
||||
return menu_languages.dump(menu_languages.normalize_names(value))
|
||||
|
||||
|
||||
def _serialize_product(p: Product) -> dict:
|
||||
quick_options = [
|
||||
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
|
||||
"sort_order": qo.sort_order, "is_favorite": qo.is_favorite,
|
||||
"favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact}
|
||||
"favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact,
|
||||
"translations": menu_languages.names_of(qo)}
|
||||
for qo in p.quick_options
|
||||
]
|
||||
options = []
|
||||
@@ -34,10 +40,12 @@ def _serialize_product(p: Product) -> dict:
|
||||
sub = json.loads(opt.sub_choices) if opt.sub_choices else []
|
||||
options.append({"name": opt.name, "extra_cost": opt.extra_cost,
|
||||
"allow_multiple": opt.allow_multiple, "sub_choices": sub,
|
||||
"is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order})
|
||||
"is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(opt)})
|
||||
ingredients = [
|
||||
{"name": ing.name, "extra_cost": ing.extra_cost,
|
||||
"is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order}
|
||||
"is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(ing)}
|
||||
for ing in p.ingredients
|
||||
]
|
||||
preference_sets = []
|
||||
@@ -50,11 +58,13 @@ def _serialize_product(p: Product) -> dict:
|
||||
default_index = i
|
||||
sub = json.loads(ch.sub_choices) if ch.sub_choices else []
|
||||
choices.append({"name": ch.name, "extra_cost": ch.extra_cost,
|
||||
"sub_choices": sub, "disables_subset": ch.disables_subset})
|
||||
"sub_choices": sub, "disables_subset": ch.disables_subset,
|
||||
"translations": menu_languages.names_of(ch)})
|
||||
preference_sets.append({
|
||||
"name": ps.name, "choices": choices,
|
||||
"default_choice_index": default_index, "shared_subset": shared,
|
||||
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(ps),
|
||||
})
|
||||
return {
|
||||
"name": p.name, "base_price": p.base_price, "is_available": p.is_available,
|
||||
@@ -226,7 +236,9 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
db.flush()
|
||||
|
||||
for qo in prod_data.get("quick_options", []):
|
||||
db.add(ProductQuickOption(product_id=product.id, **qo))
|
||||
qo = dict(qo)
|
||||
names = _names(qo.pop("translations", None))
|
||||
db.add(ProductQuickOption(product_id=product.id, **qo, translations=names))
|
||||
|
||||
for opt in prod_data.get("options", []):
|
||||
sub_json = json.dumps(opt.get("sub_choices", []))
|
||||
@@ -234,11 +246,13 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
product_id=product.id, name=opt["name"], extra_cost=opt.get("extra_cost", 0.0),
|
||||
allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json,
|
||||
is_favorite=opt.get("is_favorite", False),
|
||||
favorite_sort_order=opt.get("favorite_sort_order", 0),
|
||||
favorite_sort_order=opt.get("favorite_sort_order", 0), translations=_names(opt.get("translations")),
|
||||
))
|
||||
|
||||
for ing in prod_data.get("ingredients", []):
|
||||
db.add(ProductIngredient(product_id=product.id, **ing))
|
||||
ing = dict(ing)
|
||||
names = _names(ing.pop("translations", None))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing, translations=names))
|
||||
|
||||
for ps_data in prod_data.get("preference_sets", []):
|
||||
shared_json = json.dumps(ps_data["shared_subset"]) if ps_data.get("shared_subset") else None
|
||||
@@ -246,7 +260,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
product_id=product.id, name=ps_data["name"],
|
||||
shared_subset=shared_json,
|
||||
is_favorite=ps_data.get("is_favorite", False),
|
||||
favorite_sort_order=ps_data.get("favorite_sort_order", 0),
|
||||
favorite_sort_order=ps_data.get("favorite_sort_order", 0), translations=_names(ps_data.get("translations")),
|
||||
)
|
||||
db.add(ps)
|
||||
db.flush()
|
||||
@@ -255,7 +269,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
sub_json = json.dumps(ch.get("sub_choices", []))
|
||||
choice = ProductPreferenceChoice(
|
||||
set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0),
|
||||
sub_choices=sub_json, disables_subset=ch.get("disables_subset", False),
|
||||
sub_choices=sub_json, disables_subset=ch.get("disables_subset", False), translations=_names(ch.get("translations")),
|
||||
)
|
||||
db.add(choice)
|
||||
db.flush()
|
||||
|
||||
@@ -26,6 +26,35 @@ from core.errors import XeniaError
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _sub_dump(sub) -> dict:
|
||||
"""A sub-choice (or a shared sub-set) as stored: its names per language cleaned (0042)."""
|
||||
d = sub.model_dump()
|
||||
d["translations"] = menu_languages.normalize_names(d.get("translations"))
|
||||
if "choices" in d:
|
||||
d["choices"] = [_sub_dump(c) for c in sub.choices]
|
||||
return d
|
||||
|
||||
|
||||
def _check_names(body) -> None:
|
||||
"""Every choice's names valid before anything is replaced (a refusal changes nothing)."""
|
||||
subs = lambda xs: [menu_languages.normalize_names(x.translations) for x in xs or []] # noqa: E731
|
||||
for g in body.modifier_groups or []:
|
||||
menu_languages.normalize_names(g.translations)
|
||||
for x in [*(body.quick_options or []), *(body.ingredients or [])]:
|
||||
menu_languages.normalize_names(x.translations)
|
||||
for o in body.options or []:
|
||||
menu_languages.normalize_names(o.translations)
|
||||
subs(o.sub_choices)
|
||||
for ps in body.preference_sets or []:
|
||||
menu_languages.normalize_names(ps.translations)
|
||||
for c in ps.choices:
|
||||
menu_languages.normalize_names(c.translations)
|
||||
subs(c.sub_choices)
|
||||
if ps.shared_subset:
|
||||
menu_languages.normalize_names(ps.shared_subset.translations)
|
||||
subs(ps.shared_subset.choices)
|
||||
|
||||
|
||||
def _broadcast_products_changed():
|
||||
broadcast_sync("products_changed", {})
|
||||
|
||||
@@ -43,6 +72,7 @@ def _replace_modifier_groups(db, product, groups):
|
||||
modifier_type=g.modifier_type,
|
||||
name=g.name,
|
||||
sort_order=i,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(g.translations)),
|
||||
)
|
||||
db.add(new_g)
|
||||
db.flush()
|
||||
@@ -64,6 +94,7 @@ def _replace_quick_options(db, product, quick_options):
|
||||
is_favorite=qo.is_favorite,
|
||||
favorite_sort_order=qo.favorite_sort_order,
|
||||
is_compact=qo.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
|
||||
))
|
||||
|
||||
|
||||
@@ -72,7 +103,7 @@ def _replace_options(db, product, options, group_id_map=None):
|
||||
db.delete(opt)
|
||||
db.flush()
|
||||
for opt in options:
|
||||
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
|
||||
resolved_group = group_id_map[opt.group_id] if (group_id_map and opt.group_id is not None and opt.group_id < len(group_id_map)) else None
|
||||
db.add(ProductOption(
|
||||
product_id=product.id,
|
||||
@@ -85,6 +116,7 @@ def _replace_options(db, product, options, group_id_map=None):
|
||||
favorite_sort_order=opt.favorite_sort_order,
|
||||
is_compact=opt.is_compact,
|
||||
group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
|
||||
))
|
||||
|
||||
|
||||
@@ -94,7 +126,8 @@ def _replace_ingredients(db, product, ingredients, group_id_map=None):
|
||||
db.flush()
|
||||
for ing in ingredients:
|
||||
resolved_group = group_id_map[ing.group_id] if (group_id_map and ing.group_id is not None and ing.group_id < len(group_id_map)) else None
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
|
||||
|
||||
|
||||
def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group_id_map=None):
|
||||
@@ -102,7 +135,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
db.delete(ps)
|
||||
db.flush()
|
||||
for ps in sets:
|
||||
shared_json = json.dumps(ps.shared_subset.model_dump()) if ps.shared_subset else None
|
||||
shared_json = json.dumps(_sub_dump(ps.shared_subset), ensure_ascii=False) if ps.shared_subset else None
|
||||
resolved_group = group_id_map[ps.group_id] if (group_id_map and ps.group_id is not None and ps.group_id < len(group_id_map)) else None
|
||||
new_set = ProductPreferenceSet(
|
||||
product_id=product.id,
|
||||
@@ -113,12 +146,13 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
group_id=resolved_group,
|
||||
allow_multi_select=ps.allow_multi_select,
|
||||
allow_choice_quantity=ps.allow_choice_quantity,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ps.translations)),
|
||||
)
|
||||
db.add(new_set)
|
||||
db.flush()
|
||||
created_choices = []
|
||||
for ch in ps.choices:
|
||||
sub_json = json.dumps([s.model_dump() for s in ch.sub_choices]) if ch.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in ch.sub_choices], ensure_ascii=False) if ch.sub_choices else None
|
||||
choice = ProductPreferenceChoice(
|
||||
set_id=new_set.id,
|
||||
name=ch.name,
|
||||
@@ -126,6 +160,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
sub_choices=sub_json,
|
||||
disables_subset=ch.disables_subset,
|
||||
is_compact=ch.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ch.translations)),
|
||||
)
|
||||
db.add(choice)
|
||||
db.flush()
|
||||
@@ -371,6 +406,7 @@ 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)):
|
||||
_check_names(body)
|
||||
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", "translations"})
|
||||
if data.get("sort_order") == 0:
|
||||
@@ -400,11 +436,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
|
||||
is_favorite=qo.is_favorite,
|
||||
favorite_sort_order=qo.favorite_sort_order,
|
||||
is_compact=qo.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
|
||||
))
|
||||
created_groups = _replace_modifier_groups(db, product, body.modifier_groups)
|
||||
group_id_map = [g.id for g in created_groups]
|
||||
for opt in body.options:
|
||||
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
|
||||
resolved_group = group_id_map[opt.group_id] if (opt.group_id is not None and opt.group_id < len(group_id_map)) else None
|
||||
db.add(ProductOption(
|
||||
product_id=product.id,
|
||||
@@ -417,10 +454,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
|
||||
favorite_sort_order=opt.favorite_sort_order,
|
||||
is_compact=opt.is_compact,
|
||||
group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
|
||||
))
|
||||
for ing in body.ingredients:
|
||||
resolved_group = group_id_map[ing.group_id] if (ing.group_id is not None and ing.group_id < len(group_id_map)) else None
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
|
||||
_replace_preference_sets(db, product, body.preference_sets, group_id_map)
|
||||
db.commit()
|
||||
db.refresh(product)
|
||||
@@ -434,6 +473,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise XeniaError("product.not_found")
|
||||
_check_names(body)
|
||||
scalar_fields = body.model_dump(
|
||||
exclude_none=True,
|
||||
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
|
||||
@@ -495,7 +535,8 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise XeniaError("product.not_found")
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order)
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(body.translations)))
|
||||
db.add(g)
|
||||
db.commit()
|
||||
db.refresh(g)
|
||||
|
||||
@@ -4,7 +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
|
||||
from core.menu_languages import of as _menu_tr_of, _load as _menu_tr, names_of as _choice_names
|
||||
|
||||
SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
|
||||
|
||||
@@ -76,6 +76,7 @@ class ModifierGroupCreate(BaseModel):
|
||||
modifier_type: str # "option" | "ingredient" | "preference"
|
||||
name: str
|
||||
sort_order: int = 0
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ModifierGroupOut(BaseModel):
|
||||
@@ -84,9 +85,15 @@ class ModifierGroupOut(BaseModel):
|
||||
modifier_type: str
|
||||
name: str
|
||||
sort_order: int = 0
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Quick Options ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -98,6 +105,7 @@ class ProductQuickOptionCreate(BaseModel):
|
||||
is_favorite: bool = False
|
||||
favorite_sort_order: int = 0
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductQuickOptionOut(BaseModel):
|
||||
@@ -110,9 +118,15 @@ class ProductQuickOptionOut(BaseModel):
|
||||
is_favorite: bool = False
|
||||
favorite_sort_order: int = 0
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Options ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -124,6 +138,7 @@ class OptionSubChoice(BaseModel):
|
||||
allow_multiple: bool = False
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductOptionBase(BaseModel):
|
||||
@@ -137,6 +152,7 @@ class ProductOptionBase(BaseModel):
|
||||
# When True renders the option itself as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
group_id: Optional[int] = None
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductOptionCreate(ProductOptionBase):
|
||||
@@ -168,6 +184,7 @@ class ProductOptionOut(ProductOptionBase):
|
||||
'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0,
|
||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||
'group_id': getattr(data, 'group_id', None),
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -182,6 +199,7 @@ class ProductIngredientBase(BaseModel):
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
group_id: Optional[int] = None
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductIngredientCreate(ProductIngredientBase):
|
||||
@@ -194,6 +212,11 @@ class ProductIngredientOut(ProductIngredientBase):
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Sub-choices (nested under a preference choice) ────────────────────────────
|
||||
|
||||
@@ -202,6 +225,7 @@ class SubChoice(BaseModel):
|
||||
extra_cost: float = 0.0
|
||||
is_default: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
# ── Shared subset (set-level, shown for all non-disabling choices) ─────────────
|
||||
@@ -211,10 +235,12 @@ class SharedSubsetChoice(BaseModel):
|
||||
extra_cost: float = 0.0
|
||||
is_default: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class SharedSubset(BaseModel):
|
||||
name: str
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
choices: List[SharedSubsetChoice] = []
|
||||
|
||||
|
||||
@@ -227,6 +253,7 @@ class PreferenceChoiceCreate(BaseModel):
|
||||
disables_subset: bool = False
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class PreferenceChoiceOut(BaseModel):
|
||||
@@ -237,6 +264,7 @@ class PreferenceChoiceOut(BaseModel):
|
||||
sub_choices: List[SubChoice] = []
|
||||
disables_subset: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -260,6 +288,7 @@ class PreferenceChoiceOut(BaseModel):
|
||||
'sub_choices': parsed,
|
||||
'disables_subset': data.disables_subset or False,
|
||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -274,6 +303,7 @@ class PreferenceSetCreate(BaseModel):
|
||||
group_id: Optional[int] = None
|
||||
allow_multi_select: bool = False
|
||||
allow_choice_quantity: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class PreferenceSetOut(BaseModel):
|
||||
@@ -288,6 +318,7 @@ class PreferenceSetOut(BaseModel):
|
||||
group_id: Optional[int] = None
|
||||
allow_multi_select: bool = False
|
||||
allow_choice_quantity: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -315,6 +346,7 @@ class PreferenceSetOut(BaseModel):
|
||||
'group_id': getattr(data, 'group_id', None),
|
||||
'allow_multi_select': getattr(data, 'allow_multi_select', False) or False,
|
||||
'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False,
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
|
||||
@@ -289,7 +289,7 @@ def menu_snapshot(db) -> tuple[dict, list]:
|
||||
"digital_image_url": p.digital_image_url,
|
||||
"image_url": p.image_url,
|
||||
"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],
|
||||
"names": menu_languages.quick_texts(o.name, menu_languages.of(p), menu_languages.names_of(o))} 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}
|
||||
})
|
||||
|
||||
@@ -82,3 +82,71 @@ def test_the_frontend_list_matches_the_backend():
|
||||
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)
|
||||
|
||||
|
||||
def test_every_choice_keeps_its_names_per_language(client, db, owner_h, menu):
|
||||
"""Owner 2026-11-21 (0042): every choice has its name per language; empty ones dropped,
|
||||
unknown languages refused; sub-choices and the shared sub-set keep theirs in their JSON."""
|
||||
pid = menu["souvlaki"].id
|
||||
body = {
|
||||
"modifier_groups": [{"modifier_type": "ingredient", "name": "Sauces", "translations": {"el": "Σάλτσες", "en": "Sauces"}}],
|
||||
"quick_options": [{"name": "Πίτα", "translations": {"el": "Πίτα", "en": " Pitta ", "fr": ""}}],
|
||||
"ingredients": [{"name": "Κρεμμύδι", "group_id": 0, "translations": {"el": "Κρεμμύδι"}}],
|
||||
"options": [{"name": "Σιρόπι", "translations": {"en": "Syrup"}, "sub_choices": [{"name": "Καραμέλα", "translations": {"en": "Caramel", "el": ""}}]}],
|
||||
"preference_sets": [{"name": "Ζάχαρη", "translations": {"en": "Sugar"},
|
||||
"choices": [{"name": "Σκέτος", "translations": {"en": "No sugar"}, "sub_choices": [{"name": "Στέβια", "translations": {"en": "Stevia"}}]}],
|
||||
"shared_subset": {"name": "Γάλα", "translations": {"en": "Milk"}, "choices": [{"name": "Φρέσκο", "translations": {"en": "Fresh"}}]}}],
|
||||
}
|
||||
r = client.put(f"/api/products/{pid}", headers=owner_h, json=body)
|
||||
assert r.status_code == 200, r.text
|
||||
p = r.json()
|
||||
assert p["modifier_groups"][0]["translations"] == {"el": "Σάλτσες", "en": "Sauces"}
|
||||
assert p["quick_options"][0]["translations"] == {"el": "Πίτα", "en": "Pitta"}
|
||||
assert p["ingredients"][0]["translations"] == {"el": "Κρεμμύδι"}
|
||||
assert p["options"][0]["translations"] == {"en": "Syrup"}
|
||||
assert p["options"][0]["sub_choices"][0]["translations"] == {"en": "Caramel"}
|
||||
ps = p["preference_sets"][0]
|
||||
assert ps["translations"] == {"en": "Sugar"} and ps["choices"][0]["translations"] == {"en": "No sugar"}
|
||||
assert ps["choices"][0]["sub_choices"][0]["translations"] == {"en": "Stevia"}
|
||||
assert ps["shared_subset"]["translations"] == {"en": "Milk"} and ps["shared_subset"]["choices"][0]["translations"] == {"en": "Fresh"}
|
||||
bad = client.put(f"/api/products/{pid}", headers=owner_h, json={"quick_options": [{"name": "x", "translations": {"de": "x"}}]})
|
||||
assert bad.status_code == 422 and err(bad) == "catalog.translation"
|
||||
# the cloud's quick option names come from the option itself now
|
||||
from services.cloud_sync import menu_snapshot
|
||||
db.expire_all()
|
||||
snap, _ = menu_snapshot(db)
|
||||
souv = next(x for c in snap["categories"] for x in c["products"] if x["id"] == pid)
|
||||
assert souv["quick_options"][0]["names"] == {"el": "Πίτα", "en": "Pitta"}
|
||||
|
||||
|
||||
def test_migration_0042_puts_the_texts_in_their_language(tmp_path):
|
||||
"""0042: texts typed before had no language: Greek letters → el, else the venue's language;
|
||||
the product's old quick translations move onto the quick options."""
|
||||
import json
|
||||
from alembic import command
|
||||
from sqlalchemy import create_engine, text
|
||||
from core.schema import alembic_config, upgrade_to_head
|
||||
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
|
||||
with eng.begin() as conn:
|
||||
command.upgrade(alembic_config(conn), "0041_floor_item_color")
|
||||
conn.execute(text("insert into pos_settings (key, value, updated_at) values ('venue.language', 'el', '2026-01-01')"))
|
||||
conn.execute(text("insert into categories (id, name, sort_order, general_sort_order, auto_expanded) values (1, 'Ψητά', 0, 0, 0)"))
|
||||
conn.execute(text("insert into products (id, name, description, base_price, is_available, lifecycle_status, sort_order, sold_at, digital_available, "
|
||||
"unit_type, quick_add_enabled, is_service_item, translations) values (1, 'Burger', 'Με πατάτες', 8, 1, 'active', 0, '[]', 1, 'piece', 1, 0, "
|
||||
"'{\"en\": {\"description\": \"With fries\", \"quick\": {\"Μπέικον\": \"Bacon\"}}}')"))
|
||||
conn.execute(text("insert into product_quick_options (id, product_id, name, price, allow_multiple, sort_order, is_favorite, favorite_sort_order, is_compact) "
|
||||
"values (1, 1, 'Μπέικον', 1, 0, 0, 0, 0, 0)"))
|
||||
conn.execute(text("insert into product_options (id, product_id, name, extra_cost, allow_multiple, multi_select, is_favorite, favorite_sort_order, is_compact, sub_choices) "
|
||||
"values (1, 1, 'Σάλτσα', 0, 0, 0, 0, 0, 0, '[{\"name\": \"BBQ\"}]')"))
|
||||
upgrade_to_head(eng)
|
||||
with eng.connect() as conn:
|
||||
p = json.loads(conn.execute(text("select translations from products where id = 1")).scalar())
|
||||
q = json.loads(conn.execute(text("select translations from product_quick_options where id = 1")).scalar())
|
||||
o = conn.execute(text("select translations, sub_choices from product_options where id = 1")).fetchone()
|
||||
c = json.loads(conn.execute(text("select translations from categories where id = 1")).scalar())
|
||||
eng.dispose()
|
||||
# "Burger" has no Greek letters: the venue's language (el); the description is Greek; the English one is kept
|
||||
assert p == {"el": {"name": "Burger", "description": "Με πατάτες"}, "en": {"description": "With fries"}}
|
||||
assert q == {"el": "Μπέικον", "en": "Bacon"}
|
||||
assert json.loads(o[0]) == {"el": "Σάλτσα"} and json.loads(o[1])[0]["translations"] == {"el": "BBQ"}
|
||||
assert c == {"el": {"name": "Ψητά"}}
|
||||
|
||||
Reference in New Issue
Block a user