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