Skip to content

Commit 869a91e

Browse files
authored
Merge pull request #39 from OpenDash-Team/feature/menu-item-create-update
Add menu item create, update and delete endpoints with JSON saving Adds save_restaurants with safe temp-file writes, and POST/PATCH/DELETE for menu items under /restaurants/{id}/menu-items. Items go into an "Uncategorized" section, which is created along with the menu if the restaurant doesn't have one yet. Closes #27 Closes #34 Closes #35
2 parents 02ff906 + 474f4ea commit 869a91e

10 files changed

Lines changed: 532 additions & 8 deletions

File tree

‎.gitignore‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,7 @@ backend/data
44
__pycache__
55
.env
66

7-
# Frontend
7+
# Frontend
8+
9+
# VSCode Settings
10+
.vscode

‎backend/app/api/routes.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from backend.app.schemas.restaurant import Restaurant
66
from backend.app.schemas.restaurant_query import RestaurantQuery
77
from backend.app.services.restaurant_service import RestaurantService
8+
from backend.app.schemas.menu_item import MenuItem
9+
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
810

911
def create_routes(app: FastAPI):
1012
@app.get("/health")
@@ -30,6 +32,38 @@ def list_restaurants(params: RestaurantQuery = Depends()):
3032
raise HTTPException(status_code=400, detail=str(e))
3133
raise HTTPException(status_code=500, detail="Restaurant data failed to follow correct list[Restaurant] schema")
3234

35+
@app.post("/restaurants/{restaurant_id}/menu-items", response_model=MenuItem, status_code=201)
36+
def create_menu_item(restaurant_id: str, request: MenuItemCreate):
37+
restaurant_service = get_restaurant_service()
38+
39+
try:
40+
return restaurant_service.add_menu_item(restaurant_id=restaurant_id, request=request)
41+
42+
except ValueError as e:
43+
raise HTTPException(status_code=404, detail=str(e))
44+
45+
@app.patch("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", response_model=MenuItem)
46+
def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpdate):
47+
restaurant_service = get_restaurant_service()
48+
49+
try:
50+
return restaurant_service.update_menu_item(restaurant_id=restaurant_id, menu_item_id=menu_item_id, request=request)
51+
52+
except ValueError as e:
53+
raise HTTPException(status_code=404,detail=str(e))
54+
55+
56+
@app.delete("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", status_code=204)
57+
def delete_menu_item(restaurant_id: str, menu_item_id: str):
58+
restaurant_service = get_restaurant_service()
59+
60+
try:
61+
restaurant_service.delete_menu_item(restaurant_id=restaurant_id, menu_item_id=menu_item_id)
62+
63+
return None
64+
65+
except ValueError as e:
66+
raise HTTPException(status_code=404, detail=str(e))
3367

3468
@app.get("/restaurants/{restaurant_id}", response_model=Restaurant)
3569
def get_restaurant(restaurant_id: str):
@@ -41,4 +75,4 @@ def get_restaurant(restaurant_id: str):
4175
raise HTTPException(status_code=404, detail="Restaurant not found")
4276
return restaurant
4377
except JSONDecodeError:
44-
raise HTTPException(status_code=500, detail="Invalid JSON data")
78+
raise HTTPException(status_code=500, detail="Invalid JSON data")

‎backend/app/repositories/restaurant_repository.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@
44
from pydantic import TypeAdapter, ValidationError
55
import warnings
66
from backend.app.schemas.restaurant import Restaurant
7+
import os
8+
import tempfile
79

810
restaurants_list_adapter = TypeAdapter(list[Restaurant])
911

1012
class RestaurantRepository:
1113
def __init__(self, restaurants_file_path: Path) -> None:
1214
self.restaurants_file_path: Path = restaurants_file_path
1315

14-
def __load_restaurants(self) -> list[Restaurant]:
16+
def __load_restaurants(self) -> list[Restaurant]:
1517
if not self.restaurants_file_path.exists():
1618
warnings.warn(f"'{self.restaurants_file_path.absolute()}' does not exist. Defaulting to empty restaurants list.")
1719
return []
@@ -24,13 +26,39 @@ def __load_restaurants(self) -> list[Restaurant]:
2426
except ValidationError as e:
2527
raise ValueError(f"{self.restaurants_file_path.absolute()} does not follow the correct list[Restaurant] schema. See backend/app/schemas/restaurant.py or visit https://www.schema.org/Restaurant for schema specifications.") from e
2628

29+
def __save_restaurants(self, restaurants: list[Restaurant]) -> None:
30+
temp_file_path = None
31+
32+
try:
33+
with tempfile.NamedTemporaryFile(mode = "w",
34+
encoding = "utf-8",
35+
dir = self.restaurants_file_path.parent, #creates temporary file in the same directory as the original JSON
36+
delete = False, # so python won't delete this file when the while bloack is exited
37+
suffix = ".tmp") as temp_file:
38+
temp_file_path = temp_file.name
39+
40+
json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], temp_file, indent=4)
41+
42+
os.replace(temp_file_path, self.restaurants_file_path)
43+
44+
except OSError as e:
45+
if temp_file_path is not None:
46+
try:
47+
os.remove(temp_file_path) # removes failed temp files so that they don't accumulate
48+
except FileNotFoundError:
49+
pass
50+
51+
raise OSError(f"Failed to save restaurants to '{self.restaurants_file_path.absolute()}'") from e
52+
2753
def get_all_restaurants(self) -> list[Restaurant]:
2854
return self.__load_restaurants()
2955

56+
def save_restaurants(self, restaurants: list[Restaurant]) -> None:
57+
self.__save_restaurants(restaurants)
3058
def get_restaurant_by_id(self, restaurant_id: str) -> Restaurant | None:
3159
restaurants = self.get_all_restaurants()
3260

3361
for restaurant in restaurants:
3462
if restaurant.id == restaurant_id:
3563
return restaurant
36-
return None
64+
return None
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from pydantic import BaseModel, ConfigDict, model_validator, Field
2+
from .offer import Offer
3+
from .restricted_diet import RestrictedDiet
4+
5+
class MenuItemCreate(BaseModel):
6+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
7+
8+
name: str = Field(min_length=1)
9+
description: str = ""
10+
suitableForDiet: RestrictedDiet | list[RestrictedDiet]
11+
offers: Offer | list[Offer]
12+
13+
14+
class MenuItemUpdate(BaseModel):
15+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
16+
17+
name: str | None = Field(None, min_length=1)
18+
description: str | None = None
19+
suitableForDiet: RestrictedDiet | list[RestrictedDiet] | None = None
20+
offers: Offer | list[Offer] | None = None
21+
22+
@model_validator(mode="after")
23+
def check_at_least_one_field(self):
24+
if all(value is None for value in self.model_dump().values()):
25+
raise ValueError("At least one field must be provided")
26+
return self

‎backend/app/schemas/menu_section.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ class MenuSection(BaseModel):
1212
name: str
1313
description: str = ""
1414
hasMenuSection: MenuSection | list[MenuSection] | None = None
15-
hasMenuItem: MenuItem | list[MenuItem]
15+
hasMenuItem: MenuItem | list[MenuItem] | None = None

‎backend/app/schemas/offer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@
66

77
class Offer(BaseModel):
88
type: str = Field("Offer", frozen=True)
9-
price: Decimal
9+
price: Decimal = Field(ge=0)
1010
priceCurrency: str
1111
availability: ItemAvailability

‎backend/app/services/restaurant_service.py‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
from backend.app.repositories.restaurant_repository import RestaurantRepository
22
from backend.app.schemas.restaurant import Restaurant
3+
from backend.app.schemas.menu_section import MenuSection
4+
from backend.app.schemas.menu_item import MenuItem
5+
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
6+
from backend.app.schemas.menu import Menu
37

8+
UNCATEGORIZED_MENU_SECTION_ID = "uncategorized"
9+
UNCATEGORIZED_MENU_SECTION_NAME = "Uncategorized"
410

511
class RestaurantService:
612
def __init__(self, repository: RestaurantRepository):
@@ -32,4 +38,120 @@ def get_sort_value(r):
3238
return restaurantsList
3339

3440
def get_restaurant_by_id(self, restaurant_id: str):
35-
return self.repository.get_restaurant_by_id(restaurant_id)
41+
return self.repository.get_restaurant_by_id(restaurant_id)
42+
43+
def _find_restaurant(self, restaurants: list[Restaurant], restaurant_id: str) -> Restaurant:
44+
for restaurant in restaurants:
45+
if restaurant.id == restaurant_id:
46+
return restaurant
47+
raise ValueError(f"Restaurant with id '{restaurant_id}' is not found")
48+
49+
def _find_menu_section(self, menu_sections: MenuSection | list[MenuSection], menu_section_id: str) -> MenuSection:
50+
section_list = (menu_sections if isinstance(menu_sections, list) else [menu_sections])
51+
52+
for menu_section in section_list:
53+
if menu_section.id == menu_section_id:
54+
return menu_section
55+
56+
if menu_section.hasMenuSection is not None:
57+
try:
58+
return self._find_menu_section(menu_section.hasMenuSection, menu_section_id)
59+
60+
except ValueError:
61+
pass
62+
63+
raise ValueError(f"MenuSection with id '{menu_section_id}' is not found")
64+
65+
def add_menu_item(self, restaurant_id: str, request: MenuItemCreate) -> MenuItem:
66+
restaurants = self.repository.get_all_restaurants()
67+
restaurant = self._find_restaurant(restaurants, restaurant_id)
68+
69+
menu_section = self._get_or_create_uncategorized_section(restaurant)
70+
new_menu_item = MenuItem(**request.model_dump())
71+
72+
if menu_section.hasMenuItem is None:
73+
menu_section.hasMenuItem = [new_menu_item]
74+
elif isinstance(menu_section.hasMenuItem, list):
75+
menu_section.hasMenuItem.append(new_menu_item)
76+
else:
77+
menu_section.hasMenuItem = [menu_section.hasMenuItem, new_menu_item]
78+
79+
self.repository.save_restaurants(restaurants)
80+
81+
return new_menu_item
82+
83+
def update_menu_item(self, restaurant_id: str, menu_item_id: str, request: MenuItemUpdate) -> MenuItem:
84+
restaurants = self.repository.get_all_restaurants()
85+
restaurant = self._find_restaurant(restaurants, restaurant_id)
86+
87+
if restaurant.hasMenu is None:
88+
raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")
89+
90+
_, menu_item = self._find_menu_item(restaurant.hasMenu.hasMenuSection, menu_item_id)
91+
92+
update_data = request.model_dump(exclude_unset=True)
93+
94+
for field, value in update_data.items():
95+
setattr(menu_item, field, value)
96+
97+
self.repository.save_restaurants(restaurants)
98+
return menu_item
99+
100+
101+
def delete_menu_item(self, restaurant_id: str, menu_item_id: str) -> None:
102+
restaurants = self.repository.get_all_restaurants()
103+
restaurant = self._find_restaurant(restaurants, restaurant_id)
104+
105+
if restaurant.hasMenu is None:
106+
raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")
107+
108+
menu_section, menu_item = self._find_menu_item(restaurant.hasMenu.hasMenuSection, menu_item_id)
109+
menu_items = (menu_section.hasMenuItem if isinstance(menu_section.hasMenuItem, list) else [menu_section.hasMenuItem])
110+
menu_items.remove(menu_item)
111+
menu_section.hasMenuItem = menu_items
112+
113+
self.repository.save_restaurants(restaurants)
114+
115+
def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSection:
116+
117+
if restaurant.hasMenu is None:
118+
uncategorized_section = MenuSection(id=UNCATEGORIZED_MENU_SECTION_ID, name=UNCATEGORIZED_MENU_SECTION_NAME, description="", hasMenuItem=[])
119+
120+
restaurant.hasMenu = Menu(hasMenuSection=[uncategorized_section])
121+
122+
return uncategorized_section
123+
124+
menu_sections = (restaurant.hasMenu.hasMenuSection if isinstance(restaurant.hasMenu.hasMenuSection, list) else [restaurant.hasMenu.hasMenuSection])
125+
126+
for section in menu_sections:
127+
if section.id == UNCATEGORIZED_MENU_SECTION_ID:
128+
return section
129+
130+
uncategorized_section = MenuSection(id=UNCATEGORIZED_MENU_SECTION_ID, name=UNCATEGORIZED_MENU_SECTION_NAME, description="", hasMenuItem=[])
131+
132+
menu_sections.append(uncategorized_section)
133+
restaurant.hasMenu.hasMenuSection = menu_sections
134+
135+
return uncategorized_section
136+
137+
138+
def _find_menu_item(self, menu_sections: MenuSection | list[MenuSection], menu_item_id: str) -> tuple[MenuSection, MenuItem]:
139+
140+
section_list = (menu_sections if isinstance(menu_sections, list) else [menu_sections])
141+
142+
for section in section_list:
143+
if section.hasMenuItem is not None:
144+
menu_items = (section.hasMenuItem if isinstance(section.hasMenuItem, list) else [section.hasMenuItem])
145+
146+
for item in menu_items:
147+
if item.id == menu_item_id:
148+
return section, item
149+
150+
if section.hasMenuSection is not None:
151+
try:
152+
return self._find_menu_item(section.hasMenuSection, menu_item_id)
153+
except ValueError:
154+
pass
155+
156+
raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")
157+

0 commit comments

Comments
 (0)