feat: Implement custom view tracking

This commit is contained in:
gpt-engineer-app[bot]
2025-10-10 15:53:56 +00:00
parent c39aba6994
commit 4d2d39fb5a
10 changed files with 288 additions and 58 deletions

View File

@@ -6,9 +6,7 @@ import { Park, Ride } from '@/types/database';
import { supabase } from '@/integrations/supabase/client'; import { supabase } from '@/integrations/supabase/client';
export function ContentTabs() { export function ContentTabs() {
const [popularParks, setPopularParks] = useState<Park[]>([]);
const [trendingParks, setTrendingParks] = useState<Park[]>([]); const [trendingParks, setTrendingParks] = useState<Park[]>([]);
const [popularRides, setPopularRides] = useState<Ride[]>([]);
const [trendingRides, setTrendingRides] = useState<Ride[]>([]); const [trendingRides, setTrendingRides] = useState<Ride[]>([]);
const [recentParks, setRecentParks] = useState<Park[]>([]); const [recentParks, setRecentParks] = useState<Park[]>([]);
const [recentRides, setRecentRides] = useState<Ride[]>([]); const [recentRides, setRecentRides] = useState<Ride[]>([]);
@@ -20,18 +18,11 @@ export function ContentTabs() {
const fetchContent = async () => { const fetchContent = async () => {
try { try {
// Most Popular Parks (by rating) // Trending Parks (by 30-day view count)
const { data: popular } = await supabase
.from('parks')
.select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
.order('average_rating', { ascending: false })
.limit(12);
// Trending Parks (by review count)
const { data: trending } = await supabase const { data: trending } = await supabase
.from('parks') .from('parks')
.select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`) .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
.order('review_count', { ascending: false }) .order('view_count_30d', { ascending: false })
.limit(12); .limit(12);
// Recently Added Parks // Recently Added Parks
@@ -41,18 +32,11 @@ export function ContentTabs() {
.order('created_at', { ascending: false }) .order('created_at', { ascending: false })
.limit(12); .limit(12);
// Popular Rides (by rating) // Trending Rides (by 30-day view count)
const { data: popularRidesData } = await supabase
.from('rides')
.select(`*, park:parks!inner(name, slug, location:locations(*))`)
.order('average_rating', { ascending: false })
.limit(12);
// Trending Rides (by review count)
const { data: trendingRidesData } = await supabase const { data: trendingRidesData } = await supabase
.from('rides') .from('rides')
.select(`*, park:parks!inner(name, slug, location:locations(*))`) .select(`*, park:parks!inner(name, slug, location:locations(*))`)
.order('review_count', { ascending: false }) .order('view_count_30d', { ascending: false })
.limit(12); .limit(12);
// Recently Added Rides // Recently Added Rides
@@ -62,10 +46,8 @@ export function ContentTabs() {
.order('created_at', { ascending: false }) .order('created_at', { ascending: false })
.limit(12); .limit(12);
setPopularParks(popular || []);
setTrendingParks(trending || []); setTrendingParks(trending || []);
setRecentParks(recent || []); setRecentParks(recent || []);
setPopularRides(popularRidesData || []);
setTrendingRides(trendingRidesData || []); setTrendingRides(trendingRidesData || []);
setRecentRides(recentRidesData || []); setRecentRides(recentRidesData || []);
} catch (error) { } catch (error) {
@@ -96,18 +78,12 @@ export function ContentTabs() {
return ( return (
<section className="py-8"> <section className="py-8">
<div className="container mx-auto px-4"> <div className="container mx-auto px-4">
<Tabs defaultValue="popular-parks" className="w-full"> <Tabs defaultValue="trending-parks" className="w-full">
<div className="text-center mb-8"> <div className="text-center mb-8">
<TabsList className="grid w-full max-w-4xl mx-auto grid-cols-3 md:grid-cols-6 h-auto p-2 bg-gradient-to-r from-primary/10 via-secondary/10 to-accent/10 dark:from-primary/20 dark:via-secondary/20 dark:to-accent/20 dark:bg-card/50 border border-primary/20 dark:border-primary/30 rounded-xl shadow-lg backdrop-blur-sm"> <TabsList className="grid w-full max-w-3xl mx-auto grid-cols-2 md:grid-cols-4 h-auto p-2 bg-gradient-to-r from-primary/10 via-secondary/10 to-accent/10 dark:from-primary/20 dark:via-secondary/20 dark:to-accent/20 dark:bg-card/50 border border-primary/20 dark:border-primary/30 rounded-xl shadow-lg backdrop-blur-sm">
<TabsTrigger value="popular-parks" className="text-xs md:text-sm px-2 py-3">
Popular Parks
</TabsTrigger>
<TabsTrigger value="trending-parks" className="text-xs md:text-sm px-2 py-3"> <TabsTrigger value="trending-parks" className="text-xs md:text-sm px-2 py-3">
Trending Parks Trending Parks
</TabsTrigger> </TabsTrigger>
<TabsTrigger value="popular-rides" className="text-xs md:text-sm px-2 py-3">
Popular Rides
</TabsTrigger>
<TabsTrigger value="trending-rides" className="text-xs md:text-sm px-2 py-3"> <TabsTrigger value="trending-rides" className="text-xs md:text-sm px-2 py-3">
Trending Rides Trending Rides
</TabsTrigger> </TabsTrigger>
@@ -120,22 +96,10 @@ export function ContentTabs() {
</TabsList> </TabsList>
</div> </div>
<TabsContent value="popular-parks" className="mt-8">
<div className="text-center mb-6">
<h2 className="text-2xl font-bold mb-2">Most Popular Parks</h2>
<p className="text-muted-foreground">Highest rated theme parks worldwide</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
{popularParks.map((park) => (
<ParkCard key={park.id} park={park} />
))}
</div>
</TabsContent>
<TabsContent value="trending-parks" className="mt-8"> <TabsContent value="trending-parks" className="mt-8">
<div className="text-center mb-6"> <div className="text-center mb-6">
<h2 className="text-2xl font-bold mb-2">Trending Parks</h2> <h2 className="text-2xl font-bold mb-2">Trending Parks</h2>
<p className="text-muted-foreground">Most reviewed parks this month</p> <p className="text-muted-foreground">Most viewed parks in the last 30 days</p>
</div> </div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5"> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
{trendingParks.map((park) => ( {trendingParks.map((park) => (
@@ -144,22 +108,10 @@ export function ContentTabs() {
</div> </div>
</TabsContent> </TabsContent>
<TabsContent value="popular-rides" className="mt-8">
<div className="text-center mb-6">
<h2 className="text-2xl font-bold mb-2">Most Popular Rides</h2>
<p className="text-muted-foreground">Highest rated attractions worldwide</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
{popularRides.map((ride) => (
<RideCard key={ride.id} ride={ride} />
))}
</div>
</TabsContent>
<TabsContent value="trending-rides" className="mt-8"> <TabsContent value="trending-rides" className="mt-8">
<div className="text-center mb-6"> <div className="text-center mb-6">
<h2 className="text-2xl font-bold mb-2">Trending Rides</h2> <h2 className="text-2xl font-bold mb-2">Trending Rides</h2>
<p className="text-muted-foreground">Most talked about attractions</p> <p className="text-muted-foreground">Most viewed rides in the last 30 days</p>
</div> </div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5"> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7 3xl:grid-cols-8 gap-4 lg:gap-5 xl:gap-4 2xl:gap-5">
{trendingRides.map((ride) => ( {trendingRides.map((ride) => (

View File

@@ -93,6 +93,9 @@ export type Database = {
review_count: number | null review_count: number | null
slug: string slug: string
updated_at: string updated_at: string
view_count_30d: number | null
view_count_7d: number | null
view_count_all: number | null
website_url: string | null website_url: string | null
} }
Insert: { Insert: {
@@ -113,6 +116,9 @@ export type Database = {
review_count?: number | null review_count?: number | null
slug: string slug: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
website_url?: string | null website_url?: string | null
} }
Update: { Update: {
@@ -133,6 +139,9 @@ export type Database = {
review_count?: number | null review_count?: number | null
slug?: string slug?: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
website_url?: string | null website_url?: string | null
} }
Relationships: [] Relationships: []
@@ -359,6 +368,33 @@ export type Database = {
}, },
] ]
} }
entity_page_views: {
Row: {
created_at: string | null
entity_id: string
entity_type: string
id: string
session_hash: string | null
viewed_at: string | null
}
Insert: {
created_at?: string | null
entity_id: string
entity_type: string
id?: string
session_hash?: string | null
viewed_at?: string | null
}
Update: {
created_at?: string | null
entity_id?: string
entity_type?: string
id?: string
session_hash?: string | null
viewed_at?: string | null
}
Relationships: []
}
entity_relationships_history: { entity_relationships_history: {
Row: { Row: {
change_type: string change_type: string
@@ -960,6 +996,9 @@ export type Database = {
slug: string slug: string
status: string status: string
updated_at: string updated_at: string
view_count_30d: number | null
view_count_7d: number | null
view_count_all: number | null
website_url: string | null website_url: string | null
} }
Insert: { Insert: {
@@ -986,6 +1025,9 @@ export type Database = {
slug: string slug: string
status?: string status?: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
website_url?: string | null website_url?: string | null
} }
Update: { Update: {
@@ -1012,6 +1054,9 @@ export type Database = {
slug?: string slug?: string
status?: string status?: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
website_url?: string | null website_url?: string | null
} }
Relationships: [ Relationships: [
@@ -2030,6 +2075,9 @@ export type Database = {
slug: string slug: string
status: string status: string
updated_at: string updated_at: string
view_count_30d: number | null
view_count_7d: number | null
view_count_all: number | null
} }
Insert: { Insert: {
age_requirement?: number | null age_requirement?: number | null
@@ -2067,6 +2115,9 @@ export type Database = {
slug: string slug: string
status?: string status?: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
} }
Update: { Update: {
age_requirement?: number | null age_requirement?: number | null
@@ -2104,6 +2155,9 @@ export type Database = {
slug?: string slug?: string
status?: string status?: string
updated_at?: string updated_at?: string
view_count_30d?: number | null
view_count_7d?: number | null
view_count_all?: number | null
} }
Relationships: [ Relationships: [
{ {
@@ -2707,6 +2761,10 @@ export type Database = {
Args: Record<PropertyKey, never> Args: Record<PropertyKey, never>
Returns: undefined Returns: undefined
} }
cleanup_old_page_views: {
Args: Record<PropertyKey, never>
Returns: undefined
}
compare_versions: { compare_versions: {
Args: { p_from_version_id: string; p_to_version_id: string } Args: { p_from_version_id: string; p_to_version_id: string }
Returns: Json Returns: Json
@@ -2825,6 +2883,10 @@ export type Database = {
Args: { target_company_id: string } Args: { target_company_id: string }
Returns: undefined Returns: undefined
} }
update_entity_view_counts: {
Args: Record<PropertyKey, never>
Returns: undefined
}
update_park_ratings: { update_park_ratings: {
Args: { target_park_id: string } Args: { target_park_id: string }
Returns: undefined Returns: undefined

47
src/lib/viewTracking.ts Normal file
View 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);
}
}

View File

@@ -18,6 +18,7 @@ import { toast } from '@/hooks/use-toast';
import { submitCompanyUpdate } from '@/lib/companyHelpers'; import { submitCompanyUpdate } from '@/lib/companyHelpers';
import { VersionIndicator } from '@/components/versioning/VersionIndicator'; import { VersionIndicator } from '@/components/versioning/VersionIndicator';
import { EntityHistoryTabs } from '@/components/history/EntityHistoryTabs'; import { EntityHistoryTabs } from '@/components/history/EntityHistoryTabs';
import { trackPageView } from '@/lib/viewTracking';
export default function DesignerDetail() { export default function DesignerDetail() {
const { slug } = useParams<{ slug: string }>(); const { slug } = useParams<{ slug: string }>();
@@ -37,6 +38,13 @@ export default function DesignerDetail() {
} }
}, [slug]); }, [slug]);
// Track page view when designer is loaded
useEffect(() => {
if (designer?.id) {
trackPageView('company', designer.id);
}
}, [designer?.id]);
const fetchDesignerData = async () => { const fetchDesignerData = async () => {
try { try {
const { data, error } = await supabase const { data, error } = await supabase

View File

@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header'; import { Header } from '@/components/layout/Header';
import { trackPageView } from '@/lib/viewTracking';
import { getBannerUrls } from '@/lib/cloudflareImageUtils'; import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -38,6 +39,13 @@ export default function ManufacturerDetail() {
} }
}, [slug]); }, [slug]);
// Track page view when manufacturer is loaded
useEffect(() => {
if (manufacturer?.id) {
trackPageView('company', manufacturer.id);
}
}, [manufacturer?.id]);
const fetchManufacturerData = async () => { const fetchManufacturerData = async () => {
try { try {
const { data, error } = await supabase const { data, error } = await supabase

View File

@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header'; import { Header } from '@/components/layout/Header';
import { trackPageView } from '@/lib/viewTracking';
import { getBannerUrls } from '@/lib/cloudflareImageUtils'; import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -41,6 +42,13 @@ export default function OperatorDetail() {
} }
}, [slug]); }, [slug]);
// Track page view when operator is loaded
useEffect(() => {
if (operator?.id) {
trackPageView('company', operator.id);
}
}, [operator?.id]);
const fetchOperatorData = async () => { const fetchOperatorData = async () => {
try { try {
const { data, error } = await supabase const { data, error } = await supabase

View File

@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header'; import { Header } from '@/components/layout/Header';
import { getBannerUrls } from '@/lib/cloudflareImageUtils'; import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { trackPageView } from '@/lib/viewTracking';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -45,6 +46,13 @@ export default function ParkDetail() {
fetchParkData(); fetchParkData();
} }
}, [slug]); }, [slug]);
// Track page view when park is loaded
useEffect(() => {
if (park?.id) {
trackPageView('park', park.id);
}
}, [park?.id]);
const fetchParkData = async () => { const fetchParkData = async () => {
try { try {
// Fetch park details // Fetch park details

View File

@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header'; import { Header } from '@/components/layout/Header';
import { trackPageView } from '@/lib/viewTracking';
import { getBannerUrls } from '@/lib/cloudflareImageUtils'; import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -41,6 +42,13 @@ export default function PropertyOwnerDetail() {
} }
}, [slug]); }, [slug]);
// Track page view when property owner is loaded
useEffect(() => {
if (owner?.id) {
trackPageView('company', owner.id);
}
}, [owner?.id]);
const fetchOwnerData = async () => { const fetchOwnerData = async () => {
try { try {
const { data, error } = await supabase const { data, error } = await supabase

View File

@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { Header } from '@/components/layout/Header'; import { Header } from '@/components/layout/Header';
import { getBannerUrls } from '@/lib/cloudflareImageUtils'; import { getBannerUrls } from '@/lib/cloudflareImageUtils';
import { trackPageView } from '@/lib/viewTracking';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
@@ -50,14 +51,14 @@ import { EntityHistoryTabs } from '@/components/history/EntityHistoryTabs';
export default function RideDetail() { export default function RideDetail() {
const { parkSlug, rideSlug } = useParams<{ parkSlug: string; rideSlug: string }>(); const { parkSlug, rideSlug } = useParams<{ parkSlug: string; rideSlug: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const { user } = useAuth();
const { isModerator } = useUserRole();
const [ride, setRide] = useState<Ride | null>(null); const [ride, setRide] = useState<Ride | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState("overview"); const [activeTab, setActiveTab] = useState("overview");
const [isEditModalOpen, setIsEditModalOpen] = useState(false); const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [photoCount, setPhotoCount] = useState<number>(0); const [photoCount, setPhotoCount] = useState<number>(0);
const [statsLoading, setStatsLoading] = useState(true); const [statsLoading, setStatsLoading] = useState(true);
const { user } = useAuth();
const { isModerator } = useUserRole();
useEffect(() => { useEffect(() => {
if (parkSlug && rideSlug) { if (parkSlug && rideSlug) {
@@ -65,6 +66,13 @@ export default function RideDetail() {
} }
}, [parkSlug, rideSlug]); }, [parkSlug, rideSlug]);
// Track page view when ride is loaded
useEffect(() => {
if (ride?.id) {
trackPageView('ride', ride.id);
}
}, [ride?.id]);
const fetchRideData = async () => { const fetchRideData = async () => {
try { try {
// First get park to find park_id // First get park to find park_id

View File

@@ -0,0 +1,121 @@
-- Phase 1: Create view tracking infrastructure
-- Create entity_page_views table for tracking page views
CREATE TABLE entity_page_views (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
entity_type text NOT NULL CHECK (entity_type IN ('park', 'ride', 'company')),
entity_id uuid NOT NULL,
viewed_at timestamp with time zone DEFAULT now(),
session_hash text,
created_at timestamp with time zone DEFAULT now()
);
-- Create index for fast trending queries
CREATE INDEX idx_entity_views_trending ON entity_page_views(entity_type, entity_id, viewed_at DESC);
CREATE INDEX idx_entity_views_by_type ON entity_page_views(entity_type, viewed_at DESC);
-- Enable RLS
ALTER TABLE entity_page_views ENABLE ROW LEVEL SECURITY;
-- Policy: Allow inserts from anyone (tracking is anonymous)
CREATE POLICY "Anyone can track page views" ON entity_page_views
FOR INSERT WITH CHECK (true);
-- Policy: Only moderators can read analytics
CREATE POLICY "Moderators can read analytics" ON entity_page_views
FOR SELECT USING (is_moderator(auth.uid()));
-- Add view count columns to parks
ALTER TABLE parks ADD COLUMN IF NOT EXISTS view_count_7d integer DEFAULT 0;
ALTER TABLE parks ADD COLUMN IF NOT EXISTS view_count_30d integer DEFAULT 0;
ALTER TABLE parks ADD COLUMN IF NOT EXISTS view_count_all integer DEFAULT 0;
-- Add view count columns to rides
ALTER TABLE rides ADD COLUMN IF NOT EXISTS view_count_7d integer DEFAULT 0;
ALTER TABLE rides ADD COLUMN IF NOT EXISTS view_count_30d integer DEFAULT 0;
ALTER TABLE rides ADD COLUMN IF NOT EXISTS view_count_all integer DEFAULT 0;
-- Add view count columns to companies
ALTER TABLE companies ADD COLUMN IF NOT EXISTS view_count_7d integer DEFAULT 0;
ALTER TABLE companies ADD COLUMN IF NOT EXISTS view_count_30d integer DEFAULT 0;
ALTER TABLE companies ADD COLUMN IF NOT EXISTS view_count_all integer DEFAULT 0;
-- Create indexes for sorting by view count
CREATE INDEX idx_parks_view_count_30d ON parks(view_count_30d DESC);
CREATE INDEX idx_rides_view_count_30d ON rides(view_count_30d DESC);
CREATE INDEX idx_companies_view_count_30d ON companies(view_count_30d DESC);
-- Create function to update view counts (runs daily via cron)
CREATE OR REPLACE FUNCTION update_entity_view_counts()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
-- Update parks view counts
UPDATE parks p SET
view_count_7d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'park' AND entity_id = p.id
AND viewed_at >= NOW() - INTERVAL '7 days'
),
view_count_30d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'park' AND entity_id = p.id
AND viewed_at >= NOW() - INTERVAL '30 days'
),
view_count_all = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'park' AND entity_id = p.id
);
-- Update rides view counts
UPDATE rides r SET
view_count_7d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'ride' AND entity_id = r.id
AND viewed_at >= NOW() - INTERVAL '7 days'
),
view_count_30d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'ride' AND entity_id = r.id
AND viewed_at >= NOW() - INTERVAL '30 days'
),
view_count_all = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'ride' AND entity_id = r.id
);
-- Update companies view counts
UPDATE companies c SET
view_count_7d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'company' AND entity_id = c.id
AND viewed_at >= NOW() - INTERVAL '7 days'
),
view_count_30d = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'company' AND entity_id = c.id
AND viewed_at >= NOW() - INTERVAL '30 days'
),
view_count_all = (
SELECT COUNT(*) FROM entity_page_views
WHERE entity_type = 'company' AND entity_id = c.id
);
END;
$$;
-- Create cleanup function to prevent database bloat
CREATE OR REPLACE FUNCTION cleanup_old_page_views()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
-- Delete views older than 90 days (keep recent data only)
DELETE FROM entity_page_views
WHERE viewed_at < NOW() - INTERVAL '90 days';
END;
$$;