64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
from typing import List, Dict, Optional
|
|
from pydantic import BaseModel, validator
|
|
|
|
class FoodItem(BaseModel):
|
|
name: str
|
|
description: Optional[str] = None
|
|
price: float
|
|
category: str
|
|
is_vegetarian: bool = False
|
|
is_vegan: bool = False
|
|
|
|
@validator('name')
|
|
def name_must_not_be_blank(cls, value):
|
|
if not value.strip():
|
|
raise ValueError('Food item name cannot be blank')
|
|
return value
|
|
|
|
@validator('price')
|
|
def price_must_be_positive(cls, value):
|
|
if value <= 0:
|
|
raise ValueError('Price must be a positive value')
|
|
return value
|
|
|
|
class Menu(BaseModel):
|
|
items: List[FoodItem]
|
|
|
|
@validator('items')
|
|
def items_must_not_be_empty(cls, value):
|
|
if not value:
|
|
raise ValueError('Menu must contain at least one food item')
|
|
return value
|
|
|
|
def validate_food_item(food_item: FoodItem) -> Dict[str, str]:
|
|
errors = {}
|
|
if not food_item.name.strip():
|
|
errors['name'] = 'Food item name cannot be blank'
|
|
if food_item.price <= 0:
|
|
errors['price'] = 'Price must be a positive value'
|
|
return errors
|
|
|
|
def validate_menu(menu: Menu) -> Dict[str, str]:
|
|
errors = {}
|
|
if not menu.items:
|
|
errors['items'] = 'Menu must contain at least one food item'
|
|
for item in menu.items:
|
|
item_errors = validate_food_item(item)
|
|
if item_errors:
|
|
errors[item.name] = item_errors
|
|
return errors
|
|
|
|
def create_menu_categories(menu: Menu) -> Dict[str, List[FoodItem]]:
|
|
categories = {}
|
|
for item in menu.items:
|
|
category = item.category
|
|
if category not in categories:
|
|
categories[category] = []
|
|
categories[category].append(item)
|
|
return categories
|
|
|
|
def get_vegetarian_menu(menu: Menu) -> List[FoodItem]:
|
|
return [item for item in menu.items if item.is_vegetarian]
|
|
|
|
def get_vegan_menu(menu: Menu) -> List[FoodItem]:
|
|
return [item for item in menu.items if item.is_vegan] |