mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-24 09:31:12 -05:00
feat: Implement custom view tracking
This commit is contained in:
47
src/lib/viewTracking.ts
Normal file
47
src/lib/viewTracking.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
|
||||
// Generate anonymous session hash (no PII)
|
||||
function getSessionHash(): string {
|
||||
// Check if we have a session hash in sessionStorage
|
||||
let sessionHash = sessionStorage.getItem('session_hash');
|
||||
|
||||
if (!sessionHash) {
|
||||
// Create a random hash for this session (no user data)
|
||||
sessionHash = `session_${Math.random().toString(36).substring(2, 15)}`;
|
||||
sessionStorage.setItem('session_hash', sessionHash);
|
||||
}
|
||||
|
||||
return sessionHash;
|
||||
}
|
||||
|
||||
// Debounce tracking to avoid rapid-fire views
|
||||
const trackedViews = new Set<string>();
|
||||
|
||||
export async function trackPageView(
|
||||
entityType: 'park' | 'ride' | 'company',
|
||||
entityId: string
|
||||
) {
|
||||
// Create unique key for this view
|
||||
const viewKey = `${entityType}:${entityId}`;
|
||||
|
||||
// Don't track the same entity twice in the same session
|
||||
if (trackedViews.has(viewKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
trackedViews.add(viewKey);
|
||||
|
||||
try {
|
||||
// Track view asynchronously (fire and forget)
|
||||
await supabase.from('entity_page_views').insert({
|
||||
entity_type: entityType,
|
||||
entity_id: entityId,
|
||||
session_hash: getSessionHash()
|
||||
});
|
||||
|
||||
console.log(`✅ Tracked view: ${entityType} ${entityId}`);
|
||||
} catch (error) {
|
||||
// Fail silently - don't break the page if tracking fails
|
||||
console.error('Failed to track page view:', error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user