Spaces:
Sleeping

File size: 7,194 Bytes
a812c01
 
 
 
 
 
 
a6db9fd
a812c01
a6db9fd
a812c01
 
 
 
 
a6db9fd
a812c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6db9fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a812c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6db9fd
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
"""Menu tools called by the Bolna agent (get_menu, get_dish_details).

Tool endpoints always return 200 with {success: bool, ...} β€” the agent's
scripted retry/fallback lines depend on never seeing a transport error.
"""

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 get_store

router = APIRouter(prefix="/api/menu", tags=["menu"])

MAX_ITEMS = 12

# Single source of truth mapping the agent's category vocabulary β†’ filters.
# A filter is (field, value) checked against each menu row.
CATEGORY_ALIASES: dict[str, dict] = {
    "all": {},
    # veg/non-veg mean food in the agent's vocabulary β€” beers excluded
    "veg": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]},
    "vegetarian": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]},
    "non-veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]},
    "nonveg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]},
    "non veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]},
    "starters": {"category": "starters"},
    "appetizers": {"category": "starters"},
    "mains": {"category": "mains"},
    "main course": {"category": "mains"},
    "sides": {"category": "sides"},
    "desserts": {"category": "desserts"},
    "dessert": {"category": "desserts"},
    "mocktails": {"category": "mocktails"},
    "mocktail": {"category": "mocktails"},
    "drinks": {"category": ["mocktails", "craft-beer", "beverages"]},
    "beverages": {"category": ["mocktails", "craft-beer", "beverages"]},
    "craft-beer": {"category": "craft-beer"},
    "craft beer": {"category": "craft-beer"},
    "beer": {"category": "craft-beer"},
    "beers": {"category": "craft-beer"},
    "food": {"category": ["starters", "mains", "sides", "desserts"]},
}


def _matches(item: dict, filters: dict) -> bool:
    for field, expected in filters.items():
        actual = item.get(field)
        if isinstance(expected, list):
            if actual not in expected:
                return False
        elif actual != expected:
            return False
    return True


def _at_outlet(item: dict, outlet: str | None) -> bool:
    if not outlet:
        return True
    outlets = [o.lower() for o in (item.get("outlet_location") or [])]
    # Unknown outlet name β†’ don't filter (better to show menu than nothing).
    return outlet.lower() in outlets if outlets else True


def _compact(item: dict) -> dict:
    out = {
        "name": item["name"],
        "price": item["price"],
        "category": item["category"],
        "is_veg": item.get("is_veg"),
        "description": (item.get("description") or "")[:140],
        "rating": item.get("rating"),
        "tags": item.get("tags") or [],
    }
    if item.get("abv"):
        out["abv"] = item["abv"]
        out["style"] = item.get("style")
    return out


@router.get("/full")
async def get_menu_full(outlet_location: str = Query(default="")):
    """All menu items grouped by category β€” no cap, full fields. Used by the visual menu browser."""
    try:
        menu = get_store().get_menu()
        outlet = sanitize.clean(outlet_location)
        rows = [m for m in menu if _at_outlet(m, outlet)]
        grouped: dict[str, list] = {}
        for item in rows:
            cat = item.get("category", "other")
            grouped.setdefault(cat, []).append(item)
        # Sort each category by rating desc
        for cat in grouped:
            grouped[cat].sort(key=lambda m: (m.get("rating") or 0), reverse=True)
        return {"success": True, "grouped": grouped, "total": len(rows)}
    except Exception as exc:
        return {"success": False, "message": f"Menu temporarily unavailable: {exc}"}


class AvailabilityBody(BaseModel):
    name: str
    is_available: bool


@router.patch("/availability")
async def set_menu_availability(
    body: AvailabilityBody,
    admin_key: str = Query(default=""),
):
    if config.ADMIN_KEY and admin_key != config.ADMIN_KEY:
        return {"success": False, "message": "Invalid admin key."}
    updated = get_store().update_menu_availability(body.name, body.is_available)
    if not updated:
        return {"success": False, "message": f"No item named '{body.name}' found."}
    return {
        "success": True,
        "message": f"'{body.name}' is now {'available' if body.is_available else 'unavailable'}.",
    }


@router.get("", dependencies=[Depends(require_token)])
async def get_menu(
    category: str = Query(default="all"),
    outlet_location: str = Query(default=""),
):
    try:
        menu = get_store().get_menu()
        key = (sanitize.clean(category) or "all").lower()
        filters = CATEGORY_ALIASES.get(key)
        if filters is None:
            # Unknown category from the LLM β€” fuzzy-fall back to everything
            # rather than failing the tool call.
            filters = {}

        outlet = sanitize.clean(outlet_location)
        rows = [m for m in menu if _matches(m, filters) and _at_outlet(m, outlet)]
        rows.sort(key=lambda m: (m.get("rating") or 0), reverse=True)
        items = [_compact(m) for m in rows[:MAX_ITEMS]]

        if not items:
            return {
                "success": True,
                "items": [],
                "message": f"No items found for category '{category}'. Try another category.",
            }
        return {"success": True, "category": key, "count": len(items), "items": items}
    except Exception as exc:  # never 500 a tool call
        return {"success": False, "message": f"Menu temporarily unavailable: {exc}"}


@router.get("/dish", dependencies=[Depends(require_token)])
async def get_dish_details(dish_name: str = Query(default="")):
    try:
        name = sanitize.clean(dish_name)
        if not name:
            return {"success": False, "found": False, "message": "No dish name provided."}

        menu = get_store().get_menu()
        item, confidence = find_dish(name, menu)
        if item is None:
            return {
                "success": True,
                "found": False,
                "message": f"No close match for '{dish_name}' on the menu.",
            }
        return {
            "success": True,
            "found": True,
            "confidence": confidence,
            "dish": {
                "name": item["name"],
                "price": item["price"],
                "currency": "INR",
                "category": item["category"],
                "is_veg": item.get("is_veg"),
                "description": item.get("description"),
                "rating": item.get("rating"),
                "spice_level": item.get("spice_level"),
                "abv": item.get("abv"),
                "style": item.get("style"),
                "allergens": item.get("allergens") or [],
                "tags": item.get("tags") or [],
                "available_at": item.get("outlet_location") or [],
            },
        }
    except Exception as exc:
        return {"success": False, "message": f"Dish lookup failed: {exc}"}