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
+6
View File
@@ -19,3 +19,9 @@ If the Django server is stopped, find and use the repository's normal developmen
## Accessibility
For UI changes, check relevant semantic headings and controls, accessible names and labels, keyboard operation and visible focus, form errors, ARIA state for custom controls, obvious contrast/readability problems, and narrow viewport behavior. Use both visual inspection and the accessibility/DOM representation where each is appropriate; neither alone proves the other.
# Project Manager MCP
When I give you a card to work on, you should:
1. Move the card to in-progress and add any pertinent findings at the end to the progress notes. This also applies to passes/phases that have a defined downtime for me to check and push things to git.
2. When you're done with the card you can move it to complete.
+2
View File
@@ -68,6 +68,8 @@ For ambiguous candidates, ask the user to select one or supply more identifying
Recipe tools use the connected user's recipes and products. `recipe_search` and `recipe_get` require `food:read`. Creation, updates, deletion, variation, ingredient, and subrecipe tools require `food:write`. Ingredient product IDs must belong to the user. Variations copy ingredients, substitutions, and component links; later edits are independent. Component recipes cannot form cycles.
`recipe_cook_later_add`, `recipe_cook_later_remove`, and `recipe_cook_later_list` manage the authenticated user's Cook Later bookmarks. Add and remove require `food:write`; list requires `food:read`. The list includes owned recipes and currently published demo recipes visible in discovery. These actions do not log a meal or deduct inventory. Existing `recipe_search` and `recipe_get` responses include `is_cook_later`.
Create a recipe, then add ingredients:
```json
+6
View File
@@ -143,6 +143,12 @@ def schema(request):
'patch': operation('Update hydration settings', 'food:write', HYDRATION_SETTINGS),
},
'/recipes/': {'get': operation('Search own recipes by query, category, and limit', 'food:read')},
'/recipes/cook-later/': {
'get': operation('List Cook Later recipes with search and pagination', 'food:read'),
'post': operation('Idempotently add a visible recipe to Cook Later', 'food:write',
{'type': 'object', 'required': ['recipe_id'], 'properties': {'recipe_id': {'type': 'string'}}}),
},
'/recipes/cook-later/{id}/': {'delete': operation('Remove recipe from Cook Later', 'food:write')},
'/recipes/create/': {'post': operation('Create own recipe with optional Idempotency-Key', 'food:write', RECIPE)},
'/recipes/{id}/': {
'get': operation('Read own recipe with ingredients, subrecipes, and variations', 'food:read'),
+2
View File
@@ -27,6 +27,8 @@ urlpatterns = [
path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry),
path('hydration/settings/', api.hydration_settings),
path('recipes/', recipe_api.recipe_search),
path('recipes/cook-later/', recipe_api.recipe_cook_later_collection),
path('recipes/cook-later/<uuid:identifier>/', recipe_api.recipe_cook_later_item),
path('recipes/create/', recipe_api.recipe_create),
path('recipes/<uuid:identifier>/', recipe_api.recipe_item),
path('recipes/<uuid:identifier>/variations/', recipe_api.recipe_variation),
+13
View File
@@ -531,6 +531,19 @@ def create_server() -> MCPServer:
async def recipe_get(recipe_id: str) -> dict[str, Any]:
return await api_request('GET', f'recipes/{recipe_id}/')
@server.tool(structured_output=True, description='Save one owned recipe to your Cook Later list. Idempotent; does not log a meal or use inventory.')
async def recipe_cook_later_add(recipe_id: str) -> dict[str, Any]:
return await api_request('POST', 'recipes/cook-later/', payload={'recipe_id': recipe_id})
@server.tool(structured_output=True, description='Remove one owned recipe from your Cook Later list. Repeated removal is safe.')
async def recipe_cook_later_remove(recipe_id: str) -> dict[str, Any]:
return await api_request('DELETE', f'recipes/cook-later/{recipe_id}/')
@server.tool(structured_output=True, description='List your Cook Later recipes with stable recipe IDs, titles, summaries and save dates. Read only.')
async def recipe_cook_later_list(search: str = '', limit: int = 20, offset: int = 0) -> dict[str, Any]:
return await api_request('GET', 'recipes/cook-later/',
params={'search': search, 'limit': limit, 'offset': offset})
@server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.')
async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
+13 -2
View File
@@ -212,9 +212,10 @@ class McpHttpTests(LiveServerTestCase):
async def check(client):
names = {tool.name for tool in (await client.list_tools()).tools}
self.assertEqual(len(names), 41)
self.assertEqual(len(names), 44)
self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product',
'inventory_import_groceries'} <= names)
'inventory_import_groceries', 'recipe_cook_later_add',
'recipe_cook_later_remove', 'recipe_cook_later_list'} <= names)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content
@@ -343,6 +344,16 @@ class McpHttpTests(LiveServerTestCase):
self.assertEqual(again['recipe']['id'], recipe_id)
self.assertEqual((await client.call_tool('recipe_search',
{'query': 'Pasta supper'})).structured_content['count'], 1)
saved = await client.call_tool('recipe_cook_later_add', {'recipe_id': recipe_id})
self.assertFalse(saved.is_error, saved)
self.assertTrue(saved.structured_content['is_cook_later'])
self.assertFalse((await client.call_tool('recipe_cook_later_add',
{'recipe_id': recipe_id})).structured_content['created'])
self.assertEqual((await client.call_tool('recipe_cook_later_list', {})).structured_content['count'], 1)
self.assertTrue((await client.call_tool('recipe_get',
{'recipe_id': recipe_id})).structured_content['is_cook_later'])
self.assertTrue((await client.call_tool('recipe_cook_later_remove',
{'recipe_id': recipe_id})).structured_content['removed'])
ingredient = (await client.call_tool('recipe_ingredient_add', {'recipe_id': recipe_id,
'ingredient': {'name': 'Pasta', 'quantity': '200', 'unit': 'g',
'inventory_product_id': str(self.a_product.api_id),
+8 -8
View File
@@ -229,7 +229,7 @@ class SleepCheckInForm(forms.ModelForm):
fields = ('wake_up_date', 'rested_score', 'watch_sleep_score', 'note')
widgets = {
'wake_up_date': forms.DateInput(attrs={'type': 'date'}),
'rested_score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'rested_score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric', 'data-severity-scale': 'positive'}),
'watch_sleep_score': forms.NumberInput(attrs={'min': 0, 'max': 100, 'inputmode': 'numeric'}),
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
}
@@ -258,7 +258,7 @@ class BowelHealthCheckInForm(forms.ModelForm):
fields = ('check_in_date', 'morning_severity', 'morning_note', 'afternoon_severity', 'afternoon_note', 'evening_severity', 'evening_note')
widgets = {
'check_in_date': forms.DateInput(attrs={'type': 'date'}),
**{f'{period}_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}) for period in ('morning', 'afternoon', 'evening')},
**{f'{period}_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric', 'data-severity-scale': 'symptom'}) for period in ('morning', 'afternoon', 'evening')},
**{f'{period}_note': forms.Textarea(attrs={'maxlength': 500, 'rows': 2}) for period in ('morning', 'afternoon', 'evening')},
}
labels = {'check_in_date': 'Date', **{f'{period}_severity': 'Gut symptoms (0–10)' for period in ('morning', 'afternoon', 'evening')}, **{f'{period}_note': 'Note (optional)' for period in ('morning', 'afternoon', 'evening')}}
@@ -294,14 +294,14 @@ class NeckHeadacheCheckInForm(forms.ModelForm):
)
widgets = {
"check_in_date": forms.DateInput(attrs={"type": "date"}),
"morning_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"morning_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"morning_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"morning_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"morning_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
"afternoon_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"afternoon_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"afternoon_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"afternoon_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"afternoon_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
"evening_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"evening_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"evening_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"evening_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric", "data-severity-scale": "symptom"}),
"evening_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
}
labels = {
@@ -22,18 +22,25 @@
}
const summary = panel.querySelector('[data-checkin-summary]');
const entered = scores.filter(Boolean);
summary.textContent = entered.length ? entered.join(' · ') : 'No scores recorded';
const base = entered.length ? entered.join(' · ') : 'No scores recorded';
summary.textContent = panel.dataset.checkinDirty === 'true' ? `${base} · Unsaved` : base;
};
const initialise = (root = document) => {
root.querySelectorAll('[data-checkin-summary-panel]').forEach(updateSummary);
root.querySelectorAll('[data-checkin-summary-panel]').forEach((panel) => {
if (panel.querySelector('.field-error, .errorlist')) panel.dataset.checkinDirty = 'true';
updateSummary(panel);
});
};
document.addEventListener('DOMContentLoaded', () => initialise());
document.addEventListener('htmx:afterSwap', (event) => initialise(event.detail.elt));
document.addEventListener('input', (event) => {
const panel = event.target.closest?.('[data-checkin-summary-panel]');
if (panel) updateSummary(panel);
if (panel) {
if (event.target.matches('[data-severity-scale]')) panel.dataset.checkinDirty = 'true';
updateSummary(panel);
}
});
document.addEventListener('change', (event) => {
const panel = event.target.closest?.('[data-checkin-summary-panel]');
@@ -0,0 +1,25 @@
.severity-scale{min-width:0;margin-top:2px}
.severity-scale__top{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:30px}
.severity-scale__value{color:#263b30;font-size:1.15rem;font-weight:800;line-height:1.2}
.severity-scale--unset .severity-scale__value{color:#58675e;font-size:.82rem;font-weight:600}
.severity-scale__clear{min-width:44px;min-height:36px;padding:4px 8px;border:0;border-radius:7px;background:transparent;color:#235943;font:600 .78rem 'DM Sans',system-ui,sans-serif;text-decoration:underline;cursor:pointer}
.severity-scale__clear:hover{background:#e7f0e9}
.severity-scale__clear:focus-visible{outline:3px solid #235943;outline-offset:2px}
.severity-scale__track{position:relative;height:48px;display:flex;align-items:center}
.severity-scale__segments{display:grid;grid-template-columns:repeat(11,minmax(0,1fr));gap:3px;width:100%;height:24px;pointer-events:none}
.severity-scale__segment{border:1px solid #aebbb0;border-radius:4px;background:#e8ede8;transition:background-color .12s ease,transform .12s ease}
.severity-scale__segment.is-filled{border-color:var(--severity-colour);background:var(--severity-colour)}
.severity-scale__segment.is-current{transform:scaleY(1.3);box-shadow:0 0 0 2px #fff,0 0 0 4px #263b30}
.field input.severity-scale__range,.checkin-form .field input.severity-scale__range{position:absolute;inset:0;width:100%;height:48px;min-height:48px;margin:0;padding:0;border:0;border-radius:4px;background:transparent;opacity:0;cursor:pointer;touch-action:pan-y}
.severity-scale__track:focus-within{outline:3px solid #235943;outline-offset:3px;border-radius:5px}
.severity-scale__ends{display:flex;justify-content:space-between;color:#56645b;font-size:.72rem;font-weight:700}
body[data-theme=dark] .severity-scale__value{color:#edf5ef}
body[data-theme=dark] .severity-scale--unset .severity-scale__value,body[data-theme=dark] .severity-scale__ends{color:#b5c5b9}
body[data-theme=dark] .severity-scale__clear{color:#b8e2c4}
body[data-theme=dark] .severity-scale__clear:hover{background:#33463a}
body[data-theme=dark] .severity-scale__segment{border-color:#6c7b70;background:#38463c}
body[data-theme=dark] .severity-scale__segment.is-filled{border-color:var(--severity-colour);background:var(--severity-colour)}
body[data-theme=dark] .severity-scale__segment.is-current{box-shadow:0 0 0 2px #263229,0 0 0 4px #f0f7f1}
body[data-theme=dark] .severity-scale__track:focus-within,body[data-theme=dark] .severity-scale__clear:focus-visible{outline-color:#b8e2c4}
@media(max-width:900px){.checkin-period__scores{grid-template-columns:1fr}}
@media(prefers-reduced-motion:reduce){.severity-scale__segment{transition:none}}
@@ -0,0 +1,115 @@
(() => {
const colours = ['#2e7654', '#39865a', '#50915a', '#779b4d', '#a49c39', '#be9235', '#cd8134', '#d06c36', '#c9583b', '#ba4440', '#a8323b'];
function enhance(input) {
if (input.dataset.severityReady) return;
const label = input.id && document.querySelector(`label[for="${input.id}"]`);
if (!label) return;
const min = Number(input.min || 0);
const max = Number(input.max || 10);
const profile = input.dataset.severityScale;
const initial = input.value;
const control = document.createElement('div');
control.className = 'severity-scale';
control.dataset.profile = profile;
const top = document.createElement('div');
top.className = 'severity-scale__top';
const value = document.createElement('output');
value.className = 'severity-scale__value';
value.htmlFor = `${input.id}-range`;
const clear = document.createElement('button');
clear.type = 'button';
clear.className = 'severity-scale__clear';
clear.textContent = 'Clear';
clear.setAttribute('aria-label', `Clear ${label.textContent.trim()}`);
top.append(value, clear);
const track = document.createElement('div');
track.className = 'severity-scale__track';
const segments = document.createElement('div');
segments.className = 'severity-scale__segments';
segments.style.gridTemplateColumns = `repeat(${max - min + 1}, minmax(0, 1fr))`;
segments.setAttribute('aria-hidden', 'true');
for (let number = min; number <= max; number += 1) {
const segment = document.createElement('span');
segment.className = 'severity-scale__segment';
const colourIndex = Math.round(((number - min) / Math.max(1, max - min)) * (colours.length - 1));
segment.style.setProperty('--severity-colour', colours[profile === 'positive' ? colours.length - 1 - colourIndex : colourIndex]);
segments.append(segment);
}
const range = document.createElement('input');
range.type = 'range';
range.id = `${input.id}-range`;
range.min = String(min);
range.max = String(max);
range.step = '1';
range.value = initial === '' ? String(min) : initial;
range.className = 'severity-scale__range';
range.setAttribute('aria-describedby', `${input.id}-value`);
value.id = `${input.id}-value`;
if (input.getAttribute('aria-describedby')) {
range.setAttribute('aria-describedby', `${input.getAttribute('aria-describedby')} ${value.id}`);
}
if (input.getAttribute('aria-invalid')) range.setAttribute('aria-invalid', input.getAttribute('aria-invalid'));
track.append(segments, range);
const ends = document.createElement('div');
ends.className = 'severity-scale__ends';
for (const endpoint of [min, max]) {
const marker = document.createElement('span');
marker.textContent = String(endpoint);
ends.append(marker);
}
control.append(top, track, ends);
const render = () => {
const selected = input.value !== '';
const number = selected ? Number(input.value) : min;
control.classList.toggle('severity-scale--unset', !selected);
value.textContent = selected ? `${number}/${max}` : 'Not recorded';
range.setAttribute('aria-valuetext', selected ? `${number} out of ${max}` : 'Not recorded');
clear.hidden = !selected;
[...segments.children].forEach((segment, index) => {
segment.classList.toggle('is-filled', selected && index <= number - min);
segment.classList.toggle('is-current', selected && index === number - min);
});
};
const sync = (eventType) => {
input.value = range.value;
render();
input.dispatchEvent(new Event(eventType, { bubbles: true }));
};
range.addEventListener('input', () => sync('input'));
range.addEventListener('change', () => sync('change'));
// A click or Home key on the minimum still records an explicit zero.
range.addEventListener('pointerdown', () => {
if (input.value === '') sync('input');
});
range.addEventListener('keydown', (event) => {
if (input.value === '' && ['Home', 'End', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) {
window.setTimeout(() => sync('input'), 0);
}
});
clear.addEventListener('click', () => {
input.value = '';
range.value = String(min);
render();
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
range.focus();
});
input.dataset.severityReady = 'true';
input.type = 'hidden';
label.htmlFor = range.id;
input.insertAdjacentElement('afterend', control);
render();
}
const initialise = (root = document) => {
root.querySelectorAll('[data-severity-scale]').forEach(enhance);
};
document.addEventListener('DOMContentLoaded', () => initialise());
document.addEventListener('htmx:afterSwap', (event) => initialise(event.detail.elt));
})();
+3 -1
View File
@@ -4,6 +4,7 @@
{% block content %}
<link rel="stylesheet" href="{% static 'planner/checkin_sections.css' %}?v=2">
<link rel="stylesheet" href="{% static 'planner/severity_scale.css' %}?v=1">
<section class="hero" aria-labelledby="health-heading">
<div>
<p class="eyebrow">Personal health tracking</p>
@@ -21,5 +22,6 @@
{% include 'planner/partials/hydration_widget.html' %}
</aside>
</div>
<script src="{% static 'planner/checkin_sections.js' %}?v=1" defer></script>
<script src="{% static 'planner/checkin_sections.js' %}?v=2" defer></script>
<script src="{% static 'planner/severity_scale.js' %}?v=2" defer></script>
{% endblock %}
+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,
})