feat: one way to count sales in every report; exports for Excel; the report kit and Today on v2 (platform-v2 step 6.12a)
- services/sales.py: sold = active + paid lines; a line's value net of what
was refunded of it; system lines (the delivery fee) counted apart as fees;
cost/profit with has_gap. Products, categories, tables, traffic, revenue
trends, business days (list and current), per-waiter sales, order history
totals and the printed products/categories/tables reports all use it (they
used to differ: closed-only vs all orders, fee as a product, refunds never
subtracted)
- the overview's day summary values lines with their price change (discounts
were valued at full price)
- services/csv_export.py: UTF-8 BOM, times in venue time with the zone in the
header, ';' and decimal commas for a Greek venue (',' and '.' otherwise);
every report export uses it; orders export has products / fees / refunded
- fix: /api/reports/shift/orders with business_day_id crashed (no window)
- manager: src/pages/reports/kit (page with tabs, period picker, panels,
figures, sortable table, export button, order dialog reusing the order
page's parts, hour chart on tokens) and reports/today on it; v1 Today removed
- tests: test_sales_accounting.py (a day with a fee and a partial refund adds
up the same in every report), test_reports_export.py (Excel format),
reports.test.mjs, e2e manager.mjs (Today, order dialog, export, Greek)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+105
-297
@@ -64,6 +64,7 @@ history_router = APIRouter(dependencies=[Depends(_business_day_guard("history"))
|
||||
|
||||
|
||||
from services.refunds import day_refunds # noqa: E402 (3.3e: refunds shown apart from revenue)
|
||||
from services import csv_export, sales # noqa: E402 (6.12a: one way to count sales; exports for Excel)
|
||||
|
||||
|
||||
def _item_val(item) -> float:
|
||||
@@ -163,6 +164,7 @@ def shift_orders_summary(
|
||||
):
|
||||
"""Items sent (added) per waiter — regardless of payment status."""
|
||||
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
|
||||
start = end = None # 6.12a: with a business day there is no window (was a crash)
|
||||
if business_day_id:
|
||||
q = q.join(Order).filter(Order.business_day_id == business_day_id)
|
||||
else:
|
||||
@@ -208,7 +210,10 @@ def shift_orders_summary(
|
||||
hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta
|
||||
|
||||
summary: dict[int, dict] = {}
|
||||
for item in items:
|
||||
for line in sales.lines(db, items): # 6.12a: net of refunds, the delivery fee left out
|
||||
if line.fee or not line.kept:
|
||||
continue
|
||||
item = line.item
|
||||
wid = item.added_by
|
||||
if wid not in summary:
|
||||
w = waiters_db.get(wid)
|
||||
@@ -221,8 +226,8 @@ def shift_orders_summary(
|
||||
"cancellations": 0,
|
||||
"order_data": {},
|
||||
}
|
||||
summary[wid]["items"] += item.quantity
|
||||
val = _item_val(item)
|
||||
summary[wid]["items"] += line.quantity
|
||||
val = line.value
|
||||
summary[wid]["total"] += val
|
||||
|
||||
oid = item.order_id
|
||||
@@ -239,7 +244,7 @@ def shift_orders_summary(
|
||||
summary[wid]["order_data"][oid]["total"] += val
|
||||
product_name = item.product_name
|
||||
summary[wid]["order_data"][oid]["items"].append(
|
||||
{"name": product_name, "quantity": item.quantity}
|
||||
{"name": product_name, "quantity": line.quantity}
|
||||
)
|
||||
|
||||
for item in cancelled_items:
|
||||
@@ -262,9 +267,11 @@ def shift_orders_summary(
|
||||
entry["orders"] = len(entry["order_data"])
|
||||
entry["order_data"] = list(entry["order_data"].values())
|
||||
entry["hours_worked"] = round(hours_by_waiter.get(entry["waiter_id"], 0.0), 2)
|
||||
entry["items"] = round(entry["items"], 3)
|
||||
entry["total"] = round(entry["total"], 2)
|
||||
result.append(entry)
|
||||
|
||||
return {"from": start.isoformat(), "to": end.isoformat(), "waiters": result}
|
||||
return {"from": _dt(start), "to": _dt(end), "waiters": result}
|
||||
|
||||
|
||||
@history_router.get("/orders/history")
|
||||
@@ -346,6 +353,7 @@ def order_history(
|
||||
return None
|
||||
return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat()
|
||||
|
||||
per_order = sales.order_totals(db, orders) # 6.12a: products net of refunds, fees apart
|
||||
result = []
|
||||
for o in orders:
|
||||
items_out = []
|
||||
@@ -362,6 +370,7 @@ def order_history(
|
||||
"unit_price": float(item.unit_price),
|
||||
"price_adjustment": float(item.price_adjustment or 0.0),
|
||||
"status": item.status,
|
||||
"system_key": item.system_key,
|
||||
"paid_by": item.paid_by,
|
||||
"paid_by_name": _wname(item.paid_by),
|
||||
"paid_at": _dt_local(item.paid_at),
|
||||
@@ -402,6 +411,7 @@ def order_history(
|
||||
"notes": o.notes,
|
||||
"business_day_id": o.business_day_id,
|
||||
"items": items_out,
|
||||
"totals": per_order[o.id].out(),
|
||||
"waiters": [{"waiter_id": w.waiter_id} for w in o.waiters],
|
||||
"audit_logs": audit_out,
|
||||
})
|
||||
@@ -777,15 +787,10 @@ def print_products(
|
||||
)
|
||||
items = q.all()
|
||||
|
||||
sold: dict = {}
|
||||
for item in items:
|
||||
pid = item.product_id
|
||||
if pid not in sold:
|
||||
sold[pid] = {"qty": 0, "revenue": 0.0}
|
||||
sold[pid]["qty"] += item.quantity
|
||||
sold[pid]["revenue"] += _item_val(item)
|
||||
|
||||
sold_names, _ = _names_as_sold(items) # names as sold (D-18)
|
||||
# 6.12a: the screen's numbers (net of refunds, the delivery fee left out), names as sold (D-18)
|
||||
per_product = sales.products(db, items)
|
||||
sold = {pid: {"qty": round(v["qty_sold"], 3), "revenue": v["revenue"]} for pid, v in per_product.items()}
|
||||
sold_names = {pid: v["product_name"] for pid, v in per_product.items()}
|
||||
if body.mode == "full":
|
||||
# All active products, 0-sold included (unsold ones under their current name),
|
||||
# plus anything sold that's no longer active
|
||||
@@ -841,20 +846,10 @@ def print_categories(
|
||||
)
|
||||
items = q.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:
|
||||
cid = item.category_id # as sold (D-18)
|
||||
pid = item.product_id
|
||||
if cid not in summary:
|
||||
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": prod_names[pid], "qty": 0, "revenue": 0.0}
|
||||
summary[cid]["products"][pid]["qty"] += item.quantity
|
||||
summary[cid]["products"][pid]["revenue"] += _item_val(item)
|
||||
# 6.12a: the screen's numbers (net of refunds, fees left out), as sold (D-18)
|
||||
summary: dict = {cid: {"name": v["category_name"], "units_sold": round(v["units_sold"], 3), "revenue": v["revenue"],
|
||||
"products": {pid: {**p, "qty": round(p["qty"], 3)} for pid, p in v["products"].items()}}
|
||||
for cid, v in sales.categories(db, items).items()}
|
||||
|
||||
total_rev = sum(v["revenue"] for v in summary.values())
|
||||
total_qty = sum(v["units_sold"] for v in summary.values())
|
||||
@@ -913,28 +908,9 @@ def print_tables(
|
||||
)
|
||||
orders = q.all()
|
||||
|
||||
tables_db = {t.id: t for t in db.query(Table).all()}
|
||||
summary: dict = {}
|
||||
for order in orders:
|
||||
tid = order.table_id
|
||||
if tid not in summary:
|
||||
t = tables_db.get(tid)
|
||||
summary[tid] = {
|
||||
"name": (t.label or f"T{t.number}") if t else f"#{tid}",
|
||||
"order_count": 0, "revenue": 0.0, "durations": [],
|
||||
}
|
||||
summary[tid]["order_count"] += 1
|
||||
summary[tid]["revenue"] += sum(_item_val(i) for i in order.items if i.status in ("active", "paid"))
|
||||
if order.closed_at and order.opened_at:
|
||||
summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60)
|
||||
|
||||
table_list = []
|
||||
for entry in summary.values():
|
||||
durations = entry.pop("durations")
|
||||
entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None
|
||||
entry["revenue"] = round(entry["revenue"], 2)
|
||||
table_list.append(entry)
|
||||
table_list.sort(key=lambda x: x["revenue"], reverse=True)
|
||||
# 6.12a: the screen's numbers
|
||||
table_list = [{"name": t["table_name"] or "—", "order_count": t["order_count"], "revenue": t["revenue"],
|
||||
"avg_duration_minutes": t["avg_duration_minutes"]} for t in _table_summary(db, orders)]
|
||||
|
||||
report = {
|
||||
"mode": body.mode,
|
||||
@@ -1027,37 +1003,8 @@ 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
|
||||
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": sold_names[pid],
|
||||
"category_id": item.category_id,
|
||||
"qty_sold": 0,
|
||||
"revenue": 0.0,
|
||||
"total_cost": 0.0,
|
||||
"trackable_profit": 0.0,
|
||||
"uncosted_revenue": 0.0,
|
||||
"uncosted_items": 0,
|
||||
"order_ids": set(),
|
||||
}
|
||||
qty = item.quantity
|
||||
revenue = _item_val(item)
|
||||
summary[pid]["qty_sold"] += qty
|
||||
summary[pid]["revenue"] += revenue
|
||||
summary[pid]["order_ids"].add(item.order_id)
|
||||
if item.unit_cost is not None:
|
||||
cost = item.unit_cost * qty
|
||||
summary[pid]["total_cost"] += cost
|
||||
summary[pid]["trackable_profit"] += revenue - cost
|
||||
else:
|
||||
summary[pid]["uncosted_revenue"] += revenue
|
||||
summary[pid]["uncosted_items"] += qty
|
||||
# 6.12a: net of refunds, the delivery fee left out (services/sales.py); the category it was sold in (D-18)
|
||||
summary: dict = sales.products(db, items, category_id)
|
||||
|
||||
# Also include products that only have waste (not sold) in the period
|
||||
for pid, wdata in waste_by_product.items():
|
||||
@@ -1069,7 +1016,7 @@ def product_performance(
|
||||
"product_id": pid,
|
||||
"product_name": product.name if product else f"#{pid}",
|
||||
"category_id": product.primary_category_id if product else None,
|
||||
"qty_sold": 0, "revenue": 0.0, "total_cost": 0.0, "trackable_profit": 0.0,
|
||||
"qty_sold": 0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0,
|
||||
"uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(),
|
||||
}
|
||||
|
||||
@@ -1078,7 +1025,10 @@ def product_performance(
|
||||
pid = entry["product_id"]
|
||||
wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0})
|
||||
entry["order_count"] = len(entry.pop("order_ids"))
|
||||
entry["qty_sold"] = round(entry["qty_sold"], 3)
|
||||
entry["uncosted_items"] = round(entry["uncosted_items"], 3)
|
||||
entry["revenue"] = round(entry["revenue"], 2)
|
||||
entry["refunded"] = round(entry["refunded"], 2)
|
||||
entry["total_cost"] = round(entry["total_cost"], 2)
|
||||
entry["trackable_profit"] = round(entry["trackable_profit"], 2)
|
||||
entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 2)
|
||||
@@ -1113,38 +1063,34 @@ def table_performance(
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
orders = q.all()
|
||||
|
||||
tables_db = {t.id: t for t in db.query(Table).all()}
|
||||
return {"tables": _table_summary(db, orders)}
|
||||
|
||||
|
||||
def _table_summary(db, orders) -> list[dict]:
|
||||
"""Per table: orders, revenue (products, net of refunds) and fees, average time (6.12a)."""
|
||||
tables_db = {t.id: t for t in db.query(Table).all()}
|
||||
per_order = sales.order_totals(db, orders)
|
||||
summary: dict = {}
|
||||
for order in orders:
|
||||
tid = order.table_id
|
||||
if tid not in summary:
|
||||
t = tables_db.get(tid)
|
||||
summary[tid] = {
|
||||
"table_id": tid,
|
||||
"table_name": (t.label or f"T{t.number}") if t else f"#{tid}",
|
||||
"order_count": 0,
|
||||
"revenue": 0.0,
|
||||
"durations": [],
|
||||
}
|
||||
summary[tid] = {"table_id": tid, "table_name": (t.label or f"T{t.number}") if t else None,
|
||||
"order_count": 0, "revenue": 0.0, "fees": 0.0, "durations": []}
|
||||
summary[tid]["order_count"] += 1
|
||||
summary[tid]["revenue"] += sum(
|
||||
_item_val(i) for i in order.items if i.status in ("active", "paid")
|
||||
)
|
||||
summary[tid]["revenue"] += per_order[order.id].revenue
|
||||
summary[tid]["fees"] += per_order[order.id].fees
|
||||
if order.closed_at and order.opened_at:
|
||||
summary[tid]["durations"].append(
|
||||
(order.closed_at - order.opened_at).total_seconds() / 60
|
||||
)
|
||||
|
||||
summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60)
|
||||
result = []
|
||||
for entry in summary.values():
|
||||
durations = entry.pop("durations")
|
||||
entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None
|
||||
entry["revenue"] = round(entry["revenue"], 2)
|
||||
entry["fees"] = round(entry["fees"], 2)
|
||||
result.append(entry)
|
||||
|
||||
result.sort(key=lambda x: x["revenue"], reverse=True)
|
||||
return {"tables": result}
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1193,10 +1139,8 @@ def traffic_analysis(
|
||||
q = q.filter(Order.business_day_id == business_day_id)
|
||||
orders = q.all()
|
||||
|
||||
by_hour, by_weekday = traffic_buckets(
|
||||
(order.opened_at, sum(_item_val(i) for i in order.items if i.status in ("active", "paid")))
|
||||
for order in orders
|
||||
)
|
||||
per_order = sales.order_totals(db, orders) # 6.12a: products, net of refunds
|
||||
by_hour, by_weekday = traffic_buckets((order.opened_at, per_order[order.id].revenue) for order in orders)
|
||||
|
||||
return {
|
||||
"by_hour": list(by_hour.values()),
|
||||
@@ -1231,22 +1175,8 @@ def business_days_list(
|
||||
cancelled_orders = [o for o in orders if o.status == "cancelled"]
|
||||
day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all()
|
||||
waiter_ids = {s.waiter_id for s in day_shifts}
|
||||
revenue = 0.0
|
||||
total_cost = 0.0
|
||||
trackable_profit = 0.0
|
||||
has_gap = False
|
||||
for o in closed_orders:
|
||||
for i in o.items:
|
||||
if i.status not in ("active", "paid"):
|
||||
continue
|
||||
rev = _item_val(i)
|
||||
revenue += rev
|
||||
if i.unit_cost is not None:
|
||||
cost = i.unit_cost * i.quantity
|
||||
total_cost += cost
|
||||
trackable_profit += rev - cost
|
||||
else:
|
||||
has_gap = True
|
||||
# 6.12a: everything sold that day (open orders too), net of refunds, fees apart
|
||||
money = sales.totals(sales.lines(db, [i for o in orders for i in o.items])).out()
|
||||
opener = waiters_db.get(d.opened_by_id)
|
||||
closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None
|
||||
result.append({
|
||||
@@ -1262,11 +1192,8 @@ def business_days_list(
|
||||
"cancellation_count": len(cancelled_orders),
|
||||
"waiter_count": len(waiter_ids),
|
||||
"shift_count": len(day_shifts),
|
||||
"revenue": round(revenue, 2),
|
||||
**money,
|
||||
"refunds": day_refunds(db, d.id),
|
||||
"total_cost": round(total_cost, 2),
|
||||
"trackable_profit": round(trackable_profit, 2),
|
||||
"has_gap": has_gap,
|
||||
})
|
||||
return {"business_days": result}
|
||||
|
||||
@@ -1288,37 +1215,21 @@ def current_business_day(
|
||||
WaiterShift.business_day_id == day.id,
|
||||
WaiterShift.ended_at == None,
|
||||
).all()
|
||||
revenue = 0.0
|
||||
total_cost = 0.0
|
||||
trackable_profit = 0.0
|
||||
has_gap = False
|
||||
for o in closed_orders:
|
||||
for i in o.items:
|
||||
if i.status not in ("active", "paid"):
|
||||
continue
|
||||
rev = _item_val(i)
|
||||
revenue += rev
|
||||
if i.unit_cost is not None:
|
||||
cost = i.unit_cost * i.quantity
|
||||
total_cost += cost
|
||||
trackable_profit += rev - cost
|
||||
else:
|
||||
has_gap = True
|
||||
day_lines = sales.lines(db, [i for o in orders for i in o.items])
|
||||
money = sales.totals(day_lines).out() # 6.12a: everything sold so far, net of refunds, fees apart
|
||||
|
||||
item_counts: dict = {}
|
||||
for o in orders:
|
||||
if o.status == "cancelled":
|
||||
item_names: dict = {}
|
||||
for line in day_lines:
|
||||
if line.fee or not line.kept:
|
||||
continue
|
||||
for item in o.items:
|
||||
if item.status in ("active", "paid"):
|
||||
pid = item.product_id
|
||||
item_counts[pid] = item_counts.get(pid, 0) + item.quantity
|
||||
pid = line.item.product_id
|
||||
item_counts[pid] = item_counts.get(pid, 0) + line.quantity
|
||||
item_names[pid] = line.item.product_name
|
||||
top_product_id = max(item_counts, key=item_counts.get) if item_counts else None
|
||||
top_product = None
|
||||
if top_product_id:
|
||||
from models.product import Product
|
||||
p = db.query(Product).filter(Product.id == top_product_id).first()
|
||||
top_product = {"id": top_product_id, "name": p.name if p else f"#{top_product_id}", "qty": item_counts[top_product_id]}
|
||||
top_product = {"id": top_product_id, "name": item_names.get(top_product_id) or f"#{top_product_id}", "qty": round(item_counts[top_product_id], 3)}
|
||||
|
||||
# Count cancelled items (individual items cancelled, across all orders in this day)
|
||||
all_order_ids = [o.id for o in orders]
|
||||
@@ -1339,11 +1250,8 @@ def current_business_day(
|
||||
"business_day": {
|
||||
"id": day.id,
|
||||
"opened_at": _dt(day.opened_at),
|
||||
"revenue": round(revenue, 2),
|
||||
**money,
|
||||
"refunds": day_refunds(db, day.id),
|
||||
"total_cost": round(total_cost, 2),
|
||||
"trackable_profit": round(trackable_profit, 2),
|
||||
"has_gap": has_gap,
|
||||
"orders_closed": len(closed_orders),
|
||||
"orders_open": len(open_orders),
|
||||
"active_waiters": len(active_shifts),
|
||||
@@ -1367,13 +1275,14 @@ def revenue_trends(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(Order).filter(Order.status.in_(["closed", "paid"]))
|
||||
q = db.query(Order).filter(Order.status != "cancelled") # 6.12a: what was sold, open orders too
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
if to_dt:
|
||||
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
|
||||
orders = q.all()
|
||||
per_order = sales.order_totals(db, orders)
|
||||
|
||||
# Bucket by business date (D-11): the stored date of the order's business day,
|
||||
# or computed from opened_at for orders outside a business day.
|
||||
@@ -1390,21 +1299,18 @@ def revenue_trends(
|
||||
key = dt.strftime("%Y-%m-%d")
|
||||
|
||||
if key not in buckets:
|
||||
buckets[key] = {"date": key, "revenue": 0.0, "profit": 0.0, "has_gap": False, "orders": 0}
|
||||
for i in order.items:
|
||||
if i.status not in ("active", "paid"):
|
||||
continue
|
||||
rev = _item_val(i)
|
||||
buckets[key]["revenue"] += rev
|
||||
if i.unit_cost is not None:
|
||||
buckets[key]["profit"] += rev - i.unit_cost * i.quantity
|
||||
else:
|
||||
buckets[key]["has_gap"] = True
|
||||
buckets[key] = {"date": key, "revenue": 0.0, "fees": 0.0, "profit": 0.0, "has_gap": False, "orders": 0}
|
||||
t = per_order[order.id]
|
||||
buckets[key]["revenue"] += t.revenue
|
||||
buckets[key]["fees"] += t.fees
|
||||
buckets[key]["profit"] += t.profit
|
||||
buckets[key]["has_gap"] = buckets[key]["has_gap"] or t.has_gap
|
||||
buckets[key]["orders"] += 1
|
||||
|
||||
arr = sorted(buckets.values(), key=lambda x: x["date"])
|
||||
for d in arr:
|
||||
d["revenue"] = round(d["revenue"], 2)
|
||||
d["fees"] = round(d["fees"], 2)
|
||||
d["profit"] = round(d["profit"], 2)
|
||||
|
||||
if granularity == "daily":
|
||||
@@ -1419,17 +1325,6 @@ 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"),
|
||||
@@ -1451,43 +1346,18 @@ def category_performance(
|
||||
items = q.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:
|
||||
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_names.get(cid) or "—",
|
||||
"color": cat.color if cat and hasattr(cat, "color") else None,
|
||||
"units_sold": 0,
|
||||
"revenue": 0.0,
|
||||
"total_cost": 0.0,
|
||||
"trackable_profit": 0.0,
|
||||
"uncosted_revenue": 0.0,
|
||||
"has_gap": False,
|
||||
"product_ids": set(),
|
||||
}
|
||||
qty = item.quantity
|
||||
rev = _item_val(item)
|
||||
summary[cid]["units_sold"] += qty
|
||||
summary[cid]["revenue"] += rev
|
||||
summary[cid]["product_ids"].add(item.product_id)
|
||||
if item.unit_cost is not None:
|
||||
cost = item.unit_cost * qty
|
||||
summary[cid]["total_cost"] += cost
|
||||
summary[cid]["trackable_profit"] += rev - cost
|
||||
else:
|
||||
summary[cid]["uncosted_revenue"] += rev
|
||||
summary[cid]["has_gap"] = True
|
||||
# 6.12a: net of refunds, fees left out; the category it was in when sold (D-18)
|
||||
summary: dict = sales.categories(db, items)
|
||||
|
||||
total_rev = sum(v["revenue"] for v in summary.values())
|
||||
total_profit = sum(v["trackable_profit"] for v in summary.values())
|
||||
result = []
|
||||
for entry in summary.values():
|
||||
entry["product_count"] = len(entry.pop("product_ids"))
|
||||
cat = categories_db.get(entry["category_id"])
|
||||
entry["color"] = cat.color if cat is not None else None
|
||||
entry["product_count"] = len(entry.pop("products"))
|
||||
entry["units_sold"] = round(entry["units_sold"], 3)
|
||||
entry["refunded"] = round(entry["refunded"], 2)
|
||||
entry["revenue"] = round(entry["revenue"], 2)
|
||||
entry["total_cost"] = round(entry["total_cost"], 2)
|
||||
entry["trackable_profit"] = round(entry["trackable_profit"], 2)
|
||||
@@ -1721,30 +1591,6 @@ def meta_products(
|
||||
# CSV export endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _csv_response_fields(rows: list, fields: list, filename: str) -> StreamingResponse:
|
||||
output = io.StringIO()
|
||||
writer = csv.DictWriter(output, fieldnames=fields)
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
return StreamingResponse(iter([output.getvalue()]), media_type="text/csv",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
||||
|
||||
|
||||
def _csv_response(rows: list, filename: str) -> StreamingResponse:
|
||||
if not rows:
|
||||
rows = [{}]
|
||||
output = io.StringIO()
|
||||
writer = csv.DictWriter(output, fieldnames=list(rows[0].keys()))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
output.seek(0)
|
||||
return StreamingResponse(
|
||||
iter([output.getvalue()]),
|
||||
media_type="text/csv",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/shifts/export")
|
||||
def shifts_export(
|
||||
waiter_id: Optional[int] = None,
|
||||
@@ -1754,26 +1600,18 @@ def shifts_export(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Shifts as CSV (6.12a: venue time, the zone in the header; csv_export)."""
|
||||
data = shifts_report(waiter_id=waiter_id, business_day_id=business_day_id, from_dt=from_dt, to_dt=to_dt, active_only=False, db=db, user=user)
|
||||
rows = []
|
||||
for s in data["shifts"]:
|
||||
rows.append({
|
||||
"id": s["id"],
|
||||
"waiter": s["waiter_name"],
|
||||
"started_at": s["started_at"],
|
||||
"ended_at": s["ended_at"] or "",
|
||||
"duration_hours": s.get("duration_hours", ""),
|
||||
"hourly_rate": s.get("hourly_rate_snapshot", ""),
|
||||
"shift_pay": s.get("shift_pay", ""),
|
||||
"counted_cash_end": s.get("counted_cash_end", ""),
|
||||
"cash_discrepancy": s.get("cash_discrepancy", ""),
|
||||
"starting_cash": s["starting_cash"],
|
||||
"total_collected": s["total_collected"],
|
||||
"net_to_deliver": s["net_to_deliver"],
|
||||
"status": "active" if s["is_active"] else "ended",
|
||||
})
|
||||
date_str = (from_dt or "")[:10]
|
||||
return _csv_response(rows, f"shifts-{date_str}.csv")
|
||||
rows = [{
|
||||
"id": s["id"], "waiter": s["waiter_name"], "started_at": s["started_at"], "ended_at": s["ended_at"],
|
||||
"duration_hours": s.get("duration_hours"), "hourly_rate": s.get("hourly_rate_snapshot"), "shift_pay": s.get("shift_pay"),
|
||||
"starting_cash": s["starting_cash"], "total_collected": s["total_collected"], "net_to_deliver": s["net_to_deliver"],
|
||||
"counted_cash_end": s.get("counted_cash_end"), "cash_discrepancy": s.get("cash_discrepancy"),
|
||||
"status": "active" if s["is_active"] else "ended",
|
||||
} for s in data["shifts"]]
|
||||
fields = ["id", "waiter", "started_at", "ended_at", "duration_hours", "hourly_rate", "shift_pay", "starting_cash",
|
||||
"total_collected", "net_to_deliver", "counted_cash_end", "cash_discrepancy", "status"]
|
||||
return csv_export.response(db, rows, fields, f"shifts-{(from_dt or '')[:10]}.csv", times=("started_at", "ended_at"))
|
||||
|
||||
|
||||
@router.get("/orders/export")
|
||||
@@ -1787,23 +1625,17 @@ def orders_export(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Orders as CSV, same filters as GET /orders/history (KI-008: it read the history's
|
||||
dicts as ORM rows and always failed; business_day_id was ignored). Times are UTC ISO,
|
||||
like the other exports."""
|
||||
"""Orders as CSV, same filters as GET /orders/history: products (net of refunds), the
|
||||
delivery fee apart, what was refunded (6.12a), times in venue time."""
|
||||
orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status,
|
||||
table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user)
|
||||
rows = [{
|
||||
"id": o["id"],
|
||||
"table": o["table_name"] or "",
|
||||
"waiter": o["opened_by_name"] or "",
|
||||
"opened_at": o["opened_at"] or "",
|
||||
"closed_at": o["closed_at"] or "",
|
||||
"status": o["status"],
|
||||
"total": round(sum((i["unit_price"] + i["price_adjustment"]) * i["quantity"]
|
||||
for i in o["items"] if i["status"] in ("active", "paid")), 2),
|
||||
"id": o["id"], "table": o["table_name"] or "", "waiter": o["opened_by_name"] or "",
|
||||
"opened_at": o["opened_at"], "closed_at": o["closed_at"], "status": o["status"],
|
||||
"products": o["totals"]["revenue"], "fees": o["totals"]["fees"], "refunded": o["totals"]["refunded"], "total": o["totals"]["takings"],
|
||||
} for o in orders]
|
||||
fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "total"] # header even when empty
|
||||
return _csv_response_fields(rows, fields, f"orders-{(from_date or '')[:10]}.csv")
|
||||
fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "products", "fees", "refunded", "total"]
|
||||
return csv_export.response(db, rows, fields, f"orders-{(from_date or '')[:10]}.csv", times=("opened_at", "closed_at"))
|
||||
|
||||
|
||||
@router.get("/products/export")
|
||||
@@ -1816,16 +1648,8 @@ def products_export(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = product_performance(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, category_id=category_id, db=db, user=user)
|
||||
rows = [{
|
||||
"product_id": p["product_id"],
|
||||
"product_name": p["product_name"],
|
||||
"category_id": p.get("category_id", ""),
|
||||
"qty_sold": p["qty_sold"],
|
||||
"revenue": p["revenue"],
|
||||
"order_count": p["order_count"],
|
||||
} for p in data["products"]]
|
||||
date_str = (from_dt or "")[:10]
|
||||
return _csv_response(rows, f"products-{date_str}.csv")
|
||||
fields = ["product_id", "product_name", "category_id", "qty_sold", "revenue", "refunded", "total_cost", "trackable_profit", "order_count"]
|
||||
return csv_export.response(db, data["products"], fields, f"products-{(from_dt or '')[:10]}.csv")
|
||||
|
||||
|
||||
@router.get("/printers/export")
|
||||
@@ -1838,17 +1662,10 @@ def printers_export(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = printer_history(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, printer_id=printer_id, db=db, user=user)
|
||||
rows = [{
|
||||
"id": r["id"],
|
||||
"printed_at": r["printed_at"],
|
||||
"printer": r["printer_name"],
|
||||
"order_id": r["order_id"],
|
||||
"table": r["table"],
|
||||
"success": r["success"],
|
||||
"error_message": r.get("error_message") or "",
|
||||
} for r in data["logs"]]
|
||||
date_str = (from_dt or "")[:10]
|
||||
return _csv_response(rows, f"printer-history-{date_str}.csv")
|
||||
rows = [{"id": r["id"], "printed_at": r["printed_at"], "printer": r["printer_name"], "order_id": r["order_id"],
|
||||
"table": r["table"], "success": r["success"], "error_message": r.get("error_message") or ""} for r in data["logs"]]
|
||||
fields = ["id", "printed_at", "printer", "order_id", "table", "success", "error_message"]
|
||||
return csv_export.response(db, rows, fields, f"printer-history-{(from_dt or '')[:10]}.csv", times=("printed_at",))
|
||||
|
||||
|
||||
@router.get("/cancellations/export")
|
||||
@@ -1861,20 +1678,11 @@ def cancellations_export(
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = cancellations_log(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, waiter_id=waiter_id, db=db, user=user)
|
||||
rows = [{
|
||||
"id": c["id"],
|
||||
"order_id": c["order_id"],
|
||||
"table": c["table"],
|
||||
"waiter": c["waiter_name"],
|
||||
"product": c["product_name"],
|
||||
"quantity": c["quantity"],
|
||||
"value": c["value"],
|
||||
"cancelled_by": c.get("cancelled_by") or "",
|
||||
"reason": c.get("cancel_reason") or "",
|
||||
"cancelled_at": c["cancelled_at"],
|
||||
} for c in data["cancellations"]]
|
||||
date_str = (from_dt or "")[:10]
|
||||
return _csv_response(rows, f"cancellations-{date_str}.csv")
|
||||
rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table"], "waiter": c["waiter_name"], "product": c["product_name"],
|
||||
"quantity": c["quantity"], "value": c["value"], "cancelled_by": c.get("cancelled_by") or "",
|
||||
"reason": c.get("cancel_reason") or "", "cancelled_at": c["cancelled_at"]} for c in data["cancellations"]]
|
||||
fields = ["id", "order_id", "table", "waiter", "product", "quantity", "value", "cancelled_by", "reason", "cancelled_at"]
|
||||
return csv_export.response(db, rows, fields, f"cancellations-{(from_dt or '')[:10]}.csv", times=("cancelled_at",))
|
||||
|
||||
|
||||
# ── Prep Zones report ──────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user