Spaces:
Sleeping
Sleeping
Download store.py from brocode12/bell-backend: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/store.py
- Command line
-
hf download hf://spaces/brocode12/bell-backend/store.py
-
curl -L -o store.py https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/store.py
11.2 kB
| """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 | |