Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,7 @@ backend/data
__pycache__
.env

# Frontend
# Frontend

# VSCode Settings
.vscode
36 changes: 35 additions & 1 deletion backend/app/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from backend.app.schemas.restaurant import Restaurant
from backend.app.schemas.restaurant_query import RestaurantQuery
from backend.app.services.restaurant_service import RestaurantService
from backend.app.schemas.menu_item import MenuItem
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate

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

@app.post("/restaurants/{restaurant_id}/menu-items", response_model=MenuItem, status_code=201)
def create_menu_item(restaurant_id: str, request: MenuItemCreate):
restaurant_service = get_restaurant_service()

try:
return restaurant_service.add_menu_item(restaurant_id=restaurant_id, request=request)

except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))

@app.patch("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", response_model=MenuItem)
def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpdate):
restaurant_service = get_restaurant_service()

try:
return restaurant_service.update_menu_item(restaurant_id=restaurant_id, menu_item_id=menu_item_id, request=request)

except ValueError as e:
raise HTTPException(status_code=404,detail=str(e))


@app.delete("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", status_code=204)
def delete_menu_item(restaurant_id: str, menu_item_id: str):
restaurant_service = get_restaurant_service()

try:
restaurant_service.delete_menu_item(restaurant_id=restaurant_id, menu_item_id=menu_item_id)

return None

except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))

@app.get("/restaurants/{restaurant_id}", response_model=Restaurant)
def get_restaurant(restaurant_id: str):
Expand All @@ -41,4 +75,4 @@ def get_restaurant(restaurant_id: str):
raise HTTPException(status_code=404, detail="Restaurant not found")
return restaurant
except JSONDecodeError:
raise HTTPException(status_code=500, detail="Invalid JSON data")
raise HTTPException(status_code=500, detail="Invalid JSON data")
32 changes: 30 additions & 2 deletions backend/app/repositories/restaurant_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
from pydantic import TypeAdapter, ValidationError
import warnings
from backend.app.schemas.restaurant import Restaurant
import os
import tempfile

restaurants_list_adapter = TypeAdapter(list[Restaurant])

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

def __load_restaurants(self) -> list[Restaurant]:
def __load_restaurants(self) -> list[Restaurant]:
if not self.restaurants_file_path.exists():
warnings.warn(f"'{self.restaurants_file_path.absolute()}' does not exist. Defaulting to empty restaurants list.")
return []
Expand All @@ -24,13 +26,39 @@ def __load_restaurants(self) -> list[Restaurant]:
except ValidationError as e:
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

def __save_restaurants(self, restaurants: list[Restaurant]) -> None:
temp_file_path = None

try:
with tempfile.NamedTemporaryFile(mode = "w",
encoding = "utf-8",
dir = self.restaurants_file_path.parent, #creates temporary file in the same directory as the original JSON
delete = False, # so python won't delete this file when the while bloack is exited
suffix = ".tmp") as temp_file:
temp_file_path = temp_file.name

json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], temp_file, indent=4)

os.replace(temp_file_path, self.restaurants_file_path)

except OSError as e:
if temp_file_path is not None:
try:
os.remove(temp_file_path) # removes failed temp files so that they don't accumulate
except FileNotFoundError:
pass

raise OSError(f"Failed to save restaurants to '{self.restaurants_file_path.absolute()}'") from e

def get_all_restaurants(self) -> list[Restaurant]:
return self.__load_restaurants()

def save_restaurants(self, restaurants: list[Restaurant]) -> None:
self.__save_restaurants(restaurants)
def get_restaurant_by_id(self, restaurant_id: str) -> Restaurant | None:
restaurants = self.get_all_restaurants()

for restaurant in restaurants:
if restaurant.id == restaurant_id:
return restaurant
return None
return None
26 changes: 26 additions & 0 deletions backend/app/schemas/menu_item_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from pydantic import BaseModel, ConfigDict, model_validator, Field
from .offer import Offer
from .restricted_diet import RestrictedDiet

class MenuItemCreate(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

name: str = Field(min_length=1)
description: str = ""
suitableForDiet: RestrictedDiet | list[RestrictedDiet]
offers: Offer | list[Offer]


class MenuItemUpdate(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)

name: str | None = Field(None, min_length=1)
description: str | None = None
suitableForDiet: RestrictedDiet | list[RestrictedDiet] | None = None
offers: Offer | list[Offer] | None = None

@model_validator(mode="after")
def check_at_least_one_field(self):
if all(value is None for value in self.model_dump().values()):
raise ValueError("At least one field must be provided")
return self
2 changes: 1 addition & 1 deletion backend/app/schemas/menu_section.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ class MenuSection(BaseModel):
name: str
description: str = ""
hasMenuSection: MenuSection | list[MenuSection] | None = None
hasMenuItem: MenuItem | list[MenuItem]
hasMenuItem: MenuItem | list[MenuItem] | None = None
2 changes: 1 addition & 1 deletion backend/app/schemas/offer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@

class Offer(BaseModel):
type: str = Field("Offer", frozen=True)
price: Decimal
price: Decimal = Field(ge=0)
priceCurrency: str
availability: ItemAvailability
124 changes: 123 additions & 1 deletion backend/app/services/restaurant_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from backend.app.repositories.restaurant_repository import RestaurantRepository
from backend.app.schemas.restaurant import Restaurant
from backend.app.schemas.menu_section import MenuSection
from backend.app.schemas.menu_item import MenuItem
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
from backend.app.schemas.menu import Menu

UNCATEGORIZED_MENU_SECTION_ID = "uncategorized"
UNCATEGORIZED_MENU_SECTION_NAME = "Uncategorized"

class RestaurantService:
def __init__(self, repository: RestaurantRepository):
Expand Down Expand Up @@ -32,4 +38,120 @@ def get_sort_value(r):
return restaurantsList

def get_restaurant_by_id(self, restaurant_id: str):
return self.repository.get_restaurant_by_id(restaurant_id)
return self.repository.get_restaurant_by_id(restaurant_id)

def _find_restaurant(self, restaurants: list[Restaurant], restaurant_id: str) -> Restaurant:
for restaurant in restaurants:
if restaurant.id == restaurant_id:
return restaurant
raise ValueError(f"Restaurant with id '{restaurant_id}' is not found")

def _find_menu_section(self, menu_sections: MenuSection | list[MenuSection], menu_section_id: str) -> MenuSection:
section_list = (menu_sections if isinstance(menu_sections, list) else [menu_sections])

for menu_section in section_list:
if menu_section.id == menu_section_id:
return menu_section

if menu_section.hasMenuSection is not None:
try:
return self._find_menu_section(menu_section.hasMenuSection, menu_section_id)

except ValueError:
pass

raise ValueError(f"MenuSection with id '{menu_section_id}' is not found")

def add_menu_item(self, restaurant_id: str, request: MenuItemCreate) -> MenuItem:
restaurants = self.repository.get_all_restaurants()
restaurant = self._find_restaurant(restaurants, restaurant_id)

menu_section = self._get_or_create_uncategorized_section(restaurant)
new_menu_item = MenuItem(**request.model_dump())

if menu_section.hasMenuItem is None:
menu_section.hasMenuItem = [new_menu_item]
elif isinstance(menu_section.hasMenuItem, list):
menu_section.hasMenuItem.append(new_menu_item)
else:
menu_section.hasMenuItem = [menu_section.hasMenuItem, new_menu_item]

self.repository.save_restaurants(restaurants)

return new_menu_item

def update_menu_item(self, restaurant_id: str, menu_item_id: str, request: MenuItemUpdate) -> MenuItem:
restaurants = self.repository.get_all_restaurants()
restaurant = self._find_restaurant(restaurants, restaurant_id)

if restaurant.hasMenu is None:
raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")

_, menu_item = self._find_menu_item(restaurant.hasMenu.hasMenuSection, menu_item_id)

update_data = request.model_dump(exclude_unset=True)

for field, value in update_data.items():
setattr(menu_item, field, value)

self.repository.save_restaurants(restaurants)
return menu_item


def delete_menu_item(self, restaurant_id: str, menu_item_id: str) -> None:
restaurants = self.repository.get_all_restaurants()
restaurant = self._find_restaurant(restaurants, restaurant_id)

if restaurant.hasMenu is None:
raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")

menu_section, menu_item = self._find_menu_item(restaurant.hasMenu.hasMenuSection, menu_item_id)
menu_items = (menu_section.hasMenuItem if isinstance(menu_section.hasMenuItem, list) else [menu_section.hasMenuItem])
menu_items.remove(menu_item)
menu_section.hasMenuItem = menu_items

self.repository.save_restaurants(restaurants)

def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSection:

if restaurant.hasMenu is None:
uncategorized_section = MenuSection(id=UNCATEGORIZED_MENU_SECTION_ID, name=UNCATEGORIZED_MENU_SECTION_NAME, description="", hasMenuItem=[])

restaurant.hasMenu = Menu(hasMenuSection=[uncategorized_section])

return uncategorized_section

menu_sections = (restaurant.hasMenu.hasMenuSection if isinstance(restaurant.hasMenu.hasMenuSection, list) else [restaurant.hasMenu.hasMenuSection])

for section in menu_sections:
if section.id == UNCATEGORIZED_MENU_SECTION_ID:
return section

uncategorized_section = MenuSection(id=UNCATEGORIZED_MENU_SECTION_ID, name=UNCATEGORIZED_MENU_SECTION_NAME, description="", hasMenuItem=[])

menu_sections.append(uncategorized_section)
restaurant.hasMenu.hasMenuSection = menu_sections

return uncategorized_section


def _find_menu_item(self, menu_sections: MenuSection | list[MenuSection], menu_item_id: str) -> tuple[MenuSection, MenuItem]:

section_list = (menu_sections if isinstance(menu_sections, list) else [menu_sections])

for section in section_list:
if section.hasMenuItem is not None:
menu_items = (section.hasMenuItem if isinstance(section.hasMenuItem, list) else [section.hasMenuItem])

for item in menu_items:
if item.id == menu_item_id:
return section, item

if section.hasMenuSection is not None:
try:
return self._find_menu_item(section.hasMenuSection, menu_item_id)
except ValueError:
pass

raise ValueError(f"MenuItem with id '{menu_item_id}' is not found")

Loading
Loading