from datetime import date from django.contrib.auth.models import User from django.core.management.base import BaseCommand from fiches.models import Department, Profile from ._ldap import ClipperLDAP class Command(BaseCommand): help = "Crée les fiches annuaire des conscrit·e·s automatiquement" def add_arguments(self, parser): group = parser.add_mutually_exclusive_group() group.add_argument( "--all", action="store_true", help="Importe l'intégralité des promotions" ) group.add_argument("--promo", type=int, help="Spécifie la promotion à importer") def get_current_promo(self): today = date.today() year = today.year if today.month < 9: year -= 1 return year def handle(self, *args, **options): if options["all"]: promo = None elif options["promo"] is not None: promo = options["promo"] if promo < 100: promo = 2000 + promo else: promo = self.get_current_promo() # On récupère la liste des élèves à créer ldap = ClipperLDAP() clipper_list = ldap.get_clipper_list(promo_filter=promo) # On vire les élèves déjà existants existing_users = set(User.objects.values_list("username", flat=True)) clippers = [ clipper for clipper in clipper_list if clipper.uid not in existing_users ] # Les départements sont créés à la main ; il y en a peu. depts = { dept: Department.objects.get_or_create(name=dept)[0].id for dept in ldap.verbose_depts.values() } users_to_create = [] profiles_to_create = [] dept_m2m_to_create = [] for clipper in clippers: user = User(username=clipper.uid, email=clipper.email) profile = Profile(user=user, full_name=clipper.name, promotion=clipper.year) users_to_create.append(user) profiles_to_create.append(profile) dept_m2m_to_create.append( Profile.department.through( profile=profile, department_id=depts[clipper.dept] ) ) User.objects.bulk_create(users_to_create) for profile in profiles_to_create: profile.user_id = profile.user.id Profile.objects.bulk_create(profiles_to_create) for dept_m2m in dept_m2m_to_create: dept_m2m.profile_id = dept_m2m.profile.id Profile.department.through.objects.bulk_create(dept_m2m_to_create) print( "Création de {} utilisateur·ices et de {} profils effectuée avec succès".format( len(users_to_create), len(profiles_to_create) ) )