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

@ -23,6 +23,7 @@ import {
fetchRegisterForm,
fetchStudents,
createRegisterForm,
editRegisterForm,
} from '@/app/actions/subscriptionAction';
import {
fetchRegistrationDiscounts,
@ -53,7 +54,9 @@ export default function CreateSubscriptionPage() {
guardianFirstName: '',
guardianEmail: '',
guardianPhone: '',
guardianProfileRole: '',
selectedGuardians: [],
associatedGuardians: [],
autoMail: false,
selectedRegistrationDiscounts: [],
selectedRegistrationFees: [],
@ -86,6 +89,8 @@ export default function CreateSubscriptionPage() {
const [selectedStudent, setSelectedEleve] = useState(null);
const [isNewResponsable, setIsNewResponsable] = useState(true);
const [initialGuardianEmail, setInitialGuardianEmail] = useState('');
const { getNiveauLabel } = useClasses();
const formDataRef = useRef(formData);
@ -164,11 +169,13 @@ export default function CreateSubscriptionPage() {
useEffect(() => {
if (!formData.guardianEmail) {
// Si l'email est vide, réinitialiser existingProfileId
// Si l'email est vide, réinitialiser existingProfileId et existingProfileInSchool
setFormData((prevData) => ({
...prevData,
isExistingParentProfile: false,
existingProfileId: null,
existingProfileInSchool: false,
associatedGuardians: [],
}));
return;
}
@ -179,12 +186,28 @@ export default function CreateSubscriptionPage() {
);
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) => ({
...prevData,
isExistingParentProfile: true,
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 {
// Si aucun profil avec cet email n'existe, réinitialiser les champs
@ -192,9 +215,11 @@ export default function CreateSubscriptionPage() {
...prevData,
isExistingParentProfile: false,
existingProfileId: null,
existingProfileInSchool: false,
associatedGuardians: [],
}));
}
}, [formData.guardianEmail, profiles]);
}, [formData.guardianEmail, profiles, selectedEstablishmentId]);
useEffect(() => {
fetchProfiles()
@ -214,11 +239,19 @@ export default function CreateSubscriptionPage() {
studentGender: data?.student?.gender || '',
guardianLastName: data?.student?.guardians[0]?.last_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 || '',
selectedFileGroup: data?.fileGroup || '',
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);
}
@ -317,8 +350,8 @@ export default function CreateSubscriptionPage() {
}
};
const createRF = () => {
logger.debug('createRF formData:', formDataRef.current);
const submit = () => {
logger.debug('formData:', formDataRef.current);
const selectedRegistrationFeesIds =
formDataRef.current.selectedRegistrationFees.map((feeId) => feeId);
@ -344,6 +377,79 @@ export default function CreateSubscriptionPage() {
...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 = {
student: {
last_name: formDataRef.current.studentLastName,
@ -354,42 +460,7 @@ export default function CreateSubscriptionPage() {
...(formDataRef.current.studentGender && {
gender: formDataRef.current.studentGender,
}),
guardians: formDataRef.current.selectedGuardians.length
? 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,
},
],
guardians,
sibling: [],
},
fees: allFeesIds,
@ -400,90 +471,113 @@ export default function CreateSubscriptionPage() {
};
setIsLoading(true);
if (registerFormID) {
const formData = new FormData();
// 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)
);
// 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
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) =>
cloneTemplate(
templateMaster.id,
formData.guardianEmail,
templateMaster.is_required
)
.then((clonedDocument) => {
const cloneData = {
name: `${templateMaster.name}_${formData.studentFirstName}_${formData.studentLastName}`,
slug: clonedDocument.slug,
id: clonedDocument.id,
master: templateMaster.id,
registration_form: data.student.id,
};
const clonePromises = masters.map((templateMaster) =>
cloneTemplate(
templateMaster.id,
formData.guardianEmail,
templateMaster.is_required
)
.then((clonedDocument) => {
const cloneData = {
name: `${templateMaster.name}_${formData.studentFirstName}_${formData.studentLastName}`,
slug: clonedDocument.slug,
id: clonedDocument.id,
master: templateMaster.id,
registration_form: data.student.id,
};
return createRegistrationSchoolFileTemplate(cloneData, csrfToken)
.then((response) =>
logger.debug('Template enregistré avec succès:', response)
return createRegistrationSchoolFileTemplate(
cloneData,
csrfToken
)
.catch((error) => {
setIsLoading(false);
logger.error(
"Erreur lors de l'enregistrement du template:",
error
);
});
.then((response) =>
logger.debug('Template enregistré avec succès:', response)
)
.catch((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) => {
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
);
});
})
.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) => {
setSelectedEleve(student);
setExistingGuardians(student.guardians);
@ -1086,7 +1180,7 @@ export default function CreateSubscriptionPage() {
<div className="flex justify-end">
<Button
text={`${registerFormID ? 'Modifier' : 'Créer'} le dossier`}
onClick={createRF}
onClick={submit}
className={`px-6 py-2 rounded-md shadow ${
isSubmitDisabled()
? '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 { useCsrfToken } from '@/context/CsrfContext';
import { useEstablishment } from '@/context/EstablishmentContext';
import { editRegisterFormWithBinaryFile } from '@/app/actions/subscriptionAction';
import { editRegisterForm } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
import Loader from '@/components/Loader';
@ -22,7 +22,7 @@ export default function Page() {
const handleSubmit = (data) => {
setIsLoading(true);
editRegisterFormWithBinaryFile(studentId, data, csrfToken)
editRegisterForm(studentId, data, csrfToken)
.then((result) => {
setIsLoading(false);
logger.debug('Success:', result);

View File

@ -26,7 +26,6 @@ import {
sendRegisterForm,
archiveRegisterForm,
editRegisterForm,
editRegisterFormWithBinaryFile,
} from '@/app/actions/subscriptionAction';
import { fetchClasses } from '@/app/actions/schoolAction';
@ -291,7 +290,7 @@ export default function Page({ params: { locale } }) {
formData.append('sepa_file', file);
// Appeler l'API pour uploader le fichier SEPA
editRegisterFormWithBinaryFile(row.student.id, formData, csrfToken)
editRegisterForm(row.student.id, formData, csrfToken)
.then((response) => {
logger.debug('Mandat SEPA uploadé avec succès :', response);
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 actions = {
// Etat "A envoyer" :
@ -511,7 +430,7 @@ export default function Page({ params: { locale } }) {
),
onClick: () =>
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 { useSearchParams, useRouter } from 'next/navigation';
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 { useCsrfToken } from '@/context/CsrfContext';
import logger from '@/utils/logger';
@ -60,7 +60,7 @@ export default function Page() {
setIsLoading(true);
// Appeler l'API pour mettre à jour le RF
editRegisterFormWithBinaryFile(studentId, formData, csrfToken)
editRegisterForm(studentId, formData, csrfToken)
.then((response) => {
logger.debug('RF mis à jour avec succès:', response);
router.push(FE_ADMIN_SUBSCRIPTIONS_URL);

View File

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

View File

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