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:
@@ -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
|
||||
@@ -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')
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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},
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user