From 82c6ca4e0aced20e27b84ecf51d463730dda218e Mon Sep 17 00:00:00 2001 From: bonamin Date: Fri, 13 Nov 2026 11:33:55 +0200 Subject: [PATCH] feat(backend): order items keep the product and category they were sold under; reports use them Platform v2 step 1.12 (APPS_PLATFORM D-18, CS-4). - order_items.product_name (NOT NULL), category_id, category_name (revision 0011, back-filled from the current catalogue). A before_flush hook in models/order.py fills them for every new item, whoever creates it; an item created with product_name set is left alone (importer). - Reports read the snapshots: order history, shift/printer/prep-zone breakdowns, cancellations, product and category performance (grouped by the category as sold, newest name in the period wins), and the printed product/category reports. Catalogue listings (unsold products in 'full' mode, meta endpoints, waste-only rows) keep live names on purpose. - Order detail and OrderItemOut expose product_name/category_id/category_name next to the live . Co-Authored-By: Claude Opus 5.5 --- .../versions/0011_order_item_names.py | 52 +++++++++++++ local_backend/models/order.py | 32 ++++++++ local_backend/routers/orders.py | 1 + local_backend/routers/reports.py | 73 ++++++++++--------- local_backend/schemas/order.py | 3 + local_backend/tests/test_item_snapshots.py | 66 +++++++++++++++++ 6 files changed, 194 insertions(+), 33 deletions(-) create mode 100644 local_backend/migrations/versions/0011_order_item_names.py create mode 100644 local_backend/tests/test_item_snapshots.py diff --git a/local_backend/migrations/versions/0011_order_item_names.py b/local_backend/migrations/versions/0011_order_item_names.py new file mode 100644 index 0000000..1f5d061 --- /dev/null +++ b/local_backend/migrations/versions/0011_order_item_names.py @@ -0,0 +1,52 @@ +"""order_items name snapshots (product_name, category_id, category_name) (D-18, step 1.12) + +Hand-edited: product_name is added nullable, back-filled from the CURRENT catalogue +(the best a v2 DB can know; v1 history comes through the migration tool, plan 7.1), +then made NOT NULL. Items of deleted products get "#". + +Revision ID: 0011_order_item_names +Revises: 0010_notifications +Create Date: 2026-11-13 11:29:59.346931 +""" +from alembic import op +import sqlalchemy as sa + + +revision = '0011_order_item_names' +down_revision = '0010_notifications' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.add_column(sa.Column('product_name', sa.String(), nullable=True)) + batch_op.add_column(sa.Column('category_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('category_name', sa.String(), nullable=True)) + batch_op.create_index(batch_op.f('ix_order_items_category_id'), ['category_id'], unique=False) + + # ### end Alembic commands ### + op.execute(""" + UPDATE order_items SET + product_name = COALESCE((SELECT p.name FROM products p WHERE p.id = order_items.product_id), + '#' || order_items.product_id), + category_id = (SELECT p.category_id FROM products p WHERE p.id = order_items.product_id) + """) + op.execute(""" + UPDATE order_items SET category_name = (SELECT c.name FROM categories c WHERE c.id = order_items.category_id) + WHERE category_id IS NOT NULL + """) + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.alter_column('product_name', existing_type=sa.String(), nullable=False) + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_order_items_category_id')) + batch_op.drop_column('category_name') + batch_op.drop_column('category_id') + batch_op.drop_column('product_name') + + # ### end Alembic commands ### diff --git a/local_backend/models/order.py b/local_backend/models/order.py index 7a71b0f..d9bb5ae 100644 --- a/local_backend/models/order.py +++ b/local_backend/models/order.py @@ -75,6 +75,13 @@ class OrderItem(Base): added_by = Column(Integer, ForeignKey("users.id"), nullable=False) quantity = Column(Float, nullable=False) unit_price = Column(Float, nullable=False) # price snapshot at time of order + # Name snapshots (D-18, CS-4): what the item was called, and its category, when it was + # ordered. Reports read these, so renaming or moving a product never rewrites history. + # Filled automatically for every new item by the before_flush hook at the end of this + # file; never updated afterwards. category_id is a plain id (categories can be deleted). + product_name = Column(String, nullable=False) + category_id = Column(Integer, nullable=True, index=True) + category_name = Column(String, nullable=True) selected_options = Column(Text, nullable=True) # JSON array of option ids removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids notes = Column(Text, nullable=True) @@ -204,3 +211,28 @@ class OrderDiscount(Base): order = relationship("Order", back_populates="discounts") item = relationship("OrderItem") applied_by_user = relationship("User") + + +# ── Name snapshots for new order items (D-18) ──────────────────────────────── +from sqlalchemy import event as _event # noqa: E402 +from sqlalchemy.orm import Session as _Session # noqa: E402 + + +@_event.listens_for(_Session, "before_flush") +def _snapshot_item_names(session, flush_context, instances): + """Every new OrderItem gets the product's current name and category, whoever creates + it (waiter, counter, online orders, deals, demo seed). An item created with a + product_name already set is left alone: the caller snapshots everything itself + (the v1 importer, plan 7.1).""" + from models.product import Category, Product + for obj in session.new: + if not isinstance(obj, OrderItem) or obj.product_name: + 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 not None and obj.category_name is None: + cat = session.get(Category, obj.category_id) + obj.category_name = cat.name if cat else None + diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py index e133636..8ee43f3 100644 --- a/local_backend/routers/orders.py +++ b/local_backend/routers/orders.py @@ -357,6 +357,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends "order_id": i.order_id, "product_id": i.product_id, "product": {"id": i.product.id, "name": i.product.name} if i.product else None, + "product_name": i.product_name, "category_id": i.category_id, "category_name": i.category_name, "added_by": i.added_by, "added_by_name": name_map.get(i.added_by), "quantity": i.quantity, diff --git a/local_backend/routers/reports.py b/local_backend/routers/reports.py index 90ee8d9..06dd96b 100644 --- a/local_backend/routers/reports.py +++ b/local_backend/routers/reports.py @@ -134,7 +134,7 @@ def shift_summary( "items": [], } summary[wid]["order_data"][oid]["total"] += val - product_name = item.product.name if item.product else f"#{item.product_id}" + product_name = item.product_name summary[wid]["order_data"][oid]["items"].append( {"name": product_name, "quantity": item.quantity} ) @@ -234,7 +234,7 @@ def shift_orders_summary( "items": [], } summary[wid]["order_data"][oid]["total"] += val - product_name = item.product.name if item.product else f"#{item.product_id}" + product_name = item.product_name summary[wid]["order_data"][oid]["items"].append( {"name": product_name, "quantity": item.quantity} ) @@ -351,7 +351,7 @@ def order_history( "id": item.id, "order_id": item.order_id, "product_id": item.product_id, - "product": {"id": item.product.id, "name": item.product.name} if item.product else None, + "product": {"id": item.product_id, "name": item.product_name}, # name as sold (D-18) "added_by": item.added_by, "added_by_name": _wname(item.added_by), "added_at": _dt_local(item.added_at), @@ -487,7 +487,7 @@ def printer_totals( val = _item_val(item) summary[pid]["total"] += val order_map[pid][oid]["total"] += val - product_name = item.product.name if item.product else f"#{item.product_id}" + product_name = item.product_name order_map[pid][oid]["items"].append({"name": product_name, "quantity": item.quantity}) result = [] @@ -555,7 +555,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m items_count += item.quantity val = _item_val(item) grand_total += val - product_name = item.product.name if item.product else f"#{item.product_id}" + product_name = item.product_name if oid in order_map: order_map[oid]["total"] += val order_map[oid]["items"].append({ @@ -628,7 +628,7 @@ def print_waiter( "table": tables.get(o.table_id, f"#{o.table_id}"), "total": total, "items": [ - {"name": (i.product.name if i.product else f"#{i.product_id}"), "quantity": i.quantity} + {"name": i.product_name, "quantity": i.quantity} for i in active_items ], }) @@ -782,18 +782,22 @@ def print_products( sold[pid]["qty"] += item.quantity sold[pid]["revenue"] += _item_val(item) + sold_names, _ = _names_as_sold(items) # names as sold (D-18) if body.mode == "full": - # All active products, 0-sold included + # All active products, 0-sold included (unsold ones under their current name), + # plus anything sold that's no longer active all_products = db.query(Product).filter(Product.lifecycle_status == "active").order_by(Product.name).all() + rows = {p.id: sold_names.get(p.id, p.name) for p in all_products} + rows.update(sold_names) report_items = sorted( - [{"name": p.name, "qty": sold.get(p.id, {}).get("qty", 0), "revenue": round(sold.get(p.id, {}).get("revenue", 0.0), 2)} for p in all_products], + [{"name": name, "qty": sold.get(pid, {}).get("qty", 0), "revenue": round(sold.get(pid, {}).get("revenue", 0.0), 2)} + for pid, name in rows.items()], key=lambda x: x["qty"], reverse=True, ) else: # Smart: only sold - products_db = {p.id: p for p in db.query(Product).all()} report_items = sorted( - [{"name": (products_db[pid].name if pid in products_db else f"#{pid}"), "qty": v["qty"], "revenue": round(v["revenue"], 2)} for pid, v in sold.items()], + [{"name": sold_names[pid], "qty": v["qty"], "revenue": round(v["revenue"], 2)} for pid, v in sold.items()], key=lambda x: x["qty"], reverse=True, ) @@ -834,23 +838,18 @@ def print_categories( ) items = q.all() - products_db = {p.id: p for p in db.query(Product).all()} - categories_db = {c.id: c for c in db.query(Category).all()} + prod_names, cat_names = _names_as_sold(items) # summary[cid] = {name, units_sold, revenue, products: {pid: {name, qty, revenue}}} summary: dict = {} for item in items: - product = products_db.get(item.product_id) - if not product: - continue - cid = product.category_id + cid = item.category_id # as sold (D-18) pid = item.product_id if cid not in summary: - cat = categories_db.get(cid) - summary[cid] = {"name": cat.name if cat else f"#{cid}", "units_sold": 0, "revenue": 0.0, "products": {}} + summary[cid] = {"name": cat_names.get(cid) or "—", "units_sold": 0, "revenue": 0.0, "products": {}} summary[cid]["units_sold"] += item.quantity summary[cid]["revenue"] += _item_val(item) if pid not in summary[cid]["products"]: - summary[cid]["products"][pid] = {"name": product.name, "qty": 0, "revenue": 0.0} + summary[cid]["products"][pid] = {"name": prod_names[pid], "qty": 0, "revenue": 0.0} summary[cid]["products"][pid]["qty"] += item.quantity summary[cid]["products"][pid]["revenue"] += _item_val(item) @@ -1025,17 +1024,17 @@ def product_performance( waste_by_product[pid]["waste_qty"] += w.quantity waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0 + sold_names, _ = _names_as_sold(items) summary: dict = {} for item in items: pid = item.product_id - product = products_db.get(pid) - if category_id and (not product or product.category_id != category_id): + if category_id and item.category_id != category_id: # the category it was sold in (D-18) continue if pid not in summary: summary[pid] = { "product_id": pid, - "product_name": product.name if product else f"#{pid}", - "category_id": product.category_id if product else None, + "product_name": sold_names[pid], + "category_id": item.category_id, "qty_sold": 0, "revenue": 0.0, "total_cost": 0.0, @@ -1415,6 +1414,17 @@ def revenue_trends( # Category performance # --------------------------------------------------------------------------- +def _names_as_sold(items) -> tuple[dict, dict]: + """{product_id: name}, {category_id: name} from the order items' snapshots (D-18, CS-4). + If a product or category was renamed within the period, the newest name sold wins.""" + pnames, cnames = {}, {} + for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)): + pnames[it.product_id] = it.product_name + if it.category_id is not None: + cnames[it.category_id] = it.category_name + return pnames, cnames + + @router.get("/categories/performance") def category_performance( from_dt: Optional[str] = Query(default=None, alias="from"), @@ -1435,20 +1445,17 @@ def category_performance( q = q.join(Order).filter(Order.business_day_id == business_day_id) items = q.all() - products_db = {p.id: p for p in db.query(Product).all()} categories_db = {c.id: c for c in db.query(Category).all()} + _, cat_names = _names_as_sold(items) summary: dict = {} for item in items: - product = products_db.get(item.product_id) - if not product: - continue - cid = product.category_id + cid = item.category_id # the category it was in when sold (D-18) if cid not in summary: cat = categories_db.get(cid) summary[cid] = { "category_id": cid, - "category_name": cat.name if cat else f"#{cid}", + "category_name": cat_names.get(cid) or "—", "color": cat.color if cat and hasattr(cat, "color") else None, "units_sold": 0, "revenue": 0.0, @@ -1547,7 +1554,7 @@ def cancellations_log( waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}" cancelled_by_user = waiters_db.get(item.cancelled_by) if item.cancelled_by else None cancelled_by_name = (cancelled_by_user.full_name or cancelled_by_user.username) if cancelled_by_user else None - product_name = item.product.name if item.product else f"#{item.product_id}" + product_name = item.product_name cancelled_at = getattr(item, "cancelled_at", None) result.append({ "id": item.id, @@ -1618,7 +1625,7 @@ def printer_history( for iid in item_ids: oi = db.query(OrderItem).filter(OrderItem.id == iid).first() if oi: - pname = oi.product.name if oi.product else f"#{oi.product_id}" + pname = oi.product_name items.append({"name": pname, "quantity": oi.quantity}) # Compute full order total (all active+paid items, not just printed slice) @@ -1907,7 +1914,7 @@ def prep_zones_report( for item in items: zids = product_zone_map.get(item.product_id, []) - pname = item.product.name if item.product else f"#{item.product_id}" + pname = item.product_name ivalue = round(_item_val(item), 2) order = item.order table_label = None @@ -2020,7 +2027,7 @@ def print_prep_zone( for item in items: if item.product_id not in product_ids: continue - pname = item.product.name if item.product else f"#{item.product_id}" + pname = item.product_name if pname not in product_counts: product_counts[pname] = {"count": 0, "value": 0.0} product_counts[pname]["count"] += item.quantity diff --git a/local_backend/schemas/order.py b/local_backend/schemas/order.py index c394ddd..dd827c9 100644 --- a/local_backend/schemas/order.py +++ b/local_backend/schemas/order.py @@ -42,6 +42,9 @@ class OrderItemOut(BaseModel): order_id: int product_id: int product: Optional[ProductNameOut] = None + product_name: Optional[str] = None # name when ordered (D-18); `product` is the live catalogue + category_id: Optional[int] = None # category when ordered + category_name: Optional[str] = None added_by: int quantity: float unit_type: str = "piece" diff --git a/local_backend/tests/test_item_snapshots.py b/local_backend/tests/test_item_snapshots.py new file mode 100644 index 0000000..9341f9e --- /dev/null +++ b/local_backend/tests/test_item_snapshots.py @@ -0,0 +1,66 @@ +"""Order items keep the product and category names they were sold under (plan step 1.12, D-18).""" +import pytest + + +@pytest.fixture +def sold(db, make_user): + """'Freddo' in 'Coffees', sold twice on one order, then renamed and moved to 'Drinks'.""" + from models.order import Order, OrderItem + from models.product import Category, Product + waiter = make_user(role="waiter") + 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) + db.add(prod) + db.flush() + order = Order(opened_by=waiter.id, order_type="takeaway") + db.add(order) + db.flush() + items = [OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=1, unit_price=4.0) + for _ in range(2)] + db.add_all(items) + db.commit() + prod.name, prod.category_id = "Freddo Espresso", drinks.id + coffees.name = "Hot & cold coffees" + db.commit() + return {"product": prod, "coffees": coffees, "drinks": drinks, "items": items, "order": order} + + +def test_items_snapshot_names_on_insert(db, sold): + it = sold["items"][0] + db.refresh(it) + assert (it.product_name, it.category_id, it.category_name) == ("Freddo", sold["coffees"].id, "Coffees") + + +def test_explicit_values_win(db, sold, make_user): + from models.order import OrderItem + it = OrderItem(order_id=sold["order"].id, product_id=sold["product"].id, added_by=make_user(role="waiter").id, + quantity=1, unit_price=4.0, product_name="Imported name", category_name=None) + db.add(it) + db.commit() + # an explicit product_name means the caller snapshots everything (e.g. an importer) + assert (it.product_name, it.category_id, it.category_name) == ("Imported name", None, None) + + +def test_reports_use_names_as_sold(client, sold, make_user, login): # "done when" + h = login(make_user(role="owner")) + products = client.get("/api/reports/products/performance", headers=h).json()["products"] + assert [(p["product_name"], p["category_id"], p["qty_sold"]) for p in products] == [("Freddo", sold["coffees"].id, 2)] + # filtering by category uses the category it was sold in + assert client.get("/api/reports/products/performance", headers=h, + params={"category_id": sold["drinks"].id}).json()["products"] == [] + + cats = client.get("/api/reports/categories/performance", headers=h).json()["categories"] + assert [(c["category_id"], c["category_name"], c["units_sold"]) for c in cats] == [(sold["coffees"].id, "Coffees", 2)] + + hist = client.get("/api/reports/orders/history", headers=h).json() + names = {i["product"]["name"] for o in hist for i in o["items"]} + assert names == {"Freddo"} + + +def test_api_exposes_snapshot_and_live_name(client, sold, make_user, login): + h = login(make_user(role="owner")) + item = client.get(f"/api/orders/{sold['order'].id}", headers=h).json()["items"][0] + assert item["product_name"] == "Freddo" and item["category_name"] == "Coffees" + assert item["product"]["name"] == "Freddo Espresso" # `product` is the live catalogue