first commit

This commit is contained in:
nBiqoz
2025-10-05 16:10:35 +02:00
parent 201fca4e68
commit 13cd637391
70 changed files with 7287 additions and 130 deletions

View File

@@ -0,0 +1,55 @@
"use client";
import { CollectionTable } from "@/components/collections/collection-table";
import { Badge } from "@/components/ui/badge";
import { Agent } from "@/lib/types";
export function AgentsTable() {
const columns = [
{
key: "_id",
label: "ID",
render: (value: unknown) => (
<span className="font-mono text-xs">{String(value).slice(-8)}</span>
)
},
{
key: "name",
label: "Nom",
render: (value: unknown) => (
<span className="font-semibold">{String(value)}</span>
)
},
{
key: "description",
label: "Description",
render: (value: unknown) => (
<span className="max-w-xs truncate">{String(value) || '-'}</span>
)
},
{
key: "category",
label: "Catégorie",
render: (value: unknown) => (
<Badge variant="outline">{String(value)}</Badge>
)
},
{
key: "isActive",
label: "Statut",
render: (value: unknown) => (
<Badge variant={value ? 'default' : 'destructive'}>
{value ? 'Actif' : 'Inactif'}
</Badge>
)
}
];
return (
<CollectionTable<Agent>
collectionName="agents"
title="Liste des agents"
columns={columns}
/>
);
}

View File

@@ -0,0 +1,107 @@
"use client";
import { useState } from "react";
import { CollectionTable } from "@/components/collections/collection-table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CollectionItem } from "@/lib/types";
const COLLECTIONS = [
"accessroles",
"aclentries",
"actions",
"agentcategories",
"agents",
"assistants",
"balances",
"banners",
"conversations",
"conversationtags",
"files",
"groups",
"keys",
"memoryentries",
"messages",
"pluginauths",
"presets",
"projects",
"promptgroups",
"prompts",
"roles",
"sessions",
"sharedlinks",
"tokens",
"toolcalls",
"transactions",
"users",
];
export function CollectionSelector() {
const [selectedCollection, setSelectedCollection] = useState<string>("users");
// Colonnes génériques pour toutes les collections
const genericColumns = [
{
key: "_id",
label: "ID",
render: (value: unknown) => (
<span className="font-mono text-xs">{String(value).slice(-8)}</span>
),
},
{
key: "name",
label: "Nom",
render: (value: unknown) => String(value) || "-",
},
{
key: "email",
label: "Email",
render: (value: unknown) => String(value) || "-",
},
{
key: "createdAt",
label: "Créé le",
render: (value: unknown) => {
if (!value) return "-";
try {
return new Date(String(value)).toLocaleDateString("fr-FR");
} catch {
return String(value);
}
},
},
];
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Sélectionner une collection</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
{COLLECTIONS.map((collection) => (
<Button
key={collection}
variant={
selectedCollection === collection ? "default" : "outline"
}
size="sm"
onClick={() => setSelectedCollection(collection)}
className="text-xs"
>
{collection}
</Button>
))}
</div>
</CardContent>
</Card>
<CollectionTable<CollectionItem>
collectionName={selectedCollection}
title={`Collection: ${selectedCollection}`}
columns={genericColumns}
/>
</div>
);
}

View File

@@ -0,0 +1,123 @@
"use client";
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 { ChevronLeft, ChevronRight } from "lucide-react";
import { useState } from "react";
interface CollectionTableProps<T = Record<string, unknown>> {
collectionName: string;
title: string;
columns: Array<{
key: string;
label: string;
render?: (value: unknown, item: T) => React.ReactNode;
}>;
}
export function CollectionTable<T extends Record<string, unknown>>({
collectionName,
title,
columns
}: CollectionTableProps<T>) {
const [page, setPage] = useState(1);
const { data, loading, error, total, totalPages } = useCollection<T>(
collectionName,
{ page, limit: 20 }
);
if (loading) {
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="h-12 bg-muted animate-pulse rounded" />
))}
</div>
</CardContent>
</Card>
);
}
if (error) {
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-muted-foreground">
Erreur: {error}
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>{title} ({total} éléments)</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
{columns.map((column) => (
<TableHead key={column.key}>{column.label}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{data.map((item, index) => (
<TableRow key={(item as { _id?: string })._id || index}>
{columns.map((column) => (
<TableCell key={column.key}>
{column.render
? column.render(item[column.key], item)
: String(item[column.key] || '-')
}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
{totalPages > 1 && (
<div className="flex items-center justify-between mt-4">
<p className="text-sm text-muted-foreground">
Page {page} sur {totalPages}
</p>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => Math.max(1, p - 1))}
disabled={page === 1}
>
<ChevronLeft className="h-4 w-4" />
Précédent
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage(p => Math.min(totalPages, p + 1))}
disabled={page === totalPages}
>
Suivant
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,561 @@
"use client";
import { useState } 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 {
ChevronLeft,
ChevronRight,
Users,
MessageSquare,
Calendar,
X,
User,
Bot,
} from "lucide-react";
import { formatDate } from "@/lib/utils";
import {
LibreChatConversation,
LibreChatUser,
LibreChatMessage,
} from "@/lib/types";
// Types pour les messages étendus
interface ExtendedMessage extends LibreChatMessage {
content?: Array<{ type: string; text: string }> | string;
message?: Record<string, unknown>;
parts?: Array<string | { text: string }>;
metadata?: { text?: string };
[key: string]: unknown;
}
export function ConversationsTable() {
const [page, setPage] = useState(1);
const [selectedConversationId, setSelectedConversationId] = useState<
string | null
>(null);
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
const limit = 10;
// Charger toutes les conversations pour le groupement côté client
const {
data: conversations = [],
total = 0,
loading,
} = useCollection<LibreChatConversation>("conversations", {
limit: 1000,
page: 1, // Remplacer skip par page
});
const { data: users = [] } = useCollection<LibreChatUser>("users", {
limit: 1000,
});
// Charger les messages seulement si une conversation est sélectionnée
const { data: messages = [] } = useCollection<LibreChatMessage>("messages", {
limit: 1000,
filter: selectedConversationId
? { conversationId: selectedConversationId }
: {},
});
const userMap = new Map(users.map((user) => [user._id, user]));
const getUserDisplayName = (userId: string): string => {
if (userId === "unknown") return "Utilisateur inconnu";
const user = userMap.get(userId);
if (user) {
return (
user.name ||
user.username ||
user.email ||
`Utilisateur ${userId.slice(-8)}`
);
}
return `Utilisateur ${userId.slice(-8)}`;
};
const getUserEmail = (userId: string): string | null => {
if (userId === "unknown") return null;
const user = userMap.get(userId);
return user?.email || null;
};
// Fonction améliorée pour extraire le contenu du message
const getMessageContent = (message: LibreChatMessage): string => {
// Fonction helper pour nettoyer le texte
const cleanText = (text: string): string => {
return text.trim().replace(/\n\s*\n/g, "\n");
};
// 1. Vérifier le tableau content (structure LibreChat)
const messageObj = message as ExtendedMessage;
if (messageObj.content && Array.isArray(messageObj.content)) {
for (const contentItem of messageObj.content) {
if (
contentItem &&
typeof contentItem === "object" &&
contentItem.text
) {
return cleanText(contentItem.text);
}
}
}
// 2. Essayer le champ text principal
if (
message.text &&
typeof message.text === "string" &&
message.text.trim()
) {
return cleanText(message.text);
}
// 3. Essayer le champ content (format legacy string)
if (
messageObj.content &&
typeof messageObj.content === "string" &&
messageObj.content.trim()
) {
return cleanText(messageObj.content);
}
// 4. Vérifier s'il y a des propriétés imbriquées
if (message.message && typeof message.message === "object") {
const nestedMessage = message.message as Record<string, unknown>;
if (nestedMessage.content && typeof nestedMessage.content === "string") {
return cleanText(nestedMessage.content);
}
if (nestedMessage.text && typeof nestedMessage.text === "string") {
return cleanText(nestedMessage.text);
}
}
// 5. Vérifier les propriétés spécifiques à LibreChat
// Parfois le contenu est dans une propriété 'parts'
if (
messageObj.parts &&
Array.isArray(messageObj.parts) &&
messageObj.parts.length > 0
) {
const firstPart = messageObj.parts[0];
if (typeof firstPart === "string") {
return cleanText(firstPart);
}
if (firstPart && typeof firstPart === "object" && firstPart.text) {
return cleanText(firstPart.text);
}
}
// 6. Vérifier si c'est un message avec des métadonnées
if (messageObj.metadata && messageObj.metadata.text) {
return cleanText(messageObj.metadata.text);
}
// 7. Vérifier les propriétés alternatives
const alternativeFields = ["body", "messageText", "textContent", "data"];
for (const field of alternativeFields) {
const value = messageObj[field];
if (value && typeof value === "string" && value.trim()) {
return cleanText(value);
}
}
// Debug: afficher la structure du message si aucun contenu n'est trouvé
console.log("Message sans contenu trouvé:", {
messageId: message.messageId,
isCreatedByUser: message.isCreatedByUser,
keys: Object.keys(messageObj),
content: messageObj.content,
text: messageObj.text,
});
return "Contenu non disponible";
};
const handleShowMessages = (conversationId: string, userId: string) => {
if (
selectedConversationId === conversationId &&
selectedUserId === userId
) {
setSelectedConversationId(null);
setSelectedUserId(null);
} else {
setSelectedConversationId(conversationId);
setSelectedUserId(userId);
}
};
const handleCloseMessages = () => {
setSelectedConversationId(null);
setSelectedUserId(null);
};
const getStatus = (conversation: LibreChatConversation) => {
if (conversation.isArchived) return "archived";
return "active";
};
const getStatusLabel = (status: string) => {
switch (status) {
case "archived":
return "Archivée";
case "active":
return "Active";
default:
return "Inconnue";
}
};
const getStatusVariant = (status: string) => {
switch (status) {
case "archived":
return "outline" as const;
case "active":
return "default" as const;
default:
return "secondary" as const;
}
};
if (loading) {
return (
<Card>
<CardContent className="p-6">
<div className="text-center">Chargement des conversations...</div>
</CardContent>
</Card>
);
}
// Grouper les conversations par utilisateur
const groupedConversations = conversations.reduce((acc, conversation) => {
const userId = conversation.user || "unknown";
if (!acc[userId]) {
acc[userId] = [];
}
acc[userId].push(conversation);
return acc;
}, {} as Record<string, LibreChatConversation[]>);
// Pagination des groupes d'utilisateurs
const totalPages = Math.ceil(
Object.keys(groupedConversations).length / limit
);
const skip = (page - 1) * limit;
const userIds = Object.keys(groupedConversations).slice(skip, skip + limit);
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
Conversations par utilisateur
</CardTitle>
<p className="text-sm text-muted-foreground">
{Object.keys(groupedConversations).length} utilisateurs {" "}
{conversations.length} conversations au total
</p>
</CardHeader>
<CardContent>
<div className="space-y-6">
{userIds.map((userId) => {
const conversations = groupedConversations[userId];
const totalMessages = conversations.reduce(
(sum, conv) => sum + (conv.messages?.length || 0),
0
);
const activeConversations = conversations.filter(
(conv) => !conv.isArchived
).length;
const archivedConversations = conversations.filter(
(conv) => conv.isArchived
).length;
const userName = getUserDisplayName(userId);
const userEmail = getUserEmail(userId);
return (
<div key={userId} className="border rounded-lg p-4">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Badge variant="outline" className="font-mono text-xs">
{userId === "unknown" ? "unknown" : userId.slice(-8)}
</Badge>
<div className="flex flex-col">
<span className="font-semibold">{userName}</span>
{userEmail && (
<span className="text-xs text-muted-foreground">
{userEmail}
</span>
)}
</div>
<Badge variant="secondary">
{conversations.length} conversation
{conversations.length > 1 ? "s" : ""}
</Badge>
{activeConversations > 0 && (
<Badge variant="default" className="text-xs">
{activeConversations} actives
</Badge>
)}
{archivedConversations > 0 && (
<Badge variant="outline" className="text-xs">
{archivedConversations} archivées
</Badge>
)}
</div>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
<div className="flex items-center gap-1">
<MessageSquare className="h-4 w-4" />
{totalMessages} message{totalMessages > 1 ? "s" : ""}
</div>
<div className="flex items-center gap-1">
<Calendar className="h-4 w-4" />
Dernière:{" "}
{formatDate(
new Date(
Math.max(
...conversations.map((c) =>
new Date(c.updatedAt).getTime()
)
)
)
)}
</div>
</div>
</div>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Titre</TableHead>
<TableHead>Endpoint</TableHead>
<TableHead>Modèle</TableHead>
<TableHead>Messages</TableHead>
<TableHead>Statut</TableHead>
<TableHead>Créée le</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{conversations
.sort(
(a, b) =>
new Date(b.updatedAt).getTime() -
new Date(a.updatedAt).getTime()
)
.map((conversation) => {
const status = getStatus(conversation);
const messageCount =
conversation.messages?.length || 0;
return (
<TableRow key={conversation._id}>
<TableCell>
<span className="font-mono text-xs">
{String(conversation._id).slice(-8)}
</span>
</TableCell>
<TableCell>
<span className="max-w-xs truncate block">
{String(conversation.title) || "Sans titre"}
</span>
</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{String(conversation.endpoint).slice(0, 20)}
{String(conversation.endpoint).length > 20
? "..."
: ""}
</Badge>
</TableCell>
<TableCell>
<span className="text-xs text-muted-foreground font-mono">
{String(conversation.model)}
</span>
</TableCell>
<TableCell>
<Badge
variant="outline"
className="text-xs cursor-pointer hover:bg-primary hover:text-primary-foreground transition-colors"
onClick={() =>
handleShowMessages(
conversation.conversationId,
userId
)
}
>
{messageCount}
</Badge>
</TableCell>
<TableCell>
<Badge
variant={getStatusVariant(status)}
className="text-xs"
>
{getStatusLabel(status)}
</Badge>
</TableCell>
<TableCell>
<span className="text-xs text-muted-foreground">
{formatDate(conversation.createdAt)}
</span>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
{/* Section des messages pour cet utilisateur */}
{selectedConversationId && selectedUserId === userId && (
<div className="mt-6 border-t pt-6">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
<MessageSquare className="h-5 w-5" />
Messages de la conversation
</h3>
<Button
variant="outline"
size="sm"
onClick={handleCloseMessages}
>
<X className="h-4 w-4" />
Fermer
</Button>
</div>
<p className="text-sm text-muted-foreground mb-4">
Conversation ID: {selectedConversationId}
</p>
<div className="space-y-4 max-h-96 overflow-y-auto border rounded-lg p-4 bg-gray-50">
{messages.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
Aucun message trouvé pour cette conversation
</p>
) : (
messages
.sort(
(a, b) =>
new Date(a.createdAt).getTime() -
new Date(b.createdAt).getTime()
)
.map((message) => {
const content = getMessageContent(message);
return (
<div
key={message._id}
className={`flex gap-3 p-4 rounded-lg ${
message.isCreatedByUser
? "bg-blue-50 border-l-4 border-l-blue-500"
: "bg-white border-l-4 border-l-gray-500"
}`}
>
<div className="flex-shrink-0">
{message.isCreatedByUser ? (
<User className="h-5 w-5 text-blue-600" />
) : (
<Bot className="h-5 w-5 text-gray-600" />
)}
</div>
<div className="flex-1 space-y-2">
<div className="flex items-center gap-2">
<Badge
variant={
message.isCreatedByUser
? "default"
: "secondary"
}
className="text-xs"
>
{message.isCreatedByUser
? "Utilisateur"
: "Assistant"}
</Badge>
<span className="text-xs text-muted-foreground">
{formatDate(message.createdAt)}
</span>
{message.tokenCount > 0 && (
<Badge
variant="outline"
className="text-xs"
>
{message.tokenCount} tokens
</Badge>
)}
<Badge
variant="outline"
className="text-xs font-mono"
>
{message._id.slice(-8)}
</Badge>
</div>
<div className="text-sm whitespace-pre-wrap">
{content}
</div>
{message.error && (
<Badge
variant="destructive"
className="text-xs"
>
Erreur
</Badge>
)}
</div>
</div>
);
})
)}
</div>
</div>
)}
</div>
);
})}
</div>
{totalPages > 1 && (
<div className="flex items-center justify-between mt-6">
<p className="text-sm text-muted-foreground">
Page {page} sur {totalPages} {total} conversations au total
</p>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setPage(page - 1)}
disabled={page === 1}
>
<ChevronLeft className="h-4 w-4" />
Précédent
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setPage(page + 1)}
disabled={page === totalPages}
>
Suivant
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,304 @@
"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 { ChevronLeft, ChevronRight, User, Bot } from "lucide-react";
import { formatDate } from "@/lib/utils";
import {
LibreChatMessage,
LibreChatUser,
LibreChatConversation,
} from "@/lib/types";
// Définir des interfaces pour les types de contenu
interface MessageContentItem {
text?: string;
content?: string;
type?: string;
}
interface MessagePart {
text?: string;
content?: string;
type?: string;
}
interface MessageWithParts extends LibreChatMessage {
parts?: MessagePart[];
content?: MessageContentItem[] | string;
}
export function MessagesTable() {
const [page, setPage] = useState(1);
const limit = 20;
// Charger les messages
const {
data: messages = [],
total = 0,
loading: messagesLoading,
} = useCollection<LibreChatMessage>("messages", {
page,
limit,
});
// Charger les utilisateurs pour les noms
const { data: users = [] } = useCollection<LibreChatUser>("users", {
limit: 1000,
});
// Charger les conversations pour les titres
const { data: conversations = [] } = useCollection<LibreChatConversation>(
"conversations",
{
limit: 1000,
}
);
// Créer des maps pour les lookups
const userMap = useMemo(() => {
return new Map(users.map((user) => [user._id, user]));
}, [users]);
const conversationMap = useMemo(() => {
return new Map(
conversations.map((conv) => [conv.conversationId || conv._id, conv])
);
}, [conversations]);
const totalPages = Math.ceil(total / limit);
const handlePrevPage = () => {
setPage((prev) => Math.max(1, prev - 1));
};
const handleNextPage = () => {
setPage((prev) => Math.min(totalPages, prev + 1));
};
// Fonction pour extraire le contenu du message
const getMessageContent = (message: LibreChatMessage): string => {
try {
// Vérifier le champ text principal
if (message.text && typeof message.text === "string") {
return message.text.trim();
}
// Traiter le message comme ayant potentiellement des parties
const messageWithParts = message as MessageWithParts;
// Vérifier le champ content (peut être un array ou string)
if (messageWithParts.content) {
if (typeof messageWithParts.content === "string") {
return messageWithParts.content.trim();
}
if (Array.isArray(messageWithParts.content)) {
// Extraire le texte des objets content
const textContent = messageWithParts.content
.map((item: MessageContentItem | string) => {
if (typeof item === "string") return item;
if (item && typeof item === "object" && item.text)
return item.text;
if (item && typeof item === "object" && item.content)
return item.content;
return "";
})
.filter(Boolean)
.join(" ");
if (textContent.trim()) return textContent.trim();
}
}
// Vérifier les propriétés alternatives
if (messageWithParts.parts && Array.isArray(messageWithParts.parts)) {
const textContent = messageWithParts.parts
.map((part: MessagePart) => {
if (typeof part === "string") return part;
if (part && typeof part === "object" && part.text) return part.text;
return "";
})
.filter(Boolean)
.join(" ");
if (textContent.trim()) return textContent.trim();
}
return "Contenu non disponible";
} catch (error) {
console.error("Erreur lors de l'extraction du contenu:", error);
return "Erreur de lecture du contenu";
}
};
// Fonction pour obtenir le nom d'utilisateur
const getUserName = (userId: string): string => {
if (!userId || userId === "undefined") return "Utilisateur inconnu";
const user = userMap.get(userId);
return user?.name || user?.email || `Utilisateur ${userId.slice(-8)}`;
};
// Fonction pour obtenir le titre de la conversation
const getConversationTitle = (conversationId: string): string => {
if (!conversationId || conversationId === "undefined")
return "Conversation inconnue";
const conversation = conversationMap.get(conversationId);
if (conversation && conversation.title) {
return conversation.title;
}
return `Conversation ${conversationId.slice(-6)}`;
};
if (messagesLoading) {
return (
<Card>
<CardHeader>
<CardTitle>Messages</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>
<CardTitle>Messages récents ({total})</CardTitle>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Conversation</TableHead>
<TableHead>Utilisateur</TableHead>
<TableHead>Rôle</TableHead>
<TableHead>Contenu</TableHead>
<TableHead>Tokens</TableHead>
<TableHead>Créé le</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{messages.map((message) => {
const content = getMessageContent(message);
const userName = getUserName(message.user);
const conversationTitle = getConversationTitle(
message.conversationId
);
const isUser = message.isCreatedByUser;
return (
<TableRow key={message._id}>
<TableCell>
<span className="font-mono text-xs">
{message._id.slice(-8)}
</span>
</TableCell>
<TableCell>
<div className="max-w-xs">
<span className="font-mono text-xs text-muted-foreground">
{message.conversationId?.slice(-8) || "N/A"}
</span>
<div className="text-sm truncate">
{conversationTitle}
</div>
</div>
</TableCell>
<TableCell>
<div className="max-w-xs">
<span className="font-mono text-xs text-muted-foreground">
{message.user?.slice(-8) || "N/A"}
</span>
<div className="text-sm truncate">{userName}</div>
</div>
</TableCell>
<TableCell>
<Badge
variant={isUser ? "default" : "secondary"}
className="flex items-center gap-1"
>
{isUser ? (
<User className="h-3 w-3" />
) : (
<Bot className="h-3 w-3" />
)}
{isUser ? "Utilisateur" : "Assistant"}
</Badge>
</TableCell>
<TableCell>
<div className="max-w-md">
<p className="text-sm truncate">
{content.length > 100
? `${content.substring(0, 100)}...`
: content}
</p>
</div>
</TableCell>
<TableCell>
{message.tokenCount > 0 && (
<Badge variant="outline" className="text-xs">
{message.tokenCount}
</Badge>
)}
</TableCell>
<TableCell>
<span className="text-sm text-muted-foreground">
{formatDate(new Date(message.createdAt))}
</span>
</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">
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>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,53 @@
"use client";
import { CollectionTable } from "@/components/collections/collection-table";
import { Badge } from "@/components/ui/badge";
import { AccessRole } from "@/lib/types";
export function RolesTable() {
const columns = [
{
key: "_id",
label: "ID",
render: (value: unknown) => (
<span className="font-mono text-xs">{String(value).slice(-8)}</span>
),
},
{
key: "name",
label: "Nom du rôle",
render: (value: unknown) => (
<span className="font-semibold">{String(value)}</span>
),
},
{
key: "permissions",
label: "Permissions",
render: (value: unknown) => {
if (!Array.isArray(value)) return "-";
return (
<div className="flex flex-wrap gap-1">
{value.slice(0, 3).map((permission, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{String(permission)}
</Badge>
))}
{value.length > 3 && (
<Badge variant="outline" className="text-xs">
+{value.length - 3}
</Badge>
)}
</div>
);
},
},
];
return (
<CollectionTable<AccessRole>
collectionName="accessroles"
title="Liste des rôles"
columns={columns}
/>
);
}

View File

@@ -0,0 +1,213 @@
"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 { ChevronLeft, ChevronRight } from "lucide-react";
import { formatDate, formatCurrency } from "@/lib/utils";
import { LibreChatTransaction, LibreChatUser } from "@/lib/types";
// Interface étendue pour les transactions avec description optionnelle
interface TransactionWithDescription extends LibreChatTransaction {
description?: string;
}
export function TransactionsTable() {
const { data: transactions, loading } =
useCollection<LibreChatTransaction>("transactions");
const { data: users } = useCollection<LibreChatUser>("users");
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
// Créer une map pour les lookups rapides des utilisateurs
const usersMap = useMemo(() => {
if (!users) return new Map();
return new Map(users.map((user) => [user._id, user]));
}, [users]);
const totalPages = Math.ceil((transactions?.length || 0) / itemsPerPage);
const handlePrevPage = () => {
setCurrentPage((prev) => Math.max(1, prev - 1));
};
const handleNextPage = () => {
setCurrentPage((prev) => Math.min(totalPages, prev + 1));
};
// Fonction pour obtenir le nom d'utilisateur
const getUserName = (userId: string): string => {
if (!userId || userId === "undefined") return "Utilisateur inconnu";
const user = usersMap.get(userId);
return user?.name || user?.email || `Utilisateur ${userId.slice(-8)}`;
};
// Fonction pour formater le montant en euros
const formatAmount = (rawAmount: number): string => {
// Convertir les tokens en euros (exemple: 1000 tokens = 1 euro)
const euros = rawAmount / 1000;
return formatCurrency(euros);
};
// Fonction pour obtenir la description
const getDescription = (transaction: LibreChatTransaction): string => {
const transactionWithDesc = transaction as TransactionWithDescription;
if (transactionWithDesc.description &&
typeof transactionWithDesc.description === 'string' &&
transactionWithDesc.description !== "undefined") {
return transactionWithDesc.description;
}
// Générer une description basée sur le type et le montant
const amount = Math.abs(Number(transaction.rawAmount) || 0);
if (amount > 0) {
return `Consommation de ${amount.toLocaleString()} tokens`;
}
return "Transaction sans description";
};
if (loading) {
return (
<Card>
<CardHeader>
<CardTitle>Transactions</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>
<CardTitle>
Transactions récentes ({transactions?.length || 0})
</CardTitle>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Utilisateur</TableHead>
<TableHead>Type</TableHead>
<TableHead>Montant</TableHead>
<TableHead>Tokens</TableHead>
<TableHead>Description</TableHead>
<TableHead>Date</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{transactions
?.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage
)
.map((transaction) => {
const userName = getUserName(transaction.user);
const description = getDescription(transaction);
const tokenAmount = Math.abs(
Number(transaction.rawAmount) || 0
);
const isCredit = Number(transaction.rawAmount) > 0;
return (
<TableRow key={transaction._id}>
<TableCell>
<span className="font-mono text-xs">
{transaction._id.slice(-8)}
</span>
</TableCell>
<TableCell>
<div className="max-w-xs">
<span className="font-mono text-xs text-muted-foreground">
{transaction.user?.slice(-8) || "N/A"}
</span>
<div className="text-sm truncate">{userName}</div>
</div>
</TableCell>
<TableCell>
<Badge variant={isCredit ? "default" : "destructive"}>
{isCredit ? "Crédit" : "Débit"}
</Badge>
</TableCell>
<TableCell>
<span className="font-semibold">
{formatAmount(transaction.rawAmount)}
</span>
</TableCell>
<TableCell>
{tokenAmount > 0 && (
<Badge variant="outline" className="text-xs">
{tokenAmount.toLocaleString()} tokens
</Badge>
)}
</TableCell>
<TableCell>
<span className="max-w-xs truncate block text-sm">
{description}
</span>
</TableCell>
<TableCell>
<span className="text-sm text-muted-foreground">
{formatDate(new Date(transaction.createdAt))}
</span>
</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">
Page {currentPage} sur {totalPages} ({transactions?.length || 0}{" "}
éléments au total)
</div>
<div className="flex space-x-2">
<Button
variant="outline"
size="sm"
onClick={handlePrevPage}
disabled={currentPage <= 1}
>
<ChevronLeft className="h-4 w-4" />
Précédent
</Button>
<Button
variant="outline"
size="sm"
onClick={handleNextPage}
disabled={currentPage >= totalPages}
>
Suivant
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,170 @@
"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 { ChevronLeft, ChevronRight } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { LibreChatUser, LibreChatBalance } from "@/lib/types";
export function UsersTable() {
const [page, setPage] = useState(1);
const limit = 20;
// Charger les utilisateurs
const {
data: users = [],
total = 0,
loading: usersLoading,
} = useCollection<LibreChatUser>("users", {
page,
limit,
});
// 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>
<CardTitle>Liste des utilisateurs ({total})</CardTitle>
</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.map((user) => {
const userCredits = creditsMap.get(user._id) || 0;
const isActive = new Date(user.updatedAt || user.createdAt) >
new Date(Date.now() - 5 * 60 * 1000); // 5 minutes 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>
<Badge variant={isActive ? 'default' : 'destructive'}>
{isActive ? 'Actif' : 'Inactif'}
</Badge>
</TableCell>
<TableCell>
<span className="text-sm text-muted-foreground">
{formatDate(new Date(user.createdAt))}
</span>
</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">
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>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from "recharts";
interface ModelDistributionChartProps {
title: string;
data: Array<{
name: string;
value: number;
}>;
}
interface TooltipPayload {
value: number;
payload: {
name: string;
value: number;
};
}
interface CustomTooltipProps {
active?: boolean;
payload?: TooltipPayload[];
}
const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
if (active && payload && payload.length) {
return (
<div style={{
backgroundColor: "hsl(var(--background))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
padding: "8px",
fontSize: "12px"
}}>
<p style={{ margin: 0, color: "#ff0000" }}>
{`${payload[0].value.toLocaleString()} tokens`}
</p>
<p style={{ margin: 0, color: "#ff0000" }}>
{payload[0].payload.name}
</p>
</div>
);
}
return null;
};
export function ModelDistributionChart({
title,
data,
}: ModelDistributionChartProps) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{title}
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<ResponsiveContainer width="100%" height={200}>
<BarChart data={data}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted/20" />
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
tick={false}
/>
<YAxis
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
/>
<Tooltip content={<CustomTooltip />} />
<Bar
dataKey="value"
fill="#000000"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,58 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer
} from "recharts";
interface ModelUsageChartProps {
data: Record<string, number>;
}
export function ModelUsageChart({ data }: ModelUsageChartProps) {
const chartData = Object.entries(data).map(([model, usage]) => ({
model: model.replace('gpt-', 'GPT-').replace('claude-', 'Claude-'),
usage,
}));
return (
<Card>
<CardHeader>
<CardTitle className="text-base font-medium">Usage par modèle</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="model"
className="text-xs fill-muted-foreground"
angle={-45}
textAnchor="end"
height={60}
/>
<YAxis className="text-xs fill-muted-foreground" />
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--background))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
/>
<Bar
dataKey="usage"
fill="hsl(var(--primary))"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,110 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
PieChart,
Pie,
Cell,
ResponsiveContainer,
Tooltip,
Legend,
} from "recharts";
import { useUserActivity } from "@/hooks/useUserActivity";
import { AlertCircle } from "lucide-react";
export function RealUserActivityChart() {
const { activity, loading, error } = useUserActivity();
if (loading) {
return (
<Card>
<CardContent className="flex items-center justify-center h-64">
<div className="h-64 bg-muted animate-pulse rounded-lg w-full" />
</CardContent>
</Card>
);
}
if (error || !activity) {
return (
<Card>
<CardContent className="flex items-center justify-center h-64">
<div className="text-center">
<AlertCircle className="h-8 w-8 text-destructive mx-auto mb-2" />
<p className="text-sm text-muted-foreground">
Erreur lors du chargement
</p>
</div>
</CardContent>
</Card>
);
}
const data = [
{
name: "Utilisateurs actifs",
value: activity.activeUsers,
color: "#22c55e", // Vert clair pour actifs
},
{
name: "Utilisateurs inactifs",
value: activity.inactiveUsers,
color: "#ef4444", // Rouge pour inactifs
},
];
const total = activity.activeUsers + activity.inactiveUsers;
return (
<Card>
<CardHeader>
<CardTitle className="text-base font-medium">
Activité des utilisateurs
</CardTitle>
<p className="text-sm text-muted-foreground">
Actifs = connectés dans les 7 derniers jours
</p>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={data}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
paddingAngle={5}
dataKey="value"
>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--background))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
}}
formatter={(value: number) => [
`${value} utilisateurs (${((value / total) * 100).toFixed(
1
)}%)`,
"",
]}
/>
<Legend
formatter={(value, entry) => (
<span style={{ color: entry.color }}>
{value}: {entry.payload?.value} (
{((entry.payload?.value / total) * 100).toFixed(1)}%)
</span>
)}
/>
</PieChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,62 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer
} from "recharts";
interface SimpleBarChartProps {
title: string;
data: Array<{
name: string;
value: number;
}>;
color?: string;
}
export function SimpleBarChart({ title, data, color = "hsl(var(--primary))" }: SimpleBarChartProps) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">{title}</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<ResponsiveContainer width="100%" height={200}>
<BarChart data={data}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted/20" />
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
/>
<YAxis
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
/>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--background))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
fontSize: '12px'
}}
/>
<Bar
dataKey="value"
fill={color}
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,70 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer
} from "recharts";
interface SimpleStatsChartProps {
title: string;
data: Array<{
name: string;
value: number;
}>;
color?: string;
}
export function SimpleStatsChart({ title, data, color = "hsl(var(--primary))" }: SimpleStatsChartProps) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">{title}</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<ResponsiveContainer width="100%" height={200}>
<AreaChart data={data}>
<defs>
<linearGradient id="colorGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.3}/>
<stop offset="95%" stopColor={color} stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted/20" />
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
/>
<YAxis
axisLine={false}
tickLine={false}
className="text-xs fill-muted-foreground"
/>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--background))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
fontSize: '12px'
}}
/>
<Area
type="monotone"
dataKey="value"
stroke={color}
strokeWidth={2}
fill="url(#colorGradient)"
/>
</AreaChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,74 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer
} from "recharts";
interface UsageChartProps {
data: Array<{
date: string;
conversations: number;
tokens: number;
}>;
}
export function UsageChart({ data }: UsageChartProps) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base font-medium">Usage quotidien</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="date"
className="text-xs fill-muted-foreground"
tickFormatter={(value) => new Date(value).toLocaleDateString('fr-FR', {
month: 'short',
day: 'numeric'
})}
/>
<YAxis className="text-xs fill-muted-foreground" />
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--background))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
labelFormatter={(value) => new Date(value).toLocaleDateString('fr-FR')}
formatter={(value: number, name: string) => {
if (name === 'tokens') {
return [Math.round(value / 1000), "Tokens (k)"];
}
return [value, name];
}}
/>
<Line
type="monotone"
dataKey="conversations"
stroke="hsl(var(--primary))"
strokeWidth={2}
name="Conversations"
/>
<Line
type="monotone"
dataKey="tokens"
stroke="hsl(var(--destructive))"
strokeWidth={2}
name="tokens"
/>
</LineChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,81 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
PieChart,
Pie,
Cell,
ResponsiveContainer,
Tooltip,
Legend
} from "recharts";
interface UserActivityChartProps {
activeUsers: number;
inactiveUsers: number;
}
export function UserActivityChart({ activeUsers, inactiveUsers }: UserActivityChartProps) {
const data = [
{
name: 'Utilisateurs actifs',
value: activeUsers,
color: '#22c55e' // Vert clair pour actifs
},
{
name: 'Utilisateurs inactifs',
value: inactiveUsers,
color: '#ef4444' // Rouge pour inactifs
},
];
const total = activeUsers + inactiveUsers;
return (
<Card>
<CardHeader>
<CardTitle className="text-base font-medium">Activité des utilisateurs</CardTitle>
<p className="text-sm text-muted-foreground">
Actifs = connectés dans les 7 derniers jours
</p>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={data}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
paddingAngle={5}
dataKey="value"
>
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--background))',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
}}
formatter={(value: number) => [
`${value} utilisateurs (${((value / total) * 100).toFixed(1)}%)`,
''
]}
/>
<Legend
formatter={(value, entry) => (
<span style={{ color: entry.color }}>
{value}: {entry.payload?.value} ({((entry.payload?.value / total) * 100).toFixed(1)}%)
</span>
)}
/>
</PieChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,126 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Users,
MessageSquare,
CreditCard,
TrendingUp,
TrendingDown,
Activity,
} from "lucide-react";
import { cn } from "@/lib/utils";
interface MetricCardProps {
title: string;
value: string;
change?: {
value: number;
type: "increase" | "decrease";
};
icon: React.ComponentType<{ className?: string }>;
description?: string;
}
function MetricCard({
title,
value,
change,
icon: Icon,
description,
}: MetricCardProps) {
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{title}
</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{value}</div>
{description && (
<p className="text-xs text-muted-foreground mt-1">{description}</p>
)}
{change && (
<div className="flex items-center space-x-2 text-xs text-muted-foreground mt-1">
{change.type === "increase" ? (
<TrendingUp className="h-3 w-3 text-green-500" />
) : (
<TrendingDown className="h-3 w-3 text-red-500" />
)}
<span
className={cn(
change.type === "increase" ? "text-green-500" : "text-red-500"
)}
>
{change.type === "increase" ? "+" : "-"}
{change.value}%
</span>
<span>par rapport au mois dernier</span>
</div>
)}
</CardContent>
</Card>
);
}
interface MetricCardsProps {
metrics: {
totalUsers: number;
activeUsers: number;
totalConversations: number;
totalMessages: number;
totalTokensConsumed: number;
totalCreditsUsed: number;
};
}
export function MetricCards({ metrics }: MetricCardsProps) {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<MetricCard
title="Utilisateurs totaux"
value={metrics.totalUsers.toLocaleString()}
change={{ value: 12, type: "increase" }}
icon={Users}
description={`${metrics.activeUsers} actifs cette semaine`}
/>
<MetricCard
title="Conversations"
value={metrics.totalConversations.toLocaleString()}
change={{ value: 8, type: "increase" }}
icon={MessageSquare}
description={`${metrics.totalMessages.toLocaleString()} messages au total`}
/>
<MetricCard
title="Tokens consommés"
value={metrics.totalTokensConsumed.toLocaleString()}
change={{ value: 15, type: "increase" }}
icon={Activity}
description="Tokens utilisés au total"
/>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Crédits totaux
</CardTitle>
<CreditCard className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{metrics.totalCreditsUsed.toLocaleString()}
</div>
<p className="text-xs text-muted-foreground mt-1">
crédits disponibles
</p>
<div className="flex items-center space-x-2 text-xs text-muted-foreground mt-1">
<TrendingUp className="h-3 w-3 text-green-500" />
<span className="text-green-500">+23%</span>
<span>par rapport au mois dernier</span>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,62 @@
"use client";
import { useMetrics } from "@/hooks/useMetrics";
import { MetricCard } from "@/components/ui/metric-card";
import { Users, UserCheck, Shield, Coins, MessageSquare, FileText } from "lucide-react";
export function OverviewMetrics() {
const { metrics, loading, error } = useMetrics();
if (loading) {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="h-32 bg-muted animate-pulse rounded-lg" />
))}
</div>
);
}
if (error || !metrics) {
return (
<div className="text-center py-8 text-muted-foreground">
Erreur lors du chargement des métriques
</div>
);
}
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<MetricCard
title="Utilisateurs totaux"
value={metrics.totalUsers}
icon={Users}
/>
<MetricCard
title="Utilisateurs actifs"
value={metrics.activeUsers}
icon={UserCheck}
/>
<MetricCard
title="Administrateurs"
value={metrics.totalAdmins}
icon={Shield}
/>
<MetricCard
title="Crédits totaux"
value={metrics.totalCredits}
icon={Coins}
/>
<MetricCard
title="Conversations actives"
value={metrics.activeConversations}
icon={MessageSquare}
/>
<MetricCard
title="Messages totaux"
value={metrics.totalMessages}
icon={FileText}
/>
</div>
);
}

View File

@@ -0,0 +1,82 @@
"use client";
import { Card, CardContent } from "@/components/ui/card";
import { useStats } from "@/hooks/useStats";
import { SimpleStatsChart } from "./charts/simple-stats-chart";
import { ModelDistributionChart } from "./charts/model-distribution-chart";
import { AlertCircle } from "lucide-react";
export function RealTimeStats() {
const { stats, loading, error } = useStats();
if (loading) {
return (
<div className="grid gap-6 md:grid-cols-2">
<div className="h-64 bg-muted animate-pulse rounded-lg" />
<div className="h-64 bg-muted animate-pulse rounded-lg" />
</div>
);
}
if (error) {
return (
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardContent className="flex items-center justify-center h-64">
<div className="text-center">
<AlertCircle className="h-8 w-8 text-destructive mx-auto mb-2" />
<p className="text-sm text-muted-foreground">
Erreur lors du chargement des données
</p>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="flex items-center justify-center h-64">
<div className="text-center">
<AlertCircle className="h-8 w-8 text-destructive mx-auto mb-2" />
<p className="text-sm text-muted-foreground">
Erreur lors du chargement des données
</p>
</div>
</CardContent>
</Card>
</div>
);
}
if (!stats) {
return (
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardContent className="flex items-center justify-center h-64">
<p className="text-sm text-muted-foreground">
Aucune donnée disponible
</p>
</CardContent>
</Card>
<Card>
<CardContent className="flex items-center justify-center h-64">
<p className="text-sm text-muted-foreground">
Aucune donnée disponible
</p>
</CardContent>
</Card>
</div>
);
}
return (
<div className="grid gap-6 md:grid-cols-2">
<SimpleStatsChart
title="Tokens consommés par jour"
data={stats.dailyTokens}
color="hsl(var(--primary))"
/>
<ModelDistributionChart
title="Répartition par modèle"
data={stats.modelDistribution}
/>
</div>
);
}

View File

@@ -0,0 +1,62 @@
"use client";
import { useMetrics } from "@/hooks/useMetrics";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { formatDate } from "@/lib/utils";
export function RecentTransactions() {
const { metrics, loading } = useMetrics();
if (loading) {
return (
<Card>
<CardHeader>
<CardTitle>Transactions récentes</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>
<CardTitle>Transactions récentes</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{metrics?.recentTransactions.map((transaction) => (
<div
key={transaction._id}
className="flex items-center justify-between"
>
<div>
<p className="text-sm font-medium">{transaction.description}</p>
<p className="text-xs text-muted-foreground">
{formatDate(new Date(transaction.createdAt))}
</p>
</div>
<div className="flex items-center gap-2">
<Badge
variant={
transaction.type === "credit" ? "default" : "destructive"
}
>
{transaction.type === "credit" ? "+" : "-"}
{Math.abs(transaction.amount).toLocaleString()} tokens
</Badge>
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,331 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Users, MessageSquare, DollarSign, Activity } from "lucide-react";
import { useCollection } from "@/hooks/useCollection";
import {
LibreChatUser,
LibreChatConversation,
LibreChatTransaction,
LibreChatBalance,
} from "@/lib/types";
interface UsageStats {
totalUsers: number;
activeUsers: number;
totalConversations: number;
totalMessages: number;
totalTokensConsumed: number;
totalCreditsUsed: number;
averageTokensPerUser: number;
topUsers: Array<{
userId: string;
userName: string;
conversations: number;
tokens: number;
credits: number;
}>;
}
export function UsageAnalytics() {
const [stats, setStats] = useState<UsageStats | null>(null);
const [loading, setLoading] = useState(true);
const { data: users = [] } = useCollection<LibreChatUser>("users", { limit: 1000 });
const { data: conversations = [] } = useCollection<LibreChatConversation>("conversations", { limit: 1000 });
const { data: transactions = [] } = useCollection<LibreChatTransaction>("transactions", { limit: 1000 });
const { data: balances = [] } = useCollection<LibreChatBalance>("balances", { limit: 1000 });
const calculateStats = useCallback(() => {
if (!users.length) {
return;
}
setLoading(true);
// Console log pour débugger les données balances
console.log("=== DONNÉES BALANCES RÉCUPÉRÉES ===");
console.log("Nombre total d'entrées balances:", balances.length);
console.log("Toutes les entrées balances:", balances);
// NOUVEAU : Console log pour débugger les utilisateurs
console.log("=== DONNÉES UTILISATEURS ===");
console.log("Nombre total d'utilisateurs:", users.length);
console.log("Premiers 5 utilisateurs:", users.slice(0, 5));
// Analyser les doublons
const userCounts = new Map<string, number>();
balances.forEach(balance => {
const userId = balance.user;
userCounts.set(userId, (userCounts.get(userId) || 0) + 1);
});
const duplicateUsers = Array.from(userCounts.entries()).filter(([_, count]) => count > 1);
console.log("Utilisateurs avec plusieurs entrées:", duplicateUsers);
// Afficher quelques exemples d'entrées
console.log("Premières 5 entrées:", balances.slice(0, 5));
// Calculer le total brut (avec doublons)
const totalBrut = balances.reduce((sum, balance) => sum + (balance.tokenCredits || 0), 0);
console.log("Total brut (avec doublons potentiels):", totalBrut);
// NOUVEAU : Identifier les utilisateurs fantômes
console.log("=== ANALYSE DES UTILISATEURS FANTÔMES ===");
const userIds = new Set(users.map(user => user._id));
const balanceUserIds = balances.map(balance => balance.user);
const phantomUsers = balanceUserIds.filter(userId => !userIds.has(userId));
const uniquePhantomUsers = [...new Set(phantomUsers)];
console.log("Utilisateurs fantômes (ont des balances mais n'existent plus):", uniquePhantomUsers);
console.log("Nombre d'utilisateurs fantômes:", uniquePhantomUsers.length);
// Calculer les crédits des utilisateurs fantômes
const phantomCredits = balances
.filter(balance => uniquePhantomUsers.includes(balance.user))
.reduce((sum, balance) => sum + (balance.tokenCredits || 0), 0);
console.log("Crédits des utilisateurs fantômes:", phantomCredits);
console.log("Crédits des vrais utilisateurs:", totalBrut - phantomCredits);
// Calculer les utilisateurs actifs (5 dernières minutes)
const fiveMinutesAgo = new Date();
fiveMinutesAgo.setMinutes(fiveMinutesAgo.getMinutes() - 5);
const activeUsers = users.filter((user) => {
const lastActivity = new Date(user.updatedAt || user.createdAt);
return lastActivity >= fiveMinutesAgo;
}).length;
// CORRECTION : Créer une map des crédits par utilisateur en évitant les doublons
const creditsMap = new Map<string, number>();
// Grouper les balances par utilisateur
const balancesByUser = new Map<string, LibreChatBalance[]>();
balances.forEach((balance) => {
const userId = balance.user;
if (!balancesByUser.has(userId)) {
balancesByUser.set(userId, []);
}
balancesByUser.get(userId)!.push(balance);
});
// Pour chaque utilisateur, prendre seulement la dernière entrée
balancesByUser.forEach((userBalances, userId) => {
if (userBalances.length > 0) {
// Trier par date de mise à jour (plus récent en premier)
const sortedBalances = userBalances.sort((a, b) => {
const aDate = new Date((a.updatedAt as string) || (a.createdAt as string) || 0);
const bDate = new Date((b.updatedAt as string) || (b.createdAt as string) || 0);
return bDate.getTime() - aDate.getTime();
});
// Prendre la plus récente
const latestBalance = sortedBalances[0];
creditsMap.set(userId, latestBalance.tokenCredits || 0);
}
});
// Initialiser les stats par utilisateur
const userStats = new Map<
string,
{
userName: string;
conversations: number;
tokens: number;
credits: number;
}
>();
users.forEach((user) => {
userStats.set(user._id, {
userName: user.name || user.email || "Utilisateur inconnu",
conversations: 0,
tokens: 0,
credits: creditsMap.get(user._id) || 0,
});
});
// Calculer les conversations par utilisateur
conversations.forEach((conv) => {
const userStat = userStats.get(conv.user);
if (userStat) {
userStat.conversations++;
}
});
// Calculer les tokens par utilisateur depuis les transactions
let totalTokensConsumed = 0;
transactions.forEach((transaction) => {
const userStat = userStats.get(transaction.user);
if (userStat && transaction.rawAmount) {
const tokens = Math.abs(Number(transaction.rawAmount) || 0);
userStat.tokens += tokens;
totalTokensConsumed += tokens;
}
});
// CORRECTION : Calculer le total des crédits depuis la map corrigée
const totalCreditsUsed = Array.from(creditsMap.values()).reduce(
(sum, credits) => sum + credits,
0
);
// Tous les utilisateurs triés par tokens puis conversations
const allUsers = Array.from(userStats.entries())
.map(([userId, stats]) => ({
userId,
...stats,
}))
.sort((a, b) => {
// Trier d'abord par tokens, puis par conversations si tokens égaux
if (b.tokens !== a.tokens) {
return b.tokens - a.tokens;
}
return b.conversations - a.conversations;
});
const totalMessages = conversations.reduce(
(sum, conv) =>
sum + (Array.isArray(conv.messages) ? conv.messages.length : 0),
0
);
setStats({
totalUsers: users.length,
activeUsers,
totalConversations: conversations.length,
totalMessages,
totalTokensConsumed,
totalCreditsUsed,
averageTokensPerUser:
users.length > 0 ? totalTokensConsumed / users.length : 0,
topUsers: allUsers, // Afficher tous les utilisateurs
});
setLoading(false);
}, [users, conversations, transactions, balances]);
useEffect(() => {
calculateStats();
}, [calculateStats]);
if (loading || !stats) {
return (
<div className="space-y-4">
{Array.from({ length: 4 }).map((_, i) => (
<Card key={i}>
<CardContent className="p-6">
<div className="animate-pulse space-y-2">
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="h-8 bg-gray-200 rounded"></div>
</div>
</CardContent>
</Card>
))}
</div>
);
}
return (
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Utilisateurs totaux
</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.totalUsers}</div>
<p className="text-xs text-muted-foreground">
{stats.activeUsers} actifs cette semaine
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Conversations</CardTitle>
<MessageSquare className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.totalConversations}</div>
<p className="text-xs text-muted-foreground">
{stats.totalMessages} messages au total
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Tokens consommés
</CardTitle>
<Activity className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.totalTokensConsumed.toLocaleString()}
</div>
<p className="text-xs text-muted-foreground">
{Math.round(stats.averageTokensPerUser)} par utilisateur
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Crédits totaux
</CardTitle>
<DollarSign className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{stats.totalCreditsUsed.toLocaleString()}
</div>
<p className="text-xs text-muted-foreground">crédits disponibles</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Tous les utilisateurs</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4 max-h-96 overflow-y-auto">
{stats.topUsers.map((user, index) => (
<div
key={user.userId}
className="flex items-center justify-between p-4 border rounded-lg"
>
<div className="flex items-center space-x-4">
<Badge variant="outline">#{index + 1}</Badge>
<div>
<p className="font-medium">{user.userName}</p>
<p className="text-sm text-muted-foreground">
{user.conversations} conversations
</p>
</div>
</div>
<div className="text-right">
<p className="font-medium">
{user.tokens.toLocaleString()} tokens
</p>
<p className="text-sm text-muted-foreground">
{user.credits.toLocaleString()} crédits
</p>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import Image from "next/image";
import {
LayoutDashboard,
Users,
MessageSquare,
CreditCard,
Settings,
Database,
FileText,
Shield,
Bot,
ChevronLeft,
ChevronRight,
BarChart3,
Activity,
} from "lucide-react";
interface NavigationItem {
name: string;
href: string;
icon: React.ElementType;
badge?: string | null;
}
const navigation: NavigationItem[] = [
{
name: "Vue d'ensemble",
href: "/",
icon: LayoutDashboard,
badge: null,
},
{
name: "Analytics",
href: "/analytics",
icon: BarChart3,
badge: "Nouveau",
},
];
const dataNavigation: NavigationItem[] = [
{ name: "Utilisateurs", href: "/users", icon: Users, badge: null },
{
name: "Conversations",
href: "/conversations",
icon: MessageSquare,
badge: null,
},
{ name: "Messages", href: "/messages", icon: FileText, badge: null },
{
name: "Transactions",
href: "/transactions",
icon: CreditCard,
badge: null,
},
];
const systemNavigation: NavigationItem[] = [
{ name: "Agents", href: "/agents", icon: Bot, badge: null },
{ name: "Rôles", href: "/roles", icon: Shield, badge: null },
{ name: "Collections", href: "/collections", icon: Database, badge: null },
{ name: "Paramètres", href: "/settings", icon: Settings, badge: null },
];
export function Sidebar() {
const [collapsed, setCollapsed] = useState(false);
const pathname = usePathname();
const NavSection = ({
title,
items,
showTitle = true,
}: {
title: string;
items: NavigationItem[];
showTitle?: boolean;
}) => (
<div className="space-y-2">
{!collapsed && showTitle && (
<h3 className="px-3 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
{title}
</h3>
)}
{items.map((item) => {
const isActive = pathname === item.href;
return (
<Link key={item.name} href={item.href}>
<Button
variant={isActive ? "secondary" : "ghost"}
className={cn(
"w-full justify-start h-9 px-3",
collapsed && "px-2 justify-center",
isActive && "bg-secondary font-medium"
)}
>
<item.icon className={cn("h-4 w-4", collapsed ? "" : "mr-3")} />
{!collapsed && (
<div className="flex items-center justify-between w-full">
<span>{item.name}</span>
{item.badge && (
<Badge variant="secondary" className="text-xs">
{item.badge}
</Badge>
)}
</div>
)}
</Button>
</Link>
);
})}
</div>
);
return (
<div
className={cn(
"flex flex-col h-screen bg-background border-r border-border transition-all duration-300 ease-in-out",
collapsed ? "w-16" : "w-64"
)}
>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-border">
{!collapsed && (
<div className="flex items-center space-x-2">
<div className="w-8 h-8 rounded-lg flex items-center justify-center">
<Image
src="/img/logo.png"
alt="Cercle GPT Logo"
width={32}
height={32}
className="rounded-lg"
/>
</div>
<div>
<h1 className="text-sm font-semibold">Cercle GPT</h1>
<p className="text-xs text-muted-foreground">Admin Dashboard</p>
</div>
</div>
)}
<Button
variant="ghost"
size="icon"
onClick={() => setCollapsed(!collapsed)}
className="h-8 w-8"
>
{collapsed ? (
<ChevronRight className="h-4 w-4" />
) : (
<ChevronLeft className="h-4 w-4" />
)}
</Button>
</div>
{/* Navigation */}
<nav className="flex-1 p-3 space-y-6 overflow-y-auto">
<NavSection title="Dashboard" items={navigation} showTitle={false} />
{!collapsed && <Separator />}
<NavSection title="Données" items={dataNavigation} />
{!collapsed && <Separator />}
<NavSection title="Système" items={systemNavigation} />
</nav>
{/* Footer */}
{!collapsed && (
<div className="p-3 border-t border-border">
<div className="flex items-center space-x-3 p-2 rounded-lg bg-muted/50">
<div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
<Activity className="h-4 w-4 text-primary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-xs font-medium">Système en ligne</p>
<p className="text-xs text-muted-foreground">Tout fonctionne</p>
</div>
</div>
</div>
)}
</div>
);
}

46
components/ui/badge.tsx Normal file
View File

@@ -0,0 +1,46 @@
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 badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

60
components/ui/button.tsx Normal file
View File

@@ -0,0 +1,60 @@
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 rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

92
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

21
components/ui/input.tsx Normal file
View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,47 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { LucideIcon } from "lucide-react";
import { formatNumber } from "@/lib/utils";
interface MetricCardProps {
title: string;
value: number | string;
icon: LucideIcon;
trend?: {
value: number;
isPositive: boolean;
};
className?: string;
}
export function MetricCard({
title,
value,
icon: Icon,
trend,
className
}: MetricCardProps) {
return (
<Card className={className}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{title}
</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{typeof value === 'number' ? formatNumber(value) : value}
</div>
{trend && (
<Badge
variant={trend.isPositive ? "default" : "destructive"}
className="mt-2"
>
{trend.isPositive ? '+' : ''}{trend.value}%
</Badge>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,168 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function NavigationMenu({
className,
children,
viewport = true,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
viewport?: boolean
}) {
return (
<NavigationMenuPrimitive.Root
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
className
)}
{...props}
>
{children}
{viewport && <NavigationMenuViewport />}
</NavigationMenuPrimitive.Root>
)
}
function NavigationMenuList({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
className={cn(
"group flex flex-1 list-none items-center justify-center gap-1",
className
)}
{...props}
/>
)
}
function NavigationMenuItem({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
className={cn("relative", className)}
{...props}
/>
)
}
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
)
function NavigationMenuTrigger({
className,
children,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
)
}
function NavigationMenuContent({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
return (
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
"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 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
className
)}
{...props}
/>
)
}
function NavigationMenuViewport({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
<div
className={cn(
"absolute top-full left-0 isolate z-50 flex justify-center"
)}
>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
className
)}
{...props}
/>
</div>
)
}
function NavigationMenuLink({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
return (
<NavigationMenuPrimitive.Link
data-slot="navigation-menu-link"
className={cn(
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function NavigationMenuIndicator({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
return (
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
className
)}
{...props}
>
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
</NavigationMenuPrimitive.Indicator>
)
}
export {
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
navigationMenuTriggerStyle,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

139
components/ui/sheet.tsx Normal file
View File

@@ -0,0 +1,139 @@
"use client"
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

726
components/ui/sidebar.tsx Normal file
View File

@@ -0,0 +1,726 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, VariantProps } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
_setOpen(openState)
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
},
[setOpenProp, open]
)
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
}
}
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
)}
{...props}
>
{children}
</div>
)
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
)
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
)
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
)}
{...props}
/>
)
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
)
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
)
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
)
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
)
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
)
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
)
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
)
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
if (!tooltip) {
return button
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
}
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
)
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
)}
{...props}
/>
)
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
)
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
)
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}) {
const Comp = asChild ? Slot : "a"
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
)
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

116
components/ui/table.tsx Normal file
View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

55
components/ui/tabs.tsx Normal file
View File

@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }

61
components/ui/tooltip.tsx Normal file
View File

@@ -0,0 +1,61 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }