Fixed bugs on Calendar
This commit is contained in:
115
app/api/trajets/[id]/validate/route.ts
Normal file
115
app/api/trajets/[id]/validate/route.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getCurrentUser } from '@/lib/auth';
|
||||
|
||||
// POST - Valider un trajet et déduire les heures du chauffeur
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { dureeHeures } = body;
|
||||
|
||||
if (!dureeHeures || dureeHeures <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'La durée du trajet est requise' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Récupérer le trajet avec le chauffeur
|
||||
const trajet = await prisma.trajet.findUnique({
|
||||
where: { id: params.id },
|
||||
include: {
|
||||
chauffeur: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!trajet) {
|
||||
return NextResponse.json({ error: 'Trajet non trouvé' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (!trajet.chauffeur) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Aucun chauffeur assigné à ce trajet' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (trajet.statut === 'Validé' || trajet.statut === 'Terminé') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ce trajet a déjà été validé' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Vérifier que le chauffeur a assez d'heures disponibles
|
||||
const heuresRestantes = trajet.chauffeur.heuresRestantes;
|
||||
const heuresADeduire = Math.round(dureeHeures);
|
||||
|
||||
if (heuresRestantes < heuresADeduire) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `Le chauffeur n'a que ${heuresRestantes}h disponibles. Le trajet nécessite ${heuresADeduire}h.`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Mettre à jour le trajet et déduire les heures du chauffeur
|
||||
const [trajetUpdated, chauffeurUpdated] = await Promise.all([
|
||||
prisma.trajet.update({
|
||||
where: { id: params.id },
|
||||
data: {
|
||||
statut: 'Validé',
|
||||
},
|
||||
include: {
|
||||
adherent: {
|
||||
select: {
|
||||
id: true,
|
||||
nom: true,
|
||||
prenom: true,
|
||||
telephone: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
chauffeur: {
|
||||
select: {
|
||||
id: true,
|
||||
nom: true,
|
||||
prenom: true,
|
||||
telephone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.chauffeur.update({
|
||||
where: { id: trajet.chauffeur.id },
|
||||
data: {
|
||||
heuresRestantes: heuresRestantes - heuresADeduire,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
trajet: trajetUpdated,
|
||||
chauffeur: {
|
||||
id: chauffeurUpdated.id,
|
||||
heuresRestantes: chauffeurUpdated.heuresRestantes,
|
||||
},
|
||||
heuresDeduites: heuresADeduire,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la validation du trajet:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Erreur serveur' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { DndContext, DragEndEvent, DragOverlay, DragStartEvent, useDraggable, useDroppable } from '@dnd-kit/core';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import TrajetDetailModal from './TrajetDetailModal';
|
||||
|
||||
interface Trajet {
|
||||
id: string;
|
||||
@@ -28,12 +31,135 @@ interface CalendrierTrajetsProps {
|
||||
refreshTrigger?: number;
|
||||
}
|
||||
|
||||
// Composant draggable pour un événement de trajet
|
||||
function DraggableTrajetEvent({ trajet, onClick }: { trajet: Trajet; onClick: (e: React.MouseEvent, trajet: Trajet) => void }) {
|
||||
// Empêcher le drag pour les trajets annulés ou validés
|
||||
const canDrag = trajet.statut !== 'Annulé' && trajet.statut !== 'Validé' && trajet.statut !== 'Terminé';
|
||||
|
||||
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
|
||||
id: trajet.id,
|
||||
data: { trajet },
|
||||
disabled: !canDrag,
|
||||
});
|
||||
|
||||
const style = {
|
||||
transform: CSS.Translate.toString(transform),
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
const getStatutStyle = (statut: string) => {
|
||||
switch (statut) {
|
||||
case 'Validé':
|
||||
return {
|
||||
bg: 'bg-purple-500',
|
||||
text: 'text-white',
|
||||
border: 'border-purple-600',
|
||||
};
|
||||
case 'Terminé':
|
||||
return {
|
||||
bg: 'bg-green-500',
|
||||
text: 'text-white',
|
||||
border: 'border-green-600',
|
||||
};
|
||||
case 'En cours':
|
||||
return {
|
||||
bg: 'bg-blue-500',
|
||||
text: 'text-white',
|
||||
border: 'border-blue-600',
|
||||
};
|
||||
case 'Annulé':
|
||||
return {
|
||||
bg: 'bg-red-500',
|
||||
text: 'text-white',
|
||||
border: 'border-red-600',
|
||||
};
|
||||
default:
|
||||
return {
|
||||
bg: 'bg-lblue',
|
||||
text: 'text-white',
|
||||
border: 'border-lblue',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
|
||||
};
|
||||
|
||||
const styleObj = getStatutStyle(trajet.statut);
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
{...listeners}
|
||||
{...attributes}
|
||||
onClick={(e) => onClick(e, trajet)}
|
||||
className={`text-[10px] px-1.5 py-0.5 rounded border ${styleObj.bg} ${styleObj.text} ${styleObj.border} font-semibold truncate w-full text-left transition-all flex items-center gap-1 ${canDrag ? 'hover:shadow-md cursor-grab active:cursor-grabbing' : 'cursor-default opacity-75'} ${isDragging ? 'opacity-50' : ''}`}
|
||||
title={`${trajet.adherent.prenom} ${trajet.adherent.nom} - ${trajet.chauffeur ? `${trajet.chauffeur.prenom} ${trajet.chauffeur.nom}` : 'Sans chauffeur'} - ${trajet.statut}`}
|
||||
>
|
||||
<span className="font-bold">
|
||||
{trajet.chauffeur
|
||||
? `${trajet.chauffeur.prenom.charAt(0)}${trajet.chauffeur.nom.charAt(0)}`
|
||||
: '?'}
|
||||
</span>
|
||||
<span className="opacity-90">•</span>
|
||||
<span className="opacity-90">{formatTime(trajet.date)}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Composant droppable pour une cellule de jour
|
||||
function DroppableDayCell({
|
||||
date,
|
||||
children,
|
||||
isToday,
|
||||
isSelected,
|
||||
onDateClick
|
||||
}: {
|
||||
date: Date;
|
||||
children: React.ReactNode;
|
||||
isToday: boolean;
|
||||
isSelected: boolean;
|
||||
onDateClick: (date: Date) => void;
|
||||
}) {
|
||||
// Créer un ID basé sur les composants de date pour éviter les problèmes de fuseau horaire
|
||||
const dayId = `day-${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
|
||||
const { setNodeRef, isOver } = useDroppable({
|
||||
id: dayId,
|
||||
data: { date },
|
||||
});
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={setNodeRef}
|
||||
onClick={() => onDateClick(date)}
|
||||
className={`h-24 p-2 rounded-lg border-2 transition-all flex flex-col ${
|
||||
isSelected
|
||||
? 'border-lblue bg-lblue/10'
|
||||
: isToday
|
||||
? 'border-lblue bg-lblue/5'
|
||||
: isOver
|
||||
? 'border-lgreen bg-lgreen/20 border-2'
|
||||
: 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsProps) {
|
||||
const [trajets, setTrajets] = useState<Trajet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [currentDate, setCurrentDate] = useState(new Date());
|
||||
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
|
||||
const [selectedTrajets, setSelectedTrajets] = useState<Trajet[]>([]);
|
||||
const [selectedTrajet, setSelectedTrajet] = useState<Trajet | null>(null);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const [draggedTrajet, setDraggedTrajet] = useState<Trajet | null>(null);
|
||||
|
||||
const month = currentDate.getMonth();
|
||||
const year = currentDate.getFullYear();
|
||||
@@ -47,11 +173,13 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
const adjustedStartingDay = startingDayOfWeek === 0 ? 6 : startingDayOfWeek - 1;
|
||||
|
||||
useEffect(() => {
|
||||
fetchTrajets();
|
||||
fetchTrajets(true);
|
||||
}, [currentDate, refreshTrigger]);
|
||||
|
||||
const fetchTrajets = async () => {
|
||||
setLoading(true);
|
||||
const fetchTrajets = async (showLoading = true) => {
|
||||
if (showLoading) {
|
||||
setLoading(true);
|
||||
}
|
||||
try {
|
||||
const startDate = new Date(year, month, 1).toISOString();
|
||||
const endDate = new Date(year, month + 1, 0, 23, 59, 59).toISOString();
|
||||
@@ -62,19 +190,45 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setTrajets(data);
|
||||
|
||||
// Mettre à jour la liste des trajets du jour sélectionné après le fetch
|
||||
if (selectedDate) {
|
||||
const trajetsDuJour = data.filter((t: Trajet) => {
|
||||
const trajetDate = new Date(t.date);
|
||||
return (
|
||||
trajetDate.getDate() === selectedDate.getDate() &&
|
||||
trajetDate.getMonth() === selectedDate.getMonth() &&
|
||||
trajetDate.getFullYear() === selectedDate.getFullYear()
|
||||
);
|
||||
});
|
||||
setSelectedTrajets(trajetsDuJour);
|
||||
}
|
||||
} else {
|
||||
console.error('Erreur lors de la récupération des trajets:', response.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors du chargement des trajets:', error);
|
||||
// Ne pas vider les trajets en cas d'erreur
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (showLoading) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getTrajetsForDate = (date: Date): Trajet[] => {
|
||||
const dateStr = date.toISOString().split('T')[0];
|
||||
// Utiliser les composants de date directement pour éviter les problèmes de fuseau horaire
|
||||
const targetYear = date.getFullYear();
|
||||
const targetMonth = date.getMonth();
|
||||
const targetDay = date.getDate();
|
||||
|
||||
return trajets.filter((trajet) => {
|
||||
const trajetDate = new Date(trajet.date).toISOString().split('T')[0];
|
||||
return trajetDate === dateStr;
|
||||
const trajetDate = new Date(trajet.date);
|
||||
return (
|
||||
trajetDate.getFullYear() === targetYear &&
|
||||
trajetDate.getMonth() === targetMonth &&
|
||||
trajetDate.getDate() === targetDay
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -84,6 +238,89 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
setSelectedTrajets(trajetsDuJour);
|
||||
};
|
||||
|
||||
const handleTrajetClick = (e: React.MouseEvent, trajet: Trajet) => {
|
||||
e.stopPropagation(); // Empêcher le clic sur la date
|
||||
setSelectedTrajet(trajet);
|
||||
};
|
||||
|
||||
const handleDragStart = (event: DragStartEvent) => {
|
||||
setActiveId(event.active.id as string);
|
||||
const trajet = event.active.data.current?.trajet as Trajet;
|
||||
setDraggedTrajet(trajet);
|
||||
};
|
||||
|
||||
const handleDragEnd = async (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
setActiveId(null);
|
||||
setDraggedTrajet(null);
|
||||
|
||||
if (!over || !active.data.current?.trajet) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trajet = active.data.current.trajet as Trajet;
|
||||
|
||||
// Vérifier que le trajet peut être déplacé
|
||||
if (trajet.statut === 'Annulé' || trajet.statut === 'Validé' || trajet.statut === 'Terminé') {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetDayId = over.id as string;
|
||||
|
||||
// Extraire la date de la cible (format: "day-2026-01-23")
|
||||
if (typeof targetDayId === 'string' && targetDayId.startsWith('day-')) {
|
||||
const dateStr = targetDayId.replace('day-', '');
|
||||
const [year, month, day] = dateStr.split('-').map(Number);
|
||||
|
||||
// Vérifier que les composants de date sont valides
|
||||
if (isNaN(year) || isNaN(month) || isNaN(day)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Conserver l'heure du trajet original, changer seulement la date
|
||||
const originalDate = new Date(trajet.date);
|
||||
|
||||
// Créer la nouvelle date avec les composants locaux pour correspondre exactement au calendrier
|
||||
// Note: month - 1 car les mois sont indexés à partir de 0 en JavaScript
|
||||
// On crée la date directement avec l'heure originale mais la date cible
|
||||
// Pour éviter les problèmes de fuseau horaire, on crée d'abord à midi puis on ajuste
|
||||
const newDate = new Date(year, month - 1, day, 12, 0, 0, 0);
|
||||
newDate.setHours(originalDate.getHours(), originalDate.getMinutes(), originalDate.getSeconds(), originalDate.getMilliseconds());
|
||||
|
||||
// Vérifier que la date a changé
|
||||
const originalDateOnly = new Date(originalDate.getFullYear(), originalDate.getMonth(), originalDate.getDate());
|
||||
const newDateOnly = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate());
|
||||
|
||||
if (originalDateOnly.getTime() === newDateOnly.getTime()) {
|
||||
return; // Même jour, pas besoin de mettre à jour
|
||||
}
|
||||
|
||||
// Mettre à jour le trajet
|
||||
try {
|
||||
const response = await fetch(`/api/trajets/${trajet.id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
date: newDate.toISOString(),
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Utiliser fetchTrajets sans loading pour éviter de vider les trajets pendant le chargement
|
||||
await fetchTrajets(false);
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || 'Erreur lors du déplacement du trajet');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors du déplacement:', error);
|
||||
alert('Erreur lors du déplacement du trajet');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const goToPreviousMonth = () => {
|
||||
setCurrentDate(new Date(year, month - 1, 1));
|
||||
};
|
||||
@@ -162,71 +399,80 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
<div className="text-center py-8 text-gray-500">Chargement...</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Grille du calendrier */}
|
||||
<div className="grid grid-cols-7 gap-2 mb-6">
|
||||
{/* En-têtes des jours */}
|
||||
{days.map((day) => (
|
||||
<div key={day} className="text-center text-sm font-semibold text-gray-600 py-2">
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
{/* Grille du calendrier avec drag and drop */}
|
||||
<DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
|
||||
<div className="grid grid-cols-7 gap-2 mb-6">
|
||||
{/* En-têtes des jours */}
|
||||
{days.map((day) => (
|
||||
<div key={day} className="text-center text-sm font-semibold text-gray-600 py-2">
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Jours du calendrier */}
|
||||
{calendarDays.map((date, index) => {
|
||||
if (!date) {
|
||||
return <div key={`empty-${index}`} className="h-24" />;
|
||||
}
|
||||
{/* Jours du calendrier */}
|
||||
{calendarDays.map((date, index) => {
|
||||
if (!date) {
|
||||
return <div key={`empty-${index}`} className="h-24" />;
|
||||
}
|
||||
|
||||
const trajetsDuJour = getTrajetsForDate(date);
|
||||
const isToday =
|
||||
date.getDate() === new Date().getDate() &&
|
||||
date.getMonth() === new Date().getMonth() &&
|
||||
date.getFullYear() === new Date().getFullYear();
|
||||
const isSelected =
|
||||
selectedDate &&
|
||||
date.getDate() === selectedDate.getDate() &&
|
||||
date.getMonth() === selectedDate.getMonth() &&
|
||||
date.getFullYear() === selectedDate.getFullYear();
|
||||
const trajetsDuJour = getTrajetsForDate(date);
|
||||
const isToday =
|
||||
date.getDate() === new Date().getDate() &&
|
||||
date.getMonth() === new Date().getMonth() &&
|
||||
date.getFullYear() === new Date().getFullYear();
|
||||
const isSelected =
|
||||
selectedDate &&
|
||||
date.getDate() === selectedDate.getDate() &&
|
||||
date.getMonth() === selectedDate.getMonth() &&
|
||||
date.getFullYear() === selectedDate.getFullYear();
|
||||
|
||||
return (
|
||||
<button
|
||||
key={date.toISOString()}
|
||||
onClick={() => handleDateClick(date)}
|
||||
className={`h-24 p-2 rounded-lg border-2 transition-all flex flex-col ${
|
||||
isSelected
|
||||
? 'border-lblue bg-lblue/10'
|
||||
: isToday
|
||||
? 'border-lblue bg-lblue/5'
|
||||
: 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<div className="text-sm font-medium text-gray-900 mb-1">
|
||||
{date.getDate()}
|
||||
</div>
|
||||
{trajetsDuJour.length > 0 && (
|
||||
<div className="space-y-1 flex-1 overflow-hidden">
|
||||
{trajetsDuJour.slice(0, 2).map((trajet) => (
|
||||
<div
|
||||
key={trajet.id}
|
||||
className="text-xs px-1.5 py-0.5 rounded bg-lblue text-white truncate"
|
||||
title={`${trajet.adherent.prenom} ${trajet.adherent.nom} - ${trajet.chauffeur ? `${trajet.chauffeur.prenom} ${trajet.chauffeur.nom}` : 'Sans chauffeur'}`}
|
||||
>
|
||||
{trajet.chauffeur
|
||||
? `${trajet.chauffeur.prenom.charAt(0)}. ${trajet.chauffeur.nom.charAt(0)}`
|
||||
: 'Sans ch.'}
|
||||
</div>
|
||||
))}
|
||||
{trajetsDuJour.length > 2 && (
|
||||
<div className="text-xs text-gray-500 font-medium">
|
||||
+{trajetsDuJour.length - 2}
|
||||
</div>
|
||||
)}
|
||||
return (
|
||||
<DroppableDayCell
|
||||
key={date.toISOString()}
|
||||
date={date}
|
||||
isToday={isToday}
|
||||
isSelected={isSelected}
|
||||
onDateClick={handleDateClick}
|
||||
>
|
||||
<div className="text-sm font-medium text-gray-900 mb-1">
|
||||
{date.getDate()}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{trajetsDuJour.length > 0 && (
|
||||
<div className="space-y-1 flex-1 overflow-hidden">
|
||||
{trajetsDuJour.slice(0, 3).map((trajet) => (
|
||||
<DraggableTrajetEvent
|
||||
key={trajet.id}
|
||||
trajet={trajet}
|
||||
onClick={handleTrajetClick}
|
||||
/>
|
||||
))}
|
||||
{trajetsDuJour.length > 3 && (
|
||||
<div className="text-[10px] text-gray-500 font-semibold text-center pt-0.5">
|
||||
+{trajetsDuJour.length - 3}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DroppableDayCell>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Overlay pour l'élément en cours de drag */}
|
||||
<DragOverlay>
|
||||
{draggedTrajet ? (
|
||||
<div className="text-[10px] px-2 py-1 rounded-lg border-2 bg-lblue text-white border-lblue font-semibold flex items-center gap-1 shadow-2xl transform rotate-2">
|
||||
<span className="font-bold">
|
||||
{draggedTrajet.chauffeur
|
||||
? `${draggedTrajet.chauffeur.prenom.charAt(0)}${draggedTrajet.chauffeur.nom.charAt(0)}`
|
||||
: '?'}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>{formatTime(draggedTrajet.date)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
|
||||
{/* Détails des trajets du jour sélectionné */}
|
||||
{selectedDate && selectedTrajets.length > 0 && (
|
||||
@@ -235,68 +481,81 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
Trajets du {formatDate(selectedDate)}
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{selectedTrajets.map((trajet) => (
|
||||
<div
|
||||
key={trajet.id}
|
||||
className="p-4 bg-gray-50 rounded-lg border border-gray-200"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-sm font-semibold text-gray-900">
|
||||
{trajet.adherent.prenom} {trajet.adherent.nom}
|
||||
</span>
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded bg-lblue/10 text-lblue">
|
||||
{formatTime(trajet.date)}
|
||||
</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 text-xs font-medium rounded ${
|
||||
trajet.statut === 'Terminé'
|
||||
? 'bg-green-100 text-green-700'
|
||||
: trajet.statut === 'En cours'
|
||||
? 'bg-blue-100 text-blue-700'
|
||||
: trajet.statut === 'Annulé'
|
||||
? 'bg-red-100 text-red-700'
|
||||
: 'bg-gray-100 text-gray-700'
|
||||
}`}
|
||||
>
|
||||
{trajet.statut}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 mb-1">
|
||||
<span className="font-medium">Départ:</span> {trajet.adresseDepart}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 mb-2">
|
||||
<span className="font-medium">Arrivée:</span> {trajet.adresseArrivee}
|
||||
</div>
|
||||
{trajet.chauffeur ? (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17a2 2 0 11-4 0 2 2 0 014 0zM19 17a2 2 0 11-4 0 2 2 0 014 0z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
Chauffeur: {trajet.chauffeur.prenom} {trajet.chauffeur.nom}
|
||||
{selectedTrajets.map((trajet) => {
|
||||
const getStatutColor = (statut: string) => {
|
||||
switch (statut) {
|
||||
case 'Validé':
|
||||
return 'bg-purple-100 text-purple-700 border-purple-200';
|
||||
case 'Terminé':
|
||||
return 'bg-green-100 text-green-700 border-green-200';
|
||||
case 'En cours':
|
||||
return 'bg-blue-100 text-blue-700 border-blue-200';
|
||||
case 'Annulé':
|
||||
return 'bg-red-100 text-red-700 border-red-200';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-700 border-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
key={trajet.id}
|
||||
onClick={() => setSelectedTrajet(trajet)}
|
||||
className="w-full p-4 bg-gray-50 rounded-lg border border-gray-200 hover:border-gray-300 hover:shadow-sm transition-all text-left"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-sm font-semibold text-gray-900">
|
||||
{trajet.adherent.prenom} {trajet.adherent.nom}
|
||||
</span>
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded bg-lblue/10 text-lblue">
|
||||
{formatTime(trajet.date)}
|
||||
</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 text-xs font-medium rounded border ${getStatutColor(trajet.statut)}`}
|
||||
>
|
||||
{trajet.statut}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<svg className="w-4 h-4 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
<span className="text-sm text-orange-600 font-medium">
|
||||
Aucun chauffeur assigné
|
||||
</span>
|
||||
<div className="text-sm text-gray-600 mb-1">
|
||||
<span className="font-medium">Départ:</span> {trajet.adresseDepart}
|
||||
</div>
|
||||
)}
|
||||
{trajet.commentaire && (
|
||||
<div className="mt-2 text-sm text-gray-500 italic">
|
||||
{trajet.commentaire}
|
||||
<div className="text-sm text-gray-600 mb-2">
|
||||
<span className="font-medium">Arrivée:</span> {trajet.adresseArrivee}
|
||||
</div>
|
||||
)}
|
||||
{trajet.chauffeur ? (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17a2 2 0 11-4 0 2 2 0 014 0zM19 17a2 2 0 11-4 0 2 2 0 014 0z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
Chauffeur: {trajet.chauffeur.prenom} {trajet.chauffeur.nom}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<svg className="w-4 h-4 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
<span className="text-sm text-orange-600 font-medium">
|
||||
Aucun chauffeur assigné
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{trajet.commentaire && (
|
||||
<div className="mt-2 text-sm text-gray-500 italic line-clamp-2">
|
||||
{trajet.commentaire}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<svg className="w-5 h-5 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -308,6 +567,18 @@ export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsP
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Modal de détails du trajet */}
|
||||
{selectedTrajet && (
|
||||
<TrajetDetailModal
|
||||
trajet={selectedTrajet}
|
||||
onClose={() => setSelectedTrajet(null)}
|
||||
onUpdate={() => {
|
||||
fetchTrajets();
|
||||
setSelectedTrajet(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
316
components/TrajetDetailModal.tsx
Normal file
316
components/TrajetDetailModal.tsx
Normal file
@@ -0,0 +1,316 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import TrajetForm from './TrajetForm';
|
||||
import ValidationModal from './ValidationModal';
|
||||
|
||||
interface Trajet {
|
||||
id: string;
|
||||
date: string;
|
||||
adresseDepart: string;
|
||||
adresseArrivee: string;
|
||||
commentaire?: string | null;
|
||||
statut: string;
|
||||
adherent: {
|
||||
id: string;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
telephone: string;
|
||||
email: string;
|
||||
};
|
||||
chauffeur?: {
|
||||
id: string;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
telephone: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface TrajetDetailModalProps {
|
||||
trajet: Trajet;
|
||||
onClose: () => void;
|
||||
onUpdate: () => void;
|
||||
}
|
||||
|
||||
export default function TrajetDetailModal({ trajet, onClose, onUpdate }: TrajetDetailModalProps) {
|
||||
const [showEditForm, setShowEditForm] = useState(false);
|
||||
const [showValidationModal, setShowValidationModal] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('fr-FR', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
});
|
||||
};
|
||||
|
||||
const formatTime = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
|
||||
};
|
||||
|
||||
const handleCancel = async () => {
|
||||
if (!confirm('Êtes-vous sûr de vouloir annuler ce trajet ?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/trajets/${trajet.id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
statut: 'Annulé',
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
onUpdate();
|
||||
onClose();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || 'Erreur lors de l\'annulation du trajet');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de l\'annulation:', error);
|
||||
alert('Erreur lors de l\'annulation du trajet');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getInitials = (nom: string, prenom: string) => {
|
||||
return `${prenom.charAt(0)}${nom.charAt(0)}`.toUpperCase();
|
||||
};
|
||||
|
||||
const getStatutColor = (statut: string) => {
|
||||
switch (statut) {
|
||||
case 'Terminé':
|
||||
return 'bg-green-100 text-green-700 border-green-200';
|
||||
case 'En cours':
|
||||
return 'bg-blue-100 text-blue-700 border-blue-200';
|
||||
case 'Annulé':
|
||||
return 'bg-red-100 text-red-700 border-red-200';
|
||||
case 'Validé':
|
||||
return 'bg-purple-100 text-purple-700 border-purple-200';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-700 border-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
if (showEditForm) {
|
||||
return (
|
||||
<TrajetForm
|
||||
onClose={() => setShowEditForm(false)}
|
||||
onSuccess={() => {
|
||||
onUpdate();
|
||||
setShowEditForm(false);
|
||||
onClose();
|
||||
}}
|
||||
trajetToEdit={trajet}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (showValidationModal) {
|
||||
return (
|
||||
<ValidationModal
|
||||
trajet={trajet}
|
||||
onClose={() => setShowValidationModal(false)}
|
||||
onSuccess={() => {
|
||||
onUpdate();
|
||||
setShowValidationModal(false);
|
||||
onClose();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fadeIn">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col animate-slideUp border border-gray-200">
|
||||
{/* Header */}
|
||||
<div className="border-b border-gray-200 px-6 py-5 bg-white">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold text-gray-900">Détails du trajet</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">Informations complètes du trajet</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 transition-colors p-2 hover:bg-gray-100 rounded-lg"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-6">
|
||||
<div className="space-y-6">
|
||||
{/* Statut */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-gray-500">Statut</span>
|
||||
<span className={`px-3 py-1.5 text-sm font-semibold rounded-lg border ${getStatutColor(trajet.statut)}`}>
|
||||
{trajet.statut}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Adhérent */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Adhérent</label>
|
||||
<div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="w-12 h-12 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold">
|
||||
{getInitials(trajet.adherent.nom, trajet.adherent.prenom)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-semibold text-gray-900">
|
||||
{trajet.adherent.prenom} {trajet.adherent.nom}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{trajet.adherent.email}</div>
|
||||
<div className="text-xs text-gray-500">{trajet.adherent.telephone}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chauffeur */}
|
||||
{trajet.chauffeur ? (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Chauffeur</label>
|
||||
<div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="w-12 h-12 rounded-full bg-lblue flex items-center justify-center text-white font-semibold">
|
||||
{getInitials(trajet.chauffeur.nom, trajet.chauffeur.prenom)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-semibold text-gray-900">
|
||||
{trajet.chauffeur.prenom} {trajet.chauffeur.nom}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">{trajet.chauffeur.telephone}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Chauffeur</label>
|
||||
<div className="p-3 bg-orange-50 rounded-lg border border-orange-200">
|
||||
<div className="flex items-center gap-2 text-orange-700">
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium">Aucun chauffeur assigné</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Date et heure */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Date</label>
|
||||
<div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium text-gray-900">{formatDate(trajet.date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Heure</label>
|
||||
<div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium text-gray-900">{formatTime(trajet.date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Adresses */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Adresse de départ</label>
|
||||
<div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-6 h-6 rounded-full bg-lgreen flex items-center justify-center text-white text-xs font-bold mt-0.5 flex-shrink-0">
|
||||
A
|
||||
</div>
|
||||
<span className="text-sm text-gray-900">{trajet.adresseDepart}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Adresse d'arrivée</label>
|
||||
<div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-6 h-6 rounded-full bg-lblue flex items-center justify-center text-white text-xs font-bold mt-0.5 flex-shrink-0">
|
||||
B
|
||||
</div>
|
||||
<span className="text-sm text-gray-900">{trajet.adresseArrivee}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Commentaire */}
|
||||
{trajet.commentaire && (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-500 mb-2 block">Commentaire</label>
|
||||
<div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<p className="text-sm text-gray-700 whitespace-pre-wrap">{trajet.commentaire}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="border-t border-gray-200 px-6 py-4 bg-gray-50/50">
|
||||
<div className="flex justify-between gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
disabled={loading || trajet.statut === 'Validé' || trajet.statut === 'Terminé' || trajet.statut === 'Annulé'}
|
||||
className="px-4 py-2 text-sm font-medium text-red-600 hover:text-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
{trajet.statut === 'Annulé' ? 'Trajet annulé' : 'Annuler le trajet'}
|
||||
</button>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEditForm(true)}
|
||||
disabled={trajet.statut === 'Validé' || trajet.statut === 'Terminé'}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
Modifier
|
||||
</button>
|
||||
{trajet.chauffeur && trajet.statut === 'Planifié' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowValidationModal(true)}
|
||||
className="px-6 py-2 bg-lgreen text-white text-sm font-medium rounded-lg hover:bg-dgreen transition-colors flex items-center gap-2"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
Valider le trajet
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,9 +24,19 @@ interface Chauffeur {
|
||||
interface TrajetFormProps {
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
trajetToEdit?: {
|
||||
id: string;
|
||||
date: string;
|
||||
adresseDepart: string;
|
||||
adresseArrivee: string;
|
||||
commentaire?: string | null;
|
||||
statut: string;
|
||||
adherentId: string;
|
||||
chauffeurId?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
export default function TrajetForm({ onClose, onSuccess, trajetToEdit }: TrajetFormProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [adherents, setAdherents] = useState<Adherent[]>([]);
|
||||
const [chauffeurs, setChauffeurs] = useState<Chauffeur[]>([]);
|
||||
@@ -38,20 +48,20 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
const chauffeurDropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
adherentId: '',
|
||||
adherentId: trajetToEdit?.adherentId || '',
|
||||
adherentNom: '',
|
||||
adherentPrenom: '',
|
||||
adherentAdresse: '',
|
||||
adherentTelephone: '',
|
||||
chauffeurId: '',
|
||||
chauffeurId: trajetToEdit?.chauffeurId || '',
|
||||
chauffeurNom: '',
|
||||
chauffeurPrenom: '',
|
||||
chauffeurTelephone: '',
|
||||
date: '',
|
||||
heure: '',
|
||||
adresseDepart: '',
|
||||
adresseArrivee: '',
|
||||
commentaire: '',
|
||||
date: trajetToEdit ? new Date(trajetToEdit.date).toISOString().split('T')[0] : '',
|
||||
heure: trajetToEdit ? new Date(trajetToEdit.date).toTimeString().slice(0, 5) : '',
|
||||
adresseDepart: trajetToEdit?.adresseDepart || '',
|
||||
adresseArrivee: trajetToEdit?.adresseArrivee || '',
|
||||
commentaire: trajetToEdit?.commentaire || '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -59,6 +69,49 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
fetchChauffeurs();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Si on modifie un trajet, charger les données de l'adhérent et du chauffeur
|
||||
if (trajetToEdit) {
|
||||
if (trajetToEdit.adherentId) {
|
||||
fetch(`/api/adherents/${trajetToEdit.adherentId}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
adherentId: data.id,
|
||||
adherentNom: data.nom,
|
||||
adherentPrenom: data.prenom,
|
||||
adherentAdresse: data.adresse,
|
||||
adherentTelephone: data.telephone,
|
||||
adresseDepart: data.adresse,
|
||||
}));
|
||||
setSearchAdherent(`${data.prenom} ${data.nom}`);
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
if (trajetToEdit.chauffeurId) {
|
||||
fetch(`/api/chauffeurs/${trajetToEdit.chauffeurId}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
chauffeurId: data.id,
|
||||
chauffeurNom: data.nom,
|
||||
chauffeurPrenom: data.prenom,
|
||||
chauffeurTelephone: data.telephone,
|
||||
}));
|
||||
setSearchChauffeur(`${data.prenom} ${data.nom}`);
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
}
|
||||
}, [trajetToEdit]);
|
||||
|
||||
// Fermer les dropdowns quand on clique en dehors
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
@@ -160,8 +213,11 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
? new Date(`${formData.date}T09:00`).toISOString()
|
||||
: new Date().toISOString();
|
||||
|
||||
const response = await fetch('/api/trajets', {
|
||||
method: 'POST',
|
||||
const url = trajetToEdit ? `/api/trajets/${trajetToEdit.id}` : '/api/trajets';
|
||||
const method = trajetToEdit ? 'PUT' : 'POST';
|
||||
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
@@ -170,7 +226,7 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
adresseDepart: formData.adresseDepart,
|
||||
adresseArrivee: formData.adresseArrivee,
|
||||
commentaire: formData.commentaire || null,
|
||||
statut: 'Planifié',
|
||||
statut: trajetToEdit?.statut || 'Planifié',
|
||||
adherentId: formData.adherentId,
|
||||
chauffeurId: formData.chauffeurId || null,
|
||||
}),
|
||||
@@ -181,11 +237,11 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
onClose();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(`Erreur: ${error.error || 'Erreur lors de la création du trajet'}`);
|
||||
alert(`Erreur: ${error.error || `Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet`}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la création du trajet:', error);
|
||||
alert('Erreur lors de la création du trajet');
|
||||
console.error(`Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet:`, error);
|
||||
alert(`Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -202,8 +258,12 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
<div className="border-b border-gray-200 px-6 py-5 bg-white">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold text-gray-900">Nouveau trajet</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">Créez un nouveau trajet pour un adhérent</p>
|
||||
<h2 className="text-2xl font-semibold text-gray-900">
|
||||
{trajetToEdit ? 'Modifier le trajet' : 'Nouveau trajet'}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{trajetToEdit ? 'Modifiez les informations du trajet' : 'Créez un nouveau trajet pour un adhérent'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
@@ -487,10 +547,10 @@ export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Création...
|
||||
{trajetToEdit ? 'Modification...' : 'Création...'}
|
||||
</>
|
||||
) : (
|
||||
'Créer le trajet'
|
||||
trajetToEdit ? 'Modifier le trajet' : 'Créer le trajet'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
259
components/ValidationModal.tsx
Normal file
259
components/ValidationModal.tsx
Normal file
@@ -0,0 +1,259 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
interface Trajet {
|
||||
id: string;
|
||||
date: string;
|
||||
adresseDepart: string;
|
||||
adresseArrivee: string;
|
||||
chauffeur?: {
|
||||
id: string;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface ValidationModalProps {
|
||||
trajet: Trajet;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function ValidationModal({ trajet, onClose, onSuccess }: ValidationModalProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [dureeTrajet, setDureeTrajet] = useState<number | null>(null);
|
||||
|
||||
// Calculer la durée du trajet en heures
|
||||
const calculateDuration = async () => {
|
||||
if (!trajet.adresseDepart || !trajet.adresseArrivee) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Géocoder l'adresse de départ
|
||||
const departResponse = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(trajet.adresseDepart)}&limit=1&countrycodes=fr`,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent': 'MAD Platform',
|
||||
'Accept-Language': 'fr-FR,fr;q=0.9',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!departResponse.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Attendre avant la deuxième requête
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
const arriveeResponse = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(trajet.adresseArrivee)}&limit=1&countrycodes=fr`,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent': 'MAD Platform',
|
||||
'Accept-Language': 'fr-FR,fr;q=0.9',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (departResponse.ok && arriveeResponse.ok) {
|
||||
const [departData, arriveeData] = await Promise.all([
|
||||
departResponse.json(),
|
||||
arriveeResponse.json(),
|
||||
]);
|
||||
|
||||
if (departData.length > 0 && arriveeData.length > 0) {
|
||||
const lat1 = parseFloat(departData[0].lat);
|
||||
const lon1 = parseFloat(departData[0].lon);
|
||||
const lat2 = parseFloat(arriveeData[0].lat);
|
||||
const lon2 = parseFloat(arriveeData[0].lon);
|
||||
|
||||
// Calcul de la distance (Haversine)
|
||||
const R = 6371; // Rayon de la Terre en km
|
||||
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const dLon = ((lon2 - lon1) * Math.PI) / 180;
|
||||
const a =
|
||||
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos((lat1 * Math.PI) / 180) *
|
||||
Math.cos((lat2 * Math.PI) / 180) *
|
||||
Math.sin(dLon / 2) *
|
||||
Math.sin(dLon / 2);
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
const distance = R * c; // Distance en km
|
||||
|
||||
// Estimation du temps : vitesse moyenne de 50 km/h en ville
|
||||
// On multiplie par 1.3 pour tenir compte des détours
|
||||
const distanceWithDetour = distance * 1.3;
|
||||
const vitesseMoyenne = 50; // km/h
|
||||
const dureeEnHeures = distanceWithDetour / vitesseMoyenne;
|
||||
|
||||
setDureeTrajet(Math.round(dureeEnHeures * 10) / 10); // Arrondir à 1 décimale
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors du calcul de la durée:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
calculateDuration();
|
||||
}, []);
|
||||
|
||||
const handleValidate = async () => {
|
||||
if (!trajet.chauffeur || !dureeTrajet) {
|
||||
alert('Impossible de calculer la durée du trajet');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/trajets/${trajet.id}/validate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
dureeHeures: dureeTrajet,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
onSuccess();
|
||||
onClose();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
alert(error.error || 'Erreur lors de la validation du trajet');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la validation:', error);
|
||||
alert('Erreur lors de la validation du trajet');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fadeIn">
|
||||
<div className="bg-white rounded-lg shadow-xl max-w-md w-full animate-slideUp border border-gray-200">
|
||||
{/* Header */}
|
||||
<div className="border-b border-gray-200 px-6 py-5 bg-white">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-gray-900">Valider le trajet</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">Confirmer la validation du trajet</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 transition-colors p-2 hover:bg-gray-100 rounded-lg"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="px-6 py-6">
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
|
||||
<div className="flex items-start gap-3">
|
||||
<svg className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-blue-900 mb-1">
|
||||
En validant ce trajet, les heures seront déduites du contrat du chauffeur.
|
||||
</p>
|
||||
<p className="text-xs text-blue-700">
|
||||
Cette action ne peut pas être annulée.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{trajet.chauffeur && (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700 mb-2 block">Chauffeur</label>
|
||||
<div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{trajet.chauffeur.prenom} {trajet.chauffeur.nom}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dureeTrajet !== null ? (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700 mb-2 block">Durée estimée du trajet</label>
|
||||
<div className="p-4 bg-gradient-to-r from-lgreen/10 to-lblue/10 rounded-lg border border-gray-200">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-600">Temps estimé</span>
|
||||
<span className="text-2xl font-bold text-gray-900">
|
||||
{dureeTrajet.toFixed(1)}h
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 pt-2 border-t border-gray-200">
|
||||
<p className="text-xs text-gray-500">
|
||||
{dureeTrajet.toFixed(1)} heure{dureeTrajet >= 2 ? 's' : ''} sera{dureeTrajet < 2 ? '' : 'ont'} déduite{dureeTrajet < 2 ? '' : 's'} des heures disponibles du chauffeur.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
|
||||
<div className="flex items-center gap-2 text-gray-500">
|
||||
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
<span className="text-sm">Calcul de la durée du trajet...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="border-t border-gray-200 px-6 py-4 bg-gray-50/50">
|
||||
<div className="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleValidate}
|
||||
disabled={loading || dureeTrajet === null || !trajet.chauffeur}
|
||||
className="px-6 py-2 bg-lgreen text-white text-sm font-medium rounded-lg hover:bg-dgreen transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Validation...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
Confirmer la validation
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
56
package-lock.json
generated
56
package-lock.json
generated
@@ -8,6 +8,9 @@
|
||||
"name": "platform",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@prisma/client": "^5.19.1",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"bcryptjs": "^2.4.3",
|
||||
@@ -55,6 +58,59 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz",
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
"setup": "tsx scripts/setup.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@prisma/client": "^5.19.1",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"bcryptjs": "^2.4.3",
|
||||
|
||||
BIN
prisma/dev.db
BIN
prisma/dev.db
Binary file not shown.
Reference in New Issue
Block a user