feat: Mise à jour des Teacher

This commit is contained in:
N3WT DE COMPET
2025-03-16 19:33:07 +01:00
parent a3182c0ba7
commit 173ac47fb2
3 changed files with 101 additions and 107 deletions

View File

@ -601,4 +601,12 @@ class ProfileRoleSimpleView(APIView):
responses={200: 'Suppression réussie'}
)
def delete(self, request, id):
return bdd.delete_object(ProfileRole, id)
profile_role = ProfileRole.objects.get(id=id)
profile = profile_role.profile
profile_role.delete()
# Vérifier si le profil n'a plus de rôles associés
if not ProfileRole.objects.filter(profile=profile).exists():
profile.delete()
return JsonResponse({'message': 'Suppression réussie'}, safe=False)

View File

@ -33,34 +33,49 @@ class TeacherSerializer(serializers.ModelSerializer):
specialities = serializers.PrimaryKeyRelatedField(queryset=Speciality.objects.all(), many=True, required=False)
specialities_details = serializers.SerializerMethodField()
updated_date_formatted = serializers.SerializerMethodField()
role_type = serializers.SerializerMethodField()
associated_profile_email = serializers.SerializerMethodField()
role_type_display = serializers.SerializerMethodField()
role_type = serializers.IntegerField(write_only=True)
associated_profile_email = serializers.EmailField(write_only=True)
profile_role = serializers.PrimaryKeyRelatedField(queryset=ProfileRole.objects.all(), required=False)
profile_role_data = ProfileRoleSerializer(write_only=True, required=False)
associated_profile_email_display = serializers.SerializerMethodField()
class Meta:
model = Teacher
fields = '__all__'
def create_or_update_profile_role(self, profile, associated_profile_email, establishment_id, role_type):
# Mettre à jour l'email du profil si nécessaire
if profile.email != associated_profile_email:
profile.email = associated_profile_email
profile.username = associated_profile_email
profile.save()
profile_role, created = ProfileRole.objects.update_or_create(
profile=profile,
establishment_id=establishment_id,
defaults={'role_type': role_type, 'is_active': True}
)
if not created:
profile_role.role_type = role_type
profile_role.establishment_id = establishment_id
profile_role.save()
return profile_role
def create(self, validated_data):
specialities_data = validated_data.pop('specialities', None)
profile_role_data = validated_data.pop('profile_role_data', None)
profile_role = validated_data.pop('profile_role', None)
associated_profile_email = validated_data.pop('associated_profile_email')
establishment_id = validated_data.pop('establishment')
role_type = validated_data.pop('role_type')
if profile_role_data:
establishment_id = profile_role_data.pop('establishment').id
profile_id = profile_role_data.pop('profile').id
profile_role_data['establishment'] = establishment_id
profile_role_data['profile'] = profile_id
profile, created = Profile.objects.get_or_create(
email=associated_profile_email,
defaults={'username': associated_profile_email}
)
# Créer l'instance de ProfileRole
profile_role_serializer = ProfileRoleSerializer(data=profile_role_data)
profile_role_serializer.is_valid(raise_exception=True)
profile_role = profile_role_serializer.save()
elif profile_role:
profile_role = ProfileRole.objects.get(id=profile_role.id)
profile_role = self.create_or_update_profile_role(profile, associated_profile_email, establishment_id, role_type)
# Créer l'enseignant avec l'instance de ProfileRole
teacher = Teacher.objects.create(profile_role=profile_role, **validated_data)
if specialities_data:
teacher.specialities.set(specialities_data)
@ -69,21 +84,17 @@ class TeacherSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
specialities_data = validated_data.pop('specialities', [])
profile_role_data = validated_data.pop('profile_role_data', None)
profile_role = validated_data.pop('profile_role', None)
associated_profile_email = validated_data.pop('associated_profile_email', instance.profile_role.profile.email)
establishment_id = validated_data.get('establishment', instance.profile_role.establishment.id)
role_type = validated_data.get('role_type', instance.profile_role.role_type)
if profile_role_data:
establishment_id = profile_role_data.pop('establishment').id
profile_role_data['establishment'] = establishment_id
profile_role_serializer = ProfileRoleSerializer(instance.profile_role, data=profile_role_data)
profile_role_serializer.is_valid(raise_exception=True)
profile_role_serializer.save()
elif profile_role:
instance.profile_role = ProfileRole.objects.get(id=profile_role.id)
profile = instance.profile_role.profile
profile_role = self.create_or_update_profile_role(profile, associated_profile_email, establishment_id, role_type)
instance.profile_role = profile_role
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.email = validated_data.get('email', instance.email)
instance.save()
if specialities_data:
instance.specialities.set(specialities_data)
@ -95,12 +106,6 @@ class TeacherSerializer(serializers.ModelSerializer):
local_time = utc_time.astimezone(local_tz)
return local_time.strftime("%d-%m-%Y %H:%M")
def get_role_type(self, obj):
profile_role = obj.profile_role
if profile_role:
return {'role_type': profile_role.role_type, 'establishment': profile_role.establishment.name}
return None
def get_specialities_details(self, obj):
return [{'id': speciality.id, 'name': speciality.name, 'color_code': speciality.color_code} for speciality in obj.specialities.all()]
@ -109,6 +114,14 @@ class TeacherSerializer(serializers.ModelSerializer):
return obj.profile_role.profile.email
return None
def get_role_type_display(self, obj):
if obj.profile_role:
return obj.profile_role.role_type
return None
def get_associated_profile_email_display(self, obj):
return self.get_associated_profile_email(obj)
class PlanningSerializer(serializers.ModelSerializer):
class Meta:
model = Planning

View File

@ -111,22 +111,6 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
const { selectedEstablishmentId } = useEstablishment();
const handleSelectProfile = (profile) => {
setNewTeacher((prevData) => ({
...prevData,
selectedProfile: profile,
}));
setFormData((prevData) => ({
...prevData,
selectedProfile: profile
}));
setConfirmPopupMessage(`Vous êtes sur le point de rattacher l'enseignant ${newTeacher?.first_name} ${newTeacher?.last_name} au profil ${profile.email} ID = ${profile.id}.`);
setConfirmPopupOnConfirm(() => () => {
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const handleCancelConfirmation = () => {
setConfirmPopupVisible(false);
};
@ -137,8 +121,8 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
};
const handleAddTeacher = () => {
setNewTeacher({ id: Date.now(), last_name: '', first_name: '', selectedProfile: null, specialities: [], droit: 0 });
setFormData({ last_name: '', first_name: '', selectedProfile: null, specialities: [], droit: 0});
setNewTeacher({ id: Date.now(), last_name: '', first_name: '', associated_profile_email: '', specialities: [], role_type: 0 });
setFormData({ last_name: '', first_name: '', associated_profile_email: '', specialities: [], role_type: 0});
};
const handleRemoveTeacher = (id) => {
@ -152,16 +136,13 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
};
const handleSaveNewTeacher = () => {
if (formData.last_name && formData.first_name && formData.selectedProfile) {
if (formData.last_name && formData.first_name && formData.associated_profile_email) {
const data = {
last_name: formData.last_name,
first_name: formData.first_name,
profile_role_data: {
role_type: formData.droit,
associated_profile_email: formData.associated_profile_email,
establishment: selectedEstablishmentId,
is_active: true,
profile: formData.selectedProfile.id
},
role_type: formData.role_type,
specialities: formData.specialities
};
@ -185,16 +166,16 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
};
const handleUpdateTeacher = (id, updatedData) => {
if (updatedData.last_name && updatedData.first_name && updatedData.email) {
if (updatedData.last_name && updatedData.first_name && updatedData.associated_profile_email_display) {
const data = {
email: updatedData.email,
username: updatedData.email,
droit: updatedData.droit,
last_name: formData.last_name,
first_name: formData.first_name,
associated_profile_email: formData.associated_profile_email || formData.associated_profile_email_display,
establishment: selectedEstablishmentId,
role_type: formData.role_type,
specialities: formData.specialities
};
updateProfile(updatedData.associated_profile, data, csrfToken)
.then(response => {
logger.debug('Success:', response);
handleEdit(id, updatedData)
handleEdit(id, data)
.then((updatedTeacher) => {
setTeachers(prevTeachers => prevTeachers.map(teacher => teacher.id === id ? { ...teacher, ...updatedTeacher } : teacher));
setEditingTeacher(null);
@ -207,14 +188,6 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
setLocalErrors(error.details);
}
});
})
.catch((error) => {
logger.error('Error:', error.message);
if (error.details) {
logger.error('Form errors:', error.details);
setLocalErrors(error.details);
}
});
}
else {
setPopupMessage("Tous les champs doivent être remplis et valides");
@ -265,6 +238,15 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
}
};
const handleEditTeacher = (teacher) => {
setEditingTeacher(teacher.id);
setFormData({
...teacher,
associated_profile_email: teacher.associated_profile_email_display,
role_type: teacher.role_type_display,
});
};
const renderTeacherCell = (teacher, column) => {
const isEditing = editingTeacher === teacher.id;
const isCreating = newTeacher && newTeacher.id === teacher.id;
@ -293,23 +275,14 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
);
case 'EMAIL':
return (
<div className="flex items-center space-x-2">
{currentData.selectedProfile ? (
<span className="text-gray-900">
{currentData.selectedProfile.email}
</span>
) : (
<span className="text-gray-500 italic">
Rechercher un profil existant
</span>
)}
<button
type="button"
onClick={() => setDirectoryPopupVisible(true)}
>
<Search className="w-5 h-5 text-emerald-500 hover:text-emerald-700"/>
</button>
</div>
<InputText
name="associated_profile_email"
type="email"
value={currentData.associated_profile_email || teacher.associated_profile_email_display || ''}
onChange={handleChange}
placeholder="Adresse email de l'enseignant"
errorMsg={getError('email')}
/>
);
case 'SPECIALITES':
return (
@ -319,8 +292,8 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
return (
<div className="flex justify-center">
<ToggleSwitch
name="droit"
checked={currentData.droit === 1}
name="role_type"
checked={currentData.role_type === 1}
onChange={handleChange}
/>
</div>
@ -354,7 +327,7 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
<TeacherItem key={teacher.id} teacher={teacher} />
);
case 'EMAIL':
return teacher.associated_profile_email;
return teacher.associated_profile_email_display;
case 'SPECIALITES':
return (
<div className="flex justify-center space-x-2 flex-wrap">
@ -364,9 +337,9 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
</div>
);
case 'ADMINISTRATEUR':
if (teacher.associated_profile_email) {
const badgeClass = teacher.role_type.role_type === 1 ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600';
const label = teacher.role_type.role_type === 1 ? 'OUI' : 'NON';
if (teacher.associated_profile_email_display) {
const badgeClass = teacher.role_type_display === 1 ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600';
const label = teacher.role_type_display === 1 ? 'OUI' : 'NON';
return (
<div key={teacher.id} className="flex justify-center items-center space-x-2">
<span className={`px-3 py-1 rounded-full font-bold ${badgeClass}`}>
@ -384,7 +357,7 @@ const TeachersSection = ({ teachers, setTeachers, specialities, handleCreate, ha
<div className="flex justify-center space-x-2">
<button
type="button"
onClick={() => setEditingTeacher(teacher.id) || setFormData(teacher)}
onClick={() => handleEditTeacher(teacher)}
className="text-blue-500 hover:text-blue-700"
>
<Edit3 className="w-5 h-5" />