From 2934662d7a1963c01f2e226b2033e05a77c2372c Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Mon, 12 Oct 2026 16:25:58 +0200 Subject: [PATCH] Recipes phase 6 --- main/recipes/MATCH.md | 25 ++++ main/recipes/management/__init__.py | 0 main/recipes/management/commands/__init__.py | 0 .../management/commands/seed_recipe_match.py | 51 ++++++++ .../migrations/0005_recipeselection.py | 28 +++++ main/recipes/models.py | 14 +++ main/recipes/static/recipes/match.css | 6 + main/recipes/static/recipes/match.js | 115 ++++++++++++++++++ main/recipes/templates/recipes/library.html | 2 +- main/recipes/templates/recipes/match.html | 39 ++++++ main/recipes/test_match.py | 70 +++++++++++ main/recipes/urls.py | 3 + main/recipes/views.py | 71 ++++++++++- main/tasksnest/settings.py | 3 + 14 files changed, 425 insertions(+), 2 deletions(-) create mode 100644 main/recipes/MATCH.md create mode 100644 main/recipes/management/__init__.py create mode 100644 main/recipes/management/commands/__init__.py create mode 100644 main/recipes/management/commands/seed_recipe_match.py create mode 100644 main/recipes/migrations/0005_recipeselection.py create mode 100644 main/recipes/static/recipes/match.css create mode 100644 main/recipes/static/recipes/match.js create mode 100644 main/recipes/templates/recipes/match.html create mode 100644 main/recipes/test_match.py diff --git a/main/recipes/MATCH.md b/main/recipes/MATCH.md new file mode 100644 index 0000000..3156bc8 --- /dev/null +++ b/main/recipes/MATCH.md @@ -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. diff --git a/main/recipes/management/__init__.py b/main/recipes/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/recipes/management/commands/__init__.py b/main/recipes/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main/recipes/management/commands/seed_recipe_match.py b/main/recipes/management/commands/seed_recipe_match.py new file mode 100644 index 0000000..136f6b7 --- /dev/null +++ b/main/recipes/management/commands/seed_recipe_match.py @@ -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}.')) diff --git a/main/recipes/migrations/0005_recipeselection.py b/main/recipes/migrations/0005_recipeselection.py new file mode 100644 index 0000000..ab21999 --- /dev/null +++ b/main/recipes/migrations/0005_recipeselection.py @@ -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')], + }, + ), + ] diff --git a/main/recipes/models.py b/main/recipes/models.py index 51b3a8b..dee4d76 100644 --- a/main/recipes/models.py +++ b/main/recipes/models.py @@ -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' diff --git a/main/recipes/static/recipes/match.css b/main/recipes/static/recipes/match.css new file mode 100644 index 0000000..0626dc4 --- /dev/null +++ b/main/recipes/static/recipes/match.css @@ -0,0 +1,6 @@ +.recipes-match-link{display:inline-block;margin-top:9px;color:#235943;font-size:.83rem;font-weight:700;text-decoration:none}.recipes-match-link:hover{text-decoration:underline}body[data-theme=dark] .recipes-match-link{color:#a7d9b6} +.recipe-match{max-width:1040px;margin:auto;color:var(--recipe-ink,#25292e)}.recipe-match *{box-sizing:border-box}.recipe-match__header{margin-bottom:22px}.recipe-match__header h1{margin:6px 0;font-size:clamp(2rem,4vw,3.2rem);line-height:1.1}.recipe-match__header h1 span{color:#e94f78}.recipe-match__header p:last-child{margin:0;color:var(--recipe-muted,#687178)}.recipe-match__eyebrow{margin:23px 0 4px;color:#a44cbe;font-size:.75rem;font-weight:800;letter-spacing:.09em;text-transform:uppercase}.recipe-match__filters{display:flex;flex-wrap:wrap;align-items:end;gap:9px;margin-bottom:28px;padding:15px;border:1px solid var(--recipe-line,#e4e8e2);border-radius:15px;background:var(--recipe-surface,#fff)}.recipe-match__filters label{display:grid;flex:1 1 135px;gap:5px;font-size:.73rem;font-weight:700}.recipe-match__filters label:first-child{flex:2 1 210px}.recipe-match__filters input,.recipe-match__filters select{width:100%;min-height:44px;padding:9px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:9px;color:inherit;background:var(--recipe-surface,#fff)}.recipe-match__filters button{min-height:44px;padding:9px 15px;border:0;border-radius:9px;color:#fff;background:#235943;font-weight:700;cursor:pointer}.recipe-match__stage{display:grid;justify-items:center;min-height:530px}.recipe-match__counter{min-height:20px;margin:0 0 12px;color:var(--recipe-muted,#687178);font-size:.82rem}.recipe-match__deck{width:min(100%,380px)}.recipe-match__card{position:relative;overflow:hidden;width:100%;border:1px solid var(--recipe-line,#e4e8e2);border-radius:20px;background:var(--recipe-surface,#fff);box-shadow:0 18px 45px rgba(24,40,30,.16);touch-action:pan-y;user-select:none;transition:transform .23s ease,opacity .23s ease}.recipe-match__card[hidden],.recipe-match__celebration[hidden]{display:none!important}.recipe-match__card.is-leaving{opacity:0;transform:translateX(var(--match-exit,0)) rotate(var(--match-tilt,0deg))}.recipe-match__image{position:relative;height:320px;overflow:hidden;background:linear-gradient(135deg,#e6efe6,#f5e9e5)}.recipe-match__image img,.recipe-match__image-fallback{width:100%;height:100%;object-fit:cover}.recipe-match__image-fallback{display:grid;place-items:center;background:radial-gradient(circle at 35% 25%,#f8e3c7,#cee7d4);font-size:5rem}.recipe-match__stamp{position:absolute;top:24px;right:17px;padding:8px 16px;border:3px solid currentColor;border-radius:10px;color:#22a65a;background:rgba(255,255,255,.9);font-size:1.4rem;font-weight:900;transform:rotate(11deg);opacity:0}.recipe-match__stamp.is-visible{opacity:1}.recipe-match__stamp.is-skip{color:#7f8490;transform:rotate(-11deg)}.recipe-match__card-body{padding:18px 20px 22px}.recipe-match__card-body h2{margin:3px 0 7px;font-family:Fraunces,Georgia,serif;font-size:1.5rem;line-height:1.2}.recipe-match__kind{margin:0;color:#337b56;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.recipe-match__meta{display:flex;flex-wrap:wrap;gap:14px;margin:0;color:var(--recipe-muted,#687178);font-size:.83rem}.recipe-match__tags{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}.recipe-match__tags span{padding:5px 9px;border-radius:999px;background:#edf1ed;font-size:.72rem}.recipe-match__actions{display:flex;justify-content:center;gap:36px;margin:24px 0 10px}.recipe-match__actions button{display:grid;place-items:center;width:72px;height:72px;padding:4px;border:0;border-radius:50%;box-shadow:0 7px 18px rgba(0,0,0,.13);cursor:pointer}.recipe-match__actions button span{font-size:2.25rem;line-height:1}.recipe-match__actions button small{font-size:.65rem;font-weight:800}.recipe-match__skip{color:#1e2930;background:#fff}.recipe-match__select{color:#fff;background:#e94f78}.recipe-match__actions button:disabled{opacity:.45;cursor:default}.recipe-match__hint,.recipe-match__status,.recipe-match__setup{text-align:center;color:var(--recipe-muted,#687178);font-size:.8rem}.recipe-match__setup,.recipe-match__empty{padding:16px;border-radius:12px;background:var(--recipe-surface,#fff)}.recipe-match__celebration{position:absolute;inset:0;display:grid;align-items:end;justify-items:center;overflow:hidden;background:linear-gradient(transparent 20%,rgba(12,29,23,.38) 65%,rgba(12,29,23,.55))}.recipe-match__celebration-copy{position:relative;z-index:2;width:calc(100% - 28px);margin:0 14px 18px;padding:17px;border-radius:16px;background:#fff;color:#202b2a;text-align:center;box-shadow:0 9px 28px rgba(0,0,0,.2)}.recipe-match__celebration-copy>span{font-size:1.6rem}.recipe-match__celebration-copy h3{margin:4px 0;font-size:1.45rem}.recipe-match__celebration-copy p{margin:0 0 12px;font-size:.81rem}.recipe-match__celebration-copy button{width:100%;min-height:44px;border:0;border-radius:999px;color:#fff;background:#25a65a;font-weight:800;cursor:pointer}.recipe-match__celebration-copy a{display:block;margin-top:9px;color:#235943;font-size:.8rem}.recipe-match__confetti{position:absolute;inset:0;pointer-events:none}.recipe-match__confetti i{position:absolute;top:40%;left:50%;width:8px;height:14px;border-radius:2px;background:var(--confetti-color);animation:match-confetti .85s ease-out forwards}@keyframes match-confetti{to{opacity:0;transform:translate(var(--confetti-x),var(--confetti-y)) rotate(480deg)}}.recipe-match :is(a,button,input,select):focus-visible{outline:3px solid #a44cbe;outline-offset:3px}body[data-theme=dark] .recipe-match__tags span{background:#354339}body[data-theme=dark] .recipe-match__filters button{background:#32734c}body[data-theme=dark] .recipe-match__skip{color:#253129} +@media(max-width:600px){.recipe-match__filters{padding:12px}.recipe-match__filters label{flex-basis:calc(50% - 9px)}.recipe-match__filters label:first-child{flex-basis:100%}.recipe-match__filters button{width:100%}.recipe-match__image{height:min(76vw,320px)}.recipe-match__stage{min-height:0}.recipe-match__actions{margin-top:18px}} +@media(prefers-reduced-motion:reduce){.recipe-match__card{transition:none}.recipe-match__confetti i{animation:none;display:none}} +.recipe-match{--recipe-surface:#fff;--recipe-line:#e4e8e2;--recipe-ink:#25292e;--recipe-muted:#687178}body[data-theme=dark] .recipe-match{--recipe-surface:#202a23;--recipe-line:#435046;--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2} +.recipe-match__celebration{bottom:auto;height:320px}@media(max-width:600px){.recipe-match__celebration{height:min(76vw,320px)}} diff --git a/main/recipes/static/recipes/match.js b/main/recipes/static/recipes/match.js new file mode 100644 index 0000000..49cbe62 --- /dev/null +++ b/main/recipes/static/recipes/match.js @@ -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(); +})(); diff --git a/main/recipes/templates/recipes/library.html b/main/recipes/templates/recipes/library.html index 56c6eab..a412ad6 100644 --- a/main/recipes/templates/recipes/library.html +++ b/main/recipes/templates/recipes/library.html @@ -6,7 +6,7 @@