"""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)