Files
n3wt-school/Front-End/src/components/Structure/Planning/SpecialityEventModal.js

235 lines
7.3 KiB
JavaScript

import React, { useState, useEffect } from 'react';
import SelectChoice from '@/components/SelectChoice';
import { useClasses } from '@/context/ClassesContext';
import { useClasseForm } from '@/context/ClasseFormContext';
import { BE_SCHOOL_PLANNING_URL } from '@/utils/Url';
import { BookOpen, Users } from 'lucide-react';
const SpecialityEventModal = ({ isOpen, onClose, selectedCell, existingEvent, handleUpdatePlanning, classe }) => {
const { formData, setFormData } = useClasseForm();
const { groupSpecialitiesBySubject } = useClasses();
const [selectedSpeciality, setSelectedSpeciality] = useState('');
const [selectedTeacher, setSelectedTeacher] = useState('');
const [eventData, setEventData] = useState({
specialiteId: '',
teacherId: '',
start: '',
duration: '1h'
});
useEffect(() => {
if (!isOpen) {
// Réinitialiser eventData lorsque la modale se ferme
setEventData({
specialiteId: '',
teacherId: '',
start: '',
duration: '1h'
});
setSelectedSpeciality('');
setSelectedTeacher('');
}
}, [isOpen]);
useEffect(() => {
if (isOpen) {
console.log('debug : ', selectedCell);
if (existingEvent) {
// Mode édition
setEventData(existingEvent);
setSelectedSpeciality(existingEvent.specialiteId);
setSelectedTeacher(existingEvent.teacherId);
} else {
// Mode création
setEventData(prev => ({
...prev,
start: selectedCell.hour,
duration: '1h'
}));
setSelectedSpeciality('');
setSelectedTeacher('');
}
}
}, [isOpen, existingEvent, selectedCell]);
if (!isOpen) return null;
const handleSubmit = (e) => {
e.preventDefault();
if (!eventData.specialiteId) {
alert('Veuillez sélectionner une spécialité');
return;
}
if (!eventData.teacherId) {
alert('Veuillez sélectionner un enseignant');
return;
}
// Transformer eventData pour correspondre au format du planning
const selectedTeacherData = formData.teachers.find(teacher => teacher.id === parseInt(eventData.teacherId, 10));
const newCourse = {
color: '#FF0000', // Vous pouvez définir la couleur de manière dynamique si nécessaire
teachers: selectedTeacherData ? [`${selectedTeacherData.nom} ${selectedTeacherData.prenom}`] : [],
heure: `${eventData.start}:00`,
duree: eventData.duration.replace('h', ''), // Supposons que '1h' signifie 1
matiere: 'GROUPE'
};
// Mettre à jour le planning
const updatedPlannings = classe.plannings_read.map(planning => {
if (planning.niveau === selectedCell.selectedLevel) {
const newEmploiDuTemps = { ...planning.emploiDuTemps };
if (!newEmploiDuTemps[selectedCell.day]) {
newEmploiDuTemps[selectedCell.day] = [];
}
const courseTime = newCourse.heure;
const existingCourseIndex = newEmploiDuTemps[selectedCell.day].findIndex(course => course.heure === courseTime);
if (existingCourseIndex !== -1) {
newEmploiDuTemps[selectedCell.day][existingCourseIndex] = newCourse;
} else {
newEmploiDuTemps[selectedCell.day].push(newCourse);
}
return {
...planning,
emploiDuTemps: newEmploiDuTemps
};
}
return planning;
});
const updatedPlanning = updatedPlannings.find(planning => planning.niveau === selectedCell.selectedLevel);
setFormData(prevFormData => ({
...prevFormData,
plannings: updatedPlannings
}));
// Appeler handleUpdatePlanning avec les arguments appropriés
const planningId = updatedPlanning ? updatedPlanning.planning.id : null;
console.log("id : ", planningId)
if (planningId) {
handleUpdatePlanning(BE_SCHOOL_PLANNING_URL, planningId, updatedPlanning.emploiDuTemps);
}
onClose();
};
const filteredTeachers = selectedSpeciality
? formData.teachers.filter(teacher =>
teacher.specialites.includes(parseInt(selectedSpeciality, 10))
)
: formData.teachers;
const handleSpecialityChange = (e) => {
const specialityId = e.target.value;
setSelectedSpeciality(specialityId);
// Mettre à jour eventData
setEventData(prev => ({
...prev,
specialiteId: specialityId
}));
};
const handleTeacherChange = (e) => {
const teacherId = e.target.value;
setSelectedTeacher(teacherId);
// Mettre à jour eventData
setEventData(prev => ({
...prev,
teacherId: teacherId
}));
};
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>
<SelectChoice
name="specialites"
placeHolder="Spécialités"
selected={selectedSpeciality}
choices={[
{ value: '', label: 'Sélectionner une spécialité' },
...groupSpecialitiesBySubject(formData.teachers).map((speciality) => ({
value: speciality.id,
label: speciality.nom
}))
]}
callback={handleSpecialityChange}
IconItem={BookOpen}
/>
</div>
{/* Sélection de l'enseignant */}
<div>
<SelectChoice
name="teachers"
placeHolder="Enseignants"
selected={selectedTeacher}
choices={[
{ value: '', label: 'Sélectionner un enseignant'},
...filteredTeachers.map(teacher => ({
value: teacher.id,
label: `${teacher.nom} ${teacher.prenom}`
}))
]}
callback={handleTeacherChange}
IconItem={Users}
disabled={!selectedSpeciality} // Désactive le sélecteur si aucune spécialité n'est sélectionnée
/>
</div>
{/* Durée */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Durée
</label>
<input
type="text"
value={eventData.duration}
onChange={(e) => setEventData(prev => ({
...prev,
duration: 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">
<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>
</form>
</div>
</div>
);
};
export default SpecialityEventModal;