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:
2026-11-20 18:21:50 +02:00
co-authored by Claude Opus 5.5
parent 301502965c
commit 15413dea1b
30 changed files with 853 additions and 313 deletions
+2
View File
@@ -59,6 +59,8 @@ Every page is on `<Page>` 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 `<body>`, 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 |
+48 -3
View File
@@ -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')
+12
View File
@@ -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")
+23 -9
View File
@@ -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()
+48 -7
View File
@@ -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)
+33 -1
View File
@@ -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
+1 -1
View File
@@ -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": "Ψητά"}}
@@ -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 (
<Dialog open size="sm" onClose={onClose} title={title} description={sub && parentName ? t('products.category.under', { name: parentName }) : undefined}
<EditLang.Provider value={editLangOf(lang, venue)}>
<Dialog open size="md" onClose={onClose} title={title} description={sub && parentName ? t('products.category.under', { name: parentName }) : undefined}
headerEnd={<LanguagePicker value={lang} onChange={setLang} testId="category-lang" />}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button disabled={!name.trim()} loading={saving} onClick={() => onSave({ name: name.trim(), color, media_id: image?.id ?? null,
translations: Object.fromEntries(Object.entries(tr).filter(([, v]) => v.trim()).map(([l, v]) => [l, { name: v.trim() }])) })} data-testid="category-save">{t('products.save')}</Button>
<Button disabled={!name} loading={saving} onClick={() => onSave({ name, color, media_id: image?.id ?? null,
translations: Object.fromEntries(Object.entries(cleanTexts(names)).map(([l, v]) => [l, { name: v }])) })} data-testid="category-save">{t('products.save')}</Button>
</>}>
<div className="grid gap-4">
<Field label={t('products.category.name')}><Input value={name} onChange={e => setName(e.target.value)} autoFocus data-testid="category-name" /></Field>
{others.map(l => (
<Field key={l} label={t('products.editor.inLanguage', { language: t(`products.editor.lang.${l}`) })} hint={t('products.editor.trNameHint')}>
<Input value={tr[l] ?? ''} onChange={e => setTr(s => ({ ...s, [l]: e.target.value }))} placeholder={name} data-testid={`category-name-${l}`} />
</Field>
))}
<Field label={t('products.category.name')}><TrInput texts={names} fallback={category.name} onChange={setNames} autoFocus data-testid="category-name" /></Field>
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')} label={t('media.photo')} testid="category-photo" />
<div className="grid gap-2">
<span className="text-label font-semibold text-ink">{t('products.category.colour')}</span>
@@ -48,6 +49,7 @@ export default function CategoryDialog({ category, parentName, saving, onSave, o
</div>
</div>
</Dialog>
</EditLang.Provider>
)
}
@@ -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() {
<Pane sunken data-testid="products-panel" bodyClassName="p-card" header={<>
<Toolbar title={title} shown={allIds.length} total={products.filter(p => !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 && (
<SubChips parent={scopeCat} subs={subs} value={sub} onChange={setSub}
counts={key => (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} />
@@ -136,7 +138,11 @@ export default function ProductsPage() {
</Pane>
</div>
{editing && (
{editing?.is_service_item && (
<ServiceItemDialog key={editing.id ?? 'new'} product={editing} prepZones={zones} saving={saveProduct.isPending}
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)} />
)}
{editing && !editing.is_service_item && (
<ProductEditor key={editing.id ?? 'new'} product={editing} categories={categories} prepZones={zones} saving={saveProduct.isPending}
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)}
onCopy={form => setEditing({ _form: { ...form, name: t('products.copyOf', { name: form.name }) } })} />
@@ -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
</Button>
<Segmented aria-label={t('products.view')} value={view} onChange={onView}
options={[['list', <List key="l" size={16} />], ['grid', <LayoutGrid key="g" size={16} />]].map(([v, icon]) => ({ value: v, icon, label: <span className="sr-only">{t(`products.view_${v}`)}</span>, testId: `products-view-${v}` }))} />
<Button variant="secondary" icon={<Plus size={16} />} onClick={onNewService} data-testid="service-new">{t('products.newService')}</Button>
<Button icon={<Plus size={16} />} onClick={onNew} data-testid="product-new">{t('products.new')}</Button>
</Bar>
{open && (
@@ -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 <FilterChip size="sm" tone={tone} pressed={!!on} onClick={() => onChange(!on)} {...rest}>{children}</FilterChip>
}
/** Delete a row: grey, red under the pointer. */
export function RemoveButton({ onClick, label }) {
const { t } = useTranslation('manager')
return <IconButton size="sm" tone="danger" label={label ?? t('products.editor.remove')} onClick={onClick}><Trash2 size={16} /></IconButton>
}
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: <Heart size={14} className={favCount ? 'text-danger' : 'text-ink-3'} fill={favCount ? 'currentColor' : 'none'} aria-hidden="true" /> },
{ id: 'quick', testId: 'choices-tab-quick', label: t('products.editor.tab.quick'), badge: form.quick_options.length || null },
{ id: 'ingredients', testId: 'choices-tab-ingredients', label: t('products.editor.tab.ingredients'), badge: form.ingredients.length || null },
{ id: 'options', testId: 'choices-tab-options', label: t('products.editor.tab.options'), badge: form.options.length || null },
...form.preference_sets.map((ps, i) => ({ id: i, label: labelIn(ps, slot, venue) || t('products.editor.prefN', { n: i + 1 }), badge: ps.choices.length || null })),
]
return (
<div className="flex flex-col min-h-0 h-full">
<div className="flex items-end border-b border-line overflow-x-auto shrink-0" role="tablist">
{tabs.map(tb => (
<button key={String(tb.key)} type="button" role="tab" aria-selected={tab === tb.key} onClick={() => setTab(tb.key)}
className={cx('flex items-center gap-1.5 px-4 py-2.5 -mb-px border-b-2 text-label whitespace-nowrap',
tab === tb.key ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
{tb.key === 'favourites' && <Heart size={14} className={favCount ? 'text-danger' : 'text-ink-3'} fill={favCount ? 'currentColor' : 'none'} aria-hidden="true" />}
{tb.label}
{tb.count > 0 && <span className="px-1.5 rounded-full bg-surface-2 text-caption tabular-nums">{tb.count}</span>}
</button>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={addPref} data-testid="add-pref">{t('products.editor.addPref')}</Button>
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={() => addGroup('preference')}>{t('products.editor.addPrefGroup')}</Button>
</div>
<Tabs className="px-card bg-surface shrink-0" value={tab} onChange={setTab} tabs={tabs}
end={<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={addPref} data-testid="add-pref">{t('products.editor.addPref')}</Button>} />
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-5">
{tab === 'favourites' && <Favourites form={form} setForm={setForm} />}
{tab === 'quick' && <QuickList form={form} setForm={setForm} />}
@@ -75,20 +84,20 @@ function Intro({ text, children }) {
function Favourites({ form, setForm }) {
const { t } = useTranslation('manager')
const { slot, venue } = useEditLang()
const list = favourites(form)
return (
<div className="grid gap-2">
<p className="text-label text-ink-2">{t('products.editor.favouritesHint')}</p>
{list.length === 0 && <EmptyState compact title={t('products.editor.noFavourites')} />}
{list.map((fav, i) => (
<div key={`${fav.kind}-${fav.idx}`} className="flex items-center gap-3 rounded-card border border-line p-2.5">
<div key={`${fav.kind}-${fav.idx}`} className={`${ROW} rounded-card border border-line bg-surface`}>
<MoveButtons first={i === 0} last={i === list.length - 1} onUp={() => setForm(f => moveFavourite(f, i, -1))} onDown={() => setForm(f => moveFavourite(f, i, 1))} />
<Heart size={16} className="text-danger shrink-0" fill="currentColor" aria-hidden="true" />
<FavouriteToggle on onClick={() => setForm(f => toggleFavourite(f, fav.kind, fav.idx))} />
<span className="flex-1 min-w-0 grid">
<span className="text-body font-medium text-ink truncate">{fav.item.name || t('products.editor.unnamed')}</span>
<span className="text-body font-medium text-ink truncate">{labelIn(fav.item, slot, venue) || t('products.editor.unnamed')}</span>
<span className="text-caption text-ink-3">{t(`products.editor.kind.${fav.kind}`)}</span>
</span>
<Button size="sm" variant="ghost" onClick={() => setForm(f => toggleFavourite(f, fav.kind, fav.idx))}>{t('products.editor.remove')}</Button>
</div>
))}
</div>
@@ -97,29 +106,23 @@ function Favourites({ form, setForm }) {
function QuickList({ form, setForm }) {
const { t } = useTranslation('manager')
const { venue } = useAccess()
const others = translatedLanguages(venue?.language)
const set = (i, k, v) => setForm(f => ({ ...f, quick_options: f.quick_options.map((q, j) => (j === i ? { ...q, [k]: v } : q)) }))
const add = () => setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, is_favorite: false, favorite_sort_order: 0, is_compact: false, tr: {} }] }))
const add = () => setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', tr: {}, price: 0, allow_multiple: false, is_favorite: false, favorite_sort_order: 0, is_compact: false }] }))
return (
<div>
<Intro text={t('products.editor.quickHint')}><Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t('products.editor.addQuick')}</Button></Intro>
<Intro text={t('products.editor.quickHint')}><Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add} data-testid="add-quick">{t('products.editor.addQuick')}</Button></Intro>
{form.quick_options.length === 0 && <EmptyState compact title={t('products.editor.noQuick')} />}
<div className="grid gap-2">
{form.quick_options.map((q, i) => (
<div key={i} className={cx('flex flex-wrap items-center gap-2 rounded-card border p-2.5', q.is_favorite ? 'border-danger' : 'border-line')}>
<div key={i} className={`${ROW} rounded-card border border-line bg-surface`} data-testid="quick-row">
<MoveButtons first={i === 0} last={i === form.quick_options.length - 1}
onUp={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, -1) }))} onDown={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, 1) }))} />
<FavouriteToggle on={q.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'quick', i))} />
<Input className="flex-1 min-w-36" value={q.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.quickPlaceholder')} />
{others.map(l => (
<Input key={l} className="flex-1 min-w-32" value={q.tr?.[l] ?? ''} onChange={e => set(i, 'tr', { ...(q.tr ?? {}), [l]: e.target.value })}
placeholder={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} aria-label={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} />
))}
<PriceInput className="w-32" value={q.price} onChange={v => set(i, 'price', v)} label={t('products.editor.extraCost')} />
<Check checked={q.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>
<Check checked={q.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, quick_options: f.quick_options.filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
<TrInput size="sm" className="flex-1 min-w-36" texts={q.tr} fallback={q.name} onChange={v => set(i, 'tr', v)} placeholder={t('products.editor.quickPlaceholder')} data-testid="quick-name" />
<PriceInput size="sm" className="w-32" value={q.price} onChange={v => set(i, 'price', v)} label={t('products.editor.extraCost')} />
<Toggle on={q.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Toggle>
<Toggle on={q.is_compact} tone="accent" onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Toggle>
<RemoveButton onClick={() => setForm(f => ({ ...f, quick_options: f.quick_options.filter((_, j) => j !== i) }))} />
</div>
))}
</div>
@@ -127,6 +130,19 @@ function QuickList({ form, setForm }) {
)
}
/** A choice's group (folder): the shared dropdown. */
function GroupPicker({ value, groups, onChange }) {
const { t } = useTranslation('manager')
const { slot, venue } = useEditLang()
if (!groups.length) return null
return (
<Dropdown size="sm" className="w-40" value={value ?? ''} onChange={v => onChange(v === '' ? null : Number(v))} aria-label={t('products.editor.group')}
options={[{ value: '', label: t('products.editor.noGroup') }, ...groups.map(g => ({ value: g.key, label: labelIn(g, slot, venue) || t('products.editor.unnamedGroup') }))]} />
)
}
const renameGroup = (setForm, key, tr) => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === key ? { ...x, tr } : x)) }))
/** Ingredients or extras, with their groups (folders). */
function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
const { t } = useTranslation('manager')
@@ -134,36 +150,31 @@ function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
const myGroups = form.modifier_groups.filter(g => g.modifier_type === kind)
const set = (i, k, v) => setForm(f => ({ ...f, [list]: f[list].map((x, j) => (j === i ? { ...x, [k]: v } : x)) }))
const add = () => setForm(f => ({ ...f, [list]: [...f[list], kind === 'option'
? { name: '', extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0, group_id: null }
: { name: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, group_id: null }] }))
? { name: '', tr: {}, extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0, group_id: null }
: { name: '', tr: {}, extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, group_id: null }] }))
const row = (x, i) => (
<div key={i} className={cx('rounded-card border overflow-hidden', x.is_favorite ? 'border-danger' : 'border-line')}>
<div className="flex flex-wrap items-center gap-2 p-2.5">
<div key={i} className="rounded-card border border-line bg-surface overflow-hidden" data-testid={`${kind}-row`}>
<div className={ROW}>
<MoveButtons first={i === 0} last={i === items.length - 1}
onUp={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, -1) }))} onDown={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, 1) }))} />
<FavouriteToggle on={x.is_favorite} onClick={() => setForm(f => toggleFavourite(f, kind, i))} />
<Input className="flex-1 min-w-36" value={x.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t(`products.editor.${kind}Placeholder`)} />
<PriceInput className="w-32" value={x.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{kind === 'option' && <Check checked={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
{kind === 'option' && <Check checked={x.multi_select} onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Check>}
<Check checked={x.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
{myGroups.length > 0 && (
<Select size="sm" className="w-36" value={x.group_id ?? ''} onChange={e => set(i, 'group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
<option value="">{t('products.editor.noGroup')}</option>
{myGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
</Select>
)}
{kind === 'option' && <Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => set(i, 'sub_choices', [...x.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>}
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, [list]: f[list].filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
<TrInput size="sm" className="flex-1 min-w-36" texts={x.tr} fallback={x.name} onChange={v => set(i, 'tr', v)} placeholder={t(`products.editor.${kind}Placeholder`)} />
<PriceInput size="sm" className="w-32" value={x.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{kind === 'option' && <Toggle on={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Toggle>}
{kind === 'option' && <Toggle on={x.multi_select} tone="success" onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Toggle>}
<Toggle on={x.is_compact} tone="accent" onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Toggle>
<GroupPicker value={x.group_id} groups={myGroups} onChange={v => set(i, 'group_id', v)} />
{kind === 'option' && <Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={() => set(i, 'sub_choices', [...x.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>}
<RemoveButton onClick={() => setForm(f => ({ ...f, [list]: f[list].filter((_, j) => j !== i) }))} />
</div>
{kind === 'option' && <SubChoices subs={x.sub_choices} parent={x.name} withMultiple={x.multi_select} onChange={subs => set(i, 'sub_choices', subs)} />}
{kind === 'option' && <SubChoices subs={x.sub_choices} parent={x} withMultiple={x.multi_select} onChange={subs => set(i, 'sub_choices', subs)} />}
</div>
)
return (
<div>
<Intro text={t(`products.editor.${kind}Hint`)}>
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => addGroup(kind)}>{t('products.editor.addGroup')}</Button>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t(`products.editor.add.${kind}`)}</Button>
<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={() => addGroup(kind)}>{t('products.editor.addGroup')}</Button>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add} data-testid={`add-${kind}`}>{t(`products.editor.add.${kind}`)}</Button>
</Intro>
{items.length === 0 && <EmptyState compact title={t(`products.editor.none.${kind}`)} />}
<div className="grid gap-2">
@@ -171,8 +182,7 @@ function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
{myGroups.map(g => (
<div key={g.key}>
<GroupHeader group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
onRemove={() => setForm(f => removeGroup(f, g.key))} />
onRename={tr => renameGroup(setForm, g.key, tr)} onRemove={() => setForm(f => removeGroup(f, g.key))} />
{!folded[g.key] && (
<div className="ml-4 border-l-2 border-accent-soft pl-3 mt-1 grid gap-2">
{items.every(x => x.group_id !== g.key) && <p className="text-caption text-ink-3 py-1">{t('products.editor.emptyGroup')}</p>}
@@ -186,7 +196,7 @@ function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
)
}
function PrefSet({ si, form, setForm, folded, fold, onRemoved }) {
function PrefSet({ si, form, setForm, folded, fold, addGroup, onRemoved }) {
const { t } = useTranslation('manager')
const ps = form.preference_sets[si]
const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference')
@@ -194,54 +204,52 @@ function PrefSet({ si, form, setForm, folded, fold, onRemoved }) {
const set = (k, v) => put(x => ({ ...x, [k]: v }))
const setChoice = (ci, k, v) => put(x => ({ ...x, choices: x.choices.map((c, j) => (j === ci ? { ...c, [k]: v } : c)) }))
const shared = ps.shared_subset
const setShared = patch => set('shared_subset', { ...shared, ...patch })
return (
<div className="grid gap-4" data-testid="pref-set">
<div className="flex flex-wrap items-center gap-2">
<Input className="flex-1 min-w-40 font-semibold" value={ps.name} onChange={e => set('name', e.target.value)} placeholder={t('products.editor.prefPlaceholder')} autoFocus data-testid="pref-name" />
{prefGroups.length > 0 && (
<Select size="sm" className="w-40" value={ps.group_id ?? ''} onChange={e => set('group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
<option value="">{t('products.editor.noGroup')}</option>
{prefGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
</Select>
)}
<FavouriteToggle on={ps.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'pref', si))} />
<Button size="sm" variant="danger" icon={<Trash2 size={14} />}
<TrInput size="sm" className="flex-1 min-w-40 font-semibold" texts={ps.tr} fallback={ps.name} onChange={v => set('tr', v)}
placeholder={t('products.editor.prefPlaceholder')} autoFocus data-testid="pref-name" />
<GroupPicker value={ps.group_id} groups={prefGroups} onChange={v => set('group_id', v)} />
{/* preference groups: made here, inside a preference (2026-11-21) */}
<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={() => addGroup('preference')} data-testid="add-pref-group">{t('products.editor.addPrefGroup')}</Button>
<Button size="sm" variant="ghost" tone="danger" icon={<Trash2 size={14} />}
onClick={() => { setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, i) => i !== si) })); onRemoved() }}>{t('products.editor.removePref')}</Button>
</div>
{prefGroups.length > 0 && (
<div className="rounded-card bg-accent-soft p-3">
<p className="text-caption font-semibold text-accent-ink">{t('products.editor.prefGroups')}</p>
<div className="rounded-card border border-line bg-surface p-3 grid gap-1">
<p className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('products.editor.prefGroups')}</p>
{prefGroups.map(g => (
<GroupHeader key={g.key} group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
onRemove={() => setForm(f => removeGroup(f, g.key))} />
onRename={tr => renameGroup(setForm, g.key, tr)} onRemove={() => setForm(f => removeGroup(f, g.key))} />
))}
</div>
)}
<div className="flex flex-wrap gap-5">
<Check checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)}>{t('products.editor.multiChoice')}</Check>
<Check checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)}>{t('products.editor.choiceQuantity')}</Check>
<div className="flex flex-wrap gap-x-8 gap-y-2">
<Switch checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)} label={t('products.editor.multiChoice')} />
<Switch checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)} label={t('products.editor.choiceQuantity')} />
</div>
<p className="text-caption text-ink-3">{t('products.editor.prefLegend')}</p>
<div className="grid gap-2">
{ps.choices.map((c, ci) => (
<div key={ci} className="rounded-card border border-line overflow-hidden" data-testid="pref-choice">
<div className="flex flex-wrap items-center gap-2 p-2.5">
<div key={ci} className="rounded-card border border-line bg-surface overflow-hidden" data-testid="pref-choice">
<div className={ROW}>
<MoveButtons first={ci === 0} last={ci === ps.choices.length - 1} onUp={() => put(x => moveChoice(x, ci, -1))} onDown={() => put(x => moveChoice(x, ci, 1))} />
<DefaultToggle on={ps.default_choice_index === ci} onClick={() => set('default_choice_index', ps.default_choice_index === ci ? -1 : ci)} />
<Input className="flex-1 min-w-32" value={c.name} onChange={e => setChoice(ci, 'name', e.target.value)} placeholder={t('products.editor.choicePlaceholder')} />
<PriceInput className="w-32" value={c.extra_cost} allowNegative onChange={v => setChoice(ci, 'extra_cost', v)} label={t('products.editor.extraCost')} />
<Check checked={c.is_compact} onChange={v => setChoice(ci, 'is_compact', v)}>{t('products.editor.compact')}</Check>
{shared && <Check checked={c.disables_subset} onChange={v => setChoice(ci, 'disables_subset', v)}>{t('products.editor.hidesShared')}</Check>}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => setChoice(ci, 'sub_choices', [...c.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => put(x => removeChoice(x, ci))}><Trash2 size={14} /></IconButton>
<TrInput size="sm" className="flex-1 min-w-32" texts={c.tr} fallback={c.name} onChange={v => setChoice(ci, 'tr', v)} placeholder={t('products.editor.choicePlaceholder')} data-testid="pref-choice-name" />
<PriceInput size="sm" className="w-32" value={c.extra_cost} allowNegative onChange={v => setChoice(ci, 'extra_cost', v)} label={t('products.editor.extraCost')} />
<Toggle on={c.is_compact} tone="accent" onChange={v => setChoice(ci, 'is_compact', v)}>{t('products.editor.compact')}</Toggle>
{shared && <Toggle on={c.disables_subset} tone="warning" onChange={v => setChoice(ci, 'disables_subset', v)}>{t('products.editor.hidesShared')}</Toggle>}
<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={() => setChoice(ci, 'sub_choices', [...c.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>
<RemoveButton onClick={() => put(x => removeChoice(x, ci))} />
</div>
<SubChoices subs={c.sub_choices} parent={c.name} onChange={subs => setChoice(ci, 'sub_choices', subs)} />
<SubChoices subs={c.sub_choices} parent={c} onChange={subs => setChoice(ci, 'sub_choices', subs)} />
</div>
))}
</div>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} className="justify-self-start" data-testid="add-choice"
onClick={() => put(x => ({ ...x, choices: [...x.choices, { name: '', extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] }))}>{t('products.editor.addChoice')}</Button>
onClick={() => put(x => ({ ...x, choices: [...x.choices, { name: '', tr: {}, extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] }))}>{t('products.editor.addChoice')}</Button>
<section className="border-t border-line pt-4 grid gap-3">
<div className="flex items-center justify-between gap-2">
<span className="grid">
@@ -249,26 +257,25 @@ function PrefSet({ si, form, setForm, folded, fold, onRemoved }) {
<span className="text-caption text-ink-3">{t('products.editor.sharedHint')}</span>
</span>
{shared
? <Button size="sm" variant="danger" onClick={() => set('shared_subset', null)}>{t('products.editor.remove')}</Button>
: <Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('shared_subset', { name: '', choices: [] })}>{t('products.editor.addShared')}</Button>}
? <Button size="sm" variant="ghost" tone="danger" icon={<Trash2 size={14} />} onClick={() => set('shared_subset', null)}>{t('products.editor.remove')}</Button>
: <Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('shared_subset', { name: '', tr: {}, choices: [] })}>{t('products.editor.addShared')}</Button>}
</div>
{shared && (
<div className="rounded-card border border-line bg-surface-2 p-3 grid gap-2">
<Input value={shared.name} onChange={e => set('shared_subset', { ...shared, name: e.target.value })} placeholder={t('products.editor.sharedPlaceholder')} aria-label={t('products.editor.sharedName')} />
<TrInput size="sm" texts={shared.tr} fallback={shared.name} onChange={v => setShared({ tr: v })} placeholder={t('products.editor.sharedPlaceholder')} aria-label={t('products.editor.sharedName')} />
{shared.choices.map((s, i) => (
<div key={i} className="flex items-center gap-2">
<MoveButtons first={i === 0} last={i === shared.choices.length - 1}
onUp={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, -1) })} onDown={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, 1) })} />
<DefaultToggle on={s.is_default} onClick={() => set('shared_subset', { ...shared, choices: setSub(shared.choices, i, 'is_default', !s.is_default) })} />
<Input className="flex-1" value={s.name} onChange={e => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)) })} />
<PriceInput className="w-32" value={s.extra_cost} allowNegative label={t('products.editor.extraCost')}
onChange={v => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, extra_cost: v } : x)) })} />
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')}
onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)}><Trash2 size={14} /></IconButton>
onUp={() => setShared({ choices: moveItem(shared.choices, i, -1) })} onDown={() => setShared({ choices: moveItem(shared.choices, i, 1) })} />
<DefaultToggle on={s.is_default} onClick={() => setShared({ choices: setSub(shared.choices, i, 'is_default', !s.is_default) })} />
<TrInput size="sm" className="flex-1" texts={s.tr} fallback={s.name} onChange={v => setShared({ choices: shared.choices.map((x, j) => (j === i ? { ...x, tr: v } : x)) })} />
<PriceInput size="sm" className="w-32" value={s.extra_cost} allowNegative label={t('products.editor.extraCost')}
onChange={v => setShared({ choices: shared.choices.map((x, j) => (j === i ? { ...x, extra_cost: v } : x)) })} />
<RemoveButton onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)} />
</div>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
onClick={() => set('shared_subset', { ...shared, choices: [...shared.choices, { name: '', extra_cost: 0, is_default: false }] })}>{t('products.editor.addChoice')}</Button>
<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} className="justify-self-start"
onClick={() => setShared({ choices: [...shared.choices, { name: '', tr: {}, extra_cost: 0, is_default: false }] })}>{t('products.editor.addChoice')}</Button>
</div>
)}
</section>
@@ -3,7 +3,7 @@
import { X } from 'lucide-react'
import { ALLERGENS, nextAllergenLevel, setAllergen } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, InfoTip, Select, cx } from '@xenia/ui'
import { Button, Dropdown, IconButton, InfoTip, cx } from '@xenia/ui'
import { categoryTree, treeLabel } from '../productsLogic'
import { addCategory, removeCategory } from './formLogic'
@@ -39,12 +39,10 @@ export function CategoriesField({ form, setForm, categories }) {
)
})}
</ul>
<Select value="" onChange={e => e.target.value && setForm(f => addCategory(f, Number(e.target.value)))} aria-label={t('products.editor.addCategory')} data-testid="add-category">
<option value="">{t('products.editor.addCategory')}</option>
{tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => (
<option key={cat.id} value={cat.id}>{treeLabel(cat, depth)}</option>
))}
</Select>
{/* the shared dropdown (2026-11-21): searchable, a sub-category under its parent, the category's colour */}
<Dropdown value={null} onChange={v => v != null && setForm(f => addCategory(f, Number(v)))} aria-label={t('products.editor.addCategory')}
placeholder={t('products.editor.addCategory')} searchable data-testid="add-category"
options={tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => ({ value: cat.id, label: treeLabel(cat, depth), dot: cat.color || undefined }))} />
</div>
)
}
@@ -4,70 +4,54 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { BadgeEuro, Plus, Trash2, X } from 'lucide-react'
import { SALES_POINTS, translatedLanguages, useAccess, useCan, useModule } from '@xenia/access'
import { SALES_POINTS, shownText, useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, IconButton, InfoTip, Input, Segmented, Select, Switch, Textarea, cx } from '@xenia/ui'
import { Button, Dropdown, Field, IconButton, InfoTip, Input, Select, Switch, Textarea, cx } from '@xenia/ui'
import ProductChannelPricesDialog from '../../pricing/ProductChannelPricesDialog'
import MediaField from '../../media/MediaField'
import { costOf } from '../productsLogic'
import { AllergensField, CategoriesField } from './Fields'
import { UNITS, WEIGHED, cleanTag, setTranslation } from './formLogic'
import { UNITS, WEIGHED, cleanTag } from './formLogic'
import { TrInput } from './LanguageFields'
import { useEditLang } from './editLang'
import { Check, PriceInput } from './parts'
export function InfoTab({ form, set, setForm, categories, prepZones }) {
const { t } = useTranslation('manager')
const { venue } = useAccess()
const service = form.is_service_item
const others = translatedLanguages(venue?.language)
const main = venue?.language || 'el'
const [lang, setLang] = useState(main)
const tr = lang !== main && others.includes(lang)
const trOf = k => form.translations?.[lang]?.[k] ?? ''
const { venue } = useEditLang()
return (
<div className="grid gap-4">
<Switch checked={service} onChange={v => set('is_service_item', v)} label={t('products.editor.serviceItem')}
description={service ? (Number(form.base_price) > 0 ? t('products.editor.servicePaid') : t('products.editor.serviceFree')) : t('products.editor.serviceHint')} />
{!service && others.length > 0 && (
// one name and one description; the switch picks the language being typed (2026-11-20)
<div className="flex items-center gap-2" data-testid="product-lang">
<Segmented size="sm" value={lang} onChange={setLang} aria-label={t('products.editor.langOf')}
options={[main, ...others].map(l => ({ value: l, testId: `product-lang-${l}`,
label: l === main ? t('products.editor.mainLang', { language: t(`products.editor.lang.${l}`) }) : t(`products.editor.lang.${l}`) }))} />
<InfoTip>{t('products.editor.translationTip')}</InfoTip>
</div>
)}
{tr ? (
<div className="grid gap-4" data-testid={`translation-${lang}`}>
<Field label={t('products.editor.name')} hint={t('products.editor.trNameHint')}>
<Input value={trOf('name')} onChange={e => setForm(f => setTranslation(f, lang, 'name', e.target.value))} placeholder={form.name} data-testid={`translation-${lang}-name`} />
</Field>
<Field label={t('products.editor.description')}>
<Textarea rows={3} value={trOf('description')} onChange={e => setForm(f => setTranslation(f, lang, 'description', e.target.value))} placeholder={form.description} />
</Field>
</div>
) : (<>
<Field label={t('products.editor.name')} required>
<Input value={form.name} onChange={e => set('name', e.target.value)} autoFocus data-testid="product-name"
placeholder={service ? t('products.editor.servicePlaceholder') : t('products.editor.namePlaceholder')} />
{/* one name and one description, in the language picked at the top (2026-11-21) */}
<Field label={t('products.editor.name')} required>
<TrInput texts={form.names} fallback={form.name} onChange={v => set('names', v)} autoFocus data-testid="product-name"
placeholder={t('products.editor.namePlaceholder')} />
</Field>
<Field label={t('products.editor.description')} hint={t('products.editor.descriptionHint')}>
<TrInput multiline rows={3} texts={form.descriptions} fallback={form.description} onChange={v => set('descriptions', v)} data-testid="product-description" />
</Field>
<Tags tags={form.tags} onChange={v => set('tags', v)} />
<div className="grid gap-3 grid-cols-2">
<Field label={t('products.editor.unit')} hint={WEIGHED.has(form.unit_type) ? t('products.editor.unitWeighed') : undefined}>
<Dropdown value={form.unit_type} onChange={v => set('unit_type', v)} data-testid="product-unit" options={UNITS.map(u => ({ value: u, label: t(`products.unit.${u}`) }))} />
</Field>
{!service && (
<Field label={t('products.editor.description')} hint={t('products.editor.descriptionHint')}>
<Textarea rows={3} value={form.description} onChange={e => set('description', e.target.value)} />
</Field>
)}
</>)}
{!service && <Tags tags={form.tags} onChange={v => set('tags', v)} />}
<div className={cx('grid gap-3', !service && 'grid-cols-2')}>
{!service && (
<Field label={t('products.editor.unit')} hint={WEIGHED.has(form.unit_type) ? t('products.editor.unitWeighed') : undefined}>
<Dropdown value={form.unit_type} onChange={v => set('unit_type', v)} data-testid="product-unit" options={UNITS.map(u => ({ value: u, label: t(`products.unit.${u}`) }))} />
</Field>
)}
<Field label={service ? t('products.editor.priceOptional') : t('products.editor.price')} required={!service}>
<Field label={t('products.editor.price')} required>
<PriceInput className="w-full" value={form.base_price} onChange={v => set('base_price', v)} label={t('products.editor.price')} data-testid="product-price" />
</Field>
</div>
<CategoriesField form={form} setForm={setForm} categories={categories} />
<PrepZonesField form={form} set={set} prepZones={prepZones} />
<AllergensField value={form.allergens} onChange={v => set('allergens', v)} />
<Switch checked={form.is_available} onChange={v => set('is_available', v)} label={t('products.editor.available')} description={t('products.editor.availableHint')} />
<Switch checked={form.quick_add_enabled} onChange={v => set('quick_add_enabled', v)} label={t('products.editor.quickAdd')} description={t('products.editor.quickAddHint')} />
<MediaField value={form.image} onChange={image => set('image', image)} nameAfter={shownText(form.names, venue, form.name)} label={t('media.photo')} testid="product-photo" />
</div>
)
}
/** The prep zones its tickets go to (also the service items' dialog). */
export function PrepZonesField({ form, set, prepZones }) {
const { t } = useTranslation('manager')
return (
<div className="grid gap-2">
<span className="flex items-center gap-1 text-label font-semibold text-ink">{t('products.editor.prepZones')}<InfoTip>{t('products.editor.prepZonesTip')}</InfoTip></span>
{prepZones.length === 0
@@ -79,13 +63,6 @@ export function InfoTab({ form, set, setForm, categories, prepZones }) {
</Check>
))}
</div>
{!service && <AllergensField value={form.allergens} onChange={v => set('allergens', v)} />}
{!service && (<>
<Switch checked={form.is_available} onChange={v => set('is_available', v)} label={t('products.editor.available')} description={t('products.editor.availableHint')} />
<Switch checked={form.quick_add_enabled} onChange={v => set('quick_add_enabled', v)} label={t('products.editor.quickAdd')} description={t('products.editor.quickAddHint')} />
<MediaField value={form.image} onChange={image => set('image', image)} nameAfter={form.name} label={t('media.photo')} testid="product-photo" />
</>)}
</div>
)
}
@@ -0,0 +1,33 @@
// The editors' language picker and the fields it drives (owner 2026-11-21).
// <LanguagePicker value={lang} onChange={setLang} /> Default (the venue's language) + every menu language
// <TrInput texts={x.tr} fallback={x.name} onChange={tr => …} />
// A field shows the text in the picked language; when that language has none, its placeholder
// is what customers and staff see instead (the venue language's text, else any).
import { DEFAULT_LANGUAGE, MENU_LANGUAGES, shownText } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Dropdown, Input, Textarea } from '@xenia/ui'
import { useEditLang, useVenueLanguage } from './editLang'
export function LanguagePicker({ value, onChange, testId = 'product-lang' }) {
const { t } = useTranslation('manager')
const venue = useVenueLanguage()
const options = [
{ value: DEFAULT_LANGUAGE, label: t('products.editor.langDefault', { language: t(`products.editor.lang.${venue}`) }), hint: t('products.editor.langDefaultHint') },
...MENU_LANGUAGES.map(l => ({ value: l, label: t(`products.editor.lang.${l}`) })),
]
return (
<Dropdown size="sm" className="w-56" value={value} onChange={onChange} options={options} searchable={false}
aria-label={t('products.editor.langOf')} data-testid={testId} />
)
}
/** A name (or, `multiline`, a description) in the picked language. */
export function TrInput({ texts, fallback, onChange, multiline = false, placeholder, ...rest }) {
const { slot, venue } = useEditLang()
const shown = shownText(texts, venue, fallback)
const Tag = multiline ? Textarea : Input
return (
<Tag value={texts?.[slot] ?? ''} onChange={e => onChange({ ...(texts ?? {}), [slot]: e.target.value })}
placeholder={shown || placeholder} lang={slot} {...rest} />
)
}
@@ -1,54 +1,64 @@
// The product editor (plan step 6.3, was Management/ProductFormModal): the product on the left
// (its details, where it's sold, cost, fiscal fields), what a waiter can choose on the right
// (ChoicesPanel). A service item (cutlery, a cover charge) has only the left side.
// "Copy" opens a new product filled from this one.
// (ChoicesPanel). Service items (cutlery, a cover charge) have their own small dialog
// (ServiceItemDialog, 2026-11-21). "Copy" opens a new product filled from this one.
// The language picker at the top (owner 2026-11-21) sets the language every name and description
// field edits, on both sides: "Default" is the venue's language; a language without a text shows
// the venue language's (else any) in its place.
import { useState } from 'react'
import { Copy } from 'lucide-react'
import { DEFAULT_LANGUAGE } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Tabs, cx } from '@xenia/ui'
import { Button, Dialog, Tabs } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import ChoicesPanel from './ChoicesPanel'
import { CostTab, FiscalTab, InfoTab, SoldAtTab } from './InfoTabs'
import { LanguagePicker } from './LanguageFields'
import { EditLang, editLangOf, useVenueLanguage } from './editLang'
import { buildBody, buildForm, canSave } from './formLogic'
export default function ProductEditor({ product, categories, prepZones, saving, onSave, onCopy, onClose }) {
const { t } = useTranslation('manager')
const venue = useVenueLanguage()
const [form, setForm] = useState(() => product._form ?? buildForm(product)) // a copy brings its form
const [left, setLeft] = useState('info')
const [lang, setLang] = useState(DEFAULT_LANGUAGE)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
const fiscalOn = settings?.['fiscal.enabled']?.value === 'true'
let vatGroups = []
try { vatGroups = JSON.parse(settings?.['fiscal.vat_groups']?.value || '[]') } catch { vatGroups = [] }
const service = form.is_service_item
const isNew = !product.id
const leftTabs = ['info', ...(service ? [] : ['soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])])]
const leftTabs = ['info', 'soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])]
return (
<Dialog open size="wide" onClose={onClose} className="h-[94vh]" bodyClass="!p-0 flex"
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
footer={<div className="flex items-center gap-2 w-full">
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<span className="flex-1" />
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
<Button disabled={!canSave(form)} loading={saving} onClick={() => onSave(buildBody(form))} data-testid="product-save">
{isNew ? t('products.editor.create') : t('products.save')}
</Button>
</div>}>
<div className="flex-1 flex flex-col md:flex-row min-h-0 w-full overflow-y-auto md:overflow-hidden" data-testid="product-editor">
<div className={cx('flex flex-col md:min-h-0 border-b md:border-b-0 md:border-r border-line bg-surface-2', service ? 'w-full' : 'w-full md:w-[34%] md:min-w-[24rem]')}>
<Tabs fill className="px-card bg-surface shrink-0" value={left} onChange={setLeft}
tabs={leftTabs.map(k => ({ id: k, label: t(`products.editor.left.${k}`), testId: `editor-tab-${k}` }))} />
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
{left === 'soldAt' && <SoldAtTab form={form} set={set} product={product} />}
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
<EditLang.Provider value={editLangOf(lang, venue)}>
<Dialog open size="wide" onClose={onClose} className="h-[94vh]" bodyClass="!p-0 flex"
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
headerEnd={<LanguagePicker value={lang} onChange={setLang} />}
footer={<div className="flex items-center gap-2 w-full">
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<span className="flex-1" />
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
<Button disabled={!canSave(form, venue)} loading={saving} onClick={() => onSave(buildBody(form, venue))} data-testid="product-save">
{isNew ? t('products.editor.create') : t('products.save')}
</Button>
</div>}>
<div className="flex-1 flex flex-col md:flex-row min-h-0 w-full overflow-y-auto md:overflow-hidden" data-testid="product-editor">
<div className="flex flex-col md:min-h-0 border-b md:border-b-0 md:border-r border-line bg-surface-2 w-full md:w-[34%] md:min-w-[24rem]">
<Tabs fill className="px-card bg-surface shrink-0" value={left} onChange={setLeft}
tabs={leftTabs.map(k => ({ id: k, label: t(`products.editor.left.${k}`), testId: `editor-tab-${k}` }))} />
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
{left === 'soldAt' && <SoldAtTab form={form} set={set} product={product} />}
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
</div>
</div>
<div className="flex flex-1 min-w-0 flex-col min-h-[30rem] md:min-h-0"><ChoicesPanel form={form} setForm={setForm} /></div>
</div>
{!service && <div className="flex flex-1 min-w-0 flex-col min-h-[30rem] md:min-h-0"><ChoicesPanel form={form} setForm={setForm} /></div>}
</div>
</Dialog>
</Dialog>
</EditLang.Provider>
)
}
@@ -0,0 +1,47 @@
// A service item (2026-11-21, was a switch in the product editor): cutlery, glasses, a cover
// charge. Only what it needs: its name (in the language picked at the top right, like products),
// an optional price and the prep zones it prints at. Free: printed once, not kept on the order;
// with a price: printed in its own SERVICE section and counted in the takings.
import { useState } from 'react'
import { DEFAULT_LANGUAGE } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field } from '@xenia/ui'
import { PrepZonesField } from './InfoTabs'
import { LanguagePicker, TrInput } from './LanguageFields'
import { EditLang, editLangOf, useVenueLanguage } from './editLang'
import { buildBody, buildForm, canSave } from './formLogic'
import { PriceInput } from './parts'
export default function ServiceItemDialog({ product, prepZones, saving, onSave, onClose }) {
const { t } = useTranslation('manager')
const venue = useVenueLanguage()
const [form, setForm] = useState(() => buildForm({ ...product, is_service_item: true }))
const [lang, setLang] = useState(DEFAULT_LANGUAGE)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const isNew = !product.id
const paid = Number(String(form.base_price ?? '').replace(',', '.')) > 0
return (
<EditLang.Provider value={editLangOf(lang, venue)}>
<Dialog open size="md" onClose={onClose}
title={isNew ? t('products.editor.serviceNewTitle') : t('products.editor.editTitle', { name: product.name })}
headerEnd={<LanguagePicker value={lang} onChange={setLang} testId="service-lang" />}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button disabled={!canSave(form, venue)} loading={saving} onClick={() => onSave({ ...buildBody(form, venue), is_service_item: true })} data-testid="service-save">
{isNew ? t('products.editor.create') : t('products.save')}
</Button>
</>}>
<div className="grid gap-4" data-testid="service-dialog">
<p className="text-label text-ink-2">{t('products.editor.serviceHint')}</p>
<Field label={t('products.editor.name')} required>
<TrInput texts={form.names} fallback={form.name} onChange={v => set('names', v)} autoFocus placeholder={t('products.editor.servicePlaceholder')} data-testid="service-name" />
</Field>
<Field label={t('products.editor.priceOptional')} hint={paid ? t('products.editor.servicePaid') : t('products.editor.serviceFree')}>
<PriceInput className="w-full" value={form.base_price} onChange={v => set('base_price', v)} label={t('products.editor.price')} data-testid="service-price" />
</Field>
<PrepZonesField form={form} set={set} prepZones={prepZones} />
</div>
</Dialog>
</EditLang.Provider>
)
}
@@ -0,0 +1,19 @@
// The language the product editor's fields are typed in (owner 2026-11-21): the picker at the
// top of the editor sets it; every name / description field (the product's and every choice's)
// edits that language. "default" is the venue's language (Settings → venue.language).
import { createContext, useContext } from 'react'
import { DEFAULT_LANGUAGE, MENU_LANGUAGES, slotOf, useAccess } from '@xenia/access'
export const EditLang = createContext({ lang: DEFAULT_LANGUAGE, slot: MENU_LANGUAGES[0], venue: MENU_LANGUAGES[0] })
/** { lang: the picker's value, slot: the language edited, venue: the venue's language }. */
export const useEditLang = () => useContext(EditLang)
/** The venue's language, one of the menu languages. */
export function useVenueLanguage() {
const { venue } = useAccess()
return MENU_LANGUAGES.includes(venue?.language) ? venue.language : MENU_LANGUAGES[0]
}
/** The context value for a picker's choice. */
export const editLangOf = (lang, venue) => ({ lang, slot: slotOf(lang, venue), venue })
@@ -1,14 +1,29 @@
// The product editor's form (plan step 6.3): a product → the form, the form → the API body,
// and the edits that touch several lists at once (favourites, choice groups). No React
// (tests/products.test.mjs). The body's shapes are the API's (schemas/product.py).
// Texts per language (owner 2026-11-21, core/menu_languages.py): the product's name and
// description in `names` / `descriptions` {language: text}, every choice's name in `tr`; the
// stored `name` is what is shown when a language has none (the venue's, else any). The editor's
// language picker picks which language the fields edit; "Default" is the venue's language.
import { SALES_POINTS } from '@xenia/access/salesPoints'
import { MENU_LANGUAGES, shownText } from '@xenia/access/menuLanguages'
export const UNITS = ['piece', 'portion', 'kg', 'liter', 'gram', 'ml']
export const WEIGHED = new Set(['kg', 'liter', 'gram', 'ml'])
export const LISTS = { quick: 'quick_options', ingredient: 'ingredients', option: 'options', pref: 'preference_sets' }
const num = v => (v === '' || v == null ? 0 : Number(String(v).replace(',', '.')) || 0)
const sub = s => ({ name: s.name ?? '', extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
const sub = s => ({ name: s.name ?? '', tr: { ...(s.translations ?? {}) }, extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
const field = (tr, k) => Object.fromEntries(Object.entries(tr ?? {}).filter(([, v]) => v?.[k]).map(([l, v]) => [l, v[k]]))
/** {language: text} without empty texts or unknown languages (the API's shape). */
export const cleanTexts = tr => Object.fromEntries(MENU_LANGUAGES.filter(l => (tr?.[l] ?? '').trim()).map(l => [l, tr[l].trim()]))
/** A text item's name for the API: the venue language's, else any language's, else what was stored. */
export const nameOf = (x, venue) => shownText(x.tr, venue, x.name)
/** What an item is called in the editor's language (else what is shown), for labels. */
export const labelIn = (x, slot, venue) => (x.tr?.[slot] ?? '').trim() || nameOf(x, venue)
export function emptyProduct(preset = {}) {
return { name: '', base_price: '', category_ids: [], primary_category_id: null, is_available: true, lifecycle_status: 'active', ...preset }
@@ -18,6 +33,8 @@ export function buildForm(p) {
return {
name: p.name ?? '',
description: p.description ?? '',
names: field(p.translations, 'name'),
descriptions: field(p.translations, 'description'),
category_ids: [...(p.category_ids ?? (p.category_id ? [p.category_id] : []))],
primary_category_id: p.primary_category_id ?? p.category_id ?? (p.category_ids?.[0] ?? null),
base_price: p.base_price ?? '',
@@ -26,31 +43,30 @@ export function buildForm(p) {
lifecycle_status: p.lifecycle_status ?? 'active',
prep_zone_ids: [...(p.prep_zone_ids ?? [])],
allergens: { ...(p.allergens ?? {}) },
// the menu in other languages (6.4): {lang: {name, description}}; quick options' own on each row (`tr`)
translations: Object.fromEntries(Object.entries(p.translations ?? {}).map(([l, v]) => [l, { name: v.name ?? '', description: v.description ?? '' }])),
quick_options: (p.quick_options ?? []).map(q => ({
name: q.name, price: q.price ?? 0, allow_multiple: !!q.allow_multiple, is_favorite: !!q.is_favorite,
favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: !!q.is_compact,
tr: Object.fromEntries(Object.entries(p.translations ?? {}).map(([l, v]) => [l, v.quick?.[q.name] ?? ''])),
// its own names (0042), else the product's old `quick` map
tr: { ...Object.fromEntries(Object.entries(p.translations ?? {}).filter(([, v]) => v?.quick?.[q.name]).map(([l, v]) => [l, v.quick[q.name]])), ...(q.translations ?? {}) },
})),
options: (p.options ?? []).map(o => ({
name: o.name, extra_cost: o.extra_cost ?? 0, allow_multiple: !!o.allow_multiple, multi_select: !!o.multi_select,
name: o.name, tr: { ...(o.translations ?? {}) }, extra_cost: o.extra_cost ?? 0, allow_multiple: !!o.allow_multiple, multi_select: !!o.multi_select,
is_compact: !!o.is_compact, sub_choices: (o.sub_choices ?? []).map(sub),
is_favorite: !!o.is_favorite, favorite_sort_order: o.favorite_sort_order ?? 0, group_id: o.group_id ?? null,
})),
ingredients: (p.ingredients ?? []).map(i => ({
name: i.name, extra_cost: i.extra_cost ?? 0, is_favorite: !!i.is_favorite, favorite_sort_order: i.favorite_sort_order ?? 0,
name: i.name, tr: { ...(i.translations ?? {}) }, extra_cost: i.extra_cost ?? 0, is_favorite: !!i.is_favorite, favorite_sort_order: i.favorite_sort_order ?? 0,
is_compact: !!i.is_compact, group_id: i.group_id ?? null,
})),
preference_sets: (p.preference_sets ?? []).map(ps => ({
name: ps.name,
name: ps.name, tr: { ...(ps.translations ?? {}) },
default_choice_index: ps.choices ? ps.choices.findIndex(c => c.id === ps.default_choice_id) : -1,
choices: (ps.choices ?? []).map(c => ({
name: c.name, extra_cost: c.extra_cost ?? 0, disables_subset: !!c.disables_subset, is_compact: !!c.is_compact,
name: c.name, tr: { ...(c.translations ?? {}) }, extra_cost: c.extra_cost ?? 0, disables_subset: !!c.disables_subset, is_compact: !!c.is_compact,
sub_choices: (c.sub_choices ?? []).map(sub),
})),
group_id: ps.group_id ?? null,
shared_subset: ps.shared_subset ? { name: ps.shared_subset.name ?? '', choices: (ps.shared_subset.choices ?? []).map(sub) } : null,
shared_subset: ps.shared_subset ? { name: ps.shared_subset.name ?? '', tr: { ...(ps.shared_subset.translations ?? {}) }, choices: (ps.shared_subset.choices ?? []).map(sub) } : null,
is_favorite: !!ps.is_favorite, favorite_sort_order: ps.favorite_sort_order ?? 0,
allow_multi_select: !!ps.allow_multi_select, allow_choice_quantity: !!ps.allow_choice_quantity,
})),
@@ -69,16 +85,18 @@ export function buildForm(p) {
fiscal_name: p.fiscal_name ?? '',
fiscal_vat_group_id: p.fiscal_vat_group_id ?? null,
// choice groups (folders) keyed by a form id; the API takes their index
modifier_groups: (p.modifier_groups ?? []).map(g => ({ key: g.id, modifier_type: g.modifier_type, name: g.name })),
modifier_groups: (p.modifier_groups ?? []).map(g => ({ key: g.id, modifier_type: g.modifier_type, name: g.name, tr: { ...(g.translations ?? {}) } })),
}
}
export function buildBody(f) {
/** The form → the API body. `venue`: the venue's language (what "Default" edits). */
export function buildBody(f, venue = 'el') {
const groupIndex = key => (key == null ? null : f.modifier_groups.findIndex(g => g.key === key))
const subOut = s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
const texts = x => ({ name: nameOf(x, venue), translations: cleanTexts(x.tr) })
const subOut = s => ({ ...texts(s), extra_cost: num(s.extra_cost), is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
return {
name: f.name.trim(),
description: f.description.trim() || null,
name: shownText(f.names, venue, f.name),
description: shownText(f.descriptions, venue, f.description) || null,
category_ids: f.category_ids,
primary_category_id: f.category_ids.includes(f.primary_category_id) ? f.primary_category_id : (f.category_ids[0] ?? null),
base_price: num(f.base_price),
@@ -89,28 +107,28 @@ export function buildBody(f) {
allergens: f.allergens,
translations: translationsBody(f),
quick_options: f.quick_options.map((q, i) => ({
name: q.name, price: num(q.price), allow_multiple: q.allow_multiple, sort_order: i,
...texts(q), price: num(q.price), allow_multiple: q.allow_multiple, sort_order: i,
is_favorite: q.is_favorite, favorite_sort_order: q.favorite_sort_order, is_compact: q.is_compact,
})),
modifier_groups: f.modifier_groups.map((g, i) => ({ modifier_type: g.modifier_type, name: g.name, sort_order: i })),
modifier_groups: f.modifier_groups.map((g, i) => ({ modifier_type: g.modifier_type, ...texts(g), sort_order: i })),
options: f.options.map(o => ({
name: o.name, extra_cost: num(o.extra_cost), allow_multiple: o.allow_multiple, multi_select: o.multi_select,
...texts(o), extra_cost: num(o.extra_cost), allow_multiple: o.allow_multiple, multi_select: o.multi_select,
is_compact: o.is_compact, sub_choices: o.sub_choices.map(subOut),
is_favorite: o.is_favorite, favorite_sort_order: o.favorite_sort_order, group_id: groupIndex(o.group_id),
})),
ingredients: f.ingredients.map(i => ({
name: i.name, extra_cost: num(i.extra_cost), is_favorite: i.is_favorite, favorite_sort_order: i.favorite_sort_order,
...texts(i), extra_cost: num(i.extra_cost), is_favorite: i.is_favorite, favorite_sort_order: i.favorite_sort_order,
is_compact: i.is_compact, group_id: groupIndex(i.group_id),
})),
preference_sets: f.preference_sets.map(ps => ({
name: ps.name,
...texts(ps),
default_choice_index: ps.default_choice_index >= 0 ? ps.default_choice_index : null,
shared_subset: ps.shared_subset?.choices?.length
? { name: ps.shared_subset.name || '', choices: ps.shared_subset.choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default })) }
? { ...texts(ps.shared_subset), choices: ps.shared_subset.choices.map(s => ({ ...texts(s), extra_cost: num(s.extra_cost), is_default: !!s.is_default })) }
: null,
choices: ps.choices.map(c => ({
name: c.name, extra_cost: num(c.extra_cost), disables_subset: c.disables_subset, is_compact: c.is_compact,
sub_choices: c.sub_choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, is_compact: !!s.is_compact })),
...texts(c), extra_cost: num(c.extra_cost), disables_subset: c.disables_subset, is_compact: c.is_compact,
sub_choices: c.sub_choices.map(s => ({ ...texts(s), extra_cost: num(s.extra_cost), is_default: !!s.is_default, is_compact: !!s.is_compact })),
})),
is_favorite: ps.is_favorite, favorite_sort_order: ps.favorite_sort_order, group_id: groupIndex(ps.group_id),
allow_multi_select: ps.allow_multi_select, allow_choice_quantity: ps.allow_choice_quantity,
@@ -132,24 +150,20 @@ export function buildBody(f) {
}
}
/** The translations for the API: per language its name, description and the quick options' names (by their base name). */
/** The product's translations for the API: per language its name and description. */
export function translationsBody(f) {
const langs = new Set([...Object.keys(f.translations ?? {}), ...f.quick_options.flatMap(q => Object.keys(q.tr ?? {}))])
const names = cleanTexts(f.names)
const descs = cleanTexts(f.descriptions)
const out = {}
for (const l of langs) {
const t = f.translations?.[l] ?? {}
const quick = Object.fromEntries(f.quick_options.filter(q => q.name.trim() && (q.tr?.[l] ?? '').trim()).map(q => [q.name, q.tr[l].trim()]))
const v = { ...(t.name?.trim() ? { name: t.name.trim() } : {}), ...(t.description?.trim() ? { description: t.description.trim() } : {}), ...(Object.keys(quick).length ? { quick } : {}) }
for (const l of MENU_LANGUAGES) {
const v = { ...(names[l] ? { name: names[l] } : {}), ...(descs[l] ? { description: descs[l] } : {}) }
if (Object.keys(v).length) out[l] = v
}
return out
}
/** A translated field of the product. */
export const setTranslation = (f, lang, field, value) => ({ ...f, translations: { ...f.translations, [lang]: { ...(f.translations?.[lang] ?? {}), [field]: value } } })
/** Can it be saved: a name, and a price unless it's a service item. */
export const canSave = f => !!f.name.trim() && (f.is_service_item || (f.base_price !== '' && f.base_price != null))
/** Can it be saved: a name in some language, and a price unless it's a service item. */
export const canSave = (f, venue = 'el') => !!shownText(f.names, venue, f.name) && (f.is_service_item || (f.base_price !== '' && f.base_price != null))
// ── categories ──────────────────────────────────────────────────────────────
@@ -1,11 +1,16 @@
// Small controls of the product editor (plan step 6.3).
// Small controls of the product editor (plan step 6.3). 2026-11-21: one height in a row (sm),
// the shared buttons (the heart red when on, delete red under the pointer), names in the
// language picked at the top of the editor.
import { useState } from 'react'
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, cx } from '@xenia/ui'
import { Button, FilterChip, IconButton, cx } from '@xenia/ui'
import { TrInput } from './LanguageFields'
import { useEditLang } from './editLang'
import { labelIn } from './formLogic'
/** A price with − / + of 0.10 (negative allowed for choices that lower the price). */
export function PriceInput({ value, onChange, allowNegative = false, className, label, ...rest }) {
export function PriceInput({ value, onChange, allowNegative = false, size = 'md', className, label, ...rest }) {
const { t } = useTranslation('manager')
const n = Number(String(value ?? '').replace(',', '.')) || 0
const step = d => {
@@ -13,7 +18,7 @@ export function PriceInput({ value, onChange, allowNegative = false, className,
onChange(allowNegative ? next : Math.max(0, next))
}
return (
<span className={cx('inline-flex items-stretch rounded-control border border-line bg-surface h-control overflow-hidden', className)}>
<span className={cx('inline-flex items-stretch rounded-control border border-line bg-surface overflow-hidden', size === 'sm' ? 'h-control-sm' : 'h-control', className)}>
<button type="button" className="px-2 text-ink-2 hover:bg-surface-2" onClick={() => step(-0.1)} aria-label={t('products.editor.less')}><Minus size={14} /></button>
<input type="text" inputMode="decimal" value={value ?? ''} onChange={e => onChange(e.target.value)} placeholder="0.00" aria-label={label}
className="w-full min-w-0 text-center text-body bg-transparent outline-none tabular-nums" {...rest} />
@@ -27,8 +32,8 @@ export function MoveButtons({ onUp, onDown, first, last }) {
const { t } = useTranslation('manager')
return (
<span className="flex flex-col shrink-0">
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveUp')} disabled={first} onClick={onUp}><ChevronUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveDown')} disabled={last} onClick={onDown}><ChevronDown size={14} /></IconButton>
<IconButton size="sm" variant="ghost" className="!min-h-0 !h-[18px]" label={t('products.moveUp')} disabled={first} onClick={onUp}><ChevronUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" className="!min-h-0 !h-[18px]" label={t('products.moveDown')} disabled={last} onClick={onDown}><ChevronDown size={14} /></IconButton>
</span>
)
}
@@ -48,8 +53,7 @@ export function DefaultToggle({ on, onClick }) {
export function FavouriteToggle({ on, onClick }) {
const { t } = useTranslation('manager')
return (
<IconButton size="sm" variant="ghost" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={on} onClick={onClick}
className={on ? 'text-danger' : 'text-ink-3'}>
<IconButton size="sm" tone="danger" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={!!on} onClick={onClick} data-testid="favourite">
<Heart size={16} fill={on ? 'currentColor' : 'none'} />
</IconButton>
)
@@ -68,46 +72,49 @@ export function Check({ checked, onChange, children }) {
/** The sub-choices under a choice ("Syrup" → Caramel, Vanilla). */
export function SubChoices({ subs, parent, onChange, withMultiple = false }) {
const { t } = useTranslation('manager')
const { slot, venue } = useEditLang()
if (!subs?.length) return null
const set = (i, k, v) => onChange(subs.map((s, j) => (j === i ? { ...s, [k]: v } : k === 'is_default' && v ? { ...s, is_default: false } : s)))
const move = (i, d) => { const j = i + d; if (j < 0 || j >= subs.length) return; const n = [...subs]; [n[i], n[j]] = [n[j], n[i]]; onChange(n) }
return (
<div className="border-t border-line bg-surface-2 px-3 py-2 grid gap-2">
<p className="text-caption font-semibold text-ink-2">{t('products.editor.subsOf', { name: parent || '…' })}</p>
<p className="text-caption font-semibold text-ink-2">{t('products.editor.subsOf', { name: labelIn(parent, slot, venue) || '…' })}</p>
{subs.map((s, i) => (
<div key={i} className="flex flex-wrap items-center gap-2 pl-4">
<MoveButtons first={i === 0} last={i === subs.length - 1} onUp={() => move(i, -1)} onDown={() => move(i, 1)} />
<DefaultToggle on={s.is_default} onClick={() => set(i, 'is_default', !s.is_default)} />
<Input size="sm" className="flex-1 min-w-28" value={s.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.subPlaceholder')} />
<PriceInput className="w-28" value={s.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{withMultiple && <Check checked={s.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
<Check checked={s.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
<TrInput size="sm" className="flex-1 min-w-28" texts={s.tr} fallback={s.name} onChange={v => set(i, 'tr', v)} placeholder={t('products.editor.subPlaceholder')} />
<PriceInput size="sm" className="w-28" value={s.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{withMultiple && <FilterChip size="sm" tone="info" pressed={!!s.allow_multiple} onClick={() => set(i, 'allow_multiple', !s.allow_multiple)}>{t('products.editor.multiple')}</FilterChip>}
<FilterChip size="sm" tone="accent" pressed={!!s.is_compact} onClick={() => set(i, 'is_compact', !s.is_compact)}>{t('products.editor.compact')}</FilterChip>
<IconButton size="sm" tone="danger" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={16} /></IconButton>
</div>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start ml-4"
onClick={() => onChange([...subs, { name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }])}>{t('products.editor.addSub')}</Button>
<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} className="justify-self-start ml-4"
onClick={() => onChange([...subs, { name: '', tr: {}, extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }])}>{t('products.editor.addSub')}</Button>
</div>
)
}
/** A choice group's header (a folder of choices): fold, rename, remove. */
/** A choice group's header (a folder of choices): fold, rename (in the editor's language), remove. */
export function GroupHeader({ group, folded, onFold, onRename, onRemove }) {
const { t } = useTranslation('manager')
const { slot, venue } = useEditLang()
const [editing, setEditing] = useState(false)
const [name, setName] = useState(group.name)
return (
<div className="flex items-center gap-1.5 mt-2">
<button type="button" onClick={onFold} aria-expanded={!folded}
className="flex-1 flex items-center gap-2 px-3 py-2 rounded-control bg-accent-soft text-accent-ink text-label font-semibold text-left">
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
{editing
? <input className="flex-1 min-w-0 bg-surface text-ink rounded px-1" autoFocus value={name} onChange={e => setName(e.target.value)}
onClick={e => e.stopPropagation()} onBlur={() => { onRename(name); setEditing(false) }} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
: <span className="flex-1 truncate">{group.name || t('products.editor.unnamedGroup')}</span>}
</button>
<IconButton size="sm" variant="ghost" label={t('products.editor.renameGroup')} onClick={() => { setName(group.name); setEditing(true) }}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('products.editor.removeGroup')} onClick={onRemove}><Trash2 size={14} /></IconButton>
{editing ? (
<TrInput size="sm" className="flex-1" autoFocus texts={group.tr} fallback={group.name} onChange={onRename}
onBlur={() => setEditing(false)} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} aria-label={t('products.editor.renameGroup')} />
) : (
<button type="button" onClick={onFold} aria-expanded={!folded}
className="flex-1 flex items-center gap-2 px-3 h-control-sm rounded-control bg-accent-soft text-accent-ink text-label font-semibold text-left">
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
<span className="flex-1 truncate">{labelIn(group, slot, venue) || t('products.editor.unnamedGroup')}</span>
</button>
)}
<IconButton size="sm" tone="accent" label={t('products.editor.renameGroup')} onClick={() => setEditing(true)}><Pencil size={16} /></IconButton>
<IconButton size="sm" tone="danger" label={t('products.editor.removeGroup')} onClick={onRemove}><Trash2 size={16} /></IconButton>
</div>
)
}
+21 -9
View File
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict'
import {
SCOPES, applyFilters, bulkCategories, categoryTree, costOf, countIn, groupProducts, moveId, reorderBody, scopeProducts, stepBody, treeLabel,
} from '../src/pages/products/productsLogic.js'
import { addCategory, buildBody, buildForm, canSave, cleanTag, favourites, moveChoice, moveFavourite, removeCategory, removeChoice, removeGroup, setSub, toggleFavourite } from '../src/pages/products/editor/formLogic.js'
import { addCategory, buildBody, buildForm, canSave, cleanTag, cleanTexts, labelIn, favourites, moveChoice, moveFavourite, removeCategory, removeChoice, removeGroup, setSub, toggleFavourite } from '../src/pages/products/editor/formLogic.js'
const cats = [
{ id: 1, name: 'Coffees', sort_order: 0 },
@@ -110,12 +110,24 @@ test('the editor: favourites across lists, choices, groups', () => {
assert.equal(buildBody(removeGroup(f, 7)).ingredients[0].group_id, null)
})
test('the editor keeps the menu in other languages (6.4)', () => {
const f = buildForm({ name: 'Σουβλάκι', base_price: 3, quick_options: [{ name: 'Πίτα' }, { name: 'Σάλτσα' }],
translations: { en: { name: 'Skewer', quick: { 'Πίτα': 'Pitta' } } } })
assert.equal(f.translations.en.name, 'Skewer')
assert.equal(f.quick_options[0].tr.en, 'Pitta')
const renamed = { ...f, quick_options: [{ ...f.quick_options[0], name: 'Πίτα αραβική' }, f.quick_options[1]] }
assert.deepEqual(buildBody(renamed).translations, { en: { name: 'Skewer', quick: { 'Πίτα αραβική': 'Pitta' } } }) // kept by the new base name
assert.deepEqual(buildBody({ ...f, translations: { en: { name: ' ', description: '' } }, quick_options: [] }).translations, {})
test('the editor: every text per language; "Default" is the venue language (owner 2026-11-21)', () => {
const f = buildForm({ name: 'Σουβλάκι', base_price: 3, quick_options: [{ name: 'Πίτα', translations: { el: 'Πίτα' } }, { name: 'Σάλτσα' }],
translations: { el: { name: 'Σουβλάκι' }, en: { name: 'Skewer', quick: { 'Σάλτσα': 'Sauce' } } } })
assert.deepEqual(f.names, { el: 'Σουβλάκι', en: 'Skewer' })
assert.equal(f.quick_options[1].tr.en, 'Sauce') // the product's old quick map
// the venue speaks Greek: the shown name is the Greek one
let body = buildBody(f, 'el')
assert.equal(body.name, 'Σουβλάκι')
assert.deepEqual(body.translations, { el: { name: 'Σουβλάκι' }, en: { name: 'Skewer' } })
assert.deepEqual(body.quick_options[1].translations, { en: 'Sauce' })
// the venue switches to English: English is shown; with no English, the only text there is
assert.equal(buildBody(f, 'en').name, 'Skewer')
const greekOnly = { ...f, names: { el: 'Πίτα' } }
assert.equal(buildBody(greekOnly, 'en').name, 'Πίτα')
assert.equal(labelIn(f.quick_options[0], 'en', 'en'), 'Πίτα') // nothing in English: what is shown
// a choice typed only in English is called that
const typed = { ...f, ingredients: [{ name: '', tr: { en: 'Onion' }, extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, group_id: null }] }
assert.deepEqual([buildBody(typed, 'el').ingredients[0].name, buildBody(typed, 'el').ingredients[0].translations], ['Onion', { en: 'Onion' }])
assert.equal(canSave({ ...f, names: {}, name: '' }, 'el'), false)
assert.deepEqual(cleanTexts({ el: ' ', en: ' x ', fr: 'y' }), { en: 'x' })
})
+1 -1
View File
@@ -20,4 +20,4 @@ export { OverrideHost } from './OverrideHost.jsx'
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js'
export { Allergens } from './Allergens.jsx'
export { MENU_LANGUAGES, translatedLanguages, inLanguage } from './menuLanguages.js'
export { DEFAULT_LANGUAGE, MENU_LANGUAGES, inLanguage, shownText, slotOf, translatedLanguages } from './menuLanguages.js'
+17 -2
View File
@@ -1,6 +1,8 @@
// The menu's languages (plan step 6.4, owner 2026-11-18): English and Greek, the same list as the
// backend's core/menu_languages.py. A product's own name is its base text; a translation adds
// the other language; a missing translation shows the base text.
// backend's core/menu_languages.py. Since 2026-11-21 every menu text is kept per language, the
// venue's own included; "Default" in the editors is the venue's language. What is shown for an
// item: the venue language's text, else the first language that has one (never mixed, never
// machine-translated).
export const MENU_LANGUAGES = ['el', 'en']
/** The languages a venue translates its menu into: every menu language but its own. */
@@ -9,3 +11,16 @@ export const translatedLanguages = venueLanguage => MENU_LANGUAGES.filter(l => l
/** A product's or category's text in a language: `names` / `descriptions` {lang: text} as the
* backend resolves them for customer screens, else the base text. */
export const inLanguage = (texts, lang, base) => (texts && texts[lang]) || base
/** The editors' "Default" (owner 2026-11-21): the venue's language. */
export const DEFAULT_LANGUAGE = 'default'
/** The language a picker's choice edits: "default" → the venue's language. */
export const slotOf = (lang, venueLanguage) => (!lang || lang === DEFAULT_LANGUAGE ? (MENU_LANGUAGES.includes(venueLanguage) ? venueLanguage : MENU_LANGUAGES[0]) : lang)
const filled = v => (typeof v === 'string' && v.trim() ? v.trim() : '')
/** The text shown for an item {language: text}: the venue language's, else the first language
* that has one, else `fallback` (the row's stored text, for items never given a language). */
export const shownText = (texts, venueLanguage, fallback = '') =>
filled(texts?.[venueLanguage]) || MENU_LANGUAGES.map(l => filled(texts?.[l])).find(Boolean) || filled(fallback)
@@ -0,0 +1,20 @@
// Menu texts per language (owner 2026-11-21): "Default" is the venue's language; what is shown is
// the venue language's text, else the first language that has one, else the stored text.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { DEFAULT_LANGUAGE, shownText, slotOf } from '../src/menuLanguages.js'
test('"Default" edits the venue language', () => {
assert.equal(slotOf(DEFAULT_LANGUAGE, 'el'), 'el')
assert.equal(slotOf(DEFAULT_LANGUAGE, 'en'), 'en')
assert.equal(slotOf('en', 'el'), 'en')
assert.equal(slotOf(DEFAULT_LANGUAGE, 'xx'), 'el') // an unknown venue language: the first menu language
})
test('shown: the venue language, else any, never mixed', () => {
assert.equal(shownText({ el: 'Πίτα', en: 'Pie' }, 'el'), 'Πίτα')
assert.equal(shownText({ el: 'Πίτα', en: 'Pie' }, 'en'), 'Pie')
assert.equal(shownText({ el: 'Πίτα' }, 'en'), 'Πίτα') // the venue went English: the only text there is
assert.equal(shownText({ el: ' ' }, 'en', 'Old'), 'Old') // nothing in any language: what was stored
assert.equal(shownText({}, 'en'), '')
})
+4
View File
@@ -1929,6 +1929,7 @@
"view_list": "Λίστα",
"view_grid": "Πλέγμα",
"new": "Νέο προϊόν",
"newService": "Νέο είδος σερβιρίσματος",
"price": "Τιμή",
"from": "από",
"to": "έως",
@@ -2046,6 +2047,9 @@
"done_other": "{{count}} προϊόντα ενημερώθηκαν"
},
"editor": {
"serviceNewTitle": "Νέο είδος σερβιρίσματος",
"langDefault": "Προεπιλογή ({{language}})",
"langDefaultHint": "Η γλώσσα του καταστήματος",
"newTitle": "Νέο προϊόν",
"editTitle": "Επεξεργασία: {{name}}",
"copy": "Αντιγραφή",
+4
View File
@@ -1929,6 +1929,7 @@
"view_list": "List",
"view_grid": "Grid",
"new": "New product",
"newService": "New service item",
"price": "Price",
"from": "from",
"to": "to",
@@ -2046,6 +2047,9 @@
"done_other": "{{count}} products updated"
},
"editor": {
"serviceNewTitle": "New service item",
"langDefault": "Default ({{language}})",
"langDefaultHint": "The venue's language",
"newTitle": "New product",
"editTitle": "Edit: {{name}}",
"copy": "Copy",
+3
View File
@@ -58,6 +58,8 @@
.x-btn--tone { color: var(--x-ink-2); }
.x-btn--tone:hover:not(:disabled), .x-btn--tone:focus-visible { color: rgb(var(--x-tone-ink)); }
.x-btn--icon.x-btn--tone { background: var(--x-surface-2); }
/* a toned toggle that is on (a favourite's heart) keeps its colour */
.x-btn--tone[aria-pressed="true"] { color: rgb(var(--x-tone-ink)); }
.x-btn--icon.x-btn--tone:hover:not(:disabled) { background: var(--x-surface-3); }
.x-btn--tone-danger { --x-tone: var(--x-danger-rgb); --x-tone-soft: var(--x-danger-soft-rgb); --x-tone-ink: var(--x-danger-ink-rgb); }
.x-btn--tone-warning { --x-tone: var(--x-warning-rgb); --x-tone-soft: var(--x-warning-soft-rgb); --x-tone-ink: var(--x-warning-ink-rgb); }
@@ -124,6 +126,7 @@
.x-modal__titles { flex: 1; min-width: 0; padding-top: var(--x-space-1-5); }
.x-modal__title { margin: 0; font-size: var(--x-text-title); line-height: var(--x-leading-title); font-weight: var(--x-weight-semibold); }
.x-modal__description { margin: var(--x-space-1) 0 0; font-size: var(--x-text-body); line-height: var(--x-leading-body); color: var(--x-ink-2); }
.x-modal__header-end { flex-shrink: 0; display: flex; align-items: center; gap: var(--x-space-2); }
.x-modal__close { margin: calc(-1 * var(--x-space-1)) calc(-1 * var(--x-space-1)) 0 0; }
.x-modal__toolbar { flex-shrink: 0; padding: var(--x-space-2) var(--x-space-6) var(--x-space-3); border-bottom: var(--x-border-width) solid var(--x-line); }
.x-modal__body {
+4 -2
View File
@@ -13,7 +13,7 @@ const CloseIcon = () => (
/** The shared body of Dialog and Sheet: backdrop, panel, header with ×, toolbar, body, footer. */
export function ModalFrame({
open, onClose, title, description, toolbar, children, footer,
open, onClose, title, description, headerEnd, toolbar, children, footer,
dismissible = true, closeLabel, initialFocus,
overlayClass, panelClass, grip = false, bodyClass,
}) {
@@ -41,12 +41,14 @@ export function ModalFrame({
className={panelClass}
>
{grip && <div className="x-sheet__grip" aria-hidden="true" />}
{(title || description || showClose) && (
{(title || description || showClose || headerEnd) && (
<div className="x-modal__header">
<div className="x-modal__titles">
{title && <h2 id={titleId} className="x-modal__title">{title}</h2>}
{description && <p id={descId} className="x-modal__description">{description}</p>}
</div>
{/* headerEnd: beside the close button (a language picker…) */}
{headerEnd && <div className="x-modal__header-end">{headerEnd}</div>}
{showClose && (
<IconButton label={closeLabel ?? labels.close} size="sm" className="x-modal__close" onClick={onClose} data-x-autofocus-skip="">
<CloseIcon />
+27 -5
View File
@@ -1014,12 +1014,23 @@ try {
await pRow.waitFor({ timeout: 15_000 })
await pRow.getByTestId('product-edit').click()
await page.getByTestId('product-editor').waitFor({ timeout: 10_000 })
await page.getByTestId('add-category').selectOption(String(catB.id))
await page.getByTestId('add-category').click() // 2026-11-21: the shared dropdown
await page.getByRole('option', { name: catB.name, exact: true }).click()
await page.getByTestId('allergen-gluten').click()
await page.getByTestId('allergen-milk').click()
await page.getByTestId('allergen-milk').click()
await page.getByTestId('product-lang-el').click() // 2026-11-20: one name field, a language switch above it
await page.getByTestId('translation-el-name').fill('E2E name in Greek') // 6.4: the test venue speaks English, so the other menu language is Greek
// 2026-11-21: the language picker at the top drives every name field; "Default" = the venue's (English here)
const pickLang = async label => { await page.getByTestId('product-lang').click(); await page.getByRole('option', { name: label }).first().click() }
await pickLang(/^Greek/)
await page.getByTestId('product-name').fill('Ε2Ε όνομα')
await page.getByTestId('choices-tab-quick').click()
await page.getByTestId('add-quick').click()
await page.getByTestId('quick-name').last().fill('Ε2Ε μπέικον')
await pickLang(/^Default \(English\)/)
const nameEmptyInDefault = await page.getByTestId('product-name').inputValue() === '' && await page.getByTestId('quick-name').last().inputValue() === ''
await page.getByTestId('product-name').fill('E2E name')
await page.getByTestId('quick-name').last().fill('E2E bacon')
r.check(`${pr} the language picker: a language without a text is empty (its placeholder shows what is used instead)`, nameEmptyInDefault)
r.check(`${pr} the editor lists both categories, the first one main; gluten "contains", milk "may contain"`,
await page.locator(`[data-testid="product-category"][data-id="${catA.id}"][data-main="true"]`).count() === 1
&& await page.locator(`[data-testid="product-category"][data-id="${catB.id}"][data-main="false"]`).count() === 1
@@ -1030,8 +1041,19 @@ try {
const savedP = (await api('GET', '/api/products/?all=true', { token: boss })).find(p => p.id === prodP.id)
r.check(`${pr} saved: listed in both, the main one kept, its allergens`, JSON.stringify(savedP.category_ids) === JSON.stringify([catA.id, catB.id])
&& savedP.primary_category_id === catA.id && JSON.stringify(savedP.allergens) === JSON.stringify({ gluten: 'contains', milk: 'may_contain' }), JSON.stringify([savedP.category_ids, savedP.allergens]))
r.check(`${pr} 6.4: its name for the other menu language is saved; the name itself is unchanged`, savedP.translations?.el?.name === 'E2E name in Greek' && savedP.name === prodP.name,
JSON.stringify(savedP.translations))
const quickP = savedP.quick_options.find(q => q.name === 'E2E bacon')
r.check(`${pr} every text per language: the name and a quick option in Greek and in the default (English, which is shown)`,
JSON.stringify(savedP.translations) === JSON.stringify({ el: { name: 'Ε2Ε όνομα' }, en: { name: 'E2E name' } }) && savedP.name === 'E2E name'
&& JSON.stringify(quickP?.translations) === JSON.stringify({ el: 'Ε2Ε μπέικον', en: 'E2E bacon' }), JSON.stringify([savedP.name, savedP.translations, savedP.quick_options]))
// a service item: its own small dialog (the switch is gone)
await page.getByTestId('service-new').click()
await page.getByTestId('service-dialog').waitFor({ timeout: 8000 })
await page.getByTestId('service-name').fill('E2E cutlery')
await page.getByTestId('service-save').click()
await page.getByTestId('service-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
let svc = null
for (let i = 0; i < 20 && !svc; i++) { await sleep(250); svc = (await api('GET', '/api/products/?all=true', { token: boss })).find(p => p.name === 'E2E cutlery') }
r.check(`${pr} "New service item" makes a service item, its name in the default language`, svc?.is_service_item === true && svc.translations?.en?.name === 'E2E cutlery', JSON.stringify(svc))
await page.getByTestId(`category-${catB.id}`).click()
const inB = page.locator(`[data-testid="product-group"][data-category="${catB.id}"] [data-testid="product-row"][data-id="${prodP.id}"]`)
r.check(`${pr} it shows in the second category too, marked "also in" the first`, await inB.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)