foodapp-380mbh/helpers/food_helpers.py
2025-03-28 14:45:41 +00:00

123 lines
3.2 KiB
Python

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_menu_items(db: Session, active_only: bool = True) -> List[Food]:
"""
Get list of food items in the menu.
Args:
db: Database session
active_only: If True, returns only active menu items
Returns:
List of Food objects from the menu
"""
query = db.query(Food)
if active_only:
query = query.filter(Food.is_active == True)
return query.all()
def filter_menu_by_category(
db: Session,
category: str,
active_only: bool = True
) -> List[Food]:
"""
Filter menu items by category.
Args:
db: Database session
category: Food category to filter by
active_only: If True, returns only active menu items
Returns:
List of Food objects filtered by category
"""
query = db.query(Food).filter(Food.category == category)
if active_only:
query = query.filter(Food.is_active == True)
return query.all()
def search_menu_items(
db: Session,
search_term: str,
active_only: bool = True
) -> List[Food]:
"""
Search menu items by name or description.
Args:
db: Database session
search_term: Term to search for in name/description
active_only: If True, returns only active menu items
Returns:
List of matching Food objects
"""
search = f"%{search_term}%"
query = db.query(Food).filter(
or_(
Food.name.ilike(search),
Food.description.ilike(search)
)
)
if active_only:
query = query.filter(Food.is_active == True)
return query.all()
def get_food_by_price_range(
db: Session,
min_price: float,
max_price: float,
active_only: bool = True
) -> List[Food]:
"""
Get menu items within a price range.
Args:
db: Database session
min_price: Minimum price
max_price: Maximum price
active_only: If True, returns only active menu items
Returns:
List of Food objects within price range
"""
query = db.query(Food).filter(
and_(
Food.price >= min_price,
Food.price <= max_price
)
)
if active_only:
query = query.filter(Food.is_active == True)
return query.order_by(Food.price.asc()).all()
def format_menu_response(foods: List[Food]) -> List[Dict[str, Any]]:
"""
Format menu items for API response.
Args:
foods: List of Food objects
Returns:
List of formatted food dictionaries
"""
return [
{
"id": food.id,
"name": food.name,
"description": food.description,
"price": float(food.price),
"category": food.category,
"is_available": food.is_active,
"image_url": food.image_url,
"allergens": food.allergens,
"nutritional_info": food.nutritional_info
}
for food in foods
]