from core.access.queries import holders_filter from core.errors import XeniaError from core.modules.entitlements import clamp_start, history_floor, history_since, limit from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow from services import tab_books import csv import io import json from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request from fastapi.responses import StreamingResponse from pydantic import BaseModel from sqlalchemy.orm import Session, contains_eager, selectinload from sqlalchemy import func from datetime import date, datetime, timedelta, timezone from typing import Optional, List from database import get_db from models.order import Order, OrderItem, OrderWaiter, PrintLog from models.prep_zone import PrepZone from models.user import User from models.table import Table from models.printer import Printer from models.shift import WaiterShift from models.business_day import BusinessDay from schemas.order import OrderOut from schemas.table import TableOut from routers.deps import require_history, require_reports from services.printer_service import ( print_waiter_report, print_printer_report, print_order_receipt, load_divider_style, print_products_report, print_categories_report, print_tables_report, print_prep_zone_summary, ) def _business_day_guard(module: str): """Router-level dependency (D-6): a business_day_id (query or JSON body) older than the module's history_days is refused, so per-day views respect the limit too.""" async def guard(request: Request, db: Session = Depends(get_db)) -> None: bid = request.query_params.get("business_day_id") if bid is None and request.method in ("POST", "PUT", "PATCH"): try: body = await request.json() bid = body.get("business_day_id") if isinstance(body, dict) else None except Exception: bid = None if not bid: return floor = history_floor(module) if floor is None: return try: day = db.get(BusinessDay, int(bid)) except (TypeError, ValueError): return if day is not None and (day.closed_at or day.opened_at) < floor: raise XeniaError("license.history_limited", module=module, days=limit(module, "history_days")) return guard router = APIRouter(dependencies=[Depends(_business_day_guard("reports"))]) # The free `history` module (APPS_PLATFORM §4.2, D-5): order history, business-day # summaries and the filter lookups. Mounted under the same /api/reports prefix but # gated by `history`, so it still works on the free tier when `reports` isn't licensed. 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: """Effective line value: unit_price + any price adjustment, times quantity.""" return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * item.quantity def _dt(dt): if dt is None: return None return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat() @router.get("/shift") def shift_summary( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), report_date: Optional[date] = Query(default=None, alias="date"), waiter_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): """Payments collected per waiter — based on paid_by on order items.""" if from_dt and to_dt: start = history_since(from_dt, 'reports') end = parse_api_datetime(to_dt) else: # A date means a business date (D-11): its rollover-to-rollover window in UTC start, end = business_date_window(report_date or business_date_of()) start = clamp_start(start, 'reports') q = db.query(OrderItem).filter( OrderItem.status == "paid", OrderItem.paid_at >= start, OrderItem.paid_at < end, ) if waiter_id: q = q.filter(OrderItem.paid_by == waiter_id) items = q.all() waiters_db = {u.id: u for u in db.query(User).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # Build per-waiter summary keyed by waiter_id summary: dict[int, dict] = {} for item in items: wid = item.paid_by if wid not in summary: w = waiters_db.get(wid) wname = (w.full_name or w.username) if w else f"#{wid}" summary[wid] = { "waiter_id": wid, "waiter_name": wname, "items": 0, "total": 0.0, "order_data": {}, } summary[wid]["items"] += item.quantity val = _item_val(item) summary[wid]["total"] += val oid = item.order_id if oid not in summary[wid]["order_data"]: order = db.query(Order).filter(Order.id == oid).first() summary[wid]["order_data"][oid] = { "id": oid, "time_open": venue_strftime(order.opened_at, "%H:%M") if order else "", "time_close": venue_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "", "table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}", "total": 0.0, "items": [], } 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} ) result = [] for entry in summary.values(): entry["orders"] = len(entry["order_data"]) entry["order_data"] = list(entry["order_data"].values()) result.append(entry) return {"from": start.isoformat(), "to": end.isoformat(), "waiters": result} @router.get("/shift/orders") def shift_orders_summary( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), report_date: Optional[date] = Query(default=None, alias="date"), waiter_id: Optional[int] = None, business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): """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: if from_dt and to_dt: start = history_since(from_dt, 'reports') end = parse_api_datetime(to_dt) else: start, end = business_date_window(report_date or business_date_of()) start = clamp_start(start, 'reports') q = q.filter(OrderItem.added_at >= start, OrderItem.added_at < end) if waiter_id: q = q.filter(OrderItem.added_by == waiter_id) items = q.all() # Also fetch cancelled items for the same window/waiter cq = db.query(OrderItem).filter(OrderItem.status == "cancelled") if business_day_id: cq = cq.join(Order, OrderItem.order_id == Order.id).filter(Order.business_day_id == business_day_id) else: cq = cq.filter(OrderItem.added_at >= start, OrderItem.added_at < end) if waiter_id: cq = cq.filter(OrderItem.added_by == waiter_id) cancelled_items = cq.all() waiters_db = {u.id: u for u in db.query(User).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # Track shifts for duration (hours worked) shift_q = db.query(WaiterShift) if business_day_id: shift_q = shift_q.filter(WaiterShift.business_day_id == business_day_id) else: shift_q = shift_q.filter(WaiterShift.started_at >= start, WaiterShift.started_at < end) if waiter_id: shift_q = shift_q.filter(WaiterShift.waiter_id == waiter_id) shifts_list = shift_q.all() # hours worked per waiter hours_by_waiter: dict[int, float] = {} for s in shifts_list: wid = s.waiter_id end_time = s.ended_at or utcnow() delta = (end_time - s.started_at).total_seconds() / 3600.0 hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta summary: dict[int, dict] = {} 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) wname = (w.full_name or w.username) if w else f"#{wid}" summary[wid] = { "waiter_id": wid, "waiter_name": wname, "items": 0, "total": 0.0, "cancellations": 0, "order_data": {}, } summary[wid]["items"] += line.quantity val = line.value summary[wid]["total"] += val oid = item.order_id if oid not in summary[wid]["order_data"]: order = db.query(Order).filter(Order.id == oid).first() summary[wid]["order_data"][oid] = { "id": oid, "time_open": venue_strftime(order.opened_at, "%H:%M") if order else "", "time_close": venue_strftime(order.closed_at, "%H:%M") if order and order.closed_at else "", "table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}", "total": 0.0, "items": [], } summary[wid]["order_data"][oid]["total"] += val product_name = item.product_name summary[wid]["order_data"][oid]["items"].append( {"name": product_name, "quantity": line.quantity} ) for item in cancelled_items: wid = item.added_by if wid not in summary: w = waiters_db.get(wid) wname = (w.full_name or w.username) if w else f"#{wid}" summary[wid] = { "waiter_id": wid, "waiter_name": wname, "items": 0, "total": 0.0, "cancellations": 0, "order_data": {}, } summary[wid]["cancellations"] = summary[wid].get("cancellations", 0) + item.quantity result = [] for entry in summary.values(): 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": _dt(start), "to": _dt(end), "waiters": result} @history_router.get("/orders/history") def order_history( from_date: Optional[str] = Query(default=None, alias="from"), to_date: Optional[str] = Query(default=None, alias="to"), waiter_id: Optional[int] = None, order_status: Optional[str] = Query(default=None, alias="status"), table_id: Optional[int] = None, business_day_id: Optional[int] = None, page: int = 1, page_size: int = 50, db: Session = Depends(get_db), user: User = Depends(require_history), ): from sqlalchemy.orm import joinedload from models.table import Table as TableModel q = db.query(Order).options( joinedload(Order.items).joinedload(OrderItem.product), joinedload(Order.waiters), joinedload(Order.audit_logs), ) if business_day_id: q = q.filter(Order.business_day_id == business_day_id) elif from_date or to_date: _since = history_since(from_date, 'history') if _since: q = q.filter(Order.opened_at >= _since) if to_date: q = q.filter(Order.opened_at <= parse_api_datetime(to_date)) if waiter_id: q = q.join(OrderWaiter).filter(OrderWaiter.waiter_id == waiter_id) if order_status: q = q.filter(Order.status == order_status) if table_id: q = q.filter(Order.table_id == table_id) orders = q.order_by(Order.opened_at.desc()).offset((page - 1) * page_size).limit(page_size).all() # Collect all waiter IDs and table IDs to resolve in bulk waiter_ids: set[int] = set() table_ids: set[int] = set() item_waiter_ids: set[int] = set() for o in orders: if o.opened_by: waiter_ids.add(o.opened_by) if o.closed_by: waiter_ids.add(o.closed_by) if o.table_id: table_ids.add(o.table_id) for item in o.items: if item.added_by: item_waiter_ids.add(item.added_by) if item.paid_by: item_waiter_ids.add(item.paid_by) for log in o.audit_logs: if log.waiter_id: waiter_ids.add(log.waiter_id) all_waiter_ids = waiter_ids | item_waiter_ids waiters_map: dict[int, str] = {} if all_waiter_ids: for w in db.query(User).filter(User.id.in_(all_waiter_ids)).all(): waiters_map[w.id] = w.full_name or w.username tables_map: dict[int, str] = {} if table_ids: for t in db.query(TableModel).filter(TableModel.id.in_(table_ids)).all(): prefix = (t.group.prefix if t.group and t.group.prefix else "") if t.group else "" tables_map[t.id] = t.label if t.label else f"{prefix}{t.number}" def _wname(wid): if wid is None: return None return waiters_map.get(wid, f"#{wid}") def _dt_local(dt): if dt is None: 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 = [] for item in o.items: items_out.append({ "id": item.id, "order_id": item.order_id, "product_id": item.product_id, "product": {"id": item.product_id, "name": item.product_name}, # name as sold (D-18) "added_by": item.added_by, "added_by_name": _wname(item.added_by), "added_at": _dt_local(item.added_at), "quantity": item.quantity, "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), "payment_method": item.payment_method, "paid_in_shift_id": item.paid_in_shift_id, "notes": item.notes, "printed": item.printed, "selected_options": item.selected_options, "removed_ingredients": item.removed_ingredients, }) audit_out = [] for log in o.audit_logs: audit_out.append({ "id": log.id, "order_id": log.order_id, "event_type": log.event_type, "waiter_id": log.waiter_id, "waiter_name": _wname(log.waiter_id), "item_ids": log.item_ids, "amount": log.amount, "payment_method": log.payment_method, "note": log.note, "created_at": _dt_local(log.created_at), "offline_at": log.offline_at, "is_duplicate": log.is_duplicate, }) result.append({ "id": o.id, "table_id": o.table_id, "table_name": tables_map.get(o.table_id) if o.table_id else None, "opened_by": o.opened_by, "opened_by_name": _wname(o.opened_by), "opened_at": _dt_local(o.opened_at), "closed_by": o.closed_by, "closed_by_name": _wname(o.closed_by), "closed_at": _dt_local(o.closed_at), "status": o.status, "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, }) return result @router.get("/tables/summary") def tables_summary(db: Session = Depends(get_db), user: User = Depends(require_reports)): tables = db.query(Table).filter(Table.is_active == True).all() result = [] for table in tables: active_order = db.query(Order).filter( Order.table_id == table.id, Order.status.in_(["open", "partially_paid"]), ).first() result.append({ "table": TableOut.model_validate(table), "status": active_order.status if active_order else "free", "order_id": active_order.id if active_order else None, }) return result @router.get("/printers") def printer_totals( from_date: Optional[str] = Query(default=None, alias="from"), to_date: Optional[str] = Query(default=None, alias="to"), db: Session = Depends(get_db), user: User = Depends(require_reports), ): """Returns totals per printer based on print_log entries in the date range.""" q = db.query(PrintLog).filter(PrintLog.success == True) _since = history_since(from_date, 'reports') if _since: q = q.filter(PrintLog.printed_at >= _since) if to_date: q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_date)) logs = q.all() printers_db = {p.id: p for p in db.query(Printer).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # summary[pid] — aggregated totals summary: dict[int, dict] = {} # order_map[pid][order_id] — per-order detail with items order_map: dict[int, dict] = {} for log in logs: pid = log.printer_id if pid not in summary: printer = printers_db.get(pid) summary[pid] = { "printer_id": pid, "printer_name": printer.name if printer else f"Printer #{pid}", "print_jobs": 0, "orders": set(), "items": 0, "total": 0.0, } order_map[pid] = {} summary[pid]["print_jobs"] += 1 summary[pid]["orders"].add(log.order_id) oid = log.order_id if oid not in order_map[pid]: order = db.query(Order).filter(Order.id == oid).first() order_map[pid][oid] = { "order_id": oid, "time": venue_strftime(log.printed_at, "%H:%M"), "table": tables_db.get(order.table_id, f"#{oid}") if order else f"#{oid}", "total": 0.0, "items": [], } try: item_ids = json.loads(log.item_ids) except Exception: item_ids = [] if item_ids is None: item_ids = [] for item_id in item_ids: item = db.query(OrderItem).filter(OrderItem.id == item_id).first() if item and item.status in ("active", "paid"): summary[pid]["items"] += item.quantity val = _item_val(item) summary[pid]["total"] += val order_map[pid][oid]["total"] += val product_name = item.product_name order_map[pid][oid]["items"].append({"name": product_name, "quantity": item.quantity}) result = [] for pid, entry in summary.items(): entry["orders"] = len(entry["orders"]) entry["order_data"] = list(order_map.get(pid, {}).values()) result.append(entry) return {"printers": result} class PrintWaiterReportBody(BaseModel): waiter_name: str printer_id: int mode: str # "simple" | "extensive" from_dt: str to_dt: str class PrintPrinterReportBody(BaseModel): # printer_target_id: 0 = all printers, >0 = specific printer id printer_target_id: int printer_id: int # mode: "quick" | "orders" | "detailed" mode: str from_dt: Optional[str] = None to_dt: Optional[str] = None business_day_id: Optional[int] = None item_breakdown: bool = False class PrintOrderBody(BaseModel): printer_id: int def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, mode: str) -> dict: """ Build a report block for a single printer from its logs. Returns dict with print_jobs, orders, items, total, order_data, item_breakdown. item_breakdown is always computed (used for product analysis section when requested). """ order_map: dict = {} item_breakdown: dict = {} # name → {"qty": int, "value": float} items_count = 0 grand_total = 0.0 for log in logs: oid = log.order_id if oid not in order_map: order = db.query(Order).filter(Order.id == oid).first() if order: order_map[oid] = { "id": oid, "time": venue_strftime(log.printed_at, "%H:%M"), "table": tables.get(order.table_id, f"#{order.table_id}"), "total": 0.0, "items": [], } try: item_ids = json.loads(log.item_ids) except Exception: item_ids = [] for item_id in item_ids: item = db.query(OrderItem).filter(OrderItem.id == item_id).first() if item and item.status in ("active", "paid"): items_count += item.quantity val = _item_val(item) grand_total += val product_name = item.product_name if oid in order_map: order_map[oid]["total"] += val order_map[oid]["items"].append({ "name": product_name, "quantity": item.quantity, "unit_price": float((item.unit_price or 0.0) + (item.price_adjustment or 0.0)), "total": round(val, 2), }) # Accumulate item breakdown (always, regardless of mode) if product_name not in item_breakdown: item_breakdown[product_name] = {"qty": 0, "value": 0.0} item_breakdown[product_name]["qty"] += item.quantity item_breakdown[product_name]["value"] = round(item_breakdown[product_name]["value"] + val, 2) # Convert breakdown to sorted list for easy rendering breakdown_list = sorted( [{"name": k, "qty": v["qty"], "value": v["value"]} for k, v in item_breakdown.items()], key=lambda x: x["qty"], reverse=True, ) return { "printer_id": printer_id, "printer_name": printer_name, "print_jobs": len(logs), "orders": len(order_map), "items": items_count, "total": round(grand_total, 2), "order_data": list(order_map.values()) if mode in ("orders", "detailed") else [], "item_breakdown": breakdown_list, } @router.post("/print/waiter") def print_waiter( body: PrintWaiterReportBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") from_dt = history_since(body.from_dt, 'reports') to_dt = parse_api_datetime(body.to_dt) # Gather orders for this waiter in time range waiter = db.query(User).filter(User.username == body.waiter_name).first() q = db.query(Order).filter( Order.opened_at >= from_dt, Order.opened_at <= to_dt, ) if waiter: q = q.filter(Order.opened_by == waiter.id) else: q = q.filter(False) orders = q.all() # Enrich with table names tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} order_data = [] for o in orders: active_items = [i for i in o.items if i.status in ("active", "paid")] total = sum(_item_val(i) for i in active_items) order_data.append({ "id": o.id, "time_open": venue_strftime(o.opened_at, "%H:%M"), "time_close": venue_strftime(o.closed_at, "%H:%M") if o.closed_at else "", "table": tables.get(o.table_id, f"#{o.table_id}"), "total": total, "items": [ {"name": i.product_name, "quantity": i.quantity} for i in active_items ], }) items_count = sum( i.quantity for o in orders for i in o.items if i.status in ("active", "paid") ) grand_total = sum(d["total"] for d in order_data) report = { "waiter_name": body.waiter_name, "orders": len(orders), "items": items_count, "total": grand_total, "order_data": order_data if body.mode == "extensive" else [], "from_dt": venue_strftime(from_dt, "%d/%m/%Y %H:%M"), "to_dt": venue_strftime(to_dt, "%d/%m/%Y %H:%M"), } background_tasks.add_task(print_waiter_report, printer.ip_address, printer.port, report, body.mode, printer.codepage_n) return {"status": "printing"} @router.post("/print/printer") def print_printer_totals( body: PrintPrinterReportBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): # The physical printer that will receive the paper printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # Build time filter for logs def _base_log_q(): q = db.query(PrintLog).filter(PrintLog.success == True) if body.business_day_id: q = q.join(Order).filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: from_dt = history_since(body.from_dt, 'reports') to_dt = parse_api_datetime(body.to_dt) q = q.filter(PrintLog.printed_at >= from_dt, PrintLog.printed_at <= to_dt) return q # Determine period label for the receipt header if body.business_day_id: bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first() period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}" period_is_workday = True else: from_dt = history_since(body.from_dt, 'reports') if body.from_dt else None to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None period_label = ( f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}" if from_dt and to_dt else "—" ) period_is_workday = False if body.printer_target_id == 0: # All printers — build one block per active printer that has logs all_printers = db.query(Printer).filter(Printer.is_active == True).all() printer_blocks = [] for p in all_printers: logs = _base_log_q().filter(PrintLog.printer_id == p.id).all() if not logs: continue block = _build_printer_block(p.id, p.name, logs, tables, db, body.mode) printer_blocks.append(block) else: target_printer = db.query(Printer).filter(Printer.id == body.printer_target_id).first() target_name = target_printer.name if target_printer else f"Printer #{body.printer_target_id}" logs = _base_log_q().filter(PrintLog.printer_id == body.printer_target_id).all() printer_blocks = [_build_printer_block(body.printer_target_id, target_name, logs, tables, db, body.mode)] report = { "printer_blocks": printer_blocks, "period_label": period_label, "period_is_workday": period_is_workday, "mode": body.mode, "item_breakdown": body.item_breakdown, "line_width": printer.line_width, "div_style": load_divider_style(db), } background_tasks.add_task(print_printer_report, printer.ip_address, printer.port, report, body.mode, printer.codepage_n) return {"status": "printing"} # --------------------------------------------------------------------------- # Print: products / categories / tables # --------------------------------------------------------------------------- class PrintAnalyticsBody(BaseModel): printer_id: int mode: str # "smart" | "full" from_dt: Optional[str] = None to_dt: Optional[str] = None business_day_id: Optional[int] = None def _analytics_period(body: PrintAnalyticsBody, db) -> tuple[str, bool]: """Return (period_label, period_is_workday).""" if body.business_day_id: bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first() label = bd.business_date.strftime("%d/%m/%Y") if bd else f"Workday #{body.business_day_id}" return label, True from_dt = history_since(body.from_dt, 'reports') if body.from_dt else None to_dt = parse_api_datetime(body.to_dt) if body.to_dt else None label = ( f"{venue_strftime(from_dt, '%d/%m/%Y')} - {venue_strftime(to_dt, '%d/%m/%Y')}" if from_dt and to_dt else "—" ) return label, False @router.post("/print/products") def print_products( body: PrintAnalyticsBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from models.product import Product, Category printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") period_label, period_is_workday = _analytics_period(body, db) # Build sold-item summary q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) if body.business_day_id: q = q.join(Order).filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: q = q.filter( OrderItem.added_at >= history_since(body.from_dt, 'reports'), OrderItem.added_at <= parse_api_datetime(body.to_dt), ) items = q.all() # 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 all_products = db.query(Product).filter(Product.lifecycle_status == "active").order_by(Product.name).all() rows = {p.id: sold_names.get(p.id, p.name) for p in all_products} rows.update(sold_names) report_items = sorted( [{"name": name, "qty": sold.get(pid, {}).get("qty", 0), "revenue": round(sold.get(pid, {}).get("revenue", 0.0), 2)} for pid, name in rows.items()], key=lambda x: x["qty"], reverse=True, ) else: # Smart: only sold report_items = sorted( [{"name": sold_names[pid], "qty": v["qty"], "revenue": round(v["revenue"], 2)} for pid, v in sold.items()], key=lambda x: x["qty"], reverse=True, ) report = { "mode": body.mode, "period_label": period_label, "period_is_workday": period_is_workday, "items": report_items, "line_width": printer.line_width, "div_style": load_divider_style(db), } background_tasks.add_task(print_products_report, printer.ip_address, printer.port, report, printer.codepage_n) return {"status": "printing"} @router.post("/print/categories") def print_categories( body: PrintAnalyticsBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from models.product import Product, Category printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") period_label, period_is_workday = _analytics_period(body, db) q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) if body.business_day_id: q = q.join(Order).filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: q = q.filter( OrderItem.added_at >= history_since(body.from_dt, 'reports'), OrderItem.added_at <= parse_api_datetime(body.to_dt), ) items = q.all() # 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()) cat_list = [] for v in sorted(summary.values(), key=lambda x: x["revenue"], reverse=True): cat_total_qty = v["units_sold"] cat_total_rev = v["revenue"] products_list = sorted( [{"name": p["name"], "qty": p["qty"], "revenue": round(p["revenue"], 2), "pct_qty": round(p["qty"] / cat_total_qty * 100, 1) if cat_total_qty else 0, "pct_rev": round(p["revenue"] / cat_total_rev * 100, 1) if cat_total_rev else 0} for p in v["products"].values()], key=lambda x: x["qty"], reverse=True, ) cat_list.append({ "name": v["name"], "units_sold": v["units_sold"], "revenue": round(v["revenue"], 2), "pct_rev": round(v["revenue"] / total_rev * 100, 1) if total_rev else 0, "pct_qty": round(v["units_sold"] / total_qty * 100, 1) if total_qty else 0, "products": products_list, }) report = { "mode": body.mode, "period_label": period_label, "period_is_workday": period_is_workday, "categories": cat_list, "line_width": printer.line_width, "div_style": load_divider_style(db), } background_tasks.add_task(print_categories_report, printer.ip_address, printer.port, report, printer.codepage_n) return {"status": "printing"} @router.post("/print/tables") def print_tables( body: PrintAnalyticsBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") period_label, period_is_workday = _analytics_period(body, db) q = db.query(Order).filter(Order.status.in_(["closed", "paid"])) if body.business_day_id: q = q.filter(Order.business_day_id == body.business_day_id) elif body.from_dt and body.to_dt: q = q.filter( Order.opened_at >= history_since(body.from_dt, 'reports'), Order.opened_at <= parse_api_datetime(body.to_dt), ) orders = q.all() # 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, "period_label": period_label, "period_is_workday": period_is_workday, "tables": table_list, "line_width": printer.line_width, "div_style": load_divider_style(db), } background_tasks.add_task(print_tables_report, printer.ip_address, printer.port, report, printer.codepage_n) return {"status": "printing"} # --------------------------------------------------------------------------- # Shift history report # --------------------------------------------------------------------------- @router.get("/shifts") def shifts_report( waiter_id: Optional[int] = None, business_day_id: Optional[int] = None, from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), active_only: bool = False, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from routers.shifts import _enrich_shift q = db.query(WaiterShift) if waiter_id: q = q.filter(WaiterShift.waiter_id == waiter_id) if business_day_id: q = q.filter(WaiterShift.business_day_id == business_day_id) _since = history_since(from_dt, 'reports') if _since: q = q.filter(WaiterShift.started_at >= _since) if to_dt: q = q.filter(WaiterShift.started_at <= parse_api_datetime(to_dt)) if active_only: q = q.filter(WaiterShift.ended_at == None) shifts = q.order_by(WaiterShift.started_at.desc()).all() return {"shifts": [_enrich_shift(s, db) for s in shifts]} # --------------------------------------------------------------------------- # Product performance analytics # --------------------------------------------------------------------------- @router.get("/products/performance") def product_performance( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, category_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from models.product import Product from models.waste import WasteLog q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) _since = history_since(from_dt, 'reports') if _since: q = q.filter(OrderItem.added_at >= _since) if to_dt: q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt)) if business_day_id: q = q.join(Order).filter(Order.business_day_id == business_day_id) items = q.all() products_db = {p.id: p for p in db.query(Product).all()} # Phase 2H: load waste for the same period wq = db.query(WasteLog) if business_day_id: wq = wq.filter(WasteLog.business_day_id == business_day_id) elif from_dt and to_dt: wq = wq.filter( WasteLog.logged_at >= history_since(from_dt, 'reports'), WasteLog.logged_at <= parse_api_datetime(to_dt), ) waste_entries = wq.all() waste_by_product: dict = {} for w in waste_entries: pid = w.product_id if pid not in waste_by_product: waste_by_product[pid] = {"waste_qty": 0.0, "waste_cost": 0.0} waste_by_product[pid]["waste_qty"] += w.quantity waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0 # 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(): if pid not in summary: product = products_db.get(pid) if category_id and (not product or product.primary_category_id != category_id): continue summary[pid] = { "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, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(), } result = [] for entry in summary.values(): 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) entry["has_gap"] = entry["uncosted_items"] > 0 entry["waste_qty"] = round(wdata["waste_qty"], 3) entry["waste_cost"] = round(wdata["waste_cost"], 2) result.append(entry) result.sort(key=lambda x: x["qty_sold"], reverse=True) return {"products": result} # --------------------------------------------------------------------------- # Table performance analytics # --------------------------------------------------------------------------- @router.get("/tables/performance") def table_performance( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): q = db.query(Order).filter(Order.status.in_(["closed", "paid"])) _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)) if business_day_id: q = q.filter(Order.business_day_id == business_day_id) orders = q.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 None, "order_count": 0, "revenue": 0.0, "fees": 0.0, "durations": []} summary[tid]["order_count"] += 1 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) 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 result # --------------------------------------------------------------------------- # Traffic analysis (hour-of-day / day-of-week) # --------------------------------------------------------------------------- def traffic_buckets(entries): """(opened_at UTC, revenue) pairs -> hour-of-day and weekday buckets (D-11). Hour = venue wall-clock hour (SQLite can't do zones, so this is done in Python). Weekday = weekday of the business date, so a 01:30 Saturday order counts on Friday. Both 03:xx hours of the autumn DST change land in bucket 3; nothing is dropped. """ by_hour = {h: {"hour": h, "orders": 0, "revenue": 0.0} for h in range(24)} day_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] by_weekday = {d: {"day": d, "label": day_labels[d], "orders": 0, "revenue": 0.0} for d in range(7)} for opened_at, revenue in entries: h = to_venue(opened_at).hour d = business_date_of(opened_at).weekday() by_hour[h]["orders"] += 1 by_hour[h]["revenue"] += revenue by_weekday[d]["orders"] += 1 by_weekday[d]["revenue"] += revenue for h in by_hour: by_hour[h]["revenue"] = round(by_hour[h]["revenue"], 2) for d in by_weekday: by_weekday[d]["revenue"] = round(by_weekday[d]["revenue"], 2) return by_hour, by_weekday @router.get("/traffic") def traffic_analysis( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): q = db.query(Order) _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)) if business_day_id: q = q.filter(Order.business_day_id == business_day_id) orders = q.all() 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()), "by_weekday": list(by_weekday.values()), } # --------------------------------------------------------------------------- # Business days list # --------------------------------------------------------------------------- @history_router.get("/business-days") def business_days_list( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), db: Session = Depends(get_db), user: User = Depends(require_history), ): q = db.query(BusinessDay) _since = history_since(from_dt, 'history') if _since: q = q.filter(BusinessDay.opened_at >= _since) if to_dt: q = q.filter(BusinessDay.opened_at <= parse_api_datetime(to_dt)) days = q.order_by(BusinessDay.opened_at.desc()).all() waiters_db = {u.id: u for u in db.query(User).all()} result = [] for d in days: orders = db.query(Order).filter(Order.business_day_id == d.id).all() closed_orders = [o for o in orders if o.status in ("closed", "paid")] 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} # 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({ "id": d.id, "status": d.status, "opened_at": _dt(d.opened_at), "closed_at": _dt(d.closed_at), "opened_by": (opener.full_name or opener.username) if opener else None, "closed_by": (closer.full_name or closer.username) if closer else None, "notes": d.notes, "order_count": len(orders), "closed_order_count": len(closed_orders), "cancellation_count": len(cancelled_orders), "waiter_count": len(waiter_ids), "shift_count": len(day_shifts), **money, "refunds": day_refunds(db, d.id), }) return {"business_days": result} @history_router.get("/business-days/current") def current_business_day( db: Session = Depends(get_db), user: User = Depends(require_history), ): day = db.query(BusinessDay).filter(BusinessDay.status == "open").order_by(BusinessDay.opened_at.desc()).first() if not day: return {"business_day": None} orders = db.query(Order).filter(Order.business_day_id == day.id).all() closed_orders = [o for o in orders if o.status in ("closed", "paid")] open_orders = [o for o in orders if o.status in ("open", "partially_paid")] cancelled_orders = [o for o in orders if o.status == "cancelled"] active_shifts = db.query(WaiterShift).filter( WaiterShift.business_day_id == day.id, WaiterShift.ended_at == None, ).all() 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 = {} item_names: dict = {} for line in day_lines: if line.fee or not line.kept: continue 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: 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] cancelled_items_qty = 0 cancellation_events = 0 if all_order_ids: from sqlalchemy import func as sqlfunc cancelled_items_qty = db.query(sqlfunc.sum(OrderItem.quantity)).filter( OrderItem.order_id.in_(all_order_ids), OrderItem.status == "cancelled", ).scalar() or 0 cancellation_events = db.query(sqlfunc.count(OrderItem.id)).filter( OrderItem.order_id.in_(all_order_ids), OrderItem.status == "cancelled", ).scalar() or 0 return { "business_day": { "id": day.id, "opened_at": _dt(day.opened_at), **money, "refunds": day_refunds(db, day.id), "tab_received": tab_books.for_day(db, day.id)["received"], # 6.13c: money paid on tabs today "orders_closed": len(closed_orders), "orders_open": len(open_orders), "active_waiters": len(active_shifts), "cancellations": len(cancelled_orders), "cancelled_items": int(cancelled_items_qty), "cancellation_events": int(cancellation_events), "top_product": top_product, } } # --------------------------------------------------------------------------- # Revenue trends # --------------------------------------------------------------------------- @router.get("/revenue/trends") def revenue_trends( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), granularity: str = Query(default="daily"), # daily | weekly | monthly db: Session = Depends(get_db), user: User = Depends(require_reports), ): 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. bd_dates = {bid: bdate for bid, bdate in db.query(BusinessDay.id, BusinessDay.business_date).all()} buckets: dict = {} for order in orders: dt = bd_dates.get(order.business_day_id) or business_date_of(order.opened_at) if granularity == "monthly": key = dt.strftime("%Y-%m") elif granularity == "weekly": monday = dt - timedelta(days=dt.weekday()) key = monday.strftime("%Y-%m-%d") else: key = dt.strftime("%Y-%m-%d") if key not in buckets: 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": for i, d in enumerate(arr): window = arr[max(0, i - 6): i + 1] d["rolling7"] = round(sum(x["revenue"] for x in window) / len(window), 2) return {"trends": arr, "granularity": granularity} # --------------------------------------------------------------------------- # Category performance # --------------------------------------------------------------------------- @router.get("/categories/performance") def category_performance( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from models.product import Product, Category q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"])) _since = history_since(from_dt, 'reports') if _since: q = q.filter(OrderItem.added_at >= _since) if to_dt: q = q.filter(OrderItem.added_at <= parse_api_datetime(to_dt)) if business_day_id: q = q.join(Order).filter(Order.business_day_id == business_day_id) items = q.all() categories_db = {c.id: c for c in db.query(Category).all()} # 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(): 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) entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 2) entry["pct_rev"] = round((entry["revenue"] / total_rev * 100) if total_rev else 0, 1) entry["pct_profit"] = round((entry["trackable_profit"] / total_profit * 100) if total_profit > 0 else 0, 1) entry["pct"] = entry["pct_rev"] result.append(entry) result.sort(key=lambda x: x["revenue"], reverse=True) return {"categories": result} # --------------------------------------------------------------------------- # Cancellations log # --------------------------------------------------------------------------- @router.get("/cancellations") def cancellations_log( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, waiter_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): q = db.query(OrderItem).filter(OrderItem.status == "cancelled").options(selectinload(OrderItem.order)) # Date filter on cancelled_at if available, otherwise fall back to added_at dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6) if dt_from: from sqlalchemy import or_ q = q.filter(or_( OrderItem.cancelled_at >= dt_from, (OrderItem.cancelled_at == None) & (OrderItem.added_at >= dt_from), )) if to_dt: dt_to = parse_api_datetime(to_dt) from sqlalchemy import or_ q = q.filter(or_( OrderItem.cancelled_at <= dt_to, (OrderItem.cancelled_at == None) & (OrderItem.added_at <= dt_to), )) if business_day_id: q = q.join(Order, Order.id == OrderItem.order_id).filter(Order.business_day_id == business_day_id) if waiter_id: # Show items cancelled BY this waiter OR items that were on this waiter's order from sqlalchemy import or_ q = q.filter(or_( OrderItem.cancelled_by == waiter_id, OrderItem.added_by == waiter_id, )) items = q.order_by(OrderItem.added_at.desc()).all() waiters_db = {u.id: u for u in db.query(User).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} result = [] for item in items: order = item.order # loaded with the items (selectinload above) table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—" waiter = waiters_db.get(item.added_by) waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}" cancelled_by_user = waiters_db.get(item.cancelled_by) if item.cancelled_by else None cancelled_by_name = (cancelled_by_user.full_name or cancelled_by_user.username) if cancelled_by_user else None product_name = item.product_name cancelled_at = getattr(item, "cancelled_at", None) result.append({ "id": item.id, "order_id": item.order_id, "table": table_name, "waiter_name": waiter_name, "product_name": product_name, "quantity": item.quantity, "unit_price": item.unit_price, "value": round(_item_val(item), 2), "cancelled_by": cancelled_by_name, "cancel_reason": getattr(item, "cancel_reason", None), "cancelled_at": _dt(cancelled_at) if cancelled_at else _dt(item.added_at), }) total_value = sum(r["value"] for r in result) return {"cancellations": result, "total_value": round(total_value, 2)} # --------------------------------------------------------------------------- # Printer history (detailed log) # --------------------------------------------------------------------------- @router.get("/printers/history") def printer_history( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, printer_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): q = db.query(PrintLog) _since = history_since(from_dt, 'reports') if _since: q = q.filter(PrintLog.printed_at >= _since) if to_dt: q = q.filter(PrintLog.printed_at <= parse_api_datetime(to_dt)) if printer_id: q = q.filter(PrintLog.printer_id == printer_id) if business_day_id: q = q.join(Order).filter(Order.business_day_id == business_day_id) logs = q.order_by(PrintLog.printed_at.desc()).all() printers_db = {p.id: p for p in db.query(Printer).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # Cache orders to avoid repeated queries order_cache = {} def _get_order(oid): if oid not in order_cache: order_cache[oid] = db.query(Order).filter(Order.id == oid).first() return order_cache[oid] result = [] seen_order_totals = {} # order_id → total, so we don't double-count reprints for log in logs: order = _get_order(log.order_id) printer = printers_db.get(log.printer_id) try: item_ids = json.loads(log.item_ids) except Exception: item_ids = [] if item_ids is None: item_ids = [] items = [] for iid in item_ids: oi = db.query(OrderItem).filter(OrderItem.id == iid).first() if oi: pname = oi.product_name items.append({"name": pname, "quantity": oi.quantity}) # Compute full order total (all active+paid items, not just printed slice) order_total = None if order: order_total = sum( _item_val(i) for i in order.items if i.status in ("active", "paid") ) if log.success and log.order_id not in seen_order_totals: seen_order_totals[log.order_id] = order_total result.append({ "id": log.id, "printed_at": _dt(log.printed_at), "printer_name": printer.name if printer else f"#{log.printer_id}", "order_id": log.order_id, "table": tables_db.get(order.table_id, "—") if order else "—", "items": items, "success": log.success, "error_message": log.error_message, "order_total": round(order_total, 2) if order_total is not None else None, }) total = len(result) failed = sum(1 for r in result if not r["success"]) # Sum unique order totals (avoid inflating on reprints of the same order) total_amount = round(sum(seen_order_totals.values()), 2) if seen_order_totals else None return {"logs": result, "total": total, "failed": failed, "total_amount": total_amount} # --------------------------------------------------------------------------- # Waiters list (for filter dropdowns) # --------------------------------------------------------------------------- @history_router.get("/meta/waiters") def meta_waiters( db: Session = Depends(get_db), user: User = Depends(require_history), ): waiters = db.query(User).filter(holders_filter("waiter_app.access"), User.is_active == True).all() return {"waiters": [{"id": w.id, "name": w.full_name or w.username} for w in waiters]} @history_router.get("/meta/tables") def meta_tables( db: Session = Depends(get_db), user: User = Depends(require_history), ): tables = db.query(Table).filter(Table.is_active == True).all() return {"tables": [{"id": t.id, "name": t.label or f"T{t.number}", "group": t.group.name if t.group else None} for t in tables]} @history_router.get("/meta/printers") def meta_printers( db: Session = Depends(get_db), user: User = Depends(require_history), ): printers = db.query(Printer).filter(Printer.is_active == True).all() return {"printers": [{"id": p.id, "name": p.name} for p in printers]} @history_router.get("/meta/products") def meta_products( db: Session = Depends(get_db), user: User = Depends(require_history), ): from models.product import Product, Category products = db.query(Product).filter(Product.lifecycle_status == "active").order_by(Product.name).all() categories_db = {c.id: c.name for c in db.query(Category).all()} return { "products": [ { "id": p.id, "name": p.name, "category_id": p.primary_category_id, "category_ids": p.category_ids, # every category it's listed in (D-23) "category_name": categories_db.get(p.primary_category_id, "—"), "price": float(p.base_price), } for p in products ] } # --------------------------------------------------------------------------- # CSV export endpoints # --------------------------------------------------------------------------- @router.get("/shifts/export") def shifts_export( waiter_id: Optional[int] = None, business_day_id: Optional[int] = None, from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), 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 = [{ "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") def orders_export( from_date: Optional[str] = Query(default=None, alias="from"), to_date: Optional[str] = Query(default=None, alias="to"), waiter_id: Optional[int] = None, order_status: Optional[str] = Query(default=None, alias="status"), table_id: Optional[int] = None, business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): """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"], "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", "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") def products_export( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, category_id: Optional[int] = None, db: Session = Depends(get_db), 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) 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") def printers_export( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), printer_id: Optional[int] = None, business_day_id: Optional[int] = None, db: Session = Depends(get_db), 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"]] 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") def cancellations_export( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, waiter_id: Optional[int] = None, db: Session = Depends(get_db), 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"]] 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 ────────────────────────────────────────────────────────── @router.get("/prep-zones") def prep_zones_report( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): """ Per-prep-zone stats: item totals, full product list, and full order list for the requested date range / business day. """ zones = db.query(PrepZone).order_by(PrepZone.id).all() # Build product → zones mapping product_zone_map: dict[int, list[int]] = {} for zone in zones: for product in zone.products: if product.id not in product_zone_map: product_zone_map[product.id] = [] product_zone_map[product.id].append(zone.id) # Query order items in the requested range q = db.query(OrderItem).join(Order).options(contains_eager(OrderItem.order)) _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)) if business_day_id: q = q.filter(Order.business_day_id == business_day_id) q = q.filter(OrderItem.status.in_(["active", "paid"])) items = q.all() # Aggregate per zone zone_stats: dict[int, dict] = { zone.id: { "id": zone.id, "name": zone.name, "notification_name": zone.notification_name, "printers": [{"id": p.id, "name": p.name} for p in zone.printers], "item_count": 0, "total_value": 0.0, "product_counts": {}, # product_name → {count, value} "orders_map": {}, # order_id → {order_id, table, opened_at, items_count, value} } for zone in zones } for item in items: zids = product_zone_map.get(item.product_id, []) pname = item.product_name ivalue = round(_item_val(item), 2) order = item.order table_label = None if order and order.table: t = order.table table_label = t.label or str(t.number) for zid in zids: if zid not in zone_stats: continue zs = zone_stats[zid] zs["item_count"] += item.quantity zs["total_value"] += ivalue if pname not in zs["product_counts"]: zs["product_counts"][pname] = {"count": 0, "value": 0.0} zs["product_counts"][pname]["count"] += item.quantity zs["product_counts"][pname]["value"] += ivalue if order: oid = order.id if oid not in zs["orders_map"]: zs["orders_map"][oid] = { "order_id": oid, "table": table_label or f"#{oid}", "opened_at": order.opened_at.isoformat() if order.opened_at else None, "items_count": 0, "value": 0.0, } zs["orders_map"][oid]["items_count"] += item.quantity zs["orders_map"][oid]["value"] += ivalue result = [] for zs in zone_stats.values(): all_products = sorted( [ {"name": k, "count": v["count"], "value": round(v["value"], 2)} for k, v in zs["product_counts"].items() ], key=lambda x: -x["count"], ) all_orders = sorted( [ {**o, "value": round(o["value"], 2)} for o in zs["orders_map"].values() ], key=lambda x: x["opened_at"] or "", ) result.append({ "id": zs["id"], "name": zs["name"], "notification_name": zs["notification_name"], "printers": zs["printers"], "item_count": zs["item_count"], "total_value": round(zs["total_value"], 2), "all_products": all_products, "all_orders": all_orders, }) return {"zones": result} class PrintPrepZoneBody(BaseModel): printer_id: int zone_id: int from_dt: Optional[str] = None to_dt: Optional[str] = None business_day_id: Optional[int] = None @router.post("/print/prep-zone") def print_prep_zone( body: PrintPrepZoneBody, background_tasks: BackgroundTasks, db: Session = Depends(get_db), user: User = Depends(require_reports), ): printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() if not printer: raise XeniaError("printer.not_found") zone = db.query(PrepZone).filter(PrepZone.id == body.zone_id).first() if not zone: raise XeniaError("prep_zone.not_found") # Resolve period label if body.business_day_id: from models.business_day import BusinessDay bd = db.query(BusinessDay).filter(BusinessDay.id == body.business_day_id).first() period_label = bd.business_date.strftime("%d/%m/%Y") if bd else f"#{body.business_day_id}" elif body.from_dt and body.to_dt: d1 = venue_strftime(parse_api_datetime(body.from_dt), "%d/%m/%Y") d2 = venue_strftime(parse_api_datetime(body.to_dt), "%d/%m/%Y") period_label = f"{d1} - {d2}" else: period_label = "Όλες" # Build product→zone mapping for this zone product_ids = {product.id for product in zone.products} q = db.query(OrderItem).join(Order) _since = history_since(body.from_dt, 'reports') if _since: q = q.filter(Order.opened_at >= _since) if body.to_dt: q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt)) if body.business_day_id: q = q.filter(Order.business_day_id == body.business_day_id) q = q.filter(OrderItem.status.in_(["active", "paid"])) items = q.all() product_counts: dict[str, dict] = {} for item in items: if item.product_id not in product_ids: continue pname = item.product_name if pname not in product_counts: product_counts[pname] = {"count": 0, "value": 0.0} product_counts[pname]["count"] += item.quantity product_counts[pname]["value"] += _item_val(item) report_items = sorted( [{"name": k, "count": v["count"], "value": round(v["value"], 2)} for k, v in product_counts.items()], key=lambda x: -x["count"], ) report = { "zone_name": zone.name, "period_label": period_label, "items": report_items, "line_width": printer.line_width, "div_style": load_divider_style(db), } background_tasks.add_task(print_prep_zone_summary, printer.ip_address, printer.port, report, printer.codepage_n) return {"status": "printing"} # --------------------------------------------------------------------------- # Phase 2L — Discount audit report # --------------------------------------------------------------------------- @router.get("/price-changes") def price_changes_report( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, applied_by: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): """Prices changed by hand (6F.3) in a period or a business day: each change (the line, before → after, the difference for its quantity, the stage, who, the approving manager, why, the table), totals per person. Needs ordering.prices.view_changes besides the reports key.""" from core.access.check import holds from models.pricing import PriceEventLog from services import price_changes if not holds(user, "ordering.prices.view_changes"): raise XeniaError("access.denied", key="ordering.prices.view_changes") q = db.query(PriceEventLog).filter(PriceEventLog.event_type == price_changes.EVENT) if business_day_id: q = q.join(Order, Order.id == PriceEventLog.order_id).filter(Order.business_day_id == business_day_id) elif from_dt and to_dt: q = q.filter(PriceEventLog.applied_at >= history_since(from_dt, 'reports'), PriceEventLog.applied_at <= parse_api_datetime(to_dt)) if applied_by: q = q.filter(PriceEventLog.applied_by_user_id == applied_by) events = q.order_by(PriceEventLog.applied_at.desc()).all() tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} orders_map = {o.id: o for o in db.query(Order).filter(Order.id.in_({e.order_id for e in events})).all()} if events else {} rows, by_person, total = [], {}, 0.0 for ev in events: row = price_changes.event_out(ev, db) row["at"] = _dt(ev.applied_at) order = orders_map.get(ev.order_id) row["table_name"] = tables_map.get(order.table_id) if order is not None and order.table_id else None row["value"] = round((ev.delta_amount or 0.0) * (ev.quantity or 1.0), 2) total += row["value"] p = by_person.setdefault(ev.applied_by_user_id, {"user_id": ev.applied_by_user_id, "name": row["by"], "count": 0, "total_value": 0.0}) p["count"] += 1 p["total_value"] = round(p["total_value"] + row["value"], 2) rows.append(row) return {"changes": rows, "total_value": round(total, 2), "count": len(rows), "by_person": sorted(by_person.values(), key=lambda x: x["total_value"])} @router.get("/price-changes/export") def price_changes_export( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, applied_by: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): data = price_changes_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, applied_by=applied_by, db=db, user=user) rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table_name"] or "", "product": c["product_name"] or "", "quantity": c["quantity"], "before": c["before"], "after": c["after"], "value": c["value"], "stage": c["stage"] or "", "by": c["by"] or "", "approved_by": c["approved_by"] or "", "reason": c["reason"] or "", "at": c["at"]} for c in data["changes"]] fields = ["id", "order_id", "table", "product", "quantity", "before", "after", "value", "stage", "by", "approved_by", "reason", "at"] return csv_export.response(db, rows, fields, f"price-changes-{(from_dt or '')[:10]}.csv", times=("at",)) @router.get("/discounts") def discounts_report( from_dt: Optional[str] = Query(default=None, alias="from"), to_dt: Optional[str] = Query(default=None, alias="to"), business_day_id: Optional[int] = None, applied_by: Optional[int] = None, db: Session = Depends(get_db), user: User = Depends(require_reports), ): from models.order import OrderDiscount, OrderItem q = db.query(OrderDiscount) if business_day_id: q = q.join(Order, Order.id == OrderDiscount.order_id).filter(Order.business_day_id == business_day_id) elif from_dt and to_dt: q = q.filter( OrderDiscount.applied_at >= history_since(from_dt, 'reports'), OrderDiscount.applied_at <= parse_api_datetime(to_dt), ) if applied_by: q = q.filter(OrderDiscount.applied_by == applied_by) discounts = q.order_by(OrderDiscount.applied_at.desc()).all() users_map = {u.id: u for u in db.query(User).all()} tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} # Preload orders for table names order_ids = {d.order_id for d in discounts} orders_map = {} if order_ids: for o in db.query(Order).filter(Order.id.in_(order_ids)).all(): orders_map[o.id] = o def _compute_discount_amount(d: OrderDiscount) -> float: """Compute the actual euro amount discounted.""" order = orders_map.get(d.order_id) if d.discount_type == "fixed": return round(d.discount_value, 2) if d.discount_type == "percent": if d.item_id: item = db.query(OrderItem).filter(OrderItem.id == d.item_id).first() if item: base = _item_val(item) return round(base * d.discount_value / 100, 2) elif order: base = sum(_item_val(i) for i in order.items if i.status != "cancelled") return round(base * d.discount_value / 100, 2) return 0.0 result = [] total_discount_value = 0.0 by_waiter: dict = {} for d in discounts: order = orders_map.get(d.order_id) applier = users_map.get(d.applied_by) applier_name = (applier.full_name or applier.username) if applier else f"#{d.applied_by}" table_name = tables_map.get(order.table_id) if order and order.table_id else None order_total = sum(_item_val(i) for i in order.items if i.status != "cancelled") if order else None discount_amount = _compute_discount_amount(d) total_discount_value += discount_amount if d.applied_by not in by_waiter: by_waiter[d.applied_by] = {"waiter_id": d.applied_by, "waiter_name": applier_name, "count": 0, "total_value": 0.0} by_waiter[d.applied_by]["count"] += 1 by_waiter[d.applied_by]["total_value"] = round(by_waiter[d.applied_by]["total_value"] + discount_amount, 2) result.append({ "id": d.id, "order_id": d.order_id, "table_name": table_name, "applied_by_id": d.applied_by, "applied_by_name": applier_name, "applied_at": _dt(d.applied_at), "discount_type": d.discount_type, "discount_value": d.discount_value, "discount_amount": discount_amount, "order_total_before": round(order_total, 2) if order_total is not None else None, "item_id": d.item_id, "reason": d.reason, }) return { "discounts": result, "total_discount_value": round(total_discount_value, 2), "order_count": len({d["order_id"] for d in result}), "by_waiter": sorted(by_waiter.values(), key=lambda x: -x["total_value"]), }