Add registration_activity chart and enhance admin statistics

- Introduced `RegistrationActivityChart` to display user registration trends over 14 days.
- Enhanced `AdminStatsResponse` with `registration_activity`, providing improved insights for admin users.
- Updated demo data to include realistic registration activity and organization details.
- Refactored admin page to use updated statistics data model and improved query handling.
- Fixed inconsistent timezone handling in statistical analytics and demo user timestamps.
This commit is contained in:
Felipe Cardoso
2025-11-24 17:42:43 +01:00
parent 9f655913b1
commit a05def5906
9 changed files with 664 additions and 226 deletions

View File

@@ -11,7 +11,7 @@ import { DashboardStats } from '@/components/admin';
import {
UserGrowthChart,
OrganizationDistributionChart,
SessionActivityChart,
RegistrationActivityChart,
UserStatusChart,
} from '@/components/charts';
import { Users, Building2, Settings } from 'lucide-react';
@@ -19,16 +19,40 @@ import { useQuery } from '@tanstack/react-query';
import { getAdminStats } from '@/lib/api/admin';
export default function AdminPage() {
console.log('[AdminPage] Component rendering');
const {
data: stats,
isLoading,
error,
status,
fetchStatus,
} = useQuery({
queryKey: ['admin', 'stats'],
queryKey: ['admin', 'analytics'], // Changed from 'stats' to avoid collision with useAdminStats hook
queryFn: async () => {
const response = await getAdminStats();
return response.data;
console.log('[AdminPage] QueryFn executing - fetching stats...');
try {
const response = await getAdminStats();
console.log('[AdminPage] Stats response received:', response);
return response.data;
} catch (err) {
console.error('[AdminPage] Error fetching stats:', err);
throw err;
}
},
enabled: true, // Explicitly enable the query
retry: 1,
staleTime: 60000, // Cache for 1 minute
});
console.log('[AdminPage] Current state:', {
isLoading,
hasError: Boolean(error),
error: error?.message,
hasData: Boolean(stats),
dataKeys: stats ? Object.keys(stats) : null,
status,
fetchStatus,
});
return (
@@ -94,7 +118,11 @@ export default function AdminPage() {
loading={isLoading}
error={error ? (error as Error).message : null}
/>
<SessionActivityChart />
<RegistrationActivityChart
data={stats?.registration_activity}
loading={isLoading}
error={error ? (error as Error).message : null}
/>
<OrganizationDistributionChart
data={stats?.organization_distribution}
loading={isLoading}

View File

@@ -14,39 +14,56 @@ import {
Tooltip,
ResponsiveContainer,
Legend,
Rectangle,
} from 'recharts';
import { ChartCard } from './ChartCard';
import { CHART_PALETTES } from '@/lib/chart-colors';
export interface OrganizationDistributionData {
export interface OrgDistributionData {
name: string;
value: number;
}
interface OrganizationDistributionChartProps {
data?: OrganizationDistributionData[];
data?: OrgDistributionData[];
loading?: boolean;
error?: string | null;
}
// Generate mock data for development/demo
function generateMockData(): OrganizationDistributionData[] {
return [
{ name: 'Engineering', value: 45 },
{ name: 'Marketing', value: 28 },
{ name: 'Sales', value: 35 },
{ name: 'Operations', value: 22 },
{ name: 'HR', value: 15 },
{ name: 'Finance', value: 18 },
];
}
// Custom tooltip with proper theme colors
const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) {
return (
<div
style={{
backgroundColor: 'hsl(var(--popover) / 0.95)',
border: '1px solid hsl(var(--border))',
borderRadius: '8px',
padding: '10px 14px',
boxShadow: '0 2px 2px rgba(0, 0, 0, 0.5)',
backdropFilter: 'blur(8px)',
}}
>
<p style={{ color: 'hsl(var(--popover-foreground))', margin: 0, fontSize: '14px', fontWeight: 600 }}>
{payload[0].payload.name}
</p>
<p style={{ color: 'hsl(var(--muted-foreground))', margin: '4px 0 0 0', fontSize: '13px' }}>
Members: <span style={{ fontWeight: 600, color: 'hsl(var(--popover-foreground))' }}>{payload[0].value}</span>
</p>
</div>
);
}
return null;
};
export function OrganizationDistributionChart({
data,
loading,
error,
}: OrganizationDistributionChartProps) {
const chartData = data || generateMockData();
// Show empty chart if no data available
const rawData = data || [];
const hasData = rawData.length > 0 && rawData.some((d) => d.value > 0);
return (
<ChartCard
@@ -55,42 +72,33 @@ export function OrganizationDistributionChart({
loading={loading}
error={error}
>
<ResponsiveContainer width="100%" height={300}>
<BarChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="name"
stroke="hsl(var(--border))"
tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12 }}
tickLine={{ stroke: 'hsl(var(--border))' }}
/>
<YAxis
stroke="hsl(var(--border))"
tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12 }}
tickLine={{ stroke: 'hsl(var(--border))' }}
/>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
color: 'hsl(var(--popover-foreground))',
}}
labelStyle={{ color: 'hsl(var(--popover-foreground))' }}
/>
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
/>
<Bar
dataKey="value"
name="Total Members"
fill={CHART_PALETTES.bar[0]}
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
{!hasData && !loading && !error ? (
<div className="flex items-center justify-center h-[300px] text-muted-foreground">
<p>No organization data available</p>
</div>
) : (
<ResponsiveContainer width="100%" height={300}>
<BarChart data={rawData} margin={{ top: 5, right: 30, left: 20, bottom: 80 }}>
<CartesianGrid strokeDasharray="3 3" style={{ stroke: 'var(--muted)', opacity: 0.2 }} />
<XAxis
dataKey="name"
angle={-45}
textAnchor="end"
style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }}
/>
<YAxis
style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }}
/>
<Tooltip content={<CustomTooltip />} />
<Bar
dataKey="value"
fill={CHART_PALETTES.bar[0]}
radius={[4, 4, 0, 0]}
activeBar={{ fill: CHART_PALETTES.bar[0] }}
/>
</BarChart>
</ResponsiveContainer>
)}
</ChartCard>
);
}

View File

@@ -0,0 +1,113 @@
/**
* RegistrationActivityChart Component
* Displays user registration activity over time using an area chart
*/
'use client';
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
} from 'recharts';
import { ChartCard } from './ChartCard';
import { CHART_PALETTES } from '@/lib/chart-colors';
export interface RegistrationActivityData {
date: string;
registrations: number;
}
interface RegistrationActivityChartProps {
data?: RegistrationActivityData[];
loading?: boolean;
error?: string | null;
}
// Custom tooltip with proper theme colors
const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) {
return (
<div
style={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
padding: '8px 12px',
}}
>
<p style={{ color: 'hsl(var(--popover-foreground))', margin: 0, fontSize: '13px', fontWeight: 600 }}>
{payload[0].payload.date}
</p>
<p style={{ color: 'hsl(var(--popover-foreground))', margin: '4px 0 0 0', fontSize: '12px' }}>
New Registrations: {payload[0].value}
</p>
</div>
);
}
return null;
};
export function RegistrationActivityChart({
data,
loading,
error,
}: RegistrationActivityChartProps) {
// Show empty chart if no data available
const chartData = data || [];
const hasData = chartData.length > 0 && chartData.some((d) => d.registrations > 0);
return (
<ChartCard
title="User Registration Activity"
description="New user registrations over the last 14 days"
loading={loading}
error={error}
>
{!hasData && !loading && !error ? (
<div className="flex items-center justify-center h-[300px] text-muted-foreground">
<p>No registration data available</p>
</div>
) : (
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<defs>
<linearGradient id="colorRegistrations" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={CHART_PALETTES.area[0]} stopOpacity={0.8} />
<stop offset="95%" stopColor={CHART_PALETTES.area[0]} stopOpacity={0.1} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" style={{ stroke: 'var(--muted)', opacity: 0.2 }} />
<XAxis
dataKey="date"
style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }}
/>
<YAxis
style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }}
/>
<Tooltip content={<CustomTooltip />} />
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
/>
<Area
type="monotone"
dataKey="registrations"
name="New Registrations"
stroke={CHART_PALETTES.area[0]}
strokeWidth={2}
fillOpacity={1}
fill="url(#colorRegistrations)"
/>
</AreaChart>
</ResponsiveContainer>
)}
</ChartCard>
);
}

View File

@@ -5,19 +5,18 @@
'use client';
import { ChartCard } from './ChartCard';
import { CHART_PALETTES } from '@/lib/chart-colors';
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
} from 'recharts';
import { ChartCard } from './ChartCard';
import { format, subDays } from 'date-fns';
import { CHART_PALETTES } from '@/lib/chart-colors';
export interface UserGrowthData {
date: string;
@@ -25,32 +24,46 @@ export interface UserGrowthData {
active_users: number;
}
interface UserGrowthChartProps {
export interface UserGrowthChartProps {
data?: UserGrowthData[];
loading?: boolean;
error?: string | null;
}
// Generate mock data for development/demo
function generateMockData(): UserGrowthData[] {
const data: UserGrowthData[] = [];
const today = new Date();
for (let i = 29; i >= 0; i--) {
const date = subDays(today, i);
const baseUsers = 100 + i * 3;
data.push({
date: format(date, 'MMM d'),
total_users: baseUsers + Math.floor(Math.random() * 10),
active_users: Math.floor(baseUsers * 0.8) + Math.floor(Math.random() * 5),
});
// Custom tooltip with proper theme colors
const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) {
return (
<div
style={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
padding: '8px 12px',
}}
>
<p style={{ color: 'hsl(var(--popover-foreground))', margin: 0, fontSize: '13px', fontWeight: 600 }}>
{payload[0].payload.date}
</p>
<p style={{ color: 'hsl(var(--popover-foreground))', margin: '4px 0 0 0', fontSize: '12px' }}>
Total Users: {payload[0].value}
</p>
{payload[1] && (
<p style={{ color: 'hsl(var(--popover-foreground))', margin: '2px 0 0 0', fontSize: '12px' }}>
Active Users: {payload[1].value}
</p>
)}
</div>
);
}
return data;
}
return null;
};
export function UserGrowthChart({ data, loading, error }: UserGrowthChartProps) {
const chartData = data || generateMockData();
// Show empty chart if no data available
const rawData = data || [];
const hasData =
rawData.length > 0 && rawData.some((d) => d.total_users > 0 || d.active_users > 0);
return (
<ChartCard
@@ -59,54 +72,51 @@ export function UserGrowthChart({ data, loading, error }: UserGrowthChartProps)
loading={loading}
error={error}
>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
<XAxis
dataKey="date"
stroke="hsl(var(--border))"
tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12 }}
tickLine={{ stroke: 'hsl(var(--border))' }}
/>
<YAxis
stroke="hsl(var(--border))"
tick={{ fill: 'hsl(var(--muted-foreground))', fontSize: 12 }}
tickLine={{ stroke: 'hsl(var(--border))' }}
/>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
color: 'hsl(var(--popover-foreground))',
}}
labelStyle={{ color: 'hsl(var(--popover-foreground))' }}
/>
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
/>
<Line
type="monotone"
dataKey="total_users"
name="Total Users"
stroke={CHART_PALETTES.line[0]}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
/>
<Line
type="monotone"
dataKey="active_users"
name="Active Users"
stroke={CHART_PALETTES.line[1]}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
/>
</LineChart>
</ResponsiveContainer>
{!hasData && !loading && !error ? (
<div className="flex items-center justify-center h-[300px] text-muted-foreground">
<p>No user growth data available</p>
</div>
) : (
<ResponsiveContainer width="100%" height={300}>
<LineChart data={rawData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" style={{ stroke: 'var(--muted)', opacity: 0.2 }} />
<XAxis dataKey="date" style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }} />
<YAxis
style={{ fill: 'var(--muted-foreground)', fontSize: '12px' }}
label={{
value: 'Users',
angle: -90,
position: 'insideLeft',
style: { fill: 'var(--muted-foreground)', textAnchor: 'middle' },
}}
/>
<Tooltip content={<CustomTooltip />} />
<Legend
wrapperStyle={{
paddingTop: '20px',
}}
/>
<Line
type="monotone"
dataKey="total_users"
name="Total Users"
stroke={CHART_PALETTES.line[0]}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
/>
<Line
type="monotone"
dataKey="active_users"
name="Active Users"
stroke={CHART_PALETTES.line[1]}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
/>
</LineChart>
</ResponsiveContainer>
)}
</ChartCard>
);
}

View File

@@ -21,16 +21,6 @@ interface UserStatusChartProps {
error?: string | null;
}
// Generate mock data for development/demo
function generateMockData(): UserStatusData[] {
return [
{ name: 'Active', value: 142, color: CHART_PALETTES.pie[0] },
{ name: 'Inactive', value: 28, color: CHART_PALETTES.pie[1] },
{ name: 'Pending', value: 15, color: CHART_PALETTES.pie[2] },
{ name: 'Suspended', value: 5, color: CHART_PALETTES.pie[3] },
];
}
// Custom label component to show percentages
const renderLabel = (entry: { percent: number; name: string }) => {
const percent = (entry.percent * 100).toFixed(0);
@@ -38,7 +28,9 @@ const renderLabel = (entry: { percent: number; name: string }) => {
};
export function UserStatusChart({ data, loading, error }: UserStatusChartProps) {
const rawData = data || generateMockData();
// Show empty chart if no data available
const rawData = data || [];
const hasData = rawData.length > 0 && rawData.some((d) => d.value > 0);
// Assign colors if missing
const chartData = rawData.map((item, index) => ({
@@ -53,41 +45,47 @@ export function UserStatusChart({ data, loading, error }: UserStatusChartProps)
loading={loading}
error={error}
>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={chartData}
cx="50%"
cy="50%"
labelLine={false}
label={renderLabel}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{chartData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
color: 'hsl(var(--popover-foreground))',
}}
labelStyle={{ color: 'hsl(var(--popover-foreground))' }}
/>
<Legend
verticalAlign="bottom"
height={36}
wrapperStyle={{
paddingTop: '20px',
color: 'hsl(var(--foreground))',
}}
/>
</PieChart>
</ResponsiveContainer>
{!hasData && !loading && !error ? (
<div className="flex items-center justify-center h-[300px] text-muted-foreground">
<p>No user status data available</p>
</div>
) : (
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={chartData}
cx="50%"
cy="50%"
labelLine={false}
label={renderLabel}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{chartData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: 'hsl(var(--popover))',
border: '1px solid hsl(var(--border))',
borderRadius: '6px',
color: 'hsl(var(--popover-foreground))',
}}
labelStyle={{ color: 'hsl(var(--popover-foreground))' }}
/>
<Legend
verticalAlign="bottom"
height={36}
wrapperStyle={{
paddingTop: '20px',
color: 'hsl(var(--foreground))',
}}
/>
</PieChart>
</ResponsiveContainer>
)}
</ChartCard>
);
}

View File

@@ -7,7 +7,7 @@ export { UserGrowthChart } from './UserGrowthChart';
export type { UserGrowthData } from './UserGrowthChart';
export { OrganizationDistributionChart } from './OrganizationDistributionChart';
export type { OrganizationDistributionData } from './OrganizationDistributionChart';
export { SessionActivityChart } from './SessionActivityChart';
export type { SessionActivityData } from './SessionActivityChart';
export { RegistrationActivityChart } from './RegistrationActivityChart';
export type { RegistrationActivityData } from './RegistrationActivityChart';
export { UserStatusChart } from './UserStatusChart';
export type { UserStatusData } from './UserStatusChart';