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:
2026-11-19 08:51:13 +02:00
co-authored by Claude Opus 5.5
parent 6643614ff6
commit 4df59c33ef
21 changed files with 1197 additions and 558 deletions
+8 -7
View File
@@ -246,6 +246,7 @@ def business_day_summary(
if not day: if not day:
raise XeniaError("business_day.none_open") raise XeniaError("business_day.none_open")
from services.sales import gross # 6.12a: a line's value includes its price change (discounts)
orders = db.query(Order).filter(Order.business_day_id == day.id).all() orders = db.query(Order).filter(Order.business_day_id == day.id).all()
order_ids = [o.id for o in orders] order_ids = [o.id for o in orders]
@@ -309,12 +310,12 @@ def business_day_summary(
continue continue
e = _waiter_entry(item.added_by) e = _waiter_entry(item.added_by)
e["items_ordered"] += item.quantity e["items_ordered"] += item.quantity
e["total_items_value"] += item.unit_price * item.quantity e["total_items_value"] += gross(item)
for item in paid_items: for item in paid_items:
if item.paid_by: if item.paid_by:
e = _waiter_entry(item.paid_by) e = _waiter_entry(item.paid_by)
val = item.unit_price * item.quantity val = gross(item)
e["items_paid"] += item.quantity e["items_paid"] += item.quantity
e["total_collected"] += val e["total_collected"] += val
method = (item.payment_method or "cash").lower() method = (item.payment_method or "cash").lower()
@@ -392,11 +393,11 @@ def business_day_summary(
continue continue
entry["items"] += item.quantity entry["items"] += item.quantity
if item.status == "paid": if item.status == "paid":
entry["revenue"] += item.unit_price * item.quantity entry["revenue"] += gross(item)
# ── Per-printer summary ───────────────────────────────────────────────── # ── Per-printer summary ─────────────────────────────────────────────────
# Build item_id → value lookup for revenue-per-printer calculation # Build item_id → value lookup for revenue-per-printer calculation
items_value_map = {i.id: i.unit_price * i.quantity for i in all_items if i.status != "cancelled"} items_value_map = {i.id: gross(i) for i in all_items if i.status != "cancelled"}
printer_stats: dict = {} printer_stats: dict = {}
if order_ids: if order_ids:
@@ -438,7 +439,7 @@ def business_day_summary(
) )
active_shift_count = sum(1 for s in shifts if s.ended_at is None) active_shift_count = sum(1 for s in shifts if s.ended_at is None)
total_revenue = sum(i.unit_price * i.quantity for i in paid_items) total_revenue = sum(gross(i) for i in paid_items)
total_items_ordered = sum(i.quantity for i in all_items if i.status != "cancelled") total_items_ordered = sum(i.quantity for i in all_items if i.status != "cancelled")
total_orders = sum(1 for o in orders if o.status != "cancelled") total_orders = sum(1 for o in orders if o.status != "cancelled")
@@ -462,7 +463,7 @@ def business_day_summary(
cogs_uncosted_revenue = 0.0 cogs_uncosted_revenue = 0.0
cogs_uncosted_count = 0 cogs_uncosted_count = 0
for item in paid_items: for item in paid_items:
rev = item.unit_price * item.quantity rev = gross(item)
if item.unit_cost is not None: if item.unit_cost is not None:
cogs_trackable += item.unit_cost * item.quantity cogs_trackable += item.unit_cost * item.quantity
else: else:
@@ -494,7 +495,7 @@ def business_day_summary(
# TABBED REVENUE (items moved to tabs — not yet collected) # TABBED REVENUE (items moved to tabs — not yet collected)
tabbed_items = [i for i in all_items if i.status == "tabbed"] tabbed_items = [i for i in all_items if i.status == "tabbed"]
tabbed_revenue = round(sum(i.unit_price * i.quantity for i in tabbed_items), 2) tabbed_revenue = round(sum(gross(i) for i in tabbed_items), 2)
# NET estimate (revenue - COGS - labor - waste - expenses paid) # NET estimate (revenue - COGS - labor - waste - expenses paid)
net_estimate = round( net_estimate = round(
+104 -296
View File
@@ -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.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: def _item_val(item) -> float:
@@ -163,6 +164,7 @@ def shift_orders_summary(
): ):
"""Items sent (added) per waiter — regardless of payment status.""" """Items sent (added) per waiter — regardless of payment status."""
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) 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: if business_day_id:
q = q.join(Order).filter(Order.business_day_id == business_day_id) q = q.join(Order).filter(Order.business_day_id == business_day_id)
else: else:
@@ -208,7 +210,10 @@ def shift_orders_summary(
hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta
summary: dict[int, dict] = {} 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 wid = item.added_by
if wid not in summary: if wid not in summary:
w = waiters_db.get(wid) w = waiters_db.get(wid)
@@ -221,8 +226,8 @@ def shift_orders_summary(
"cancellations": 0, "cancellations": 0,
"order_data": {}, "order_data": {},
} }
summary[wid]["items"] += item.quantity summary[wid]["items"] += line.quantity
val = _item_val(item) val = line.value
summary[wid]["total"] += val summary[wid]["total"] += val
oid = item.order_id oid = item.order_id
@@ -239,7 +244,7 @@ def shift_orders_summary(
summary[wid]["order_data"][oid]["total"] += val summary[wid]["order_data"][oid]["total"] += val
product_name = item.product_name product_name = item.product_name
summary[wid]["order_data"][oid]["items"].append( summary[wid]["order_data"][oid]["items"].append(
{"name": product_name, "quantity": item.quantity} {"name": product_name, "quantity": line.quantity}
) )
for item in cancelled_items: for item in cancelled_items:
@@ -262,9 +267,11 @@ def shift_orders_summary(
entry["orders"] = len(entry["order_data"]) entry["orders"] = len(entry["order_data"])
entry["order_data"] = list(entry["order_data"].values()) entry["order_data"] = list(entry["order_data"].values())
entry["hours_worked"] = round(hours_by_waiter.get(entry["waiter_id"], 0.0), 2) 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) 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") @history_router.get("/orders/history")
@@ -346,6 +353,7 @@ def order_history(
return None return None
return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat() 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 = [] result = []
for o in orders: for o in orders:
items_out = [] items_out = []
@@ -362,6 +370,7 @@ def order_history(
"unit_price": float(item.unit_price), "unit_price": float(item.unit_price),
"price_adjustment": float(item.price_adjustment or 0.0), "price_adjustment": float(item.price_adjustment or 0.0),
"status": item.status, "status": item.status,
"system_key": item.system_key,
"paid_by": item.paid_by, "paid_by": item.paid_by,
"paid_by_name": _wname(item.paid_by), "paid_by_name": _wname(item.paid_by),
"paid_at": _dt_local(item.paid_at), "paid_at": _dt_local(item.paid_at),
@@ -402,6 +411,7 @@ def order_history(
"notes": o.notes, "notes": o.notes,
"business_day_id": o.business_day_id, "business_day_id": o.business_day_id,
"items": items_out, "items": items_out,
"totals": per_order[o.id].out(),
"waiters": [{"waiter_id": w.waiter_id} for w in o.waiters], "waiters": [{"waiter_id": w.waiter_id} for w in o.waiters],
"audit_logs": audit_out, "audit_logs": audit_out,
}) })
@@ -777,15 +787,10 @@ def print_products(
) )
items = q.all() items = q.all()
sold: dict = {} # 6.12a: the screen's numbers (net of refunds, the delivery fee left out), names as sold (D-18)
for item in items: per_product = sales.products(db, items)
pid = item.product_id sold = {pid: {"qty": round(v["qty_sold"], 3), "revenue": v["revenue"]} for pid, v in per_product.items()}
if pid not in sold: sold_names = {pid: v["product_name"] for pid, v in per_product.items()}
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)
if body.mode == "full": if body.mode == "full":
# All active products, 0-sold included (unsold ones under their current name), # All active products, 0-sold included (unsold ones under their current name),
# plus anything sold that's no longer active # plus anything sold that's no longer active
@@ -841,20 +846,10 @@ def print_categories(
) )
items = q.all() items = q.all()
prod_names, cat_names = _names_as_sold(items) # 6.12a: the screen's numbers (net of refunds, fees left out), as sold (D-18)
# summary[cid] = {name, units_sold, revenue, products: {pid: {name, qty, revenue}}} summary: dict = {cid: {"name": v["category_name"], "units_sold": round(v["units_sold"], 3), "revenue": v["revenue"],
summary: dict = {} "products": {pid: {**p, "qty": round(p["qty"], 3)} for pid, p in v["products"].items()}}
for item in items: for cid, v in sales.categories(db, items).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)
total_rev = sum(v["revenue"] for v in summary.values()) total_rev = sum(v["revenue"] for v in summary.values())
total_qty = sum(v["units_sold"] 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() orders = q.all()
tables_db = {t.id: t for t in db.query(Table).all()} # 6.12a: the screen's numbers
summary: dict = {} table_list = [{"name": t["table_name"] or "—", "order_count": t["order_count"], "revenue": t["revenue"],
for order in orders: "avg_duration_minutes": t["avg_duration_minutes"]} for t in _table_summary(db, 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)
report = { report = {
"mode": body.mode, "mode": body.mode,
@@ -1027,37 +1003,8 @@ def product_performance(
waste_by_product[pid]["waste_qty"] += w.quantity waste_by_product[pid]["waste_qty"] += w.quantity
waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0 waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0
sold_names, _ = _names_as_sold(items) # 6.12a: net of refunds, the delivery fee left out (services/sales.py); the category it was sold in (D-18)
summary: dict = {} summary: dict = sales.products(db, items, category_id)
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
# Also include products that only have waste (not sold) in the period # Also include products that only have waste (not sold) in the period
for pid, wdata in waste_by_product.items(): for pid, wdata in waste_by_product.items():
@@ -1069,7 +1016,7 @@ def product_performance(
"product_id": pid, "product_id": pid,
"product_name": product.name if product else f"#{pid}", "product_name": product.name if product else f"#{pid}",
"category_id": product.primary_category_id if product else None, "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(), "uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(),
} }
@@ -1078,7 +1025,10 @@ def product_performance(
pid = entry["product_id"] pid = entry["product_id"]
wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0}) wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0})
entry["order_count"] = len(entry.pop("order_ids")) 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["revenue"] = round(entry["revenue"], 2)
entry["refunded"] = round(entry["refunded"], 2)
entry["total_cost"] = round(entry["total_cost"], 2) entry["total_cost"] = round(entry["total_cost"], 2)
entry["trackable_profit"] = round(entry["trackable_profit"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2)
entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 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) q = q.filter(Order.business_day_id == business_day_id)
orders = q.all() 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 = {} summary: dict = {}
for order in orders: for order in orders:
tid = order.table_id tid = order.table_id
if tid not in summary: if tid not in summary:
t = tables_db.get(tid) t = tables_db.get(tid)
summary[tid] = { summary[tid] = {"table_id": tid, "table_name": (t.label or f"T{t.number}") if t else None,
"table_id": tid, "order_count": 0, "revenue": 0.0, "fees": 0.0, "durations": []}
"table_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]["order_count"] += 1
summary[tid]["revenue"] += sum( summary[tid]["revenue"] += per_order[order.id].revenue
_item_val(i) for i in order.items if i.status in ("active", "paid") summary[tid]["fees"] += per_order[order.id].fees
)
if order.closed_at and order.opened_at: if order.closed_at and order.opened_at:
summary[tid]["durations"].append( summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60)
(order.closed_at - order.opened_at).total_seconds() / 60
)
result = [] result = []
for entry in summary.values(): for entry in summary.values():
durations = entry.pop("durations") durations = entry.pop("durations")
entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None
entry["revenue"] = round(entry["revenue"], 2) entry["revenue"] = round(entry["revenue"], 2)
entry["fees"] = round(entry["fees"], 2)
result.append(entry) result.append(entry)
result.sort(key=lambda x: x["revenue"], reverse=True) 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) q = q.filter(Order.business_day_id == business_day_id)
orders = q.all() orders = q.all()
by_hour, by_weekday = traffic_buckets( per_order = sales.order_totals(db, orders) # 6.12a: products, net of refunds
(order.opened_at, sum(_item_val(i) for i in order.items if i.status in ("active", "paid"))) by_hour, by_weekday = traffic_buckets((order.opened_at, per_order[order.id].revenue) for order in orders)
for order in orders
)
return { return {
"by_hour": list(by_hour.values()), "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"] cancelled_orders = [o for o in orders if o.status == "cancelled"]
day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all() day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all()
waiter_ids = {s.waiter_id for s in day_shifts} waiter_ids = {s.waiter_id for s in day_shifts}
revenue = 0.0 # 6.12a: everything sold that day (open orders too), net of refunds, fees apart
total_cost = 0.0 money = sales.totals(sales.lines(db, [i for o in orders for i in o.items])).out()
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
opener = waiters_db.get(d.opened_by_id) opener = waiters_db.get(d.opened_by_id)
closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None
result.append({ result.append({
@@ -1262,11 +1192,8 @@ def business_days_list(
"cancellation_count": len(cancelled_orders), "cancellation_count": len(cancelled_orders),
"waiter_count": len(waiter_ids), "waiter_count": len(waiter_ids),
"shift_count": len(day_shifts), "shift_count": len(day_shifts),
"revenue": round(revenue, 2), **money,
"refunds": day_refunds(db, d.id), "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} return {"business_days": result}
@@ -1288,37 +1215,21 @@ def current_business_day(
WaiterShift.business_day_id == day.id, WaiterShift.business_day_id == day.id,
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).all() ).all()
revenue = 0.0 day_lines = sales.lines(db, [i for o in orders for i in o.items])
total_cost = 0.0 money = sales.totals(day_lines).out() # 6.12a: everything sold so far, net of refunds, fees apart
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
item_counts: dict = {} item_counts: dict = {}
for o in orders: item_names: dict = {}
if o.status == "cancelled": for line in day_lines:
if line.fee or not line.kept:
continue continue
for item in o.items: pid = line.item.product_id
if item.status in ("active", "paid"): item_counts[pid] = item_counts.get(pid, 0) + line.quantity
pid = item.product_id item_names[pid] = line.item.product_name
item_counts[pid] = item_counts.get(pid, 0) + item.quantity
top_product_id = max(item_counts, key=item_counts.get) if item_counts else None top_product_id = max(item_counts, key=item_counts.get) if item_counts else None
top_product = None top_product = None
if top_product_id: if top_product_id:
from models.product import Product 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)}
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]}
# Count cancelled items (individual items cancelled, across all orders in this day) # Count cancelled items (individual items cancelled, across all orders in this day)
all_order_ids = [o.id for o in orders] all_order_ids = [o.id for o in orders]
@@ -1339,11 +1250,8 @@ def current_business_day(
"business_day": { "business_day": {
"id": day.id, "id": day.id,
"opened_at": _dt(day.opened_at), "opened_at": _dt(day.opened_at),
"revenue": round(revenue, 2), **money,
"refunds": day_refunds(db, day.id), "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_closed": len(closed_orders),
"orders_open": len(open_orders), "orders_open": len(open_orders),
"active_waiters": len(active_shifts), "active_waiters": len(active_shifts),
@@ -1367,13 +1275,14 @@ def revenue_trends(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(Order.opened_at >= _since) q = q.filter(Order.opened_at >= _since)
if to_dt: if to_dt:
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt)) q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
orders = q.all() 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, # 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. # or computed from opened_at for orders outside a business day.
@@ -1390,21 +1299,18 @@ def revenue_trends(
key = dt.strftime("%Y-%m-%d") key = dt.strftime("%Y-%m-%d")
if key not in buckets: if key not in buckets:
buckets[key] = {"date": key, "revenue": 0.0, "profit": 0.0, "has_gap": False, "orders": 0} buckets[key] = {"date": key, "revenue": 0.0, "fees": 0.0, "profit": 0.0, "has_gap": False, "orders": 0}
for i in order.items: t = per_order[order.id]
if i.status not in ("active", "paid"): buckets[key]["revenue"] += t.revenue
continue buckets[key]["fees"] += t.fees
rev = _item_val(i) buckets[key]["profit"] += t.profit
buckets[key]["revenue"] += rev buckets[key]["has_gap"] = buckets[key]["has_gap"] or t.has_gap
if i.unit_cost is not None:
buckets[key]["profit"] += rev - i.unit_cost * i.quantity
else:
buckets[key]["has_gap"] = True
buckets[key]["orders"] += 1 buckets[key]["orders"] += 1
arr = sorted(buckets.values(), key=lambda x: x["date"]) arr = sorted(buckets.values(), key=lambda x: x["date"])
for d in arr: for d in arr:
d["revenue"] = round(d["revenue"], 2) d["revenue"] = round(d["revenue"], 2)
d["fees"] = round(d["fees"], 2)
d["profit"] = round(d["profit"], 2) d["profit"] = round(d["profit"], 2)
if granularity == "daily": if granularity == "daily":
@@ -1419,17 +1325,6 @@ def revenue_trends(
# Category performance # 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") @router.get("/categories/performance")
def category_performance( def category_performance(
from_dt: Optional[str] = Query(default=None, alias="from"), from_dt: Optional[str] = Query(default=None, alias="from"),
@@ -1451,43 +1346,18 @@ def category_performance(
items = q.all() items = q.all()
categories_db = {c.id: c for c in db.query(Category).all()} categories_db = {c.id: c for c in db.query(Category).all()}
_, cat_names = _names_as_sold(items) # 6.12a: net of refunds, fees left out; the category it was in when sold (D-18)
summary: dict = sales.categories(db, 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
total_rev = sum(v["revenue"] for v in summary.values()) total_rev = sum(v["revenue"] for v in summary.values())
total_profit = sum(v["trackable_profit"] for v in summary.values()) total_profit = sum(v["trackable_profit"] for v in summary.values())
result = [] result = []
for entry in summary.values(): 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["revenue"] = round(entry["revenue"], 2)
entry["total_cost"] = round(entry["total_cost"], 2) entry["total_cost"] = round(entry["total_cost"], 2)
entry["trackable_profit"] = round(entry["trackable_profit"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2)
@@ -1721,30 +1591,6 @@ def meta_products(
# CSV export endpoints # 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") @router.get("/shifts/export")
def shifts_export( def shifts_export(
waiter_id: Optional[int] = None, waiter_id: Optional[int] = None,
@@ -1754,26 +1600,18 @@ def shifts_export(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), 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) 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 = [] rows = [{
for s in data["shifts"]: "id": s["id"], "waiter": s["waiter_name"], "started_at": s["started_at"], "ended_at": s["ended_at"],
rows.append({ "duration_hours": s.get("duration_hours"), "hourly_rate": s.get("hourly_rate_snapshot"), "shift_pay": s.get("shift_pay"),
"id": s["id"], "starting_cash": s["starting_cash"], "total_collected": s["total_collected"], "net_to_deliver": s["net_to_deliver"],
"waiter": s["waiter_name"], "counted_cash_end": s.get("counted_cash_end"), "cash_discrepancy": s.get("cash_discrepancy"),
"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", "status": "active" if s["is_active"] else "ended",
}) } for s in data["shifts"]]
date_str = (from_dt or "")[:10] fields = ["id", "waiter", "started_at", "ended_at", "duration_hours", "hourly_rate", "shift_pay", "starting_cash",
return _csv_response(rows, f"shifts-{date_str}.csv") "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") @router.get("/orders/export")
@@ -1787,23 +1625,17 @@ def orders_export(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
"""Orders as CSV, same filters as GET /orders/history (KI-008: it read the history's """Orders as CSV, same filters as GET /orders/history: products (net of refunds), the
dicts as ORM rows and always failed; business_day_id was ignored). Times are UTC ISO, delivery fee apart, what was refunded (6.12a), times in venue time."""
like the other exports."""
orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status, 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) table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user)
rows = [{ rows = [{
"id": o["id"], "id": o["id"], "table": o["table_name"] or "", "waiter": o["opened_by_name"] or "",
"table": o["table_name"] or "", "opened_at": o["opened_at"], "closed_at": o["closed_at"], "status": o["status"],
"waiter": o["opened_by_name"] or "", "products": o["totals"]["revenue"], "fees": o["totals"]["fees"], "refunded": o["totals"]["refunded"], "total": o["totals"]["takings"],
"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),
} for o in orders] } for o in orders]
fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "total"] # header even when empty fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "products", "fees", "refunded", "total"]
return _csv_response_fields(rows, fields, f"orders-{(from_date or '')[:10]}.csv") return csv_export.response(db, rows, fields, f"orders-{(from_date or '')[:10]}.csv", times=("opened_at", "closed_at"))
@router.get("/products/export") @router.get("/products/export")
@@ -1816,16 +1648,8 @@ def products_export(
user: User = Depends(require_reports), 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) 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 = [{ fields = ["product_id", "product_name", "category_id", "qty_sold", "revenue", "refunded", "total_cost", "trackable_profit", "order_count"]
"product_id": p["product_id"], return csv_export.response(db, data["products"], fields, f"products-{(from_dt or '')[:10]}.csv")
"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")
@router.get("/printers/export") @router.get("/printers/export")
@@ -1838,17 +1662,10 @@ def printers_export(
user: User = Depends(require_reports), 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) 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 = [{ rows = [{"id": r["id"], "printed_at": r["printed_at"], "printer": r["printer_name"], "order_id": r["order_id"],
"id": r["id"], "table": r["table"], "success": r["success"], "error_message": r.get("error_message") or ""} for r in data["logs"]]
"printed_at": r["printed_at"], fields = ["id", "printed_at", "printer", "order_id", "table", "success", "error_message"]
"printer": r["printer_name"], return csv_export.response(db, rows, fields, f"printer-history-{(from_dt or '')[:10]}.csv", times=("printed_at",))
"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")
@router.get("/cancellations/export") @router.get("/cancellations/export")
@@ -1861,20 +1678,11 @@ def cancellations_export(
user: User = Depends(require_reports), 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) 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 = [{ rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table"], "waiter": c["waiter_name"], "product": c["product_name"],
"id": c["id"], "quantity": c["quantity"], "value": c["value"], "cancelled_by": c.get("cancelled_by") or "",
"order_id": c["order_id"], "reason": c.get("cancel_reason") or "", "cancelled_at": c["cancelled_at"]} for c in data["cancellations"]]
"table": c["table"], fields = ["id", "order_id", "table", "waiter", "product", "quantity", "value", "cancelled_by", "reason", "cancelled_at"]
"waiter": c["waiter_name"], return csv_export.response(db, rows, fields, f"cancellations-{(from_dt or '')[:10]}.csv", times=("cancelled_at",))
"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")
# ── Prep Zones report ────────────────────────────────────────────────────────── # ── Prep Zones report ──────────────────────────────────────────────────────────
+70
View File
@@ -0,0 +1,70 @@
"""CSV exports that open right in the venue's Excel (plan step 6.12a, from 2.99e).
- Times in **venue time** ("2026-11-19 21:30"), the zone named in the column header
("Opened (Europe/Athens)"), instead of UTC ISO.
- A UTF-8 byte-order mark, so Excel shows Greek names instead of mojibake.
- The venue's language picks the separators Excel expects: Greek → columns split by `;`
and decimal commas (12,50); otherwise `,` and decimal points.
"""
from __future__ import annotations
import csv
import io
from datetime import date, datetime
from fastapi.responses import StreamingResponse
BOM = chr(0xFEFF) # tells Excel the file is UTF-8
def _language(db) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == "venue.language").first() if db is not None else None
return (row.value if row and row.value else "en").lower()
def dialect(db) -> tuple[str, str]:
"""(column separator, decimal mark) for the venue's Excel."""
return (";", ",") if _language(db) == "el" else (",", ".")
def venue_time(value) -> str:
"""An ISO string or a datetime (UTC) → "YYYY-MM-DD HH:MM" in venue time; "" for nothing."""
from core.timeutil import parse_api_datetime, to_venue
if value in (None, ""):
return ""
dt = value if isinstance(value, datetime) else parse_api_datetime(str(value))
if dt is None:
return str(value)
return to_venue(dt).strftime("%Y-%m-%d %H:%M")
def response(db, rows: list[dict], fields: list[str], filename: str, *, times=(), labels: dict | None = None) -> StreamingResponse:
"""`fields` in order (the header even with no rows); `times` are converted to venue time and
their header names the zone; `labels` renames headers."""
from core.timeutil import venue_tz
sep, dec = dialect(db)
zone = venue_tz().key
labels = labels or {}
header = [f"{labels.get(f, f)} ({zone})" if f in times else labels.get(f, f) for f in fields]
def cell(field, v):
if field in times:
return venue_time(v)
if isinstance(v, bool):
return "1" if v else "0"
if isinstance(v, float):
text = f"{v:.2f}" if abs(v - round(v, 2)) < 1e-9 else repr(v)
return text.replace(".", dec) if dec != "." else text
if isinstance(v, (date, datetime)):
return v.isoformat()
return "" if v is None else v
out = io.StringIO()
w = csv.writer(out, delimiter=sep, lineterminator="\r\n")
w.writerow(header)
for r in rows:
w.writerow([cell(f, r.get(f)) for f in fields])
body = BOM + out.getvalue()
return StreamingResponse(iter([body.encode("utf-8")]), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{filename}"'})
+183
View File
@@ -0,0 +1,183 @@
"""How every report counts sales (plan step 6.12a). One set of rules, so a day adds up the same
in every report, on screen, printed and exported.
- **Sold** = order lines that are `active` (ordered, not paid yet) or `paid`. Cancelled lines,
lines written off at closing (`closed`) and lines on a customer's tab (`tabbed`) are not sales.
- A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded**
of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the
product, the category, the table, the hour and the day they belong to).
- **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are
money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
`takings` = revenue + fees.
- **Cost / profit**: a line with a cost snapshot adds its cost (for the quantity kept) and its
profit; a line without one makes the total a lower bound (`has_gap`).
"""
from __future__ import annotations
from dataclasses import dataclass
SOLD = ("active", "paid")
def gross(item, quantity: float | None = None) -> float:
q = item.quantity if quantity is None else quantity
return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * q
def is_fee(item) -> bool:
return getattr(item, "system_key", None) is not None
@dataclass
class Line:
item: object
quantity: float # sold minus refunded
value: float # its value minus the refunded part
refunded: float # the refunded value
fee: bool
@property
def kept(self) -> bool:
"""Something of it was kept (not refunded in full)."""
return self.quantity > 1e-9
@property
def cost(self) -> float | None:
uc = getattr(self.item, "unit_cost", None)
return None if uc is None else uc * self.quantity
def lines(db, items) -> list[Line]:
"""Sold lines (see the module doc) with their refunds taken off. A line refunded in full
stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
from services.refunds import refunded_quantities
sold = [i for i in items if i.status in SOLD]
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
out = []
for i in sold:
r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0)
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=is_fee(i)))
return out
@dataclass
class Totals:
revenue: float = 0.0 # products, net of refunds
fees: float = 0.0 # delivery fees (and other system lines), net of refunds
refunded: float = 0.0 # what was refunded of these lines (already taken off)
cost: float = 0.0
profit: float = 0.0
has_gap: bool = False
units: float = 0.0 # products' quantity
@property
def takings(self) -> float:
return self.revenue + self.fees
def add(self, line: Line) -> "Totals":
self.refunded += line.refunded
if line.fee:
self.fees += line.value
return self
self.revenue += line.value
self.units += line.quantity
c = line.cost
if c is None:
self.has_gap = self.has_gap or line.kept
else:
self.cost += c
self.profit += line.value - c
return self
def out(self) -> dict:
r = lambda v: round(v + 0.0, 2) # noqa: E731 (-0.0 → 0.0)
return {"revenue": r(self.revenue), "fees": r(self.fees), "takings": r(self.takings), "refunded": r(self.refunded),
"total_cost": r(self.cost), "trackable_profit": r(self.profit), "has_gap": self.has_gap}
def totals(ls) -> Totals:
t = Totals()
for line in ls:
t.add(line)
return t
def order_totals(db, orders) -> dict[int, Totals]:
"""{order_id: Totals} for orders (their items loaded through the relationship)."""
all_items = [i for o in orders for i in o.items]
by_order: dict[int, Totals] = {o.id: Totals() for o in orders}
for line in lines(db, all_items):
by_order[line.item.order_id].add(line)
return by_order
# ── summaries shared by the screens, the printed reports and the exports ─────
def products(db, items, category_id: int | None = None) -> dict:
"""{product_id: {...}} for product lines (fees left out), names and categories as sold (D-18)."""
pnames = _names(items)
out: dict = {}
for line in lines(db, items):
if line.fee or not line.kept:
continue
it = line.item
if category_id and it.category_id != category_id:
continue
e = out.setdefault(it.product_id, {
"product_id": it.product_id, "product_name": pnames.get(it.product_id) or f"#{it.product_id}",
"category_id": it.category_id, "qty_sold": 0.0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0,
"trackable_profit": 0.0, "uncosted_revenue": 0.0, "uncosted_items": 0.0, "order_ids": set(),
})
e["qty_sold"] += line.quantity
e["revenue"] += line.value
e["refunded"] += line.refunded
e["order_ids"].add(it.order_id)
c = line.cost
if c is None:
e["uncosted_revenue"] += line.value
e["uncosted_items"] += line.quantity
else:
e["total_cost"] += c
e["trackable_profit"] += line.value - c
return out
def categories(db, items) -> dict:
"""{category_id: {...}} for product lines, with each category's products."""
pnames = _names(items)
cnames = _names(items, "category")
out: dict = {}
for line in lines(db, items):
if line.fee or not line.kept:
continue
it = line.item
cid = it.category_id
e = out.setdefault(cid, {"category_id": cid, "category_name": cnames.get(cid) or "—", "units_sold": 0.0, "revenue": 0.0,
"refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0,
"has_gap": False, "products": {}})
e["units_sold"] += line.quantity
e["revenue"] += line.value
e["refunded"] += line.refunded
c = line.cost
if c is None:
e["uncosted_revenue"] += line.value
e["has_gap"] = True
else:
e["total_cost"] += c
e["trackable_profit"] += line.value - c
p = e["products"].setdefault(it.product_id, {"name": pnames.get(it.product_id) or f"#{it.product_id}", "qty": 0.0, "revenue": 0.0})
p["qty"] += line.quantity
p["revenue"] += line.value
return out
def _names(items, kind: str = "product") -> dict:
"""Names as sold; if renamed within the period, the newest wins (D-18, CS-4)."""
out = {}
for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)):
if kind == "product":
out[it.product_id] = it.product_name
elif it.category_id is not None:
out[it.category_id] = it.category_name
return out
+30 -8
View File
@@ -1,15 +1,20 @@
"""Orders CSV export (KI-008, fixed in platform-v2 cleanup before phase 3).""" """Report exports (KI-008; plan step 6.12a): CSV for the venue's Excel — a UTF-8 mark, venue
time with the zone in the header, the separators of the venue's language — and each order's
products, delivery fee and refunds counted by services/sales.py."""
import csv import csv
import io import io
def _rows(r): def _rows(r, sep=","):
assert r.status_code == 200, r.text assert r.status_code == 200, r.text
assert r.headers["content-type"].startswith("text/csv") assert r.headers["content-type"].startswith("text/csv")
return list(csv.DictReader(io.StringIO(r.text))) text = r.content.decode("utf-8")
assert text.startswith("\ufeff") # Excel reads it as UTF-8
return list(csv.DictReader(io.StringIO(text[1:]), delimiter=sep))
def test_orders_export_returns_a_csv(client, db, make_user, login): def _order(db, make_user):
from datetime import datetime, timezone
from models.order import Order, OrderItem from models.order import Order, OrderItem
from models.product import Category, Product from models.product import Category, Product
waiter = make_user(role="waiter", full_name="Maria W") waiter = make_user(role="waiter", full_name="Maria W")
@@ -19,7 +24,7 @@ def test_orders_export_returns_a_csv(client, db, make_user, login):
prod = Product(name="Freddo", base_price=4.0, primary_category_id=cat.id) prod = Product(name="Freddo", base_price=4.0, primary_category_id=cat.id)
db.add(prod) db.add(prod)
db.flush() db.flush()
order = Order(opened_by=waiter.id, order_type="takeaway") order = Order(opened_by=waiter.id, order_type="takeaway", opened_at=datetime(2026, 11, 19, 19, 30, tzinfo=timezone.utc))
db.add(order) db.add(order)
db.flush() db.flush()
db.add_all([OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=2, unit_price=4.0), db.add_all([OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=2, unit_price=4.0),
@@ -28,17 +33,34 @@ def test_orders_export_returns_a_csv(client, db, make_user, login):
OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=1, unit_price=4.0, OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=1, unit_price=4.0,
status="cancelled")]) status="cancelled")])
db.commit() db.commit()
return order
def test_orders_export_for_excel_in_venue_time(client, db, make_user, login):
order = _order(db, make_user)
h = login(make_user(role="owner")) h = login(make_user(role="owner"))
rows = _rows(client.get("/api/reports/orders/export", headers=h)) rows = _rows(client.get("/api/reports/orders/export", headers=h))
assert len(rows) == 1 assert len(rows) == 1
row = rows[0] row = rows[0]
assert row["id"] == str(order.id) and row["waiter"] == "Maria W" and row["status"] == order.status assert row["id"] == str(order.id) and row["waiter"] == "Maria W" and row["status"] == order.status
assert float(row["total"]) == 11.0 # 2×4 + 1×(4−1); the cancelled item doesn't count assert row["products"] == "11.00" and row["fees"] == "0.00" and row["total"] == "11.00" # 2×4 + 1×(4−1); not the cancelled one
assert row["opened_at"].endswith(("Z", "+00:00")) # UTC, like the other exports assert row["opened_at (Europe/Athens)"] == "2026-11-19 21:30" # 19:30 UTC, venue time
# business_day_id is honoured (the Today page sends it): no order in day 999 # business_day_id is honoured (the Today page sends it): no order in day 999
assert _rows(client.get("/api/reports/orders/export", headers=h, params={"business_day_id": 999})) == [] assert _rows(client.get("/api/reports/orders/export", headers=h, params={"business_day_id": 999})) == []
def test_a_greek_venue_gets_semicolons_and_decimal_commas(client, db, make_user, login):
from models.settings import PosSettings
_order(db, make_user)
db.add(PosSettings(key="venue.language", value="el"))
db.commit()
r = client.get("/api/reports/orders/export", headers=login(make_user(role="owner")))
row = _rows(r, sep=";")[0]
assert row["total"] == "11,00"
def test_orders_export_empty_still_has_a_header(client, make_user, login): def test_orders_export_empty_still_has_a_header(client, make_user, login):
r = client.get("/api/reports/orders/export", headers=login(make_user(role="owner"))) r = client.get("/api/reports/orders/export", headers=login(make_user(role="owner")))
assert r.status_code == 200 and r.text.splitlines()[0] == "id,table,waiter,opened_at,closed_at,status,total" assert r.status_code == 200
assert r.content.decode("utf-8").lstrip("\ufeff").splitlines()[0] == \
"id,table,waiter,opened_at (Europe/Athens),closed_at (Europe/Athens),status,products,fees,refunded,total"
@@ -0,0 +1,109 @@
"""One way to count sales in every report (plan step 6.12a, services/sales.py): a day with
products, a delivery fee and a partial refund adds up the same everywhere — products net of
what was refunded, the delivery fee apart, cancelled lines out."""
from datetime import timedelta
import pytest
@pytest.fixture
def the_day(db, make_user):
"""Table 4: a burger (10, cost 4), two coffees (3 each, no cost), the delivery fee (2.50),
a cancelled coffee; one coffee refunded (3)."""
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.order import Order, OrderItem
from models.product import Category, Product
from models.refund import Refund, RefundItem
from models.table import Table
owner = make_user(role="owner")
waiter = make_user(role="waiter", full_name="Maria W")
now = utcnow() - timedelta(minutes=30)
day = BusinessDay(status="open", opened_by_id=owner.id, opened_at=now - timedelta(hours=2), business_date=business_date_of(now))
food, drinks = Category(name="Food"), Category(name="Drinks")
table = Table(number=4)
db.add_all([day, food, drinks, table])
db.flush()
burger = Product(name="Burger", base_price=10.0, primary_category_id=food.id)
coffee = Product(name="Freddo", base_price=3.0, primary_category_id=drinks.id)
fee = Product(name="Delivery", base_price=2.5, primary_category_id=food.id, system_key="delivery_fee")
db.add_all([burger, coffee, fee])
db.flush()
order = Order(opened_by=waiter.id, table_id=table.id, business_day_id=day.id, opened_at=now, closed_at=now + timedelta(minutes=40), status="closed")
db.add(order)
db.flush()
item = lambda p, qty, price, **kw: OrderItem(order_id=order.id, product_id=p.id, added_by=waiter.id, quantity=qty, unit_price=price, # noqa: E731
status=kw.pop("status", "paid"), paid_by=waiter.id, paid_at=now, payment_method="cash", **kw)
b = item(burger, 1, 10.0, unit_cost=4.0)
c = item(coffee, 2, 3.0)
f = item(fee, 1, 2.5) # its system_key comes from the product
x = item(coffee, 1, 3.0, status="cancelled")
db.add_all([b, c, f, x])
db.flush()
refund = Refund(order_id=order.id, business_day_id=day.id, refunded_by=owner.id, method="cash", amount=3.0)
db.add(refund)
db.flush()
db.add(RefundItem(refund_id=refund.id, order_item_id=c.id, quantity=1, amount=3.0))
db.commit()
return {"day": day, "order": order, "owner": owner, "waiter": waiter, "food": food, "drinks": drinks}
def test_the_day_adds_up_the_same_in_every_report(client, the_day, login):
h = login(the_day["owner"])
day_id = the_day["day"].id
get = lambda url, **p: client.get(url, headers=h, params=p).json() # noqa: E731
# the business day (list and "now"): products 10 + 3 (one coffee refunded), the fee apart
day = next(d for d in get("/api/reports/business-days")["business_days"] if d["id"] == day_id)
now = get("/api/reports/business-days/current")["business_day"]
for d in (day, now):
assert (d["revenue"], d["fees"], d["takings"], d["refunded"]) == (13.0, 2.5, 15.5, 3.0), d
assert d["total_cost"] == 4.0 and d["trackable_profit"] == 6.0 and d["has_gap"] is True
assert d["refunds"]["amount"] == 3.0
assert now["top_product"]["name"] == "Burger" or now["top_product"]["qty"] == 1
# products and categories: no "Delivery" product, the coffee net of its refund
products = {p["product_name"]: p for p in get("/api/reports/products/performance", business_day_id=day_id)["products"]}
assert set(products) == {"Burger", "Freddo"}
assert (products["Freddo"]["qty_sold"], products["Freddo"]["revenue"], products["Freddo"]["refunded"]) == (1, 3.0, 3.0)
cats = {c["category_name"]: c["revenue"] for c in get("/api/reports/categories/performance", business_day_id=day_id)["categories"]}
assert cats == {"Food": 10.0, "Drinks": 3.0}
# by table, by hour, by day: the same 13, the fee beside it
tables = get("/api/reports/tables/performance", business_day_id=day_id)["tables"]
assert [(t["table_name"], t["revenue"], t["fees"]) for t in tables] == [("T4", 13.0, 2.5)]
traffic = get("/api/reports/traffic", business_day_id=day_id)
assert round(sum(h["revenue"] for h in traffic["by_hour"]), 2) == 13.0
trend = get("/api/reports/revenue/trends")["trends"]
assert [(t["revenue"], t["fees"]) for t in trend] == [(13.0, 2.5)]
# per waiter, and the order history's totals
staff = get("/api/reports/shift/orders", business_day_id=day_id)["waiters"]
assert [(w["waiter_name"], w["total"], w["items"]) for w in staff] == [("Maria W", 13.0, 2)]
history = get("/api/reports/orders/history", business_day_id=day_id)
assert history[0]["totals"] == {"revenue": 13.0, "fees": 2.5, "takings": 15.5, "refunded": 3.0,
"total_cost": 4.0, "trackable_profit": 6.0, "has_gap": True}
# the products export says the same
import csv
import io
text = client.get("/api/reports/products/export", headers=h, params={"business_day_id": day_id}).content.decode("utf-8")[1:]
rows = {r["product_name"]: r for r in csv.DictReader(io.StringIO(text))}
assert rows["Freddo"]["revenue"] == "3.00" and rows["Freddo"]["refunded"] == "3.00" and "Delivery" not in rows
def test_a_line_refunded_in_full_leaves_the_lists_but_its_refund_counts(db, the_day):
from models.order import OrderItem
from models.refund import Refund, RefundItem
from services import sales
burger = next(i for i in the_day["order"].items if i.product_name == "Burger")
r = Refund(order_id=the_day["order"].id, business_day_id=the_day["day"].id, refunded_by=the_day["owner"].id, method="card", amount=10.0)
db.add(r)
db.flush()
db.add(RefundItem(refund_id=r.id, order_item_id=burger.id, quantity=1, amount=10.0))
db.commit()
items = db.query(OrderItem).filter(OrderItem.order_id == the_day["order"].id).all()
t = sales.totals(sales.lines(db, items))
assert (round(t.revenue, 2), round(t.fees, 2), round(t.refunded, 2), t.cost) == (3.0, 2.5, 13.0, 0.0)
assert [line.kept for line in sales.lines(db, items) if line.item.product_name == "Burger"] == [False]
assert "Burger" not in {v["product_name"] for v in sales.products(db, items).values()} # not listed as sold
+1 -1
View File
@@ -45,7 +45,7 @@ import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
import StockPage from './pages/inventory/StockPage' import StockPage from './pages/inventory/StockPage'
// Reports // Reports
import TodayPage from './pages/reports/TodayPage' import TodayPage from './pages/reports/today/TodayReport'
import StorePage from './pages/reports/StorePage' import StorePage from './pages/reports/StorePage'
import StaffReportPage from './pages/reports/StaffReportPage' import StaffReportPage from './pages/reports/StaffReportPage'
import ProductsReportPage from './pages/reports/ProductsReportPage' import ProductsReportPage from './pages/reports/ProductsReportPage'
@@ -1,9 +0,0 @@
import Today from './restaurant/Today'
export default function TodayPage() {
return (
<div className="flex flex-col h-full min-h-0">
<Today />
</div>
)
}
@@ -0,0 +1,25 @@
// Revenue per hour of the day (plan step 6.12a): one bar per hour; on today's report the hours
// still to come are faint. Colours are the tokens (CSS variables), so dark mode follows.
import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
import { useFormat } from '@xenia/i18n'
export default function HourChart({ series, nowHour = null, height = 220 }) {
const { formatMoney } = useFormat()
const data = series.map(s => ({ ...s, label: `${String(s.hour).padStart(2, '0')}:00` }))
return (
<div style={{ height }} data-testid="hour-chart">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="var(--x-line)" />
<XAxis dataKey="label" tick={{ fontSize: 11, fill: 'var(--x-ink-3)' }} axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 11, fill: 'var(--x-ink-3)' }} axisLine={false} tickLine={false} tickFormatter={v => formatMoney(v, { decimals: 0 })} width={56} />
<Tooltip cursor={{ fill: 'var(--x-surface-2)' }} formatter={v => formatMoney(v)}
contentStyle={{ background: 'var(--x-surface)', border: '1px solid var(--x-line)', borderRadius: 8, color: 'var(--x-ink)' }} />
<Bar dataKey="revenue" radius={[3, 3, 0, 0]} maxBarSize={44}>
{data.map(d => <Cell key={d.hour} fill={nowHour != null && d.hour > nowHour ? 'var(--x-surface-3)' : 'var(--x-accent)'} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)
}
@@ -0,0 +1,52 @@
// An order from a report (plan step 6.12a; replaces the v1 report OrderDetailModal): the same
// lines, price changes and history the order page shows (6.9), read-only, with the order's
// totals (products, the delivery fee, refunds) and a link to the order page.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowRight } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { AuditList, PriceEventList } from '../../orders/OrderHistory'
import OrderLines from '../../orders/OrderLines'
import { Pill } from '../../overview/parts'
import { Loading } from './parts'
import { orderTotals } from './reportLogic'
const TABS = ['lines', 'prices', 'history']
const TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
export default function OrderDialog({ order: summary, onClose }) {
const { t } = useTranslation('manager')
const { formatMoney, formatDateTime } = useFormat()
const navigate = useNavigate()
const [tab, setTab] = useState('lines')
const { data: order } = useLiveQuery({ queryKey: ['order', summary.id], queryFn: () => client.get(`/api/orders/${summary.id}`).then(r => r.data) })
const { data: events = [] } = useLiveQuery({ queryKey: ['price-events', summary.id], queryFn: () => client.get(`/api/pricing/events/order/${summary.id}`).then(r => r.data) })
const totals = orderTotals(summary)
const place = summary.table_name || order?.table_name
return (
<Dialog open size="lg" onClose={onClose}
title={<span className="flex flex-wrap items-center gap-2">{place ? t('orders.title', { table: place }) : t('orders.titleNoTable', { id: summary.id })}
<Pill tone={TONE[summary.status] ?? 'neutral'}>{t(`overview.orderStatus.${summary.status}`, { defaultValue: summary.status })}</Pill></span>}
description={`#${summary.id} · ${formatDateTime(summary.opened_at, 'datetimeShort')}${summary.closed_at ? ` – ${formatDateTime(summary.closed_at, 'datetimeShort')}` : ''}${summary.opened_by_name ? ` · ${summary.opened_by_name}` : ''}`}
footer={<>
<span className="flex-1 flex flex-wrap gap-x-4 text-label text-ink-2" data-testid="order-dialog-totals">
<span>{t('reports.products')} <b className="text-ink tabular-nums">{formatMoney(totals.revenue)}</b></span>
{totals.fees > 0 && <span>{t('reports.fees')} <b className="text-ink tabular-nums">{formatMoney(totals.fees)}</b></span>}
{totals.refunded > 0 && <span>{t('reports.refunded')} <b className="text-danger-ink tabular-nums">{formatMoney(totals.refunded)}</b></span>}
</span>
<Button variant="ghost" iconEnd={<ArrowRight size={16} />} onClick={() => navigate(`/orders/${summary.id}`)}>{t('reports.openOrder')}</Button>
</>}>
<div className="grid gap-3" data-testid="report-order-dialog">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)}>{t(`reports.orderTabs.${k}`)}</Button>)}
</span>
{!order ? <Loading /> : tab === 'lines' ? <OrderLines order={order} open={false} priceEvents={events} onPay={() => {}} onChanged={() => {}} />
: tab === 'prices' ? <PriceEventList events={events} /> : <AuditList order={order} />}
</div>
</Dialog>
)
}
@@ -0,0 +1,54 @@
// The period a report covers (plan step 6.12a): dates (from – to, with quick choices) or one
// business day. Dates are venue calendar days; the backend reads them in venue time.
import { useId } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Input, Select } from '@xenia/ui'
import { dayChoices, quickRange, rangeProblem } from './reportLogic'
import { useBusinessDays } from './useBusinessDays'
export function PeriodPicker({ value, onChange, allowDay = true, right }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const id = useId()
const today = fmt.venueToday()
const { data: days = [] } = useBusinessDays()
const set = patch => onChange({ ...value, ...patch })
const problem = rangeProblem(value)
const dayLabel = d => `${fmt.formatDateTime(d.opened_at, 'datetimeShort')}${d.status === 'open' ? ` · ${t('reports.open')}` : ''}`
return (
<div className="rounded-card border border-line bg-surface shadow-raised px-4 py-3 flex flex-wrap items-end gap-3" data-testid="report-period">
{allowDay && (
<div className="flex rounded-control border border-line overflow-hidden self-end" role="group" aria-label={t('reports.period')}>
{['range', 'day'].map(m => (
<button key={m} type="button" aria-pressed={value.mode === m} onClick={() => set({ mode: m, dayId: m === 'day' && !value.dayId ? String(days[0]?.id ?? '') : value.dayId })}
className={`px-3 py-1.5 text-label font-medium ${value.mode === m ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2'}`}>
{t(`reports.modes.${m}`)}
</button>
))}
</div>
)}
{value.mode === 'range' ? (<>
<label className="grid gap-1 text-caption text-ink-2" htmlFor={`${id}-from`}>{t('reports.from')}
<Input id={`${id}-from`} type="date" value={value.from} max={today} onChange={e => set({ from: e.target.value })} data-testid="period-from" />
</label>
<label className="grid gap-1 text-caption text-ink-2" htmlFor={`${id}-to`}>{t('reports.to')}
<Input id={`${id}-to`} type="date" value={value.to} max={today} onChange={e => set({ to: e.target.value })} data-testid="period-to" />
</label>
<span className="flex flex-wrap gap-1">
{['today', 'week', 'month', 'thirty'].map(k => (
<Button key={k} size="sm" variant="ghost" onClick={() => set(quickRange(k, today))}>{t(`reports.quick.${k}`)}</Button>
))}
</span>
</>) : (
<label className="grid gap-1 text-caption text-ink-2 min-w-56" htmlFor={`${id}-day`}>{t('reports.businessDay')}
<Select id={`${id}-day`} value={value.dayId} onChange={e => set({ dayId: e.target.value })} data-testid="period-day"
options={dayChoices(days).map(d => ({ value: String(d.id), label: dayLabel(d) }))} placeholder={days.length ? undefined : t('reports.noDays')} />
</label>
)}
<span className="flex-1" />
{right}
{problem && <p role="alert" className="w-full text-label text-danger-ink">{t(`reports.rangeProblem.${problem}`)}</p>}
</div>
)
}
@@ -0,0 +1,155 @@
// The report kit's building blocks (plan step 6.12a): a report's page with tabs, a panel, a big
// figure, a sortable table, loading / error states, the export button. On the tokens, texts in
// `manager:reports.*`, money and dates through useFormat().
import { useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Download, Info } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, InfoTip, Spinner, cx } from '@xenia/ui'
import client from '../../../api/client'
import { sortRows } from './reportLogic'
/** A report page: its tabs (kept in the address as ?tab=) over the chosen tab's content. */
export function ReportPage({ title, tabs = [], children, testId }) {
const [params, setParams] = useSearchParams()
const active = tabs.find(t => t.id === params.get('tab'))?.id ?? tabs[0]?.id
const tab = tabs.find(t => t.id === active)
return (
<div className="h-full overflow-y-auto" data-testid={testId}>
<div className="max-w-7xl mx-auto p-4 lg:p-6 grid gap-4">
<header className="flex flex-wrap items-end gap-3">
<h1 className="text-title font-semibold text-ink flex-1 min-w-0">{title}</h1>
{tabs.length > 1 && (
<nav className="flex flex-wrap gap-1" role="tablist">
{tabs.map(t => (
<Button key={t.id} size="sm" variant={t.id === active ? 'primary' : 'ghost'} role="tab" aria-selected={t.id === active}
onClick={() => setParams(p => { const n = new URLSearchParams(p); n.set('tab', t.id); return n }, { replace: true })} data-testid={`report-tab-${t.id}`}>
{t.label}
</Button>
))}
</nav>
)}
</header>
{tab ? <tab.Component key={tab.id} /> : children}
</div>
</div>
)
}
/** A card with a title, an optional tip and actions. */
export function Panel({ title, tip, actions, children, className, padded = true, testId }) {
return (
<section className={cx('rounded-card border border-line bg-surface shadow-raised overflow-hidden', className)} data-testid={testId}>
{(title || actions) && (
<header className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-line">
<h2 className="flex-1 min-w-0 text-body font-semibold text-ink flex items-center gap-1">{title}{tip && <InfoTip>{tip}</InfoTip>}</h2>
{actions}
</header>
)}
<div className={padded ? 'p-4' : ''}>{children}</div>
</section>
)
}
const TONE = { success: 'text-success-ink', danger: 'text-danger-ink', warning: 'text-warning-ink', info: 'text-info-ink', accent: 'text-accent-ink' }
/** A figure: a label over a value, an optional line under it, a tone for the value. */
export function Stat({ label, value, sub, tip, tone, big = false, testId }) {
return (
<div className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-1 content-start" data-testid={testId}>
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3 flex items-center gap-1">{label}{tip && <InfoTip>{tip}</InfoTip>}</span>
<span className={cx('font-semibold tabular-nums', big ? 'text-display' : 'text-title', TONE[tone] ?? 'text-ink')}>{value}</span>
{sub && <span className="text-caption text-ink-2">{sub}</span>}
</div>
)
}
export function Loading() {
return <div className="py-16 grid place-items-center"><Spinner /></div>
}
export function Failed({ error, retry }) {
const { t } = useTranslation('manager')
return <EmptyState title={t('reports.failed')} description={errorMessage(error, t)}
action={retry ? <Button variant="secondary" onClick={retry}>{t('reports.retry')}</Button> : undefined} />
}
/**
* A sortable table. columns: [{ key, label, align?, render?(row), sort? (key or fn; false = not sortable), tip? }]
* Shows at most `limit` rows ("Showing 100 of 240").
*/
export function Table({ columns, rows, initialSort, onRow, rowTestId, limit = 200, empty, rowKey = r => r.id }) {
const { t, i18n } = useTranslation('manager')
const [sort, setSort] = useState(initialSort ?? null) // { key, dir }
if (!rows.length) return <EmptyState compact title={empty ?? t('reports.nothing')} />
const col = sort && columns.find(c => c.key === sort.key)
const sorted = col ? sortRows(rows, typeof col.sort === 'function' ? col.sort : (col.sort ?? col.key), sort.dir, i18n.language) : rows
const shown = sorted.slice(0, limit)
const flip = c => setSort(s => (s?.key === c.key ? { key: c.key, dir: s.dir === 'desc' ? 'asc' : 'desc' } : { key: c.key, dir: c.align === 'right' ? 'desc' : 'asc' }))
return (
<div className="overflow-x-auto">
<table className="w-full text-label border-collapse">
<thead>
<tr className="bg-surface-2 text-ink-2">
{columns.map(c => (
<th key={c.key} className={cx('px-3 py-2 font-semibold whitespace-nowrap', c.align === 'right' ? 'text-right' : 'text-left')}>
{c.sort === false ? c.label : (
<button type="button" className="inline-flex items-center gap-1 hover:text-ink" onClick={() => flip(c)}>
{c.label}{sort?.key === c.key && (sort.dir === 'desc' ? <ArrowDown size={12} /> : <ArrowUp size={12} />)}
</button>
)}
{c.tip && <InfoTip>{c.tip}</InfoTip>}
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-line">
{shown.map(r => (
<tr key={rowKey(r)} onClick={onRow ? () => onRow(r) : undefined} data-testid={rowTestId}
className={cx(onRow && 'cursor-pointer hover:bg-surface-2')}>
{columns.map(c => (
<td key={c.key} className={cx('px-3 py-2 align-top', c.align === 'right' && 'text-right tabular-nums')}>{c.render ? c.render(r) : r[c.key]}</td>
))}
</tr>
))}
</tbody>
</table>
{sorted.length > limit && <p className="px-3 py-2 text-caption text-ink-3 border-t border-line">{t('reports.showing', { shown: limit, total: sorted.length })}</p>}
</div>
)
}
/** Money with an optional "includes estimates" mark (a has_gap total is a lower bound). */
export function MoneyCell({ value, partial }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
return (
<span className="inline-flex items-center gap-1">
{formatMoney(value ?? 0)}
{partial && <span title={t('reports.partialTip')} className="text-warning-ink"><Info size={12} aria-label={t('reports.partial')} /></span>}
</span>
)
}
/** Downloads a CSV from a report's export endpoint (venue time, the venue's Excel separators). */
export function ExportButton({ endpoint, params, filename }) {
const { t } = useTranslation('manager')
const [busy, setBusy] = useState(false)
async function run() {
setBusy(true)
try {
const r = await client.get(endpoint, { params, responseType: 'blob' })
const url = URL.createObjectURL(r.data)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return <Button size="sm" variant="secondary" icon={<Download size={14} />} loading={busy} onClick={run} data-testid="report-export">{t('reports.export')}</Button>
}
@@ -0,0 +1,81 @@
// The report kit's plain data (plan step 6.12a), tested in tests/reports.test.mjs. Periods are
// business days or venue calendar dates; the backend reads a time without an offset as venue
// time (D-11), so a date range is sent as "YYYY-MM-DDT00:00:00" … "YYYY-MM-DDT23:59:59".
const DAY_MS = 86_400_000
const parse = key => Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)))
export const addDays = (key, n) => new Date(parse(key) + n * DAY_MS).toISOString().slice(0, 10)
/** The period a report starts with: the last 30 days up to today (venue date). */
export const defaultPeriod = today => ({ mode: 'range', from: addDays(today, -29), to: today, dayId: '' })
/** Quick ranges: today, the last 7 / 30 days, this month. */
export function quickRange(kind, today) {
if (kind === 'today') return { from: today, to: today }
if (kind === 'week') return { from: addDays(today, -6), to: today }
if (kind === 'month') return { from: `${today.slice(0, 8)}01`, to: today }
return { from: addDays(today, -29), to: today }
}
/** A period → the query parameters every report endpoint takes. */
export function periodParams(p) {
if (p.mode === 'day') return p.dayId ? { business_day_id: p.dayId } : {}
const out = {}
if (p.from) out.from = `${p.from}T00:00:00`
if (p.to) out.to = `${p.to}T23:59:59`
return out
}
/** A period's part of a file name: "2026-11-01_2026-11-19" or "day-12". */
export const periodSlug = p => (p.mode === 'day' ? `day-${p.dayId || 'all'}` : `${p.from}_${p.to}`)
/** Is the range the right way round (and not more than `maxDays`)? */
export function rangeProblem(p, maxDays = 366) {
if (p.mode !== 'range' || !p.from || !p.to) return null
if (p.from > p.to) return 'order'
if ((parse(p.to) - parse(p.from)) / DAY_MS + 1 > maxDays) return 'long'
return null
}
export const ratio = (part, whole) => (whole ? part / whole : 0)
/** Margin of profit on revenue (null when nothing was sold). */
export const margin = (profit, revenue) => (revenue > 0 ? profit / revenue : null)
/** Rows sorted by a column (numbers numerically, text by the language's rules); stable. */
export function sortRows(rows, key, dir = 'desc', locale) {
const sign = dir === 'asc' ? 1 : -1
return rows.map((r, i) => [r, i]).sort(([a, i], [b, j]) => {
const x = typeof key === 'function' ? key(a) : a[key]
const y = typeof key === 'function' ? key(b) : b[key]
let c
if (x == null && y == null) c = 0
else if (x == null) c = 1
else if (y == null) c = -1
else if (typeof x === 'number' && typeof y === 'number') c = (x - y) * sign
else c = String(x).localeCompare(String(y), locale) * sign
return c || i - j
}).map(([r]) => r)
}
/** The hours a day's chart shows: from `from` to `to` (inclusive), each with its revenue;
* widened to any hour that has sales (an early breakfast, a late night). */
export function hourSeries(byHour = [], { from = 10, to = 23 } = {}) {
const map = new Map(byHour.map(h => [h.hour, h]))
const busy = byHour.filter(h => h.orders || h.revenue).map(h => h.hour)
if (busy.length) { from = Math.min(from, ...busy); to = Math.max(to, ...busy) }
const out = []
for (let h = from; h <= to; h++) out.push({ hour: h, revenue: map.get(h)?.revenue ?? 0, orders: map.get(h)?.orders ?? 0 })
return out
}
/** The order history's totals for an order (the backend's services/sales.py), with a fallback. */
export function orderTotals(o) {
if (o?.totals) return o.totals
const sold = (o?.items ?? []).filter(i => i.status === 'active' || i.status === 'paid')
const revenue = sold.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
return { revenue, fees: 0, takings: revenue, refunded: 0, total_cost: 0, trackable_profit: 0, has_gap: true }
}
/** The business days list → choices for a select, newest first (label filled by the page). */
export const dayChoices = (days = []) => [...days].sort((a, b) => (b.opened_at ?? '').localeCompare(a.opened_at ?? ''))
@@ -0,0 +1,10 @@
// The business days for the period pickers (GET /api/reports/business-days), newest first.
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
export function useBusinessDays() {
return useLiveQuery({
queryKey: ['business-days'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data.business_days),
refetchInterval: 60_000, staleTime: 30_000, // no live event for business days
})
}
@@ -1,234 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts'
import { TrendingUp, ReceiptText, Clock, Users, Trophy, XCircle, Package, Sunset, PiggyBank, ShoppingBag } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import OrderDetailModal from '../shared/OrderDetailModal'
import { fmtEUR, fmtNum, fmtTime, fmtDateTime } from '../shared/reportDesignTokens'
export default function Today() {
const [drillOrder, setDrillOrder] = useState(null)
const { data: bdData, isLoading: bdLoading } = useQuery({
queryKey: ['business-day-current'],
queryFn: () => client.get('/api/reports/business-days/current').then(r => r.data),
staleTime: 30 * 1000,
refetchInterval: 30 * 1000,
})
const bd = bdData?.business_day
const { data: ordersData, isLoading: ordersLoading } = useQuery({
queryKey: ['today-orders', bd?.id],
queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: bd.id, page_size: 200 } }).then(r => r.data),
enabled: !!bd?.id,
staleTime: 30 * 1000,
refetchInterval: 30 * 1000,
})
const { data: trafficData } = useQuery({
queryKey: ['today-traffic', bd?.id],
queryFn: () => client.get('/api/reports/traffic', { params: { business_day_id: bd.id } }).then(r => r.data),
enabled: !!bd?.id,
staleTime: 30 * 1000,
})
if (bdLoading || ordersLoading) {
return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={8} showChart /></div>
}
if (!bd) {
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar>
<span className="font-mono text-[12px] uppercase tracking-wider text-slate-500">Live snapshot</span>
</FilterBar>
<div className="flex flex-1 items-center justify-center p-12">
<EmptyState
icon={Sunset}
title="Δεν υπάρχει ενεργή εργάσιμη μέρα"
description="Ανοίξτε μια εργάσιμη μέρα από τον Πίνακα Ελέγχου για να ξεκινήσετε."
/>
</div>
</div>
)
}
const orders = Array.isArray(ordersData) ? ordersData : []
const hourlyMap = {}
;(trafficData?.by_hour || []).forEach(h => { hourlyMap[h.hour] = h })
const hours = Array.from({ length: 14 }, (_, i) => 10 + i)
const hourlyChart = hours.map(h => ({
hour: `${String(h).padStart(2, '0')}:00`,
revenue: hourlyMap[h]?.revenue || 0,
}))
const nowH = new Date().getHours()
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<div className="flex items-center gap-2 rounded-md bg-emerald-50 px-2.5 py-1 text-[12px] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200">
<span className="relative h-1.5 w-1.5 rounded-full bg-emerald-500">
<span className="absolute inset-0 rounded-full bg-emerald-500 animate-ping opacity-75" />
</span>
Εργάσιμη μέρα ανοιχτή · άνοιξε {fmtTime(bd.opened_at)}
</div>
}>
<span className="font-mono text-[12px] uppercase tracking-wider text-slate-500">Ζωντανή Εικόνα</span>
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
<div className="grid grid-cols-12 gap-4">
<div className="col-span-5 rounded-lg border border-slate-200 bg-gradient-to-br from-sky-50 to-white p-6 shadow-[0_1px_0_rgba(15,23,42,0.04)]">
<div className="flex items-center justify-between">
<div className="text-[11px] font-medium uppercase tracking-[0.1em] text-slate-500">Έσοδα Μέχρι Τώρα</div>
<TrendingUp className="h-4 w-4 text-sky-400" />
</div>
<div className="mt-2 font-mono text-[52px] font-medium tabular-nums leading-none tracking-tight text-slate-900">
{fmtEUR(bd.revenue)}
</div>
<div className="mt-3 flex items-center gap-4 text-[12px] text-slate-600">
<span><span className="font-mono font-semibold text-slate-900">{bd.orders_closed}</span> κλειστές παραγγελίες</span>
<span>·</span>
<span><span className="font-mono font-semibold text-slate-900">{fmtEUR(bd.orders_closed ? bd.revenue / bd.orders_closed : 0)}</span> μέσος όρος</span>
</div>
{bd.trackable_profit > 0 && (
<div className="mt-4 flex items-center gap-3 border-t border-sky-100 pt-4">
<div className="flex-1">
<div className="text-[10px] font-medium uppercase tracking-[0.08em] text-slate-400">Μεικτό Κέρδος</div>
<div className="font-mono text-[22px] font-semibold tabular-nums text-green-700">
{fmtEUR(bd.trackable_profit)}
</div>
</div>
{bd.revenue > 0 && (
<div className="rounded-md bg-green-50 px-2.5 py-1 text-[13px] font-semibold text-green-700 ring-1 ring-inset ring-green-200">
{((bd.trackable_profit / bd.revenue) * 100).toFixed(0)}% margin
{bd.has_gap && <span className="ml-1 text-[10px] text-amber-500">⚠ μερικό</span>}
</div>
)}
</div>
)}
</div>
<div className="col-span-7 grid grid-cols-3 gap-4">
<StatCard label="Κλειστές Παραγγελίες" value={fmtNum(bd.orders_closed)} sub="πληρωμένες + κλειστές" icon={ReceiptText} />
<StatCard label="Ανοιχτές Παραγγελίες" value={fmtNum(bd.orders_open)} sub="αναμένουν πληρωμή" icon={Clock} accent />
<StatCard label="Ενεργοί Σερβιτόροι" value={fmtNum(bd.active_waiters)} icon={Users} />
{bd.top_product && (
<StatCard label="Κορυφαίο Προϊόν" value={bd.top_product.name} sub={`${bd.top_product.qty} τεμ.`} icon={Trophy} />
)}
<StatCard
label="Ακυρώσεις"
value={fmtNum(bd.cancellation_events ?? bd.cancellations)}
sub={
(bd.cancellations > 0 || bd.cancelled_items > 0)
? `${fmtNum(bd.cancellations)} παραγγελίες / ${fmtNum(bd.cancelled_items)} είδη`
: 'καμία ακύρωση'
}
icon={XCircle}
/>
{bd.total_cost > 0 && (
<StatCard label="Κόστος Πωλήσεων" value={fmtEUR(bd.total_cost)} sub="κόστος ειδών" icon={ShoppingBag} />
)}
{bd.trackable_profit > 0 && (
<StatCard
label="Μεικτό Κέρδος"
value={fmtEUR(bd.trackable_profit)}
sub={bd.has_gap ? '⚠ μερικό κέρδος' : `${((bd.trackable_profit / bd.revenue) * 100).toFixed(0)}% margin`}
icon={PiggyBank}
/>
)}
</div>
</div>
<div className="mt-4">
<Panel title="Έσοδα ανά Ώρα" subtitle="Μόνο κλειστές παραγγελίες" right={<span className="font-mono text-[11px] uppercase tracking-wider text-slate-500">Σήμερα</span>}>
<div style={{ height: 220 }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={hourlyChart} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="hour" tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} tickFormatter={v => '€' + v} />
<Tooltip content={<ChartTooltip formatter={(v, n) => fmtEUR(v)} />} cursor={{ fill: '#f1f5f9' }} />
<Bar dataKey="revenue" radius={[3, 3, 0, 0]} maxBarSize={48}>
{hourlyChart.map((entry, i) => (
<Cell key={i} fill={parseInt(entry.hour) > nowH ? '#e2e8f0' : '#60a5fa'} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</Panel>
</div>
<div className="mt-4">
<Panel
padded={false}
title={
<span className="flex items-center gap-1.5">
<span>Παραγγελίες Σήμερα</span>
<span className="text-slate-300">·</span>
<span className="font-normal text-slate-500">{orders.length} συνολικά</span>
</span>
}
right={
<div className="flex items-center gap-3">
<span className="text-[11px] text-slate-400 italic">Κάντε Click για Λεπτομέρειες Παραγγελίας</span>
<ExportButton
endpoint="/api/reports/orders/export"
params={{ business_day_id: bd.id }}
filename={`today-orders-${bd.id}.csv`}
/>
</div>
}
>
<DataTable>
<THead>
<TH>#</TH><TH>Τραπέζι</TH><TH>Άνοιξε</TH><TH>Έκλεισε</TH>
<TH align="right">Είδη</TH><TH align="right">Σύνολο</TH><TH align="right">Κέρδος</TH><TH>Κατάσταση</TH>
</THead>
<tbody>
{orders.slice(0, 30).map(o => {
const activeItems = (o.items || []).filter(i => ['active', 'paid'].includes(i.status))
const total = activeItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
const costedItems = activeItems.filter(i => i.unit_cost != null)
const orderProfit = costedItems.length > 0
? costedItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0) - (i.unit_cost ?? 0)) * i.quantity, 0)
: null
const isCancelled = o.status === 'cancelled'
return (
<TR key={o.id} striped onClick={() => setDrillOrder(o)} className={isCancelled ? 'opacity-50' : ''}>
<TD mono>#{o.id}</TD>
<TD>{o.table_id}</TD>
<TD mono>{fmtDateTime(o.opened_at)}</TD>
<TD mono>{fmtDateTime(o.closed_at)}</TD>
<TD mono align="right">{(o.items || []).length}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(total)}</TD>
<TD mono align="right">
{orderProfit != null
? <span className={orderProfit >= 0 ? 'text-green-700' : 'text-red-600'}>{fmtEUR(orderProfit)}</span>
: <span className="text-slate-300">—</span>
}
</TD>
<TD><StatusBadge status={o.status} pulse /></TD>
</TR>
)
})}
</tbody>
</DataTable>
</Panel>
</div>
</div>
{drillOrder && (
<OrderDetailModal order={drillOrder} onClose={() => setDrillOrder(null)} />
)}
</div>
)
}
@@ -0,0 +1,98 @@
// Reports → Today (plan step 6.12a; replaces the v1 "live snapshot"): the open business day as
// it stands — products sold (net of refunds), delivery fees apart, refunds, cost and profit,
// open and finished orders, staff on shift, the best seller, cancellations; revenue per hour;
// every order of the day (tap one for its lines and history), with a CSV export. All numbers
// are counted like every other report (backend services/sales.py) and refresh by themselves.
import { useState } from 'react'
import { Sunset } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { Pill } from '../../overview/parts'
import HourChart from '../kit/HourChart'
import OrderDialog from '../kit/OrderDialog'
import { ExportButton, Failed, Loading, MoneyCell, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { hourSeries, margin, orderTotals } from '../kit/reportLogic'
const EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
const TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
export default function TodayPage() {
const { t } = useTranslation('manager')
return <ReportPage title={t('reports.today.title')} testId="report-today"><Today /></ReportPage>
}
function Today() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [order, setOrder] = useState(null)
const { data, isPending, error, refetch } = useLiveQuery({
queryKey: ['report-today'], queryFn: () => client.get('/api/reports/business-days/current').then(r => r.data.business_day),
events: EVENTS, refetchInterval: 60_000,
})
const dayId = data?.id
const { data: orders = [] } = useLiveQuery({
queryKey: ['report-today-orders', dayId], enabled: !!dayId, events: EVENTS,
queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: dayId, page_size: 500 } }).then(r => r.data),
})
const { data: traffic } = useLiveQuery({
queryKey: ['report-today-traffic', dayId], enabled: !!dayId, events: EVENTS,
queryFn: () => client.get('/api/reports/traffic', { params: { business_day_id: dayId } }).then(r => r.data),
})
if (isPending) return <Loading />
if (error) return <Failed error={error} retry={refetch} />
if (!data) return <EmptyState icon={<Sunset size={28} />} title={t('reports.today.closed')} description={t('reports.today.closedHint')} />
const d = data
const finished = d.orders_closed || 0
const m = margin(d.trackable_profit, d.revenue)
const nowHour = Number(fmt.formatDateTime(new Date(), { hour: '2-digit', hourCycle: 'h23' }))
const columns = [
{ key: 'id', label: '#', render: o => <span className="tabular-nums text-ink-2">#{o.id}</span> },
{ key: 'place', label: t('reports.place'), sort: o => o.table_name ?? '', render: o => o.table_name || t('reports.noTable') },
{ key: 'opened_at', label: t('reports.opened'), render: o => fmt.formatTime(o.opened_at) },
{ key: 'closed_at', label: t('reports.closed'), render: o => (o.closed_at ? fmt.formatTime(o.closed_at) : '—') },
{ key: 'waiter', label: t('reports.by'), sort: o => o.opened_by_name ?? '', render: o => o.opened_by_name ?? '' },
{ key: 'products', label: t('reports.products'), align: 'right', sort: o => orderTotals(o).revenue, render: o => fmt.formatMoney(orderTotals(o).revenue) },
{ key: 'fees', label: t('reports.fees'), align: 'right', sort: o => orderTotals(o).fees, render: o => (orderTotals(o).fees ? fmt.formatMoney(orderTotals(o).fees) : '') },
{ key: 'refunded', label: t('reports.refunded'), align: 'right', sort: o => orderTotals(o).refunded,
render: o => (orderTotals(o).refunded ? <span className="text-danger-ink">{fmt.formatMoney(orderTotals(o).refunded)}</span> : '') },
{ key: 'status', label: t('reports.status'), render: o => <Pill tone={TONE[o.status] ?? 'neutral'}>{t(`overview.orderStatus.${o.status}`, { defaultValue: o.status })}</Pill> },
]
return (
<div className="grid gap-4">
<p className="text-label text-ink-2" data-testid="today-day">{t('reports.today.since', { time: fmt.formatDateTime(d.opened_at, 'datetimeShort') })}</p>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat big label={t('reports.revenue')} tip={t('reports.revenueTip')} testId="today-revenue"
value={<MoneyCell value={d.revenue} />}
sub={t('reports.today.finished', { count: finished, avg: fmt.formatMoney(finished ? d.revenue / finished : 0) })} />
{d.fees > 0 && <Stat label={t('reports.fees')} tip={t('reports.feesTip')} value={fmt.formatMoney(d.fees)} testId="today-fees" />}
{d.refunded > 0 && <Stat label={t('reports.refunded')} tip={t('reports.refundedTip')} tone="danger" value={fmt.formatMoney(d.refunded)}
sub={t('reports.today.refunds', { count: d.refunds?.count ?? 0 })} testId="today-refunded" />}
{d.total_cost > 0 && (
<Stat label={t('reports.profit')} tip={t('reports.profitTip')} tone="success" value={<MoneyCell value={d.trackable_profit} partial={d.has_gap} />}
sub={m != null ? t('reports.margin', { pct: fmt.formatPercent(m, { maxDecimals: 0 }) }) : undefined} />
)}
<Stat label={t('reports.today.open')} value={d.orders_open} sub={t('reports.today.openSub')} />
<Stat label={t('reports.today.staff')} value={d.active_waiters} />
{d.top_product && <Stat label={t('reports.today.top')} value={d.top_product.name} sub={t('reports.today.topSub', { qty: d.top_product.qty })} />}
<Stat label={t('reports.today.cancellations')} value={d.cancellation_events ?? 0}
sub={d.cancellations || d.cancelled_items ? t('reports.today.cancelSub', { orders: d.cancellations, items: d.cancelled_items }) : t('reports.today.noCancels')} />
</div>
<Panel title={t('reports.byHour')} tip={t('reports.byHourTip')}>
<HourChart series={hourSeries(traffic?.by_hour)} nowHour={nowHour} />
</Panel>
<Panel padded={false} title={t('reports.today.orders', { count: orders.length })}
actions={<ExportButton endpoint="/api/reports/orders/export" params={{ business_day_id: d.id }} filename={`orders-day-${d.id}.csv`} />}>
<Table columns={columns} rows={orders} onRow={setOrder} rowTestId="today-order" initialSort={{ key: 'id', dir: 'desc' }} />
</Panel>
{order && <OrderDialog order={order} onClose={() => setOrder(null)} />}
</div>
)
}
+40
View File
@@ -0,0 +1,40 @@
// The report kit's plain data (plan step 6.12a).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
addDays, dayChoices, defaultPeriod, hourSeries, margin, orderTotals, periodParams, periodSlug, quickRange, rangeProblem, ratio, sortRows,
} from '../src/pages/reports/kit/reportLogic.js'
test('periods: the default, quick ranges, the parameters sent (venue time), file names', () => {
assert.deepEqual(defaultPeriod('2026-11-19'), { mode: 'range', from: '2026-10-21', to: '2026-11-19', dayId: '' })
assert.deepEqual(quickRange('week', '2026-11-19'), { from: '2026-11-13', to: '2026-11-19' })
assert.deepEqual(quickRange('month', '2026-11-19'), { from: '2026-11-01', to: '2026-11-19' })
assert.equal(addDays('2026-03-01', -1), '2026-02-28')
assert.deepEqual(periodParams({ mode: 'range', from: '2026-11-01', to: '2026-11-19' }), { from: '2026-11-01T00:00:00', to: '2026-11-19T23:59:59' })
assert.deepEqual(periodParams({ mode: 'day', dayId: '12' }), { business_day_id: '12' })
assert.deepEqual(periodParams({ mode: 'day', dayId: '' }), {})
assert.equal(periodSlug({ mode: 'range', from: '2026-11-01', to: '2026-11-19' }), '2026-11-01_2026-11-19')
assert.equal(rangeProblem({ mode: 'range', from: '2026-11-19', to: '2026-11-01' }), 'order')
assert.equal(rangeProblem({ mode: 'range', from: '2024-01-01', to: '2026-11-01' }), 'long')
assert.equal(rangeProblem({ mode: 'day' }), null)
})
test('numbers: ratios, margins, sorting (numbers, text, empty last, stable)', () => {
assert.equal(ratio(1, 4), 0.25)
assert.equal(ratio(1, 0), 0)
assert.equal(margin(6, 13), 6 / 13)
assert.equal(margin(0, 0), null)
const rows = [{ n: 'b', v: 2 }, { n: 'a', v: null }, { n: 'c', v: 10 }, { n: 'd', v: 2 }]
assert.deepEqual(sortRows(rows, 'v').map(r => r.n), ['c', 'b', 'd', 'a'])
assert.deepEqual(sortRows(rows, 'v', 'asc').map(r => r.n), ['b', 'd', 'c', 'a'])
assert.deepEqual(sortRows(rows, 'n', 'asc').map(r => r.n), ['a', 'b', 'c', 'd'])
assert.deepEqual(sortRows(rows, r => r.n.charCodeAt(0), 'desc').map(r => r.n), ['d', 'c', 'b', 'a'])
})
test('a day by the hour, an order\'s totals, business days newest first', () => {
const s = hourSeries([{ hour: 12, revenue: 30, orders: 2 }, { hour: 3, revenue: 5 }], { from: 11, to: 13 })
assert.deepEqual(s.map(h => [h.hour, h.revenue]), [[3, 5], ...Array.from({ length: 7 }, (_, i) => [4 + i, 0]), [11, 0], [12, 30], [13, 0]]) // widened to 03:00
assert.equal(orderTotals({ totals: { revenue: 13, fees: 2.5 } }).fees, 2.5)
assert.equal(orderTotals({ items: [{ status: 'paid', unit_price: 4, price_adjustment: -1, quantity: 2 }, { status: 'cancelled', unit_price: 9, quantity: 1 }] }).revenue, 6)
assert.deepEqual(dayChoices([{ id: 1, opened_at: '2026-11-17' }, { id: 2, opened_at: '2026-11-19' }]).map(d => d.id), [2, 1])
})
+2 -2
View File
@@ -1,9 +1,9 @@
{ {
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [ "paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule" "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today"
], ],
"strict": [ "strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule" "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today"
] ]
} }
+73
View File
@@ -2715,5 +2715,78 @@
"opens": "Ανοίγει", "opens": "Ανοίγει",
"closes": "Κλείνει", "closes": "Κλείνει",
"openingHint": "Σκιασμένα στον άξονα." "openingHint": "Σκιασμένα στον άξονα."
},
"reports": {
"failed": "Η αναφορά δεν φορτώθηκε.",
"retry": "Ξανά",
"nothing": "Τίποτα σε αυτή την περίοδο.",
"showing": "Εμφανίζονται {{shown}} από {{total}}.",
"export": "Εξαγωγή (Excel)",
"period": "Περίοδος",
"modes": {
"range": "Ημερομηνίες",
"day": "Εργάσιμη ημέρα"
},
"from": "Από",
"to": "Έως",
"quick": {
"today": "Σήμερα",
"week": "Τελευταίες 7 ημέρες",
"month": "Αυτός ο μήνας",
"thirty": "Τελευταίες 30 ημέρες"
},
"businessDay": "Εργάσιμη ημέρα",
"noDays": "Δεν υπάρχουν εργάσιμες ημέρες ακόμα",
"open": "ανοιχτή",
"rangeProblem": {
"order": "Η αρχή είναι μετά το τέλος.",
"long": "Επιλέξτε έως έναν χρόνο."
},
"revenue": "Έσοδα",
"revenueTip": "Προϊόντα που πουλήθηκαν, μείον όσα επιστράφηκαν. Τα έξοδα αποστολής μετρώνται χωριστά.",
"fees": "Έξοδα αποστολής",
"feesTip": "Χρήματα για την αποστολή: δεν είναι προϊόν, οπότε δεν μπαίνουν στα έσοδα.",
"refunded": "Επιστροφές",
"refundedTip": "Χρήματα που επιστράφηκαν. Έχουν ήδη αφαιρεθεί από τα έσοδα και τα προϊόντα.",
"profit": "Κέρδος",
"profitTip": "Έσοδα μείον το κόστος όσων πουλήθηκαν. Προϊόντα χωρίς κόστος μετρούν χωρίς κέρδος, οπότε είναι τουλάχιστον αυτό.",
"margin": "περιθώριο {{pct}}",
"partial": "τουλάχιστον",
"partialTip": "Κάποια προϊόντα δεν έχουν κόστος: το πραγματικό ποσό είναι τουλάχιστον αυτό.",
"products": "Προϊόντα",
"place": "Τραπέζι",
"noTable": "Χωρίς τραπέζι",
"opened": "Άνοιξε",
"closed": "Έκλεισε",
"by": "Από",
"status": "Κατάσταση",
"byHour": "Έσοδα ανά ώρα",
"byHourTip": "Προϊόντα που πουλήθηκαν, ανά ώρα που άνοιξε η παραγγελία (ώρα καταστήματος).",
"openOrder": "Άνοιγμα παραγγελίας",
"orderTabs": {
"lines": "Γραμμές",
"prices": "Αλλαγές τιμών",
"history": "Ιστορικό"
},
"today": {
"title": "Σήμερα",
"closed": "Η εργάσιμη ημέρα δεν είναι ανοιχτή",
"closedHint": "Ανοίξτε την ημέρα από την επισκόπηση για να τη δείτε εδώ.",
"since": "Εργάσιμη ημέρα ανοιχτή από {{time}}",
"finished_one": "{{count}} ολοκληρωμένη παραγγελία · {{avg}} μέσος όρος",
"finished_other": "{{count}} ολοκληρωμένες παραγγελίες · {{avg}} μέσος όρος",
"refunds_one": "{{count}} επιστροφή",
"refunds_other": "{{count}} επιστροφές",
"open": "Ανοιχτές παραγγελίες",
"openSub": "μένουν να πληρωθούν",
"staff": "Προσωπικό σε βάρδια",
"top": "Πρώτο σε πωλήσεις",
"topSub": "{{qty}} πουλήθηκαν",
"cancellations": "Ακυρώσεις",
"cancelSub": "{{orders}} παραγγελίες / {{items}} είδη",
"noCancels": "καμία",
"orders_one": "{{count}} παραγγελία σήμερα",
"orders_other": "{{count}} παραγγελίες σήμερα"
}
} }
} }
+73
View File
@@ -2715,5 +2715,78 @@
"opens": "Opens", "opens": "Opens",
"closes": "Closes", "closes": "Closes",
"openingHint": "Shaded on the timeline." "openingHint": "Shaded on the timeline."
},
"reports": {
"failed": "This report couldn't be loaded.",
"retry": "Try again",
"nothing": "Nothing in this period.",
"showing": "Showing {{shown}} of {{total}}.",
"export": "Export (Excel)",
"period": "Period",
"modes": {
"range": "Dates",
"day": "Business day"
},
"from": "From",
"to": "To",
"quick": {
"today": "Today",
"week": "Last 7 days",
"month": "This month",
"thirty": "Last 30 days"
},
"businessDay": "Business day",
"noDays": "No business days yet",
"open": "open",
"rangeProblem": {
"order": "The start is after the end.",
"long": "Pick at most a year."
},
"revenue": "Revenue",
"revenueTip": "Products sold, minus what was refunded. Delivery fees are counted apart.",
"fees": "Delivery fees",
"feesTip": "Money taken for delivery: not a product, so it's not in the revenue.",
"refunded": "Refunded",
"refundedTip": "Money given back. Already taken off the revenue and the products.",
"profit": "Profit",
"profitTip": "Revenue minus the cost of what was sold. Products without a cost count without profit, so this is at least the profit.",
"margin": "{{pct}} margin",
"partial": "at least",
"partialTip": "Some products have no cost: the real figure is at least this.",
"products": "Products",
"place": "Table",
"noTable": "No table",
"opened": "Opened",
"closed": "Closed",
"by": "By",
"status": "Status",
"byHour": "Revenue by hour",
"byHourTip": "Products sold, by the hour their order was opened (venue time).",
"openOrder": "Open the order",
"orderTabs": {
"lines": "Lines",
"prices": "Price changes",
"history": "History"
},
"today": {
"title": "Today",
"closed": "The business day isn't open",
"closedHint": "Open the day from the overview to see it here.",
"since": "Business day open since {{time}}",
"finished_one": "{{count}} finished order · {{avg}} average",
"finished_other": "{{count}} finished orders · {{avg}} average",
"refunds_one": "{{count}} refund",
"refunds_other": "{{count}} refunds",
"open": "Open orders",
"openSub": "still to be paid",
"staff": "Staff on shift",
"top": "Best seller",
"topSub": "{{qty}} sold",
"cancellations": "Cancellations",
"cancelSub": "{{orders}} orders / {{items}} items",
"noCancels": "none",
"orders_one": "{{count}} order today",
"orders_other": "{{count}} orders today"
}
} }
} }
+28
View File
@@ -1161,6 +1161,34 @@ try {
await page.screenshot({ path: path.join(OUT, 'manager-schedule.png'), fullPage: true }) await page.screenshot({ path: path.join(OUT, 'manager-schedule.png'), fullPage: true })
await page.keyboard.press('Escape') await page.keyboard.press('Escape')
// ── 6.12a: Reports → Today on the kit; an export for Excel ──────────────────
const rp = 'reports:'
const current = (await api('GET', '/api/reports/business-days/current', { token: boss })).business_day
await page.goto(`${APP}/reports/today`)
const todayRevenue = page.getByTestId('today-revenue')
await todayRevenue.waitFor({ timeout: 10_000 }).catch(() => {})
r.check(`${rp} Today shows the day's revenue as the backend counts it`, !!current
&& (await todayRevenue.textContent()).replace(/[\s,]/g, '').includes(current.revenue.toFixed(2)), `${current?.revenue} vs ${await todayRevenue.textContent().catch(() => '')}`)
const firstOrder = page.getByTestId('today-order').first()
if (await firstOrder.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) {
await firstOrder.click()
r.check(`${rp} an order opens with its lines and totals`, await page.getByTestId('report-order-dialog').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& await page.getByTestId('order-dialog-totals').count() === 1)
await page.keyboard.press('Escape')
}
const [download] = await Promise.all([page.waitForEvent('download', { timeout: 10_000 }), page.getByTestId('report-export').click()])
const csvText = (await import('node:fs')).readFileSync(await download.path(), 'utf8')
r.check(`${rp} the export is for Excel: UTF-8 mark, times in venue time with the zone in the header`,
csvText.charCodeAt(0) === 0xFEFF && csvText.split(/\r?\n/)[0].includes('opened_at (Europe/Athens)') && /\d{4}-\d\d-\d\d \d\d:\d\d/.test(csvText), csvText.slice(0, 160))
await page.screenshot({ path: path.join(OUT, 'manager-report-today.png'), fullPage: true })
await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'Ελληνικά' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid="report-today"] h1')?.textContent === 'Σήμερα', null, { timeout: 5000 }).catch(() => {})
r.check(`${rp} Today in Greek`, (await page.locator('[data-testid="report-today"] h1').textContent()) === 'Σήμερα' && (await todayRevenue.textContent()).includes('Έσοδα'))
await page.screenshot({ path: path.join(OUT, 'manager-report-today-el.png'), fullPage: true })
await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'English' }).click()
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`) await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {}) await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})