Initial commit

This commit is contained in:
LogiFlow committed 2025-08-11 14:38:44 +00:00
commit e3fb29ab1d
163 files changed
+8140

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import RouterProduction from "@/components/RouterProduction";
import ErrorBoundary from "@/components/ErrorBoundary";
function App() {
return (
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<Toaster />
<RouterProduction />
</TooltipProvider>
</QueryClientProvider>
</ErrorBoundary>
);
}
export default App;
+97
View File
@@ -0,0 +1,97 @@
import { Info, ExternalLink, Lock, Mail } from "lucide-react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export default function AuthInfo() {
// En production (pas sur Replit), toujours utiliser l'auth locale
const isProduction = window.location.hostname !== 'localhost' && !window.location.hostname.includes('replit');
const USE_LOCAL_AUTH = import.meta.env.VITE_USE_LOCAL_AUTH === 'true' || isProduction;
if (USE_LOCAL_AUTH) {
return (
<Card className="border-green-200 bg-green-50">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-green-900">
<Lock className="w-5 h-5" />
Authentification locale activée
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-3 text-sm text-green-800">
<div>
<Badge variant="outline" className="mb-2">Étape 1</Badge>
<p>L'utilisateur recevra ses identifiants par email ou communication sécurisée</p>
</div>
<div>
<Badge variant="outline" className="mb-2">Étape 2</Badge>
<p>Il se connecte avec son email et mot de passe sur l'application</p>
</div>
<div>
<Badge variant="outline" className="mb-2">Étape 3</Badge>
<p>Le système applique automatiquement ses permissions configurées</p>
</div>
</div>
<div className="pt-3 border-t border-green-200">
<p className="text-sm text-green-700 font-medium mb-2">
Sécurité :
</p>
<div className="flex items-center gap-2 text-sm text-green-700">
<Mail className="w-4 h-4" />
<span>Le mot de passe initial sera communiqué de manière sécurisée à l'utilisateur</span>
</div>
</div>
</CardContent>
</Card>
);
}
return (
<Card className="border-blue-200 bg-blue-50">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-blue-900">
<Info className="w-5 h-5" />
Système d'authentification Replit
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-3 text-sm text-blue-800">
<div>
<Badge variant="outline" className="mb-2">Étape 1</Badge>
<p>L'utilisateur doit posséder un compte Replit avec l'email spécifié</p>
</div>
<div>
<Badge variant="outline" className="mb-2">Étape 2</Badge>
<p>Il accède à l'application et clique sur "Se connecter"</p>
</div>
<div>
<Badge variant="outline" className="mb-2">Étape 3</Badge>
<p>Le système reconnaît automatiquement l'email et applique les permissions configurées</p>
</div>
</div>
<div className="pt-3 border-t border-blue-200">
<p className="text-sm text-blue-700 font-medium mb-2">
Si l'utilisateur n'a pas de compte Replit :
</p>
<div className="flex items-center gap-2 text-sm text-blue-700">
<ExternalLink className="w-4 h-4" />
<span>Il peut en créer un gratuitement sur</span>
<a
href="https://replit.com"
target="_blank"
rel="noopener noreferrer"
className="underline hover:text-blue-900"
>
replit.com
</a>
</div>
</div>
</CardContent>
</Card>
);
}
+252
View File
@@ -0,0 +1,252 @@
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isSameMonth, isToday } from "date-fns";
import { fr } from "date-fns/locale";
import { safeDate } from "@/lib/dateUtils";
import { Plus, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { OrderWithRelations, DeliveryWithRelations } from "@shared/schema";
interface CalendarGridProps {
currentDate: Date;
orders: OrderWithRelations[];
deliveries: DeliveryWithRelations[];
onDateClick: (date: Date) => void;
onItemClick: (item: any, type: 'order' | 'delivery') => void;
}
export default function CalendarGrid({
currentDate,
orders,
deliveries,
onDateClick,
onItemClick,
}: CalendarGridProps) {
const monthStart = startOfMonth(currentDate);
const monthEnd = endOfMonth(currentDate);
// Get all days in the month
const monthDays = eachDayOfInterval({
start: monthStart,
end: monthEnd,
});
// Pad the calendar to start on Monday
const firstDayOfWeek = monthStart.getDay();
const startPadding = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
const paddedDays = [];
// Add padding days from previous month
for (let i = startPadding; i > 0; i--) {
const paddingDate = new Date(monthStart);
paddingDate.setDate(paddingDate.getDate() - i);
paddedDays.push(paddingDate);
}
// Add current month days
paddedDays.push(...monthDays);
// Add padding days from next month to complete the grid
const remainingCells = 42 - paddedDays.length; // 6 weeks * 7 days
for (let i = 1; i <= remainingCells; i++) {
const paddingDate = new Date(monthEnd);
paddingDate.setDate(paddingDate.getDate() + i);
paddedDays.push(paddingDate);
}
const weekDays = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
const getItemsForDate = (date: Date) => {
// Debug: Log des commandes reçues (seulement une fois)
if (orders.length > 0 && date.getDate() === 1) {
console.log('📅 CalendarGrid Debug - Orders received:', orders.length);
console.log('📅 First order structure:', orders[0]);
console.log('📅 All orders dates:', orders.map(o => ({ id: o.id, plannedDate: o.plannedDate, supplier: o.supplier?.name })));
}
// Debug: Log des livraisons reçues (seulement une fois)
if (deliveries.length > 0 && date.getDate() === 1) {
console.log('🚛 CalendarGrid Debug - Deliveries received:', deliveries.length);
console.log('🚛 First delivery structure:', deliveries[0]);
console.log('🚛 All deliveries dates:', deliveries.map(d => ({ id: d.id, scheduledDate: d.scheduledDate, supplier: d.supplier?.name })));
}
const dayOrders = orders.filter(order => {
// Protection contre undefined/null
if (!order || !order.supplier) {
console.warn('📅 Invalid order found:', order);
return false;
}
// Essayer plusieurs champs de date possibles
const orderDate = safeDate(order.plannedDate || order.orderDate || order.createdAt);
const matches = orderDate && isSameDay(orderDate, date);
if (matches) {
console.log('📅 Order matches date:', {
orderId: order.id,
supplier: order.supplier?.name,
plannedDate: order.plannedDate,
matchingDate: format(date, 'yyyy-MM-dd')
});
}
return matches;
});
const dayDeliveries = deliveries.filter(delivery => {
// Protection contre undefined/null
if (!delivery || !delivery.supplier) {
console.warn('🚛 Invalid delivery found:', delivery);
return false;
}
// Essayer plusieurs champs de date possibles
const deliveryDate = safeDate(delivery.scheduledDate || delivery.deliveryDate || delivery.createdAt);
const matches = deliveryDate && isSameDay(deliveryDate, date);
if (matches) {
console.log('🚛 Delivery matches date:', {
deliveryId: delivery.id,
supplier: delivery.supplier?.name,
scheduledDate: delivery.scheduledDate,
matchingDate: format(date, 'yyyy-MM-dd')
});
}
return matches;
});
return { orders: dayOrders, deliveries: dayDeliveries };
};
const formatQuantity = (quantity: number, unit: string) => {
return `${quantity}${unit === 'palettes' ? 'P' : 'C'}`;
};
return (
<div className="bg-white shadow-sm border border-gray-200 overflow-hidden">
{/* Calendar Header */}
<div className="grid grid-cols-7 bg-gray-50 border-b border-gray-200">
{weekDays.map(day => (
<div key={day} className="p-4 text-center text-sm font-medium text-gray-700">
{day}
</div>
))}
</div>
{/* Calendar Days */}
<div className="grid grid-cols-7">
{paddedDays.map((date, index) => {
const isCurrentMonth = isSameMonth(date, currentDate);
const isTodayDate = isToday(date);
const { orders: dayOrders, deliveries: dayDeliveries } = getItemsForDate(date);
return (
<div
key={index}
className={`h-32 border-r border-b border-gray-100 relative group cursor-pointer transition-colors ${
isTodayDate
? "bg-blue-50 hover:bg-blue-100 ring-1 ring-blue-200"
: isCurrentMonth
? "bg-white hover:bg-gray-50"
: "bg-gray-50"
}`}
onClick={() => onDateClick(date)}
>
<div className="p-2">
<span className={`text-sm font-medium ${
isTodayDate
? "text-blue-700 font-semibold"
: isCurrentMonth ? "text-gray-900" : "text-gray-400"
}`}>
{format(date, 'd')}
</span>
{/* Orders and Deliveries */}
<div className="mt-1 space-y-1">
{dayOrders.map((order) => {
// Vérifier si la commande a une livraison liée (peu importe le statut)
const hasLinkedDelivery = order.deliveries && order.deliveries.length > 0;
const colorClass = order.status === 'delivered'
? 'bg-delivered text-white'
: order.status === 'planned'
? 'bg-orange-500 text-white border-2 border-orange-300'
: 'bg-primary text-white';
return (
<div
key={`order-${order.id}`}
className={`text-xs px-2 py-1 flex items-center justify-between cursor-pointer ${colorClass}`}
onClick={(e) => {
e.stopPropagation();
onItemClick(order, 'order');
}}
>
<span className="truncate">
{order.supplier.name}
</span>
<div className="flex items-center ml-1 flex-shrink-0">
{order.status === 'planned' && (
<span className="w-2 h-2 bg-yellow-300 mr-1" title="Commande planifiée (liée à une livraison)" />
)}
{order.status === 'delivered' && (
<Check className="w-3 h-3" />
)}
</div>
</div>
);
})}
{dayDeliveries.map((delivery) => (
<div
key={`delivery-${delivery.id}`}
className={`text-xs px-2 py-1 flex items-center justify-between cursor-pointer ${
delivery.status === 'delivered'
? 'bg-delivered text-white'
: delivery.status === 'pending'
? 'bg-yellow-500 text-white border-2 border-yellow-300'
: 'bg-secondary text-white'
}`}
onClick={(e) => {
e.stopPropagation();
onItemClick(delivery, 'delivery');
}}
>
<span className="truncate">
{delivery.supplier.name} - {formatQuantity(delivery.quantity, delivery.unit)}
</span>
<div className="flex items-center ml-1 flex-shrink-0">
{delivery.status === 'pending' && (
<span className="w-2 h-2 bg-orange-300 mr-1" title="En attente de validation" />
)}
{delivery.status === 'delivered' && (
<Check className="w-3 h-3" />
)}
</div>
</div>
))}
</div>
</div>
{/* Quick Create Button */}
{isCurrentMonth && (
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
size="sm"
className="w-6 h-6 bg-accent text-white rounded-full p-0 hover:bg-orange-600"
onClick={(e) => {
e.stopPropagation();
onDateClick(date);
}}
>
<Plus className="w-3 h-3" />
</Button>
</div>
)}
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,62 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
interface ConfirmationModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
title: string;
description: string;
confirmText?: string;
cancelText?: string;
isLoading?: boolean;
variant?: "default" | "destructive";
}
export function ConfirmationModal({
open,
onOpenChange,
onConfirm,
title,
description,
confirmText = "Confirmer",
cancelText = "Annuler",
isLoading = false,
variant = "default",
}: ConfirmationModalProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
{cancelText}
</Button>
<Button
type="button"
variant={variant}
onClick={onConfirm}
disabled={isLoading}
>
{isLoading ? "Chargement..." : confirmText}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,261 @@
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { safeFormat } from "@/lib/dateUtils";
import { Phone, Package, User, Store, Calendar, CreditCard, Tag } from "lucide-react";
import type { CustomerOrderWithRelations } from "@shared/schema";
interface CustomerOrderDetailsProps {
order: CustomerOrderWithRelations;
}
export function CustomerOrderDetails({ order }: CustomerOrderDetailsProps) {
const getStatusColor = (status: string) => {
switch (status) {
case "En attente de Commande":
return "bg-yellow-50 text-yellow-700 border border-yellow-200";
case "Commande en Cours":
return "bg-blue-50 text-blue-700 border border-blue-200";
case "Disponible":
return "bg-green-50 text-green-700 border border-green-200";
case "Retiré":
return "bg-gray-50 text-gray-700 border border-gray-200";
case "Annulé":
return "bg-red-50 text-red-700 border border-red-200";
default:
return "bg-gray-50 text-gray-700 border border-gray-200";
}
};
// Générer le code-barres simple (représentation textuelle)
const renderBarcode = (gencode: string) => {
return (
<div className="font-mono text-center border-2 border-dashed p-4 bg-gray-50">
<div className="text-2xl tracking-widest font-bold mb-2">
{gencode.split('').map((char, index) => (
<span key={index} className="inline-block border-l-2 border-black h-8 w-1 mr-1"></span>
))}
</div>
<div className="text-sm">{gencode}</div>
</div>
);
};
return (
<div className="space-y-4">
{/* En-tête avec statut */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium">Commande #{order.id}</h3>
<p className="text-sm text-muted-foreground">
Créée le {safeFormat(order.createdAt, 'dd MMMM yyyy à HH:mm')}
</p>
</div>
<Badge className={`${getStatusColor(order.status)} rounded-none`}>
{order.status}
</Badge>
</div>
<Separator />
{/* Informations client */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<User className="h-4 w-4" />
Informations Client
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-2">
<div className="flex items-center gap-2">
<span className="font-medium">Nom:</span>
<span>{order.customerName}</span>
</div>
<div className="flex items-center gap-2">
<Phone className="h-4 w-4" />
<span className="font-medium">Téléphone:</span>
<span>{order.customerPhone}</span>
</div>
{order.customerNotified && order.status === 'Disponible' && (
<div className="flex items-center gap-2 text-green-600">
<Phone className="h-4 w-4" />
<span className="text-sm">Client notifié de la disponibilité</span>
</div>
)}
</CardContent>
</Card>
{/* Informations produit */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<Package className="h-4 w-4" />
Informations Produit
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-3">
<div>
<span className="font-medium">Désignation:</span>
<p className="mt-1 text-sm bg-gray-50 p-2 rounded">
{order.productDesignation}
</p>
</div>
{order.productReference && (
<div className="flex items-center gap-2">
<span className="font-medium">Référence:</span>
<code className="bg-gray-100 px-2 py-1 rounded text-sm">
{order.productReference}
</code>
</div>
)}
<div className="flex items-center gap-2">
<span className="font-medium">Quantité:</span>
<Badge variant="secondary" className="font-mono">
{order.quantity || 1}
</Badge>
</div>
{order.gencode && (
<div>
<span className="font-medium">Code à barres:</span>
<div className="mt-2">
<div className="font-mono text-center border border-dashed p-2 bg-gray-50 rounded">
<div className="text-sm text-gray-600 mb-1 text-center">
Code-barres EAN13 scannable
</div>
<div className="border bg-white p-2 text-center">
<svg width="200" height="40" viewBox="0 0 200 40" className="mx-auto">
<rect width="200" height="40" fill="white"/>
<g stroke="black" strokeWidth="1">
<line x1="10" y1="5" x2="10" y2="35"/>
<line x1="15" y1="5" x2="15" y2="35"/>
<line x1="18" y1="5" x2="18" y2="35"/>
<line x1="25" y1="5" x2="25" y2="35"/>
<line x1="30" y1="5" x2="30" y2="35"/>
<line x1="35" y1="5" x2="35" y2="35"/>
<line x1="40" y1="5" x2="40" y2="35"/>
<line x1="45" y1="5" x2="45" y2="35"/>
<line x1="50" y1="5" x2="50" y2="35"/>
<line x1="60" y1="5" x2="60" y2="35"/>
<line x1="65" y1="5" x2="65" y2="35"/>
<line x1="70" y1="5" x2="70" y2="35"/>
<line x1="75" y1="5" x2="75" y2="35"/>
<line x1="80" y1="5" x2="80" y2="35"/>
<line x1="85" y1="5" x2="85" y2="35"/>
<line x1="90" y1="5" x2="90" y2="35"/>
<line x1="95" y1="5" x2="95" y2="35"/>
<line x1="100" y1="5" x2="100" y2="35"/>
<line x1="110" y1="5" x2="110" y2="35"/>
<line x1="115" y1="5" x2="115" y2="35"/>
<line x1="120" y1="5" x2="120" y2="35"/>
<line x1="125" y1="5" x2="125" y2="35"/>
<line x1="130" y1="5" x2="130" y2="35"/>
<line x1="135" y1="5" x2="135" y2="35"/>
<line x1="140" y1="5" x2="140" y2="35"/>
<line x1="145" y1="5" x2="145" y2="35"/>
<line x1="150" y1="5" x2="150" y2="35"/>
<line x1="160" y1="5" x2="160" y2="35"/>
<line x1="165" y1="5" x2="165" y2="35"/>
<line x1="170" y1="5" x2="170" y2="35"/>
<line x1="175" y1="5" x2="175" y2="35"/>
<line x1="180" y1="5" x2="180" y2="35"/>
<line x1="185" y1="5" x2="185" y2="35"/>
<line x1="190" y1="5" x2="190" y2="35"/>
</g>
</svg>
</div>
<div className="text-xs">{order.gencode}</div>
</div>
</div>
</div>
)}
{order.isPromotionalPrice && (
<div className="flex items-center gap-2 text-orange-600">
<Tag className="h-4 w-4" />
<span className="text-sm font-medium">Prix publicité appliqué</span>
</div>
)}
</CardContent>
</Card>
{/* Informations commande */}
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<User className="h-4 w-4" />
Informations Commande
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-2">
<div className="flex items-center gap-2">
<span className="font-medium">Prise par:</span>
<span>{order.orderTaker}</span>
</div>
{order.deposit && parseFloat(order.deposit) > 0 && (
<div className="flex items-center gap-2">
<span className="font-medium">💰 Acompte:</span>
<Badge variant="outline" className="text-orange-600 border-orange-300 font-mono">
{parseFloat(order.deposit).toFixed(2)}€
</Badge>
</div>
)}
<div className="flex items-center gap-2">
<Store className="h-4 w-4" />
<span className="font-medium">Magasin:</span>
<Badge
style={{
backgroundColor: order.group.color + "20",
color: order.group.color,
border: `1px solid ${order.group.color}30`
}}
>
{order.group.name}
</Badge>
</div>
<div className="flex items-center gap-2">
<span className="font-medium">Fournisseur:</span>
<span>{order.supplier.name}</span>
</div>
<div className="flex items-center gap-2">
<Calendar className="h-4 w-4" />
<span className="font-medium">Date de création:</span>
<span>{safeFormat(order.createdAt, 'dd/MM/yyyy à HH:mm')}</span>
</div>
</CardContent>
</Card>
{/* Actions disponibles selon le statut */}
{order.status === 'Disponible' && (
<div className="bg-green-50 border border-green-200 rounded-lg p-3">
<h4 className="font-medium text-green-800 mb-2">Actions disponibles</h4>
<div className="space-y-1 text-sm text-green-700">
<p>• Étiquette imprimable disponible</p>
<p>• Notification client possible</p>
<p>• Prêt pour retrait en magasin</p>
</div>
</div>
)}
{(order.status === 'Retiré' || order.status === 'Annulé') && (
<div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
<h4 className="font-medium text-gray-600 mb-2">Commande terminée</h4>
<p className="text-sm text-gray-600">
{order.status === 'Retiré'
? 'Cette commande a été retirée par le client.'
: 'Cette commande a été annulée.'
}
</p>
</div>
)}
</div>
);
}
+379
View File
@@ -0,0 +1,379 @@
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useQuery } from "@tanstack/react-query";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { insertCustomerOrderSchema, type CustomerOrderWithRelations, type Group, type Supplier } from "@shared/schema";
import { useStore } from "@/components/Layout";
const customerOrderFormSchema = insertCustomerOrderSchema.extend({
deposit: z.string().optional(),
gencode: z.string().min(1, "Le gencode est obligatoire"),
customerName: z.string().min(1, "Le nom du client est obligatoire"),
quantity: z.union([z.string(), z.number()]).transform(val => typeof val === 'string' ? parseInt(val) || 1 : val),
supplierId: z.union([z.string(), z.number()]).transform(val => typeof val === 'string' ? parseInt(val) : val),
groupId: z.union([z.string(), z.number()]).transform(val => typeof val === 'string' ? parseInt(val) : val).optional(),
createdBy: z.string().optional(), // Will be set automatically
});
type CustomerOrderFormData = z.infer<typeof customerOrderFormSchema>;
interface CustomerOrderFormProps {
order?: CustomerOrderWithRelations;
onSubmit: (data: CustomerOrderFormData) => void;
onCancel: () => void;
isLoading?: boolean;
}
const STATUS_OPTIONS = [
"En attente de Commande",
"Commande en Cours",
"Disponible",
"Retiré",
"Annulé"
];
export function CustomerOrderForm({
order,
onSubmit,
onCancel,
isLoading = false
}: CustomerOrderFormProps) {
const { user } = useAuthUnified();
const { selectedStoreId } = useStore();
// Fetch groups for store selection
const { data: groups = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
// Fetch suppliers for supplier selection
const { data: suppliers = [] } = useQuery<Supplier[]>({
queryKey: ['/api/suppliers'],
});
const form = useForm<CustomerOrderFormData>({
resolver: zodResolver(customerOrderFormSchema),
defaultValues: {
orderTaker: order?.orderTaker || user?.name || "",
customerName: order?.customerName || "",
customerPhone: order?.customerPhone || "",
productDesignation: order?.productDesignation || "",
productReference: order?.productReference || "",
gencode: order?.gencode || "",
quantity: order?.quantity || 1,
supplierId: order?.supplierId || undefined,
status: "En attente de Commande", // Statut fixe
deposit: order?.deposit ? order.deposit.toString() : "0",
isPromotionalPrice: order?.isPromotionalPrice || false,
customerNotified: order?.customerNotified || false,
groupId: order?.groupId || (user?.role === 'admin' && selectedStoreId ? selectedStoreId : user?.userGroups?.[0]?.groupId) || undefined, // Respect admin store selection
},
});
const handleSubmit = (data: CustomerOrderFormData) => {
console.log("Form submission data:", data);
console.log("Form errors:", form.formState.errors);
console.log("Form is valid:", form.formState.isValid);
// Validate required fields
if (!data.customerName || data.customerName.trim() === '') {
console.error("Customer name is required but empty");
return;
}
// Ensure groupId is set - prioritize selectedStoreId for admins
let groupId = data.groupId;
if (!groupId) {
if (user?.role === 'admin' && selectedStoreId) {
// Admin has selected a specific store - use it
groupId = selectedStoreId;
console.log("🏪 Using admin selected store:", selectedStoreId);
} else if (user?.userGroups?.[0]?.groupId) {
groupId = user.userGroups[0].groupId;
} else if (user?.role === 'admin' && groups.length > 0) {
groupId = groups[0].id; // Admin in "tous magasins" mode - use first group
}
}
if (!groupId) {
console.error("No groupId available - user groups:", user?.userGroups, "available groups:", groups);
return;
}
// Prepare data with proper types
const submitData = {
...data,
customerName: data.customerName.trim(), // Clean the customer name
deposit: data.deposit || "0.00", // Keep as string for decimal field
groupId: typeof groupId === 'number' ? groupId : parseInt(groupId.toString()),
createdBy: user?.id || '', // Add the current user ID
};
console.log("Processed submit data:", submitData);
onSubmit(submitData);
};
// Get available groups for the user
const availableGroups = user?.role === 'admin'
? groups
: user?.userGroups?.map(ug => ug.group) || [];
// Auto-select group for users respecting admin store selection
const currentGroupId = form.getValues('groupId');
if (!currentGroupId) {
if (user?.role === 'admin' && selectedStoreId) {
// Admin has selected a specific store - use it
form.setValue('groupId', selectedStoreId);
console.log("🏪 Auto-selecting admin store:", selectedStoreId);
} else if (user?.userGroups?.[0]?.groupId) {
// User has assigned groups - use first one
form.setValue('groupId', user.userGroups[0].groupId);
} else if (user?.role === 'admin' && groups.length > 0) {
// Admin with no specific groups - use first available group
form.setValue('groupId', groups[0].id);
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
<div className="space-y-4">
{/* Informations de commande */}
<h3 className="text-lg font-medium">Informations de commande</h3>
<FormField
control={form.control}
name="orderTaker"
render={({ field }) => (
<FormItem>
<FormLabel>Qui a pris la commande</FormLabel>
<FormControl>
<Input placeholder="Nom de l'employé" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerName"
render={({ field }) => (
<FormItem>
<FormLabel>Nom du client</FormLabel>
<FormControl>
<Input placeholder="Nom complet du client" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="customerPhone"
render={({ field }) => (
<FormItem>
<FormLabel>N° de téléphone</FormLabel>
<FormControl>
<Input placeholder="0X XX XX XX XX" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="supplierId"
render={({ field }) => (
<FormItem>
<FormLabel>Fournisseur</FormLabel>
<Select onValueChange={field.onChange} value={field.value?.toString()}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner un fournisseur" />
</SelectTrigger>
</FormControl>
<SelectContent>
{suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.id.toString()}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{/* Magasin automatiquement sélectionné - pas de champ visible */}
<h3 className="text-lg font-medium">Informations produit</h3>
<FormField
control={form.control}
name="productDesignation"
render={({ field }) => (
<FormItem>
<FormLabel>Désignation du produit</FormLabel>
<FormControl>
<Textarea
placeholder="Description détaillée du produit"
rows={3}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="productReference"
render={({ field }) => (
<FormItem>
<FormLabel>Référence (optionnel)</FormLabel>
<FormControl>
<Input placeholder="REF-123456" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="gencode"
render={({ field }) => (
<FormItem>
<FormLabel>Gencode (obligatoire)</FormLabel>
<FormControl>
<Input placeholder="Code à barres" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="quantity"
render={({ field }) => (
<FormItem>
<FormLabel>Quantité</FormLabel>
<FormControl>
<Input
type="number"
min="1"
placeholder="1"
{...field}
value={field.value?.toString() || "1"}
onChange={(e) => field.onChange(parseInt(e.target.value) || 1)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Statut fixé automatiquement à "En attente de Commande" */}
{/* Options supplémentaires */}
<h3 className="text-lg font-medium">Options supplémentaires</h3>
<FormField
control={form.control}
name="deposit"
render={({ field }) => (
<FormItem>
<FormLabel>Acompte (€)</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
min="0"
placeholder="0.00"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="isPromotionalPrice"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel>
Prix publicité
</FormLabel>
<p className="text-sm text-muted-foreground">
Cocher si le produit était en promotion
</p>
</div>
</FormItem>
)}
/>
{/* Case "Client appelé" cachée pour nouvelles commandes */}
</div>
{/* Actions */}
<div className="flex justify-end space-x-3 pt-4">
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={isLoading}
>
Annuler
</Button>
<Button
type="submit"
disabled={isLoading}
onClick={(e) => {
console.log("Submit button clicked");
console.log("Form state:", form.formState);
console.log("Form values:", form.getValues());
console.log("Form validation errors:", form.formState.errors);
console.log("Current user context:", user?.userGroups, "available groups:", groups);
}}
>
{isLoading ? "Enregistrement..." : order ? "Modifier" : "Créer"}
</Button>
</div>
</form>
</Form>
);
}
+73
View File
@@ -0,0 +1,73 @@
import React from 'react';
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}
interface ErrorBoundaryProps {
children: React.ReactNode;
fallback?: React.ComponentType<{ error: Error | null; retry: () => void }>;
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
retry = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
const FallbackComponent = this.props.fallback;
return <FallbackComponent error={this.state.error} retry={this.retry} />;
}
return (
<div className="min-h-screen w-full flex items-center justify-center bg-surface">
<div className="text-center max-w-md p-6">
<div className="text-red-500 text-6xl mb-4">⚠️</div>
<h2 className="text-xl font-semibold text-gray-800 mb-2">
Une erreur s'est produite
</h2>
<p className="text-gray-600 mb-4">
L'application a rencontré un problème inattendu.
</p>
<button
onClick={this.retry}
className="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90 transition-colors"
>
Réessayer
</button>
{this.state.error && (
<details className="mt-4 text-left">
<summary className="cursor-pointer text-sm text-gray-500">
Détails de l'erreur
</summary>
<pre className="mt-2 text-xs text-red-600 bg-red-50 p-2 rounded overflow-auto">
{this.state.error.toString()}
</pre>
</details>
)}
</div>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
+125
View File
@@ -0,0 +1,125 @@
import { ReactNode, useState, createContext, useContext } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { LogOut, Store } from "lucide-react";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import Sidebar from "./Sidebar";
import type { Group } from "@shared/schema";
interface StoreContextType {
selectedStoreId: number | null;
setSelectedStoreId: (storeId: number | null) => void;
stores: Group[];
}
const StoreContext = createContext<StoreContextType | undefined>(undefined);
export const useStore = () => {
const context = useContext(StoreContext);
if (!context) {
throw new Error("useStore must be used within a StoreProvider");
}
return context;
};
interface LayoutProps {
children: ReactNode;
}
export default function Layout({ children }: LayoutProps) {
const { user } = useAuthUnified();
const queryClient = useQueryClient();
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(() => {
// Restaurer le selectedStoreId depuis localStorage si disponible
const saved = localStorage.getItem('selectedStoreId');
const restoredId = saved ? parseInt(saved) : null;
console.log('🏪 Layout - Restoring selectedStoreId from localStorage:', { saved, restoredId });
return restoredId;
});
const { data: stores = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
enabled: !!user,
});
const handleLogout = () => {
window.location.href = "/api/logout";
};
return (
<StoreContext.Provider value={{ selectedStoreId, setSelectedStoreId, stores }}>
<div className="flex h-screen overflow-hidden bg-gray-50">
<Sidebar />
<main className="flex-1 flex flex-col overflow-hidden">
{/* Header with store selector for admin */}
<header className="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-6">
<div className="flex items-center gap-4">
<h1 className="text-lg font-medium text-gray-800">LogiFlow</h1>
</div>
{/* Store selector for admin - moved to top right */}
{user?.role === 'admin' && stores.length > 0 && (
<div className="flex items-center gap-2">
<Store className="h-4 w-4 text-gray-500" />
<Select
value={selectedStoreId?.toString() || "all"}
onValueChange={(value) => {
console.log('🏪 Store selector changed:', { value, parsed: value === "all" ? null : parseInt(value) });
const newStoreId = value === "all" ? null : parseInt(value);
// Invalider toutes les variantes de queryKey pour changement magasin
console.log('🧹 Invalidating data caches for store change');
queryClient.invalidateQueries({ predicate: (query) => {
const key = query.queryKey;
return key[0]?.toString().includes('/api/orders') ||
key[0]?.toString().includes('/api/deliveries') ||
key[0]?.toString().includes('/api/stats/monthly');
}});
// Sauvegarder dans localStorage et mettre à jour l'état
if (newStoreId) {
localStorage.setItem('selectedStoreId', newStoreId.toString());
console.log('💾 Store saved to localStorage:', newStoreId);
} else {
localStorage.removeItem('selectedStoreId');
console.log('🗑️ Store removed from localStorage');
}
setSelectedStoreId(newStoreId);
}}
>
<SelectTrigger className="w-64 border border-gray-300">
<SelectValue placeholder="Sélectionner un magasin" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-gray-400"></div>
<span>Tous les magasins</span>
</div>
</SelectItem>
{stores.map((store) => (
<SelectItem key={store.id} value={store.id.toString()}>
<div className="flex items-center gap-2">
<div
className="w-3 h-3"
style={{ backgroundColor: store.color }}
/>
<span>{store.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</header>
<div className="flex-1 overflow-auto bg-gray-50 p-6">
{children}
</div>
</main>
</div>
</StoreContext.Provider>
);
}
+330
View File
@@ -0,0 +1,330 @@
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { safeDate } from "@/lib/dateUtils";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";
import type { PublicityWithRelations, Group } from "@shared/schema";
const publicityFormSchema = z.object({
pubNumber: z.string().min(1, "Le numéro PUB est requis"),
designation: z.string().min(1, "La désignation est requise"),
startDate: z.date({ required_error: "La date de début est requise" }),
endDate: z.date({ required_error: "La date de fin est requise" }),
year: z.number().min(2020).max(2030),
participatingGroups: z.array(z.number()), // Suppression de .min(1) pour permettre 0 magasin
}).refine((data) => data.endDate >= data.startDate, {
message: "La date de fin doit être postérieure à la date de début",
path: ["endDate"]
});
type PublicityFormData = z.infer<typeof publicityFormSchema>;
interface PublicityFormProps {
publicity?: PublicityWithRelations | null;
groups: Group[];
onSuccess: () => void;
selectedYear?: number; // Année sélectionnée depuis le filtre principal
}
export default function PublicityForm({ publicity, groups, onSuccess, selectedYear }: PublicityFormProps) {
const [startCalendarOpen, setStartCalendarOpen] = useState(false);
const [endCalendarOpen, setEndCalendarOpen] = useState(false);
const { toast } = useToast();
const queryClient = useQueryClient();
const form = useForm<PublicityFormData>({
resolver: zodResolver(publicityFormSchema),
defaultValues: {
pubNumber: publicity?.pubNumber || "",
designation: publicity?.designation || "",
startDate: publicity?.startDate ? safeDate(publicity.startDate) : undefined,
endDate: publicity?.endDate ? safeDate(publicity.endDate) : undefined,
year: publicity?.year || selectedYear || 2025, // Utilise l'année sélectionnée ou 2025 par défaut
participatingGroups: publicity?.participations?.map(p => p.groupId) || [],
},
});
// L'année est définie manuellement par l'utilisateur, pas automatiquement par la date
const createMutation = useMutation({
mutationFn: async (data: PublicityFormData) => {
const response = await fetch('/api/publicities', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pubNumber: data.pubNumber,
designation: data.designation,
startDate: format(data.startDate, 'yyyy-MM-dd'),
endDate: format(data.endDate, 'yyyy-MM-dd'),
year: data.year,
participatingGroups: data.participatingGroups,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Erreur lors de la création');
}
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/publicities'] });
toast({ description: "Publicité créée avec succès" });
onSuccess();
},
onError: (error: Error) => {
toast({
variant: "destructive",
description: error.message || "Erreur lors de la création"
});
}
});
const updateMutation = useMutation({
mutationFn: async (data: PublicityFormData) => {
const response = await fetch(`/api/publicities/${publicity!.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pubNumber: data.pubNumber,
designation: data.designation,
startDate: format(data.startDate, 'yyyy-MM-dd'),
endDate: format(data.endDate, 'yyyy-MM-dd'),
year: data.year,
participatingGroups: data.participatingGroups,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'Erreur lors de la modification');
}
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/publicities'] });
toast({ description: "Publicité modifiée avec succès" });
onSuccess();
},
onError: (error: Error) => {
toast({
variant: "destructive",
description: error.message || "Erreur lors de la modification"
});
}
});
const onSubmit = (data: PublicityFormData) => {
if (publicity) {
updateMutation.mutate(data);
} else {
createMutation.mutate(data);
}
};
const isLoading = createMutation.isPending || updateMutation.isPending;
return (
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="pubNumber">N° PUB</Label>
<Input
id="pubNumber"
{...form.register("pubNumber")}
placeholder="Ex: PUB2025-001"
/>
{form.formState.errors.pubNumber && (
<p className="text-sm text-red-600">{form.formState.errors.pubNumber.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="year">Année</Label>
<Input
id="year"
type="number"
{...form.register("year", { valueAsNumber: true })}
min="2020"
max="2030"
/>
{form.formState.errors.year && (
<p className="text-sm text-red-600">{form.formState.errors.year.message}</p>
)}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="designation">Désignation</Label>
<Textarea
id="designation"
{...form.register("designation")}
placeholder="Description de la campagne publicitaire"
rows={3}
/>
{form.formState.errors.designation && (
<p className="text-sm text-red-600">{form.formState.errors.designation.message}</p>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Date de début</Label>
<Popover open={startCalendarOpen} onOpenChange={setStartCalendarOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"w-full justify-start text-left font-normal",
!form.watch("startDate") && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.watch("startDate") ? (
format(form.watch("startDate"), "dd/MM/yyyy", { locale: fr })
) : (
<span>Sélectionner une date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={form.watch("startDate")}
onSelect={(date) => {
form.setValue("startDate", date!);
setStartCalendarOpen(false);
}}
disabled={(date) => date < new Date("1900-01-01")}
initialFocus
locale={fr}
/>
</PopoverContent>
</Popover>
{form.formState.errors.startDate && (
<p className="text-sm text-red-600">{form.formState.errors.startDate.message}</p>
)}
</div>
<div className="space-y-2">
<Label>Date de fin</Label>
<Popover open={endCalendarOpen} onOpenChange={setEndCalendarOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className={cn(
"w-full justify-start text-left font-normal",
!form.watch("endDate") && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{form.watch("endDate") ? (
format(form.watch("endDate"), "dd/MM/yyyy", { locale: fr })
) : (
<span>Sélectionner une date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={form.watch("endDate")}
onSelect={(date) => {
form.setValue("endDate", date!);
setEndCalendarOpen(false);
}}
disabled={(date) => {
const startDate = form.watch("startDate");
return date < new Date("1900-01-01") || (startDate && date < startDate);
}}
initialFocus
locale={fr}
/>
</PopoverContent>
</Popover>
{form.formState.errors.endDate && (
<p className="text-sm text-red-600">{form.formState.errors.endDate.message}</p>
)}
</div>
</div>
<div className="space-y-3">
<Label>Magasins participants</Label>
<p className="text-sm text-gray-600">Sélectionnez les magasins qui participent à cette publicité (optionnel)</p>
<Card>
<CardContent className="pt-4">
<div className="grid grid-cols-2 gap-3">
{groups.map((group) => (
<div key={group.id} className="flex items-center space-x-2">
<Checkbox
id={`group-${group.id}`}
checked={form.watch("participatingGroups").includes(group.id)}
onCheckedChange={(checked) => {
const current = form.watch("participatingGroups");
if (checked) {
form.setValue("participatingGroups", [...current, group.id]);
} else {
form.setValue("participatingGroups", current.filter(id => id !== group.id));
}
}}
/>
<Label
htmlFor={`group-${group.id}`}
className="flex items-center space-x-2 cursor-pointer"
>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: group.color }}
/>
<span>{group.name}</span>
</Label>
</div>
))}
</div>
{form.watch("participatingGroups").length === 0 && (
<div className="mt-3 p-3 bg-red-50 rounded-lg text-center">
<p className="text-sm text-red-700">Aucun magasin sélectionné</p>
</div>
)}
</CardContent>
</Card>
{form.formState.errors.participatingGroups && (
<p className="text-sm text-red-600">{form.formState.errors.participatingGroups.message}</p>
)}
</div>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
onClick={onSuccess}
disabled={isLoading}
>
Annuler
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? (
<div className="flex items-center gap-2">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
{publicity ? 'Modification...' : 'Création...'}
</div>
) : (
publicity ? 'Modifier' : 'Créer'
)}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,88 @@
import { Switch, Route } from "wouter";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import NotFound from "@/pages/not-found";
import AuthPage from "@/pages/AuthPage";
import Dashboard from "@/pages/Dashboard";
import Calendar from "@/pages/Calendar";
import Orders from "@/pages/Orders";
import Deliveries from "@/pages/Deliveries";
import Suppliers from "@/pages/Suppliers";
import Groups from "@/pages/Groups";
import Users from "@/pages/Users";
import BLReconciliation from "@/pages/BLReconciliation";
import Publicities from "@/pages/Publicities";
import NocoDBConfig from "@/pages/NocoDBConfig";
import CustomerOrders from "@/pages/CustomerOrders";
import RoleManagement from "@/pages/RoleManagement";
import DlcPage from "@/pages/DlcPage";
import Tasks from "@/pages/Tasks";
import TasksSimplified from "@/pages/TasksSimplified";
import Layout from "@/components/Layout";
function RouterProduction() {
const { isAuthenticated, isLoading, user, environment, error } = useAuthUnified();
// Debug complet pour la production
console.log('🔍 RouterProduction Debug:', {
environment,
isAuthenticated,
isLoading,
hasUser: !!user,
userId: user?.id,
username: user?.username,
error: error?.message
});
// Debug minimal basé sur l'environnement
if (environment === 'production' && error) {
console.error('🚨 Production Auth Error:', error);
}
if (isLoading) {
return (
<div className="min-h-screen w-full flex items-center justify-center bg-surface">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
<p className="text-gray-600">Chargement...</p>
</div>
</div>
);
}
if (!isAuthenticated) {
return (
<Switch>
<Route path="/auth" component={AuthPage} />
<Route path="/" component={AuthPage} />
<Route component={NotFound} />
</Switch>
);
}
return (
<Layout>
<Switch>
<Route path="/calendar" component={Calendar} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/orders" component={Orders} />
<Route path="/deliveries" component={Deliveries} />
<Route path="/suppliers" component={Suppliers} />
<Route path="/groups" component={Groups} />
<Route path="/users" component={Users} />
<Route path="/roles" component={RoleManagement} />
<Route path="/role-management" component={RoleManagement} />
<Route path="/bl-reconciliation" component={BLReconciliation} />
<Route path="/publicities" component={Publicities} />
<Route path="/customer-orders" component={CustomerOrders} />
<Route path="/dlc" component={DlcPage} />
<Route path="/tasks" component={Tasks} />
<Route path="/nocodb-config" component={NocoDBConfig} />
<Route path="/" component={Dashboard} />
<Route component={NotFound} />
</Switch>
</Layout>
);
}
export default RouterProduction;
+343
View File
@@ -0,0 +1,343 @@
import { Link, useLocation } from "wouter";
import { useAuthSimple } from "@/hooks/useAuthSimple";
import { Button } from "@/components/ui/button";
import {
Store,
Calendar,
BarChart3,
Package,
Truck,
Building,
Users,
UserCog,
LogOut,
FileText,
Megaphone,
Shield,
Database,
ShoppingCart,
Clock,
ListTodo
} from "lucide-react";
export default function Sidebar() {
const { user, isLoading, error } = useAuthSimple();
const [location] = useLocation();
// Debug logging pour production
console.log('Sidebar - User:', user);
console.log('Sidebar - isLoading:', isLoading);
console.log('Sidebar - error:', error);
const handleLogout = async () => {
try {
// Force logout via fetch to ensure session is destroyed
await fetch('/api/logout', {
method: 'POST',
credentials: 'include'
});
} catch (error) {
console.error('Logout error:', error);
} finally {
// Force redirect to auth page regardless of API response
window.location.href = "/auth";
}
};
const getInitials = (firstName?: string, lastName?: string) => {
if (!firstName && !lastName) return "U";
return `${firstName?.[0] || ""}${lastName?.[0] || ""}`.toUpperCase();
};
const isActive = (path: string) => {
if (path === "/" && location === "/") return true;
if (path !== "/" && location.startsWith(path)) return true;
return false;
};
const menuItems = [
{
path: "/dashboard",
label: "Tableau de bord",
icon: BarChart3,
roles: ["admin", "manager", "employee"]
},
{
path: "/calendar",
label: "Calendrier",
icon: Calendar,
roles: ["admin", "manager", "employee"]
},
{
path: "/orders",
label: "Commandes",
icon: Package,
roles: ["admin", "manager"]
},
{
path: "/deliveries",
label: "Livraisons",
icon: Truck,
roles: ["admin", "manager"]
},
{
path: "/bl-reconciliation",
label: "Rapprochement",
icon: FileText,
roles: ["admin", "manager"]
},
{
path: "/publicities",
label: "Publicités",
icon: Megaphone,
roles: ["admin", "manager"]
},
{
path: "/customer-orders",
label: "Commandes Client",
icon: ShoppingCart,
roles: ["admin", "manager", "employee"]
},
{
path: "/dlc",
label: "Gestion DLC",
icon: Clock,
roles: ["admin", "manager", "employee"]
},
{
path: "/tasks",
label: "Tâches",
icon: ListTodo,
roles: ["admin", "manager", "employee"]
},
];
const managementItems = [
{
path: "/suppliers",
label: "Fournisseurs",
icon: Building,
roles: ["admin", "manager"]
},
{
path: "/groups",
label: "Magasins",
icon: Users,
roles: ["admin", "manager"]
},
];
const adminItems = [
{
path: "/users",
label: "Utilisateurs",
icon: UserCog,
roles: ["admin"]
},
{
path: "/roles",
label: "Gestion des Rôles",
icon: Shield,
roles: ["admin"]
},
{
path: "/nocodb-config",
label: "Configuration NocoDB",
icon: Database,
roles: ["admin"]
},
];
const hasPermission = (roles: string[]) => {
const hasRole = user?.role && roles.includes(user.role);
// Debug uniquement en développement pour éviter spam console
if (import.meta.env.MODE === 'development') {
console.log('hasPermission check:', { userRole: user?.role, roles, hasRole });
}
return hasRole;
};
// Si l'utilisateur n'est pas encore chargé, afficher un état de chargement
if (isLoading) {
return (
<aside className="w-64 bg-white border-r border-gray-200 flex flex-col shadow-lg">
<div className="h-16 flex items-center justify-center border-b border-gray-200 bg-white">
<div className="flex items-center space-x-3">
<Store className="h-6 w-6 text-blue-600" />
<span className="text-lg font-semibold text-gray-900">LogiFlow</span>
</div>
</div>
<div className="flex-1 flex items-center justify-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
</div>
</aside>
);
}
// Si l'utilisateur n'est pas authentifié, afficher seulement le logo
if (!user) {
return (
<aside className="w-64 bg-white border-r border-gray-200 flex flex-col shadow-lg">
<div className="h-16 flex items-center justify-center border-b border-gray-200 bg-white">
<div className="flex items-center space-x-3">
<Store className="h-6 w-6 text-blue-600" />
<span className="text-lg font-semibold text-gray-900">LogiFlow</span>
</div>
</div>
<div className="flex-1 flex items-center justify-center">
<div className="text-center text-gray-500">
<p>Authentification requise</p>
</div>
</div>
</aside>
);
}
return (
<aside className="w-64 bg-white border-r border-gray-200 flex flex-col shadow-lg">
{/* Logo */}
<div className="h-16 flex items-center justify-center border-b border-gray-200 bg-white">
<div className="flex items-center space-x-3">
<Store className="h-6 w-6 text-blue-600" />
<span className="text-lg font-semibold text-gray-900">LogiFlow</span>
</div>
</div>
{/* Navigation */}
<nav className="flex-1 py-4 px-3">
<div className="space-y-1">
{menuItems.map((item) => {
const hasRolePermission = hasPermission(item.roles);
// console.log(`🔍 Menu item ${item.path} (${item.label}):`, {
// roles: item.roles,
// hasPermission: hasRolePermission,
// userRole: user?.role
// });
if (!hasRolePermission) return null;
const Icon = item.icon;
const active = isActive(item.path);
return (
<Link key={item.path} href={item.path}>
<div
className={`flex items-center px-3 py-2 text-sm font-medium transition-colors hover:bg-gray-100 ${
active
? 'bg-gray-100 text-gray-900 border-r-2 border-gray-700'
: 'text-gray-700'
}`}
onClick={() => console.log(`Navigating to: ${item.path}`)}
>
<Icon className="mr-3 h-4 w-4" />
{item.label}
</div>
</Link>
);
})}
</div>
{/* Management Section */}
{managementItems.some(item => hasPermission(item.roles)) && (
<>
<div className="mt-6 mb-2">
<h3 className="px-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
Gestion
</h3>
</div>
<div className="space-y-1">
{managementItems.map((item) => {
if (!hasPermission(item.roles)) return null;
const Icon = item.icon;
const active = isActive(item.path);
return (
<Link key={item.path} href={item.path}>
<div
className={`flex items-center px-3 py-2 text-sm font-medium transition-colors hover:bg-gray-100 ${
active
? 'bg-gray-100 text-gray-900 border-r-2 border-gray-700'
: 'text-gray-700'
}`}
onClick={() => console.log(`Navigating to management: ${item.path}`)}
>
<Icon className="mr-3 h-4 w-4" />
{item.label}
</div>
</Link>
);
})}
</div>
</>
)}
</nav>
{/* Administration Section */}
{adminItems.some(item => hasPermission(item.roles)) && (
<div className="border-t border-gray-200 py-4 px-3">
<div className="mb-2">
<h3 className="px-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
Administration
</h3>
</div>
<div className="space-y-1">
{adminItems.map((item) => {
if (!hasPermission(item.roles)) return null;
const Icon = item.icon;
const active = isActive(item.path);
return (
<Link key={item.path} href={item.path}>
<div
className={`flex items-center px-3 py-2 text-sm font-medium transition-colors hover:bg-gray-100 ${
active
? 'bg-gray-100 text-gray-900 border-r-2 border-gray-700'
: 'text-gray-700'
}`}
onClick={() => console.log(`Navigating to admin: ${item.path}`)}
>
<Icon className="mr-3 h-4 w-4" />
{item.label}
</div>
</Link>
);
})}
</div>
</div>
)}
{/* User Profile & Logout */}
<div className="border-t border-gray-200 p-4">
<div className="flex items-center space-x-3 mb-3">
<div className="h-8 w-8 bg-gray-100 flex items-center justify-center">
<span className="text-xs font-medium text-gray-700">
{getInitials(user?.firstName, user?.lastName)}
</span>
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900 truncate">
{user?.firstName} {user?.lastName}
</p>
<p className="text-xs text-gray-500 truncate">
{user?.email}
</p>
</div>
</div>
<Button
onClick={handleLogout}
variant="outline"
size="sm"
className="w-full justify-start text-gray-600 hover:text-red-600 hover:border-red-300"
>
<LogOut className="mr-2 h-4 w-4" />
Déconnexion
</Button>
</div>
</aside>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { TrendingUp, Package, Truck, Clock } from "lucide-react";
import { useStore } from "./Layout";
import { useAuthUnified } from "@/hooks/useAuthUnified";
export default function StatsPanel() {
const { selectedStoreId } = useStore();
const { user } = useAuthUnified();
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// Construire l'URL avec les paramètres
const statsUrl = `/api/stats/monthly?year=${year}&month=${month}${selectedStoreId ? `&storeId=${selectedStoreId}` : ''}`;
const { data: stats, isLoading } = useQuery({
queryKey: [statsUrl, selectedStoreId], // Include selectedStoreId in key to force refetch
});
if (isLoading) {
return (
<div className="fixed bottom-6 right-6 bg-white rounded-xl shadow-lg border border-gray-200 p-4 min-w-80">
<div className="animate-pulse">
<div className="h-4 bg-gray-200 rounded w-3/4 mb-4"></div>
<div className="grid grid-cols-2 gap-4">
{[...Array(4)].map((_, i) => (
<div key={i} className="text-center">
<div className="h-8 bg-gray-200 rounded w-16 mx-auto mb-2"></div>
<div className="h-3 bg-gray-200 rounded w-12 mx-auto"></div>
</div>
))}
</div>
</div>
</div>
);
}
return (
<Card className="fixed bottom-6 right-6 min-w-80 shadow-lg border-gray-200">
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center">
<TrendingUp className="w-5 h-5 text-accent mr-2" />
Statistiques du mois
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-primary flex items-center justify-center">
<Package className="w-5 h-5 mr-1" />
{stats?.ordersCount || 0}
</div>
<div className="text-xs text-gray-600">Commandes</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-secondary flex items-center justify-center">
<Truck className="w-5 h-5 mr-1" />
{stats?.deliveriesCount || 0}
</div>
<div className="text-xs text-gray-600">Livraisons</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-accent">
{stats?.totalPalettes || 0}
</div>
<div className="text-xs text-gray-600">Palettes</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-delivered">
{stats?.totalPackages || 0}
</div>
<div className="text-xs text-gray-600">Colis</div>
</div>
</div>
<div className="mt-3 pt-3 border-t border-gray-200 text-center">
<div className="text-sm text-gray-600 flex items-center justify-center">
<Clock className="w-4 h-4 mr-1" />
Délai moyen:
<span className="font-medium text-gray-900 ml-1">
{stats?.averageDeliveryTime?.toFixed(1) || '0'} jours
</span>
</div>
</div>
{stats?.pendingOrdersCount > 0 && (
<div className="mt-2 text-center">
<div className="text-sm text-orange-600">
{stats.pendingOrdersCount} commandes en attente
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,73 @@
import React from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { AlertTriangle } from "lucide-react";
interface ConfirmDeleteModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
description: string;
itemName?: string;
isLoading?: boolean;
}
export default function ConfirmDeleteModal({
isOpen,
onClose,
onConfirm,
title,
description,
itemName,
isLoading = false,
}: ConfirmDeleteModalProps) {
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="delete-modal-description">
<DialogHeader>
<DialogTitle className="flex items-center space-x-2">
<AlertTriangle className="w-5 h-5 text-red-500" />
<span>{title}</span>
</DialogTitle>
</DialogHeader>
<div className="py-4">
<p id="delete-modal-description" className="text-sm text-gray-600">
{description}
</p>
{itemName && (
<div className="mt-3 p-3 bg-red-50 rounded-lg border border-red-200">
<p className="text-sm font-medium text-red-800">
Élément à supprimer : <span className="font-bold">{itemName}</span>
</p>
</div>
)}
<div className="mt-4 p-3 bg-amber-50 rounded-lg border border-amber-200">
<p className="text-xs text-amber-700 font-medium">
⚠️ Cette action est définitive et ne peut pas être annulée.
</p>
</div>
</div>
<DialogFooter className="flex justify-end space-x-2">
<Button
variant="outline"
onClick={onClose}
disabled={isLoading}
>
Annuler
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isLoading}
className="bg-red-600 hover:bg-red-700"
>
{isLoading ? "Suppression..." : "Supprimer définitivement"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,337 @@
import { useState, useEffect } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useStore } from "@/components/Layout";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { format } from "date-fns";
import { safeFormat } from "@/lib/dateUtils";
import type { Group, Supplier, OrderWithRelations } from "@shared/schema";
interface CreateDeliveryModalProps {
isOpen: boolean;
onClose: () => void;
selectedDate: Date | null;
}
export default function CreateDeliveryModal({
isOpen,
onClose,
selectedDate,
}: CreateDeliveryModalProps) {
const { user } = useAuthUnified();
const { selectedStoreId } = useStore();
const { toast } = useToast();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
orderId: "",
supplierId: "",
groupId: "",
scheduledDate: selectedDate ? format(selectedDate, 'yyyy-MM-dd') : "",
quantity: "",
unit: "palettes",
notes: "",
});
const { data: suppliers = [] } = useQuery<Supplier[]>({
queryKey: ['/api/suppliers'],
enabled: user?.role === 'admin' || user?.role === 'manager',
});
const { data: groupsData = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
// Filtrer les groupes selon le magasin sélectionné pour les admins
const groups = Array.isArray(groupsData) ? (
user?.role === 'admin' && selectedStoreId
? groupsData.filter(g => g.id === selectedStoreId)
: groupsData
) : [];
// Filtrer les commandes par fournisseur sélectionné
const { data: allOrders = [] } = useQuery<OrderWithRelations[]>({
queryKey: ['/api/orders'],
});
// Filtrer les commandes par fournisseur sélectionné - montrer toutes les commandes non livrées
const availableOrders = allOrders.filter(order =>
formData.supplierId ? (order.supplierId === parseInt(formData.supplierId) && order.status !== 'delivered') : false
);
// Auto-sélectionner le magasin selon les règles
useEffect(() => {
console.log('🏪 CreateDeliveryModal - Store selection effect:', {
groupsLength: groups.length,
currentFormGroupId: formData.groupId,
selectedStoreId,
userRole: user?.role,
allGroups: groups.map(g => ({ id: g.id, name: g.name })),
filteredGroups: groups.length
});
// Reset le formulaire si le magasin sélectionné change
if (user?.role === 'admin' && selectedStoreId && formData.groupId && formData.groupId !== selectedStoreId.toString()) {
console.log('🔄 Resetting delivery form because store changed:', {
currentGroupId: formData.groupId,
newStoreId: selectedStoreId.toString()
});
setFormData(prev => ({ ...prev, groupId: "", orderId: "" }));
return;
}
if (groups.length > 0 && !formData.groupId) {
let defaultGroupId = "";
if (user?.role === 'admin') {
// Pour l'admin : utiliser le magasin sélectionné dans le header (filtré), sinon le premier de la liste
if (selectedStoreId && groups.find(g => g.id === selectedStoreId)) {
defaultGroupId = selectedStoreId.toString();
} else {
defaultGroupId = groups[0].id.toString();
}
console.log('🏪 Admin delivery store selection:', {
selectedStoreId,
defaultGroupId,
firstGroupId: groups[0].id,
groupsAvailable: groups.map(g => g.name)
});
} else {
// Pour les autres rôles : prendre le premier magasin attribué
// (La logique existante filtre déjà les groupes selon les permissions)
defaultGroupId = groups[0].id.toString();
console.log('🏪 Non-admin delivery store selection:', { defaultGroupId, firstGroupId: groups[0].id });
}
if (defaultGroupId) {
console.log('🏪 Setting default group ID for delivery:', defaultGroupId, 'for group:', groups.find(g => g.id.toString() === defaultGroupId)?.name);
setFormData(prev => ({ ...prev, groupId: defaultGroupId }));
}
}
}, [groups, selectedStoreId, user?.role, formData.groupId]);
// Réinitialiser la commande sélectionnée quand on change de fournisseur
useEffect(() => {
if (formData.supplierId) {
setFormData(prev => ({ ...prev, orderId: "" }));
}
}, [formData.supplierId]);
const createDeliveryMutation = useMutation({
mutationFn: async (data: any) => {
await apiRequest("/api/deliveries", "POST", data);
},
onSuccess: () => {
toast({
title: "Succès",
description: "Livraison créée avec succès",
});
// Invalider toutes les variantes de queryKey pour assurer cohérence
console.log('🚚 Delivery created, clearing cache for consistency');
queryClient.invalidateQueries({ predicate: (query) => {
const key = query.queryKey;
return key[0]?.toString().includes('/api/orders') ||
key[0]?.toString().includes('/api/deliveries') ||
key[0]?.toString().includes('/api/stats/monthly');
}});
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de créer la livraison",
variant: "destructive",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.supplierId || !formData.groupId || !formData.scheduledDate || !formData.quantity) {
toast({
title: "Erreur",
description: "Veuillez remplir tous les champs obligatoires",
variant: "destructive",
});
return;
}
createDeliveryMutation.mutate({
orderId: formData.orderId && formData.orderId !== "none" ? parseInt(formData.orderId) : undefined,
supplierId: parseInt(formData.supplierId),
groupId: parseInt(formData.groupId),
scheduledDate: formData.scheduledDate,
quantity: parseInt(formData.quantity),
unit: formData.unit,
status: "planned",
notes: formData.notes || undefined,
createdBy: user?.id,
});
};
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
};
// Afficher toutes les commandes du fournisseur sélectionné (pas de filtrage supplémentaire)
const finalFilteredOrders = availableOrders;
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="delivery-modal-description">
<DialogHeader>
<DialogTitle>Nouvelle Livraison</DialogTitle>
<p id="delivery-modal-description" className="text-sm text-gray-600 mt-1">
Créer une nouvelle livraison pour un fournisseur
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="supplier">Fournisseur *</Label>
<Select value={formData.supplierId} onValueChange={(value) => handleChange('supplierId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un fournisseur" />
</SelectTrigger>
<SelectContent>
{Array.isArray(suppliers) && suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.id.toString()}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{formData.supplierId && (
<div>
<Label htmlFor="order">Commande liée (optionnel)</Label>
<Select value={formData.orderId} onValueChange={(value) => handleChange('orderId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez une commande de ce fournisseur" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Aucune commande liée</SelectItem>
{Array.isArray(finalFilteredOrders) && finalFilteredOrders.map((order) => (
<SelectItem key={order.id} value={order.id.toString()}>
#{order.id} - {order.supplier.name} - {safeFormat(order.plannedDate, 'dd/MM/yyyy')}
</SelectItem>
))}
{(!Array.isArray(finalFilteredOrders) || finalFilteredOrders.length === 0) && (
<SelectItem value="disabled" disabled>
Aucune commande disponible pour ce fournisseur
</SelectItem>
)}
</SelectContent>
</Select>
</div>
)}
{/* Affichage du magasin sélectionné */}
{formData.groupId && (
<div>
<Label>Magasin/Groupe</Label>
<div className="flex items-center space-x-2 p-3 bg-gray-50 rounded-md border">
{(() => {
const selectedGroup = groups.find(g => g.id.toString() === formData.groupId);
return selectedGroup ? (
<>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: selectedGroup.color }}
/>
<span className="font-medium">{selectedGroup.name}</span>
</>
) : null;
})()}
</div>
</div>
)}
<div>
<Label htmlFor="scheduledDate">Date prévue *</Label>
<Input
id="scheduledDate"
type="date"
value={formData.scheduledDate}
onChange={(e) => handleChange('scheduledDate', e.target.value)}
required
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="quantity">Quantité *</Label>
<Input
id="quantity"
type="number"
min="1"
value={formData.quantity}
onChange={(e) => handleChange('quantity', e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="unit">Unité</Label>
<Select value={formData.unit} onValueChange={(value) => handleChange('unit', value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="palettes">Palettes</SelectItem>
<SelectItem value="colis">Colis</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div>
<Label htmlFor="notes">Commentaires</Label>
<Textarea
id="notes"
value={formData.notes}
onChange={(e) => handleChange('notes', e.target.value)}
placeholder="Commentaires additionnels..."
rows={3}
/>
</div>
<div className="flex items-center space-x-3 pt-4">
<Button type="button" variant="outline" onClick={onClose}>
Annuler
</Button>
<Button
type="submit"
disabled={createDeliveryMutation.isPending}
className="bg-secondary hover:bg-green-700"
>
{createDeliveryMutation.isPending ? "Création..." : "Créer la livraison"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,261 @@
import { useState, useEffect } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useStore } from "@/components/Layout";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { format } from "date-fns";
import type { Group, Supplier } from "@shared/schema";
interface CreateOrderModalProps {
isOpen: boolean;
onClose: () => void;
selectedDate: Date | null;
}
export default function CreateOrderModal({
isOpen,
onClose,
selectedDate,
}: CreateOrderModalProps) {
const { user } = useAuthUnified();
const { selectedStoreId } = useStore();
const { toast } = useToast();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
supplierId: "",
groupId: "",
plannedDate: selectedDate ? format(selectedDate, 'yyyy-MM-dd') : "",
notes: "",
});
const { data: suppliers = [] } = useQuery<Supplier[]>({
queryKey: ['/api/suppliers'],
enabled: user?.role === 'admin' || user?.role === 'manager',
});
const { data: groupsData = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
// Filtrer les groupes selon le magasin sélectionné pour les admins
const groups = Array.isArray(groupsData) ? (
user?.role === 'admin' && selectedStoreId
? groupsData.filter(g => g.id === selectedStoreId)
: groupsData
) : [];
// Auto-sélectionner le magasin selon les règles
useEffect(() => {
console.log('🏪 CreateOrderModal - Store selection effect:', {
groupsLength: groups.length,
currentFormGroupId: formData.groupId,
selectedStoreId,
userRole: user?.role,
allGroups: groups.map(g => ({ id: g.id, name: g.name })),
filteredGroups: groups.length
});
// Reset le formulaire si le magasin sélectionné change
if (user?.role === 'admin' && selectedStoreId && formData.groupId && formData.groupId !== selectedStoreId.toString()) {
console.log('🔄 Resetting form because store changed:', {
currentGroupId: formData.groupId,
newStoreId: selectedStoreId.toString()
});
setFormData(prev => ({ ...prev, groupId: "" }));
return;
}
if (groups.length > 0 && !formData.groupId) {
let defaultGroupId = "";
if (user?.role === 'admin') {
// Pour l'admin : utiliser le magasin sélectionné dans le header (filtré), sinon le premier de la liste
if (selectedStoreId && groups.find(g => g.id === selectedStoreId)) {
defaultGroupId = selectedStoreId.toString();
} else {
defaultGroupId = groups[0].id.toString();
}
console.log('🏪 Admin store selection:', {
selectedStoreId,
defaultGroupId,
firstGroupId: groups[0].id,
groupsAvailable: groups.map(g => g.name)
});
} else {
// Pour les autres rôles : prendre le premier magasin attribué
defaultGroupId = groups[0].id.toString();
console.log('🏪 Non-admin store selection:', { defaultGroupId, firstGroupId: groups[0].id });
}
if (defaultGroupId) {
console.log('🏪 Setting default group ID:', defaultGroupId, 'for group:', groups.find(g => g.id.toString() === defaultGroupId)?.name);
setFormData(prev => ({ ...prev, groupId: defaultGroupId }));
}
}
}, [groups, selectedStoreId, user?.role, formData.groupId]);
const createOrderMutation = useMutation({
mutationFn: async (data: any) => {
console.log('🚀 Creating order with data:', data);
const response = await apiRequest("/api/orders", "POST", data);
console.log('✅ Order created successfully:', response);
return response;
},
onSuccess: () => {
toast({
title: "Succès",
description: "Commande créée avec succès",
});
// Force un nettoyage complet du cache pour éviter incohérences
console.log('🆕 Order created, clearing cache for consistency');
// Invalider toutes les variantes de queryKey pour assurer cohérence
queryClient.invalidateQueries({ predicate: (query) => {
const key = query.queryKey;
return key[0]?.toString().includes('/api/orders') ||
key[0]?.toString().includes('/api/deliveries') ||
key[0]?.toString().includes('/api/stats/monthly');
}});
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de créer la commande",
variant: "destructive",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.supplierId || !formData.groupId || !formData.plannedDate) {
toast({
title: "Erreur",
description: "Veuillez remplir tous les champs obligatoires",
variant: "destructive",
});
return;
}
createOrderMutation.mutate({
supplierId: parseInt(formData.supplierId),
groupId: parseInt(formData.groupId),
plannedDate: formData.plannedDate,
notes: formData.notes || undefined,
});
};
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="order-modal-description">
<DialogHeader>
<DialogTitle>Nouvelle Commande</DialogTitle>
<p id="order-modal-description" className="text-sm text-gray-600 mt-1">
Créer une nouvelle commande pour un fournisseur
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="supplier">Fournisseur *</Label>
<Select value={formData.supplierId} onValueChange={(value) => handleChange('supplierId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un fournisseur" />
</SelectTrigger>
<SelectContent>
{suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.id.toString()}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Affichage du magasin sélectionné */}
{formData.groupId && (
<div>
<Label>Magasin/Groupe</Label>
<div className="flex items-center space-x-2 p-3 bg-gray-50 rounded-md border">
{(() => {
const selectedGroup = groups.find(g => g.id.toString() === formData.groupId);
return selectedGroup ? (
<>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: selectedGroup.color }}
/>
<span className="font-medium">{selectedGroup.name}</span>
</>
) : null;
})()}
</div>
</div>
)}
<div>
<Label htmlFor="plannedDate">Date prévue *</Label>
<Input
id="plannedDate"
type="date"
value={formData.plannedDate}
onChange={(e) => handleChange('plannedDate', e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="notes">Commentaires</Label>
<Textarea
id="notes"
value={formData.notes}
onChange={(e) => handleChange('notes', e.target.value)}
placeholder="Commentaires additionnels..."
rows={3}
/>
</div>
<div className="flex items-center space-x-3 pt-4">
<Button type="button" variant="outline" onClick={onClose}>
Annuler
</Button>
<Button
type="submit"
disabled={createOrderMutation.isPending}
className="bg-primary hover:bg-blue-700"
>
{createOrderMutation.isPending ? "Création..." : "Créer la commande"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,270 @@
import { useState, useEffect } from "react";
import { useQueryClient, useMutation, useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { format } from "date-fns";
import { safeFormat } from "@/lib/dateUtils";
import type { Group, Supplier, DeliveryWithRelations, OrderWithRelations } from "@shared/schema";
interface EditDeliveryModalProps {
isOpen: boolean;
onClose: () => void;
delivery: DeliveryWithRelations | null;
}
export default function EditDeliveryModal({
isOpen,
onClose,
delivery,
}: EditDeliveryModalProps) {
const { user } = useAuthUnified();
const { toast } = useToast();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
supplierId: "",
groupId: "",
orderId: "",
scheduledDate: "",
quantity: "",
unit: "palettes",
notes: "",
});
const { data: suppliers = [] } = useQuery<Supplier[]>({
queryKey: ['/api/suppliers'],
enabled: user?.role === 'admin' || user?.role === 'manager',
});
const { data: groups = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
const { data: allOrders = [] } = useQuery<OrderWithRelations[]>({
queryKey: ['/api/orders'],
});
// Filtrer les commandes par fournisseur sélectionné - montrer toutes les commandes non livrées
const availableOrders = allOrders.filter(order =>
formData.supplierId ? (order.supplierId === parseInt(formData.supplierId) && order.status !== 'delivered') : false
);
// Initialiser le formulaire avec les données de la livraison
useEffect(() => {
if (delivery) {
setFormData({
supplierId: delivery.supplierId.toString(),
groupId: delivery.groupId.toString(),
orderId: delivery.orderId ? delivery.orderId.toString() : "none",
scheduledDate: safeFormat(delivery.scheduledDate, 'yyyy-MM-dd'),
quantity: delivery.quantity.toString(),
unit: delivery.unit,
notes: delivery.notes || "",
});
}
}, [delivery]);
const updateDeliveryMutation = useMutation({
mutationFn: async (data: any) => {
await apiRequest(`/api/deliveries/${delivery?.id}`, "PUT", data);
},
onSuccess: () => {
toast({
title: "Succès",
description: "Livraison modifiée avec succès",
});
// Invalider tous les caches liés aux livraisons
queryClient.invalidateQueries({ queryKey: ['/api/deliveries'] });
queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
queryClient.invalidateQueries({ queryKey: ['/api/stats/monthly'] });
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de modifier la livraison",
variant: "destructive",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.supplierId || !formData.groupId || !formData.scheduledDate || !formData.quantity) {
toast({
title: "Erreur",
description: "Veuillez remplir tous les champs obligatoires",
variant: "destructive",
});
return;
}
updateDeliveryMutation.mutate({
supplierId: parseInt(formData.supplierId),
groupId: parseInt(formData.groupId),
orderId: formData.orderId && formData.orderId !== "none" ? parseInt(formData.orderId) : null,
scheduledDate: formData.scheduledDate,
quantity: parseInt(formData.quantity),
unit: formData.unit,
notes: formData.notes || undefined,
});
};
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
};
if (!delivery) return null;
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="edit-delivery-modal-description">
<DialogHeader>
<DialogTitle>Modifier la Livraison #{delivery.id}</DialogTitle>
<p id="edit-delivery-modal-description" className="text-sm text-gray-600 mt-1">
Modifier les détails de cette livraison
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="supplier">Fournisseur *</Label>
<Select value={formData.supplierId} onValueChange={(value) => handleChange('supplierId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un fournisseur" />
</SelectTrigger>
<SelectContent>
{suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.id.toString()}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="group">Magasin/Groupe *</Label>
<Select value={formData.groupId} onValueChange={(value) => handleChange('groupId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un magasin" />
</SelectTrigger>
<SelectContent>
{groups.map((group) => (
<SelectItem key={group.id} value={group.id.toString()}>
<div className="flex items-center space-x-2">
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: group.color }}
/>
<span>{group.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{availableOrders.length > 0 && (
<div>
<Label htmlFor="order">Commande liée (optionnel)</Label>
<Select value={formData.orderId} onValueChange={(value) => handleChange('orderId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez une commande" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Aucune commande liée</SelectItem>
{availableOrders.map((order) => (
<SelectItem key={order.id} value={order.id.toString()}>
Commande #{order.id} - {order.supplier.name} - {safeFormat(order.plannedDate, 'dd/MM/yyyy')}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div>
<Label htmlFor="scheduledDate">Date prévue *</Label>
<Input
id="scheduledDate"
type="date"
value={formData.scheduledDate}
onChange={(e) => handleChange('scheduledDate', e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="quantity">Quantité *</Label>
<Input
id="quantity"
type="number"
min="1"
value={formData.quantity}
onChange={(e) => handleChange('quantity', e.target.value)}
placeholder="Ex: 10"
/>
</div>
<div>
<Label htmlFor="unit">Unité *</Label>
<Select value={formData.unit} onValueChange={(value) => handleChange('unit', value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="palettes">Palettes</SelectItem>
<SelectItem value="colis">Colis</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div>
<Label htmlFor="notes">Commentaires</Label>
<Textarea
id="notes"
placeholder="Commentaires optionnels..."
value={formData.notes}
onChange={(e) => handleChange('notes', e.target.value)}
rows={3}
/>
</div>
<div className="flex justify-end space-x-2 pt-4">
<Button type="button" variant="outline" onClick={onClose}>
Annuler
</Button>
<Button
type="submit"
disabled={updateDeliveryMutation.isPending}
className="bg-primary hover:bg-blue-700"
>
{updateDeliveryMutation.isPending ? "Modification..." : "Modifier"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,206 @@
import { useState, useEffect } from "react";
import { useQueryClient, useMutation, useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { format } from "date-fns";
import { safeFormat } from "@/lib/dateUtils";
import type { Group, Supplier, OrderWithRelations } from "@shared/schema";
interface EditOrderModalProps {
isOpen: boolean;
onClose: () => void;
order: OrderWithRelations | null;
}
export default function EditOrderModal({
isOpen,
onClose,
order,
}: EditOrderModalProps) {
const { user } = useAuthUnified();
const { toast } = useToast();
const queryClient = useQueryClient();
const [formData, setFormData] = useState({
supplierId: "",
groupId: "",
plannedDate: "",
notes: "",
});
const { data: suppliers = [] } = useQuery<Supplier[]>({
queryKey: ['/api/suppliers'],
enabled: user?.role === 'admin' || user?.role === 'manager',
});
const { data: groups = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
// Initialiser le formulaire avec les données de la commande
useEffect(() => {
if (order) {
setFormData({
supplierId: order.supplierId.toString(),
groupId: order.groupId.toString(),
plannedDate: safeFormat(order.plannedDate, 'yyyy-MM-dd'),
notes: order.notes || "",
});
}
}, [order]);
const updateOrderMutation = useMutation({
mutationFn: async (data: any) => {
await apiRequest("PUT", `/api/orders/${order?.id}`, data);
},
onSuccess: () => {
toast({
title: "Succès",
description: "Commande modifiée avec succès",
});
// Invalider tous les caches liés aux commandes
queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
queryClient.invalidateQueries({ queryKey: ['/api/stats/monthly'] });
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de modifier la commande",
variant: "destructive",
});
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.supplierId || !formData.groupId || !formData.plannedDate) {
toast({
title: "Erreur",
description: "Veuillez remplir tous les champs obligatoires",
variant: "destructive",
});
return;
}
updateOrderMutation.mutate({
supplierId: parseInt(formData.supplierId),
groupId: parseInt(formData.groupId),
plannedDate: formData.plannedDate,
notes: formData.notes || undefined,
});
};
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
};
if (!order) return null;
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="edit-order-modal-description">
<DialogHeader>
<DialogTitle>Modifier la Commande #{order.id}</DialogTitle>
<p id="edit-order-modal-description" className="text-sm text-gray-600 mt-1">
Modifier les détails de cette commande
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="supplier">Fournisseur *</Label>
<Select value={formData.supplierId} onValueChange={(value) => handleChange('supplierId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un fournisseur" />
</SelectTrigger>
<SelectContent>
{Array.isArray(suppliers) && suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.id.toString()}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="group">Magasin/Groupe *</Label>
<Select value={formData.groupId} onValueChange={(value) => handleChange('groupId', value)}>
<SelectTrigger>
<SelectValue placeholder="Sélectionnez un magasin" />
</SelectTrigger>
<SelectContent>
{Array.isArray(groups) && groups.map((group) => (
<SelectItem key={group.id} value={group.id.toString()}>
<div className="flex items-center space-x-2">
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: group.color }}
/>
<span>{group.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="plannedDate">Date prévue *</Label>
<Input
id="plannedDate"
type="date"
value={formData.plannedDate}
onChange={(e) => handleChange('plannedDate', e.target.value)}
/>
</div>
<div>
<Label htmlFor="notes">Commentaires</Label>
<Textarea
id="notes"
placeholder="Commentaires optionnels..."
value={formData.notes}
onChange={(e) => handleChange('notes', e.target.value)}
rows={3}
/>
</div>
<div className="flex justify-end space-x-2 pt-4">
<Button type="button" variant="outline" onClick={onClose}>
Annuler
</Button>
<Button
type="submit"
disabled={updateOrderMutation.isPending}
className="bg-primary hover:bg-blue-700"
>
{updateOrderMutation.isPending ? "Modification..." : "Modifier"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,424 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { safeFormat } from "@/lib/dateUtils";
import EditOrderModal from "./EditOrderModal";
import EditDeliveryModal from "./EditDeliveryModal";
import ValidateDeliveryModal from "./ValidateDeliveryModal";
import { Package, Truck, Edit, Trash2, Check, X } from "lucide-react";
interface OrderDetailModalProps {
isOpen: boolean;
onClose: () => void;
item: any;
}
export default function OrderDetailModal({
isOpen,
onClose,
item,
}: OrderDetailModalProps) {
const { user } = useAuthUnified();
const { toast } = useToast();
const queryClient = useQueryClient();
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const isOrder = item?.type === 'order';
const isDelivery = item?.type === 'delivery';
const validateDeliveryMutation = useMutation({
mutationFn: async (data: { id: number; blNumber: string; blAmount: number }) => {
await apiRequest(`/api/deliveries/${data.id}/validate`, "POST", data);
},
onSuccess: () => {
toast({
title: "Succès",
description: "Livraison validée avec succès",
});
queryClient.invalidateQueries({ queryKey: ['/api/deliveries'] });
queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de valider la livraison",
variant: "destructive",
});
},
});
const deleteMutation = useMutation({
mutationFn: async (id: number) => {
const endpoint = isOrder ? `/api/orders/${id}` : `/api/deliveries/${id}`;
console.log(`🗑️ Deleting ${isOrder ? 'order' : 'delivery'}:`, id);
await apiRequest(endpoint, "DELETE");
},
onSuccess: () => {
console.log(`✅ ${isOrder ? 'Order' : 'Delivery'} deleted successfully, clearing cache...`);
toast({
title: "Succès",
description: `${isOrder ? 'Commande' : 'Livraison'} supprimée avec succès`,
});
// SOLUTION PRODUCTION : Cache clearing radical pour éviter incohérences storeId
console.log('🗑️ Cache cleared, forcing page reload to maintain storeId consistency...');
// SOLUTION HYBRIDE : Invalidation sélective pour éviter perte storeId
console.log('🧹 Using selective invalidation to preserve storeId context...');
// Invalidation ciblée sans clear() pour préserver le contexte
queryClient.invalidateQueries({
predicate: (query) => {
const key = query.queryKey[0]?.toString() || '';
return key.includes('/api/orders') || key.includes('/api/deliveries');
}
});
// Force refetch pour garantir synchronisation immédiate
queryClient.refetchQueries({
predicate: (query) => {
const key = query.queryKey[0]?.toString() || '';
return key.includes('/api/orders') || key.includes('/api/deliveries');
}
});
onClose();
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: `Impossible de supprimer la ${isOrder ? 'commande' : 'livraison'}`,
variant: "destructive",
});
},
});
const [showValidateModal, setShowValidateModal] = useState(false);
const handleValidateDelivery = () => {
setShowValidateModal(true);
};
const handleDelete = () => {
if (item.id) {
deleteMutation.mutate(item.id);
}
};
const handleEdit = () => {
setShowEditModal(true);
};
const canEdit = user?.role === 'admin' || user?.role === 'manager';
const canDelete = user?.role === 'admin' || user?.role === 'manager';
const canValidate = (user?.role === 'admin' || user?.role === 'manager') &&
isDelivery && item.status !== 'delivered';
const getStatusBadge = (status: string) => {
switch (status) {
case 'pending':
return <Badge variant="secondary">En attente</Badge>;
case 'planned':
return <Badge className="bg-blue-100 text-blue-800">Planifié</Badge>;
case 'delivered':
return <Badge className="bg-green-100 text-green-800">Livré</Badge>;
default:
return <Badge variant="outline">{status}</Badge>;
}
};
const formatQuantity = (quantity: number, unit: string) => {
return `${quantity} ${unit === 'palettes' ? 'Palettes' : 'Colis'}`;
};
if (!item) return null;
return (
<>
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-hidden" aria-describedby="order-detail-modal-description">
{/* Header */}
<div className="bg-gradient-to-r from-primary to-blue-600 text-white p-6 -m-6 mb-4">
<DialogHeader>
<div className="flex items-center space-x-3">
<div className="w-10 h-10 bg-white bg-opacity-20 rounded-lg flex items-center justify-center">
{isOrder ? (
<Package className="w-5 h-5 text-white" />
) : (
<Truck className="w-5 h-5 text-white" />
)}
</div>
<div>
<DialogTitle className="text-xl font-bold">
Détails de la {isOrder ? 'Commande' : 'Livraison'}
</DialogTitle>
<p className="text-blue-100">
#{isOrder ? 'CMD' : 'LIV'}-{item.id}
</p>
<p id="order-detail-modal-description" className="sr-only">
Affichage détaillé de {isOrder ? 'la commande' : 'la livraison'} avec options de gestion
</p>
</div>
</div>
</DialogHeader>
</div>
{/* Content */}
<div className="overflow-y-auto max-h-96">
{/* Status */}
<div className="mb-6">
{getStatusBadge(item.status)}
</div>
{/* Information Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Left Column */}
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Fournisseur
</label>
<p className="text-gray-900 font-medium">{item.supplier?.name}</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Date prévue
</label>
<p className="text-gray-900">
{safeFormat(isDelivery ? item.scheduledDate : item.plannedDate, 'dd MMMM yyyy')}
</p>
</div>
{/* Afficher la quantité seulement pour les livraisons */}
{isDelivery && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Quantité
</label>
<Badge variant="outline" className="text-sm">
{formatQuantity(item.quantity, item.unit)}
</Badge>
</div>
)}
</div>
{/* Right Column */}
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Magasin/Groupe
</label>
<div className="flex items-center space-x-2">
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: item.group?.color }}
/>
<span className="text-gray-900">{item.group?.name}</span>
</div>
</div>
{item.deliveredDate && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Date de livraison
</label>
<p className="text-gray-900">
{safeFormat(item.deliveredDate, 'dd MMMM yyyy, HH:mm')}
</p>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Créé par
</label>
<p className="text-gray-900">
{item.creator?.firstName} {item.creator?.lastName}
</p>
</div>
</div>
</div>
{/* Comments */}
{item.notes && (
<div className="mt-6">
<label className="block text-sm font-medium text-gray-700 mb-2">
Commentaires
</label>
<div className="bg-gray-50 rounded-lg p-4">
<p className="text-gray-700">{item.notes}</p>
</div>
</div>
)}
{/* Linked Items */}
{isOrder && item.deliveries && item.deliveries.length > 0 && (
<div className="mt-6">
<label className="block text-sm font-medium text-gray-700 mb-3">
Livraisons associées
</label>
<div className="space-y-2">
{item.deliveries.map((delivery: any) => (
<div key={delivery.id} className="flex items-center justify-between p-3 bg-green-50 rounded-lg border border-green-200">
<div className="flex items-center space-x-3">
<Truck className="w-4 h-4 text-secondary" />
<div>
<p className="font-medium text-gray-900">#LIV-{delivery.id}</p>
<p className="text-sm text-gray-600">
{safeFormat(delivery.plannedDate, 'dd MMMM yyyy')}
</p>
</div>
</div>
{getStatusBadge(delivery.status)}
</div>
))}
</div>
</div>
)}
{isDelivery && item.order && (
<div className="mt-6">
<label className="block text-sm font-medium text-gray-700 mb-3">
Commande associée
</label>
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-200">
<div className="flex items-center space-x-3">
<Package className="w-4 h-4 text-primary" />
<div>
<p className="font-medium text-gray-900">#CMD-{item.order.id}</p>
<p className="text-sm text-gray-600">
{safeFormat(item.order.plannedDate, 'dd MMMM yyyy')}
</p>
</div>
</div>
{getStatusBadge(item.order.status)}
</div>
</div>
)}
</div>
{/* Actions */}
<div className="bg-gray-50 p-4 -m-6 mt-4 border-t border-gray-200 flex items-center justify-between">
<div className="flex items-center space-x-3">
{canDelete && (
<Button
variant="destructive"
size="sm"
onClick={() => setShowDeleteConfirm(true)}
disabled={deleteMutation.isPending}
>
<Trash2 className="w-4 h-4 mr-2" />
Supprimer
</Button>
)}
</div>
<div className="flex items-center space-x-3">
<Button variant="outline" onClick={onClose}>
Fermer
</Button>
{canEdit && (
<Button onClick={handleEdit}>
<Edit className="w-4 h-4 mr-2" />
Modifier
</Button>
)}
{canValidate && (
<Button
onClick={handleValidateDelivery}
className="bg-secondary hover:bg-green-700"
>
<Check className="w-4 h-4 mr-2" />
Valider livraison
</Button>
)}
</div>
</div>
{/* Delete Confirmation */}
{showDeleteConfirm && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg p-6 max-w-md mx-4">
<h3 className="text-lg font-semibold text-gray-900 mb-2">
Confirmer la suppression
</h3>
<p className="text-gray-600 mb-4">
Êtes-vous sûr de vouloir supprimer cette {isOrder ? 'commande' : 'livraison'} ?
Cette action est irréversible.
</p>
<div className="flex items-center space-x-3">
<Button
variant="outline"
onClick={() => setShowDeleteConfirm(false)}
>
Annuler
</Button>
<Button
variant="destructive"
onClick={handleDelete}
disabled={deleteMutation.isPending}
>
Supprimer
</Button>
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
{/* Edit Modals */}
{showEditModal && isOrder && (
<EditOrderModal
isOpen={showEditModal}
onClose={() => setShowEditModal(false)}
order={item}
/>
)}
{showEditModal && isDelivery && (
<EditDeliveryModal
isOpen={showEditModal}
onClose={() => setShowEditModal(false)}
delivery={item}
/>
)}
{/* Validate Delivery Modal */}
{showValidateModal && isDelivery && (
<ValidateDeliveryModal
isOpen={showValidateModal}
onClose={() => setShowValidateModal(false)}
delivery={item}
onValidated={onClose} // Fermer le modal de détail après validation
/>
)}
</>
);
}
@@ -0,0 +1,59 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Package, Truck } from "lucide-react";
interface QuickCreateMenuProps {
isOpen: boolean;
onClose: () => void;
onCreateOrder: () => void;
onCreateDelivery: () => void;
}
export default function QuickCreateMenu({
isOpen,
onClose,
onCreateOrder,
onCreateDelivery,
}: QuickCreateMenuProps) {
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="quick-create-modal-description">
<DialogHeader>
<DialogTitle>Création rapide</DialogTitle>
<p id="quick-create-modal-description" className="text-sm text-gray-600 mt-1">
Choisir le type d'élément à créer
</p>
</DialogHeader>
<div className="space-y-3">
<Button
variant="outline"
className="w-full justify-start space-x-3 p-4 h-auto hover:bg-blue-50 hover:border-blue-300"
onClick={onCreateOrder}
>
<div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center">
<Package className="w-5 h-5 text-white" />
</div>
<div className="text-left">
<p className="font-medium text-gray-900">Nouvelle Commande</p>
<p className="text-sm text-gray-600">Créer une commande fournisseur</p>
</div>
</Button>
<Button
variant="outline"
className="w-full justify-start space-x-3 p-4 h-auto hover:bg-green-50 hover:border-green-300"
onClick={onCreateDelivery}
>
<div className="w-10 h-10 bg-secondary rounded-lg flex items-center justify-center">
<Truck className="w-5 h-5 text-white" />
</div>
<div className="text-left">
<p className="font-medium text-gray-900">Nouvelle Livraison</p>
<p className="text-sm text-gray-600">Planifier une livraison</p>
</div>
</Button>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,194 @@
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { isUnauthorizedError } from "@/lib/authUtils";
import { Check, X } from "lucide-react";
const validateDeliverySchema = z.object({
blNumber: z.string().min(1, "Le numéro de BL est obligatoire"),
blAmount: z.string().optional(),
});
type ValidateDeliveryForm = z.infer<typeof validateDeliverySchema>;
interface ValidateDeliveryModalProps {
isOpen: boolean;
onClose: () => void;
delivery: any;
onValidated?: () => void; // Callback pour fermer le modal parent
}
export default function ValidateDeliveryModal({
isOpen,
onClose,
delivery,
onValidated,
}: ValidateDeliveryModalProps) {
const { toast } = useToast();
const queryClient = useQueryClient();
const form = useForm<ValidateDeliveryForm>({
resolver: zodResolver(validateDeliverySchema),
defaultValues: {
blNumber: "",
blAmount: "",
},
});
const validateDeliveryMutation = useMutation({
mutationFn: async (data: ValidateDeliveryForm) => {
const payload: any = {
blNumber: data.blNumber,
};
if (data.blAmount && data.blAmount.trim() !== '') {
payload.blAmount = parseFloat(data.blAmount);
}
await apiRequest(`/api/deliveries/${delivery.id}/validate`, "POST", payload);
},
onSuccess: () => {
toast({
title: "Succès",
description: "Livraison validée avec succès",
});
// Invalider tous les caches liés aux livraisons
queryClient.invalidateQueries({ queryKey: ['/api/deliveries'] });
// Invalider tous les caches BL/Rapprochement avec toutes les variations de clés
queryClient.invalidateQueries({
predicate: (query) =>
query.queryKey[0] === '/api/deliveries/bl' ||
query.queryKey[0] === '/api/deliveries'
});
queryClient.invalidateQueries({ queryKey: ['/api/orders'] });
queryClient.invalidateQueries({ queryKey: ['/api/stats/monthly'] });
form.reset();
onClose();
// Fermer aussi le modal parent si fourni
if (onValidated) {
onValidated();
}
},
onError: (error) => {
if (isUnauthorizedError(error)) {
toast({
title: "Non autorisé",
description: "Vous êtes déconnecté. Reconnexion...",
variant: "destructive",
});
setTimeout(() => {
window.location.href = "/api/login";
}, 500);
return;
}
toast({
title: "Erreur",
description: "Impossible de valider la livraison",
variant: "destructive",
});
},
});
const onSubmit = (data: ValidateDeliveryForm) => {
validateDeliveryMutation.mutate(data);
};
if (!delivery) return null;
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="sm:max-w-md" aria-describedby="validate-delivery-modal-description">
<DialogHeader>
<DialogTitle className="flex items-center space-x-2">
<Check className="w-5 h-5 text-green-600" />
<span>Valider la livraison</span>
</DialogTitle>
<p id="validate-delivery-modal-description" className="text-sm text-gray-600 mt-1">
Saisir les informations du bon de livraison
</p>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* Informations de la livraison */}
<div className="bg-gray-50 rounded-lg p-4 space-y-2">
<h4 className="font-medium text-gray-900">Détails de la livraison</h4>
<div className="text-sm text-gray-600">
<p><strong>Fournisseur:</strong> {delivery.supplier?.name}</p>
<p><strong>Magasin:</strong> {delivery.group?.name}</p>
<p><strong>Quantité:</strong> {delivery.quantity} {delivery.unit === 'palettes' ? 'Palettes' : 'Colis'}</p>
</div>
</div>
{/* Numéro de BL */}
<FormField
control={form.control}
name="blNumber"
render={({ field }) => (
<FormItem>
<FormLabel>N° Bon de Livraison *</FormLabel>
<FormControl>
<Input
placeholder="Ex: BL-2024-001"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Montant BL */}
<FormField
control={form.control}
name="blAmount"
render={({ field }) => (
<FormItem>
<FormLabel>Montant BL (€) - Optionnel</FormLabel>
<FormControl>
<Input
type="number"
step="0.01"
placeholder="Ex: 1200.00 (à remplir plus tard si nécessaire)"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Actions */}
<div className="flex justify-end space-x-3 pt-4">
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={validateDeliveryMutation.isPending}
>
<X className="w-4 h-4 mr-2" />
Annuler
</Button>
<Button
type="submit"
disabled={validateDeliveryMutation.isPending}
className="bg-green-600 hover:bg-green-700"
>
<Check className="w-4 h-4 mr-2" />
{validateDeliveryMutation.isPending ? "Validation..." : "Valider livraison"}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,192 @@
import { useQuery } from "@tanstack/react-query";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
ListTodo,
Circle,
Clock,
AlertTriangle,
ArrowRight
} from "lucide-react";
import { format, addDays, isAfter, isBefore } from "date-fns";
import { fr } from "date-fns/locale";
import { useLocation } from "wouter";
import { useStore } from "@/components/Layout";
import { Task } from "@shared/schema";
type TaskWithRelations = Task & {
assignedUser: { id: string; username: string; firstName?: string; lastName?: string; };
creator: { id: string; username: string; firstName?: string; lastName?: string; };
group: { id: number; name: string; color: string; };
};
export default function RecentTasksCard() {
const { user } = useAuthUnified();
const { selectedStoreId } = useStore();
const [, navigate] = useLocation();
// Fetch tasks
const { data: tasks = [], isLoading } = useQuery({
queryKey: ["/api/tasks", selectedStoreId],
queryFn: () => {
const params = new URLSearchParams();
if (selectedStoreId) {
params.append('storeId', selectedStoreId);
}
return fetch(`/api/tasks?${params.toString()}`).then(res => res.json());
},
enabled: !!user,
});
// Filtrer les tâches des 7 prochains jours qui ne sont pas terminées
const upcomingTasks = tasks
.filter((task: TaskWithRelations) => {
// Seulement les tâches incomplètes
if (task.status === 'completed') return false;
// Tâches avec date d'échéance dans les 7 prochains jours
if (task.dueDate) {
const dueDate = new Date(task.dueDate);
const now = new Date();
const sevenDaysFromNow = addDays(now, 7);
return isAfter(dueDate, now) && isBefore(dueDate, sevenDaysFromNow);
}
return false;
})
.sort((a: TaskWithRelations, b: TaskWithRelations) => {
// Trier par priorité (high -> medium -> low) puis par date
const priorityOrder = { high: 3, medium: 2, low: 1 };
const priorityDiff = (priorityOrder[b.priority as keyof typeof priorityOrder] || 2) -
(priorityOrder[a.priority as keyof typeof priorityOrder] || 2);
if (priorityDiff !== 0) return priorityDiff;
// Si même priorité, trier par date d'échéance
if (a.dueDate && b.dueDate) {
return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
}
return 0;
})
.slice(0, 5); // Limite à 5 tâches
const getPriorityConfig = (priority: string) => {
switch (priority) {
case 'high':
return {
color: 'destructive' as const,
icon: AlertTriangle,
label: 'Élevée'
};
case 'medium':
return {
color: 'default' as const,
icon: Clock,
label: 'Moyenne'
};
case 'low':
return {
color: 'secondary' as const,
icon: Circle,
label: 'Faible'
};
default:
return {
color: 'secondary' as const,
icon: Circle,
label: 'Moyenne'
};
}
};
const handleViewAllTasks = () => {
navigate("/tasks");
};
if (isLoading) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Tâches à venir</CardTitle>
<ListTodo className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="flex items-center justify-center h-32">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Tâches à venir</CardTitle>
<ListTodo className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
{upcomingTasks.length === 0 ? (
<div className="text-center py-6">
<ListTodo className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
<p className="text-sm text-muted-foreground">
Aucune tâche à venir dans les 7 prochains jours
</p>
</div>
) : (
<div className="space-y-3">
{upcomingTasks.map((task: TaskWithRelations) => {
const priorityConfig = getPriorityConfig(task.priority);
const PriorityIcon = priorityConfig.icon;
return (
<div key={task.id} className="flex items-start justify-between p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-medium text-sm truncate">
{task.title}
</h4>
<Badge variant={priorityConfig.color} className="flex items-center gap-1 text-xs">
<PriorityIcon className="w-2.5 h-2.5" />
{priorityConfig.label}
</Badge>
</div>
{task.description && (
<p className="text-xs text-muted-foreground mb-1 line-clamp-1">
{task.description}
</p>
)}
<div className="flex items-center gap-3 text-xs text-muted-foreground">
{task.dueDate && (
<span>
{format(new Date(task.dueDate), 'dd/MM à HH:mm', { locale: fr })}
</span>
)}
<span>
{task.assignedTo}
</span>
</div>
</div>
</div>
);
})}
<Button
variant="ghost"
className="w-full justify-center mt-4"
onClick={handleViewAllTasks}
>
Voir toutes les tâches
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</div>
)}
</CardContent>
</Card>
);
}
+397
View File
@@ -0,0 +1,397 @@
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { useAuthUnified } from "@/hooks/useAuthUnified";
import { useStore } from "@/components/Layout";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { apiRequest } from "@/lib/queryClient";
import { insertTaskSchema, Task, Group } from "@shared/schema";
import { z } from "zod";
type TaskWithRelations = Task & {
assignedUser: { id: string; username: string; firstName?: string; lastName?: string; };
creator: { id: string; username: string; firstName?: string; lastName?: string; };
group: { id: number; name: string; color: string; };
};
// Schéma simplifié sans magasin et sans date d'échéance
const taskFormSchema = insertTaskSchema.omit({
id: true,
createdAt: true,
updatedAt: true,
completedAt: true,
createdBy: true,
groupId: true,
dueDate: true, // Suppression du champ échéance
});
type TaskFormData = z.infer<typeof taskFormSchema>;
interface TaskFormProps {
task?: TaskWithRelations;
onClose: () => void;
}
export default function TaskForm({ task, onClose }: TaskFormProps) {
const { user } = useAuthUnified();
const { selectedStoreId } = useStore();
const { toast } = useToast();
const queryClient = useQueryClient();
// État local pour gérer le magasin sélectionné (auto-sélection intelligente)
const [localSelectedStoreId, setLocalSelectedStoreId] = useState<number | null>(null);
// Récupération des magasins pour l'auto-sélection
const { data: groupsData = [] } = useQuery<Group[]>({
queryKey: ['/api/groups'],
});
// Filtrer les groupes selon le magasin sélectionné pour les admins
const groups = Array.isArray(groupsData) ? (
user?.role === 'admin' && selectedStoreId
? groupsData.filter(g => g.id === selectedStoreId)
: groupsData
) : [];
// Auto-sélectionner le magasin selon les règles (même logique que CreateOrderModal)
useEffect(() => {
console.log('🏪 TaskForm - Store selection effect:', {
groupsLength: groups.length,
selectedStoreId,
localSelectedStoreId,
userRole: user?.role,
allGroups: groups.map(g => ({ id: g.id, name: g.name })),
});
if (groups.length > 0 && !localSelectedStoreId) {
let defaultStoreId: number | null = null;
if (user?.role === 'admin') {
// Pour l'admin : utiliser le magasin sélectionné dans le header (filtré), sinon le premier de la liste
if (selectedStoreId && groups.find(g => g.id === selectedStoreId)) {
defaultStoreId = selectedStoreId;
} else {
defaultStoreId = groups[0].id;
}
console.log('🏪 Admin task store selection:', {
selectedStoreId,
defaultStoreId,
firstGroupId: groups[0].id,
groupsAvailable: groups.map(g => g.name)
});
} else {
// Pour les autres rôles : prendre le premier magasin attribué
defaultStoreId = groups[0].id;
console.log('🏪 Non-admin task store selection:', { defaultStoreId, firstGroupId: groups[0].id });
}
if (defaultStoreId) {
console.log('🏪 Setting default task store ID:', defaultStoreId, 'for group:', groups.find(g => g.id === defaultStoreId)?.name);
setLocalSelectedStoreId(defaultStoreId);
}
}
// Mettre à jour localSelectedStoreId si selectedStoreId change (pour les admins)
if (user?.role === 'admin' && selectedStoreId && selectedStoreId !== localSelectedStoreId) {
console.log('🔄 Updating task form store because header store changed:', {
oldStoreId: localSelectedStoreId,
newStoreId: selectedStoreId
});
setLocalSelectedStoreId(selectedStoreId);
}
}, [groups, selectedStoreId, user?.role, localSelectedStoreId]);
const form = useForm<TaskFormData>({
resolver: zodResolver(taskFormSchema),
defaultValues: {
title: task?.title || "",
description: task?.description || "",
priority: task?.priority || "medium",
status: task?.status || "pending",
assignedTo: task?.assignedTo || "",
},
});
// Mutation pour créer/modifier une tâche
const createMutation = useMutation({
mutationFn: (data: any) => {
// Ajouter le groupId basé sur le magasin auto-sélectionné
const taskData = {
...data,
groupId: localSelectedStoreId,
createdBy: user?.id,
dueDate: data.dueDate || null
};
console.log('🚀 Creating task with data:', taskData);
return apiRequest("/api/tasks", "POST", taskData);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/tasks"] });
toast({
title: "Succès",
description: "Tâche créée avec succès",
});
onClose();
},
onError: (error: any) => {
console.error("Error creating task:", error);
toast({
title: "Erreur",
description: "Impossible de créer la tâche",
variant: "destructive",
});
},
});
const updateMutation = useMutation({
mutationFn: (data: any) => apiRequest(`/api/tasks/${task?.id}`, "PUT", data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/tasks"] });
toast({
title: "Succès",
description: "Tâche modifiée avec succès",
});
onClose();
},
onError: (error: any) => {
console.error("Error updating task:", error);
toast({
title: "Erreur",
description: "Impossible de modifier la tâche",
variant: "destructive",
});
},
});
const onSubmit = (data: TaskFormData) => {
// Vérifier qu'un magasin est auto-sélectionné
if (!localSelectedStoreId) {
toast({
title: "Erreur",
description: "Aucun magasin disponible pour créer une tâche",
variant: "destructive",
});
return;
}
if (task) {
// Modification de tâche existante
const submitData = {
title: data.title,
description: data.description,
priority: data.priority,
status: data.status,
assignedTo: data.assignedTo,
};
updateMutation.mutate(submitData);
} else {
// Création d'une nouvelle tâche - le groupId sera ajouté dans createMutation
createMutation.mutate(data);
}
};
const getPriorityLabel = (priority: string) => {
switch (priority) {
case 'high': return 'Élevée';
case 'medium': return 'Moyenne';
case 'low': return 'Faible';
default: return 'Moyenne';
}
};
const getStatusLabel = (status: string) => {
switch (status) {
case 'pending': return 'En cours';
case 'completed': return 'Terminée';
default: return 'En cours';
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{/* Affichage du magasin auto-sélectionné */}
{localSelectedStoreId && (
<div className="bg-blue-50 border border-blue-200 rounded-md p-3">
<div className="flex items-center">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-blue-800">
<span className="font-medium">Magasin sélectionné :</span>{" "}
{(() => {
const selectedGroup = groups.find(g => g.id === localSelectedStoreId);
return selectedGroup ? (
<span className="inline-flex items-center gap-2">
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: selectedGroup.color }}
/>
{selectedGroup.name}
</span>
) : `Magasin ID: ${localSelectedStoreId}`;
})()}
</p>
</div>
</div>
</div>
)}
{/* Avertissement si aucun magasin n'est disponible */}
{!localSelectedStoreId && groups.length === 0 && (
<div className="bg-yellow-50 border border-yellow-200 rounded-md p-3">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-yellow-800">
Aucun magasin disponible. Veuillez contacter un administrateur.
</p>
</div>
</div>
</div>
)}
{/* Titre */}
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Titre *</FormLabel>
<FormControl>
<Input
placeholder="Titre de la tâche"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Description */}
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Description détaillée de la tâche (optionnel)"
rows={3}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
{/* Priorité */}
<FormField
control={form.control}
name="priority"
render={({ field }) => (
<FormItem>
<FormLabel>Priorité *</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner une priorité" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="low">Faible</SelectItem>
<SelectItem value="medium">Moyenne</SelectItem>
<SelectItem value="high">Élevée</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{/* Statut */}
<FormField
control={form.control}
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>Statut</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Sélectionner un statut" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="pending">En cours</SelectItem>
<SelectItem value="completed">Terminée</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Assigné à */}
<FormField
control={form.control}
name="assignedTo"
render={({ field }) => (
<FormItem>
<FormLabel>Assigné à *</FormLabel>
<FormControl>
<Input
placeholder="Nom de la personne assignée"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Boutons d'action */}
<div className="flex justify-end space-x-3 pt-6">
<Button type="button" variant="outline" onClick={onClose}>
Annuler
</Button>
<Button
type="submit"
disabled={createMutation.isPending || updateMutation.isPending}
className="bg-blue-600 hover:bg-blue-700"
>
{createMutation.isPending || updateMutation.isPending ? (
<div className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
{task ? "Modification..." : "Création..."}
</div>
) : (
task ? "Modifier" : "Créer"
)}
</Button>
</div>
</form>
</Form>
);
}
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+139
View File
@@ -0,0 +1,139 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}
+59
View File
@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
@@ -0,0 +1,5 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
const AspectRatio = AspectRatioPrimitive.Root
export { AspectRatio }
+50
View File
@@ -0,0 +1,50 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-gray-100 text-gray-900 hover:bg-gray-200",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground border-gray-300",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+115
View File
@@ -0,0 +1,115 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
Breadcrumb.displayName = "Breadcrumb"
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<"ol">
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
))
BreadcrumbList.displayName = "BreadcrumbList"
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
))
BreadcrumbItem.displayName = "BreadcrumbItem"
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a"
return (
<Comp
ref={ref}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
)
})
BreadcrumbLink.displayName = "BreadcrumbLink"
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
))
BreadcrumbPage.displayName = "BreadcrumbPage"
const BreadcrumbSeparator = ({
children,
className,
...props
}: React.ComponentProps<"li">) => (
<li
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
const BreadcrumbEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
}
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-white hover:bg-gray-50",
secondary:
"bg-gray-100 text-gray-900 hover:bg-gray-200",
ghost: "hover:bg-gray-100",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 px-3",
lg: "h-11 px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+68
View File
@@ -0,0 +1,68 @@
import * as React from "react"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { DayPicker } from "react-day-picker"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
export type CalendarProps = React.ComponentProps<typeof DayPicker>
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20 focus-within:outline-none",
day: cn(
buttonVariants({ variant: "ghost" }),
"h-9 w-9 p-0 font-normal aria-selected:opacity-100 focus:outline-none focus:ring-0 focus:ring-offset-0"
),
day_range_end: "day-range-end",
day_selected:
"bg-blue-600 text-white hover:bg-blue-700 hover:text-white focus:bg-blue-600 focus:text-white",
day_today: "bg-blue-50 text-blue-900 font-semibold border border-blue-200 hover:bg-blue-100",
day_outside:
"day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ className, ...props }) => (
<ChevronLeft className={cn("h-4 w-4", className)} {...props} />
),
IconRight: ({ className, ...props }) => (
<ChevronRight className={cn("h-4 w-4", className)} {...props} />
),
}}
{...props}
/>
)
}
Calendar.displayName = "Calendar"
export { Calendar }
+79
View File
@@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"border bg-white text-card-foreground shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+260
View File
@@ -0,0 +1,260 @@
import * as React from "react"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) {
return
}
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) {
return
}
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}
+365
View File
@@ -0,0 +1,365 @@
"use client"
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
})
ChartContainer.displayName = "Chart"
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref
) => {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
return (
<div
key={item.dataKey}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
)
ChartTooltipContent.displayName = "ChartTooltip"
const ChartLegend = RechartsPrimitive.Legend
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}
>(
(
{ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },
ref
) => {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
ref={ref}
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
)
ChartLegendContent.displayName = "ChartLegend"
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }
+11
View File
@@ -0,0 +1,11 @@
"use client"
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
const Collapsible = CollapsiblePrimitive.Root
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
+151
View File
@@ -0,0 +1,151 @@
import * as React from "react"
import { type DialogProps } from "@radix-ui/react-dialog"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
))
Command.displayName = CommandPrimitive.displayName
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
))
CommandInput.displayName = CommandPrimitive.Input.displayName
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
))
CommandList.displayName = CommandPrimitive.List.displayName
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
))
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
))
CommandGroup.displayName = CommandPrimitive.Group.displayName
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
))
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
/>
))
CommandItem.displayName = CommandPrimitive.Item.displayName
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
CommandShortcut.displayName = "CommandShortcut"
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}
+198
View File
@@ -0,0 +1,198 @@
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
const ContextMenuTrigger = ContextMenuPrimitive.Trigger
const ContextMenuGroup = ContextMenuPrimitive.Group
const ContextMenuPortal = ContextMenuPrimitive.Portal
const ContextMenuSub = ContextMenuPrimitive.Sub
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-context-menu-content-transform-origin]",
className
)}
{...props}
/>
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 max-h-[--radix-context-menu-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-context-menu-content-transform-origin]",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
))
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-foreground",
inset && "pl-8",
className
)}
{...props}
/>
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
const ContextMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}
+122
View File
@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-gray-200 bg-white p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 opacity-70 ring-offset-background transition-opacity hover:opacity-100 hover:bg-gray-100 p-1 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-xl font-medium leading-none tracking-tight text-gray-900",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+118
View File
@@ -0,0 +1,118 @@
"use client"
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
const Drawer = ({
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
const DrawerTrigger = DrawerPrimitive.Trigger
const DrawerPortal = DrawerPrimitive.Portal
const DrawerClose = DrawerPrimitive.Close
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
const DrawerHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
const DrawerFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}
+198
View File
@@ -0,0 +1,198 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
+178
View File
@@ -0,0 +1,178 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
+29
View File
@@ -0,0 +1,29 @@
"use client"
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
const HoverCard = HoverCardPrimitive.Root
const HoverCardTrigger = HoverCardPrimitive.Trigger
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-hover-card-content-transform-origin]",
className
)}
{...props}
/>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName
export { HoverCard, HoverCardTrigger, HoverCardContent }
+69
View File
@@ -0,0 +1,69 @@
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { Dot } from "lucide-react"
import { cn } from "@/lib/utils"
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn(
"flex items-center gap-2 has-[:disabled]:opacity-50",
containerClassName
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
))
InputOTP.displayName = "InputOTP"
const InputOTPGroup = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext)
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
)
})
InputOTPSlot.displayName = "InputOTPSlot"
const InputOTPSeparator = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div">
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full border border-input bg-white px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+256
View File
@@ -0,0 +1,256 @@
"use client"
import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu {...props} />
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group {...props} />
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal {...props} />
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return <MenubarPrimitive.RadioGroup {...props} />
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
}
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn(
"flex h-10 items-center space-x-1 rounded-md border bg-background p-1",
className
)}
{...props}
/>
))
Menubar.displayName = MenubarPrimitive.Root.displayName
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
className
)}
{...props}
/>
))
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
))
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-menubar-content-transform-origin]",
className
)}
{...props}
/>
))
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(
(
{ className, align = "start", alignOffset = -4, sideOffset = 8, ...props },
ref
) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-menubar-content-transform-origin]",
className
)}
{...props}
/>
</MenubarPrimitive.Portal>
)
)
MenubarContent.displayName = MenubarPrimitive.Content.displayName
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarItem.displayName = MenubarPrimitive.Item.displayName
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
))
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
))
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
MenubarLabel.displayName = MenubarPrimitive.Label.displayName
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName
const MenubarShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
MenubarShortcut.displayname = "MenubarShortcut"
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
}
@@ -0,0 +1,128 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
"relative z-10 flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
))
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn(
"group flex flex-1 list-none items-center justify-center space-x-1",
className
)}
{...props}
/>
))
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=open]:text-accent-foreground data-[state=open]:bg-accent/50 data-[state=open]:hover:bg-accent data-[state=open]:focus:bg-accent"
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
))
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
className
)}
{...props}
/>
))
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName
const NavigationMenuLink = NavigationMenuPrimitive.Link
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
ref={ref}
{...props}
/>
</div>
))
NavigationMenuViewport.displayName =
NavigationMenuPrimitive.Viewport.displayName
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
}
+182
View File
@@ -0,0 +1,182 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react";
interface PaginationProps {
currentPage: number;
totalPages: number;
totalItems: number;
itemsPerPage: number;
onPageChange: (page: number) => void;
onItemsPerPageChange?: (itemsPerPage: number) => void;
className?: string;
}
export function Pagination({
currentPage,
totalPages,
totalItems,
itemsPerPage,
onPageChange,
onItemsPerPageChange,
className = ""
}: PaginationProps) {
const startItem = (currentPage - 1) * itemsPerPage + 1;
const endItem = Math.min(currentPage * itemsPerPage, totalItems);
const getVisiblePages = () => {
const delta = 2;
const range = [];
const rangeWithDots = [];
let l;
for (let i = Math.max(2, currentPage - delta);
i <= Math.min(totalPages - 1, currentPage + delta);
i++) {
range.push(i);
}
if (currentPage - delta > 2) {
rangeWithDots.push(1, '...');
} else {
rangeWithDots.push(1);
}
rangeWithDots.push(...range);
if (currentPage + delta < totalPages - 1) {
rangeWithDots.push('...', totalPages);
} else {
rangeWithDots.push(totalPages);
}
return rangeWithDots;
};
if (totalPages <= 1) return null;
return (
<div className={`flex items-center justify-between px-2 ${className}`}>
<div className="flex items-center space-x-6 lg:space-x-8">
{onItemsPerPageChange && (
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Lignes par page</p>
<Select
value={itemsPerPage.toString()}
onValueChange={(value) => onItemsPerPageChange(parseInt(value))}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={itemsPerPage} />
</SelectTrigger>
<SelectContent side="top">
{[10, 20, 30, 50, 100].map((pageSize) => (
<SelectItem key={pageSize} value={pageSize.toString()}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {currentPage} sur {totalPages}
</div>
<div className="text-sm text-muted-foreground">
{totalItems > 0 ? `${startItem}-${endItem} sur ${totalItems}` : '0 élément'}
</div>
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => onPageChange(1)}
disabled={currentPage === 1}
>
<span className="sr-only">Aller à la première page</span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 1}
>
<span className="sr-only">Aller à la page précédente</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<div className="flex items-center space-x-1">
{getVisiblePages().map((page, index) => (
<Button
key={index}
variant={page === currentPage ? "default" : "outline"}
className="h-8 w-8 p-0"
onClick={() => typeof page === 'number' && onPageChange(page)}
disabled={page === '...'}
>
{page}
</Button>
))}
</div>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage === totalPages}
>
<span className="sr-only">Aller à la page suivante</span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => onPageChange(totalPages)}
disabled={currentPage === totalPages}
>
<span className="sr-only">Aller à la dernière page</span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
);
}
// Hook utilitaire pour gérer la pagination
export function usePagination(data: any[], initialItemsPerPage: number = 20) {
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(initialItemsPerPage);
const totalPages = Math.ceil(data.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const paginatedData = data.slice(startIndex, endIndex);
// Reset à la page 1 si les données changent
useEffect(() => {
setCurrentPage(1);
}, [data.length]);
// Reset à la page 1 si le nombre d'éléments par page change
useEffect(() => {
setCurrentPage(1);
}, [itemsPerPage]);
// S'assurer que la page actuelle est valide
useEffect(() => {
if (currentPage > totalPages && totalPages > 0) {
setCurrentPage(totalPages);
}
}, [currentPage, totalPages]);
return {
currentPage,
setCurrentPage,
itemsPerPage,
setItemsPerPage,
totalPages,
paginatedData,
totalItems: data.length
};
}
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-popover-content-transform-origin]",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }
+28
View File
@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }
+42
View File
@@ -0,0 +1,42 @@
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn("grid gap-2", className)}
{...props}
ref={ref}
/>
)
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }
+45
View File
@@ -0,0 +1,45 @@
"use client"
import { GripVertical } from "lucide-react"
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@/lib/utils"
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className
)}
{...props}
/>
)
const ResizablePanel = ResizablePrimitive.Panel
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
)
export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
+46
View File
@@ -0,0 +1,46 @@
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }
+160
View File
@@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between border border-input bg-white px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden border bg-white text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }