Recipes phase 4

This commit is contained in:
Joren de Graaf
2026-10-12 10:00:02 +02:00
parent b0e95c62f5
commit 2a888e5346
17 changed files with 590 additions and 5 deletions
+8
View File
@@ -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
@@ -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),
),
]
+1 -1
View File
@@ -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)
+9 -2
View File
@@ -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:
@@ -12,7 +12,7 @@
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
{% endwith %}
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% 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 }})</small></div>
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% 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 %}</small></div>
</div>
<div class="food-entry-actions"><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
</li>
+5
View File
@@ -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)
@@ -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',),
},
),
]
+25 -1
View File
@@ -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',)
+128
View File
@@ -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
+52
View File
@@ -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();
});
}
})();
+4
View File
@@ -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)}
+20
View File
@@ -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 %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=5">
<div class="recipes-layout recipes-layout--form recipes-cooking" data-cooking>
<header class="recipes-form-header"><a href="{% url 'recipes:detail' recipe.api_id %}">← Back to {{ recipe.title }}</a><h1>Cook {{ recipe.title }}</h1><p>{{ analysis.servings|floatformat:-2 }} servings · {{ recipe.total_minutes }} min total</p></header>
{% if error %}<p class="recipes-form-error" role="alert">{{ error }}</p>{% endif %}
<div class="recipes-cooking-grid">
<section class="recipes-panel recipes-cooking-steps" aria-labelledby="cooking-steps-title">
<div class="recipes-cooking-heading"><h2 id="cooking-steps-title">Instructions</h2><button type="button" class="recipes-outline-button" data-wake-lock hidden aria-pressed="false">Keep screen awake</button></div>
{% if steps %}<p class="recipes-cooking-progress" data-step-status role="status" aria-live="polite">Step 1 of {{ steps|length }}</p><progress class="recipes-cooking-meter" data-step-progress value="1" max="{{ steps|length }}" aria-label="Cooking step progress"></progress><div class="recipes-cooking-step-list" data-step-list>{% for step in steps %}<article class="recipes-cooking-step" data-step><span class="recipes-cooking-number" aria-hidden="true">{{ forloop.counter }}</span><div class="recipes-markdown-source">{{ step|recipe_markdown }}</div></article>{% endfor %}</div><div class="recipes-cooking-navigation"><button type="button" class="recipes-outline-button" data-previous disabled>Previous step</button><button type="button" class="button" data-next>Next step</button></div>{% else %}<p class="recipes-muted">No instructions added yet. You can still review the ingredients and finish cooking.</p>{% endif %}
{% if components %}<div class="recipes-cooking-components"><h3>Subrecipe instructions</h3>{% for component in components %}<details><summary>{{ component.title }} · {{ component.quantity|floatformat:-3 }} {{ component.unit }}</summary>{% for step in component.steps %}<div class="recipes-markdown-source"><strong>{{ forloop.counter }}.</strong> {{ step|recipe_markdown }}</div>{% empty %}<p>No instructions added to this subrecipe.</p>{% endfor %}</details>{% endfor %}</div>{% endif %}
</section>
<aside class="recipes-panel recipes-cooking-ingredients" aria-labelledby="cooking-ingredients-title"><h2 id="cooking-ingredients-title">Ingredients</h2><p class="recipes-muted">Check ingredients as you prepare them.</p><ul>{% for line in analysis.lines %}{% if line.status != 'optional' %}<li><label><input type="checkbox"><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}</span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong></label></li>{% endif %}{% empty %}<li>No ingredients added yet.</li>{% endfor %}</ul></aside>
</div>
<div class="recipes-cooking-footer"><p>Finishing does not automatically log a meal or use inventory.</p><a class="button" href="{% url 'recipes:cook-finish' recipe.api_id %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}">Finish cooking</a></div>
</div>
<script defer src="{% static 'recipes/cooking.js' %}?v=1"></script>
{% endblock %}
@@ -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 %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=5">
<div class="recipes-layout recipes-layout--form recipes-cooking-finish">
<header class="recipes-form-header"><a href="{% url 'recipes:cook' recipe.api_id %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}">← Back to cooking</a><h1>Finish cooking</h1><p>{{ recipe.title }} · {{ analysis.servings|floatformat:-2 }} servings prepared</p></header>
{% if error %}<p class="recipes-form-error" role="alert">{{ error }}</p>{% endif %}
<section class="recipes-panel"><h2>Nutrition for this recipe</h2><p class="recipes-muted">Your Food Diary receives a snapshot of the portion you log. Later recipe edits do not change it.</p><dl class="recipes-nutrition">{% for row in analysis.nutrition_rows %}<div><dt>{{ row.label }}</dt><dd>{% if row.per_serving is not None %}{{ row.per_serving|floatformat:1 }} {{ row.unit }} / serving{% if not row.complete %}<small>Incomplete estimate</small>{% endif %}{% else %}— <small>Data unavailable</small>{% endif %}</dd></div>{% endfor %}</dl></section>
<section class="recipes-panel"><h2>Inventory preview</h2>{% for group in analysis.groups %}<div class="recipes-preview-group"><h3>{{ group.product.product_name }} <span class="recipes-stock-label recipes-stock-label--{{ group.status }}">{{ group.status|capfirst }}</span></h3><p>{{ group.stock_amount|floatformat:-3 }} {{ group.unit }} needed{% if group.plan %} · {{ group.plan.total|floatformat:-3 }} {{ group.unit }} available{% endif %}</p>{% if group.plan %}{% for deduction in group.plan.deductions %}<div class="recipes-package"><div class="recipes-package__heading"><strong>Package {{ deduction.package.api_id|stringformat:'s'|slice:':8' }}</strong><span>{{ deduction.before|floatformat:-3 }} → {{ deduction.after|floatformat:-3 }} {{ deduction.unit }}</span></div><small>Use {{ deduction.amount|floatformat:-3 }} {{ deduction.unit }}</small></div>{% endfor %}{% endif %}</div>{% empty %}<p class="recipes-muted">No matched ingredients for inventory use.</p>{% endfor %}{% if not analysis.stock_ready %}<p class="recipes-muted">Inventory use is unavailable until stock and product matches are resolved. Food logging is still available.</p><a href="{% url 'recipes:stock-preview' recipe.api_id %}?servings={{ analysis.servings }}">Review stock and substitutions</a>{% endif %}</section>
{% if confirmation %}<form method="post" class="recipes-panel recipes-completion-form">{% csrf_token %}<input type="hidden" name="confirmation" value="{{ confirmation }}"><h2>Choose what to record</h2><p>These actions are separate. Cooking a recipe does not mean you ate every serving.</p>
<label class="recipes-completion-choice"><input type="checkbox" name="log_food" value="1" checked><span><strong>Log a portion to Food Diary</strong><small>Choose how much you personally ate.</small></span></label>
<div class="recipes-completion-fields"><label>Servings eaten<input type="number" name="consumed_servings" min="0.001" max="{{ analysis.servings }}" step="0.001" value="{{ analysis.servings|floatformat:-2 }}"></label><label>Meal<select name="meal">{% for value, label in meals %}<option value="{{ value }}"{% if value == 'dinner' %} selected{% endif %}>{{ label }}</option>{% endfor %}</select></label><label>Date<input type="date" name="date" value="{{ today|date:'Y-m-d' }}"></label></div>
<label class="recipes-completion-choice"><input type="checkbox" name="deduct_stock" value="1"{% if not analysis.stock_ready %} disabled{% endif %}><span><strong>Deduct ingredients from Kitchen Inventory</strong><small>{% if analysis.stock_ready %}Use the package amounts previewed above.{% else %}Resolve inventory checks first.{% endif %}</small></span></label>
<button class="button" type="submit">Confirm selected actions</button>
</form>{% endif %}
</div>
{% endblock %}
@@ -40,6 +40,7 @@
<div class="recipes-hero__copy"><p class="recipes-eyebrow">{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}</p><h2>{{ selected.title }}</h2><p class="recipes-hero__meta">{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings</p><div class="recipes-chips">{% if selected.category %}<span>{{ selected.category }}</span>{% endif %}{% for value in selected.tags %}<span>{{ value }}</span>{% endfor %}</div>{% if selected.description %}<p class="recipes-hero__description">{{ selected.description }}</p>{% endif %}</div>
</div>
<form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form>
<p class="recipes-cook-entry"><a class="button" href="{% url 'recipes:cook' selected.api_id %}?servings={{ analysis.servings }}{% if analysis.include_optional %}&amp;optional=1{% endif %}">Start cooking</a></p>
{% if analysis_error %}<p class="recipes-form-error" role="alert">{{ analysis_error }}</p>{% endif %}
<div class="recipes-content-grid">
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for line in analysis.lines %}<li><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}{% if line.ingredient.preparation_note %}<small>{{ line.ingredient.preparation_note }}</small>{% endif %}<small class="recipes-stock-label recipes-stock-label--{{ line.status }}">{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}</small></span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong>{% if line.optional %}<em>Optional{% if not analysis.include_optional %} · excluded{% endif %}</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
+173
View File
@@ -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')
+2
View File
@@ -10,6 +10,8 @@ urlpatterns = [
path('new/autosave/', views.autosave_new, name='autosave-new'),
path('<uuid:identifier>/', views.detail, name='detail'),
path('<uuid:identifier>/edit/', views.edit, name='edit'),
path('<uuid:identifier>/cook/', views.cook, name='cook'),
path('<uuid:identifier>/cook/finish/', views.cook_finish, name='cook-finish'),
path('<uuid:identifier>/autosave/', views.autosave, name='autosave'),
path('<uuid:identifier>/variations/new/', views.create_variation, name='create-variation'),
path('<uuid:identifier>/stock/', views.stock_preview, name='stock-preview'),
+85
View File
@@ -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)