Files
Dashboard/components/collections/users-table.tsx
2025-11-27 13:58:47 +01:00

290 lines
9.8 KiB
TypeScript

"use client";
import { useState, useMemo, useEffect } from "react";
import { useCollection } from "@/hooks/useCollection";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { ChevronLeft, ChevronRight, Search, X } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { LibreChatUser, LibreChatBalance } from "@/lib/types";
// Couleurs prédéfinies pour les référents
const REFERENT_COLORS: Record<string, string> = {
"Emmanuel WATHELE": "#3B82F6", // Bleu
"IHECS": "#10B981", // Vert
"Patrice De La Broise": "#F59E0B", // Orange
};
export function UsersTable() {
const [page, setPage] = useState(1);
const [searchInput, setSearchInput] = useState(""); // Ce que l'utilisateur tape
const [activeSearch, setActiveSearch] = useState(""); // Ce qui est réellement recherché
const [activeReferent, setActiveReferent] = useState<string | undefined>(undefined);
const limit = 20;
// Réinitialiser la page à 1 quand une nouvelle recherche ou filtre est lancé
useEffect(() => {
setPage(1);
}, [activeSearch, activeReferent]);
const {
data: users = [],
total = 0,
loading: usersLoading,
} = useCollection<LibreChatUser>("users", {
page,
limit,
search: activeSearch,
referent: activeReferent,
});
const handleReferentClick = (referent: string) => {
if (activeReferent === referent) {
setActiveReferent(undefined); // Toggle off
} else {
setActiveReferent(referent);
}
};
const clearReferentFilter = () => {
setActiveReferent(undefined);
};
// Fonction pour lancer la recherche
const handleSearch = () => {
setActiveSearch(searchInput);
};
// Gérer la touche Entrée
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
handleSearch();
}
};
// Charger tous les balances pour associer les crédits
const { data: balances = [] } = useCollection<LibreChatBalance>("balances", {
limit: 1000,
});
// Créer une map des crédits par utilisateur
const creditsMap = useMemo(() => {
const map = new Map<string, number>();
balances.forEach((balance) => {
map.set(balance.user, balance.tokenCredits || 0);
});
return map;
}, [balances]);
const totalPages = Math.ceil(total / limit);
const handlePrevPage = () => {
setPage((prev) => Math.max(1, prev - 1));
};
const handleNextPage = () => {
setPage((prev) => Math.min(totalPages, prev + 1));
};
if (usersLoading) {
return (
<Card>
<CardHeader>
<CardTitle>Liste des utilisateurs</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="h-16 bg-muted animate-pulse rounded" />
))}
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<div className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
<CardTitle>
Liste des utilisateurs ({total})
</CardTitle>
<div className="flex gap-2 w-full sm:w-auto items-center">
{activeReferent && (
<Badge
variant="secondary"
className="flex items-center gap-1 px-3 py-1"
style={{ backgroundColor: REFERENT_COLORS[activeReferent] || "#6B7280", color: "white" }}
>
{activeReferent}
<button
onClick={clearReferentFilter}
className="ml-1 hover:bg-white/20 rounded-full p-0.5"
>
<X className="h-3 w-3" />
</button>
</Badge>
)}
<div className="relative flex-1 sm:w-80">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Rechercher par nom ou email..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyPress={handleKeyPress}
className="pl-10"
/>
</div>
<Button onClick={handleSearch} variant="default">
Rechercher
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-20">ID</TableHead>
<TableHead>Nom</TableHead>
<TableHead>Email</TableHead>
<TableHead className="w-32">Référent</TableHead>
<TableHead className="w-20">Rôle</TableHead>
<TableHead className="w-32">Crédits</TableHead>
<TableHead className="w-28">Créé le</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.length > 0 ? (
users.map((user) => {
const userCredits = creditsMap.get(user._id) || 0;
const referentColor = user.referent ? (REFERENT_COLORS[user.referent] || "#6B7280") : null;
return (
<TableRow key={user._id}>
<TableCell>
<span className="font-mono text-xs">
{user._id.slice(-8)}
</span>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
{referentColor && (
<div
className="w-3 h-3 rounded-full flex-shrink-0"
style={{ backgroundColor: referentColor }}
title={user.referent}
/>
)}
<span className="font-medium">{user.name}</span>
</div>
</TableCell>
<TableCell>
<span className="text-sm">{user.email}</span>
</TableCell>
<TableCell>
{user.referent ? (
<button
onClick={() => handleReferentClick(user.referent!)}
className={`text-sm truncate block max-w-[120px] hover:underline cursor-pointer transition-colors ${
activeReferent === user.referent
? "font-bold text-primary"
: "text-foreground hover:text-primary"
}`}
title={`Cliquer pour filtrer par ${user.referent}`}
>
{user.referent}
</button>
) : (
<span className="text-sm text-gray-400">-</span>
)}
</TableCell>
<TableCell>
<Badge
variant={
user.role === "ADMIN" ? "default" : "secondary"
}
>
{user.role}
</Badge>
</TableCell>
<TableCell>
<span className="font-semibold">
{userCredits.toLocaleString()} crédits
</span>
</TableCell>
<TableCell>
<span className="text-sm text-muted-foreground">
{formatDate(user.createdAt)}
</span>
</TableCell>
</TableRow>
);
})
) : (
<TableRow>
<TableCell
colSpan={7}
className="text-center py-8 text-muted-foreground"
>
{activeSearch
? `Aucun utilisateur trouvé pour "${activeSearch}"`
: "Aucun utilisateur trouvé"}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{/* Pagination */}
<div className="flex items-center justify-between space-x-2 py-4">
<div className="text-sm text-muted-foreground">
{activeSearch ? (
<span>
{total} résultat(s) pour &quot;{activeSearch}&quot; - Page {page} sur {totalPages}
</span>
) : (
<span>
Page {page} sur {totalPages} ({total} utilisateurs au total)
</span>
)}
</div>
<div className="flex space-x-2">
<Button
variant="outline"
size="sm"
onClick={handlePrevPage}
disabled={page <= 1}
>
<ChevronLeft className="h-4 w-4" />
Précédent
</Button>
<Button
variant="outline"
size="sm"
onClick={handleNextPage}
disabled={page >= totalPages}
>
Suivant
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
}