From 91ce1f5b4dddcc5c9ff1a2d8c9c59157cc7df31a Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Thu, 27 Mar 2025 12:19:35 +0100 Subject: [PATCH] Add helper functions for Meal --- helpers/meal_helpers.py | 75 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 helpers/meal_helpers.py diff --git a/helpers/meal_helpers.py b/helpers/meal_helpers.py new file mode 100644 index 0000000..1e17701 --- /dev/null +++ b/helpers/meal_helpers.py @@ -0,0 +1,75 @@ +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 \ No newline at end of file