recipe links

This commit is contained in:
Joren de Graaf
2026-10-23 14:30:58 +02:00
parent 5b986134be
commit 4d76a2bc9c
52 changed files with 2698 additions and 19 deletions
+179 -2
View File
@@ -10,7 +10,7 @@ from django.http import JsonResponse
from food.api import (_date, _decimal, _idempotent, _json, _time, _uuid,
api_view, error)
from food.models import FoodProduct, MealType
from .models import CookLater, Recipe, RecipeIngredient, RecipeSubrecipe, RecipeUse
from .models import CookLater, Recipe, RecipeIngredient, RecipeLink, RecipeSubrecipe, RecipeUse
from .services import cook_later
from .services.analysis import AnalysisError, analyze
from .services.cooking import CookingError, complete, make_completion
@@ -82,10 +82,26 @@ def _detail(recipe):
'unit': item.unit, 'note': item.note, 'display_order': item.display_order}
for item in recipe.subrecipes.all()],
variations=[{'id': str(item.api_id), 'title': item.title}
for item in recipe.variations.all()])
for item in recipe.variations.all()],
linked_recipes=_link_data(recipe))
return data
def _link_data(recipe):
links = RecipeLink.objects.filter(owner=recipe.owner, source=recipe,
target__owner=recipe.owner).select_related('target')
incoming = RecipeLink.objects.filter(owner=recipe.owner, target=recipe, reciprocal=True,
source__owner=recipe.owner).select_related('source')
return ([{'link_id': str(link.id), 'recipe_id': str(link.target.api_id),
'title': link.target.title, 'relationship': link.relationship,
'note': link.note, 'reciprocal': link.reciprocal, 'direction': 'outgoing'}
for link in links[:50]] +
[{'link_id': str(link.id), 'recipe_id': str(link.source.api_id),
'title': link.source.title, 'relationship': link.relationship,
'note': link.note, 'reciprocal': True, 'direction': 'incoming'}
for link in incoming[:50]])
def _set_recipe(request, recipe, data):
_unknown(data, RECIPE_FIELDS)
for field, value in data.items():
@@ -198,6 +214,167 @@ def recipe_create(request):
return _idempotent(request, data, action)
def _link_payload(link, direction='outgoing'):
other = link.target if direction == 'outgoing' else link.source
return {'link_id': str(link.id), 'recipe_id': str(other.api_id), 'title': other.title,
'relationship': link.relationship, 'note': link.note,
'reciprocal': link.reciprocal, 'direction': direction}
@api_view({'GET': 'food:read', 'POST': 'food:write'}, ('GET', 'POST'))
def recipe_links(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
if request.method == 'GET':
return JsonResponse({'links': _link_data(recipe)})
data = _json(request)
try:
_unknown(data, {'recipe_id', 'relationship', 'note', 'reciprocal'})
target = _owned(request, _uuid(data.get('recipe_id')))
if target is None:
return error('recipe_not_found', 'Linked recipe not found.', 404)
if target.pk == recipe.pk:
raise ValueError('A recipe cannot link to itself.')
relationship = data.get('relationship', RecipeLink.Relationship.GOES_WELL_WITH)
note = data.get('note', '')
reciprocal = data.get('reciprocal', True)
if relationship not in RecipeLink.Relationship.values:
raise ValueError('Choose a supported relationship.')
if not isinstance(note, str) or len(note) > 255:
raise ValueError('note must be at most 255 characters.')
if not isinstance(reciprocal, bool):
raise ValueError('reciprocal must be a boolean.')
if RecipeLink.objects.filter(owner=request.api_user, source=target, target=recipe).exists():
raise ValueError('A reverse link already exists; edit that link instead.')
def action():
try:
link = RecipeLink(owner=request.api_user, source=recipe, target=target,
relationship=relationship, note=note.strip(), reciprocal=reciprocal)
link.full_clean()
link.save()
except (ValidationError, IntegrityError):
return error('duplicate_link', 'This recipe link already exists.', 409)
return JsonResponse(_link_payload(link), status=201)
return _idempotent(request, data, action)
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_link', str(exc))
@api_view({'PATCH': 'food:write', 'DELETE': 'food:write'}, ('PATCH', 'DELETE'))
def recipe_link_item(request, identifier, link_id):
link = RecipeLink.objects.filter(owner=request.api_user, id=link_id).select_related('source', 'target').first()
if link is None or str(link.source.api_id) != str(identifier):
return error('recipe_link_not_found', 'Recipe link not found.', 404)
if request.method == 'DELETE':
link.delete()
return JsonResponse({'deleted': True, 'link_id': str(link_id)})
data = _json(request)
try:
_unknown(data, {'relationship', 'note', 'reciprocal'})
for field, value in data.items():
if field == 'relationship' and value not in RecipeLink.Relationship.values:
raise ValueError('Choose a supported relationship.')
if field == 'note' and (not isinstance(value, str) or len(value) > 255):
raise ValueError('note must be at most 255 characters.')
if field == 'reciprocal' and not isinstance(value, bool):
raise ValueError('reciprocal must be a boolean.')
setattr(link, field, value.strip() if field == 'note' else value)
link.full_clean()
link.save()
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_link', str(exc))
return JsonResponse(_link_payload(link))
def _composition(request, data):
components = data.get('components')
if not isinstance(components, list) or not 1 <= len(components) <= 10:
raise ValueError('Choose between one and ten component recipes.')
resolved, seen = [], set()
for row in components:
if not isinstance(row, dict) or set(row) != {'recipe_id', 'servings'}:
raise ValueError('Each component needs recipe_id and servings.')
component = _owned(request, _uuid(row['recipe_id']))
if component is None:
raise ValueError('A selected component recipe was not found.')
if component.pk in seen:
raise ValueError('Choose each component recipe only once.')
seen.add(component.pk)
servings = _decimal(row['servings'], 'servings', positive=True)
if servings > Decimal('99999.99') or servings != servings.quantize(Decimal('.01')):
raise ValueError('Servings must be between 0.01 and 99,999.99 with at most two decimal places.')
resolved.append((component, servings))
return resolved
@api_view('food:read', ('POST',))
def recipe_composition_preview(request):
try:
resolved = _composition(request, _json(request))
component_results, ingredient_counts = [], {}
nutrition_totals = {}
nutrition_completeness = {}
for component, servings in resolved:
result = analyze(component, request.api_user, servings)
for key, value in result['nutrition'].items():
nutrition_completeness[key] = nutrition_completeness.get(key, True) and value['complete']
if value['total'] is not None:
nutrition_totals[key] = nutrition_totals.get(key, Decimal(0)) + value['total']
ingredients = []
for line in result['lines']:
key = (line['name'].strip().casefold(), line['unit'])
ingredient_counts[key] = ingredient_counts.get(key, 0) + 1
ingredients.append({'name': line['name'], 'quantity': str(line['quantity']),
'unit': line['unit'], 'source': line['source']})
component_results.append({'recipe_id': str(component.api_id), 'title': component.title,
'servings': str(servings), 'ingredients': ingredients,
'nutrition': {key: {'total': str(val['total']) if val['total'] is not None else None,
'complete': val['complete']} for key, val in result['nutrition'].items()},
'issues': result['issues']})
duplicates = [{'name': name, 'unit': unit} for (name, unit), count in ingredient_counts.items() if count > 1]
return JsonResponse({'components': component_results, 'duplicate_ingredients': duplicates,
'nutrition': {key: {'total': str(nutrition_totals[key]) if key in nutrition_totals else None,
'complete': nutrition_completeness[key] and key in nutrition_totals}
for key in nutrition_completeness},
'nutrition_complete': bool(nutrition_completeness) and all(
nutrition_completeness[key] and key in nutrition_totals for key in nutrition_completeness),
'note': 'Preview only. Suggestions are excluded; inventory and diary are unchanged.'})
except (ValueError, ValidationError, AnalysisError) as exc:
return error('invalid_composition', str(exc))
@api_view('food:write', ('POST',))
def recipe_composition_create(request):
data = _json(request)
try:
_unknown(data, {'title', 'default_servings', 'components'})
title = data.get('title')
if not isinstance(title, str) or not title.strip() or len(title.strip()) > 180:
raise ValueError('Provide a title of at most 180 characters.')
root_servings = _decimal(data.get('default_servings', '2'), 'default_servings', positive=True)
if root_servings > Decimal('99999.99') or root_servings != root_servings.quantize(Decimal('.01')):
raise ValueError('default_servings must be between 0.01 and 99,999.99 with at most two decimal places.')
resolved = _composition(request, data)
except (ValueError, ValidationError) as exc:
return error('invalid_composition', str(exc))
def action():
try:
with transaction.atomic():
recipe = Recipe(owner=request.api_user, title=title.strip(), default_servings=root_servings)
recipe.full_clean()
recipe.save()
for index, (component, servings) in enumerate(resolved):
relation = RecipeSubrecipe(recipe=recipe, component=component,
quantity=servings, unit='servings', display_order=index)
relation.full_clean()
relation.save()
except (ValidationError, IntegrityError) as exc:
return error('invalid_composition', str(exc))
return JsonResponse(_detail(recipe), status=201)
return _idempotent(request, data, action)
@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'},
('GET', 'PATCH', 'DELETE'))
def recipe_item(request, identifier):
@@ -0,0 +1,35 @@
# Generated by Django 6.1.1 on 2026-10-23 11:53
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0006_cooklater'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='RecipeLink',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('relationship', models.CharField(choices=[('goes_well_with', 'Goes well with'), ('try_with', 'Try with'), ('alternative_to', 'Alternative to')], default='goes_well_with', max_length=24)),
('note', models.CharField(blank=True, max_length=255)),
('reciprocal', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipe_links', to=settings.AUTH_USER_MODEL)),
('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='outgoing_links', to='recipes.recipe')),
('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='incoming_links', to='recipes.recipe')),
],
options={
'ordering': ('created_at', 'id'),
'constraints': [models.UniqueConstraint(fields=('owner', 'source', 'target'), name='recipes_unique_link_direction'), models.CheckConstraint(condition=models.Q(('source', models.F('target')), _negated=True), name='recipes_link_not_self')],
},
),
]
+38
View File
@@ -187,6 +187,44 @@ class RecipeSubrecipe(models.Model):
return f'{self.recipe} includes {self.component}'
class RecipeLink(models.Model):
"""A non-compositional suggestion between two recipes owned by one user."""
class Relationship(models.TextChoices):
GOES_WELL_WITH = 'goes_well_with', 'Goes well with'
TRY_WITH = 'try_with', 'Try with'
ALTERNATIVE_TO = 'alternative_to', 'Alternative to'
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='recipe_links')
source = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='outgoing_links')
target = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='incoming_links')
relationship = models.CharField(max_length=24, choices=Relationship.choices,
default=Relationship.GOES_WELL_WITH)
note = models.CharField(max_length=255, blank=True)
reciprocal = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created_at', 'id')
constraints = [
models.UniqueConstraint(fields=('owner', 'source', 'target'), name='recipes_unique_link_direction'),
models.CheckConstraint(condition=~Q(source=models.F('target')), name='recipes_link_not_self'),
]
def clean(self):
super().clean()
if self.source_id and self.target_id:
if self.source_id == self.target_id:
raise ValidationError({'target': 'A recipe cannot link to itself.'})
if self.source.owner_id != self.owner_id or self.target.owner_id != self.owner_id:
raise ValidationError({'target': 'Choose one of your own recipes.'})
if self.relationship not in self.Relationship.values:
raise ValidationError({'relationship': 'Choose a supported relationship.'})
class RecipeIngredientSubstitution(models.Model):
ingredient = models.ForeignKey(RecipeIngredient, on_delete=models.CASCADE,
related_name='substitutions')
@@ -0,0 +1,33 @@
(() => {
const form = document.querySelector('[data-recipe-link-picker]');
if (!form) return;
const search = form.querySelector('[data-recipe-search], [data-component-search]');
const empty = form.querySelector('[data-picker-empty]');
const clear = form.querySelector('[data-clear-search]');
if (!search) return;
const filter = () => {
const query = search.value.trim().toLocaleLowerCase();
let matches = 0;
const select = form.querySelector('#linked-recipe');
if (select) {
[...select.options].slice(1).forEach(option => {
const visible = option.textContent.toLocaleLowerCase().includes(query);
option.hidden = !visible;
if (visible) matches += 1;
});
}
form.querySelectorAll('[data-recipe-name]').forEach(card => {
const visible = card.dataset.recipeName.includes(query);
card.hidden = !visible;
if (visible) matches += 1;
});
if (empty) empty.hidden = !query || matches > 0;
};
search.addEventListener('input', filter);
clear?.addEventListener('click', () => {
search.value = '';
filter();
search.focus();
});
})();
+3
View File
@@ -46,3 +46,6 @@ body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--
.recipes-field .recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipes-field label.recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center}
.recipe-photo-editor__prompt small,body[data-theme=dark] .recipe-photo-editor__prompt small{color:#415c4b}
.recipes-linked{margin-top:18px}.recipes-linked__heading{display:flex;align-items:center;justify-content:space-between;gap:14px}.recipes-linked__heading h3{margin:0}.recipes-linked__heading p{margin:5px 0 0}.recipes-linked__heading>div:last-child{display:flex;flex-wrap:wrap;gap:8px}.recipes-linked-card{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 0;border-top:1px solid var(--recipe-line)}.recipes-linked-card>div{display:grid;gap:4px}.recipes-linked-actions{display:flex;gap:8px}.recipes-linked-actions a,.recipes-linked-actions button{display:inline-flex;align-items:center;padding:8px 13px;border:1px solid var(--recipe-line);border-radius:8px;color:var(--recipe-ink);background:transparent;text-decoration:none}.recipes-linked-card small{color:var(--recipe-muted)}.recipes-linked-card p{margin:3px 0 0}.recipes-linked-card a{color:var(--recipe-accent)}.recipes-linked-card button,.recipes-linked__heading a,.recipes-link-form button,.recipes-compose button{min-height:44px}.recipes-link-form,.recipes-compose{max-width:900px}.recipes-link-form .recipes-edit-card>section,.recipes-compose .recipes-edit-card>section{padding:20px}.recipes-compose-list{display:grid;gap:8px}.recipes-compose-choice{display:grid;grid-template-columns:22px minmax(0,1fr) minmax(150px,220px);align-items:center;gap:12px;padding:12px;border:1px solid var(--recipe-line);border-radius:10px;background:var(--recipe-surface)}.recipes-compose-choice>span:nth-child(2){display:grid;gap:4px}.recipes-compose-choice small,.recipes-compose-choice .recipes-field>span{color:var(--recipe-muted);font-size:.8rem}.recipes-compose-choice input[type=checkbox]{width:20px;height:20px;accent-color:var(--recipe-accent)}.recipes-compose-choice input[type=number],.recipes-link-form select,.recipes-link-form input:not([type=checkbox]){width:100%;min-height:44px;padding:8px;border:1px solid var(--recipe-line);border-radius:8px;background:var(--recipe-surface);color:var(--recipe-ink)}.recipes-compose-preview{margin-top:18px}.recipes-compose-preview h2{margin:0 0 10px}.recipes-compose-preview article{padding:12px 0;border-top:1px solid var(--recipe-line)}.recipes-compose-preview h3{margin:0;font-size:1rem}.recipes-compose-preview ul{margin-bottom:0}.recipes-linked :is(a,button):focus-visible,.recipes-compose :is(a,button,input,select):focus-visible{outline:3px solid #a44cbe;outline-offset:3px}
@media(max-width:767px){.recipes-linked__heading{align-items:flex-start;flex-direction:column}.recipes-linked__heading>div:last-child{width:100%}.recipes-linked__heading a{flex:1;text-align:center}.recipes-linked-card{align-items:flex-start}.recipes-linked-actions{flex-wrap:wrap}.recipes-compose-choice{grid-template-columns:22px minmax(0,1fr)}.recipes-compose-choice .recipes-field{grid-column:2}.recipes-compose .recipes-form-actions>*{width:100%;text-align:center}}
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Build a recipe · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=13"><div class="recipes-layout recipes-layout--form recipes-compose"><header class="recipes-form-header"><a href="{% url 'recipes:list' %}">← Back to recipes</a><h1>Build a recipe</h1><p>Create a new recipe from explicitly selected components. Linked suggestions are never included.</p></header>{% if error %}<p class="recipes-form-error" role="alert">{{ error }}</p>{% endif %}<form method="post" class="recipes-edit-card" data-recipe-link-picker>{% csrf_token %}<section><h2>New recipe</h2><div class="recipes-form-grid"><div class="recipes-field"><label for="composition-title">Recipe title</label><input id="composition-title" name="title" maxlength="180" value="{{ request.POST.title }}"></div><div class="recipes-field"><label for="composition-servings">New recipe servings</label><input id="composition-servings" type="number" name="default_servings" min="0.01" max="99999.99" step="0.01" value="{{ request.POST.default_servings|default:'2' }}"></div></div></section><section><h2>Choose components</h2><p class="recipes-muted">Select up to ten recipes and set the servings to include from each.</p><div class="recipes-field"><label for="component-search">Search recipes</label><input id="component-search" type="search" data-component-search placeholder="Search by title"><p data-picker-empty role="status" aria-live="polite" hidden>No recipes match. <button type="button" data-clear-search>Clear search</button></p></div><div class="recipes-compose-list">{% for item in available %}<label class="recipes-compose-choice" data-recipe-name="{{ item.title|lower }}"><input type="checkbox" name="component" value="{{ item.api_id }}"{% for api_id, servings in selected_rows %}{% if api_id == item.api_id|stringformat:'s' %} checked{% endif %}{% endfor %}><span><strong>{{ item.title }}</strong><small>{{ item.default_servings|floatformat:-2 }} servings · {{ item.total_minutes }} min</small></span><span class="recipes-field"><span>Servings to include</span><input aria-label="Servings of {{ item.title }}" type="number" name="servings_{{ item.api_id }}" min="0.01" max="99999.99" step="0.01" value="{{ item.default_servings|floatformat:-2 }}"></span></label>{% empty %}<p class="recipes-muted">Create a recipe first to use it as a component.</p>{% endfor %}</div></section><div class="recipes-form-actions"><button type="submit" name="action" value="preview" class="recipes-outline-button">Preview components</button><button type="submit" name="action" value="create" class="button">Create new recipe</button></div></form>{% if preview %}<section class="recipes-panel recipes-compose-preview" aria-live="polite"><h2>Component preview</h2><p>Preview only. Creating this recipe will preserve each source recipe and add explicit component references.</p><h3>Combined nutrition estimate</h3><p>{% for row in nutrition_preview %}{{ row.label }}: {% if row.total is not None %}{{ row.total|floatformat:1 }} {{ row.unit }}{% else %}unknown{% endif %}{% if not row.complete %} · incomplete{% endif %}{% if not forloop.last %} · {% endif %}{% endfor %}</p>{% if duplicates %}<p class="recipes-form-error" role="status">Ingredient overlap: {% for name in duplicates %}{{ name }}{% if not forloop.last %}, {% endif %}{% endfor %}. Check that these components should both be included.</p>{% endif %}{% for component, result in preview %}<article><h3>{{ component.title }} · {{ result.servings }} servings</h3><ul>{% for line in result.lines %}<li>{{ line.quantity|floatformat:-3 }} {{ line.unit }} {{ line.name }}</li>{% empty %}<li>No structured ingredients yet.</li>{% endfor %}</ul><p class="recipes-compose-nutrition">{% for row in result.nutrition_rows %}{{ row.label }}: {% if row.total is not None %}{{ row.total|floatformat:1 }} {{ row.unit }}{% else %}unknown{% endif %}{% if not row.complete %} · incomplete{% endif %}{% if not forloop.last %} · {% endif %}{% endfor %}</p>{% if result.issues %}<p class="recipes-muted">Nutrition or inventory data may be incomplete.</p>{% endif %}</article>{% endfor %}</section>{% endif %}</div><script src="{% static 'recipes/recipe_picker.js' %}?v=1" defer></script>{% endblock %}
@@ -51,6 +51,10 @@
<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>
<div class="recipes-content-stack"><section class="recipes-panel" aria-labelledby="recipe-instructions-heading"><h3 id="recipe-instructions-heading">Instructions</h3>{% if selected.instructions_markdown %}<div class="recipes-markdown-source">{{ selected.instructions_markdown|recipe_markdown }}</div>{% else %}<p class="recipes-muted">No instructions added yet.</p>{% endif %}</section>{% if selected.notes_markdown %}<section class="recipes-panel" aria-labelledby="recipe-notes-heading"><h3 id="recipe-notes-heading">Notes</h3><div class="recipes-markdown-source">{{ selected.notes_markdown|recipe_markdown }}</div></section>{% endif %}</div>
</div>
<section class="recipes-panel recipes-linked" aria-labelledby="linked-recipes-heading">
<div class="recipes-linked__heading"><div><h3 id="linked-recipes-heading">Linked recipes</h3><p class="recipes-muted">Suggestions stay separate from this recipe’s ingredients and nutrition.</p></div><div><a class="recipes-outline-button" href="{% url 'recipes:link' selected.api_id %}">Link a recipe</a> <a class="recipes-outline-button" href="{% url 'recipes:compose' %}">Build a recipe</a></div></div>
{% for link, other, direction in linked_recipes %}<article class="recipes-linked-card"><div><a href="{% url 'recipes:detail' other.api_id %}"><strong>{{ other.title }}</strong></a><small>{{ link.get_relationship_display }}{% if direction == 'incoming' %} · shared by {{ link.source.title }}{% endif %}</small>{% if link.note %}<p>{{ link.note }}</p>{% endif %}</div><div class="recipes-linked-actions"><a class="recipes-outline-button" href="{% url 'recipes:link-edit' link.source.api_id link.id %}">Edit</a><form method="post" action="{% url 'recipes:unlink' link.source.api_id link.id %}">{% csrf_token %}<button type="submit" class="recipes-outline-button">Remove</button></form></div></article>{% empty %}<p class="recipes-muted">Link your first recipe to keep a pairing or alternative close by.</p>{% endfor %}
</section>
{% else %}
<div class="recipes-empty-detail"><h2>Make room for something delicious.</h2><p>Save a recipe to see its ingredients and instructions here.</p><a class="button" href="{% url 'recipes:create' %}">Create your first recipe</a></div>
{% endif %}
@@ -0,0 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Link a recipe · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=13"><div class="recipes-layout recipes-layout--form recipes-link-form"><header class="recipes-form-header"><a href="{% url 'recipes:detail' recipe.api_id %}">← Back to {{ recipe.title }}</a><h1>{% if existing_link %}Edit linked recipe{% else %}Link a recipe{% endif %}</h1><p>Keep a pairing, alternative, or suggestion beside {{ recipe.title }}. Linked recipes do not change ingredient totals.</p></header><form method="post" class="recipes-edit-card" data-recipe-link-picker>{% csrf_token %}<section><h2>Recipe suggestion</h2><div class="recipes-form-grid">{% if existing_link %}<div class="recipes-field"><span>Recipe</span><strong>{{ existing_link.target.title }}</strong></div>{% else %}<div class="recipes-field"><label for="link-search">Search recipes</label><input id="link-search" type="search" data-recipe-search placeholder="Search by title"><p data-picker-empty role="status" aria-live="polite" hidden>No recipes match. <button type="button" data-clear-search>Clear search</button></p></div><div class="recipes-field"><label for="linked-recipe">Recipe</label><select id="linked-recipe" name="recipe_id" required><option value="">Choose a recipe</option>{% for item in available %}<option value="{{ item.api_id }}"{% if form_data.recipe_id == item.api_id|stringformat:"s" %} selected{% endif %}>{{ item.title }}</option>{% endfor %}</select></div>{% endif %}<div class="recipes-field"><label for="relationship">Relationship</label><select id="relationship" name="relationship">{% for value, label in choices %}<option value="{{ value }}"{% if form_data.relationship == value or not form_data and existing_link.relationship == value %} selected{% endif %}>{{ label }}</option>{% endfor %}</select></div><div class="recipes-field recipes-field--wide"><label for="link-note">Note <span class="recipes-muted">(optional)</span></label><input id="link-note" name="note" maxlength="255" autocomplete="off" value="{% if form_data %}{{ form_data.note }}{% else %}{{ existing_link.note }}{% endif %}"></div><label class="recipes-checkbox"><input type="checkbox" name="reciprocal" value="1"{% if form_data %}{% if form_data.reciprocal == "1" %} checked{% endif %}{% elif not existing_link or existing_link.reciprocal %} checked{% endif %}> Show this suggestion on both recipes</label></div></section><div class="recipes-form-actions"><button type="submit" class="button">{% if existing_link %}Save changes{% else %}Save link{% endif %}</button><a href="{% url 'recipes:detail' recipe.api_id %}">Cancel</a></div></form></div><script src="{% static 'recipes/recipe_picker.js' %}?v=1" defer></script>{% endblock %}
+34
View File
@@ -182,3 +182,37 @@ class RecipeApiTests(TestCase):
{'consumed_servings': '1', 'meal': 'lunch'}, key='meal-with-shortage').status_code, 201)
self.package.refresh_from_db()
self.assertEqual(self.package.remaining_amount, Decimal('300'))
def test_recipe_suggestion_and_explicit_composition_api(self):
base_id = self.create()
fries = self.call('post', 'recipes/create/', {'title': 'Fries'}, key='fries').json()['id']
linked = self.call('post', f'recipes/{base_id}/links/', {
'recipe_id': fries, 'relationship': 'goes_well_with', 'note': 'Serve hot',
'reciprocal': True}, key='link-fries')
self.assertEqual(linked.status_code, 201, linked.content)
replay = self.call('post', f'recipes/{base_id}/links/', {
'recipe_id': fries, 'relationship': 'goes_well_with', 'note': 'Serve hot',
'reciprocal': True}, key='link-fries')
self.assertEqual(replay.status_code, 200)
self.assertEqual(replay.json()['link_id'], linked.json()['link_id'])
self.assertEqual(self.call('get', f'recipes/{fries}/').json()['linked_recipes'][0]['recipe_id'], base_id)
edited = self.call('patch', f'recipes/{base_id}/links/{linked.json()["link_id"]}/',
{'note': 'Serve warm', 'reciprocal': False})
self.assertEqual(edited.json()['note'], 'Serve warm')
self.assertEqual(self.call('get', f'recipes/{fries}/').json()['linked_recipes'], [])
self.assertEqual(self.call('post', f'recipes/{base_id}/links/', {
'recipe_id': str(self.other_recipe.api_id)}).status_code, 404)
self.assertEqual(self.call('post', 'recipes/compositions/preview/', {
'components': [{'recipe_id': base_id, 'servings': '2'},
{'recipe_id': fries, 'servings': '1'}]}).status_code, 200)
composed = self.call('post', 'recipes/compositions/', {
'title': 'Meal plate', 'default_servings': '2', 'components': [
{'recipe_id': base_id, 'servings': '2'}, {'recipe_id': fries, 'servings': '1'}]},
key='meal-plate')
self.assertEqual(composed.status_code, 201, composed.content)
self.assertEqual(len(composed.json()['subrecipes']), 2)
self.assertEqual(self.call('post', 'recipes/compositions/', {
'title': 'bad', 'components': [{'recipe_id': str(self.other_recipe.api_id), 'servings': '1'}]
}).status_code, 400)
self.assertEqual(self.call('delete', f'recipes/{base_id}/links/{linked.json()["link_id"]}/').status_code, 200)
self.assertEqual(self.call('get', f'recipes/{base_id}/').json()['linked_recipes'], [])
+37 -1
View File
@@ -11,7 +11,7 @@ from django.test.utils import override_settings
from django.urls import reverse
from PIL import Image
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
from .models import Recipe, RecipeIngredient, RecipeLink, RecipeSubrecipe
from .templatetags.recipe_markdown import recipe_markdown
@@ -86,6 +86,42 @@ class RecipeWebTests(TestCase):
with self.assertRaises(ValidationError):
RecipeIngredient(recipe=a, name='Flour', quantity=Decimal('-1'), unit='g').full_clean()
def test_linked_recipe_and_composition_web_flows(self):
main = Recipe.objects.create(owner=self.user, title='Main')
side = Recipe.objects.create(owner=self.user, title='Side')
other = Recipe.objects.create(owner=self.other, title='Private')
response = self.client.post(reverse('recipes:link', args=[main.api_id]), {
'recipe_id': str(side.api_id), 'relationship': 'goes_well_with',
'note': 'Serve together', 'reciprocal': '1'})
self.assertRedirects(response, reverse('recipes:detail', args=[main.api_id]))
link = RecipeLink.objects.get()
edit_url = reverse('recipes:link-edit', args=[main.api_id, link.id])
self.assertContains(self.client.get(edit_url), 'Edit linked recipe')
self.assertEqual(self.client.post(edit_url, {
'relationship': 'alternative_to', 'note': 'Different texture',
'reciprocal': ''}).status_code, 302)
link.refresh_from_db()
self.assertEqual((link.relationship, link.note, link.reciprocal),
('alternative_to', 'Different texture', False))
self.assertContains(self.client.get(reverse('recipes:detail', args=[side.api_id])), 'Main')
response = self.client.post(reverse('recipes:link', args=[main.api_id]), {
'recipe_id': str(other.api_id), 'relationship': 'goes_well_with'})
self.assertEqual(response.status_code, 404)
preview = self.client.post(reverse('recipes:compose'), {
'component': [str(main.api_id), str(side.api_id)],
f'servings_{main.api_id}': '2', f'servings_{side.api_id}': '1',
'action': 'preview'})
self.assertEqual(preview.status_code, 200)
self.assertContains(preview, 'Component preview')
created = self.client.post(reverse('recipes:compose'), {
'title': 'Combined', 'default_servings': '2',
'component': [str(main.api_id), str(side.api_id)],
f'servings_{main.api_id}': '2', f'servings_{side.api_id}': '1',
'action': 'create'})
self.assertEqual(created.status_code, 302)
combined = Recipe.objects.get(title='Combined')
self.assertEqual(set(combined.subrecipes.values_list('component_id', flat=True)), {main.pk, side.pk})
def test_photo_upload_is_private(self):
image = BytesIO()
Image.new('RGB', (2, 2), '#217857').save(image, format='PNG')
+4
View File
@@ -15,6 +15,10 @@ urlpatterns = [
path('match/<uuid:identifier>/photo/', views.match_photo, name='match-photo'),
path('new/', views.create, name='create'),
path('new/autosave/', views.autosave_new, name='autosave-new'),
path('compose/', views.compose_recipe, name='compose'),
path('<uuid:identifier>/links/new/', views.link_recipe, name='link'),
path('<uuid:identifier>/links/<uuid:link_id>/edit/', views.link_recipe, name='link-edit'),
path('<uuid:identifier>/links/<uuid:link_id>/remove/', views.unlink_recipe, name='unlink'),
path('<uuid:identifier>/', views.detail, name='detail'),
path('<uuid:identifier>/edit/', views.edit, name='edit'),
path('<uuid:identifier>/photo/upload/', views.photo_upload, name='photo-upload'),
+124 -2
View File
@@ -20,7 +20,7 @@ from PIL import Image
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
RecipeSubstitutionForm, validate_recipe_photo)
from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution,
RecipeSelection, RecipeSubrecipe, RecipeUse)
RecipeLink, RecipeSelection, RecipeSubrecipe, RecipeUse)
from .services import cook_later
from .services.analysis import AnalysisError, analyze
from .services.cooking import CookingError, complete, instruction_steps, make_completion
@@ -153,12 +153,19 @@ def _library(request, selected=None):
.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)})
linked = []
if selected:
linked.extend((link, link.target, 'outgoing') for link in RecipeLink.objects.filter(
owner=request.user, source=selected, target__owner=request.user).select_related('target'))
linked.extend((link, link.source, 'incoming') for link in RecipeLink.objects.filter(
owner=request.user, target=selected, reciprocal=True,
source__owner=request.user).select_related('source'))
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,
'saved_ids': saved_ids,
'saved_ids': saved_ids, 'linked_recipes': linked,
})
@@ -174,6 +181,121 @@ def detail(request, identifier):
return _library(request, recipe)
@login_required
@require_http_methods(['GET', 'POST'])
def link_recipe(request, identifier, link_id=None):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
existing_link = get_object_or_404(RecipeLink, owner=request.user, source=recipe, id=link_id) if link_id else None
if request.method == 'POST':
target = existing_link.target if existing_link else get_object_or_404(
_owned(request.user), api_id=request.POST.get('recipe_id'))
if target.pk == recipe.pk:
messages.error(request, 'A recipe cannot link to itself.')
elif not existing_link and RecipeLink.objects.filter(owner=request.user, source=target, target=recipe).exists():
messages.error(request, 'A reverse link already exists. Edit that link instead.')
else:
link = existing_link or RecipeLink(owner=request.user, source=recipe, target=target)
link.relationship = request.POST.get('relationship', RecipeLink.Relationship.GOES_WELL_WITH)
link.note = request.POST.get('note', '').strip()[:255]
link.reciprocal = request.POST.get('reciprocal') == '1'
try:
link.full_clean()
link.save()
messages.success(request, f'Updated the link to {target.title}.' if existing_link
else f'Linked {target.title} to {recipe.title}.')
return redirect('recipes:detail', identifier=identifier)
except ValidationError as exc:
messages.error(request, '; '.join(exc.messages))
return render(request, 'recipes/link_form.html', {'recipe': recipe,
'choices': RecipeLink.Relationship.choices,
'available': _owned(request.user).exclude(pk=recipe.pk).order_by('title'),
'existing_link': existing_link,
'form_data': request.POST if request.method == 'POST' else None})
@login_required
@require_POST
def unlink_recipe(request, identifier, link_id):
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
link = get_object_or_404(RecipeLink, owner=request.user, source=recipe, id=link_id)
title = link.target.title
link.delete()
messages.success(request, f'Removed {title} from linked recipes.')
return redirect('recipes:detail', identifier=identifier)
@login_required
@require_http_methods(['GET', 'POST'])
def compose_recipe(request):
available = list(_owned(request.user).order_by('title'))
preview = None
error = ''
duplicates = []
nutrition_preview = []
selected_rows = []
if request.method == 'POST':
ids = request.POST.getlist('component')[:10]
selected_rows = [(value, request.POST.get(f'servings_{value}', '')) for value in ids]
if request.POST.get('action') == 'create':
title = request.POST.get('title', '').strip()
if not title or len(title) > 180 or not ids:
error = 'Enter a title and choose at least one component recipe.'
else:
try:
with transaction.atomic():
root = Recipe(owner=request.user, title=title,
default_servings=request.POST.get('default_servings', '2'))
root.full_clean()
root.save()
for index, (api_id, servings) in enumerate(selected_rows):
component = get_object_or_404(_owned(request.user), api_id=api_id)
relation = RecipeSubrecipe(recipe=root, component=component,
quantity=servings, unit='servings', display_order=index)
relation.full_clean()
relation.save()
messages.success(request, 'Created a new recipe from the selected components.')
return redirect('recipes:detail', identifier=root.api_id)
except (ValidationError, ValueError) as exc:
error = '; '.join(getattr(exc, 'messages', [str(exc)]))
else:
try:
component_results = []
for api_id, servings in selected_rows:
component = get_object_or_404(_owned(request.user), api_id=api_id)
result = analyze(component, request.user, servings)
component_results.append((component, result))
preview = component_results
ingredient_counts = {}
for component, result in component_results:
for line in result['lines']:
key = (line['name'].strip().casefold(), line['unit'])
if key in ingredient_counts:
ingredient_counts[key][1] += 1
else:
ingredient_counts[key] = [line['name'], 1]
duplicates = [name for name, count in ingredient_counts.values() if count > 1]
fields = {}
for component, result in component_results:
for row in result['nutrition_rows']:
current = fields.setdefault(row['label'], {
'label': row['label'], 'unit': row['unit'], 'total': 0,
'known': False, 'complete': True})
if row['total'] is not None:
current['total'] += row['total']
current['known'] = True
current['complete'] = current['complete'] and row['complete']
nutrition_preview = [{**row, 'total': row['total'] if row['known'] else None,
'complete': row['complete'] and row['known']}
for row in fields.values()]
if not selected_rows:
error = 'Choose at least one component recipe to preview.'
except (AnalysisError, ValueError) as exc:
error = str(exc)
return render(request, 'recipes/compose.html', {'available': available,
'selected_rows': selected_rows, 'preview': preview, 'duplicates': duplicates,
'nutrition_preview': nutrition_preview, 'error': error})
def _cooking_analysis(request, recipe):
selected = {key[4:]: value for key, value in request.GET.items()
if key.startswith('sub_') and value}