Refactor versioning utility functions

This commit is contained in:
gpt-engineer-app[bot]
2025-10-15 17:47:14 +00:00
parent 4e7d528c64
commit 96a5d235e9
11 changed files with 1251 additions and 140 deletions

View File

@@ -372,8 +372,11 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
toast({
title: `Content ${action}`,
description: `The ${item.type} has been ${action}`,
description: `The ${item.type} has been ${action}. Version history updated.`,
});
// Refresh stats to update counts
queue.refreshStats();
} catch (error: any) {
console.error("Error moderating content:", error);
@@ -415,10 +418,13 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
if (error) throw error;
toast({
title: "Submission deleted",
description: "The submission has been permanently deleted",
});
toast({
title: "Submission deleted",
description: "The submission has been permanently deleted",
});
// Refresh stats to update counts
queue.refreshStats();
} catch (error: any) {
console.error("Error deleting submission:", error);
@@ -454,6 +460,9 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
title: "Reset Complete",
description: "Submission and all items have been reset to pending status",
});
// Refresh stats to update counts
queue.refreshStats();
setItems((prev) => prev.filter((i) => i.id !== item.id));
} catch (error: any) {
@@ -516,6 +525,9 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
title: "Retry Complete",
description: `Processed ${failedItems.length} failed item(s)`,
});
// Refresh stats to update counts
queue.refreshStats();
} catch (error: any) {
console.error("Error retrying failed items:", error);
toast({

View File

@@ -1,26 +1,7 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
interface EntityVersion {
id: string;
entity_type: string;
entity_id: string;
version_number: number;
version_data: any;
changed_by: string;
changed_at: string;
change_reason: string | null;
change_type: 'created' | 'updated' | 'deleted' | 'restored' | 'archived';
submission_id: string | null;
is_current: boolean;
ip_address_hash: string | null;
metadata: any;
changer_profile?: {
username: string;
avatar_url: string | null;
};
}
import type { EntityType, EntityVersion } from '@/types/versioning';
interface FieldChange {
id: string;
@@ -31,50 +12,48 @@ interface FieldChange {
created_at: string;
}
export function useEntityVersions(entityType: string, entityId: string) {
/**
* Hook to manage entity versions using relational version tables
* NO JSONB - Pure relational structure for type safety and queryability
*/
export function useEntityVersions(entityType: EntityType, entityId: string) {
const [versions, setVersions] = useState<EntityVersion[]>([]);
const [currentVersion, setCurrentVersion] = useState<EntityVersion | null>(null);
const [loading, setLoading] = useState(true);
const [fieldHistory, setFieldHistory] = useState<FieldChange[]>([]);
// Track if component is mounted to prevent state updates after unmount
const isMountedRef = useRef(true);
// Track the current channel to prevent duplicate subscriptions
const channelRef = useRef<ReturnType<typeof supabase.channel> | null>(null);
// Use a request counter to track the latest fetch and prevent race conditions
const requestCounterRef = useRef(0);
// Request counter for fetchFieldHistory
const fieldHistoryRequestCounterRef = useRef(0);
const fetchVersions = useCallback(async () => {
if (!isMountedRef.current) return;
// Increment counter and capture the current request ID BEFORE try block
const currentRequestId = ++requestCounterRef.current;
try {
// Only set loading if this is still the latest request
if (isMountedRef.current && currentRequestId === requestCounterRef.current) {
setLoading(true);
}
// Build table and column names
const versionTable = `${entityType}_versions`;
const entityIdCol = `${entityType}_id`;
const { data, error } = await supabase
.from('entity_versions')
.select('*')
.eq('entity_type', entityType)
.eq('entity_id', entityId)
.from(versionTable as any)
.select(`
*,
profiles:created_by(username, display_name, avatar_url)
`)
.eq(entityIdCol, entityId)
.order('version_number', { ascending: false });
if (error) throw error;
// Only continue if this is still the latest request and component is mounted
if (!isMountedRef.current || currentRequestId !== requestCounterRef.current) return;
// Safety check: verify data is an array before processing
if (!Array.isArray(data)) {
if (isMountedRef.current && currentRequestId === requestCounterRef.current) {
setVersions([]);
@@ -84,31 +63,15 @@ export function useEntityVersions(entityType: string, entityId: string) {
return;
}
// Fetch profiles separately
const userIds = [...new Set(data.map(v => v.changed_by).filter(Boolean))];
const { data: profiles } = await supabase
.from('profiles')
.select('user_id, username, avatar_url')
.in('user_id', userIds);
const versionsWithProfiles = (data as any[]).map((v: any) => ({
...v,
profiles: v.profiles || {
username: 'Unknown',
display_name: 'Unknown',
avatar_url: null
}
})) as EntityVersion[];
// Check again if this is still the latest request and component is mounted
if (!isMountedRef.current || currentRequestId !== requestCounterRef.current) return;
// Safety check: verify profiles array exists before filtering
const profilesArray = Array.isArray(profiles) ? profiles : [];
const versionsWithProfiles = data.map(v => {
const profile = profilesArray.find(p => p.user_id === v.changed_by);
return {
...v,
changer_profile: profile || {
username: 'Unknown',
avatar_url: null
}
};
}) as EntityVersion[];
// Only update state if component is still mounted and this is still the latest request
if (isMountedRef.current && currentRequestId === requestCounterRef.current) {
setVersions(versionsWithProfiles);
setCurrentVersion(versionsWithProfiles.find(v => v.is_current) || null);
@@ -117,8 +80,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
} catch (error: any) {
console.error('Error fetching versions:', error);
// Use the captured currentRequestId (DO NOT re-read requestCounterRef.current)
// Only update state if component is mounted and this is still the latest request
if (isMountedRef.current && currentRequestId === requestCounterRef.current) {
const errorMessage = error?.message || 'Failed to load version history';
toast.error(errorMessage);
@@ -130,7 +91,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
const fetchFieldHistory = async (versionId: string) => {
if (!isMountedRef.current) return;
// Increment counter and capture the current request ID BEFORE try block
const currentRequestId = ++fieldHistoryRequestCounterRef.current;
try {
@@ -142,7 +102,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
if (error) throw error;
// Only update state if component is mounted and this is still the latest request
if (isMountedRef.current && currentRequestId === fieldHistoryRequestCounterRef.current) {
const fieldChanges = Array.isArray(data) ? data as FieldChange[] : [];
setFieldHistory(fieldChanges);
@@ -150,8 +109,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
} catch (error: any) {
console.error('Error fetching field history:', error);
// Use the captured currentRequestId (DO NOT re-read fieldHistoryRequestCounterRef.current)
// Only show error if component is mounted and this is still the latest request
if (isMountedRef.current && currentRequestId === fieldHistoryRequestCounterRef.current) {
const errorMessage = error?.message || 'Failed to load field history';
toast.error(errorMessage);
@@ -161,7 +118,8 @@ export function useEntityVersions(entityType: string, entityId: string) {
const compareVersions = async (fromVersionId: string, toVersionId: string) => {
try {
const { data, error } = await supabase.rpc('compare_versions', {
const { data, error } = await supabase.rpc('get_version_diff', {
p_entity_type: entityType,
p_from_version_id: fromVersionId,
p_to_version_id: toVersionId
});
@@ -211,49 +169,15 @@ export function useEntityVersions(entityType: string, entityId: string) {
}
};
const createVersion = async (versionData: any, changeReason?: string, submissionId?: string) => {
try {
if (!isMountedRef.current) return null;
const { data: userData } = await supabase.auth.getUser();
if (!userData.user) throw new Error('Not authenticated');
const { data, error } = await supabase.rpc('create_entity_version', {
p_entity_type: entityType,
p_entity_id: entityId,
p_version_data: versionData,
p_changed_by: userData.user.id,
p_change_reason: changeReason || null,
p_submission_id: submissionId || null
});
if (error) throw error;
if (isMountedRef.current) {
await fetchVersions();
}
return data;
} catch (error: any) {
console.error('Error creating version:', error);
if (isMountedRef.current) {
const errorMessage = error?.message || 'Failed to create version';
toast.error(errorMessage);
}
return null;
}
};
useEffect(() => {
if (entityType && entityId) {
fetchVersions();
}
}, [entityType, entityId, fetchVersions]);
// Set up realtime subscription for version changes
useEffect(() => {
if (!entityType || !entityId) return;
// Clean up existing channel if any
if (channelRef.current) {
try {
supabase.removeChannel(channelRef.current);
@@ -264,16 +188,18 @@ export function useEntityVersions(entityType: string, entityId: string) {
}
}
// Create new channel
const versionTable = `${entityType}_versions`;
const entityIdCol = `${entityType}_id`;
const channel = supabase
.channel('entity_versions_changes')
.channel(`${versionTable}_changes`)
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'entity_versions',
filter: `entity_type=eq.${entityType},entity_id=eq.${entityId}`
table: versionTable,
filter: `${entityIdCol}=eq.${entityId}`
},
() => {
if (isMountedRef.current) {
@@ -286,7 +212,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
channelRef.current = channel;
return () => {
// Ensure cleanup happens in all scenarios
if (channelRef.current) {
supabase.removeChannel(channelRef.current).catch((error) => {
console.error('Error removing channel:', error);
@@ -294,9 +219,8 @@ export function useEntityVersions(entityType: string, entityId: string) {
channelRef.current = null;
}
};
}, [entityType, entityId]);
}, [entityType, entityId, fetchVersions]);
// Set mounted ref on mount and cleanup on unmount
useEffect(() => {
isMountedRef.current = true;
@@ -313,7 +237,6 @@ export function useEntityVersions(entityType: string, entityId: string) {
fetchVersions,
fetchFieldHistory,
compareVersions,
rollbackToVersion,
createVersion
rollbackToVersion
};
}

View File

@@ -111,12 +111,30 @@ export const useModerationStats = (options: UseModerationStatsOptions = {}) => {
const channel = supabase
.channel('moderation-stats-realtime')
// Listen to ALL events on content_submissions without filter
// Manual filtering catches submissions leaving pending state
.on('postgres_changes', {
event: 'INSERT',
event: '*',
schema: 'public',
table: 'content_submissions',
filter: 'status=eq.pending'
}, debouncedFetchStats)
table: 'content_submissions'
}, (payload) => {
const oldStatus = (payload.old as any)?.status;
const newStatus = (payload.new as any)?.status;
const oldAssignedTo = (payload.old as any)?.assigned_to;
const newAssignedTo = (payload.new as any)?.assigned_to;
const oldLockedUntil = (payload.old as any)?.locked_until;
const newLockedUntil = (payload.new as any)?.locked_until;
// Only refresh if change affects pending count or assignments
if (
payload.eventType === 'INSERT' && newStatus === 'pending' ||
payload.eventType === 'UPDATE' && (oldStatus === 'pending' || newStatus === 'pending') ||
payload.eventType === 'DELETE' && oldStatus === 'pending' ||
payload.eventType === 'UPDATE' && (oldAssignedTo !== newAssignedTo || oldLockedUntil !== newLockedUntil)
) {
debouncedFetchStats();
}
})
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',

View File

@@ -0,0 +1,52 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import type { EntityType, VersionDiff } from '@/types/versioning';
/**
* Hook to compare two versions of an entity and get the diff
* Uses the relational version tables for type-safe comparison
*/
export function useVersionComparison(
entityType: EntityType,
fromVersionId: string | null,
toVersionId: string | null
) {
const [diff, setDiff] = useState<VersionDiff | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!fromVersionId || !toVersionId || !entityType) {
setDiff(null);
return;
}
async function fetchDiff() {
setLoading(true);
setError(null);
try {
// Use the database function to get diff
const { data, error: rpcError } = await supabase.rpc('get_version_diff', {
p_entity_type: entityType,
p_from_version_id: fromVersionId,
p_to_version_id: toVersionId
});
if (rpcError) throw rpcError;
setDiff(data as VersionDiff);
} catch (err) {
console.error('Error fetching version diff:', err);
setError(err instanceof Error ? err.message : 'Failed to compare versions');
setDiff(null);
} finally {
setLoading(false);
}
}
fetchDiff();
}, [entityType, fromVersionId, toVersionId]);
return { diff, loading, error };
}