import React, { useState, useEffect } from 'react'; interface PathAnalyticsProps { startTime: string; endTime: string; linkId?: string; } interface PathData { path: string; count: number; percentage: number; } const PathAnalytics: React.FC = ({ startTime, endTime, linkId }) => { const [loading, setLoading] = useState(true); const [pathData, setPathData] = useState([]); const [error, setError] = useState(null); useEffect(() => { if (!linkId) { setLoading(false); return; } const fetchPathData = async () => { try { const params = new URLSearchParams({ startTime, endTime, linkId }); const response = await fetch(`/api/events/path-analytics?${params.toString()}`); if (!response.ok) { throw new Error('Failed to fetch path analytics data'); } const result = await response.json(); if (result.success && result.data) { // 自定义处理路径数据,根据是否有子路径来分组 const rawData = result.data; const pathMap = new Map(); let totalClicks = 0; rawData.forEach((item: PathData) => { const urlPath = item.path; totalClicks += item.count; // 解析路径,检查是否有子路径 const pathParts = urlPath.split('?')[0].split('/').filter(Boolean); // 基础路径(例如/5seaii)或者带有查询参数但没有子路径的路径视为同一个路径 // 子路径(例如/5seaii/bbbbb)单独统计 const groupKey = pathParts.length > 1 ? urlPath : `/${pathParts[0]}`; const currentCount = pathMap.get(groupKey) || 0; pathMap.set(groupKey, currentCount + item.count); }); // 转换回数组并排序 const groupedPathData = Array.from(pathMap.entries()) .map(([path, count]) => ({ path, count, percentage: totalClicks > 0 ? count / totalClicks : 0, })) .sort((a, b) => b.count - a.count); setPathData(groupedPathData); } else { setError(result.error || 'Failed to load path analytics'); } } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); } finally { setLoading(false); } }; fetchPathData(); }, [startTime, endTime, linkId]); if (loading) { return
; } if (error) { return
{error}
; } if (!linkId) { return
Select a specific link to view path analytics.
; } if (pathData.length === 0) { return
No path data available for this link.
; } return (
Note: Paths are grouped by subpath. URLs with different query parameters but the same base path (without subpath) are grouped together.
{pathData.map((item, index) => ( ))}
Path Clicks Percentage
{item.path} {item.count}
{(item.percentage * 100).toFixed(1)}%
); }; export default PathAnalytics;