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

14
app/agents/page.tsx Normal file
View File

@@ -0,0 +1,14 @@
import { AgentsTable } from "@/components/collections/agents-table";
export default function AgentsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Agents</h1>
<p className="text-muted-foreground">Gestion des agents Cercle GPT</p>
</div>
<AgentsTable />
</div>
);
}

49
app/analytics/page.tsx Normal file
View File

@@ -0,0 +1,49 @@
import { Suspense } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { UsageAnalytics } from "@/components/dashboard/usage-analytics";
import { RecentTransactions } from "@/components/dashboard/recent-transactions";
import { BarChart3 } from "lucide-react";
function AnalyticsSkeleton() {
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>
);
}
export default function AnalyticsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
<BarChart3 className="h-8 w-8" />
Analytics détaillées
</h1>
<p className="text-muted-foreground">
Analyses approfondies des performances et de l&apos;utilisation de
Cercle GPT
</p>
</div>
<Suspense fallback={<AnalyticsSkeleton />}>
<div className="space-y-6">
{/* Analytics des utilisateurs */}
<UsageAnalytics />
{/* Transactions récentes - toute la largeur */}
<RecentTransactions />
</div>
</Suspense>
</div>
);
}

View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDatabase } from '@/lib/db/mongodb';
const ALLOWED_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 async function GET(
request: NextRequest,
{ params }: { params: Promise<{ collection: string }> }
) {
const { collection } = await params;
try {
if (!ALLOWED_COLLECTIONS.includes(collection)) {
return NextResponse.json(
{ error: 'Collection non autorisée' },
{ status: 400 }
);
}
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const limit = parseInt(searchParams.get('limit') || '20');
const filter = JSON.parse(searchParams.get('filter') || '{}');
const db = await getDatabase();
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
db.collection(collection)
.find(filter)
.skip(skip)
.limit(limit)
.sort({ createdAt: -1 })
.toArray(),
db.collection(collection).countDocuments(filter)
]);
return NextResponse.json({
data,
total,
page,
limit,
totalPages: Math.ceil(total / limit)
});
} catch (error) {
console.error(`Erreur lors de la récupération de ${collection}:`, error);
return NextResponse.json(
{ error: 'Erreur serveur' },
{ status: 500 }
);
}
}

75
app/api/metrics/route.ts Normal file
View File

@@ -0,0 +1,75 @@
import { NextResponse } from "next/server";
import { getDatabase } from "@/lib/db/mongodb";
export async function GET() {
try {
const db = await getDatabase();
// Récupérer toutes les données nécessaires en parallèle
const [users, conversations, transactions, balances] = await Promise.all([
db.collection("users").find({}).toArray(),
db.collection("conversations").find({}).toArray(),
db.collection("transactions").find({}).toArray(),
db.collection("balances").find({}).toArray(),
]);
// Calculer les utilisateurs actifs (dernière semaine)
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
const activeUsers = users.filter((user) => {
const lastActivity = new Date(user.updatedAt || user.createdAt);
return lastActivity >= oneWeekAgo;
}).length;
// Calculer les administrateurs
const totalAdmins = users.filter(user => user.role === 'ADMIN').length;
// Calculer les conversations actives (dernière semaine)
const activeConversations = conversations.filter((conv) => {
const lastActivity = new Date(conv.updatedAt || conv.createdAt);
return lastActivity >= oneWeekAgo;
}).length;
// Calculer le total des messages
const totalMessages = conversations.reduce(
(sum, conv) => sum + (Array.isArray(conv.messages) ? conv.messages.length : 0),
0
);
// Calculer le total des tokens depuis les transactions
const totalTokensConsumed = transactions.reduce((sum, transaction) => {
return sum + Math.abs(Number(transaction.rawAmount) || 0);
}, 0);
// Calculer le total des crédits depuis balances
const totalCredits = balances.reduce((sum, balance) => {
return sum + (Number(balance.tokenCredits) || 0);
}, 0);
// Récupérer les transactions récentes (dernières 10)
const recentTransactions = transactions
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
.slice(0, 10)
.map(transaction => ({
_id: transaction._id,
description: `Transaction ${transaction.tokenType} - ${transaction.model}`,
amount: transaction.rawAmount,
type: transaction.rawAmount > 0 ? 'credit' : 'debit',
createdAt: transaction.createdAt
}));
return NextResponse.json({
totalUsers: users.length,
activeUsers,
totalAdmins,
totalCredits,
activeConversations,
totalMessages: totalMessages,
totalTokensConsumed,
recentTransactions
});
} catch (error) {
console.error("Erreur lors du calcul des métriques:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}

61
app/api/stats/route.ts Normal file
View File

@@ -0,0 +1,61 @@
import { NextResponse } from "next/server";
import { getDatabase } from "@/lib/db/mongodb";
export async function GET() {
try {
const db = await getDatabase();
// Récupérer toutes les transactions
const transactions = await db.collection("transactions").find({}).toArray();
// Calculer les tokens par jour (7 derniers jours)
const dailyStats = [];
const today = new Date();
const dayNames = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"];
for (let i = 6; i >= 0; i--) {
const date = new Date(today);
date.setDate(date.getDate() - i);
date.setHours(0, 0, 0, 0);
const nextDate = new Date(date);
nextDate.setDate(nextDate.getDate() + 1);
const dayTransactions = transactions.filter(transaction => {
const transactionDate = new Date(transaction.createdAt);
return transactionDate >= date && transactionDate < nextDate;
});
const totalTokens = dayTransactions.reduce((sum, transaction) => {
return sum + Math.abs(Number(transaction.rawAmount) || 0);
}, 0);
dailyStats.push({
name: dayNames[date.getDay()],
value: totalTokens
});
}
// Calculer la répartition par modèle (vraies données)
const modelStats = new Map<string, number>();
transactions.forEach(transaction => {
const model = transaction.model || "Inconnu";
const tokens = Math.abs(Number(transaction.rawAmount) || 0);
modelStats.set(model, (modelStats.get(model) || 0) + tokens);
});
// Convertir en array et trier par usage
const modelData = Array.from(modelStats.entries())
.map(([name, value]) => ({ name, value }))
.sort((a, b) => b.value - a.value);
return NextResponse.json({
dailyTokens: dailyStats,
modelDistribution: modelData
});
} catch (error) {
console.error("Erreur lors du calcul des statistiques:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}

View File

@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { getDatabase } from "@/lib/db/mongodb";
export async function GET() {
try {
const db = await getDatabase();
// Récupérer tous les utilisateurs
const users = await db.collection("users").find({}).toArray();
// Calculer les utilisateurs actifs (dernière semaine)
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
let activeUsers = 0;
let inactiveUsers = 0;
users.forEach(user => {
const lastActivity = new Date(user.updatedAt || user.createdAt);
if (lastActivity >= oneWeekAgo) {
activeUsers++;
} else {
inactiveUsers++;
}
});
return NextResponse.json({
activeUsers,
inactiveUsers,
totalUsers: users.length
});
} catch (error) {
console.error("Erreur lors du calcul de l'activité des utilisateurs:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}

18
app/collections/page.tsx Normal file
View File

@@ -0,0 +1,18 @@
import { CollectionSelector } from "@/components/collections/collection-selector";
export default function CollectionsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">
Collections
</h1>
<p className="text-muted-foreground">
Explorez toutes les collections de votre base Cercle GPT
</p>
</div>
<CollectionSelector />
</div>
);
}

View File

@@ -0,0 +1,16 @@
import { ConversationsTable } from "@/components/collections/conversations-table";
export default function ConversationsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Conversations</h1>
<p className="text-muted-foreground">
Gestion des conversations Cercle GPTTT
</p>
</div>
<ConversationsTable />
</div>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -1,26 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
:root {
--background: #ffffff;
--foreground: #171717;
}
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Sidebar } from "@/components/layout/sidebar";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +14,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "Dashboard - Cercle GPT",
description: "Dashboard d'administration pour Cercle GPT",
};
export default function RootLayout({
@@ -23,11 +24,16 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en">
<html lang="fr">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<div className="flex h-screen">
<Sidebar />
<main className="flex-1 overflow-auto">
<div className="container mx-auto p-6">{children}</div>
</main>
</div>
</body>
</html>
);

16
app/messages/page.tsx Normal file
View File

@@ -0,0 +1,16 @@
import { MessagesTable } from "@/components/collections/messages-table";
export default function MessagesPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Messages</h1>
<p className="text-muted-foreground">
Historique des messages Cercle GPT
</p>
</div>
<MessagesTable />
</div>
);
}

View File

@@ -1,103 +1,146 @@
import Image from "next/image";
import { Suspense } from "react";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { OverviewMetrics } from "@/components/dashboard/overview-metrics";
import { RealTimeStats } from "@/components/dashboard/real-time-stats";
import { RealUserActivityChart } from "@/components/dashboard/charts/real-user-activity-chart";
import {
Users,
MessageSquare,
CreditCard,
BarChart3,
TrendingUp,
Activity,
} from "lucide-react";
export default function Home() {
export default function Dashboard() {
return (
<div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded">
app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
<div className="space-y-6">
{/* En-tête simplifié */}
<div>
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
<TrendingUp className="h-8 w-8" />
Vue d&apos;ensemble
</h1>
<p className="text-muted-foreground">
Tableau de bord administrateur Cercle GPT
</p>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
{/* Métriques principales */}
<Suspense
fallback={<div className="h-32 bg-muted animate-pulse rounded-lg" />}
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
<OverviewMetrics />
</Suspense>
{/* Graphiques en temps réel */}
<div className="space-y-6">
<h2 className="text-xl font-semibold flex items-center gap-2">
<Activity className="h-5 w-5" />
Statistiques en temps réel
</h2>
<Suspense
fallback={<div className="h-64 bg-muted animate-pulse rounded-lg" />}
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
<RealTimeStats />
</Suspense>
</div>
{/* Grille pour activité utilisateurs et actions */}
<div className="grid gap-6 md:grid-cols-3">
{/* Activité des utilisateurs avec vraies données */}
<div className="md:col-span-1">
<Suspense
fallback={
<div className="h-64 bg-muted animate-pulse rounded-lg" />
}
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
<RealUserActivityChart />
</Suspense>
</div>
{/* Actions rapides épurées */}
<div className="md:col-span-2 grid gap-4 md:grid-cols-2">
<Card className="hover:shadow-md transition-shadow border-l-4 border-l-blue-500">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center">
<Users className="h-4 w-4 mr-2 text-blue-600" />
Utilisateurs
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground mb-3">
Gérer les comptes utilisateurs
</p>
<Link href="/users">
<Button variant="outline" size="sm" className="w-full">
Voir les utilisateurs
</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow border-l-4 border-l-green-500">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center">
<MessageSquare className="h-4 w-4 mr-2 text-green-600" />
Conversations
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground mb-3">
Consulter les discussions
</p>
<Link href="/conversations">
<Button variant="outline" size="sm" className="w-full">
Voir les conversations
</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow border-l-4 border-l-purple-500">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center">
<CreditCard className="h-4 w-4 mr-2 text-purple-600" />
Transactions
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground mb-3">
Historique des paiements
</p>
<Link href="/transactions">
<Button variant="outline" size="sm" className="w-full">
Voir les transactions
</Button>
</Link>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow border-l-4 border-l-orange-500">
<CardHeader className="pb-3">
<CardTitle className="text-base flex items-center">
<BarChart3 className="h-4 w-4 mr-2 text-orange-600" />
Analytics
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground mb-3">
Analyses détaillées
</p>
<Link href="/analytics">
<Button variant="outline" size="sm" className="w-full">
Voir les analytics
</Button>
</Link>
</CardContent>
</Card>
</div>
</div>
</div>
);
}

18
app/roles/page.tsx Normal file
View File

@@ -0,0 +1,18 @@
import { RolesTable } from "@/components/collections/roles-table";
export default function RolesPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">
Rôles et Permissions
</h1>
<p className="text-muted-foreground">
Gestion des rôles d&apos;accès Cercle GPT
</p>
</div>
<RolesTable />
</div>
);
}

71
app/settings/page.tsx Normal file
View File

@@ -0,0 +1,71 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export default function SettingsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Paramètres</h1>
<p className="text-muted-foreground">
Configuration du dashboard Cercle GPT
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Connexion MongoDB</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">Statut:</span>
<Badge variant="default">Connecté</Badge>
</div>
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">
Base de données:
</span>
<span className="text-sm font-mono">Cercle GPT</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">
Collections:
</span>
<span className="text-sm">29 collections</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Informations système</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">
Version Next.js:
</span>
<span className="text-sm">15.5.4</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">
Version Node.js:
</span>
<span className="text-sm">{process.version}</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-muted-foreground">
Environnement:
</span>
<Badge variant="outline">{process.env.NODE_ENV}</Badge>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

16
app/transactions/page.tsx Normal file
View File

@@ -0,0 +1,16 @@
import { TransactionsTable } from "@/components/collections/transactions-table";
export default function TransactionsPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Transactions</h1>
<p className="text-muted-foreground">
Historique des transactions Cercle GPT
</p>
</div>
<TransactionsTable />
</div>
);
}

16
app/users/page.tsx Normal file
View File

@@ -0,0 +1,16 @@
import { UsersTable } from "@/components/collections/users-table";
export default function UsersPage() {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Utilisateurs</h1>
<p className="text-muted-foreground">
Gestion des utilisateurs Cercle GPTT
</p>
</div>
<UsersTable />
</div>
);
}

22
components.json Normal file
View File

@@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

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 }

19
hooks/use-mobile.ts Normal file
View File

@@ -0,0 +1,19 @@
import * as React from "react"
const MOBILE_BREAKPOINT = 768
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile
}

66
hooks/useCollection.ts Normal file
View File

@@ -0,0 +1,66 @@
"use client";
import { useState, useEffect, useCallback, useMemo } from 'react';
interface UseCollectionOptions {
page?: number;
limit?: number;
filter?: Record<string, unknown>;
}
interface CollectionResponse<T> {
data: T[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export function useCollection<T = Record<string, unknown>>(
collectionName: string,
options: UseCollectionOptions = {}
) {
const [data, setData] = useState<T[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [total, setTotal] = useState(0);
const [totalPages, setTotalPages] = useState(0);
const { page = 1, limit = 20, filter = {} } = options;
// Mémoriser la chaîne JSON du filtre pour éviter les re-renders inutiles
const filterString = useMemo(() => JSON.stringify(filter), [filter]);
const fetchData = useCallback(async () => {
try {
setLoading(true);
const params = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
filter: filterString
});
const response = await fetch(`/api/collections/${collectionName}?${params}`);
if (!response.ok) throw new Error(`Erreur lors du chargement de ${collectionName}`);
const result: CollectionResponse<T> = await response.json();
setData(result.data);
setTotal(result.total);
setTotalPages(result.totalPages);
} catch (err) {
setError(err instanceof Error ? err.message : 'Erreur inconnue');
} finally {
setLoading(false);
}
}, [collectionName, page, limit, filterString]);
useEffect(() => {
fetchData();
}, [fetchData]);
const refetch = useCallback(() => {
return fetchData();
}, [fetchData]);
return { data, loading, error, total, totalPages, refetch };
}

34
hooks/useMetrics.ts Normal file
View File

@@ -0,0 +1,34 @@
"use client";
import { useState, useEffect, useCallback } from 'react';
import { DashboardMetrics } from '@/lib/types';
export function useMetrics() {
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchMetrics = useCallback(async () => {
try {
setLoading(true);
const response = await fetch('/api/metrics');
if (!response.ok) throw new Error('Erreur lors du chargement des métriques');
const data = await response.json();
setMetrics(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Erreur inconnue');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchMetrics();
}, [fetchMetrics]);
const refetch = useCallback(() => {
return fetchMetrics();
}, [fetchMetrics]);
return { metrics, loading, error, refetch };
}

54
hooks/useStats.ts Normal file
View File

@@ -0,0 +1,54 @@
"use client";
import { useState, useEffect } from "react";
interface DailyToken {
name: string;
value: number;
}
interface ModelDistribution {
name: string;
value: number;
}
interface StatsData {
dailyTokens: DailyToken[];
modelDistribution: ModelDistribution[];
}
export function useStats() {
const [stats, setStats] = useState<StatsData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchStats = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch("/api/stats");
if (!response.ok) {
throw new Error("Erreur lors du chargement des statistiques");
}
const data = await response.json();
setStats(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Erreur inconnue");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchStats();
}, []);
return {
stats,
loading,
error,
refetch: fetchStats
};
}

45
hooks/useUserActivity.ts Normal file
View File

@@ -0,0 +1,45 @@
"use client";
import { useState, useEffect } from "react";
interface UserActivityData {
activeUsers: number;
inactiveUsers: number;
totalUsers: number;
}
export function useUserActivity() {
const [activity, setActivity] = useState<UserActivityData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchActivity = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch("/api/user-activity");
if (!response.ok) {
throw new Error("Erreur lors du chargement de l'activité des utilisateurs");
}
const data = await response.json();
setActivity(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Erreur inconnue");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchActivity();
}, []);
return {
activity,
loading,
error,
refetch: fetchActivity
};
}

33
lib/db/mongodb.ts Normal file
View File

@@ -0,0 +1,33 @@
import { MongoClient, Db } from 'mongodb';
if (!process.env.MONGODB_URI) {
throw new Error('Please add your MongoDB URI to .env.local');
}
const uri = process.env.MONGODB_URI;
const options = {};
let client: MongoClient;
let clientPromise: Promise<MongoClient>;
if (process.env.NODE_ENV === 'development') {
const globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise<MongoClient>;
};
if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options);
globalWithMongo._mongoClientPromise = client.connect();
}
clientPromise = globalWithMongo._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export async function getDatabase(): Promise<Db> {
const client = await clientPromise;
return client.db('librechat'); // Nom de votre base de données
}
export default clientPromise;

185
lib/types/index.ts Normal file
View File

@@ -0,0 +1,185 @@
// Types pour les collections MongoDB LibreChat (structure réelle)
export interface LibreChatUser extends Record<string, unknown> {
_id: string;
name: string;
username: string;
email: string;
emailVerified: boolean;
password: string;
avatar: string | null;
provider: string;
role: 'ADMIN' | 'USER';
plugins: unknown[];
twoFactorEnabled: boolean;
termsAccepted: boolean;
personalization: {
memories: boolean;
_id: string;
};
backupCodes: unknown[];
refreshToken: unknown[];
createdAt: Date;
updatedAt: Date;
__v: number;
}
export interface LibreChatConversation extends Record<string, unknown> {
_id: string;
conversationId: string;
user: string; // ObjectId du user
__v: number;
_meiliIndex: boolean;
agent_id: string;
createdAt: Date;
endpoint: string;
endpointType: string;
expiredAt: Date | null;
files: unknown[];
isArchived: boolean;
messages: string[]; // Array d'ObjectIds
model: string;
resendFiles: boolean;
tags: unknown[];
title: string;
updatedAt: Date;
}
export interface LibreChatMessage extends Record<string, unknown> {
_id: string;
messageId: string;
user: string; // ObjectId du user
__v: number;
_meiliIndex: boolean;
conversationId: string;
createdAt: Date;
endpoint: string;
error: boolean;
expiredAt: Date | null;
isCreatedByUser: boolean;
model: string | null;
parentMessageId: string;
sender: string;
text: string;
tokenCount: number;
unfinished: boolean;
updatedAt: Date;
}
export interface LibreChatTransaction extends Record<string, unknown> {
_id: string;
user: string; // ObjectId
conversationId: string;
tokenType: 'prompt' | 'completion';
model: string;
context: string;
rawAmount: number;
tokenValue: number;
rate: number;
createdAt: Date;
updatedAt: Date;
__v: number;
}
export interface LibreChatBalance extends Record<string, unknown> {
_id: string;
user: string; // ObjectId
__v: number;
autoRefillEnabled: boolean;
lastRefill: Date;
refillAmount: number;
refillIntervalUnit: string;
refillIntervalValue: number;
tokenCredits: number;
}
// Types legacy pour compatibilité
export interface User extends Record<string, unknown> {
_id: string;
name: string;
email: string;
role: string;
credits: number;
isActive: boolean;
createdAt: Date;
lastLogin?: Date;
}
export interface Conversation extends Record<string, unknown> {
_id: string;
title: string;
participants: string[];
messageCount: number;
status: 'active' | 'archived' | 'deleted';
createdAt: Date;
updatedAt: Date;
}
export interface Transaction extends Record<string, unknown> {
_id: string;
userId: string;
amount: number;
type: 'credit' | 'debit';
description: string;
createdAt: Date;
}
export interface Message extends Record<string, unknown> {
_id: string;
conversationId: string;
userId: string;
content: string;
role: 'user' | 'assistant' | 'system';
createdAt: Date;
}
export interface Balance extends Record<string, unknown> {
_id: string;
userId: string;
credits: number;
lastUpdated: Date;
}
export interface DashboardMetrics {
totalUsers: number;
activeUsers: number;
totalAdmins: number;
totalCredits: number;
activeConversations: number;
totalMessages: number;
totalTokensConsumed: number;
totalCreditsUsed: number;
recentTransactions: Transaction[];
}
// Types pour les autres collections
export interface AccessRole extends Record<string, unknown> {
_id: string;
name: string;
permissions: string[];
}
export interface Agent extends Record<string, unknown> {
_id: string;
name: string;
description: string;
category: string;
isActive: boolean;
}
export interface File extends Record<string, unknown> {
_id: string;
filename: string;
size: number;
uploadedBy: string;
uploadedAt: Date;
}
// Types génériques pour les collections MongoDB
export interface MongoDocument extends Record<string, unknown> {
_id: string;
createdAt?: Date;
updatedAt?: Date;
}
// Type utilitaire pour les collections
export type CollectionItem = MongoDocument & Record<string, unknown>;

35
lib/utils.ts Normal file
View File

@@ -0,0 +1,35 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatNumber(num: number): string {
return new Intl.NumberFormat('fr-FR').format(num);
}
export function formatDate(date: Date | string | number): string {
// Convertir en objet Date si ce n'est pas déjà le cas
const dateObj = date instanceof Date ? date : new Date(date);
// Vérifier si la date est valide
if (isNaN(dateObj.getTime())) {
return 'Date invalide';
}
return new Intl.DateTimeFormat('fr-FR', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(dateObj);
}
export function formatCurrency(amount: number): string {
return new Intl.NumberFormat('fr-FR', {
style: 'currency',
currency: 'EUR'
}).format(amount);
}

27
lib/utils/index.ts Normal file
View File

@@ -0,0 +1,27 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatNumber(num: number): string {
return new Intl.NumberFormat('fr-FR').format(num);
}
export function formatDate(date: Date): string {
return new Intl.DateTimeFormat('fr-FR', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(date);
}
export function formatCurrency(amount: number): string {
return new Intl.NumberFormat('fr-FR', {
style: 'currency',
currency: 'EUR'
}).format(amount);
}

View File

@@ -2,6 +2,7 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
allowedDevOrigins: ['10.8.0.2', '*.local'],
};
export default nextConfig;

1468
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,19 +9,34 @@
"lint": "eslint"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-navigation-menu": "^1.2.14",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"@types/mongodb": "^4.0.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.544.0",
"mongodb": "^6.20.0",
"next": "15.5.4",
"react": "19.1.0",
"react-dom": "19.1.0",
"next": "15.5.4"
"recharts": "^3.2.1",
"tailwind-merge": "^3.3.1"
},
"devDependencies": {
"typescript": "^5",
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@tailwindcss/postcss": "^4",
"tailwindcss": "^4",
"eslint": "^9",
"eslint-config-next": "15.5.4",
"@eslint/eslintrc": "^3"
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}

View File

@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

BIN
public/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B