52 lines
2.5 KiB
Python
52 lines
2.5 KiB
Python
"""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}.'))
|