diff --git a/main/food/forms.py b/main/food/forms.py
index 1834ebf..a1a8cf4 100644
--- a/main/food/forms.py
+++ b/main/food/forms.py
@@ -74,6 +74,8 @@ class FoodLogForm(forms.ModelForm):
def __init__(self, *args, product=None, **kwargs):
super().__init__(*args, **kwargs)
self.product = product or getattr(self.instance, 'product', None)
+ if self.instance.pk and self.instance.created_via == 'recipe':
+ self.fields['unit'].choices = [('servings', 'servings')]
if self.product and self.product.pk:
self.fields['unit'].initial = self.product.base_unit
unit = self.product.base_unit
@@ -106,12 +108,18 @@ class FoodLogForm(forms.ModelForm):
def clean_unit(self):
unit = self.cleaned_data['unit']
+ if self.instance.pk and self.instance.created_via == 'recipe' and unit != 'servings':
+ raise forms.ValidationError('Recipe entries use servings.')
if self.product and unit != self.product.base_unit:
raise forms.ValidationError('Use the same unit as the product nutrition basis.')
return unit
def clean(self):
data = super().clean()
+ if self.instance.pk and self.instance.created_via == 'recipe':
+ run = getattr(self.instance, 'recipe_cooking_run', None)
+ 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'
if not self.product or not selected:
return data
diff --git a/main/food/migrations/0010_alter_foodlogentry_unit.py b/main/food/migrations/0010_alter_foodlogentry_unit.py
new file mode 100644
index 0000000..6e4c057
--- /dev/null
+++ b/main/food/migrations/0010_alter_foodlogentry_unit.py
@@ -0,0 +1,18 @@
+# Generated by Django 6.1.1 on 2026-10-12 07:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('food', '0009_backfill_food_hydration'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='foodlogentry',
+ name='unit',
+ field=models.CharField(choices=[('g', 'g'), ('ml', 'ml'), ('servings', 'servings')], max_length=8),
+ ),
+ ]
diff --git a/main/food/models.py b/main/food/models.py
index e39fe99..ef821b6 100644
--- a/main/food/models.py
+++ b/main/food/models.py
@@ -79,7 +79,7 @@ class FoodLogEntry(models.Model):
barcode_snapshot = models.CharField(max_length=64, blank=True)
portion_label_snapshot = models.CharField(max_length=100, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
- unit = models.CharField(max_length=2, choices=Unit.choices)
+ unit = models.CharField(max_length=8, choices=[*Unit.choices, ('servings', 'servings')])
beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE)
hydration_factor_snapshot = models.DecimalField(max_digits=4, decimal_places=3, default=0, validators=NON_NEGATIVE)
diff --git a/main/food/services/diary.py b/main/food/services/diary.py
index 76ea918..4de3278 100644
--- a/main/food/services/diary.py
+++ b/main/food/services/diary.py
@@ -25,12 +25,19 @@ def selected_date(request):
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')
+ entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product', 'recipe_cooking_run')
.prefetch_related('attachments').defer('product__raw_data'))
+ for entry in entries:
+ 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()))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')}
fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None]
- fibre_incomplete = len(fibre_values) != len(entries)
+ fibre_incomplete = len(fibre_values) != len(entries) 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)
totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None
meals = []
for key, label in MealType.choices:
diff --git a/main/food/templates/food/partials/diary_content.html b/main/food/templates/food/partials/diary_content.html
index 1dc2d52..5934ba1 100644
--- a/main/food/templates/food/partials/diary_content.html
+++ b/main/food/templates/food/partials/diary_content.html
@@ -12,7 +12,7 @@
{% if images %}
Ingredients
{% for line in analysis.lines %}- {{ line.name }}{% if line.source %}From {{ line.source }}{% endif %}{% if line.ingredient.preparation_note %}{{ line.ingredient.preparation_note }}{% endif %}{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}{{ line.quantity|floatformat:-3 }} {{ line.unit }}{% if line.optional %}Optional{% if not analysis.include_optional %} · excluded{% endif %}{% endif %}
{% empty %}- No ingredients added yet.
{% endfor %}
diff --git a/main/recipes/test_cooking.py b/main/recipes/test_cooking.py
new file mode 100644
index 0000000..dbff5d4
--- /dev/null
+++ b/main/recipes/test_cooking.py
@@ -0,0 +1,173 @@
+from datetime import date
+from decimal import Decimal
+
+from django.contrib.auth import get_user_model
+from django.test import TestCase
+from django.urls import reverse
+
+from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
+from recipes.models import Recipe, RecipeCookingRun, RecipeIngredient, RecipeSubrecipe, RecipeUse
+from recipes.services.analysis import analyze
+from recipes.services.cooking import CookingError, complete, instruction_steps, make_completion
+
+
+class RecipeCookingTests(TestCase):
+ def setUp(self):
+ users = get_user_model()
+ self.user = users.objects.create_user(username='cooking-owner')
+ self.other = users.objects.create_user(username='cooking-other')
+ self.client.force_login(self.user)
+ self.product = FoodProduct.objects.create(
+ owner=self.user, product_name='Oats', base_unit='g',
+ energy_kcal_100=Decimal('400'), protein_100=Decimal('10'),
+ carbohydrates_100=Decimal('60'), fat_100=Decimal('5'), fibre_100=Decimal('8'))
+ self.recipe = Recipe.objects.create(owner=self.user, title='Oat bowl',
+ default_servings=2,
+ instructions_markdown='1. Mix oats\n2. Serve warm')
+ RecipeIngredient.objects.create(recipe=self.recipe, name='Oats', quantity=Decimal('200'),
+ unit='g', inventory_product=self.product,
+ nutrition_product=self.product)
+ location = InventoryLocation.objects.create(user=self.user, name='Pantry')
+ self.package = KitchenInventoryItem.objects.create(
+ user=self.user, product=self.product, location=location,
+ original_amount=Decimal('300'), remaining_amount=Decimal('300'), inventory_unit='g')
+ self.day = date(2026, 10, 12)
+
+ def token(self):
+ return make_completion(analyze(self.recipe, self.user, 2))
+
+ def test_log_one_serving_without_inventory_and_keep_historical_nutrition(self):
+ token = self.token()
+ run = complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
+ consumed_servings='1', meal='breakfast', day=self.day)
+ entry = run.food_entry
+ self.assertEqual((entry.amount, entry.unit, entry.calories_kcal),
+ (Decimal('1'), 'servings', Decimal('400.000')))
+ self.assertEqual(entry.protein_g, Decimal('10.000'))
+ self.assertEqual(self.package.remaining_amount, Decimal('300'))
+ self.assertFalse(RecipeUse.objects.exists())
+ self.recipe.title = 'Changed bowl'; self.recipe.save()
+ self.product.energy_kcal_100 = Decimal('100'); self.product.save()
+ entry.refresh_from_db()
+ self.assertEqual((entry.product_name_snapshot, entry.calories_kcal),
+ ('Oat bowl', Decimal('400.000')))
+ self.assertEqual(Decimal(run.nutrition_snapshot['calories_kcal']['per_serving']), Decimal('400'))
+ again = complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
+ consumed_servings='1', meal='breakfast', day=self.day)
+ self.assertEqual(again.pk, run.pk)
+ self.assertEqual(FoodLogEntry.objects.count(), 1)
+
+ def test_stock_only_and_both_actions_are_separate_and_idempotent(self):
+ stock_token = self.token()
+ stock = complete(self.user, self.recipe, stock_token, log_food=False, deduct_stock=True)
+ self.assertIsNone(stock.food_entry)
+ self.package.refresh_from_db()
+ self.assertEqual(self.package.remaining_amount, Decimal('100'))
+ self.assertEqual(RecipeUse.objects.count(), 1)
+ self.assertEqual(complete(self.user, self.recipe, stock_token, log_food=False,
+ deduct_stock=True).pk, stock.pk)
+ self.assertEqual(RecipeUse.objects.count(), 1)
+ self.assertEqual(FoodLogEntry.objects.count(), 0)
+
+ self.package.remaining_amount = Decimal('300'); self.package.opened = True
+ self.package.save()
+ both_token = self.token()
+ both = complete(self.user, self.recipe, both_token, log_food=True, deduct_stock=True,
+ consumed_servings='0.5', meal='dinner', day=self.day)
+ self.assertTrue(both.food_entry_id)
+ self.assertTrue(both.stock_use_id)
+ self.assertEqual(both.food_entry.calories_kcal, Decimal('200.000'))
+ self.package.refresh_from_db()
+ self.assertEqual(self.package.remaining_amount, Decimal('100'))
+ complete(self.user, self.recipe, both_token, log_food=True, deduct_stock=True,
+ consumed_servings='0.5', meal='dinner', day=self.day)
+ self.assertEqual(FoodLogEntry.objects.count(), 1)
+ self.assertEqual(RecipeUse.objects.count(), 2)
+
+ def test_invalid_stock_rolls_back_food_log_and_unavailable_stock_still_allows_log(self):
+ token = self.token()
+ self.package.remaining_amount = Decimal('50'); self.package.opened = True
+ self.package.save()
+ with self.assertRaises(CookingError):
+ complete(self.user, self.recipe, token, log_food=True, deduct_stock=True,
+ consumed_servings='1', meal='dinner', day=self.day)
+ self.assertFalse(FoodLogEntry.objects.exists())
+ self.assertFalse(RecipeCookingRun.objects.exists())
+ log_only_token = self.token()
+ run = complete(self.user, self.recipe, log_only_token, log_food=True,
+ deduct_stock=False, consumed_servings='1', meal='dinner', day=self.day)
+ self.assertTrue(run.food_entry_id)
+ self.assertIsNone(run.stock_use_id)
+
+ def test_missing_nutrients_and_nested_ingredients_are_snapshotted(self):
+ self.product.fibre_100 = None; self.product.save()
+ subrecipe = Recipe.objects.create(owner=self.user, title='Topping', default_servings=2,
+ instructions_markdown='Toast briefly.')
+ RecipeIngredient.objects.create(recipe=subrecipe, name='Oats', quantity=Decimal('100'),
+ unit='g', nutrition_product=self.product)
+ RecipeSubrecipe.objects.create(recipe=self.recipe, component=subrecipe,
+ quantity=Decimal('1'), unit='servings')
+ result = analyze(self.recipe, self.user, 2)
+ self.assertEqual(result['nutrition']['calories_kcal']['total'], Decimal('1000'))
+ self.assertFalse(result['nutrition']['fibre_g']['complete'])
+ run = complete(self.user, self.recipe, make_completion(result), log_food=True,
+ deduct_stock=False, consumed_servings='1', meal='lunch', day=self.day)
+ self.assertEqual(run.food_entry.calories_kcal, Decimal('500.000'))
+ self.assertIsNone(run.food_entry.fibre_g)
+ self.assertEqual(len(run.ingredient_snapshot), 2)
+ self.assertEqual(instruction_steps(self.recipe.instructions_markdown), ['Mix oats', 'Serve warm'])
+ diary = self.client.get(reverse('food:diary'), {'date': self.day.isoformat()})
+ self.assertContains(diary, 'Incomplete nutrition estimate')
+
+ def test_web_completion_and_owner_isolation(self):
+ cook_url = reverse('recipes:cook', args=[self.recipe.api_id])
+ finish_url = reverse('recipes:cook-finish', args=[self.recipe.api_id])
+ self.assertContains(self.client.get(cook_url), 'Step 1 of 2')
+ response = self.client.get(finish_url)
+ self.assertContains(response, 'Confirm selected actions')
+ token = response.context['confirmation']
+ post = {'confirmation': token, 'log_food': '1', 'consumed_servings': '1',
+ 'meal': 'dinner', 'date': self.day.isoformat()}
+ self.assertEqual(self.client.post(finish_url, post).status_code, 302)
+ self.assertEqual(FoodLogEntry.objects.count(), 1)
+ self.assertEqual(self.client.post(finish_url, post).status_code, 302)
+ self.assertEqual(FoodLogEntry.objects.count(), 1)
+ stock_token = self.client.get(finish_url).context['confirmation']
+ stock_only = self.client.post(finish_url, {'confirmation': stock_token,
+ 'deduct_stock': '1'})
+ self.assertEqual(stock_only.status_code, 302)
+ self.assertEqual(FoodLogEntry.objects.count(), 1)
+ self.package.refresh_from_db()
+ self.assertEqual(self.package.remaining_amount, Decimal('100'))
+ self.client.force_login(self.other)
+ self.assertEqual(self.client.get(cook_url).status_code, 404)
+ self.assertEqual(self.client.get(finish_url).status_code, 404)
+ self.assertEqual(self.client.post(finish_url, post).status_code, 404)
+
+ def test_invalid_consumed_portion_does_not_write(self):
+ token = self.token()
+ for amount in ('0', '-1', '2.001', 'nan'):
+ with self.assertRaises(CookingError):
+ complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
+ consumed_servings=amount, meal='dinner', day=self.day)
+ self.assertFalse(RecipeCookingRun.objects.exists())
+
+ def test_diary_recipe_edit_keeps_serving_unit_and_scales_snapshot(self):
+ run = complete(self.user, self.recipe, self.token(), log_food=True,
+ deduct_stock=False, consumed_servings='1', meal='breakfast', day=self.day)
+ url = reverse('food:edit', args=[run.food_entry.pk])
+ invalid = self.client.post(url, {'meal': 'breakfast', 'amount': '1',
+ 'unit': 'g', 'portion_label_snapshot': 'Recipe serving'})
+ self.assertEqual(invalid.status_code, 200)
+ run.food_entry.refresh_from_db()
+ self.assertEqual(run.food_entry.unit, 'servings')
+ too_much = self.client.post(url, {'meal': 'breakfast', 'amount': '3',
+ 'unit': 'servings', 'portion_label_snapshot': 'Recipe serving'})
+ self.assertContains(too_much, 'exceeds the prepared servings')
+ saved = self.client.post(url, {'meal': 'lunch', 'amount': '0.5',
+ 'unit': 'servings', 'portion_label_snapshot': 'Recipe serving'})
+ self.assertEqual(saved.status_code, 302)
+ run.refresh_from_db(); run.food_entry.refresh_from_db()
+ self.assertEqual(run.consumed_servings, Decimal('0.5'))
+ self.assertEqual(run.food_entry.calories_kcal, Decimal('200.000'))
+ self.assertEqual(run.food_entry.meal, 'lunch')
diff --git a/main/recipes/urls.py b/main/recipes/urls.py
index 6b04a5e..098610f 100644
--- a/main/recipes/urls.py
+++ b/main/recipes/urls.py
@@ -10,6 +10,8 @@ urlpatterns = [
path('new/autosave/', views.autosave_new, name='autosave-new'),
path('
/', views.detail, name='detail'),
path('/edit/', views.edit, name='edit'),
+ path('/cook/', views.cook, name='cook'),
+ path('/cook/finish/', views.cook_finish, name='cook-finish'),
path('/autosave/', views.autosave, name='autosave'),
path('/variations/new/', views.create_variation, name='create-variation'),
path('/stock/', views.stock_preview, name='stock-preview'),
diff --git a/main/recipes/views.py b/main/recipes/views.py
index 5922867..0ca632d 100644
--- a/main/recipes/views.py
+++ b/main/recipes/views.py
@@ -9,12 +9,16 @@ from django.http import FileResponse, Http404, HttpResponseBadRequest, JsonRespo
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST
+from django.utils.dateparse import parse_date
+from planner.timezones import localdate_for_user
+from food.models import MealType
from PIL import Image
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
RecipeSubstitutionForm)
from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse
from .services.analysis import AnalysisError, analyze
+from .services.cooking import CookingError, complete, instruction_steps, make_completion
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
@@ -77,6 +81,87 @@ def detail(request, identifier):
return _library(request, recipe)
+def _cooking_analysis(request, recipe):
+ selected = {key[4:]: value for key, value in request.GET.items()
+ if key.startswith('sub_') and value}
+ return analyze(recipe, request.user, request.GET.get('servings'),
+ include_optional=request.GET.get('optional') == '1',
+ substitutions=selected)
+
+
+@login_required
+def cook(request, identifier):
+ recipe = get_object_or_404(_owned(request.user), api_id=identifier)
+ try:
+ result = _cooking_analysis(request, recipe)
+ error = ''
+ except AnalysisError as exc:
+ error = str(exc)
+ result = analyze(recipe, request.user, recipe.default_servings)
+ components = []
+
+ def gather(current, scale, ancestors, depth):
+ if depth > 8 or current.pk in ancestors:
+ return
+ for item in current.subrecipes.select_related('component'):
+ component = item.component
+ if item.unit == 'servings':
+ quantity = item.quantity * scale
+ child_scale = quantity / component.default_servings
+ elif component.yield_amount and component.yield_unit == item.unit:
+ quantity = item.quantity * scale
+ child_scale = quantity / component.yield_amount
+ else:
+ continue
+ components.append({'title': component.title, 'quantity': quantity,
+ 'unit': item.unit, 'depth': depth,
+ 'steps': instruction_steps(component.instructions_markdown)})
+ gather(component, child_scale, ancestors | {current.pk}, depth + 1)
+
+ gather(recipe, result['servings'] / recipe.default_servings, set(), 1)
+ return render(request, 'recipes/cook.html', {'recipe': recipe, 'analysis': result,
+ 'error': error, 'steps': instruction_steps(recipe.instructions_markdown),
+ 'components': components})
+
+
+@login_required
+@require_http_methods(['GET', 'POST'])
+def cook_finish(request, identifier):
+ recipe = get_object_or_404(_owned(request.user), api_id=identifier)
+ if request.method == 'POST':
+ log_food = request.POST.get('log_food') == '1'
+ day_text = request.POST.get('date', '')
+ day = parse_date(day_text) if day_text else None
+ if log_food and (day is None or day.isoformat() != day_text):
+ messages.error(request, 'Choose a valid Food Diary date.')
+ return redirect('recipes:cook-finish', identifier=identifier)
+ try:
+ run = complete(
+ request.user, recipe, request.POST.get('confirmation', ''),
+ log_food=log_food,
+ deduct_stock=request.POST.get('deduct_stock') == '1',
+ consumed_servings=request.POST.get('consumed_servings'),
+ meal=request.POST.get('meal'), day=day)
+ except CookingError as exc:
+ messages.error(request, str(exc))
+ return redirect('recipes:cook-finish', identifier=identifier)
+ messages.success(request, 'Cooking completion saved.')
+ if run.food_logged_at:
+ return redirect(f'{reverse("food:diary")}?date={day.isoformat()}')
+ return redirect('recipes:detail', identifier=recipe.api_id)
+ try:
+ result = _cooking_analysis(request, recipe)
+ error = ''
+ except AnalysisError as exc:
+ error = str(exc)
+ result = analyze(recipe, request.user, recipe.default_servings)
+ return render(request, 'recipes/cook_finish.html', {
+ 'recipe': recipe, 'analysis': result, 'error': error,
+ 'confirmation': make_completion(result) if not error else '',
+ 'today': localdate_for_user(request.user), 'meals': MealType.choices,
+ })
+
+
@login_required
def stock_preview(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)