Compare commits
2 Commits
1c7bca8e35
...
0d95eca1ee
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d95eca1ee | ||
|
|
dde1c8ba93 |
15
.claude/settings.local.json
Normal file
15
.claude/settings.local.json
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(cat:*)",
|
||||||
|
"Bash(awk:*)",
|
||||||
|
"Bash(useCollection.tmp)",
|
||||||
|
"Bash(npm run build:*)",
|
||||||
|
"Bash(git add:*)",
|
||||||
|
"Bash(git commit:*)",
|
||||||
|
"Bash(git push)"
|
||||||
|
],
|
||||||
|
"deny": [],
|
||||||
|
"ask": []
|
||||||
|
}
|
||||||
|
}
|
||||||
13
CLAUDE.md
Normal file
13
CLAUDE.md
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
## CRITICAL: File Editing on Windows
|
||||||
|
|
||||||
|
### ⚠️ MANDATORY: Always Use Backslashes on Windows for File Paths
|
||||||
|
|
||||||
|
When using Edit or MultiEdit tools on Windows, you MUST use backslashes (\) in file paths, NOT forward slashes (/).
|
||||||
|
|
||||||
|
#### ❌ WRONG - Will cause errors:
|
||||||
|
|
||||||
|
Edit(file_path: "D:/repos/project/file.tsx", ...)
|
||||||
|
|
||||||
|
#### ✅ CORRECT - Always works:
|
||||||
|
|
||||||
|
Edit(file_path: "D:\repos\project\file.tsx", ...)
|
||||||
@@ -55,6 +55,7 @@ export async function GET(
|
|||||||
if (collection === "users") {
|
if (collection === "users") {
|
||||||
const email = searchParams.get("email");
|
const email = searchParams.get("email");
|
||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
|
const search = searchParams.get("search"); // ✅ AJOUTER cette ligne
|
||||||
|
|
||||||
if (email) {
|
if (email) {
|
||||||
filter.email = email.toLowerCase();
|
filter.email = email.toLowerCase();
|
||||||
@@ -69,6 +70,13 @@ export async function GET(
|
|||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
} else if (search) {
|
||||||
|
// ✅ AJOUTER ce bloc
|
||||||
|
// Recherche partielle sur nom et email
|
||||||
|
filter.$or = [
|
||||||
|
{ name: { $regex: search, $options: "i" } },
|
||||||
|
{ email: { $regex: search, $options: "i" } },
|
||||||
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
215
components/collections/users-table.old.tsx
Normal file
215
components/collections/users-table.old.tsx
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useMemo } 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 } from "lucide-react";
|
||||||
|
import { formatDate } from "@/lib/utils";
|
||||||
|
import { LibreChatUser, LibreChatBalance } from "@/lib/types";
|
||||||
|
|
||||||
|
export function UsersTable() {
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
|
const limit = 20;
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: users = [],
|
||||||
|
total = 0,
|
||||||
|
loading: usersLoading,
|
||||||
|
} = useCollection<LibreChatUser>("users", {
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
// ✅ AJOUTER le searchTerm ici
|
||||||
|
search: searchTerm,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Charger tous les balances pour associer les crédits
|
||||||
|
const { data: balances = [] } = useCollection<LibreChatBalance>("balances", {
|
||||||
|
limit: 1000, // Charger tous les balances
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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 ({searchTerm ? users.length : total})
|
||||||
|
</CardTitle>
|
||||||
|
<div className="relative w-full 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={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="pl-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="rounded-md border">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>ID</TableHead>
|
||||||
|
<TableHead>Nom</TableHead>
|
||||||
|
<TableHead>Email</TableHead>
|
||||||
|
<TableHead>Rôle</TableHead>
|
||||||
|
<TableHead>Crédits</TableHead>
|
||||||
|
<TableHead>Statut</TableHead>
|
||||||
|
<TableHead>Créé le</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{users.length > 0 ? (
|
||||||
|
users.map((user) => {
|
||||||
|
const userCredits = creditsMap.get(user._id) || 0;
|
||||||
|
const isActive =
|
||||||
|
new Date(user.updatedAt || user.createdAt) >
|
||||||
|
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 jours en millisecondes
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TableRow key={user._id}>
|
||||||
|
<TableCell>
|
||||||
|
<span className="font-mono text-xs">
|
||||||
|
{user._id.slice(-8)}
|
||||||
|
</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="font-medium">{user.name}</span>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<span className="text-sm">{user.email}</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">
|
||||||
|
<Badge variant={isActive ? "default" : "secondary"}>
|
||||||
|
{isActive ? "Actif" : "Inactif"}
|
||||||
|
</Badge>
|
||||||
|
</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"
|
||||||
|
>
|
||||||
|
{searchTerm
|
||||||
|
? `Aucun utilisateur trouvé pour "${searchTerm}"`
|
||||||
|
: "Aucun utilisateur trouvé"}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Pagination - masquée lors de la recherche */}
|
||||||
|
{!searchTerm && (
|
||||||
|
<div className="flex items-center justify-between space-x-2 py-4">
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Page {page} sur {totalPages} ({total} éléments au total)
|
||||||
|
</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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Info de recherche */}
|
||||||
|
{searchTerm && (
|
||||||
|
<div className="py-4 text-sm text-muted-foreground">
|
||||||
|
{users.length} résultat(s) trouvé(s) pour "{searchTerm}
|
||||||
|
"
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo, useEffect } from "react";
|
||||||
import { useCollection } from "@/hooks/useCollection";
|
import { useCollection } from "@/hooks/useCollection";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import {
|
import {
|
||||||
@@ -20,10 +20,15 @@ import { LibreChatUser, LibreChatBalance } from "@/lib/types";
|
|||||||
|
|
||||||
export function UsersTable() {
|
export function UsersTable() {
|
||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchInput, setSearchInput] = useState(""); // Ce que l'utilisateur tape
|
||||||
|
const [activeSearch, setActiveSearch] = useState(""); // Ce qui est réellement recherché
|
||||||
const limit = 20;
|
const limit = 20;
|
||||||
|
|
||||||
// Charger les utilisateurs
|
// Réinitialiser la page à 1 quand une nouvelle recherche est lancée
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1);
|
||||||
|
}, [activeSearch]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: users = [],
|
data: users = [],
|
||||||
total = 0,
|
total = 0,
|
||||||
@@ -31,11 +36,24 @@ export function UsersTable() {
|
|||||||
} = useCollection<LibreChatUser>("users", {
|
} = useCollection<LibreChatUser>("users", {
|
||||||
page,
|
page,
|
||||||
limit,
|
limit,
|
||||||
|
search: activeSearch,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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
|
// Charger tous les balances pour associer les crédits
|
||||||
const { data: balances = [] } = useCollection<LibreChatBalance>("balances", {
|
const { data: balances = [] } = useCollection<LibreChatBalance>("balances", {
|
||||||
limit: 1000, // Charger tous les balances
|
limit: 1000,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Créer une map des crédits par utilisateur
|
// Créer une map des crédits par utilisateur
|
||||||
@@ -47,20 +65,6 @@ export function UsersTable() {
|
|||||||
return map;
|
return map;
|
||||||
}, [balances]);
|
}, [balances]);
|
||||||
|
|
||||||
// Filtrer les utilisateurs selon le terme de recherche
|
|
||||||
const filteredUsers = useMemo(() => {
|
|
||||||
if (!searchTerm.trim()) {
|
|
||||||
return users;
|
|
||||||
}
|
|
||||||
|
|
||||||
const searchLower = searchTerm.toLowerCase();
|
|
||||||
return users.filter(
|
|
||||||
(user) =>
|
|
||||||
user.name?.toLowerCase().includes(searchLower) ||
|
|
||||||
user.email?.toLowerCase().includes(searchLower)
|
|
||||||
);
|
|
||||||
}, [users, searchTerm]);
|
|
||||||
|
|
||||||
const totalPages = Math.ceil(total / limit);
|
const totalPages = Math.ceil(total / limit);
|
||||||
|
|
||||||
const handlePrevPage = () => {
|
const handlePrevPage = () => {
|
||||||
@@ -93,17 +97,23 @@ export function UsersTable() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<div className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
|
<div className="flex flex-col space-y-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
|
||||||
<CardTitle>
|
<CardTitle>
|
||||||
Liste des utilisateurs ({searchTerm ? filteredUsers.length : total})
|
Liste des utilisateurs ({total})
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<div className="relative w-full sm:w-80">
|
<div className="flex gap-2 w-full sm:w-auto">
|
||||||
|
<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" />
|
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
placeholder="Rechercher par nom ou email..."
|
placeholder="Rechercher par nom ou email..."
|
||||||
value={searchTerm}
|
value={searchInput}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
|
onKeyPress={handleKeyPress}
|
||||||
className="pl-10"
|
className="pl-10"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<Button onClick={handleSearch} variant="default">
|
||||||
|
Rechercher
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@@ -121,12 +131,12 @@ export function UsersTable() {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{filteredUsers.length > 0 ? (
|
{users.length > 0 ? (
|
||||||
filteredUsers.map((user) => {
|
users.map((user) => {
|
||||||
const userCredits = creditsMap.get(user._id) || 0;
|
const userCredits = creditsMap.get(user._id) || 0;
|
||||||
const isActive =
|
const isActive =
|
||||||
new Date(user.updatedAt || user.createdAt) >
|
new Date(user.updatedAt || user.createdAt) >
|
||||||
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 jours en millisecondes
|
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableRow key={user._id}>
|
<TableRow key={user._id}>
|
||||||
@@ -176,8 +186,8 @@ export function UsersTable() {
|
|||||||
colSpan={7}
|
colSpan={7}
|
||||||
className="text-center py-8 text-muted-foreground"
|
className="text-center py-8 text-muted-foreground"
|
||||||
>
|
>
|
||||||
{searchTerm
|
{activeSearch
|
||||||
? `Aucun utilisateur trouvé pour "${searchTerm}"`
|
? `Aucun utilisateur trouvé pour "${activeSearch}"`
|
||||||
: "Aucun utilisateur trouvé"}
|
: "Aucun utilisateur trouvé"}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
@@ -186,11 +196,18 @@ export function UsersTable() {
|
|||||||
</Table>
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pagination - masquée lors de la recherche */}
|
{/* Pagination */}
|
||||||
{!searchTerm && (
|
|
||||||
<div className="flex items-center justify-between space-x-2 py-4">
|
<div className="flex items-center justify-between space-x-2 py-4">
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-sm text-muted-foreground">
|
||||||
Page {page} sur {totalPages} ({total} éléments au total)
|
{activeSearch ? (
|
||||||
|
<span>
|
||||||
|
{total} résultat(s) pour "{activeSearch}" - Page {page} sur {totalPages}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span>
|
||||||
|
Page {page} sur {totalPages} ({total} utilisateurs au total)
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex space-x-2">
|
<div className="flex space-x-2">
|
||||||
<Button
|
<Button
|
||||||
@@ -213,15 +230,6 @@ export function UsersTable() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Info de recherche */}
|
|
||||||
{searchTerm && (
|
|
||||||
<div className="py-4 text-sm text-muted-foreground">
|
|
||||||
{filteredUsers.length} résultat(s) trouvé(s) pour "{searchTerm}
|
|
||||||
"
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
73
hooks/useCollection.old.ts
Normal file
73
hooks/useCollection.old.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||||
|
|
||||||
|
interface UseCollectionOptions {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
filter?: Record<string, unknown>;
|
||||||
|
search?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CollectionResponse<T> {
|
||||||
|
data: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
totalPages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCollection<T = Record<string, unknown>>(
|
||||||
|
collectionName: string,
|
||||||
|
options: UseCollectionOptions = {}
|
||||||
|
) {
|
||||||
|
const [data, setData] = useState<T[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [totalPages, setTotalPages] = useState(0);
|
||||||
|
|
||||||
|
const { page = 1, limit = 20, filter = {}, search } = options;
|
||||||
|
|
||||||
|
// Mémoriser la chaîne JSON du filtre pour éviter les re-renders inutiles
|
||||||
|
const filterString = useMemo(() => JSON.stringify(filter), [filter]);
|
||||||
|
|
||||||
|
const fetchData = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
page: page.toString(),
|
||||||
|
limit: limit.toString(),
|
||||||
|
filter: filterString,
|
||||||
|
});
|
||||||
|
if (search) {
|
||||||
|
params.append("search", search);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/collections/${collectionName}?${params}`
|
||||||
|
);
|
||||||
|
if (!response.ok)
|
||||||
|
throw new Error(`Erreur lors du chargement de ${collectionName}`);
|
||||||
|
|
||||||
|
const result: CollectionResponse<T> = await response.json();
|
||||||
|
setData(result.data);
|
||||||
|
setTotal(result.total);
|
||||||
|
setTotalPages(result.totalPages);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Erreur inconnue");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [collectionName, page, limit, filterString]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchData();
|
||||||
|
}, [fetchData]);
|
||||||
|
|
||||||
|
const refetch = useCallback(() => {
|
||||||
|
return fetchData();
|
||||||
|
}, [fetchData]);
|
||||||
|
|
||||||
|
return { data, loading, error, total, totalPages, refetch };
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||||
|
|
||||||
interface UseCollectionOptions {
|
interface UseCollectionOptions {
|
||||||
page?: number;
|
page?: number;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
filter?: Record<string, unknown>;
|
filter?: Record<string, unknown>;
|
||||||
|
search?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CollectionResponse<T> {
|
interface CollectionResponse<T> {
|
||||||
@@ -26,7 +27,7 @@ export function useCollection<T = Record<string, unknown>>(
|
|||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [totalPages, setTotalPages] = useState(0);
|
const [totalPages, setTotalPages] = useState(0);
|
||||||
|
|
||||||
const { page = 1, limit = 20, filter = {} } = options;
|
const { page = 1, limit = 20, filter = {}, search } = options;
|
||||||
|
|
||||||
// Mémoriser la chaîne JSON du filtre pour éviter les re-renders inutiles
|
// Mémoriser la chaîne JSON du filtre pour éviter les re-renders inutiles
|
||||||
const filterString = useMemo(() => JSON.stringify(filter), [filter]);
|
const filterString = useMemo(() => JSON.stringify(filter), [filter]);
|
||||||
@@ -37,22 +38,28 @@ export function useCollection<T = Record<string, unknown>>(
|
|||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
page: page.toString(),
|
page: page.toString(),
|
||||||
limit: limit.toString(),
|
limit: limit.toString(),
|
||||||
filter: filterString
|
filter: filterString,
|
||||||
});
|
});
|
||||||
|
if (search) {
|
||||||
|
params.append("search", search);
|
||||||
|
}
|
||||||
|
|
||||||
const response = await fetch(`/api/collections/${collectionName}?${params}`);
|
const response = await fetch(
|
||||||
if (!response.ok) throw new Error(`Erreur lors du chargement de ${collectionName}`);
|
`/api/collections/${collectionName}?${params}`
|
||||||
|
);
|
||||||
|
if (!response.ok)
|
||||||
|
throw new Error(`Erreur lors du chargement de ${collectionName}`);
|
||||||
|
|
||||||
const result: CollectionResponse<T> = await response.json();
|
const result: CollectionResponse<T> = await response.json();
|
||||||
setData(result.data);
|
setData(result.data);
|
||||||
setTotal(result.total);
|
setTotal(result.total);
|
||||||
setTotalPages(result.totalPages);
|
setTotalPages(result.totalPages);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Erreur inconnue');
|
setError(err instanceof Error ? err.message : "Erreur inconnue");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [collectionName, page, limit, filterString]);
|
}, [collectionName, page, limit, filterString, search]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData();
|
fetchData();
|
||||||
|
|||||||
73
hooks/useCollection.ts.bak
Normal file
73
hooks/useCollection.ts.bak
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback, useMemo } from "react";
|
||||||
|
|
||||||
|
interface UseCollectionOptions {
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
filter?: Record<string, unknown>;
|
||||||
|
search?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CollectionResponse<T> {
|
||||||
|
data: T[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
limit: number;
|
||||||
|
totalPages: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCollection<T = Record<string, unknown>>(
|
||||||
|
collectionName: string,
|
||||||
|
options: UseCollectionOptions = {}
|
||||||
|
) {
|
||||||
|
const [data, setData] = useState<T[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [totalPages, setTotalPages] = useState(0);
|
||||||
|
|
||||||
|
const { page = 1, limit = 20, filter = {}, search } = options;
|
||||||
|
|
||||||
|
// Mémoriser la chaîne JSON du filtre pour éviter les re-renders inutiles
|
||||||
|
const filterString = useMemo(() => JSON.stringify(filter), [filter]);
|
||||||
|
|
||||||
|
const fetchData = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
page: page.toString(),
|
||||||
|
limit: limit.toString(),
|
||||||
|
filter: filterString,
|
||||||
|
});
|
||||||
|
if (search) {
|
||||||
|
params.append("search", search);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/collections/${collectionName}?${params}`
|
||||||
|
);
|
||||||
|
if (!response.ok)
|
||||||
|
throw new Error(`Erreur lors du chargement de ${collectionName}`);
|
||||||
|
|
||||||
|
const result: CollectionResponse<T> = await response.json();
|
||||||
|
setData(result.data);
|
||||||
|
setTotal(result.total);
|
||||||
|
setTotalPages(result.totalPages);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Erreur inconnue");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [collectionName, page, limit, filterString]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchData();
|
||||||
|
}, [fetchData]);
|
||||||
|
|
||||||
|
const refetch = useCallback(() => {
|
||||||
|
return fetchData();
|
||||||
|
}, [fetchData]);
|
||||||
|
|
||||||
|
return { data, loading, error, total, totalPages, refetch };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user