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 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 11:33:55 +02:00
co-authored by Claude Opus 5.5
parent 834fe6e250
commit 82c6ca4e0a
6 changed files with 194 additions and 33 deletions
+40 -33
View File
@@ -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