diff --git a/main/food/api.py b/main/food/api.py index fc3db0f..c754df4 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -24,6 +24,7 @@ from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, Food InventoryCategory, InventoryLocation, KitchenInventoryItem, MealType, PersonalAccessToken, Unit) from .services.logging import apply_product_snapshot +from .services.diary import nutrition_breakdown from .services.hydration import sync_food_hydration, validate_rules from planner.services.hydration import daily_hydration from .services.openfoodfacts import OpenFoodFactsError @@ -250,20 +251,20 @@ def today(request): if day is None or day.isoformat() != requested_date: return error('invalid_date', 'Use a date in YYYY-MM-DD format.') entries = list(FoodLogEntry.objects.filter(user=request.api_user, date=day) - .select_related('product').prefetch_related('attachments')) + .select_related('product', 'recipe_cooking_run').prefetch_related('attachments')) meals = {meal: [_entry_data(e) for e in entries if e.meal == meal] for meal in MealType.values} - totals = {name: str(sum((getattr(e, name) or Decimal('0') for e in entries), Decimal('0'))) - for name in NUTRIENTS if name != 'fibre_g'} - fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None] - fibre_incomplete = len(fibre_values) != len(entries) - totals['fibre_g'] = str(sum(fibre_values, Decimal('0'))) if fibre_values or not entries else None + known_totals, known_counts, incomplete, _ = nutrition_breakdown(entries) + totals = {name: str(known_totals[name].quantize(Decimal('0.001'))) if known_counts[name] or not entries else None + for name in NUTRIENTS} + fibre_incomplete = incomplete['fibre_g'] goals = UserSettings.objects.filter(user=request.api_user).first() goal_data = {name: str(getattr(goals, name)) if goals and getattr(goals, name) is not None else None for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g', 'fibre_goal_g')} if goals is None: goal_data['fibre_goal_g'] = '40.0' return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, - 'fibre_incomplete': fibre_incomplete, 'goals': goal_data}) + 'incomplete': incomplete, 'fibre_incomplete': fibre_incomplete, + 'goals': goal_data}) @api_view(None, ('GET',)) diff --git a/main/food/services/diary.py b/main/food/services/diary.py index 4fcf502..8b96f7e 100644 --- a/main/food/services/diary.py +++ b/main/food/services/diary.py @@ -11,6 +11,34 @@ from planner.timezones import localdate_for_user ZERO = Decimal('0') +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): @@ -27,20 +55,9 @@ 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') - run = getattr(entry, 'recipe_cooking_run', None) - entry.nutrition_incomplete = bool(run and any( - not row.get('complete', False) for row in run.nutrition_snapshot.values())) - names = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') - totals = {name: sum((entry.effective_nutrient(name) or ZERO for entry in entries), ZERO) - if all(getattr(entry, name) is not None for entry in entries) else None for name in names} - fibre_incomplete = totals['fibre_g'] is None or any( - (getattr(entry, 'recipe_cooking_run', None) and - not entry.recipe_cooking_run.nutrition_snapshot.get('fibre_g', {}).get('complete', False)) - for entry in entries) - if fibre_incomplete: - totals['fibre_g'] = sum((entry.effective_nutrient('fibre_g') or ZERO for entry in entries), ZERO) if any(entry.fibre_g is not None for entry in entries) else None meals = [] for key, label in MealType.choices: items = [entry for entry in entries if entry.meal == key] @@ -54,16 +71,18 @@ def diary_context(user, day, language='en'): ('Fibre', 'fibre_g', goals.fibre_goal_g, 'green'), ): eaten = totals[name] - incomplete = name == 'fibre_g' and fibre_incomplete + is_incomplete = incomplete[name] macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language), - 'eaten': eaten, 'goal': goal, - 'remaining': goal - eaten if goal is not None and eaten is not None and not incomplete else None, - 'percent': min(100, int(eaten * 100 / goal)) if goal and eaten is not None else None, - 'color': color, 'incomplete': incomplete}) + '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': min(100, int(eaten * 100 / goal)) if goal and (known_counts[name] or not entries) else None, + '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 calories is not None else None, - 'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal and calories is not None else 0} + '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} diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index b807977..eac4c9b 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -24,6 +24,8 @@ body[data-theme="dark"]{--food-surface:#202923;--food-border:#3b473f;--food-ink: .food-export-actions a{color:var(--food-ink);border-color:var(--food-border)} .food-export-actions a:hover,.food-export-actions a:focus-visible{background:var(--food-progress-track)} .food-macro p,.food-product-list small{color:var(--food-muted)} +.food-warning-mark{display:inline-grid;place-items:center;width:1.25em;height:1.25em;border-radius:50%;background:#a15a12;color:#fff;font-size:.85em;font-weight:800;vertical-align:middle} +.food-incomplete-warning{border-color:#b98b45}.food-incomplete-warning h2{font-size:1.1rem}.food-incomplete-warning p{line-height:1.45}.food-incomplete-warning details{margin-top:.65rem}.food-incomplete-warning summary{cursor:pointer;font-weight:700}.food-incomplete-warning ul{padding-left:1.25rem;margin:.6rem 0 0}.food-incomplete-warning li{margin:.4rem 0;overflow-wrap:anywhere}.food-partial-note{line-height:1.4} body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} /* Four goals fit the existing nutrition sidebar in a compact two-column grid. */ @@ -47,6 +49,7 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} /* Nutrient guidance sits above the card content and stays within the viewport. */ .food-macro{position:relative;padding-top:2.8rem} +@media(max-width:460px){.food-macros{grid-template-columns:1fr}.food-macro{flex-direction:row;align-items:center;text-align:left;gap:1rem;padding:.85rem 3rem .85rem .85rem}.food-macro h3{font-size:1rem;white-space:normal}.food-macro p{font-size:.88rem;line-height:1.35}.food-ring{flex:none}} .food-help-trigger{position:absolute;top:.25rem;right:.25rem;display:grid;place-items:center;width:44px;height:44px;padding:0;border:0;background:transparent;color:var(--food-ink);cursor:pointer} .food-help-trigger span{display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--food-muted);border-radius:50%;font:700 .85rem/1 inherit} .food-help-trigger:hover span,.food-help-trigger[aria-expanded="true"] span{background:var(--food-progress-track)} diff --git a/main/food/templates/food/diary.html b/main/food/templates/food/diary.html index 1b88ae4..bb701f4 100644 --- a/main/food/templates/food/diary.html +++ b/main/food/templates/food/diary.html @@ -2,7 +2,7 @@ {% load static %} {% block title %}Food · Tasknest{% endblock %} {% block content %} - + {% include 'food/partials/diary_content.html' %} diff --git a/main/food/templates/food/partials/nutrition_summary.html b/main/food/templates/food/partials/nutrition_summary.html index ae50206..c7529bf 100644 --- a/main/food/templates/food/partials/nutrition_summary.html +++ b/main/food/templates/food/partials/nutrition_summary.html @@ -1,14 +1,41 @@
-

Calories

{% if calorie_goal is not None and totals.calories_kcal is not None %}

{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}

{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal

{% else %}

{% if totals.calories_kcal is None %}Calories unknown{% else %}{{ totals.calories_kcal|floatformat:0 }} kcal eaten{% endif %}

No calorie goal. Set one in Settings.

{% endif %}
-
{% for macro in macros %}
- -
-

{{ macro.label }}

{% if macro.eaten is None %}Unknown{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}

{% if macro.incomplete %}

Some entries unknown

{% elif macro.goal is not None %}

{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}

{% else %}

No target

{% endif %}
- -
{% endfor %}
+
+

Calories

+ {% if nutrition_incomplete.calories_kcal %} +

{% if known_counts.calories_kcal %}At least {{ totals.calories_kcal|floatformat:0 }} kcal eaten{% else %}Known calories unavailable{% endif %}

+ {% else %} +

{{ totals.calories_kcal|floatformat:0 }} kcal eaten

+ {% endif %} + {% if calorie_goal is not None %} +

Goal: {{ calorie_goal }} kcal

+ {% if nutrition_incomplete.calories_kcal %}

Remaining amount unknown until missing calories are added.

+ {% else %}

{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}

{% endif %} + {% if known_counts.calories_kcal or not missing_entries %}
{% endif %} + {% else %}

No calorie goal. Set one in Settings.

{% endif %} +
+ {% if missing_entries %} +
+

Nutrition incomplete

+

Some foods have missing nutrition. The totals above and below show only known values and may be incomplete.

+
{{ missing_entries|length }} food entr{{ missing_entries|length|pluralize:'y,ies' }} to review + +
+
+ {% endif %} +
+ {% for macro in macros %}
+ +
+

{{ macro.label }}

+

{% if macro.eaten is None %}Known amount unavailable{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}

+ {% if macro.incomplete %}

{% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}

{% elif macro.goal is not None %}

{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}

{% else %}

No target

{% endif %} +
+ +
{% endfor %} +
diff --git a/main/food/test_api.py b/main/food/test_api.py index e5bf6dd..6db4f2f 100644 --- a/main/food/test_api.py +++ b/main/food/test_api.py @@ -39,6 +39,20 @@ class FoodApiTests(TestCase): data = json.dumps(data) return getattr(self.client, method)(path, data=data, **args) + def test_today_reports_quantity_scaled_known_subtotals_and_missing_fields(self): + day = timezone.localdate() + FoodLogEntry.objects.create(user=self.a, date=day, meal='lunch', + product_name_snapshot='Known lunch', amount=Decimal('100'), quantity=Decimal('2'), + unit='g', calories_kcal=Decimal('120'), protein_g=Decimal('5')) + FoodLogEntry.objects.create(user=self.a, date=day, meal='dinner', + product_name_snapshot='Unknown dinner', amount=Decimal('100'), unit='g') + result = self.call('get', '/api/v1/food/today/').json() + self.assertEqual(Decimal(result['totals']['calories_kcal']), Decimal('240')) + self.assertEqual(Decimal(result['totals']['protein_g']), Decimal('10')) + self.assertTrue(result['incomplete']['calories_kcal']) + self.assertTrue(result['incomplete']['protein_g']) + self.assertIsNone(result['totals']['fat_g']) + def test_atomic_food_log_and_inventory_keeps_historical_snapshot(self): old = FoodLogEntry.objects.create(user=self.a, product=self.product_a, date=timezone.localdate() - timedelta(days=1), meal='dinner', diff --git a/main/food/tests.py b/main/food/tests.py index bce5d90..27da799 100644 --- a/main/food/tests.py +++ b/main/food/tests.py @@ -172,6 +172,50 @@ class FoodFoundationTests(TestCase): self.assertContains(response, 'date=2026-10-02') self.assertContains(response, 'date=2026-10-04') + def test_goals_and_partial_nutrition_across_recent_dates(self): + UserSettings.objects.create(user=self.user, daily_calorie_goal=2050, + protein_goal_g=Decimal('132'), carbohydrate_goal_g=Decimal('250'), + fat_goal_g=Decimal('48'), fibre_goal_g=Decimal('40')) + complete = {'calories_kcal': Decimal('300'), 'protein_g': Decimal('20'), + 'carbohydrates_g': Decimal('30'), 'fat_g': Decimal('10'), + 'fibre_g': Decimal('5'), 'sugars_g': Decimal('4'), 'salt_g': Decimal('1')} + for day in (15, 16, 17): + FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, day), + meal=MealType.LUNCH, product_name_snapshot='Known lunch', + amount=Decimal('100'), unit='g', **complete) + unknown = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 16), + meal=MealType.DINNER, product_name_snapshot='Unknown meatballs', + amount=Decimal('160'), unit='g') + FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 17), + meal=MealType.DINNER, product_name_snapshot='Partial dinner', + amount=Decimal('100'), unit='g', protein_g=Decimal('8'), fibre_g=Decimal('2')) + before = list(FoodLogEntry.objects.filter(user=self.user).values_list('pk', 'calories_kcal')) + self.client.force_login(self.user) + for day in (15, 16, 17): + selected = date(2026, 10, day) + context = diary_context(self.user, selected) + self.assertEqual(context['calorie_goal'], 2050) + self.assertEqual(context['totals']['calories_kcal'], Decimal('300')) + self.assertEqual(context['totals']['protein_g'], Decimal('20') if day != 17 else Decimal('28')) + self.assertEqual(context['nutrition_incomplete']['calories_kcal'], day != 15) + self.assertEqual(context['calorie_remaining'], Decimal('1750') if day == 15 else None) + response = self.client.get(reverse('food:diary'), {'date': selected.isoformat()}) + self.assertContains(response, 'Goal: 2050 kcal') + self.assertNotContains(response, 'No calorie goal') + self.assertContains(response, '132.0 g goal') + self.assertContains(response, '250.0 g goal') + self.assertContains(response, '48.0 g goal') + if day == 15: + self.assertContains(response, '1750 kcal remaining') + self.assertNotContains(response, 'Nutrition incomplete') + else: + self.assertContains(response, 'At least 300 kcal eaten') + self.assertContains(response, 'Nutrition incomplete') + self.assertContains(response, 'food entry to review') + self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-16'}), + f'href="#food-entry-{unknown.pk}"') + self.assertEqual(before, list(FoodLogEntry.objects.filter(user=self.user).values_list('pk', 'calories_kcal'))) + def test_bad_date_and_user_isolation(self): FoodLogEntry.objects.create(user=self.other, date=date(2026, 10, 3), meal=MealType.LUNCH, product_name_snapshot='Private food', amount=Decimal('100'), unit=Unit.GRAM, diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index ad9d05f..9406d49 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -344,9 +344,10 @@ def create_server() -> MCPServer: 'protein_g': 'protein_goal_g', 'fat_g': 'fat_goal_g', 'fibre_g': 'fibre_goal_g'} remaining = {name: str(Decimal(goals[goal]) - Decimal(data['totals'][name])) for name, goal in mapping.items() if goals.get(goal) is not None and - data['totals'][name] is not None and not (name == 'fibre_g' and data.get('fibre_incomplete'))} + data['totals'][name] is not None and not data.get('incomplete', {}).get(name, False)} return {'date': data['date'], 'meals': entries, 'totals': data['totals'], 'goals': goals, - 'remaining': remaining, 'fibre_incomplete': data.get('fibre_incomplete', False)} + 'remaining': remaining, 'incomplete': data.get('incomplete', {}), + 'fibre_incomplete': data.get('fibre_incomplete', False)} @server.tool(structured_output=True, description='Search the authenticated user’s saved TaskNest food products before logging a known food. Returns serving sizes, portions, and nutrition per 100 g/ml. Does not change data.') async def food_search_products(query: str, limit: int = 20) -> dict[str, Any]: