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
+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