move page

This commit is contained in:
2025-04-01 22:18:25 +08:00
parent 36f22059e9
commit 1be6a6dbf0
4 changed files with 210 additions and 441 deletions

View File

@@ -1,7 +1,10 @@
'use client';
import React from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { ProtectedRoute, useAuth } from '@/lib/auth';
import { LayoutDashboard, BarChart3, UserCircle } from 'lucide-react';
export default function AppLayoutClient({
children,
@@ -9,6 +12,13 @@ export default function AppLayoutClient({
children: React.ReactNode;
}) {
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 () => {
await signOut();
@@ -16,64 +26,56 @@ export default function AppLayoutClient({
return (
<ProtectedRoute>
<div className="min-h-screen bg-gray-50">
<nav className="bg-white border-b border-gray-200">
<div className="container mx-auto px-4">
<div className="flex items-center justify-between h-16">
<div className="flex min-h-screen bg-gray-100">
{/* 侧边栏导航 */}
<div className="fixed inset-y-0 left-0 w-64 bg-white shadow-lg">
<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">
<Link href="/" className="text-xl font-bold text-gray-900">
ShortURL Analytics
</Link>
<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>
<span className="text-sm font-medium text-gray-700 mr-4">
{user?.email}
</span>
<button
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
</button>
</div>
</div>
</div>
</nav>
<main className="container mx-auto px-4 py-8">
{children}
</main>
</header>
{/* 页面内容 */}
<main className="py-6">
{children}
</main>
</div>
</div>
</ProtectedRoute>
);

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

@@ -8,6 +8,62 @@ import GeoAnalytics from '@/app/components/analytics/GeoAnalytics';
import DevicePieCharts from '@/app/components/charts/DevicePieCharts';
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() {
const [dateRange, setDateRange] = useState({
from: new Date('2024-02-01'),
@@ -20,6 +76,8 @@ export default function DashboardPage() {
const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]);
const [geoData, setGeoData] = useState<GeoData[]>([]);
const [deviceData, setDeviceData] = useState<DeviceAnalyticsType | null>(null);
const [events, setEvents] = useState<Event[]>([]);
const [urlFilter, setUrlFilter] = useState('');
useEffect(() => {
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 [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/time-series?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([
@@ -54,6 +113,7 @@ export default function DashboardPage() {
setTimeSeriesData(timeSeriesData.data);
setGeoData(geoData.data);
setDeviceData(deviceData.data);
setEvents(eventsRes || []);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
} finally {
@@ -62,7 +122,7 @@ export default function DashboardPage() {
};
fetchData();
}, [dateRange]);
}, [dateRange, urlFilter]);
if (loading) {
return (
@@ -131,10 +191,104 @@ export default function DashboardPage() {
{deviceData && <DevicePieCharts data={deviceData} />}
</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>
<GeoAnalytics data={geoData} />
</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>
);
}

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>
);
}