from datetime import datetime import functools from django.core.management.base import BaseCommand, CommandError import faker import pytz from room.models import Room, Parcours import string import random import uuid class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): parser.add_argument('parcoursId', nargs='+', type=str) parser.add_argument('number', nargs='+', type=int) def handle(self, *args, **options): try: parcours = Parcours.objects.get(id_code=options['parcoursId'][0]) except: raise CommandError(f'Parcours "{options["parcoursId"][0]}" does not exist') participants = [*parcours.room.anonymousMembers, * [{'code': u.id_code, 'nick': u.username, 'clientId': u.clientId} for u in parcours.room.userMembers.all()]] new_challengers = parcours.challenger if len(parcours.exercices) != 1: maxNote = functools.reduce(lambda a, b:{'number': a['number'] + b['number']}, parcours.exercices )['number'] else: maxNote = parcours.exercices[0]['number'] for i in range(options['number'][0]): challenger = random.choice(participants) if challenger['code'] in [n['code'] for n in new_challengers]: index = [i for i, n in enumerate( new_challengers) if n['code'] == challenger['code']][0] while True: code = ''.join(random.choices(string.ascii_uppercase, k=6)) if code not in [p['code'] for p in new_challengers[index]['exos']]: break now = datetime.now() date = str(now.astimezone(pytz.timezone('Europe/Berlin'))) fake = faker.Faker() date = str(fake.date_time_this_month()) new_challengers[index] = { **new_challengers[index], 'exos': [*new_challengers[index]['exos'], {'result': [], 'endAt': date, 'timer': random.randint(1, parcours.timer * 60), 'note': {'value': random.randint(0, maxNote), 'total': maxNote, 'isTrust': True}, 'code': code}]} else: code = ''.join(random.choices(string.ascii_uppercase, k=6)) now = datetime.now() date = str(now.astimezone(pytz.timezone('Europe/Berlin'))) fake = faker.Faker() date = str(fake.date_time_this_month()) new_challengers.append({**challenger, 'validate': False, 'exos': [{'result': [], 'endAt': date, 'timer': random.randint( 1, parcours.timer * 60), 'note': {'value': random.randint(0, maxNote), 'total': maxNote, 'isTrust': True, }, 'code': code}]}) parcours.challenger = new_challengers parcours.save() self.stdout.write(self.style.SUCCESS( f'Successfully added {options["number"][0]} challenges to parcours {options["parcoursId"][0]}'))