Added Calendar Page

This commit is contained in:
2026-01-21 17:34:48 +01:00
parent 3a8a6d1576
commit c9f6b53c13
14 changed files with 2188 additions and 9 deletions

View File

@@ -0,0 +1,154 @@
'use client';
import { useState, useEffect, useRef } from 'react';
interface AddressSuggestion {
display_name: string;
lat: string;
lon: string;
}
interface AddressAutocompleteProps {
value: string;
onChange: (address: string) => void;
placeholder?: string;
required?: boolean;
}
export default function AddressAutocomplete({
value,
onChange,
placeholder = 'Rechercher une adresse...',
required = false,
}: AddressAutocompleteProps) {
const [suggestions, setSuggestions] = useState<AddressSuggestion[]>([]);
const [showSuggestions, setShowSuggestions] = useState(false);
const [loading, setLoading] = useState(false);
const wrapperRef = useRef<HTMLDivElement>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
setShowSuggestions(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
const searchAddresses = async (query: string) => {
if (query.length < 3) {
setSuggestions([]);
return;
}
setLoading(true);
try {
// Annuler la requête précédente si elle existe
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Attendre un peu avant de faire la requête (debounce)
timeoutRef.current = setTimeout(async () => {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5&addressdetails=1&countrycodes=fr`,
{
headers: {
'User-Agent': 'MAD Platform',
'Accept-Language': 'fr-FR,fr;q=0.9',
},
}
);
if (response.ok) {
const data = await response.json();
setSuggestions(data);
setShowSuggestions(true);
}
} catch (error) {
console.error('Erreur lors de la recherche d\'adresses:', error);
} finally {
setLoading(false);
}
}, 300);
} catch (error) {
console.error('Erreur:', error);
setLoading(false);
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
onChange(newValue);
searchAddresses(newValue);
};
const handleSelectSuggestion = (suggestion: AddressSuggestion) => {
onChange(suggestion.display_name);
setShowSuggestions(false);
setSuggestions([]);
};
return (
<div className="relative" ref={wrapperRef}>
<div className="relative">
<input
type="text"
value={value}
onChange={handleInputChange}
onFocus={() => {
if (suggestions.length > 0) {
setShowSuggestions(true);
}
}}
placeholder={placeholder}
required={required}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
{loading && (
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
<svg className="animate-spin h-5 w-5 text-gray-400" 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>
</div>
)}
</div>
{showSuggestions && suggestions.length > 0 && (
<div className="absolute z-20 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
{suggestions.map((suggestion, index) => (
<button
key={index}
type="button"
onClick={() => handleSelectSuggestion(suggestion)}
className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-start gap-3 border-b border-gray-100 last:border-b-0 transition-colors"
>
<svg className="w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 truncate">
{suggestion.display_name.split(',').slice(0, 2).join(', ')}
</div>
<div className="text-xs text-gray-500 mt-0.5 truncate">
{suggestion.display_name}
</div>
</div>
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,27 @@
'use client';
import { useState } from 'react';
import CalendrierTrajets from './CalendrierTrajets';
import ListeTrajets from './ListeTrajets';
export default function CalendrierPageContent() {
const [refreshTrigger, setRefreshTrigger] = useState(0);
const handleTrajetCreated = () => {
setRefreshTrigger((prev) => prev + 1);
};
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Calendrier - Prend 2 colonnes sur grand écran */}
<div className="lg:col-span-2">
<CalendrierTrajets refreshTrigger={refreshTrigger} />
</div>
{/* Liste des derniers trajets - Prend 1 colonne sur grand écran */}
<div className="lg:col-span-1">
<ListeTrajets onTrajetCreated={handleTrajetCreated} />
</div>
</div>
);
}

View File

@@ -0,0 +1,313 @@
'use client';
import { useState, useEffect } from 'react';
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 CalendrierTrajetsProps {
refreshTrigger?: number;
}
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 month = currentDate.getMonth();
const year = currentDate.getFullYear();
const firstDayOfMonth = new Date(year, month, 1);
const lastDayOfMonth = new Date(year, month + 1, 0);
const daysInMonth = lastDayOfMonth.getDate();
const startingDayOfWeek = firstDayOfMonth.getDay();
// Ajuster pour que lundi soit le premier jour (0 = lundi)
const adjustedStartingDay = startingDayOfWeek === 0 ? 6 : startingDayOfWeek - 1;
useEffect(() => {
fetchTrajets();
}, [currentDate, refreshTrigger]);
const fetchTrajets = async () => {
setLoading(true);
try {
const startDate = new Date(year, month, 1).toISOString();
const endDate = new Date(year, month + 1, 0, 23, 59, 59).toISOString();
const response = await fetch(
`/api/trajets?startDate=${startDate}&endDate=${endDate}`
);
if (response.ok) {
const data = await response.json();
setTrajets(data);
}
} catch (error) {
console.error('Erreur lors du chargement des trajets:', error);
} finally {
setLoading(false);
}
};
const getTrajetsForDate = (date: Date): Trajet[] => {
const dateStr = date.toISOString().split('T')[0];
return trajets.filter((trajet) => {
const trajetDate = new Date(trajet.date).toISOString().split('T')[0];
return trajetDate === dateStr;
});
};
const handleDateClick = (date: Date) => {
setSelectedDate(date);
const trajetsDuJour = getTrajetsForDate(date);
setSelectedTrajets(trajetsDuJour);
};
const goToPreviousMonth = () => {
setCurrentDate(new Date(year, month - 1, 1));
};
const goToNextMonth = () => {
setCurrentDate(new Date(year, month + 1, 1));
};
const goToToday = () => {
setCurrentDate(new Date());
};
const formatDate = (date: Date) => {
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 days = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
const calendarDays = [];
// Ajouter les jours vides du début
for (let i = 0; i < adjustedStartingDay; i++) {
calendarDays.push(null);
}
// Ajouter les jours du mois
for (let day = 1; day <= daysInMonth; day++) {
calendarDays.push(new Date(year, month, day));
}
return (
<div className="bg-white rounded-lg shadow-sm p-6">
{/* En-tête du calendrier */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-semibold text-gray-900">
{currentDate.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })}
</h2>
<div className="flex items-center gap-2">
<button
onClick={goToPreviousMonth}
className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
title="Mois précédent"
>
<svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</button>
<button
onClick={goToToday}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
>
Aujourd'hui
</button>
<button
onClick={goToNextMonth}
className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
title="Mois suivant"
>
<svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
{loading ? (
<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>
))}
{/* 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();
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>
)}
</div>
)}
</button>
);
})}
</div>
{/* Détails des trajets du jour sélectionné */}
{selectedDate && selectedTrajets.length > 0 && (
<div className="mt-6 pt-6 border-t border-gray-200">
<h3 className="text-lg font-semibold text-gray-900 mb-4">
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}
</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">
{trajet.commentaire}
</div>
)}
</div>
</div>
</div>
))}
</div>
</div>
)}
{selectedDate && selectedTrajets.length === 0 && (
<div className="mt-6 pt-6 border-t border-gray-200 text-center text-gray-500">
Aucun trajet prévu pour le {formatDate(selectedDate)}
</div>
)}
</>
)}
</div>
);
}

343
components/ListeTrajets.tsx Normal file
View File

@@ -0,0 +1,343 @@
'use client';
import { useState, useEffect } from 'react';
import TrajetForm from './TrajetForm';
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 ListeTrajetsProps {
onTrajetCreated?: () => void;
}
export default function ListeTrajets({ onTrajetCreated }: ListeTrajetsProps) {
const [trajets, setTrajets] = useState<Trajet[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
const [showFilters, setShowFilters] = useState(false);
const [filterStatut, setFilterStatut] = useState<string>('');
const [showTrajetForm, setShowTrajetForm] = useState(false);
useEffect(() => {
fetchTrajets();
}, []);
const fetchTrajets = async () => {
setLoading(true);
try {
const response = await fetch('/api/trajets?limit=10');
if (response.ok) {
const data = await response.json();
// L'API retourne déjà les trajets triés par date de création (plus récents en premier)
setTrajets(data);
}
} catch (error) {
console.error('Erreur lors du chargement des trajets:', error);
} finally {
setLoading(false);
}
};
const filteredTrajets = trajets.filter((trajet) => {
const matchesSearch =
!search ||
trajet.adherent.nom.toLowerCase().includes(search.toLowerCase()) ||
trajet.adherent.prenom.toLowerCase().includes(search.toLowerCase()) ||
trajet.adresseDepart.toLowerCase().includes(search.toLowerCase()) ||
trajet.adresseArrivee.toLowerCase().includes(search.toLowerCase()) ||
(trajet.chauffeur &&
`${trajet.chauffeur.prenom} ${trajet.chauffeur.nom}`
.toLowerCase()
.includes(search.toLowerCase()));
const matchesStatut = !filterStatut || trajet.statut === filterStatut;
return matchesSearch && matchesStatut;
});
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString('fr-FR', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
};
const formatTime = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
};
const getInitials = (nom: string, prenom: string) => {
return `${prenom.charAt(0)}${nom.charAt(0)}`.toUpperCase();
};
return (
<div className="bg-white rounded-lg shadow-sm">
{/* Bloc d'actions */}
<div className="p-6 border-b border-gray-200">
<div className="flex flex-col gap-4">
{/* Barre de recherche */}
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg className="h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<input
type="text"
placeholder="Rechercher un trajet..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="block w-full pl-10 pr-3 py-2.5 text-sm border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
</div>
{/* Actions */}
<div className="flex items-center gap-2">
<button
onClick={() => setShowTrajetForm(true)}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-lgreen text-white text-sm font-medium rounded-lg hover:bg-dgreen transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
Nouveau trajet
</button>
<button
onClick={() => setShowFilters(!showFilters)}
className={`px-4 py-2.5 text-sm font-medium rounded-lg transition-colors flex items-center gap-2 ${
showFilters || filterStatut
? 'bg-lblue text-white hover:bg-dblue'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
</svg>
Filtrer
</button>
</div>
{/* Filtres */}
{showFilters && (
<div className="pt-3 border-t border-gray-200">
<div className="flex flex-wrap gap-2">
<button
onClick={() => setFilterStatut('')}
className={`px-3 py-2 text-xs font-medium rounded ${
!filterStatut
? 'bg-lblue text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Tous
</button>
<button
onClick={() => setFilterStatut('Planifié')}
className={`px-3 py-2 text-xs font-medium rounded ${
filterStatut === 'Planifié'
? 'bg-lblue text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Planifié
</button>
<button
onClick={() => setFilterStatut('En cours')}
className={`px-3 py-2 text-xs font-medium rounded ${
filterStatut === 'En cours'
? 'bg-lblue text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
En cours
</button>
<button
onClick={() => setFilterStatut('Terminé')}
className={`px-3 py-2 text-xs font-medium rounded ${
filterStatut === 'Terminé'
? 'bg-lblue text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Terminé
</button>
<button
onClick={() => setFilterStatut('Annulé')}
className={`px-3 py-2 text-xs font-medium rounded ${
filterStatut === 'Annulé'
? 'bg-lblue text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Annulé
</button>
</div>
</div>
)}
</div>
</div>
{/* Liste des trajets */}
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-semibold text-gray-900">
Derniers trajets créés
</h2>
<button
onClick={fetchTrajets}
className="text-sm text-lblue hover:text-dblue font-medium 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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
Actualiser
</button>
</div>
{loading ? (
<div className="text-center py-8 text-gray-500">Chargement...</div>
) : filteredTrajets.length === 0 ? (
<div className="text-center py-8 text-gray-500">
{trajets.length === 0
? 'Aucun trajet créé récemment'
: 'Aucun trajet ne correspond à votre recherche'}
</div>
) : (
<div className="space-y-3">
{filteredTrajets.map((trajet) => (
<div
key={trajet.id}
className="p-4 bg-gray-50 rounded-lg border border-gray-200 hover:border-gray-300 transition-colors"
>
<div className="flex items-start gap-4">
{/* Avatar adhérent */}
<div className="w-12 h-12 rounded-full bg-lgreen flex items-center justify-center text-white text-sm font-semibold flex-shrink-0">
{getInitials(trajet.adherent.nom, trajet.adherent.prenom)}
</div>
{/* Informations principales */}
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-4 mb-2">
<div>
<h3 className="text-sm font-semibold text-gray-900">
{trajet.adherent.prenom} {trajet.adherent.nom}
</h3>
<div className="flex items-center gap-3 mt-1">
<span className="text-xs text-gray-500 flex items-center gap-1">
<svg className="w-3 h-3" 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>
{formatDate(trajet.date)}
</span>
<span className="text-xs text-gray-500 flex items-center gap-1">
<svg className="w-3 h-3" 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>
{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>
</div>
{/* Adresses */}
<div className="space-y-1 mb-2">
<div className="text-sm text-gray-600">
<span className="font-medium">Départ:</span>{' '}
<span className="text-gray-900">{trajet.adresseDepart}</span>
</div>
<div className="text-sm text-gray-600">
<span className="font-medium">Arrivée:</span>{' '}
<span className="text-gray-900">{trajet.adresseArrivee}</span>
</div>
</div>
{/* Chauffeur */}
<div className="flex items-center gap-4 mt-3">
{trajet.chauffeur ? (
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full bg-lblue flex items-center justify-center text-white text-xs font-semibold">
{getInitials(trajet.chauffeur.nom, trajet.chauffeur.prenom)}
</div>
<div>
<div className="text-xs text-gray-500">Chauffeur</div>
<div className="text-sm font-medium text-gray-900">
{trajet.chauffeur.prenom} {trajet.chauffeur.nom}
</div>
</div>
</div>
) : (
<div className="flex items-center gap-2">
<svg className="w-5 h-5 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>
)}
</div>
{/* Commentaire */}
{trajet.commentaire && (
<div className="mt-2 pt-2 border-t border-gray-200">
<p className="text-xs text-gray-500 italic">{trajet.commentaire}</p>
</div>
)}
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Modal formulaire trajet */}
{showTrajetForm && (
<TrajetForm
onClose={() => setShowTrajetForm(false)}
onSuccess={() => {
fetchTrajets();
if (onTrajetCreated) {
onTrajetCreated();
}
}}
/>
)}
</div>
);
}

501
components/TrajetForm.tsx Normal file
View File

@@ -0,0 +1,501 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import TrajetMap from './TrajetMap';
import AddressAutocomplete from './AddressAutocomplete';
interface Adherent {
id: string;
nom: string;
prenom: string;
adresse: string;
telephone: string;
email: string;
}
interface Chauffeur {
id: string;
nom: string;
prenom: string;
telephone: string;
email: string;
}
interface TrajetFormProps {
onClose: () => void;
onSuccess: () => void;
}
export default function TrajetForm({ onClose, onSuccess }: TrajetFormProps) {
const [loading, setLoading] = useState(false);
const [adherents, setAdherents] = useState<Adherent[]>([]);
const [chauffeurs, setChauffeurs] = useState<Chauffeur[]>([]);
const [searchAdherent, setSearchAdherent] = useState('');
const [searchChauffeur, setSearchChauffeur] = useState('');
const [showAdherentDropdown, setShowAdherentDropdown] = useState(false);
const [showChauffeurDropdown, setShowChauffeurDropdown] = useState(false);
const adherentDropdownRef = useRef<HTMLDivElement>(null);
const chauffeurDropdownRef = useRef<HTMLDivElement>(null);
const [formData, setFormData] = useState({
adherentId: '',
adherentNom: '',
adherentPrenom: '',
adherentAdresse: '',
adherentTelephone: '',
chauffeurId: '',
chauffeurNom: '',
chauffeurPrenom: '',
chauffeurTelephone: '',
date: '',
heure: '',
adresseDepart: '',
adresseArrivee: '',
commentaire: '',
});
useEffect(() => {
fetchAdherents();
fetchChauffeurs();
}, []);
// Fermer les dropdowns quand on clique en dehors
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
adherentDropdownRef.current &&
!adherentDropdownRef.current.contains(event.target as Node)
) {
setShowAdherentDropdown(false);
}
if (
chauffeurDropdownRef.current &&
!chauffeurDropdownRef.current.contains(event.target as Node)
) {
setShowChauffeurDropdown(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
const fetchAdherents = async () => {
try {
const response = await fetch('/api/adherents');
if (response.ok) {
const data = await response.json();
setAdherents(data);
}
} catch (error) {
console.error('Erreur lors du chargement des adhérents:', error);
}
};
const fetchChauffeurs = async () => {
try {
const response = await fetch('/api/chauffeurs');
if (response.ok) {
const data = await response.json();
setChauffeurs(data);
}
} catch (error) {
console.error('Erreur lors du chargement des chauffeurs:', error);
}
};
const handleSelectAdherent = (adherent: Adherent) => {
setFormData({
...formData,
adherentId: adherent.id,
adherentNom: adherent.nom,
adherentPrenom: adherent.prenom,
adherentAdresse: adherent.adresse,
adherentTelephone: adherent.telephone,
adresseDepart: adherent.adresse, // Remplir automatiquement l'adresse de départ
});
setSearchAdherent(`${adherent.prenom} ${adherent.nom}`);
setShowAdherentDropdown(false);
};
const handleSelectChauffeur = (chauffeur: Chauffeur) => {
setFormData({
...formData,
chauffeurId: chauffeur.id,
chauffeurNom: chauffeur.nom,
chauffeurPrenom: chauffeur.prenom,
chauffeurTelephone: chauffeur.telephone,
});
setSearchChauffeur(`${chauffeur.prenom} ${chauffeur.nom}`);
setShowChauffeurDropdown(false);
};
const filteredAdherents = adherents.filter(
(a) =>
!searchAdherent ||
`${a.prenom} ${a.nom}`.toLowerCase().includes(searchAdherent.toLowerCase()) ||
a.email.toLowerCase().includes(searchAdherent.toLowerCase()) ||
a.telephone.includes(searchAdherent)
);
const filteredChauffeurs = chauffeurs.filter(
(c) =>
!searchChauffeur ||
`${c.prenom} ${c.nom}`.toLowerCase().includes(searchChauffeur.toLowerCase()) ||
c.email.toLowerCase().includes(searchChauffeur.toLowerCase()) ||
c.telephone.includes(searchChauffeur)
);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
// Combiner date et heure
const dateTime = formData.date && formData.heure
? new Date(`${formData.date}T${formData.heure}`).toISOString()
: formData.date
? new Date(`${formData.date}T09:00`).toISOString()
: new Date().toISOString();
const response = await fetch('/api/trajets', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
date: dateTime,
adresseDepart: formData.adresseDepart,
adresseArrivee: formData.adresseArrivee,
commentaire: formData.commentaire || null,
statut: 'Planifié',
adherentId: formData.adherentId,
chauffeurId: formData.chauffeurId || null,
}),
});
if (response.ok) {
onSuccess();
onClose();
} else {
const error = await response.json();
alert(`Erreur: ${error.error || 'Erreur lors de la 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');
} finally {
setLoading(false);
}
};
const getInitials = (nom: string, prenom: string) => {
return `${prenom.charAt(0)}${nom.charAt(0)}`.toUpperCase();
};
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-7xl w-full max-h-[95vh] 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">Nouveau trajet</h2>
<p className="text-sm text-gray-500 mt-1">Créez un nouveau trajet pour un adhérent</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 */}
<form id="trajet-form" onSubmit={handleSubmit} className="flex-1 overflow-hidden flex">
{/* Colonne gauche - Formulaire */}
<div className="flex-1 overflow-y-auto px-8 py-8 border-r border-gray-200">
<div className="space-y-6">
{/* Sélection adhérent */}
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Adhérent <span className="text-red-500">*</span>
</label>
<div className="relative" ref={adherentDropdownRef}>
<input
type="text"
placeholder="Rechercher un adhérent..."
value={searchAdherent}
onChange={(e) => {
setSearchAdherent(e.target.value);
setShowAdherentDropdown(true);
}}
onFocus={() => setShowAdherentDropdown(true)}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
{showAdherentDropdown && filteredAdherents.length > 0 && (
<div className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
{filteredAdherents.map((adherent) => (
<button
key={adherent.id}
type="button"
onClick={() => handleSelectAdherent(adherent)}
className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-b-0"
>
<div className="w-10 h-10 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold text-sm">
{getInitials(adherent.nom, adherent.prenom)}
</div>
<div>
<div className="text-sm font-medium text-gray-900">
{adherent.prenom} {adherent.nom}
</div>
<div className="text-xs text-gray-500">{adherent.email}</div>
</div>
</button>
))}
</div>
)}
</div>
{formData.adherentId && (
<div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold text-sm">
{getInitials(formData.adherentNom, formData.adherentPrenom)}
</div>
<div className="flex-1">
<div className="text-sm font-medium text-gray-900">
{formData.adherentPrenom} {formData.adherentNom}
</div>
<div className="text-xs text-gray-500">{formData.adherentTelephone}</div>
<div className="text-xs text-gray-500 mt-1">{formData.adherentAdresse}</div>
</div>
</div>
</div>
)}
</div>
{/* Sélection chauffeur */}
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Chauffeur
</label>
<div className="relative" ref={chauffeurDropdownRef}>
<input
type="text"
placeholder="Rechercher un chauffeur..."
value={searchChauffeur}
onChange={(e) => {
setSearchChauffeur(e.target.value);
setShowChauffeurDropdown(true);
}}
onFocus={() => setShowChauffeurDropdown(true)}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
{showChauffeurDropdown && filteredChauffeurs.length > 0 && (
<div className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
{filteredChauffeurs.map((chauffeur) => (
<button
key={chauffeur.id}
type="button"
onClick={() => handleSelectChauffeur(chauffeur)}
className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-b-0"
>
<div className="w-10 h-10 rounded-full bg-lblue flex items-center justify-center text-white font-semibold text-sm">
{getInitials(chauffeur.nom, chauffeur.prenom)}
</div>
<div>
<div className="text-sm font-medium text-gray-900">
{chauffeur.prenom} {chauffeur.nom}
</div>
<div className="text-xs text-gray-500">{chauffeur.email}</div>
</div>
</button>
))}
</div>
)}
</div>
{formData.chauffeurId && (
<div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-lblue flex items-center justify-center text-white font-semibold text-sm">
{getInitials(formData.chauffeurNom, formData.chauffeurPrenom)}
</div>
<div className="flex-1">
<div className="text-sm font-medium text-gray-900">
{formData.chauffeurPrenom} {formData.chauffeurNom}
</div>
<div className="text-xs text-gray-500">{formData.chauffeurTelephone}</div>
</div>
</div>
</div>
)}
</div>
{/* Date et heure */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Date <span className="text-red-500">*</span>
</label>
<input
type="date"
required
value={formData.date}
onChange={(e) => setFormData({ ...formData, date: e.target.value })}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
</div>
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Heure <span className="text-red-500">*</span>
</label>
<input
type="time"
required
value={formData.heure}
onChange={(e) => setFormData({ ...formData, heure: e.target.value })}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
/>
</div>
</div>
{/* Adresse de départ */}
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Adresse de départ <span className="text-red-500">*</span>
</label>
<AddressAutocomplete
value={formData.adresseDepart}
onChange={(address) => setFormData({ ...formData, adresseDepart: address })}
placeholder="Rechercher une adresse de départ..."
required
/>
</div>
{/* Adresse d'arrivée */}
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Adresse d'arrivée <span className="text-red-500">*</span>
</label>
<AddressAutocomplete
value={formData.adresseArrivee}
onChange={(address) => setFormData({ ...formData, adresseArrivee: address })}
placeholder="Rechercher une adresse d'arrivée..."
required
/>
</div>
{/* Commentaire */}
<div>
<label className="block text-sm font-semibold text-gray-900 mb-2">
Commentaire
</label>
<textarea
value={formData.commentaire}
onChange={(e) => setFormData({ ...formData, commentaire: e.target.value })}
placeholder="Commentaire optionnel..."
rows={4}
className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent resize-none"
/>
</div>
</div>
</div>
{/* Colonne droite - Carte */}
<div className="w-[700px] bg-gradient-to-br from-gray-50 to-gray-100 border-l border-gray-200 p-6 flex flex-col">
<h3 className="text-xl font-semibold text-gray-900 mb-6">Aperçu du trajet</h3>
<div className="flex-1 min-h-[600px] rounded-xl overflow-hidden shadow-lg">
<TrajetMap
adresseDepart={formData.adresseDepart}
adresseArrivee={formData.adresseArrivee}
adherentNom={formData.adherentId ? `${formData.adherentPrenom} ${formData.adherentNom}` : undefined}
/>
</div>
{/* Informations supplémentaires */}
{(formData.date || formData.heure || formData.chauffeurId || formData.commentaire) && (
<div className="mt-4 bg-white rounded-lg p-4 border border-gray-200 space-y-3">
{formData.date && (
<div className="flex items-center gap-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="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 text-gray-900">
{new Date(formData.date).toLocaleDateString('fr-FR', {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
})}
</span>
</div>
)}
{formData.heure && (
<div className="flex items-center gap-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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span className="text-sm text-gray-900">{formData.heure}</span>
</div>
)}
{formData.chauffeurId && (
<div className="flex items-center gap-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 text-gray-900">
{formData.chauffeurPrenom} {formData.chauffeurNom}
</span>
</div>
)}
{formData.commentaire && (
<div className="pt-3 border-t border-gray-200">
<div className="text-xs font-semibold text-gray-500 uppercase mb-1">Commentaire</div>
<p className="text-sm text-gray-700">{formData.commentaire}</p>
</div>
)}
</div>
)}
</div>
</form>
{/* 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}
className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"
>
Annuler
</button>
<button
type="submit"
form="trajet-form"
disabled={loading || !formData.adherentId || !formData.date || !formData.adresseDepart || !formData.adresseArrivee}
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>
Création...
</>
) : (
'Créer le trajet'
)}
</button>
</div>
</div>
</div>
</div>
);
}

429
components/TrajetMap.tsx Normal file
View File

@@ -0,0 +1,429 @@
'use client';
import { useEffect, useState, useRef } from 'react';
import dynamic from 'next/dynamic';
import L from 'leaflet';
// Fix pour les icônes Leaflet avec Next.js
if (typeof window !== 'undefined') {
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});
}
// Import dynamique pour éviter les problèmes SSR avec Leaflet
const MapContainer = dynamic(() => import('react-leaflet').then((mod) => mod.MapContainer), { ssr: false });
const TileLayer = dynamic(() => import('react-leaflet').then((mod) => mod.TileLayer), { ssr: false });
const Marker = dynamic(() => import('react-leaflet').then((mod) => mod.Marker), { ssr: false });
const Popup = dynamic(() => import('react-leaflet').then((mod) => mod.Popup), { ssr: false });
const Polyline = dynamic(() => import('react-leaflet').then((mod) => mod.Polyline), { ssr: false });
interface TrajetMapProps {
adresseDepart: string;
adresseArrivee: string;
adherentNom?: string;
}
interface Coordinates {
lat: number;
lng: number;
}
interface RouteInfo {
distance: number; // en mètres
duration: number; // en secondes
}
export default function TrajetMap({ adresseDepart, adresseArrivee, adherentNom }: TrajetMapProps) {
const [departCoords, setDepartCoords] = useState<Coordinates | null>(null);
const [arriveeCoords, setArriveeCoords] = useState<Coordinates | null>(null);
const [routeInfo, setRouteInfo] = useState<RouteInfo | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Cache simple pour éviter de regéocoder les mêmes adresses
const geocodeCacheRef = useRef<Map<string, Coordinates>>(new Map());
useEffect(() => {
// Réinitialiser les coordonnées quand les adresses changent
setDepartCoords(null);
setArriveeCoords(null);
setRouteInfo(null);
setError(null);
if (adresseDepart && adresseArrivee && adresseDepart.length >= 5 && adresseArrivee.length >= 5) {
// Délai réduit pour une réponse plus rapide
const timeoutId = setTimeout(() => {
geocodeAddresses();
}, 400);
return () => clearTimeout(timeoutId);
}
}, [adresseDepart, adresseArrivee]);
const geocodeAddresses = async () => {
if (!adresseDepart || !adresseArrivee) {
return;
}
// Vérifier que les adresses ont au moins 5 caractères
if (adresseDepart.length < 5 || adresseArrivee.length < 5) {
return;
}
setLoading(true);
setError(null);
try {
// Géocoder les deux adresses en parallèle pour plus de rapidité
// (l'API Nominatim permet généralement 1 req/sec, mais on peut essayer)
const [departResult, arriveeResult] = await Promise.all([
geocodeAddress(adresseDepart).catch(() => null),
// Petit délai pour la deuxième requête pour respecter les limites
new Promise(resolve => setTimeout(resolve, 1000)).then(() =>
geocodeAddress(adresseArrivee).catch(() => null)
),
]);
if (departResult && arriveeResult) {
setDepartCoords(departResult);
setArriveeCoords(arriveeResult);
// Calculer la distance et le temps estimé
const info = calculateRouteInfo(departResult, arriveeResult);
setRouteInfo(info);
} else if (!departResult) {
setError(`Impossible de trouver l'adresse de départ: "${adresseDepart}"`);
} else {
setError(`Impossible de trouver l'adresse d'arrivée: "${adresseArrivee}"`);
}
} catch (err) {
console.error('Erreur lors du géocodage:', err);
setError('Erreur lors du chargement de la carte. Veuillez réessayer.');
} finally {
setLoading(false);
}
};
const geocodeAddress = async (address: string): Promise<Coordinates | null> => {
if (!address || address.length < 5) {
return null;
}
try {
// Nettoyer l'adresse pour améliorer les résultats
const cleanAddress = address.trim().toLowerCase();
// Vérifier le cache
if (geocodeCacheRef.current.has(cleanAddress)) {
return geocodeCacheRef.current.get(cleanAddress)!;
}
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address.trim())}&limit=1&addressdetails=1&countrycodes=fr`,
{
headers: {
'User-Agent': 'MAD Platform',
'Accept-Language': 'fr-FR,fr;q=0.9',
'Referer': window.location.origin,
},
}
);
if (response.ok) {
const data = await response.json();
if (data && data.length > 0 && data[0].lat && data[0].lon) {
const lat = parseFloat(data[0].lat);
const lng = parseFloat(data[0].lon);
// Vérifier que les coordonnées sont valides
if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
const coords = { lat, lng };
// Mettre en cache (limiter à 50 entrées pour éviter la surconsommation mémoire)
if (geocodeCacheRef.current.size < 50) {
geocodeCacheRef.current.set(cleanAddress, coords);
}
return coords;
}
}
} else {
console.warn('Réponse non OK de Nominatim:', response.status);
}
return null;
} catch (error) {
console.error('Erreur de géocodage:', error);
return null;
}
};
const calculateRouteInfo = (depart: Coordinates, arrivee: Coordinates): RouteInfo => {
// Calcul de la distance à vol d'oiseau (formule de Haversine)
const R = 6371e3; // Rayon de la Terre en mètres
const φ1 = (depart.lat * Math.PI) / 180;
const φ2 = (arrivee.lat * Math.PI) / 180;
const Δφ = ((arrivee.lat - depart.lat) * Math.PI) / 180;
const Δλ = ((arrivee.lng - depart.lng) * Math.PI) / 180;
const a =
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c; // Distance en mètres
// Estimation du temps : vitesse moyenne de 50 km/h en ville
// On multiplie la distance par 1.3 pour tenir compte des détours
const distanceWithDetour = distance * 1.3;
const vitesseMoyenne = 50; // km/h
const duration = (distanceWithDetour / 1000 / vitesseMoyenne) * 3600; // en secondes
return { distance: distanceWithDetour, duration };
};
const formatDistance = (meters: number): string => {
if (meters < 1000) {
return `${Math.round(meters)} m`;
}
return `${(meters / 1000).toFixed(1)} km`;
};
const formatDuration = (seconds: number): string => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (hours > 0) {
return `${hours}h${minutes > 0 ? minutes : ''}`;
}
return `${minutes} min`;
};
if (!adresseDepart || !adresseArrivee) {
return (
<div className="h-full flex items-center justify-center text-gray-400">
<div className="text-center">
<svg className="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
</svg>
<p className="text-sm">Remplissez les adresses pour voir la carte</p>
</div>
</div>
);
}
if (loading) {
return (
<div className="h-full flex items-center justify-center bg-white rounded-xl">
<div className="text-center">
<svg className="animate-spin h-12 w-12 text-lblue mx-auto mb-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>
<p className="text-sm font-medium text-gray-700 mb-1">Chargement de la carte...</p>
<p className="text-xs text-gray-500">Géocodage des adresses en cours</p>
</div>
</div>
);
}
if (error) {
return (
<div className="h-full flex items-center justify-center text-gray-400 bg-white rounded-xl p-8">
<div className="text-center max-w-md">
<svg className="w-20 h-20 mx-auto mb-4 opacity-50 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>
<p className="text-sm font-medium text-gray-700 mb-2">{error}</p>
<p className="text-xs text-gray-500 mb-4">Vérifiez que les adresses sont correctes et complètes</p>
<button
onClick={geocodeAddresses}
className="px-4 py-2 text-xs font-medium text-white bg-lblue rounded-lg hover:bg-dblue transition-colors"
>
Réessayer
</button>
</div>
</div>
);
}
if (!departCoords || !arriveeCoords) {
return (
<div className="h-full flex items-center justify-center text-gray-400">
<div className="text-center">
<svg className="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
</svg>
<p className="text-sm">Chargement de la carte...</p>
</div>
</div>
);
}
// Calculer le centre et le zoom optimal pour afficher les deux points
const centerLat = departCoords && arriveeCoords ? (departCoords.lat + arriveeCoords.lat) / 2 : 48.8566;
const centerLng = departCoords && arriveeCoords ? (departCoords.lng + arriveeCoords.lng) / 2 : 2.3522;
// Calculer le zoom optimal pour voir les deux points
let optimalZoom = 12;
if (departCoords && arriveeCoords) {
const latDiff = Math.abs(departCoords.lat - arriveeCoords.lat);
const lngDiff = Math.abs(departCoords.lng - arriveeCoords.lng);
const maxDiff = Math.max(latDiff, lngDiff);
if (maxDiff > 0.5) optimalZoom = 7;
else if (maxDiff > 0.2) optimalZoom = 8;
else if (maxDiff > 0.1) optimalZoom = 9;
else if (maxDiff > 0.05) optimalZoom = 10;
else if (maxDiff > 0.02) optimalZoom = 11;
else optimalZoom = 12;
}
if (typeof window === 'undefined') {
return null;
}
return (
<div className="h-full flex flex-col min-h-[500px]">
{/* Informations du trajet */}
{routeInfo && (
<div className="bg-white rounded-lg border border-gray-200 p-4 mb-4 shadow-sm">
<div className="grid grid-cols-2 gap-6">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-lgreen/10 flex items-center justify-center">
<svg className="w-5 h-5 text-lgreen" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</div>
<div>
<div className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Distance</div>
<div className="text-xl font-semibold text-gray-900">{formatDistance(routeInfo.distance)}</div>
</div>
</div>
<div className="flex items-center gap-3 border-l border-gray-200 pl-6">
<div className="w-10 h-10 rounded-lg bg-lblue/10 flex items-center justify-center">
<svg className="w-5 h-5 text-lblue" 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>
</div>
<div>
<div className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-1">Temps estimé</div>
<div className="text-xl font-semibold text-gray-900">{formatDuration(routeInfo.duration)}</div>
</div>
</div>
</div>
</div>
)}
{/* Carte */}
<div className="flex-1 rounded-xl overflow-hidden border-2 border-gray-300 shadow-2xl" style={{ minHeight: '500px' }}>
<MapContainer
center={[centerLat, centerLng]}
zoom={optimalZoom}
style={{ height: '100%', width: '100%', zIndex: 0 }}
zoomControl={true}
scrollWheelZoom={true}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[departCoords.lat, departCoords.lng]}
icon={L.divIcon({
className: 'custom-marker-depart',
html: `
<div style="
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
width: 40px;
height: 40px;
border-radius: 50% 50% 50% 0;
transform: rotate(-45deg);
border: 4px solid white;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
display: flex;
align-items: center;
justify-content: center;
">
<div style="
transform: rotate(45deg);
color: white;
font-weight: bold;
font-size: 18px;
">A</div>
</div>
`,
iconSize: [40, 40],
iconAnchor: [20, 40],
popupAnchor: [0, -40],
})}
>
<Popup className="custom-popup">
<div className="text-sm p-2">
<div className="font-bold text-lgreen mb-1 flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-lgreen"></div>
Départ
</div>
<div className="text-gray-700 font-medium">{adresseDepart}</div>
{adherentNom && <div className="text-gray-500 mt-1 text-xs">{adherentNom}</div>}
</div>
</Popup>
</Marker>
<Marker
position={[arriveeCoords.lat, arriveeCoords.lng]}
icon={L.divIcon({
className: 'custom-marker-arrivee',
html: `
<div style="
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
width: 40px;
height: 40px;
border-radius: 50% 50% 50% 0;
transform: rotate(-45deg);
border: 4px solid white;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
display: flex;
align-items: center;
justify-content: center;
">
<div style="
transform: rotate(45deg);
color: white;
font-weight: bold;
font-size: 18px;
">B</div>
</div>
`,
iconSize: [40, 40],
iconAnchor: [20, 40],
popupAnchor: [0, -40],
})}
>
<Popup className="custom-popup">
<div className="text-sm p-2">
<div className="font-bold text-lblue mb-1 flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-lblue"></div>
Arrivée
</div>
<div className="text-gray-700 font-medium">{adresseArrivee}</div>
</div>
</Popup>
</Marker>
<Polyline
positions={[
[departCoords.lat, departCoords.lng],
[arriveeCoords.lat, arriveeCoords.lng],
]}
pathOptions={{
color: '#6B46C1',
weight: 5,
opacity: 0.8,
dashArray: '10, 10',
}}
/>
</MapContainer>
</div>
</div>
);
}