mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-23 15:11:12 -05:00
Refactor moderation queues
This commit is contained in:
@@ -1,209 +0,0 @@
|
||||
import { useEffect, useState, useRef, useCallback } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { RealtimeChannel } from '@supabase/supabase-js';
|
||||
import { useUserRole } from './useUserRole';
|
||||
|
||||
type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
|
||||
interface ModerationStats {
|
||||
pendingSubmissions: number;
|
||||
openReports: number;
|
||||
flaggedContent: number;
|
||||
}
|
||||
|
||||
interface UseRealtimeModerationStatsOptions {
|
||||
onStatsChange?: (stats: ModerationStats) => void;
|
||||
enabled?: boolean;
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOptions = {}) => {
|
||||
const { onStatsChange, enabled = true, debounceMs = 1000 } = options;
|
||||
const { isModerator, loading: roleLoading } = useUserRole();
|
||||
const [stats, setStats] = useState<ModerationStats>({
|
||||
pendingSubmissions: 0,
|
||||
openReports: 0,
|
||||
flaggedContent: 0,
|
||||
});
|
||||
const [channel, setChannel] = useState<RealtimeChannel | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
const updateTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const onStatsChangeRef = useRef(onStatsChange);
|
||||
|
||||
// Only enable realtime when user is confirmed as moderator
|
||||
const realtimeEnabled = enabled && !roleLoading && isModerator();
|
||||
|
||||
// Update ref when callback changes
|
||||
useEffect(() => {
|
||||
onStatsChangeRef.current = onStatsChange;
|
||||
}, [onStatsChange]);
|
||||
|
||||
const fetchStats = useCallback(async () => {
|
||||
try {
|
||||
const [submissionsResult, reportsResult, reviewsResult] = await Promise.all([
|
||||
supabase
|
||||
.from('content_submissions')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('status', 'pending'),
|
||||
supabase
|
||||
.from('reports')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('status', 'pending'),
|
||||
supabase
|
||||
.from('reviews')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('moderation_status', 'flagged'),
|
||||
]);
|
||||
|
||||
const newStats = {
|
||||
pendingSubmissions: submissionsResult.count || 0,
|
||||
openReports: reportsResult.count || 0,
|
||||
flaggedContent: reviewsResult.count || 0,
|
||||
};
|
||||
|
||||
setStats(newStats);
|
||||
onStatsChangeRef.current?.(newStats);
|
||||
} catch (error) {
|
||||
console.error('Error fetching moderation stats:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const debouncedFetchStats = useCallback(() => {
|
||||
if (updateTimerRef.current) {
|
||||
clearTimeout(updateTimerRef.current);
|
||||
}
|
||||
updateTimerRef.current = setTimeout(fetchStats, debounceMs);
|
||||
}, [fetchStats, debounceMs]);
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
if (channel) {
|
||||
supabase.removeChannel(channel);
|
||||
}
|
||||
setConnectionState('connecting');
|
||||
fetchStats();
|
||||
}, [channel, fetchStats]);
|
||||
|
||||
// Initial fetch and polling fallback
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
fetchStats();
|
||||
|
||||
let pollInterval: NodeJS.Timeout | null = null;
|
||||
if (connectionState !== 'connected') {
|
||||
pollInterval = setInterval(fetchStats, 30000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (pollInterval) {
|
||||
clearInterval(pollInterval);
|
||||
}
|
||||
if (updateTimerRef.current) {
|
||||
clearTimeout(updateTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [enabled, fetchStats, connectionState]);
|
||||
|
||||
// Set up broadcast channels for real-time updates
|
||||
useEffect(() => {
|
||||
if (!realtimeEnabled) {
|
||||
console.log('[Realtime:moderation-stats] Realtime disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Realtime:moderation-stats] Creating broadcast channels');
|
||||
setConnectionState('connecting');
|
||||
|
||||
const setupChannels = async () => {
|
||||
// Set auth token for private channels
|
||||
await supabase.realtime.setAuth();
|
||||
|
||||
const submissionsChannel = supabase
|
||||
.channel('moderation:content_submissions', {
|
||||
config: { private: true },
|
||||
})
|
||||
.on('broadcast', { event: 'INSERT' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Content submission inserted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'UPDATE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Content submission updated');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'DELETE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Content submission deleted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.subscribe((status) => {
|
||||
console.log('[Realtime:moderation-stats] Submissions channel status:', status);
|
||||
|
||||
if (status === 'SUBSCRIBED') {
|
||||
setConnectionState('connected');
|
||||
} else if (status === 'CHANNEL_ERROR') {
|
||||
setConnectionState('error');
|
||||
} else if (status === 'TIMED_OUT') {
|
||||
setConnectionState('disconnected');
|
||||
console.log('[Realtime:moderation-stats] Falling back to polling');
|
||||
} else if (status === 'CLOSED') {
|
||||
setConnectionState('disconnected');
|
||||
}
|
||||
});
|
||||
|
||||
const reportsChannel = supabase
|
||||
.channel('moderation:reports', {
|
||||
config: { private: true },
|
||||
})
|
||||
.on('broadcast', { event: 'INSERT' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Report inserted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'UPDATE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Report updated');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'DELETE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Report deleted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
const reviewsChannel = supabase
|
||||
.channel('moderation:reviews', {
|
||||
config: { private: true },
|
||||
})
|
||||
.on('broadcast', { event: 'INSERT' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Review inserted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'UPDATE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Review updated');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.on('broadcast', { event: 'DELETE' }, () => {
|
||||
console.log('[Realtime:moderation-stats] Review deleted');
|
||||
debouncedFetchStats();
|
||||
})
|
||||
.subscribe();
|
||||
|
||||
setChannel(submissionsChannel);
|
||||
|
||||
return { submissionsChannel, reportsChannel, reviewsChannel };
|
||||
};
|
||||
|
||||
let channels: Awaited<ReturnType<typeof setupChannels>>;
|
||||
setupChannels().then((c) => {
|
||||
channels = c;
|
||||
});
|
||||
|
||||
return () => {
|
||||
console.log('[Realtime:moderation-stats] Cleaning up channels');
|
||||
if (channels) {
|
||||
supabase.removeChannel(channels.submissionsChannel);
|
||||
supabase.removeChannel(channels.reportsChannel);
|
||||
supabase.removeChannel(channels.reviewsChannel);
|
||||
}
|
||||
};
|
||||
}, [realtimeEnabled, debouncedFetchStats]);
|
||||
|
||||
return { stats, refresh: fetchStats, connectionState, reconnect };
|
||||
};
|
||||
@@ -1,87 +0,0 @@
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { RealtimeChannel } from '@supabase/supabase-js';
|
||||
|
||||
type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
|
||||
interface UseRealtimeSubmissionItemsOptions {
|
||||
submissionId?: string;
|
||||
onUpdate?: (payload: any) => void;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const useRealtimeSubmissionItems = (options: UseRealtimeSubmissionItemsOptions = {}) => {
|
||||
const { submissionId, onUpdate, enabled = true } = options;
|
||||
|
||||
const [channel, setChannel] = useState<RealtimeChannel | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
|
||||
// Use ref to store latest callback without triggering re-subscriptions
|
||||
const onUpdateRef = useRef(onUpdate);
|
||||
|
||||
// Update ref when callback changes
|
||||
useEffect(() => {
|
||||
onUpdateRef.current = onUpdate;
|
||||
}, [onUpdate]);
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
if (channel) {
|
||||
supabase.removeChannel(channel);
|
||||
}
|
||||
setConnectionState('connecting');
|
||||
}, [channel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !submissionId) {
|
||||
console.log('[Realtime:submission-items] Disabled or no submission ID');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Realtime:submission-items] Creating new broadcast channel for submission:', submissionId);
|
||||
setConnectionState('connecting');
|
||||
|
||||
const setupChannel = async () => {
|
||||
// Set auth token for private channel
|
||||
await supabase.realtime.setAuth();
|
||||
|
||||
const newChannel = supabase
|
||||
.channel('moderation:submission_items', {
|
||||
config: { private: true },
|
||||
})
|
||||
.on('broadcast', { event: 'UPDATE' }, (payload) => {
|
||||
// Client-side filtering for specific submission
|
||||
const itemData = payload.payload;
|
||||
if (itemData?.new?.submission_id === submissionId) {
|
||||
console.log('Submission item updated:', payload);
|
||||
onUpdateRef.current?.(payload);
|
||||
}
|
||||
})
|
||||
.subscribe((status) => {
|
||||
console.log(`[Realtime:submission-items] Subscription status:`, status);
|
||||
|
||||
if (status === 'SUBSCRIBED') {
|
||||
setConnectionState('connected');
|
||||
} else if (status === 'CHANNEL_ERROR') {
|
||||
setConnectionState('error');
|
||||
} else if (status === 'TIMED_OUT') {
|
||||
setConnectionState('disconnected');
|
||||
} else if (status === 'CLOSED') {
|
||||
setConnectionState('disconnected');
|
||||
}
|
||||
});
|
||||
|
||||
setChannel(newChannel);
|
||||
};
|
||||
|
||||
setupChannel();
|
||||
|
||||
return () => {
|
||||
if (channel) {
|
||||
console.log('[Realtime:submission-items] Cleaning up channel');
|
||||
supabase.removeChannel(channel);
|
||||
}
|
||||
};
|
||||
}, [enabled, submissionId]);
|
||||
|
||||
return { channel, connectionState, reconnect };
|
||||
};
|
||||
@@ -1,101 +0,0 @@
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { RealtimeChannel } from '@supabase/supabase-js';
|
||||
import { useUserRole } from './useUserRole';
|
||||
|
||||
type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
|
||||
interface UseRealtimeSubmissionsOptions {
|
||||
onInsert?: (payload: any) => void;
|
||||
onUpdate?: (payload: any) => void;
|
||||
onDelete?: (payload: any) => void;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = {}) => {
|
||||
const { onInsert, onUpdate, onDelete, enabled = true } = options;
|
||||
const { isModerator, loading: roleLoading } = useUserRole();
|
||||
|
||||
const [channel, setChannel] = useState<RealtimeChannel | null>(null);
|
||||
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
|
||||
|
||||
// Only enable realtime when user is confirmed as moderator
|
||||
const realtimeEnabled = enabled && !roleLoading && isModerator();
|
||||
|
||||
// Use refs to store latest callbacks without triggering re-subscriptions
|
||||
const onInsertRef = useRef(onInsert);
|
||||
const onUpdateRef = useRef(onUpdate);
|
||||
const onDeleteRef = useRef(onDelete);
|
||||
|
||||
// Update refs when callbacks change
|
||||
useEffect(() => {
|
||||
onInsertRef.current = onInsert;
|
||||
onUpdateRef.current = onUpdate;
|
||||
onDeleteRef.current = onDelete;
|
||||
}, [onInsert, onUpdate, onDelete]);
|
||||
|
||||
const reconnect = useCallback(() => {
|
||||
if (channel) {
|
||||
supabase.removeChannel(channel);
|
||||
}
|
||||
setConnectionState('connecting');
|
||||
}, [channel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!realtimeEnabled) {
|
||||
console.log('[Realtime:content-submissions] Realtime disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[Realtime:content-submissions] Creating new broadcast channel');
|
||||
setConnectionState('connecting');
|
||||
|
||||
const setupChannel = async () => {
|
||||
// Set auth token for private channel
|
||||
await supabase.realtime.setAuth();
|
||||
|
||||
const newChannel = supabase
|
||||
.channel('moderation:content_submissions', {
|
||||
config: { private: true },
|
||||
})
|
||||
.on('broadcast', { event: 'INSERT' }, (payload) => {
|
||||
console.log('Submission inserted:', payload);
|
||||
onInsertRef.current?.(payload);
|
||||
})
|
||||
.on('broadcast', { event: 'UPDATE' }, (payload) => {
|
||||
console.log('Submission updated:', payload);
|
||||
onUpdateRef.current?.(payload);
|
||||
})
|
||||
.on('broadcast', { event: 'DELETE' }, (payload) => {
|
||||
console.log('Submission deleted:', payload);
|
||||
onDeleteRef.current?.(payload);
|
||||
})
|
||||
.subscribe((status) => {
|
||||
console.log('[Realtime:content-submissions] Subscription status:', status);
|
||||
|
||||
if (status === 'SUBSCRIBED') {
|
||||
setConnectionState('connected');
|
||||
} else if (status === 'CHANNEL_ERROR') {
|
||||
setConnectionState('error');
|
||||
} else if (status === 'TIMED_OUT') {
|
||||
setConnectionState('disconnected');
|
||||
} else if (status === 'CLOSED') {
|
||||
setConnectionState('disconnected');
|
||||
}
|
||||
});
|
||||
|
||||
setChannel(newChannel);
|
||||
};
|
||||
|
||||
setupChannel();
|
||||
|
||||
return () => {
|
||||
if (channel) {
|
||||
console.log('[Realtime:content-submissions] Cleaning up channel');
|
||||
supabase.removeChannel(channel);
|
||||
}
|
||||
};
|
||||
}, [realtimeEnabled]);
|
||||
|
||||
return { channel, connectionState, reconnect };
|
||||
};
|
||||
Reference in New Issue
Block a user