refactor: Création de nouveaux composants / update formulaire de

création de classe (#2)
This commit is contained in:
N3WT DE COMPET
2024-12-14 15:28:07 +01:00
parent cf144310a1
commit 7acae479da
43 changed files with 2374 additions and 441 deletions

View File

@ -0,0 +1,81 @@
import React, { useState } from 'react';
import SelectChoice from '@/components/SelectChoice';
import { Users } from 'lucide-react';
import DraggableSpeciality from '@/components/Structure/Planning/DraggableSpeciality';
const groupSpecialitiesBySubject = (enseignants) => {
const groupedSpecialities = {};
enseignants.forEach(teacher => {
teacher.specialites.forEach(specialite => {
if (!groupedSpecialities[specialite.id]) {
groupedSpecialities[specialite.id] = {
...specialite,
teachers: [`${teacher.nom} ${teacher.prenom}`],
};
} else {
groupedSpecialities[specialite.id].teachers.push(`${teacher.nom} ${teacher.prenom}`);
}
});
});
return Object.values(groupedSpecialities);
};
const ClassesInfo = ({ classes, onClassSelect }) => {
const [selectedClass, setSelectedClass] = useState(null); // Nouvelle variable d'état pour la classe sélectionnée
const handleClassChange = (event) => {
const classId = event.target.value;
const selectedClass = classes.find(classe => classe.id === parseInt(classId));
setSelectedClass(selectedClass);
onClassSelect(selectedClass);
};
const classChoices = [
{ value: '', label: 'Sélectionner...' },
...classes.map(classe => ({
value: classe.id,
label: classe.nom_ambiance,
}))
];
// S'assurer que `selectedClass` n'est pas null avant d'appeler `groupSpecialitiesBySubject`
const groupedSpecialities = selectedClass ? groupSpecialitiesBySubject(selectedClass.enseignants) : [];
return (
<div className="p-4 bg-white shadow rounded mb-4">
{classes.length > 0 ? (
<SelectChoice
name="classes"
label="Classes"
IconItem={Users}
selected={selectedClass ? selectedClass.id : ''}
choices={classChoices}
callback={handleClassChange}
/>
) : (
<p>Aucune classe disponible.</p>
)}
{selectedClass && (
<div className="specialities mt-4">
<label className="block text-sm font-medium text-gray-700 mb-4">Spécialités</label>
{groupedSpecialities.map((specialite, index) => {
// Combiner l'ID de la spécialité avec les IDs des enseignants pour créer une clé unique
const uniqueId = `${specialite.id}-${specialite.teachers.map(teacher => teacher.id).join('-')}-${index}`;
return (
<DraggableSpeciality
key={uniqueId} // Utilisation de l'ID unique généré
specialite={specialite}
/>
);
})}
</div>
)}
</div>
);
};
export default ClassesInfo;

View File

@ -0,0 +1,38 @@
import { useDrag } from 'react-dnd';
const DraggableSpeciality = ({ specialite }) => {
const [{ isDragging }, drag] = useDrag(() => ({
type: 'SPECIALITY',
item: { id: specialite.id,
name: specialite.nom,
color: specialite.codeCouleur,
teachers: specialite.teachers,
duree: specialite.duree },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
}));
const isColorDark = (color) => {
const r = parseInt(color.slice(1, 3), 16);
const g = parseInt(color.slice(3, 5), 16);
const b = parseInt(color.slice(5, 7), 16);
return ((r * 0.299 + g * 0.587 + b * 0.114) < 150);
};
return (
<span
ref={drag}
className="speciality-tag p-2 m-1 rounded cursor-pointer"
style={{
backgroundColor: specialite.codeCouleur,
color: isColorDark(specialite.codeCouleur) ? 'white' : 'black',
opacity: isDragging ? 0.5 : 1,
}}
>
{specialite.nom} ({specialite.teachers.join(', ')})
</span>
);
};
export default DraggableSpeciality;

View File

@ -0,0 +1,64 @@
import React from 'react';
import { useDrop } from 'react-dnd';
import PropTypes from 'prop-types';
const DropTargetCell = ({ day, hour, course, onDrop }) => {
const [{ isOver }, drop] = useDrop(() => ({
accept: 'SPECIALITY',
drop: (item) => onDrop(item, hour, day),
collect: (monitor) => ({
isOver: monitor.isOver(),
}),
}));
const isColorDark = (color) => {
if (!color) return false; // Vérification si color est défini
const r = parseInt(color.slice(1, 3), 16);
const g = parseInt(color.slice(3, 5), 16);
const b = parseInt(color.slice(5, 7), 16);
return (r * 0.299 + g * 0.587 + b * 0.114) < 150;
};
const isToday = (someDate) => {
const today = new Date();
return someDate.getDate() === today.getDate() &&
someDate.getMonth() === today.getMonth() &&
someDate.getFullYear() === today.getFullYear();
};
const cellBackgroundColor = course ? course.color : 'transparent';
const cellTextColor = isColorDark(course?.color) ? '#E5E5E5' : '#333333';
return (
<div
ref={drop}
className={`h-20 relative border-b border-gray-100 cursor-pointer ${isToday(new Date(day)) ? 'bg-emerald-100/50 border-x border-emerald-600' : ''} hover:bg-emerald-100`}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
backgroundColor: cellBackgroundColor,
color: cellTextColor
}}
>
<div className="flex flex-col items-center gap-1">
{course && (
<>
<div className="text-base font-bold">{course.matiere}</div>
<div className="text-sm">{course.teachers.join(", ")}</div>
</>
)}
</div>
</div>
);
};
DropTargetCell.propTypes = {
day: PropTypes.string.isRequired,
hour: PropTypes.number.isRequired,
course: PropTypes.object,
onDrop: PropTypes.func.isRequired
};
export default DropTargetCell;

View File

@ -0,0 +1,249 @@
import React, { useEffect, useState, useRef } from 'react';
import { format, startOfWeek, addDays, isSameDay } from 'date-fns';
import { fr } from 'date-fns/locale';
import { isToday } from 'date-fns';
import DropTargetCell from '@/components/Structure/Planning/DropTargetCell';
import { BK_GESTIONENSEIGNANTS_PLANNING_URL } from '@/utils/Url';
const PlanningClassView = ({ schedule }) => {
const [currentTime, setCurrentTime] = useState(new Date());
const scrollContainerRef = React.useRef(null);
const scheduleIdRef = useRef(scheduleId);
const eventsRef = useRef(events);
const [planning, setPlanning] = useState([])
// Fonction pour récupérer les données du depuis l'API
const fetchPlanning = () => {
if (schedule) {
fetch(`${BK_GESTIONENSEIGNANTS_PLANNING_URL}/${schedule.id}`)
.then(response => response.json())
.then(data => {
console.log('DATA : ', data);
if (!data || data.emploiDuTemps.length === 0) {
setEvents([]);
setPlanning([]);
return;
}
const planningData = data.emploiDuTemps || {};
console.log('succès : ', planningData);
let events = [];
Object.keys(planningData).forEach(day => {
if (planningData[day]) {
planningData[day].forEach(event => {
if (event) {
events.push({
...event,
day: day.toLowerCase(), // Ajouter une clé jour en minuscule pour faciliter le filtrage
scheduleId: data.id
});
}
});
}
});
if (JSON.stringify(events) !== JSON.stringify(eventsRef.current)) {
setEvents(events);
setPlanning(events);
}
})
.catch(error => {
console.error('Erreur lors de la récupération du planning :', error);
});
}
};
useEffect(() => {
setEvents([])
setPlanning([]);
fetchPlanning();
}, [scheduleId]);
useEffect(() => {
scheduleIdRef.current = scheduleId;
// Mettre à jour la référence chaque fois que scheduleId change
}, [scheduleId]);
/*useEffect(() => {
eventsRef.current = events;
// Mettre à jour la référence chaque fois que events change
}, [events]);*/
// Déplacer ces déclarations avant leur utilisation
const timeSlots = Array.from({ length: 11 }, (_, i) => i + 8);
const weekStart = startOfWeek(currentDate, { weekStartsOn: 1 });
const weekDays = Array.from({ length: 6 }, (_, i) => addDays(weekStart, i));
// Maintenant on peut utiliser weekDays
const isCurrentWeek = weekDays.some(day => isSameDay(day, new Date()));
const getFilteredEvents = (day, hour) => {
const dayName = format(day, 'eeee', { locale: fr }).toLowerCase(); // Obtenir le nom du jour en minuscule pour le filtrage
if (!Array.isArray(planning)) {
console.error("planning n'est pas un tableau:", planning);
return [];
}
return planning.filter(event => {
const eventDay = event.day.toLowerCase(); // Convertir le jour de l'événement en minuscule
return (
eventDay === dayName &&
event.heure.startsWith(hour.toString().padStart(2, '0')) // Comparer l'heure sans les minutes
);
});
};
/*const handleDrop = (item, hour, day) => {
const dateKey = format(new Date(day), 'yyyy-MM-dd');
const newEvent = {
id: `event-${dateKey}-${hour}`,
start: new Date(day).setHours(hour),
end: new Date(day).setHours(hour + 1),
matiere: item.matiere || item.name, // Assurer que 'matiere' soit défini
color: item.color || '#FFFFFF', // Ajouter une couleur par défaut si indéfini
teachers: item.teachers || [], // Assurer que 'teachers' soit défini
day: format(new Date(day), 'eeee', { locale: fr }).toLowerCase(), // Ajouter le jour
heure: hour.toString().padStart(2, '0') + ':00', // Ajouter l'heure ici
scheduleId: scheduleIdRef.current // Utiliser la référence à scheduleId ici
};
// Utiliser la référence pour accéder aux événements actuels
const existingEvents = eventsRef.current.filter(event => {
const eventHour = event.heure;
const eventDay = event.day;
console.log("DEBUG : " + event);
console.log("DEBUG : " + eventHour + " - " + hour.toString().padStart(2, '0') + ':00');
console.log("DEBUG : " + eventDay + " - " + format(new Date(day), 'eeee', { locale: fr }).toLowerCase());
console.log("DEBUG : " + event.scheduleId + " - " + scheduleIdRef.current);
console.log("----");
// Comparer la date, l'heure et le scheduleId pour trouver les événements correspondants
return eventHour === hour.toString().padStart(2, '0') + ':00' && eventDay === format(new Date(day), 'eeee', { locale: fr }).toLowerCase() && event.scheduleId === scheduleIdRef.current;
});
console.log("existingEvents :", existingEvents);
if (existingEvents.length > 0) {
existingEvents.forEach(event => {
deleteEvent(event.id); // Supprimer l'événement existant
});
}
// Ajouter l'événement à l'état global des événements
addEvent(newEvent);
setPlanning(prevEvents => {
// Filtrer les événements pour conserver ceux qui n'ont pas le même jour et créneau horaire
const updatedEvents = prevEvents.filter(event =>
!(event.day === newEvent.day && event.heure === newEvent.heure)
);
// Ajouter le nouvel événement
updatedEvents.push(newEvent);
return updatedEvents;
});
};*/
// Mettre à jour la position de la ligne toutes les minutes
useEffect(() => {
const interval = setInterval(() => {
setCurrentTime(new Date());
}, 60000);
return () => clearInterval(interval);
}, []);
// Modifier l'useEffect pour l'auto-scroll
useEffect(() => {
if (scrollContainerRef.current && isCurrentWeek) {
const currentHour = new Date().getHours();
const scrollPosition = currentHour * 80;
// Ajout d'un délai pour laisser le temps au DOM de se mettre à jour
setTimeout(() => {
scrollContainerRef.current.scrollTop = scrollPosition - 200;
}, 0);
}
}, [currentDate, isCurrentWeek]); // Ajout de currentDate dans les dépendances
// Calculer la position de la ligne de temps
const getCurrentTimePosition = () => {
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
if (hours < 8 || hours > 18) {
return -1; // Hors de la plage horaire
}
const totalMinutes = (hours - 8) * 60 + minutes; // Minutes écoulées depuis 8h
const cellHeight = 80; // Hauteur des cellules (par exemple 80px pour 20rem / 24)
const position = (totalMinutes / 60) * cellHeight;
return position;
};
return (
<div className="flex-1 max-h-[calc(100vh-192px)] overflow-hidden">
{/* En-tête des jours */}
<div className="grid gap-[1px] bg-gray-100 w-full" style={{ gridTemplateColumns: "2.5rem repeat(6, 1fr)" }}>
<div className="bg-white h-14"></div>
{weekDays.map((day) => (
<div
key={day}
className={`p-3 text-center border-b ${isToday(day) ? 'bg-emerald-400 border-x border-emerald-600' : 'bg-white'}`} >
<div className={`text font-medium ${isToday(day) ? 'text-white' : 'text-gray-500'}`}>
{format(day, 'EEEE', { locale: fr })}
</div>
</div>
))}
</div>
{/* Grille horaire */}
<div ref={scrollContainerRef} className="flex-1 overflow-y-auto relative">
{/* Ligne de temps actuelle */}
{isCurrentWeek && (
<div
className="absolute left-0 right-0 z-10 border-emerald-500 border pointer-events-none"
style={{
top: getCurrentTimePosition(),
}}
>
<div
className="absolute -left-2 -top-1 w-2 h-2 rounded-full bg-emerald-500"
/>
</div>
)}
<div className="grid gap-[1px] bg-white" style={{ gridTemplateColumns: "2.5rem repeat(6, 1fr)" }}>
{timeSlots.map(hour => (
<React.Fragment key={hour}>
<div className="h-20 p-1 text-right text-sm text-gray-500 bg-gray-100 font-medium">
{`${hour.toString().padStart(2, '0')}:00`}
</div>
{weekDays.map(day => {
const filteredEvents = getFilteredEvents(day, hour);
return(
<DropTargetCell
key={`${hour}-${day}`}
hour={hour}
day={day}
onDrop={handleDrop}
onDateClick={onDateClick}
filteredEvents={filteredEvents}
/>
)
})}
</React.Fragment>
))}
</div>
</div>
</div>
);
};
export default PlanningClassView;

View File

@ -0,0 +1,130 @@
import React, {useRef} from 'react';
import PropTypes from 'prop-types';
import { format, isToday, isSameDay, startOfWeek, addDays } from 'date-fns';
import { fr } from 'date-fns/locale';
import DropTargetCell from './DropTargetCell';
const PlanningClassView = ({ schedule, onDrop, planningType }) => {
const weekDays = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"];
const isCurrentWeek = weekDays.some(day => isSameDay(day, new Date()));
const scrollContainerRef = useRef(null);
// Calcul des dates des jours de la semaine
const startDate = startOfWeek(new Date(), { weekStartsOn: 1 }); // Début de la semaine (lundi)
const weekDayDates = weekDays.map((_, index) => addDays(startDate, index));
// Fonction pour formater l'heure
const formatTime = (time) => {
const [hour, minute] = time.split(':');
return `${hour}h${minute}`;
};
const renderCells = () => {
const cells = [];
const timeSlots = Array.from({ length: 12 }, (_, index) => index + 8); // Heures de 08:00 à 19:00
timeSlots.forEach(hour => {
cells.push(
<div key={`hour-${hour}`} className="h-20 p-1 text-right text-sm text-gray-500 bg-gray-100 font-medium">
{`${hour.toString().padStart(2, '0')}:00`}
</div>
);
weekDays.forEach(day => {
const daySchedule = schedule?.emploiDuTemps?.[day] || [];
const courses = daySchedule.filter(course => {
const courseHour = parseInt(course.heure.split(':')[0], 10);
const courseDuration = parseInt(course.duree, 10); // Utiliser la durée comme un nombre
return courseHour <= hour && hour < (courseHour + courseDuration);
});
const course = courses.length > 0 ? courses[0] : null;
cells.push(
<DropTargetCell
key={`${day}-${hour}`}
day={day}
hour={hour}
course={course}
onDrop={onDrop}
/>
);
});
});
return cells;
};
// Calculer la position de la ligne de temps
const getCurrentTimePosition = () => {
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes();
if (hours < 8 || hours > 18) {
return -1; // Hors de la plage horaire
}
const totalMinutes = (hours - 8) * 60 + minutes; // Minutes écoulées depuis 8h
const cellHeight = 80; // Hauteur des cellules (par exemple 80px pour 20rem / 24)
const position = (totalMinutes / 60) * cellHeight;
return position;
};
return (
<div className="flex-1 max-h-[calc(100vh-192px)] overflow-hidden">
{/* En-tête des jours */}
<div className="grid gap-[1px] bg-gray-100 w-full" style={{ gridTemplateColumns: "2.5rem repeat(6, 1fr)" }}>
<div className="bg-white h-14"></div>
{weekDayDates.map((day) => (
<div
key={day}
className={`p-3 text-center border-b ${isToday(day) ? 'bg-emerald-400 border-x border-emerald-600' : 'bg-white'}`} >
<div className={`text font-medium ${isToday(day) ? 'text-white' : 'text-gray-500'}`}>
{format(day, 'EEEE', { locale: fr })}
</div>
</div>
))}
</div>
{/* Grille horaire */}
<div ref={scrollContainerRef} className="flex-1 overflow-y-auto relative">
{isCurrentWeek && (
<div
className="absolute left-0 right-0 z-10 border-emerald-500 border pointer-events-none"
style={{
top: getCurrentTimePosition(),
}}
>
<div
className="absolute -left-2 -top-1 w-2 h-2 rounded-full bg-emerald-500"
/>
</div>
)}
<div className={`grid gap-[1px] bg-white`} style={{ gridTemplateColumns: `2.5rem repeat(6, 1fr)` }}>
{renderCells()}
</div>
</div>
</div>
);
};
PlanningClassView.propTypes = {
schedule: PropTypes.shape({
emploiDuTemps: PropTypes.objectOf(
PropTypes.arrayOf(
PropTypes.shape({
duree: PropTypes.string.isRequired,
heure: PropTypes.string.isRequired,
matiere: PropTypes.string.isRequired,
teachers: PropTypes.arrayOf(PropTypes.string).isRequired,
color: PropTypes.string.isRequired,
})
)
).isRequired,
}).isRequired,
};
export default PlanningClassView;

View File

@ -0,0 +1,195 @@
'use client'
import React, { useState, useEffect, useRef } from 'react';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';
import { AnimatePresence, findSpring, motion } from 'framer-motion'; // Ajouter cet import
import PlanningClassView from '@/components/Structure/Planning/PlanningClassView';
import SpecialityEventModal from '@/components/Structure/Planning/SpecialityEventModal';
import ClassesInfo from '@/components/Structure/Planning/ClassesInfo';
import { BK_GESTIONENSEIGNANTS_PLANNING_URL } from '@/utils/Url';
import { ChevronLeft, ChevronRight, Calendar } from 'lucide-react'
import SelectChoice from '@/components/SelectChoice';
const ScheduleManagement = ({ schedules, setSchedules, handleUpdatePlanning, specialities, teachers, classes }) => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [selectedClass, setSelectedClass] = useState(null);
const [schedule, setSchedule] = useState(null);
const scheduleRef = useRef(null);
const scheduleId = useRef(null);
const [planningType, setPlanningType] = useState('TRIMESTRIEL');
const [currentPeriod, setCurrentPeriod] = useState('T1');
const planningChoices = [
{ value: 'TRIMESTRIEL', label: 'TRIMESTRIEL' },
{ value: 'SEMESTRIEL', label: 'SEMESTRIEL' },
{ value: 'ANNUEL', label: 'ANNUEL' },
];
useEffect(() => {
if (selectedClass) {
scheduleId.current = selectedClass.planning.id;
setSchedule(selectedClass.planning);
} else {
setSchedule(null);
}
}, [selectedClass]);
// Synchroniser scheduleRef avec schedule
useEffect(() => {
scheduleRef.current = schedule;
}, [schedule]);
const handleClassSelect = (cls) => {
setSelectedClass(cls);
};
useEffect(() => {
if (schedule) {
console.log("Schedule data:", schedule);
}
}, [schedule]);
// Fonction onDrop dans PlanningClassView ou un composant parent
const onDrop = (item, hour, day) => {
// Les données de l'élément drag and drop (spécialité par exemple)
const { id, name, color, teachers } = item;
// Créez une nouvelle copie du planning
const newSchedule = { ...scheduleRef.current };
// Vérifiez s'il existe déjà une entrée pour le jour
if (!newSchedule.emploiDuTemps[day]) {
newSchedule.emploiDuTemps[day] = [];
}
const courseTime = `${hour.toString().padStart(2, '0')}:00`;
// Rechercher s'il y a déjà un cours à l'heure spécifiée
const existingCourseIndex = newSchedule.emploiDuTemps[day].findIndex(course =>
course.heure === courseTime
);
const newCourse = {
duree: '1',
heure: courseTime,
matiere: name,
teachers: teachers,
color: color,
};
// S'il existe déjà un cours à cette heure, on le remplace
if (existingCourseIndex !== -1) {
newSchedule.emploiDuTemps[day][existingCourseIndex] = newCourse;
} else {
// Sinon on ajoute le nouveau cours
newSchedule.emploiDuTemps[day].push(newCourse);
}
// Mettez à jour l'état du planning
setSchedule(newSchedule)
// Appelez la fonction handleUpdatePlanning en dehors de setSchedule
handleUpdatePlanning(`${BK_GESTIONENSEIGNANTS_PLANNING_URL}`, scheduleId.current, newSchedule);
};
const getPeriodLabel = (period) => {
switch(period) {
case 'T1': return '1er trimestre';
case 'T2': return '2e trimestre';
case 'T3': return '3e trimestre';
case 'S1': return '1er semestre';
case 'S2': return '2e semestre';
default: return period;
}
};
const handlePeriodChange = (direction) => {
if (planningType === 'TRIMESTRIEL') {
if (direction === 'prev') {
setCurrentPeriod(currentPeriod === 'T1' ? 'T3' : `T${parseInt(currentPeriod.slice(1)) - 1}`);
} else {
setCurrentPeriod(currentPeriod === 'T3' ? 'T1' : `T${parseInt(currentPeriod.slice(1)) + 1}`);
}
} else if (planningType === 'SEMESTRIEL') {
setCurrentPeriod(currentPeriod === 'S1' ? 'S2' : 'S1');
}
};
// Fonctionnalité de gestion des emplois du temps
return (
<div className="flex flex-col h-full overflow-hidden">
<DndProvider backend={HTML5Backend}>
<ClassesInfo classes={classes} onClassSelect={handleClassSelect}/>
<div className="flex justify-between items-center p-4 w-full">
<div className="flex items-center w-full">
<SelectChoice
name="planningType"
IconItem={Calendar}
selected={planningType}
choices={planningChoices}
callback={(e) => {
setPlanningType(e.target.value);
setCurrentPeriod(e.target.value === 'TRIMESTRIEL' ? 'T1' : 'S1');
}}
/>
</div>
{planningType !== 'ANNUEL' && (
<div className="flex items-center justify-center w-full">
<button
onClick={() => handlePeriodChange('prev')}
className={`mr-4 p-2 border rounded-lg ${
currentPeriod === 'T1' || currentPeriod === 'S1' ? 'bg-gray-300 text-gray-700 cursor-not-allowed' : 'bg-emerald-500 text-white hover:bg-emerald-600'
} transition-colors duration-300`}
disabled={currentPeriod === 'T1' || currentPeriod === 'S1'}
>
<ChevronLeft className="h-6 w-6" />
</button>
<span className="text-lg font-semibold mx-4">{getPeriodLabel(currentPeriod)}</span>
<button
onClick={() => handlePeriodChange('next')}
className={`ml-4 p-2 border rounded-lg ${
(planningType === 'TRIMESTRIEL' && currentPeriod === 'T3') || (planningType === 'SEMESTRIEL' && currentPeriod === 'S2') ? 'bg-gray-300 text-gray-700 cursor-not-allowed' : 'bg-emerald-500 text-white hover:bg-emerald-600'
} transition-colors duration-300`}
disabled={(planningType === 'TRIMESTRIEL' && currentPeriod === 'T3') || (planningType === 'SEMESTRIEL' && currentPeriod === 'S2')}
>
<ChevronRight className="h-6 w-6" />
</button>
</div>
)}
</div>
<div className="flex-1 max-h-[calc(100vh-192px)] overflow-hidden">
<AnimatePresence mode="wait">
<motion.div
key="year"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
>
<PlanningClassView
schedule={schedule}
onDrop={onDrop}
planningType={planningType}
currentPeriod={currentPeriod}
/>
</motion.div>
</AnimatePresence>
</div>
</DndProvider>
{/* <SpecialityEventModal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
eventData={eventData}
setEventData={setEventData}
selectedClass={selectedClass}
/> */}
</div>
);
};
export default ScheduleManagement;

View File

@ -0,0 +1,186 @@
import { usePlanning } from '@/context/PlanningContext';
import SelectChoice from '@/components/SelectChoice';
import { format } from 'date-fns';
import React, { useEffect } from 'react';
import { Users, BookOpen } from 'lucide-react';
export default function SpecialityEventModal({ isOpen, onClose, eventData, setEventData, selectedClass }) {
const { addEvent, updateEvent, deleteEvent, schedules } = usePlanning();
useEffect(() => {
if (!isOpen) {
// Réinitialiser eventData lorsque la modale se ferme
setEventData({
scheduleId: '',
specialiteId: '',
specialities: [],
// Réinitialiser d'autres champs si nécessaire
});
}
}, [isOpen, setEventData]);
useEffect(() => {
if (isOpen && selectedClass) {
setEventData(prev => ({
...prev,
scheduleId: selectedClass.id,
specialities: Array.from(new Map(
selectedClass.enseignants.flatMap(teacher =>
teacher.specialites.map(specialite => [specialite.id, {
id: specialite.id,
nom: specialite.nom,
codeCouleur: specialite.codeCouleur
}])
)
).values())
}));
}
}, [isOpen, selectedClass, setEventData]);
if (!isOpen) return null;
const handleSubmit = (e) => {
e.preventDefault();
if (!eventData.scheduleId) {
alert('Veuillez sélectionner une spécialité');
return;
}
const selectedSchedule = schedules.find(s => s.id === eventData.scheduleId);
if (eventData.id) {
updateEvent(eventData.id, {
...eventData,
scheduleId: eventData.scheduleId,
color: eventData.color || selectedSchedule?.color
});
} else {
addEvent({
...eventData,
id: `event-${Date.now()}`,
scheduleId: eventData.scheduleId,
color: eventData.color || selectedSchedule?.color
});
}
onClose();
};
const handleDelete = () => {
if (eventData.id && confirm('Êtes-vous sûr de vouloir supprimer cet événement ?')) {
deleteEvent(eventData.id);
onClose();
}
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white p-6 rounded-lg w-full max-w-md">
<h2 className="text-xl font-semibold mb-4">
{eventData.id ? 'Modifier l\'événement' : 'Nouvel événement'}
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Sélection de la Spécialité */}
<div>
{eventData.scheduleId && eventData.specialities && eventData.specialities.length > 0 ? (
<SelectChoice
name={`spécialités-${eventData.scheduleId}`}
label="Spécialités"
selected={eventData.specialiteId ? eventData.specialiteId : ''}
choices={eventData.specialities.map(specialite => ({
value: specialite.id,
label: specialite.nom
}))}
callback={(event) => {
const selectedSpecialityId = event.target.value;
const selectedSpeciality = eventData.specialities.find(specialite => specialite.id === parseInt(selectedSpecialityId, 10));
setEventData({
...eventData,
specialiteId: selectedSpecialityId,
color: selectedSpeciality?.codeCouleur || '#10b981'
});
}}
IconItem={BookOpen}
/>
) : (
<p>Aucune spécialité disponible pour cette classe.</p>
)}
</div>
{/* Dates */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Début
</label>
<input
type="datetime-local"
value={format(new Date(eventData.start), "yyyy-MM-dd'T'HH:mm")}
onChange={(e) => setEventData({ ...eventData, start: new Date(e.target.value).toISOString() })}
className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-emerald-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Fin
</label>
<input
type="datetime-local"
value={format(new Date(eventData.end), "yyyy-MM-dd'T'HH:mm")}
onChange={(e) => setEventData({ ...eventData, end: new Date(e.target.value).toISOString() })}
className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-emerald-500"
required
/>
</div>
</div>
{/* Lieu */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Lieu
</label>
<input
type="text"
value={eventData.location || ''}
onChange={(e) => setEventData({ ...eventData, location: e.target.value })}
className="w-full p-2 border rounded focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
</div>
{/* Boutons */}
<div className="flex justify-between gap-2 mt-6">
<div>
{eventData.id && (
<button
type="button"
onClick={handleDelete}
className="px-4 py-2 text-red-600 hover:bg-red-50 rounded"
>
Supprimer
</button>
)}
</div>
<div className="flex gap-2">
<button
type="button"
onClick={onClose}
className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded"
>
Annuler
</button>
<button
type="submit"
className="px-4 py-2 bg-emerald-600 text-white rounded hover:bg-emerald-700"
>
{eventData.id ? 'Modifier' : 'Créer'}
</button>
</div>
</div>
</form>
</div>
</div>
);
}