feat(backend): a product can be listed in several categories, with one primary category

Platform v2 step 1.13 (APPS_PLATFORM D-23).
- product_categories(product_id, category_id, sort_order); products.category_id becomes
  products.primary_category_id (revision 0013 moves the data: one listing per product at its
  old position). services/catalog.py keeps the rule "the primary is one of its categories"
  and fixes up products when a category is deleted.
- Products API: category_ids + primary_category_id in and out, plus categories
  [{category_id, sort_order}]; GET /api/products/?category_id= lists a category's products in
  that category's order; PUT /reorder with category_id orders within a category. category_id
  stays as dev scaffolding (section 3.3): output = primary, input = "move the primary".
- Primary category: ticket grouping and prep-zone category order, the order-item category
  snapshot (1.12), report filters for waste-only rows and /meta/products.
- Every listing: price modifier / deal / min-quantity category targets, deal free choices,
  the QR menu snapshot (product in each category it's listed in; images pushed once).
- Catalogue export v2: each category lists all its products with "primary" and
  "category_sort_order"; import restores listings and order. v1 files are refused (D-21).
- New errors catalog.unknown_category, catalog.primary_not_listed.
This commit is contained in:
2026-11-13 12:39:02 +02:00
parent 3c5751025c
commit 6d42be95f8
20 changed files with 445 additions and 56 deletions
+2
View File
@@ -85,6 +85,8 @@ CODES: dict[str, tuple[int, str]] = {
# domain
"order.not_found": (404, "Order {order_id} not found."),
"notification.not_found": (404, "Notification {notification_id} not found."),
"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."),
}
+4 -3
View File
@@ -59,7 +59,7 @@ import models.recovery_code # noqa: F401
from models.user import User, WaiterZone
from models.table import TableGroup, Table
from models.product import Category, Product
from models.product import Category, Product, ProductCategory
from models.order import Order, OrderItem, OrderWaiter, OrderAuditLog
from models.business_day import BusinessDay
from models.shift import WaiterShift
@@ -282,17 +282,18 @@ try:
cat_products = []
for prod_sort, (prod_name, prod_price, prod_cost) in enumerate(items):
p = db.query(Product).filter(Product.name == prod_name, Product.category_id == cat.id).first()
p = db.query(Product).filter(Product.name == prod_name, Product.primary_category_id == cat.id).first()
if not p:
p = Product(
name=prod_name,
category_id=cat.id,
primary_category_id=cat.id,
base_price=prod_price,
cost_simple=prod_cost,
is_available=True,
lifecycle_status="active",
sort_order=prod_sort,
)
p.memberships.append(ProductCategory(category_id=cat.id, sort_order=prod_sort))
db.add(p)
db.flush()
else:
@@ -0,0 +1,63 @@
"""product_categories + products.primary_category_id (multi-category) (D-23, step 1.13)
Hand-written data move: products.category_id becomes products.primary_category_id (new
column with a named FK, copied, old column dropped by the batch rebuild, which also drops
its unnamed FK), and every product with a category gets one listing in it, at its old
products.sort_order position. products.sort_order stays (global order for the current
screens).
Revision ID: 0013_product_categories
Revises: 0012_drop_product_printer_zone
Create Date: 2026-11-13 12:30:55.936976
"""
from alembic import op
import sqlalchemy as sa
revision = '0013_product_categories'
down_revision = '0012_drop_product_printer_zone'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('product_categories',
sa.Column('product_id', sa.Integer(), nullable=False),
sa.Column('category_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['product_id'], ['products.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('product_id', 'category_id')
)
with op.batch_alter_table('product_categories', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_product_categories_category_id'), ['category_id'], unique=False)
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('primary_category_id', sa.Integer(), nullable=True))
batch_op.create_index(batch_op.f('ix_products_primary_category_id'), ['primary_category_id'], unique=False)
batch_op.create_foreign_key('fk_products_primary_category_id', 'categories', ['primary_category_id'], ['id'])
# only ids of categories that still exist (v1 never enforced the FK)
op.execute("""UPDATE products SET primary_category_id = category_id
WHERE category_id IN (SELECT id FROM categories)""")
op.execute("""INSERT INTO product_categories (product_id, category_id, sort_order)
SELECT id, primary_category_id, COALESCE(sort_order, 0) FROM products
WHERE primary_category_id IS NOT NULL""")
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('category_id')
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('category_id', sa.INTEGER(), nullable=True))
op.execute("UPDATE products SET category_id = primary_category_id")
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_constraint('fk_products_primary_category_id', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_products_primary_category_id'))
batch_op.drop_column('primary_category_id')
with op.batch_alter_table('product_categories', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_product_categories_category_id'))
op.drop_table('product_categories')
+2 -2
View File
@@ -230,8 +230,8 @@ def _snapshot_item_names(session, flush_context, instances):
continue
product = session.get(Product, obj.product_id) if obj.product_id is not None else None
obj.product_name = product.name if product else f"#{obj.product_id}"
if obj.category_id is None and product is not None and product.category_id is not None:
obj.category_id = product.category_id
if obj.category_id is None and product is not None and product.primary_category_id is not None:
obj.category_id = product.primary_category_id # the PRIMARY category (D-23)
if obj.category_id is not None and obj.category_name is None:
cat = session.get(Category, obj.category_id)
obj.category_name = cat.name if cat else None
+33 -3
View File
@@ -17,7 +17,10 @@ class Category(Base):
# sub-categories only: if True, the accordion section is expanded by default on the PWA
auto_expanded = Column(Boolean, default=False, nullable=False)
products = relationship("Product", back_populates="category")
# Products whose PRIMARY category this is (tickets, reports). Every product listed in
# this category, primary or not: `memberships` (ProductCategory, D-23).
primary_products = relationship("Product", back_populates="primary_category")
memberships = relationship("ProductCategory", back_populates="category", cascade="all, delete-orphan")
subcategories = relationship("Category", back_populates="parent", foreign_keys="Category.parent_id")
parent = relationship("Category", back_populates="subcategories", remote_side="Category.id", foreign_keys="Category.parent_id")
@@ -28,7 +31,10 @@ class Product(Base):
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
description = Column(Text, nullable=True)
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
# D-23: a product can be listed in several categories (product_categories). The primary
# one decides ticket grouping, prep-zone category order and the category order items
# snapshot (D-18). It is always one of the product's categories (routers/products.py).
primary_category_id = Column(Integer, ForeignKey("categories.id"), nullable=True, index=True)
base_price = Column(Float, nullable=False)
is_available = Column(Boolean, default=True, nullable=False)
# "active" | "archived" — archived products are kept for order history but hidden from active use
@@ -68,7 +74,18 @@ class Product(Base):
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
fiscal_vat_group_id = Column(Integer, nullable=True) # machine VAT group ID (1-based integer)
category = relationship("Category", back_populates="products")
primary_category = relationship("Category", back_populates="primary_products")
memberships = relationship("ProductCategory", back_populates="product", cascade="all, delete-orphan",
order_by="ProductCategory.category_id")
@property
def category_ids(self) -> list[int]:
"""The categories it's listed in, primary first."""
ids = [m.category_id for m in self.memberships]
if self.primary_category_id in ids:
ids.remove(self.primary_category_id)
ids.insert(0, self.primary_category_id)
return ids
prep_zones = relationship("PrepZone", secondary="product_prep_zones", back_populates="products")
quick_options = relationship("ProductQuickOption", back_populates="product", cascade="all, delete-orphan")
options = relationship("ProductOption", back_populates="product", cascade="all, delete-orphan")
@@ -186,3 +203,16 @@ class ProductPreferenceChoice(Base):
is_compact = Column(Boolean, default=False, nullable=False)
set = relationship("ProductPreferenceSet", back_populates="choices")
class ProductCategory(Base):
"""A product listed in a category, with its position in that category's list (D-23)."""
__tablename__ = "product_categories"
product_id = Column(Integer, ForeignKey("products.id", ondelete="CASCADE"), primary_key=True)
category_id = Column(Integer, ForeignKey("categories.id", ondelete="CASCADE"), primary_key=True, index=True)
sort_order = Column(Integer, nullable=False, default=0)
product = relationship("Product", back_populates="memberships")
category = relationship("Category", back_populates="memberships")
+37 -15
View File
@@ -16,7 +16,8 @@ from routers.deps import require_manager
router = APIRouter()
EXPORT_VERSION = 1
EXPORT_VERSION = 1 # tables bundle
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23)
def _serialize_product(p: Product) -> dict:
@@ -62,7 +63,12 @@ def _serialize_product(p: Product) -> dict:
def _serialize_category(cat: Category) -> dict:
products = [_serialize_product(p) for p in cat.products if p.lifecycle_status != "archived"]
# Every product LISTED in this category (D-23), in its order there. A product listed in
# several categories appears in each; "primary" marks its main one.
listings = sorted(cat.memberships, key=lambda m: (m.sort_order, m.product_id))
products = [{**_serialize_product(m.product), "primary": m.product.primary_category_id == cat.id,
"category_sort_order": m.sort_order}
for m in listings if m.product.lifecycle_status != "archived"]
return {
"name": cat.name, "color": cat.color, "sort_order": cat.sort_order,
"parent_name": cat.parent.name if cat.parent else None,
@@ -76,7 +82,7 @@ def export_catalog(db: Session = Depends(get_db), user: User = Depends(require_m
categories = db.query(Category).order_by(Category.sort_order).all()
orphan_products = (
db.query(Product)
.filter(Product.category_id == None, Product.lifecycle_status != "archived")
.filter(~Product.memberships.any(), Product.lifecycle_status != "archived")
.order_by(Product.sort_order)
.all()
)
@@ -85,7 +91,7 @@ def export_catalog(db: Session = Depends(get_db), user: User = Depends(require_m
"uncategorized_products": [_serialize_product(p) for p in orphan_products],
}
payload = {
"xenia_export_version": EXPORT_VERSION,
"xenia_export_version": CATALOG_EXPORT_VERSION,
"bundle": "catalog",
"exported_at": utcnow().isoformat(),
"data": data,
@@ -139,7 +145,7 @@ def export_tables(db: Session = Depends(get_db), user: User = Depends(require_ma
def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)):
if payload.get("bundle") != "catalog":
raise HTTPException(status_code=400, detail="Wrong bundle type. Expected 'catalog'.")
if payload.get("xenia_export_version", 0) != EXPORT_VERSION:
if payload.get("xenia_export_version", 0) != CATALOG_EXPORT_VERSION:
raise HTTPException(status_code=400, detail="Unsupported export version.")
data = payload.get("data", {})
@@ -170,14 +176,13 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
db.flush()
return cat
def _upsert_product(prod_data: dict, category_id=None):
def _upsert_product(prod_data: dict):
existing = db.query(Product).filter(Product.name == prod_data["name"]).first()
if existing:
existing.base_price = prod_data["base_price"]
existing.is_available = prod_data.get("is_available", True)
existing.lifecycle_status = prod_data.get("lifecycle_status", "active")
existing.sort_order = prod_data.get("sort_order", 0)
existing.category_id = category_id
db.flush()
product = existing
else:
@@ -187,7 +192,6 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
is_available=prod_data.get("is_available", True),
lifecycle_status=prod_data.get("lifecycle_status", "active"),
sort_order=prod_data.get("sort_order", 0),
category_id=category_id,
)
db.add(product)
db.flush()
@@ -242,12 +246,19 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
if idx is not None and 0 <= idx < len(created_choices):
ps.default_choice_id = created_choices[idx].id
# Listings: product name -> [(category id, position, primary, data)]. Products are
# upserted once (from their primary listing) after all categories exist (D-23).
listings: dict = {}
def _collect(cat, cat_data):
for i, prod_data in enumerate(cat_data.get("products", [])):
listings.setdefault(prod_data["name"], []).append(
(cat.id, prod_data.get("category_sort_order", i), bool(prod_data.get("primary")), prod_data))
# First pass: top-level categories (parent_name is None)
for cat_data in categories_data:
if cat_data.get("parent_name") is None:
cat = _upsert_category(cat_data, parent_id=None)
for prod_data in cat_data.get("products", []):
_upsert_product(prod_data, category_id=cat.id)
_collect(_upsert_category(cat_data, parent_id=None), cat_data)
# Second pass: sub-categories (parent must already exist from first pass)
for cat_data in categories_data:
@@ -257,13 +268,24 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
Category.parent_id == None,
).first()
parent_id = parent.id if parent else None
cat = _upsert_category(cat_data, parent_id=parent_id)
for prod_data in cat_data.get("products", []):
_upsert_product(prod_data, category_id=cat.id)
_collect(_upsert_category(cat_data, parent_id=parent_id), cat_data)
from models.product import ProductCategory
from services.catalog import set_categories
for name, rows in listings.items():
primary = next((r for r in rows if r[2]), rows[0])
_upsert_product(primary[3])
product = db.query(Product).filter(Product.name == name).first()
set_categories(db, product, [r[0] for r in rows], primary[0])
db.flush()
for cat_id, pos, _p, _d in rows:
db.get(ProductCategory, (product.id, cat_id)).sort_order = pos
# Uncategorized products (no category)
for prod_data in data.get("uncategorized_products", []):
_upsert_product(prod_data, category_id=None)
_upsert_product(prod_data)
product = db.query(Product).filter(Product.name == prod_data["name"]).first()
set_categories(db, product, [], None)
db.commit()
return {"ok": True, "message": "Catalog imported successfully."}
+8 -4
View File
@@ -508,7 +508,8 @@ def add_items(
existing_cart = [
{
"product_id": i.product_id,
"category_id": i.product.category_id if i.product else None,
"category_id": i.product.primary_category_id if i.product else None,
"category_ids": i.product.category_ids if i.product else [],
"quantity": i.quantity,
"unit_price": i.unit_price,
}
@@ -539,7 +540,8 @@ def add_items(
cart_items=existing_cart + [
{
"product_id": product.id,
"category_id": product.category_id,
"category_id": product.primary_category_id,
"category_ids": product.category_ids,
"quantity": item_in.quantity,
"unit_price": product.base_price + extra_cost,
}
@@ -589,7 +591,8 @@ def add_items(
# Update rolling cart snapshot so subsequent items in this batch see correct context
existing_cart.append({
"product_id": product.id,
"category_id": product.category_id,
"category_id": product.primary_category_id,
"category_ids": product.category_ids,
"quantity": item_in.quantity,
"unit_price": unit_price,
})
@@ -665,7 +668,8 @@ def add_items(
final_cart = [
{
"product_id": i.product_id,
"category_id": i.product.category_id if i.product else None,
"category_id": i.product.primary_category_id if i.product else None,
"category_ids": i.product.category_ids if i.product else [],
"quantity": i.quantity,
"unit_price": i.unit_price,
}
+40 -5
View File
@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session
from typing import List
from database import get_db
from models.product import Product, Category, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup
from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup
from models.prep_zone import PrepZone
from models.order import OrderItem
from models.user import User
@@ -253,6 +253,8 @@ def delete_category(category_id: int, db: Session = Depends(get_db), user: User
cat = db.query(Category).filter(Category.id == category_id).first()
if not cat:
raise HTTPException(status_code=404, detail="Category not found")
from services.catalog import remove_category
remove_category(db, category_id) # its listings go; products whose main category it was get their next one
db.delete(cat)
db.commit()
_broadcast_products_changed()
@@ -261,15 +263,39 @@ def delete_category(category_id: int, db: Session = Depends(get_db), user: User
# ── Products ──────────────────────────────────────────────────────────────────
@router.get("/", response_model=List[ProductOut])
def list_products(all: bool = False, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
q = db.query(Product)
def list_products(all: bool = False, category_id: int | None = None, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Every product once, with `category_ids` / `categories` (D-23). With `category_id`:
the products LISTED in that category (primary or not), in that category's order."""
from sqlalchemy.orm import selectinload
q = db.query(Product).options(selectinload(Product.memberships), selectinload(Product.prep_zones))
has_dashboard = holds(user, "core.dashboard.access")
if not all or not has_dashboard:
# Waiters only see active, available products
q = q.filter(Product.is_available == True, Product.lifecycle_status == "active")
if category_id is not None:
q = q.join(ProductCategory, ProductCategory.product_id == Product.id) \
.filter(ProductCategory.category_id == category_id) \
.order_by(ProductCategory.sort_order, Product.id)
return q.all()
return q.order_by(Product.sort_order, Product.id).all()
def _apply_categories(db, product, body, creating: bool) -> None:
"""category_ids / primary_category_id, or the scaffolding category_id (§3.3)."""
from services.catalog import set_categories
sent = body.model_fields_set
if body.category_ids is not None:
set_categories(db, product, body.category_ids, body.primary_category_id)
elif body.primary_category_id is not None:
set_categories(db, product, product.category_ids + [body.primary_category_id], body.primary_category_id)
elif "category_id" in sent or (creating and body.category_id is not None):
# current screens: "the product's category" = replace the primary
rest = [c for c in product.category_ids if c != product.primary_category_id]
new = body.category_id
set_categories(db, product, ([new] if new else []) + rest, new)
class BulkPrepZoneBody(BaseModel):
product_ids: List[int]
prep_zone_ids: List[int]
@@ -289,6 +315,11 @@ def bulk_assign_prep_zones(body: BulkPrepZoneBody, db: Session = Depends(get_db)
@router.put("/reorder", status_code=status.HTTP_204_NO_CONTENT)
def reorder_products(items: List[ProductReorderItem], db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
for item in items:
if item.category_id is not None:
m = db.get(ProductCategory, (item.id, item.category_id))
if m:
m.sort_order = item.sort_order
continue
product = db.query(Product).filter(Product.id == item.id).first()
if product:
product.sort_order = item.sort_order
@@ -298,7 +329,8 @@ 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"})
data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags",
"category_id", "primary_category_id", "category_ids"})
if data.get("sort_order") == 0:
data["sort_order"] = db.query(Product).count()
if body.cost_breakdown is not None:
@@ -307,6 +339,7 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
product = Product(**data)
db.add(product)
db.flush()
_apply_categories(db, product, body, creating=True)
# Assign prep zones
if body.prep_zone_ids:
zones = db.query(PrepZone).filter(PrepZone.id.in_(body.prep_zone_ids)).all()
@@ -356,10 +389,12 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
raise HTTPException(status_code=404, detail="Product not found")
scalar_fields = body.model_dump(
exclude_none=True,
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups"},
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
"category_id", "primary_category_id", "category_ids"},
)
for field, value in scalar_fields.items():
setattr(product, field, value)
_apply_categories(db, product, body, creating=False)
# Update prep zones if provided
if body.prep_zone_ids is not None:
zones = db.query(PrepZone).filter(PrepZone.id.in_(body.prep_zone_ids)).all()
+5 -4
View File
@@ -1060,12 +1060,12 @@ def product_performance(
for pid, wdata in waste_by_product.items():
if pid not in summary:
product = products_db.get(pid)
if category_id and (not product or product.category_id != category_id):
if category_id and (not product or product.primary_category_id != category_id):
continue
summary[pid] = {
"product_id": pid,
"product_name": product.name if product else f"#{pid}",
"category_id": product.category_id if product else None,
"category_id": product.primary_category_id if product else None,
"qty_sold": 0, "revenue": 0.0, "total_cost": 0.0, "trackable_profit": 0.0,
"uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(),
}
@@ -1702,8 +1702,9 @@ def meta_products(
{
"id": p.id,
"name": p.name,
"category_id": p.category_id,
"category_name": categories_db.get(p.category_id, "—"),
"category_id": p.primary_category_id,
"category_ids": p.category_ids, # every category it's listed in (D-23)
"category_name": categories_db.get(p.primary_category_id, "—"),
"price": float(p.base_price),
}
for p in products
+19 -2
View File
@@ -311,7 +311,12 @@ class CostBreakdownItem(BaseModel):
class ProductBase(BaseModel):
name: str
description: Optional[str] = None
# D-23: listed in category_ids (primary first in output); primary_category_id decides
# tickets/reports. category_id is DEV SCAFFOLDING (§3.3) for the current manager and
# waiter screens: in output = the primary; as input = "move the product's primary to".
category_id: Optional[int] = None
primary_category_id: Optional[int] = None
category_ids: Optional[List[int]] = None
base_price: float
# piece | portion | kg | liter | gram | ml
unit_type: str = "piece"
@@ -353,7 +358,9 @@ class ProductCreate(ProductBase):
class ProductUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
category_id: Optional[int] = None
category_id: Optional[int] = None # scaffolding, see ProductBase
primary_category_id: Optional[int] = None
category_ids: Optional[List[int]] = None # None = memberships unchanged
base_price: Optional[float] = None
unit_type: Optional[str] = None
is_available: Optional[bool] = None
@@ -390,10 +397,17 @@ class ProductUpdate(BaseModel):
class ProductReorderItem(BaseModel):
id: int
sort_order: int
category_id: Optional[int] = None # set: position within that category (D-23); unset: global order (v1)
class ProductCategoryOut(BaseModel):
category_id: int
sort_order: int
class ProductOut(ProductBase):
id: int
categories: List[ProductCategoryOut] = [] # every listing with its position in that category
quick_options: List[ProductQuickOptionOut] = []
options: List[ProductOptionOut] = []
ingredients: List[ProductIngredientOut] = []
@@ -419,7 +433,10 @@ class ProductOut(ProductBase):
'id': data.id,
'name': data.name,
'description': data.description,
'category_id': data.category_id,
'category_id': data.primary_category_id, # scaffolding (§3.3)
'primary_category_id': data.primary_category_id,
'category_ids': data.category_ids,
'categories': [{'category_id': m.category_id, 'sort_order': m.sort_order} for m in data.memberships],
'base_price': data.base_price,
'unit_type': getattr(data, 'unit_type', 'piece') or 'piece',
'is_available': data.is_available,
+52
View File
@@ -0,0 +1,52 @@
"""Product ↔ category membership (APPS_PLATFORM D-23, plan step 1.13).
A product is listed in any number of categories (product_categories, each with its own
position) and has one primary category (products.primary_category_id) that decides
ticket grouping, prep-zone category order and the category snapshot on order items.
Rule: the primary is always one of the product's categories; no categories = no primary.
Change memberships only through set_categories().
"""
from __future__ import annotations
from core.errors import XeniaError
def set_categories(db, product, category_ids, primary_id=None) -> None:
"""Make `product` listed in exactly `category_ids` with `primary_id` as primary
(default: the current primary if kept, else the first). Kept memberships keep their
position; new ones go to the end of that category. Validates ids. Doesn't commit."""
from models.product import Category, ProductCategory
wanted = list(dict.fromkeys(int(c) for c in category_ids or []))
if primary_id is not None and primary_id not in wanted:
raise XeniaError("catalog.primary_not_listed", category_id=primary_id)
found = {c.id for c in db.query(Category.id).filter(Category.id.in_(wanted))} if wanted else set()
missing = [c for c in wanted if c not in found]
if missing:
raise XeniaError("catalog.unknown_category", category_id=missing[0])
current = {m.category_id: m for m in product.memberships}
product.memberships = [m for cid, m in current.items() if cid in wanted]
for cid in wanted:
if cid not in current:
last = db.query(ProductCategory.sort_order).filter(ProductCategory.category_id == cid) \
.order_by(ProductCategory.sort_order.desc()).first()
product.memberships.append(ProductCategory(category_id=cid, sort_order=(last[0] + 1) if last else 0))
if primary_id is None:
primary_id = product.primary_category_id if product.primary_category_id in wanted else (wanted[0] if wanted else None)
product.primary_category_id = primary_id
def remove_category(db, category_id: int) -> None:
"""Before deleting a category: drop its memberships and give products that had it as
primary their next category (or none). Doesn't commit."""
from models.product import Product, ProductCategory
for p in db.query(Product).filter(Product.primary_category_id == category_id).all():
rest = [c for c in p.category_ids if c != category_id]
p.primary_category_id = rest[0] if rest else None
db.query(ProductCategory).filter(ProductCategory.category_id == category_id).delete()
db.flush()
# The category's loaded collections are stale now; without this, deleting it would
# null primary_category_id on the products just moved to their next category.
from models.product import Category
cat = db.get(Category, category_id)
if cat is not None:
db.expire(cat)
+6 -4
View File
@@ -255,7 +255,7 @@ async def _push_menu_snapshot():
try:
from database import SessionLocal
from models.product import Category, Product
from models.product import Category, Product, ProductCategory
db = SessionLocal()
try:
@@ -263,17 +263,19 @@ async def _push_menu_snapshot():
payload_categories = []
all_products = []
for cat in categories:
# every product LISTED in this category, in its order there (D-23)
products = (
db.query(Product)
.join(ProductCategory, ProductCategory.product_id == Product.id)
.filter(
Product.category_id == cat.id,
ProductCategory.category_id == cat.id,
Product.digital_visible == 1,
Product.lifecycle_status == "active",
)
.order_by(Product.sort_order)
.order_by(ProductCategory.sort_order, Product.id)
.all()
)
all_products.extend(products)
all_products.extend(p for p in products if p not in all_products) # once, even if listed twice
product_list = []
for p in products:
product_list.append({
+6 -5
View File
@@ -35,7 +35,7 @@ class OrderContext:
"""Snapshot of order-level facts needed to evaluate conditions."""
channel: str # 'pos' | 'online' | 'qr' | 'takeaway'
now: datetime # current UTC time
cart_items: list # list of {product_id, category_id, quantity, unit_price}
cart_items: list # list of {product_id, category_id (primary), category_ids, quantity, unit_price}
active_price_group_ids: set # set of PriceGroup.id that are currently active
user_tier: Optional[str] = None # 'bronze'|'silver'|'gold' — placeholder
@@ -124,7 +124,7 @@ def _eval_condition(ctype: str, params: dict, ctx: OrderContext,
cat_id = params.get("category_id")
cart_qty = sum(
ci["quantity"] for ci in ctx.cart_items
if ci.get("category_id") == cat_id
if cat_id in (ci.get("category_ids") or [ci.get("category_id")])
)
passed = cart_qty >= params.get("min", 1)
return passed, {"min_category_qty": cart_qty}
@@ -269,7 +269,7 @@ def _modifier_targets_product(modifier, product, db: Session) -> bool:
return True
if t.target_type == "category":
ids = _parse_ids(t.target_ids) or ([t.target_id] if t.target_id else [])
if product.category_id in ids:
if any(c in ids for c in product.category_ids): # listed in a target category (D-23)
return True
if t.target_type == "prep_zone":
ids = _parse_ids(t.target_ids) or ([t.target_id] if t.target_id else [])
@@ -414,7 +414,7 @@ def _deal_targets_met(deal, ctx: OrderContext, db: Session) -> bool:
return True
if target.target_type == "category":
ids = _parse_ids(target.target_ids) or ([target.target_id] if target.target_id else [])
if any(ci.get("category_id") in ids for ci in ctx.cart_items):
if any(c in ids for ci in ctx.cart_items for c in (ci.get("category_ids") or [ci.get("category_id")])):
return True
if target.target_type == "tag":
tags = _parse_ids(target.target_tags) or ([target.target_tag] if target.target_tag else [])
@@ -483,8 +483,9 @@ def evaluate_deals(
prods = db.query(Product).filter(Product.id.in_(target_ids)).all()
offer.free_choices = [{"id": p.id, "name": p.name} for p in prods]
elif deal.action_free_target_type == "category":
from models.product import ProductCategory
prods = db.query(Product).filter(
Product.category_id.in_(target_ids),
Product.id.in_(db.query(ProductCategory.product_id).filter(ProductCategory.category_id.in_(target_ids))),
Product.lifecycle_status == "active",
Product.is_available == True, # noqa: E712
).all()
+3 -3
View File
@@ -446,7 +446,7 @@ def send_test_order_print(ip: str, port: int, db: Session, line_width: int = LIN
class _P:
name = _FAKE_NAMES[self._filter_id]
unit_type = "piece"
category_id = None
primary_category_id = None
return _P()
return _orig_query(self._model).filter(self._model.id == self._filter_id).first()
@@ -568,8 +568,8 @@ def _sort_and_group_items(items: List[OrderItem], zone, db: Session) -> List[Ord
def _cat_for_item(item: OrderItem) -> int:
product = db.query(Product).filter(Product.id == item.product_id).first()
if product and product.category_id:
return product.category_id
if product and product.primary_category_id: # tickets group by the PRIMARY category (D-23)
return product.primary_category_id
return 0
cat_id_for = {item.id: _cat_for_item(item) for item in items}
+1 -1
View File
@@ -100,7 +100,7 @@ def _orders_at(db, user, days_ago_list):
cat = Category(name="C")
db.add(cat)
db.flush()
prod = Product(name="P", base_price=5.0, category_id=cat.id)
prod = Product(name="P", base_price=5.0, primary_category_id=cat.id)
db.add(prod)
db.flush()
for d in days_ago_list:
+1 -1
View File
@@ -97,7 +97,7 @@ def _order_with_item(db, make_user):
table = Table(number=7)
db.add_all([cat, table])
db.flush()
prod = Product(name="Souvlaki", base_price=3.5, category_id=cat.id)
prod = Product(name="Souvlaki", base_price=3.5, primary_category_id=cat.id)
db.add(prod)
db.flush()
order = Order(opened_by=waiter.id, table_id=table.id, status="open")
+2 -2
View File
@@ -11,7 +11,7 @@ def sold(db, make_user):
coffees, drinks = Category(name="Coffees"), Category(name="Drinks")
db.add_all([coffees, drinks])
db.flush()
prod = Product(name="Freddo", base_price=4.0, category_id=coffees.id)
prod = Product(name="Freddo", base_price=4.0, primary_category_id=coffees.id)
db.add(prod)
db.flush()
order = Order(opened_by=waiter.id, order_type="takeaway")
@@ -21,7 +21,7 @@ def sold(db, make_user):
for _ in range(2)]
db.add_all(items)
db.commit()
prod.name, prod.category_id = "Freddo Espresso", drinks.id
prod.name, prod.primary_category_id = "Freddo Espresso", drinks.id
coffees.name = "Hot & cold coffees"
db.commit()
return {"product": prod, "coffees": coffees, "drinks": drinks, "items": items, "order": order}
+159
View File
@@ -0,0 +1,159 @@
"""A product in several categories (plan step 1.13, APPS_PLATFORM D-23)."""
from types import SimpleNamespace
import pytest
def err(r):
return r.json()["error"]["code"]
@pytest.fixture
def menu(db):
from models.product import Category
cats = {n: Category(name=n, sort_order=i) for i, n in enumerate(("Coffees", "Breakfast", "Drinks"))}
db.add_all(cats.values())
db.commit()
return {n: c.id for n, c in cats.items()}
@pytest.fixture
def owner_h(make_user, login):
return login(make_user(role="owner"))
def create(client, h, name, **body):
r = client.post("/api/products/", headers=h, json={"name": name, "base_price": 3.0, **body})
assert r.status_code == 201, r.text
return r.json()
def listed(client, h, cat_id):
return [p["name"] for p in client.get("/api/products/", headers=h, params={"category_id": cat_id}).json()]
# ── done when ────────────────────────────────────────────────────────────────
def test_product_in_two_lists(client, menu, owner_h, make_user, login):
freddo = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]],
primary_category_id=menu["Coffees"])
create(client, owner_h, "Toast", category_ids=[menu["Breakfast"]])
assert freddo["category_ids"] == [menu["Coffees"], menu["Breakfast"]]
assert freddo["primary_category_id"] == menu["Coffees"] and freddo["category_id"] == menu["Coffees"] # scaffolding
# manager API and the waiter catalogue endpoint
waiter_h = login(make_user(role="waiter"), client="waiter")
for h in (owner_h, waiter_h):
assert listed(client, h, menu["Coffees"]) == ["Freddo"]
assert listed(client, h, menu["Breakfast"]) == ["Freddo", "Toast"]
everything = {p["name"]: p for p in client.get("/api/products/", headers=h).json()}
assert set(everything["Freddo"]["category_ids"]) == {menu["Coffees"], menu["Breakfast"]}
# each list has its own order
r = client.put("/api/products/reorder", headers=owner_h, json=[
{"id": freddo["id"], "sort_order": 9, "category_id": menu["Breakfast"]}])
assert r.status_code == 204
assert listed(client, owner_h, menu["Breakfast"]) == ["Toast", "Freddo"]
assert listed(client, owner_h, menu["Coffees"]) == ["Freddo"]
def test_prints_under_primary_and_reports_group_once(client, db, menu, owner_h, make_user):
from models.order import Order, OrderItem
from services.printer_service import _sort_and_group_items
freddo = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]],
primary_category_id=menu["Coffees"])
toast = create(client, owner_h, "Toast", category_ids=[menu["Breakfast"]])
waiter = make_user(role="waiter")
order = Order(opened_by=waiter.id, order_type="takeaway")
db.add(order)
db.flush()
items = [OrderItem(order_id=order.id, product_id=pid, added_by=waiter.id, quantity=1, unit_price=3.0)
for pid in (freddo["id"], toast["id"])]
db.add_all(items)
db.commit()
assert items[0].category_id == menu["Coffees"] and items[0].category_name == "Coffees" # snapshot = primary
# ticket grouping by category: zone order Breakfast, Coffees -> Toast first, Freddo with the coffees
zone = SimpleNamespace(sort_items_by="order_time", group_by_category=True,
category_order=f'[{menu["Breakfast"]}, {menu["Coffees"]}]')
assert [i.product_id for i in _sort_and_group_items(items, zone, db)] == [toast["id"], freddo["id"]]
cats = client.get("/api/reports/categories/performance", headers=owner_h).json()["categories"]
assert sorted((c["category_name"], c["units_sold"]) for c in cats) == [("Breakfast", 1), ("Coffees", 1)]
prods = client.get("/api/reports/products/performance", headers=owner_h).json()["products"]
assert sorted((p["product_name"], p["qty_sold"]) for p in prods) == [("Freddo", 1), ("Toast", 1)]
# ── editing ──────────────────────────────────────────────────────────────────
def test_validation(client, menu, owner_h):
r = client.post("/api/products/", headers=owner_h, json={"name": "X", "base_price": 1, "category_ids": [999]})
assert r.status_code == 422 and err(r) == "catalog.unknown_category"
r = client.post("/api/products/", headers=owner_h, json={"name": "X", "base_price": 1,
"category_ids": [menu["Coffees"]], "primary_category_id": menu["Drinks"]})
assert err(r) == "catalog.primary_not_listed"
def test_current_screens_category_id_moves_the_primary(client, menu, owner_h):
p = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]], primary_category_id=menu["Coffees"])
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"category_id": menu["Drinks"]})
assert r.json()["category_ids"] == [menu["Drinks"], menu["Breakfast"]] and r.json()["category_id"] == menu["Drinks"]
# sending the same category again (a plain re-save) changes nothing
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"category_id": menu["Drinks"], "base_price": 3.5})
assert r.json()["category_ids"] == [menu["Drinks"], menu["Breakfast"]]
# new primary among the existing ones
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"primary_category_id": menu["Breakfast"]})
assert r.json()["category_ids"] == [menu["Breakfast"], menu["Drinks"]]
# and a full replacement
r = client.put(f"/api/products/{p['id']}", headers=owner_h, json={"category_ids": []})
assert r.json()["category_ids"] == [] and r.json()["primary_category_id"] is None
def test_deleting_a_primary_category(client, menu, owner_h):
p = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]], primary_category_id=menu["Coffees"])
assert client.delete(f"/api/products/categories/{menu['Coffees']}", headers=owner_h).status_code == 204
out = next(x for x in client.get("/api/products/", headers=owner_h).json() if x["id"] == p["id"])
assert out["category_ids"] == [menu["Breakfast"]] and out["primary_category_id"] == menu["Breakfast"]
def test_pricing_category_target_covers_every_listing(db, client, menu, owner_h):
from models.product import Product
from services.pricing import _modifier_targets_product
p = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]], primary_category_id=menu["Coffees"])
product = db.get(Product, p["id"])
modifier = SimpleNamespace(targets=[SimpleNamespace(target_type="category", target_ids=f'[{menu["Breakfast"]}]', target_id=None)])
assert _modifier_targets_product(modifier, product, db)
modifier.targets[0].target_ids = f'[{menu["Drinks"]}]'
assert not _modifier_targets_product(modifier, product, db)
# ── export / import ──────────────────────────────────────────────────────────
def test_catalog_export_import_round_trip(client, menu, owner_h):
p = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]], primary_category_id=menu["Coffees"])
create(client, owner_h, "Toast", category_ids=[menu["Breakfast"]])
client.put("/api/products/reorder", headers=owner_h, json=[{"id": p["id"], "sort_order": 7, "category_id": menu["Breakfast"]}])
exported = client.get("/api/data-transfer/export/catalog", headers=owner_h).json()
assert exported["xenia_export_version"] == 2
bf = next(c for c in exported["data"]["categories"] if c["name"] == "Breakfast")
assert [(x["name"], x["primary"], x["category_sort_order"]) for x in bf["products"]] == [("Toast", True, 1), ("Freddo", False, 7)]
# break it, then import the export back
client.put(f"/api/products/{p['id']}", headers=owner_h, json={"category_ids": [menu["Drinks"]]})
r = client.post("/api/data-transfer/import/catalog", headers=owner_h, json=exported)
assert r.status_code == 200, r.text
out = next(x for x in client.get("/api/products/", headers=owner_h).json() if x["id"] == p["id"])
assert out["category_ids"] == [menu["Coffees"], menu["Breakfast"]]
assert {c["category_id"]: c["sort_order"] for c in out["categories"]}[menu["Breakfast"]] == 7
# a v1 file is refused (D-21: v1 menus come over through the migration tool)
old = {**exported, "xenia_export_version": 1}
assert client.post("/api/data-transfer/import/catalog", headers=owner_h, json=old).status_code == 400
def test_report_filters_product_list(client, menu, owner_h): # /meta/products (caught by the route smoke test)
p = create(client, owner_h, "Freddo", category_ids=[menu["Coffees"], menu["Breakfast"]], primary_category_id=menu["Coffees"])
meta = client.get("/api/reports/meta/products", headers=owner_h).json()["products"]
row = next(x for x in meta if x["id"] == p["id"])
assert row["category_id"] == menu["Coffees"] and row["category_name"] == "Coffees"
assert row["category_ids"] == [menu["Coffees"], menu["Breakfast"]]
+1 -1
View File
@@ -31,7 +31,7 @@ def venue(db, make_user, login):
cat = Category(name="Coffees")
db.add(cat)
db.flush()
prod = Product(name="Freddo", base_price=4.0, category_id=cat.id)
prod = Product(name="Freddo", base_price=4.0, primary_category_id=cat.id)
db.add(prod)
db.flush()
order = Order(opened_by=waiter.id, order_type="takeaway")
+1 -1
View File
@@ -188,7 +188,7 @@ def _day_with_late_order(db, manager):
cat = Category(name="Food")
db.add_all([bd, cat])
db.flush()
prod = Product(name="Pita", base_price=4.0, category_id=cat.id)
prod = Product(name="Pita", base_price=4.0, primary_category_id=cat.id)
db.add(prod)
db.flush()
order = Order(opened_by=manager.id, business_day_id=bd.id, status="closed",