diff --git a/docs/README.md b/docs/README.md index ae6d414..10d7797 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (CS-18) | +| `packages/access/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (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 `` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | | `packages/i18n/` | Translations (`locales//.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/`. | diff --git a/local_backend/core/allergens.py b/local_backend/core/allergens.py new file mode 100644 index 0000000..169516d --- /dev/null +++ b/local_backend/core/allergens.py @@ -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.`), 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 diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 5657ad2..f3b0cc7 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), diff --git a/local_backend/migrations/versions/0032_product_allergens.py b/local_backend/migrations/versions/0032_product_allergens.py new file mode 100644 index 0000000..4fe03e1 --- /dev/null +++ b/local_backend/migrations/versions/0032_product_allergens.py @@ -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') diff --git a/local_backend/models/product.py b/local_backend/models/product.py index aeb13f5..30bc768 100644 --- a/local_backend/models/product.py +++ b/local_backend/models/product.py @@ -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) diff --git a/local_backend/routers/data_transfer.py b/local_backend/routers/data_transfer.py index 5017331..14d2367 100644 --- a/local_backend/routers/data_transfer.py +++ b/local_backend/routers/data_transfer.py @@ -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() diff --git a/local_backend/routers/menu_tablet.py b/local_backend/routers/menu_tablet.py index 7d041cd..d984077 100644 --- a/local_backend/routers/menu_tablet.py +++ b/local_backend/routers/menu_tablet.py @@ -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}, } diff --git a/local_backend/routers/pos.py b/local_backend/routers/pos.py index 418fbb3..029bfb5 100644 --- a/local_backend/routers/pos.py +++ b/local_backend/routers/pos.py @@ -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, diff --git a/local_backend/routers/products.py b/local_backend/routers/products.py index 9c65df4..f8ec76c 100644 --- a/local_backend/routers/products.py +++ b/local_backend/routers/products.py @@ -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 diff --git a/local_backend/schemas/product.py b/local_backend/schemas/product.py index 6fe23b4..747aea7 100644 --- a/local_backend/schemas/product.py +++ b/local_backend/schemas/product.py @@ -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), diff --git a/local_backend/services/cloud_sync.py b/local_backend/services/cloud_sync.py index d20e5a4..48bd7b8 100644 --- a/local_backend/services/cloud_sync.py +++ b/local_backend/services/cloud_sync.py @@ -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, diff --git a/local_backend/tests/test_allergens.py b/local_backend/tests/test_allergens.py new file mode 100644 index 0000000..51c20c8 --- /dev/null +++ b/local_backend/tests/test_allergens.py @@ -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) diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 6c43ab7..83c92b3 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -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' diff --git a/manager_dashboard/src/components/NotificationBell.jsx b/manager_dashboard/src/components/NotificationBell.jsx index 9d6405d..05710a4 100644 --- a/manager_dashboard/src/components/NotificationBell.jsx +++ b/manager_dashboard/src/components/NotificationBell.jsx @@ -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 diff --git a/manager_dashboard/src/pages/Management/ProductFormModal.jsx b/manager_dashboard/src/pages/Management/ProductFormModal.jsx deleted file mode 100644 index fe20693..0000000 --- a/manager_dashboard/src/pages/Management/ProductFormModal.jsx +++ /dev/null @@ -1,1381 +0,0 @@ -import { useState, useEffect, useRef } from 'react' -import { useQuery } from '@tanstack/react-query' -import client from '../../api/client' -import { useTranslation } from '@xenia/i18n' -import { SALES_POINTS } from '@xenia/access' -import MediaField from '../media/MediaField' - -// ── Small helpers ───────────────────────────────────────────────────────────── -function moveItem(arr, i, dir) { - const j = i + dir - if (j < 0 || j >= arr.length) return arr - const next = [...arr] - ;[next[i], next[j]] = [next[j], next[i]] - return next -} - -function HeartIcon({ filled, className = '' }) { - return ( - - ) -} - -function ReorderBtns({ onUp, onDown, disableUp, disableDown }) { - return ( -
- - -
- ) -} - -function DefaultBtn({ isDefault, onClick }) { - return ( - - ) -} - -function FavoriteBtn({ isFavorite, onClick }) { - return ( - - ) -} - -function PriceInput({ value, onChange, placeholder, className = '', allowNegative = false }) { - const step = 0.10 - const num = parseFloat(value) || 0 - function inc() { onChange(Math.round((num + step) * 100) / 100) } - function dec() { - const next = Math.round((num - step) * 100) / 100 - onChange(allowNegative ? next : Math.max(0, next)) - } - return ( -
- - onChange(e.target.value)} - placeholder={placeholder ?? '0.00'} - className="flex-1 min-w-0 text-center text-sm outline-none bg-transparent px-1 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" /> - -
- ) -} - -function SubChoiceRows({ subChoices, onMove, onToggleDefault, onChange, onRemove, onAdd, parentLabel, showMultiple = false }) { - if (!subChoices || subChoices.length === 0) return null - return ( -
-

- Υπο-επιλογές του «{parentLabel || '…'}» -

- {subChoices.map((sc, sci) => ( -
- onMove(sci, -1)} onDown={() => onMove(sci, 1)} - disableUp={sci === 0} disableDown={sci === subChoices.length - 1} /> - onToggleDefault(sci)} /> - onChange(sci, 'name', e.target.value)} /> - onChange(sci, 'extra_cost', v)} - allowNegative className="w-28 text-sm" /> - {showMultiple && ( - - )} - - -
- ))} - -
- ) -} - -// ── Group helpers ───────────────────────────────────────────────────────────── -function GroupHeader({ group, onRename, onDelete, collapsed, onToggle }) { - const [editing, setEditing] = useState(false) - const [val, setVal] = useState(group.name) - return ( -
- - - -
- ) -} - -// ── Form builder ────────────────────────────────────────────────────────────── -function buildFormFromProduct(product) { - return { - name: product.name || '', - description: product.description || '', - category_id: product.category_id ?? '', - base_price: product.base_price ?? '', - unit_type: product.unit_type ?? 'piece', - is_available: product.is_available ?? true, - lifecycle_status: product.lifecycle_status ?? 'active', - prep_zone_ids: product.prep_zone_ids ?? [], - quick_options: product.quick_options?.map(q => ({ - name: q.name, price: q.price ?? 0, allow_multiple: q.allow_multiple ?? false, - sort_order: q.sort_order ?? 0, is_favorite: q.is_favorite ?? false, - favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: q.is_compact ?? false, - })) ?? [], - options: product.options?.map(o => ({ - name: o.name, extra_cost: o.extra_cost ?? 0, allow_multiple: o.allow_multiple ?? false, - multi_select: o.multi_select ?? false, is_compact: o.is_compact ?? false, - sub_choices: o.sub_choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false, allow_multiple: s.allow_multiple ?? false, is_compact: s.is_compact ?? false })) ?? [], - is_favorite: o.is_favorite ?? false, favorite_sort_order: o.favorite_sort_order ?? 0, - group_id: o.group_id ?? null, - })) ?? [], - ingredients: product.ingredients?.map(i => ({ - name: i.name, extra_cost: i.extra_cost ?? 0, - is_favorite: i.is_favorite ?? false, favorite_sort_order: i.favorite_sort_order ?? 0, - is_compact: i.is_compact ?? false, group_id: i.group_id ?? null, - })) ?? [], - preference_sets: product.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 ?? false, - is_compact: c.is_compact ?? false, - sub_choices: c.sub_choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false, is_compact: s.is_compact ?? false })) ?? [], - })) ?? [], - group_id: ps.group_id ?? null, - shared_subset: ps.shared_subset ? { - name: ps.shared_subset.name, - choices: ps.shared_subset.choices?.map(s => ({ name: s.name, extra_cost: s.extra_cost ?? 0, is_default: s.is_default ?? false })) ?? [], - } : null, - is_favorite: ps.is_favorite ?? false, favorite_sort_order: ps.favorite_sort_order ?? 0, - allow_multi_select: ps.allow_multi_select ?? false, - allow_choice_quantity: ps.allow_choice_quantity ?? false, - })) ?? [], - sold_at: product.sold_at ?? [...SALES_POINTS], - digital_available: product.digital_available ?? true, - digital_name: product.digital_name ?? '', - digital_description: product.digital_description ?? '', - digital_image_url: product.digital_image_url ?? '', - // Its photo in the media library (plan step 5.2): { id, name, thumb, card, full } or null - image: product.image ?? null, - // Phase 2A — cost tracking - cost_mode: product.cost_breakdown?.length ? 'detailed' : 'simple', - cost_simple: product.cost_simple ?? '', - cost_breakdown: product.cost_breakdown?.length - ? product.cost_breakdown.map(e => ({ label: e.label, amount: e.amount })) - : [], - // Quick Add - quick_add_enabled: product.quick_add_enabled ?? true, - // Tags - tags: product.tags ?? [], - tagsInput: '', - // Service items - is_service_item: product.is_service_item ?? false, - // Fiscal printer (ΦΗΜ) - fiscal_name: product.fiscal_name ?? '', - fiscal_vat_group_id: product.fiscal_vat_group_id ?? null, - // Modifier groups (folders) — keyed by _tempId in form, id from server - modifier_groups: (product.modifier_groups || []).map(g => ({ _tempId: g.id, id: g.id, modifier_type: g.modifier_type, name: g.name, sort_order: g.sort_order })), - } -} - -function buildFavoritesList(form) { - const items = [] - form.quick_options.forEach((q, i) => { if (q.is_favorite) items.push({ type: 'quick', idx: i, favorite_sort_order: q.favorite_sort_order ?? 0 }) }) - form.ingredients.forEach((ing, i) => { if (ing.is_favorite) items.push({ type: 'ingredient', idx: i, favorite_sort_order: ing.favorite_sort_order ?? 0 }) }) - form.options.forEach((o, i) => { if (o.is_favorite) items.push({ type: 'option', idx: i, favorite_sort_order: o.favorite_sort_order ?? 0 }) }) - form.preference_sets.forEach((ps, i) => { if (ps.is_favorite) items.push({ type: 'pref', idx: i, favorite_sort_order: ps.favorite_sort_order ?? 0 }) }) - return items.sort((a, b) => a.favorite_sort_order - b.favorite_sort_order) -} - -function setFavSortField(form, type, idx, value) { - if (type === 'quick') return { ...form, quick_options: form.quick_options.map((q, i) => i === idx ? { ...q, favorite_sort_order: value } : q) } - if (type === 'ingredient') return { ...form, ingredients: form.ingredients.map((ing, i) => i === idx ? { ...ing, favorite_sort_order: value } : ing) } - if (type === 'option') return { ...form, options: form.options.map((o, i) => i === idx ? { ...o, favorite_sort_order: value } : o) } - if (type === 'pref') return { ...form, preference_sets: form.preference_sets.map((ps, i) => i === idx ? { ...ps, favorite_sort_order: value } : ps) } - return form -} - -function getItemLabel(form, type, idx) { - if (type === 'quick') return form.quick_options[idx]?.name || '(χωρίς όνομα)' - if (type === 'ingredient') return form.ingredients[idx]?.name || '(χωρίς όνομα)' - if (type === 'option') return form.options[idx]?.name || '(χωρίς όνομα)' - if (type === 'pref') return form.preference_sets[idx]?.name || '(χωρίς όνομα)' - return '' -} - -function getItemTypeLabel(type) { - if (type === 'quick') return 'Γρήγορη' - if (type === 'ingredient') return 'Υλικό' - if (type === 'option') return 'Έξτρα' - if (type === 'pref') return 'Προτίμηση' - return '' -} - -// ── Main modal ──────────────────────────────────────────────────────────────── -export default function ProductFormModal({ product, categories, printers, prepZones = [], onSave, onCopy, onClose }) { - const [form, setForm] = useState(() => buildFormFromProduct(product)) - const [activeTab, setActiveTab] = useState('favorites') - const [leftTab, setLeftTab] = useState('info') - const { t: tm } = useTranslation('manager') - - // Fetch fiscal VAT groups from settings (needed for the Ταμειακή tab dropdown) - const { data: settingsData } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 60_000, - }) - const fiscalEnabled = settingsData?.['fiscal.enabled']?.value === 'true' - const vatGroups = (() => { - try { return JSON.parse(settingsData?.['fiscal.vat_groups']?.value || '[]') } catch { return [] } - })() - - useEffect(() => { - // Escape inside a dialog on top (the media picker) closes only that dialog - function onKey(e) { if (e.key === 'Escape' && !document.querySelector('.x-dialog')) onClose() } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [onClose]) - - useEffect(() => { - setForm(buildFormFromProduct(product)) - setActiveTab('favorites') - setLeftTab('info') - }, [product.id, product.name]) - - function setField(k, v) { setForm(f => ({ ...f, [k]: v })) } - - // Favorites reorder - function moveFavorite(favList, favIdx, dir) { - const newList = [...favList] - const swapIdx = favIdx + dir - if (swapIdx < 0 || swapIdx >= newList.length) return - const aOrder = newList[favIdx].favorite_sort_order - const bOrder = newList[swapIdx].favorite_sort_order - setForm(f => { - let next = setFavSortField(f, newList[favIdx].type, newList[favIdx].idx, bOrder) - next = setFavSortField(next, newList[swapIdx].type, newList[swapIdx].idx, aOrder) - return next - }) - } - - function toggleFavorite(type, idx) { - setForm(f => { - const currentFavs = buildFavoritesList(f) - const isFav = (() => { - if (type === 'quick') return f.quick_options[idx]?.is_favorite - if (type === 'ingredient') return f.ingredients[idx]?.is_favorite - if (type === 'option') return f.options[idx]?.is_favorite - if (type === 'pref') return f.preference_sets[idx]?.is_favorite - })() - const newSortOrder = isFav ? 0 : (currentFavs.length > 0 ? Math.max(...currentFavs.map(x => x.favorite_sort_order)) + 1 : 0) - if (type === 'quick') return { ...f, quick_options: f.quick_options.map((q, i) => i === idx ? { ...q, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : q) } - if (type === 'ingredient') return { ...f, ingredients: f.ingredients.map((ing, i) => i === idx ? { ...ing, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : ing) } - if (type === 'option') return { ...f, options: f.options.map((o, i) => i === idx ? { ...o, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : o) } - if (type === 'pref') return { ...f, preference_sets: f.preference_sets.map((ps, i) => i === idx ? { ...ps, is_favorite: !isFav, favorite_sort_order: isFav ? 0 : newSortOrder } : ps) } - return f - }) - } - - // Quick Options - function addQuickOption() { setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, sort_order: f.quick_options.length, is_favorite: false, favorite_sort_order: 0, is_compact: false }] })) } - function removeQuickOption(i) { setForm(f => ({ ...f, quick_options: f.quick_options.filter((_, idx) => idx !== i) })) } - function setQuickOption(i, k, v) { setForm(f => ({ ...f, quick_options: f.quick_options.map((q, idx) => idx === i ? { ...q, [k]: v } : q) })) } - function moveQuickOption(i, dir) { setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, dir) })) } - - // Options - function addOption() { setForm(f => ({ ...f, options: [...f.options, { name: '', extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0 }] })) } - function removeOption(i) { setForm(f => ({ ...f, options: f.options.filter((_, idx) => idx !== i) })) } - function setOption(i, k, v) { setForm(f => ({ ...f, options: f.options.map((o, idx) => idx === i ? { ...o, [k]: v } : o) })) } - function moveOption(i, dir) { setForm(f => ({ ...f, options: moveItem(f.options, i, dir) })) } - - function addOptionSubChoice(oi) { - setForm(f => ({ ...f, options: f.options.map((o, idx) => - idx !== oi ? o : { ...o, sub_choices: [...(o.sub_choices || []), { name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }] } - )})) - } - function removeOptionSubChoice(oi, sci) { - setForm(f => ({ ...f, options: f.options.map((o, idx) => - idx !== oi ? o : { ...o, sub_choices: o.sub_choices.filter((_, i) => i !== sci) } - )})) - } - function setOptionSubChoice(oi, sci, k, v) { - setForm(f => ({ ...f, options: f.options.map((o, idx) => - idx !== oi ? o : { - ...o, sub_choices: o.sub_choices.map((sc, scidx) => { - if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc - return { ...sc, [k]: v } - }) - } - )})) - } - function moveOptionSubChoice(oi, sci, dir) { - setForm(f => ({ ...f, options: f.options.map((o, idx) => - idx !== oi ? o : { ...o, sub_choices: moveItem(o.sub_choices, sci, dir) } - )})) - } - function toggleOptionSubDefault(oi, sci) { - const sc = form.options[oi]?.sub_choices?.[sci] - setOptionSubChoice(oi, sci, 'is_default', !sc?.is_default) - } - - // Ingredients - function addIngredient() { setForm(f => ({ ...f, ingredients: [...f.ingredients, { name: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false }] })) } - function removeIngredient(i) { setForm(f => ({ ...f, ingredients: f.ingredients.filter((_, idx) => idx !== i) })) } - function setIngredient(i, k, v) { setForm(f => ({ ...f, ingredients: f.ingredients.map((ing, idx) => idx === i ? { ...ing, [k]: v } : ing) })) } - function moveIngredient(i, dir) { setForm(f => ({ ...f, ingredients: moveItem(f.ingredients, i, dir) })) } - - // Preference sets - function addPrefSet() { - setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', default_choice_index: -1, choices: [], shared_subset: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] })) - setActiveTab(form.preference_sets.length) - } - function removePrefSet(si) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, idx) => idx !== si) })) - setActiveTab('favorites') - } - function setPrefSetField(si, k, v) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => idx === si ? { ...ps, [k]: v } : ps) })) - } - function addChoice(si) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => - idx === si ? { ...ps, choices: [...ps.choices, { name: '', extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] } : ps - )})) - } - function removeChoice(si, ci) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - const newChoices = ps.choices.filter((_, cidx) => cidx !== ci) - const d = ps.default_choice_index - const newDefault = d === ci ? -1 : d > ci ? d - 1 : d - return { ...ps, choices: newChoices, default_choice_index: newDefault } - })})) - } - function setChoice(si, ci, k, v) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => - idx === si ? { ...ps, choices: ps.choices.map((ch, cidx) => cidx === ci ? { ...ch, [k]: v } : ch) } : ps - )})) - } - function moveChoice(si, ci, dir) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - const newChoices = moveItem(ps.choices, ci, dir) - const j = ci + dir - let nd = ps.default_choice_index - if (nd === ci) nd = j; else if (nd === j) nd = ci - return { ...ps, choices: newChoices, default_choice_index: nd } - })})) - } - function toggleDefaultChoice(si, ci) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => - idx !== si ? ps : { ...ps, default_choice_index: ps.default_choice_index === ci ? -1 : ci } - )})) - } - function addSubChoice(si, ci) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) => - pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) => - cidx !== ci ? ch : { ...ch, sub_choices: [...(ch.sub_choices || []), { name: '', extra_cost: 0, is_default: false, is_compact: false }] } - )} - )})) - } - function removeSubChoice(si, ci, sci) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) => - pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) => - cidx !== ci ? ch : { ...ch, sub_choices: ch.sub_choices.filter((_, i) => i !== sci) } - )} - )})) - } - function setSubChoice(si, ci, sci, k, v) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) => - pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) => - cidx !== ci ? ch : { ...ch, sub_choices: ch.sub_choices.map((sc, scidx) => { - if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc - return { ...sc, [k]: v } - })} - )} - )})) - } - function moveSubChoice(si, ci, sci, dir) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, pidx) => - pidx !== si ? ps : { ...ps, choices: ps.choices.map((ch, cidx) => - cidx !== ci ? ch : { ...ch, sub_choices: moveItem(ch.sub_choices, sci, dir) } - )} - )})) - } - function setSharedSubsetName(si, name) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - return { ...ps, shared_subset: ps.shared_subset ? { ...ps.shared_subset, name } : { name, choices: [] } } - })})) - } - function addSharedSubsetChoice(si) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - const ss = ps.shared_subset || { name: '', choices: [] } - return { ...ps, shared_subset: { ...ss, choices: [...ss.choices, { name: '', extra_cost: 0, is_default: false }] } } - })})) - } - function removeSharedSubsetChoice(si, sci) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - const newChoices = ps.shared_subset.choices.filter((_, i) => i !== sci) - return { ...ps, shared_subset: newChoices.length ? { ...ps.shared_subset, choices: newChoices } : null } - })})) - } - function setSharedSubsetChoice(si, sci, k, v) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => { - if (idx !== si) return ps - const newChoices = ps.shared_subset.choices.map((sc, scidx) => { - if (scidx !== sci) return k === 'is_default' && v === true ? { ...sc, is_default: false } : sc - return { ...sc, [k]: v } - }) - return { ...ps, shared_subset: { ...ps.shared_subset, choices: newChoices } } - })})) - } - function moveSharedSubsetChoice(si, sci, dir) { - setForm(f => ({ ...f, preference_sets: f.preference_sets.map((ps, idx) => - idx !== si ? ps : { ...ps, shared_subset: { ...ps.shared_subset, choices: moveItem(ps.shared_subset.choices, sci, dir) } } - )})) - } - - // Modifier groups - const _nextTempId = useRef(-1) - function addModifierGroup(modifier_type) { - const _tempId = _nextTempId.current-- - setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { _tempId, id: null, modifier_type, name: 'Νέα ομάδα', sort_order: f.modifier_groups.length }] })) - } - function renameModifierGroup(_tempId, name) { - setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(g => g._tempId === _tempId ? { ...g, name } : g) })) - } - function deleteModifierGroup(_tempId) { - setForm(f => { - const next = { ...f, modifier_groups: f.modifier_groups.filter(g => g._tempId !== _tempId) } - // Un-assign all items that belonged to this group - next.options = f.options.map(o => o.group_id === _tempId ? { ...o, group_id: null } : o) - next.ingredients = f.ingredients.map(i => i.group_id === _tempId ? { ...i, group_id: null } : i) - next.preference_sets = f.preference_sets.map(ps => ps.group_id === _tempId ? { ...ps, group_id: null } : ps) - return next - }) - } - function setItemGroup(listKey, idx, _tempId) { - setForm(f => ({ ...f, [listKey]: f[listKey].map((item, i) => i === idx ? { ...item, group_id: _tempId } : item) })) - } - const [collapsedGroups, setCollapsedGroups] = useState({}) - function toggleGroupCollapsed(_tempId) { - setCollapsedGroups(s => ({ ...s, [_tempId]: !s[_tempId] })) - } - - function buildBody() { - return { - name: form.name, - description: form.description || null, - category_id: form.category_id ? Number(form.category_id) : null, - base_price: form.base_price !== '' && form.base_price !== null && form.base_price !== undefined ? parseFloat(form.base_price) : 0, - unit_type: form.unit_type || 'piece', - is_available: form.is_available, - lifecycle_status: form.lifecycle_status, - prep_zone_ids: form.prep_zone_ids, - quick_options: form.quick_options.map((q, i) => ({ - name: q.name, price: parseFloat(q.price) || 0, allow_multiple: q.allow_multiple ?? false, - sort_order: i, is_favorite: q.is_favorite ?? false, favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: q.is_compact ?? false, - })), - modifier_groups: form.modifier_groups.map((g, gi) => ({ modifier_type: g.modifier_type, name: g.name, sort_order: gi })), - options: form.options.map(o => ({ - name: o.name, extra_cost: parseFloat(o.extra_cost) || 0, allow_multiple: o.allow_multiple ?? false, - multi_select: o.multi_select ?? false, is_compact: o.is_compact ?? false, - sub_choices: (o.sub_choices || []).map(s => ({ name: s.name, extra_cost: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false, allow_multiple: s.allow_multiple ?? false, is_compact: s.is_compact ?? false })), - is_favorite: o.is_favorite ?? false, favorite_sort_order: o.favorite_sort_order ?? 0, - group_id: o.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === o.group_id) : null, - })), - ingredients: form.ingredients.map(i => ({ - name: i.name, extra_cost: parseFloat(i.extra_cost) || 0, - is_favorite: i.is_favorite ?? false, favorite_sort_order: i.favorite_sort_order ?? 0, - is_compact: i.is_compact ?? false, - group_id: i.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === i.group_id) : null, - })), - preference_sets: form.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: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false })), - } : null, - choices: ps.choices.map(c => ({ - name: c.name, extra_cost: parseFloat(c.extra_cost) || 0, disables_subset: c.disables_subset ?? false, - is_compact: c.is_compact ?? false, - sub_choices: (c.sub_choices || []).map(s => ({ name: s.name, extra_cost: parseFloat(s.extra_cost) || 0, is_default: s.is_default ?? false, is_compact: s.is_compact ?? false })), - })), - is_favorite: ps.is_favorite ?? false, favorite_sort_order: ps.favorite_sort_order ?? 0, - group_id: ps.group_id != null ? form.modifier_groups.findIndex(g => g._tempId === ps.group_id) : null, - allow_multi_select: ps.allow_multi_select ?? false, - allow_choice_quantity: ps.allow_choice_quantity ?? false, - })), - sold_at: form.sold_at, - digital_available: form.digital_available, - digital_name: form.digital_name || null, - digital_description: form.digital_description || null, - digital_image_url: form.digital_image_url || null, - // Phase 2A — cost tracking - cost_simple: form.cost_mode === 'simple' && form.cost_simple !== '' ? parseFloat(form.cost_simple) : null, - cost_breakdown: form.cost_mode === 'detailed' && form.cost_breakdown.length > 0 - ? form.cost_breakdown.map(e => ({ label: e.label, amount: parseFloat(e.amount) || 0 })) - : null, - // Quick Add - quick_add_enabled: form.quick_add_enabled, - // Tags - tags: form.tags || [], - // Service items - is_service_item: form.is_service_item ?? false, - // Fiscal printer (ΦΗΜ) - fiscal_name: form.fiscal_name?.trim() || null, - fiscal_vat_group_id: form.fiscal_vat_group_id ? parseInt(form.fiscal_vat_group_id, 10) : null, - media_id: form.image?.id ?? null, - } - } - - function submit() { onSave(buildBody()) } - - const isNew = !product.id - const canSave = form.name.trim() && (form.is_service_item || (form.base_price !== '' && form.base_price !== null && form.base_price !== undefined)) - const favCount = buildFavoritesList(form).length - const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference') - const tabs = [ - { key: 'favorites', label: 'Αγαπημένα', count: favCount, isFavTab: true }, - { key: 'quick', label: 'Γρήγορες', count: form.quick_options.length }, - { key: 'ingredients', label: 'Υλικά', count: form.ingredients.length }, - { key: 'options', label: 'Έξτρα', count: form.options.length }, - ...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || `Προτ. ${i + 1}`, count: ps.choices.length })), - { key: '__add_pref__', label: '+ Προτίμηση', isAdd: true }, - { key: '__add_pref_group__', label: '+ Ομάδα', isAddGroup: true }, - ] - const favList = buildFavoritesList(form) - - return ( -
-
- - {/* Header */} -
-

- {isNew ? 'Νέο προϊόν' : `Επεξεργασία — ${product.name}`} -

- -
- - {/* Body */} -
- - {/* LEFT: tabbed product info — 25% normally, 100% for service items */} -
- {/* Left tab bar */} -
- {[ - { key: 'info', label: 'Πληροφορίες' }, - ...(!form.is_service_item ? [ - { key: 'digital', label: 'Πού πωλείται' }, - { key: 'cost', label: 'Κόστος' }, - ...(fiscalEnabled ? [{ key: 'fiscal', label: 'Ταμειακή' }] : []), - ] : []), - ].map(t => ( - - ))} -
- - {/* Left tab content */} -
- - {/* Tab 1: Main Info */} - {leftTab === 'info' && (<> - {/* Service Item toggle */} - - - {form.is_service_item && ( -

- {form.base_price && parseFloat(form.base_price) > 0 - ? 'Τυπώνεται σε ξεχωριστή ενότητα SERVICE. Καταγράφεται στα έσοδα.' - : 'Τυπώνεται μία φορά — δεν αποθηκεύεται στην παραγγελία, δεν καταγράφεται στα έσοδα.'} -

- )} - -
- - setField('name', e.target.value)} autoFocus placeholder={form.is_service_item ? 'π.χ. Σερβίτσιο' : 'π.χ. Espresso'} /> -
- - {!form.is_service_item &&
- -