From 2a888e534606ac54ca22f1e3d8b4687496df2383 Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Mon, 12 Oct 2026 10:00:02 +0200 Subject: [PATCH] Recipes phase 4 --- main/food/forms.py | 8 + .../0010_alter_foodlogentry_unit.py | 18 ++ main/food/models.py | 2 +- main/food/services/diary.py | 11 +- .../food/partials/diary_content.html | 2 +- main/food/views.py | 5 + .../migrations/0004_recipecookingrun.py | 40 ++++ main/recipes/models.py | 26 ++- main/recipes/services/cooking.py | 128 +++++++++++++ main/recipes/static/recipes/cooking.js | 52 ++++++ main/recipes/static/recipes/recipes.css | 4 + main/recipes/templates/recipes/cook.html | 20 ++ .../templates/recipes/cook_finish.html | 18 ++ main/recipes/templates/recipes/library.html | 1 + main/recipes/test_cooking.py | 173 ++++++++++++++++++ main/recipes/urls.py | 2 + main/recipes/views.py | 85 +++++++++ 17 files changed, 590 insertions(+), 5 deletions(-) create mode 100644 main/food/migrations/0010_alter_foodlogentry_unit.py create mode 100644 main/recipes/migrations/0004_recipecookingrun.py create mode 100644 main/recipes/services/cooking.py create mode 100644 main/recipes/static/recipes/cooking.js create mode 100644 main/recipes/templates/recipes/cook.html create mode 100644 main/recipes/templates/recipes/cook_finish.html create mode 100644 main/recipes/test_cooking.py 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 %}
{% for attachment in images %}{% endfor %}
{% elif entry.product and entry.product.image_url %}{% endif %} {% endwith %} -
{{ entry.product_name_snapshot }}{% if entry.brand_snapshot %}{{ entry.brand_snapshot }}{% endif %}{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }})
+
{{ entry.product_name_snapshot }}{% if entry.brand_snapshot %}{{ entry.brand_snapshot }}{% endif %}{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }}){% if entry.nutrition_incomplete %} · Incomplete nutrition estimate{% endif %}
Edit{% if entry.product %}Drink settings{% endif %}
diff --git a/main/food/views.py b/main/food/views.py index 504edff..0d64c3e 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -372,6 +372,11 @@ def edit_entry(request, pk): sync_food_hydration(updated) updated.full_clean() updated.save() + if updated.created_via == 'recipe': + run = getattr(updated, 'recipe_cooking_run', None) + if run: + run.consumed_servings = updated.amount + run.save(update_fields=('consumed_servings',)) if product: _save_custom_portion(form, request.user, product, updated) return _diary_response(request, entry.date) diff --git a/main/recipes/migrations/0004_recipecookingrun.py b/main/recipes/migrations/0004_recipecookingrun.py new file mode 100644 index 0000000..4f64b66 --- /dev/null +++ b/main/recipes/migrations/0004_recipecookingrun.py @@ -0,0 +1,40 @@ +# Generated by Django 6.1.1 on 2026-10-12 07:41 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0010_alter_foodlogentry_unit'), + ('recipes', '0003_recipe_yield_amount_recipe_yield_unit_and_more'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='RecipeCookingRun', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('recipe_title_snapshot', models.CharField(max_length=180)), + ('prepared_servings', models.DecimalField(decimal_places=2, max_digits=7)), + ('consumed_servings', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True)), + ('request_signature', models.CharField(max_length=64)), + ('nutrition_snapshot', models.JSONField(default=dict)), + ('ingredient_snapshot', models.JSONField(default=list)), + ('food_logged_at', models.DateTimeField(blank=True, null=True)), + ('stock_used_at', models.DateTimeField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('food_entry', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_cooking_run', to='food.foodlogentry')), + ('recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='cooking_runs', to='recipes.recipe')), + ('stock_use', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='cooking_run', to='recipes.recipeuse')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ('-created_at',), + }, + ), + ] diff --git a/main/recipes/models.py b/main/recipes/models.py index ce750ea..51b3a8b 100644 --- a/main/recipes/models.py +++ b/main/recipes/models.py @@ -1,4 +1,4 @@ -"""Owned, structured recipes. Calculations and cooking workflows arrive in later passes.""" +"""Owned, structured recipes and audited cooking actions.""" import uuid from decimal import Decimal @@ -209,3 +209,27 @@ class RecipeUseLine(models.Model): recipe_use = models.ForeignKey(RecipeUse, on_delete=models.CASCADE, related_name='lines') consumption = models.OneToOneField('food.InventoryConsumption', on_delete=models.PROTECT, related_name='recipe_use_line') + + +class RecipeCookingRun(models.Model): + """A confirmed cooking completion; each selected action is recorded at most once.""" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + recipe = models.ForeignKey(Recipe, on_delete=models.SET_NULL, null=True, related_name='cooking_runs') + recipe_title_snapshot = models.CharField(max_length=180) + prepared_servings = models.DecimalField(max_digits=7, decimal_places=2) + consumed_servings = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True) + request_signature = models.CharField(max_length=64) + nutrition_snapshot = models.JSONField(default=dict) + ingredient_snapshot = models.JSONField(default=list) + food_entry = models.OneToOneField('food.FoodLogEntry', on_delete=models.SET_NULL, + null=True, blank=True, related_name='recipe_cooking_run') + stock_use = models.OneToOneField(RecipeUse, on_delete=models.SET_NULL, + null=True, blank=True, related_name='cooking_run') + food_logged_at = models.DateTimeField(null=True, blank=True) + stock_used_at = models.DateTimeField(null=True, blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ('-created_at',) diff --git a/main/recipes/services/cooking.py b/main/recipes/services/cooking.py new file mode 100644 index 0000000..acdf120 --- /dev/null +++ b/main/recipes/services/cooking.py @@ -0,0 +1,128 @@ +"""Signed cooking completion and historical Food Diary snapshots.""" + +import hashlib +import uuid +from decimal import Decimal, InvalidOperation + +from django.contrib.auth import get_user_model +from django.core import signing +from django.db import transaction +from django.utils import timezone + +from food.models import FoodLogEntry, MealType +from planner.timezones import timezone_for_user +from recipes.models import RecipeCookingRun + +from .analysis import parse_servings +from .stock_use import RecipeStockError, confirm as confirm_stock, make_confirmation + + +SALT = 'recipes.cooking.v1' +THREE_PLACES = Decimal('0.001') + + +class CookingError(ValueError): + pass + + +def instruction_steps(markdown): + """Treat Markdown paragraphs and list items as navigable cooking steps.""" + import re + + steps = [] + for block in re.split(r'\n\s*\n', (markdown or '').strip()): + if not block.strip(): + continue + lines = block.splitlines() + if all(re.match(r'^\s*(?:\d+[.)]|[-*+])\s+', line) for line in lines): + steps.extend(re.sub(r'^\s*(?:\d+[.)]|[-*+])\s+', '', line).strip() for line in lines) + else: + steps.append(block.strip()) + return steps + + +def make_completion(analysis): + nutrition = {field: {'per_serving': str(row['per_serving']) if row['per_serving'] is not None else None, + 'complete': row['complete']} + for field, row in analysis['nutrition'].items()} + ingredients = [{'name': line['name'], 'quantity': str(line['quantity']), + 'unit': line['unit'], 'source': line['source']} + for line in analysis['lines'] if line['status'] != 'optional'] + return signing.dumps({ + 'operation_id': str(uuid.uuid4()), 'recipe_id': str(analysis['recipe'].api_id), + 'title': analysis['recipe'].title, 'prepared_servings': str(analysis['servings']), + 'nutrition': nutrition, 'ingredients': ingredients, + 'stock_confirmation': make_confirmation(analysis) if analysis['stock_ready'] else '', + }, salt=SALT) + + +def complete(user, recipe, token, *, log_food, deduct_stock, consumed_servings=None, + meal=None, day=None, time=None): + try: + payload = signing.loads(token, salt=SALT, max_age=3600) + operation_id = uuid.UUID(payload['operation_id']) + prepared = parse_servings(payload['prepared_servings'], recipe.default_servings) + except (signing.BadSignature, ValueError, KeyError, TypeError, AttributeError) as error: + raise CookingError('This cooking confirmation expired. Review the recipe again.') from error + if recipe.owner_id != user.pk or payload.get('recipe_id') != str(recipe.api_id): + raise CookingError('This cooking confirmation does not belong to this recipe.') + if not log_food and not deduct_stock: + raise CookingError('Choose at least one completion action.') + if deduct_stock and not payload.get('stock_confirmation'): + raise CookingError('Inventory is not ready. Review stock before deducting it.') + if log_food: + if meal not in MealType.values or day is None: + raise CookingError('Choose a valid meal and date.') + try: + consumed = Decimal(str(consumed_servings)) + except (InvalidOperation, TypeError, ValueError): + raise CookingError('Enter a valid consumed portion.') from None + if (not consumed.is_finite() or consumed < Decimal('0.001') or consumed > prepared or + consumed != consumed.quantize(THREE_PLACES)): + raise CookingError('Consumed servings must be positive and no more than prepared servings.') + else: + consumed = None + signature = hashlib.sha256(token.encode()).hexdigest() + with transaction.atomic(): + get_user_model().objects.select_for_update().get(pk=user.pk) + run = RecipeCookingRun.objects.select_for_update().filter(pk=operation_id).first() + if run: + if run.user_id != user.pk or run.request_signature != signature: + raise CookingError('This cooking confirmation was already used for another request.') + if ((log_food and not run.food_logged_at and run.stock_used_at) or + (deduct_stock and not run.stock_used_at and run.food_logged_at)): + raise CookingError('Start a new cooking completion for another action.') + if ((log_food and run.food_logged_at and run.consumed_servings != consumed) or + (deduct_stock and not run.stock_used_at and run.food_logged_at)): + raise CookingError('This confirmation was already used with different choices.') + else: + run = RecipeCookingRun.objects.create( + id=operation_id, user=user, recipe=recipe, + recipe_title_snapshot=payload['title'], prepared_servings=prepared, + request_signature=signature, nutrition_snapshot=payload['nutrition'], + ingredient_snapshot=payload['ingredients']) + if deduct_stock and not run.stock_used_at: + try: + stock_use, _ = confirm_stock(user, recipe, payload['stock_confirmation']) + except RecipeStockError as error: + raise CookingError(str(error)) from error + run.stock_use = stock_use + run.stock_used_at = timezone.now() + if log_food and not run.food_logged_at: + values = {} + for field, row in payload['nutrition'].items(): + per_serving = row['per_serving'] + values[field] = (Decimal(per_serving) * consumed).quantize(THREE_PLACES) if per_serving is not None else None + local_now = timezone.localtime(timezone.now(), timezone_for_user(user)) + entry = FoodLogEntry( + user=user, date=day, time=time or local_now.time().replace(second=0, microsecond=0), + meal=meal, product_name_snapshot=payload['title'], + portion_label_snapshot='Recipe serving', amount=consumed, + unit='servings', source='manual', created_via='recipe', **values) + entry.full_clean() + entry.save() + run.food_entry = entry + run.consumed_servings = consumed + run.food_logged_at = timezone.now() + run.save() + return run diff --git a/main/recipes/static/recipes/cooking.js b/main/recipes/static/recipes/cooking.js new file mode 100644 index 0000000..06daec9 --- /dev/null +++ b/main/recipes/static/recipes/cooking.js @@ -0,0 +1,52 @@ +(() => { + const root = document.querySelector('[data-cooking]'); + if (!root) return; + const steps = [...root.querySelectorAll('[data-step]')]; + const previous = root.querySelector('[data-previous]'); + const next = root.querySelector('[data-next]'); + const status = root.querySelector('[data-step-status]'); + const meter = root.querySelector('[data-step-progress]'); + let current = 0; + function showStep(index) { + current = Math.max(0, Math.min(index, steps.length - 1)); + steps.forEach((step, position) => { step.hidden = position !== current; }); + if (previous) previous.disabled = current === 0; + if (next) next.disabled = current === steps.length - 1; + if (status) status.textContent = `Step ${current + 1} of ${steps.length}`; + if (meter) meter.value = current + 1; + } + if (steps.length) { + showStep(0); + previous?.addEventListener('click', () => showStep(current - 1)); + next?.addEventListener('click', () => showStep(current + 1)); + } + + const wakeButton = root.querySelector('[data-wake-lock]'); + let wakeLock = null; + if (wakeButton && 'wakeLock' in navigator) { + wakeButton.hidden = false; + wakeButton.addEventListener('click', async () => { + try { + if (wakeLock) { + await wakeLock.release(); + wakeLock = null; + } else { + wakeLock = await navigator.wakeLock.request('screen'); + wakeLock.addEventListener('release', () => { + wakeLock = null; + wakeButton.setAttribute('aria-pressed', 'false'); + wakeButton.textContent = 'Keep screen awake'; + }); + } + wakeButton.setAttribute('aria-pressed', String(Boolean(wakeLock))); + wakeButton.textContent = wakeLock ? 'Allow screen to sleep' : 'Keep screen awake'; + } catch { + wakeButton.textContent = 'Screen wake lock unavailable'; + wakeButton.disabled = true; + } + }); + document.addEventListener('visibilitychange', () => { + if (document.hidden && wakeLock) wakeLock.release(); + }); + } +})(); diff --git a/main/recipes/static/recipes/recipes.css b/main/recipes/static/recipes/recipes.css index 2a1aded..1c1caba 100644 --- a/main/recipes/static/recipes/recipes.css +++ b/main/recipes/static/recipes/recipes.css @@ -20,3 +20,7 @@ body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[da .recipes-serving-form{display:flex;align-items:center;flex-wrap:wrap;gap:10px;margin-top:17px;padding:12px;border:1px solid var(--recipe-line);border-radius:10px;background:var(--recipe-soft);font-size:.8rem}.recipes-serving-form>label:first-child{font-weight:700}.recipes-serving-form input[type=number]{width:88px;min-height:40px;padding:7px;border:1px solid var(--recipe-line);border-radius:7px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-serving-form .recipes-checkbox{margin-left:auto}.recipes-serving-form .recipes-outline-button{min-height:40px}.recipes-stock-label{display:inline-block;color:var(--recipe-muted);font-size:.72rem;font-weight:700}.recipes-stock-label--available{color:#25714c}.recipes-stock-label--partial{color:#a36a19}.recipes-stock-label--missing{color:#b6413b}.recipes-stock-label--unknown{color:var(--recipe-muted)}.recipes-stock-label--optional{color:var(--recipe-muted)}.recipes-nutrition{margin:0}.recipes-nutrition>div{display:flex;align-items:start;justify-content:space-between;gap:7px;padding:8px 0;border-bottom:1px solid var(--recipe-line);font-size:.78rem}.recipes-nutrition>div:last-child{border:0}.recipes-nutrition dt{color:var(--recipe-muted)}.recipes-nutrition dd{margin:0;text-align:right;font-weight:700}.recipes-nutrition dd small{display:block;color:var(--recipe-muted);font-size:.7rem;font-weight:400}.recipes-stock-group{padding:9px 0;border-top:1px solid var(--recipe-line)}.recipes-stock-group>div:first-child{display:flex;justify-content:space-between;gap:7px;font-size:.78rem}.recipes-stock-group strong{overflow-wrap:anywhere}.recipes-stock-group small{display:block;margin:3px 0 7px;color:var(--recipe-muted);font-size:.72rem}.recipes-fill{height:8px;overflow:hidden;border-radius:999px;background:#d9e1d8}.recipes-fill span{display:block;height:100%;border-radius:inherit;background:#39845f}.recipes-preview-link{display:block;margin-top:12px;text-align:center}body[data-theme=dark] .recipes-stock-label--available{color:#9bdbab}body[data-theme=dark] .recipes-stock-label--partial{color:#f0bf6c}body[data-theme=dark] .recipes-stock-label--missing{color:#f3a09b}body[data-theme=dark] .recipes-fill{background:#3b4c40}body[data-theme=dark] .recipes-fill span{background:#6bb482} .recipes-stock-preview{max-width:1000px}.recipes-stock-preview>.recipes-panel{margin-bottom:14px}.recipes-stock-preview h2,.recipes-substitution-list h2{margin:0 0 14px;font-family:Fraunces,Georgia,serif;font-size:1.25rem}.recipes-preview-options{display:flex;align-items:end;flex-wrap:wrap;gap:14px}.recipes-preview-options>label:first-child{display:grid;gap:5px;font-size:.8rem;font-weight:700}.recipes-preview-options input[type=number],.recipes-preview-options select{min-height:42px;padding:8px;border:1px solid var(--recipe-line);border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-preview-options input[type=number]{width:100px}.recipes-preview-options .recipes-checkbox{align-self:center}.recipes-preview-choices{display:flex;flex-wrap:wrap;gap:10px;width:100%}.recipes-preview-choices label{display:grid;gap:5px;min-width:220px;font-size:.8rem}.recipes-preview-group{padding:15px 0;border-top:1px solid var(--recipe-line)}.recipes-preview-group h3{display:flex;align-items:center;gap:10px;margin:0 0 4px}.recipes-preview-group p{margin:0 0 10px;color:var(--recipe-muted);font-size:.82rem}.recipes-preview-issues{padding-left:1.3rem;color:#a36a19;font-size:.82rem}.recipes-package{margin:8px 0;padding:11px;border:1px solid var(--recipe-line);border-radius:9px;background:var(--recipe-soft)}.recipes-package__heading{display:flex;justify-content:space-between;gap:12px;font-size:.83rem}.recipes-package small{display:block;margin:4px 0 8px;color:var(--recipe-muted)}.recipes-preview-confirm p{font-size:.84rem}.recipes-substitution-list{margin-top:18px}.recipes-substitution-list>div{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 0;border-top:1px solid var(--recipe-line)}.recipes-substitute-link{margin:8px 0 0;font-size:.8rem}.recipes-substitute-link a,.recipes-stock-preview .recipes-panel a{color:var(--recipe-accent)} @media(max-width:767px){.recipes-serving-form .recipes-checkbox{margin-left:0}.recipes-serving-form .recipes-outline-button{width:100%}.recipes-preview-options .recipes-outline-button{width:100%}.recipes-preview-choices,.recipes-preview-choices label{width:100%;min-width:0}.recipes-package__heading{flex-wrap:wrap}} + +.recipes-cook-entry{margin:16px 0 0}.recipes-cook-entry .button{display:inline-flex;align-items:center;min-height:44px}.recipes-cooking,.recipes-cooking-finish{max-width:960px}.recipes-cooking-grid{display:grid;grid-template-columns:minmax(0,1.5fr) minmax(260px,1fr);gap:16px}.recipes-cooking .recipes-panel h2,.recipes-cooking-finish .recipes-panel h2{margin:0 0 12px;font-family:Fraunces,Georgia,serif;font-size:1.35rem}.recipes-cooking-heading{display:flex;align-items:start;justify-content:space-between;gap:12px}.recipes-cooking-progress{margin:4px 0 18px;color:var(--recipe-accent);font-size:.85rem;font-weight:700}.recipes-cooking-step{display:flex;align-items:start;gap:18px;min-height:180px;font-size:1.15rem;line-height:1.65}.recipes-cooking-step[hidden]{display:none}.recipes-cooking-step .recipes-markdown-source{font-size:inherit}.recipes-cooking-number{display:grid;flex:none;place-items:center;width:40px;height:40px;border-radius:50%;color:#fff;background:#235943;font-weight:700}.recipes-cooking-navigation{display:flex;justify-content:space-between;gap:12px;margin-top:18px}.recipes-cooking-navigation button{min-height:44px}.recipes-cooking-navigation button:disabled{opacity:.5;cursor:not-allowed}.recipes-cooking-ingredients ul{padding:0;margin:0;list-style:none}.recipes-cooking-ingredients li{border-bottom:1px solid var(--recipe-line)}.recipes-cooking-ingredients li:last-child{border:0}.recipes-cooking-ingredients label{display:flex;align-items:center;gap:10px;min-height:52px;font-size:.87rem}.recipes-cooking-ingredients input{flex:none;width:20px;height:20px;accent-color:var(--recipe-accent)}.recipes-cooking-ingredients span{flex:1;min-width:0}.recipes-cooking-ingredients small{display:block;color:var(--recipe-muted)}.recipes-cooking-ingredients strong{white-space:nowrap}.recipes-cooking-ingredients input:checked+span{text-decoration:line-through;color:var(--recipe-muted)}.recipes-cooking-components{margin-top:25px;border-top:1px solid var(--recipe-line)}.recipes-cooking-components h3{margin:18px 0 8px}.recipes-cooking-components details{padding:10px 0;border-bottom:1px solid var(--recipe-line)}.recipes-cooking-components summary{cursor:pointer;font-weight:700}.recipes-cooking-components .recipes-markdown-source{margin-top:12px}.recipes-cooking-footer{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-top:16px;padding:16px;border:1px solid var(--recipe-line);border-radius:12px;background:var(--recipe-surface)}.recipes-cooking-footer p{margin:0;color:var(--recipe-muted);font-size:.84rem}.recipes-cooking-finish>.recipes-panel{margin-bottom:14px}.recipes-completion-form{display:grid;gap:15px}.recipes-completion-form>p{margin:0;color:var(--recipe-muted);font-size:.85rem}.recipes-completion-choice{display:flex;align-items:start;gap:12px;padding:13px;border:1px solid var(--recipe-line);border-radius:10px;cursor:pointer}.recipes-completion-choice input{width:20px;height:20px;accent-color:var(--recipe-accent)}.recipes-completion-choice span{display:grid;gap:3px}.recipes-completion-choice small{color:var(--recipe-muted)}.recipes-completion-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.recipes-completion-fields label{display:grid;gap:5px;font-size:.82rem;font-weight:700}.recipes-completion-fields input,.recipes-completion-fields select{width:100%;min-height:44px;padding:8px;border:1px solid var(--recipe-line);border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-completion-form>.button{justify-self:start;min-height:44px} +@media(max-width:767px){.recipes-cooking-grid{grid-template-columns:1fr}.recipes-cooking-steps{min-height:300px}.recipes-cooking-step{min-height:190px}.recipes-cooking-footer .button{width:100%;text-align:center}.recipes-completion-fields{grid-template-columns:1fr}.recipes-cooking-navigation button{flex:1}} +.recipes-cooking-meter{display:block;width:100%;height:9px;margin:-9px 0 21px;accent-color:var(--recipe-accent)} diff --git a/main/recipes/templates/recipes/cook.html b/main/recipes/templates/recipes/cook.html new file mode 100644 index 0000000..bea5547 --- /dev/null +++ b/main/recipes/templates/recipes/cook.html @@ -0,0 +1,20 @@ +{% extends 'planner/base.html' %}{% load static recipe_markdown %} +{% block title %}Cook {{ recipe.title }} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %} + +
+
← Back to {{ recipe.title }}

Cook {{ recipe.title }}

{{ analysis.servings|floatformat:-2 }} servings · {{ recipe.total_minutes }} min total

+ {% if error %}{% endif %} +
+
+

Instructions

+ {% if steps %}

Step 1 of {{ steps|length }}

{% for step in steps %}
{{ step|recipe_markdown }}
{% endfor %}
{% else %}

No instructions added yet. You can still review the ingredients and finish cooking.

{% endif %} + {% if components %}

Subrecipe instructions

{% for component in components %}
{{ component.title }} · {{ component.quantity|floatformat:-3 }} {{ component.unit }}{% for step in component.steps %}
{{ forloop.counter }}. {{ step|recipe_markdown }}
{% empty %}

No instructions added to this subrecipe.

{% endfor %}
{% endfor %}
{% endif %} +
+ +
+ +
+ +{% endblock %} diff --git a/main/recipes/templates/recipes/cook_finish.html b/main/recipes/templates/recipes/cook_finish.html new file mode 100644 index 0000000..21d85ff --- /dev/null +++ b/main/recipes/templates/recipes/cook_finish.html @@ -0,0 +1,18 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Finish {{ recipe.title }} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %} + +
+
← Back to cooking

Finish cooking

{{ recipe.title }} · {{ analysis.servings|floatformat:-2 }} servings prepared

+ {% if error %}{% endif %} +

Nutrition for this recipe

Your Food Diary receives a snapshot of the portion you log. Later recipe edits do not change it.

{% for row in analysis.nutrition_rows %}
{{ row.label }}
{% if row.per_serving is not None %}{{ row.per_serving|floatformat:1 }} {{ row.unit }} / serving{% if not row.complete %}Incomplete estimate{% endif %}{% else %}— Data unavailable{% endif %}
{% endfor %}
+

Inventory preview

{% for group in analysis.groups %}

{{ group.product.product_name }} {{ group.status|capfirst }}

{{ group.stock_amount|floatformat:-3 }} {{ group.unit }} needed{% if group.plan %} · {{ group.plan.total|floatformat:-3 }} {{ group.unit }} available{% endif %}

{% if group.plan %}{% for deduction in group.plan.deductions %}
Package {{ deduction.package.api_id|stringformat:'s'|slice:':8' }}{{ deduction.before|floatformat:-3 }} → {{ deduction.after|floatformat:-3 }} {{ deduction.unit }}
Use {{ deduction.amount|floatformat:-3 }} {{ deduction.unit }}
{% endfor %}{% endif %}
{% empty %}

No matched ingredients for inventory use.

{% endfor %}{% if not analysis.stock_ready %}

Inventory use is unavailable until stock and product matches are resolved. Food logging is still available.

Review stock and substitutions{% endif %}
+ {% if confirmation %}
{% csrf_token %}

Choose what to record

These actions are separate. Cooking a recipe does not mean you ate every serving.

+ +
+ + +
{% endif %} +
+{% endblock %} diff --git a/main/recipes/templates/recipes/library.html b/main/recipes/templates/recipes/library.html index 29baec0..56c6eab 100644 --- a/main/recipes/templates/recipes/library.html +++ b/main/recipes/templates/recipes/library.html @@ -40,6 +40,7 @@

{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}

{{ selected.title }}

{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings

{% if selected.category %}{{ selected.category }}{% endif %}{% for value in selected.tags %}{{ value }}{% endfor %}
{% if selected.description %}

{{ selected.description }}

{% endif %}
+

Start cooking

{% if analysis_error %}{% endif %}

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)