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:
@@ -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` |
|
| 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` |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
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
|
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}
|
return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES}
|
||||||
|
|
||||||
|
|
||||||
def quick_texts(base: str, translations: dict) -> dict:
|
def quick_texts(base: str, translations: dict, own: dict | None = None) -> dict:
|
||||||
return {lang: ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES}
|
"""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:
|
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
|
name = (product.digital_name if customer else None) or product.name
|
||||||
desc = (product.digital_description if customer else None) or product.description
|
desc = (product.digital_description if customer else None) or product.description
|
||||||
return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "description")}
|
return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "description")}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_names(value) -> dict:
|
||||||
|
"""A choice's translations {language: text}: API input → stored; empty texts dropped."""
|
||||||
|
data = _load(value)
|
||||||
|
out = {}
|
||||||
|
for lang, text in data.items():
|
||||||
|
if text is not None and not isinstance(text, str):
|
||||||
|
raise _bad(str(lang))
|
||||||
|
if not (text or "").strip():
|
||||||
|
continue # empty: nothing to keep, whatever the language
|
||||||
|
if lang not in MENU_LANGUAGES:
|
||||||
|
raise _bad(str(lang))
|
||||||
|
out[lang] = text.strip()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def names_of(row) -> dict:
|
||||||
|
"""A choice row's translations {language: text}, read safely."""
|
||||||
|
return {k: v for k, v in _load(getattr(row, "translations", None)).items() if isinstance(v, str)}
|
||||||
|
|
||||||
|
|
||||||
|
def name_texts(base: str, names: dict) -> dict:
|
||||||
|
"""{language: text} of a choice for every menu language: its own, else the base text."""
|
||||||
|
return {lang: names.get(lang) or base for lang in MENU_LANGUAGES}
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Every menu text per language (owner 2026-11-21, core/menu_languages.py).
|
||||||
|
|
||||||
|
- Every choice gets its own `translations` {language: text}: choice groups, quick options,
|
||||||
|
extras, ingredients, preference sets and their choices (sub-choices and a set's shared
|
||||||
|
sub-set keep theirs inside their JSON).
|
||||||
|
- The texts typed so far had no language: they become the text **in their language**: Greek
|
||||||
|
letters → "el", else the venue's language (`venue.language`, default "en"). A language that
|
||||||
|
already had a translation keeps it.
|
||||||
|
- The product's old `"quick": {"<quick option's name>": "…"}` translations move onto the quick
|
||||||
|
options.
|
||||||
|
|
||||||
|
Revision ID: 0042_menu_texts_per_language
|
||||||
|
Revises: 0041_floor_item_color
|
||||||
|
Create Date: 2026-11-21 12:00:00
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0042_menu_texts_per_language'
|
||||||
|
down_revision = '0041_floor_item_color'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
CHOICE_TABLES = ('product_modifier_groups', 'product_quick_options', 'product_options', 'product_ingredients',
|
||||||
|
'product_preference_sets', 'product_preference_choices')
|
||||||
|
GREEK = re.compile('[Ͱ-Ͽἀ-]')
|
||||||
|
LANGS = ('el', 'en')
|
||||||
|
|
||||||
|
|
||||||
|
def _load(v):
|
||||||
|
if not v:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
d = json.loads(v)
|
||||||
|
except ValueError:
|
||||||
|
return {}
|
||||||
|
return d if isinstance(d, (dict, list)) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _dump(d):
|
||||||
|
return json.dumps(d, ensure_ascii=False) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table in CHOICE_TABLES:
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
bind = op.get_bind()
|
||||||
|
row = bind.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'venue.language'")).first()
|
||||||
|
venue = (row[0] if row else None) or 'en'
|
||||||
|
venue = venue if venue in LANGS else 'en'
|
||||||
|
|
||||||
|
def lang_of(text):
|
||||||
|
return 'el' if GREEK.search(text or '') else venue
|
||||||
|
|
||||||
|
def names(text, current=None):
|
||||||
|
out = dict(current or {})
|
||||||
|
if (text or '').strip():
|
||||||
|
out.setdefault(lang_of(text), text.strip())
|
||||||
|
return out
|
||||||
|
|
||||||
|
def subs(raw):
|
||||||
|
"""Sub-choices (a JSON list of dicts) with their names per language."""
|
||||||
|
data = _load(raw)
|
||||||
|
if not isinstance(data, list) or not data:
|
||||||
|
return raw
|
||||||
|
for s in data:
|
||||||
|
if isinstance(s, dict):
|
||||||
|
s['translations'] = names(s.get('name'), s.get('translations') if isinstance(s.get('translations'), dict) else None)
|
||||||
|
return json.dumps(data, ensure_ascii=False)
|
||||||
|
|
||||||
|
# products: name / description in their language; the quick options' translations move out
|
||||||
|
quick_moved = {}
|
||||||
|
for pid, name, desc, tr in bind.execute(sa.text("SELECT id, name, description, translations FROM products")).fetchall():
|
||||||
|
data = _load(tr)
|
||||||
|
data = data if isinstance(data, dict) else {}
|
||||||
|
for lang, fields in list(data.items()):
|
||||||
|
if not isinstance(fields, dict):
|
||||||
|
data.pop(lang)
|
||||||
|
continue
|
||||||
|
for base, text in (fields.pop('quick', None) or {}).items():
|
||||||
|
quick_moved.setdefault(pid, {}).setdefault(base, {})[lang] = text
|
||||||
|
for field, text in (('name', name), ('description', desc)):
|
||||||
|
if (text or '').strip():
|
||||||
|
data.setdefault(lang_of(text), {}).setdefault(field, text.strip())
|
||||||
|
data = {k: v for k, v in data.items() if v}
|
||||||
|
bind.execute(sa.text("UPDATE products SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': pid})
|
||||||
|
|
||||||
|
for cid, name, tr in bind.execute(sa.text("SELECT id, name, translations FROM categories")).fetchall():
|
||||||
|
data = _load(tr)
|
||||||
|
data = data if isinstance(data, dict) else {}
|
||||||
|
if (name or '').strip():
|
||||||
|
data.setdefault(lang_of(name), {}).setdefault('name', name.strip())
|
||||||
|
bind.execute(sa.text("UPDATE categories SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': cid})
|
||||||
|
|
||||||
|
for qid, pid, name in bind.execute(sa.text("SELECT id, product_id, name FROM product_quick_options")).fetchall():
|
||||||
|
bind.execute(sa.text("UPDATE product_quick_options SET translations = :t WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name, quick_moved.get(pid, {}).get(name))), 'id': qid})
|
||||||
|
for table in ('product_modifier_groups', 'product_ingredients'):
|
||||||
|
for rid, name in bind.execute(sa.text(f"SELECT id, name FROM {table}")).fetchall():
|
||||||
|
bind.execute(sa.text(f"UPDATE {table} SET translations = :t WHERE id = :id"), {'t': _dump(names(name)), 'id': rid})
|
||||||
|
for table in ('product_options', 'product_preference_choices'):
|
||||||
|
for rid, name, sub in bind.execute(sa.text(f"SELECT id, name, sub_choices FROM {table}")).fetchall():
|
||||||
|
bind.execute(sa.text(f"UPDATE {table} SET translations = :t, sub_choices = :s WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name)), 's': subs(sub), 'id': rid})
|
||||||
|
for rid, name, shared in bind.execute(sa.text("SELECT id, name, shared_subset FROM product_preference_sets")).fetchall():
|
||||||
|
data = _load(shared)
|
||||||
|
if isinstance(data, dict) and data:
|
||||||
|
data['translations'] = names(data.get('name'))
|
||||||
|
data['choices'] = json.loads(subs(json.dumps(data.get('choices') or [])) or '[]')
|
||||||
|
shared = json.dumps(data, ensure_ascii=False)
|
||||||
|
bind.execute(sa.text("UPDATE product_preference_sets SET translations = :t, shared_subset = :s WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name)), 's': shared, 'id': rid})
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in CHOICE_TABLES:
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('translations')
|
||||||
@@ -140,6 +140,8 @@ class ProductModifierGroup(Base):
|
|||||||
modifier_type = Column(String, nullable=False)
|
modifier_type = Column(String, nullable=False)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
sort_order = Column(Integer, default=0, 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")
|
product = relationship("Product", back_populates="modifier_groups")
|
||||||
|
|
||||||
@@ -162,6 +164,8 @@ class ProductOption(Base):
|
|||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
# Optional group/folder this option belongs to
|
# Optional group/folder this option belongs to
|
||||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
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")
|
product = relationship("Product", back_populates="options")
|
||||||
|
|
||||||
@@ -178,6 +182,8 @@ class ProductQuickOption(Base):
|
|||||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||||
favorite_sort_order = Column(Integer, default=0, nullable=False)
|
favorite_sort_order = Column(Integer, default=0, nullable=False)
|
||||||
is_compact = Column(Boolean, default=False, 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")
|
product = relationship("Product", back_populates="quick_options")
|
||||||
|
|
||||||
@@ -195,6 +201,8 @@ class ProductIngredient(Base):
|
|||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
# Optional group/folder this ingredient belongs to
|
# Optional group/folder this ingredient belongs to
|
||||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
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")
|
product = relationship("Product", back_populates="ingredients")
|
||||||
|
|
||||||
@@ -217,6 +225,8 @@ class ProductPreferenceSet(Base):
|
|||||||
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
||||||
# When True, each selected choice can have a quantity (x2, x3, …)
|
# When True, each selected choice can have a quantity (x2, x3, …)
|
||||||
allow_choice_quantity = Column(Boolean, default=False, nullable=False)
|
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")
|
product = relationship("Product", back_populates="preference_sets")
|
||||||
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
|
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)
|
disables_subset = Column(Boolean, default=False, nullable=False)
|
||||||
# When True renders as half-width card on the PWA
|
# When True renders as half-width card on the PWA
|
||||||
is_compact = Column(Boolean, default=False, 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)
|
||||||
|
|
||||||
set = relationship("ProductPreferenceSet", back_populates="choices")
|
set = relationship("ProductPreferenceSet", back_populates="choices")
|
||||||
|
|
||||||
|
|||||||
@@ -22,11 +22,17 @@ EXPORT_VERSION = 1 # tables bundle
|
|||||||
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23)
|
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:
|
def _serialize_product(p: Product) -> dict:
|
||||||
quick_options = [
|
quick_options = [
|
||||||
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
|
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
|
||||||
"sort_order": qo.sort_order, "is_favorite": qo.is_favorite,
|
"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
|
for qo in p.quick_options
|
||||||
]
|
]
|
||||||
options = []
|
options = []
|
||||||
@@ -34,10 +40,12 @@ def _serialize_product(p: Product) -> dict:
|
|||||||
sub = json.loads(opt.sub_choices) if opt.sub_choices else []
|
sub = json.loads(opt.sub_choices) if opt.sub_choices else []
|
||||||
options.append({"name": opt.name, "extra_cost": opt.extra_cost,
|
options.append({"name": opt.name, "extra_cost": opt.extra_cost,
|
||||||
"allow_multiple": opt.allow_multiple, "sub_choices": sub,
|
"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 = [
|
ingredients = [
|
||||||
{"name": ing.name, "extra_cost": ing.extra_cost,
|
{"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
|
for ing in p.ingredients
|
||||||
]
|
]
|
||||||
preference_sets = []
|
preference_sets = []
|
||||||
@@ -50,11 +58,13 @@ def _serialize_product(p: Product) -> dict:
|
|||||||
default_index = i
|
default_index = i
|
||||||
sub = json.loads(ch.sub_choices) if ch.sub_choices else []
|
sub = json.loads(ch.sub_choices) if ch.sub_choices else []
|
||||||
choices.append({"name": ch.name, "extra_cost": ch.extra_cost,
|
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({
|
preference_sets.append({
|
||||||
"name": ps.name, "choices": choices,
|
"name": ps.name, "choices": choices,
|
||||||
"default_choice_index": default_index, "shared_subset": shared,
|
"default_choice_index": default_index, "shared_subset": shared,
|
||||||
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
|
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
|
||||||
|
"translations": menu_languages.names_of(ps),
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
"name": p.name, "base_price": p.base_price, "is_available": p.is_available,
|
"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()
|
db.flush()
|
||||||
|
|
||||||
for qo in prod_data.get("quick_options", []):
|
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", []):
|
for opt in prod_data.get("options", []):
|
||||||
sub_json = json.dumps(opt.get("sub_choices", []))
|
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),
|
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,
|
allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json,
|
||||||
is_favorite=opt.get("is_favorite", False),
|
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", []):
|
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", []):
|
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
|
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"],
|
product_id=product.id, name=ps_data["name"],
|
||||||
shared_subset=shared_json,
|
shared_subset=shared_json,
|
||||||
is_favorite=ps_data.get("is_favorite", False),
|
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.add(ps)
|
||||||
db.flush()
|
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", []))
|
sub_json = json.dumps(ch.get("sub_choices", []))
|
||||||
choice = ProductPreferenceChoice(
|
choice = ProductPreferenceChoice(
|
||||||
set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0),
|
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.add(choice)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|||||||
@@ -26,6 +26,35 @@ from core.errors import XeniaError
|
|||||||
router = APIRouter()
|
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():
|
def _broadcast_products_changed():
|
||||||
broadcast_sync("products_changed", {})
|
broadcast_sync("products_changed", {})
|
||||||
|
|
||||||
@@ -43,6 +72,7 @@ def _replace_modifier_groups(db, product, groups):
|
|||||||
modifier_type=g.modifier_type,
|
modifier_type=g.modifier_type,
|
||||||
name=g.name,
|
name=g.name,
|
||||||
sort_order=i,
|
sort_order=i,
|
||||||
|
translations=menu_languages.dump(menu_languages.normalize_names(g.translations)),
|
||||||
)
|
)
|
||||||
db.add(new_g)
|
db.add(new_g)
|
||||||
db.flush()
|
db.flush()
|
||||||
@@ -64,6 +94,7 @@ def _replace_quick_options(db, product, quick_options):
|
|||||||
is_favorite=qo.is_favorite,
|
is_favorite=qo.is_favorite,
|
||||||
favorite_sort_order=qo.favorite_sort_order,
|
favorite_sort_order=qo.favorite_sort_order,
|
||||||
is_compact=qo.is_compact,
|
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.delete(opt)
|
||||||
db.flush()
|
db.flush()
|
||||||
for opt in options:
|
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
|
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(
|
db.add(ProductOption(
|
||||||
product_id=product.id,
|
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,
|
favorite_sort_order=opt.favorite_sort_order,
|
||||||
is_compact=opt.is_compact,
|
is_compact=opt.is_compact,
|
||||||
group_id=resolved_group,
|
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()
|
db.flush()
|
||||||
for ing in ingredients:
|
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
|
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):
|
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.delete(ps)
|
||||||
db.flush()
|
db.flush()
|
||||||
for ps in sets:
|
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
|
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(
|
new_set = ProductPreferenceSet(
|
||||||
product_id=product.id,
|
product_id=product.id,
|
||||||
@@ -113,12 +146,13 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
|||||||
group_id=resolved_group,
|
group_id=resolved_group,
|
||||||
allow_multi_select=ps.allow_multi_select,
|
allow_multi_select=ps.allow_multi_select,
|
||||||
allow_choice_quantity=ps.allow_choice_quantity,
|
allow_choice_quantity=ps.allow_choice_quantity,
|
||||||
|
translations=menu_languages.dump(menu_languages.normalize_names(ps.translations)),
|
||||||
)
|
)
|
||||||
db.add(new_set)
|
db.add(new_set)
|
||||||
db.flush()
|
db.flush()
|
||||||
created_choices = []
|
created_choices = []
|
||||||
for ch in ps.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(
|
choice = ProductPreferenceChoice(
|
||||||
set_id=new_set.id,
|
set_id=new_set.id,
|
||||||
name=ch.name,
|
name=ch.name,
|
||||||
@@ -126,6 +160,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
|||||||
sub_choices=sub_json,
|
sub_choices=sub_json,
|
||||||
disables_subset=ch.disables_subset,
|
disables_subset=ch.disables_subset,
|
||||||
is_compact=ch.is_compact,
|
is_compact=ch.is_compact,
|
||||||
|
translations=menu_languages.dump(menu_languages.normalize_names(ch.translations)),
|
||||||
)
|
)
|
||||||
db.add(choice)
|
db.add(choice)
|
||||||
db.flush()
|
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)
|
@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)):
|
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",
|
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"})
|
"category_id", "primary_category_id", "category_ids", "allergens", "translations"})
|
||||||
if data.get("sort_order") == 0:
|
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,
|
is_favorite=qo.is_favorite,
|
||||||
favorite_sort_order=qo.favorite_sort_order,
|
favorite_sort_order=qo.favorite_sort_order,
|
||||||
is_compact=qo.is_compact,
|
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)
|
created_groups = _replace_modifier_groups(db, product, body.modifier_groups)
|
||||||
group_id_map = [g.id for g in created_groups]
|
group_id_map = [g.id for g in created_groups]
|
||||||
for opt in body.options:
|
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
|
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(
|
db.add(ProductOption(
|
||||||
product_id=product.id,
|
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,
|
favorite_sort_order=opt.favorite_sort_order,
|
||||||
is_compact=opt.is_compact,
|
is_compact=opt.is_compact,
|
||||||
group_id=resolved_group,
|
group_id=resolved_group,
|
||||||
|
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
|
||||||
))
|
))
|
||||||
for ing in body.ingredients:
|
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
|
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)
|
_replace_preference_sets(db, product, body.preference_sets, group_id_map)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(product)
|
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()
|
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||||
if not product:
|
if not product:
|
||||||
raise XeniaError("product.not_found")
|
raise XeniaError("product.not_found")
|
||||||
|
_check_names(body)
|
||||||
scalar_fields = body.model_dump(
|
scalar_fields = body.model_dump(
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
|
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()
|
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||||
if not product:
|
if not product:
|
||||||
raise XeniaError("product.not_found")
|
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.add(g)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(g)
|
db.refresh(g)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Optional, List, Any, Literal, Dict
|
|||||||
|
|
||||||
from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at
|
from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at
|
||||||
from core.allergens import of as _allergens_of
|
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"]
|
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"
|
modifier_type: str # "option" | "ingredient" | "preference"
|
||||||
name: str
|
name: str
|
||||||
sort_order: int = 0
|
sort_order: int = 0
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class ModifierGroupOut(BaseModel):
|
class ModifierGroupOut(BaseModel):
|
||||||
@@ -84,9 +85,15 @@ class ModifierGroupOut(BaseModel):
|
|||||||
modifier_type: str
|
modifier_type: str
|
||||||
name: str
|
name: str
|
||||||
sort_order: int = 0
|
sort_order: int = 0
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
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 ─────────────────────────────────────────────────────────────
|
# ── Quick Options ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -98,6 +105,7 @@ class ProductQuickOptionCreate(BaseModel):
|
|||||||
is_favorite: bool = False
|
is_favorite: bool = False
|
||||||
favorite_sort_order: int = 0
|
favorite_sort_order: int = 0
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class ProductQuickOptionOut(BaseModel):
|
class ProductQuickOptionOut(BaseModel):
|
||||||
@@ -110,9 +118,15 @@ class ProductQuickOptionOut(BaseModel):
|
|||||||
is_favorite: bool = False
|
is_favorite: bool = False
|
||||||
favorite_sort_order: int = 0
|
favorite_sort_order: int = 0
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
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 ──────────────────────────────────────────────────────────────────
|
# ── Options ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -124,6 +138,7 @@ class OptionSubChoice(BaseModel):
|
|||||||
allow_multiple: bool = False
|
allow_multiple: bool = False
|
||||||
# When True renders as half-width card on the PWA
|
# When True renders as half-width card on the PWA
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class ProductOptionBase(BaseModel):
|
class ProductOptionBase(BaseModel):
|
||||||
@@ -137,6 +152,7 @@ class ProductOptionBase(BaseModel):
|
|||||||
# When True renders the option itself as half-width card on the PWA
|
# When True renders the option itself as half-width card on the PWA
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
group_id: Optional[int] = None
|
group_id: Optional[int] = None
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class ProductOptionCreate(ProductOptionBase):
|
class ProductOptionCreate(ProductOptionBase):
|
||||||
@@ -168,6 +184,7 @@ class ProductOptionOut(ProductOptionBase):
|
|||||||
'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0,
|
'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0,
|
||||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||||
'group_id': getattr(data, 'group_id', None),
|
'group_id': getattr(data, 'group_id', None),
|
||||||
|
'translations': _choice_names(data),
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -182,6 +199,7 @@ class ProductIngredientBase(BaseModel):
|
|||||||
# When True renders as half-width card on the PWA
|
# When True renders as half-width card on the PWA
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
group_id: Optional[int] = None
|
group_id: Optional[int] = None
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class ProductIngredientCreate(ProductIngredientBase):
|
class ProductIngredientCreate(ProductIngredientBase):
|
||||||
@@ -194,6 +212,11 @@ class ProductIngredientOut(ProductIngredientBase):
|
|||||||
|
|
||||||
model_config = {"from_attributes": True}
|
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) ────────────────────────────
|
# ── Sub-choices (nested under a preference choice) ────────────────────────────
|
||||||
|
|
||||||
@@ -202,6 +225,7 @@ class SubChoice(BaseModel):
|
|||||||
extra_cost: float = 0.0
|
extra_cost: float = 0.0
|
||||||
is_default: bool = False
|
is_default: bool = False
|
||||||
is_compact: 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) ─────────────
|
# ── Shared subset (set-level, shown for all non-disabling choices) ─────────────
|
||||||
@@ -211,10 +235,12 @@ class SharedSubsetChoice(BaseModel):
|
|||||||
extra_cost: float = 0.0
|
extra_cost: float = 0.0
|
||||||
is_default: bool = False
|
is_default: bool = False
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class SharedSubset(BaseModel):
|
class SharedSubset(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
choices: List[SharedSubsetChoice] = []
|
choices: List[SharedSubsetChoice] = []
|
||||||
|
|
||||||
|
|
||||||
@@ -227,6 +253,7 @@ class PreferenceChoiceCreate(BaseModel):
|
|||||||
disables_subset: bool = False
|
disables_subset: bool = False
|
||||||
# When True renders as half-width card on the PWA
|
# When True renders as half-width card on the PWA
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class PreferenceChoiceOut(BaseModel):
|
class PreferenceChoiceOut(BaseModel):
|
||||||
@@ -237,6 +264,7 @@ class PreferenceChoiceOut(BaseModel):
|
|||||||
sub_choices: List[SubChoice] = []
|
sub_choices: List[SubChoice] = []
|
||||||
disables_subset: bool = False
|
disables_subset: bool = False
|
||||||
is_compact: bool = False
|
is_compact: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
@@ -260,6 +288,7 @@ class PreferenceChoiceOut(BaseModel):
|
|||||||
'sub_choices': parsed,
|
'sub_choices': parsed,
|
||||||
'disables_subset': data.disables_subset or False,
|
'disables_subset': data.disables_subset or False,
|
||||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||||
|
'translations': _choice_names(data),
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -274,6 +303,7 @@ class PreferenceSetCreate(BaseModel):
|
|||||||
group_id: Optional[int] = None
|
group_id: Optional[int] = None
|
||||||
allow_multi_select: bool = False
|
allow_multi_select: bool = False
|
||||||
allow_choice_quantity: bool = False
|
allow_choice_quantity: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
|
|
||||||
class PreferenceSetOut(BaseModel):
|
class PreferenceSetOut(BaseModel):
|
||||||
@@ -288,6 +318,7 @@ class PreferenceSetOut(BaseModel):
|
|||||||
group_id: Optional[int] = None
|
group_id: Optional[int] = None
|
||||||
allow_multi_select: bool = False
|
allow_multi_select: bool = False
|
||||||
allow_choice_quantity: bool = False
|
allow_choice_quantity: bool = False
|
||||||
|
translations: Dict[str, str] = {} # its name per language (0042)
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
@@ -315,6 +346,7 @@ class PreferenceSetOut(BaseModel):
|
|||||||
'group_id': getattr(data, 'group_id', None),
|
'group_id': getattr(data, 'group_id', None),
|
||||||
'allow_multi_select': getattr(data, 'allow_multi_select', False) or False,
|
'allow_multi_select': getattr(data, 'allow_multi_select', False) or False,
|
||||||
'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False,
|
'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False,
|
||||||
|
'translations': _choice_names(data),
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|||||||
@@ -289,7 +289,7 @@ def menu_snapshot(db) -> tuple[dict, list]:
|
|||||||
"digital_image_url": p.digital_image_url,
|
"digital_image_url": p.digital_image_url,
|
||||||
"image_url": p.image_url,
|
"image_url": p.image_url,
|
||||||
"quick_options": [{"id": o.id, "name": o.name, "price": o.price,
|
"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"}
|
"allergens": allergens.of(p), # 6.3: {key: "contains" | "may_contain"}
|
||||||
**menu_languages.product_texts(p), # 6.4: names / descriptions {language: text}
|
**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")
|
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)
|
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)
|
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
|
// 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 { useState } from 'react'
|
||||||
import { Check } from 'lucide-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 { 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 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 { CATEGORY_COLOURS } from './categoryColours'
|
||||||
import { topLevel } from './productsLogic'
|
import { topLevel } from './productsLogic'
|
||||||
|
|
||||||
export default function CategoryDialog({ category, parentName, saving, onSave, onClose }) {
|
export default function CategoryDialog({ category, parentName, saving, onSave, onClose }) {
|
||||||
const { t } = useTranslation('manager')
|
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 [color, setColor] = useState(category.color ?? CATEGORY_COLOURS[0])
|
||||||
const [image, setImage] = useState(category.image ?? null)
|
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 sub = !!category.parent_id
|
||||||
const title = t(`products.category.${category.id ? 'edit' : 'new'}${sub ? 'Sub' : ''}`)
|
const title = t(`products.category.${category.id ? 'edit' : 'new'}${sub ? 'Sub' : ''}`)
|
||||||
return (
|
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={<>
|
footer={<>
|
||||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
<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,
|
<Button disabled={!name} loading={saving} onClick={() => onSave({ name, 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>
|
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">
|
<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>
|
<Field label={t('products.category.name')}><TrInput texts={names} fallback={category.name} onChange={setNames} 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>
|
|
||||||
))}
|
|
||||||
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')} label={t('media.photo')} testid="category-photo" />
|
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')} label={t('media.photo')} testid="category-photo" />
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<span className="text-label font-semibold text-ink">{t('products.category.colour')}</span>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
</EditLang.Provider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import ProductList from './ProductList'
|
|||||||
import Toolbar, { BulkBar, SubChips } from './Toolbar'
|
import Toolbar, { BulkBar, SubChips } from './Toolbar'
|
||||||
import { CategoryBulkDialog, ZonesDialog } from './BulkDialogs'
|
import { CategoryBulkDialog, ZonesDialog } from './BulkDialogs'
|
||||||
import ProductEditor from './editor/ProductEditor'
|
import ProductEditor from './editor/ProductEditor'
|
||||||
|
import ServiceItemDialog from './editor/ServiceItemDialog'
|
||||||
import { emptyProduct } from './editor/formLogic'
|
import { emptyProduct } from './editor/formLogic'
|
||||||
import { NO_FILTERS, SCOPES, applyFilters, bulkCategories, groupProducts, isArchived, isCategoryScope, listedIn, scopeProducts, subsOf } from './productsLogic'
|
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 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')
|
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')
|
: 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 = () => {
|
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)
|
const preset = (subs.length && sub) || (isCategoryScope(scope) ? scope : null)
|
||||||
setEditing(emptyProduct(preset ? { category_ids: [preset], primary_category_id: preset } : {}))
|
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={<>
|
<Pane sunken data-testid="products-panel" bodyClassName="p-card" header={<>
|
||||||
<Toolbar title={title} shown={allIds.length} total={products.filter(p => !isArchived(p)).length}
|
<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 && (
|
{subs.length > 0 && (
|
||||||
<SubChips parent={scopeCat} subs={subs} value={sub} onChange={setSub}
|
<SubChips parent={scopeCat} subs={subs} value={sub} onChange={setSub}
|
||||||
counts={key => (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} />
|
counts={key => (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} />
|
||||||
@@ -136,7 +138,11 @@ export default function ProductsPage() {
|
|||||||
</Pane>
|
</Pane>
|
||||||
</div>
|
</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}
|
<ProductEditor key={editing.id ?? 'new'} product={editing} categories={categories} prepZones={zones} saving={saveProduct.isPending}
|
||||||
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)}
|
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)}
|
||||||
onCopy={form => setEditing({ _form: { ...form, name: t('products.copyOf', { name: form.name }) } })} />
|
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 { Dot } from './CategoryTree'
|
||||||
import { NO_FILTERS } from './productsLogic'
|
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 { t } = useTranslation('manager')
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const any = JSON.stringify(filters) !== JSON.stringify(NO_FILTERS)
|
const any = JSON.stringify(filters) !== JSON.stringify(NO_FILTERS)
|
||||||
@@ -27,6 +27,7 @@ export default function Toolbar({ title, shown, total, search, onSearch, filters
|
|||||||
</Button>
|
</Button>
|
||||||
<Segmented aria-label={t('products.view')} value={view} onChange={onView}
|
<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}` }))} />
|
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>
|
<Button icon={<Plus size={16} />} onClick={onNew} data-testid="product-new">{t('products.new')}</Button>
|
||||||
</Bar>
|
</Bar>
|
||||||
{open && (
|
{open && (
|
||||||
|
|||||||
@@ -5,52 +5,61 @@
|
|||||||
// Extras ticked add-ons, each with optional sub-choices (syrup → caramel / vanilla)
|
// 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
|
// 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
|
// 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 { useRef, useState } from 'react'
|
||||||
import { Heart, Plus, Trash2 } from 'lucide-react'
|
import { Heart, Plus, Trash2 } from 'lucide-react'
|
||||||
import { translatedLanguages, useAccess } from '@xenia/access'
|
|
||||||
import { useTranslation } from '@xenia/i18n'
|
import { useTranslation } from '@xenia/i18n'
|
||||||
import { Button, EmptyState, IconButton, Input, Select, cx } from '@xenia/ui'
|
import { Button, Dropdown, EmptyState, FilterChip, IconButton, Switch, Tabs } from '@xenia/ui'
|
||||||
import { favourites, moveChoice, moveFavourite, moveItem, removeChoice, removeGroup, setSub, toggleFavourite } from './formLogic'
|
import { TrInput } from './LanguageFields'
|
||||||
import { Check, DefaultToggle, FavouriteToggle, GroupHeader, MoveButtons, PriceInput, SubChoices } from './parts'
|
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 }) {
|
export default function ChoicesPanel({ form, setForm }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
|
const { slot, venue } = useEditLang()
|
||||||
const [tab, setTab] = useState('favourites')
|
const [tab, setTab] = useState('favourites')
|
||||||
const [folded, setFolded] = useState({})
|
const [folded, setFolded] = useState({})
|
||||||
const nextKey = useRef(-1)
|
const nextKey = useRef(-1)
|
||||||
const favCount = favourites(form).length
|
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 groups = { form, setForm, folded, fold: key => setFolded(s => ({ ...s, [key]: !s[key] })), addGroup }
|
||||||
const addPref = () => {
|
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)
|
setTab(form.preference_sets.length)
|
||||||
}
|
}
|
||||||
const tabs = [
|
const tabs = [
|
||||||
{ key: 'favourites', label: t('products.editor.tab.favourites'), count: favCount },
|
{ id: 'favourites', label: t('products.editor.tab.favourites'), badge: favCount || null,
|
||||||
{ key: 'quick', label: t('products.editor.tab.quick'), count: form.quick_options.length },
|
icon: <Heart size={14} className={favCount ? 'text-danger' : 'text-ink-3'} fill={favCount ? 'currentColor' : 'none'} aria-hidden="true" /> },
|
||||||
{ key: 'ingredients', label: t('products.editor.tab.ingredients'), count: form.ingredients.length },
|
{ id: 'quick', testId: 'choices-tab-quick', label: t('products.editor.tab.quick'), badge: form.quick_options.length || null },
|
||||||
{ key: 'options', label: t('products.editor.tab.options'), count: form.options.length },
|
{ id: 'ingredients', testId: 'choices-tab-ingredients', label: t('products.editor.tab.ingredients'), badge: form.ingredients.length || null },
|
||||||
...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || t('products.editor.prefN', { n: i + 1 }), count: ps.choices.length })),
|
{ 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 (
|
return (
|
||||||
<div className="flex flex-col min-h-0 h-full">
|
<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 className="px-card bg-surface shrink-0" value={tab} onChange={setTab} tabs={tabs}
|
||||||
{tabs.map(tb => (
|
end={<Button size="sm" variant="ghost" tone="accent" icon={<Plus size={14} />} onClick={addPref} data-testid="add-pref">{t('products.editor.addPref')}</Button>} />
|
||||||
<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>
|
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-5">
|
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-5">
|
||||||
{tab === 'favourites' && <Favourites form={form} setForm={setForm} />}
|
{tab === 'favourites' && <Favourites form={form} setForm={setForm} />}
|
||||||
{tab === 'quick' && <QuickList form={form} setForm={setForm} />}
|
{tab === 'quick' && <QuickList form={form} setForm={setForm} />}
|
||||||
@@ -75,20 +84,20 @@ function Intro({ text, children }) {
|
|||||||
|
|
||||||
function Favourites({ form, setForm }) {
|
function Favourites({ form, setForm }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
|
const { slot, venue } = useEditLang()
|
||||||
const list = favourites(form)
|
const list = favourites(form)
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<p className="text-label text-ink-2">{t('products.editor.favouritesHint')}</p>
|
<p className="text-label text-ink-2">{t('products.editor.favouritesHint')}</p>
|
||||||
{list.length === 0 && <EmptyState compact title={t('products.editor.noFavourites')} />}
|
{list.length === 0 && <EmptyState compact title={t('products.editor.noFavourites')} />}
|
||||||
{list.map((fav, i) => (
|
{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))} />
|
<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="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 className="text-caption text-ink-3">{t(`products.editor.kind.${fav.kind}`)}</span>
|
||||||
</span>
|
</span>
|
||||||
<Button size="sm" variant="ghost" onClick={() => setForm(f => toggleFavourite(f, fav.kind, fav.idx))}>{t('products.editor.remove')}</Button>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -97,29 +106,23 @@ function Favourites({ form, setForm }) {
|
|||||||
|
|
||||||
function QuickList({ form, setForm }) {
|
function QuickList({ form, setForm }) {
|
||||||
const { t } = useTranslation('manager')
|
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 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 (
|
return (
|
||||||
<div>
|
<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')} />}
|
{form.quick_options.length === 0 && <EmptyState compact title={t('products.editor.noQuick')} />}
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
{form.quick_options.map((q, i) => (
|
{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}
|
<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) }))} />
|
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))} />
|
<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')} />
|
<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" />
|
||||||
{others.map(l => (
|
<PriceInput size="sm" className="w-32" value={q.price} onChange={v => set(i, 'price', v)} label={t('products.editor.extraCost')} />
|
||||||
<Input key={l} className="flex-1 min-w-32" value={q.tr?.[l] ?? ''} onChange={e => set(i, 'tr', { ...(q.tr ?? {}), [l]: e.target.value })}
|
<Toggle on={q.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Toggle>
|
||||||
placeholder={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} aria-label={t('products.editor.inLanguageShort', { language: t(`products.editor.lang.${l}`) })} />
|
<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) }))} />
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</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). */
|
/** Ingredients or extras, with their groups (folders). */
|
||||||
function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
|
function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
|
||||||
const { t } = useTranslation('manager')
|
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 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 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'
|
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: '', 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: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, 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) => (
|
const row = (x, i) => (
|
||||||
<div key={i} className={cx('rounded-card border overflow-hidden', x.is_favorite ? 'border-danger' : 'border-line')}>
|
<div key={i} className="rounded-card border border-line bg-surface overflow-hidden" data-testid={`${kind}-row`}>
|
||||||
<div className="flex flex-wrap items-center gap-2 p-2.5">
|
<div className={ROW}>
|
||||||
<MoveButtons first={i === 0} last={i === items.length - 1}
|
<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) }))} />
|
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))} />
|
<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`)} />
|
<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 className="w-32" value={x.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
<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' && <Check checked={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
|
{kind === 'option' && <Toggle on={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Toggle>}
|
||||||
{kind === 'option' && <Check checked={x.multi_select} onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Check>}
|
{kind === 'option' && <Toggle on={x.multi_select} tone="success" onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Toggle>}
|
||||||
<Check checked={x.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
<Toggle on={x.is_compact} tone="accent" onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Toggle>
|
||||||
{myGroups.length > 0 && (
|
<GroupPicker value={x.group_id} groups={myGroups} onChange={v => set(i, 'group_id', v)} />
|
||||||
<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')}>
|
{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>}
|
||||||
<option value="">{t('products.editor.noGroup')}</option>
|
<RemoveButton onClick={() => setForm(f => ({ ...f, [list]: f[list].filter((_, j) => j !== i) }))} />
|
||||||
{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>
|
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Intro text={t(`products.editor.${kind}Hint`)}>
|
<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="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}>{t(`products.editor.add.${kind}`)}</Button>
|
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add} data-testid={`add-${kind}`}>{t(`products.editor.add.${kind}`)}</Button>
|
||||||
</Intro>
|
</Intro>
|
||||||
{items.length === 0 && <EmptyState compact title={t(`products.editor.none.${kind}`)} />}
|
{items.length === 0 && <EmptyState compact title={t(`products.editor.none.${kind}`)} />}
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
@@ -171,8 +182,7 @@ function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
|
|||||||
{myGroups.map(g => (
|
{myGroups.map(g => (
|
||||||
<div key={g.key}>
|
<div key={g.key}>
|
||||||
<GroupHeader group={g} folded={folded[g.key]} onFold={() => fold(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)) }))}
|
onRename={tr => renameGroup(setForm, g.key, tr)} onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
||||||
onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
|
||||||
{!folded[g.key] && (
|
{!folded[g.key] && (
|
||||||
<div className="ml-4 border-l-2 border-accent-soft pl-3 mt-1 grid gap-2">
|
<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>}
|
{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 { t } = useTranslation('manager')
|
||||||
const ps = form.preference_sets[si]
|
const ps = form.preference_sets[si]
|
||||||
const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference')
|
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 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 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 shared = ps.shared_subset
|
||||||
|
const setShared = patch => set('shared_subset', { ...shared, ...patch })
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-4" data-testid="pref-set">
|
<div className="grid gap-4" data-testid="pref-set">
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<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))} />
|
<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>
|
onClick={() => { setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, i) => i !== si) })); onRemoved() }}>{t('products.editor.removePref')}</Button>
|
||||||
</div>
|
</div>
|
||||||
{prefGroups.length > 0 && (
|
{prefGroups.length > 0 && (
|
||||||
<div className="rounded-card bg-accent-soft p-3">
|
<div className="rounded-card border border-line bg-surface p-3 grid gap-1">
|
||||||
<p className="text-caption font-semibold text-accent-ink">{t('products.editor.prefGroups')}</p>
|
<p className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('products.editor.prefGroups')}</p>
|
||||||
{prefGroups.map(g => (
|
{prefGroups.map(g => (
|
||||||
<GroupHeader key={g.key} group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
|
<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)) }))}
|
onRename={tr => renameGroup(setForm, g.key, tr)} onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
||||||
onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex flex-wrap gap-5">
|
<div className="flex flex-wrap gap-x-8 gap-y-2">
|
||||||
<Check checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)}>{t('products.editor.multiChoice')}</Check>
|
<Switch checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)} label={t('products.editor.multiChoice')} />
|
||||||
<Check checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)}>{t('products.editor.choiceQuantity')}</Check>
|
<Switch checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)} label={t('products.editor.choiceQuantity')} />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-caption text-ink-3">{t('products.editor.prefLegend')}</p>
|
<p className="text-caption text-ink-3">{t('products.editor.prefLegend')}</p>
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
{ps.choices.map((c, ci) => (
|
{ps.choices.map((c, ci) => (
|
||||||
<div key={ci} className="rounded-card border border-line overflow-hidden" data-testid="pref-choice">
|
<div key={ci} className="rounded-card border border-line bg-surface overflow-hidden" data-testid="pref-choice">
|
||||||
<div className="flex flex-wrap items-center gap-2 p-2.5">
|
<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))} />
|
<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)} />
|
<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')} />
|
<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 className="w-32" value={c.extra_cost} allowNegative onChange={v => setChoice(ci, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
<PriceInput size="sm" 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>
|
<Toggle on={c.is_compact} tone="accent" onChange={v => setChoice(ci, 'is_compact', v)}>{t('products.editor.compact')}</Toggle>
|
||||||
{shared && <Check checked={c.disables_subset} onChange={v => setChoice(ci, 'disables_subset', v)}>{t('products.editor.hidesShared')}</Check>}
|
{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" icon={<Plus size={14} />} onClick={() => setChoice(ci, 'sub_choices', [...c.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>
|
<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>
|
||||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => put(x => removeChoice(x, ci))}><Trash2 size={14} /></IconButton>
|
<RemoveButton onClick={() => put(x => removeChoice(x, ci))} />
|
||||||
</div>
|
</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>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} className="justify-self-start" data-testid="add-choice"
|
<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">
|
<section className="border-t border-line pt-4 grid gap-3">
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<span className="grid">
|
<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 className="text-caption text-ink-3">{t('products.editor.sharedHint')}</span>
|
||||||
</span>
|
</span>
|
||||||
{shared
|
{shared
|
||||||
? <Button size="sm" variant="danger" onClick={() => set('shared_subset', null)}>{t('products.editor.remove')}</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: '', choices: [] })}>{t('products.editor.addShared')}</Button>}
|
: <Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('shared_subset', { name: '', tr: {}, choices: [] })}>{t('products.editor.addShared')}</Button>}
|
||||||
</div>
|
</div>
|
||||||
{shared && (
|
{shared && (
|
||||||
<div className="rounded-card border border-line bg-surface-2 p-3 grid gap-2">
|
<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) => (
|
{shared.choices.map((s, i) => (
|
||||||
<div key={i} className="flex items-center gap-2">
|
<div key={i} className="flex items-center gap-2">
|
||||||
<MoveButtons first={i === 0} last={i === shared.choices.length - 1}
|
<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) })} />
|
onUp={() => setShared({ choices: moveItem(shared.choices, i, -1) })} onDown={() => setShared({ 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) })} />
|
<DefaultToggle on={s.is_default} onClick={() => setShared({ 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)) })} />
|
<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 className="w-32" value={s.extra_cost} allowNegative label={t('products.editor.extraCost')}
|
<PriceInput size="sm" 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)) })} />
|
onChange={v => setShared({ choices: shared.choices.map((x, j) => (j === i ? { ...x, extra_cost: v } : x)) })} />
|
||||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')}
|
<RemoveButton onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)} />
|
||||||
onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)}><Trash2 size={14} /></IconButton>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
|
<Button size="sm" variant="ghost" tone="accent" 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>
|
onClick={() => setShared({ choices: [...shared.choices, { name: '', tr: {}, extra_cost: 0, is_default: false }] })}>{t('products.editor.addChoice')}</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import { X } from 'lucide-react'
|
import { X } from 'lucide-react'
|
||||||
import { ALLERGENS, nextAllergenLevel, setAllergen } from '@xenia/access'
|
import { ALLERGENS, nextAllergenLevel, setAllergen } from '@xenia/access'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
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 { categoryTree, treeLabel } from '../productsLogic'
|
||||||
import { addCategory, removeCategory } from './formLogic'
|
import { addCategory, removeCategory } from './formLogic'
|
||||||
|
|
||||||
@@ -39,12 +39,10 @@ export function CategoriesField({ form, setForm, categories }) {
|
|||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</ul>
|
</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">
|
{/* the shared dropdown (2026-11-21): searchable, a sub-category under its parent, the category's colour */}
|
||||||
<option value="">{t('products.editor.addCategory')}</option>
|
<Dropdown value={null} onChange={v => v != null && setForm(f => addCategory(f, Number(v)))} aria-label={t('products.editor.addCategory')}
|
||||||
{tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => (
|
placeholder={t('products.editor.addCategory')} searchable data-testid="add-category"
|
||||||
<option key={cat.id} value={cat.id}>{treeLabel(cat, depth)}</option>
|
options={tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => ({ value: cat.id, label: treeLabel(cat, depth), dot: cat.color || undefined }))} />
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,70 +4,54 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { BadgeEuro, Plus, Trash2, X } from 'lucide-react'
|
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 { 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 ProductChannelPricesDialog from '../../pricing/ProductChannelPricesDialog'
|
||||||
import MediaField from '../../media/MediaField'
|
import MediaField from '../../media/MediaField'
|
||||||
import { costOf } from '../productsLogic'
|
import { costOf } from '../productsLogic'
|
||||||
import { AllergensField, CategoriesField } from './Fields'
|
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'
|
import { Check, PriceInput } from './parts'
|
||||||
|
|
||||||
export function InfoTab({ form, set, setForm, categories, prepZones }) {
|
export function InfoTab({ form, set, setForm, categories, prepZones }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
const { venue } = useAccess()
|
const { venue } = useEditLang()
|
||||||
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] ?? ''
|
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-4">
|
<div className="grid gap-4">
|
||||||
<Switch checked={service} onChange={v => set('is_service_item', v)} label={t('products.editor.serviceItem')}
|
{/* one name and one description, in the language picked at the top (2026-11-21) */}
|
||||||
description={service ? (Number(form.base_price) > 0 ? t('products.editor.servicePaid') : t('products.editor.serviceFree')) : t('products.editor.serviceHint')} />
|
<Field label={t('products.editor.name')} required>
|
||||||
{!service && others.length > 0 && (
|
<TrInput texts={form.names} fallback={form.name} onChange={v => set('names', v)} autoFocus data-testid="product-name"
|
||||||
// one name and one description; the switch picks the language being typed (2026-11-20)
|
placeholder={t('products.editor.namePlaceholder')} />
|
||||||
<div className="flex items-center gap-2" data-testid="product-lang">
|
</Field>
|
||||||
<Segmented size="sm" value={lang} onChange={setLang} aria-label={t('products.editor.langOf')}
|
<Field label={t('products.editor.description')} hint={t('products.editor.descriptionHint')}>
|
||||||
options={[main, ...others].map(l => ({ value: l, testId: `product-lang-${l}`,
|
<TrInput multiline rows={3} texts={form.descriptions} fallback={form.description} onChange={v => set('descriptions', v)} data-testid="product-description" />
|
||||||
label: l === main ? t('products.editor.mainLang', { language: t(`products.editor.lang.${l}`) }) : t(`products.editor.lang.${l}`) }))} />
|
</Field>
|
||||||
<InfoTip>{t('products.editor.translationTip')}</InfoTip>
|
<Tags tags={form.tags} onChange={v => set('tags', v)} />
|
||||||
</div>
|
<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}>
|
||||||
{tr ? (
|
<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}`) }))} />
|
||||||
<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')} />
|
|
||||||
</Field>
|
</Field>
|
||||||
{!service && (
|
<Field label={t('products.editor.price')} required>
|
||||||
<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}>
|
|
||||||
<PriceInput className="w-full" value={form.base_price} onChange={v => set('base_price', v)} label={t('products.editor.price')} data-testid="product-price" />
|
<PriceInput className="w-full" value={form.base_price} onChange={v => set('base_price', v)} label={t('products.editor.price')} data-testid="product-price" />
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
<CategoriesField form={form} setForm={setForm} categories={categories} />
|
<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">
|
<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>
|
<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
|
{prepZones.length === 0
|
||||||
@@ -79,13 +63,6 @@ export function InfoTab({ form, set, setForm, categories, prepZones }) {
|
|||||||
</Check>
|
</Check>
|
||||||
))}
|
))}
|
||||||
</div>
|
</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
|
// 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
|
// (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.
|
// (ChoicesPanel). Service items (cutlery, a cover charge) have their own small dialog
|
||||||
// "Copy" opens a new product filled from this one.
|
// (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 { useState } from 'react'
|
||||||
import { Copy } from 'lucide-react'
|
import { Copy } from 'lucide-react'
|
||||||
|
import { DEFAULT_LANGUAGE } from '@xenia/access'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
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 client from '../../../api/client'
|
||||||
import { useLiveQuery } from '../../../live/useLiveQuery'
|
import { useLiveQuery } from '../../../live/useLiveQuery'
|
||||||
import ChoicesPanel from './ChoicesPanel'
|
import ChoicesPanel from './ChoicesPanel'
|
||||||
import { CostTab, FiscalTab, InfoTab, SoldAtTab } from './InfoTabs'
|
import { CostTab, FiscalTab, InfoTab, SoldAtTab } from './InfoTabs'
|
||||||
|
import { LanguagePicker } from './LanguageFields'
|
||||||
|
import { EditLang, editLangOf, useVenueLanguage } from './editLang'
|
||||||
import { buildBody, buildForm, canSave } from './formLogic'
|
import { buildBody, buildForm, canSave } from './formLogic'
|
||||||
|
|
||||||
export default function ProductEditor({ product, categories, prepZones, saving, onSave, onCopy, onClose }) {
|
export default function ProductEditor({ product, categories, prepZones, saving, onSave, onCopy, onClose }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
|
const venue = useVenueLanguage()
|
||||||
const [form, setForm] = useState(() => product._form ?? buildForm(product)) // a copy brings its form
|
const [form, setForm] = useState(() => product._form ?? buildForm(product)) // a copy brings its form
|
||||||
const [left, setLeft] = useState('info')
|
const [left, setLeft] = useState('info')
|
||||||
|
const [lang, setLang] = useState(DEFAULT_LANGUAGE)
|
||||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
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 { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
|
||||||
const fiscalOn = settings?.['fiscal.enabled']?.value === 'true'
|
const fiscalOn = settings?.['fiscal.enabled']?.value === 'true'
|
||||||
let vatGroups = []
|
let vatGroups = []
|
||||||
try { vatGroups = JSON.parse(settings?.['fiscal.vat_groups']?.value || '[]') } catch { vatGroups = [] }
|
try { vatGroups = JSON.parse(settings?.['fiscal.vat_groups']?.value || '[]') } catch { vatGroups = [] }
|
||||||
const service = form.is_service_item
|
|
||||||
const isNew = !product.id
|
const isNew = !product.id
|
||||||
const leftTabs = ['info', ...(service ? [] : ['soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])])]
|
const leftTabs = ['info', 'soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])]
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open size="wide" onClose={onClose} className="h-[94vh]" bodyClass="!p-0 flex"
|
<EditLang.Provider value={editLangOf(lang, venue)}>
|
||||||
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
|
<Dialog open size="wide" onClose={onClose} className="h-[94vh]" bodyClass="!p-0 flex"
|
||||||
footer={<div className="flex items-center gap-2 w-full">
|
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
|
||||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
headerEnd={<LanguagePicker value={lang} onChange={setLang} />}
|
||||||
<span className="flex-1" />
|
footer={<div className="flex items-center gap-2 w-full">
|
||||||
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
|
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||||
<Button disabled={!canSave(form)} loading={saving} onClick={() => onSave(buildBody(form))} data-testid="product-save">
|
<span className="flex-1" />
|
||||||
{isNew ? t('products.editor.create') : t('products.save')}
|
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
|
||||||
</Button>
|
<Button disabled={!canSave(form, venue)} loading={saving} onClick={() => onSave(buildBody(form, venue))} data-testid="product-save">
|
||||||
</div>}>
|
{isNew ? t('products.editor.create') : t('products.save')}
|
||||||
<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">
|
</Button>
|
||||||
<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]')}>
|
</div>}>
|
||||||
<Tabs fill className="px-card bg-surface shrink-0" value={left} onChange={setLeft}
|
<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">
|
||||||
tabs={leftTabs.map(k => ({ id: k, label: t(`products.editor.left.${k}`), testId: `editor-tab-${k}` }))} />
|
<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]">
|
||||||
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
|
<Tabs fill className="px-card bg-surface shrink-0" value={left} onChange={setLeft}
|
||||||
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
|
tabs={leftTabs.map(k => ({ id: k, label: t(`products.editor.left.${k}`), testId: `editor-tab-${k}` }))} />
|
||||||
{left === 'soldAt' && <SoldAtTab form={form} set={set} product={product} />}
|
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
|
||||||
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
|
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
|
||||||
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
|
{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>
|
||||||
|
<div className="flex flex-1 min-w-0 flex-col min-h-[30rem] md:min-h-0"><ChoicesPanel form={form} setForm={setForm} /></div>
|
||||||
</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>}
|
</Dialog>
|
||||||
</div>
|
</EditLang.Provider>
|
||||||
</Dialog>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
// 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
|
// 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).
|
// (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 { 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 UNITS = ['piece', 'portion', 'kg', 'liter', 'gram', 'ml']
|
||||||
export const WEIGHED = new Set(['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' }
|
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 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 = {}) {
|
export function emptyProduct(preset = {}) {
|
||||||
return { name: '', base_price: '', category_ids: [], primary_category_id: null, is_available: true, lifecycle_status: 'active', ...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 {
|
return {
|
||||||
name: p.name ?? '',
|
name: p.name ?? '',
|
||||||
description: p.description ?? '',
|
description: p.description ?? '',
|
||||||
|
names: field(p.translations, 'name'),
|
||||||
|
descriptions: field(p.translations, 'description'),
|
||||||
category_ids: [...(p.category_ids ?? (p.category_id ? [p.category_id] : []))],
|
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),
|
primary_category_id: p.primary_category_id ?? p.category_id ?? (p.category_ids?.[0] ?? null),
|
||||||
base_price: p.base_price ?? '',
|
base_price: p.base_price ?? '',
|
||||||
@@ -26,31 +43,30 @@ export function buildForm(p) {
|
|||||||
lifecycle_status: p.lifecycle_status ?? 'active',
|
lifecycle_status: p.lifecycle_status ?? 'active',
|
||||||
prep_zone_ids: [...(p.prep_zone_ids ?? [])],
|
prep_zone_ids: [...(p.prep_zone_ids ?? [])],
|
||||||
allergens: { ...(p.allergens ?? {}) },
|
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 => ({
|
quick_options: (p.quick_options ?? []).map(q => ({
|
||||||
name: q.name, price: q.price ?? 0, allow_multiple: !!q.allow_multiple, is_favorite: !!q.is_favorite,
|
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,
|
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 => ({
|
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_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,
|
is_favorite: !!o.is_favorite, favorite_sort_order: o.favorite_sort_order ?? 0, group_id: o.group_id ?? null,
|
||||||
})),
|
})),
|
||||||
ingredients: (p.ingredients ?? []).map(i => ({
|
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,
|
is_compact: !!i.is_compact, group_id: i.group_id ?? null,
|
||||||
})),
|
})),
|
||||||
preference_sets: (p.preference_sets ?? []).map(ps => ({
|
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,
|
default_choice_index: ps.choices ? ps.choices.findIndex(c => c.id === ps.default_choice_id) : -1,
|
||||||
choices: (ps.choices ?? []).map(c => ({
|
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),
|
sub_choices: (c.sub_choices ?? []).map(sub),
|
||||||
})),
|
})),
|
||||||
group_id: ps.group_id ?? null,
|
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,
|
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,
|
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_name: p.fiscal_name ?? '',
|
||||||
fiscal_vat_group_id: p.fiscal_vat_group_id ?? null,
|
fiscal_vat_group_id: p.fiscal_vat_group_id ?? null,
|
||||||
// choice groups (folders) keyed by a form id; the API takes their index
|
// 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 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 {
|
return {
|
||||||
name: f.name.trim(),
|
name: shownText(f.names, venue, f.name),
|
||||||
description: f.description.trim() || null,
|
description: shownText(f.descriptions, venue, f.description) || null,
|
||||||
category_ids: f.category_ids,
|
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),
|
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),
|
base_price: num(f.base_price),
|
||||||
@@ -89,28 +107,28 @@ export function buildBody(f) {
|
|||||||
allergens: f.allergens,
|
allergens: f.allergens,
|
||||||
translations: translationsBody(f),
|
translations: translationsBody(f),
|
||||||
quick_options: f.quick_options.map((q, i) => ({
|
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,
|
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 => ({
|
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_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),
|
is_favorite: o.is_favorite, favorite_sort_order: o.favorite_sort_order, group_id: groupIndex(o.group_id),
|
||||||
})),
|
})),
|
||||||
ingredients: f.ingredients.map(i => ({
|
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),
|
is_compact: i.is_compact, group_id: groupIndex(i.group_id),
|
||||||
})),
|
})),
|
||||||
preference_sets: f.preference_sets.map(ps => ({
|
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,
|
default_choice_index: ps.default_choice_index >= 0 ? ps.default_choice_index : null,
|
||||||
shared_subset: ps.shared_subset?.choices?.length
|
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,
|
: null,
|
||||||
choices: ps.choices.map(c => ({
|
choices: ps.choices.map(c => ({
|
||||||
name: c.name, extra_cost: num(c.extra_cost), disables_subset: c.disables_subset, is_compact: c.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 => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, is_compact: !!s.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),
|
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,
|
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) {
|
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 = {}
|
const out = {}
|
||||||
for (const l of langs) {
|
for (const l of MENU_LANGUAGES) {
|
||||||
const t = f.translations?.[l] ?? {}
|
const v = { ...(names[l] ? { name: names[l] } : {}), ...(descs[l] ? { description: descs[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 } : {}) }
|
|
||||||
if (Object.keys(v).length) out[l] = v
|
if (Object.keys(v).length) out[l] = v
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A translated field of the product. */
|
/** Can it be saved: a name in some language, and a price unless it's a service item. */
|
||||||
export const setTranslation = (f, lang, field, value) => ({ ...f, translations: { ...f.translations, [lang]: { ...(f.translations?.[lang] ?? {}), [field]: value } } })
|
export const canSave = (f, venue = 'el') => !!shownText(f.names, venue, f.name) && (f.is_service_item || (f.base_price !== '' && f.base_price != null))
|
||||||
|
|
||||||
/** 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))
|
|
||||||
|
|
||||||
// ── categories ──────────────────────────────────────────────────────────────
|
// ── 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 { useState } from 'react'
|
||||||
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
|
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||||
import { useTranslation } from '@xenia/i18n'
|
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). */
|
/** 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 { t } = useTranslation('manager')
|
||||||
const n = Number(String(value ?? '').replace(',', '.')) || 0
|
const n = Number(String(value ?? '').replace(',', '.')) || 0
|
||||||
const step = d => {
|
const step = d => {
|
||||||
@@ -13,7 +18,7 @@ export function PriceInput({ value, onChange, allowNegative = false, className,
|
|||||||
onChange(allowNegative ? next : Math.max(0, next))
|
onChange(allowNegative ? next : Math.max(0, next))
|
||||||
}
|
}
|
||||||
return (
|
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>
|
<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}
|
<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} />
|
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')
|
const { t } = useTranslation('manager')
|
||||||
return (
|
return (
|
||||||
<span className="flex flex-col shrink-0">
|
<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="!min-h-0 !h-[18px]" 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.moveDown')} disabled={last} onClick={onDown}><ChevronDown size={14} /></IconButton>
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -48,8 +53,7 @@ export function DefaultToggle({ on, onClick }) {
|
|||||||
export function FavouriteToggle({ on, onClick }) {
|
export function FavouriteToggle({ on, onClick }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
return (
|
return (
|
||||||
<IconButton size="sm" variant="ghost" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={on} onClick={onClick}
|
<IconButton size="sm" tone="danger" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={!!on} onClick={onClick} data-testid="favourite">
|
||||||
className={on ? 'text-danger' : 'text-ink-3'}>
|
|
||||||
<Heart size={16} fill={on ? 'currentColor' : 'none'} />
|
<Heart size={16} fill={on ? 'currentColor' : 'none'} />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
)
|
)
|
||||||
@@ -68,46 +72,49 @@ export function Check({ checked, onChange, children }) {
|
|||||||
/** The sub-choices under a choice ("Syrup" → Caramel, Vanilla). */
|
/** The sub-choices under a choice ("Syrup" → Caramel, Vanilla). */
|
||||||
export function SubChoices({ subs, parent, onChange, withMultiple = false }) {
|
export function SubChoices({ subs, parent, onChange, withMultiple = false }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
|
const { slot, venue } = useEditLang()
|
||||||
if (!subs?.length) return null
|
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 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) }
|
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 (
|
return (
|
||||||
<div className="border-t border-line bg-surface-2 px-3 py-2 grid gap-2">
|
<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) => (
|
{subs.map((s, i) => (
|
||||||
<div key={i} className="flex flex-wrap items-center gap-2 pl-4">
|
<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)} />
|
<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)} />
|
<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')} />
|
<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 className="w-28" value={s.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
<PriceInput size="sm" 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>}
|
{withMultiple && <FilterChip size="sm" tone="info" pressed={!!s.allow_multiple} onClick={() => set(i, 'allow_multiple', !s.allow_multiple)}>{t('products.editor.multiple')}</FilterChip>}
|
||||||
<Check checked={s.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
<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" variant="ghost" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
|
<IconButton size="sm" tone="danger" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={16} /></IconButton>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start ml-4"
|
<Button size="sm" variant="ghost" tone="accent" 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>
|
onClick={() => onChange([...subs, { name: '', tr: {}, extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }])}>{t('products.editor.addSub')}</Button>
|
||||||
</div>
|
</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 }) {
|
export function GroupHeader({ group, folded, onFold, onRename, onRemove }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
|
const { slot, venue } = useEditLang()
|
||||||
const [editing, setEditing] = useState(false)
|
const [editing, setEditing] = useState(false)
|
||||||
const [name, setName] = useState(group.name)
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1.5 mt-2">
|
<div className="flex items-center gap-1.5 mt-2">
|
||||||
<button type="button" onClick={onFold} aria-expanded={!folded}
|
{editing ? (
|
||||||
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">
|
<TrInput size="sm" className="flex-1" autoFocus texts={group.tr} fallback={group.name} onChange={onRename}
|
||||||
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
|
onBlur={() => setEditing(false)} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} aria-label={t('products.editor.renameGroup')} />
|
||||||
{editing
|
) : (
|
||||||
? <input className="flex-1 min-w-0 bg-surface text-ink rounded px-1" autoFocus value={name} onChange={e => setName(e.target.value)}
|
<button type="button" onClick={onFold} aria-expanded={!folded}
|
||||||
onClick={e => e.stopPropagation()} onBlur={() => { onRename(name); setEditing(false) }} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
|
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">
|
||||||
: <span className="flex-1 truncate">{group.name || t('products.editor.unnamedGroup')}</span>}
|
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
|
||||||
</button>
|
<span className="flex-1 truncate">{labelIn(group, slot, venue) || t('products.editor.unnamedGroup')}</span>
|
||||||
<IconButton size="sm" variant="ghost" label={t('products.editor.renameGroup')} onClick={() => { setName(group.name); setEditing(true) }}><Pencil size={14} /></IconButton>
|
</button>
|
||||||
<IconButton size="sm" variant="ghost" label={t('products.editor.removeGroup')} onClick={onRemove}><Trash2 size={14} /></IconButton>
|
)}
|
||||||
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict'
|
|||||||
import {
|
import {
|
||||||
SCOPES, applyFilters, bulkCategories, categoryTree, costOf, countIn, groupProducts, moveId, reorderBody, scopeProducts, stepBody, treeLabel,
|
SCOPES, applyFilters, bulkCategories, categoryTree, costOf, countIn, groupProducts, moveId, reorderBody, scopeProducts, stepBody, treeLabel,
|
||||||
} from '../src/pages/products/productsLogic.js'
|
} 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 = [
|
const cats = [
|
||||||
{ id: 1, name: 'Coffees', sort_order: 0 },
|
{ 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)
|
assert.equal(buildBody(removeGroup(f, 7)).ingredients[0].group_id, null)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('the editor keeps the menu in other languages (6.4)', () => {
|
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: 'Πίτα' }, { name: 'Σάλτσα' }],
|
const f = buildForm({ name: 'Σουβλάκι', base_price: 3, quick_options: [{ name: 'Πίτα', translations: { el: 'Πίτα' } }, { name: 'Σάλτσα' }],
|
||||||
translations: { en: { name: 'Skewer', quick: { 'Πίτα': 'Pitta' } } } })
|
translations: { el: { name: 'Σουβλάκι' }, en: { name: 'Skewer', quick: { 'Σάλτσα': 'Sauce' } } } })
|
||||||
assert.equal(f.translations.en.name, 'Skewer')
|
assert.deepEqual(f.names, { el: 'Σουβλάκι', en: 'Skewer' })
|
||||||
assert.equal(f.quick_options[0].tr.en, 'Pitta')
|
assert.equal(f.quick_options[1].tr.en, 'Sauce') // the product's old quick map
|
||||||
const renamed = { ...f, quick_options: [{ ...f.quick_options[0], name: 'Πίτα αραβική' }, f.quick_options[1]] }
|
// the venue speaks Greek: the shown name is the Greek one
|
||||||
assert.deepEqual(buildBody(renamed).translations, { en: { name: 'Skewer', quick: { 'Πίτα αραβική': 'Pitta' } } }) // kept by the new base name
|
let body = buildBody(f, 'el')
|
||||||
assert.deepEqual(buildBody({ ...f, translations: { en: { name: ' ', description: '' } }, quick_options: [] }).translations, {})
|
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' })
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,4 +20,4 @@ export { OverrideHost } from './OverrideHost.jsx'
|
|||||||
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
|
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
|
||||||
export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js'
|
export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js'
|
||||||
export { Allergens } from './Allergens.jsx'
|
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'
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// The menu's languages (plan step 6.4, owner 2026-11-18): English and Greek, the same list as the
|
// 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
|
// backend's core/menu_languages.py. Since 2026-11-21 every menu text is kept per language, the
|
||||||
// the other language; a missing translation shows the base text.
|
// 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']
|
export const MENU_LANGUAGES = ['el', 'en']
|
||||||
|
|
||||||
/** The languages a venue translates its menu into: every menu language but its own. */
|
/** 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
|
/** 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. */
|
* backend resolves them for customer screens, else the base text. */
|
||||||
export const inLanguage = (texts, lang, base) => (texts && texts[lang]) || base
|
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'), '')
|
||||||
|
})
|
||||||
@@ -1929,6 +1929,7 @@
|
|||||||
"view_list": "Λίστα",
|
"view_list": "Λίστα",
|
||||||
"view_grid": "Πλέγμα",
|
"view_grid": "Πλέγμα",
|
||||||
"new": "Νέο προϊόν",
|
"new": "Νέο προϊόν",
|
||||||
|
"newService": "Νέο είδος σερβιρίσματος",
|
||||||
"price": "Τιμή",
|
"price": "Τιμή",
|
||||||
"from": "από",
|
"from": "από",
|
||||||
"to": "έως",
|
"to": "έως",
|
||||||
@@ -2046,6 +2047,9 @@
|
|||||||
"done_other": "{{count}} προϊόντα ενημερώθηκαν"
|
"done_other": "{{count}} προϊόντα ενημερώθηκαν"
|
||||||
},
|
},
|
||||||
"editor": {
|
"editor": {
|
||||||
|
"serviceNewTitle": "Νέο είδος σερβιρίσματος",
|
||||||
|
"langDefault": "Προεπιλογή ({{language}})",
|
||||||
|
"langDefaultHint": "Η γλώσσα του καταστήματος",
|
||||||
"newTitle": "Νέο προϊόν",
|
"newTitle": "Νέο προϊόν",
|
||||||
"editTitle": "Επεξεργασία: {{name}}",
|
"editTitle": "Επεξεργασία: {{name}}",
|
||||||
"copy": "Αντιγραφή",
|
"copy": "Αντιγραφή",
|
||||||
|
|||||||
@@ -1929,6 +1929,7 @@
|
|||||||
"view_list": "List",
|
"view_list": "List",
|
||||||
"view_grid": "Grid",
|
"view_grid": "Grid",
|
||||||
"new": "New product",
|
"new": "New product",
|
||||||
|
"newService": "New service item",
|
||||||
"price": "Price",
|
"price": "Price",
|
||||||
"from": "from",
|
"from": "from",
|
||||||
"to": "to",
|
"to": "to",
|
||||||
@@ -2046,6 +2047,9 @@
|
|||||||
"done_other": "{{count}} products updated"
|
"done_other": "{{count}} products updated"
|
||||||
},
|
},
|
||||||
"editor": {
|
"editor": {
|
||||||
|
"serviceNewTitle": "New service item",
|
||||||
|
"langDefault": "Default ({{language}})",
|
||||||
|
"langDefaultHint": "The venue's language",
|
||||||
"newTitle": "New product",
|
"newTitle": "New product",
|
||||||
"editTitle": "Edit: {{name}}",
|
"editTitle": "Edit: {{name}}",
|
||||||
"copy": "Copy",
|
"copy": "Copy",
|
||||||
|
|||||||
@@ -58,6 +58,8 @@
|
|||||||
.x-btn--tone { color: var(--x-ink-2); }
|
.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--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); }
|
.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--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-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); }
|
.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__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__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__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__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__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 {
|
.x-modal__body {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const CloseIcon = () => (
|
|||||||
|
|
||||||
/** The shared body of Dialog and Sheet: backdrop, panel, header with ×, toolbar, body, footer. */
|
/** The shared body of Dialog and Sheet: backdrop, panel, header with ×, toolbar, body, footer. */
|
||||||
export function ModalFrame({
|
export function ModalFrame({
|
||||||
open, onClose, title, description, toolbar, children, footer,
|
open, onClose, title, description, headerEnd, toolbar, children, footer,
|
||||||
dismissible = true, closeLabel, initialFocus,
|
dismissible = true, closeLabel, initialFocus,
|
||||||
overlayClass, panelClass, grip = false, bodyClass,
|
overlayClass, panelClass, grip = false, bodyClass,
|
||||||
}) {
|
}) {
|
||||||
@@ -41,12 +41,14 @@ export function ModalFrame({
|
|||||||
className={panelClass}
|
className={panelClass}
|
||||||
>
|
>
|
||||||
{grip && <div className="x-sheet__grip" aria-hidden="true" />}
|
{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__header">
|
||||||
<div className="x-modal__titles">
|
<div className="x-modal__titles">
|
||||||
{title && <h2 id={titleId} className="x-modal__title">{title}</h2>}
|
{title && <h2 id={titleId} className="x-modal__title">{title}</h2>}
|
||||||
{description && <p id={descId} className="x-modal__description">{description}</p>}
|
{description && <p id={descId} className="x-modal__description">{description}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
{/* headerEnd: beside the close button (a language picker…) */}
|
||||||
|
{headerEnd && <div className="x-modal__header-end">{headerEnd}</div>}
|
||||||
{showClose && (
|
{showClose && (
|
||||||
<IconButton label={closeLabel ?? labels.close} size="sm" className="x-modal__close" onClick={onClose} data-x-autofocus-skip="">
|
<IconButton label={closeLabel ?? labels.close} size="sm" className="x-modal__close" onClick={onClose} data-x-autofocus-skip="">
|
||||||
<CloseIcon />
|
<CloseIcon />
|
||||||
|
|||||||
+27
-5
@@ -1014,12 +1014,23 @@ try {
|
|||||||
await pRow.waitFor({ timeout: 15_000 })
|
await pRow.waitFor({ timeout: 15_000 })
|
||||||
await pRow.getByTestId('product-edit').click()
|
await pRow.getByTestId('product-edit').click()
|
||||||
await page.getByTestId('product-editor').waitFor({ timeout: 10_000 })
|
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-gluten').click()
|
||||||
await page.getByTestId('allergen-milk').click()
|
await page.getByTestId('allergen-milk').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
|
// 2026-11-21: the language picker at the top drives every name field; "Default" = the venue's (English here)
|
||||||
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
|
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"`,
|
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="${catA.id}"][data-main="true"]`).count() === 1
|
||||||
&& await page.locator(`[data-testid="product-category"][data-id="${catB.id}"][data-main="false"]`).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)
|
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])
|
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]))
|
&& 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,
|
const quickP = savedP.quick_options.find(q => q.name === 'E2E bacon')
|
||||||
JSON.stringify(savedP.translations))
|
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()
|
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}"]`)
|
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)
|
r.check(`${pr} it shows in the second category too, marked "also in" the first`, await inB.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
|
||||||
|
|||||||
Reference in New Issue
Block a user