Spaces:
Sleeping
Sleeping
File size: 11,222 Bytes
a812c01 c6e972c a812c01 c6e972c a812c01 c6e972c 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | """Storage layer: SupabaseStore when keys are configured, MemoryStore otherwise.
MemoryStore keeps the whole stack runnable with zero external services —
menu loads from data/byg_menu.json and orders live in process memory
(the frontend polls instead of using realtime in that mode).
"""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timezone
from typing import Any, Optional
import config
ORDER_STATUSES = ["received", "preparing", "ready", "served"]
def load_menu_from_file() -> list[dict]:
"""Flatten byg_menu.json into menu_items rows (food shared across outlets,
craft beers merged per-outlet by name)."""
raw = json.loads(config.MENU_FILE.read_text())
items: list[dict] = []
for food in raw["food_menu"]:
items.append(
{
"name": food["name"],
"category": food["category"],
"description": food.get("description"),
"price": food["price"],
"is_veg": food.get("is_veg", False),
"is_available": True,
"rating": food.get("rating"),
"spice_level": food.get("spice_level"),
"abv": None,
"style": None,
"outlet_location": raw["outlets"],
"tags": food.get("tags", []),
}
)
beers: dict[str, dict] = {}
for outlet, brews in raw["craft_beers"].items():
for brew in brews:
entry = beers.setdefault(
brew["name"],
{
"name": brew["name"],
"category": "craft-beer",
"description": brew.get("description"),
"price": brew["price"],
"is_veg": True,
"is_available": True,
"rating": brew.get("rating"),
"spice_level": "none",
"abv": brew.get("abv"),
"style": brew.get("style"),
"outlet_location": [],
"tags": brew.get("tags", []),
},
)
entry["outlet_location"].append(outlet)
items.extend(beers.values())
return items
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
class MemoryStore:
mode = "memory"
def __init__(self):
self.menu = load_menu_from_file()
self.orders: list[dict] = []
self.call_logs: dict[str, dict] = {}
self.reservations: list[dict] = []
def get_menu(self) -> list[dict]:
return self.menu
def insert_order(self, order: dict) -> dict:
order = {
**order,
"id": str(uuid.uuid4()),
"status": "received",
"created_at": _now(),
"updated_at": _now(),
}
self.orders.append(order)
return order
def list_orders(self, outlet_location: Optional[str] = None) -> list[dict]:
rows = [
o
for o in self.orders
if not outlet_location
or o["outlet_location"].lower() == outlet_location.lower()
]
return sorted(rows, key=lambda o: o["created_at"], reverse=True)
def latest_order(self, table_number: str, outlet_location: str) -> Optional[dict]:
for o in self.list_orders(outlet_location):
if str(o.get("table_number")) == str(table_number):
return o
return None
def orders_for_table(self, table_number: str, outlet_location: str) -> list[dict]:
return [
o
for o in self.list_orders(outlet_location)
if str(o.get("table_number")) == str(table_number)
]
def update_order_status(self, order_id: str, status: str) -> Optional[dict]:
for o in self.orders:
if o["id"] == order_id:
o["status"] = status
o["updated_at"] = _now()
return o
return None
def upsert_call_log(self, log: dict) -> dict:
key = log.get("session_id") or str(uuid.uuid4())
existing = self.call_logs.get(key, {"id": str(uuid.uuid4()), "created_at": _now()})
existing.update({k: v for k, v in log.items() if v is not None})
existing["session_id"] = key
self.call_logs[key] = existing
return existing
def list_call_logs(self, limit: int = 50) -> list[dict]:
rows = sorted(self.call_logs.values(), key=lambda r: r.get("created_at", ""), reverse=True)
return rows[:limit]
def latest_call_log(self, table_number: str, outlet_location: str) -> Optional[dict]:
from datetime import datetime, timezone, timedelta
cutoff = (datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat()
for row in self.list_call_logs(100):
if (
str(row.get("table_number")) == str(table_number)
and (row.get("outlet_location") or "").lower() == outlet_location.lower()
and row.get("created_at", "") >= cutoff
):
return row
return None
def insert_reservation(self, reservation: dict) -> dict:
reservation = {
**reservation,
"id": str(uuid.uuid4()),
"status": "pending",
"created_at": _now(),
}
self.reservations.append(reservation)
return reservation
def list_reservations(self, status: Optional[str] = None) -> list[dict]:
rows = self.reservations
if status:
rows = [r for r in rows if r.get("status") == status]
return sorted(rows, key=lambda r: r.get("created_at", ""), reverse=True)
def update_reservation_status(self, reservation_id: str, status: str) -> Optional[dict]:
for r in self.reservations:
if r["id"] == reservation_id:
r["status"] = status
return r
return None
def update_menu_availability(self, item_name: str, is_available: bool) -> bool:
name_lower = item_name.strip().lower()
for item in self.menu:
if item["name"].lower() == name_lower:
item["is_available"] = is_available
return True
return False
def health(self) -> dict:
return {"store": "memory", "menu_items": len(self.menu), "orders": len(self.orders)}
class SupabaseStore:
mode = "supabase"
def __init__(self):
from supabase import create_client
self.client = create_client(config.SUPABASE_URL, config.SUPABASE_SERVICE_KEY)
self._menu_cache: list[dict] = []
def get_menu(self) -> list[dict]:
if not self._menu_cache:
res = (
self.client.table("menu_items")
.select("*")
.eq("is_available", True)
.execute()
)
self._menu_cache = res.data or []
if not self._menu_cache:
# Table not seeded yet — fall back to the bundled menu so
# the agent tools keep working.
self._menu_cache = load_menu_from_file()
return self._menu_cache
def insert_order(self, order: dict) -> dict:
res = self.client.table("orders").insert(order).execute()
return res.data[0]
def list_orders(self, outlet_location: Optional[str] = None) -> list[dict]:
q = self.client.table("orders").select("*").order("created_at", desc=True).limit(50)
if outlet_location:
q = q.ilike("outlet_location", outlet_location)
return q.execute().data or []
def latest_order(self, table_number: str, outlet_location: str) -> Optional[dict]:
rows = self.orders_for_table(table_number, outlet_location)
return rows[0] if rows else None
def orders_for_table(self, table_number: str, outlet_location: str) -> list[dict]:
res = (
self.client.table("orders")
.select("*")
.eq("table_number", str(table_number))
.ilike("outlet_location", outlet_location)
.order("created_at", desc=True)
.limit(20)
.execute()
)
return res.data or []
def update_order_status(self, order_id: str, status: str) -> Optional[dict]:
res = (
self.client.table("orders")
.update({"status": status, "updated_at": _now()})
.eq("id", order_id)
.execute()
)
return res.data[0] if res.data else None
def upsert_call_log(self, log: dict) -> dict:
res = (
self.client.table("call_logs")
.upsert(log, on_conflict="session_id")
.execute()
)
return res.data[0] if res.data else log
def list_call_logs(self, limit: int = 50) -> list[dict]:
res = (
self.client.table("call_logs")
.select("*")
.order("created_at", desc=True)
.limit(limit)
.execute()
)
return res.data or []
def latest_call_log(self, table_number: str, outlet_location: str) -> Optional[dict]:
from datetime import datetime, timezone, timedelta
cutoff = (datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat()
res = (
self.client.table("call_logs")
.select("*")
.eq("table_number", str(table_number))
.ilike("outlet_location", outlet_location)
.gte("created_at", cutoff)
.order("created_at", desc=True)
.limit(1)
.execute()
)
return res.data[0] if res.data else None
def insert_reservation(self, reservation: dict) -> dict:
res = self.client.table("reservations").insert(reservation).execute()
return res.data[0]
def list_reservations(self, status: Optional[str] = None) -> list[dict]:
q = self.client.table("reservations").select("*").order("created_at", desc=True).limit(100)
if status:
q = q.eq("status", status)
return q.execute().data or []
def update_reservation_status(self, reservation_id: str, status: str) -> Optional[dict]:
res = (
self.client.table("reservations")
.update({"status": status})
.eq("id", reservation_id)
.execute()
)
return res.data[0] if res.data else None
def update_menu_availability(self, item_name: str, is_available: bool) -> bool:
res = (
self.client.table("menu_items")
.update({"is_available": is_available})
.ilike("name", item_name)
.execute()
)
self._menu_cache = [] # bust the cache
return bool(res.data)
def health(self) -> dict:
count = (
self.client.table("menu_items").select("id", count="exact").execute().count
)
return {"store": "supabase", "menu_items": count}
_store: MemoryStore | SupabaseStore | None = None
def get_store():
global _store
if _store is None:
_store = SupabaseStore() if config.supabase_configured() else MemoryStore()
return _store
|