diff --git a/local_backend/routers/business_day.py b/local_backend/routers/business_day.py index 09b5d38..fab265a 100644 --- a/local_backend/routers/business_day.py +++ b/local_backend/routers/business_day.py @@ -246,6 +246,7 @@ def business_day_summary( if not day: 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() order_ids = [o.id for o in orders] @@ -309,12 +310,12 @@ def business_day_summary( continue e = _waiter_entry(item.added_by) 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: if item.paid_by: e = _waiter_entry(item.paid_by) - val = item.unit_price * item.quantity + val = gross(item) e["items_paid"] += item.quantity e["total_collected"] += val method = (item.payment_method or "cash").lower() @@ -392,11 +393,11 @@ def business_day_summary( continue entry["items"] += item.quantity if item.status == "paid": - entry["revenue"] += item.unit_price * item.quantity + entry["revenue"] += gross(item) # ── Per-printer summary ───────────────────────────────────────────────── # 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 = {} 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) - 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_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_count = 0 for item in paid_items: - rev = item.unit_price * item.quantity + rev = gross(item) if item.unit_cost is not None: cogs_trackable += item.unit_cost * item.quantity else: @@ -494,7 +495,7 @@ def business_day_summary( # TABBED REVENUE (items moved to tabs — not yet collected) 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 = round( diff --git a/local_backend/routers/reports.py b/local_backend/routers/reports.py index 0415f74..176ef66 100644 --- a/local_backend/routers/reports.py +++ b/local_backend/routers/reports.py @@ -64,6 +64,7 @@ history_router = APIRouter(dependencies=[Depends(_business_day_guard("history")) from services.refunds import day_refunds # noqa: E402 (3.3e: refunds shown apart from revenue) +from services import csv_export, sales # noqa: E402 (6.12a: one way to count sales; exports for Excel) def _item_val(item) -> float: @@ -163,6 +164,7 @@ def shift_orders_summary( ): """Items sent (added) per waiter — regardless of payment status.""" q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) + start = end = None # 6.12a: with a business day there is no window (was a crash) if business_day_id: q = q.join(Order).filter(Order.business_day_id == business_day_id) else: @@ -208,7 +210,10 @@ def shift_orders_summary( hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta summary: dict[int, dict] = {} - for item in items: + for line in sales.lines(db, items): # 6.12a: net of refunds, the delivery fee left out + if line.fee or not line.kept: + continue + item = line.item wid = item.added_by if wid not in summary: w = waiters_db.get(wid) @@ -221,8 +226,8 @@ def shift_orders_summary( "cancellations": 0, "order_data": {}, } - summary[wid]["items"] += item.quantity - val = _item_val(item) + summary[wid]["items"] += line.quantity + val = line.value summary[wid]["total"] += val oid = item.order_id @@ -239,7 +244,7 @@ def shift_orders_summary( summary[wid]["order_data"][oid]["total"] += val product_name = item.product_name summary[wid]["order_data"][oid]["items"].append( - {"name": product_name, "quantity": item.quantity} + {"name": product_name, "quantity": line.quantity} ) for item in cancelled_items: @@ -262,9 +267,11 @@ def shift_orders_summary( entry["orders"] = len(entry["order_data"]) entry["order_data"] = list(entry["order_data"].values()) entry["hours_worked"] = round(hours_by_waiter.get(entry["waiter_id"], 0.0), 2) + entry["items"] = round(entry["items"], 3) + entry["total"] = round(entry["total"], 2) result.append(entry) - return {"from": start.isoformat(), "to": end.isoformat(), "waiters": result} + return {"from": _dt(start), "to": _dt(end), "waiters": result} @history_router.get("/orders/history") @@ -346,6 +353,7 @@ def order_history( return None return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat() + per_order = sales.order_totals(db, orders) # 6.12a: products net of refunds, fees apart result = [] for o in orders: items_out = [] @@ -362,6 +370,7 @@ def order_history( "unit_price": float(item.unit_price), "price_adjustment": float(item.price_adjustment or 0.0), "status": item.status, + "system_key": item.system_key, "paid_by": item.paid_by, "paid_by_name": _wname(item.paid_by), "paid_at": _dt_local(item.paid_at), @@ -402,6 +411,7 @@ def order_history( "notes": o.notes, "business_day_id": o.business_day_id, "items": items_out, + "totals": per_order[o.id].out(), "waiters": [{"waiter_id": w.waiter_id} for w in o.waiters], "audit_logs": audit_out, }) @@ -777,15 +787,10 @@ def print_products( ) items = q.all() - sold: dict = {} - for item in items: - pid = item.product_id - if pid not in sold: - sold[pid] = {"qty": 0, "revenue": 0.0} - sold[pid]["qty"] += item.quantity - sold[pid]["revenue"] += _item_val(item) - - sold_names, _ = _names_as_sold(items) # names as sold (D-18) + # 6.12a: the screen's numbers (net of refunds, the delivery fee left out), names as sold (D-18) + per_product = sales.products(db, items) + sold = {pid: {"qty": round(v["qty_sold"], 3), "revenue": v["revenue"]} for pid, v in per_product.items()} + sold_names = {pid: v["product_name"] for pid, v in per_product.items()} if body.mode == "full": # All active products, 0-sold included (unsold ones under their current name), # plus anything sold that's no longer active @@ -841,20 +846,10 @@ def print_categories( ) items = q.all() - prod_names, cat_names = _names_as_sold(items) - # summary[cid] = {name, units_sold, revenue, products: {pid: {name, qty, revenue}}} - summary: dict = {} - for item in items: - cid = item.category_id # as sold (D-18) - pid = item.product_id - if cid not in summary: - summary[cid] = {"name": cat_names.get(cid) or "—", "units_sold": 0, "revenue": 0.0, "products": {}} - summary[cid]["units_sold"] += item.quantity - summary[cid]["revenue"] += _item_val(item) - if pid not in summary[cid]["products"]: - summary[cid]["products"][pid] = {"name": prod_names[pid], "qty": 0, "revenue": 0.0} - summary[cid]["products"][pid]["qty"] += item.quantity - summary[cid]["products"][pid]["revenue"] += _item_val(item) + # 6.12a: the screen's numbers (net of refunds, fees left out), as sold (D-18) + summary: dict = {cid: {"name": v["category_name"], "units_sold": round(v["units_sold"], 3), "revenue": v["revenue"], + "products": {pid: {**p, "qty": round(p["qty"], 3)} for pid, p in v["products"].items()}} + for cid, v in sales.categories(db, items).items()} total_rev = sum(v["revenue"] for v in summary.values()) total_qty = sum(v["units_sold"] for v in summary.values()) @@ -913,28 +908,9 @@ def print_tables( ) orders = q.all() - tables_db = {t.id: t for t in db.query(Table).all()} - summary: dict = {} - for order in orders: - tid = order.table_id - if tid not in summary: - t = tables_db.get(tid) - summary[tid] = { - "name": (t.label or f"T{t.number}") if t else f"#{tid}", - "order_count": 0, "revenue": 0.0, "durations": [], - } - summary[tid]["order_count"] += 1 - summary[tid]["revenue"] += sum(_item_val(i) for i in order.items if i.status in ("active", "paid")) - if order.closed_at and order.opened_at: - summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60) - - table_list = [] - for entry in summary.values(): - durations = entry.pop("durations") - entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None - entry["revenue"] = round(entry["revenue"], 2) - table_list.append(entry) - table_list.sort(key=lambda x: x["revenue"], reverse=True) + # 6.12a: the screen's numbers + table_list = [{"name": t["table_name"] or "—", "order_count": t["order_count"], "revenue": t["revenue"], + "avg_duration_minutes": t["avg_duration_minutes"]} for t in _table_summary(db, orders)] report = { "mode": body.mode, @@ -1027,37 +1003,8 @@ def product_performance( waste_by_product[pid]["waste_qty"] += w.quantity waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0 - sold_names, _ = _names_as_sold(items) - summary: dict = {} - for item in items: - pid = item.product_id - if category_id and item.category_id != category_id: # the category it was sold in (D-18) - continue - if pid not in summary: - summary[pid] = { - "product_id": pid, - "product_name": sold_names[pid], - "category_id": item.category_id, - "qty_sold": 0, - "revenue": 0.0, - "total_cost": 0.0, - "trackable_profit": 0.0, - "uncosted_revenue": 0.0, - "uncosted_items": 0, - "order_ids": set(), - } - qty = item.quantity - revenue = _item_val(item) - summary[pid]["qty_sold"] += qty - summary[pid]["revenue"] += revenue - summary[pid]["order_ids"].add(item.order_id) - if item.unit_cost is not None: - cost = item.unit_cost * qty - summary[pid]["total_cost"] += cost - summary[pid]["trackable_profit"] += revenue - cost - else: - summary[pid]["uncosted_revenue"] += revenue - summary[pid]["uncosted_items"] += qty + # 6.12a: net of refunds, the delivery fee left out (services/sales.py); the category it was sold in (D-18) + summary: dict = sales.products(db, items, category_id) # Also include products that only have waste (not sold) in the period for pid, wdata in waste_by_product.items(): @@ -1069,7 +1016,7 @@ def product_performance( "product_id": pid, "product_name": product.name if product else f"#{pid}", "category_id": product.primary_category_id if product else None, - "qty_sold": 0, "revenue": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, + "qty_sold": 0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(), } @@ -1078,7 +1025,10 @@ def product_performance( pid = entry["product_id"] wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0}) entry["order_count"] = len(entry.pop("order_ids")) + entry["qty_sold"] = round(entry["qty_sold"], 3) + entry["uncosted_items"] = round(entry["uncosted_items"], 3) entry["revenue"] = round(entry["revenue"], 2) + entry["refunded"] = round(entry["refunded"], 2) entry["total_cost"] = round(entry["total_cost"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2) entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 2) @@ -1113,38 +1063,34 @@ def table_performance( q = q.filter(Order.business_day_id == business_day_id) orders = q.all() - tables_db = {t.id: t for t in db.query(Table).all()} + return {"tables": _table_summary(db, orders)} + +def _table_summary(db, orders) -> list[dict]: + """Per table: orders, revenue (products, net of refunds) and fees, average time (6.12a).""" + tables_db = {t.id: t for t in db.query(Table).all()} + per_order = sales.order_totals(db, orders) summary: dict = {} for order in orders: tid = order.table_id if tid not in summary: t = tables_db.get(tid) - summary[tid] = { - "table_id": tid, - "table_name": (t.label or f"T{t.number}") if t else f"#{tid}", - "order_count": 0, - "revenue": 0.0, - "durations": [], - } + summary[tid] = {"table_id": tid, "table_name": (t.label or f"T{t.number}") if t else None, + "order_count": 0, "revenue": 0.0, "fees": 0.0, "durations": []} summary[tid]["order_count"] += 1 - summary[tid]["revenue"] += sum( - _item_val(i) for i in order.items if i.status in ("active", "paid") - ) + summary[tid]["revenue"] += per_order[order.id].revenue + summary[tid]["fees"] += per_order[order.id].fees if order.closed_at and order.opened_at: - summary[tid]["durations"].append( - (order.closed_at - order.opened_at).total_seconds() / 60 - ) - + summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60) result = [] for entry in summary.values(): durations = entry.pop("durations") entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None entry["revenue"] = round(entry["revenue"], 2) + entry["fees"] = round(entry["fees"], 2) result.append(entry) - result.sort(key=lambda x: x["revenue"], reverse=True) - return {"tables": result} + return result # --------------------------------------------------------------------------- @@ -1193,10 +1139,8 @@ def traffic_analysis( q = q.filter(Order.business_day_id == business_day_id) orders = q.all() - by_hour, by_weekday = traffic_buckets( - (order.opened_at, sum(_item_val(i) for i in order.items if i.status in ("active", "paid"))) - for order in orders - ) + per_order = sales.order_totals(db, orders) # 6.12a: products, net of refunds + by_hour, by_weekday = traffic_buckets((order.opened_at, per_order[order.id].revenue) for order in orders) return { "by_hour": list(by_hour.values()), @@ -1231,22 +1175,8 @@ def business_days_list( cancelled_orders = [o for o in orders if o.status == "cancelled"] day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all() waiter_ids = {s.waiter_id for s in day_shifts} - revenue = 0.0 - total_cost = 0.0 - trackable_profit = 0.0 - has_gap = False - for o in closed_orders: - for i in o.items: - if i.status not in ("active", "paid"): - continue - rev = _item_val(i) - revenue += rev - if i.unit_cost is not None: - cost = i.unit_cost * i.quantity - total_cost += cost - trackable_profit += rev - cost - else: - has_gap = True + # 6.12a: everything sold that day (open orders too), net of refunds, fees apart + money = sales.totals(sales.lines(db, [i for o in orders for i in o.items])).out() opener = waiters_db.get(d.opened_by_id) closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None result.append({ @@ -1262,11 +1192,8 @@ def business_days_list( "cancellation_count": len(cancelled_orders), "waiter_count": len(waiter_ids), "shift_count": len(day_shifts), - "revenue": round(revenue, 2), + **money, "refunds": day_refunds(db, d.id), - "total_cost": round(total_cost, 2), - "trackable_profit": round(trackable_profit, 2), - "has_gap": has_gap, }) return {"business_days": result} @@ -1288,37 +1215,21 @@ def current_business_day( WaiterShift.business_day_id == day.id, WaiterShift.ended_at == None, ).all() - revenue = 0.0 - total_cost = 0.0 - trackable_profit = 0.0 - has_gap = False - for o in closed_orders: - for i in o.items: - if i.status not in ("active", "paid"): - continue - rev = _item_val(i) - revenue += rev - if i.unit_cost is not None: - cost = i.unit_cost * i.quantity - total_cost += cost - trackable_profit += rev - cost - else: - has_gap = True + day_lines = sales.lines(db, [i for o in orders for i in o.items]) + money = sales.totals(day_lines).out() # 6.12a: everything sold so far, net of refunds, fees apart item_counts: dict = {} - for o in orders: - if o.status == "cancelled": + item_names: dict = {} + for line in day_lines: + if line.fee or not line.kept: continue - for item in o.items: - if item.status in ("active", "paid"): - pid = item.product_id - item_counts[pid] = item_counts.get(pid, 0) + item.quantity + pid = line.item.product_id + item_counts[pid] = item_counts.get(pid, 0) + line.quantity + item_names[pid] = line.item.product_name top_product_id = max(item_counts, key=item_counts.get) if item_counts else None top_product = None if top_product_id: - from models.product import Product - p = db.query(Product).filter(Product.id == top_product_id).first() - top_product = {"id": top_product_id, "name": p.name if p else f"#{top_product_id}", "qty": item_counts[top_product_id]} + top_product = {"id": top_product_id, "name": item_names.get(top_product_id) or f"#{top_product_id}", "qty": round(item_counts[top_product_id], 3)} # Count cancelled items (individual items cancelled, across all orders in this day) all_order_ids = [o.id for o in orders] @@ -1339,11 +1250,8 @@ def current_business_day( "business_day": { "id": day.id, "opened_at": _dt(day.opened_at), - "revenue": round(revenue, 2), + **money, "refunds": day_refunds(db, day.id), - "total_cost": round(total_cost, 2), - "trackable_profit": round(trackable_profit, 2), - "has_gap": has_gap, "orders_closed": len(closed_orders), "orders_open": len(open_orders), "active_waiters": len(active_shifts), @@ -1367,13 +1275,14 @@ def revenue_trends( db: Session = Depends(get_db), user: User = Depends(require_reports), ): - q = db.query(Order).filter(Order.status.in_(["closed", "paid"])) + q = db.query(Order).filter(Order.status != "cancelled") # 6.12a: what was sold, open orders too _since = history_since(from_dt, 'reports') if _since: q = q.filter(Order.opened_at >= _since) if to_dt: q = q.filter(Order.opened_at <= parse_api_datetime(to_dt)) orders = q.all() + per_order = sales.order_totals(db, orders) # Bucket by business date (D-11): the stored date of the order's business day, # or computed from opened_at for orders outside a business day. @@ -1390,21 +1299,18 @@ def revenue_trends( key = dt.strftime("%Y-%m-%d") if key not in buckets: - buckets[key] = {"date": key, "revenue": 0.0, "profit": 0.0, "has_gap": False, "orders": 0} - for i in order.items: - if i.status not in ("active", "paid"): - continue - rev = _item_val(i) - buckets[key]["revenue"] += rev - if i.unit_cost is not None: - buckets[key]["profit"] += rev - i.unit_cost * i.quantity - else: - buckets[key]["has_gap"] = True + buckets[key] = {"date": key, "revenue": 0.0, "fees": 0.0, "profit": 0.0, "has_gap": False, "orders": 0} + t = per_order[order.id] + buckets[key]["revenue"] += t.revenue + buckets[key]["fees"] += t.fees + buckets[key]["profit"] += t.profit + buckets[key]["has_gap"] = buckets[key]["has_gap"] or t.has_gap buckets[key]["orders"] += 1 arr = sorted(buckets.values(), key=lambda x: x["date"]) for d in arr: d["revenue"] = round(d["revenue"], 2) + d["fees"] = round(d["fees"], 2) d["profit"] = round(d["profit"], 2) if granularity == "daily": @@ -1419,17 +1325,6 @@ def revenue_trends( # Category performance # --------------------------------------------------------------------------- -def _names_as_sold(items) -> tuple[dict, dict]: - """{product_id: name}, {category_id: name} from the order items' snapshots (D-18, CS-4). - If a product or category was renamed within the period, the newest name sold wins.""" - pnames, cnames = {}, {} - for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)): - pnames[it.product_id] = it.product_name - if it.category_id is not None: - cnames[it.category_id] = it.category_name - return pnames, cnames - - @router.get("/categories/performance") def category_performance( from_dt: Optional[str] = Query(default=None, alias="from"), @@ -1451,43 +1346,18 @@ def category_performance( items = q.all() categories_db = {c.id: c for c in db.query(Category).all()} - _, cat_names = _names_as_sold(items) - - summary: dict = {} - for item in items: - cid = item.category_id # the category it was in when sold (D-18) - if cid not in summary: - cat = categories_db.get(cid) - summary[cid] = { - "category_id": cid, - "category_name": cat_names.get(cid) or "—", - "color": cat.color if cat and hasattr(cat, "color") else None, - "units_sold": 0, - "revenue": 0.0, - "total_cost": 0.0, - "trackable_profit": 0.0, - "uncosted_revenue": 0.0, - "has_gap": False, - "product_ids": set(), - } - qty = item.quantity - rev = _item_val(item) - summary[cid]["units_sold"] += qty - summary[cid]["revenue"] += rev - summary[cid]["product_ids"].add(item.product_id) - if item.unit_cost is not None: - cost = item.unit_cost * qty - summary[cid]["total_cost"] += cost - summary[cid]["trackable_profit"] += rev - cost - else: - summary[cid]["uncosted_revenue"] += rev - summary[cid]["has_gap"] = True + # 6.12a: net of refunds, fees left out; the category it was in when sold (D-18) + summary: dict = sales.categories(db, items) total_rev = sum(v["revenue"] for v in summary.values()) total_profit = sum(v["trackable_profit"] for v in summary.values()) result = [] for entry in summary.values(): - entry["product_count"] = len(entry.pop("product_ids")) + cat = categories_db.get(entry["category_id"]) + entry["color"] = cat.color if cat is not None else None + entry["product_count"] = len(entry.pop("products")) + entry["units_sold"] = round(entry["units_sold"], 3) + entry["refunded"] = round(entry["refunded"], 2) entry["revenue"] = round(entry["revenue"], 2) entry["total_cost"] = round(entry["total_cost"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2) @@ -1721,30 +1591,6 @@ def meta_products( # CSV export endpoints # --------------------------------------------------------------------------- -def _csv_response_fields(rows: list, fields: list, filename: str) -> StreamingResponse: - output = io.StringIO() - writer = csv.DictWriter(output, fieldnames=fields) - writer.writeheader() - writer.writerows(rows) - return StreamingResponse(iter([output.getvalue()]), media_type="text/csv", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}) - - -def _csv_response(rows: list, filename: str) -> StreamingResponse: - if not rows: - rows = [{}] - output = io.StringIO() - writer = csv.DictWriter(output, fieldnames=list(rows[0].keys())) - writer.writeheader() - writer.writerows(rows) - output.seek(0) - return StreamingResponse( - iter([output.getvalue()]), - media_type="text/csv", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, - ) - - @router.get("/shifts/export") def shifts_export( waiter_id: Optional[int] = None, @@ -1754,26 +1600,18 @@ def shifts_export( db: Session = Depends(get_db), user: User = Depends(require_reports), ): + """Shifts as CSV (6.12a: venue time, the zone in the header; csv_export).""" data = shifts_report(waiter_id=waiter_id, business_day_id=business_day_id, from_dt=from_dt, to_dt=to_dt, active_only=False, db=db, user=user) - rows = [] - for s in data["shifts"]: - rows.append({ - "id": s["id"], - "waiter": s["waiter_name"], - "started_at": s["started_at"], - "ended_at": s["ended_at"] or "", - "duration_hours": s.get("duration_hours", ""), - "hourly_rate": s.get("hourly_rate_snapshot", ""), - "shift_pay": s.get("shift_pay", ""), - "counted_cash_end": s.get("counted_cash_end", ""), - "cash_discrepancy": s.get("cash_discrepancy", ""), - "starting_cash": s["starting_cash"], - "total_collected": s["total_collected"], - "net_to_deliver": s["net_to_deliver"], - "status": "active" if s["is_active"] else "ended", - }) - date_str = (from_dt or "")[:10] - return _csv_response(rows, f"shifts-{date_str}.csv") + rows = [{ + "id": s["id"], "waiter": s["waiter_name"], "started_at": s["started_at"], "ended_at": s["ended_at"], + "duration_hours": s.get("duration_hours"), "hourly_rate": s.get("hourly_rate_snapshot"), "shift_pay": s.get("shift_pay"), + "starting_cash": s["starting_cash"], "total_collected": s["total_collected"], "net_to_deliver": s["net_to_deliver"], + "counted_cash_end": s.get("counted_cash_end"), "cash_discrepancy": s.get("cash_discrepancy"), + "status": "active" if s["is_active"] else "ended", + } for s in data["shifts"]] + fields = ["id", "waiter", "started_at", "ended_at", "duration_hours", "hourly_rate", "shift_pay", "starting_cash", + "total_collected", "net_to_deliver", "counted_cash_end", "cash_discrepancy", "status"] + return csv_export.response(db, rows, fields, f"shifts-{(from_dt or '')[:10]}.csv", times=("started_at", "ended_at")) @router.get("/orders/export") @@ -1787,23 +1625,17 @@ def orders_export( db: Session = Depends(get_db), user: User = Depends(require_reports), ): - """Orders as CSV, same filters as GET /orders/history (KI-008: it read the history's - dicts as ORM rows and always failed; business_day_id was ignored). Times are UTC ISO, - like the other exports.""" + """Orders as CSV, same filters as GET /orders/history: products (net of refunds), the + delivery fee apart, what was refunded (6.12a), times in venue time.""" orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status, table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user) rows = [{ - "id": o["id"], - "table": o["table_name"] or "", - "waiter": o["opened_by_name"] or "", - "opened_at": o["opened_at"] or "", - "closed_at": o["closed_at"] or "", - "status": o["status"], - "total": round(sum((i["unit_price"] + i["price_adjustment"]) * i["quantity"] - for i in o["items"] if i["status"] in ("active", "paid")), 2), + "id": o["id"], "table": o["table_name"] or "", "waiter": o["opened_by_name"] or "", + "opened_at": o["opened_at"], "closed_at": o["closed_at"], "status": o["status"], + "products": o["totals"]["revenue"], "fees": o["totals"]["fees"], "refunded": o["totals"]["refunded"], "total": o["totals"]["takings"], } for o in orders] - fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "total"] # header even when empty - return _csv_response_fields(rows, fields, f"orders-{(from_date or '')[:10]}.csv") + fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "products", "fees", "refunded", "total"] + return csv_export.response(db, rows, fields, f"orders-{(from_date or '')[:10]}.csv", times=("opened_at", "closed_at")) @router.get("/products/export") @@ -1816,16 +1648,8 @@ def products_export( user: User = Depends(require_reports), ): data = product_performance(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, category_id=category_id, db=db, user=user) - rows = [{ - "product_id": p["product_id"], - "product_name": p["product_name"], - "category_id": p.get("category_id", ""), - "qty_sold": p["qty_sold"], - "revenue": p["revenue"], - "order_count": p["order_count"], - } for p in data["products"]] - date_str = (from_dt or "")[:10] - return _csv_response(rows, f"products-{date_str}.csv") + fields = ["product_id", "product_name", "category_id", "qty_sold", "revenue", "refunded", "total_cost", "trackable_profit", "order_count"] + return csv_export.response(db, data["products"], fields, f"products-{(from_dt or '')[:10]}.csv") @router.get("/printers/export") @@ -1838,17 +1662,10 @@ def printers_export( user: User = Depends(require_reports), ): data = printer_history(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, printer_id=printer_id, db=db, user=user) - rows = [{ - "id": r["id"], - "printed_at": r["printed_at"], - "printer": r["printer_name"], - "order_id": r["order_id"], - "table": r["table"], - "success": r["success"], - "error_message": r.get("error_message") or "", - } for r in data["logs"]] - date_str = (from_dt or "")[:10] - return _csv_response(rows, f"printer-history-{date_str}.csv") + rows = [{"id": r["id"], "printed_at": r["printed_at"], "printer": r["printer_name"], "order_id": r["order_id"], + "table": r["table"], "success": r["success"], "error_message": r.get("error_message") or ""} for r in data["logs"]] + fields = ["id", "printed_at", "printer", "order_id", "table", "success", "error_message"] + return csv_export.response(db, rows, fields, f"printer-history-{(from_dt or '')[:10]}.csv", times=("printed_at",)) @router.get("/cancellations/export") @@ -1861,20 +1678,11 @@ def cancellations_export( user: User = Depends(require_reports), ): data = cancellations_log(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, waiter_id=waiter_id, db=db, user=user) - rows = [{ - "id": c["id"], - "order_id": c["order_id"], - "table": c["table"], - "waiter": c["waiter_name"], - "product": c["product_name"], - "quantity": c["quantity"], - "value": c["value"], - "cancelled_by": c.get("cancelled_by") or "", - "reason": c.get("cancel_reason") or "", - "cancelled_at": c["cancelled_at"], - } for c in data["cancellations"]] - date_str = (from_dt or "")[:10] - return _csv_response(rows, f"cancellations-{date_str}.csv") + rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table"], "waiter": c["waiter_name"], "product": c["product_name"], + "quantity": c["quantity"], "value": c["value"], "cancelled_by": c.get("cancelled_by") or "", + "reason": c.get("cancel_reason") or "", "cancelled_at": c["cancelled_at"]} for c in data["cancellations"]] + fields = ["id", "order_id", "table", "waiter", "product", "quantity", "value", "cancelled_by", "reason", "cancelled_at"] + return csv_export.response(db, rows, fields, f"cancellations-{(from_dt or '')[:10]}.csv", times=("cancelled_at",)) # ── Prep Zones report ────────────────────────────────────────────────────────── diff --git a/local_backend/services/csv_export.py b/local_backend/services/csv_export.py new file mode 100644 index 0000000..e05270a --- /dev/null +++ b/local_backend/services/csv_export.py @@ -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}"'}) diff --git a/local_backend/services/sales.py b/local_backend/services/sales.py new file mode 100644 index 0000000..d9d3112 --- /dev/null +++ b/local_backend/services/sales.py @@ -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 diff --git a/local_backend/tests/test_reports_export.py b/local_backend/tests/test_reports_export.py index 2131c47..743ff8c 100644 --- a/local_backend/tests/test_reports_export.py +++ b/local_backend/tests/test_reports_export.py @@ -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 io -def _rows(r): +def _rows(r, sep=","): assert r.status_code == 200, r.text 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.product import Category, Product 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) db.add(prod) 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.flush() 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, status="cancelled")]) 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")) rows = _rows(client.get("/api/reports/orders/export", headers=h)) assert len(rows) == 1 row = rows[0] 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["opened_at"].endswith(("Z", "+00:00")) # UTC, like the other exports + 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 (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 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): 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" diff --git a/local_backend/tests/test_sales_accounting.py b/local_backend/tests/test_sales_accounting.py new file mode 100644 index 0000000..842a335 --- /dev/null +++ b/local_backend/tests/test_sales_accounting.py @@ -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 diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 68b157c..caf5c9e 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -45,7 +45,7 @@ import ThrowawaysPage from './pages/inventory/ThrowawaysPage' import StockPage from './pages/inventory/StockPage' // Reports -import TodayPage from './pages/reports/TodayPage' +import TodayPage from './pages/reports/today/TodayReport' import StorePage from './pages/reports/StorePage' import StaffReportPage from './pages/reports/StaffReportPage' import ProductsReportPage from './pages/reports/ProductsReportPage' diff --git a/manager_dashboard/src/pages/reports/TodayPage.jsx b/manager_dashboard/src/pages/reports/TodayPage.jsx deleted file mode 100644 index 767bc49..0000000 --- a/manager_dashboard/src/pages/reports/TodayPage.jsx +++ /dev/null @@ -1,9 +0,0 @@ -import Today from './restaurant/Today' - -export default function TodayPage() { - return ( -
{t(`reports.rangeProblem.${problem}`)}
} +|
+ {c.sort === false ? c.label : (
+
+ )}
+ {c.tip && |
+ ))}
+
|---|
| {c.render ? c.render(r) : r[c.key]} | + ))} +
{t('reports.showing', { shown: limit, total: sorted.length })}
} +{t('reports.today.since', { time: fmt.formatDateTime(d.opened_at, 'datetimeShort') })}
+