From 7c6d478782366203ec82b969a989716981626c39 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:24:55 -0700 Subject: [PATCH 01/14] Add menu item create and update request models --- backend/app/schemas/menu_item_request.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 backend/app/schemas/menu_item_request.py diff --git a/backend/app/schemas/menu_item_request.py b/backend/app/schemas/menu_item_request.py new file mode 100644 index 0000000..eb8cbad --- /dev/null +++ b/backend/app/schemas/menu_item_request.py @@ -0,0 +1,18 @@ +from pydantic import BaseModel + +from .offer import Offer +from .restricted_diet import RestrictedDiet + +class MenuItemCreate(BaseModel): + name: str + description: str = "" + suitableForDiet: RestrictedDiet | list[RestrictedDiet] + offers: Offer | list[Offer] + + +class MenuItemUpdate(BaseModel): + name: str | None = None + description: str | None = None + suitableForDiet: RestrictedDiet | list[RestrictedDiet] | None = None + offers: Offer | list[Offer] | None = None + From 632c97bed0323ea37a557600401ca35443db821f Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:29:46 -0700 Subject: [PATCH 02/14] added gitignore for VSCode setting files --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 014a82e..98f504d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,7 @@ backend/data __pycache__ .env -# Frontend \ No newline at end of file +# Frontend + +# VSCode Settings +.vscode \ No newline at end of file From 2a482074e28ecae2af9f82e16ad118eabbf18097 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:57:51 -0700 Subject: [PATCH 03/14] Implement restuaurant JSON saving --- .../app/repositories/restaurant_repository.py | 11 ++++++++-- backend/tests/test_restaurants_repository.py | 22 ++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/backend/app/repositories/restaurant_repository.py b/backend/app/repositories/restaurant_repository.py index 4178d4e..1097f35 100644 --- a/backend/app/repositories/restaurant_repository.py +++ b/backend/app/repositories/restaurant_repository.py @@ -11,7 +11,7 @@ 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 [] @@ -24,5 +24,12 @@ 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: + with open(self.restaurants_file_path, "w", encoding="utf-8") as restaurants_file: + json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], restaurants_file, indent = 4) + def get_all_restaurants(self) -> list[Restaurant]: - return self.__load_restaurants() \ No newline at end of file + return self.__load_restaurants() + + def save_restaurants(self, restaurants: list[Restaurant]) -> None: + self.__save_restaurants(restaurants) \ No newline at end of file diff --git a/backend/tests/test_restaurants_repository.py b/backend/tests/test_restaurants_repository.py index 4fab0d7..1c78a12 100644 --- a/backend/tests/test_restaurants_repository.py +++ b/backend/tests/test_restaurants_repository.py @@ -62,4 +62,24 @@ def test_repository_loads_real_data(): assert len(results) >= 2 assert results[0].name is not None - assert results[0].id is not None \ No newline at end of file + assert results[0].id is not None + + +def test_repository_saves_restaurants(tmp_path): + from backend.tests.conftest import REAL_DATA + + source_repo = RestaurantRepository(REAL_DATA / "restaurants.json") + restaurants = source_repo.get_all_restaurants() + + output_file = tmp_path / "restaurants.json" + output_repo = RestaurantRepository(output_file) + + output_repo.save_restaurants(restaurants) + + assert output_file.exists() + + reloaded = output_repo.get_all_restaurants() + + assert len(reloaded) == len(restaurants) + assert reloaded[0].id == restaurants[0].id + assert reloaded[0].name == restaurants[0].name \ No newline at end of file From 0a3aabe44f2f924d7dccd7d526509c5b4e30b28a Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:00 -0700 Subject: [PATCH 04/14] added exception handling for restaurant saving --- backend/app/repositories/restaurant_repository.py | 7 +++++-- backend/tests/test_restaurants_repository.py | 10 +++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/backend/app/repositories/restaurant_repository.py b/backend/app/repositories/restaurant_repository.py index 1097f35..b7a4a3a 100644 --- a/backend/app/repositories/restaurant_repository.py +++ b/backend/app/repositories/restaurant_repository.py @@ -25,8 +25,11 @@ def __load_restaurants(self) -> list[Restaurant]: 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: - with open(self.restaurants_file_path, "w", encoding="utf-8") as restaurants_file: - json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], restaurants_file, indent = 4) + try: + with open(self.restaurants_file_path, "w", encoding="utf-8") as restaurants_file: + json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], restaurants_file, indent = 4) + except OSError as e: + 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() diff --git a/backend/tests/test_restaurants_repository.py b/backend/tests/test_restaurants_repository.py index 1c78a12..9ea4a87 100644 --- a/backend/tests/test_restaurants_repository.py +++ b/backend/tests/test_restaurants_repository.py @@ -82,4 +82,12 @@ def test_repository_saves_restaurants(tmp_path): assert len(reloaded) == len(restaurants) assert reloaded[0].id == restaurants[0].id - assert reloaded[0].name == restaurants[0].name \ No newline at end of file + assert reloaded[0].name == restaurants[0].name + + +@patch("builtins.open", side_effect=PermissionError("Permission denied")) +def test_repository_handles_save_error(mock_file, tmp_path): + repo = RestaurantRepository(tmp_path / "restaurants.json") + + with pytest.raises(OSError, match="Failed to save restaurants"): + repo.save_restaurants([]) \ No newline at end of file From 652d30177bd3e9aa6b395f157efec432365b06ac Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:42:25 -0700 Subject: [PATCH 05/14] implement menu item creation service --- backend/app/schemas/menu_section.py | 2 +- backend/app/services/restaurant_service.py | 47 +++++++++++++++++++++- backend/tests/test_restaurant_service.py | 40 ++++++++++++++++++ 3 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 backend/tests/test_restaurant_service.py diff --git a/backend/app/schemas/menu_section.py b/backend/app/schemas/menu_section.py index 4d46feb..f032f83 100644 --- a/backend/app/schemas/menu_section.py +++ b/backend/app/schemas/menu_section.py @@ -12,4 +12,4 @@ class MenuSection(BaseModel): name: str description: str = "" hasMenuSection: MenuSection | list[MenuSection] | None = None - hasMenuItem: MenuItem | list[MenuItem] \ No newline at end of file + hasMenuItem: MenuItem | list[MenuItem] | None = None \ No newline at end of file diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index 365f27a..c46929f 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -1,4 +1,8 @@ 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 class RestaurantService: @@ -6,4 +10,45 @@ def __init__(self, repository: RestaurantRepository): self.repository: RestaurantRepository = repository def list_restaurants(self): - return self.repository.get_all_restaurants() \ No newline at end of file + return self.repository.get_all_restaurants() + + 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: + for menu_section in menu_sections: + 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, menu_section_id: str, request: MenuItemCreate) -> MenuItem: + restaurants = self.repository.get_all_restaurants() + + restaurant = self._find_restaurant(restaurants, restaurant_id) + + menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) + + new_menu_item = MenuItem(**request.model_dump()) #** means to take all key value pairs in this diciontary and pass them as keyword arguments to the MenuItem constructor. + #otherwise it will pass the entire dictionary as one positional argument and raise a TypeError. + + if 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 \ No newline at end of file diff --git a/backend/tests/test_restaurant_service.py b/backend/tests/test_restaurant_service.py new file mode 100644 index 0000000..0b07d9e --- /dev/null +++ b/backend/tests/test_restaurant_service.py @@ -0,0 +1,40 @@ +from backend.app.repositories.restaurant_repository import RestaurantRepository +from backend.app.services.restaurant_service import RestaurantService +from backend.app.schemas.menu_item_request import MenuItemCreate +from backend.app.schemas.restricted_diet import RestrictedDiet +from backend.app.schemas.offer import Offer +from backend.app.schemas.item_availability import ItemAvailability + +def test_add_menu_item(tmp_path): + from backend.tests.conftest import REAL_DATA + + source_file = REAL_DATA / "restaurants.json" + test_file = tmp_path / "restaurants.json" + + test_file.write_text(source_file.read_text(encoding="utf-8"), encoding="utf-8") + + repository = RestaurantRepository(test_file) + service = RestaurantService(repository) + + request = MenuItemCreate(name="Test Late", description="A test menu item", suitableForDiet=RestrictedDiet.VEGETARIAN, + offers=Offer(price=4.99, priceCurrency="USD", availability=ItemAvailability.IN_STOCK)) + + new_item = service.add_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_section_id="q9th4Uh9iO6lHbCEJIVz2", request=request) + + assert new_item.id is not None + assert new_item.name == "Test Late" + assert new_item.description == "A test menu item" + + + reloaded_repository = RestaurantRepository(test_file) + restaurants = reloaded_repository.get_all_restaurants() + + restaurant = next(restaurant + for restaurant in restaurants + if restaurant.id == "NwYJoaOHusWdiqXpM7mQH") + + section = next(section + for section in restaurant.hasMenu.hasMenuSection + if section.id == "q9th4Uh9iO6lHbCEJIVz2") + + assert any(item.id == new_item.id for item in section.hasMenuItem) \ No newline at end of file From 0123a744526a4224a421e7f5ebd7ccc18c84ccb3 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:44:45 -0700 Subject: [PATCH 06/14] add temp files writes to prevent broken JSON --- .../app/repositories/restaurant_repository.py | 23 +++++++++++++++++-- backend/tests/test_restaurants_repository.py | 11 ++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/backend/app/repositories/restaurant_repository.py b/backend/app/repositories/restaurant_repository.py index b7a4a3a..03b77ed 100644 --- a/backend/app/repositories/restaurant_repository.py +++ b/backend/app/repositories/restaurant_repository.py @@ -4,6 +4,8 @@ from pydantic import TypeAdapter, ValidationError import warnings from backend.app.schemas.restaurant import Restaurant +import os +import tempfile restaurants_list_adapter = TypeAdapter(list[Restaurant]) @@ -25,10 +27,27 @@ def __load_restaurants(self) -> list[Restaurant]: 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 open(self.restaurants_file_path, "w", encoding="utf-8") as restaurants_file: - json.dump([restaurant.model_dump(mode="json") for restaurant in restaurants], restaurants_file, indent = 4) + 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]: diff --git a/backend/tests/test_restaurants_repository.py b/backend/tests/test_restaurants_repository.py index 9ea4a87..3904af3 100644 --- a/backend/tests/test_restaurants_repository.py +++ b/backend/tests/test_restaurants_repository.py @@ -85,9 +85,18 @@ def test_repository_saves_restaurants(tmp_path): assert reloaded[0].name == restaurants[0].name -@patch("builtins.open", side_effect=PermissionError("Permission denied")) +@patch("backend.app.repositories.restaurant_repository.tempfile.NamedTemporaryFile", side_effect=PermissionError("Permission denied")) def test_repository_handles_save_error(mock_file, tmp_path): repo = RestaurantRepository(tmp_path / "restaurants.json") + with pytest.raises(OSError, match="Failed to save restaurants"): + repo.save_restaurants([]) + + +@patch("backend.app.repositories.restaurant_repository.os.replace", side_effect=OSError("replace failed")) +def test_repository_handles_replace_error(mock_replace, tmp_path): + output_file = tmp_path / "restaurants.json" + repo = RestaurantRepository(output_file) + with pytest.raises(OSError, match="Failed to save restaurants"): repo.save_restaurants([]) \ No newline at end of file From 654c369fd9cc7e5a1ecd66f33168f1c9d1453edc Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:14:08 -0700 Subject: [PATCH 07/14] Fix _find_menu_section() to handle both single and list values --- backend/app/services/restaurant_service.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index c46929f..cc567f6 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -20,7 +20,10 @@ def _find_restaurant(self, restaurants: list[Restaurant], restaurant_id: str) -> def _find_menu_section(self, menu_sections: MenuSection | list[MenuSection], menu_section_id: str) -> MenuSection: - for menu_section in menu_sections: + + 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 From 82e9c9143bc99aaee1a10594efa06b0cfc56f021 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:42:56 -0700 Subject: [PATCH 08/14] implement menu item update --- backend/app/services/restaurant_service.py | 24 +++++++++++++++++++--- backend/tests/test_restaurant_service.py | 20 ++++++++++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index cc567f6..beba626 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -39,11 +39,9 @@ def _find_menu_section(self, menu_sections: MenuSection | list[MenuSection], men def add_menu_item(self, restaurant_id: str, menu_section_id: str, request: MenuItemCreate) -> MenuItem: restaurants = self.repository.get_all_restaurants() - restaurant = self._find_restaurant(restaurants, restaurant_id) menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) - new_menu_item = MenuItem(**request.model_dump()) #** means to take all key value pairs in this diciontary and pass them as keyword arguments to the MenuItem constructor. #otherwise it will pass the entire dictionary as one positional argument and raise a TypeError. @@ -54,4 +52,24 @@ def add_menu_item(self, restaurant_id: str, menu_section_id: str, request: MenuI self.repository.save_restaurants(restaurants) - return new_menu_item \ No newline at end of file + return new_menu_item + + + def update_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_id: str, request: MenuItemUpdate) -> MenuItem: + restaurants = self.repository.get_all_restaurants() + restaurant = self._find_restaurant(restaurants, restaurant_id) + menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) + menu_items = (menu_section.hasMenuItem if isinstance(menu_section.hasMenuItem, list) else [menu_section.hasMenuItem]) + + for menu_item in menu_items: + if menu_item.id == 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 + + raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") \ No newline at end of file diff --git a/backend/tests/test_restaurant_service.py b/backend/tests/test_restaurant_service.py index 0b07d9e..3620192 100644 --- a/backend/tests/test_restaurant_service.py +++ b/backend/tests/test_restaurant_service.py @@ -1,6 +1,6 @@ from backend.app.repositories.restaurant_repository import RestaurantRepository from backend.app.services.restaurant_service import RestaurantService -from backend.app.schemas.menu_item_request import MenuItemCreate +from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate from backend.app.schemas.restricted_diet import RestrictedDiet from backend.app.schemas.offer import Offer from backend.app.schemas.item_availability import ItemAvailability @@ -37,4 +37,20 @@ def test_add_menu_item(tmp_path): for section in restaurant.hasMenu.hasMenuSection if section.id == "q9th4Uh9iO6lHbCEJIVz2") - assert any(item.id == new_item.id for item in section.hasMenuItem) \ No newline at end of file + assert any(item.id == new_item.id for item in section.hasMenuItem) + + +def test_update_menu_item(tmp_path): + from backend.tests.conftest import REAL_DATA + + source_file = REAL_DATA / "restaurants.json" + test_file = tmp_path / "restaurants.json" + test_file.write_text(source_file.read_text(encoding="utf-8"), encoding="utf-8") + + repository = RestaurantRepository(test_file) + service = RestaurantService(repository) + + request = MenuItemUpdate(description="Updated description") + updated_item = service.update_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_section_id="q9th4Uh9iO6lHbCEJIVz2", menu_item_id="F5hn9s3VD9qzKsLV4z8CW", request=request) + + assert updated_item.description == "Updated description" \ No newline at end of file From 2272ab63ca79c61e4d545180a93f8c7e9fbf85ce Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 00:00:39 -0700 Subject: [PATCH 09/14] implemented deletion of menu items --- backend/app/services/restaurant_service.py | 21 ++++++++++++++++- backend/tests/test_restaurant_service.py | 27 +++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index beba626..bc56d4b 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -72,4 +72,23 @@ def update_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_i return menu_item - raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") \ No newline at end of file + raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") + + def delete_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_id: str) -> None: + restaurants = self.repository.get_all_restaurants() + restaurant = self._find_restaurant(restaurants, restaurant_id) + + menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) + menu_items = (menu_section.hasMenuItem if isinstance(menu_section.hasMenuItem, list) else [menu_section.hasMenuItem]) + + for menu_item in menu_items: + if menu_item.id == menu_item_id: + menu_items.remove(menu_item) + menu_section.hasMenuItem = menu_items + + self.repository.save_restaurants(restaurants) + return + + raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") + + diff --git a/backend/tests/test_restaurant_service.py b/backend/tests/test_restaurant_service.py index 3620192..4cab748 100644 --- a/backend/tests/test_restaurant_service.py +++ b/backend/tests/test_restaurant_service.py @@ -53,4 +53,29 @@ def test_update_menu_item(tmp_path): request = MenuItemUpdate(description="Updated description") updated_item = service.update_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_section_id="q9th4Uh9iO6lHbCEJIVz2", menu_item_id="F5hn9s3VD9qzKsLV4z8CW", request=request) - assert updated_item.description == "Updated description" \ No newline at end of file + assert updated_item.description == "Updated description" + +def test_delete_menu_item(tmp_path): + from backend.tests.conftest import REAL_DATA + + source_file = REAL_DATA / "restaurants.json" + test_file = tmp_path / "restaurants.json" + + test_file.write_text(source_file.read_text(encoding="utf-8"), encoding="utf-8") + + repository = RestaurantRepository(test_file) + service = RestaurantService(repository) + + service.delete_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", + menu_section_id="q9th4Uh9iO6lHbCEJIVz2", + menu_item_id="F5hn9s3VD9qzKsLV4z8CW") + + reloaded_repository = RestaurantRepository(test_file) + restaurants = reloaded_repository.get_all_restaurants() + + restaurant = next(restaurant for restaurant in restaurants if restaurant.id == "NwYJoaOHusWdiqXpM7mQH") + + section = next(section for section in restaurant.hasMenu.hasMenuSection if section.id == "q9th4Uh9iO6lHbCEJIVz2") + + assert all(item.id != "F5hn9s3VD9qzKsLV4z8CW" for item in section.hasMenuItem) + From f347ef98365583efd3c2c5d869fac2271a41da05 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 01:22:36 -0700 Subject: [PATCH 10/14] Add menu item management API endpoints --- backend/app/api/routes.py | 35 +++++++++ backend/tests/test_menu_item_routes.py | 101 +++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 backend/tests/test_menu_item_routes.py diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index b29be6d..8faaded 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -4,6 +4,8 @@ from backend.app.core.dependencies import get_restaurant_service from backend.app.schemas.restaurant import Restaurant 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") @@ -22,3 +24,36 @@ def list_restaurants(): except ValueError: raise HTTPException(status_code=500, detail="Restaurant data failed to follow correct list[Restaurant] schema") + + @app.post("/restaurants/{restaurant_id}/menu-sections/{menu_section_id}/items", response_model=MenuItem, status_code=201) + def create_menu_item(restaurant_id: str, menu_section_id: str, request: MenuItemCreate): + restaurant_service = get_restaurant_service() + + try: + return restaurant_service.add_menu_item(restaurant_id=restaurant_id, menu_section_id=menu_section_id, request=request) + + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) + + @app.patch("/restaurants/{restaurant_id}/menu-sections/{menu_section_id}/items/{menu_item_id}", response_model=MenuItem) + def update_menu_item(restaurant_id: str, menu_section_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_section_id=menu_section_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-sections/{menu_section_id}/items/{menu_item_id}", status_code=204) + def delete_menu_item(restaurant_id: str, menu_section_id: str, menu_item_id: str): + restaurant_service = get_restaurant_service() + + try: + restaurant_service.delete_menu_item(restaurant_id=restaurant_id, menu_section_id=menu_section_id, menu_item_id=menu_item_id) + + return None + + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) \ No newline at end of file diff --git a/backend/tests/test_menu_item_routes.py b/backend/tests/test_menu_item_routes.py new file mode 100644 index 0000000..0f88df3 --- /dev/null +++ b/backend/tests/test_menu_item_routes.py @@ -0,0 +1,101 @@ +def test_create_menu_item_endpoint(client): + response = client.post( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + json={ + "name": "Test Mocha", + "description": "Chocolate and espresso", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 4.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } + ) + + assert response.status_code == 201 + + data = response.json() + + assert data["name"] == "Test Mocha" + assert data["description"] == "Chocolate and espresso" + assert data["id"] is not None + +def test_create_menu_item_endpoint_invalid_restaurant(client): + response = client.post( + "/restaurants/not-a-real-id/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + json={ + "name": "Test Mocha", + "description": "Chocolate and espresso", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 4.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } + ) + + assert response.status_code == 404 + + data = response.json() + + assert "not found" in data["detail"].lower() + +def test_create_menu_item_endpoint_invalid_section(client): + response = client.post( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/not-a-real-section/items", + json={ + "name": "Test Mocha", + "description": "Chocolate and espresso", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 4.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } + ) + + assert response.status_code == 404 + + +def test_create_menu_item_endpoint_invalid_body(client): + response = client.post( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + json={"description": "Missing required fields"}) + + assert response.status_code == 422 + +def test_update_menu_item_endpoint(client): + response = client.patch( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW", + json={"description": "Updated through API"}) + + assert response.status_code == 200 + data = response.json() + assert data["description"] == "Updated through API" + +def test_delete_menu_item_endpoint(client): + response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW") + assert response.status_code == 204 + +def test_delete_menu_item_endpoint_invalid_item(client): + response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/not-a-real-item") + assert response.status_code == 404 + +def test_delete_menu_item_endpoint_invalid_restaurant(client): + response = client.delete("/restaurants/not-a-real-restaurant/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW") + assert response.status_code == 404 + +def test_delete_menu_item_endpoint_invalid_section(client): + response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/not-a-real-section/items/F5hn9s3VD9qzKsLV4z8CW") + assert response.status_code == 404 + + From 13a06ac1c3300f3fe86a0a94672fdd8851c9ef21 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:37:53 -0700 Subject: [PATCH 11/14] add ConfigDict and validator to request models --- backend/app/schemas/menu_item_request.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/backend/app/schemas/menu_item_request.py b/backend/app/schemas/menu_item_request.py index eb8cbad..0ce8cd3 100644 --- a/backend/app/schemas/menu_item_request.py +++ b/backend/app/schemas/menu_item_request.py @@ -1,9 +1,10 @@ -from pydantic import BaseModel - +from pydantic import BaseModel, ConfigDict, model_validator from .offer import Offer from .restricted_diet import RestrictedDiet class MenuItemCreate(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + name: str description: str = "" suitableForDiet: RestrictedDiet | list[RestrictedDiet] @@ -11,8 +12,15 @@ class MenuItemCreate(BaseModel): class MenuItemUpdate(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + name: str | None = None 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 \ No newline at end of file From 4fcf286bfa1c0c8242989947636f3e8c34da1f47 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:38:14 -0700 Subject: [PATCH 12/14] add tests for extra fields, whitespace stripping and empty PATCH --- backend/tests/test_menu_item_routes.py | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/backend/tests/test_menu_item_routes.py b/backend/tests/test_menu_item_routes.py index 0f88df3..c3f837a 100644 --- a/backend/tests/test_menu_item_routes.py +++ b/backend/tests/test_menu_item_routes.py @@ -99,3 +99,53 @@ def test_delete_menu_item_endpoint_invalid_section(client): assert response.status_code == 404 +def test_create_menu_item_rejects_extra_fields(client): + response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + json={ + "name": "Test Lemon Tea", + "description": "Test item", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 9.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + }, + "randomField": "this should not be allowed" + } + ) + + assert response.status_code == 422 + + +def test_create_menu_item_strips_whitespace(client): + response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + json={ + "name": " Test Lemon Tea ", + "description": " Lemon and Tea ", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 9.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } + ) + + assert response.status_code == 201 + + data = response.json() + + assert data["name"] == "Test Lemon Tea" + assert data["description"] == "Lemon and Tea" + + +def test_update_menu_item_rejects_empty_body(client): + response = client.patch("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW", + json={} + ) + + assert response.status_code == 422 \ No newline at end of file From 92dff36302e9a42346006953ae6c82d4b1e2831e Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:09:06 -0700 Subject: [PATCH 13/14] remove the need for a menu_section_id in the endpoint for creating a menu item --- backend/app/api/routes.py | 6 +-- backend/app/services/restaurant_service.py | 29 +++++++++++--- backend/tests/test_menu_item_routes.py | 46 +++++++++++----------- backend/tests/test_restaurant_service.py | 30 ++++++++------ 4 files changed, 68 insertions(+), 43 deletions(-) diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index 20ee2b4..a838d22 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -32,12 +32,12 @@ 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-sections/{menu_section_id}/items", response_model=MenuItem, status_code=201) - def create_menu_item(restaurant_id: str, menu_section_id: str, request: MenuItemCreate): + @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, menu_section_id=menu_section_id, request=request) + return restaurant_service.add_menu_item(restaurant_id=restaurant_id, request=request) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index edb15c5..a9dd90b 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -4,6 +4,9 @@ from backend.app.schemas.menu_item import MenuItem from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate +UNCATEGORIZED_MENU_SECTION_ID = "uncategorized" +UNCATEGORIZED_MENU_SECTION_NAME = "Uncategorized" + class RestaurantService: def __init__(self, repository: RestaurantRepository): self.repository: RestaurantRepository = repository @@ -58,14 +61,16 @@ def _find_menu_section(self, menu_sections: MenuSection | list[MenuSection], men raise ValueError(f"MenuSection with id '{menu_section_id}' is not found") - def add_menu_item(self, restaurant_id: str, menu_section_id: str, request: MenuItemCreate) -> MenuItem: + 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._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) - new_menu_item = MenuItem(**request.model_dump()) + menu_section = self._get_or_create_uncategorized_section(restaurant) + new_menu_item = MenuItem(**request.model_dump()) - if isinstance(menu_section.hasMenuItem, list): + 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] @@ -108,4 +113,18 @@ def delete_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_i self.repository.save_restaurants(restaurants) return - raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") \ No newline at end of file + raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") + + def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSection: + 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 diff --git a/backend/tests/test_menu_item_routes.py b/backend/tests/test_menu_item_routes.py index c3f837a..526f9c2 100644 --- a/backend/tests/test_menu_item_routes.py +++ b/backend/tests/test_menu_item_routes.py @@ -1,6 +1,6 @@ def test_create_menu_item_endpoint(client): response = client.post( - "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", json={ "name": "Test Mocha", "description": "Chocolate and espresso", @@ -25,7 +25,7 @@ def test_create_menu_item_endpoint(client): def test_create_menu_item_endpoint_invalid_restaurant(client): response = client.post( - "/restaurants/not-a-real-id/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + "/restaurants/not-a-real-id/menu-items", json={ "name": "Test Mocha", "description": "Chocolate and espresso", @@ -46,29 +46,29 @@ def test_create_menu_item_endpoint_invalid_restaurant(client): assert "not found" in data["detail"].lower() -def test_create_menu_item_endpoint_invalid_section(client): - response = client.post( - "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/not-a-real-section/items", - json={ - "name": "Test Mocha", - "description": "Chocolate and espresso", - "suitableForDiet": [ - "https://schema.org/VegetarianDiet" - ], - "offers": { - "price": 4.99, - "priceCurrency": "USD", - "availability": "https://schema.org/InStock" - } - } - ) - - assert response.status_code == 404 +# def test_create_menu_item_endpoint_invalid_section(client): +# response = client.post( +# "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", +# json={ +# "name": "Test Mocha", +# "description": "Chocolate and espresso", +# "suitableForDiet": [ +# "https://schema.org/VegetarianDiet" +# ], +# "offers": { +# "price": 4.99, +# "priceCurrency": "USD", +# "availability": "https://schema.org/InStock" +# } +# } +# ) + + # assert response.status_code == 422 def test_create_menu_item_endpoint_invalid_body(client): response = client.post( - "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", json={"description": "Missing required fields"}) assert response.status_code == 422 @@ -100,7 +100,7 @@ def test_delete_menu_item_endpoint_invalid_section(client): def test_create_menu_item_rejects_extra_fields(client): - response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", json={ "name": "Test Lemon Tea", "description": "Test item", @@ -120,7 +120,7 @@ def test_create_menu_item_rejects_extra_fields(client): def test_create_menu_item_strips_whitespace(client): - response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items", + response = client.post("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", json={ "name": " Test Lemon Tea ", "description": " Lemon and Tea ", diff --git a/backend/tests/test_restaurant_service.py b/backend/tests/test_restaurant_service.py index 4cab748..5d1ae33 100644 --- a/backend/tests/test_restaurant_service.py +++ b/backend/tests/test_restaurant_service.py @@ -16,29 +16,35 @@ def test_add_menu_item(tmp_path): repository = RestaurantRepository(test_file) service = RestaurantService(repository) - request = MenuItemCreate(name="Test Late", description="A test menu item", suitableForDiet=RestrictedDiet.VEGETARIAN, - offers=Offer(price=4.99, priceCurrency="USD", availability=ItemAvailability.IN_STOCK)) - - new_item = service.add_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_section_id="q9th4Uh9iO6lHbCEJIVz2", request=request) + request = MenuItemCreate( + name="Test Late", + description="A test menu item", + suitableForDiet=RestrictedDiet.VEGETARIAN, + offers=Offer( + price=4.99, + priceCurrency="USD", + availability=ItemAvailability.IN_STOCK + ) + ) + + new_item = service.add_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", request=request) assert new_item.id is not None assert new_item.name == "Test Late" assert new_item.description == "A test menu item" - reloaded_repository = RestaurantRepository(test_file) restaurants = reloaded_repository.get_all_restaurants() - restaurant = next(restaurant - for restaurant in restaurants - if restaurant.id == "NwYJoaOHusWdiqXpM7mQH") + restaurant = next(restaurant for restaurant in restaurants if restaurant.id == "NwYJoaOHusWdiqXpM7mQH") + + menu_sections = (restaurant.hasMenu.hasMenuSection if isinstance(restaurant.hasMenu.hasMenuSection, list) else [restaurant.hasMenu.hasMenuSection]) - section = next(section - for section in restaurant.hasMenu.hasMenuSection - if section.id == "q9th4Uh9iO6lHbCEJIVz2") + uncategorized_section = next(section for section in menu_sections if section.id == "uncategorized") - assert any(item.id == new_item.id for item in section.hasMenuItem) + menu_items = (uncategorized_section.hasMenuItem if isinstance(uncategorized_section.hasMenuItem, list) else [uncategorized_section.hasMenuItem]) + assert any(item.id == new_item.id for item in menu_items) def test_update_menu_item(tmp_path): from backend.tests.conftest import REAL_DATA From 474f4ea6d8cd3c5946838b58e3631a516e236b28 Mon Sep 17 00:00:00 2001 From: Fa22Orbit <142140579+Fa22Orbit@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:37:14 -0700 Subject: [PATCH 14/14] implement createing empty Menu first when hasMenu is None --- backend/app/api/routes.py | 12 ++-- backend/app/schemas/menu_item_request.py | 6 +- backend/app/schemas/offer.py | 2 +- backend/app/services/restaurant_service.py | 69 +++++++++++++++------- backend/tests/test_menu_item_routes.py | 58 ++++++++++++++---- backend/tests/test_restaurant_service.py | 6 +- 6 files changed, 108 insertions(+), 45 deletions(-) diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index a838d22..d1bd6c0 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -42,23 +42,23 @@ def create_menu_item(restaurant_id: str, request: MenuItemCreate): except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) - @app.patch("/restaurants/{restaurant_id}/menu-sections/{menu_section_id}/items/{menu_item_id}", response_model=MenuItem) - def update_menu_item(restaurant_id: str, menu_section_id: str, menu_item_id: str, request: MenuItemUpdate): + @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_section_id=menu_section_id, menu_item_id=menu_item_id, request=request) + 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-sections/{menu_section_id}/items/{menu_item_id}", status_code=204) - def delete_menu_item(restaurant_id: str, menu_section_id: str, menu_item_id: str): + @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_section_id=menu_section_id, menu_item_id=menu_item_id) + restaurant_service.delete_menu_item(restaurant_id=restaurant_id, menu_item_id=menu_item_id) return None diff --git a/backend/app/schemas/menu_item_request.py b/backend/app/schemas/menu_item_request.py index 0ce8cd3..066d1c3 100644 --- a/backend/app/schemas/menu_item_request.py +++ b/backend/app/schemas/menu_item_request.py @@ -1,11 +1,11 @@ -from pydantic import BaseModel, ConfigDict, model_validator +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 + name: str = Field(min_length=1) description: str = "" suitableForDiet: RestrictedDiet | list[RestrictedDiet] offers: Offer | list[Offer] @@ -14,7 +14,7 @@ class MenuItemCreate(BaseModel): class MenuItemUpdate(BaseModel): model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) - name: str | None = None + name: str | None = Field(None, min_length=1) description: str | None = None suitableForDiet: RestrictedDiet | list[RestrictedDiet] | None = None offers: Offer | list[Offer] | None = None diff --git a/backend/app/schemas/offer.py b/backend/app/schemas/offer.py index 2e1d278..c9b9092 100644 --- a/backend/app/schemas/offer.py +++ b/backend/app/schemas/offer.py @@ -6,6 +6,6 @@ class Offer(BaseModel): type: str = Field("Offer", frozen=True) - price: Decimal + price: Decimal = Field(ge=0) priceCurrency: str availability: ItemAvailability \ No newline at end of file diff --git a/backend/app/services/restaurant_service.py b/backend/app/services/restaurant_service.py index a9dd90b..8b58872 100644 --- a/backend/app/services/restaurant_service.py +++ b/backend/app/services/restaurant_service.py @@ -3,6 +3,7 @@ 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" @@ -79,43 +80,47 @@ def add_menu_item(self, restaurant_id: str, request: MenuItemCreate) -> MenuItem return new_menu_item - def update_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_id: str, request: MenuItemUpdate) -> MenuItem: + 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) - menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_id) - menu_items = (menu_section.hasMenuItem if isinstance(menu_section.hasMenuItem, list) else [menu_section.hasMenuItem]) - for menu_item in menu_items: - if menu_item.id == menu_item_id: - update_data = request.model_dump(exclude_unset=True) + if restaurant.hasMenu is None: + raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") - for field, value in update_data.items(): - setattr(menu_item, field, value) + _, menu_item = self._find_menu_item(restaurant.hasMenu.hasMenuSection, menu_item_id) - self.repository.save_restaurants(restaurants) + update_data = request.model_dump(exclude_unset=True) - return menu_item + for field, value in update_data.items(): + setattr(menu_item, field, value) - raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") + self.repository.save_restaurants(restaurants) + return menu_item - def delete_menu_item(self, restaurant_id: str, menu_section_id: str, menu_item_id: str) -> None: + + 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) - menu_section = self._find_menu_section(restaurant.hasMenu.hasMenuSection, menu_section_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) - for menu_item in menu_items: - if menu_item.id == menu_item_id: - menu_items.remove(menu_item) - menu_section.hasMenuItem = menu_items + def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSection: - self.repository.save_restaurants(restaurants) - return + if restaurant.hasMenu is None: + uncategorized_section = MenuSection(id=UNCATEGORIZED_MENU_SECTION_ID, name=UNCATEGORIZED_MENU_SECTION_NAME, description="", hasMenuItem=[]) - raise ValueError(f"MenuItem with id '{menu_item_id}' is not found") + restaurant.hasMenu = Menu(hasMenuSection=[uncategorized_section]) + + return uncategorized_section - def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSection: menu_sections = (restaurant.hasMenu.hasMenuSection if isinstance(restaurant.hasMenu.hasMenuSection, list) else [restaurant.hasMenu.hasMenuSection]) for section in menu_sections: @@ -128,3 +133,25 @@ def _get_or_create_uncategorized_section(self, restaurant: Restaurant) -> MenuSe 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") + diff --git a/backend/tests/test_menu_item_routes.py b/backend/tests/test_menu_item_routes.py index 526f9c2..4ed7445 100644 --- a/backend/tests/test_menu_item_routes.py +++ b/backend/tests/test_menu_item_routes.py @@ -75,7 +75,7 @@ def test_create_menu_item_endpoint_invalid_body(client): def test_update_menu_item_endpoint(client): response = client.patch( - "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW", + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items/F5hn9s3VD9qzKsLV4z8CW", json={"description": "Updated through API"}) assert response.status_code == 200 @@ -83,20 +83,20 @@ def test_update_menu_item_endpoint(client): assert data["description"] == "Updated through API" def test_delete_menu_item_endpoint(client): - response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW") + response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items/F5hn9s3VD9qzKsLV4z8CW") assert response.status_code == 204 def test_delete_menu_item_endpoint_invalid_item(client): - response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/not-a-real-item") + response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items/not-a-real-item") assert response.status_code == 404 def test_delete_menu_item_endpoint_invalid_restaurant(client): - response = client.delete("/restaurants/not-a-real-restaurant/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW") + response = client.delete("/restaurants/not-a-real-restaurant/menu-items/F5hn9s3VD9qzKsLV4z8CW") assert response.status_code == 404 -def test_delete_menu_item_endpoint_invalid_section(client): - response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/not-a-real-section/items/F5hn9s3VD9qzKsLV4z8CW") - assert response.status_code == 404 +# def test_delete_menu_item_endpoint_invalid_section(client): +# response = client.delete("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/not-a-real-section/items/F5hn9s3VD9qzKsLV4z8CW") +# assert response.status_code == 404 def test_create_menu_item_rejects_extra_fields(client): @@ -144,8 +144,46 @@ def test_create_menu_item_strips_whitespace(client): def test_update_menu_item_rejects_empty_body(client): - response = client.patch("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-sections/q9th4Uh9iO6lHbCEJIVz2/items/F5hn9s3VD9qzKsLV4z8CW", - json={} + response = client.patch("/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items/F5hn9s3VD9qzKsLV4z8CW", json={}) + + assert response.status_code == 422 + + +def test_create_menu_item_rejects_blank_name(client): + response = client.post( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", + json={ + "name": " ", + "description": "Test", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": 4.99, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } ) - assert response.status_code == 422 \ No newline at end of file + assert response.status_code == 422 + +def test_create_menu_item_rejects_negative_price(client): + response = client.post( + "/restaurants/NwYJoaOHusWdiqXpM7mQH/menu-items", + json={ + "name": "Test Item", + "description": "Test", + "suitableForDiet": [ + "https://schema.org/VegetarianDiet" + ], + "offers": { + "price": -1, + "priceCurrency": "USD", + "availability": "https://schema.org/InStock" + } + } + ) + + assert response.status_code == 422 + diff --git a/backend/tests/test_restaurant_service.py b/backend/tests/test_restaurant_service.py index 5d1ae33..b93fc59 100644 --- a/backend/tests/test_restaurant_service.py +++ b/backend/tests/test_restaurant_service.py @@ -57,7 +57,7 @@ def test_update_menu_item(tmp_path): service = RestaurantService(repository) request = MenuItemUpdate(description="Updated description") - updated_item = service.update_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_section_id="q9th4Uh9iO6lHbCEJIVz2", menu_item_id="F5hn9s3VD9qzKsLV4z8CW", request=request) + updated_item = service.update_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_item_id="F5hn9s3VD9qzKsLV4z8CW", request=request) assert updated_item.description == "Updated description" @@ -72,9 +72,7 @@ def test_delete_menu_item(tmp_path): repository = RestaurantRepository(test_file) service = RestaurantService(repository) - service.delete_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", - menu_section_id="q9th4Uh9iO6lHbCEJIVz2", - menu_item_id="F5hn9s3VD9qzKsLV4z8CW") + service.delete_menu_item(restaurant_id="NwYJoaOHusWdiqXpM7mQH", menu_item_id="F5hn9s3VD9qzKsLV4z8CW") reloaded_repository = RestaurantRepository(test_file) restaurants = reloaded_repository.get_all_restaurants()