diff --git a/main/planner/templates/planner/base.html b/main/planner/templates/planner/base.html index f0f9541..caeb121 100644 --- a/main/planner/templates/planner/base.html +++ b/main/planner/templates/planner/base.html @@ -24,6 +24,7 @@ Daily planner Health Food + Recipes Kitchen Inventory Settings
{% csrf_token %}{% if user_appearance == 'dark' %}{% else %}{% endif %}
@@ -36,7 +37,7 @@ -
+
{% if messages %}{% for message in messages %}

{{ message }}

{% endfor %}{% endif %} {% block content %}{% endblock %}
diff --git a/main/recipes/__init__.py b/main/recipes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/recipes/admin.py b/main/recipes/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/main/recipes/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/main/recipes/apps.py b/main/recipes/apps.py new file mode 100644 index 0000000..076e356 --- /dev/null +++ b/main/recipes/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class RecipesConfig(AppConfig): + name = 'recipes' diff --git a/main/recipes/forms.py b/main/recipes/forms.py new file mode 100644 index 0000000..28a004e --- /dev/null +++ b/main/recipes/forms.py @@ -0,0 +1,96 @@ +from django import forms +from django.forms import BaseInlineFormSet, inlineformset_factory +from django.core.files.uploadedfile import UploadedFile +from PIL import Image, UnidentifiedImageError + +from food.models import FoodProduct +from .models import Recipe, RecipeIngredient + + +class RecipeForm(forms.ModelForm): + tags_text = forms.CharField(required=False, label='Tags', + help_text='Separate tags with commas.') + remove_photo = forms.BooleanField(required=False, label='Remove current photo') + + class Meta: + model = Recipe + fields = ('title', 'description', 'category', 'preparation_minutes', + 'cooking_minutes', 'default_servings', 'status', 'parent', + 'instructions_markdown', 'notes_markdown', 'photo') + labels = {'instructions_markdown': 'Instructions (Markdown)', + 'notes_markdown': 'Personal notes (Markdown)', + 'default_servings': 'Servings', 'parent': 'Variation of'} + widgets = { + 'description': forms.Textarea(attrs={'rows': 3}), + 'instructions_markdown': forms.Textarea(attrs={'rows': 10}), + 'notes_markdown': forms.Textarea(attrs={'rows': 4}), + 'photo': forms.ClearableFileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}), + 'preparation_minutes': forms.NumberInput(attrs={'min': 0}), + 'cooking_minutes': forms.NumberInput(attrs={'min': 0}), + 'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}), + } + + def __init__(self, *args, user, **kwargs): + super().__init__(*args, **kwargs) + self.fields['parent'].queryset = Recipe.objects.filter(owner=user).exclude(pk=self.instance.pk) + if self.instance.pk: + self.fields['tags_text'].initial = ', '.join(self.instance.tags) + + def clean_tags_text(self): + tags = [tag.strip() for tag in self.cleaned_data['tags_text'].split(',') if tag.strip()] + if len(tags) > 12 or any(len(tag) > 40 for tag in tags): + raise forms.ValidationError('Use up to 12 tags of at most 40 characters each.') + return list(dict.fromkeys(tags)) + + def clean_photo(self): + photo = self.cleaned_data.get('photo') + if not isinstance(photo, UploadedFile): + return photo + if photo.size > 5 * 1024 * 1024: + raise forms.ValidationError('Choose an image smaller than 5 MB.') + if photo.content_type not in ('image/jpeg', 'image/png', 'image/webp'): + raise forms.ValidationError('Choose a JPEG, PNG, or WebP image.') + try: + image = Image.open(photo) + if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 25_000_000: + raise forms.ValidationError('Choose a valid image smaller than 25 megapixels.') + image.verify() + except (UnidentifiedImageError, OSError): + raise forms.ValidationError('Choose a valid JPEG, PNG, or WebP image.') from None + finally: + photo.seek(0) + return photo + + def save(self, commit=True): + recipe = super().save(commit=False) + recipe.tags = self.cleaned_data['tags_text'] + if commit: + recipe.save() + return recipe + + +class RecipeIngredientForm(forms.ModelForm): + class Meta: + model = RecipeIngredient + fields = ('name', 'quantity', 'unit', 'preparation_note', 'is_optional', + 'inventory_product', 'nutrition_product', 'display_order') + widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), + 'display_order': forms.NumberInput(attrs={'min': 0})} + + +class OwnedIngredientFormSet(BaseInlineFormSet): + def __init__(self, *args, user, **kwargs): + self.user = user + super().__init__(*args, **kwargs) + + def add_fields(self, form, index): + super().add_fields(form, index) + products = FoodProduct.objects.filter(owner=self.user).order_by('product_name') + for name in ('inventory_product', 'nutrition_product'): + form.fields[name].queryset = products + + +RecipeIngredientFormSet = inlineformset_factory( + Recipe, RecipeIngredient, form=RecipeIngredientForm, + formset=OwnedIngredientFormSet, extra=2, can_delete=True, +) diff --git a/main/recipes/migrations/0001_initial.py b/main/recipes/migrations/0001_initial.py new file mode 100644 index 0000000..0bba537 --- /dev/null +++ b/main/recipes/migrations/0001_initial.py @@ -0,0 +1,108 @@ +# Generated by Django 6.1.1 on 2026-10-11 18:51 + +import django.core.validators +import django.db.models.deletion +import uuid +from decimal import Decimal +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('food', '0009_backfill_food_hydration'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Recipe', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('api_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + ('title', models.CharField(max_length=180)), + ('description', models.TextField(blank=True)), + ('instructions_markdown', models.TextField(blank=True)), + ('notes_markdown', models.TextField(blank=True)), + ('photo', models.ImageField(blank=True, upload_to='recipes/%Y/%m/')), + ('preparation_minutes', models.PositiveIntegerField(default=0)), + ('cooking_minutes', models.PositiveIntegerField(default=0)), + ('default_servings', models.DecimalField(decimal_places=2, default=2, max_digits=7, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))])), + ('category', models.CharField(blank=True, max_length=80)), + ('tags', models.JSONField(blank=True, default=list)), + ('is_favourite', models.BooleanField(default=False)), + ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=12)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('copied_from', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='copies', to='recipes.recipe')), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipes', to=settings.AUTH_USER_MODEL)), + ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='variations', to='recipes.recipe')), + ], + options={ + 'ordering': ('-updated_at', '-pk'), + }, + ), + migrations.CreateModel( + name='RecipeIngredient', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=180)), + ('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])), + ('unit', models.CharField(choices=[('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('pieces', 'pieces'), ('tsp', 'tsp'), ('tbsp', 'tbsp'), ('portions', 'portions')], max_length=10)), + ('display_order', models.PositiveIntegerField(default=0)), + ('preparation_note', models.CharField(blank=True, max_length=255)), + ('is_optional', models.BooleanField(default=False)), + ('inventory_product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_inventory_ingredients', to='food.foodproduct')), + ('nutrition_product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_nutrition_ingredients', to='food.foodproduct')), + ('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ingredients', to='recipes.recipe')), + ], + options={ + 'ordering': ('display_order', 'pk'), + }, + ), + migrations.CreateModel( + name='RecipeIngredientSubstitution', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=180)), + ('quantity', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])), + ('unit', models.CharField(choices=[('g', 'g'), ('kg', 'kg'), ('ml', 'ml'), ('L', 'L'), ('pieces', 'pieces'), ('tsp', 'tsp'), ('tbsp', 'tbsp'), ('portions', 'portions')], max_length=10)), + ('display_order', models.PositiveIntegerField(default=0)), + ('ingredient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='substitutions', to='recipes.recipeingredient')), + ('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='recipe_substitutions', to='food.foodproduct')), + ], + options={ + 'ordering': ('display_order', 'pk'), + }, + ), + migrations.CreateModel( + name='RecipeSubrecipe', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('quantity', models.DecimalField(decimal_places=3, default=1, max_digits=10, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))])), + ('unit', models.CharField(choices=[('servings', 'servings'), ('g', 'g'), ('ml', 'ml')], default='servings', max_length=16)), + ('display_order', models.PositiveIntegerField(default=0)), + ('note', models.CharField(blank=True, max_length=255)), + ('component', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='used_in_recipes', to='recipes.recipe')), + ('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subrecipes', to='recipes.recipe')), + ], + options={ + 'ordering': ('display_order', 'pk'), + }, + ), + migrations.AddConstraint( + model_name='recipe', + constraint=models.CheckConstraint(condition=models.Q(('default_servings__gt', 0)), name='recipes_positive_servings'), + ), + migrations.AddConstraint( + model_name='recipeingredient', + constraint=models.CheckConstraint(condition=models.Q(('quantity__gt', 0)), name='recipes_positive_ingredient_quantity'), + ), + migrations.AddConstraint( + model_name='recipesubrecipe', + constraint=models.UniqueConstraint(fields=('recipe', 'component'), name='recipes_unique_component'), + ), + ] diff --git a/main/recipes/migrations/__init__.py b/main/recipes/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/recipes/models.py b/main/recipes/models.py new file mode 100644 index 0000000..12679cd --- /dev/null +++ b/main/recipes/models.py @@ -0,0 +1,168 @@ +"""Owned, structured recipes. Calculations and cooking workflows arrive in later passes.""" + +import uuid +from decimal import Decimal + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.validators import MinValueValidator +from django.db import models +from django.db.models import Q + + +class Recipe(models.Model): + class Status(models.TextChoices): + DRAFT = 'draft', 'Draft' + PUBLISHED = 'published', 'Published' + + api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) + owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, + related_name='recipes') + title = models.CharField(max_length=180) + description = models.TextField(blank=True) + instructions_markdown = models.TextField(blank=True) + notes_markdown = models.TextField(blank=True) + photo = models.ImageField(upload_to='recipes/%Y/%m/', blank=True) + preparation_minutes = models.PositiveIntegerField(default=0) + cooking_minutes = models.PositiveIntegerField(default=0) + default_servings = models.DecimalField(max_digits=7, decimal_places=2, default=2, + validators=[MinValueValidator(Decimal('0.01'))]) + category = models.CharField(max_length=80, blank=True) + tags = models.JSONField(default=list, blank=True) + is_favourite = models.BooleanField(default=False) + status = models.CharField(max_length=12, choices=Status.choices, default=Status.DRAFT) + parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, + related_name='variations') + copied_from = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, + related_name='copies') + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + ordering = ('-updated_at', '-pk') + constraints = [models.CheckConstraint(condition=Q(default_servings__gt=0), + name='recipes_positive_servings')] + + @property + def total_minutes(self): + return self.preparation_minutes + self.cooking_minutes + + def clean(self): + super().clean() + if not isinstance(self.tags, list) or any(not isinstance(tag, str) for tag in self.tags): + raise ValidationError({'tags': 'Tags must be a list of names.'}) + if self.parent_id: + if self.parent_id == self.pk: + raise ValidationError({'parent': 'A recipe cannot be its own variation.'}) + if self.owner_id and self.parent.owner_id != self.owner_id: + raise ValidationError({'parent': 'Choose one of your own recipes.'}) + seen = {self.pk} + cursor = self.parent + while cursor: + if cursor.pk in seen: + raise ValidationError({'parent': 'Variations cannot form a cycle.'}) + seen.add(cursor.pk) + cursor = cursor.parent + if self.copied_from_id and self.owner_id and self.copied_from.owner_id != self.owner_id: + raise ValidationError({'copied_from': 'Choose one of your own recipes.'}) + + def __str__(self): + return self.title + + +class RecipeIngredient(models.Model): + class Unit(models.TextChoices): + GRAM = 'g', 'g' + KILOGRAM = 'kg', 'kg' + MILLILITRE = 'ml', 'ml' + LITRE = 'L', 'L' + PIECE = 'pieces', 'pieces' + TEASPOON = 'tsp', 'tsp' + TABLESPOON = 'tbsp', 'tbsp' + PORTION = 'portions', 'portions' + + recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') + name = models.CharField(max_length=180) + quantity = models.DecimalField(max_digits=10, decimal_places=3, + validators=[MinValueValidator(Decimal('0.001'))]) + unit = models.CharField(max_length=10, choices=Unit.choices) + display_order = models.PositiveIntegerField(default=0) + inventory_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, + null=True, blank=True, related_name='recipe_inventory_ingredients') + nutrition_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, + null=True, blank=True, related_name='recipe_nutrition_ingredients') + preparation_note = models.CharField(max_length=255, blank=True) + is_optional = models.BooleanField(default=False) + + class Meta: + ordering = ('display_order', 'pk') + constraints = [models.CheckConstraint(condition=Q(quantity__gt=0), + name='recipes_positive_ingredient_quantity')] + + def clean(self): + super().clean() + if self.recipe_id: + for field in ('inventory_product', 'nutrition_product'): + product = getattr(self, field) + if product and product.owner_id != self.recipe.owner_id: + raise ValidationError({field: 'Choose one of your own food products.'}) + + def __str__(self): + return f'{self.quantity} {self.unit} {self.name}' + + +class RecipeSubrecipe(models.Model): + recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='subrecipes') + component = models.ForeignKey(Recipe, on_delete=models.PROTECT, related_name='used_in_recipes') + quantity = models.DecimalField(max_digits=10, decimal_places=3, default=1, + validators=[MinValueValidator(Decimal('0.001'))]) + unit = models.CharField(max_length=16, default='servings', choices=[ + ('servings', 'servings'), ('g', 'g'), ('ml', 'ml')]) + display_order = models.PositiveIntegerField(default=0) + note = models.CharField(max_length=255, blank=True) + + class Meta: + ordering = ('display_order', 'pk') + constraints = [models.UniqueConstraint(fields=('recipe', 'component'), + name='recipes_unique_component')] + + def clean(self): + super().clean() + if self.recipe_id and self.component_id: + if self.recipe.owner_id != self.component.owner_id: + raise ValidationError({'component': 'Choose one of your own recipes.'}) + if self.recipe_id == self.component_id: + raise ValidationError({'component': 'A recipe cannot contain itself.'}) + seen = set() + pending = [self.component_id] + while pending: + current = pending.pop() + if current == self.recipe_id: + raise ValidationError({'component': 'Subrecipes cannot form a cycle.'}) + if current not in seen: + seen.add(current) + pending.extend(RecipeSubrecipe.objects.filter(recipe_id=current) + .exclude(pk=self.pk).values_list('component_id', flat=True)) + + def __str__(self): + return f'{self.recipe} includes {self.component}' + + +class RecipeIngredientSubstitution(models.Model): + ingredient = models.ForeignKey(RecipeIngredient, on_delete=models.CASCADE, + related_name='substitutions') + name = models.CharField(max_length=180) + quantity = models.DecimalField(max_digits=10, decimal_places=3, + validators=[MinValueValidator(Decimal('0.001'))]) + unit = models.CharField(max_length=10, choices=RecipeIngredient.Unit.choices) + product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL, + null=True, blank=True, related_name='recipe_substitutions') + display_order = models.PositiveIntegerField(default=0) + + class Meta: + ordering = ('display_order', 'pk') + + def clean(self): + super().clean() + if self.product_id and self.ingredient_id and self.product.owner_id != self.ingredient.recipe.owner_id: + raise ValidationError({'product': 'Choose one of your own food products.'}) diff --git a/main/recipes/static/recipes/form.js b/main/recipes/static/recipes/form.js new file mode 100644 index 0000000..011368d --- /dev/null +++ b/main/recipes/static/recipes/form.js @@ -0,0 +1,17 @@ +(() => { + const button = document.querySelector('[data-add-ingredient]'); + const container = document.querySelector('[data-ingredient-forms]'); + const template = document.querySelector('#recipe-empty-ingredient'); + const total = document.querySelector('#id_ingredients-TOTAL_FORMS'); + if (!button || !container || !template || !total) return; + button.addEventListener('click', () => { + const index = Number(total.value); + const wrapper = document.createElement('div'); + wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', String(index)); + const row = wrapper.firstElementChild; + if (!row) return; + container.appendChild(row); + total.value = String(index + 1); + row.querySelector('input[name$="-name"]')?.focus(); + }); +})(); diff --git a/main/recipes/static/recipes/recipes.css b/main/recipes/static/recipes/recipes.css new file mode 100644 index 0000000..bcc2b17 --- /dev/null +++ b/main/recipes/static/recipes/recipes.css @@ -0,0 +1,14 @@ +.page-content.recipes-page-content{max-width:1600px;padding:28px clamp(16px,3vw,32px) 72px} +.recipes-layout{--recipe-surface:#fff;--recipe-line:#e4e8e2;--recipe-ink:#25292e;--recipe-muted:#687178;--recipe-soft:#f5f7f3;--recipe-accent:#235943;display:grid;grid-template-columns:minmax(260px,340px) minmax(0,1fr) minmax(245px,290px);gap:20px;align-items:start;width:100%;max-width:1600px;margin-inline:auto;color:var(--recipe-ink)} +.recipes-layout *{box-sizing:border-box}.recipes-layout a:focus-visible,.recipes-layout button:focus-visible,.recipes-layout input:focus-visible,.recipes-layout select:focus-visible,.recipes-layout textarea:focus-visible,.recipes-layout summary:focus-visible{outline:3px solid #77b68b;outline-offset:3px} +.recipes-browser,.recipes-detail,.recipes-info{min-width:0}.recipes-browser__heading{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin:0 0 18px}.recipes-browser__heading h1{margin:0 0 2px;font-size:2.35rem}.recipes-browser__heading p{margin:0;color:var(--recipe-muted);font-size:.85rem}.recipes-new{flex:none;min-height:42px;margin-top:4px;padding-inline:14px;white-space:nowrap} +.recipes-filters{display:grid;gap:12px;margin:0 0 16px}.recipes-filters>label:first-child{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)}.recipes-search-row{display:flex;gap:7px}.recipes-search-row input{flex:1;min-width:0}.recipes-search-row button,.recipes-filter-apply,.recipes-outline-button{min-height:42px;padding:8px 12px;border:1px solid #d7dcd5;border-radius:9px;color:var(--recipe-ink);background:var(--recipe-surface);font-size:.81rem;font-weight:700;text-decoration:none}.recipes-search-row button:hover,.recipes-filter-apply:hover,.recipes-outline-button:hover{border-color:var(--recipe-accent);color:var(--recipe-accent)}.recipes-search-row input,.recipes-filter-grid select{width:100%;min-height:42px;padding:9px 11px;border:1px solid #d7dcd5;border-radius:9px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-filter-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}.recipes-filter-grid label{min-width:0;color:var(--recipe-muted);font-size:.75rem;font-weight:700}.recipes-filter-grid select{margin-top:4px}.recipes-favourite-filter{display:flex;align-items:center;gap:7px;color:var(--recipe-ink);font-size:.82rem}.recipes-favourite-filter input{width:17px;height:17px;accent-color:var(--recipe-accent)}.recipes-filter-apply{justify-self:start} +.recipes-list{display:grid;gap:8px}.recipes-list-item{display:flex;align-items:center;gap:11px;min-height:86px;padding:9px;border:1px solid var(--recipe-line);border-radius:13px;color:inherit;background:var(--recipe-surface);text-decoration:none}.recipes-list-item:hover,.recipes-list-item--selected{border-color:#69a581;background:#f8fcf8}.recipes-list-item__image,.recipes-list-item__placeholder{flex:none;width:68px;height:68px;border-radius:9px;object-fit:cover}.recipes-list-item__placeholder{display:grid;place-items:center;color:#3f6954;background:#e1eee5;font-family:Fraunces,Georgia,serif;font-size:.72rem;font-weight:700}.recipes-list-item__body{display:grid;gap:1px;min-width:0}.recipes-list-item__body strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:Fraunces,Georgia,serif;font-size:.96rem;line-height:1.2}.recipes-list-item__body small{color:var(--recipe-muted);font-size:.73rem}.recipes-list-item__tags,.recipes-chips{display:flex;flex-wrap:wrap;gap:5px;margin-top:4px}.recipes-list-item__tags span,.recipes-chips span{padding:3px 8px;border-radius:999px;background:#eef1ed;font-size:.7rem}.recipes-list-item__favourite{align-self:flex-start;margin-left:auto;color:#bd4e48;font-size:1rem}.recipes-empty-list{padding:24px;border:1px dashed var(--recipe-line);border-radius:13px;background:var(--recipe-surface)}.recipes-empty-list p{margin:0 0 8px}.recipes-empty-list a{color:var(--recipe-accent)} +.recipes-detail{min-height:560px;padding:20px;border:1px solid var(--recipe-line);border-radius:17px;background:var(--recipe-surface);box-shadow:0 12px 35px rgba(29,43,37,.045)}.recipes-detail__top{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 17px}.recipes-back{color:var(--recipe-accent);font-size:.8rem;font-weight:700;text-decoration:none}.recipes-back:hover{text-decoration:underline}.recipes-detail__top-actions{display:flex;align-items:center;gap:7px}.recipes-detail__top-actions form{margin:0}.recipes-heart{display:grid;place-items:center;width:42px;height:42px;padding:0;border:0;color:#bd4e48;background:transparent;font-size:1.6rem}.recipes-hero{display:grid;grid-template-columns:minmax(180px,42%) minmax(0,1fr);gap:22px;align-items:start;padding-bottom:21px;border-bottom:1px solid var(--recipe-line)}.recipes-hero>img,.recipes-photo-placeholder{display:block;width:100%;height:220px;border-radius:12px;object-fit:cover}.recipes-photo-placeholder{display:grid;place-items:center;border:1px dashed #acc8b4;color:#466c54;background:#e5f1e8;font-family:Fraunces,Georgia,serif}.recipes-hero__copy{min-width:0}.recipes-eyebrow{margin:0 0 4px;color:var(--recipe-accent);font-size:.7rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase}.recipes-hero h2{margin:0 0 9px;font-size:clamp(1.8rem,2.6vw,2.7rem);line-height:1.12}.recipes-hero__meta{margin:0;color:var(--recipe-muted);font-size:.85rem}.recipes-chips{margin-top:11px}.recipes-chips span{padding:5px 10px;font-size:.73rem}.recipes-hero__description{margin:14px 0 0;color:var(--recipe-muted);font-size:.88rem;line-height:1.6}.recipes-content-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px;margin-top:18px}.recipes-content-stack{display:grid;gap:12px;align-content:start}.recipes-panel{min-width:0;padding:17px;border:1px solid var(--recipe-line);border-radius:13px;background:var(--recipe-surface)}.recipes-panel h3{margin:0 0 13px;font-family:Fraunces,Georgia,serif;font-size:1.05rem}.recipes-ingredient-list{padding:0;margin:0;list-style:none}.recipes-ingredient-list li{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 12px;padding:10px 0;border-bottom:1px solid var(--recipe-line);font-size:.83rem}.recipes-ingredient-list li:last-child{border-bottom:0}.recipes-ingredient-list small{display:block;color:var(--recipe-muted)}.recipes-ingredient-list strong{white-space:nowrap;font-weight:700}.recipes-ingredient-list em{width:100%;color:var(--recipe-muted);font-size:.72rem}.recipes-markdown-source{overflow-wrap:anywhere;font-size:.86rem;line-height:1.65}.recipes-muted{color:var(--recipe-muted);font-size:.84rem}.recipes-empty-detail{display:grid;align-content:center;justify-items:start;min-height:490px;max-width:470px;margin:auto}.recipes-empty-detail h2{margin:0 0 9px;font-size:2rem}.recipes-empty-detail p{color:var(--recipe-muted)} +.recipes-info{display:grid;gap:12px}.recipes-info .recipes-panel{padding:18px}.recipes-facts{margin:0}.recipes-facts div{display:flex;justify-content:space-between;gap:8px;padding:8px 0;border-bottom:1px solid var(--recipe-line);font-size:.82rem}.recipes-facts div:last-child{border-bottom:0}.recipes-facts dt{color:var(--recipe-muted)}.recipes-facts dd{margin:0;font-weight:700}.recipes-info p{margin:0 0 9px;font-size:.82rem}.recipes-info p:last-child{margin-bottom:0}.recipes-info a:not(.recipes-action){color:var(--recipe-accent)}.recipes-action{display:block;padding:9px 0;border-bottom:1px solid var(--recipe-line);font-size:.84rem;text-decoration:none}.recipes-action:last-child{border:0}.recipes-action--danger{color:#b6413b} +.recipes-layout--form{display:block;max-width:1100px}.recipes-form-header{margin:0 0 23px}.recipes-form-header>a{color:var(--recipe-accent);font-size:.85rem;font-weight:700}.recipes-form-header h1{margin:8px 0 4px;font-size:2.7rem}.recipes-form-header p{margin:0;color:var(--recipe-muted)}.recipes-edit-card{display:grid;gap:28px;padding:24px;border:1px solid var(--recipe-line);border-radius:17px;background:var(--recipe-surface)}.recipes-edit-card section+section{padding-top:24px;border-top:1px solid var(--recipe-line)}.recipes-edit-card h2{margin:0 0 16px;font-size:1.25rem}.recipes-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.recipes-field{min-width:0}.recipes-field label:not(.recipes-checkbox){display:block;margin:0 0 5px;font-size:.81rem;font-weight:700}.recipes-field input:not([type=checkbox]),.recipes-field textarea,.recipes-field select{width:100%;min-height:43px;padding:9px 10px;border:1px solid #cbd3cb;border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-field textarea{min-height:94px;resize:vertical}.recipes-field small{display:block;margin-top:4px;color:var(--recipe-muted);font-size:.73rem}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:1/-1}.recipes-field--photo input{height:auto}.recipes-checkbox{display:inline-flex;align-items:center;gap:7px;font-size:.8rem}.recipes-checkbox input{width:17px;height:17px;accent-color:var(--recipe-accent)}.recipes-current-photo{display:block;width:170px;max-height:120px;margin:0 0 9px;border-radius:9px;object-fit:cover}.recipes-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.recipes-section-heading h2{margin:0 0 2px}.recipes-section-heading p{margin:0;color:var(--recipe-muted);font-size:.8rem}.recipes-ingredient-forms{display:grid;gap:12px}.recipes-ingredient-form{padding:14px;border:1px solid var(--recipe-line);border-radius:12px;background:var(--recipe-soft)}.recipes-ingredient-form__main{display:grid;grid-template-columns:minmax(0,1fr) 110px 120px;gap:10px}.recipes-ingredient-form__more{margin-top:9px}.recipes-ingredient-form__more summary{color:var(--recipe-accent);font-size:.8rem;cursor:pointer}.recipes-ingredient-form__more .recipes-form-grid{padding-top:12px}.recipes-form-error,.recipes-field .errorlist{margin:7px 0;color:#b6413b;font-size:.8rem}.recipes-form-actions{display:flex;align-items:center;gap:20px;padding-top:19px;border-top:1px solid var(--recipe-line)}.recipes-form-actions>a,.recipes-delete a{color:var(--recipe-accent)}.recipes-delete{max-width:620px}.recipes-delete h1{font-size:2.3rem}.recipes-delete form{display:flex;align-items:center;gap:20px} +body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#435046;--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-soft:#29352d;--recipe-accent:#a7d9b6}body[data-theme=dark] .recipes-list-item:hover,body[data-theme=dark] .recipes-list-item--selected{background:#2a3b30}body[data-theme=dark] .recipes-list-item__placeholder,body[data-theme=dark] .recipes-photo-placeholder{color:#b8e4c5;background:#314d39;border-color:#5d8968}body[data-theme=dark] .recipes-list-item__tags span,body[data-theme=dark] .recipes-chips span{background:#354339}body[data-theme=dark] .recipes-search-row button,body[data-theme=dark] .recipes-filter-apply,body[data-theme=dark] .recipes-outline-button,body[data-theme=dark] .recipes-search-row input,body[data-theme=dark] .recipes-filter-grid select,body[data-theme=dark] .recipes-field input:not([type=checkbox]),body[data-theme=dark] .recipes-field textarea,body[data-theme=dark] .recipes-field select{border-color:#526055;background:var(--recipe-surface);color:var(--recipe-ink)} +@media(max-width:1399px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(260px,320px) minmax(0,1fr)}.recipes-info{grid-column:2;grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:1/-1}.recipes-hero{grid-template-columns:minmax(170px,40%) minmax(0,1fr)}} +@media(max-width:991px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(0,1fr)}.recipes-browser,.recipes-detail,.recipes-info{grid-column:1}.recipes-list{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-hero{grid-template-columns:minmax(170px,38%) minmax(0,1fr)}.recipes-info{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:auto}} +@media(max-width:767px){.page-content.recipes-page-content{padding-top:25px}.recipes-layout--list .recipes-detail,.recipes-layout--list .recipes-info{display:none}.recipes-layout--detail .recipes-browser{display:none}.recipes-browser__heading h1{font-size:2.4rem}.recipes-detail{padding:16px}.recipes-hero{grid-template-columns:1fr;gap:15px}.recipes-hero>img,.recipes-photo-placeholder{height:230px}.recipes-hero h2{font-size:2rem}.recipes-content-grid,.recipes-info{grid-template-columns:1fr}.recipes-list{grid-template-columns:1fr}.recipes-form-grid{grid-template-columns:1fr}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:auto}.recipes-ingredient-form__main{grid-template-columns:minmax(0,1fr) minmax(90px,1fr)}.recipes-ingredient-form__main .recipes-field:first-child{grid-column:1/-1}.recipes-edit-card{padding:18px}.recipes-section-heading{align-items:flex-start;flex-wrap:wrap}.recipes-section-heading button{width:100%}} +@media(max-width:400px){.recipes-browser__heading{display:block}.recipes-new{margin-top:12px}.recipes-filter-grid{grid-template-columns:1fr}.recipes-detail__top{flex-wrap:wrap}.recipes-ingredient-form__main{grid-template-columns:1fr 1fr}} diff --git a/main/recipes/templates/recipes/delete.html b/main/recipes/templates/recipes/delete.html new file mode 100644 index 0000000..b580a25 --- /dev/null +++ b/main/recipes/templates/recipes/delete.html @@ -0,0 +1,4 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Delete {{ recipe.title }} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %}

Delete {{ recipe.title }}?

This removes the recipe and its ingredients. This action cannot be undone.

{% csrf_token %}Cancel
{% endblock %} diff --git a/main/recipes/templates/recipes/form.html b/main/recipes/templates/recipes/form.html new file mode 100644 index 0000000..d07f410 --- /dev/null +++ b/main/recipes/templates/recipes/form.html @@ -0,0 +1,11 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %} +
← Back to recipes

{% if creating %}New recipe{% else %}Edit recipe{% endif %}

Keep ingredients structured and instructions in Markdown.

+
{% csrf_token %} + {% if form.non_field_errors %}{% endif %} +

Recipe details

{% for field in form %}{% if field.name != 'remove_photo' %}
{{ field }}{% if field.help_text %}{{ field.help_text }}{% endif %}{% if field.errors %}{% endif %}
{% endif %}{% endfor %}{% if recipe.photo %}
Current recipe photo
{% endif %}
+

Ingredients

Add measured ingredients now; product matching can be refined later.

{{ ingredients.management_form }}{% if ingredients.non_form_errors %}{% endif %}
{% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}
+
Cancel
+
{% endblock %} diff --git a/main/recipes/templates/recipes/ingredient_row.html b/main/recipes/templates/recipes/ingredient_row.html new file mode 100644 index 0000000..1ad6e63 --- /dev/null +++ b/main/recipes/templates/recipes/ingredient_row.html @@ -0,0 +1,6 @@ +
+ {% for hidden in ingredient.hidden_fields %}{{ hidden }}{% endfor %} +
{{ ingredient.name }}{{ ingredient.name.errors }}
{{ ingredient.quantity }}{{ ingredient.quantity.errors }}
{{ ingredient.unit }}{{ ingredient.unit.errors }}
+
Ingredient details
{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}
{{ ingredient.display_order }}{{ ingredient.display_order.errors }}
{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}
{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}
{% if ingredient.DELETE %}{% endif %}
+ {% if ingredient.non_field_errors %}{% endif %} +
diff --git a/main/recipes/templates/recipes/library.html b/main/recipes/templates/recipes/library.html new file mode 100644 index 0000000..df847d1 --- /dev/null +++ b/main/recipes/templates/recipes/library.html @@ -0,0 +1,57 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Recipes · Tasknest{% endblock %} +{% block page_class %}recipes-page-content{% endblock %} +{% block content %} + +
+ + +
+ {% if selected %} +
← Back to recipes
{% csrf_token %}
Edit
+
+ {% if selected.photo %}Photo of {{ selected.title }}{% else %}{% endif %} +

{% 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 %}
+
+
+

Ingredients

    {% for ingredient in selected.ingredients.all %}
  • {{ ingredient.name }}{% if ingredient.preparation_note %}{{ ingredient.preparation_note }}{% endif %}{{ ingredient.quantity|floatformat:-3 }} {{ ingredient.unit }}{% if ingredient.is_optional %}Optional{% endif %}
  • {% empty %}
  • No ingredients added yet.
  • {% endfor %}
+

Instructions

{% if selected.instructions_markdown %}
{{ selected.instructions_markdown|linebreaksbr }}
{% else %}

No instructions added yet.

{% endif %}
{% if selected.notes_markdown %}

Notes

{{ selected.notes_markdown|linebreaksbr }}
{% endif %}
+
+ {% else %} +

Make room for something delicious.

Save a recipe to see its ingredients and instructions here.

Create your first recipe
+ {% endif %} +
+ + {% if selected %}{% endif %} +
+{% endblock %} diff --git a/main/recipes/tests.py b/main/recipes/tests.py new file mode 100644 index 0000000..35b6e0a --- /dev/null +++ b/main/recipes/tests.py @@ -0,0 +1,95 @@ +from decimal import Decimal +from io import BytesIO +from tempfile import TemporaryDirectory + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import TestCase +from django.test.utils import override_settings +from django.urls import reverse +from PIL import Image + +from .models import Recipe, RecipeIngredient, RecipeSubrecipe + + +class RecipeWebTests(TestCase): + def setUp(self): + user_model = get_user_model() + self.user = user_model.objects.create_user(username='cook', password='test-password') + self.other = user_model.objects.create_user(username='other', password='test-password') + self.client.force_login(self.user) + + def data(self, title='Noodles', **changes): + data = { + 'title': title, 'description': 'A weeknight meal', 'category': 'Dinner', + 'preparation_minutes': '10', 'cooking_minutes': '15', + 'default_servings': '2', 'status': 'draft', 'tags_text': 'Asian, Quick', + 'instructions_markdown': 'Cook the noodles.', 'notes_markdown': '', + 'ingredients-TOTAL_FORMS': '1', 'ingredients-INITIAL_FORMS': '0', + 'ingredients-MIN_NUM_FORMS': '0', 'ingredients-MAX_NUM_FORMS': '1000', + 'ingredients-0-name': 'Noodles', 'ingredients-0-quantity': '250', + 'ingredients-0-unit': 'g', 'ingredients-0-display_order': '0', + } + data.update(changes) + return data + + def test_create_search_filter_edit_favourite_and_delete(self): + response = self.client.post(reverse('recipes:create'), self.data()) + self.assertEqual(response.status_code, 302) + recipe = Recipe.objects.get(owner=self.user) + self.assertEqual(recipe.tags, ['Asian', 'Quick']) + self.assertEqual(recipe.ingredients.get().quantity, Decimal('250')) + self.assertContains(self.client.get(reverse('recipes:list'), {'q': 'Noodles'}), 'Noodles') + self.assertContains(self.client.get(reverse('recipes:list'), {'tag': 'Asian'}), 'Noodles') + self.assertNotContains(self.client.get(reverse('recipes:list'), {'tag': 'Other'}), 'A weeknight meal') + self.client.post(reverse('recipes:favourite', args=[recipe.api_id])) + recipe.refresh_from_db() + self.assertTrue(recipe.is_favourite) + edit_data = self.data('Updated noodles', **{ + 'ingredients-INITIAL_FORMS': '1', 'ingredients-0-id': str(recipe.ingredients.get().pk), + 'ingredients-0-quantity': '300', + }) + self.assertEqual(self.client.post(reverse('recipes:edit', args=[recipe.api_id]), edit_data).status_code, 302) + recipe.refresh_from_db() + self.assertEqual(recipe.title, 'Updated noodles') + self.assertEqual(recipe.ingredients.get().quantity, Decimal('300')) + self.assertEqual(self.client.post(reverse('recipes:delete', args=[recipe.api_id])).status_code, 302) + self.assertFalse(Recipe.objects.filter(pk=recipe.pk).exists()) + + def test_owner_isolation(self): + recipe = Recipe.objects.create(owner=self.other, title='Private') + for name in ('detail', 'edit', 'delete', 'photo'): + self.assertEqual(self.client.get(reverse(f'recipes:{name}', args=[recipe.api_id])).status_code, 404) + self.assertEqual(self.client.post(reverse('recipes:favourite', args=[recipe.api_id])).status_code, 404) + self.assertNotContains(self.client.get(reverse('recipes:list')), 'Private') + + def test_invalid_ingredient_does_not_create_recipe(self): + response = self.client.post(reverse('recipes:create'), self.data(**{'ingredients-0-quantity': '-1'})) + self.assertEqual(response.status_code, 200) + self.assertFalse(Recipe.objects.exists()) + + def test_subrecipe_ownership_and_cycles(self): + a = Recipe.objects.create(owner=self.user, title='A') + b = Recipe.objects.create(owner=self.user, title='B') + other = Recipe.objects.create(owner=self.other, title='Other') + RecipeSubrecipe.objects.create(recipe=a, component=b) + with self.assertRaises(ValidationError): + RecipeSubrecipe(recipe=b, component=a).full_clean() + with self.assertRaises(ValidationError): + RecipeSubrecipe(recipe=a, component=other).full_clean() + with self.assertRaises(ValidationError): + RecipeIngredient(recipe=a, name='Flour', quantity=Decimal('-1'), unit='g').full_clean() + + def test_photo_upload_is_private(self): + image = BytesIO() + Image.new('RGB', (2, 2), '#217857').save(image, format='PNG') + with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root): + data = self.data() + data['photo'] = SimpleUploadedFile('noodles.png', image.getvalue(), content_type='image/png') + self.assertEqual(self.client.post(reverse('recipes:create'), data).status_code, 302) + recipe = Recipe.objects.get(owner=self.user) + photo_url = reverse('recipes:photo', args=[recipe.api_id]) + self.assertEqual(self.client.get(photo_url).status_code, 200) + self.client.force_login(self.other) + self.assertEqual(self.client.get(photo_url).status_code, 404) diff --git a/main/recipes/urls.py b/main/recipes/urls.py new file mode 100644 index 0000000..e10b03c --- /dev/null +++ b/main/recipes/urls.py @@ -0,0 +1,15 @@ +from django.urls import path + +from . import views + +app_name = 'recipes' + +urlpatterns = [ + path('', views.library, name='list'), + path('new/', views.create, name='create'), + path('/', views.detail, name='detail'), + path('/edit/', views.edit, name='edit'), + path('/delete/', views.delete, name='delete'), + path('/favourite/', views.toggle_favourite, name='favourite'), + path('/photo/', views.photo, name='photo'), +] diff --git a/main/recipes/views.py b/main/recipes/views.py new file mode 100644 index 0000000..b3f091d --- /dev/null +++ b/main/recipes/views.py @@ -0,0 +1,144 @@ +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.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 + + +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] + 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, + }) + + +@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 _edit(request, recipe=None): + creating = recipe 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(): + 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) + return render(request, 'recipes/form.html', { + 'form': form, 'ingredients': ingredients, 'recipe': recipe, + 'creating': creating, + }) + + +@login_required +@require_http_methods(['GET', 'POST']) +def create(request): + 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_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 diff --git a/main/tasksnest/settings.py b/main/tasksnest/settings.py index e982382..e2c0827 100644 --- a/main/tasksnest/settings.py +++ b/main/tasksnest/settings.py @@ -44,6 +44,7 @@ INSTALLED_APPS = [ 'oauth2_provider', 'planner', 'food.apps.FoodConfig', + 'recipes', ] MIDDLEWARE = [ diff --git a/main/tasksnest/urls.py b/main/tasksnest/urls.py index 275a99e..3555a3e 100644 --- a/main/tasksnest/urls.py +++ b/main/tasksnest/urls.py @@ -24,5 +24,6 @@ urlpatterns = [ path('api/v1/', include('food.api_urls')), path('admin/', admin.site.urls), path('food/', include('food.urls', namespace='food')), + path('recipes/', include('recipes.urls', namespace='recipes')), path('', include('planner.urls')), ]