/* Copyright 2026 Arctel.net Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use client'; import { useCallback, useEffect, useState } from 'react'; import { BarChart3, Globe, RefreshCw, TrendingUp, Users, XCircle, } from 'lucide-react'; import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from 'recharts'; import services from '@/lib/services'; import { useTranslations } from 'next-intl'; import { ErrorInline } from '@/components/layout/error'; import { LoadingStateWithBorder } from '@/components/layout/loading'; import { EmptyStateWithBorder } from '@/components/layout/empty'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card'; import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent, } from '@/components/ui/chart'; import { Spinner } from '@/components/ui/spinner'; interface TrendData { date: string; count: number; } interface BrowserData { browser: string; count: number; } interface TopUserData { user_id: string; username: string; nickname: string; count: number; } function useAnalyticsChartConfig() { const t = useTranslations('admin.logs.analytics'); return { count: { label: t('requestVolume'), color: 'hsl(var(--primary))', }, } satisfies ChartConfig; } // Format YYYY-MM-DD to MM/DD function formatDateLabel(dateStr: string) { if (!dateStr || dateStr.length < 10) return dateStr; const parts = dateStr.split('-'); if (parts.length === 3) { return `${parts[1]}/${parts[2]}`; } return dateStr; } export function AccessAnalytics() { const t = useTranslations('admin.logs.analytics'); const chartConfig = useAnalyticsChartConfig(); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [clickhouseDisabled, setClickhouseDisabled] = useState(false); const [trend, setTrend] = useState([]); const [browsers, setBrowsers] = useState([]); const [topUsers, setTopUsers] = useState([]); const fetchAnalytics = useCallback(async () => { try { setLoading(true); setError(null); const data = await services.adminLog.getLogsAnalytics(); // Formats the date labels for the X-axis representation const formattedTrend = (data.trend || []).map((item) => ({ ...item, formattedDate: formatDateLabel(item.date), })); setTrend(formattedTrend); setBrowsers(data.browsers || []); setTopUsers(data.top_users || []); setClickhouseDisabled(false); } catch (err) { const errorInstance = err instanceof Error ? err : new Error(t('fetchFailed')); const errMsg = errorInstance.message || ''; if (errMsg.includes('ClickHouse') || errMsg.includes('未启用')) { setClickhouseDisabled(true); } else { setError(errorInstance); } } finally { setLoading(false); } }, [t]); useEffect(() => { fetchAnalytics(); }, [fetchAnalytics]); const totalBrowserRequests = browsers.reduce( (sum, item) => sum + item.count, 0, ); const totalTrendRequests = trend.reduce((sum, item) => sum + item.count, 0); if (clickhouseDisabled) { return (

{t('clickhouseDisabled')}

{t('clickhouseDisabledDesc')}

); } if (error) { return ; } if (loading) { return ( ); } return (
{/* Overview Cards */}
{t('totalRequests7d')}
{totalTrendRequests.toLocaleString()}

{t('totalRequests7dDesc')}

{t('activeBrowserTypes')}
{browsers.length}

{t('activeBrowserTypesDesc')}

{t('activeUsers')}
{topUsers.length}

{t('activeUsersDesc')}

{/* Access Trend Chart */}
{t('weeklyAccessTrend')} {t('weeklyAccessTrendDesc')}
{trend.length === 0 ? ( ) : (
} />
)}
{/* Two Columns for Ranking Statistics */}
{/* Browser Rankings */} {t('browserRanking')} {t('browserRankingDesc')} {browsers.length === 0 ? ( ) : (
{browsers.map((item, index) => { const percent = totalBrowserRequests > 0 ? (item.count / totalBrowserRequests) * 100 : 0; return (
{index + 1} {item.browser} {t('countTimes', { count: item.count.toLocaleString(), percent: percent.toFixed(1), })}
); })}
)} {/* Top Users */} {t('topActiveUsers')} {t('topActiveUsersDesc')} {topUsers.length === 0 ? ( ) : (
{topUsers.map((user) => (
{(user.username || 'U').slice(0, 1).toUpperCase()}
{user.username || t('unknown')}
{user.nickname ? `(${user.nickname})` : t('noNickname')}{' '} | ID: {user.user_id}
{user.count.toLocaleString()}
{t('requests')}
))}
)}
); }