first commit
This commit is contained in:
95
components/dashboard/charts/model-distribution-chart.tsx
Normal file
95
components/dashboard/charts/model-distribution-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
58
components/dashboard/charts/model-usage-chart.tsx
Normal file
58
components/dashboard/charts/model-usage-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
110
components/dashboard/charts/real-user-activity-chart.tsx
Normal file
110
components/dashboard/charts/real-user-activity-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
62
components/dashboard/charts/simple-bar-chart.tsx
Normal file
62
components/dashboard/charts/simple-bar-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
70
components/dashboard/charts/simple-stats-chart.tsx
Normal file
70
components/dashboard/charts/simple-stats-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
74
components/dashboard/charts/usage-chart.tsx
Normal file
74
components/dashboard/charts/usage-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
81
components/dashboard/charts/user-activity-chart.tsx
Normal file
81
components/dashboard/charts/user-activity-chart.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
126
components/dashboard/metric-cards.tsx
Normal file
126
components/dashboard/metric-cards.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
62
components/dashboard/overview-metrics.tsx
Normal file
62
components/dashboard/overview-metrics.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
82
components/dashboard/real-time-stats.tsx
Normal file
82
components/dashboard/real-time-stats.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
62
components/dashboard/recent-transactions.tsx
Normal file
62
components/dashboard/recent-transactions.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
331
components/dashboard/usage-analytics.tsx
Normal file
331
components/dashboard/usage-analytics.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user