Add cook later

This commit is contained in:
Joren de Graaf
2026-10-15 19:58:33 +02:00
parent b72283818c
commit f36f05b9bc
27 changed files with 523 additions and 129 deletions
+39 -3
View File
@@ -10,7 +10,8 @@ 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 Recipe, RecipeIngredient, RecipeSubrecipe, RecipeUse
from .models import CookLater, Recipe, RecipeIngredient, RecipeSubrecipe, RecipeUse
from .services import cook_later
from .services.analysis import AnalysisError, analyze
from .services.cooking import CookingError, complete, make_completion
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
@@ -45,7 +46,8 @@ def _product(request, value):
def _summary(recipe):
return {'id': str(recipe.api_id), 'title': recipe.title, 'description': recipe.description,
'category': recipe.category, 'tags': recipe.tags, 'status': recipe.status,
'is_favourite': recipe.is_favourite, 'default_servings': str(recipe.default_servings),
'is_favourite': recipe.is_favourite, 'is_cook_later': getattr(recipe, 'is_cook_later', False),
'default_servings': str(recipe.default_servings),
'total_minutes': recipe.total_minutes,
'parent_id': str(recipe.parent.api_id) if recipe.parent_id else None,
'updated_at': recipe.updated_at.isoformat()}
@@ -145,7 +147,40 @@ def recipe_search(request):
return error('invalid_limit', 'limit must be an integer.')
if not 1 <= limit <= 100:
return error('invalid_limit', 'limit must be between 1 and 100.')
return JsonResponse({'count': recipes.count(), 'recipes': [_summary(item) for item in recipes[:limit]]})
items = list(recipes[:limit])
saved = set(CookLater.objects.filter(user=request.api_user, recipe__in=items)
.values_list('recipe_id', flat=True))
for item in items:
item.is_cook_later = item.pk in saved
return JsonResponse({'count': recipes.count(), 'recipes': [_summary(item) for item in items]})
@api_view({'GET': 'food:read', 'POST': 'food:write'}, ('GET', 'POST'))
def recipe_cook_later_collection(request):
if request.method == 'GET':
try:
limit = int(request.GET.get('limit', 20))
offset = int(request.GET.get('offset', 0))
result = cook_later.list_entries(request.api_user, request.GET.get('search', '')[:100], limit, offset)
except (ValueError, ValidationError) as exc:
return error('invalid_pagination', str(exc))
return JsonResponse(result)
try:
result = cook_later.add(request.api_user, _json(request).get('recipe_id'))
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_id', str(exc))
except Recipe.DoesNotExist:
return error('recipe_not_found', 'Recipe not found.', 404)
return JsonResponse(result)
@api_view('food:write', ('DELETE',))
def recipe_cook_later_item(request, identifier):
try:
result = cook_later.remove(request.api_user, identifier)
except Recipe.DoesNotExist:
return error('recipe_not_found', 'Recipe not found.', 404)
return JsonResponse(result)
@api_view('food:write', ('POST',))
@@ -170,6 +205,7 @@ def recipe_item(request, identifier):
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
if request.method == 'GET':
recipe.is_cook_later = CookLater.objects.filter(user=request.api_user, recipe=recipe).exists()
return JsonResponse(_detail(recipe))
if request.method == 'PATCH':
data = _json(request)
+29
View File
@@ -0,0 +1,29 @@
# Generated by Django 6.1.1 on 2026-10-15 17:42
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0005_recipeselection'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CookLater',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cook_later_entries', to='recipes.recipe')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cook_later_recipes', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-created_at', '-pk'),
'constraints': [models.UniqueConstraint(fields=('user', 'recipe'), name='recipes_unique_cook_later')],
},
),
]
+12
View File
@@ -90,6 +90,18 @@ class RecipeSelection(models.Model):
name='recipes_unique_user_selection')]
class CookLater(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='cook_later_recipes')
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='cook_later_entries')
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created_at', '-pk')
constraints = [models.UniqueConstraint(fields=('user', 'recipe'),
name='recipes_unique_cook_later')]
class RecipeIngredient(models.Model):
class Unit(models.TextChoices):
GRAM = 'g', 'g'
+63
View File
@@ -0,0 +1,63 @@
"""Canonical owner-scoped Cook Later operations for web and MCP."""
import uuid
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db.models import Q
from recipes.models import CookLater, Recipe
def visible_recipes(user):
visible = Q(owner=user)
demo_name = getattr(settings, 'RECIPE_MATCH_DEMO_USERNAME', '')
if demo_name:
demo = get_user_model().objects.filter(username=demo_name, is_active=True).first()
if demo:
visible |= Q(owner=demo, status=Recipe.Status.PUBLISHED)
return Recipe.objects.filter(visible)
def owned_recipe(user, recipe_id):
try:
identifier = uuid.UUID(str(recipe_id))
except (ValueError, AttributeError, TypeError):
raise ValidationError('Invalid recipe ID.')
recipe = visible_recipes(user).filter(api_id=identifier).first()
if recipe is None:
raise Recipe.DoesNotExist
return recipe
def add(user, recipe_id):
recipe = owned_recipe(user, recipe_id)
entry, created = CookLater.objects.get_or_create(user=user, recipe=recipe)
return {'recipe_id': str(recipe.api_id), 'is_cook_later': True, 'created': created,
'created_at': entry.created_at.isoformat()}
def remove(user, recipe_id):
try:
identifier = uuid.UUID(str(recipe_id))
except (ValueError, AttributeError, TypeError):
raise ValidationError('Invalid recipe ID.')
saved = CookLater.objects.filter(user=user, recipe__api_id=identifier).select_related('recipe').first()
recipe = saved.recipe if saved else owned_recipe(user, identifier)
removed, _ = CookLater.objects.filter(user=user, recipe=recipe).delete()
return {'recipe_id': str(recipe.api_id), 'is_cook_later': False, 'removed': bool(removed)}
def list_entries(user, search='', limit=20, offset=0):
if not 1 <= limit <= 100 or offset < 0:
raise ValidationError('limit must be 1–100 and offset must be non-negative.')
entries = CookLater.objects.filter(user=user, recipe__in=visible_recipes(user)).select_related('recipe')
if search:
entries = entries.filter(Q(recipe__title__icontains=search) |
Q(recipe__description__icontains=search))
count = entries.count()
items = [{'recipe_id': str(entry.recipe.api_id), 'title': entry.recipe.title,
'summary': entry.recipe.description, 'created_at': entry.created_at.isoformat(),
'is_cook_later': True} for entry in entries[offset:offset + limit]]
return {'count': count, 'limit': limit, 'offset': offset, 'recipes': items}
+1
View File
@@ -29,3 +29,4 @@ body[data-theme=dark] .recipe-match__image-fallback{color:#253029}body[data-them
.recipe-match__reset button:hover{border-color:#a44cbe}
@media(min-width:821px){.recipe-match__more-filters[open]>summary{display:none}}
@media(max-width:600px){.recipe-match__filter-panel{padding:12px}.recipe-match__filter-panel .recipe-match__filters{padding-top:7px}.recipe-match__search-row button{padding-inline:12px}}
.recipe-match__header .recipes-mode{margin-top:16px}.recipe-match__stage{min-height:0}.recipe-match__card-body>a{display:inline-block;margin-top:12px;color:#235943;font-weight:700}body[data-theme=dark] .recipe-match__card-body>a{color:#a7d9b6}
+23 -55
View File
@@ -3,26 +3,21 @@
if (!deck) return;
const cards = [...deck.querySelectorAll('[data-match-card]')];
const skip = document.querySelector('[data-match-skip]');
const select = document.querySelector('[data-match-select]');
const save = document.querySelector('[data-match-select]');
const status = document.querySelector('[data-match-status]');
const counter = document.querySelector('[data-match-counter]');
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
let index = 0;
let busy = false;
let drag = null;
function current() { return cards[index]; }
let index = 0, busy = false, drag = null;
const current = () => cards[index];
function update() {
cards.forEach((card, position) => { card.hidden = position !== index; });
if (counter) counter.textContent = index < cards.length ? `Recipe ${index + 1} of ${cards.length}` : (cards.length ? 'You have seen all matching recipes' : '');
if (skip) skip.disabled = index >= cards.length;
if (select) select.disabled = index >= cards.length;
if (index >= cards.length && cards.length) status.textContent = 'That’s all for now. Change the filters to explore again.';
if (counter) counter.textContent = index < cards.length ? `Recipe ${index + 1} of ${cards.length}` : 'No more recipes in this set';
if (skip) skip.disabled = busy || index >= cards.length;
if (save) save.disabled = busy || index >= cards.length;
if (index >= cards.length && cards.length) status.textContent = 'You have seen all matching recipes. Change the filters to explore again.';
}
function advance(direction) {
const card = current();
if (!card) return;
const moveFocus = card.contains(document.activeElement);
card.style.setProperty('--match-exit', direction === 'left' ? '-110%' : '110%');
card.style.setProperty('--match-tilt', direction === 'left' ? '-8deg' : '8deg');
card.classList.add('is-leaving');
@@ -32,84 +27,57 @@
index += 1;
busy = false;
update();
if (moveFocus) {
if (skip && !skip.disabled) skip.focus(); else status.focus();
}
if (save && !save.disabled) save.focus(); else status.focus();
}, reduced.matches ? 0 : 230);
}
function confetti(card) {
if (reduced.matches) return;
const area = card.querySelector('.recipe-match__confetti');
const colors = ['#f84d7c', '#ffa62b', '#24ac61', '#8d53df'];
for (let i = 0; i < 25; i++) {
const piece = document.createElement('i');
piece.style.setProperty('--confetti-color', colors[i % colors.length]);
piece.style.setProperty('--confetti-x', `${Math.round((Math.random() - .5) * 300)}px`);
piece.style.setProperty('--confetti-y', `${Math.round((Math.random() - .6) * 330)}px`);
area.append(piece);
}
window.setTimeout(() => area.replaceChildren(), 900);
}
function skipCurrent() {
if (busy || !current()) return;
busy = true;
status.textContent = `Skipped ${current().querySelector('h2').textContent}.`;
advance('left');
update();
advance('right');
}
async function selectCurrent() {
async function saveCurrent() {
if (busy || !current()) return;
busy = true;
update();
const card = current();
status.textContent = `Saving ${card.querySelector('h2').textContent}…`;
try {
const response = await fetch(card.dataset.selectUrl, {
method: 'POST', credentials: 'same-origin',
headers: {'X-CSRFToken': document.getElementById('recipe-match-csrf').value, 'Accept': 'application/json'},
});
if (!response.ok) throw new Error('Could not save your choice. Please try again.');
if (!response.ok) throw new Error('Could not save this recipe. Please try again.');
const result = await response.json();
if (result.matched) {
card.querySelector('[data-match-celebration]').hidden = false;
status.textContent = `It's a match! The demo account selected ${result.title} too.`;
if (skip) skip.disabled = true;
if (select) select.disabled = true;
confetti(card);
card.querySelector('[data-match-continue]').focus();
} else {
status.textContent = `Selected ${result.title}.`;
advance('right');
}
status.textContent = `${result.title} added to Cook Later.`;
card.querySelector('.recipe-match__kind').textContent = 'Saved in Cook Later';
advance('left');
} catch (error) {
status.textContent = error.message;
busy = false;
update();
}
}
deck.addEventListener('click', event => {
if (event.target.closest('[data-match-continue]')) {
current().querySelector('[data-match-celebration]').hidden = true;
advance('right');
}
});
deck.addEventListener('pointerdown', event => {
if (busy || !current() || event.target.closest('button,a')) return;
drag = {id: event.pointerId, x: event.clientX, y: event.clientY};
});
deck.addEventListener('pointerup', event => {
if (!drag || drag.id !== event.pointerId || busy) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
drag = null;
current().style.transform = '';
if (Math.abs(dx) < 75 || Math.abs(dx) < Math.abs(dy) * 1.3) return;
if (dx < 0) skipCurrent(); else selectCurrent();
if (dx < 0) saveCurrent(); else skipCurrent();
});
deck.addEventListener('pointercancel', () => { drag = null; if (current()) current().style.transform = ''; });
deck.addEventListener('pointermove', event => {
if (!drag || drag.id !== event.pointerId || !current()) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
if (Math.abs(dx) > Math.abs(dy) * 1.3) current().style.transform = `translateX(${Math.max(-35, Math.min(35, dx / 4))}px) rotate(${Math.max(-3, Math.min(3, dx / 40))}deg)`;
});
if (skip) skip.addEventListener('click', skipCurrent);
if (select) select.addEventListener('click', selectCurrent);
skip?.addEventListener('click', skipCurrent);
save?.addEventListener('click', saveCurrent);
update();
})();
+7
View File
@@ -33,3 +33,10 @@ body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[da
@media(min-width:821px){.recipes-filter-details[open]>summary{display:none}}
.recipes-filter-details summary::after{content:'⌄';margin-left:auto;font-size:1.2rem;line-height:1}
.recipes-filter-details[open] summary::after{transform:rotate(180deg)}
.recipes-mode{display:flex;width:max-content;max-width:100%;margin:12px 0 16px;padding:4px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:12px;background:var(--recipe-surface,#fff)}
.recipes-mode a{padding:8px 20px;border-radius:9px;color:inherit;text-decoration:none;font-weight:700}
.recipes-mode a[aria-current=page]{background:#235943;color:#fff}
.recipes-mode a:focus-visible,.cook-later :is(a,button):focus-visible{outline:3px solid #a44cbe;outline-offset:3px}
.recipes-saved-badge{align-self:center;padding:5px 8px;border-radius:99px;background:#e1f2e8;color:#235943;font-size:.72rem;font-weight:700}
.cook-later{max-width:850px;margin:0 auto;padding:20px;color:var(--recipe-ink,#25292e)}.cook-later h1{margin:15px 0 5px;font-family:Fraunces,Georgia,serif}.cook-later__list{display:grid;gap:12px;margin-top:24px}.cook-later__item{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:14px;background:var(--recipe-surface,#fff)}.cook-later__item h2{margin:0;font-size:1.15rem}.cook-later__item p{margin:6px 0}.cook-later__item small{color:var(--recipe-muted,#687178)}.cook-later__item button{min-height:44px;padding:8px 14px;border:1px solid #b94a55;border-radius:9px;background:transparent;color:#a12435;cursor:pointer}body[data-theme=dark] .cook-later__item button{color:#ffb3bb}body[data-theme=dark] .recipes-saved-badge{background:#294d38;color:#b7e8c5}@media(max-width:600px){.cook-later__item{align-items:flex-start;flex-direction:column}}
body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-surface:#202a23;--recipe-line:#435046}body[data-theme=dark] .cook-later a{color:#a7d9b6}
@@ -0,0 +1,9 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Cook Later · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7">
<div class="cook-later"><a class="recipes-back" href="{% url 'recipes:list' %}">← Recipes</a><h1>Cook Later</h1><p>Recipes you saved to make another day.</p>
<div class="cook-later__list">{% for entry in entries %}<article class="cook-later__item"><div><h2><a href="{% if entry.recipe.owner_id == request.user.pk %}{% url 'recipes:detail' entry.recipe.api_id %}{% else %}{% url 'recipes:discover-detail' entry.recipe.api_id %}{% endif %}">{{ entry.recipe.title }}</a></h2>{% if entry.recipe.description %}<p>{{ entry.recipe.description }}</p>{% endif %}<small>Saved {{ entry.created_at|date:'j M Y' }}</small></div><form method="post" action="{% url 'recipes:cook-later-remove' entry.recipe.api_id %}">{% csrf_token %}<button type="submit" aria-label="Remove {{ entry.recipe.title }} from Cook Later">Remove</button></form></article>{% empty %}<p>No recipes saved yet. <a href="{% url 'recipes:match' %}">Browse recipes to save</a>.</p>{% endfor %}</div>
</div>
{% endblock %}
@@ -0,0 +1,7 @@
{% extends 'planner/base.html' %}{% load static recipe_markdown %}
{% block title %}{{ recipe.title }} · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7">
<div class="cook-later"><a class="recipes-back" href="{% url 'recipes:match' %}">← Browse recipes</a><h1>{{ recipe.title }}</h1>{% if recipe.description %}<p>{{ recipe.description }}</p>{% endif %}<p>{{ recipe.total_minutes }} min · {{ recipe.default_servings|floatformat:-2 }} servings</p><section class="recipes-panel"><h2>Ingredients</h2><ul>{% for ingredient in recipe.ingredients.all %}<li>{{ ingredient.quantity|floatformat:-3 }} {{ ingredient.unit }} {{ ingredient.name }}</li>{% empty %}<li>No ingredients listed.</li>{% endfor %}</ul></section><section class="recipes-panel"><h2>Instructions</h2>{% if recipe.instructions_markdown %}{{ recipe.instructions_markdown|recipe_markdown }}{% else %}<p>No instructions listed.</p>{% endif %}</section></div>
{% endblock %}
+4 -3
View File
@@ -2,13 +2,14 @@
{% block title %}Recipes · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=5">
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7">
<div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}">
<aside class="recipes-browser" aria-label="Recipe browser">
<div class="recipes-browser__heading">
<div><h1>Recipes</h1><p>Find, create and cook with what you have.</p><a class="recipes-match-link" href="{% url 'recipes:match' %}">♡ Try Recipe Match</a></div>
<div><h1>Recipes</h1><p>Find, create and cook with what you have.</p><a class="recipes-match-link" href="{% url 'recipes:cook-later' %}">Cook Later</a></div>
<a class="button recipes-new" href="{% url 'recipes:create' %}">+ New recipe</a>
</div>
<nav class="recipes-mode" aria-label="Recipe view"><a href="{% url 'recipes:list' %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" aria-current="page">Search</a><a href="{% url 'recipes:match' %}?q={{ query|urlencode }}&amp;category={{ category|urlencode }}&amp;tag={{ tag|urlencode }}">Swipe</a></nav>
<form method="get" action="{% url 'recipes:list' %}" class="recipes-filters" role="search">
<label for="recipes-search">Search recipes</label>
<div class="recipes-search-row"><input id="recipes-search" type="search" name="q" value="{{ query }}" placeholder="Search recipes or ingredients"><button type="submit">Search</button></div>
@@ -27,7 +28,7 @@
<a class="recipes-list-item{% if selected.pk == recipe.pk %} recipes-list-item--selected{% endif %}" href="{% url 'recipes:detail' recipe.api_id %}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}"{% if selected.pk == recipe.pk %} aria-current="page"{% endif %}>
{% if recipe.photo %}<img class="recipes-list-item__image" src="{% url 'recipes:photo' recipe.api_id %}" alt="" loading="lazy">{% else %}<span class="recipes-list-item__placeholder" aria-hidden="true">Recipe</span>{% endif %}
<span class="recipes-list-item__body"><strong>{{ recipe.title }}</strong><small>{{ recipe.total_minutes }} min · {{ recipe.default_servings|floatformat:-2 }} servings</small><span class="recipes-list-item__tags">{% if recipe.category %}<span>{{ recipe.category }}</span>{% endif %}{% for value in recipe.tags|slice:':2' %}<span>{{ value }}</span>{% endfor %}</span></span>
{% if recipe.is_favourite %}<span class="recipes-list-item__favourite" aria-label="Favourite">♥</span>{% endif %}
{% if recipe.pk in saved_ids %}<span class="recipes-saved-badge">Cook Later</span>{% endif %}{% if recipe.is_favourite %}<span class="recipes-list-item__favourite" aria-label="Favourite">♥</span>{% endif %}
</a>
{% empty %}
<div class="recipes-empty-list"><p>{% if query or category or tag or favourite %}No recipes match these filters.{% else %}Your recipe library is ready.{% endif %}</p><a href="{% url 'recipes:create' %}">Create a recipe</a></div>
+7 -10
View File
@@ -1,12 +1,12 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Recipe Match · Tasknest{% endblock %}
{% block title %}Swipe recipes · Tasknest{% endblock %}
{% block page_class %}recipes-page-content{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4">
<link rel="stylesheet" href="{% static 'recipes/match.css' %}?v=7">
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=7">
<link rel="stylesheet" href="{% static 'recipes/match.css' %}?v=8">
<div class="recipe-match">
<header class="recipe-match__header">
<div><a class="recipes-back" href="{% url 'recipes:list' %}">← Back to recipes</a><p class="recipe-match__eyebrow">A little cooking demo</p><h1>Recipe Match <span aria-hidden="true">♡</span></h1><p>Explore recipes one card at a time. Select a recipe to see if the demo account picked it too.</p></div>
<div><a class="recipes-back" href="{% url 'recipes:list' %}?q={{ query|urlencode }}&amp;category={{ category|urlencode }}&amp;tag={{ tag|urlencode }}">← Back to recipes</a><h1>Swipe recipes</h1><p>Save a recipe for later or skip to the next one.</p><nav class="recipes-mode" aria-label="Recipe view"><a href="{% url 'recipes:list' %}?q={{ query|urlencode }}&amp;category={{ category|urlencode }}&amp;tag={{ tag|urlencode }}">Search</a><a href="{% url 'recipes:match' %}?{{ request.GET.urlencode }}" aria-current="page">Swipe</a></nav><a href="{% url 'recipes:cook-later' %}">View Cook Later</a></div>
</header>
<form class="recipe-match__filter-panel" method="get" role="search" aria-label="Filter recipe cards">
<div class="recipe-match__search-row"><label for="match-search">Search recipes</label><input id="match-search" type="search" name="q" value="{{ query }}" placeholder="Title or ingredient"><button type="submit">Search</button></div>
@@ -21,7 +21,6 @@
</details>
</form>
<section class="recipe-match__stage" aria-label="Recipe discovery">
<form class="recipe-match__reset" method="post" action="{% url 'recipes:match-reset' %}">{% csrf_token %}<button type="submit" aria-label="Start over and show all recipes">↺ Start over</button></form>
<p class="recipe-match__counter" data-match-counter aria-live="polite"></p>
<div class="recipe-match__deck" data-match-deck>
{% for recipe in recipes %}
@@ -30,17 +29,15 @@
{% if recipe.photo %}<img src="{% url 'recipes:match-photo' recipe.api_id %}" alt="Photo of {{ recipe.title }}">{% else %}<div class="recipe-match__image-fallback" role="img" aria-label="No photo for {{ recipe.title }}"><span aria-hidden="true">🍽</span></div>{% endif %}
<span class="recipe-match__stamp" data-match-stamp aria-hidden="true"></span>
</div>
<div class="recipe-match__card-body"><p class="recipe-match__kind">{% if recipe.owner_id == request.user.pk %}Your recipe{% else %}Demo recipe{% endif %}</p><h2>{{ recipe.title }}</h2><p class="recipe-match__meta">{% if recipe.total_minutes %}◷ {{ recipe.total_minutes }} min{% endif %}{% if recipe.category %}<span>{{ recipe.category }}</span>{% endif %}</p>{% if recipe.tags %}<div class="recipe-match__tags">{% for tag in recipe.tags|slice:':3' %}<span>{{ tag }}</span>{% endfor %}</div>{% endif %}</div>
<div class="recipe-match__celebration" data-match-celebration hidden><div class="recipe-match__confetti" aria-hidden="true"></div><div class="recipe-match__celebration-copy"><span aria-hidden="true">🎉</span><h3>It's a match!</h3><p>The demo account selected this recipe too.</p><button type="button" data-match-continue>Keep swiping</button>{% if recipe.owner_id == request.user.pk %}<a href="{% url 'recipes:detail' recipe.api_id %}">View recipe</a>{% endif %}</div></div>
<div class="recipe-match__card-body"><p class="recipe-match__kind">{% if recipe.pk in saved_ids %}Saved in Cook Later{% elif recipe.owner_id == request.user.pk %}Your recipe{% else %}Demo recipe{% endif %}</p><h2>{{ recipe.title }}</h2><p class="recipe-match__meta">{% if recipe.total_minutes %}◷ {{ recipe.total_minutes }} min{% endif %}{% if recipe.category %}<span>{{ recipe.category }}</span>{% endif %}</p>{% if recipe.tags %}<div class="recipe-match__tags">{% for tag in recipe.tags|slice:':3' %}<span>{{ tag }}</span>{% endfor %}</div>{% endif %}<a href="{% if recipe.owner_id == request.user.pk %}{% url 'recipes:detail' recipe.api_id %}{% else %}{% url 'recipes:discover-detail' recipe.api_id %}{% endif %}">View recipe</a></div>
</article>
{% empty %}<p class="recipe-match__empty">No recipes match these filters. Try another search or return to your recipes.</p>{% endfor %}
</div>
{% if recipes %}<div class="recipe-match__actions"><button type="button" class="recipe-match__skip" data-match-skip aria-label="Skip recipe"><span aria-hidden="true">×</span><small>Skip</small></button><button type="button" class="recipe-match__select" data-match-select aria-label="Select recipe"><span aria-hidden="true">♥</span><small>Select</small></button></div><p class="recipe-match__hint">Swipe left to skip or right to select. The buttons work with keyboard too.</p>{% endif %}
{% if recipes %}<div class="recipe-match__actions"><button type="button" class="recipe-match__select" data-match-select aria-label="Save recipe to Cook Later"><span aria-hidden="true">+</span><small>Cook Later</small></button><button type="button" class="recipe-match__skip" data-match-skip aria-label="Skip recipe"><span aria-hidden="true">→</span><small>Skip</small></button></div><p class="recipe-match__hint">Swipe left to save to Cook Later, or right to skip. Both actions have buttons.</p>{% endif %}
<p class="recipe-match__status" data-match-status role="status" aria-live="polite" tabindex="-1"></p>
{% if not demo_ready %}<p class="recipe-match__setup">The demo account is not configured yet. You can explore cards, but matches will appear after demo selections are seeded.</p>{% endif %}
</section>
</div>
<input type="hidden" id="recipe-match-csrf" value="{{ csrf_token }}">
<script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script>
<script src="{% static 'recipes/match.js' %}?v=7" defer></script>
<script src="{% static 'recipes/match.js' %}?v=8" defer></script>
{% endblock %}
+16
View File
@@ -45,6 +45,22 @@ class RecipeApiTests(TestCase):
self.assertEqual(response.status_code, 201, response.content)
return response.json()['id']
def test_cook_later_api_is_idempotent_scoped_and_paged(self):
recipe_id = self.create()
path = 'recipes/cook-later/'
self.assertFalse(self.call('get', f'recipes/{recipe_id}/').json()['is_cook_later'])
self.assertEqual(self.call('post', path, {'recipe_id': recipe_id}, token=self.food_read).status_code, 403)
self.assertEqual(self.call('post', path, {'recipe_id': str(self.other_recipe.api_id)}).status_code, 404)
self.assertTrue(self.call('post', path, {'recipe_id': recipe_id}).json()['created'])
self.assertFalse(self.call('post', path, {'recipe_id': recipe_id}).json()['created'])
self.assertTrue(self.call('get', f'recipes/{recipe_id}/').json()['is_cook_later'])
self.assertTrue(self.call('get', 'recipes/?query=Oat').json()['recipes'][0]['is_cook_later'])
self.assertEqual(self.call('get', path).json()['count'], 1)
self.assertEqual(self.call('get', f'{path}?offset=1').json()['recipes'], [])
self.assertEqual(self.call('get', f'{path}?limit=0').status_code, 400)
self.assertTrue(self.call('delete', f'{path}{recipe_id}/').json()['removed'])
self.assertFalse(self.call('delete', f'{path}{recipe_id}/').json()['removed'])
def test_recipe_crud_variation_and_scopes(self):
recipe_id = self.create()
repeat = self.call('post', 'recipes/create/',
+50
View File
@@ -0,0 +1,50 @@
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import CookLater, Recipe, RecipeSelection
from .services import cook_later
class CookLaterTests(TestCase):
def setUp(self):
users = get_user_model()
self.user = users.objects.create_user(username='cook-later-owner', password='test')
self.other = users.objects.create_user(username='cook-later-other', password='test')
self.recipe = Recipe.objects.create(owner=self.user, title='Soup')
self.foreign = Recipe.objects.create(owner=self.other, title='Secret')
self.client.force_login(self.user)
def test_save_is_idempotent_and_list_is_owner_scoped(self):
url = reverse('recipes:match-select', args=[self.recipe.api_id])
self.assertEqual(self.client.post(url).json()['is_cook_later'], True)
self.assertEqual(self.client.post(url).json()['created'], False)
self.assertEqual(CookLater.objects.filter(user=self.user).count(), 1)
self.assertContains(self.client.get(reverse('recipes:cook-later')), 'Soup')
self.assertNotContains(self.client.get(reverse('recipes:cook-later')), 'Secret')
self.assertEqual(self.client.post(reverse('recipes:match-select', args=[self.foreign.api_id])).status_code, 404)
self.assertEqual(cook_later.list_entries(self.user)['count'], 1)
def test_skip_does_not_save_and_old_selections_are_not_imported(self):
RecipeSelection.objects.create(user=self.user, recipe=self.recipe)
self.assertContains(self.client.get(reverse('recipes:match')), 'Soup')
self.assertEqual(CookLater.objects.filter(user=self.user).count(), 0)
self.assertContains(self.client.get(reverse('recipes:match')), 'Swipe left to save')
def test_remove_and_deleted_recipe(self):
cook_later.add(self.user, self.recipe.api_id)
url = reverse('recipes:cook-later-remove', args=[self.recipe.api_id])
self.assertEqual(self.client.get(url).status_code, 405)
self.assertEqual(self.client.post(url).status_code, 302)
self.assertEqual(self.client.post(url).status_code, 302)
self.assertEqual(CookLater.objects.filter(user=self.user).count(), 0)
self.assertFalse(cook_later.remove(self.user, self.recipe.api_id)['removed'])
cook_later.add(self.user, self.recipe.api_id)
self.recipe.delete()
self.assertEqual(CookLater.objects.filter(user=self.user).count(), 0)
def test_empty_and_search(self):
self.assertContains(self.client.get(reverse('recipes:cook-later')), 'No recipes saved yet')
self.assertEqual(cook_later.list_entries(self.user)['recipes'], [])
cook_later.add(self.user, self.recipe.api_id)
self.assertEqual(cook_later.list_entries(self.user, search='no match')['count'], 0)
+16 -34
View File
@@ -1,11 +1,10 @@
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import IntegrityError, transaction
from django.test import TestCase, override_settings
from django.urls import reverse
from .models import Recipe, RecipeSelection
from .models import CookLater, Recipe, RecipeSelection
@override_settings(RECIPE_MATCH_DEMO_USERNAME='match-demo')
@@ -25,49 +24,38 @@ class RecipeMatchTests(TestCase):
self.own = Recipe.objects.create(owner=self.user, title='My pasta')
self.client.force_login(self.user)
def test_discovery_filters_and_existing_permissions(self):
def test_discovery_filters_and_permissions(self):
page = self.client.get(reverse('recipes:match'))
self.assertContains(page, 'Lemon salmon')
self.assertContains(page, 'My pasta')
self.assertNotContains(page, 'Private cake')
self.assertNotContains(page, 'Foreign meal')
self.assertNotContains(self.client.get(reverse('recipes:match'), {'time': '30', 'tag': 'Fish'}),
'My pasta')
self.assertNotContains(self.client.get(reverse('recipes:match'), {'time': '30', 'tag': 'Fish'}), 'My pasta')
self.assertContains(self.client.get(reverse('recipes:match'), {'q': 'Salmon'}), 'Lemon salmon')
self.assertEqual(self.client.get(reverse('recipes:detail', args=[self.recipe.api_id])).status_code, 404)
self.assertEqual(self.client.get(reverse('recipes:photo', args=[self.recipe.api_id])).status_code, 404)
self.assertEqual(self.client.get(reverse('recipes:match-photo', args=[self.private.api_id])).status_code, 404)
self.assertEqual(self.client.get(reverse('recipes:discover-detail', args=[self.recipe.api_id])).status_code, 200)
self.assertEqual(self.client.get(reverse('recipes:discover-detail', args=[self.private.api_id])).status_code, 404)
def test_select_is_idempotent_and_matches_server_side(self):
def test_save_is_idempotent_without_match_semantics(self):
RecipeSelection.objects.create(user=self.demo, recipe=self.recipe)
url = reverse('recipes:match-select', args=[self.recipe.api_id])
self.assertEqual(self.client.get(url).status_code, 405)
first = self.client.post(url)
self.assertTrue(first.json()['matched'])
self.assertTrue(self.client.post(url).json()['matched'])
self.assertEqual(RecipeSelection.objects.filter(user=self.user, recipe=self.recipe).count(), 1)
self.assertNotContains(self.client.get(reverse('recipes:match')), 'Lemon salmon')
self.assertFalse(self.client.post(reverse('recipes:match-select', args=[self.own.api_id])).json()['matched'])
self.assertTrue(self.client.post(url).json()['is_cook_later'])
self.assertFalse(self.client.post(url).json()['created'])
self.assertEqual(CookLater.objects.filter(user=self.user, recipe=self.recipe).count(), 1)
self.assertContains(self.client.get(reverse('recipes:match')), 'Lemon salmon')
self.assertContains(self.client.get(reverse('recipes:cook-later')), 'Lemon salmon')
self.assertEqual(self.client.post(reverse('recipes:match-select', args=[self.private.api_id])).status_code, 404)
self.assertEqual(self.client.post(reverse('recipes:match-select', args=[self.foreign.api_id])).status_code, 404)
with transaction.atomic(), self.assertRaises(IntegrityError):
RecipeSelection.objects.create(user=self.user, recipe=self.recipe)
def test_reset_restores_own_cards_and_preserves_other_picks(self):
RecipeSelection.objects.create(user=self.demo, recipe=self.recipe)
RecipeSelection.objects.create(user=self.other, recipe=self.recipe)
def test_old_reset_does_not_remove_cook_later(self):
RecipeSelection.objects.create(user=self.user, recipe=self.recipe)
url = reverse('recipes:match-reset')
self.assertEqual(self.client.get(url).status_code, 405)
self.assertNotContains(self.client.get(reverse('recipes:match')), 'Lemon salmon')
response = self.client.post(url)
self.assertRedirects(response, reverse('recipes:match'))
self.client.post(reverse('recipes:match-select', args=[self.recipe.api_id]))
self.client.post(reverse('recipes:match-reset'))
self.assertFalse(RecipeSelection.objects.filter(user=self.user).exists())
self.assertTrue(RecipeSelection.objects.filter(user=self.demo, recipe=self.recipe).exists())
self.assertTrue(RecipeSelection.objects.filter(user=self.other, recipe=self.recipe).exists())
self.assertContains(self.client.get(reverse('recipes:match')), 'Lemon salmon')
self.assertTrue(CookLater.objects.filter(user=self.user, recipe=self.recipe).exists())
def test_seed_and_reset_uses_existing_demo_recipes(self):
def test_seed_still_uses_existing_demo_recipes(self):
self.recipe.status = Recipe.Status.DRAFT
self.recipe.save(update_fields=('status',))
with self.assertRaises(CommandError):
@@ -76,9 +64,3 @@ class RecipeMatchTests(TestCase):
self.recipe.save(update_fields=('status',))
call_command('seed_recipe_match')
self.assertTrue(RecipeSelection.objects.filter(user=self.demo, recipe=self.recipe).exists())
RecipeSelection.objects.create(user=self.user, recipe=self.recipe)
call_command('seed_recipe_match', reset_user='visitor')
self.assertFalse(RecipeSelection.objects.filter(user=self.user).exists())
self.assertTrue(RecipeSelection.objects.filter(user=self.demo).exists())
call_command('seed_recipe_match', source_username='visitor', reset_demo=True)
self.assertTrue(RecipeSelection.objects.filter(user=self.demo, recipe=self.own).exists())
+3
View File
@@ -6,6 +6,9 @@ app_name = 'recipes'
urlpatterns = [
path('', views.library, name='list'),
path('cook-later/', views.cook_later_list, name='cook-later'),
path('cook-later/<uuid:identifier>/remove/', views.cook_later_remove, name='cook-later-remove'),
path('discover/<uuid:identifier>/', views.discover_detail, name='discover-detail'),
path('match/', views.match, name='match'),
path('match/reset/', views.match_reset, name='match-reset'),
path('match/<uuid:identifier>/select/', views.match_select, name='match-select'),
+34 -10
View File
@@ -18,8 +18,9 @@ from PIL import Image
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
RecipeSubstitutionForm)
from .models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution,
from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution,
RecipeSelection, RecipeSubrecipe, RecipeUse)
from .services import cook_later
from .services.analysis import AnalysisError, analyze
from .services.cooking import CookingError, complete, instruction_steps, make_completion
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
@@ -45,8 +46,7 @@ def _match_recipes(user):
@login_required
def match(request):
demo = _match_demo_user()
recipes = _match_recipes(request.user).exclude(match_selections__user=request.user)
recipes = _match_recipes(request.user)
query = request.GET.get('q', '').strip()[:100]
category = request.GET.get('category', '').strip()[:80]
tag = request.GET.get('tag', '').strip()[:40]
@@ -70,7 +70,7 @@ def match(request):
return render(request, 'recipes/match.html', {
'recipes': recipes, 'query': query, 'category': category, 'tag': tag,
'time_limit': time_limit, 'categories': categories, 'tags': tags,
'demo_ready': bool(demo and RecipeSelection.objects.filter(user=demo).exists()),
'saved_ids': set(CookLater.objects.filter(user=request.user).values_list('recipe_id', flat=True)),
})
@@ -86,12 +86,34 @@ def match_reset(request):
@require_POST
def match_select(request, identifier):
recipe = get_object_or_404(_match_recipes(request.user), api_id=identifier)
RecipeSelection.objects.get_or_create(user=request.user, recipe=recipe)
demo = _match_demo_user()
matched = bool(demo and demo.pk != request.user.pk and
RecipeSelection.objects.filter(user=demo, recipe=recipe).exists())
return JsonResponse({'matched': matched, 'recipe_id': str(recipe.api_id),
'title': recipe.title})
result = cook_later.add(request.user, recipe.api_id)
return JsonResponse({**result, 'title': recipe.title})
@login_required
def cook_later_list(request):
return render(request, 'recipes/cook_later.html', {
'entries': CookLater.objects.filter(user=request.user, recipe__in=_match_recipes(request.user))
.select_related('recipe'),
})
@login_required
@require_POST
def cook_later_remove(request, identifier):
try:
cook_later.remove(request.user, identifier)
except Recipe.DoesNotExist:
raise Http404
messages.success(request, 'Removed from Cook Later.')
return redirect('recipes:cook-later')
@login_required
def discover_detail(request, identifier):
recipe = get_object_or_404(_match_recipes(request.user).prefetch_related('ingredients'),
api_id=identifier)
return render(request, 'recipes/discover_detail.html', {'recipe': recipe})
def _library(request, selected=None):
@@ -112,6 +134,7 @@ def _library(request, selected=None):
if tag:
recipes = [recipe for recipe in recipes if tag in recipe.tags]
recipes = recipes[:100]
saved_ids = set(CookLater.objects.filter(user=request.user).values_list('recipe_id', flat=True))
if selected is None and recipes:
selected = recipes[0]
analysis = None
@@ -134,6 +157,7 @@ def _library(request, selected=None):
'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,
})