Add helper functions for Food

This commit is contained in:
Backend IM Bot 2025-03-28 15:19:07 +00:00
parent 0d1f4b8a2f
commit 79974ffa14

114
helpers/food_helpers.py Normal file
View File

@ -0,0 +1,114 @@
from typing import List, Dict, Optional, Union, Any
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from models.food import Food
from schemas.food import FoodCreate, FoodUpdate
def get_available_menu_items(db: Session) -> List[Food]:
"""
Get all currently available food items in the menu.
Args:
db: Database session
Returns:
List of available Food objects
"""
return db.query(Food).filter(Food.is_available == True).all()
def filter_menu_by_category(db: Session, category: str) -> List[Food]:
"""
Filter menu items by food category.
Args:
db: Database session
category: Food category to filter by
Returns:
List of Food objects in the specified category
"""
return db.query(Food).filter(
and_(
Food.category == category,
Food.is_available == True
)
).all()
def search_menu_items(
db: Session,
search_term: str,
category: Optional[str] = None
) -> List[Food]:
"""
Search menu items by name or description.
Args:
db: Database session
search_term: Term to search for
category: Optional category filter
Returns:
List of matching Food objects
"""
query = db.query(Food).filter(
and_(
Food.is_available == True,
or_(
Food.name.ilike(f"%{search_term}%"),
Food.description.ilike(f"%{search_term}%")
)
)
)
if category:
query = query.filter(Food.category == category)
return query.all()
def format_menu_item(food: Food) -> Dict[str, Any]:
"""
Format a food item for API response.
Args:
food: Food object to format
Returns:
Formatted food item dictionary
"""
return {
"id": food.id,
"name": food.name,
"description": food.description,
"price": float(food.price),
"category": food.category,
"is_vegetarian": food.is_vegetarian,
"calories": food.calories,
"image_url": food.image_url
}
def validate_food_data(food_data: Union[FoodCreate, FoodUpdate]) -> Dict[str, str]:
"""
Validate food item data before creation/update.
Args:
food_data: Food data to validate
Returns:
Dictionary with error message if validation fails, empty dict if successful
"""
errors = {}
if food_data.price <= 0:
errors["price"] = "Price must be greater than 0"
if food_data.calories < 0:
errors["calories"] = "Calories cannot be negative"
if len(food_data.name) < 2:
errors["name"] = "Name must be at least 2 characters long"
if len(food_data.description) < 10:
errors["description"] = "Description must be at least 10 characters long"
return errors