feat(manager): products and categories on v2, a product in several categories, allergens (platform-v2 step 6.3)

- Management/ProductsTab + ProductFormModal (3.1k lines) → src/pages/products/: category tree,
  list/grid, toolbar + filters (search folds accents and Latin letters), bulk actions, category
  dialogs; the editor in editor/ (details, sold at, cost, fiscal; the waiter's choices).
  Arithmetic in productsLogic.js / editor/formLogic.js (tests/products.test.mjs).
- Several categories per product with a main one (D-23): edited in the editor, "also in" on the
  rows, each category's list ordered on its own (drag or up/down → PUT /reorder with category_id);
  bulk "move to" / "also list in". The waiter's picker now shows a product in every category.
- Allergens: products.allergens (Alembic 0032, core/allergens.py: 14 EU, contains | may_contain,
  catalog.allergen), in the API, POS menu, menu tablet, catalogue bundles and the cloud snapshot
  (C-2); @xenia/access allergens.js + <Allergens> shown on the phone, the counter, the tablet.
- Bell: only the newest load sets the list (an older answer could hide a live notification).
- e2e: manager (two categories, order per category, allergens), terminal / menu tablet / waiter
  (allergens shown); media saves by test id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 10:04:35 +02:00
co-authored by Claude Opus 5.5
parent 8a02173450
commit 5048f82a4c
53 changed files with 2812 additions and 3179 deletions
+1 -1
View File
@@ -68,7 +68,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` |
| `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) |
| `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18) |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) and the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3; tests compare them), and `<Allergens>` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests |
| `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) |
| `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. |
+50
View File
@@ -0,0 +1,50 @@
"""Allergens (plan step 6.3): the 14 that EU Regulation 1169/2011 (Annex II) requires a venue
to declare. A fixed list in code, in the Annex's order; labels live in the i18n packages
(`common:allergens.<key>`), the same list in `packages/access/src/allergens.js`.
A product stores what it has (`products.allergens`, JSON) as {key: level}:
contains it is in the recipe
may_contain traces, e.g. made in the same kitchen ("may contain")
A key that isn't listed means neither. Unknown keys or levels are refused (catalog.allergen).
"""
from __future__ import annotations
import json
ALLERGENS: tuple[str, ...] = (
"gluten", "crustaceans", "eggs", "fish", "peanuts", "soybeans", "milk",
"nuts", "celery", "mustard", "sesame", "sulphites", "lupin", "molluscs",
)
LEVELS: tuple[str, ...] = ("contains", "may_contain")
def normalize(value) -> dict[str, str]:
"""A product's allergens as {key: level} in the list's order; raises XeniaError on anything else."""
from core.errors import XeniaError
if value in (None, "", {}):
return {}
if isinstance(value, str):
value = json.loads(value)
if not isinstance(value, dict):
raise XeniaError("catalog.allergen", allergen=str(value))
for key, level in value.items():
if key not in ALLERGENS or level not in LEVELS:
raise XeniaError("catalog.allergen", allergen=f"{key}: {level}")
return {k: value[k] for k in ALLERGENS if k in value}
def of(product) -> dict[str, str]:
"""What a product row stores, read safely (bad data in the column: nothing)."""
raw = getattr(product, "allergens", None)
if not raw:
return {}
try:
return normalize(raw)
except Exception:
return {}
def dump(value) -> str | None:
"""For the column: JSON, or None when there are none."""
data = normalize(value)
return json.dumps(data) if data else None
+1
View File
@@ -147,6 +147,7 @@ CODES: dict[str, tuple[int, str]] = {
"system.log_not_found": (404, "There is no log file for {date}."),
"catalog.unknown_category": (422, "There is no category {category_id}."),
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
"catalog.allergen": (422, "Unknown allergen or level: {allergen}."),
# converted from HTTPException (plan step 6.1)
"auth.password_current_required": (400, "Enter your current password to set a new one."),
"auth.no_password": (400, "This account has no password yet."),
@@ -0,0 +1,24 @@
"""Allergens (plan step 6.3): the 14 EU allergens per product, each "contains" or
"may contain" (core/allergens.py), as JSON {key: level}; null = none declared.
Revision ID: 0032_product_allergens
Revises: 0031_video_versions
Create Date: 2026-11-18 12:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0032_product_allergens'
down_revision = '0031_video_versions'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('allergens', sa.Text(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('allergens')
+2
View File
@@ -86,6 +86,8 @@ class Product(Base):
# Tags: JSON array of strings e.g. ["vegan", "gluten-free"]
tags = Column(Text, nullable=True)
# The EU allergens it has (plan step 6.3, core/allergens.py): JSON {key: "contains" | "may_contain"}
allergens = Column(Text, nullable=True)
# Fiscal printer (ΦΗΜ) fields
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
+5 -1
View File
@@ -1,6 +1,6 @@
from core.timeutil import venue_date, utcnow
import json
from core import sales_points
from core import allergens, sales_points
from datetime import datetime, timezone
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
@@ -60,6 +60,7 @@ def _serialize_product(p: Product) -> dict:
"name": p.name, "base_price": p.base_price, "is_available": p.is_available,
"lifecycle_status": p.lifecycle_status, "sort_order": p.sort_order,
"sold_at": sales_points.sold_at(p),
"allergens": allergens.of(p),
"quick_options": quick_options, "options": options,
"ingredients": ingredients, "preference_sets": preference_sets,
}
@@ -188,6 +189,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
existing.sort_order = prod_data.get("sort_order", 0)
if "sold_at" in prod_data: # phase 3S; older bundles: unchanged
existing.sold_at = sales_points.dump(prod_data["sold_at"])
if "allergens" in prod_data: # 6.3; older bundles: unchanged
existing.allergens = allergens.dump(prod_data["allergens"])
db.flush()
product = existing
else:
@@ -198,6 +201,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
lifecycle_status=prod_data.get("lifecycle_status", "active"),
sort_order=prod_data.get("sort_order", 0),
sold_at=sales_points.dump(prod_data.get("sold_at", sales_points.ALL)),
allergens=allergens.dump(prod_data.get("allergens")),
)
db.add(product)
db.flush()
+2 -1
View File
@@ -26,7 +26,7 @@ import time
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from core import sales_points
from core import allergens, sales_points
from core.access.deps import require_device
from core.errors import XeniaError
from database import get_db
@@ -124,6 +124,7 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
"config": cfg,
"categories": out_cats,
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
"allergens": allergens.of(p),
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
"image": media_store.image_of(p.media)} for p in shown},
}
+2 -1
View File
@@ -83,13 +83,14 @@ def _subs_out(raw):
def _product_out(p, price: float, prices: dict | None = None) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
from core import sales_points
from core import allergens, sales_points
return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"tags": _tags(p.tags),
"allergens": allergens.of(p),
"primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order,
+6 -3
View File
@@ -5,7 +5,7 @@ from pydantic import BaseModel
from sqlalchemy.orm import Session
from typing import List
from core import sales_points
from core import allergens, sales_points
from database import get_db
from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup
from models.prep_zone import PrepZone
@@ -369,12 +369,13 @@ def reorder_products(items: List[ProductReorderItem], db: Session = Depends(get_
@router.post("/", response_model=ProductOut, status_code=status.HTTP_201_CREATED)
def create_product(body: ProductCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags",
"category_id", "primary_category_id", "category_ids"})
"category_id", "primary_category_id", "category_ids", "allergens"})
if data.get("sort_order") == 0:
data["sort_order"] = db.query(Product).count()
if body.cost_breakdown is not None:
data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown])
data["tags"] = json.dumps(body.tags) if body.tags is not None else None
data["allergens"] = allergens.dump(body.allergens)
data["sold_at"] = sales_points.dump(body.sold_at)
data["media_id"] = _picture(db, body.media_id)
product = Product(**data)
@@ -432,7 +433,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
scalar_fields = body.model_dump(
exclude_none=True,
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
"category_id", "primary_category_id", "category_ids", "media_id"},
"category_id", "primary_category_id", "category_ids", "media_id", "allergens"},
)
if "media_id" in body.model_fields_set:
product.media_id = _picture(db, body.media_id)
@@ -454,6 +455,8 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
product.tags = json.dumps(body.tags)
elif "tags" in body.model_fields_set:
product.tags = None
if body.allergens is not None:
product.allergens = allergens.dump(body.allergens)
if body.quick_options is not None:
_replace_quick_options(db, product, body.quick_options)
# Modifier groups must be recreated before items so we have the ID map
+6 -1
View File
@@ -1,8 +1,9 @@
import json
from pydantic import BaseModel, model_validator, field_validator
from typing import Optional, List, Any, Literal
from typing import Optional, List, Any, Literal, Dict
from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at
from core.allergens import of as _allergens_of
SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
@@ -346,6 +347,8 @@ class ProductBase(BaseModel):
quick_add_enabled: bool = True
# Tags
tags: Optional[List[str]] = None
# The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py
allergens: Dict[str, str] = {}
# Service item flag
is_service_item: bool = False
# Fiscal printer (ΦΗΜ)
@@ -393,6 +396,7 @@ class ProductUpdate(BaseModel):
quick_add_enabled: Optional[bool] = None
# Tags
tags: Optional[List[str]] = None
allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none
# Service item flag
is_service_item: Optional[bool] = None
# Fiscal printer (ΦΗΜ)
@@ -463,6 +467,7 @@ class ProductOut(ProductBase):
'cost_breakdown': parsed,
'quick_add_enabled': getattr(data, 'quick_add_enabled', True),
'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []),
'allergens': _allergens_of(data),
'is_service_item': bool(getattr(data, 'is_service_item', False)),
'fiscal_name': getattr(data, 'fiscal_name', None),
'fiscal_vat_group_id': getattr(data, 'fiscal_vat_group_id', None),
+2 -1
View File
@@ -11,7 +11,7 @@ Lock behaviour (unchanged):
- cloud sets locked=true → lock_pending while a workday is open, locked once it closes
- expiry past grace / site deactivated → likewise never mid-service
"""
from core import sales_points
from core import allergens, sales_points
from core.access.queries import holders_filter
from core.timeutil import utcnow
import asyncio
@@ -289,6 +289,7 @@ def menu_snapshot(db) -> tuple[dict, list]:
"digital_image_url": p.digital_image_url,
"image_url": p.image_url,
"quick_options": [{"id": o.id, "name": o.name, "price": o.price} for o in p.quick_options],
"allergens": allergens.of(p), # 6.3: {key: "contains" | "may_contain"}
})
if product_list:
payload_categories.append({"id": cat.id, "name": cat.name, "sort_order": cat.sort_order,
+77
View File
@@ -0,0 +1,77 @@
"""Allergens per product (plan step 6.3): the 14 EU allergens, "contains" or "may contain",
set in the manager, carried to the counter, the phones, the menu tablet, the catalogue bundle
and the customer apps' menu (cloud contract C-2)."""
import re
from pathlib import Path
import pytest
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_menu_tablet import menu, tablet # noqa: F401 (fixtures)
ROOT = Path(__file__).resolve().parents[2]
def test_set_change_and_clear(client, owner_h, menu):
pid = menu["souvlaki"].id
r = client.put(f"/api/products/{pid}", headers=owner_h,
json={"allergens": {"milk": "may_contain", "gluten": "contains"}})
assert r.status_code == 200, r.text
assert r.json()["allergens"] == {"gluten": "contains", "milk": "may_contain"} # the Annex's order
# other changes leave them alone
assert client.put(f"/api/products/{pid}", headers=owner_h, json={"base_price": 4}).json()["allergens"]["gluten"] == "contains"
assert client.put(f"/api/products/{pid}", headers=owner_h, json={"allergens": {}}).json()["allergens"] == {}
created = client.post("/api/products/", headers=owner_h, json={"name": "Salad", "base_price": 6, "allergens": {"celery": "contains"}})
assert created.status_code == 201 and created.json()["allergens"] == {"celery": "contains"}
plain = client.post("/api/products/", headers=owner_h, json={"name": "Water", "base_price": 1}).json()
assert plain["allergens"] == {}
@pytest.mark.parametrize("bad", [{"pollen": "contains"}, {"milk": "a_little"}])
def test_unknown_allergens_or_levels_are_refused(client, owner_h, menu, bad):
r = client.put(f"/api/products/{menu['beer'].id}", headers=owner_h, json={"allergens": bad})
assert r.status_code == 422 and err(r) == "catalog.allergen"
def test_they_reach_the_counter_the_phones_and_the_tablet(client, owner_h, menu, tablet, make_user, login):
pid = menu["steak"].id
client.put(f"/api/products/{pid}", headers=owner_h, json={"allergens": {"mustard": "contains"}})
waiter_h = login(make_user(role="waiter"), client="waiter")
phones = {p["id"]: p for p in client.get("/api/products/", headers=waiter_h).json()}
assert phones[pid]["allergens"] == {"mustard": "contains"}
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert data["products"][str(pid)]["allergens"] == {"mustard": "contains"}
from routers.pos import _product_out
assert _product_out(menu["steak"], 12.0)["allergens"] == {"mustard": "contains"}
def test_catalogue_bundle_and_cloud_menu(client, db, owner_h, menu):
pid = menu["beer"].id
client.put(f"/api/products/{pid}", headers=owner_h, json={"allergens": {"gluten": "contains", "sulphites": "may_contain"}})
bundle = client.get("/api/data-transfer/export/catalog", headers=owner_h).json()
beer = next(p for c in bundle["data"]["categories"] for p in c["products"] if p["name"] == "Beer")
assert beer["allergens"] == {"gluten": "contains", "sulphites": "may_contain"}
client.put(f"/api/products/{pid}", headers=owner_h, json={"allergens": {}})
assert client.post("/api/data-transfer/import/catalog", headers=owner_h, json=bundle).status_code < 300
assert client.get("/api/products/?all=true", headers=owner_h).json()
db.expire_all()
from models.product import Product
from core.allergens import of
assert of(db.get(Product, pid)) == {"gluten": "contains", "sulphites": "may_contain"}
from services.cloud_sync import menu_snapshot
snap, _ = menu_snapshot(db)
products = {p["id"]: p for c in snap["categories"] for p in c["products"]}
assert products[pid]["allergens"] == {"gluten": "contains", "sulphites": "may_contain"}
def test_the_frontend_list_matches_the_backend():
"""packages/access/src/allergens.js keeps the same 14, in the same order."""
from core.allergens import ALLERGENS, LEVELS
js = (ROOT / "packages" / "access" / "src" / "allergens.js").read_text(encoding="utf-8")
listed = re.search(r"export const ALLERGENS = \[([^\]]*)\]", js).group(1)
assert [x.strip().strip("'") for x in listed.split(",") if x.strip()] == list(ALLERGENS)
levels = re.search(r"export const ALLERGEN_LEVELS = \[([^\]]*)\]", js).group(1)
assert [x.strip().strip("'") for x in levels.split(",") if x.strip()] == list(LEVELS)
+1 -1
View File
@@ -29,7 +29,7 @@ import ExpensesPage from './pages/financials/ExpensesPage'
import TabsPage from './pages/financials/TabsPage'
// Management
import ProductsPage from './pages/Management/ProductsPage'
import ProductsPage from './pages/products/ProductsPage'
import MediaPage from './pages/media/MediaPage'
import SignagePage from './pages/signage/SignagePage'
import TablesConfigPage from './pages/Management/TablesConfigPage'
@@ -23,10 +23,14 @@ export default function NotificationBell() {
const [open, setOpen] = useState(false)
const ref = useRef(null)
const asked = useRef(0)
const load = useCallback(async () => {
// Loads overlap (the timer, a reconnect, a live event); only the newest may set the list,
// else an answer sent before the event lands after it and hides the new one (seen in e2e).
const mine = ++asked.current
try {
const r = await client.get('/api/platform/notifications', { params: { limit: 30 } })
setData(r.data)
if (mine === asked.current) setData(r.data)
return r.data
} catch {
return null // the bell stays as it was; the next event or refresh tries again
File diff suppressed because it is too large Load Diff
@@ -1,9 +0,0 @@
import ProductsTab from '../Management/ProductsTab'
export default function ProductsPage() {
return (
<div className="flex flex-col h-full min-h-0">
<ProductsTab />
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,57 @@
// What the selected products get in one go (plan step 6.3): their prep zones, or a category —
// "move" makes it their only category, "also list" adds it to the ones they have.
import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Select } from '@xenia/ui'
import { Check } from './editor/parts'
import { categoryTree, treeLabel } from './productsLogic'
export function ZonesDialog({ count, zones, onApply, onClose }) {
const { t } = useTranslation('manager')
const [ids, setIds] = useState([])
return (
<Dialog open size="sm" onClose={onClose} title={t('products.bulkZones.title')} description={t('products.bulkZones.body', { count })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button disabled={!ids.length} onClick={() => onApply(ids)}>{t('products.apply')}</Button>
</>}>
{zones.length === 0 ? <EmptyState compact title={t('products.editor.noZones')} /> : (
<div className="grid gap-2">
{zones.map(z => (
<Check key={z.id} checked={ids.includes(z.id)} onChange={on => setIds(s => (on ? [...s, z.id] : s.filter(x => x !== z.id)))}>
<span className="text-body text-ink">{z.name}</span>{z.description && <span className="text-caption text-ink-3"> · {z.description}</span>}
</Check>
))}
</div>
)}
</Dialog>
)
}
export function CategoryBulkDialog({ count, categories, onApply, onClose }) {
const { t } = useTranslation('manager')
const [cat, setCat] = useState('')
const [mode, setMode] = useState('move')
return (
<Dialog open size="sm" onClose={onClose} title={t('products.bulkCategory.title')} description={t('products.bulkCategory.body', { count })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button disabled={!cat} onClick={() => onApply(Number(cat), mode)} data-testid="bulk-category-apply">{t('products.apply')}</Button>
</>}>
<div className="grid gap-4">
<div className="grid gap-2" role="radiogroup">
{['move', 'add'].map(m => (
<label key={m} className="flex items-start gap-2 cursor-pointer">
<input type="radio" name="bulk-mode" className="mt-1 accent-[var(--x-accent)]" checked={mode === m} onChange={() => setMode(m)} data-testid={`bulk-mode-${m}`} />
<span className="grid"><span className="text-body font-medium text-ink">{t(`products.bulkCategory.${m}`)}</span><span className="text-caption text-ink-3">{t(`products.bulkCategory.${m}Hint`)}</span></span>
</label>
))}
</div>
<Select value={cat} onChange={e => setCat(e.target.value)} aria-label={t('products.bulkCategory.which')} data-testid="bulk-category-pick">
<option value="">{t('products.bulkCategory.which')}</option>
{categoryTree(categories).map(({ cat: c, depth }) => <option key={c.id} value={c.id}>{treeLabel(c, depth)}</option>)}
</Select>
</div>
</Dialog>
)
}
@@ -0,0 +1,63 @@
// A category or sub-category (plan step 6.3): its name, picture and colour; or where it goes
// (top level or under another category).
import { useState } from 'react'
import { Check } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, cx } from '@xenia/ui'
import MediaField from '../media/MediaField'
import { CATEGORY_COLOURS } from './categoryColours'
import { topLevel } from './productsLogic'
export default function CategoryDialog({ category, parentName, saving, onSave, onClose }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(category.name ?? '')
const [color, setColor] = useState(category.color ?? CATEGORY_COLOURS[0])
const [image, setImage] = useState(category.image ?? null)
const sub = !!category.parent_id
const title = t(`products.category.${category.id ? 'edit' : 'new'}${sub ? 'Sub' : ''}`)
return (
<Dialog open size="sm" onClose={onClose} title={title} description={sub && parentName ? t('products.category.under', { name: parentName }) : undefined}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button disabled={!name.trim()} loading={saving} onClick={() => onSave({ name: name.trim(), color, media_id: image?.id ?? null })} data-testid="category-save">{t('products.save')}</Button>
</>}>
<div className="grid gap-4">
<Field label={t('products.category.name')}><Input value={name} onChange={e => setName(e.target.value)} autoFocus data-testid="category-name" /></Field>
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')} label={t('media.photo')} testid="category-photo" />
<div className="grid gap-2">
<span className="text-label font-semibold text-ink">{t('products.category.colour')}</span>
<div className="grid grid-cols-6 gap-2" role="radiogroup" aria-label={t('products.category.colour')}>
{CATEGORY_COLOURS.map(c => (
<button key={c} type="button" role="radio" aria-checked={color === c} aria-label={c} onClick={() => setColor(c)}
className={cx('aspect-square rounded-full grid place-items-center text-accent-fg ring-offset-2 ring-offset-surface', color === c && 'ring-2 ring-[var(--x-ink)]')}
style={{ background: c }}>
{color === c && <Check size={16} />}
</button>
))}
</div>
</div>
</div>
</Dialog>
)
}
/** Move a category: to the top level, or under another top-level category. */
export function MoveCategoryDialog({ category, categories, onMove, onClose }) {
const { t } = useTranslation('manager')
const own = new Set([category.id, ...categories.filter(c => c.parent_id === category.id).map(c => c.id)])
const [target, setTarget] = useState('')
return (
<Dialog open size="sm" onClose={onClose} title={t('products.category.moveTitle')} description={t('products.category.moving', { name: category.name })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<Button onClick={() => onMove(target === '' ? null : Number(target))}>{t('products.category.move')}</Button>
</>}>
<Field label={t('products.category.newPlace')}>
<Select value={target} onChange={e => setTarget(e.target.value)}>
<option value="">{t('products.category.topLevel')}</option>
{topLevel(categories).filter(c => !own.has(c.id)).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</Select>
</Field>
</Dialog>
)
}
@@ -0,0 +1,108 @@
// The categories beside the products (plan step 6.3): service items, all products, each
// category with its sub-categories (drag to reorder within a level; add a sub-category, move,
// edit or delete from a row), then products without a category and the archive. A category's
// count is the products listed in it, so a product in two categories counts in both. The chosen
// category's row shows its actions.
import { useRef, useState } from 'react'
import { Archive, ArrowRightLeft, ChevronDown, ChevronRight, Folder, GripVertical, Pencil, Plus, Search, Trash2, Truck, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { IconButton, Input, cx } from '@xenia/ui'
import { SCOPES, countIn, isArchived, moveId, subsOf, topLevel } from './productsLogic'
export function Dot({ cat, size = 'w-2 h-2' }) {
// a category's colour is the venue's choice (data)
return <span className={cx(size, 'rounded-full shrink-0', !cat?.color && 'bg-ink-3')} style={cat?.color ? { background: cat.color } : undefined} aria-hidden="true" />
}
export default function CategoryTree({ categories, products, scope, onScope, onAdd, onEdit, onDelete, onMove, onReorder }) {
const { t } = useTranslation('manager')
const [query, setQuery] = useState('')
const [open, setOpen] = useState(() => new Set(topLevel(categories).map(c => c.id)))
const drag = useRef(null)
const [dropAt, setDropAt] = useState(null)
const q = query.trim().toLowerCase()
const matches = c => !q || c.name.toLowerCase().includes(q) || subsOf(categories, c.id).some(s => s.name.toLowerCase().includes(q))
const live = products.filter(p => !isArchived(p))
const dnd = (cat, level, parent) => ({
draggable: true,
onDragStart: e => { drag.current = { id: cat.id, level, parent }; e.dataTransfer.effectAllowed = 'move' },
onDragOver: e => { e.preventDefault(); if (drag.current && drag.current.id !== cat.id && drag.current.level === level && drag.current.parent === parent) setDropAt(cat.id) },
onDragLeave: () => setDropAt(null),
onDrop: e => {
e.preventDefault()
setDropAt(null)
const d = drag.current
drag.current = null
if (!d || d.level !== level || d.parent !== parent) return
const siblings = (level === 'top' ? topLevel(categories) : subsOf(categories, parent)).map(c => c.id)
const next = moveId(siblings, d.id, cat.id)
if (next) onReorder(level, next)
},
})
const row = (cat, depth, parent) => (
<div key={cat.id} {...dnd(cat, depth ? 'sub' : 'top', parent)} className={cx(dropAt === cat.id && 'border-t-2 border-accent')}>
<Row label={cat.name} count={countIn(products, categories, cat.id)} active={scope === cat.id} onClick={() => onScope(cat.id)} depth={depth}
dot={<Dot cat={cat} />} drag testId={`category-${cat.id}`}
caret={!depth && subsOf(categories, cat.id).length > 0 ? (open.has(cat.id) || !!q) : null}
onCaret={() => setOpen(s => { const n = new Set(s); if (n.has(cat.id)) n.delete(cat.id); else n.add(cat.id); return n })}
actions={<>
{!depth && <IconButton size="sm" variant="ghost" label={t('products.category.newSub')} onClick={() => onAdd(cat.id)}><Plus size={14} /></IconButton>}
<IconButton size="sm" variant="ghost" label={t('products.category.moveTitle')} onClick={() => onMove(cat)}><ArrowRightLeft size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('products.category.edit')} onClick={() => onEdit(cat)}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('products.category.delete')} onClick={() => onDelete(cat)}><Trash2 size={14} /></IconButton>
</>} />
</div>
)
return (
<aside className="w-full md:w-80 md:min-w-80 border-b md:border-b-0 md:border-r border-line flex flex-col min-h-0 bg-surface" data-testid="category-tree">
<div className="flex items-center gap-2 px-4 pt-3 pb-2">
<Folder size={16} className="text-ink-3" aria-hidden="true" />
<h2 className="flex-1 text-label font-semibold text-ink">{t('products.categories')}</h2>
<IconButton size="sm" variant="secondary" label={t('products.category.new')} onClick={() => onAdd(null)} data-testid="category-add"><Plus size={14} /></IconButton>
</div>
<div className="px-4 pb-2 relative">
<Search size={14} className="absolute left-7 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" aria-hidden="true" />
<Input size="sm" className="pl-8" value={query} onChange={e => setQuery(e.target.value)} placeholder={t('products.searchCategories')} aria-label={t('products.searchCategories')} />
{query && <IconButton size="sm" variant="ghost" className="absolute right-5 top-1/2 -translate-y-1/2" label={t('products.clear')} onClick={() => setQuery('')}><X size={12} /></IconButton>}
</div>
<div className="flex-1 min-h-0 overflow-y-auto px-2 pb-2 max-h-72 md:max-h-none">
<Row label={t('products.service')} count={live.filter(p => p.is_service_item).length} active={scope === SCOPES.service} onClick={() => onScope(SCOPES.service)}
dot={<Truck size={14} className="text-warning-ink shrink-0" aria-hidden="true" />} />
<Row label={t('products.all')} count={live.filter(p => !p.is_service_item).length} active={scope === SCOPES.all} onClick={() => onScope(SCOPES.all)}
dot={<span className="w-2 h-2 rounded-full bg-accent shrink-0" aria-hidden="true" />} testId="category-all" />
{topLevel(categories).filter(matches).map(cat => (
<div key={cat.id}>
{row(cat, 0, null)}
{(open.has(cat.id) || q) && subsOf(categories, cat.id).map(s => row(s, 1, cat.id))}
</div>
))}
</div>
<div className="border-t border-line p-2">
<Row label={t('products.uncategorized')} count={live.filter(p => !(p.category_ids ?? []).length && !p.is_service_item).length}
active={scope === SCOPES.none} onClick={() => onScope(SCOPES.none)} dot={<Folder size={14} className="text-ink-3 shrink-0" aria-hidden="true" />} />
<Row label={t('products.archived')} count={products.filter(isArchived).length}
active={scope === SCOPES.archived} onClick={() => onScope(SCOPES.archived)} dot={<Archive size={14} className="text-ink-3 shrink-0" aria-hidden="true" />} />
</div>
</aside>
)
}
function Row({ label, count, active, onClick, dot, depth = 0, caret = null, onCaret, actions, drag = false, testId }) {
return (
<div className={cx('group relative flex flex-wrap items-center gap-1.5 pr-1 py-1 rounded-control cursor-pointer', active ? 'bg-accent-soft text-accent-ink' : 'hover:bg-surface-2 text-ink')}
style={{ paddingLeft: `${0.25 + depth}rem` }} onClick={onClick} data-active={active}>
{drag ? <GripVertical size={14} className="text-ink-3 cursor-grab shrink-0" aria-hidden="true" /> : <span className="w-3.5 shrink-0" />}
{caret !== null
? <button type="button" className="text-ink-3 shrink-0" onClick={e => { e.stopPropagation(); onCaret() }} aria-expanded={caret}>{caret ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</button>
: <span className="w-3.5 shrink-0" />}
{dot}
<button type="button" className={cx('flex-1 min-w-0 truncate text-left text-body', active && 'font-semibold')} data-testid={testId}>{label}</button>
{/* a category's own actions show on its row once it's chosen (touch screens have no hover) */}
<span className="px-1.5 rounded-full bg-surface-2 text-caption text-ink-2 tabular-nums shrink-0">{count}</span>
{actions && active && <span className="w-full flex justify-end gap-0.5" onClick={e => e.stopPropagation()} data-testid="category-actions">{actions}</span>}
</div>
)
}
@@ -0,0 +1,184 @@
// The products of the chosen category (plan step 6.3), as a list or a grid. The list is in
// groups, each a category's own list in its own order: drag a product (or use ▲ / ▼) to move it
// in that category only. A product listed in several categories shows in each, with its other
// categories named; its main one is marked.
import { useRef, useState } from 'react'
import { Archive, ChevronDown, ChevronRight, ChevronUp, GripVertical, Pencil, Star, Trash2 } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, IconButton, cx } from '@xenia/ui'
import { Dot } from './CategoryTree'
import { costOf, isArchived, reorderBody, stepBody } from './productsLogic'
export function Photo({ product, className }) {
if (product.image_url) return <img src={product.image?.thumb || product.image_url} alt="" className={cx('object-cover bg-surface-2', className)} />
return <span className={cx('grid place-items-center bg-surface-2 text-ink-3 font-semibold', className)} aria-hidden="true">{(product.name || '?').trim()[0]?.toUpperCase()}</span>
}
export default function ProductList({ groups, view, categories, prepZones, selected, onSelect, onEdit, onRemove, onToggle, onReorder }) {
const { t } = useTranslation('manager')
const [folded, setFolded] = useState(new Set())
const drag = useRef(null)
const [drop, setDrop] = useState(null) // { id, key, after }
const headers = groups.length > 1 || (groups[0] && groups[0].key !== '__none__')
if (view === 'grid') {
const seen = new Set()
const items = groups.flatMap(g => g.items).filter(p => !seen.has(p.id) && seen.add(p.id))
return (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]" data-testid="product-grid">
{items.map(p => <Card key={p.id} p={p} categories={categories} selected={selected.has(p.id)} onSelect={onSelect} onEdit={onEdit} onRemove={onRemove} onToggle={onToggle} />)}
</div>
)
}
const handlers = (g, p) => ({
draggable: true,
onDragStart: e => { drag.current = { id: p.id, key: g.key }; e.dataTransfer.effectAllowed = 'move' },
onDragOver: e => {
e.preventDefault()
if (!drag.current || drag.current.key !== g.key || drag.current.id === p.id) return
const r = e.currentTarget.getBoundingClientRect()
setDrop({ id: p.id, key: g.key, after: e.clientY > r.top + r.height / 2 })
},
onDragLeave: () => setDrop(null),
onDrop: e => {
e.preventDefault()
const d = drag.current
const after = drop?.after ?? false
drag.current = null
setDrop(null)
if (!d || d.key !== g.key) return
const body = reorderBody(g, d.id, p.id, after)
if (body) onReorder(body)
},
})
return (
<div className="grid gap-4">
{groups.map(g => {
const shut = folded.has(g.key)
return (
<section key={g.key} data-testid="product-group" data-category={g.key}>
{headers && (
<button type="button" onClick={() => setFolded(s => { const n = new Set(s); if (n.has(g.key)) n.delete(g.key); else n.add(g.key); return n })}
className="flex items-center gap-2 py-1.5 text-caption font-semibold uppercase tracking-wide text-ink-3" aria-expanded={!shut}>
{shut ? <ChevronRight size={14} /> : <ChevronDown size={14} />}
{g.cat && <Dot cat={g.cat} />}
{g.cat ? (g.cat.parent_id ? `${categories.find(c => c.id === g.cat.parent_id)?.name ?? ''} › ${g.cat.name}` : g.cat.name) : t('products.uncategorized')}
<span className="px-1.5 rounded-full bg-surface-2 normal-case tracking-normal tabular-nums">{g.items.length}</span>
</button>
)}
{!shut && (
<div className="rounded-card border border-line bg-surface divide-y divide-line">
{g.items.map((p, i) => (
<Row key={p.id} p={p} g={g} first={i === 0} last={i === g.items.length - 1} categories={categories} prepZones={prepZones}
selected={selected.has(p.id)} onSelect={onSelect} onEdit={onEdit} onRemove={onRemove} onToggle={onToggle}
onStep={step => { const body = stepBody(g, p.id, step); if (body) onReorder(body) }}
drop={drop?.id === p.id && drop?.key === g.key ? (drop.after ? 'after' : 'before') : null} dnd={handlers(g, p)} />
))}
</div>
)}
</section>
)
})}
</div>
)
}
function Others({ p, here, categories }) {
const { t } = useTranslation('manager')
const other = (p.category_ids ?? []).filter(id => id !== here)
if (!other.length) return null // only in this category: nothing to say
return (
<>
{here != null && here === p.primary_category_id && <span className="inline-flex items-center gap-1 text-accent-ink" title={t('products.mainHere')}><Star size={12} aria-hidden="true" />{t('products.main')}</span>}
{other.map(id => {
const c = categories.find(x => x.id === id)
return c && (
<span key={id} className="inline-flex items-center gap-1 px-1.5 rounded-full bg-surface-2" data-testid="also-in">
<Dot cat={c} size="w-1.5 h-1.5" />{t('products.alsoIn', { name: c.name })}{id === p.primary_category_id && <Star size={10} className="text-accent-ink" aria-label={t('products.main')} />}
</span>
)
})}
</>
)
}
function Row({ p, g, first, last, categories, prepZones, selected, onSelect, onEdit, onRemove, onToggle, onStep, drop, dnd }) {
const { t } = useTranslation('manager')
const { formatMoney, formatPercent } = useFormat()
const c = costOf(p)
const archived = isArchived(p)
const zones = (p.prep_zone_ids ?? []).map(id => prepZones.find(z => z.id === id)?.name).filter(Boolean)
return (
<div {...dnd} className={cx('group grid grid-cols-[auto_auto_auto_1fr_auto] md:grid-cols-[auto_auto_auto_1fr_auto_auto] items-center gap-3 px-2 py-2',
selected && 'bg-accent-soft', drop === 'before' && 'border-t-2 !border-t-accent', drop === 'after' && 'border-b-2 !border-b-accent')}
data-testid="product-row" data-name={p.name} data-id={p.id}>
<span className="flex flex-col items-center text-ink-3">
<button type="button" className="leading-none opacity-0 group-hover:opacity-100 focus:opacity-100 disabled:invisible hover:text-ink" aria-label={t('products.moveUp')} title={t('products.moveUp')}
disabled={first} onClick={() => onStep(-1)} data-testid="product-up"><ChevronUp size={14} /></button>
<GripVertical size={14} className="cursor-grab" aria-hidden="true" />
<button type="button" className="leading-none opacity-0 group-hover:opacity-100 focus:opacity-100 disabled:invisible hover:text-ink" aria-label={t('products.moveDown')} title={t('products.moveDown')}
disabled={last} onClick={() => onStep(1)} data-testid="product-down"><ChevronDown size={14} /></button>
</span>
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={selected} onChange={() => onSelect(p.id)} aria-label={t('products.select', { name: p.name })} />
<Photo product={p} className="w-11 h-11 rounded-control" />
<div className="min-w-0 grid gap-0.5">
<span className="flex items-center gap-2 min-w-0">
<span className="text-body font-medium text-ink truncate">{p.name}</span>
{archived && <span className="px-1.5 rounded bg-surface-2 text-caption font-semibold uppercase text-ink-2">{t('products.archivedBadge')}</span>}
{p.is_service_item && !archived && <span className="px-1.5 rounded bg-warning-soft text-caption font-semibold uppercase text-warning-ink">{t('products.service')}</span>}
{Object.keys(p.allergens ?? {}).length > 0 && <span className="px-1.5 rounded bg-warning-soft text-caption text-warning-ink" title={t('products.hasAllergens')}>{t('products.allergenCount', { count: Object.keys(p.allergens).length })}</span>}
</span>
<span className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-caption text-ink-2">
<Others p={p} here={g.key === '__none__' ? null : g.key} categories={categories} />
{zones.map(z => <span key={z} className="px-1.5 rounded bg-info-soft text-info-ink">{z}</span>)}
</span>
</div>
<span className="grid justify-items-end">
<span className="text-body font-semibold tabular-nums text-ink">{formatMoney(p.base_price)}</span>
{c && <span className={cx('text-caption', c.over ? 'text-danger-ink' : 'text-success-ink')}>{c.over ? t('products.costOverPrice') : c.margin != null ? t('products.margin', { pct: formatPercent(c.margin, { maxDecimals: 0 }) }) : null}</span>}
</span>
<span className="col-span-5 md:col-span-1 flex items-center justify-end gap-1.5">
{!archived && (
<Button size="sm" variant={p.is_available ? 'secondary' : 'ghost'} onClick={() => onToggle(p)} aria-pressed={p.is_available} data-testid="product-available">
<span className={cx('w-2 h-2 rounded-full', p.is_available ? 'bg-success' : 'bg-ink-3')} aria-hidden="true" />
{p.is_available ? t('products.available') : t('products.unavailable')}
</Button>
)}
<Button size="sm" variant="secondary" icon={<Pencil size={14} />} onClick={() => onEdit(p)} data-testid="product-edit">{t('products.edit')}</Button>
<IconButton size="sm" variant="ghost" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)}>{archived ? <Trash2 size={16} /> : <Archive size={16} />}</IconButton>
</span>
</div>
)
}
function Card({ p, categories, selected, onSelect, onEdit, onRemove, onToggle }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const main = categories.find(c => c.id === p.primary_category_id)
const archived = isArchived(p)
return (
<div className={cx('group rounded-card border bg-surface overflow-hidden flex flex-col', selected ? 'border-accent shadow-focus' : 'border-line hover:shadow-raised')} data-testid="product-card" data-name={p.name}>
<div className="relative h-36">
<Photo product={p} className="w-full h-full text-display" />
<span className="absolute top-2 left-2 flex gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
<input type="checkbox" className="w-5 h-5 accent-[var(--x-accent)]" checked={selected} onChange={() => onSelect(p.id)} aria-label={t('products.select', { name: p.name })} />
<IconButton size="sm" variant="secondary" label={t('products.edit')} onClick={() => onEdit(p)}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="secondary" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)}><Archive size={14} /></IconButton>
</span>
{!archived && (
<button type="button" onClick={() => onToggle(p)} title={p.is_available ? t('products.available') : t('products.unavailable')} aria-label={p.is_available ? t('products.available') : t('products.unavailable')}
className="absolute top-2 right-2 w-7 h-7 rounded-full bg-surface grid place-items-center shadow-raised">
<span className={cx('w-2.5 h-2.5 rounded-full', p.is_available ? 'bg-success' : 'bg-ink-3')} />
</button>
)}
</div>
<div className="p-3 grid gap-1.5">
<span className="text-body font-semibold text-ink">{p.name}</span>
{main && <span className="inline-flex items-center gap-1 text-caption text-ink-2"><Dot cat={main} />{main.name}{(p.category_ids?.length ?? 0) > 1 && ` +${p.category_ids.length - 1}`}</span>}
<span className="text-body font-bold tabular-nums text-ink">{formatMoney(p.base_price)}</span>
</div>
</div>
)
}
@@ -0,0 +1,162 @@
// Management → Products (plan step 6.3, was Management/ProductsTab): the categories on the left,
// the chosen category's products on the right. A product can be listed in several categories
// (D-23); each category's list has its own order, and one of the product's categories is its
// main one (tickets and reports group it there). Changes reach every screen live
// (`products_changed`).
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Spinner } from '@xenia/ui'
import { Package } from 'lucide-react'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import CategoryDialog, { MoveCategoryDialog } from './CategoryDialog'
import CategoryTree from './CategoryTree'
import ProductList from './ProductList'
import Toolbar, { BulkBar, SubChips } from './Toolbar'
import { CategoryBulkDialog, ZonesDialog } from './BulkDialogs'
import ProductEditor from './editor/ProductEditor'
import { emptyProduct } from './editor/formLogic'
import { NO_FILTERS, SCOPES, applyFilters, bulkCategories, groupProducts, isArchived, isCategoryScope, listedIn, scopeProducts, subsOf } from './productsLogic'
const EVENTS = ['products_changed']
const number = v => (v === '' ? null : Number(String(v).replace(',', '.')))
export default function ProductsPage() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const [scope, setScope] = useState(SCOPES.all)
const [sub, setSub] = useState(null)
const [search, setSearch] = useState('')
const [filters, setFilters] = useState(NO_FILTERS)
const [view, setView] = useState('list')
const [selected, setSelected] = useState(new Set())
const [editing, setEditing] = useState(null) // a product (new: no id)
const [catEdit, setCatEdit] = useState(null) // a category (new: no id, parent_id)
const [catMove, setCatMove] = useState(null)
const [confirm, setConfirm] = useState(null) // { kind: 'category' | 'archive' | 'delete' | 'bulkArchive', item? }
const [bulk, setBulk] = useState(null) // 'zones' | 'category'
const { data: categories = [], isPending: catsPending } = useLiveQuery({ queryKey: ['categories'], queryFn: () => client.get('/api/products/categories').then(r => r.data), events: EVENTS })
const { data: products = [], isPending: productsPending } = useLiveQuery({ queryKey: ['products-all'], queryFn: () => client.get('/api/products/', { params: { all: true } }).then(r => r.data), events: EVENTS })
const { data: zones = [] } = useLiveQuery({ queryKey: ['prep-zones'], queryFn: () => client.get('/api/prep-zones').then(r => r.data) })
const refresh = () => { qc.invalidateQueries({ queryKey: ['products-all'] }); qc.invalidateQueries({ queryKey: ['categories'] }) }
const onError = err => toast.error(errorMessage(err, t))
const run = (fn, done) => ({ mutationFn: fn, onSuccess: () => { if (done) toast.success(done); refresh() }, onError })
const saveProduct = useMutation({ ...run(b => (editing?.id ? client.put(`/api/products/${editing.id}`, b) : client.post('/api/products/', b)), t('products.saved')), onSuccess: () => { toast.success(t('products.saved')); setEditing(null); refresh() } })
const saveCategory = useMutation({ ...run(b => (catEdit?.id ? client.put(`/api/products/categories/${catEdit.id}`, b) : client.post('/api/products/categories', b))), onSuccess: () => { toast.success(t('products.category.saved')); setCatEdit(null); refresh() } })
const reorder = useMutation(run(body => client.put('/api/products/reorder', body)))
const reorderCats = useMutation(run(({ level, ids }) => client.put(level === 'top' ? '/api/products/categories/reorder' : '/api/products/categories/reorder-subcategories', ids.map((id, i) => ({ id, sort_order: i })))))
const reparent = useMutation(run(({ id, parent_id }) => client.put(`/api/products/categories/${id}/reparent`, { parent_id }), t('products.category.moved')))
const toggle = useMutation(run(p => client.put(`/api/products/${p.id}`, { is_available: !p.is_available })))
async function confirmed() {
const c = confirm
setConfirm(null)
try {
if (c.kind === 'category') { await client.delete(`/api/products/categories/${c.item.id}`); if (scope === c.item.id) setScope(SCOPES.all) }
if (c.kind === 'archive') await client.delete(`/api/products/${c.item.id}`)
if (c.kind === 'delete') await client.delete(`/api/products/${c.item.id}`, { params: { hard: true } })
if (c.kind === 'bulkArchive') { await Promise.all([...selected].map(id => client.delete(`/api/products/${id}`))); setSelected(new Set()) }
toast.success(t(`products.done.${c.kind}`))
} catch (err) { onError(err) } finally { refresh() }
}
async function bulkPut(bodyOf, done) {
try {
await Promise.all([...selected].map(id => client.put(`/api/products/${id}`, bodyOf(products.find(p => p.id === id)))))
toast.success(done)
setSelected(new Set())
} catch (err) { onError(err) } finally { setBulk(null); refresh() }
}
async function bulkZones(ids) {
try {
await client.post('/api/products/bulk-prep-zones', { product_ids: [...selected], prep_zone_ids: ids })
toast.success(t('products.bulkZones.done', { count: selected.size }))
setSelected(new Set())
} catch (err) { onError(err) } finally { setBulk(null); refresh() }
}
if (catsPending || productsPending) return <div className="p-6 flex justify-center"><Spinner /></div>
const scopeCat = isCategoryScope(scope) ? categories.find(c => c.id === scope) : null
const subs = scopeCat && !scopeCat.parent_id ? subsOf(categories, scope) : []
const inScope = scopeProducts(products, categories, scope, { showArchived: filters.showArchived })
const shown = applyFilters(inScope, { search, priceMin: number(filters.priceMin), priceMax: number(filters.priceMax), quality: filters.quality, unavailableOnly: filters.unavailableOnly })
const groups = groupProducts(shown, categories, scope, subs.length ? sub : null)
const title = scope === SCOPES.all ? t('products.all') : scope === SCOPES.service ? t('products.service') : scope === SCOPES.none ? t('products.uncategorized')
: scope === SCOPES.archived ? t('products.archived') : scopeCat ? (scopeCat.parent_id ? `${categories.find(c => c.id === scopeCat.parent_id)?.name ?? ''} › ${scopeCat.name}` : scopeCat.name) : t('products.title')
const newProduct = () => {
if (scope === SCOPES.service) return setEditing(emptyProduct({ is_service_item: true, base_price: 0 }))
const preset = (subs.length && sub) || (isCategoryScope(scope) ? scope : null)
setEditing(emptyProduct(preset ? { category_ids: [preset], primary_category_id: preset } : {}))
}
const toggleSelect = id => setSelected(s => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n })
const allIds = [...new Set(groups.flatMap(g => g.items.map(p => p.id)))]
return (
<div className="flex flex-col md:flex-row h-full min-h-0" data-testid="products-page">
<CategoryTree categories={categories} products={products} scope={scope}
onScope={s => { setScope(s); setSub(null); setSelected(new Set()) }}
onAdd={parent => setCatEdit({ parent_id: parent })} onEdit={setCatEdit} onMove={setCatMove}
onDelete={c => setConfirm({ kind: 'category', item: c })}
onReorder={(level, ids) => reorderCats.mutate({ level, ids })} />
<div className="flex-1 min-w-0 min-h-0 flex flex-col">
<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} />
{subs.length > 0 && (
<SubChips parent={scopeCat} subs={subs} value={sub} onChange={setSub}
counts={key => (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} />
)}
{selected.size > 0 && (
<BulkBar count={selected.size} onClear={() => setSelected(new Set())}
onAvailable={() => bulkPut(() => ({ is_available: true }), t('products.updated', { count: selected.size }))}
onUnavailable={() => bulkPut(() => ({ is_available: false }), t('products.updated', { count: selected.size }))}
onArchive={() => setConfirm({ kind: 'bulkArchive' })} onZones={() => setBulk('zones')} onCategory={() => setBulk('category')} />
)}
<div className="flex items-center justify-between px-4 md:px-6 py-2 border-b border-line bg-surface-2 text-label text-ink-2">
<label className="flex items-center gap-2 cursor-pointer select-none">
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={allIds.length > 0 && allIds.every(id => selected.has(id))}
onChange={e => setSelected(e.target.checked ? new Set(allIds) : new Set())} />
{selected.size ? t('products.selected', { count: selected.size }) : t('products.selectAll')}
</label>
<span>{t('products.totals', { active: products.filter(p => !isArchived(p)).length, categories: categories.length, archived: products.filter(isArchived).length })}</span>
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-6">
{allIds.length === 0
? <EmptyState icon={<Package size={28} />} title={t('products.none')} description={t('products.noneHint')} action={<Button onClick={newProduct}>{t('products.new')}</Button>} />
: <ProductList groups={groups} view={view} categories={categories} prepZones={zones} selected={selected} onSelect={toggleSelect}
onEdit={setEditing} onToggle={p => toggle.mutate(p)} onReorder={body => reorder.mutate(body)}
onRemove={p => setConfirm({ kind: isArchived(p) ? 'delete' : 'archive', item: p })} />}
</div>
</div>
{editing && (
<ProductEditor key={editing.id ?? 'new'} product={editing} categories={categories} prepZones={zones} saving={saveProduct.isPending}
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)}
onCopy={form => setEditing({ _form: { ...form, name: t('products.copyOf', { name: form.name }) } })} />
)}
{catEdit && (
<CategoryDialog category={catEdit} parentName={categories.find(c => c.id === catEdit.parent_id)?.name} saving={saveCategory.isPending}
onClose={() => setCatEdit(null)} onSave={b => saveCategory.mutate({ ...b, parent_id: catEdit.parent_id ?? null })} />
)}
{catMove && <MoveCategoryDialog category={catMove} categories={categories} onClose={() => setCatMove(null)}
onMove={parent => { reparent.mutate({ id: catMove.id, parent_id: parent }); setCatMove(null) }} />}
{bulk === 'zones' && <ZonesDialog count={selected.size} zones={zones} onApply={bulkZones} onClose={() => setBulk(null)} />}
{bulk === 'category' && <CategoryBulkDialog count={selected.size} categories={categories} onClose={() => setBulk(null)}
onApply={(cat, mode) => bulkPut(p => bulkCategories(p, cat, mode), t('products.bulkCategory.done', { count: selected.size }))} />}
{confirm && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(`products.confirm.${confirm.kind}`, { name: confirm.item?.name, count: selected.size })}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('products.cancel')}</Button>
<Button variant="danger" onClick={confirmed} data-testid="confirm">{t(`products.confirmButton.${confirm.kind}`)}</Button>
</>}>
<p>{t(`products.confirmBody.${confirm.kind}`)}</p>
</Dialog>
)}
</div>
)
}
@@ -0,0 +1,95 @@
// The products' toolbar (plan step 6.3): the title and count, search (accents ignored, Latin
// letters find Greek names), filters (price, missing photo / category, unavailable only,
// archived too), list or grid, and "New product". Then the sub-category chips of a top-level
// category, and the bar of what to do with the selected products.
import { useState } from 'react'
import { Archive, Eye, EyeOff, Filter, FolderInput, LayoutGrid, List, Plus, Search, Utensils, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, cx } from '@xenia/ui'
import { Dot } from './CategoryTree'
import { NO_FILTERS } from './productsLogic'
export default function Toolbar({ title, shown, total, search, onSearch, filters, onFilters, view, onView, onNew }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
const any = JSON.stringify(filters) !== JSON.stringify(NO_FILTERS)
const set = (k, v) => onFilters({ ...filters, [k]: v })
return (
<div className="relative border-b border-line px-4 md:px-6 py-3 flex flex-wrap items-center gap-2">
<h1 className="text-title font-semibold text-ink" data-testid="products-title">{title}</h1>
<span className="px-2 rounded-full bg-surface-2 text-caption text-ink-2 tabular-nums">{shown}/{total}</span>
<div className="relative flex-1 min-w-48">
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" aria-hidden="true" />
<Input size="sm" className="pl-8" value={search} onChange={e => onSearch(e.target.value)} placeholder={t('products.search')} aria-label={t('products.search')} data-testid="products-search" />
{search && <IconButton size="sm" variant="ghost" className="absolute right-1 top-1/2 -translate-y-1/2" label={t('products.clear')} onClick={() => onSearch('')}><X size={12} /></IconButton>}
</div>
<Button size="sm" variant={open ? 'primary' : 'secondary'} icon={<Filter size={14} />} onClick={() => setOpen(o => !o)} aria-expanded={open}>
{t('products.filters')}{any && <span className="w-1.5 h-1.5 rounded-full bg-accent" aria-hidden="true" />}
</Button>
<span className="inline-flex rounded-control border border-line overflow-hidden" role="radiogroup" aria-label={t('products.view')}>
{[['list', <List key="l" size={14} />], ['grid', <LayoutGrid key="g" size={14} />]].map(([v, icon]) => (
<button key={v} type="button" role="radio" aria-checked={view === v} title={t(`products.view_${v}`)} aria-label={t(`products.view_${v}`)} onClick={() => onView(v)}
className={cx('w-9 h-control-sm grid place-items-center', view === v ? 'bg-accent text-accent-fg' : 'text-ink-2 hover:bg-surface-2')}
>{icon}</button>
))}
</span>
<Button size="sm" icon={<Plus size={14} />} onClick={onNew} data-testid="product-new">{t('products.new')}</Button>
{open && (
<div className="absolute z-popover top-full left-4 right-4 md:left-6 md:right-6 mt-1 p-4 rounded-card border border-line bg-surface shadow-popover flex flex-wrap items-end gap-5">
<label className="grid gap-1">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.price')}</span>
<span className="flex items-center gap-1.5">
<Input size="sm" className="w-20" inputMode="decimal" value={filters.priceMin} onChange={e => set('priceMin', e.target.value)} placeholder={t('products.from')} aria-label={t('products.from')} />
<span className="text-ink-3">–</span>
<Input size="sm" className="w-20" inputMode="decimal" value={filters.priceMax} onChange={e => set('priceMax', e.target.value)} placeholder={t('products.to')} aria-label={t('products.to')} />
</span>
</label>
<div className="grid gap-1">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.quality')}</span>
<span className="flex gap-1">
{['all', 'no-photo', 'no-cat'].map(q => <Button key={q} size="sm" variant={filters.quality === q ? 'primary' : 'secondary'} onClick={() => set('quality', q)}>{t(`products.qualityOf.${q}`)}</Button>)}
</span>
</div>
<div className="grid gap-1">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.show')}</span>
<span className="flex gap-1">
<Button size="sm" variant={filters.unavailableOnly ? 'primary' : 'secondary'} onClick={() => set('unavailableOnly', !filters.unavailableOnly)}>{t('products.unavailableOnly')}</Button>
<Button size="sm" variant={filters.showArchived ? 'primary' : 'secondary'} onClick={() => set('showArchived', !filters.showArchived)}>{t('products.withArchived')}</Button>
</span>
</div>
{any && <Button size="sm" variant="ghost" icon={<X size={14} />} className="ml-auto" onClick={() => onFilters(NO_FILTERS)}>{t('products.clearFilters')}</Button>}
</div>
)}
</div>
)
}
/** The sub-categories of a top-level category as chips: all, the category's own list, each sub-category. */
export function SubChips({ parent, subs, counts, value, onChange }) {
const { t } = useTranslation('manager')
const chips = [{ key: null, label: t('products.allOf') }, { key: parent.id, label: parent.name, cat: parent }, ...subs.map(s => ({ key: s.id, label: s.name, cat: s }))]
return (
<div className="flex flex-wrap gap-1.5 px-4 md:px-6 py-2 border-b border-line">
{chips.map(c => (
<Button key={String(c.key)} size="sm" variant={value === c.key ? 'primary' : 'secondary'} onClick={() => onChange(c.key)}>
{c.cat && <Dot cat={c.cat} />}{c.label}<span className="tabular-nums opacity-70">{counts(c.key)}</span>
</Button>
))}
</div>
)
}
export function BulkBar({ count, onClear, onAvailable, onUnavailable, onArchive, onZones, onCategory }) {
const { t } = useTranslation('manager')
return (
<div className="mx-4 md:mx-6 mt-3 px-3 py-2 rounded-card bg-accent text-accent-fg flex flex-wrap items-center gap-2" data-testid="bulk-bar">
<IconButton size="sm" variant="ghost" className="text-accent-fg" label={t('products.clearSelection')} onClick={onClear}><X size={14} /></IconButton>
<span className="text-label font-semibold flex-1">{t('products.selected', { count })}</span>
<Button size="sm" variant="secondary" icon={<Eye size={14} />} onClick={onAvailable}>{t('products.makeAvailable')}</Button>
<Button size="sm" variant="secondary" icon={<EyeOff size={14} />} onClick={onUnavailable}>{t('products.makeUnavailable')}</Button>
<Button size="sm" variant="secondary" icon={<Archive size={14} />} onClick={onArchive}>{t('products.archive')}</Button>
<Button size="sm" variant="secondary" icon={<Utensils size={14} />} onClick={onZones}>{t('products.prepZone')}</Button>
<Button size="sm" variant="secondary" icon={<FolderInput size={14} />} onClick={onCategory} data-testid="bulk-category">{t('products.toCategory')}</Button>
</div>
)
}
@@ -0,0 +1,4 @@
// The colours a venue can give a category (plan step 6.3). These are the venue's data (stored on
// the category and shown as its dot here and on the phones), not the manager's styling: listed
// in tests/v2-guards.test.mjs DATA.
export const CATEGORY_COLOURS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#ec4899', '#8b5cf6', '#14b8a6', '#f97316', '#64748b', '#84cc16', '#06b6d4']
@@ -0,0 +1,270 @@
// The editor's right side (plan step 6.3): what a waiter can choose for the product.
// Favourites the choices shown first, in their own order, across the lists below
// Quick one-tap add-ons with a price (extra bacon)
// Ingredients what the guest can leave out (or pay to add more), optionally in groups
// Extras ticked add-ons, each with optional sub-choices (syrup → caramel / vanilla)
// Preferences one set per tab (sugar: none / medium / sweet), a default, sub-choices, a
// shared sub-set shown for every choice except those marked to hide it
import { useRef, useState } from 'react'
import { Heart, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Input, Select, cx } from '@xenia/ui'
import { favourites, moveChoice, moveFavourite, moveItem, removeChoice, removeGroup, setSub, toggleFavourite } from './formLogic'
import { Check, DefaultToggle, FavouriteToggle, GroupHeader, MoveButtons, PriceInput, SubChoices } from './parts'
const newSub = () => ({ name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false })
export default function ChoicesPanel({ form, setForm }) {
const { t } = useTranslation('manager')
const [tab, setTab] = useState('favourites')
const [folded, setFolded] = useState({})
const nextKey = useRef(-1)
const favCount = favourites(form).length
const addGroup = type => setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { key: nextKey.current--, modifier_type: type, name: t('products.editor.newGroup') }] }))
const groups = { form, setForm, folded, fold: key => setFolded(s => ({ ...s, [key]: !s[key] })), addGroup }
const addPref = () => {
setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', default_choice_index: -1, choices: [], shared_subset: null, group_id: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] }))
setTab(form.preference_sets.length)
}
const tabs = [
{ key: 'favourites', label: t('products.editor.tab.favourites'), count: favCount },
{ key: 'quick', label: t('products.editor.tab.quick'), count: form.quick_options.length },
{ key: 'ingredients', label: t('products.editor.tab.ingredients'), count: form.ingredients.length },
{ key: 'options', label: t('products.editor.tab.options'), count: form.options.length },
...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || t('products.editor.prefN', { n: i + 1 }), count: ps.choices.length })),
]
return (
<div className="flex flex-col min-h-0 h-full">
<div className="flex items-end border-b border-line overflow-x-auto shrink-0" role="tablist">
{tabs.map(tb => (
<button key={String(tb.key)} type="button" role="tab" aria-selected={tab === tb.key} onClick={() => setTab(tb.key)}
className={cx('flex items-center gap-1.5 px-4 py-2.5 -mb-px border-b-2 text-label whitespace-nowrap',
tab === tb.key ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
{tb.key === 'favourites' && <Heart size={14} className={favCount ? 'text-danger' : 'text-ink-3'} fill={favCount ? 'currentColor' : 'none'} aria-hidden="true" />}
{tb.label}
{tb.count > 0 && <span className="px-1.5 rounded-full bg-surface-2 text-caption tabular-nums">{tb.count}</span>}
</button>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={addPref} data-testid="add-pref">{t('products.editor.addPref')}</Button>
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={() => addGroup('preference')}>{t('products.editor.addPrefGroup')}</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-5">
{tab === 'favourites' && <Favourites form={form} setForm={setForm} />}
{tab === 'quick' && <QuickList form={form} setForm={setForm} />}
{tab === 'ingredients' && <GroupedList kind="ingredient" list="ingredients" {...groups} />}
{tab === 'options' && <GroupedList kind="option" list="options" {...groups} />}
{typeof tab === 'number' && form.preference_sets[tab] && (
<PrefSet si={tab} {...groups} onRemoved={() => setTab('favourites')} />
)}
</div>
</div>
)
}
function Intro({ text, children }) {
return (
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<p className="text-label text-ink-2">{text}</p>
<div className="flex gap-2">{children}</div>
</div>
)
}
function Favourites({ form, setForm }) {
const { t } = useTranslation('manager')
const list = favourites(form)
return (
<div className="grid gap-2">
<p className="text-label text-ink-2">{t('products.editor.favouritesHint')}</p>
{list.length === 0 && <EmptyState compact title={t('products.editor.noFavourites')} />}
{list.map((fav, i) => (
<div key={`${fav.kind}-${fav.idx}`} className="flex items-center gap-3 rounded-card border border-line p-2.5">
<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" />
<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-caption text-ink-3">{t(`products.editor.kind.${fav.kind}`)}</span>
</span>
<Button size="sm" variant="ghost" onClick={() => setForm(f => toggleFavourite(f, fav.kind, fav.idx))}>{t('products.editor.remove')}</Button>
</div>
))}
</div>
)
}
function QuickList({ form, setForm }) {
const { t } = useTranslation('manager')
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 }] }))
return (
<div>
<Intro text={t('products.editor.quickHint')}><Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t('products.editor.addQuick')}</Button></Intro>
{form.quick_options.length === 0 && <EmptyState compact title={t('products.editor.noQuick')} />}
<div className="grid gap-2">
{form.quick_options.map((q, i) => (
<div key={i} className={cx('flex flex-wrap items-center gap-2 rounded-card border p-2.5', q.is_favorite ? 'border-danger' : 'border-line')}>
<MoveButtons first={i === 0} last={i === form.quick_options.length - 1}
onUp={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, -1) }))} onDown={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, 1) }))} />
<FavouriteToggle on={q.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'quick', i))} />
<Input className="flex-1 min-w-36" value={q.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.quickPlaceholder')} />
<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>
)
}
/** Ingredients or extras, with their groups (folders). */
function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
const { t } = useTranslation('manager')
const items = form[list]
const myGroups = form.modifier_groups.filter(g => g.modifier_type === kind)
const set = (i, k, v) => setForm(f => ({ ...f, [list]: f[list].map((x, j) => (j === i ? { ...x, [k]: v } : x)) }))
const add = () => setForm(f => ({ ...f, [list]: [...f[list], kind === 'option'
? { name: '', extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0, group_id: null }
: { name: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, group_id: null }] }))
const row = (x, i) => (
<div key={i} className={cx('rounded-card border overflow-hidden', x.is_favorite ? 'border-danger' : 'border-line')}>
<div className="flex flex-wrap items-center gap-2 p-2.5">
<MoveButtons first={i === 0} last={i === items.length - 1}
onUp={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, -1) }))} onDown={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, 1) }))} />
<FavouriteToggle on={x.is_favorite} onClick={() => setForm(f => toggleFavourite(f, kind, i))} />
<Input className="flex-1 min-w-36" value={x.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t(`products.editor.${kind}Placeholder`)} />
<PriceInput className="w-32" value={x.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{kind === 'option' && <Check checked={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
{kind === 'option' && <Check checked={x.multi_select} onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Check>}
<Check checked={x.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
{myGroups.length > 0 && (
<Select size="sm" className="w-36" value={x.group_id ?? ''} onChange={e => set(i, 'group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
<option value="">{t('products.editor.noGroup')}</option>
{myGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
</Select>
)}
{kind === 'option' && <Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => set(i, 'sub_choices', [...x.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>}
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, [list]: f[list].filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
</div>
{kind === 'option' && <SubChoices subs={x.sub_choices} parent={x.name} withMultiple={x.multi_select} onChange={subs => set(i, 'sub_choices', subs)} />}
</div>
)
return (
<div>
<Intro text={t(`products.editor.${kind}Hint`)}>
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => addGroup(kind)}>{t('products.editor.addGroup')}</Button>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t(`products.editor.add.${kind}`)}</Button>
</Intro>
{items.length === 0 && <EmptyState compact title={t(`products.editor.none.${kind}`)} />}
<div className="grid gap-2">
{items.map((x, i) => (x.group_id == null ? row(x, i) : null))}
{myGroups.map(g => (
<div key={g.key}>
<GroupHeader group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
onRemove={() => setForm(f => removeGroup(f, g.key))} />
{!folded[g.key] && (
<div className="ml-4 border-l-2 border-accent-soft pl-3 mt-1 grid gap-2">
{items.every(x => x.group_id !== g.key) && <p className="text-caption text-ink-3 py-1">{t('products.editor.emptyGroup')}</p>}
{items.map((x, i) => (x.group_id === g.key ? row(x, i) : null))}
</div>
)}
</div>
))}
</div>
</div>
)
}
function PrefSet({ si, form, setForm, folded, fold, onRemoved }) {
const { t } = useTranslation('manager')
const ps = form.preference_sets[si]
const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference')
const put = fn => setForm(f => ({ ...f, preference_sets: f.preference_sets.map((x, i) => (i === si ? fn(x) : x)) }))
const set = (k, v) => put(x => ({ ...x, [k]: v }))
const setChoice = (ci, k, v) => put(x => ({ ...x, choices: x.choices.map((c, j) => (j === ci ? { ...c, [k]: v } : c)) }))
const shared = ps.shared_subset
return (
<div className="grid gap-4" data-testid="pref-set">
<div className="flex flex-wrap items-center gap-2">
<Input className="flex-1 min-w-40 font-semibold" value={ps.name} onChange={e => set('name', e.target.value)} placeholder={t('products.editor.prefPlaceholder')} autoFocus data-testid="pref-name" />
{prefGroups.length > 0 && (
<Select size="sm" className="w-40" value={ps.group_id ?? ''} onChange={e => set('group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
<option value="">{t('products.editor.noGroup')}</option>
{prefGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
</Select>
)}
<FavouriteToggle on={ps.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'pref', si))} />
<Button size="sm" variant="danger" icon={<Trash2 size={14} />}
onClick={() => { setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, i) => i !== si) })); onRemoved() }}>{t('products.editor.removePref')}</Button>
</div>
{prefGroups.length > 0 && (
<div className="rounded-card bg-accent-soft p-3">
<p className="text-caption font-semibold text-accent-ink">{t('products.editor.prefGroups')}</p>
{prefGroups.map(g => (
<GroupHeader key={g.key} group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
onRemove={() => setForm(f => removeGroup(f, g.key))} />
))}
</div>
)}
<div className="flex flex-wrap gap-5">
<Check checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)}>{t('products.editor.multiChoice')}</Check>
<Check checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)}>{t('products.editor.choiceQuantity')}</Check>
</div>
<p className="text-caption text-ink-3">{t('products.editor.prefLegend')}</p>
<div className="grid gap-2">
{ps.choices.map((c, ci) => (
<div key={ci} className="rounded-card border border-line overflow-hidden" data-testid="pref-choice">
<div className="flex flex-wrap items-center gap-2 p-2.5">
<MoveButtons first={ci === 0} last={ci === ps.choices.length - 1} onUp={() => put(x => moveChoice(x, ci, -1))} onDown={() => put(x => moveChoice(x, ci, 1))} />
<DefaultToggle on={ps.default_choice_index === ci} onClick={() => set('default_choice_index', ps.default_choice_index === ci ? -1 : ci)} />
<Input className="flex-1 min-w-32" value={c.name} onChange={e => setChoice(ci, 'name', e.target.value)} placeholder={t('products.editor.choicePlaceholder')} />
<PriceInput className="w-32" value={c.extra_cost} allowNegative onChange={v => setChoice(ci, 'extra_cost', v)} label={t('products.editor.extraCost')} />
<Check checked={c.is_compact} onChange={v => setChoice(ci, 'is_compact', v)}>{t('products.editor.compact')}</Check>
{shared && <Check checked={c.disables_subset} onChange={v => setChoice(ci, 'disables_subset', v)}>{t('products.editor.hidesShared')}</Check>}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => setChoice(ci, 'sub_choices', [...c.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => put(x => removeChoice(x, ci))}><Trash2 size={14} /></IconButton>
</div>
<SubChoices subs={c.sub_choices} parent={c.name} onChange={subs => setChoice(ci, 'sub_choices', subs)} />
</div>
))}
</div>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} className="justify-self-start" data-testid="add-choice"
onClick={() => put(x => ({ ...x, choices: [...x.choices, { name: '', extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] }))}>{t('products.editor.addChoice')}</Button>
<section className="border-t border-line pt-4 grid gap-3">
<div className="flex items-center justify-between gap-2">
<span className="grid">
<span className="text-label font-semibold text-ink">{t('products.editor.shared')}</span>
<span className="text-caption text-ink-3">{t('products.editor.sharedHint')}</span>
</span>
{shared
? <Button size="sm" variant="danger" onClick={() => set('shared_subset', null)}>{t('products.editor.remove')}</Button>
: <Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('shared_subset', { name: '', choices: [] })}>{t('products.editor.addShared')}</Button>}
</div>
{shared && (
<div className="rounded-card border border-line bg-surface-2 p-3 grid gap-2">
<Input value={shared.name} onChange={e => set('shared_subset', { ...shared, name: e.target.value })} placeholder={t('products.editor.sharedPlaceholder')} aria-label={t('products.editor.sharedName')} />
{shared.choices.map((s, i) => (
<div key={i} className="flex items-center gap-2">
<MoveButtons first={i === 0} last={i === shared.choices.length - 1}
onUp={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, -1) })} onDown={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, 1) })} />
<DefaultToggle on={s.is_default} onClick={() => set('shared_subset', { ...shared, choices: setSub(shared.choices, i, 'is_default', !s.is_default) })} />
<Input className="flex-1" value={s.name} onChange={e => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)) })} />
<PriceInput className="w-32" value={s.extra_cost} allowNegative label={t('products.editor.extraCost')}
onChange={v => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, extra_cost: v } : x)) })} />
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')}
onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)}><Trash2 size={14} /></IconButton>
</div>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
onClick={() => set('shared_subset', { ...shared, choices: [...shared.choices, { name: '', extra_cost: 0, is_default: false }] })}>{t('products.editor.addChoice')}</Button>
</div>
)}
</section>
</div>
)
}
@@ -0,0 +1,81 @@
// The editor's two list fields (plan step 6.3): the product's categories with its main one, and
// its allergens.
import { Star, X } from 'lucide-react'
import { ALLERGENS, nextAllergenLevel, setAllergen } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { IconButton, InfoTip, Select, cx } from '@xenia/ui'
import { categoryTree, treeLabel } from '../productsLogic'
import { addCategory, removeCategory } from './formLogic'
/** The categories it's listed in (shown in each), one of them the main one (tickets, reports). */
export function CategoriesField({ form, setForm, categories }) {
const { t } = useTranslation('manager')
const tree = categoryTree(categories)
const name = id => {
const c = categories.find(x => x.id === id)
if (!c) return `#${id}`
const parent = c.parent_id ? categories.find(x => x.id === c.parent_id) : null
return parent ? `${parent.name} › ${c.name}` : c.name
}
return (
<div className="grid gap-2" data-testid="product-categories">
<span className="flex items-center gap-1 text-label font-semibold text-ink">
{t('products.editor.categories')}
<InfoTip>{t('products.editor.categoriesTip')}</InfoTip>
</span>
{form.category_ids.length === 0 && <span className="text-label text-ink-3">{t('products.editor.noCategory')}</span>}
<ul className="grid gap-1">
{form.category_ids.map(id => {
const main = form.primary_category_id === id
return (
<li key={id} className={cx('flex items-center gap-2 pl-3 pr-1 py-1 rounded-control border', main ? 'border-accent bg-accent-soft' : 'border-line bg-surface')}
data-testid="product-category" data-id={id} data-main={main}>
<span className="flex-1 min-w-0 truncate text-body text-ink">{name(id)}</span>
{main
? <span className="text-caption font-semibold text-accent-ink">{t('products.editor.main')}</span>
: <IconButton size="sm" variant="ghost" label={t('products.editor.makeMain')} onClick={() => setForm(f => ({ ...f, primary_category_id: id }))} data-testid="make-main"><Star size={14} /></IconButton>}
<IconButton size="sm" variant="ghost" label={t('products.editor.removeCategory')} onClick={() => setForm(f => removeCategory(f, id))}><X size={14} /></IconButton>
</li>
)
})}
</ul>
<Select value="" onChange={e => e.target.value && setForm(f => addCategory(f, Number(e.target.value)))} aria-label={t('products.editor.addCategory')} data-testid="add-category">
<option value="">{t('products.editor.addCategory')}</option>
{tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => (
<option key={cat.id} value={cat.id}>{treeLabel(cat, depth)}</option>
))}
</Select>
</div>
)
}
/** The 14 EU allergens; a tap goes none → contains → may contain → none. */
export function AllergensField({ value, onChange }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
return (
<div className="grid gap-2" data-testid="product-allergens">
<span className="flex items-center gap-1 text-label font-semibold text-ink">
{tc('allergens.title')}
<InfoTip>{t('products.editor.allergensTip')}</InfoTip>
</span>
<div className="flex flex-wrap gap-1.5">
{ALLERGENS.map(key => {
const level = value?.[key] ?? null
return (
<button key={key} type="button" onClick={() => onChange(setAllergen(value, key, nextAllergenLevel(level)))}
aria-label={`${tc(`allergens.${key}`)}: ${level ? tc(`allergens.level.${level}`) : t('products.editor.allergenNone')}`}
className={cx('px-2.5 py-1 rounded-full text-label border transition-colors duration-fast',
level === 'contains' ? 'bg-warning-soft text-warning-ink border-warning font-semibold'
: level === 'may_contain' ? 'bg-surface text-ink border-dashed border-line-strong'
: 'bg-surface-2 text-ink-3 border-transparent hover:text-ink')}
data-testid={`allergen-${key}`} data-level={level ?? ''}>
{tc(`allergens.${key}`)}{level === 'may_contain' && ` · ${t('products.editor.traces')}`}
</button>
)
})}
</div>
<span className="text-caption text-ink-3">{t('products.editor.allergensHint')}</span>
</div>
)
}
@@ -0,0 +1,183 @@
// The editor's left side (plan step 6.3): the product itself (name, description, tags, unit,
// price, categories, prep zones, allergens, availability, photo), where it's sold and what the
// customer apps show, its cost, and its fiscal fields (when fiscal receipts are on).
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Plus, Trash2, X } from 'lucide-react'
import { SALES_POINTS } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Field, IconButton, InfoTip, Input, Select, Switch, Textarea, cx } from '@xenia/ui'
import MediaField from '../../media/MediaField'
import { costOf } from '../productsLogic'
import { AllergensField, CategoriesField } from './Fields'
import { UNITS, WEIGHED, cleanTag } from './formLogic'
import { Check, PriceInput } from './parts'
export function InfoTab({ form, set, setForm, categories, prepZones }) {
const { t } = useTranslation('manager')
const service = form.is_service_item
return (
<div className="grid gap-4">
<Switch checked={service} onChange={v => set('is_service_item', v)} label={t('products.editor.serviceItem')}
description={service ? (Number(form.base_price) > 0 ? t('products.editor.servicePaid') : t('products.editor.serviceFree')) : t('products.editor.serviceHint')} />
<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>
{!service && (
<Field label={t('products.editor.description')} hint={t('products.editor.descriptionHint')}>
<Textarea rows={3} value={form.description} onChange={e => set('description', e.target.value)} />
</Field>
)}
{!service && <Tags tags={form.tags} onChange={v => set('tags', v)} />}
{!service && (
<Field label={t('products.editor.unit')} hint={WEIGHED.has(form.unit_type) ? t('products.editor.unitWeighed') : undefined}>
<Select value={form.unit_type} onChange={e => set('unit_type', e.target.value)} 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" />
</Field>
<CategoriesField form={form} setForm={setForm} categories={categories} />
<div className="grid gap-2">
<span className="flex items-center gap-1 text-label font-semibold text-ink">{t('products.editor.prepZones')}<InfoTip>{t('products.editor.prepZonesTip')}</InfoTip></span>
{prepZones.length === 0
? <span className="text-label text-ink-3">{t('products.editor.noZones')} <Link className="underline text-accent-ink" to="/management/prep-zones">{t('products.editor.makeZone')}</Link></span>
: prepZones.map(z => (
<Check key={z.id} checked={form.prep_zone_ids.includes(z.id)}
onChange={on => set('prep_zone_ids', on ? [...form.prep_zone_ids, z.id] : form.prep_zone_ids.filter(id => id !== z.id))}>
<span className="text-body text-ink">{z.name}</span>{z.description && <span className="text-caption text-ink-3"> · {z.description}</span>}
</Check>
))}
</div>
{!service && <AllergensField value={form.allergens} onChange={v => set('allergens', v)} />}
{!service && (<>
<Switch checked={form.is_available} onChange={v => set('is_available', v)} label={t('products.editor.available')} description={t('products.editor.availableHint')} />
<Switch checked={form.quick_add_enabled} onChange={v => set('quick_add_enabled', v)} label={t('products.editor.quickAdd')} description={t('products.editor.quickAddHint')} />
<MediaField value={form.image} onChange={image => set('image', image)} nameAfter={form.name} label={t('media.photo')} testid="product-photo" />
</>)}
</div>
)
}
function Tags({ tags, onChange }) {
const { t } = useTranslation('manager')
const [text, setText] = useState('')
const add = () => { const tag = cleanTag(tags, text); if (tag) onChange([...tags, tag]); setText('') }
return (
<Field label={t('products.editor.tags')} hint={t('products.editor.tagsHint')}>
<div className="grid gap-1.5">
{tags.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{tags.map(tag => (
<span key={tag} className="inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold">
{tag}
<button type="button" onClick={() => onChange(tags.filter(x => x !== tag))} aria-label={t('products.editor.removeTag', { tag })}><X size={12} /></button>
</span>
))}
</div>
)}
<Input value={text} onChange={e => setText(e.target.value)} onBlur={add}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add() } }} placeholder={t('products.editor.tagsPlaceholder')} />
</div>
</Field>
)
}
export function SoldAtTab({ form, set }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const toggle = sp => set('sold_at', form.sold_at.includes(sp) ? form.sold_at.filter(x => x !== sp) : SALES_POINTS.filter(x => x === sp || form.sold_at.includes(x)))
return (
<div className="grid gap-6">
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink">{t('products.editor.soldAt')}</h3>
<p className="text-caption text-ink-3">{t('products.editor.soldAtHint')}</p>
<div className="grid gap-2" data-testid="sold-at">
{SALES_POINTS.map(sp => (
<label key={sp} className="flex items-start gap-3 cursor-pointer select-none">
<input type="checkbox" className="w-4 h-4 mt-0.5 accent-[var(--x-accent)]" checked={form.sold_at.includes(sp)} onChange={() => toggle(sp)} data-testid={`sold-at-${sp}`} />
<span className="grid">
<span className="text-body font-medium text-ink">{tc(`salesPoints.${sp}.name`)}</span>
<span className="text-caption text-ink-3">{tc(`salesPoints.${sp}.hint`)}</span>
</span>
</label>
))}
</div>
<p className="text-caption text-ink-2 rounded-control bg-surface-2 border border-line px-3 py-2">{t('products.editor.pricePerPoint')}</p>
</section>
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink">{t('products.editor.online')}</h3>
<Switch checked={form.digital_available} onChange={v => set('digital_available', v)} label={t('products.editor.orderableNow')} description={t('products.editor.orderableNowHint')} />
</section>
<section className="grid gap-3">
<h3 className="text-label font-semibold text-ink">{t('products.editor.forCustomers')}</h3>
<p className="text-caption text-ink-3">{t('products.editor.forCustomersHint')}</p>
<Field label={t('products.editor.customerName')}><Input value={form.digital_name} onChange={e => set('digital_name', e.target.value)} placeholder={form.name} /></Field>
<Field label={t('products.editor.customerDescription')}><Textarea rows={3} value={form.digital_description} onChange={e => set('digital_description', e.target.value)} /></Field>
<Field label={t('products.editor.customerImage')}><Input value={form.digital_image_url} onChange={e => set('digital_image_url', e.target.value)} placeholder="https://…" /></Field>
</section>
</div>
)
}
export function CostTab({ form, set, setForm }) {
const { t } = useTranslation('manager')
const { formatMoney, formatPercent } = useFormat()
const c = costOf({ base_price: form.base_price, cost_simple: form.cost_mode === 'simple' && form.cost_simple !== '' ? form.cost_simple : null,
cost_breakdown: form.cost_mode === 'detailed' ? form.cost_breakdown : null })
const setLine = (i, k, v) => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.map((x, j) => (j === i ? { ...x, [k]: v } : x)) }))
return (
<div className="grid gap-4">
<p className="text-caption text-ink-3">{t('products.editor.costHint')}</p>
<div className="flex gap-1" role="radiogroup" aria-label={t('products.editor.costMode')}>
{['simple', 'detailed'].map(m => (
<Button key={m} size="sm" variant={form.cost_mode === m ? 'primary' : 'secondary'} role="radio" aria-checked={form.cost_mode === m} onClick={() => set('cost_mode', m)}>
{t(`products.editor.cost.${m}`)}
</Button>
))}
</div>
{form.cost_mode === 'simple' ? (
<Field label={t('products.editor.costPerUnit')}><PriceInput className="w-full" value={form.cost_simple} onChange={v => set('cost_simple', v)} label={t('products.editor.costPerUnit')} /></Field>
) : (
<div className="grid gap-2">
{form.cost_breakdown.map((e, i) => (
<div key={i} className="flex items-center gap-2">
<Input className="flex-1" value={e.label} onChange={ev => setLine(i, 'label', ev.target.value)} placeholder={t('products.editor.costLinePlaceholder')} />
<PriceInput className="w-32" value={e.amount} onChange={v => setLine(i, 'amount', v)} label={t('products.editor.costPerUnit')} />
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
</div>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
onClick={() => setForm(f => ({ ...f, cost_breakdown: [...f.cost_breakdown, { label: '', amount: 0 }] }))}>{t('products.editor.addCostLine')}</Button>
{form.cost_breakdown.length > 0 && c && <span className="text-label text-ink-2">{t('products.editor.costTotal', { total: formatMoney(c.cost) })}</span>}
</div>
)}
{c && c.cost > 0 && (
<p className={cx('text-label font-semibold', c.over ? 'text-danger-ink' : 'text-success-ink')} data-testid="product-margin">
{c.over ? t('products.costOverPrice') : c.margin != null ? t('products.margin', { pct: formatPercent(c.margin, { maxDecimals: 1 }) }) : null}
</p>
)}
</div>
)
}
export function FiscalTab({ form, set, vatGroups }) {
const { t } = useTranslation('manager')
return (
<div className="grid gap-4">
<p className="text-caption rounded-control bg-info-soft text-info-ink px-3 py-2">{t('products.editor.fiscalHint')}</p>
<Field label={t('products.editor.fiscalName')} hint={t('products.editor.fiscalNameHint')}>
<Input className="font-mono uppercase" maxLength={30} value={form.fiscal_name} onChange={e => set('fiscal_name', e.target.value.toUpperCase())} placeholder={form.name.toUpperCase()} />
</Field>
<Field label={t('products.editor.vatGroup')} error={!form.fiscal_vat_group_id ? t('products.editor.vatGroupNeeded') : undefined}>
{vatGroups.length === 0
? <p className="text-label text-warning-ink">{t('products.editor.noVatGroups')}</p>
: <Select value={form.fiscal_vat_group_id ?? ''} onChange={e => set('fiscal_vat_group_id', e.target.value ? Number(e.target.value) : null)}>
<option value="">{t('products.editor.noVatGroup')}</option>
{vatGroups.map(g => <option key={g.machine_id} value={g.machine_id}>{g.machine_id} · {g.friendly_name}</option>)}
</Select>}
</Field>
</div>
)
}
@@ -0,0 +1,61 @@
// The product editor (plan step 6.3, was Management/ProductFormModal): the product on the left
// (its details, where it's sold, cost, fiscal fields), what a waiter can choose on the right
// (ChoicesPanel). A service item (cutlery, a cover charge) has only the left side.
// "Copy" opens a new product filled from this one.
import { useState } from 'react'
import { Copy } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, cx } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import ChoicesPanel from './ChoicesPanel'
import { CostTab, FiscalTab, InfoTab, SoldAtTab } from './InfoTabs'
import { buildBody, buildForm, canSave } from './formLogic'
export default function ProductEditor({ product, categories, prepZones, saving, onSave, onCopy, onClose }) {
const { t } = useTranslation('manager')
const [form, setForm] = useState(() => product._form ?? buildForm(product)) // a copy brings its form
const [left, setLeft] = useState('info')
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
const fiscalOn = settings?.['fiscal.enabled']?.value === 'true'
let vatGroups = []
try { vatGroups = JSON.parse(settings?.['fiscal.vat_groups']?.value || '[]') } catch { vatGroups = [] }
const service = form.is_service_item
const isNew = !product.id
const leftTabs = ['info', ...(service ? [] : ['soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])])]
return (
<Dialog open onClose={onClose} className="!max-w-[min(1280px,96vw)] h-[94vh]" bodyClass="!p-0 flex"
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
footer={<div className="flex items-center gap-2 w-full">
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
<span className="flex-1" />
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
<Button disabled={!canSave(form)} loading={saving} onClick={() => onSave(buildBody(form))} data-testid="product-save">
{isNew ? t('products.editor.create') : t('products.save')}
</Button>
</div>}>
<div className="flex-1 flex flex-col md:flex-row min-h-0 w-full overflow-y-auto md:overflow-hidden" data-testid="product-editor">
<div className={cx('flex flex-col md:min-h-0 border-b md:border-b-0 md:border-r border-line bg-surface-2', service ? 'w-full' : 'w-full md:w-[34%] md:min-w-[22rem]')}>
<div className="flex border-b border-line bg-surface shrink-0 overflow-x-auto" role="tablist">
{leftTabs.map(k => (
<button key={k} type="button" role="tab" aria-selected={left === k} onClick={() => setLeft(k)} data-testid={`editor-tab-${k}`}
className={cx('flex-1 px-3 py-2.5 -mb-px border-b-2 text-label whitespace-nowrap',
left === k ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
{t(`products.editor.left.${k}`)}
</button>
))}
</div>
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
{left === 'soldAt' && <SoldAtTab form={form} set={set} />}
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
</div>
</div>
{!service && <div className="flex flex-1 min-w-0 flex-col min-h-[30rem] md:min-h-0"><ChoicesPanel form={form} setForm={setForm} /></div>}
</div>
</Dialog>
)
}
@@ -0,0 +1,211 @@
// The product editor's form (plan step 6.3): a product → the form, the form → the API body,
// and the edits that touch several lists at once (favourites, choice groups). No React
// (tests/products.test.mjs). The body's shapes are the API's (schemas/product.py).
import { SALES_POINTS } from '@xenia/access/salesPoints'
export const UNITS = ['piece', 'portion', 'kg', 'liter', 'gram', 'ml']
export const WEIGHED = new Set(['kg', 'liter', 'gram', 'ml'])
export const LISTS = { quick: 'quick_options', ingredient: 'ingredients', option: 'options', pref: 'preference_sets' }
const num = v => (v === '' || v == null ? 0 : Number(String(v).replace(',', '.')) || 0)
const sub = s => ({ name: s.name ?? '', extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
export function emptyProduct(preset = {}) {
return { name: '', base_price: '', category_ids: [], primary_category_id: null, is_available: true, lifecycle_status: 'active', ...preset }
}
export function buildForm(p) {
return {
name: p.name ?? '',
description: p.description ?? '',
category_ids: [...(p.category_ids ?? (p.category_id ? [p.category_id] : []))],
primary_category_id: p.primary_category_id ?? p.category_id ?? (p.category_ids?.[0] ?? null),
base_price: p.base_price ?? '',
unit_type: p.unit_type ?? 'piece',
is_available: p.is_available ?? true,
lifecycle_status: p.lifecycle_status ?? 'active',
prep_zone_ids: [...(p.prep_zone_ids ?? [])],
allergens: { ...(p.allergens ?? {}) },
quick_options: (p.quick_options ?? []).map(q => ({
name: q.name, price: q.price ?? 0, allow_multiple: !!q.allow_multiple, is_favorite: !!q.is_favorite,
favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: !!q.is_compact,
})),
options: (p.options ?? []).map(o => ({
name: o.name, extra_cost: o.extra_cost ?? 0, allow_multiple: !!o.allow_multiple, multi_select: !!o.multi_select,
is_compact: !!o.is_compact, sub_choices: (o.sub_choices ?? []).map(sub),
is_favorite: !!o.is_favorite, favorite_sort_order: o.favorite_sort_order ?? 0, group_id: o.group_id ?? null,
})),
ingredients: (p.ingredients ?? []).map(i => ({
name: i.name, extra_cost: i.extra_cost ?? 0, is_favorite: !!i.is_favorite, favorite_sort_order: i.favorite_sort_order ?? 0,
is_compact: !!i.is_compact, group_id: i.group_id ?? null,
})),
preference_sets: (p.preference_sets ?? []).map(ps => ({
name: ps.name,
default_choice_index: ps.choices ? ps.choices.findIndex(c => c.id === ps.default_choice_id) : -1,
choices: (ps.choices ?? []).map(c => ({
name: c.name, extra_cost: c.extra_cost ?? 0, disables_subset: !!c.disables_subset, is_compact: !!c.is_compact,
sub_choices: (c.sub_choices ?? []).map(sub),
})),
group_id: ps.group_id ?? null,
shared_subset: ps.shared_subset ? { name: ps.shared_subset.name ?? '', choices: (ps.shared_subset.choices ?? []).map(sub) } : null,
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,
})),
sold_at: [...(p.sold_at ?? SALES_POINTS)],
digital_available: p.digital_available ?? true,
digital_name: p.digital_name ?? '',
digital_description: p.digital_description ?? '',
digital_image_url: p.digital_image_url ?? '',
image: p.image ?? null,
cost_mode: p.cost_breakdown?.length ? 'detailed' : 'simple',
cost_simple: p.cost_simple ?? '',
cost_breakdown: (p.cost_breakdown ?? []).map(e => ({ label: e.label, amount: e.amount })),
quick_add_enabled: p.quick_add_enabled ?? true,
tags: [...(p.tags ?? [])],
is_service_item: !!p.is_service_item,
fiscal_name: p.fiscal_name ?? '',
fiscal_vat_group_id: p.fiscal_vat_group_id ?? null,
// choice groups (folders) keyed by a form id; the API takes their index
modifier_groups: (p.modifier_groups ?? []).map(g => ({ key: g.id, modifier_type: g.modifier_type, name: g.name })),
}
}
export function buildBody(f) {
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 })
return {
name: f.name.trim(),
description: f.description.trim() || null,
category_ids: f.category_ids,
primary_category_id: f.category_ids.includes(f.primary_category_id) ? f.primary_category_id : (f.category_ids[0] ?? null),
base_price: num(f.base_price),
unit_type: f.unit_type || 'piece',
is_available: f.is_available,
lifecycle_status: f.lifecycle_status,
prep_zone_ids: f.prep_zone_ids,
allergens: f.allergens,
quick_options: f.quick_options.map((q, i) => ({
name: q.name, price: num(q.price), allow_multiple: q.allow_multiple, sort_order: i,
is_favorite: q.is_favorite, favorite_sort_order: q.favorite_sort_order, is_compact: q.is_compact,
})),
modifier_groups: f.modifier_groups.map((g, i) => ({ modifier_type: g.modifier_type, name: g.name, sort_order: i })),
options: f.options.map(o => ({
name: o.name, extra_cost: num(o.extra_cost), allow_multiple: o.allow_multiple, multi_select: o.multi_select,
is_compact: o.is_compact, sub_choices: o.sub_choices.map(subOut),
is_favorite: o.is_favorite, favorite_sort_order: o.favorite_sort_order, group_id: groupIndex(o.group_id),
})),
ingredients: f.ingredients.map(i => ({
name: i.name, extra_cost: num(i.extra_cost), is_favorite: i.is_favorite, favorite_sort_order: i.favorite_sort_order,
is_compact: i.is_compact, group_id: groupIndex(i.group_id),
})),
preference_sets: f.preference_sets.map(ps => ({
name: ps.name,
default_choice_index: ps.default_choice_index >= 0 ? ps.default_choice_index : null,
shared_subset: ps.shared_subset?.choices?.length
? { name: ps.shared_subset.name || '', choices: ps.shared_subset.choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default })) }
: null,
choices: ps.choices.map(c => ({
name: c.name, extra_cost: num(c.extra_cost), disables_subset: c.disables_subset, is_compact: c.is_compact,
sub_choices: c.sub_choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, is_compact: !!s.is_compact })),
})),
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,
})),
sold_at: f.sold_at,
digital_available: f.digital_available,
digital_name: f.digital_name.trim() || null,
digital_description: f.digital_description.trim() || null,
digital_image_url: f.digital_image_url.trim() || null,
cost_simple: f.cost_mode === 'simple' && f.cost_simple !== '' ? num(f.cost_simple) : null,
cost_breakdown: f.cost_mode === 'detailed' && f.cost_breakdown.length
? f.cost_breakdown.map(e => ({ label: e.label, amount: num(e.amount) })) : null,
quick_add_enabled: f.quick_add_enabled,
tags: f.tags,
is_service_item: f.is_service_item,
fiscal_name: f.fiscal_name.trim() || null,
fiscal_vat_group_id: f.fiscal_vat_group_id ? Number(f.fiscal_vat_group_id) : null,
media_id: f.image?.id ?? 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 ──────────────────────────────────────────────────────────────
/** Add a category (the first one becomes the main one). */
export function addCategory(f, id) {
if (f.category_ids.includes(id)) return f
return { ...f, category_ids: [...f.category_ids, id], primary_category_id: f.primary_category_id ?? id }
}
/** Remove a category; when it was the main one, the next listed one takes over. */
export function removeCategory(f, id) {
const ids = f.category_ids.filter(c => c !== id)
return { ...f, category_ids: ids, primary_category_id: f.primary_category_id === id ? (ids[0] ?? null) : f.primary_category_id }
}
// ── favourites: the choices a waiter sees first, across the four lists ────────
export function favourites(f) {
return Object.entries(LISTS).flatMap(([kind, list]) =>
f[list].map((item, idx) => ({ kind, idx, item })).filter(x => x.item.is_favorite))
.sort((a, b) => a.item.favorite_sort_order - b.item.favorite_sort_order)
}
const patch = (f, kind, idx, fields) => ({ ...f, [LISTS[kind]]: f[LISTS[kind]].map((x, i) => (i === idx ? { ...x, ...fields } : x)) })
export function toggleFavourite(f, kind, idx) {
const on = f[LISTS[kind]][idx]?.is_favorite
const last = favourites(f).reduce((m, x) => Math.max(m, x.item.favorite_sort_order), -1)
return patch(f, kind, idx, on ? { is_favorite: false, favorite_sort_order: 0 } : { is_favorite: true, favorite_sort_order: last + 1 })
}
/** Swap a favourite with its neighbour (step -1 / +1). */
export function moveFavourite(f, at, step) {
const list = favourites(f)
const a = list[at]
const b = list[at + step]
if (!a || !b) return f
return patch(patch(f, a.kind, a.idx, { favorite_sort_order: b.item.favorite_sort_order }), b.kind, b.idx, { favorite_sort_order: a.item.favorite_sort_order })
}
// ── list helpers ────────────────────────────────────────────────────────────
export function moveItem(arr, i, step) {
const j = i + step
if (j < 0 || j >= arr.length) return arr
const next = [...arr]
;[next[i], next[j]] = [next[j], next[i]]
return next
}
/** A preference set's choices moved, keeping which one is the default. */
export function moveChoice(ps, i, step) {
const j = i + step
if (j < 0 || j >= ps.choices.length) return ps
const d = ps.default_choice_index
return { ...ps, choices: moveItem(ps.choices, i, step), default_choice_index: d === i ? j : d === j ? i : d }
}
/** A choice removed, the default index following it. */
export function removeChoice(ps, i) {
const d = ps.default_choice_index
return { ...ps, choices: ps.choices.filter((_, k) => k !== i), default_choice_index: d === i ? -1 : d > i ? d - 1 : d }
}
/** Set a field of one sub-choice; marking one as the default unmarks the others. */
export function setSub(subs, i, key, value) {
return subs.map((s, k) => (k === i ? { ...s, [key]: value } : key === 'is_default' && value ? { ...s, is_default: false } : s))
}
/** Remove a choice group: its members go back to "no group". */
export function removeGroup(f, key) {
const free = x => (x.group_id === key ? { ...x, group_id: null } : x)
return { ...f, modifier_groups: f.modifier_groups.filter(g => g.key !== key), options: f.options.map(free), ingredients: f.ingredients.map(free), preference_sets: f.preference_sets.map(free) }
}
/** A tag typed by hand: trimmed, lower case, no commas; null when empty or already there. */
export function cleanTag(tags, text) {
const tag = String(text ?? '').trim().toLowerCase().replace(/,/g, '')
return tag && !tags.includes(tag) ? tag : null
}
@@ -0,0 +1,113 @@
// Small controls of the product editor (plan step 6.3).
import { useState } from 'react'
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, cx } from '@xenia/ui'
/** A price with − / + of 0.10 (negative allowed for choices that lower the price). */
export function PriceInput({ value, onChange, allowNegative = false, className, label, ...rest }) {
const { t } = useTranslation('manager')
const n = Number(String(value ?? '').replace(',', '.')) || 0
const step = d => {
const next = Math.round((n + d) * 100) / 100
onChange(allowNegative ? next : Math.max(0, next))
}
return (
<span className={cx('inline-flex items-stretch rounded-control border border-line bg-surface h-control overflow-hidden', className)}>
<button type="button" className="px-2 text-ink-2 hover:bg-surface-2" onClick={() => step(-0.1)} aria-label={t('products.editor.less')}><Minus size={14} /></button>
<input type="text" inputMode="decimal" value={value ?? ''} onChange={e => onChange(e.target.value)} placeholder="0.00" aria-label={label}
className="w-full min-w-0 text-center text-body bg-transparent outline-none tabular-nums" {...rest} />
<button type="button" className="px-2 text-ink-2 hover:bg-surface-2" onClick={() => step(0.1)} aria-label={t('products.editor.more')}><Plus size={14} /></button>
</span>
)
}
/** ▲ / ▼ to move a row. */
export function MoveButtons({ onUp, onDown, first, last }) {
const { t } = useTranslation('manager')
return (
<span className="flex flex-col shrink-0">
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveUp')} disabled={first} onClick={onUp}><ChevronUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveDown')} disabled={last} onClick={onDown}><ChevronDown size={14} /></IconButton>
</span>
)
}
/** The round "default" marker of a choice. */
export function DefaultToggle({ on, onClick }) {
const { t } = useTranslation('manager')
return (
<button type="button" onClick={onClick} aria-pressed={on} title={t('products.editor.default')} aria-label={t('products.editor.default')}
className={cx('w-6 h-6 shrink-0 rounded-full border-2 grid place-items-center', on ? 'border-accent bg-accent' : 'border-line-strong bg-surface hover:border-accent')}>
{on && <span className="w-2.5 h-2.5 rounded-full bg-accent-fg" />}
</button>
)
}
/** The heart: shown first to the waiter. */
export function FavouriteToggle({ on, onClick }) {
const { t } = useTranslation('manager')
return (
<IconButton size="sm" variant="ghost" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={on} onClick={onClick}
className={on ? 'text-danger' : 'text-ink-3'}>
<Heart size={16} fill={on ? 'currentColor' : 'none'} />
</IconButton>
)
}
/** A small labelled checkbox. */
export function Check({ checked, onChange, children }) {
return (
<label className="inline-flex items-center gap-1.5 text-label text-ink-2 cursor-pointer select-none shrink-0">
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={!!checked} onChange={e => onChange(e.target.checked)} />
{children}
</label>
)
}
/** The sub-choices under a choice ("Syrup" → Caramel, Vanilla). */
export function SubChoices({ subs, parent, onChange, withMultiple = false }) {
const { t } = useTranslation('manager')
if (!subs?.length) return null
const set = (i, k, v) => onChange(subs.map((s, j) => (j === i ? { ...s, [k]: v } : k === 'is_default' && v ? { ...s, is_default: false } : s)))
const move = (i, d) => { const j = i + d; if (j < 0 || j >= subs.length) return; const n = [...subs]; [n[i], n[j]] = [n[j], n[i]]; onChange(n) }
return (
<div className="border-t border-line bg-surface-2 px-3 py-2 grid gap-2">
<p className="text-caption font-semibold text-ink-2">{t('products.editor.subsOf', { name: parent || '…' })}</p>
{subs.map((s, i) => (
<div key={i} className="flex flex-wrap items-center gap-2 pl-4">
<MoveButtons first={i === 0} last={i === subs.length - 1} onUp={() => move(i, -1)} onDown={() => move(i, 1)} />
<DefaultToggle on={s.is_default} onClick={() => set(i, 'is_default', !s.is_default)} />
<Input size="sm" className="flex-1 min-w-28" value={s.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.subPlaceholder')} />
<PriceInput className="w-28" value={s.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
{withMultiple && <Check checked={s.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
<Check checked={s.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
</div>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start ml-4"
onClick={() => onChange([...subs, { name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }])}>{t('products.editor.addSub')}</Button>
</div>
)
}
/** A choice group's header (a folder of choices): fold, rename, remove. */
export function GroupHeader({ group, folded, onFold, onRename, onRemove }) {
const { t } = useTranslation('manager')
const [editing, setEditing] = useState(false)
const [name, setName] = useState(group.name)
return (
<div className="flex items-center gap-1.5 mt-2">
<button type="button" onClick={onFold} aria-expanded={!folded}
className="flex-1 flex items-center gap-2 px-3 py-2 rounded-control bg-accent-soft text-accent-ink text-label font-semibold text-left">
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
{editing
? <input className="flex-1 min-w-0 bg-surface text-ink rounded px-1" autoFocus value={name} onChange={e => setName(e.target.value)}
onClick={e => e.stopPropagation()} onBlur={() => { onRename(name); setEditing(false) }} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
: <span className="flex-1 truncate">{group.name || t('products.editor.unnamedGroup')}</span>}
</button>
<IconButton size="sm" variant="ghost" label={t('products.editor.renameGroup')} onClick={() => { setName(group.name); setEditing(true) }}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('products.editor.removeGroup')} onClick={onRemove}><Trash2 size={14} /></IconButton>
</div>
)
}
@@ -0,0 +1,140 @@
// The products page's arithmetic (plan step 6.3), without React (tests/products.test.mjs).
//
// A product is listed in one or more categories (D-23): `category_ids` (main one first) and
// `categories` [{category_id, sort_order}] = its position in each list. The main category
// (`primary_category_id`) decides tickets and reports. The page shows a product in every
// category it's listed in, and orders each category's list on its own.
import { latin } from '@xenia/i18n/latin'
/** The filters when nothing is filtered. */
export const NO_FILTERS = { priceMin: '', priceMax: '', quality: 'all', unavailableOnly: false, showArchived: false }
export const SCOPES = { all: null, service: '__service__', none: '__uncategorized__', archived: '__archived__' }
const SPECIAL = new Set(Object.values(SCOPES))
export const isCategoryScope = scope => !SPECIAL.has(scope)
const bySort = (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id - b.id
export const topLevel = (categories = []) => categories.filter(c => !c.parent_id).sort(bySort)
export const subsOf = (categories = [], id) => categories.filter(c => c.parent_id === id).sort(bySort)
/** The categories as a tree for pickers: [{cat, depth}] top level first, each followed by its sub-categories. */
export const categoryTree = (categories = []) =>
topLevel(categories).flatMap(c => [{ cat: c, depth: 0 }, ...subsOf(categories, c.id).map(s => ({ cat: s, depth: 1 }))])
/** A category's name in a picker: sub-categories indented under their parent. */
export const treeLabel = (cat, depth) => (depth ? `${String.fromCharCode(160, 160)}↳ ${cat.name}` : cat.name)
export const listedIn = (p, catId) => (p.category_ids ?? []).includes(catId)
export const isArchived = p => p.lifecycle_status === 'archived'
/** Its position in a category's list (falls back to the old global order). */
export function positionIn(p, catId) {
const m = (p.categories ?? []).find(x => x.category_id === catId)
return m ? m.sort_order : (p.sort_order ?? 0)
}
/** How many live products a category lists (a top-level one counts its sub-categories' too, each product once). */
export function countIn(products = [], categories = [], catId) {
const ids = new Set([catId, ...subsOf(categories, catId).map(c => c.id)])
return products.filter(p => !isArchived(p) && (p.category_ids ?? []).some(c => ids.has(c))).length
}
/** The products a scope shows, before filters. */
export function scopeProducts(products = [], categories = [], scope, { showArchived = false } = {}) {
const live = p => showArchived || !isArchived(p)
if (scope === SCOPES.archived) return products.filter(isArchived)
if (scope === SCOPES.service) return products.filter(p => p.is_service_item && !isArchived(p))
if (scope === SCOPES.none) return products.filter(p => !(p.category_ids ?? []).length && !p.is_service_item && !isArchived(p))
if (scope == null) return products.filter(p => !p.is_service_item && live(p))
const ids = new Set([scope, ...subsOf(categories, scope).map(c => c.id)])
return products.filter(p => live(p) && (p.category_ids ?? []).some(c => ids.has(c)))
}
/** Search (accents ignored, Latin letters find Greek names), price range, missing photo / category, unavailable. */
export function applyFilters(list, { search = '', priceMin = null, priceMax = null, quality = 'all', unavailableOnly = false } = {}) {
const fold = v => latin(v).toLowerCase()
const q = fold(search.trim())
return list.filter(p => (!q || fold(p.name).includes(q))
&& (priceMin == null || p.base_price >= priceMin)
&& (priceMax == null || p.base_price <= priceMax)
&& (quality !== 'no-photo' || !p.image_url)
&& (quality !== 'no-cat' || !(p.category_ids ?? []).length)
&& (!unavailableOnly || !p.is_available))
}
/**
* The list in groups, each a category's list in its own order:
* all products → by main category (each product once);
* a top-level category → itself and each sub-category (a product listed in two shows in both);
* `sub` narrows it to one of them;
* a sub-category → that list; the special scopes → one group without a category.
* Each group: { key (category id or '__none__'), cat, items }.
*/
export function groupProducts(list, categories = [], scope, sub = null) {
const catOf = id => categories.find(c => c.id === id) ?? null
const make = (key, items) => {
const cat = key === '__none__' ? null : catOf(key)
return { key, cat, items: [...items].sort((a, b) => (key === '__none__' ? bySort(a, b) : positionIn(a, key) - positionIn(b, key) || a.id - b.id)) }
}
if (!isCategoryScope(scope) && scope !== null) return list.length ? [make('__none__', list)] : []
if (scope === null) {
const groups = new Map()
for (const p of list) {
const key = p.primary_category_id ?? '__none__'
if (!groups.has(key)) groups.set(key, [])
groups.get(key).push(p)
}
const order = new Map(categoryTree(categories).map(({ cat }, i) => [cat.id, i]))
return [...groups.entries()].map(([k, items]) => make(k, items))
.sort((a, b) => (order.get(a.key) ?? 1e9) - (order.get(b.key) ?? 1e9))
}
const keys = [scope, ...subsOf(categories, scope).map(c => c.id)].filter(k => sub == null || k === sub)
return keys.map(k => make(k, list.filter(p => listedIn(p, k)))).filter(g => g.items.length)
}
/** Move `fromId` before/after `toId` in a group: the body for PUT /api/products/reorder (per category). */
export function reorderBody(group, fromId, toId, after = false) {
const items = group.items.filter(p => p.id !== fromId)
const moved = group.items.find(p => p.id === fromId)
if (!moved || fromId === toId) return null
const at = items.findIndex(p => p.id === toId)
if (at < 0) return null
items.splice(after ? at + 1 : at, 0, moved)
const category_id = group.key === '__none__' ? null : group.key
return items.map((p, i) => ({ id: p.id, sort_order: i, ...(category_id != null ? { category_id } : {}) }))
}
/** One step up (-1) or down (+1) in a group; null at the ends. */
export function stepBody(group, id, step) {
const i = group.items.findIndex(p => p.id === id)
const j = i + step
if (i < 0 || j < 0 || j >= group.items.length) return null
return reorderBody(group, id, group.items[j].id, step > 0)
}
/** Reorder ids: move `fromId` to where `toId` is. */
export function moveId(ids, fromId, toId) {
const from = ids.indexOf(fromId)
const to = ids.indexOf(toId)
if (from < 0 || to < 0 || from === to) return null
const next = [...ids]
next.splice(to, 0, next.splice(from, 1)[0])
return next
}
/** What it costs the venue (the breakdown's sum, else the simple cost) and the margin; null without a cost. */
export function costOf(p) {
const cost = p.cost_breakdown?.length ? p.cost_breakdown.reduce((s, e) => s + (Number(e.amount) || 0), 0)
: (p.cost_simple ?? null)
if (cost == null || cost === '') return null
const price = Number(p.base_price) || 0
return { cost: Number(cost), over: Number(cost) > price, margin: price > 0 ? (price - cost) / price : null }
}
/** A product's categories after a bulk change: 'move' = only that one, 'add' = also that one. */
export function bulkCategories(p, catId, mode) {
if (mode === 'move') return { category_ids: [catId], primary_category_id: catId }
const ids = [...new Set([...(p.category_ids ?? []), catId])]
return { category_ids: ids, primary_category_id: p.primary_category_id ?? catId }
}
+111
View File
@@ -0,0 +1,111 @@
// The products page: categories, per-category order, filters and the editor's form (plan step 6.3).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
SCOPES, applyFilters, bulkCategories, categoryTree, costOf, countIn, groupProducts, moveId, reorderBody, scopeProducts, stepBody, treeLabel,
} from '../src/pages/products/productsLogic.js'
import { addCategory, buildBody, buildForm, canSave, cleanTag, favourites, moveChoice, moveFavourite, removeCategory, removeChoice, removeGroup, setSub, toggleFavourite } from '../src/pages/products/editor/formLogic.js'
const cats = [
{ id: 1, name: 'Coffees', sort_order: 0 },
{ id: 2, name: 'Breakfast', sort_order: 1 },
{ id: 3, name: 'Hot', parent_id: 1, sort_order: 0 },
]
const prod = (id, name, ids, positions = {}, o = {}) => ({
id, name, base_price: 3, is_available: true, lifecycle_status: 'active', category_ids: ids, primary_category_id: ids[0] ?? null,
categories: ids.map(c => ({ category_id: c, sort_order: positions[c] ?? 0 })), ...o,
})
const freddo = prod(10, 'Freddo', [1, 2], { 1: 0, 2: 5 })
const toast = prod(11, 'Τοστ', [2], { 2: 1 })
const latte = prod(12, 'Latte', [3], { 3: 0 }, { base_price: 4.5, image_url: '/x' })
const old = prod(13, 'Old', [1], {}, { lifecycle_status: 'archived' })
const fork = prod(14, 'Fork', [], {}, { is_service_item: true })
const loose = prod(15, 'Loose', [])
const all = [freddo, toast, latte, old, fork, loose]
test('the tree, counts and scopes follow every listing', () => {
assert.deepEqual(categoryTree(cats).map(x => [x.cat.id, x.depth]), [[1, 0], [3, 1], [2, 0]])
assert.equal(treeLabel(cats[2], 1).endsWith('↳ Hot'), true)
assert.equal(countIn(all, cats, 1), 2) // freddo + latte (sub), not the archived one
assert.equal(countIn(all, cats, 2), 2) // freddo also counts here
assert.deepEqual(scopeProducts(all, cats, 2).map(p => p.id), [10, 11])
assert.deepEqual(scopeProducts(all, cats, 1).map(p => p.id), [10, 12])
assert.deepEqual(scopeProducts(all, cats, 1, { showArchived: true }).map(p => p.id), [10, 12, 13])
assert.deepEqual(scopeProducts(all, cats, SCOPES.service).map(p => p.id), [14])
assert.deepEqual(scopeProducts(all, cats, SCOPES.none).map(p => p.id), [15])
assert.deepEqual(scopeProducts(all, cats, SCOPES.archived).map(p => p.id), [13])
assert.deepEqual(scopeProducts(all, cats, SCOPES.all).map(p => p.id), [10, 11, 12, 15])
})
test('filters: search ignores accents and finds Greek names in Latin letters', () => {
const list = scopeProducts(all, cats, SCOPES.all)
assert.deepEqual(applyFilters(list, { search: 'tost' }).map(p => p.id), [11])
assert.deepEqual(applyFilters(list, { search: 'ΤΟΣΤ' }).map(p => p.id), [11])
assert.deepEqual(applyFilters(list, { priceMin: 4 }).map(p => p.id), [12])
assert.deepEqual(applyFilters(list, { quality: 'no-photo' }).map(p => p.id), [10, 11, 15])
assert.deepEqual(applyFilters(list, { quality: 'no-cat' }).map(p => p.id), [15])
})
test('groups: each category its own list in its own order; a product in two shows in both', () => {
const inBreakfast = groupProducts(scopeProducts(all, cats, 2), cats, 2)
assert.deepEqual(inBreakfast.map(g => [g.key, g.items.map(p => p.id)]), [[2, [11, 10]]]) // toast 1, freddo 5
const coffees = groupProducts(scopeProducts(all, cats, 1), cats, 1)
assert.deepEqual(coffees.map(g => [g.key, g.items.map(p => p.id)]), [[1, [10]], [3, [12]]])
assert.deepEqual(groupProducts(scopeProducts(all, cats, 1), cats, 1, 3).map(g => g.key), [3])
const everything = groupProducts(scopeProducts(all, cats, SCOPES.all), cats, SCOPES.all)
assert.deepEqual(everything.map(g => [g.key, g.items.map(p => p.id)]), [[1, [10]], [3, [12]], [2, [11]], ['__none__', [15]]]) // by main category
})
test('reordering sends positions for that category only', () => {
const g = groupProducts(scopeProducts(all, cats, 2), cats, 2)[0] // [toast, freddo]
assert.deepEqual(reorderBody(g, 10, 11), [{ id: 10, sort_order: 0, category_id: 2 }, { id: 11, sort_order: 1, category_id: 2 }])
assert.deepEqual(stepBody(g, 11, 1), [{ id: 10, sort_order: 0, category_id: 2 }, { id: 11, sort_order: 1, category_id: 2 }])
assert.equal(stepBody(g, 11, -1), null)
assert.deepEqual(reorderBody({ key: '__none__', items: [loose, fork] }, 14, 15), [{ id: 14, sort_order: 0 }, { id: 15, sort_order: 1 }])
assert.deepEqual(moveId([1, 2, 3], 3, 1), [3, 1, 2])
assert.equal(moveId([1, 2], 1, 1), null)
})
test('cost, margin and bulk categories', () => {
assert.deepEqual(costOf({ base_price: 4, cost_simple: 1 }), { cost: 1, over: false, margin: 0.75 })
assert.equal(costOf({ base_price: 4, cost_breakdown: [{ amount: 3 }, { amount: 2 }] }).over, true)
assert.equal(costOf({ base_price: 4 }), null)
assert.deepEqual(bulkCategories(freddo, 3, 'move'), { category_ids: [3], primary_category_id: 3 })
assert.deepEqual(bulkCategories(freddo, 3, 'add'), { category_ids: [1, 2, 3], primary_category_id: 1 })
assert.deepEqual(bulkCategories(loose, 2, 'add'), { category_ids: [2], primary_category_id: 2 })
})
test('the editor keeps categories, the main one and allergens', () => {
const f = buildForm({ ...freddo, allergens: { milk: 'contains' }, primary_category_id: 2 })
assert.deepEqual([f.category_ids, f.primary_category_id], [[1, 2], 2])
let g = removeCategory(f, 2)
assert.deepEqual([g.category_ids, g.primary_category_id], [[1], 1]) // the main one went: the next takes over
g = addCategory(removeCategory(g, 1), 3)
assert.deepEqual([g.category_ids, g.primary_category_id], [[3], 3]) // the first one becomes main
const body = buildBody({ ...f, base_price: '3,5' })
assert.deepEqual([body.category_ids, body.primary_category_id, body.base_price, body.allergens], [[1, 2], 2, 3.5, { milk: 'contains' }])
assert.equal(canSave({ ...f, name: ' ' }), false)
assert.equal(canSave({ ...f, base_price: '' }), false)
assert.equal(canSave({ ...f, base_price: '', is_service_item: true }), true)
assert.equal(cleanTag(['vegan'], ' Spicy, '), 'spicy')
assert.equal(cleanTag(['vegan'], 'VEGAN'), null)
})
test('the editor: favourites across lists, choices, groups', () => {
let f = buildForm({ name: 'X', base_price: 1, quick_options: [{ name: 'Bacon' }], ingredients: [{ name: 'Onion', group_id: 7 }],
options: [], preference_sets: [{ name: 'Sugar', default_choice_id: 2, choices: [{ id: 1, name: 'None' }, { id: 2, name: 'Medium' }, { id: 3, name: 'Sweet' }] }],
modifier_groups: [{ id: 7, modifier_type: 'ingredient', name: 'Veg' }] })
f = toggleFavourite(toggleFavourite(f, 'ingredient', 0), 'quick', 0)
assert.deepEqual(favourites(f).map(x => x.item.name), ['Onion', 'Bacon'])
f = moveFavourite(f, 1, -1)
assert.deepEqual(favourites(f).map(x => x.item.name), ['Bacon', 'Onion'])
const ps = f.preference_sets[0]
assert.equal(ps.default_choice_index, 1)
assert.equal(moveChoice(ps, 1, 1).default_choice_index, 2) // the default follows its choice
assert.equal(removeChoice(ps, 0).default_choice_index, 0)
assert.equal(removeChoice(ps, 1).default_choice_index, -1)
assert.deepEqual(setSub([{ is_default: true }, { is_default: false }], 1, 'is_default', true).map(s => s.is_default), [false, true])
const body = buildBody(f)
assert.equal(body.ingredients[0].group_id, 0) // the group's index in modifier_groups
assert.equal(buildBody(removeGroup(f, 7)).ingredients[0].group_id, null)
})
+1 -1
View File
@@ -14,7 +14,7 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const v2 = JSON.parse(readFileSync(path.join(ROOT, 'v2.json'), 'utf8'))
const DATA = new Set([
'src/pages/signage/signageLogic.js', 'src/pages/signage/SignageFields.jsx', 'src/pages/signage/SlideEditor.jsx',
'src/pages/signage/MenuEditor.jsx', 'src/pages/platform/DeviceConfigFields.jsx',
'src/pages/signage/MenuEditor.jsx', 'src/pages/platform/DeviceConfigFields.jsx', 'src/pages/products/categoryColours.js',
])
const GREEK = /[Ͱ-Ͽἀ-῿]/
const COLOUR = [
+2 -2
View File
@@ -1,9 +1,9 @@
{
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks"
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products"
],
"strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks"
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products"
]
}
+3 -1
View File
@@ -6,7 +6,9 @@
"description": "Bootstrap provider, module/permission hooks and guards, and the manager-approval dialog (plan step 2.5).",
"main": "src/index.js",
"exports": {
".": "./src/index.js"
".": "./src/index.js",
"./salesPoints": "./src/salesPoints.js",
"./allergens": "./src/allergens.js"
},
"dependencies": {
"@xenia/api": "^0.0.0",
+33
View File
@@ -0,0 +1,33 @@
// A product's allergens for staff and guests (plan step 6.3): one small chip each, what it
// contains first (warning tone), then what it may contain (outlined), under a title. Styled with
// the @xenia/ui tokens inline, so every app (waiter, terminal, manager) shows it the same way.
// Nothing when none are declared, unless `showNone`.
import { useTranslation } from '@xenia/i18n'
import { allergenList } from './allergens.js'
const chip = level => ({
display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px',
borderRadius: 999, fontSize: 'var(--x-text-caption)', fontWeight: 600, lineHeight: 1.6,
...(level === 'contains'
? { background: 'var(--x-warning-soft)', color: 'var(--x-warning-ink)', border: '1px solid transparent' }
: { background: 'transparent', color: 'var(--x-ink-2)', border: '1px dashed var(--x-line-strong)' }),
})
export function Allergens({ allergens, showNone = false, title = true, className, style }) {
const { t } = useTranslation('common')
const items = allergenList(allergens)
if (items.length === 0 && !showNone) return null
const groups = ['contains', 'may_contain'].map(level => [level, items.filter(i => i.level === level)]).filter(([, list]) => list.length)
return (
<div className={className} style={{ display: 'grid', gap: 6, ...style }} data-testid="allergens" data-count={items.length}>
{title && <div style={{ fontSize: 'var(--x-text-caption)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--x-ink-3)' }}>{t('allergens.title')}</div>}
{items.length === 0 && <div style={{ fontSize: 'var(--x-text-label)', color: 'var(--x-ink-3)' }}>{t('allergens.none')}</div>}
{groups.map(([level, list]) => (
<div key={level} style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 4 }}>
<span style={{ fontSize: 'var(--x-text-caption)', color: 'var(--x-ink-2)', marginRight: 2 }}>{t(`allergens.level.${level}`)}:</span>
{list.map(i => <span key={i.key} style={chip(level)} data-allergen={i.key} data-level={level}>{t(`allergens.${i.key}`)}</span>)}
</div>
))}
</div>
)
}
+27
View File
@@ -0,0 +1,27 @@
// Allergens (plan step 6.3): the 14 that EU Regulation 1169/2011 (Annex II) requires a venue to
// declare. The same fixed list and order as the backend's core/allergens.py (a backend test
// compares them). A product carries `allergens` = { key: 'contains' | 'may_contain' }.
// Labels: common:allergens.<key>, common:allergens.level.<level>.
export const ALLERGENS = ['gluten', 'crustaceans', 'eggs', 'fish', 'peanuts', 'soybeans', 'milk', 'nuts', 'celery', 'mustard', 'sesame', 'sulphites', 'lupin', 'molluscs']
export const ALLERGEN_LEVELS = ['contains', 'may_contain']
/** A product's allergens as a list to show: what it contains first, then traces; list order within each. */
export function allergenList(map) {
const m = map && typeof map === 'object' ? map : {}
return ALLERGEN_LEVELS.flatMap(level => ALLERGENS.filter(k => m[k] === level).map(key => ({ key, level })))
}
/** The next level when a manager taps an allergen: none → contains → may contain → none. */
export function nextAllergenLevel(level) {
return level === 'contains' ? 'may_contain' : level === 'may_contain' ? null : 'contains'
}
/** Set (or with null, clear) one allergen; a new object in the list's order. */
export function setAllergen(map, key, level) {
const out = {}
for (const k of ALLERGENS) {
const v = k === key ? level : map?.[k]
if (v) out[k] = v
}
return out
}
+3
View File
@@ -9,6 +9,7 @@
// <Can perm="…" fallback={…}> · <RequireModule module="…">
//
// SALES_POINTS, IN_PERSON, DIGITAL where an order is sold (phase 3S)
// ALLERGENS, allergenList, setAllergen the 14 EU allergens (6.3)
//
// UI hiding only: the backend checks every request (CS-14).
@@ -17,3 +18,5 @@ export { useAccess, useModule, useCan, can, useAllowed, allowed } from './hooks.
export { Can, RequireModule, ModuleOff, NoAccess } from './guards.jsx'
export { OverrideHost } from './OverrideHost.jsx'
export { SALES_POINTS, IN_PERSON, DIGITAL, normalizeSalesPoints } from './salesPoints.js'
export { ALLERGENS, ALLERGEN_LEVELS, allergenList, nextAllergenLevel, setAllergen } from './allergens.js'
export { Allergens } from './Allergens.jsx'
+23
View File
@@ -0,0 +1,23 @@
// The allergen list and its helpers (plan step 6.3).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { ALLERGENS, allergenList, nextAllergenLevel, setAllergen } from '../src/allergens.js'
test('the 14 EU allergens', () => {
assert.equal(ALLERGENS.length, 14)
assert.equal(new Set(ALLERGENS).size, 14)
})
test('what to show: contains first, then traces, in the list order', () => {
assert.deepEqual(allergenList({ sesame: 'may_contain', milk: 'contains', gluten: 'contains', pollen: 'contains' }),
[{ key: 'gluten', level: 'contains' }, { key: 'milk', level: 'contains' }, { key: 'sesame', level: 'may_contain' }])
assert.deepEqual(allergenList(null), [])
})
test('tapping cycles none → contains → may contain → none', () => {
assert.equal(nextAllergenLevel(undefined), 'contains')
assert.equal(nextAllergenLevel('contains'), 'may_contain')
assert.equal(nextAllergenLevel('may_contain'), null)
assert.deepEqual(setAllergen({ milk: 'contains' }, 'gluten', 'may_contain'), { gluten: 'may_contain', milk: 'contains' })
assert.deepEqual(setAllergen({ milk: 'contains' }, 'milk', null), {})
})
+22
View File
@@ -76,5 +76,27 @@
"name": "Online, με κράτηση",
"hint": "Κράτηση online, το φαγητό έτοιμο με την άφιξη"
}
},
"allergens": {
"title": "Αλλεργιογόνα",
"none": "Δεν έχουν δηλωθεί αλλεργιογόνα",
"level": {
"contains": "Περιέχει",
"may_contain": "Μπορεί να περιέχει"
},
"gluten": "Γλουτένη",
"crustaceans": "Καρκινοειδή",
"eggs": "Αυγά",
"fish": "Ψάρια",
"peanuts": "Αράπικα φιστίκια",
"soybeans": "Σόγια",
"milk": "Γάλα",
"nuts": "Ξηροί καρποί",
"celery": "Σέλινο",
"mustard": "Μουστάρδα",
"sesame": "Σουσάμι",
"sulphites": "Θειώδη",
"lupin": "Λούπινο",
"molluscs": "Μαλάκια"
}
}
+2 -1
View File
@@ -115,7 +115,8 @@
"nest_has_children": "Κατηγορία με υποκατηγορίες δεν μπαίνει κάτω από άλλη.",
"too_deep": "Οι κατηγορίες έχουν το πολύ δύο επίπεδα.",
"own_parent": "Μια κατηγορία δεν μπορεί να είναι γονέας του εαυτού της.",
"group_not_found": "Η ομάδα επιλογών δεν βρέθηκε."
"group_not_found": "Η ομάδα επιλογών δεν βρέθηκε.",
"allergen": "Άγνωστο αλλεργιογόνο ή επίπεδο: {{allergen}}."
},
"system": {
"log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}."
+280
View File
@@ -1523,5 +1523,285 @@
"forceClose": "Αναγκαστικό κλείσιμο",
"closeNow": "Κλείσε ημέρα"
}
},
"products": {
"title": "Προϊόντα",
"categories": "Κατηγορίες",
"searchCategories": "Αναζήτηση κατηγορίας…",
"clear": "Καθαρισμός",
"service": "Service",
"all": "Όλα τα προϊόντα",
"allOf": "Όλα",
"uncategorized": "Χωρίς κατηγορία",
"archived": "Αρχειοθετημένα",
"archivedBadge": "Αρχείο",
"search": "Αναζήτηση… (και με λατινικούς χαρακτήρες)",
"filters": "Φίλτρα",
"view": "Προβολή",
"view_list": "Λίστα",
"view_grid": "Πλέγμα",
"new": "Νέο προϊόν",
"price": "Τιμή",
"from": "από",
"to": "έως",
"quality": "Ποιότητα δεδομένων",
"qualityOf": {
"all": "Όλα",
"no-photo": "Χωρίς φωτό",
"no-cat": "Χωρίς κατηγορία"
},
"show": "Εμφάνιση",
"unavailableOnly": "Μόνο μη διαθέσιμα",
"withArchived": "Και αρχειοθετημένα",
"clearFilters": "Καθαρισμός",
"clearSelection": "Καθαρισμός επιλογής",
"selected_one": "{{count}} επιλεγμένο",
"selected_other": "{{count}} επιλεγμένα",
"selectAll": "Επιλογή όλων",
"select": "Επιλογή: {{name}}",
"totals": "{{active}} ενεργά · {{categories}} κατηγορίες · {{archived}} αρχείο",
"none": "Δεν βρέθηκαν προϊόντα",
"noneHint": "Δοκιμάστε διαφορετικά φίλτρα ή προσθέστε νέο προϊόν.",
"makeAvailable": "Διαθέσιμα",
"makeUnavailable": "Μη διαθέσιμα",
"archive": "Αρχειοθέτηση",
"delete": "Οριστική διαγραφή",
"prepZone": "Ζώνη προετοιμασίας",
"toCategory": "Κατηγορία",
"updated_one": "{{count}} προϊόν ενημερώθηκε",
"updated_other": "{{count}} προϊόντα ενημερώθηκαν",
"available": "Διαθέσιμο",
"unavailable": "Μη διαθέσιμο",
"edit": "Επεξεργασία",
"moveUp": "Μετακίνηση πάνω",
"moveDown": "Μετακίνηση κάτω",
"main": "κύρια",
"mainHere": "Κύρια κατηγορία του",
"alsoIn": "και στο {{name}}",
"hasAllergens": "Έχουν δηλωθεί αλλεργιογόνα",
"allergenCount_one": "{{count}} αλλεργιογόνο",
"allergenCount_other": "{{count}} αλλεργιογόνα",
"costOverPrice": "Κόστος > τιμή",
"margin": "περιθώριο {{pct}}",
"cancel": "Άκυρο",
"save": "Αποθήκευση",
"saved": "Αποθηκεύτηκε",
"apply": "Εφαρμογή",
"copyOf": "{{name}} (αντίγραφο)",
"unit": {
"piece": "Τεμάχιο",
"portion": "Μερίδα",
"kg": "Κιλό (kg)",
"liter": "Λίτρο (L)",
"gram": "Γραμμάριο (g)",
"ml": "Χιλιοστόλιτρο (mL)"
},
"category": {
"new": "Νέα κατηγορία",
"newSub": "Νέα υποκατηγορία",
"edit": "Επεξεργασία κατηγορίας",
"editSub": "Επεξεργασία υποκατηγορίας",
"delete": "Διαγραφή κατηγορίας",
"under": "Κατηγορία: {{name}}",
"name": "Όνομα",
"colour": "Χρώμα",
"saved": "Η κατηγορία αποθηκεύτηκε",
"moveTitle": "Μετακίνηση κατηγορίας",
"moving": "Κατηγορία: {{name}}",
"newPlace": "Νέα θέση",
"topLevel": "Κορυφαίο επίπεδο (ανεξάρτητη)",
"move": "Μετακίνηση",
"moved": "Η κατηγορία μετακινήθηκε"
},
"confirm": {
"category": "Διαγραφή της κατηγορίας «{{name}}»;",
"archive": "Αρχειοθέτηση του «{{name}}»;",
"delete": "Οριστική διαγραφή του «{{name}}»;",
"bulkArchive_one": "Αρχειοθέτηση {{count}} προϊόντος;",
"bulkArchive_other": "Αρχειοθέτηση {{count}} προϊόντων;"
},
"confirmBody": {
"category": "Τα προϊόντα της μένουν· όσα ήταν μόνο σε αυτή μένουν χωρίς κατηγορία.",
"archive": "Φεύγει από τα μενού και κρατιέται για το ιστορικό. Επανέρχεται από το αρχείο.",
"delete": "Χάνεται μόνιμα. Ένα προϊόν που έχει παραγγελθεί ποτέ μπορεί μόνο να αρχειοθετηθεί.",
"bulkArchive": "Φεύγουν από τα μενού και κρατιούνται για το ιστορικό."
},
"confirmButton": {
"category": "Διαγραφή",
"archive": "Αρχειοθέτηση",
"delete": "Διαγραφή",
"bulkArchive": "Αρχειοθέτηση"
},
"done": {
"category": "Η κατηγορία διαγράφηκε",
"archive": "Αρχειοθετήθηκε",
"delete": "Διαγράφηκε",
"bulkArchive": "Αρχειοθετήθηκαν"
},
"bulkZones": {
"title": "Ζώνες προετοιμασίας",
"body_one": "Θα οριστεί σε {{count}} προϊόν.",
"body_other": "Θα οριστεί σε {{count}} προϊόντα.",
"done_one": "Ζώνες προετοιμασίας ορίστηκαν σε {{count}} προϊόν",
"done_other": "Ζώνες προετοιμασίας ορίστηκαν σε {{count}} προϊόντα"
},
"bulkCategory": {
"title": "Κατηγορία",
"body_one": "Για {{count}} προϊόν.",
"body_other": "Για {{count}} προϊόντα.",
"move": "Μετακίνηση σε",
"moveHint": "Γίνεται η μόνη (και κύρια) κατηγορία τους.",
"add": "Και στην κατηγορία",
"addHint": "Προστίθεται σε όσες έχουν· η κύρια μένει ίδια.",
"which": "Επιλέξτε κατηγορία…",
"done_one": "{{count}} προϊόν ενημερώθηκε",
"done_other": "{{count}} προϊόντα ενημερώθηκαν"
},
"editor": {
"newTitle": "Νέο προϊόν",
"editTitle": "Επεξεργασία: {{name}}",
"copy": "Αντιγραφή",
"create": "Δημιουργία",
"left": {
"info": "Πληροφορίες",
"soldAt": "Πού πωλείται",
"cost": "Κόστος",
"fiscal": "Ταμειακή"
},
"serviceItem": "Service item",
"serviceHint": "Μαχαιροπίρουνα, ποτήρια, κουβέρ: τυπώνεται σε ξεχωριστή ενότητα SERVICE.",
"servicePaid": "Τυπώνεται σε ξεχωριστή ενότητα SERVICE. Καταγράφεται στα έσοδα.",
"serviceFree": "Τυπώνεται μία φορά: δεν αποθηκεύεται στην παραγγελία, δεν καταγράφεται στα έσοδα.",
"name": "Όνομα",
"namePlaceholder": "π.χ. Espresso",
"servicePlaceholder": "π.χ. Σερβίτσιο",
"description": "Περιγραφή (προαιρετική)",
"descriptionHint": "Χρήσιμο για ψηφιακό μενού ή ενημέρωση σερβιτόρων.",
"tags": "Tags (προαιρετικά)",
"tagsHint": "Πάτα Enter ή κόμμα για να προσθέσεις tag.",
"tagsPlaceholder": "π.χ. vegan, πικάντικο",
"removeTag": "Αφαίρεση {{tag}}",
"unit": "Μονάδα μέτρησης",
"unitWeighed": "Η ποσότητα θα εισάγεται ως δεκαδικός αριθμός στην εφαρμογή σερβιτόρων.",
"price": "Βασική τιμή",
"priceOptional": "Τιμή (προαιρετική)",
"less": "Λιγότερο",
"more": "Περισσότερο",
"categories": "Κατηγορίες",
"categoriesTip": "Ένα προϊόν μπορεί να είναι σε πολλές κατηγορίες (ένας freddo στους Καφέδες και στο Πρωινό)· εμφανίζεται σε καθεμία και κάθε λίστα έχει τη δική της σειρά. Η κύρια ορίζει πού τυπώνεται στα δελτία και πώς το ομαδοποιούν οι αναφορές.",
"noCategory": "Δεν είναι ακόμα σε κατηγορία.",
"main": "Κύρια",
"makeMain": "Ορισμός ως κύρια κατηγορία",
"removeCategory": "Αφαίρεση από την κατηγορία",
"addCategory": "Προσθήκη κατηγορίας…",
"prepZones": "Ζώνες προετοιμασίας",
"prepZonesTip": "Πού ετοιμάζεται: τα δελτία του τυπώνονται στους εκτυπωτές αυτών των ζωνών και εμφανίζονται στις οθόνες κουζίνας τους.",
"noZones": "Δεν υπάρχουν ζώνες.",
"makeZone": "Δημιουργήστε μια ζώνη",
"allergensTip": "Τα 14 αλλεργιογόνα που ο κανονισμός ΕΕ 1169/2011 ζητά να δηλώνονται. Το «Μπορεί να περιέχει» είναι για ίχνη, π.χ. ίδια κουζίνα. Εμφανίζονται στα κινητά των σερβιτόρων, στο ταμείο, στα tablet μενού και στα online μενού.",
"allergensHint": "Ένα πάτημα: περιέχει · δύο: μπορεί να περιέχει · ξανά: τίποτα.",
"allergenNone": "δεν δηλώθηκε",
"traces": "ίχνη",
"available": "Διαθέσιμο",
"availableHint": "Ανενεργό: δεν παραγγέλνεται τώρα (εξαντλήθηκε)· μένει στα μενού.",
"quickAdd": "Quick Add",
"quickAddHint": "Ο σερβιτόρος το προσθέτει με ένα πάτημα, χωρίς την οθόνη επιλογών.",
"soldAt": "Πού πωλείται",
"soldAtHint": "Όπου δεν είναι επιλεγμένο, το προϊόν δεν εμφανίζεται και δεν γίνεται δεκτό σε παραγγελίες.",
"pricePerPoint": "Διαφορετική τιμή ανά σημείο πώλησης (π.χ. φθηνότερο σε πακέτο): Τιμολόγηση → Τροποποιητές, με συνθήκη «Κανάλι παραγγελίας».",
"online": "QR μενού και online",
"orderableNow": "Διαθέσιμο για παραγγελία τώρα",
"orderableNowHint": "Ανενεργό: εμφανίζεται ως «Εξαντλήθηκε».",
"forCustomers": "Εμφάνιση στους πελάτες",
"forCustomersHint": "Αφήστε κενό για να χρησιμοποιηθούν τα στοιχεία του προϊόντος.",
"customerName": "Όνομα",
"customerDescription": "Περιγραφή",
"customerImage": "Διεύθυνση εικόνας",
"costHint": "Το κόστος καταγράφεται σε κάθε παραγγελία για τον υπολογισμό κέρδους.",
"costMode": "Τύπος κόστους",
"cost": {
"simple": "Απλό",
"detailed": "Ανάλυση"
},
"costPerUnit": "Κόστος ανά μονάδα",
"costLinePlaceholder": "π.χ. Γάλα",
"addCostLine": "Γραμμή κόστους",
"costTotal": "Σύνολο {{total}}",
"fiscalHint": "Τα πεδία αυτά χρησιμοποιούνται κατά την αυτόματη αποστολή αποδείξεων στη ΦΗΜ.",
"fiscalName": "Όνομα ΦΗΜ (προαιρετικό)",
"fiscalNameHint": "Σύντομο όνομα για την απόδειξη. Αν αφεθεί κενό, χρησιμοποιείται το κανονικό όνομα.",
"vatGroup": "Ομάδα ΦΠΑ ΦΗΜ",
"vatGroupNeeded": "Απαιτείται για πληρωμή με ΦΗΜ ενεργή.",
"noVatGroups": "Δεν έχουν οριστεί ομάδες ΦΠΑ: Ρυθμίσεις → Ταμειακή.",
"noVatGroup": "Χωρίς ανάθεση",
"tab": {
"favourites": "Αγαπημένα",
"quick": "Γρήγορες",
"ingredients": "Υλικά",
"options": "Έξτρα"
},
"prefN": "Προτ. {{n}}",
"addPref": "Προτίμηση",
"addPrefGroup": "Ομάδα",
"newGroup": "Νέα ομάδα",
"favouritesHint": "Τα αγαπημένα εμφανίζονται πρώτα στον σερβιτόρο, με αυτή τη σειρά. Πατήστε την καρδιά στις άλλες καρτέλες.",
"noFavourites": "Δεν υπάρχουν αγαπημένα.",
"unnamed": "(χωρίς όνομα)",
"kind": {
"quick": "Γρήγορη",
"ingredient": "Υλικό",
"option": "Έξτρα",
"pref": "Προτίμηση"
},
"remove": "Αφαίρεση",
"favourite": "Στα αγαπημένα",
"unfavourite": "Αφαίρεση από τα αγαπημένα",
"default": "Προεπιλογή",
"extraCost": "Τιμή",
"multiple": "Πολλαπλά",
"multiSelect": "Multi-select",
"compact": "Compact",
"group": "Ομάδα",
"noGroup": "Χωρίς ομάδα",
"addGroup": "Ομάδα",
"emptyGroup": "Κενή ομάδα: επιλέξτε την από κάθε γραμμή.",
"unnamedGroup": "(ομάδα χωρίς όνομα)",
"renameGroup": "Μετονομασία ομάδας",
"removeGroup": "Διαγραφή ομάδας (οι γραμμές μένουν)",
"quickHint": "Γρήγορες επιλογές με τιμή.",
"addQuick": "Επιλογή",
"noQuick": "Δεν υπάρχουν γρήγορες επιλογές.",
"quickPlaceholder": "π.χ. Extra Bacon",
"ingredientHint": "Υλικά που ο πελάτης μπορεί να αφαιρέσει.",
"ingredientPlaceholder": "Όνομα υλικού",
"optionHint": "Έξτρα (checkbox). Κάθε έξτρα μπορεί να έχει υπο-επιλογές.",
"optionPlaceholder": "π.χ. Κανέλα",
"add": {
"ingredient": "Υλικό",
"option": "Έξτρα"
},
"none": {
"ingredient": "Δεν υπάρχουν υλικά.",
"option": "Δεν υπάρχουν έξτρα."
},
"addSubs": "Υπο-επιλογές",
"addSub": "Υπο-επιλογή",
"subsOf": "Υπο-επιλογές του «{{name}}»",
"subPlaceholder": "π.χ. Καραμέλα",
"prefPlaceholder": "π.χ. Ζάχαρη",
"removePref": "Διαγραφή",
"prefGroups": "Ομάδες προτιμήσεων",
"multiChoice": "Πολλαπλή επιλογή",
"choiceQuantity": "Ποσότητα ανά επιλογή",
"prefLegend": "● = προεπιλογή · «Κρύβει το κοινό» = αυτή η επιλογή δεν το δείχνει",
"choicePlaceholder": "π.χ. Σκέτος",
"hidesShared": "Κρύβει το κοινό",
"addChoice": "Επιλογή",
"shared": "Κοινό υπο-σύνολο",
"sharedHint": "Εμφανίζεται για όλες εκτός όσων το κρύβουν.",
"addShared": "Κοινό υπο-σύνολο",
"sharedName": "Όνομα κοινού υπο-συνόλου",
"sharedPlaceholder": "π.χ. Είδος ζάχαρης"
}
}
}
+22
View File
@@ -76,5 +76,27 @@
"name": "Online, with a reservation",
"hint": "Reserved online, food ready on arrival"
}
},
"allergens": {
"title": "Allergens",
"none": "No allergens declared",
"level": {
"contains": "Contains",
"may_contain": "May contain"
},
"gluten": "Gluten",
"crustaceans": "Crustaceans",
"eggs": "Eggs",
"fish": "Fish",
"peanuts": "Peanuts",
"soybeans": "Soya",
"milk": "Milk",
"nuts": "Nuts",
"celery": "Celery",
"mustard": "Mustard",
"sesame": "Sesame",
"sulphites": "Sulphites",
"lupin": "Lupin",
"molluscs": "Molluscs"
}
}
+2 -1
View File
@@ -115,7 +115,8 @@
"nest_has_children": "A category with sub-categories can't go under another one.",
"too_deep": "Categories go at most two levels deep.",
"own_parent": "A category can't be its own parent.",
"group_not_found": "Option group not found."
"group_not_found": "Option group not found.",
"allergen": "Unknown allergen or level: {{allergen}}."
},
"system": {
"log_not_found": "There is no log file for {{date}}."
+280
View File
@@ -1523,5 +1523,285 @@
"forceClose": "Force the close",
"closeNow": "Close the day"
}
},
"products": {
"title": "Products",
"categories": "Categories",
"searchCategories": "Search categories…",
"clear": "Clear",
"service": "Service",
"all": "All products",
"allOf": "All",
"uncategorized": "Without a category",
"archived": "Archived",
"archivedBadge": "Archive",
"search": "Search… (Latin letters find Greek names too)",
"filters": "Filters",
"view": "View",
"view_list": "List",
"view_grid": "Grid",
"new": "New product",
"price": "Price",
"from": "from",
"to": "to",
"quality": "Missing data",
"qualityOf": {
"all": "All",
"no-photo": "No photo",
"no-cat": "No category"
},
"show": "Show",
"unavailableOnly": "Unavailable only",
"withArchived": "Archived too",
"clearFilters": "Clear filters",
"clearSelection": "Clear the selection",
"selected_one": "{{count}} selected",
"selected_other": "{{count}} selected",
"selectAll": "Select all",
"select": "Select {{name}}",
"totals": "{{active}} active · {{categories}} categories · {{archived}} archived",
"none": "No products found",
"noneHint": "Try other filters or add a product.",
"makeAvailable": "Available",
"makeUnavailable": "Unavailable",
"archive": "Archive",
"delete": "Delete for good",
"prepZone": "Prep zones",
"toCategory": "Category",
"updated_one": "{{count}} product updated",
"updated_other": "{{count}} products updated",
"available": "Available",
"unavailable": "Unavailable",
"edit": "Edit",
"moveUp": "Move up",
"moveDown": "Move down",
"main": "main",
"mainHere": "Its main category",
"alsoIn": "also in {{name}}",
"hasAllergens": "Allergens declared",
"allergenCount_one": "{{count}} allergen",
"allergenCount_other": "{{count}} allergens",
"costOverPrice": "Cost above price",
"margin": "{{pct}} margin",
"cancel": "Cancel",
"save": "Save",
"saved": "Saved",
"apply": "Apply",
"copyOf": "{{name}} (copy)",
"unit": {
"piece": "Piece",
"portion": "Portion",
"kg": "Kilo (kg)",
"liter": "Litre (L)",
"gram": "Gram (g)",
"ml": "Millilitre (mL)"
},
"category": {
"new": "New category",
"newSub": "New sub-category",
"edit": "Edit category",
"editSub": "Edit sub-category",
"delete": "Delete category",
"under": "Under {{name}}",
"name": "Name",
"colour": "Colour",
"saved": "Category saved",
"moveTitle": "Move category",
"moving": "Category: {{name}}",
"newPlace": "New place",
"topLevel": "Top level (on its own)",
"move": "Move",
"moved": "The category moved"
},
"confirm": {
"category": "Delete the category \"{{name}}\"?",
"archive": "Archive \"{{name}}\"?",
"delete": "Delete \"{{name}}\" for good?",
"bulkArchive_one": "Archive {{count}} product?",
"bulkArchive_other": "Archive {{count}} products?"
},
"confirmBody": {
"category": "Its products stay; those that were only in it end up without a category.",
"archive": "It leaves the menus and is kept for the order history. You can bring it back from the archive.",
"delete": "It is gone for good. A product that was ever ordered can only be archived.",
"bulkArchive": "They leave the menus and are kept for the order history."
},
"confirmButton": {
"category": "Delete",
"archive": "Archive",
"delete": "Delete",
"bulkArchive": "Archive"
},
"done": {
"category": "Category deleted",
"archive": "Archived",
"delete": "Deleted",
"bulkArchive": "Archived"
},
"bulkZones": {
"title": "Prep zones",
"body_one": "For {{count}} product.",
"body_other": "For {{count}} products.",
"done_one": "Prep zones set for {{count}} product",
"done_other": "Prep zones set for {{count}} products"
},
"bulkCategory": {
"title": "Category",
"body_one": "For {{count}} product.",
"body_other": "For {{count}} products.",
"move": "Move to",
"moveHint": "It becomes their only category (and their main one).",
"add": "Also list in",
"addHint": "Added to the categories they have; their main one stays.",
"which": "Choose a category…",
"done_one": "{{count}} product updated",
"done_other": "{{count}} products updated"
},
"editor": {
"newTitle": "New product",
"editTitle": "Edit: {{name}}",
"copy": "Copy",
"create": "Create",
"left": {
"info": "Details",
"soldAt": "Where it's sold",
"cost": "Cost",
"fiscal": "Fiscal"
},
"serviceItem": "Service item",
"serviceHint": "Cutlery, glasses, a cover charge: printed in its own SERVICE section.",
"servicePaid": "Printed in its own SERVICE section and counted in the takings.",
"serviceFree": "Printed once: not kept on the order, not counted in the takings.",
"name": "Name",
"namePlaceholder": "e.g. Espresso",
"servicePlaceholder": "e.g. Cutlery",
"description": "Description (optional)",
"descriptionHint": "For the menus and to tell the waiters.",
"tags": "Tags (optional)",
"tagsHint": "Enter or a comma adds a tag.",
"tagsPlaceholder": "e.g. vegan, spicy",
"removeTag": "Remove {{tag}}",
"unit": "Unit",
"unitWeighed": "The waiters type the quantity as a decimal (e.g. 0,35).",
"price": "Price",
"priceOptional": "Price (optional)",
"less": "Less",
"more": "More",
"categories": "Categories",
"categoriesTip": "A product can be listed in several categories (a freddo under Coffees and Breakfast); it shows in each and each list has its own order. The main one decides where it prints on tickets and how reports group it.",
"noCategory": "Not in any category yet.",
"main": "Main",
"makeMain": "Make it the main category",
"removeCategory": "Remove from this category",
"addCategory": "Add a category…",
"prepZones": "Prep zones",
"prepZonesTip": "Where it's made: its tickets print at these zones' printers and show on their kitchen screens.",
"noZones": "No prep zones yet.",
"makeZone": "Create one",
"allergensTip": "The 14 allergens EU law (Reg. 1169/2011) asks a venue to declare. \"May contain\" is for traces, e.g. made in the same kitchen. They show on the waiters' phones, the counter, the menu tablets and the online menus.",
"allergensHint": "Tap once: contains · twice: may contain · again: none.",
"allergenNone": "not declared",
"traces": "traces",
"available": "Available",
"availableHint": "Off: it can't be ordered now (sold out); it stays on the menus.",
"quickAdd": "Quick add",
"quickAddHint": "The waiters add one with a tap, without the choices screen.",
"soldAt": "Where it's sold",
"soldAtHint": "Where it isn't ticked, it isn't shown and orders with it are refused.",
"pricePerPoint": "A different price per sales point (e.g. cheaper to take away): Pricing → Modifiers, with the condition \"Order channel\".",
"online": "QR menu and online",
"orderableNow": "Can be ordered now",
"orderableNowHint": "Off: the customer apps show it as sold out.",
"forCustomers": "What customers see",
"forCustomersHint": "Leave empty to use the product's own.",
"customerName": "Name",
"customerDescription": "Description",
"customerImage": "Picture address",
"costHint": "The cost is copied onto every order, for the profit in the reports.",
"costMode": "How the cost is entered",
"cost": {
"simple": "One amount",
"detailed": "Itemised"
},
"costPerUnit": "Cost per unit",
"costLinePlaceholder": "e.g. Milk",
"addCostLine": "Cost line",
"costTotal": "Total {{total}}",
"fiscalHint": "Used when receipts are sent to the fiscal device by themselves.",
"fiscalName": "Name on the receipt (optional)",
"fiscalNameHint": "A short name for the receipt; empty: the product's name.",
"vatGroup": "VAT group",
"vatGroupNeeded": "Needed to take payments while fiscal receipts are on.",
"noVatGroups": "No VAT groups yet: Settings → Fiscal.",
"noVatGroup": "Not assigned",
"tab": {
"favourites": "Favourites",
"quick": "Quick",
"ingredients": "Ingredients",
"options": "Extras"
},
"prefN": "Pref. {{n}}",
"addPref": "Preference",
"addPrefGroup": "Group",
"newGroup": "New group",
"favouritesHint": "Favourites show first to the waiter, in this order. Tap a heart in the other tabs to add one.",
"noFavourites": "No favourites.",
"unnamed": "(no name)",
"kind": {
"quick": "Quick",
"ingredient": "Ingredient",
"option": "Extra",
"pref": "Preference"
},
"remove": "Remove",
"favourite": "Make it a favourite",
"unfavourite": "Remove from favourites",
"default": "Chosen by default",
"extraCost": "Price",
"multiple": "Several",
"multiSelect": "Several sub-choices",
"compact": "Compact",
"group": "Group",
"noGroup": "No group",
"addGroup": "Group",
"emptyGroup": "Nothing in this group: pick it on a row.",
"unnamedGroup": "(unnamed group)",
"renameGroup": "Rename the group",
"removeGroup": "Remove the group (its rows stay)",
"quickHint": "One-tap add-ons with a price.",
"addQuick": "Quick choice",
"noQuick": "No quick choices.",
"quickPlaceholder": "e.g. Extra bacon",
"ingredientHint": "What the guest can leave out.",
"ingredientPlaceholder": "Ingredient",
"optionHint": "Ticked add-ons; each can have sub-choices.",
"optionPlaceholder": "e.g. Cinnamon",
"add": {
"ingredient": "Ingredient",
"option": "Extra"
},
"none": {
"ingredient": "No ingredients.",
"option": "No extras."
},
"addSubs": "Sub-choices",
"addSub": "Sub-choice",
"subsOf": "Sub-choices of \"{{name}}\"",
"subPlaceholder": "e.g. Caramel",
"prefPlaceholder": "e.g. Sugar",
"removePref": "Delete",
"prefGroups": "Preference groups",
"multiChoice": "Several can be chosen",
"choiceQuantity": "A quantity per choice",
"prefLegend": "● = chosen by default · \"Hides the shared set\" = that choice doesn't offer it",
"choicePlaceholder": "e.g. No sugar",
"hidesShared": "Hides the shared set",
"addChoice": "Choice",
"shared": "Shared sub-set",
"sharedHint": "Offered with every choice except those that hide it.",
"addShared": "Shared sub-set",
"sharedName": "Name of the shared sub-set",
"sharedPlaceholder": "e.g. Kind of sugar"
}
}
}
@@ -9,6 +9,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { BellRing, Search, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { applyTheme, Dialog, getStoredTheme, Input } from '@xenia/ui'
import { Allergens } from '@xenia/access'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
import { idle, languagesOf, search, sections } from './logic'
@@ -205,6 +206,8 @@ function Details({ product: p, cfg, onClose }) {
{p.tags?.length > 0 && (
<div className="flex flex-wrap gap-1.5">{p.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink-2">{tag}</span>)}</div>
)}
<Allergens allergens={p.allergens} />
</div>
</Dialog>
)
+3
View File
@@ -6,6 +6,7 @@ import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Stepper } from '@xenia/ui'
import { Allergens } from '@xenia/access'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
@@ -69,6 +70,8 @@ export default function ProductDialog({ product, orderType, onAdd, onClose }) {
{product.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-full bg-surface-2 text-caption text-ink-2">{tag}</span>)}
</div>
)}
<Allergens allergens={product.allergens} style={{ marginTop: 4 }} />
</div>
</div>
+43
View File
@@ -857,6 +857,49 @@ try {
&& !(await api('GET', '/api/business-day/current', { token: boss }))
&& (await api('GET', `/api/orders/${ovOrder.id}`, { token: boss })).status === 'closed')
// ── 6.3: products in two categories, ordered in each; allergens ──────────────
const pr = 'products:'
const pcats = (await api('GET', '/api/products/categories', { token: boss })).filter(c => !c.parent_id)
const inCat = async id => (await api('GET', `/api/products/?category_id=${id}&all=true`, { token: boss })).map(p => p.id)
const allProducts = await api('GET', '/api/products/?all=true', { token: boss })
const [catA, catB] = pcats.filter(c => allProducts.filter(p => p.category_ids.includes(c.id) && p.lifecycle_status === 'active').length >= 2)
const prodP = allProducts.find(p => p.category_ids.length === 1 && p.category_ids[0] === catA.id && p.lifecycle_status === 'active' && !p.is_service_item)
const orderA = await inCat(catA.id)
await page.goto(`${APP}/management/products`)
const pRow = page.locator(`[data-testid="product-row"][data-name="${prodP.name}"]`).first()
await pRow.waitFor({ timeout: 15_000 })
await pRow.getByTestId('product-edit').click()
await page.getByTestId('product-editor').waitFor({ timeout: 10_000 })
await page.getByTestId('add-category').selectOption(String(catB.id))
await page.getByTestId('allergen-gluten').click()
await page.getByTestId('allergen-milk').click()
await page.getByTestId('allergen-milk').click()
r.check(`${pr} the editor lists both categories, the first one main; gluten "contains", milk "may contain"`,
await page.locator(`[data-testid="product-category"][data-id="${catA.id}"][data-main="true"]`).count() === 1
&& await page.locator(`[data-testid="product-category"][data-id="${catB.id}"][data-main="false"]`).count() === 1
&& await page.getByTestId('allergen-gluten').getAttribute('data-level') === 'contains' && await page.getByTestId('allergen-milk').getAttribute('data-level') === 'may_contain')
await page.screenshot({ path: path.join(OUT, 'manager-product-editor.png') })
await page.getByTestId('product-save').click()
await page.getByTestId('product-editor').waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {})
const savedP = (await api('GET', '/api/products/?all=true', { token: boss })).find(p => p.id === prodP.id)
r.check(`${pr} saved: listed in both, the main one kept, its allergens`, JSON.stringify(savedP.category_ids) === JSON.stringify([catA.id, catB.id])
&& savedP.primary_category_id === catA.id && JSON.stringify(savedP.allergens) === JSON.stringify({ gluten: 'contains', milk: 'may_contain' }), JSON.stringify([savedP.category_ids, savedP.allergens]))
await page.getByTestId(`category-${catB.id}`).click()
const inB = page.locator(`[data-testid="product-group"][data-category="${catB.id}"] [data-testid="product-row"][data-id="${prodP.id}"]`)
r.check(`${pr} it shows in the second category too, marked "also in" the first`, await inB.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& (await inB.getByTestId('also-in').textContent()).includes(catA.name),
`${await page.getByTestId('products-title').textContent().catch(() => '?')} | ${await page.locator('[data-testid="product-group"]').evaluateAll(gs => gs.map(g => g.dataset.category + ':' + g.querySelectorAll('[data-testid=product-row]').length).join(','))}`)
await page.screenshot({ path: path.join(OUT, 'manager-products-b.png') })
const orderB = await inCat(catB.id)
r.check(`${pr} …at the end of that category's list`, orderB.at(-1) === prodP.id, JSON.stringify(orderB))
await inB.hover()
await inB.getByTestId('product-up').click()
let orderB2 = orderB
for (let i = 0; i < 20 && orderB2.at(-2) !== prodP.id; i++) { await sleep(250); orderB2 = await inCat(catB.id) }
r.check(`${pr} moved up in the second category; the first category's order is untouched`, orderB2.at(-2) === prodP.id && JSON.stringify(await inCat(catA.id)) === JSON.stringify(orderA),
JSON.stringify(orderB2))
await page.screenshot({ path: path.join(OUT, 'manager-products.png') })
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})
+1 -1
View File
@@ -144,7 +144,7 @@ try {
await row.getByTestId('product-edit').click()
await page.getByTestId('product-photo').waitFor({ timeout: 10_000 })
}
const save = async () => { await page.getByRole('button', { name: 'Αποθήκευση', exact: true }).last().click(); await sleep(1200) }
const save = async () => { await page.getByTestId('product-save').click(); await page.getByTestId('product-editor').waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {}) }
await edit(p1.name)
await page.getByTestId('product-photo').getByTestId('media-field-pick').click()
+3
View File
@@ -36,6 +36,7 @@ try {
await api('PUT', '/api/platform/modules/menu_tablet', { token: boss, body: { enabled: true } }).catch(() => {})
const products = (await api('GET', '/api/products/?sold_at=in_store', { token: boss })).filter(p => !p.is_service_item && p.lifecycle_status === 'active')
const souvlaki = products.find(p => /Σουβλάκι/.test(p.name)) || products[0]
await api('PUT', `/api/products/${souvlaki.id}`, { token: boss, body: { allergens: { gluten: 'contains', mustard: 'may_contain' } } })
const tab = await (await browser.newContext({ viewport: { width: 1180, height: 820 }, hasTouch: true })).newPage()
tab.on('pageerror', e => errors.push(e.message))
@@ -55,6 +56,8 @@ try {
await hit.click()
r.check('…and opens it big with its price', await shown(tab, 'menu-details', 5000)
&& (await tab.getByTestId('menu-details').getByTestId('menu-price').textContent()).includes(souvlaki.base_price.toFixed(2)))
r.check('6.3: …with its allergens', await tab.getByTestId('menu-details').locator('[data-allergen="gluten"][data-level="contains"]').count() === 1
&& await tab.getByTestId('menu-details').locator('[data-allergen="mustard"][data-level="may_contain"]').count() === 1)
await tab.keyboard.press('Escape')
await tab.getByTestId('menu-search').fill('zzzz')
r.check('nothing found: says so', await shown(tab, 'menu-no-results', 5000))
+4 -1
View File
@@ -332,7 +332,7 @@ try {
preference_sets: [{ name: 'Cooking', choices: [{ name: 'Rare' }, { name: 'Well done', extra_cost: 0.5 }] }],
options: [{ name: 'Sauce', extra_cost: 0.5, sub_choices: [{ name: 'BBQ', extra_cost: 0.2, is_default: true }, { name: 'Mayo' }] }],
quick_options: [{ name: 'Cheese', price: 1, allow_multiple: true }],
ingredients: [{ name: 'Onion' }],
ingredients: [{ name: 'Onion' }], allergens: { gluten: 'contains', sesame: 'may_contain' },
} })
const posMenu = await api('GET', '/api/pos/menu', { token: boss })
const simple = posMenu.products.find(p => !p.prefs.length && p.id !== burgerP.id && p.categories.every(c => c.category_id !== cats[0].id))
@@ -359,6 +359,9 @@ try {
await burgerCard.getByTestId('product-info').click()
r.check('3.3a: price check shows the price without adding it', await shown(page, 'product-dialog', 5000)
&& (await page.getByTestId('dialog-price').textContent()).includes('10.00') && await page.getByTestId('cart-line').count() === 0)
r.check('6.3: …and its allergens (contains gluten, may contain sesame)',
await page.getByTestId('product-dialog').locator('[data-allergen="gluten"][data-level="contains"]').count() === 1
&& await page.getByTestId('product-dialog').locator('[data-allergen="sesame"][data-level="may_contain"]').count() === 1)
await page.keyboard.press('Escape')
await burgerCard.locator('button').first().click()
await page.getByTestId('product-dialog').waitFor({ timeout: 5000 })
+13
View File
@@ -177,6 +177,19 @@ try {
.catch(async e => { await a.screenshot({ path: path.join(OUT, 'waiter-add-items.png') }); throw e })
const onScreen = await a.locator('[data-testid="product-card"]:has([data-testid="product-quick-add"])').evaluateAll(els => els.map(e => e.dataset.name))
const [plain, other] = prods.filter(p => simple(p) && onScreen.includes(p.name))
// 6.3: allergens set in the manager reach the phone (live) and show in the product's details (hold it)
await api('PUT', `/api/products/${other.id}`, { token: boss, body: { allergens: { milk: 'contains', nuts: 'may_contain' } } })
await sleep(1500)
const held = a.locator(`[data-testid="product-card"][data-name="${other.name}"]`).first()
await held.hover()
await a.mouse.down()
await sleep(1600)
await a.mouse.up()
const info = a.getByTestId('allergens')
r.check('6.3: holding a product shows its allergens on the phone', await info.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& await info.locator('[data-allergen="milk"][data-level="contains"]').count() === 1 && await info.locator('[data-allergen="nuts"][data-level="may_contain"]').count() === 1)
await a.mouse.click(5, 5)
await info.waitFor({ state: 'detached', timeout: 3000 }).catch(() => {})
// a price the phone's menu doesn't know (a price modifier): only the server can say it
const mod = await api('POST', '/api/pricing/modifiers', { token: boss, body: {
name: 'e2e 4.4', scope: 'item', item_id: plain.id, action_type: 'set', action_value: 1.2 } })
+15 -4
View File
@@ -5,6 +5,7 @@ import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server'
import { money } from '../i18n'
import { useTranslation } from '@xenia/i18n'
import { Allergens } from '@xenia/access'
const FAV_CAT_ID = '__favorites__'
const SVC_CAT_ID = '__service__'
@@ -144,12 +145,22 @@ function ProductDetailModal({ product, onClose }) {
{product.description}
</div>
)}
<Allergens allergens={product.allergens} style={{ borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 12 }} />
</div>
</div>
</>
)
}
// A product is listed in every category of `category_ids` (plan step 6.3, D-23), each list in
// its own order (`categories` [{category_id, sort_order}]); older data: just `category_id`.
const cats = p => p.category_ids ?? (p.category_id ? [p.category_id] : [])
function listOf(products, catId) {
const pos = p => p.categories?.find(c => c.category_id === catId)?.sort_order ?? p.sort_order ?? 0
return products.filter(p => cats(p).includes(catId)).sort((a, b) => pos(a) - pos(b))
}
// ── useLongPress ──────────────────────────────────────────────────────────────
function useLongPress(callback, delay = 2000) {
const timerRef = useRef(null)
@@ -432,7 +443,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
const serviceProducts = products.filter(p => p.is_service_item)
// Service items with a category also appear in that category view
const regularProducts = products.filter(p => !p.is_service_item || p.category_id)
const regularProducts = products.filter(p => !p.is_service_item || cats(p).length)
const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
// Start on FAVORITES chip if there are any, otherwise first category
@@ -459,9 +470,9 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
: []
const hasSubcats = subcategories.length > 0
const directProducts = regularProducts.filter(p => p.category_id === activeCat)
const directProducts = listOf(regularProducts, activeCat)
// Products for the flat view (no sub-cats)
const flatProducts = regularProducts.filter(p => p.category_id === activeCat)
const flatProducts = directProducts
// Build sections for accordion view
const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : []
@@ -633,7 +644,7 @@ export default function ProductPicker({ categories, products, onAdd, onQuickAdd:
const isOpen = !!expandedSubs[key]
const sectionProducts = section._isGeneral
? section.products
: regularProducts.filter(p => p.category_id === section.id)
: listOf(regularProducts, section.id)
if (sectionProducts.length === 0) return null
// General products appear flat — no collapsible header