Files
Django_TasksApp/main/recipes/views.py
T
2026-10-12 14:51:58 +02:00

415 lines
19 KiB
Python

import json
import uuid
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import Q
from django.http import FileResponse, Http404, HttpResponseBadRequest, JsonResponse
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
from .services.variations import create_variation as clone_variation
def _owned(user):
return Recipe.objects.filter(owner=user)
def _library(request, selected=None):
explicit_detail = selected is not None
recipes = _owned(request.user).prefetch_related('ingredients')
query = request.GET.get('q', '').strip()[:100]
category = request.GET.get('category', '').strip()[:80]
tag = request.GET.get('tag', '').strip()[:40]
favourite = request.GET.get('favourite') == '1'
if query:
recipes = recipes.filter(Q(title__icontains=query) | Q(description__icontains=query) |
Q(ingredients__name__icontains=query)).distinct()
if category:
recipes = recipes.filter(category=category)
if favourite:
recipes = recipes.filter(is_favourite=True)
recipes = list(recipes)
if tag:
recipes = [recipe for recipe in recipes if tag in recipe.tags]
recipes = recipes[:100]
if selected is None and recipes:
selected = recipes[0]
analysis = None
analysis_error = ''
last_use = None
if selected:
try:
analysis = analyze(selected, request.user, request.GET.get('servings'),
include_optional=request.GET.get('optional') == '1')
except AnalysisError as error:
analysis_error = str(error)
analysis = analyze(selected, request.user, selected.default_servings)
last_use = RecipeUse.objects.filter(user=request.user, recipe=selected, undone_at__isnull=True).first()
categories = list(_owned(request.user).exclude(category='').order_by('category')
.values_list('category', flat=True).distinct())
tags = sorted({tag for values in _owned(request.user).values_list('tags', flat=True)
for tag in values if isinstance(tag, str)})
return render(request, 'recipes/library.html', {
'recipes': recipes, 'selected': selected, 'query': query,
'category': category, 'tag': tag, 'favourite': favourite,
'categories': categories, 'tags': tags, 'explicit_detail': explicit_detail,
'analysis': analysis, 'analysis_error': analysis_error, 'last_use': last_use,
})
@login_required
def library(request):
return _library(request)
@login_required
def detail(request, identifier):
recipe = get_object_or_404(_owned(request.user).select_related('parent')
.prefetch_related('ingredients', 'subrecipes__component', 'variations'), api_id=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)
selected = {key[4:]: value for key, value in request.GET.items() if key.startswith('sub_') and value}
try:
result = analyze(recipe, request.user, request.GET.get('servings'),
include_optional=request.GET.get('optional') == '1',
substitutions=selected)
error = ''
except AnalysisError as exc:
error = str(exc)
result = analyze(recipe, request.user, recipe.default_servings)
return render(request, 'recipes/stock_preview.html', {
'recipe': recipe, 'analysis': result, 'error': error,
'confirmation': make_confirmation(result) if result['stock_ready'] and not error else '',
})
@login_required
@require_POST
def stock_confirm(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
try:
operation, created = confirm(request.user, recipe, request.POST.get('confirmation', ''))
messages.success(request, 'Recipe ingredients deducted from inventory.' if created
else 'This recipe stock use was already recorded.')
return redirect(f'{reverse("recipes:detail", args=[recipe.api_id])}?servings={operation.servings}')
except RecipeStockError as exc:
messages.error(request, str(exc))
return redirect('recipes:stock-preview', identifier=recipe.api_id)
@login_required
@require_POST
def stock_undo(request, identifier):
operation = get_object_or_404(RecipeUse, pk=identifier, user=request.user)
try:
_, reversed_now = reverse_use(request.user, operation.pk)
messages.success(request, 'Recipe stock use reversed.' if reversed_now
else 'This stock use was already reversed.')
except RecipeStockError as exc:
messages.error(request, str(exc))
return redirect('recipes:detail', identifier=operation.recipe.api_id) if operation.recipe else redirect('recipes:list')
@login_required
@require_http_methods(['GET', 'POST'])
def substitution_add(request, identifier, ingredient_id):
ingredient = get_object_or_404(RecipeIngredient, pk=ingredient_id,
recipe__api_id=identifier, recipe__owner=request.user)
form = RecipeSubstitutionForm(request.POST or None, user=request.user)
if request.method == 'POST' and form.is_valid():
substitution = form.save(commit=False)
substitution.ingredient = ingredient
substitution.full_clean()
substitution.save()
messages.success(request, 'Substitution added.')
return redirect('recipes:edit', identifier=identifier)
return render(request, 'recipes/substitution_form.html', {'recipe': ingredient.recipe,
'ingredient': ingredient, 'form': form})
@login_required
@require_POST
def substitution_delete(request, identifier, ingredient_id, substitution_id):
item = get_object_or_404(RecipeIngredientSubstitution, pk=substitution_id,
ingredient_id=ingredient_id, ingredient__recipe__api_id=identifier,
ingredient__recipe__owner=request.user)
item.delete()
messages.success(request, 'Substitution removed.')
return redirect('recipes:edit', identifier=identifier)
def _edit(request, recipe=None, allow_draft_resume=False):
creating = recipe is None or recipe.pk is None
recipe = recipe or Recipe(owner=request.user)
old_photo = recipe.photo.name if recipe.pk and recipe.photo else ''
form = RecipeForm(request.POST or None, request.FILES or None,
instance=recipe, user=request.user)
ingredients = RecipeIngredientFormSet(request.POST or None, instance=recipe,
prefix='ingredients', user=request.user)
subrecipes = RecipeSubrecipeFormSet(request.POST or None, instance=recipe,
prefix='subrecipes', user=request.user)
if request.method == 'POST' and form.is_valid() and ingredients.is_valid() and subrecipes.is_valid():
with transaction.atomic():
current = Recipe.objects.select_for_update().get(pk=recipe.pk) if not creating else None
if (current and current.markdown_revision != form.cleaned_data['markdown_revision'] and
not (allow_draft_resume and current.markdown_revision == 1 and
form.cleaned_data['markdown_revision'] == 0)):
form.add_error(None, 'This recipe changed in another tab. Reload before saving your changes.')
else:
recipe = form.save(commit=False)
recipe.owner = request.user
if form.cleaned_data['remove_photo']:
recipe.photo = ''
if current:
recipe.markdown_revision = current.markdown_revision + 1
recipe.full_clean()
recipe.save()
ingredients.instance = recipe
ingredients.save()
subrecipes.instance = recipe
subrecipes.save()
if old_photo and old_photo != recipe.photo.name:
transaction.on_commit(lambda: recipe.photo.storage.delete(old_photo))
messages.success(request, 'Recipe saved.')
return redirect('recipes:detail', identifier=recipe.api_id)
return render(request, 'recipes/form.html', {
'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe,
'creating': creating, 'new_draft_id': recipe.api_id if creating else None,
})
@login_required
@require_http_methods(['GET', 'POST'])
def create(request):
if request.method == 'POST' and request.POST.get('draft_id'):
try:
draft_id = uuid.UUID(request.POST['draft_id'])
except (ValueError, TypeError, AttributeError):
return HttpResponseBadRequest('Invalid draft ID.')
existing = Recipe.objects.filter(api_id=draft_id).first()
if existing and existing.owner_id != request.user.pk:
raise Http404
return _edit(request, existing or Recipe(owner=request.user, api_id=draft_id),
allow_draft_resume=bool(existing))
return _edit(request)
@login_required
@require_http_methods(['GET', 'POST'])
def edit(request, identifier):
return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier))
@login_required
@require_POST
def autosave(request, identifier):
try:
payload = json.loads(request.body)
revision = payload['revision']
instructions = payload['instructions_markdown']
notes = payload['notes_markdown']
title = payload['title']
except (ValueError, TypeError, KeyError):
return JsonResponse({'error': 'Invalid Markdown data.'}, status=400)
if (type(revision) is not int or revision < 0 or
not isinstance(instructions, str) or not isinstance(notes, str) or
not isinstance(title, str) or not title.strip() or len(title) > 180 or
len(instructions) > 100_000 or len(notes) > 100_000):
return JsonResponse({'error': 'Invalid Markdown data.'}, status=400)
with transaction.atomic():
recipe = get_object_or_404(_owned(request.user).select_for_update(), api_id=identifier)
if recipe.markdown_revision != revision:
return JsonResponse({'error': 'This recipe changed in another tab. Reload to continue.',
'revision': recipe.markdown_revision}, status=409)
recipe.instructions_markdown = instructions
recipe.notes_markdown = notes
recipe.title = title.strip()
recipe.markdown_revision += 1
recipe.save(update_fields=('title', 'instructions_markdown', 'notes_markdown',
'markdown_revision', 'updated_at'))
return JsonResponse({'revision': recipe.markdown_revision})
@login_required
@require_POST
def autosave_new(request):
try:
payload = json.loads(request.body)
draft_id = uuid.UUID(payload['draft_id'])
title = payload['title']
instructions = payload['instructions_markdown']
notes = payload['notes_markdown']
except (ValueError, TypeError, KeyError, AttributeError):
return JsonResponse({'error': 'Invalid draft data.'}, status=400)
if (not isinstance(title, str) or not title.strip() or len(title) > 180 or
not isinstance(instructions, str) or not isinstance(notes, str) or
len(instructions) > 100_000 or len(notes) > 100_000):
return JsonResponse({'error': 'Invalid draft data.'}, status=400)
with transaction.atomic():
recipe = Recipe.objects.select_for_update().filter(api_id=draft_id).first()
if recipe is None:
recipe = Recipe.objects.create(owner=request.user, api_id=draft_id,
title=title.strip(), instructions_markdown=instructions,
notes_markdown=notes, markdown_revision=1)
elif recipe.owner_id != request.user.pk:
return JsonResponse({'error': 'Draft not found.'}, status=404)
elif (recipe.title != title.strip() or recipe.instructions_markdown != instructions or
recipe.notes_markdown != notes):
return JsonResponse({'error': 'This draft changed. Reload to continue.'}, status=409)
return JsonResponse({'revision': recipe.markdown_revision,
'edit_url': reverse('recipes:edit', args=[recipe.api_id]),
'autosave_url': reverse('recipes:autosave', args=[recipe.api_id])})
@login_required
@require_POST
def create_variation(request, identifier):
parent = get_object_or_404(_owned(request.user).prefetch_related('ingredients', 'subrecipes'),
api_id=identifier)
variation = clone_variation(request.user, parent)
messages.success(request, 'Variation created. Edit it to make it your own.')
return redirect('recipes:edit', identifier=variation.api_id)
@login_required
@require_http_methods(['GET', 'POST'])
def delete(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
if request.method == 'POST':
if recipe.used_in_recipes.exists():
messages.error(request, 'Remove this recipe from other recipes before deleting it.')
return redirect('recipes:detail', identifier=recipe.api_id)
photo = recipe.photo.name if recipe.photo else ''
with transaction.atomic():
recipe.delete()
if photo:
transaction.on_commit(lambda: recipe.photo.storage.delete(photo))
messages.success(request, 'Recipe deleted.')
return redirect('recipes:list')
return render(request, 'recipes/delete.html', {'recipe': recipe})
@login_required
@require_POST
def toggle_favourite(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
recipe.is_favourite = not recipe.is_favourite
recipe.save(update_fields=('is_favourite', 'updated_at'))
return redirect('recipes:detail', identifier=recipe.api_id)
@login_required
def photo(request, identifier):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
if not recipe.photo:
from django.http import Http404
raise Http404
file = recipe.photo.open('rb')
image_format = Image.open(file).format
file.seek(0)
response = FileResponse(file, content_type={
'JPEG': 'image/jpeg', 'PNG': 'image/png', 'WEBP': 'image/webp',
}.get(image_format, 'application/octet-stream'))
response['Content-Disposition'] = 'inline'
response['Cache-Control'] = 'private, max-age=3600'
response['X-Content-Type-Options'] = 'nosniff'
return response