food diary bug fix, blocking calorie count

This commit is contained in:
Joren de Graaf
2026-10-18 00:03:47 +02:00
parent e3b14d6823
commit a8418cdba7
8 changed files with 150 additions and 41 deletions
+8 -7
View File
@@ -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',))
+38 -19
View File
@@ -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}
+3
View File
@@ -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)}
+1 -1
View File
@@ -2,7 +2,7 @@
{% load static %}
{% block title %}Food · Tasknest{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261015-quantity">
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261017-nutrition">
{% include 'food/partials/diary_content.html' %}
<script defer src="{% static 'food/quantity.js' %}?v=20261015"></script>
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261015-quantity"></script>
@@ -1,14 +1,41 @@
<div id="food-nutrition-summary">
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None and totals.calories_kcal is not None %}<p class="food-remaining">{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p><div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}"><span style="width:{{ calorie_percent }}%"></span></div><p>{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal</p>{% else %}<p class="food-remaining">{% if totals.calories_kcal is None %}Calories unknown{% else %}{{ totals.calories_kcal|floatformat:0 }} kcal eaten{% endif %}</p><p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}</section>
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% 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 %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}</div>
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
</div>
</article>{% endfor %}</section>
<section class="food-card" id="food-summary" aria-labelledby="food-calories-title">
<h2 id="food-calories-title">Calories</h2>
{% if nutrition_incomplete.calories_kcal %}
<p class="food-remaining">{% if known_counts.calories_kcal %}At least {{ totals.calories_kcal|floatformat:0 }} kcal eaten{% else %}Known calories unavailable{% endif %}</p>
{% else %}
<p class="food-remaining">{{ totals.calories_kcal|floatformat:0 }} kcal eaten</p>
{% endif %}
{% if calorie_goal is not None %}
<p>Goal: {{ calorie_goal }} kcal</p>
{% if nutrition_incomplete.calories_kcal %}<p class="food-partial-note"><span class="food-warning-mark" aria-hidden="true">!</span> Remaining amount unknown until missing calories are added.</p>
{% else %}<p>{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p>{% endif %}
{% if known_counts.calories_kcal or not missing_entries %}<div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}" aria-valuetext="{% if nutrition_incomplete.calories_kcal %}At least {% endif %}{{ totals.calories_kcal|floatformat:0 }} kcal of {{ calorie_goal }} kcal{% if nutrition_incomplete.calories_kcal %}; total incomplete{% endif %}"><span style="width:{{ calorie_percent }}%"></span></div>{% endif %}
{% else %}<p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}
</section>
{% if missing_entries %}
<section class="food-card food-incomplete-warning" aria-labelledby="food-incomplete-title">
<h2 id="food-incomplete-title"><span class="food-warning-mark" aria-hidden="true">!</span> Nutrition incomplete</h2>
<p>Some foods have missing nutrition. The totals above and below show only known values and may be incomplete.</p>
<details><summary>{{ missing_entries|length }} food entr{{ missing_entries|length|pluralize:'y,ies' }} to review</summary>
<ul>{% for missing in missing_entries %}<li><a href="#food-entry-{{ missing.entry.pk }}">{{ missing.entry.product_name_snapshot }}</a>: {{ missing.nutrients }}</li>{% endfor %}</ul>
</details>
</section>
{% endif %}
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">
{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; total incomplete{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3>
<p>{% 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 %}</p>
{% if macro.incomplete %}<p><span class="food-warning-mark" aria-hidden="true">!</span> {% if macro.goal is not None %}Remaining unknown{% else %}Nutrition incomplete · No target{% endif %}</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}
</div>
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
</div>
</article>{% endfor %}
</section>
</div>
+14
View File
@@ -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',
+44
View File
@@ -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,
+3 -2
View File
@@ -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]: