feat: Gestion de la mise à jour des profiles / roles / lors de l'édition

du formulaire RF
This commit is contained in:
N3WT DE COMPET
2025-05-06 13:59:31 +02:00
parent e2a39ff74d
commit dfd707d7a0
11 changed files with 270 additions and 233 deletions

View File

@ -30,4 +30,4 @@ class ProfileRole(models.Model):
updated_date = models.DateTimeField(auto_now=True) updated_date = models.DateTimeField(auto_now=True)
def __str__(self): def __str__(self):
return f"{self.profile.email} - {self.get_role_type_display()} - {self.establishment.name}" return f"{self.profile.email} - {self.get_role_type_display()}"

View File

@ -104,6 +104,9 @@ class ProfileRoleSerializer(serializers.ModelSerializer):
elif profile: elif profile:
profile = Profile.objects.get(id=profile.id) profile = Profile.objects.get(id=profile.id)
if profile:
instance.profile = profile
instance.role_type = validated_data.get('role_type', instance.role_type) instance.role_type = validated_data.get('role_type', instance.role_type)
instance.establishment_id = validated_data.get('establishment', instance.establishment.id) instance.establishment_id = validated_data.get('establishment', instance.establishment.id)
instance.is_active = validated_data.get('is_active', instance.is_active) instance.is_active = validated_data.get('is_active', instance.is_active)

View File

@ -141,26 +141,61 @@ class StudentSerializer(serializers.ModelSerializer):
profile_role = guardian_data.pop('profile_role', None) profile_role = guardian_data.pop('profile_role', None)
if profile_role_data: if profile_role_data:
# Vérifiez si 'profile_data' est fourni pour créer un nouveau profil
profile_data = profile_role_data.pop('profile_data', None)
if profile_data:
# Créer un nouveau profil
profile_serializer = ProfileSerializer(data=profile_data)
profile_serializer.is_valid(raise_exception=True)
profile = profile_serializer.save()
profile.set_password(profile_data['password'])
profile.save()
profile_role_data['profile'] = profile.id # Associer le profil créé
# Vérifiez si 'profile' est un objet ou une clé primaire # Vérifiez si 'profile' est un objet ou une clé primaire
if isinstance(profile_role_data.get('profile'), Profile): if isinstance(profile_role_data.get('profile'), Profile):
profile_role_data['profile'] = profile_role_data['profile'].id profile_role_data['profile'] = profile_role_data['profile'].id
establishment_id = profile_role_data.pop('establishment').id establishment_id = profile_role_data.pop('establishment').id
profile_role_data['establishment'] = establishment_id profile_role_data['establishment'] = establishment_id
profile_role_serializer = ProfileRoleSerializer(data=profile_role_data) # Vérifiez si un ProfileRole existe déjà pour ce profile et cet établissement
profile_role_serializer.is_valid(raise_exception=True) existing_profile_role = ProfileRole.objects.filter(
profile_role = profile_role_serializer.save() profile_id=profile_role_data['profile'],
establishment=profile_role_data['establishment'],
role_type=profile_role_data['role_type']
).first()
if existing_profile_role:
# Mettre à jour le ProfileRole existant
profile_role_serializer = ProfileRoleSerializer(existing_profile_role, data=profile_role_data)
profile_role_serializer.is_valid(raise_exception=True)
profile_role = profile_role_serializer.save()
else:
# Créer un nouveau ProfileRole si aucun n'existe
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: elif profile_role:
# Récupérer un ProfileRole existant par son ID
profile_role = ProfileRole.objects.get(id=profile_role.id) profile_role = ProfileRole.objects.get(id=profile_role.id)
if profile_role: if profile_role:
guardian_data['profile_role'] = profile_role guardian_data['profile_role'] = profile_role
guardian_instance, created = Guardian.objects.update_or_create( # Vérifiez si un Guardian existe déjà pour ce ProfileRole
id=guardian_data.get('id'), existing_guardian = Guardian.objects.filter(profile_role=profile_role).first()
defaults=guardian_data if existing_guardian:
) # Mettre à jour le Guardian existant
guardians_ids.append(guardian_instance.id) for key, value in guardian_data.items():
setattr(existing_guardian, key, value)
existing_guardian.save()
guardians_ids.append(existing_guardian.id)
else:
# Créer un nouveau Guardian
guardian_instance = Guardian.objects.create(**guardian_data)
guardians_ids.append(guardian_instance.id)
return guardians_ids return guardians_ids
def create_or_update_siblings(self, siblings_data, student_instance): def create_or_update_siblings(self, siblings_data, student_instance):
@ -375,3 +410,4 @@ class NotificationSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Notification model = Notification
fields = '__all__' fields = '__all__'

View File

@ -236,6 +236,7 @@ class RegisterFormWithIdView(APIView):
studentForm_data = request.data.get('data', '{}') studentForm_data = request.data.get('data', '{}')
try: try:
data = json.loads(studentForm_data) data = json.loads(studentForm_data)
print(f'data : {data}')
except json.JSONDecodeError: except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON format in 'data'"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({"error": "Invalid JSON format in 'data'"}, status=status.HTTP_400_BAD_REQUEST)

View File

@ -23,6 +23,7 @@ import {
fetchRegisterForm, fetchRegisterForm,
fetchStudents, fetchStudents,
createRegisterForm, createRegisterForm,
editRegisterForm,
} from '@/app/actions/subscriptionAction'; } from '@/app/actions/subscriptionAction';
import { import {
fetchRegistrationDiscounts, fetchRegistrationDiscounts,
@ -53,7 +54,9 @@ export default function CreateSubscriptionPage() {
guardianFirstName: '', guardianFirstName: '',
guardianEmail: '', guardianEmail: '',
guardianPhone: '', guardianPhone: '',
guardianProfileRole: '',
selectedGuardians: [], selectedGuardians: [],
associatedGuardians: [],
autoMail: false, autoMail: false,
selectedRegistrationDiscounts: [], selectedRegistrationDiscounts: [],
selectedRegistrationFees: [], selectedRegistrationFees: [],
@ -86,6 +89,8 @@ export default function CreateSubscriptionPage() {
const [selectedStudent, setSelectedEleve] = useState(null); const [selectedStudent, setSelectedEleve] = useState(null);
const [isNewResponsable, setIsNewResponsable] = useState(true); const [isNewResponsable, setIsNewResponsable] = useState(true);
const [initialGuardianEmail, setInitialGuardianEmail] = useState('');
const { getNiveauLabel } = useClasses(); const { getNiveauLabel } = useClasses();
const formDataRef = useRef(formData); const formDataRef = useRef(formData);
@ -164,11 +169,13 @@ export default function CreateSubscriptionPage() {
useEffect(() => { useEffect(() => {
if (!formData.guardianEmail) { if (!formData.guardianEmail) {
// Si l'email est vide, réinitialiser existingProfileId // Si l'email est vide, réinitialiser existingProfileId et existingProfileInSchool
setFormData((prevData) => ({ setFormData((prevData) => ({
...prevData, ...prevData,
isExistingParentProfile: false, isExistingParentProfile: false,
existingProfileId: null, existingProfileId: null,
existingProfileInSchool: false,
associatedGuardians: [],
})); }));
return; return;
} }
@ -179,12 +186,28 @@ export default function CreateSubscriptionPage() {
); );
if (existingProfile) { if (existingProfile) {
// Si un profil avec cet email existe, valoriser isExistingParentProfile et existingProfileId // Vérifiez si le profil parent est associé à l'établissement sélectionné
const isInSchool = existingProfile.roles.some(
(role) =>
role.role_type === 2 && role.establishment === selectedEstablishmentId
);
// Récupérer l'ID de l'id_associated_person si applicable
const associatedPersonId = existingProfile.roles.find(
(role) =>
role.role_type === 2 && role.establishment === selectedEstablishmentId
)?.id_associated_person;
// Mettre à jour les variables en fonction des résultats
setFormData((prevData) => ({ setFormData((prevData) => ({
...prevData, ...prevData,
isExistingParentProfile: true, isExistingParentProfile: true,
existingProfileId: existingProfile.id, // Récupérer l'ID du profil associé existingProfileId: existingProfile.id, // Récupérer l'ID du profil associé
guardianEmail: existingProfile.email || '' existingProfileInSchool: isInSchool, // Vérifie si le profil est dans l'établissement
guardianEmail: existingProfile.email || '',
associatedGuardians: associatedPersonId
? [associatedPersonId] // Ajouter l'ID de l'id_associated_person si trouvé
: [],
})); }));
} else { } else {
// Si aucun profil avec cet email n'existe, réinitialiser les champs // Si aucun profil avec cet email n'existe, réinitialiser les champs
@ -192,9 +215,11 @@ export default function CreateSubscriptionPage() {
...prevData, ...prevData,
isExistingParentProfile: false, isExistingParentProfile: false,
existingProfileId: null, existingProfileId: null,
existingProfileInSchool: false,
associatedGuardians: [],
})); }));
} }
}, [formData.guardianEmail, profiles]); }, [formData.guardianEmail, profiles, selectedEstablishmentId]);
useEffect(() => { useEffect(() => {
fetchProfiles() fetchProfiles()
@ -214,11 +239,19 @@ export default function CreateSubscriptionPage() {
studentGender: data?.student?.gender || '', studentGender: data?.student?.gender || '',
guardianLastName: data?.student?.guardians[0]?.last_name || '', guardianLastName: data?.student?.guardians[0]?.last_name || '',
guardianFirstName: data?.student?.guardians[0]?.first_name || '', guardianFirstName: data?.student?.guardians[0]?.first_name || '',
guardianEmail: data?.student?.guardians[0]?.associated_profile_email || '', guardianEmail:
data?.student?.guardians[0]?.associated_profile_email || '',
guardianPhone: data?.student?.guardians[0]?.phone || '', guardianPhone: data?.student?.guardians[0]?.phone || '',
selectedFileGroup: data?.fileGroup || '', selectedFileGroup: data?.fileGroup || '',
schoolYear: data?.school_year || '', schoolYear: data?.school_year || '',
guardianProfileRole:
data?.student?.guardians[0]?.profile_role || '',
})); }));
// Définir l'email initial
setInitialGuardianEmail(
data?.student?.guardians[0]?.associated_profile_email || ''
);
}) })
.catch(requestErrorHandler); .catch(requestErrorHandler);
} }
@ -317,8 +350,8 @@ export default function CreateSubscriptionPage() {
} }
}; };
const createRF = () => { const submit = () => {
logger.debug('createRF formData:', formDataRef.current); logger.debug('formData:', formDataRef.current);
const selectedRegistrationFeesIds = const selectedRegistrationFeesIds =
formDataRef.current.selectedRegistrationFees.map((feeId) => feeId); formDataRef.current.selectedRegistrationFees.map((feeId) => feeId);
@ -344,6 +377,79 @@ export default function CreateSubscriptionPage() {
...selectedTuitionDiscountsIds, ...selectedTuitionDiscountsIds,
]; ];
// Vérifiez si le profil existe dans la liste des profils
const existingProfile = profiles.find(
(profile) => profile.id === formDataRef.current.existingProfileId
);
// Affichez le profil existant dans la console
console.log('Profil existant trouvé :', existingProfile?.email);
console.log('debug : ', initialGuardianEmail);
const guardians = (() => {
if (formDataRef.current.selectedGuardians.length > 0) {
// Cas 3 : Des guardians sont sélectionnés
console.log('Cas 3 : Des guardians sont sélectionnés');
return formDataRef.current.selectedGuardians.map((guardianId) => ({
id: guardianId,
}));
} else if (formDataRef.current.isExistingParentProfile) {
if (initialGuardianEmail !== existingProfile?.email) {
// Cas 2 : Profil existant différent de l'ancien
console.log(
"Cas 2 : Profil existant différent de l'ancien, mise à jour du profil",
{
existingProfile,
guardianEmail: formDataRef.current.guardianEmail,
}
);
return [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: true,
profile: formDataRef.current.existingProfileId,
},
last_name: formDataRef.current.guardianLastName,
first_name: formDataRef.current.guardianFirstName,
birth_date: formDataRef.current.guardianBirthDate,
phone: formDataRef.current.guardianPhone,
},
];
} else {
// Cas 4 : Profil existant avec le même email
console.log('Cas 4 : Profil existant avec le même email', {
existingProfile,
});
return [];
}
} else {
// Cas 1 : Profil inexistant
console.log("Cas 1 : Profil inexistant, création d'un nouveau profil");
return [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: false,
profile_data: {
email: formDataRef.current.guardianEmail,
password: 'Provisoire01!',
username: formDataRef.current.guardianEmail,
},
},
last_name: formDataRef.current.guardianLastName,
first_name: formDataRef.current.guardianFirstName,
birth_date: formDataRef.current.guardianBirthDate,
phone: formDataRef.current.guardianPhone,
},
];
}
})();
console.log('test : ', guardians);
const data = { const data = {
student: { student: {
last_name: formDataRef.current.studentLastName, last_name: formDataRef.current.studentLastName,
@ -354,42 +460,7 @@ export default function CreateSubscriptionPage() {
...(formDataRef.current.studentGender && { ...(formDataRef.current.studentGender && {
gender: formDataRef.current.studentGender, gender: formDataRef.current.studentGender,
}), }),
guardians: formDataRef.current.selectedGuardians.length guardians,
? formDataRef.current.selectedGuardians.map((guardianId) => ({
id: guardianId,
}))
: formDataRef.current.isExistingParentProfile
? [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: true,
profile: formDataRef.current.existingProfileId,
},
last_name: formDataRef.current.guardianLastName,
first_name: formDataRef.current.guardianFirstName,
birth_date: formDataRef.current.guardianBirthDate,
phone: formDataRef.current.guardianPhone,
},
]
: [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: false,
profile_data: {
email: formDataRef.current.guardianEmail,
password: 'Provisoire01!',
username: formDataRef.current.guardianEmail,
},
},
last_name: formDataRef.current.guardianLastName,
first_name: formDataRef.current.guardianFirstName,
phone: formDataRef.current.guardianPhone,
},
],
sibling: [], sibling: [],
}, },
fees: allFeesIds, fees: allFeesIds,
@ -400,90 +471,113 @@ export default function CreateSubscriptionPage() {
}; };
setIsLoading(true); setIsLoading(true);
if (registerFormID) {
const formData = new FormData();
// Création du dossier d'inscription // Ajouter les données JSON sous forme de chaîne
createRegisterForm(data, csrfToken) formData.append('data', JSON.stringify(data));
.then((data) => { // Mode édition
// Clonage des schoolFileTemplates editRegisterForm(registerFormID, formData, csrfToken)
const masters = schoolFileMasters.filter((file) => .then((response) => {
file.groups.includes(selectedFileGroup) logger.debug('Dossier mis à jour avec succès:', response);
); router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
const parentMasters = parentFileMasters.filter((file) => })
file.groups.includes(selectedFileGroup) .catch((error) => {
); setIsLoading(false);
logger.error('Erreur lors de la mise à jour du dossier:', error);
});
} else {
// Création du dossier d'inscription
createRegisterForm(data, csrfToken)
.then((data) => {
// Clonage des schoolFileTemplates
const masters = schoolFileMasters.filter((file) =>
file.groups.includes(selectedFileGroup)
);
const parentMasters = parentFileMasters.filter((file) =>
file.groups.includes(selectedFileGroup)
);
const clonePromises = masters.map((templateMaster) => const clonePromises = masters.map((templateMaster) =>
cloneTemplate( cloneTemplate(
templateMaster.id, templateMaster.id,
formData.guardianEmail, formData.guardianEmail,
templateMaster.is_required templateMaster.is_required
) )
.then((clonedDocument) => { .then((clonedDocument) => {
const cloneData = { const cloneData = {
name: `${templateMaster.name}_${formData.studentFirstName}_${formData.studentLastName}`, name: `${templateMaster.name}_${formData.studentFirstName}_${formData.studentLastName}`,
slug: clonedDocument.slug, slug: clonedDocument.slug,
id: clonedDocument.id, id: clonedDocument.id,
master: templateMaster.id, master: templateMaster.id,
registration_form: data.student.id, registration_form: data.student.id,
}; };
return createRegistrationSchoolFileTemplate(cloneData, csrfToken) return createRegistrationSchoolFileTemplate(
.then((response) => cloneData,
logger.debug('Template enregistré avec succès:', response) csrfToken
) )
.catch((error) => { .then((response) =>
setIsLoading(false); logger.debug('Template enregistré avec succès:', response)
logger.error( )
"Erreur lors de l'enregistrement du template:", .catch((error) => {
error setIsLoading(false);
); logger.error(
}); "Erreur lors de l'enregistrement du template:",
error
);
});
})
.catch((error) => {
setIsLoading(false);
logger.error('Error during cloning or sending:', error);
})
);
// Clonage des parentFileTemplates
const parentClonePromises = parentMasters.map((parentMaster) => {
const parentTemplateData = {
master: parentMaster.id,
registration_form: data.student.id,
};
return createRegistrationParentFileTemplate(
parentTemplateData,
csrfToken
)
.then((response) =>
logger.debug(
'Parent template enregistré avec succès:',
response
)
)
.catch((error) => {
setIsLoading(false);
logger.error(
"Erreur lors de l'enregistrement du parent template:",
error
);
});
});
// Attendre que tous les clones soient créés
Promise.all([...clonePromises, ...parentClonePromises])
.then(() => {
// Redirection après succès
router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
}) })
.catch((error) => { .catch((error) => {
setIsLoading(false); setIsLoading(false);
logger.error('Error during cloning or sending:', error); logger.error('Error during cloning or sending:', error);
})
);
// Clonage des parentFileTemplates
const parentClonePromises = parentMasters.map((parentMaster) => {
const parentTemplateData = {
master: parentMaster.id,
registration_form: data.student.id,
};
return createRegistrationParentFileTemplate(
parentTemplateData,
csrfToken
)
.then((response) =>
logger.debug('Parent template enregistré avec succès:', response)
)
.catch((error) => {
setIsLoading(false);
logger.error(
"Erreur lors de l'enregistrement du parent template:",
error
);
}); });
})
.catch((error) => {
setIsLoading(false);
logger.error('Error during register form creation:', error);
}); });
}
// Attendre que tous les clones soient créés
Promise.all([...clonePromises, ...parentClonePromises])
.then(() => {
// Redirection après succès
router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
})
.catch((error) => {
setIsLoading(false);
logger.error('Error during cloning or sending:', error);
});
})
.catch((error) => {
setIsLoading(false);
logger.error('Error during register form creation:', error);
});
}; };
const handleEleveSelection = (student) => { const handleEleveSelection = (student) => {
setSelectedEleve(student); setSelectedEleve(student);
setExistingGuardians(student.guardians); setExistingGuardians(student.guardians);
@ -1086,7 +1180,7 @@ export default function CreateSubscriptionPage() {
<div className="flex justify-end"> <div className="flex justify-end">
<Button <Button
text={`${registerFormID ? 'Modifier' : 'Créer'} le dossier`} text={`${registerFormID ? 'Modifier' : 'Créer'} le dossier`}
onClick={createRF} onClick={submit}
className={`px-6 py-2 rounded-md shadow ${ className={`px-6 py-2 rounded-md shadow ${
isSubmitDisabled() isSubmitDisabled()
? 'bg-gray-300 text-gray-500 cursor-not-allowed' ? 'bg-gray-300 text-gray-500 cursor-not-allowed'

View File

@ -5,7 +5,7 @@ import InscriptionFormShared from '@/components/Inscription/InscriptionFormShare
import { FE_ADMIN_SUBSCRIPTIONS_URL } from '@/utils/Url'; import { FE_ADMIN_SUBSCRIPTIONS_URL } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext'; import { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext'; import { useEstablishment } from '@/context/EstablishmentContext';
import { editRegisterFormWithBinaryFile } from '@/app/actions/subscriptionAction'; import { editRegisterForm } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger'; import logger from '@/utils/logger';
import Loader from '@/components/Loader'; import Loader from '@/components/Loader';
@ -22,7 +22,7 @@ export default function Page() {
const handleSubmit = (data) => { const handleSubmit = (data) => {
setIsLoading(true); setIsLoading(true);
editRegisterFormWithBinaryFile(studentId, data, csrfToken) editRegisterForm(studentId, data, csrfToken)
.then((result) => { .then((result) => {
setIsLoading(false); setIsLoading(false);
logger.debug('Success:', result); logger.debug('Success:', result);

View File

@ -26,7 +26,6 @@ import {
sendRegisterForm, sendRegisterForm,
archiveRegisterForm, archiveRegisterForm,
editRegisterForm, editRegisterForm,
editRegisterFormWithBinaryFile,
} from '@/app/actions/subscriptionAction'; } from '@/app/actions/subscriptionAction';
import { fetchClasses } from '@/app/actions/schoolAction'; import { fetchClasses } from '@/app/actions/schoolAction';
@ -291,7 +290,7 @@ export default function Page({ params: { locale } }) {
formData.append('sepa_file', file); formData.append('sepa_file', file);
// Appeler l'API pour uploader le fichier SEPA // Appeler l'API pour uploader le fichier SEPA
editRegisterFormWithBinaryFile(row.student.id, formData, csrfToken) editRegisterForm(row.student.id, formData, csrfToken)
.then((response) => { .then((response) => {
logger.debug('Mandat SEPA uploadé avec succès :', response); logger.debug('Mandat SEPA uploadé avec succès :', response);
setPopupMessage('Le mandat SEPA a été uploadé avec succès.'); setPopupMessage('Le mandat SEPA a été uploadé avec succès.');
@ -386,86 +385,6 @@ export default function Page({ params: { locale } }) {
} }
}; };
const updateRF = (updatedData) => {
logger.debug('updateRF updatedData:', updatedData);
const data = {
student: {
guardians:
updatedData.selectedGuardians.length !== 0
? updatedData.selectedGuardians.map((guardianId) => ({
id: guardianId,
}))
: (() => {
if (updatedData.isExistingParentProfile) {
return [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: false,
profile: updatedData.existingProfileId, // Associer au profil existant
},
last_name: updatedData.guardianLastName,
first_name: updatedData.guardianFirstName,
birth_date: updatedData.guardianBirthDate,
address: updatedData.guardianAddress,
phone: updatedData.guardianPhone,
profession: updatedData.guardianProfession,
},
];
}
// Si aucun profil existant n'est trouvé, créer un nouveau profil
return [
{
profile_role_data: {
establishment: selectedEstablishmentId,
role_type: 2,
is_active: false,
profile_data: {
email: updatedData.guardianEmail,
password: 'Provisoire01!',
username: updatedData.guardianEmail,
},
},
last_name: updatedData.guardianLastName,
first_name: updatedData.guardianFirstName,
birth_date: updatedData.guardianBirthDate,
address: updatedData.guardianAddress,
phone: updatedData.guardianPhone,
profession: updatedData.guardianProfession,
},
];
})(),
},
establishment: selectedEstablishmentId,
};
editRegisterForm(student.id, data, csrfToken)
.then((data) => {
// Mise à jour immédiate des données
setRegistrationFormsDataCurrentYear((prevState) => [
...(prevState || []),
data,
]);
setTotalCurrentYear((prev) => prev + 1);
if (updatedData.autoMail) {
sendConfirmRegisterForm(
data.student.id,
updatedData.studentLastName,
updatedData.studentFirstName
);
}
handleCloseAddGuardian();
// Forcer le rechargement complet des données
setReloadFetch(true);
})
.catch((error) => {
logger.error('Error during updating registration form:', error);
});
};
const getActionsByStatus = (row) => { const getActionsByStatus = (row) => {
const actions = { const actions = {
// Etat "A envoyer" : // Etat "A envoyer" :
@ -511,7 +430,7 @@ export default function Page({ params: { locale } }) {
), ),
onClick: () => onClick: () =>
router.push( router.push(
`${FE_ADMIN_SUBSCRIPTIONS_CREATE_URL}?id=${row.student.id}&school_year=${activeTab}` `${FE_ADMIN_SUBSCRIPTIONS_EDIT_URL}?studentId=${row.student.id}&enabled=true`
), ),
}, },
{ {

View File

@ -2,7 +2,7 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation'; import { useSearchParams, useRouter } from 'next/navigation';
import ValidateSubscription from '@/components/Inscription/ValidateSubscription'; import ValidateSubscription from '@/components/Inscription/ValidateSubscription';
import { editRegisterFormWithBinaryFile } from '@/app/actions/subscriptionAction'; import { editRegisterForm } from '@/app/actions/subscriptionAction';
import { fetchClasses } from '@/app/actions/schoolAction'; import { fetchClasses } from '@/app/actions/schoolAction';
import { useCsrfToken } from '@/context/CsrfContext'; import { useCsrfToken } from '@/context/CsrfContext';
import logger from '@/utils/logger'; import logger from '@/utils/logger';
@ -60,7 +60,7 @@ export default function Page() {
setIsLoading(true); setIsLoading(true);
// Appeler l'API pour mettre à jour le RF // Appeler l'API pour mettre à jour le RF
editRegisterFormWithBinaryFile(studentId, formData, csrfToken) editRegisterForm(studentId, formData, csrfToken)
.then((response) => { .then((response) => {
logger.debug('RF mis à jour avec succès:', response); logger.debug('RF mis à jour avec succès:', response);
router.push(FE_ADMIN_SUBSCRIPTIONS_URL); router.push(FE_ADMIN_SUBSCRIPTIONS_URL);

View File

@ -5,7 +5,7 @@ import { useSearchParams, useRouter } from 'next/navigation';
import { useCsrfToken } from '@/context/CsrfContext'; import { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext'; import { useEstablishment } from '@/context/EstablishmentContext';
import { FE_PARENTS_HOME_URL } from '@/utils/Url'; import { FE_PARENTS_HOME_URL } from '@/utils/Url';
import { editRegisterFormWithBinaryFile } from '@/app/actions/subscriptionAction'; import { editRegisterForm } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger'; import logger from '@/utils/logger';
export default function Page() { export default function Page() {
@ -18,11 +18,7 @@ export default function Page() {
const handleSubmit = async (data) => { const handleSubmit = async (data) => {
try { try {
const result = await editRegisterFormWithBinaryFile( const result = await editRegisterForm(studentId, data, csrfToken);
studentId,
data,
csrfToken
);
logger.debug('Success:', result); logger.debug('Success:', result);
router.push(FE_PARENTS_HOME_URL); router.push(FE_PARENTS_HOME_URL);
} catch (error) { } catch (error) {

View File

@ -8,7 +8,7 @@ import FileUpload from '@/components/FileUpload';
import { FE_PARENTS_EDIT_SUBSCRIPTION_URL } from '@/utils/Url'; import { FE_PARENTS_EDIT_SUBSCRIPTION_URL } from '@/utils/Url';
import { import {
fetchChildren, fetchChildren,
editRegisterFormWithBinaryFile, editRegisterForm,
} from '@/app/actions/subscriptionAction'; } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger'; import logger from '@/utils/logger';
import { BASE_URL } from '@/utils/Url'; import { BASE_URL } from '@/utils/Url';
@ -71,7 +71,7 @@ export default function ParentHomePage() {
formData.append('data', JSON.stringify(jsonData)); formData.append('data', JSON.stringify(jsonData));
formData.append('sepa_file', uploadedFile); // Ajoute le fichier SEPA formData.append('sepa_file', uploadedFile); // Ajoute le fichier SEPA
editRegisterFormWithBinaryFile(uploadingStudentId, formData, csrfToken) editRegisterForm(uploadingStudentId, formData, csrfToken)
.then((response) => { .then((response) => {
logger.debug('RF mis à jour avec succès:', response); logger.debug('RF mis à jour avec succès:', response);
setReloadFetch(true); setReloadFetch(true);

View File

@ -48,18 +48,6 @@ export const fetchLastGuardian = () => {
}; };
export const editRegisterForm = (id, data, csrfToken) => { export const editRegisterForm = (id, data, csrfToken) => {
return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(data),
credentials: 'include',
}).then(requestResponseHandler);
};
export const editRegisterFormWithBinaryFile = (id, data, csrfToken) => {
return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, { return fetch(`${BE_SUBSCRIPTION_REGISTERFORMS_URL}/${id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {