fix: pagination annuaire

This commit is contained in:
N3WT DE COMPET
2025-05-06 22:57:52 +02:00
parent 9e69790683
commit 980f169c1d
11 changed files with 581 additions and 568 deletions

View File

@ -363,7 +363,7 @@ class StudentByParentSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Student model = Student
fields = ['id', 'last_name', 'first_name'] fields = ['id', 'last_name', 'first_name', 'level', 'photo']
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(StudentByParentSerializer, self).__init__(*args, **kwargs) super(StudentByParentSerializer, self).__init__(*args, **kwargs)

View File

@ -1,16 +1,74 @@
'use client'; 'use client';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { fetchProfileRoles } from '@/app/actions/authAction';
import logger from '@/utils/logger';
import { useEstablishment } from '@/context/EstablishmentContext'; import { useEstablishment } from '@/context/EstablishmentContext';
import ProfileDirectory from '@/components/ProfileDirectory';
import { PARENT_FILTER, SCHOOL_FILTER } from '@/utils/constants'; import { PARENT_FILTER, SCHOOL_FILTER } from '@/utils/constants';
import { Trash2, ToggleLeft, ToggleRight, Info, XCircle } from 'lucide-react';
import Table from '@/components/Table';
import Popup from '@/components/Popup';
import StatusLabel from '@/components/StatusLabel';
import SpecialityItem from '@/components/Structure/Configuration/SpecialityItem';
import SidebarTabs from '@/components/SidebarTabs';
import {
fetchProfileRoles,
updateProfileRoles,
deleteProfileRoles,
} from '@/app/actions/authAction';
import { dissociateGuardian } from '@/app/actions/subscriptionAction';
import { useCsrfToken } from '@/context/CsrfContext';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import logger from '@/utils/logger';
const roleTypeToLabel = (roleType) => {
switch (roleType) {
case 0:
return 'ECOLE';
case 1:
return 'ADMIN';
case 2:
return 'PARENT';
default:
return 'UNKNOWN';
}
};
const roleTypeToBadgeClass = (roleType) => {
switch (roleType) {
case 0:
return 'bg-blue-100 text-blue-600';
case 1:
return 'bg-red-100 text-red-600';
case 2:
return 'bg-green-100 text-green-600';
default:
return 'bg-gray-100 text-gray-600';
}
};
export default function Page() { export default function Page() {
const [profileRolesDatasParent, setProfileRolesDatasParent] = useState([]); const [profileRolesDatasParent, setProfileRolesDatasParent] = useState([]);
const [profileRolesDatasSchool, setProfileRolesDatasSchool] = useState([]); const [profileRolesDatasSchool, setProfileRolesDatasSchool] = useState([]);
const [reloadFetch, setReloadFetch] = useState(false); const [reloadFetch, setReloadFetch] = useState(false);
const [popupVisible, setPopupVisible] = useState(false);
const [popupMessage, setPopupMessage] = useState('');
const [confirmPopupVisible, setConfirmPopupVisible] = useState(false);
const [confirmPopupMessage, setConfirmPopupMessage] = useState('');
const [confirmPopupOnConfirm, setConfirmPopupOnConfirm] = useState(() => {});
const [visibleTooltipId, setVisibleTooltipId] = useState(null);
const [activeTab, setActiveTab] = useState('parent'); // Onglet actif
const [totalProfilesParentPages, setTotalProfilesParentPages] = useState(1);
const [totalProfilesSchoolPages, setTotalProfilesSchoolPages] = useState(1);
const [currentProfilesParentPage, setCurrentProfilesParentPage] = useState(1);
const [totalProfilesParent, setTotalProfilesParent] = useState(0);
const [totalProfilesSchool, setTotalProfilesSchool] = useState(0);
const [currentProfilesSchoolPage, setCurrentProfilesSchoolPage] = useState(1);
const [profileRolesParent, setProfileRolesParent] = useState([]);
const [profileRolesSchool, setProfileRolesSchool] = useState([]);
const itemsPerPage = 15; // Nombre d'éléments par page
const csrfToken = useCsrfToken();
const { selectedEstablishmentId } = useEstablishment(); const { selectedEstablishmentId } = useEstablishment();
const requestErrorHandler = (err) => { const requestErrorHandler = (err) => {
@ -22,16 +80,31 @@ export default function Page() {
// Fetch data for profileRolesParent // Fetch data for profileRolesParent
handleProfiles(); handleProfiles();
} }
}, [selectedEstablishmentId, reloadFetch]); }, [
selectedEstablishmentId,
reloadFetch,
currentProfilesParentPage,
currentProfilesSchoolPage,
]);
const handleProfiles = () => { const handleProfiles = () => {
fetchProfileRoles(selectedEstablishmentId, PARENT_FILTER) fetchProfileRoles(
selectedEstablishmentId,
PARENT_FILTER,
currentProfilesParentPage,
itemsPerPage
)
.then((data) => { .then((data) => {
setProfileRolesDatasParent(data); setProfileRolesDatasParent(data);
}) })
.catch(requestErrorHandler); .catch(requestErrorHandler);
fetchProfileRoles(selectedEstablishmentId, SCHOOL_FILTER) fetchProfileRoles(
selectedEstablishmentId,
SCHOOL_FILTER,
currentProfilesSchoolPage,
itemsPerPage
)
.then((data) => { .then((data) => {
setProfileRolesDatasSchool(data); setProfileRolesDatasSchool(data);
}) })
@ -39,12 +112,447 @@ export default function Page() {
setReloadFetch(false); setReloadFetch(false);
}; };
return ( const handleEdit = (profileRole) => {
<div className="w-full h-full"> const updatedData = { ...profileRole, is_active: !profileRole.is_active };
<ProfileDirectory return updateProfileRoles(profileRole.id, updatedData, csrfToken)
parentProfiles={profileRolesDatasParent} .then((data) => {
schoolProfiles={profileRolesDatasSchool} setProfileRolesParent((prevState) =>
/> prevState.map((item) => (item.id === profileRole.id ? data : item))
</div> );
return data;
})
.catch((error) => {
logger.error('Error editing data:', error);
throw error;
});
};
const handleDelete = (id) => {
return deleteProfileRoles(id, csrfToken)
.then(() => {
setProfileRolesParent((prevState) =>
prevState.filter((item) => item.id !== id)
);
logger.debug('Profile deleted successfully:', id);
})
.catch((error) => {
logger.error('Error deleting profile:', error);
throw error;
});
};
const handleDissociate = (studentId, guardianId) => {
return dissociateGuardian(studentId, guardianId)
.then((response) => {
logger.debug('Guardian dissociated successfully:', guardianId);
// Vérifier si le Guardian a été supprimé
const isGuardianDeleted = response?.isGuardianDeleted;
// Mettre à jour le modèle profileRolesParent
setProfileRolesParent(
(prevState) =>
prevState
.map((profileRole) => {
if (profileRole.associated_person?.id === guardianId) {
if (isGuardianDeleted) {
// Si le Guardian est supprimé, retirer le profileRole
return null;
} else {
// Si le Guardian n'est pas supprimé, mettre à jour les élèves associés
const updatedStudents =
profileRole.associated_person.students.filter(
(student) => student.id !== studentId
);
return {
...profileRole,
associated_person: {
...profileRole.associated_person,
students: updatedStudents, // Mettre à jour les élèves associés
},
};
}
}
return profileRole; // Conserver les autres profileRolesParent
})
.filter(Boolean) // Supprimer les entrées nulles
);
})
.catch((error) => {
logger.error('Error dissociating guardian:', error);
throw error;
});
};
const profilesRoleParentDataHandler = (data) => {
if (data) {
const { profilesRoles, count, page_size } = data;
if (profilesRoles) {
setProfileRolesParent(profilesRoles);
}
const calculatedTotalPages =
count === 0 ? 1 : Math.ceil(count / page_size);
setTotalProfilesParent(count);
setTotalProfilesParentPages(calculatedTotalPages);
}
};
const profilesRoleSchoolDataHandler = (data) => {
if (data) {
const { profilesRoles, count, page_size } = data;
if (profilesRoles) {
setProfileRolesSchool(profilesRoles);
}
const calculatedTotalPages =
count === 0 ? 1 : Math.ceil(count / page_size);
setTotalProfilesSchool(count);
setTotalProfilesSchoolPages(calculatedTotalPages);
}
};
useEffect(() => {
profilesRoleParentDataHandler(profileRolesDatasParent);
profilesRoleSchoolDataHandler(profileRolesDatasSchool);
if (activeTab === 'parent') {
setTotalProfilesParentPages(
Math.ceil(totalProfilesParent / itemsPerPage)
);
} else if (activeTab === 'school') {
setTotalProfilesSchoolPages(
Math.ceil(totalProfilesSchool / itemsPerPage)
);
}
}, [profileRolesDatasParent, profileRolesDatasSchool, activeTab]);
const handlePageChange = (newPage) => {
if (activeTab === 'parent') {
setCurrentProfilesParentPage(newPage);
} else if (activeTab === 'school') {
setCurrentProfilesSchoolPage(newPage);
}
};
const handleTooltipVisibility = (id) => {
setVisibleTooltipId(id); // Définir l'ID de la ligne pour laquelle la tooltip est visible
};
const handleTooltipHide = () => {
setVisibleTooltipId(null); // Cacher toutes les tooltips
};
const handleConfirmActivateProfile = (profileRole) => {
setConfirmPopupMessage(
`Êtes-vous sûr de vouloir ${profileRole.is_active ? 'désactiver' : 'activer'} ce profil ?`
);
setConfirmPopupOnConfirm(() => () => {
handleEdit(profileRole)
.then(() => {
setPopupMessage(
`Le profil a été ${profileRole.is_active ? 'désactivé' : 'activé'} avec succès.`
);
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(
`Erreur lors de la ${profileRole.is_active ? 'désactivation' : 'activation'} du profil.`
);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const handleConfirmDeleteProfile = (id) => {
setConfirmPopupMessage('Êtes-vous sûr de vouloir supprimer ce profil ?');
setConfirmPopupOnConfirm(() => () => {
handleDelete(id)
.then(() => {
setPopupMessage('Le profil a été supprimé avec succès.');
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(error.message);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const handleConfirmDissociateGuardian = (profileRole, student) => {
setVisibleTooltipId(null);
setConfirmPopupMessage(
`Vous êtes sur le point de dissocier le responsable ${profileRole.associated_person?.guardian_name} de l'élève ${student.student_name}. Êtes-vous sûr de vouloir poursuivre cette opération ?`
);
setConfirmPopupOnConfirm(() => () => {
handleDissociate(student.id, profileRole.associated_person?.id)
.then(() => {
setPopupMessage('Le responsable a été dissocié avec succès.');
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(error.message);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const parentColumns = [
{ name: 'Identifiant', transform: (row) => row.associated_profile_email },
{ name: 'Mise à jour', transform: (row) => row.updated_date_formatted },
{
name: 'Rôle',
transform: (row) => (
<span
className={`px-2 py-1 rounded-full font-bold ${roleTypeToBadgeClass(row.role_type)}`}
>
{roleTypeToLabel(row.role_type)}
</span>
),
},
{
name: 'Utilisateur',
transform: (row) => (
<div className="flex items-center justify-center space-x-2 relative">
<span>{row.associated_person?.guardian_name}</span>
{row.associated_person && (
<div
className="relative group"
onMouseEnter={() => handleTooltipVisibility(row.id)} // Afficher la tooltip pour cette ligne
onMouseLeave={handleTooltipHide} // Cacher la tooltip
>
<button className="relative text-blue-500 hover:text-blue-700 flex items-center justify-center">
<div className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center font-bold">
{row.associated_person?.students?.length || 0}
</div>
</button>
{visibleTooltipId === row.id && ( // Afficher uniquement si l'ID correspond
<div className="fixed z-50 w-96 p-4 bg-white border border-gray-200 rounded shadow-lg -translate-x-1/2">
<div className="mb-2">
<strong>Elève(s) associé(s):</strong>
<div className="flex flex-col justify-center space-y-2 mt-4">
{row.associated_person?.students?.map((student) => (
<div
key={student.student_name}
className="flex justify-between items-center"
>
<span className="px-2 py-1 rounded-full text-gray-800 whitespace-nowrap inline-block min-w-0 max-w-fit">
{student.student_name}
</span>
<div className="flex items-center space-x-2">
<StatusLabel
status={student.registration_status}
showDropdown={false}
/>
<button
className="text-red-500 hover:text-red-700 flex items-center space-x-1"
onClick={() =>
handleConfirmDissociateGuardian(row, student)
}
>
<XCircle className="w-5 h-5" />
<span className="text-sm">Dissocier</span>
</button>
</div>
</div>
))}
</div>
</div>
</div>
)}
</div>
)}
</div>
),
},
{
name: 'Actions',
transform: (row) => (
<div className="flex justify-center space-x-2">
<button
type="button"
className={
row.is_active
? 'text-emerald-500 hover:text-emerald-700'
: 'text-orange-500 hover:text-orange-700'
}
onClick={() => handleConfirmActivateProfile(row)}
>
{row.is_active ? (
<ToggleRight className="w-5 h-5 " />
) : (
<ToggleLeft className="w-5 h-5" />
)}
</button>
<button
type="button"
className="text-red-500 hover:text-red-700"
onClick={() => handleConfirmDeleteProfile(row.id)}
>
<Trash2 className="w-5 h-5" />
</button>
</div>
),
},
];
const schoolAdminColumns = [
{ name: 'Identifiant', transform: (row) => row.associated_profile_email },
{ name: 'Mise à jour', transform: (row) => row.updated_date_formatted },
{
name: 'Rôle',
transform: (row) => (
<span
className={`px-2 py-1 rounded-full font-bold ${roleTypeToBadgeClass(row.role_type)}`}
>
{roleTypeToLabel(row.role_type)}
</span>
),
},
{
name: 'Utilisateur',
transform: (row) => (
<div className="flex items-center justify-center space-x-2 relative">
<span>{row.associated_person?.teacher_name}</span>
{row.associated_person && (
<div
className="relative group"
onMouseEnter={() => handleTooltipVisibility(row.id)} // Afficher la tooltip pour cette ligne
onMouseLeave={handleTooltipHide} // Cacher la tooltip
>
<button className="relative text-blue-500 hover:text-blue-700 flex items-center justify-center">
<div className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center font-bold">
<Info className="w-4 h-4" /> {/* Icône Info */}
</div>
</button>
{visibleTooltipId === row.id && ( // Afficher uniquement si l'ID correspond
<div className="fixed z-50 w-96 p-4 bg-white border border-gray-200 rounded shadow-lg -translate-x-1/2">
<div className="mb-2">
<strong>Classes associées:</strong>
<div className="flex flex-wrap justify-center space-x-2 mt-4">
{row.associated_person?.classes?.map((classe) => (
<span
key={classe.id}
className="px-2 py-1 rounded-full bg-gray-200 text-gray-800"
>
{classe.name}
</span>
))}
</div>
</div>
<div>
<strong>Spécialités:</strong>
<div className="flex flex-wrap justify-center space-x-2 mt-4">
{row.associated_person?.specialities?.map(
(speciality) => (
<SpecialityItem
key={speciality.name}
speciality={speciality}
isDraggable={false}
/>
)
)}
</div>
</div>
</div>
)}
</div>
)}
</div>
),
},
{
name: 'Actions',
transform: (row) => (
<div className="flex justify-center space-x-2">
<button
type="button"
className={
row.is_active
? 'text-emerald-500 hover:text-emerald-700'
: 'text-orange-500 hover:text-orange-700'
}
onClick={() => handleConfirmActivateProfile(row)}
>
{row.is_active ? (
<ToggleRight className="w-5 h-5 " />
) : (
<ToggleLeft className="w-5 h-5" />
)}
</button>
<button
type="button"
className="text-red-500 hover:text-red-700"
onClick={() => handleConfirmDeleteProfile(row.id)}
>
<Trash2 className="w-5 h-5" />
</button>
</div>
),
},
];
return (
<>
<DjangoCSRFToken csrfToken={csrfToken} />
<SidebarTabs
tabs={[
{
id: 'parent',
label: 'Parents',
content: (
<div className="h-full overflow-y-auto">
<Table
key={`parent-${currentProfilesParentPage}`}
data={profileRolesParent}
columns={parentColumns}
itemsPerPage={itemsPerPage}
currentPage={currentProfilesParentPage}
totalPages={totalProfilesParentPages}
onPageChange={handlePageChange}
/>
</div>
),
},
{
id: 'school',
label: 'École',
content: (
<div className="h-full overflow-y-auto">
<Table
key={`school-${currentProfilesSchoolPage}`}
data={profileRolesSchool}
columns={schoolAdminColumns}
itemsPerPage={itemsPerPage}
currentPage={currentProfilesSchoolPage}
totalPages={totalProfilesSchoolPages}
onPageChange={handlePageChange}
/>
</div>
),
},
]}
onTabChange={(newActiveTab) => {
setActiveTab(newActiveTab);
}}
/>
{/* Popups */}
<Popup
visible={popupVisible}
message={popupMessage}
onConfirm={() => setPopupVisible(false)}
uniqueConfirmButton={true}
/>
<Popup
visible={confirmPopupVisible}
message={confirmPopupMessage}
onConfirm={confirmPopupOnConfirm}
onCancel={() => setConfirmPopupVisible(false)}
/>
</>
); );
} }

View File

@ -8,11 +8,9 @@ import { fetchClasse } from '@/app/actions/schoolAction';
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
import logger from '@/utils/logger'; import logger from '@/utils/logger';
import { useClasses } from '@/context/ClassesContext'; import { useClasses } from '@/context/ClassesContext';
import { BASE_URL } from '@/utils/Url';
import Button from '@/components/Button'; import Button from '@/components/Button';
import SelectChoice from '@/components/SelectChoice'; import SelectChoice from '@/components/SelectChoice';
import CheckBox from '@/components/CheckBox'; import CheckBox from '@/components/CheckBox';
import InputText from '@/components/InputText';
import { import {
fetchAbsences, fetchAbsences,
createAbsences, createAbsences,

View File

@ -14,6 +14,7 @@ import logger from '@/utils/logger';
import { BASE_URL } from '@/utils/Url'; import { BASE_URL } from '@/utils/Url';
import { useEstablishment } from '@/context/EstablishmentContext'; import { useEstablishment } from '@/context/EstablishmentContext';
import { useCsrfToken } from '@/context/CsrfContext'; import { useCsrfToken } from '@/context/CsrfContext';
import { useClasses } from '@/context/ClassesContext';
export default function ParentHomePage() { export default function ParentHomePage() {
const [children, setChildren] = useState([]); const [children, setChildren] = useState([]);
@ -24,6 +25,7 @@ export default function ParentHomePage() {
const router = useRouter(); const router = useRouter();
const csrfToken = useCsrfToken(); const csrfToken = useCsrfToken();
const [reloadFetch, setReloadFetch] = useState(false); const [reloadFetch, setReloadFetch] = useState(false);
const { getNiveauLabel } = useClasses();
useEffect(() => { useEffect(() => {
if (user !== null) { if (user !== null) {
@ -96,8 +98,41 @@ export default function ParentHomePage() {
}; };
const childrenColumns = [ const childrenColumns = [
{
name: 'photo',
transform: (row) => (
<div className="flex justify-center items-center">
{row.student.photo ? (
<a
href={`${BASE_URL}${row.student.photo}`} // Lien vers la photo
target="_blank"
rel="noopener noreferrer"
>
<img
src={`${BASE_URL}${row.student.photo}`}
alt={`${row.student.first_name} ${row.student.last_name}`}
className="w-10 h-10 object-cover transition-transform duration-200 hover:scale-125 cursor-pointer rounded-full"
/>
</a>
) : (
<div className="w-10 h-10 flex items-center justify-center bg-gray-200 rounded-full">
<span className="text-gray-500 text-sm font-semibold">
{row.student.first_name[0]}
{row.student.last_name[0]}
</span>
</div>
)}
</div>
),
},
{ name: 'Nom', transform: (row) => `${row.student.last_name}` }, { name: 'Nom', transform: (row) => `${row.student.last_name}` },
{ name: 'Prénom', transform: (row) => `${row.student.first_name}` }, { name: 'Prénom', transform: (row) => `${row.student.first_name}` },
{
name: 'Niveau',
transform: (row) => (
<div className="text-center">{getNiveauLabel(row.student.level)}</div>
),
},
{ {
name: 'Statut', name: 'Statut',
transform: (row) => ( transform: (row) => (

View File

@ -81,7 +81,7 @@ export const fetchProfileRoles = (
) => { ) => {
let url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}`; let url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}`;
if (page !== '' && pageSize !== '') { if (page !== '' && pageSize !== '') {
url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}&page=${page}&search=${search}`; url = `${BE_AUTH_PROFILES_ROLES_URL}?filter=${filter}&establishment_id=${establishment}&page=${page}`;
} }
return fetch(url, { return fetch(url, {
headers: { headers: {

View File

@ -89,7 +89,7 @@ export default function ResponsableInputFields({
profile_role_data: { profile_role_data: {
establishment: selectedEstablishmentId, establishment: selectedEstablishmentId,
role_type: 2, role_type: 2,
is_active: false, is_active: true,
profile_data: { profile_data: {
email: '', email: '',
password: 'Provisoire01!', password: 'Provisoire01!',

View File

@ -16,30 +16,31 @@ const Popup = ({
const messageLines = isStringMessage ? message.split('\n') : null; const messageLines = isStringMessage ? message.split('\n') : null;
return ReactDOM.createPortal( return ReactDOM.createPortal(
<div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50"> <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60">
<div className="bg-white p-6 rounded-lg shadow-xl max-w-md w-full"> <div className="bg-white p-6 rounded-xl shadow-2xl max-w-lg w-full">
<div className="mb-4"> {/* Titre ou message */}
<div className="mb-6">
{isStringMessage {isStringMessage
? // Afficher le message sous forme de lignes si c'est une chaîne ? messageLines.map((line, index) => (
messageLines.map((line, index) => ( <p key={index} className="text-gray-800 text-base">
<p key={index} className="text-gray-700">
{line} {line}
</p> </p>
)) ))
: // Sinon, afficher directement le contenu React : message}
message}
</div> </div>
<div className="flex justify-end space-x-2">
{/* Boutons d'action */}
<div className="flex justify-end space-x-4">
{!uniqueConfirmButton && ( {!uniqueConfirmButton && (
<button <button
className="px-4 py-2 bg-gray-300 text-white rounded hover:bg-gray-700 hover:bg-gray-400" className="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 focus:outline-none transition"
onClick={onCancel} onClick={onCancel}
> >
Annuler Annuler
</button> </button>
)} )}
<button <button
className="px-4 py-2 bg-emerald-500 text-white hover:bg-emerald-600 rounded hover:bg-emerald-600" className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 focus:outline-none transition"
onClick={onConfirm} onClick={onConfirm}
> >
{uniqueConfirmButton ? 'Fermer' : 'Confirmer'} {uniqueConfirmButton ? 'Fermer' : 'Confirmer'}

View File

@ -1,523 +0,0 @@
import React, { useState, useEffect, act } from 'react';
import { Trash2, ToggleLeft, ToggleRight, Info, XCircle } from 'lucide-react';
import Table from '@/components/Table';
import Popup from '@/components/Popup';
import StatusLabel from '@/components/StatusLabel';
import SpecialityItem from '@/components/Structure/Configuration/SpecialityItem';
import SidebarTabs from '@/components/SidebarTabs';
import {
updateProfileRoles,
deleteProfileRoles,
} from '@/app/actions/authAction';
import { dissociateGuardian } from '@/app/actions/subscriptionAction';
import { useCsrfToken } from '@/context/CsrfContext';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import logger from '@/utils/logger';
const roleTypeToLabel = (roleType) => {
switch (roleType) {
case 0:
return 'ECOLE';
case 1:
return 'ADMIN';
case 2:
return 'PARENT';
default:
return 'UNKNOWN';
}
};
const roleTypeToBadgeClass = (roleType) => {
switch (roleType) {
case 0:
return 'bg-blue-100 text-blue-600';
case 1:
return 'bg-red-100 text-red-600';
case 2:
return 'bg-green-100 text-green-600';
default:
return 'bg-gray-100 text-gray-600';
}
};
const ProfileDirectory = ({ parentProfiles, schoolProfiles }) => {
const [popupVisible, setPopupVisible] = useState(false);
const [popupMessage, setPopupMessage] = useState('');
const [confirmPopupVisible, setConfirmPopupVisible] = useState(false);
const [confirmPopupMessage, setConfirmPopupMessage] = useState('');
const [confirmPopupOnConfirm, setConfirmPopupOnConfirm] = useState(() => {});
const [visibleTooltipId, setVisibleTooltipId] = useState(null);
const [activeTab, setActiveTab] = useState('parent'); // Onglet actif
const [totalProfilesParentPages, setTotalProfilesParentPages] = useState(1);
const [totalProfilesSchoolPages, setTotalProfilesSchoolPages] = useState(1);
const [currentProfilesParentPage, setCurrentProfilesParentPage] = useState(1);
const [totalProfilesParent, setTotalProfilesParent] = useState(0);
const [totalProfilesSchool, setTotalProfilesSchool] = useState(0);
const [currentProfilesSchoolPage, setCurrentProfilesSchoolPage] = useState(1);
const [profileRolesParent, setProfileRolesParent] = useState([]);
const [profileRolesSchool, setProfileRolesSchool] = useState([]);
const itemsPerPage = 10; // Nombre d'éléments par page
const csrfToken = useCsrfToken();
const handleEdit = (profileRole) => {
const updatedData = { ...profileRole, is_active: !profileRole.is_active };
return updateProfileRoles(profileRole.id, updatedData, csrfToken)
.then((data) => {
setProfileRolesParent((prevState) =>
prevState.map((item) => (item.id === profileRole.id ? data : item))
);
return data;
})
.catch((error) => {
logger.error('Error editing data:', error);
throw error;
});
};
const handleDelete = (id) => {
return deleteProfileRoles(id, csrfToken)
.then(() => {
setProfileRolesParent((prevState) =>
prevState.filter((item) => item.id !== id)
);
logger.debug('Profile deleted successfully:', id);
})
.catch((error) => {
logger.error('Error deleting profile:', error);
throw error;
});
};
const handleDissociate = (studentId, guardianId) => {
return dissociateGuardian(studentId, guardianId)
.then((response) => {
logger.debug('Guardian dissociated successfully:', guardianId);
// Vérifier si le Guardian a été supprimé
const isGuardianDeleted = response?.isGuardianDeleted;
// Mettre à jour le modèle profileRolesParent
setProfileRolesParent(
(prevState) =>
prevState
.map((profileRole) => {
if (profileRole.associated_person?.id === guardianId) {
if (isGuardianDeleted) {
// Si le Guardian est supprimé, retirer le profileRole
return null;
} else {
// Si le Guardian n'est pas supprimé, mettre à jour les élèves associés
const updatedStudents =
profileRole.associated_person.students.filter(
(student) => student.id !== studentId
);
return {
...profileRole,
associated_person: {
...profileRole.associated_person,
students: updatedStudents, // Mettre à jour les élèves associés
},
};
}
}
return profileRole; // Conserver les autres profileRolesParent
})
.filter(Boolean) // Supprimer les entrées nulles
);
})
.catch((error) => {
logger.error('Error dissociating guardian:', error);
throw error;
});
};
const profilesRoleParentDataHandler = (data) => {
if (data) {
const { profilesRoles, count, page_size } = data;
if (profilesRoles) {
setProfileRolesParent(profilesRoles);
}
const calculatedTotalPages =
count === 0 ? 1 : Math.ceil(count / page_size);
setTotalProfilesParent(count);
setTotalProfilesParentPages(calculatedTotalPages);
}
};
const profilesRoleSchoolDataHandler = (data) => {
if (data) {
const { profilesRoles, count, page_size } = data;
if (profilesRoles) {
setProfileRolesSchool(profilesRoles);
}
const calculatedTotalPages =
count === 0 ? 1 : Math.ceil(count / page_size);
setTotalProfilesSchool(count);
setTotalProfilesSchoolPages(calculatedTotalPages);
}
};
useEffect(() => {
profilesRoleParentDataHandler(parentProfiles);
profilesRoleSchoolDataHandler(schoolProfiles);
if (activeTab === 'parent') {
setTotalProfilesParentPages(
Math.ceil(totalProfilesParent / itemsPerPage)
);
} else if (activeTab === 'school') {
setTotalProfilesSchoolPages(
Math.ceil(totalProfilesSchool / itemsPerPage)
);
}
}, [parentProfiles, schoolProfiles, activeTab]);
const handlePageChange = (newPage) => {
if (activeTab === 'parent') {
setCurrentProfilesParentPage(newPage);
} else if (activeTab === 'school') {
setCurrentProfilesSchoolPage(newPage);
}
};
const handleTooltipVisibility = (id) => {
setVisibleTooltipId(id); // Définir l'ID de la ligne pour laquelle la tooltip est visible
};
const handleTooltipHide = () => {
setVisibleTooltipId(null); // Cacher toutes les tooltips
};
const handleConfirmActivateProfile = (profileRole) => {
setConfirmPopupMessage(
`Êtes-vous sûr de vouloir ${profileRole.is_active ? 'désactiver' : 'activer'} ce profil ?`
);
setConfirmPopupOnConfirm(() => () => {
handleEdit(profileRole)
.then(() => {
setPopupMessage(
`Le profil a été ${profileRole.is_active ? 'désactivé' : 'activé'} avec succès.`
);
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(
`Erreur lors de la ${profileRole.is_active ? 'désactivation' : 'activation'} du profil.`
);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const handleConfirmDeleteProfile = (id) => {
setConfirmPopupMessage('Êtes-vous sûr de vouloir supprimer ce profil ?');
setConfirmPopupOnConfirm(() => () => {
handleDelete(id)
.then(() => {
setPopupMessage('Le profil a été supprimé avec succès.');
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(error.message);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const handleConfirmDissociateGuardian = (profileRole, student) => {
setVisibleTooltipId(null);
setConfirmPopupMessage(
`Vous êtes sur le point de dissocier le responsable ${profileRole.associated_person?.guardian_name} de l'élève ${student.student_name}. Êtes-vous sûr de vouloir poursuivre cette opération ?`
);
setConfirmPopupOnConfirm(() => () => {
handleDissociate(student.id, profileRole.associated_person?.id)
.then(() => {
setPopupMessage('Le responsable a été dissocié avec succès.');
setPopupVisible(true);
})
.catch((error) => {
setPopupMessage(error.message);
setPopupVisible(true);
});
setConfirmPopupVisible(false);
});
setConfirmPopupVisible(true);
};
const parentColumns = [
{ name: 'Identifiant', transform: (row) => row.associated_profile_email },
{ name: 'Mise à jour', transform: (row) => row.updated_date_formatted },
{
name: 'Rôle',
transform: (row) => (
<span
className={`px-2 py-1 rounded-full font-bold ${roleTypeToBadgeClass(row.role_type)}`}
>
{roleTypeToLabel(row.role_type)}
</span>
),
},
{
name: 'Utilisateur',
transform: (row) => (
<div className="flex items-center justify-center space-x-2 relative">
<span>{row.associated_person?.guardian_name}</span>
{row.associated_person && (
<div
className="relative group"
onMouseEnter={() => handleTooltipVisibility(row.id)} // Afficher la tooltip pour cette ligne
onMouseLeave={handleTooltipHide} // Cacher la tooltip
>
<button className="relative text-blue-500 hover:text-blue-700 flex items-center justify-center">
<div className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center font-bold">
{row.associated_person?.students?.length || 0}
</div>
</button>
{visibleTooltipId === row.id && ( // Afficher uniquement si l'ID correspond
<div className="fixed z-50 w-96 p-4 bg-white border border-gray-200 rounded shadow-lg -translate-x-1/2">
<div className="mb-2">
<strong>Elève(s) associé(s):</strong>
<div className="flex flex-col justify-center space-y-2 mt-4">
{row.associated_person?.students?.map((student) => (
<div
key={student.student_name}
className="flex justify-between items-center"
>
<span className="px-2 py-1 rounded-full text-gray-800 whitespace-nowrap inline-block min-w-0 max-w-fit">
{student.student_name}
</span>
<div className="flex items-center space-x-2">
<StatusLabel
status={student.registration_status}
showDropdown={false}
/>
<button
className="text-red-500 hover:text-red-700 flex items-center space-x-1"
onClick={() =>
handleConfirmDissociateGuardian(row, student)
}
>
<XCircle className="w-5 h-5" />
<span className="text-sm">Dissocier</span>
</button>
</div>
</div>
))}
</div>
</div>
</div>
)}
</div>
)}
</div>
),
},
{
name: 'Actions',
transform: (row) => (
<div className="flex justify-center space-x-2">
<button
type="button"
className={
row.is_active
? 'text-emerald-500 hover:text-emerald-700'
: 'text-orange-500 hover:text-orange-700'
}
onClick={() => handleConfirmActivateProfile(row)}
>
{row.is_active ? (
<ToggleRight className="w-5 h-5 " />
) : (
<ToggleLeft className="w-5 h-5" />
)}
</button>
<button
type="button"
className="text-red-500 hover:text-red-700"
onClick={() => handleConfirmDeleteProfile(row.id)}
>
<Trash2 className="w-5 h-5" />
</button>
</div>
),
},
];
const schoolAdminColumns = [
{ name: 'Identifiant', transform: (row) => row.associated_profile_email },
{ name: 'Mise à jour', transform: (row) => row.updated_date_formatted },
{
name: 'Rôle',
transform: (row) => (
<span
className={`px-2 py-1 rounded-full font-bold ${roleTypeToBadgeClass(row.role_type)}`}
>
{roleTypeToLabel(row.role_type)}
</span>
),
},
{
name: 'Utilisateur',
transform: (row) => (
<div className="flex items-center justify-center space-x-2 relative">
<span>{row.associated_person?.teacher_name}</span>
{row.associated_person && (
<div
className="relative group"
onMouseEnter={() => handleTooltipVisibility(row.id)} // Afficher la tooltip pour cette ligne
onMouseLeave={handleTooltipHide} // Cacher la tooltip
>
<button className="relative text-blue-500 hover:text-blue-700 flex items-center justify-center">
<div className="w-6 h-6 bg-blue-100 text-blue-700 rounded-full flex items-center justify-center font-bold">
<Info className="w-4 h-4" /> {/* Icône Info */}
</div>
</button>
{visibleTooltipId === row.id && ( // Afficher uniquement si l'ID correspond
<div className="fixed z-50 w-96 p-4 bg-white border border-gray-200 rounded shadow-lg -translate-x-1/2">
<div className="mb-2">
<strong>Classes associées:</strong>
<div className="flex flex-wrap justify-center space-x-2 mt-4">
{row.associated_person?.classes?.map((classe) => (
<span
key={classe.id}
className="px-2 py-1 rounded-full bg-gray-200 text-gray-800"
>
{classe.name}
</span>
))}
</div>
</div>
<div>
<strong>Spécialités:</strong>
<div className="flex flex-wrap justify-center space-x-2 mt-4">
{row.associated_person?.specialities?.map(
(speciality) => (
<SpecialityItem
key={speciality.name}
speciality={speciality}
isDraggable={false}
/>
)
)}
</div>
</div>
</div>
)}
</div>
)}
</div>
),
},
{
name: 'Actions',
transform: (row) => (
<div className="flex justify-center space-x-2">
<button
type="button"
className={
row.is_active
? 'text-emerald-500 hover:text-emerald-700'
: 'text-orange-500 hover:text-orange-700'
}
onClick={() => handleConfirmActivateProfile(row)}
>
{row.is_active ? (
<ToggleRight className="w-5 h-5 " />
) : (
<ToggleLeft className="w-5 h-5" />
)}
</button>
<button
type="button"
className="text-red-500 hover:text-red-700"
onClick={() => handleConfirmDeleteProfile(row.id)}
>
<Trash2 className="w-5 h-5" />
</button>
</div>
),
},
];
return (
<>
<DjangoCSRFToken csrfToken={csrfToken} />
<SidebarTabs
tabs={[
{
id: 'parent',
label: 'Parents',
content: (
<div className="h-full overflow-y-auto">
<Table
key={`parent-${currentProfilesParentPage}`}
data={
Array.isArray(profileRolesParent)
? profileRolesParent.slice(
(currentProfilesParentPage - 1) * itemsPerPage,
currentProfilesParentPage * itemsPerPage
)
: [] // Fallback to an empty array if profileRolesParent is not an array
}
columns={parentColumns}
itemsPerPage={itemsPerPage}
currentPage={currentProfilesParentPage}
totalPages={totalProfilesParentPages}
onPageChange={handlePageChange}
/>
</div>
),
},
{
id: 'school',
label: 'École',
content: (
<div className="h-full overflow-y-auto">
<Table
key={`school-${currentProfilesSchoolPage}`}
data={
Array.isArray(profileRolesSchool)
? profileRolesSchool.slice(
(currentProfilesSchoolPage - 1) * itemsPerPage,
currentProfilesSchoolPage * itemsPerPage
)
: [] // Fallback to an empty array if profileRolesSchool is not an array
}
columns={schoolAdminColumns}
itemsPerPage={itemsPerPage}
currentPage={currentProfilesSchoolPage}
totalPages={totalProfilesSchoolPages}
onPageChange={handlePageChange}
/>
</div>
),
},
]}
onTabChange={(newActiveTab) => {
setActiveTab(newActiveTab);
}}
/>
{/* Popups */}
<Popup
visible={popupVisible}
message={popupMessage}
onConfirm={() => setPopupVisible(false)}
uniqueConfirmButton={true}
/>
<Popup
visible={confirmPopupVisible}
message={confirmPopupMessage}
onConfirm={confirmPopupOnConfirm}
onCancel={() => setConfirmPopupVisible(false)}
/>
</>
);
};
export default ProfileDirectory;

View File

@ -10,7 +10,7 @@ const StatusLabel = ({ status, onChange, showDropdown = true, parent }) => {
? [ ? [
{ value: 2, label: 'Nouveau' }, { value: 2, label: 'Nouveau' },
{ value: 3, label: 'En validation' }, { value: 3, label: 'En validation' },
{ value: 5, label: 'Validé' }, { value: 5, label: 'Inscrit' },
{ value: 7, label: 'SEPA reçu' }, { value: 7, label: 'SEPA reçu' },
{ value: 8, label: 'En validation' }, { value: 8, label: 'En validation' },
] ]

View File

@ -308,11 +308,6 @@ const ClassesSection = ({
} }
}; };
const openEditModalDetails = (classe) => {
setSelectedClass(classe);
setDetailsModalVisible(true);
};
const renderClassCell = (classe, column) => { const renderClassCell = (classe, column) => {
const isEditing = editingClass === classe.id; const isEditing = editingClass === classe.id;
const isCreating = newClass && newClass.id === classe.id; const isCreating = newClass && newClass.id === classe.id;
@ -427,7 +422,7 @@ const ClassesSection = ({
return classe.age_range; return classe.age_range;
case 'NIVEAUX': case 'NIVEAUX':
const levelLabels = Array.isArray(classe.levels) const levelLabels = Array.isArray(classe.levels)
? getNiveauxLabels(classe.levels) ? getNiveauxLabels(classe.levels.sort((a, b) => a - b)) // Trier les niveaux par ordre croissant
: []; : [];
return ( return (
<div className="flex flex-wrap justify-center items-center space-x-2"> <div className="flex flex-wrap justify-center items-center space-x-2">

View File

@ -24,18 +24,17 @@ const TeacherItem = ({ teacher, isDraggable = true }) => {
return ( return (
<div <div
ref={isDraggable ? drag : null} ref={isDraggable ? drag : null}
className={`inline-block px-3 py-1 rounded-lg font-bold text-white text-center transition-transform duration-200 ease-in-out ${ className={`inline-block px-4 py-2 rounded-full font-medium text-sm text-center transition-transform duration-200 ease-in-out ${
isDragging ? 'opacity-30' : 'opacity-100' isDragging ? 'opacity-50' : 'opacity-100'
} ${isDraggable ? 'cursor-grabbing hover:shadow-lg hover:scale-105' : ''}`} } ${
style={{ isDraggable ? 'cursor-grabbing hover:shadow-md hover:scale-105' : ''
backgroundColor: isDragging } ${
? '#d1d5db' isDragging
? 'bg-gradient-to-r from-emerald-100 to-emerald-200 border border-emerald-200'
: isDraggable : isDraggable
? '#10b981' ? 'bg-gradient-to-r from-emerald-400 to-emerald-300 border border-emerald-400'
: '#a7f3d0', // Change background color based on dragging state and draggable state : 'bg-gradient-to-r from-emerald-200 to-emerald-300 border border-emerald-300'
border: isDraggable ? '1px solid #10b981' : '1px solid #a7f3d0', // Add a border } text-white`}
boxShadow: isDraggable ? '0 2px 4px rgba(0, 0, 0, 0.1)' : 'none', // Add a shadow if draggable
}}
> >
{teacher.last_name} {teacher.first_name} {teacher.last_name} {teacher.first_name}
</div> </div>