From e3b14d6823360c4975a88a8cf4d1621adb40a061 Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Sat, 17 Oct 2026 12:12:41 +0200 Subject: [PATCH] food diary improvements --- main/food/api.py | 25 ++++++- main/food/forms.py | 22 ++++-- main/food/static/food/portions.js | 47 +++++++++++- .../templates/food/partials/add_content.html | 13 +++- .../food/partials/portion_fields.html | 1 + main/food/test_api.py | 27 +++++++ main/food/tests.py | 72 ++++++++++++++++++- main/food/views.py | 64 +++++++++++++++-- main/mcp_server/server.py | 7 +- 9 files changed, 258 insertions(+), 20 deletions(-) diff --git a/main/food/api.py b/main/food/api.py index 8bc6383..fc3db0f 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -523,10 +523,29 @@ def _save_entry(request, data, entry=None): @api_view('food:write', ('POST',)) def log_create(request): data = _json(request) + package_id = data.pop('inventory_package_id', None) + if package_id and not data.get('product_id'): + return error('product_required', 'Inventory logging requires a saved product ID.') + if package_id and not request.headers.get('Idempotency-Key'): + return error('idempotency_key_required', 'Inventory logging requires an Idempotency-Key.') def create(): - entry, failure = _save_entry(request, data) - return failure or JsonResponse(_entry_data(entry), status=201) - return _idempotent(request, data, create) + with transaction.atomic(): + entry, failure = _save_entry(request, data) + if failure: + return failure + result = _entry_data(entry) + if package_id: + from .services.inventory_consumption import consume + operation = consume(request.api_user, entry.product, entry.amount, entry.unit, + package_id=_uuid(package_id), source='mcp', + source_reference=str(entry.api_id), + idempotency_key=f'food-log:{entry.api_id}') + result['inventory_consumption_id'] = str(operation.pk) + return JsonResponse(result, status=201) + try: + return _idempotent(request, {**data, 'inventory_package_id': package_id}, create) + except StockError as exc: + return error('stock_error', str(exc), 409) @api_view('food:read', ('GET',)) diff --git a/main/food/forms.py b/main/food/forms.py index c8cc1f7..555847b 100644 --- a/main/food/forms.py +++ b/main/food/forms.py @@ -1,5 +1,6 @@ from django import forms from decimal import Decimal +import uuid from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem @@ -61,6 +62,9 @@ class ManualFoodForm(forms.ModelForm): class FoodLogForm(forms.ModelForm): portion = forms.ChoiceField(label='Portion', required=False) + portion_count = forms.IntegerField(label='How many portions', min_value=1, max_value=999, + required=False, initial=1) + inventory_package = forms.ChoiceField(label='Use inventory', required=False) save_portion = forms.BooleanField(required=False, label='Save custom amount as a portion') new_portion_label = forms.CharField(max_length=100, required=False, label='New portion label') make_default = forms.BooleanField(required=False, label='Use this portion by default') @@ -71,9 +75,10 @@ class FoodLogForm(forms.ModelForm): labels = {'portion_label_snapshot': 'Portion label (optional)'} widgets = {'amount': forms.NumberInput(attrs={'min': '0.001', 'step': '0.001'})} - def __init__(self, *args, product=None, **kwargs): + def __init__(self, *args, product=None, inventory_options=None, **kwargs): super().__init__(*args, **kwargs) self.product = product or getattr(self.instance, 'product', None) + self.fields['inventory_package'].choices = [('', 'Log without using inventory')] + (inventory_options or []) if self.instance.pk and self.instance.created_via == 'recipe': self.fields['unit'].choices = [('servings', 'servings')] if self.product and self.product.pk: @@ -121,18 +126,19 @@ class FoodLogForm(forms.ModelForm): if run and data.get('amount') is not None and data['amount'] > run.prepared_servings: self.add_error('amount', 'This portion exceeds the prepared servings.') selected = data.get('portion') or 'custom' + count = data.get('portion_count') or 1 if not self.product or not selected: return data if selected == 'base': - data['amount'], data['portion_label_snapshot'] = Decimal('100'), '' + data['amount'], data['portion_label_snapshot'] = Decimal('100') * count, '' elif selected == 'serving': - data['amount'], data['portion_label_snapshot'] = self.product.serving_amount, 'Serving' + data['amount'], data['portion_label_snapshot'] = self.product.serving_amount * count, f'{count} × serving' if count > 1 else 'Serving' elif selected.startswith('portion:'): portion = self.portions.get(selected.partition(':')[2]) if not portion: self.add_error('portion', 'Choose a valid portion.') else: - data['amount'], data['portion_label_snapshot'] = portion.amount, portion.label + data['amount'], data['portion_label_snapshot'] = portion.amount * count, f'{count} × {portion.label}' if count > 1 else portion.label elif selected == 'custom': if data.get('amount') is None or data['amount'] <= 0: self.add_error('amount', 'Enter an amount greater than zero.') @@ -141,7 +147,13 @@ class FoodLogForm(forms.ModelForm): if not label: self.add_error('new_portion_label', 'Enter a label for the saved portion.') elif FoodPortion.objects.filter(user=self.product.owner, product=self.product, label=label).exists(): - self.add_error('new_portion_label', 'You already have a portion with this label.') + try: + submission_id = uuid.UUID(self.data.get('submission_id', '')) + except (ValueError, TypeError, AttributeError): + submission_id = None + if not (submission_id and FoodLogEntry.objects.filter(user=self.product.owner, + api_id=submission_id).exists()): + self.add_error('new_portion_label', 'You already have a portion with this label.') else: data['portion_label_snapshot'] = label elif data.get('make_default'): diff --git a/main/food/static/food/portions.js b/main/food/static/food/portions.js index 0d49ac7..af51b3b 100644 --- a/main/food/static/food/portions.js +++ b/main/food/static/food/portions.js @@ -4,16 +4,61 @@ const amount = document.querySelector('#id_amount'); const custom = document.querySelector('[data-food-custom-fields]'); const amountField = document.querySelector('[data-food-amount-field]'); + const countField = document.querySelector('[data-food-portion-count]'); + const count = document.querySelector('#id_portion_count'); const save = document.querySelector('#id_save_portion'); const saveFields = document.querySelector('[data-food-save-fields]'); + const inventory = document.querySelector('[data-food-inventory]'); + const packageSelect = inventory?.querySelector('#id_inventory_package'); + const preview = inventory?.querySelector('[data-food-inventory-preview]'); + const fmt = value => Number(value.toFixed(3)).toString(); + const syncPreview = () => { + if (!preview) return; + const selected = packageSelect.selectedOptions[0]; + const used = Number(amount.value); + if (!Number.isFinite(used) || used <= 0) { + preview.textContent = 'Enter a valid amount to preview nutrition and stock.'; + return; + } + const countValue = Number(count.value || 1); + const selectedLabel = select.selectedOptions[0].textContent.split(' — ')[0].trim(); + const label = select.value === 'custom' ? `${fmt(used)} ${inventory.dataset.unit}` : + `${fmt(countValue)} × ${selectedLabel} = ${fmt(used)} ${inventory.dataset.unit}`; + const kcal = Number(inventory.dataset.kcal); + const nutrition = inventory.dataset.kcal ? ` · ${fmt(kcal * used / 100)} kcal` : ' · calories unavailable'; + if (!selected.value) { + preview.textContent = `${label}${nutrition}. Inventory will not change.`; + return; + } + const remaining = Number(selected.dataset.remaining); + const nativeRemaining = Number(selected.dataset.nativeRemaining); + const nativeUnit = selected.dataset.nativeUnit; + const factor = remaining / nativeRemaining; + const after = remaining - used; + const onePortion = Number(select.selectedOptions[0].dataset.amount); + const portionStock = select.value.startsWith('portion:') && onePortion > 0 ? + ` ${fmt(remaining / onePortion)} ${selectedLabel} equivalents available → ${fmt(Math.max(0, after / onePortion))} after.` : ''; + preview.textContent = after < -0.000001 ? + `${label}${nutrition}. Not enough in this package: ${fmt(remaining)} ${inventory.dataset.unit} available.` : + `${label}${nutrition}. ${fmt(nativeRemaining)} ${nativeUnit} available now → ${fmt(after / factor)} ${nativeUnit} after logging.${portionStock}`; + }; const sync = () => { const customSelected = select.value === 'custom'; custom.hidden = !customSelected; amountField.hidden = !customSelected; - if (!customSelected) amount.value = select.selectedOptions[0].dataset.amount || '100'; + countField.hidden = customSelected; + custom.style.display = customSelected ? '' : 'none'; + amountField.style.display = customSelected ? '' : 'none'; + countField.style.display = customSelected ? 'none' : ''; + if (!customSelected) amount.value = String(Number(select.selectedOptions[0].dataset.amount || '100') * Number(count.value || 1)); saveFields.hidden = !customSelected || !save.checked; + saveFields.style.display = customSelected && save.checked ? '' : 'none'; + syncPreview(); }; select.addEventListener('change', sync); save.addEventListener('change', sync); + count.addEventListener('input', sync); + amount.addEventListener('input', syncPreview); + packageSelect?.addEventListener('change', syncPreview); sync(); })(); diff --git a/main/food/templates/food/partials/add_content.html b/main/food/templates/food/partials/add_content.html index bc3fab5..fb40c13 100644 --- a/main/food/templates/food/partials/add_content.html +++ b/main/food/templates/food/partials/add_content.html @@ -19,8 +19,19 @@ {% if product.source == 'openfoodfacts' %}

Product data from Open Food Facts.

{% endif %}
- {% csrf_token %} + {% csrf_token %} {% include 'food/partials/portion_fields.html' %} +
+ {{ form.inventory_package.label_tag }} + {% if inventory_packages %}{{ inventory_packages|length }} measured package{{ inventory_packages|length|pluralize }}: {{ inventory_total_original|floatformat:-3 }} {{ product.base_unit }} originally · {{ inventory_total_available|floatformat:-3 }} {{ product.base_unit }} available now{% endif %} + {{ form.inventory_package.errors }} + {% if not inventory_packages %}No measured stock available for this product. You can still log food.{% endif %} +

+
+ {{ form.non_field_errors }}
{% else %} diff --git a/main/food/templates/food/partials/portion_fields.html b/main/food/templates/food/partials/portion_fields.html index 4fbc54b..fea61d7 100644 --- a/main/food/templates/food/partials/portion_fields.html +++ b/main/food/templates/food/partials/portion_fields.html @@ -1,6 +1,7 @@
{{ form.meal.label_tag }}{{ form.meal }}{{ form.meal.errors }}
{% if product %}
{{ form.portion.errors }}
+
{{ form.portion_count.label_tag }}{{ form.portion_count }}{{ form.portion_count.errors }}
{{ form.amount.label_tag }}{{ form.amount }}{{ form.amount.errors }}{{ product.base_unit }}
{{ form.portion_label_snapshot.label_tag }}{{ form.portion_label_snapshot }}{{ form.portion_label_snapshot.errors }}
{{ form.save_portion.errors }}
diff --git a/main/food/test_api.py b/main/food/test_api.py index 6fa44eb..e5bf6dd 100644 --- a/main/food/test_api.py +++ b/main/food/test_api.py @@ -39,6 +39,33 @@ class FoodApiTests(TestCase): data = json.dumps(data) return getattr(self.client, method)(path, data=data, **args) + 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', + product_name_snapshot='Pasta', amount=Decimal('100'), unit='g', + calories_kcal=Decimal('432')) + location = InventoryLocation.objects.create(user=self.a, name='Pantry') + package = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, + location=location, original_amount=Decimal('700'), remaining_amount=Decimal('600'), + inventory_unit='g', opened=True) + payload = {'meal': 'lunch', 'product_id': str(self.product_a.api_id), + 'amount': '90', 'unit': 'g', 'inventory_package_id': str(package.api_id)} + path = '/api/v1/food/log/' + self.assertEqual(self.call('post', path, payload).status_code, 400) + first = self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='food-stock-1') + self.assertEqual(first.status_code, 201, first.content) + self.assertIn('inventory_consumption_id', first.json()) + self.assertEqual(self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='food-stock-1').status_code, 200) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('510')) + self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1) + self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 2) + shortage = self.call('post', path, {**payload, 'amount': '600'}, HTTP_IDEMPOTENCY_KEY='food-stock-2') + self.assertEqual(shortage.status_code, 409) + self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 2) + old.refresh_from_db() + self.assertEqual(old.calories_kcal, Decimal('432')) + def test_bulk_inventory_update_preview_partial_atomic_and_retry(self): location = InventoryLocation.objects.create(user=self.a, name='Pantry') items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location) diff --git a/main/food/tests.py b/main/food/tests.py index 898762a..bce5d90 100644 --- a/main/food/tests.py +++ b/main/food/tests.py @@ -12,7 +12,7 @@ from planner.models import UserSettings from .services.diary import diary_context -from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit +from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit, InventoryLocation, KitchenInventoryItem, InventoryConsumption class FoodFoundationTests(TestCase): @@ -205,6 +205,76 @@ class FoodFoundationTests(TestCase): self.assertContains(response, '0 kcal eaten') self.assertFalse(FoodLogEntry.objects.filter(pk=entry.pk).exists()) + def test_inventory_portion_preserves_old_diary_and_retries(self): + import uuid + self.product.energy_kcal_100 = Decimal('100') + self.product.save(update_fields=['energy_kcal_100']) + historical = FoodLogEntry.objects.create(user=self.user, product=self.product, + date=date(2026, 10, 3), meal=MealType.BREAKFAST, + product_name_snapshot='Yoghurt', amount=Decimal('100'), unit='g', + calories_kcal=Decimal('275')) + location = InventoryLocation.objects.create(user=self.user, name='Fridge') + package = KitchenInventoryItem.objects.create(user=self.user, product=self.product, + location=location, original_amount=Decimal('360'), remaining_amount=Decimal('270'), + inventory_unit='g', opened=True) + portion = FoodPortion.objects.create(user=self.user, product=self.product, + label='cup', amount=Decimal('90'), unit='g') + self.client.force_login(self.user) + payload = {'date': '2026-10-04', 'product': self.product.pk, 'meal': MealType.LUNCH, + 'portion': f'portion:{portion.pk}', 'unit': 'g', 'inventory_package': str(package.api_id), + 'submission_id': str(uuid.uuid4())} + response = self.client.post(reverse('food:add'), payload) + self.assertEqual(response.status_code, 302) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('180')) + self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 1) + self.client.post(reverse('food:add'), payload) + self.assertEqual(FoodLogEntry.objects.filter(user=self.user).count(), 2) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('180')) + self.assertEqual(diary_context(self.user, date(2026, 10, 3))['totals']['calories_kcal'], Decimal('275')) + historical.refresh_from_db() + self.assertEqual(historical.calories_kcal, Decimal('275')) + + def test_inventory_shortage_does_not_log_food(self): + import uuid + location = InventoryLocation.objects.create(user=self.user, name='Fridge') + package = KitchenInventoryItem.objects.create(user=self.user, product=self.product, + location=location, original_amount=Decimal('700'), remaining_amount=Decimal('60'), + inventory_unit='g', opened=True) + self.client.force_login(self.user) + response = self.client.post(reverse('food:add'), {'date': '2026-10-04', + 'product': self.product.pk, 'meal': MealType.LUNCH, 'portion': 'custom', + 'amount': '100', 'unit': 'g', 'inventory_package': str(package.api_id), + 'submission_id': str(uuid.uuid4())}) + self.assertContains(response, 'Insufficient stock') + self.assertFalse(FoodLogEntry.objects.filter(user=self.user).exists()) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('60')) + + def test_multiple_configured_pieces_use_exact_saved_weight(self): + import uuid + self.product.energy_kcal_100 = Decimal('200') + self.product.save(update_fields=['energy_kcal_100']) + piece = FoodPortion.objects.create(user=self.user, product=self.product, + label='meatball', amount=Decimal('25'), unit='g') + location = InventoryLocation.objects.create(user=self.user, name='Freezer') + package = KitchenInventoryItem.objects.create(user=self.user, product=self.product, + location=location, original_amount=Decimal('250'), remaining_amount=Decimal('125'), + inventory_unit='g', opened=True) + self.client.force_login(self.user) + response = self.client.post(reverse('food:add'), {'date': '2026-10-04', + 'product': self.product.pk, 'meal': MealType.DINNER, + 'portion': f'portion:{piece.pk}', 'portion_count': '3', 'unit': 'g', + 'inventory_package': str(package.api_id), 'submission_id': str(uuid.uuid4())}) + self.assertEqual(response.status_code, 302) + entry = FoodLogEntry.objects.get(user=self.user) + self.assertEqual(entry.amount, Decimal('75')) + self.assertEqual(entry.calories_kcal, Decimal('150')) + self.assertEqual(entry.portion_label_snapshot, '3 × meatball') + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('50')) + def test_cannot_edit_or_delete_another_users_entry(self): entry = 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/food/views.py b/main/food/views.py index e008897..62ea42b 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -4,9 +4,11 @@ import csv from datetime import date, timedelta import logging import re +import uuid from urllib.parse import urlencode from django.contrib.auth.decorators import login_required +from django.contrib.auth import get_user_model from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse from django.contrib import messages from django.db.models import Q, F @@ -27,6 +29,7 @@ from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_s from .services.products import local_products from .services.logging import apply_product_snapshot from .services.hydration import sync_food_hydration +from .services.inventory_consumption import FACTORS, StockError, consume, stock from planner.timezones import localdate_for_user @@ -122,10 +125,12 @@ def _save_custom_portion(form, user, product, entry): portion.save() -def _save_entry(form, user, day, product): +def _save_entry(form, user, day, product, submission_id=None): entry = form.save(commit=False) entry.user = user entry.date = day + if submission_id is not None: + entry.api_id = submission_id apply_product_snapshot(entry, product) sync_food_hydration(entry) entry.full_clean() @@ -211,21 +216,68 @@ def add_food(request): item.is_favourite = item.pk in favourite_ids if product: product.is_favourite = product.pk in favourite_ids - form = FoodLogForm(request.POST or None, product=product, initial={'meal': meal, 'unit': product.base_unit if product else 'g'}) if product else None + inventory_options = [] + inventory_packages = [] + inventory_total_original = Decimal(0) + inventory_total_available = Decimal(0) + if product: + for item in stock(request.user, product): + if item.original_amount is None or item.inventory_unit not in FACTORS: + continue + dimension, factor = FACTORS[item.inventory_unit] + if dimension != FACTORS[product.base_unit][0] or item.remaining_amount <= 0: + continue + inventory_packages.append({'id': str(item.api_id), 'original': item.original_amount, + 'remaining': item.remaining_amount, 'unit': item.inventory_unit, + 'remaining_base': item.remaining_amount * factor, + 'location': item.location.name, 'opened': item.opened}) + inventory_total_original += item.original_amount * factor + inventory_total_available += item.remaining_amount * factor + inventory_options.append((str(item.api_id), + f'{item.location.name}: {item.remaining_amount:g} of {item.original_amount:g} {item.inventory_unit} left')) + form = FoodLogForm(request.POST or None, product=product, inventory_options=inventory_options, + initial={'meal': meal, 'unit': product.base_unit if product else 'g'}) if product else None + submission_id = (request.POST.get('submission_id') or str(uuid.uuid4())) if request.method == 'POST' else str(uuid.uuid4()) if request.method == 'POST': if not product: return HttpResponseBadRequest('Choose a product.') if form.is_valid(): - with transaction.atomic(): - _save_entry(form, request.user, day, product) - return _diary_response(request, day) + try: + submission_uuid = uuid.UUID(submission_id) + except (ValueError, TypeError, AttributeError): + form.add_error(None, 'Reload this form and try again.') + else: + try: + with transaction.atomic(): + get_user_model().objects.select_for_update().get(pk=request.user.pk) + previous = FoodLogEntry.objects.filter(user=request.user, api_id=submission_uuid).first() + if previous: + if (previous.date == day and previous.product_id == product.pk and + previous.meal == form.cleaned_data['meal'] and + previous.amount == form.cleaned_data['amount'] and + previous.unit == form.cleaned_data['unit']): + return _diary_response(request, day) + form.add_error(None, 'This submission was already used for a different entry.') + else: + entry = _save_entry(form, request.user, day, product, submission_uuid) + package_id = form.cleaned_data.get('inventory_package') + if package_id: + consume(request.user, product, entry.amount, entry.unit, + package_id=package_id, source='manual', + source_reference=str(entry.api_id), + idempotency_key=f'food-log:{entry.api_id}') + return _diary_response(request, day) + except StockError as exc: + form.add_error('inventory_package', str(exc)) portion_options = _portion_options(form, product) if form else [] template = 'food/partials/add_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/add.html' return render(request, template, {'day': day, 'meal': meal, 'products': products[:40], 'product': product, 'form': form, 'query': query, 'tab': tab, 'favourite_ids': favourite_ids, 'favourites': favourites if not query and tab == 'overview' else [], 'recents': recents if not query and tab == 'overview' else [], - 'is_favourite': product.pk in favourite_ids if product else False, 'portion_options': portion_options}) + 'is_favourite': product.pk in favourite_ids if product else False, 'portion_options': portion_options, + 'inventory_packages': inventory_packages, 'submission_id': submission_id, + 'inventory_total_original': inventory_total_original, 'inventory_total_available': inventory_total_available}) @login_required diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index f2a0f66..ad9d05f 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -45,6 +45,7 @@ class FoodInput(BaseModel): amount: Decimal = Field(gt=0) unit: Literal['g', 'ml'] product_id: str | None = None + inventory_package_id: str | None = None product_name: str | None = None brand: str | None = None barcode: str | None = None @@ -350,7 +351,7 @@ def create_server() -> MCPServer: @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]: data = await api_request('GET', 'food/products/', params={'search': query, 'limit': min(max(limit, 1), 100)}) - fields = ('id', 'product_name', 'brand', 'barcode', 'base_unit', 'serving_size_text', + fields = ('id', 'product_name', 'brand', 'barcode', 'base_unit', 'package_amount', 'package_unit', 'serving_size_text', 'serving_amount', 'serving_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100', 'portions') return {'count': data['count'], 'products': [{k: item.get(k) for k in fields} for item in data['results']]} @@ -384,11 +385,11 @@ def create_server() -> MCPServer: return {'status': 'failed', 'reason': str(exc), 'idempotency_key': key} return {**data, 'idempotency_key': key} - @server.tool(structured_output=True, description='Create one food log entry for the authenticated user. For known foods, search TaskNest products first and use product_id; do not fabricate nutrition when reliable product data exists. For a user-requested estimated meal, product_name and estimated nutrition are allowed. Uses the user’s local date unless date is supplied. Reuse idempotency_key on retries.') + @server.tool(structured_output=True, description='Create one food log entry for the authenticated user. For known foods, search TaskNest products first and use product_id; do not fabricate nutrition when reliable product data exists. Optional inventory_package_id atomically consumes the logged g/ml from that exact owned package; use a saved product portion conversion and inventory_get_stock to resolve natural units, never guess piece weights. Inventory logging requires idempotency_key; reuse it on retries. Uses the user’s local date unless date is supplied.') async def food_log(food: FoodInput, idempotency_key: str | None = None) -> dict[str, Any]: key = _key(idempotency_key) data = await api_request('POST', 'food/log/', payload=food.model_dump(mode='json', exclude_none=True), idempotency_key=key) - return {'success': True, 'entry': _entry(data), 'idempotency_key': key} + return {'success': True, 'entry': _entry(data), 'inventory_consumption_id': data.get('inventory_consumption_id'), 'idempotency_key': key} @server.tool(structured_output=True, description='Update only the supplied fields of one owned food log entry by opaque ID. Changes existing data; product nutrition is recalculated by TaskNest when applicable.') async def food_update_entry(entry_id: str, changes: FoodUpdate) -> dict[str, Any]: