"""Order tools (place_order, get_order_status) + kitchen display endpoints.""" from __future__ import annotations import re from typing import Optional from fastapi import APIRouter, Depends, Query from pydantic import BaseModel import config import sanitize from auth import require_token from matcher import find_dish from store import ORDER_STATUSES, get_store router = APIRouter(prefix="/api/orders", tags=["orders"]) # "2x Nachos", "2 x Nachos", "2 Nachos", "Nachos" (qty 1) _ITEM_RE = re.compile(r"^\s*(\d+)\s*[x×*]?\s*(.+?)\s*$", re.IGNORECASE) def parse_items(items_str: str, menu: list[dict]) -> tuple[list[dict], int]: """Parse the agent's comma-separated item string into priced line items. Unresolved names are kept with price=None so the kitchen still sees them. Returns (items, total) where total covers only priced items. """ items: list[dict] = [] total = 0 for segment in items_str.split(","): segment = segment.strip() if not segment: continue m = _ITEM_RE.match(segment) if m and m.group(2): quantity, name = int(m.group(1)), m.group(2) else: quantity, name = 1, segment matched, _ = find_dish(name, menu) if matched: price = matched["price"] items.append({"name": matched["name"], "quantity": quantity, "price": price}) total += price * quantity else: items.append({"name": name, "quantity": quantity, "price": None}) return items, total class PlaceOrderBody(BaseModel): items: str order_type: str = "dine-in" outlet_location: str = config.DEFAULT_OUTLET table_number: Optional[str] = None customer_name: Optional[str] = None customer_phone: Optional[str] = None call_id: Optional[str] = None @router.post("", dependencies=[Depends(require_token)]) async def place_order(body: PlaceOrderBody): try: store = get_store() items_str = sanitize.clean(body.items) if not items_str: return {"success": False, "message": "No items in the order."} items, total = parse_items(items_str, store.get_menu()) if not items: return {"success": False, "message": "Could not understand the order items."} order = store.insert_order( { "table_number": sanitize.clean(body.table_number), "outlet_location": sanitize.clean(body.outlet_location) or config.DEFAULT_OUTLET, "order_type": (sanitize.clean(body.order_type) or "dine-in").lower(), "items": items, "total_amount": total, "customer_name": sanitize.clean(body.customer_name), "customer_phone": sanitize.clean(body.customer_phone), "call_id": sanitize.clean(body.call_id), } ) unresolved = [i["name"] for i in items if i["price"] is None] message = f"Order sent to the kitchen. Total ₹{total}." if unresolved: message += f" Note: {', '.join(unresolved)} will be confirmed by staff." return {"success": True, "order_id": order["id"], "total_amount": total, "message": message} except Exception as exc: return {"success": False, "message": f"Could not place the order: {exc}"} @router.get("/status", dependencies=[Depends(require_token)]) async def get_order_status( table_number: str = Query(default=""), outlet_location: str = Query(default=config.DEFAULT_OUTLET), ): try: table = sanitize.clean(table_number) outlet = sanitize.clean(outlet_location) or config.DEFAULT_OUTLET if not table: return {"success": False, "message": "No table number provided."} order = get_store().latest_order(table, outlet) if not order: return { "success": True, "found": False, "message": f"No order found for table {table} yet.", } friendly = { "received": "Your order has reached the kitchen and will be picked up shortly.", "preparing": "The kitchen is preparing your order right now.", "ready": "Your order is ready and on its way to your table!", "served": "Your order has been served. Enjoy!", } return { "success": True, "found": True, "status": order["status"], "items": order["items"], "total_amount": order.get("total_amount"), "message": friendly.get(order["status"], f"Order status: {order['status']}"), } except Exception as exc: return {"success": False, "message": f"Could not fetch order status: {exc}"} # ---- Frontend-facing endpoints (kitchen display + table tracker polling) ---- @router.get("") async def list_orders(outlet_location: str = Query(default="")): store = get_store() return {"orders": store.list_orders(sanitize.clean(outlet_location))} @router.get("/table") async def orders_for_table( table_number: str = Query(...), outlet_location: str = Query(default=config.DEFAULT_OUTLET), ): store = get_store() return {"orders": store.orders_for_table(table_number, outlet_location)} class StatusBody(BaseModel): status: str @router.patch("/{order_id}/status") async def update_status(order_id: str, body: StatusBody): if body.status not in ORDER_STATUSES: return {"success": False, "message": f"Invalid status. Use one of {ORDER_STATUSES}."} order = get_store().update_order_status(order_id, body.status) if not order: return {"success": False, "message": "Order not found."} return {"success": True, "order": order}