diff --git a/app/api/routes/meals.py b/app/api/routes/meals.py index dd7ad35..c76118a 100644 --- a/app/api/routes/meals.py +++ b/app/api/routes/meals.py @@ -6,7 +6,7 @@ import logging from typing import List, Optional # Import from the database module -from app.database import get_db, Food, Meal, MealFood, convert_grams_to_quantity +from app.database import get_db, Food, Meal, MealFood from main import templates router = APIRouter() @@ -47,7 +47,7 @@ async def bulk_upload_meals(file: UploadFile = File(...), db: Session = Depends( food_name = row[i].strip() grams = float(row[i+1].strip()) - quantity = convert_grams_to_quantity(food.id, grams, db) + quantity = grams # Try multiple matching strategies for food names food = None @@ -183,8 +183,7 @@ async def add_food_to_meal(meal_id: int, food_id: int = Form(...), grams: float = Form(..., alias="quantity"), db: Session = Depends(get_db)): try: - quantity = convert_grams_to_quantity(food_id, grams, db) - meal_food = MealFood(meal_id=meal_id, food_id=food_id, quantity=quantity) + meal_food = MealFood(meal_id=meal_id, food_id=food_id, quantity=grams) db.add(meal_food) db.commit() return {"status": "success"} @@ -218,8 +217,7 @@ async def update_meal_food_quantity(meal_food_id: int = Form(...), grams: float if not meal_food: return {"status": "error", "message": "Meal food not found"} - quantity = convert_grams_to_quantity(meal_food.food_id, grams, db) - meal_food.quantity = quantity + meal_food.quantity = grams db.commit() return {"status": "success"} except ValueError as ve: diff --git a/app/database.py b/app/database.py index c2eedb1..f67d276 100644 --- a/app/database.py +++ b/app/database.py @@ -6,6 +6,7 @@ from sqlalchemy import or_ from sqlalchemy.orm import sessionmaker, Session, relationship, declarative_base from sqlalchemy.orm import joinedload from pydantic import BaseModel, ConfigDict + from typing import List, Optional from datetime import date, datetime import os @@ -309,42 +310,10 @@ def get_db(): db.close() # Utility functions -def convert_grams_to_quantity(food_id: int, grams: float, db: Session) -> float: - """ - Converts a given gram value to the quantity multiplier based on the food's serving size. - - Args: - food_id: The ID of the food item. - grams: The desired weight in grams. - db: The database session. - - Returns: - The quantity multiplier. - - Raises: - ValueError: If the food is not found or its serving size is invalid. - """ - food = db.query(Food).filter(Food.id == food_id).first() - if not food: - raise ValueError(f"Food with ID {food_id} not found.") - - try: - # Assuming serving_size is stored in grams for simplicity as per the plan - # If serving_size can be other units, more complex conversion is needed. - serving_size_value = float(food.serving_size) - except ValueError: - raise ValueError(f"Invalid serving_size '{food.serving_size}' for food ID {food_id}. Expected a numeric value.") - - if serving_size_value == 0: - raise ValueError(f"Serving size for food ID {food_id} cannot be zero.") - - return grams / serving_size_value - def calculate_meal_nutrition(meal, db: Session): """ Calculate total nutrition for a meal. - Quantities in MealFood are now multipliers based on the Food's serving_size, - where serving_size is assumed to be in grams. + Quantities in MealFood are now directly in grams. """ totals = { 'calories': 0, 'protein': 0, 'carbs': 0, 'fat': 0, @@ -353,16 +322,27 @@ def calculate_meal_nutrition(meal, db: Session): for meal_food in meal.meal_foods: food = meal_food.food - quantity = meal_food.quantity + grams = meal_food.quantity # quantity is now grams - totals['calories'] += food.calories * quantity - totals['protein'] += food.protein * quantity - totals['carbs'] += food.carbs * quantity - totals['fat'] += food.fat * quantity - totals['fiber'] += (food.fiber or 0) * quantity - totals['sugar'] += (food.sugar or 0) * quantity - totals['sodium'] += (food.sodium or 0) * quantity - totals['calcium'] += (food.calcium or 0) * quantity + # Convert grams to a multiplier of serving size for nutrition calculation + try: + serving_size_value = float(food.serving_size) + except ValueError: + serving_size_value = 1 # Fallback if serving_size is not a number + + if serving_size_value == 0: + multiplier = 0 # Avoid division by zero + else: + multiplier = grams / serving_size_value + + totals['calories'] += food.calories * multiplier + totals['protein'] += food.protein * multiplier + totals['carbs'] += food.carbs * multiplier + totals['fat'] += food.fat * multiplier + totals['fiber'] += (food.fiber or 0) * multiplier + totals['sugar'] += (food.sugar or 0) * multiplier + totals['sodium'] += (food.sodium or 0) * multiplier + totals['calcium'] += (food.calcium or 0) * multiplier # Calculate percentages total_cals = totals['calories'] diff --git a/foodplanner.nomad.hcl b/foodplanner.nomad.hcl index 0bbbdf8..8f15b81 100644 --- a/foodplanner.nomad.hcl +++ b/foodplanner.nomad.hcl @@ -32,11 +32,12 @@ job "foodplanner" { sidecar = false } config { - image = "litestream/litestream:latest" + # image = "litestream/litestream:latest" + image = "litestream/litestream:0.3" args = [ "restore", - "-if-replica-exists", - "-if-db-not-exists", + # "-if-replica-exists", + #"-if-db-not-exists", "-o", "/alloc/tmp/meal_planner.db", "sftp://root:odroid@192.168.4.63/mnt/Shares/litestream/foodplanner.db" ] @@ -85,7 +86,8 @@ job "foodplanner" { sidecar = true } config { - image = "litestream/litestream:latest" + # image = "litestream/litestream:0.5.0-test.10" + image = "litestream/litestream:0.3" args = [ "replicate", "/alloc/tmp/meal_planner.db", diff --git a/templates/meals.html b/templates/meals.html index 65f49e1..217200f 100644 --- a/templates/meals.html +++ b/templates/meals.html @@ -26,7 +26,7 @@ {% if meal.meal_foods %} {% else %} @@ -122,8 +122,8 @@ async function loadCurrentMealFoods(mealId) { container.innerHTML = foods.map(mf => `
- - ${mf.food_name} + + ${mf.food_name} (g)