From 15413dea1b4311b1485b5fe7529d7b1b154dfdc9 Mon Sep 17 00:00:00 2001 From: bonamin Date: Fri, 20 Nov 2026 18:21:50 +0200 Subject: [PATCH] feat(products): every menu text per language, the editor's language picker, service item dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- docs/DESIGN.md | 2 + local_backend/core/menu_languages.py | 51 ++++- .../versions/0042_menu_texts_per_language.py | 123 ++++++++++ local_backend/models/product.py | 12 + local_backend/routers/data_transfer.py | 32 ++- local_backend/routers/products.py | 55 ++++- local_backend/schemas/product.py | 34 ++- local_backend/services/cloud_sync.py | 2 +- local_backend/tests/test_menu_languages.py | 68 ++++++ .../src/pages/products/CategoryDialog.jsx | 34 +-- .../src/pages/products/ProductsPage.jsx | 12 +- .../src/pages/products/Toolbar.jsx | 3 +- .../pages/products/editor/ChoicesPanel.jsx | 213 +++++++++--------- .../src/pages/products/editor/Fields.jsx | 12 +- .../src/pages/products/editor/InfoTabs.jsx | 87 +++---- .../pages/products/editor/LanguageFields.jsx | 33 +++ .../pages/products/editor/ProductEditor.jsx | 64 +++--- .../products/editor/ServiceItemDialog.jsx | 47 ++++ .../src/pages/products/editor/editLang.js | 19 ++ .../src/pages/products/editor/formLogic.js | 80 ++++--- .../src/pages/products/editor/parts.jsx | 63 +++--- manager_dashboard/tests/products.test.mjs | 30 ++- packages/access/src/index.js | 2 +- packages/access/src/menuLanguages.js | 19 +- packages/access/tests/menuLanguages.test.mjs | 20 ++ packages/i18n/locales/el/manager.json | 4 + packages/i18n/locales/en/manager.json | 4 + packages/ui/src/components.css | 3 + packages/ui/src/internal/ModalFrame.jsx | 6 +- tests/e2e/manager.mjs | 32 ++- 30 files changed, 853 insertions(+), 313 deletions(-) create mode 100644 local_backend/migrations/versions/0042_menu_texts_per_language.py create mode 100644 manager_dashboard/src/pages/products/editor/LanguageFields.jsx create mode 100644 manager_dashboard/src/pages/products/editor/ServiceItemDialog.jsx create mode 100644 manager_dashboard/src/pages/products/editor/editLang.js create mode 100644 packages/access/tests/menuLanguages.test.mjs diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 16d4332..8f71c50 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -59,6 +59,8 @@ Every page is on `` except Inventory → Stock (a placeholder). Two-column | Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` | | A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` | | Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box | +| A control beside a dialog's close button | `headerEnd` (Dialog / Sheet) | the product editor's language picker | +| A toggle on a row (several, compact…) | `FilterChip size="sm" tone pressed` | takes its colour when on; a toned `IconButton` with `aria-pressed` (the favourite's heart) keeps its colour while on | | Print only this | `PrintArea` (+ `PrintSheet` for cards to cut out) | rendered into ``, hidden on screen; while mounted, printing prints only it. One per page | | Section titles inside a panel or drawer | `text-overline font-semibold uppercase tracking-wide text-ink-3` + a `flex-1 border-t border-line` rule after it | as the navigation's group titles | diff --git a/local_backend/core/menu_languages.py b/local_backend/core/menu_languages.py index b3bfb68..1ac63a6 100644 --- a/local_backend/core/menu_languages.py +++ b/local_backend/core/menu_languages.py @@ -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": {"": "…"}`); 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} diff --git a/local_backend/migrations/versions/0042_menu_texts_per_language.py b/local_backend/migrations/versions/0042_menu_texts_per_language.py new file mode 100644 index 0000000..9759f1b --- /dev/null +++ b/local_backend/migrations/versions/0042_menu_texts_per_language.py @@ -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": {"": "…"}` 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') diff --git a/local_backend/models/product.py b/local_backend/models/product.py index 7657aed..939d5be 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -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") diff --git a/local_backend/routers/data_transfer.py b/local_backend/routers/data_transfer.py index 8ba1296..6bf2171 100644 --- a/local_backend/routers/data_transfer.py +++ b/local_backend/routers/data_transfer.py @@ -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() diff --git a/local_backend/routers/products.py b/local_backend/routers/products.py index 3ab7713..9645202 100644 --- a/local_backend/routers/products.py +++ b/local_backend/routers/products.py @@ -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) diff --git a/local_backend/schemas/product.py b/local_backend/schemas/product.py index 3773f25..3fb316f 100644 --- a/local_backend/schemas/product.py +++ b/local_backend/schemas/product.py @@ -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 diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index cf653af..3e275e4 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -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} }) diff --git a/local_backend/tests/test_menu_languages.py b/local_backend/tests/test_menu_languages.py index 6a23fbc..3eabe8f 100644 --- a/local_backend/tests/test_menu_languages.py +++ b/local_backend/tests/test_menu_languages.py @@ -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": "Ψητά"}} diff --git a/manager_dashboard/src/pages/products/CategoryDialog.jsx b/manager_dashboard/src/pages/products/CategoryDialog.jsx index 44c6ab5..caf7b3b 100644 --- a/manager_dashboard/src/pages/products/CategoryDialog.jsx +++ b/manager_dashboard/src/pages/products/CategoryDialog.jsx @@ -1,38 +1,39 @@ // A category or sub-category (plan step 6.3): its name, picture and colour; or where it goes -// (top level or under another category). +// (top level or under another category). Its name per language (owner 2026-11-21): the picker at +// the top right, as in the product editor; "Default" is the venue's language. import { useState } from 'react' import { Check } from 'lucide-react' -import { translatedLanguages, useAccess } from '@xenia/access' +import { DEFAULT_LANGUAGE, shownText } from '@xenia/access' import { useTranslation } from '@xenia/i18n' -import { Button, Dialog, Field, Input, Select, cx } from '@xenia/ui' +import { Button, Dialog, Field, Select, cx } from '@xenia/ui' import MediaField from '../media/MediaField' +import { LanguagePicker, TrInput } from './editor/LanguageFields' +import { EditLang, editLangOf, useVenueLanguage } from './editor/editLang' +import { cleanTexts } from './editor/formLogic' import { CATEGORY_COLOURS } from './categoryColours' import { topLevel } from './productsLogic' export default function CategoryDialog({ category, parentName, saving, onSave, onClose }) { const { t } = useTranslation('manager') - const [name, setName] = useState(category.name ?? '') + const venue = useVenueLanguage() + const [lang, setLang] = useState(DEFAULT_LANGUAGE) + const [names, setNames] = useState(() => Object.fromEntries(Object.entries(category.translations ?? {}).filter(([, v]) => v?.name).map(([l, v]) => [l, v.name]))) + const name = shownText(names, venue, 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 ( - + } footer={<> - + }>
- 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')} @@ -48,6 +49,7 @@ export default function CategoryDialog({ category, parentName, saving, onSave, o
+ ) } diff --git a/manager_dashboard/src/pages/products/ProductsPage.jsx b/manager_dashboard/src/pages/products/ProductsPage.jsx index f148853..1418790 100644 --- a/manager_dashboard/src/pages/products/ProductsPage.jsx +++ b/manager_dashboard/src/pages/products/ProductsPage.jsx @@ -18,6 +18,7 @@ import ProductList from './ProductList' import Toolbar, { BulkBar, SubChips } from './Toolbar' import { CategoryBulkDialog, ZonesDialog } from './BulkDialogs' import ProductEditor from './editor/ProductEditor' +import ServiceItemDialog from './editor/ServiceItemDialog' import { emptyProduct } from './editor/formLogic' import { NO_FILTERS, SCOPES, applyFilters, bulkCategories, groupProducts, isArchived, isCategoryScope, listedIn, scopeProducts, subsOf } from './productsLogic' @@ -88,8 +89,9 @@ export default function ProductsPage() { const groups = groupProducts(shown, categories, scope, subs.length ? sub : null) const title = scope === SCOPES.all ? t('products.all') : scope === SCOPES.service ? t('products.service') : scope === SCOPES.none ? t('products.uncategorized') : scope === SCOPES.archived ? t('products.archived') : scopeCat ? (scopeCat.parent_id ? `${categories.find(c => c.id === scopeCat.parent_id)?.name ?? ''} › ${scopeCat.name}` : scopeCat.name) : t('products.title') + const newService = () => setEditing(emptyProduct({ is_service_item: true, base_price: 0 })) const newProduct = () => { - if (scope === SCOPES.service) return setEditing(emptyProduct({ is_service_item: true, base_price: 0 })) + if (scope === SCOPES.service) return newService() const preset = (subs.length && sub) || (isCategoryScope(scope) ? scope : null) setEditing(emptyProduct(preset ? { category_ids: [preset], primary_category_id: preset } : {})) } @@ -108,7 +110,7 @@ export default function ProductsPage() { !isArchived(p)).length} - search={search} onSearch={setSearch} filters={filters} onFilters={setFilters} view={view} onView={setView} onNew={newProduct} /> + search={search} onSearch={setSearch} filters={filters} onFilters={setFilters} view={view} onView={setView} onNew={newProduct} onNewService={newService} /> {subs.length > 0 && ( (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} /> @@ -136,7 +138,11 @@ export default function ProductsPage() { - {editing && ( + {editing?.is_service_item && ( + saveProduct.mutate(body)} onClose={() => setEditing(null)} /> + )} + {editing && !editing.is_service_item && ( saveProduct.mutate(body)} onClose={() => setEditing(null)} onCopy={form => setEditing({ _form: { ...form, name: t('products.copyOf', { name: form.name }) } })} /> diff --git a/manager_dashboard/src/pages/products/Toolbar.jsx b/manager_dashboard/src/pages/products/Toolbar.jsx index 655f152..09a865c 100644 --- a/manager_dashboard/src/pages/products/Toolbar.jsx +++ b/manager_dashboard/src/pages/products/Toolbar.jsx @@ -9,7 +9,7 @@ import { Button, IconButton, Input, SearchInput, Segmented, Toolbar as Bar } fro import { Dot } from './CategoryTree' import { NO_FILTERS } from './productsLogic' -export default function Toolbar({ title, shown, total, search, onSearch, filters, onFilters, view, onView, onNew }) { +export default function Toolbar({ title, shown, total, search, onSearch, filters, onFilters, view, onView, onNew, onNewService }) { const { t } = useTranslation('manager') const [open, setOpen] = useState(false) const any = JSON.stringify(filters) !== JSON.stringify(NO_FILTERS) @@ -27,6 +27,7 @@ export default function Toolbar({ title, shown, total, search, onSearch, filters ], ['grid', ]].map(([v, icon]) => ({ value: v, icon, label: {t(`products.view_${v}`)}, testId: `products-view-${v}` }))} /> + {open && ( diff --git a/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx b/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx index b5b9c3e..a3444f4 100644 --- a/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx +++ b/manager_dashboard/src/pages/products/editor/ChoicesPanel.jsx @@ -5,52 +5,61 @@ // Extras ticked add-ons, each with optional sub-choices (syrup → caramel / vanilla) // Preferences one set per tab (sugar: none / medium / sweet), a default, sub-choices, a // shared sub-set shown for every choice except those marked to hide it +// 2026-11-21: every name is typed in the language picked at the top of the editor (one field); +// the row's controls are the shared ones, one height: the heart (red when on), toggles that take +// their colour when on (several, compact…), delete (red under the pointer). "+ Preference" sits +// at the right end of the tab strip; preference groups are made inside a preference. 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' -import { Check, DefaultToggle, FavouriteToggle, GroupHeader, MoveButtons, PriceInput, SubChoices } from './parts' +import { Button, Dropdown, EmptyState, FilterChip, IconButton, Switch, Tabs } from '@xenia/ui' +import { TrInput } from './LanguageFields' +import { useEditLang } from './editLang' +import { favourites, labelIn, moveChoice, moveFavourite, moveItem, removeChoice, removeGroup, setSub, toggleFavourite } from './formLogic' +import { DefaultToggle, FavouriteToggle, GroupHeader, MoveButtons, PriceInput, SubChoices } from './parts' -const newSub = () => ({ name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }) +const newSub = () => ({ name: '', tr: {}, extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }) + +/** A toggle of a choice row (several, compact…): the shared chip, coloured when on. */ +export function Toggle({ on, onChange, tone = 'info', children, ...rest }) { + return onChange(!on)} {...rest}>{children} +} + +/** Delete a row: grey, red under the pointer. */ +export function RemoveButton({ onClick, label }) { + const { t } = useTranslation('manager') + return +} + +const ROW = 'flex flex-wrap items-center gap-2 p-2.5' export default function ChoicesPanel({ form, setForm }) { const { t } = useTranslation('manager') + const { slot, venue } = useEditLang() const [tab, setTab] = useState('favourites') const [folded, setFolded] = useState({}) const nextKey = useRef(-1) const favCount = favourites(form).length - const addGroup = type => setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { key: nextKey.current--, modifier_type: type, name: t('products.editor.newGroup') }] })) + const addGroup = type => setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { key: nextKey.current--, modifier_type: type, name: '', tr: { [slot]: t('products.editor.newGroup') } }] })) const groups = { form, setForm, folded, fold: key => setFolded(s => ({ ...s, [key]: !s[key] })), addGroup } const addPref = () => { - setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', default_choice_index: -1, choices: [], shared_subset: null, group_id: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] })) + setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', tr: {}, default_choice_index: -1, choices: [], shared_subset: null, group_id: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] })) setTab(form.preference_sets.length) } const tabs = [ - { key: 'favourites', label: t('products.editor.tab.favourites'), count: favCount }, - { key: 'quick', label: t('products.editor.tab.quick'), count: form.quick_options.length }, - { key: 'ingredients', label: t('products.editor.tab.ingredients'), count: form.ingredients.length }, - { key: 'options', label: t('products.editor.tab.options'), count: form.options.length }, - ...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || t('products.editor.prefN', { n: i + 1 }), count: ps.choices.length })), + { id: 'favourites', label: t('products.editor.tab.favourites'), badge: favCount || null, + icon: