Recipes phase 2
This commit is contained in:
+136
-20
@@ -1,15 +1,18 @@
|
||||
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
|
||||
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 PIL import Image
|
||||
|
||||
from .forms import RecipeForm, RecipeIngredientFormSet
|
||||
from .models import Recipe
|
||||
from .forms import RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
|
||||
|
||||
def _owned(user):
|
||||
@@ -59,37 +62,59 @@ def detail(request, identifier):
|
||||
return _library(request, recipe)
|
||||
|
||||
|
||||
def _edit(request, recipe=None):
|
||||
creating = recipe is None
|
||||
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)
|
||||
if request.method == 'POST' and form.is_valid() and ingredients.is_valid():
|
||||
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():
|
||||
recipe = form.save(commit=False)
|
||||
recipe.owner = request.user
|
||||
if form.cleaned_data['remove_photo']:
|
||||
recipe.photo = ''
|
||||
recipe.full_clean()
|
||||
recipe.save()
|
||||
ingredients.instance = recipe
|
||||
ingredients.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)
|
||||
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, 'recipe': recipe,
|
||||
'creating': creating,
|
||||
'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)
|
||||
|
||||
|
||||
@@ -99,6 +124,97 @@ 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)
|
||||
with transaction.atomic():
|
||||
variation = Recipe.objects.create(
|
||||
owner=request.user, parent=parent, title=f'{parent.title[:160]} variation',
|
||||
description=parent.description, instructions_markdown=parent.instructions_markdown,
|
||||
notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes,
|
||||
cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings,
|
||||
category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT,
|
||||
)
|
||||
RecipeIngredient.objects.bulk_create([
|
||||
RecipeIngredient(recipe=variation, name=item.name, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order,
|
||||
inventory_product=item.inventory_product,
|
||||
nutrition_product=item.nutrition_product,
|
||||
preparation_note=item.preparation_note, is_optional=item.is_optional)
|
||||
for item in parent.ingredients.all()
|
||||
])
|
||||
RecipeSubrecipe.objects.bulk_create([
|
||||
RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity,
|
||||
unit=item.unit, display_order=item.display_order, note=item.note)
|
||||
for item in parent.subrecipes.all()
|
||||
])
|
||||
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):
|
||||
|
||||
Reference in New Issue
Block a user