Spaces:
Sleeping
Sleeping
File size: 5,774 Bytes
a812c01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | """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}
|