import { useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ChevronLeft, ChevronRight, Plus, RefreshCw, Calendar as CalendarIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import CalendarGrid from "@/components/CalendarGrid"; import QuickCreateMenu from "@/components/modals/QuickCreateMenu"; import OrderDetailModal from "@/components/modals/OrderDetailModal"; import CreateOrderModal from "@/components/modals/CreateOrderModal"; import CreateDeliveryModal from "@/components/modals/CreateDeliveryModal"; import StatsPanel from "@/components/StatsPanel"; import { useAuthUnified } from "@/hooks/useAuthUnified"; import { useStore } from "@/components/Layout"; import { apiRequest } from "@/lib/queryClient"; import { useToast } from "@/hooks/use-toast"; import { format, startOfMonth, endOfMonth } from "date-fns"; import { fr } from "date-fns/locale"; import { hasPermission } from "@/lib/permissions"; export default function Calendar() { const { user } = useAuthUnified(); const { selectedStoreId } = useStore(); const queryClient = useQueryClient(); const { toast } = useToast(); const [currentDate, setCurrentDate] = useState(new Date()); // Current date const [selectedDate, setSelectedDate] = useState(null); const [showQuickCreate, setShowQuickCreate] = useState(false); const [showOrderDetail, setShowOrderDetail] = useState(false); const [showCreateOrder, setShowCreateOrder] = useState(false); const [showCreateDelivery, setShowCreateDelivery] = useState(false); const [selectedItem, setSelectedItem] = useState(null); const monthStart = startOfMonth(currentDate); const monthEnd = endOfMonth(currentDate); // Fetch orders and deliveries for the current month with store filtering const { data: orders = [], isLoading: loadingOrders } = useQuery({ queryKey: ['/api/orders', selectedStoreId, { startDate: format(monthStart, 'yyyy-MM-dd'), endDate: format(monthEnd, 'yyyy-MM-dd') }], queryFn: async () => { const params = new URLSearchParams({ startDate: format(monthStart, 'yyyy-MM-dd'), endDate: format(monthEnd, 'yyyy-MM-dd') }); if (selectedStoreId && user?.role === 'admin') { params.append('storeId', selectedStoreId.toString()); } const url = `/api/orders?${params.toString()}`; console.log('📅 Calendar fetching orders:', { url, selectedStoreId, userRole: user?.role, params: params.toString() }); const response = await fetch(url, { credentials: 'include' }); if (!response.ok) { throw new Error('Failed to fetch orders'); } const data = await response.json(); console.log('📅 Calendar orders received:', Array.isArray(data) ? data.length : 'NOT_ARRAY', 'items'); // Protection contre les données invalides en production if (!Array.isArray(data)) { console.warn('⚠️ Orders data is not an array, returning empty array'); return []; } return data; }, }); const { data: deliveries = [], isLoading: loadingDeliveries } = useQuery({ queryKey: ['/api/deliveries', selectedStoreId, { startDate: format(monthStart, 'yyyy-MM-dd'), endDate: format(monthEnd, 'yyyy-MM-dd') }], queryFn: async () => { const params = new URLSearchParams({ startDate: format(monthStart, 'yyyy-MM-dd'), endDate: format(monthEnd, 'yyyy-MM-dd') }); if (selectedStoreId && user?.role === 'admin') { params.append('storeId', selectedStoreId.toString()); } const url = `/api/deliveries?${params.toString()}`; console.log('📅 Calendar fetching deliveries:', { url, selectedStoreId, userRole: user?.role, params: params.toString() }); const response = await fetch(url, { credentials: 'include' }); if (!response.ok) { throw new Error('Failed to fetch deliveries'); } const data = await response.json(); console.log('📅 Calendar deliveries received:', Array.isArray(data) ? data.length : 'NOT_ARRAY', 'items'); // Protection contre les données invalides en production if (!Array.isArray(data)) { console.warn('⚠️ Deliveries data is not an array, returning empty array'); return []; } return data; }, }); // Fetch publicities for the current year const { data: publicities = [], isLoading: loadingPublicities } = useQuery({ queryKey: ['/api/publicities', currentDate.getFullYear(), selectedStoreId], queryFn: async () => { const params = new URLSearchParams(); params.append('year', currentDate.getFullYear().toString()); if (selectedStoreId && user?.role === 'admin') { params.append('storeId', selectedStoreId.toString()); } const url = `/api/publicities?${params.toString()}`; console.log('📅 Calendar fetching publicities:', { url, selectedStoreId, userRole: user?.role, year: currentDate.getFullYear() }); const response = await fetch(url, { credentials: 'include' }); if (!response.ok) { throw new Error('Failed to fetch publicities'); } const data = await response.json(); console.log('📅 Calendar publicities received:', Array.isArray(data) ? data.length : 'NOT_ARRAY', 'items'); return Array.isArray(data) ? data : []; }, }); const navigateMonth = (direction: 'prev' | 'next') => { const newDate = new Date(currentDate); if (direction === 'prev') { newDate.setMonth(newDate.getMonth() - 1); } else { newDate.setMonth(newDate.getMonth() + 1); } setCurrentDate(newDate); }; const handleDateClick = (date: Date) => { setSelectedDate(date); setShowQuickCreate(true); }; const handleItemClick = (item: any, type: 'order' | 'delivery') => { // Rafraîchir les données avant d'ouvrir le modal pour s'assurer d'avoir les liaisons à jour queryClient.invalidateQueries({ queryKey: ['/api/orders'] }); queryClient.invalidateQueries({ queryKey: ['/api/orders', selectedStoreId] }); queryClient.invalidateQueries({ queryKey: ['/api/deliveries'] }); queryClient.invalidateQueries({ queryKey: ['/api/deliveries', selectedStoreId] }); setSelectedItem({ ...item, type }); setShowOrderDetail(true); }; const handleCreateOrder = () => { setShowQuickCreate(false); setShowCreateOrder(true); }; const handleCreateDelivery = () => { setShowQuickCreate(false); setShowCreateDelivery(true); }; const isLoading = loadingOrders || loadingDeliveries || loadingPublicities; return (
{/* Header */}

Calendrier des Commandes & Livraisons

{format(currentDate, 'MMMM yyyy', { locale: fr })}

{/* Legend */}
Commandes
Livraisons
Livré
{/* Calendar Navigation */}

{format(currentDate, 'MMMM yyyy', { locale: fr })}

{(hasPermission(user?.role || '', 'orders', 'create') || hasPermission(user?.role || '', 'deliveries', 'create')) && ( )}
{/* Calendar Grid */}
{isLoading ? (
) : ( )}
{/* Modals */} {showQuickCreate && ( setShowQuickCreate(false)} onCreateOrder={handleCreateOrder} onCreateDelivery={handleCreateDelivery} /> )} {showOrderDetail && selectedItem && ( setShowOrderDetail(false)} item={selectedItem} /> )} {showCreateOrder && ( setShowCreateOrder(false)} selectedDate={selectedDate} /> )} {showCreateDelivery && ( setShowCreateDelivery(false)} selectedDate={selectedDate} /> )} {/* Stats Panel */}
); }