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
# Vérifiez si un ProfileRole existe déjà pour ce profile et cet établissement
existing_profile_role = ProfileRole.objects.filter(
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 = ProfileRoleSerializer(data=profile_role_data)
profile_role_serializer.is_valid(raise_exception=True) profile_role_serializer.is_valid(raise_exception=True)
profile_role = profile_role_serializer.save() 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
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) 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,22 +377,33 @@ export default function CreateSubscriptionPage() {
...selectedTuitionDiscountsIds, ...selectedTuitionDiscountsIds,
]; ];
const data = { // Vérifiez si le profil existe dans la liste des profils
student: { const existingProfile = profiles.find(
last_name: formDataRef.current.studentLastName, (profile) => profile.id === formDataRef.current.existingProfileId
first_name: formDataRef.current.studentFirstName, );
...(formDataRef.current.studentLevel && {
level: formDataRef.current.studentLevel, // Affichez le profil existant dans la console
}), console.log('Profil existant trouvé :', existingProfile?.email);
...(formDataRef.current.studentGender && { console.log('debug : ', initialGuardianEmail);
gender: formDataRef.current.studentGender,
}), const guardians = (() => {
guardians: formDataRef.current.selectedGuardians.length if (formDataRef.current.selectedGuardians.length > 0) {
? formDataRef.current.selectedGuardians.map((guardianId) => ({ // 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, id: guardianId,
})) }));
: formDataRef.current.isExistingParentProfile } 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: { profile_role_data: {
establishment: selectedEstablishmentId, establishment: selectedEstablishmentId,
@ -372,8 +416,18 @@ export default function CreateSubscriptionPage() {
birth_date: formDataRef.current.guardianBirthDate, birth_date: formDataRef.current.guardianBirthDate,
phone: formDataRef.current.guardianPhone, 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: { profile_role_data: {
establishment: selectedEstablishmentId, establishment: selectedEstablishmentId,
@ -387,9 +441,26 @@ export default function CreateSubscriptionPage() {
}, },
last_name: formDataRef.current.guardianLastName, last_name: formDataRef.current.guardianLastName,
first_name: formDataRef.current.guardianFirstName, first_name: formDataRef.current.guardianFirstName,
birth_date: formDataRef.current.guardianBirthDate,
phone: formDataRef.current.guardianPhone, phone: formDataRef.current.guardianPhone,
}, },
], ];
}
})();
console.log('test : ', guardians);
const data = {
student: {
last_name: formDataRef.current.studentLastName,
first_name: formDataRef.current.studentFirstName,
...(formDataRef.current.studentLevel && {
level: formDataRef.current.studentLevel,
}),
...(formDataRef.current.studentGender && {
gender: formDataRef.current.studentGender,
}),
guardians,
sibling: [], sibling: [],
}, },
fees: allFeesIds, fees: allFeesIds,
@ -400,7 +471,22 @@ export default function CreateSubscriptionPage() {
}; };
setIsLoading(true); setIsLoading(true);
if (registerFormID) {
const formData = new FormData();
// Ajouter les données JSON sous forme de chaîne
formData.append('data', JSON.stringify(data));
// Mode édition
editRegisterForm(registerFormID, formData, csrfToken)
.then((response) => {
logger.debug('Dossier mis à jour avec succès:', response);
router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
})
.catch((error) => {
setIsLoading(false);
logger.error('Erreur lors de la mise à jour du dossier:', error);
});
} else {
// Création du dossier d'inscription // Création du dossier d'inscription
createRegisterForm(data, csrfToken) createRegisterForm(data, csrfToken)
.then((data) => { .then((data) => {
@ -427,7 +513,10 @@ export default function CreateSubscriptionPage() {
registration_form: data.student.id, registration_form: data.student.id,
}; };
return createRegistrationSchoolFileTemplate(cloneData, csrfToken) return createRegistrationSchoolFileTemplate(
cloneData,
csrfToken
)
.then((response) => .then((response) =>
logger.debug('Template enregistré avec succès:', response) logger.debug('Template enregistré avec succès:', response)
) )
@ -457,7 +546,10 @@ export default function CreateSubscriptionPage() {
csrfToken csrfToken
) )
.then((response) => .then((response) =>
logger.debug('Parent template enregistré avec succès:', response) logger.debug(
'Parent template enregistré avec succès:',
response
)
) )
.catch((error) => { .catch((error) => {
setIsLoading(false); setIsLoading(false);
@ -483,7 +575,9 @@ export default function CreateSubscriptionPage() {
setIsLoading(false); setIsLoading(false);
logger.error('Error during register form creation:', error); 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: {