diff --git a/app/analytics/page.tsx b/app/analytics/page.tsx index c767beb..692c209 100644 --- a/app/analytics/page.tsx +++ b/app/analytics/page.tsx @@ -175,9 +175,46 @@ export default function AnalyticsPage() { // 如果 localStorage 中没有匹配的数据,则从 API 获取 const fetchShortUrlData = async () => { try { - // 构建带有 URL 参数的查询字符串 - const encodedUrl = encodeURIComponent(shorturlParam); - const apiUrl = `/api/shortlinks/byUrl?url=${encodedUrl}`; + let apiUrl = ''; + + // Check if shorturlParam is a URL or an ID + if (shorturlParam.startsWith('http')) { + // Direct match by shortUrl is more reliable than URL parsing + const exactApiUrl = `/api/shortlinks/exact?shortUrl=${encodeURIComponent(shorturlParam)}`; + console.log('Fetching shorturl by exact match:', exactApiUrl); + + // Try the exact endpoint first + const response = await fetch(exactApiUrl); + + if (response.ok) { + const result = await response.json(); + + if (result.success && result.data) { + console.log('Found shortlink by exact shortUrl match:', result.data); + console.log('External ID from exact API:', result.data.externalId); + + if (result.data.externalId) { + // Save to sessionStorage for immediate use + sessionStorage.setItem('current_shorturl_external_id', result.data.externalId); + console.log('Saved external ID to sessionStorage:', result.data.externalId); + } + + // Set in store and trigger data fetch + setSelectedShortUrl(result.data); + setTimeout(() => { + setShouldFetchData(true); + }, 100); + return; + } + } + + // Fallback to old method if exact match fails + console.log('Exact match failed, trying byUrl endpoint'); + apiUrl = `/api/shortlinks/byUrl?url=${encodeURIComponent(shorturlParam)}`; + } else { + // It might be an ID or slug, try the ID endpoint directly + apiUrl = `/api/shortlinks/${shorturlParam}`; + } console.log('Fetching shorturl data from:', apiUrl); @@ -186,7 +223,7 @@ export default function AnalyticsPage() { if (!response.ok) { console.error('Failed to fetch shorturl data:', response.statusText); - // Trigger data fetching even if shortURL data fetch failed + // Still trigger data fetching to show all data instead setShouldFetchData(true); return; } @@ -196,12 +233,28 @@ export default function AnalyticsPage() { // 如果找到匹配的短链接数据 if (result.success && result.data) { console.log('Retrieved shortlink data:', result.data); + // Log the external ID explicitly for debugging + console.log('External ID from API:', result.data.externalId); + // 设置到 Zustand store (会自动更新到 localStorage) setSelectedShortUrl(result.data); + + // 强制保证 externalId 被设置到 params + const savedExternalId = result.data.externalId; + if (savedExternalId) { + // Save to sessionStorage for immediate use + sessionStorage.setItem('current_shorturl_external_id', savedExternalId); + console.log('Saved external ID to sessionStorage:', savedExternalId); + } + + // Explicitly wait for the state update to be applied + // before triggering the data fetching + setTimeout(() => { + setShouldFetchData(true); + }, 100); + } else { + setShouldFetchData(true); } - - // Trigger data fetching after shortURL data is processed - setShouldFetchData(true); } catch (error) { console.error('Error fetching shorturl data:', error); // Trigger data fetching even if there was an error @@ -275,10 +328,33 @@ export default function AnalyticsPage() { pageSize: pageSize.toString() }); - // Add linkId parameter if a shorturl is selected - if (selectedShortUrl && selectedShortUrl.id) { - params.append('linkId', selectedShortUrl.id); - console.log('Adding linkId to requests:', selectedShortUrl.id); + // Verify the shortUrl data is loaded and the externalId exists + // before adding the linkId parameter + if (selectedShortUrl) { + console.log('Current selectedShortUrl data:', selectedShortUrl); + + if (selectedShortUrl.externalId) { + params.append('linkId', selectedShortUrl.externalId); + console.log('Adding linkId (externalId) to requests:', selectedShortUrl.externalId); + } else { + // Try to get externalId from sessionStorage as backup + const savedExternalId = sessionStorage.getItem('current_shorturl_external_id'); + if (savedExternalId) { + params.append('linkId', savedExternalId); + console.log('Adding linkId from sessionStorage:', savedExternalId); + } else { + // External ID is missing - this will result in no data being returned + console.warn('WARNING: externalId is missing in the shortUrl data - no results will be returned!', selectedShortUrl); + } + } + // We now know the events table exclusively uses external_id format, so never fall back to id + + // Add an extra log to debug the issue + console.log('Complete shorturl data:', JSON.stringify({ + id: selectedShortUrl.id, + externalId: selectedShortUrl.externalId, + shortUrl: selectedShortUrl.shortUrl + })); } // 添加团队ID参数 - 支持多个团队 @@ -302,15 +378,38 @@ export default function AnalyticsPage() { }); } + // 记录构建的 URL,以确保参数正确包含 + const summaryUrl = `${baseUrl}/summary?${params.toString()}`; + const timeSeriesUrl = `${baseUrl}/time-series?${params.toString()}`; + const geoUrl = `${baseUrl}/geo?${params.toString()}`; + const devicesUrl = `${baseUrl}/devices?${params.toString()}`; + const eventsUrl = `${baseUrl}?${params.toString()}`; + + console.log('Final API URLs being called:'); + console.log('- Summary API:', summaryUrl); + console.log('- TimeSeries API:', timeSeriesUrl); + console.log(`- Params contain linkId? ${params.has('linkId')}`); + console.log(`- All params: ${params.toString()}`); + // 并行获取所有数据 const [summaryRes, timeSeriesRes, geoRes, deviceRes, eventsRes] = await Promise.all([ - fetch(`${baseUrl}/summary?${params.toString()}`), - fetch(`${baseUrl}/time-series?${params.toString()}`), - fetch(`${baseUrl}/geo?${params.toString()}`), - fetch(`${baseUrl}/devices?${params.toString()}`), - fetch(`${baseUrl}?${params.toString()}`) + fetch(summaryUrl), + fetch(timeSeriesUrl), + fetch(geoUrl), + fetch(devicesUrl), + fetch(eventsUrl) ]); + // 添加额外日志,记录完整的 URL 请求 + console.log('Summary API URL:', summaryUrl); + + if (selectedShortUrl?.externalId) { + console.log('Verifying linkId is in params:', + `linkId=${selectedShortUrl.externalId}`, + `included: ${params.toString().includes(`linkId=${selectedShortUrl.externalId}`)}` + ); + } + const [summaryData, timeSeriesData, geoData, deviceData, eventsData] = await Promise.all([ summaryRes.json(), timeSeriesRes.json(), @@ -402,6 +501,68 @@ export default function AnalyticsPage() { )} + {/* Debug info - remove in production */} + {process.env.NODE_ENV !== 'production' && ( +
external_id as link_id, not the UUID format.
+ External ID format sample: cm8x34sdr0007m11yh1xe6qc2
+