75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from models.meal import Meal
|
|
|
|
def get_available_meals(db: Session, category: Optional[str] = None) -> List[Meal]:
|
|
"""
|
|
Retrieve a list of available meals from the database.
|
|
|
|
Args:
|
|
db (Session): SQLAlchemy database session.
|
|
category (str, optional): Filter meals by category. Defaults to None.
|
|
|
|
Returns:
|
|
List[Meal]: List of available meal objects.
|
|
"""
|
|
query = db.query(Meal).filter(Meal.is_available == True)
|
|
if category:
|
|
query = query.filter(Meal.category == category)
|
|
return query.all()
|
|
|
|
def validate_meal_data(meal_data: dict) -> dict:
|
|
"""
|
|
Validate meal data dictionary for required fields and data types.
|
|
|
|
Args:
|
|
meal_data (dict): Dictionary containing meal data.
|
|
|
|
Returns:
|
|
dict: Validated meal data dictionary.
|
|
|
|
Raises:
|
|
ValueError: If required fields are missing or data types are incorrect.
|
|
"""
|
|
required_fields = ['name', 'price']
|
|
for field in required_fields:
|
|
if field not in meal_data:
|
|
raise ValueError(f"Missing required field: {field}")
|
|
|
|
if not isinstance(meal_data['name'], str):
|
|
raise ValueError("Name must be a string")
|
|
|
|
if not isinstance(meal_data['price'], float):
|
|
raise ValueError("Price must be a float")
|
|
|
|
return meal_data
|
|
|
|
def format_meal_price(price: float) -> str:
|
|
"""
|
|
Format a meal price as a string with two decimal places.
|
|
|
|
Args:
|
|
price (float): The meal price.
|
|
|
|
Returns:
|
|
str: Formatted price string.
|
|
"""
|
|
return f"{price:.2f}"
|
|
|
|
def filter_meals_by_price_range(meals: List[Meal], min_price: Optional[float] = None, max_price: Optional[float] = None) -> List[Meal]:
|
|
"""
|
|
Filter a list of meals by a specified price range.
|
|
|
|
Args:
|
|
meals (List[Meal]): List of meal objects.
|
|
min_price (float, optional): Minimum price for filtering. Defaults to None.
|
|
max_price (float, optional): Maximum price for filtering. Defaults to None.
|
|
|
|
Returns:
|
|
List[Meal]: Filtered list of meal objects.
|
|
"""
|
|
filtered_meals = []
|
|
for meal in meals:
|
|
if (min_price is None or meal.price >= min_price) and (max_price is None or meal.price <= max_price):
|
|
filtered_meals.append(meal)
|
|
return filtered_meals |