Compare commits

2 Commits

Author SHA1 Message Date
1be6a6dbf0 move page 2025-04-01 22:18:25 +08:00
36f22059e9 move device 2025-04-01 21:22:23 +08:00
6 changed files with 423 additions and 751 deletions

View File

@@ -1,7 +1,10 @@
'use client'; 'use client';
import React from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { ProtectedRoute, useAuth } from '@/lib/auth'; import { ProtectedRoute, useAuth } from '@/lib/auth';
import { LayoutDashboard, BarChart3, UserCircle } from 'lucide-react';
export default function AppLayoutClient({ export default function AppLayoutClient({
children, children,
@@ -9,6 +12,13 @@ export default function AppLayoutClient({
children: React.ReactNode; children: React.ReactNode;
}) { }) {
const { signOut, user } = useAuth(); const { signOut, user } = useAuth();
const pathname = usePathname();
const navigationItems = [
{ name: 'Dashboard', href: '/dashboard', icon: <LayoutDashboard className="h-5 w-5" /> },
{ name: 'Analytics', href: '/analytics', icon: <BarChart3 className="h-5 w-5" /> },
{ name: 'Account', href: '/account', icon: <UserCircle className="h-5 w-5" /> },
];
const handleSignOut = async () => { const handleSignOut = async () => {
await signOut(); await signOut();
@@ -16,64 +26,56 @@ export default function AppLayoutClient({
return ( return (
<ProtectedRoute> <ProtectedRoute>
<div className="min-h-screen bg-gray-50"> <div className="flex min-h-screen bg-gray-100">
<nav className="bg-white border-b border-gray-200"> {/* 侧边栏导航 */}
<div className="container mx-auto px-4"> <div className="fixed inset-y-0 left-0 w-64 bg-white shadow-lg">
<div className="flex items-center justify-between h-16"> <div className="flex h-16 items-center px-6 border-b">
<Link href="/" className="text-lg font-medium text-gray-900">
ShortURL Analytics
</Link>
</div>
<nav className="mt-4 px-2">
{navigationItems.map((item) => (
<Link
key={item.href}
href={item.href}
className={`flex items-center px-3 py-2 mt-2 rounded-md text-sm font-medium ${
pathname === item.href || pathname?.startsWith(`${item.href}/`)
? 'bg-blue-100 text-blue-600'
: 'text-gray-700 hover:bg-gray-100'
}`}
>
<span className="mr-3">{item.icon}</span>
{item.name}
</Link>
))}
</nav>
</div>
{/* 主内容区域 */}
<div className="flex-1 ml-64">
{/* 顶部导航栏 */}
<header className="bg-white shadow-sm">
<div className="flex h-16 items-center justify-end px-6">
<div className="flex items-center"> <div className="flex items-center">
<Link href="/" className="text-xl font-bold text-gray-900"> <span className="text-sm font-medium text-gray-700 mr-4">
ShortURL Analytics {user?.email}
</Link> </span>
<div className="hidden md:block ml-10">
<div className="flex items-baseline space-x-4">
<Link
href="/dashboard"
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
>
Dashboard
</Link>
<Link
href="/analytics"
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
>
Analytics
</Link>
<Link
href="/events"
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
>
Events
</Link>
<Link
href="/analytics/geo"
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
>
Geographic
</Link>
<Link
href="/analytics/devices"
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
>
Devices
</Link>
</div>
</div>
</div>
<div className="flex items-center">
<span className="text-sm text-gray-500 mr-4">{user?.email}</span>
<button <button
onClick={handleSignOut} onClick={handleSignOut}
className="text-gray-500 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium" className="px-3 py-1.5 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
> >
Sign Out Sign Out
</button> </button>
</div> </div>
</div> </div>
</div> </header>
</nav>
<main className="container mx-auto px-4 py-8"> {/* 页面内容 */}
{children} <main className="py-6">
</main> {children}
</main>
</div>
</div> </div>
</ProtectedRoute> </ProtectedRoute>
); );

View File

@@ -1,308 +0,0 @@
"use client";
import { useState, useEffect, useRef } from 'react';
import { DeviceAnalytics } from '@/app/api/types';
import { Chart, PieController, ArcElement, Tooltip, Legend, CategoryScale, LinearScale } from 'chart.js';
// 注册Chart.js组件
Chart.register(PieController, ArcElement, Tooltip, Legend, CategoryScale, LinearScale);
export default function DeviceAnalyticsPage() {
const [deviceData, setDeviceData] = useState<DeviceAnalytics | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dateRange, setDateRange] = useState({
from: new Date('2024-02-01'),
to: new Date('2025-03-05')
});
// 创建图表引用
const deviceTypesChartRef = useRef<HTMLCanvasElement>(null);
const browsersChartRef = useRef<HTMLCanvasElement>(null);
const osChartRef = useRef<HTMLCanvasElement>(null);
// 图表实例引用
const deviceTypesChartInstance = useRef<Chart | null>(null);
const browsersChartInstance = useRef<Chart | null>(null);
const osChartInstance = useRef<Chart | null>(null);
// 颜色配置
const COLORS = {
deviceTypes: ['rgba(59, 130, 246, 0.8)', 'rgba(96, 165, 250, 0.8)', 'rgba(147, 197, 253, 0.8)', 'rgba(191, 219, 254, 0.8)', 'rgba(219, 234, 254, 0.8)'],
browsers: ['rgba(16, 185, 129, 0.8)', 'rgba(52, 211, 153, 0.8)', 'rgba(110, 231, 183, 0.8)', 'rgba(167, 243, 208, 0.8)', 'rgba(209, 250, 229, 0.8)'],
os: ['rgba(239, 68, 68, 0.8)', 'rgba(248, 113, 113, 0.8)', 'rgba(252, 165, 165, 0.8)', 'rgba(254, 202, 202, 0.8)', 'rgba(254, 226, 226, 0.8)']
};
useEffect(() => {
const fetchDeviceData = async () => {
try {
setIsLoading(true);
setError(null);
const response = await fetch(`/api/events/devices?startTime=${dateRange.from.toISOString().split('T')[0]}T00:00:00Z&endTime=${dateRange.to.toISOString().split('T')[0]}T23:59:59Z`);
if (!response.ok) throw new Error('Failed to fetch device data');
const data = await response.json();
setDeviceData(data.data);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setIsLoading(false);
}
};
fetchDeviceData();
}, [dateRange]);
// 初始化和更新图表
useEffect(() => {
if (!deviceData || isLoading) return;
// 销毁旧的图表实例
if (deviceTypesChartInstance.current) {
deviceTypesChartInstance.current.destroy();
}
if (browsersChartInstance.current) {
browsersChartInstance.current.destroy();
}
if (osChartInstance.current) {
osChartInstance.current.destroy();
}
// 创建设备类型图表
if (deviceTypesChartRef.current && deviceData.deviceTypes.length > 0) {
const ctx = deviceTypesChartRef.current.getContext('2d');
if (ctx) {
deviceTypesChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: deviceData.deviceTypes.map(item => item.type),
datasets: [{
data: deviceData.deviceTypes.map(item => item.count),
backgroundColor: COLORS.deviceTypes,
borderColor: COLORS.deviceTypes.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 创建浏览器图表
if (browsersChartRef.current && deviceData.browsers.length > 0) {
const ctx = browsersChartRef.current.getContext('2d');
if (ctx) {
browsersChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: deviceData.browsers.map(item => item.name),
datasets: [{
data: deviceData.browsers.map(item => item.count),
backgroundColor: COLORS.browsers,
borderColor: COLORS.browsers.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 创建操作系统图表
if (osChartRef.current && deviceData.operatingSystems.length > 0) {
const ctx = osChartRef.current.getContext('2d');
if (ctx) {
osChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: deviceData.operatingSystems.map(item => item.name),
datasets: [{
data: deviceData.operatingSystems.map(item => item.count),
backgroundColor: COLORS.os,
borderColor: COLORS.os.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 清理函数
return () => {
if (deviceTypesChartInstance.current) {
deviceTypesChartInstance.current.destroy();
}
if (browsersChartInstance.current) {
browsersChartInstance.current.destroy();
}
if (osChartInstance.current) {
osChartInstance.current.destroy();
}
};
}, [deviceData, isLoading]);
return (
<div className="container mx-auto px-4 py-8">
{/* 页面标题 */}
<div className="mb-8">
<h1 className="text-2xl font-bold text-foreground">Device Analytics</h1>
<p className="mt-2 text-foreground">Analyze visitor distribution by devices, browsers, and operating systems</p>
</div>
{/* 时间范围选择器 */}
<div className="bg-card-bg rounded-xl p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-foreground mb-1">Start Date</label>
<input
type="date"
className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm text-foreground"
value={dateRange.from.toISOString().split('T')[0]}
onChange={e => setDateRange(prev => ({ ...prev, from: new Date(e.target.value) }))}
/>
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-1">End Date</label>
<input
type="date"
className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm text-foreground"
value={dateRange.to.toISOString().split('T')[0]}
onChange={e => setDateRange(prev => ({ ...prev, to: new Date(e.target.value) }))}
/>
</div>
</div>
</div>
{/* 设备类型分析 */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
{/* 设备类型 */}
<div className="bg-card-bg rounded-xl p-6">
<h3 className="text-lg font-medium text-foreground mb-4">Device Types</h3>
{deviceData && deviceData.deviceTypes.length > 0 ? (
<div className="h-64">
<canvas ref={deviceTypesChartRef} />
</div>
) : (
<div className="flex justify-center items-center h-64 text-foreground">
No data available
</div>
)}
</div>
{/* 浏览器 */}
<div className="bg-card-bg rounded-xl p-6">
<h3 className="text-lg font-medium text-foreground mb-4">Browsers</h3>
{deviceData && deviceData.browsers.length > 0 ? (
<div className="h-64">
<canvas ref={browsersChartRef} />
</div>
) : (
<div className="flex justify-center items-center h-64 text-foreground">
No data available
</div>
)}
</div>
{/* 操作系统 */}
<div className="bg-card-bg rounded-xl p-6">
<h3 className="text-lg font-medium text-foreground mb-4">Operating Systems</h3>
{deviceData && deviceData.operatingSystems.length > 0 ? (
<div className="h-64">
<canvas ref={osChartRef} />
</div>
) : (
<div className="flex justify-center items-center h-64 text-foreground">
No data available
</div>
)}
</div>
</div>
{/* 加载状态 */}
{isLoading && (
<div className="flex justify-center items-center p-8">
<div className="w-8 h-8 border-t-2 border-b-2 border-accent-blue rounded-full animate-spin"></div>
</div>
)}
{/* 错误状态 */}
{error && (
<div className="flex justify-center items-center p-8 text-accent-red">
<p>{error}</p>
</div>
)}
{/* 无数据状态 */}
{!isLoading && !error && !deviceData && (
<div className="flex justify-center items-center p-8 text-foreground">
<p>No device data available</p>
</div>
)}
</div>
);
}

View File

@@ -1,137 +0,0 @@
"use client";
import { useState, useEffect } from 'react';
import { GeoData } from '../../api/types';
export default function GeoAnalyticsPage() {
const [geoData, setGeoData] = useState<GeoData[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [dateRange, setDateRange] = useState({
from: new Date('2024-02-01'),
to: new Date('2025-03-05')
});
useEffect(() => {
const fetchGeoData = async () => {
try {
setIsLoading(true);
setError(null);
const response = await fetch(`/api/events/geo?startTime=${dateRange.from.toISOString().split('T')[0]}T00:00:00Z&endTime=${dateRange.to.toISOString().split('T')[0]}T23:59:59Z`);
if (!response.ok) throw new Error('Failed to fetch geographic data');
const data = await response.json();
setGeoData(data.data);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setIsLoading(false);
}
};
fetchGeoData();
}, [dateRange]);
return (
<div className="container mx-auto px-4 py-8">
{/* 页面标题 */}
<div className="mb-8">
<h1 className="text-2xl font-bold text-foreground">Geographic Analysis</h1>
<p className="mt-2 text-foreground">Analyze visitor distribution by location</p>
</div>
{/* 时间范围选择器 */}
<div className="bg-card-bg rounded-xl p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-foreground mb-1">Start Date</label>
<input
type="date"
className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm text-foreground"
value={dateRange.from.toISOString().split('T')[0]}
onChange={e => setDateRange(prev => ({ ...prev, from: new Date(e.target.value) }))}
/>
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-1">End Date</label>
<input
type="date"
className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm text-foreground"
value={dateRange.to.toISOString().split('T')[0]}
onChange={e => setDateRange(prev => ({ ...prev, to: new Date(e.target.value) }))}
/>
</div>
</div>
</div>
{/* 地理数据表格 */}
<div className="bg-card-bg rounded-xl shadow-sm overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-card-border">
<thead>
<tr className="bg-background/50">
<th className="px-6 py-3 text-left text-xs font-medium text-foreground uppercase tracking-wider">Location</th>
<th className="px-6 py-3 text-left text-xs font-medium text-foreground uppercase tracking-wider">Visits</th>
<th className="px-6 py-3 text-left text-xs font-medium text-foreground uppercase tracking-wider">Unique Visitors</th>
<th className="px-6 py-3 text-left text-xs font-medium text-foreground uppercase tracking-wider">Percentage</th>
</tr>
</thead>
<tbody className="divide-y divide-card-border">
{geoData.map(item => (
<tr key={item.location} className="hover:bg-background/50">
<td className="px-6 py-4 whitespace-nowrap text-sm text-foreground">
{item.location}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-foreground">
{item.visits}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-foreground">
{item.visitors}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center">
<span className="mr-2 text-foreground">{item.percentage.toFixed(1)}%</span>
<div className="w-24 bg-gray-200 rounded-full h-2">
<div
className="bg-blue-500 h-2 rounded-full"
style={{ width: `${item.percentage}%` }}
/>
</div>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* 加载状态 */}
{isLoading && (
<div className="flex justify-center items-center p-8">
<div className="w-8 h-8 border-t-2 border-b-2 border-accent-blue rounded-full animate-spin"></div>
</div>
)}
{/* 错误状态 */}
{error && (
<div className="flex justify-center items-center p-8 text-accent-red">
<p>{error}</p>
</div>
)}
{/* 无数据状态 */}
{!isLoading && !error && geoData.length === 0 && (
<div className="flex justify-center items-center p-8 text-foreground">
<p>No geographic data available</p>
</div>
)}
</div>
{/* 提示信息 */}
<div className="mt-4 text-sm text-foreground">
<p>Note: Geographic data is based on IP addresses and may not be 100% accurate.</p>
</div>
</div>
);
}

View File

@@ -5,9 +5,65 @@ import { format } from 'date-fns';
import { DateRangePicker } from '@/app/components/ui/DateRangePicker'; import { DateRangePicker } from '@/app/components/ui/DateRangePicker';
import TimeSeriesChart from '@/app/components/charts/TimeSeriesChart'; import TimeSeriesChart from '@/app/components/charts/TimeSeriesChart';
import GeoAnalytics from '@/app/components/analytics/GeoAnalytics'; import GeoAnalytics from '@/app/components/analytics/GeoAnalytics';
import DeviceAnalytics from '@/app/components/analytics/DeviceAnalytics'; import DevicePieCharts from '@/app/components/charts/DevicePieCharts';
import { EventsSummary, TimeSeriesData, GeoData, DeviceAnalytics as DeviceAnalyticsType } from '@/app/api/types'; import { EventsSummary, TimeSeriesData, GeoData, DeviceAnalytics as DeviceAnalyticsType } from '@/app/api/types';
// 事件类型定义
interface Event {
event_id?: string;
url_id: string;
url: string;
event_type: string;
visitor_id: string;
created_at: string;
referrer?: string;
browser?: string;
os?: string;
device_type?: string;
country?: string;
city?: string;
}
// 获取事件的函数
const fetchEvents = async (
startTime?: string,
endTime?: string,
urlId?: string,
eventType?: string
): Promise<Event[]> => {
try {
// 构建查询参数
const params = new URLSearchParams();
if (startTime) params.append('startTime', startTime);
if (endTime) params.append('endTime', endTime);
if (urlId) params.append('urlId', urlId);
if (eventType) params.append('eventType', eventType);
// 发送请求
const response = await fetch(`/api/events?${params.toString()}`);
if (!response.ok) {
throw new Error('Failed to fetch events');
}
const data = await response.json();
return data.data || [];
} catch (error) {
console.error('Error fetching events:', error);
return [];
}
};
// 格式化日期函数
const formatDate = (dateString: string) => {
if (!dateString) return '';
try {
return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
} catch {
return dateString;
}
};
export default function DashboardPage() { export default function DashboardPage() {
const [dateRange, setDateRange] = useState({ const [dateRange, setDateRange] = useState({
from: new Date('2024-02-01'), from: new Date('2024-02-01'),
@@ -20,6 +76,8 @@ export default function DashboardPage() {
const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]); const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]);
const [geoData, setGeoData] = useState<GeoData[]>([]); const [geoData, setGeoData] = useState<GeoData[]>([]);
const [deviceData, setDeviceData] = useState<DeviceAnalyticsType | null>(null); const [deviceData, setDeviceData] = useState<DeviceAnalyticsType | null>(null);
const [events, setEvents] = useState<Event[]>([]);
const [urlFilter, setUrlFilter] = useState('');
useEffect(() => { useEffect(() => {
const fetchData = async () => { const fetchData = async () => {
@@ -31,11 +89,12 @@ export default function DashboardPage() {
const endTime = format(dateRange.to, "yyyy-MM-dd'T'HH:mm:ss'Z'"); const endTime = format(dateRange.to, "yyyy-MM-dd'T'HH:mm:ss'Z'");
// 并行获取所有数据 // 并行获取所有数据
const [summaryRes, timeSeriesRes, geoRes, deviceRes] = await Promise.all([ const [summaryRes, timeSeriesRes, geoRes, deviceRes, eventsRes] = await Promise.all([
fetch(`/api/events/summary?startTime=${startTime}&endTime=${endTime}`), fetch(`/api/events/summary?startTime=${startTime}&endTime=${endTime}`),
fetch(`/api/events/time-series?startTime=${startTime}&endTime=${endTime}`), fetch(`/api/events/time-series?startTime=${startTime}&endTime=${endTime}`),
fetch(`/api/events/geo?startTime=${startTime}&endTime=${endTime}`), fetch(`/api/events/geo?startTime=${startTime}&endTime=${endTime}`),
fetch(`/api/events/devices?startTime=${startTime}&endTime=${endTime}`) fetch(`/api/events/devices?startTime=${startTime}&endTime=${endTime}`),
fetchEvents(startTime, endTime, urlFilter || undefined)
]); ]);
const [summaryData, timeSeriesData, geoData, deviceData] = await Promise.all([ const [summaryData, timeSeriesData, geoData, deviceData] = await Promise.all([
@@ -54,6 +113,7 @@ export default function DashboardPage() {
setTimeSeriesData(timeSeriesData.data); setTimeSeriesData(timeSeriesData.data);
setGeoData(geoData.data); setGeoData(geoData.data);
setDeviceData(deviceData.data); setDeviceData(deviceData.data);
setEvents(eventsRes || []);
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred while fetching data'); setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
} finally { } finally {
@@ -62,7 +122,7 @@ export default function DashboardPage() {
}; };
fetchData(); fetchData();
}, [dateRange]); }, [dateRange, urlFilter]);
if (loading) { if (loading) {
return ( return (
@@ -128,13 +188,107 @@ export default function DashboardPage() {
<div className="mb-8"> <div className="mb-8">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Device Analytics</h2> <h2 className="text-lg font-semibold text-gray-900 mb-4">Device Analytics</h2>
{deviceData && <DeviceAnalytics data={deviceData} />} {deviceData && <DevicePieCharts data={deviceData} />}
</div> </div>
<div className="bg-white rounded-lg shadow p-6"> <div className="bg-white rounded-lg shadow p-6 mb-8">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Geographic Distribution</h2> <h2 className="text-lg font-semibold text-gray-900 mb-4">Geographic Distribution</h2>
<GeoAnalytics data={geoData} /> <GeoAnalytics data={geoData} />
</div> </div>
{/* 事件列表部分 */}
<div className="bg-white rounded-lg shadow overflow-hidden mb-8">
<div className="p-6 border-b border-gray-200">
<h2 className="text-lg font-semibold text-gray-900 mb-4">Recent Events</h2>
<div className="flex items-center space-x-4 mb-4">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-500 mb-1">
Filter by URL ID
</label>
<input
type="text"
value={urlFilter}
onChange={e => setUrlFilter(e.target.value)}
className="w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
placeholder="Enter URL ID to filter"
/>
</div>
</div>
</div>
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Time
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
URL ID
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
URL
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Event Type
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Visitor ID
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Referrer
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Location
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{events.map((event, index) => (
<tr key={event.event_id || index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatDate(event.created_at)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.url_id}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<a href={event.url} className="text-blue-600 hover:underline" target="_blank" rel="noopener noreferrer">
{event.url}
</a>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
event.event_type === 'click'
? 'bg-green-100 text-green-800'
: 'bg-blue-100 text-blue-800'
}`}>
{event.event_type}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.visitor_id.substring(0, 8)}...
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.referrer || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.country && event.city ? `${event.city}, ${event.country}` : (event.country || '-')}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* 表格为空状态 */}
{!loading && events.length === 0 && (
<div className="flex justify-center items-center p-8 text-gray-500">
No events found
</div>
)}
</div>
</div> </div>
); );
} }

View File

@@ -1,250 +0,0 @@
"use client";
import { useState, useEffect } from 'react';
import { format } from 'date-fns';
// 更复杂的事件类型定义
interface Event {
event_id?: string;
url_id: string;
url: string;
event_type: string;
visitor_id: string;
created_at: string;
referrer?: string;
browser?: string;
os?: string;
device_type?: string;
country?: string;
city?: string;
}
// 创建获取事件的函数
const fetchEvents = async (
startTime?: string,
endTime?: string,
urlId?: string,
eventType?: string
): Promise<Event[]> => {
try {
// 构建查询参数
const params = new URLSearchParams();
if (startTime) params.append('startTime', startTime);
if (endTime) params.append('endTime', endTime);
if (urlId) params.append('urlId', urlId);
if (eventType) params.append('eventType', eventType);
// 发送请求
const response = await fetch(`/api/events?${params.toString()}`);
if (!response.ok) {
throw new Error('Failed to fetch events');
}
const data = await response.json();
return data.data || [];
} catch (error) {
console.error('Error fetching events:', error);
return [];
}
};
const formatDate = (dateString: string) => {
if (!dateString) return '';
try {
return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
} catch {
return dateString;
}
};
export default function EventsPage() {
// 状态定义
const [events, setEvents] = useState<Event[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [filters, setFilters] = useState({
startDate: format(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd'),
endDate: format(new Date(), 'yyyy-MM-dd'),
urlId: '',
eventType: ''
});
// 加载事件数据
useEffect(() => {
const loadEvents = async () => {
setLoading(true);
setError(null);
try {
const startTime = `${filters.startDate}T00:00:00Z`;
const endTime = `${filters.endDate}T23:59:59Z`;
const eventsData = await fetchEvents(
startTime,
endTime,
filters.urlId || undefined,
filters.eventType || undefined
);
setEvents(eventsData);
} catch (err) {
setError('Failed to load events');
console.error(err);
} finally {
setLoading(false);
}
};
loadEvents();
}, [filters]);
// 处理筛选条件变化
const handleFilterChange = (name: string, value: string) => {
setFilters(prev => ({
...prev,
[name]: value
}));
};
return (
<div className="container mx-auto px-4 py-8">
{/* 页面标题 */}
<div className="mb-8">
<h1 className="text-2xl font-bold text-gray-900">Events</h1>
<p className="mt-2 text-gray-600">View and analyze all events for your URLs</p>
</div>
{/* 过滤器面板 */}
<div className="bg-white rounded-lg shadow p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div>
<label className="block text-sm font-medium text-gray-500 mb-1">
Start Date
</label>
<input
type="date"
value={filters.startDate}
onChange={e => handleFilterChange('startDate', e.target.value)}
className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-500 mb-1">
End Date
</label>
<input
type="date"
value={filters.endDate}
onChange={e => handleFilterChange('endDate', e.target.value)}
className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-500 mb-1">
URL ID
</label>
<input
type="text"
value={filters.urlId}
onChange={e => handleFilterChange('urlId', e.target.value)}
className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
placeholder="Filter by URL ID"
/>
</div>
</div>
</div>
{/* 事件表格 */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Time
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
URL ID
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
URL
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Event Type
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Visitor ID
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Referrer
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Location
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{events.map((event, index) => (
<tr key={event.event_id || index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatDate(event.created_at)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.url_id}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<a href={event.url} className="text-blue-600 hover:underline" target="_blank" rel="noopener noreferrer">
{event.url}
</a>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
event.event_type === 'click'
? 'bg-green-100 text-green-800'
: 'bg-blue-100 text-blue-800'
}`}>
{event.event_type}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.visitor_id.substring(0, 8)}...
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.referrer || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.country && event.city ? `${event.city}, ${event.country}` : (event.country || '-')}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* 加载状态 */}
{loading && (
<div className="flex justify-center items-center p-8">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
</div>
)}
{/* 错误状态 */}
{error && (
<div className="flex justify-center items-center p-8 text-red-500">
{error}
</div>
)}
{/* 空状态 */}
{!loading && !error && events.length === 0 && (
<div className="flex justify-center items-center p-8 text-gray-500">
No events found
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,211 @@
'use client';
import { useEffect, useRef } from 'react';
import { DeviceAnalytics } from '@/app/api/types';
import { Chart, PieController, ArcElement, Tooltip, Legend, CategoryScale, LinearScale } from 'chart.js';
// 注册Chart.js组件
Chart.register(PieController, ArcElement, Tooltip, Legend, CategoryScale, LinearScale);
interface DevicePieChartsProps {
data: DeviceAnalytics;
}
// 颜色配置
const COLORS = {
deviceTypes: ['rgba(59, 130, 246, 0.8)', 'rgba(96, 165, 250, 0.8)', 'rgba(147, 197, 253, 0.8)', 'rgba(191, 219, 254, 0.8)', 'rgba(219, 234, 254, 0.8)'],
browsers: ['rgba(16, 185, 129, 0.8)', 'rgba(52, 211, 153, 0.8)', 'rgba(110, 231, 183, 0.8)', 'rgba(167, 243, 208, 0.8)', 'rgba(209, 250, 229, 0.8)'],
os: ['rgba(239, 68, 68, 0.8)', 'rgba(248, 113, 113, 0.8)', 'rgba(252, 165, 165, 0.8)', 'rgba(254, 202, 202, 0.8)', 'rgba(254, 226, 226, 0.8)']
};
export default function DevicePieCharts({ data }: DevicePieChartsProps) {
// 创建图表引用
const deviceTypesChartRef = useRef<HTMLCanvasElement>(null);
const browsersChartRef = useRef<HTMLCanvasElement>(null);
const osChartRef = useRef<HTMLCanvasElement>(null);
// 图表实例引用
const deviceTypesChartInstance = useRef<Chart | null>(null);
const browsersChartInstance = useRef<Chart | null>(null);
const osChartInstance = useRef<Chart | null>(null);
// 初始化和更新图表
useEffect(() => {
if (!data) return;
// 销毁旧的图表实例
if (deviceTypesChartInstance.current) {
deviceTypesChartInstance.current.destroy();
}
if (browsersChartInstance.current) {
browsersChartInstance.current.destroy();
}
if (osChartInstance.current) {
osChartInstance.current.destroy();
}
// 创建设备类型图表
if (deviceTypesChartRef.current && data.deviceTypes.length > 0) {
const ctx = deviceTypesChartRef.current.getContext('2d');
if (ctx) {
deviceTypesChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: data.deviceTypes.map(item => item.type),
datasets: [{
data: data.deviceTypes.map(item => item.count),
backgroundColor: COLORS.deviceTypes,
borderColor: COLORS.deviceTypes.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 创建浏览器图表
if (browsersChartRef.current && data.browsers.length > 0) {
const ctx = browsersChartRef.current.getContext('2d');
if (ctx) {
browsersChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: data.browsers.map(item => item.name),
datasets: [{
data: data.browsers.map(item => item.count),
backgroundColor: COLORS.browsers,
borderColor: COLORS.browsers.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 创建操作系统图表
if (osChartRef.current && data.operatingSystems.length > 0) {
const ctx = osChartRef.current.getContext('2d');
if (ctx) {
osChartInstance.current = new Chart(ctx, {
type: 'pie',
data: {
labels: data.operatingSystems.map(item => item.name),
datasets: [{
data: data.operatingSystems.map(item => item.count),
backgroundColor: COLORS.os,
borderColor: COLORS.os.map(color => color.replace('0.8', '1')),
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom',
labels: {
color: 'currentColor'
}
},
tooltip: {
callbacks: {
label: function(context) {
const label = context.label || '';
const value = context.raw as number;
const total = (context.chart.data.datasets[0].data as number[]).reduce((a, b) => (a as number) + (b as number), 0);
const percentage = Math.round((value * 100) / total);
return `${label}: ${value} (${percentage}%)`;
}
}
}
}
}
});
}
}
// 清理函数
return () => {
if (deviceTypesChartInstance.current) {
deviceTypesChartInstance.current.destroy();
}
if (browsersChartInstance.current) {
browsersChartInstance.current.destroy();
}
if (osChartInstance.current) {
osChartInstance.current.destroy();
}
};
}, [data]);
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* 设备类型 */}
<div className="bg-white rounded-lg shadow p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Device Types</h3>
<div className="h-64">
<canvas ref={deviceTypesChartRef} />
</div>
</div>
{/* 浏览器 */}
<div className="bg-white rounded-lg shadow p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Browsers</h3>
<div className="h-64">
<canvas ref={browsersChartRef} />
</div>
</div>
{/* 操作系统 */}
<div className="bg-white rounded-lg shadow p-6">
<h3 className="text-lg font-semibold text-gray-900 mb-4">Operating Systems</h3>
<div className="h-64">
<canvas ref={osChartRef} />
</div>
</div>
</div>
);
}