Files
Django_TasksApp/main/food/services/diary.py
T
2026-10-19 16:51:53 +02:00

114 lines
5.4 KiB
Python

from datetime import timedelta
from decimal import Decimal, ROUND_HALF_UP
from django.utils import timezone
from django.utils.dateparse import parse_date
from food.models import FoodLogEntry, MealType
from food.services.nutrient_help import nutrient_guidance
from planner.models import UserSettings
from planner.timezones import localdate_for_user
ZERO = Decimal('0')
def ring_progress(amount, goal):
"""Presentation values for a two-lap ring; totals and goals stay untouched.
After two laps, the inner arc shows progress in the current lap. The
accompanying text states how many full laps have already been completed.
"""
progress = max(ZERO, amount * 100 / goal)
whole_laps = int(progress // 100)
current_lap = progress % 100
if progress and current_lap == 0:
current_lap = Decimal('100')
return {
'percent': int(progress.quantize(Decimal('1'), rounding=ROUND_HALF_UP)),
'base_lap': format(min(progress, Decimal('100')), '.2f'),
'extra_lap': format(current_lap if progress > 100 else ZERO, '.2f'),
'full_laps': whole_laps,
'current_lap': current_lap,
}
NUTRIENT_NAMES = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
NUTRIENT_LABELS = {'calories_kcal': 'calories', 'carbohydrates_g': 'carbs',
'protein_g': 'protein', 'fat_g': 'fat', 'fibre_g': 'fibre',
'sugars_g': 'sugars', 'salt_g': 'salt'}
def nutrition_breakdown(entries):
"""Known subtotals and completeness, based only on saved diary snapshots."""
totals = {name: ZERO for name in NUTRIENT_NAMES}
known_counts = {name: 0 for name in NUTRIENT_NAMES}
incomplete = {name: False for name in NUTRIENT_NAMES}
missing_entries = []
for entry in entries:
run = getattr(entry, 'recipe_cooking_run', None)
snapshot = run.nutrition_snapshot if run else None
missing = []
for name in NUTRIENT_NAMES:
value = entry.effective_nutrient(name)
if value is not None:
totals[name] += value
known_counts[name] += 1
if value is None or (snapshot is not None and not snapshot.get(name, {}).get('complete', False)):
incomplete[name] = True
missing.append(NUTRIENT_LABELS[name])
entry.nutrition_incomplete = bool(missing)
if missing:
missing_entries.append({'entry': entry, 'nutrients': ', '.join(missing)})
return totals, known_counts, incomplete, missing_entries
def selected_date(request):
value = request.GET.get('date') or request.POST.get('date')
if not value:
return localdate_for_user(request.user)
day = parse_date(value)
if day is None or day.isoformat() != value:
raise ValueError('Enter a valid date in YYYY-MM-DD format.')
return day
def diary_context(user, day, language='en'):
goals, _ = UserSettings.objects.get_or_create(user=user)
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product', 'recipe_cooking_run')
.prefetch_related('attachments').defer('product__raw_data'))
totals, known_counts, incomplete, missing_entries = nutrition_breakdown(entries)
for entry in entries:
entry.effective_calories = entry.effective_nutrient('calories_kcal')
meals = []
for key, label in MealType.choices:
items = [entry for entry in entries if entry.meal == key]
meals.append({'key': key, 'label': label, 'entries': items,
'calories': sum((entry.effective_calories or ZERO for entry in items), ZERO)})
macros = []
for label, name, goal, color in (
('Protein', 'protein_g', goals.protein_goal_g, 'blue'),
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
('Fat', 'fat_g', goals.fat_goal_g, 'orange'),
('Fibre', 'fibre_g', goals.fibre_goal_g, 'green'),
):
eaten = totals[name]
is_incomplete = incomplete[name]
ring = ring_progress(eaten, goal) if goal and (known_counts[name] or not entries) else None
macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language),
'eaten': eaten if known_counts[name] or not entries else None, 'goal': goal,
'remaining': goal - eaten if goal is not None and not is_incomplete else None,
'percent': ring['percent'] if ring else None,
'base_lap': ring['base_lap'] if ring else ZERO,
'extra_lap': ring['extra_lap'] if ring else ZERO,
'full_laps': ring['full_laps'] if ring else 0,
'current_lap': ring['current_lap'] if ring else ZERO,
'color': color, 'incomplete': is_incomplete})
calorie_goal = goals.daily_calorie_goal
calories = totals['calories_kcal']
return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1),
'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language,
'known_counts': known_counts, 'nutrition_incomplete': incomplete,
'missing_entries': missing_entries,
'calorie_goal': calorie_goal,
'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None and not incomplete['calories_kcal'] else None,
'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0}