Files
n3wt-school/Back-End/School/management/commands/init_mock_datas.py
2025-03-06 20:38:09 +01:00

296 lines
12 KiB
Python

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from Subscriptions.models import (
RegistrationForm,
Student,
Guardian,
Fee,
Discount,
RegistrationFileGroup,
RegistrationTemplateMaster,
RegistrationTemplate
)
from Auth.models import Profile
from School.models import (
Establishment,
FeeType,
Speciality,
Teacher,
SchoolClass,
PaymentMode,
PaymentModeType,
PaymentPlan,
PaymentPlanType,
StructureType,
DiscountType
)
from django.utils import timezone
from dateutil.relativedelta import relativedelta
from django.core.files import File
from django.core.exceptions import SuspiciousFileOperation
import os
from django.conf import settings
from faker import Faker
import random
import json
# Définir le chemin vers le dossier mock_datas
MOCK_DATAS_PATH = os.path.join(settings.BASE_DIR, 'School', 'management', 'mock_datas')
class Command(BaseCommand):
help = 'Initialise toutes les données mock'
def handle(self, *args, **kwargs):
self.create_or_update_establishments()
self.create_or_update_fees()
self.create_or_update_discounts()
self.create_or_update_payment_modes()
self.create_or_update_payment_plans()
self.create_or_update_specialities()
self.create_or_update_teachers()
self.create_or_update_school_classes()
self.create_or_update_registration_file_group()
self.create_register_form()
def load_data(self, filename):
with open(os.path.join(MOCK_DATAS_PATH, filename), 'r') as file:
return json.load(file)
def create_or_update_establishments(self):
establishments_data = self.load_data('establishments.json')
self.establishments = []
for establishment_data in establishments_data:
establishment, created = Establishment.objects.update_or_create(
name=establishment_data["name"],
defaults=establishment_data
)
self.establishments.append(establishment)
if created:
self.stdout.write(self.style.SUCCESS(f'Establishment {establishment.name} created successfully'))
else:
self.stdout.write(self.style.SUCCESS(f'Establishment {establishment.name} updated successfully'))
def create_or_update_fees(self):
fees_data = self.load_data('fees.json')
for fee_data in fees_data:
establishment = random.choice(self.establishments)
fee_data["name"] = f"{fee_data['name']} - {establishment.name}"
fee_data["establishment"] = establishment
Fee.objects.update_or_create(
name=fee_data["name"],
type=fee_data["type"],
defaults=fee_data
)
self.stdout.write(self.style.SUCCESS('Fees initialized or updated successfully'))
def create_or_update_discounts(self):
discounts_data = self.load_data('discounts.json')
for discount_data in discounts_data:
establishment = random.choice(self.establishments)
discount_data["name"] = f"{discount_data['name']} - {establishment.name}"
discount_data["establishment"] = establishment
Discount.objects.update_or_create(
name=discount_data["name"],
type=discount_data["type"],
discount_type=discount_data["discount_type"],
defaults=discount_data
)
self.stdout.write(self.style.SUCCESS('Discounts initialized or updated successfully'))
def create_or_update_payment_modes(self):
payment_modes_data = self.load_data('payment_modes.json')
for payment_mode_data in payment_modes_data:
establishment = random.choice(self.establishments)
payment_mode_data["establishment"] = establishment
PaymentMode.objects.update_or_create(
mode=payment_mode_data["mode"],
type=payment_mode_data["type"],
defaults=payment_mode_data
)
self.stdout.write(self.style.SUCCESS('Payment Modes initialized or updated successfully'))
def create_or_update_payment_plans(self):
payment_plans_data = self.load_data('payment_plans.json')
current_date = timezone.now().date()
for payment_plan_data in payment_plans_data:
establishment = random.choice(self.establishments)
payment_plan_data["establishment"] = establishment
payment_plan_data["due_dates"] = [current_date + relativedelta(months=1)]
if payment_plan_data["frequency"] == PaymentPlanType.THREE_TIMES:
payment_plan_data["due_dates"] = [current_date + relativedelta(months=1+4*i) for i in range(3)]
elif payment_plan_data["frequency"] == PaymentPlanType.TEN_TIMES:
payment_plan_data["due_dates"] = [current_date + relativedelta(months=1+i) for i in range(10)]
elif payment_plan_data["frequency"] == PaymentPlanType.TWELVE_TIMES:
payment_plan_data["due_dates"] = [current_date + relativedelta(months=1+i) for i in range(12)]
PaymentPlan.objects.update_or_create(
frequency=payment_plan_data["frequency"],
type=payment_plan_data["type"],
defaults=payment_plan_data
)
self.stdout.write(self.style.SUCCESS('Payment Plans initialized or updated successfully'))
def create_or_update_specialities(self):
specialities_data = self.load_data('specialities.json')
for speciality_data in specialities_data:
Speciality.objects.update_or_create(
name=speciality_data["name"],
defaults=speciality_data
)
self.stdout.write(self.style.SUCCESS('Specialities initialized or updated successfully'))
def create_or_update_teachers(self):
teachers_data = self.load_data('teachers.json')
for teacher_data in teachers_data:
specialities = teacher_data.pop("specialities")
email = teacher_data["email"]
droit = teacher_data.pop("droit")
establishment = random.choice(self.establishments)
# Create or update the user profile
user, created = Profile.objects.update_or_create(
email=email,
defaults={
"username": email,
"email": email,
"is_active": True,
"password": "Provisoire01!",
"droit": droit,
"establishment": establishment
}
)
if created:
user.set_password("Provisoire01!")
user.save()
# Create or update the teacher
teacher, created = Teacher.objects.update_or_create(
email=email,
defaults={**teacher_data, "associated_profile_id": user.id}
)
teacher.specialities.set(Speciality.objects.filter(name__in=specialities))
teacher.save()
self.stdout.write(self.style.SUCCESS('Teachers initialized or updated successfully'))
def create_or_update_school_classes(self):
school_classes_data = self.load_data('school_classes.json')
for index, class_data in enumerate(school_classes_data, start=1):
teachers_ids = class_data.pop("teachers")
establishment = random.choice(self.establishments)
class_data["atmosphere_name"] = f"Classe {index} - {establishment.name}"
class_data["establishment"] = establishment
school_class, created = SchoolClass.objects.update_or_create(
atmosphere_name=class_data["atmosphere_name"],
school_year=class_data["school_year"],
defaults=class_data
)
school_class.teachers.set(teachers_ids)
school_class.save()
self.stdout.write(self.style.SUCCESS('SchoolClasses initialized or updated successfully'))
def create_or_update_registration_file_group(self):
file_groups_data = self.load_data('file_groups.json')
for group_data in file_groups_data:
RegistrationFileGroup.objects.update_or_create(name=group_data["name"], defaults=group_data)
self.stdout.write(self.style.SUCCESS(f'RegistrationFileGroup {group_data["name"]} initialized or updated successfully'))
def create_register_form(self):
fake = Faker('fr_FR') # Utiliser le locale français pour Faker
file_group_count = RegistrationFileGroup.objects.count()
for _ in range(50):
establishment = random.choice(self.establishments)
# Générer des données fictives pour le profil
profile_data = {
"email": fake.email(),
"droit": 2,
"username": fake.user_name(),
"is_active": True,
"password": "Provisoire01!",
"establishment": establishment
}
user, created = Profile.objects.update_or_create(
email=profile_data["email"],
defaults={
"username": profile_data["username"],
"email": profile_data["email"],
"is_active": profile_data["is_active"],
"droit": profile_data["droit"],
"establishment": profile_data["establishment"]
}
)
if created:
user.set_password(profile_data["password"])
user.save()
# Générer des données fictives pour le guardian
guardian_data = {
"associated_profile_id": user.id,
"email": profile_data["email"],
}
# Générer des données fictives pour l'étudiant
student_data = {
"last_name": f"{fake.last_name()} - {establishment.name}",
"first_name": fake.first_name(),
"address": fake.address(),
"birth_date": fake.date_of_birth(),
"birth_place": fake.city(),
"birth_postal_code": fake.postcode(),
"nationality": fake.country(),
"attending_physician": fake.name(),
"level": fake.random_int(min=1, max=6)
}
# Créer ou mettre à jour l'étudiant et le guardian
student, created = Student.objects.get_or_create(
last_name=student_data["last_name"],
first_name=student_data["first_name"],
defaults=student_data
)
guardian, created = Guardian.objects.get_or_create(
last_name=guardian_data["email"],
defaults=guardian_data
)
student.guardians.add(guardian)
# Récupérer les frais et les réductions
fees = Fee.objects.filter(id__in=[1, 2, 3, 4])
discounts = Discount.objects.filter(id__in=[1])
# Créer les données du formulaire d'inscription
register_form_data = {
"student": student,
"fileGroup": RegistrationFileGroup.objects.get(id=fake.random_int(min=1, max=file_group_count)),
"establishment": establishment,
"status": fake.random_int(min=1, max=3)
}
# Créer ou mettre à jour le formulaire d'inscription
register_form, created = RegistrationForm.objects.get_or_create(student=student, defaults=register_form_data)
register_form.fees.set(fees)
register_form.discounts.set(discounts)
if not created:
register_form.fileGroup = file_group
register_form.save()
self.stdout.write(self.style.SUCCESS('50 RegistrationForms initialized or updated successfully'))