Recipes phase 6
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
# Recipe Match demo
|
||||
|
||||
Run the Recipes migration, then open **Recipes → Try Recipe Match** (`/recipes/match/`). The demo uses existing recipes. It does not change the normal recipe library, inventory, or Food Diary.
|
||||
|
||||
The demo account is selected by `TASKNEST_RECIPE_MATCH_DEMO_USERNAME` (default: `demo`). Only that account's **published** recipes are shown to other users in this view. Each user also sees their own recipes. Other users' recipes remain private. The normal recipe detail and photo routes retain their owner checks; published demo photos use a separate match-only route.
|
||||
|
||||
Seed selections from up to ten published recipes owned by the demo account:
|
||||
|
||||
```sh
|
||||
python manage.py seed_recipe_match
|
||||
```
|
||||
|
||||
If the demo account has no published recipes, an operator can explicitly select a participant's existing recipes for the demo account. Those recipes appear only to their owner; this does not copy or expose them to other users:
|
||||
|
||||
```sh
|
||||
python manage.py seed_recipe_match --source-username PARTICIPANT --reset-demo
|
||||
```
|
||||
|
||||
For another run, reset the participant's selections, then visit Recipe Match again:
|
||||
|
||||
```sh
|
||||
python manage.py seed_recipe_match --reset-user PARTICIPANT
|
||||
```
|
||||
|
||||
`--reset-demo` clears and rebuilds only the demo account's selections. The command never creates or duplicates recipes. Selection is idempotent, and skipped cards reappear on a fresh visit. No matching presence or messaging is involved.
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Seed or reset the isolated Recipe Match proof of concept."""
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.db import transaction
|
||||
|
||||
from recipes.models import Recipe, RecipeSelection
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Select existing published demo recipes, or reset one participant for another demo.'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument('--source-username', help='Select existing recipes owned by this participant for the demo.')
|
||||
parser.add_argument('--reset-user', help='Clear only this user’s Recipe Match selections.')
|
||||
parser.add_argument('--reset-demo', action='store_true', help='Clear demo selections before seeding.')
|
||||
|
||||
@transaction.atomic
|
||||
def handle(self, *args, **options):
|
||||
username = settings.RECIPE_MATCH_DEMO_USERNAME
|
||||
if not username:
|
||||
raise CommandError('Set TASKNEST_RECIPE_MATCH_DEMO_USERNAME first.')
|
||||
demo = get_user_model().objects.filter(username=username, is_active=True).first()
|
||||
if demo is None:
|
||||
raise CommandError(f'Active demo account {username!r} not found. Create it first.')
|
||||
if options['reset_user']:
|
||||
user = get_user_model().objects.filter(username=options['reset_user']).first()
|
||||
if user is None:
|
||||
raise CommandError('Reset user not found.')
|
||||
removed, _ = RecipeSelection.objects.filter(user=user).delete()
|
||||
self.stdout.write(self.style.SUCCESS(f'Cleared {removed} selections for {user.username}.'))
|
||||
if user.pk != demo.pk:
|
||||
return
|
||||
source = demo
|
||||
if options['source_username']:
|
||||
source = get_user_model().objects.filter(username=options['source_username'], is_active=True).first()
|
||||
if source is None:
|
||||
raise CommandError('Source user not found or inactive.')
|
||||
recipes = Recipe.objects.filter(owner=source)
|
||||
if source.pk == demo.pk:
|
||||
recipes = recipes.filter(status=Recipe.Status.PUBLISHED)
|
||||
recipes = list(recipes.order_by('pk')[:10])
|
||||
if not recipes:
|
||||
raise CommandError('No eligible recipes found for this account.')
|
||||
if options['reset_demo']:
|
||||
RecipeSelection.objects.filter(user=demo).delete()
|
||||
for recipe in recipes:
|
||||
RecipeSelection.objects.get_or_create(user=demo, recipe=recipe)
|
||||
self.stdout.write(self.style.SUCCESS(
|
||||
f'Demo selected {len(recipes)} existing recipes from {source.username}.'))
|
||||
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-12 13:30
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('recipes', '0004_recipecookingrun'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='RecipeSelection',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('selected_at', models.DateTimeField(auto_now_add=True)),
|
||||
('recipe', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_selections', to='recipes.recipe')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipe_match_selections', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'constraints': [models.UniqueConstraint(fields=('user', 'recipe'), name='recipes_unique_user_selection')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -76,6 +76,20 @@ class Recipe(models.Model):
|
||||
return self.title
|
||||
|
||||
|
||||
class RecipeSelection(models.Model):
|
||||
"""One user's selection of an existing recipe for the matching demo."""
|
||||
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
related_name='recipe_match_selections')
|
||||
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE,
|
||||
related_name='match_selections')
|
||||
selected_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'recipe'),
|
||||
name='recipes_unique_user_selection')]
|
||||
|
||||
|
||||
class RecipeIngredient(models.Model):
|
||||
class Unit(models.TextChoices):
|
||||
GRAM = 'g', 'g'
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,115 @@
|
||||
(() => {
|
||||
const deck = document.querySelector('[data-match-deck]');
|
||||
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 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]; }
|
||||
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.';
|
||||
}
|
||||
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');
|
||||
window.setTimeout(() => {
|
||||
card.classList.remove('is-leaving');
|
||||
card.style.transform = '';
|
||||
index += 1;
|
||||
busy = false;
|
||||
update();
|
||||
if (moveFocus) {
|
||||
if (skip && !skip.disabled) skip.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');
|
||||
}
|
||||
async function selectCurrent() {
|
||||
if (busy || !current()) return;
|
||||
busy = true;
|
||||
const card = current();
|
||||
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.');
|
||||
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');
|
||||
}
|
||||
} catch (error) {
|
||||
status.textContent = error.message;
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
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;
|
||||
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();
|
||||
});
|
||||
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;
|
||||
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);
|
||||
update();
|
||||
})();
|
||||
@@ -6,7 +6,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></div>
|
||||
<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>
|
||||
<a class="button recipes-new" href="{% url 'recipes:create' %}">+ New recipe</a>
|
||||
</div>
|
||||
<form method="get" action="{% url 'recipes:list' %}" class="recipes-filters" role="search">
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Recipe Match · 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=2">
|
||||
<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>
|
||||
</header>
|
||||
<form class="recipe-match__filters" method="get" role="search" aria-label="Filter recipe cards">
|
||||
<label>Search<input type="search" name="q" value="{{ query }}" placeholder="Title or ingredient"></label>
|
||||
<label>Category<select name="category"><option value="">All categories</option>{% for value in categories %}<option value="{{ value }}"{% if value == category %} selected{% endif %}>{{ value }}</option>{% endfor %}</select></label>
|
||||
<label>Tag<select name="tag"><option value="">All tags</option>{% for value in tags %}<option value="{{ value }}"{% if value == tag %} selected{% endif %}>{{ value }}</option>{% endfor %}</select></label>
|
||||
<label>Time<select name="time"><option value="">Any time</option><option value="30"{% if time_limit == '30' %} selected{% endif %}>Up to 30 min</option><option value="60"{% if time_limit == '60' %} selected{% endif %}>Up to 60 min</option></select></label>
|
||||
<button type="submit">Apply filters</button>
|
||||
</form>
|
||||
<section class="recipe-match__stage" aria-label="Recipe discovery">
|
||||
<p class="recipe-match__counter" data-match-counter aria-live="polite"></p>
|
||||
<div class="recipe-match__deck" data-match-deck>
|
||||
{% for recipe in recipes %}
|
||||
<article class="recipe-match__card" data-match-card data-select-url="{% url 'recipes:match-select' recipe.api_id %}" data-detail-url="{% if recipe.owner_id == request.user.pk %}{% url 'recipes:detail' recipe.api_id %}{% endif %}"{% if not forloop.first %} hidden{% endif %}>
|
||||
<div class="recipe-match__image">
|
||||
{% 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>
|
||||
</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 %}
|
||||
<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 'recipes/match.js' %}?v=4" defer></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,70 @@
|
||||
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
|
||||
|
||||
|
||||
@override_settings(RECIPE_MATCH_DEMO_USERNAME='match-demo')
|
||||
class RecipeMatchTests(TestCase):
|
||||
def setUp(self):
|
||||
users = get_user_model()
|
||||
self.user = users.objects.create_user(username='visitor', password='test')
|
||||
self.demo = users.objects.create_user(username='match-demo', password='test')
|
||||
self.other = users.objects.create_user(username='other', password='test')
|
||||
self.recipe = Recipe.objects.create(owner=self.demo, title='Lemon salmon',
|
||||
category='Dinner', tags=['Fish'],
|
||||
preparation_minutes=10, cooking_minutes=15,
|
||||
status=Recipe.Status.PUBLISHED)
|
||||
self.private = Recipe.objects.create(owner=self.demo, title='Private cake')
|
||||
self.foreign = Recipe.objects.create(owner=self.other, title='Foreign meal',
|
||||
status=Recipe.Status.PUBLISHED)
|
||||
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):
|
||||
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.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)
|
||||
|
||||
def test_select_is_idempotent_and_matches_server_side(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.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_seed_and_reset_uses_existing_demo_recipes(self):
|
||||
self.recipe.status = Recipe.Status.DRAFT
|
||||
self.recipe.save(update_fields=('status',))
|
||||
with self.assertRaises(CommandError):
|
||||
call_command('seed_recipe_match')
|
||||
self.recipe.status = Recipe.Status.PUBLISHED
|
||||
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())
|
||||
@@ -6,6 +6,9 @@ app_name = 'recipes'
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.library, name='list'),
|
||||
path('match/', views.match, name='match'),
|
||||
path('match/<uuid:identifier>/select/', views.match_select, name='match-select'),
|
||||
path('match/<uuid:identifier>/photo/', views.match_photo, name='match-photo'),
|
||||
path('new/', views.create, name='create'),
|
||||
path('new/autosave/', views.autosave_new, name='autosave-new'),
|
||||
path('<uuid:identifier>/', views.detail, name='detail'),
|
||||
|
||||
+70
-1
@@ -1,7 +1,9 @@
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
@@ -16,7 +18,8 @@ from PIL import Image
|
||||
|
||||
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
|
||||
RecipeSubstitutionForm)
|
||||
from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse
|
||||
from .models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution,
|
||||
RecipeSelection, RecipeSubrecipe, RecipeUse)
|
||||
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
|
||||
@@ -27,6 +30,62 @@ def _owned(user):
|
||||
return Recipe.objects.filter(owner=user)
|
||||
|
||||
|
||||
def _match_demo_user():
|
||||
username = settings.RECIPE_MATCH_DEMO_USERNAME
|
||||
return get_user_model().objects.filter(username=username, is_active=True).first() if username else None
|
||||
|
||||
|
||||
def _match_recipes(user):
|
||||
demo = _match_demo_user()
|
||||
visible = Q(owner=user)
|
||||
if demo and demo.pk != user.pk:
|
||||
visible |= Q(owner=demo, status=Recipe.Status.PUBLISHED)
|
||||
return Recipe.objects.filter(visible)
|
||||
|
||||
|
||||
@login_required
|
||||
def match(request):
|
||||
demo = _match_demo_user()
|
||||
recipes = _match_recipes(request.user).exclude(match_selections__user=request.user)
|
||||
query = request.GET.get('q', '').strip()[:100]
|
||||
category = request.GET.get('category', '').strip()[:80]
|
||||
tag = request.GET.get('tag', '').strip()[:40]
|
||||
time_limit = request.GET.get('time', '').strip()
|
||||
if query:
|
||||
recipes = recipes.filter(Q(title__icontains=query) | Q(description__icontains=query) |
|
||||
Q(ingredients__name__icontains=query)).distinct()
|
||||
if category:
|
||||
recipes = recipes.filter(category=category)
|
||||
if time_limit in {'30', '60'}:
|
||||
recipes = [item for item in recipes if item.total_minutes <= int(time_limit)]
|
||||
else:
|
||||
recipes = list(recipes)
|
||||
if tag:
|
||||
recipes = [item for item in recipes if tag in item.tags]
|
||||
recipes = recipes[:50]
|
||||
visible = _match_recipes(request.user)
|
||||
categories = list(visible.exclude(category='').values_list('category', flat=True).distinct().order_by('category'))
|
||||
tags = sorted({name for values in visible.values_list('tags', flat=True)
|
||||
if isinstance(values, list) for name in values if isinstance(name, str)})
|
||||
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()),
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@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})
|
||||
|
||||
|
||||
def _library(request, selected=None):
|
||||
explicit_detail = selected is not None
|
||||
recipes = _owned(request.user).prefetch_related('ingredients')
|
||||
@@ -399,6 +458,16 @@ def toggle_favourite(request, identifier):
|
||||
@login_required
|
||||
def photo(request, identifier):
|
||||
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
|
||||
return _photo_response(recipe)
|
||||
|
||||
|
||||
@login_required
|
||||
def match_photo(request, identifier):
|
||||
recipe = get_object_or_404(_match_recipes(request.user), api_id=identifier)
|
||||
return _photo_response(recipe)
|
||||
|
||||
|
||||
def _photo_response(recipe):
|
||||
if not recipe.photo:
|
||||
from django.http import Http404
|
||||
raise Http404
|
||||
|
||||
@@ -47,6 +47,9 @@ INSTALLED_APPS = [
|
||||
'recipes',
|
||||
]
|
||||
|
||||
# Published recipes owned by this account may appear in the optional matching demo.
|
||||
RECIPE_MATCH_DEMO_USERNAME = os.environ.get('TASKNEST_RECIPE_MATCH_DEMO_USERNAME', 'demo')
|
||||
|
||||
MIDDLEWARE = [
|
||||
'food.api_middleware.ApiErrorMiddleware',
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
|
||||
Reference in New Issue
Block a user