annuaire-eleves/fiches/management/commands/add_conscrits.py
2020-11-21 17:45:55 +01:00

100 lines
3.3 KiB
Python

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()
verbosity = options["verbosity"]
# On récupère la liste des élèves à créer
ldap = ClipperLDAP()
clipper_list = ldap.get_clipper_list(
promo_filter=promo, verbosity=verbosity, stdout=self.stdout
)
# 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]
)
)
# À décommenter pour utilisation locale (avec SQLite)
def _manual_ids(cls, to_create):
pid = getattr(cls.objects.order_by("-id").first(), "id", 1)
for p in to_create:
pid += 1
p.id = pid
_manual_ids(User, users_to_create)
_manual_ids(Profile, profiles_to_create)
_manual_ids(Profile.department.through, dept_m2m_to_create)
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)
if verbosity >= 1:
self.stdout.write(
(
"Création de {} utilisateur·ices et de {}"
" profils effectuée avec succès"
).format(len(users_to_create), len(profiles_to_create))
)