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