mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 09:11:12 -05:00
Refactor versioning utility functions
This commit is contained in:
@@ -10,9 +10,10 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { VersionComparisonDialog } from './VersionComparisonDialog';
|
||||
import { RollbackDialog } from './RollbackDialog';
|
||||
import { useEntityVersions } from '@/hooks/useEntityVersions';
|
||||
import type { EntityType } from '@/types/versioning';
|
||||
|
||||
interface EntityVersionHistoryProps {
|
||||
entityType: string;
|
||||
entityType: EntityType;
|
||||
entityId: string;
|
||||
entityName: string;
|
||||
}
|
||||
@@ -97,13 +98,13 @@ export function EntityVersionHistory({ entityType, entityId, entityName }: Entit
|
||||
|
||||
{versions.map((version, index) => (
|
||||
<Card
|
||||
key={version.id}
|
||||
key={version.version_id}
|
||||
className={`relative pl-16 pr-4 py-4 cursor-pointer transition-colors ${
|
||||
selectedVersions.includes(version.id)
|
||||
selectedVersions.includes(version.version_id)
|
||||
? 'border-primary bg-accent'
|
||||
: 'hover:border-primary/50'
|
||||
} ${version.is_current ? 'border-primary shadow-md' : ''}`}
|
||||
onClick={() => handleVersionSelect(version.id)}
|
||||
onClick={() => handleVersionSelect(version.version_id)}
|
||||
>
|
||||
{/* Timeline dot */}
|
||||
<div
|
||||
@@ -133,7 +134,7 @@ export function EntityVersionHistory({ entityType, entityId, entityName }: Entit
|
||||
variant="ghost"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRollback(version.id);
|
||||
handleRollback(version.version_id);
|
||||
}}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4 mr-1" />
|
||||
@@ -146,17 +147,17 @@ export function EntityVersionHistory({ entityType, entityId, entityName }: Entit
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
<AvatarImage src={version.changer_profile?.avatar_url || undefined} />
|
||||
<AvatarImage src={version.profiles?.avatar_url || undefined} />
|
||||
<AvatarFallback>
|
||||
<User className="h-3 w-3" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{version.changer_profile?.username || 'Unknown'}</span>
|
||||
<span>{version.profiles?.display_name || version.profiles?.username || 'Unknown'}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="h-4 w-4" />
|
||||
<span>{formatDistanceToNow(new Date(version.changed_at), { addSuffix: true })}</span>
|
||||
<span>{formatDistanceToNow(new Date(version.created_at), { addSuffix: true })}</span>
|
||||
</div>
|
||||
|
||||
{version.submission_id && (
|
||||
|
||||
@@ -5,11 +5,12 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ArrowRight, Plus, Minus, Edit } from 'lucide-react';
|
||||
import { useEntityVersions } from '@/hooks/useEntityVersions';
|
||||
import type { EntityType } from '@/types/versioning';
|
||||
|
||||
interface VersionComparisonDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
entityType: string;
|
||||
entityType: EntityType;
|
||||
entityId: string;
|
||||
fromVersionId: string;
|
||||
toVersionId: string;
|
||||
@@ -27,8 +28,8 @@ export function VersionComparisonDialog({
|
||||
const [diff, setDiff] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fromVersion = versions.find(v => v.id === fromVersionId);
|
||||
const toVersion = versions.find(v => v.id === toVersionId);
|
||||
const fromVersion = versions.find(v => v.version_id === fromVersionId);
|
||||
const toVersion = versions.find(v => v.version_id === toVersionId);
|
||||
|
||||
useEffect(() => {
|
||||
const loadDiff = async () => {
|
||||
@@ -65,12 +66,12 @@ export function VersionComparisonDialog({
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground mt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">Version {fromVersion?.version_number}</Badge>
|
||||
<span>{new Date(fromVersion?.changed_at || '').toLocaleString()}</span>
|
||||
<span>{new Date(fromVersion?.created_at || '').toLocaleString()}</span>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">Version {toVersion?.version_number}</Badge>
|
||||
<span>{new Date(toVersion?.changed_at || '').toLocaleString()}</span>
|
||||
<span>{new Date(toVersion?.created_at || '').toLocaleString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -6,9 +6,10 @@ import { History, Clock } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { EntityVersionHistory } from './EntityVersionHistory';
|
||||
import { useEntityVersions } from '@/hooks/useEntityVersions';
|
||||
import type { EntityType } from '@/types/versioning';
|
||||
|
||||
interface VersionIndicatorProps {
|
||||
entityType: string;
|
||||
entityType: EntityType;
|
||||
entityId: string;
|
||||
entityName: string;
|
||||
compact?: boolean;
|
||||
@@ -27,8 +28,8 @@ export function VersionIndicator({
|
||||
return null;
|
||||
}
|
||||
|
||||
const timeAgo = currentVersion.changed_at
|
||||
? formatDistanceToNow(new Date(currentVersion.changed_at), { addSuffix: true })
|
||||
const timeAgo = currentVersion.created_at
|
||||
? formatDistanceToNow(new Date(currentVersion.created_at), { addSuffix: true })
|
||||
: 'Unknown';
|
||||
|
||||
if (compact) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -419,6 +422,9 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
|
||||
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);
|
||||
|
||||
@@ -455,6 +461,9 @@ export function useModerationQueueManager(config: ModerationQueueManagerConfig):
|
||||
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) {
|
||||
console.error("Error resetting submission:", error);
|
||||
@@ -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({
|
||||
|
||||
@@ -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);
|
||||
|
||||
// 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 {
|
||||
const versionsWithProfiles = (data as any[]).map((v: any) => ({
|
||||
...v,
|
||||
changer_profile: profile || {
|
||||
profiles: v.profiles || {
|
||||
username: 'Unknown',
|
||||
display_name: 'Unknown',
|
||||
avatar_url: null
|
||||
}
|
||||
};
|
||||
}) as EntityVersion[];
|
||||
})) 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
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
52
src/hooks/useVersionComparison.ts
Normal file
52
src/hooks/useVersionComparison.ts
Normal 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 };
|
||||
}
|
||||
@@ -331,6 +331,102 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
company_versions: {
|
||||
Row: {
|
||||
banner_image_id: string | null
|
||||
banner_image_url: string | null
|
||||
card_image_id: string | null
|
||||
card_image_url: string | null
|
||||
change_reason: string | null
|
||||
change_type: Database["public"]["Enums"]["version_change_type"]
|
||||
company_id: string
|
||||
company_type: string
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
description: string | null
|
||||
founded_date: string | null
|
||||
founded_date_precision: string | null
|
||||
founded_year: number | null
|
||||
headquarters_location: string | null
|
||||
is_current: boolean
|
||||
logo_url: string | null
|
||||
name: string
|
||||
person_type: string | null
|
||||
slug: string
|
||||
submission_id: string | null
|
||||
version_id: string
|
||||
version_number: number
|
||||
website_url: string | null
|
||||
}
|
||||
Insert: {
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
company_id: string
|
||||
company_type: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
founded_date?: string | null
|
||||
founded_date_precision?: string | null
|
||||
founded_year?: number | null
|
||||
headquarters_location?: string | null
|
||||
is_current?: boolean
|
||||
logo_url?: string | null
|
||||
name: string
|
||||
person_type?: string | null
|
||||
slug: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number: number
|
||||
website_url?: string | null
|
||||
}
|
||||
Update: {
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
company_id?: string
|
||||
company_type?: string
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
founded_date?: string | null
|
||||
founded_date_precision?: string | null
|
||||
founded_year?: number | null
|
||||
headquarters_location?: string | null
|
||||
is_current?: boolean
|
||||
logo_url?: string | null
|
||||
name?: string
|
||||
person_type?: string | null
|
||||
slug?: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number?: number
|
||||
website_url?: string | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "company_versions_company_id_fkey"
|
||||
columns: ["company_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "company_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
content_submissions: {
|
||||
Row: {
|
||||
approval_mode: string | null
|
||||
@@ -1106,6 +1202,135 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
park_versions: {
|
||||
Row: {
|
||||
banner_image_id: string | null
|
||||
banner_image_url: string | null
|
||||
card_image_id: string | null
|
||||
card_image_url: string | null
|
||||
change_reason: string | null
|
||||
change_type: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date: string | null
|
||||
closing_date_precision: string | null
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
description: string | null
|
||||
email: string | null
|
||||
is_current: boolean
|
||||
location_id: string | null
|
||||
name: string
|
||||
opening_date: string | null
|
||||
opening_date_precision: string | null
|
||||
operator_id: string | null
|
||||
park_id: string
|
||||
park_type: string
|
||||
phone: string | null
|
||||
property_owner_id: string | null
|
||||
slug: string
|
||||
status: string
|
||||
submission_id: string | null
|
||||
version_id: string
|
||||
version_number: number
|
||||
website_url: string | null
|
||||
}
|
||||
Insert: {
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date?: string | null
|
||||
closing_date_precision?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
email?: string | null
|
||||
is_current?: boolean
|
||||
location_id?: string | null
|
||||
name: string
|
||||
opening_date?: string | null
|
||||
opening_date_precision?: string | null
|
||||
operator_id?: string | null
|
||||
park_id: string
|
||||
park_type: string
|
||||
phone?: string | null
|
||||
property_owner_id?: string | null
|
||||
slug: string
|
||||
status: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number: number
|
||||
website_url?: string | null
|
||||
}
|
||||
Update: {
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date?: string | null
|
||||
closing_date_precision?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
email?: string | null
|
||||
is_current?: boolean
|
||||
location_id?: string | null
|
||||
name?: string
|
||||
opening_date?: string | null
|
||||
opening_date_precision?: string | null
|
||||
operator_id?: string | null
|
||||
park_id?: string
|
||||
park_type?: string
|
||||
phone?: string | null
|
||||
property_owner_id?: string | null
|
||||
slug?: string
|
||||
status?: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number?: number
|
||||
website_url?: string | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "park_versions_location_id_fkey"
|
||||
columns: ["location_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "locations"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_versions_operator_id_fkey"
|
||||
columns: ["operator_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_versions_park_id_fkey"
|
||||
columns: ["park_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "parks"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_versions_property_owner_id_fkey"
|
||||
columns: ["property_owner_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
parks: {
|
||||
Row: {
|
||||
average_rating: number | null
|
||||
@@ -1874,6 +2099,82 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_model_versions: {
|
||||
Row: {
|
||||
category: string
|
||||
change_reason: string | null
|
||||
change_type: Database["public"]["Enums"]["version_change_type"]
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
description: string | null
|
||||
is_current: boolean
|
||||
manufacturer_id: string | null
|
||||
name: string
|
||||
ride_model_id: string
|
||||
slug: string
|
||||
submission_id: string | null
|
||||
technical_specs: Json | null
|
||||
version_id: string
|
||||
version_number: number
|
||||
}
|
||||
Insert: {
|
||||
category: string
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
is_current?: boolean
|
||||
manufacturer_id?: string | null
|
||||
name: string
|
||||
ride_model_id: string
|
||||
slug: string
|
||||
submission_id?: string | null
|
||||
technical_specs?: Json | null
|
||||
version_id?: string
|
||||
version_number: number
|
||||
}
|
||||
Update: {
|
||||
category?: string
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
is_current?: boolean
|
||||
manufacturer_id?: string | null
|
||||
name?: string
|
||||
ride_model_id?: string
|
||||
slug?: string
|
||||
submission_id?: string | null
|
||||
technical_specs?: Json | null
|
||||
version_id?: string
|
||||
version_number?: number
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "ride_model_versions_manufacturer_id_fkey"
|
||||
columns: ["manufacturer_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_model_versions_ride_model_id_fkey"
|
||||
columns: ["ride_model_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "ride_models"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_model_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_models: {
|
||||
Row: {
|
||||
banner_image_id: string | null
|
||||
@@ -2269,6 +2570,162 @@ export type Database = {
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_versions: {
|
||||
Row: {
|
||||
angle_degrees: number | null
|
||||
banner_image_id: string | null
|
||||
banner_image_url: string | null
|
||||
capacity_per_hour: number | null
|
||||
card_image_id: string | null
|
||||
card_image_url: string | null
|
||||
category: string
|
||||
change_reason: string | null
|
||||
change_type: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date: string | null
|
||||
closing_date_precision: string | null
|
||||
created_at: string
|
||||
created_by: string | null
|
||||
description: string | null
|
||||
designer_id: string | null
|
||||
drop_meters: number | null
|
||||
duration_seconds: number | null
|
||||
former_names: Json | null
|
||||
gforce_max: number | null
|
||||
height_meters: number | null
|
||||
height_requirement_cm: number | null
|
||||
inversions_count: number | null
|
||||
is_current: boolean
|
||||
length_meters: number | null
|
||||
manufacturer_id: string | null
|
||||
max_speed_kmh: number | null
|
||||
name: string
|
||||
opening_date: string | null
|
||||
opening_date_precision: string | null
|
||||
park_id: string | null
|
||||
ride_id: string
|
||||
ride_model_id: string | null
|
||||
slug: string
|
||||
status: string
|
||||
submission_id: string | null
|
||||
version_id: string
|
||||
version_number: number
|
||||
}
|
||||
Insert: {
|
||||
angle_degrees?: number | null
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
capacity_per_hour?: number | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
category: string
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date?: string | null
|
||||
closing_date_precision?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
designer_id?: string | null
|
||||
drop_meters?: number | null
|
||||
duration_seconds?: number | null
|
||||
former_names?: Json | null
|
||||
gforce_max?: number | null
|
||||
height_meters?: number | null
|
||||
height_requirement_cm?: number | null
|
||||
inversions_count?: number | null
|
||||
is_current?: boolean
|
||||
length_meters?: number | null
|
||||
manufacturer_id?: string | null
|
||||
max_speed_kmh?: number | null
|
||||
name: string
|
||||
opening_date?: string | null
|
||||
opening_date_precision?: string | null
|
||||
park_id?: string | null
|
||||
ride_id: string
|
||||
ride_model_id?: string | null
|
||||
slug: string
|
||||
status: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number: number
|
||||
}
|
||||
Update: {
|
||||
angle_degrees?: number | null
|
||||
banner_image_id?: string | null
|
||||
banner_image_url?: string | null
|
||||
capacity_per_hour?: number | null
|
||||
card_image_id?: string | null
|
||||
card_image_url?: string | null
|
||||
category?: string
|
||||
change_reason?: string | null
|
||||
change_type?: Database["public"]["Enums"]["version_change_type"]
|
||||
closing_date?: string | null
|
||||
closing_date_precision?: string | null
|
||||
created_at?: string
|
||||
created_by?: string | null
|
||||
description?: string | null
|
||||
designer_id?: string | null
|
||||
drop_meters?: number | null
|
||||
duration_seconds?: number | null
|
||||
former_names?: Json | null
|
||||
gforce_max?: number | null
|
||||
height_meters?: number | null
|
||||
height_requirement_cm?: number | null
|
||||
inversions_count?: number | null
|
||||
is_current?: boolean
|
||||
length_meters?: number | null
|
||||
manufacturer_id?: string | null
|
||||
max_speed_kmh?: number | null
|
||||
name?: string
|
||||
opening_date?: string | null
|
||||
opening_date_precision?: string | null
|
||||
park_id?: string | null
|
||||
ride_id?: string
|
||||
ride_model_id?: string | null
|
||||
slug?: string
|
||||
status?: string
|
||||
submission_id?: string | null
|
||||
version_id?: string
|
||||
version_number?: number
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "ride_versions_designer_id_fkey"
|
||||
columns: ["designer_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_versions_manufacturer_id_fkey"
|
||||
columns: ["manufacturer_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "companies"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_versions_park_id_fkey"
|
||||
columns: ["park_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "parks"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_versions_ride_id_fkey"
|
||||
columns: ["ride_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "rides"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
rides: {
|
||||
Row: {
|
||||
age_requirement: number | null
|
||||
@@ -2992,6 +3449,10 @@ export type Database = {
|
||||
Args: Record<PropertyKey, never>
|
||||
Returns: undefined
|
||||
}
|
||||
cleanup_old_versions: {
|
||||
Args: { entity_type: string; keep_versions?: number }
|
||||
Returns: number
|
||||
}
|
||||
cleanup_rate_limits: {
|
||||
Args: Record<PropertyKey, never>
|
||||
Returns: undefined
|
||||
@@ -3065,6 +3526,14 @@ export type Database = {
|
||||
Args: { _user_id: string }
|
||||
Returns: Json
|
||||
}
|
||||
get_version_diff: {
|
||||
Args: {
|
||||
p_entity_type: string
|
||||
p_from_version_id: string
|
||||
p_to_version_id: string
|
||||
}
|
||||
Returns: Json
|
||||
}
|
||||
has_aal2: {
|
||||
Args: Record<PropertyKey, never>
|
||||
Returns: boolean
|
||||
|
||||
160
src/types/versioning.ts
Normal file
160
src/types/versioning.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Universal Versioning System Types
|
||||
* Pure relational structure, no JSONB storage
|
||||
*/
|
||||
|
||||
export type EntityType = 'park' | 'ride' | 'company' | 'ride_model';
|
||||
|
||||
export type ChangeType = 'created' | 'updated' | 'deleted' | 'restored' | 'archived';
|
||||
|
||||
/**
|
||||
* Base version metadata common to all entity types
|
||||
* NOTE: Using version_id as the primary identifier (not 'id')
|
||||
* This matches the relational version table structure
|
||||
*/
|
||||
export interface BaseVersion {
|
||||
version_id: string;
|
||||
version_number: number;
|
||||
created_at: string;
|
||||
created_by: string | null;
|
||||
change_type: ChangeType;
|
||||
change_reason: string | null;
|
||||
submission_id: string | null;
|
||||
is_current: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended version with profile data joined
|
||||
*/
|
||||
export interface BaseVersionWithProfile extends BaseVersion {
|
||||
profiles?: {
|
||||
username: string | null;
|
||||
display_name: string | null;
|
||||
avatar_url: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Park Version - exact mirror of parks table structure
|
||||
*/
|
||||
export interface ParkVersion extends BaseVersionWithProfile {
|
||||
park_id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
park_type: string;
|
||||
status: string;
|
||||
location_id: string | null;
|
||||
operator_id: string | null;
|
||||
property_owner_id: string | null;
|
||||
opening_date: string | null;
|
||||
closing_date: string | null;
|
||||
opening_date_precision: string | null;
|
||||
closing_date_precision: string | null;
|
||||
website_url: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
banner_image_url: string | null;
|
||||
banner_image_id: string | null;
|
||||
card_image_url: string | null;
|
||||
card_image_id: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ride Version - exact mirror of rides table structure
|
||||
*/
|
||||
export interface RideVersion extends BaseVersionWithProfile {
|
||||
ride_id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
category: string;
|
||||
status: string;
|
||||
park_id: string | null;
|
||||
manufacturer_id: string | null;
|
||||
designer_id: string | null;
|
||||
ride_model_id: string | null;
|
||||
opening_date: string | null;
|
||||
closing_date: string | null;
|
||||
opening_date_precision: string | null;
|
||||
closing_date_precision: string | null;
|
||||
height_requirement_cm: number | null;
|
||||
max_speed_kmh: number | null;
|
||||
duration_seconds: number | null;
|
||||
capacity_per_hour: number | null;
|
||||
gforce_max: number | null;
|
||||
inversions_count: number | null;
|
||||
length_meters: number | null;
|
||||
height_meters: number | null;
|
||||
drop_meters: number | null;
|
||||
angle_degrees: number | null;
|
||||
former_names: any[] | null;
|
||||
banner_image_url: string | null;
|
||||
banner_image_id: string | null;
|
||||
card_image_url: string | null;
|
||||
card_image_id: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Company Version - exact mirror of companies table structure
|
||||
*/
|
||||
export interface CompanyVersion extends BaseVersionWithProfile {
|
||||
company_id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
company_type: string;
|
||||
person_type: string | null;
|
||||
founded_year: number | null;
|
||||
founded_date: string | null;
|
||||
founded_date_precision: string | null;
|
||||
headquarters_location: string | null;
|
||||
website_url: string | null;
|
||||
logo_url: string | null;
|
||||
banner_image_url: string | null;
|
||||
banner_image_id: string | null;
|
||||
card_image_url: string | null;
|
||||
card_image_id: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ride Model Version - exact mirror of ride_models table structure
|
||||
*/
|
||||
export interface RideModelVersion extends BaseVersionWithProfile {
|
||||
ride_model_id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
manufacturer_id: string | null;
|
||||
category: string;
|
||||
description: string | null;
|
||||
technical_specs: Record<string, any> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated union of all entity version types
|
||||
*/
|
||||
export type EntityVersion = ParkVersion | RideVersion | CompanyVersion | RideModelVersion;
|
||||
|
||||
/**
|
||||
* Version comparison diff structure
|
||||
*/
|
||||
export interface VersionDiff {
|
||||
[fieldName: string]: {
|
||||
from: any;
|
||||
to: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Version summary for list display
|
||||
*/
|
||||
export interface VersionSummary {
|
||||
version_id: string;
|
||||
version_number: number;
|
||||
created_at: string;
|
||||
created_by: string | null;
|
||||
change_type: ChangeType;
|
||||
changed_by_username?: string;
|
||||
changed_by_display_name?: string;
|
||||
entity_name: string;
|
||||
}
|
||||
@@ -231,15 +231,26 @@ serve(async (req) => {
|
||||
}
|
||||
|
||||
// Set user context for versioning trigger
|
||||
// This allows auto_create_entity_version() to capture the submitter
|
||||
const { error: setConfigError } = await supabase.rpc('set_config_value', {
|
||||
// This allows create_relational_version() trigger to capture the submitter
|
||||
const { error: setUserIdError } = await supabase.rpc('set_config_value', {
|
||||
setting_name: 'app.current_user_id',
|
||||
setting_value: submitterId,
|
||||
is_local: false
|
||||
});
|
||||
|
||||
if (setConfigError) {
|
||||
console.error('Failed to set user context:', setConfigError);
|
||||
if (setUserIdError) {
|
||||
console.error('Failed to set user context:', setUserIdError);
|
||||
}
|
||||
|
||||
// Set submission ID for version tracking
|
||||
const { error: setSubmissionIdError } = await supabase.rpc('set_config_value', {
|
||||
setting_name: 'app.submission_id',
|
||||
setting_value: submissionId,
|
||||
is_local: false
|
||||
});
|
||||
|
||||
if (setSubmissionIdError) {
|
||||
console.error('Failed to set submission context:', setSubmissionIdError);
|
||||
}
|
||||
|
||||
// Resolve dependencies in item data
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
-- ============================================================================
|
||||
-- UNIVERSAL RELATIONAL VERSIONING SYSTEM
|
||||
-- Eliminates JSONB storage, uses pure relational structure
|
||||
-- Automatic trigger-based versioning with full type safety
|
||||
-- ============================================================================
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 1: Create Version Tables (Pure Relational, No JSONB)
|
||||
-- ============================================================================
|
||||
|
||||
-- Park Versions Table
|
||||
CREATE TABLE IF NOT EXISTS public.park_versions (
|
||||
-- Version metadata
|
||||
version_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
park_id uuid NOT NULL REFERENCES public.parks(id) ON DELETE CASCADE,
|
||||
version_number integer NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid,
|
||||
change_type version_change_type NOT NULL DEFAULT 'updated',
|
||||
change_reason text,
|
||||
submission_id uuid REFERENCES public.content_submissions(id) ON DELETE SET NULL,
|
||||
is_current boolean NOT NULL DEFAULT true,
|
||||
|
||||
-- Exact mirror of parks table structure (all fields, no computed columns)
|
||||
name text NOT NULL,
|
||||
slug text NOT NULL,
|
||||
description text,
|
||||
park_type text NOT NULL,
|
||||
status text NOT NULL,
|
||||
location_id uuid REFERENCES public.locations(id) ON DELETE SET NULL,
|
||||
operator_id uuid REFERENCES public.companies(id) ON DELETE SET NULL,
|
||||
property_owner_id uuid REFERENCES public.companies(id) ON DELETE SET NULL,
|
||||
opening_date date,
|
||||
closing_date date,
|
||||
opening_date_precision text,
|
||||
closing_date_precision text,
|
||||
website_url text,
|
||||
phone text,
|
||||
email text,
|
||||
banner_image_url text,
|
||||
banner_image_id text,
|
||||
card_image_url text,
|
||||
card_image_id text,
|
||||
|
||||
-- Constraints
|
||||
UNIQUE(park_id, version_number)
|
||||
);
|
||||
|
||||
-- Ride Versions Table
|
||||
CREATE TABLE IF NOT EXISTS public.ride_versions (
|
||||
-- Version metadata
|
||||
version_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
ride_id uuid NOT NULL REFERENCES public.rides(id) ON DELETE CASCADE,
|
||||
version_number integer NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid,
|
||||
change_type version_change_type NOT NULL DEFAULT 'updated',
|
||||
change_reason text,
|
||||
submission_id uuid REFERENCES public.content_submissions(id) ON DELETE SET NULL,
|
||||
is_current boolean NOT NULL DEFAULT true,
|
||||
|
||||
-- Mirror of rides table structure
|
||||
name text NOT NULL,
|
||||
slug text NOT NULL,
|
||||
description text,
|
||||
category text NOT NULL,
|
||||
status text NOT NULL,
|
||||
park_id uuid REFERENCES public.parks(id) ON DELETE SET NULL,
|
||||
manufacturer_id uuid REFERENCES public.companies(id) ON DELETE SET NULL,
|
||||
designer_id uuid REFERENCES public.companies(id) ON DELETE SET NULL,
|
||||
ride_model_id uuid,
|
||||
opening_date date,
|
||||
closing_date date,
|
||||
opening_date_precision text,
|
||||
closing_date_precision text,
|
||||
height_requirement_cm integer,
|
||||
max_speed_kmh numeric(6,2),
|
||||
duration_seconds integer,
|
||||
capacity_per_hour integer,
|
||||
gforce_max numeric(4,2),
|
||||
inversions_count integer,
|
||||
length_meters numeric(10,2),
|
||||
height_meters numeric(10,2),
|
||||
drop_meters numeric(10,2),
|
||||
angle_degrees numeric(5,2),
|
||||
former_names jsonb DEFAULT '[]'::jsonb,
|
||||
banner_image_url text,
|
||||
banner_image_id text,
|
||||
card_image_url text,
|
||||
card_image_id text,
|
||||
|
||||
UNIQUE(ride_id, version_number)
|
||||
);
|
||||
|
||||
-- Company Versions Table
|
||||
CREATE TABLE IF NOT EXISTS public.company_versions (
|
||||
-- Version metadata
|
||||
version_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
version_number integer NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid,
|
||||
change_type version_change_type NOT NULL DEFAULT 'updated',
|
||||
change_reason text,
|
||||
submission_id uuid REFERENCES public.content_submissions(id) ON DELETE SET NULL,
|
||||
is_current boolean NOT NULL DEFAULT true,
|
||||
|
||||
-- Mirror of companies table structure
|
||||
name text NOT NULL,
|
||||
slug text NOT NULL,
|
||||
description text,
|
||||
company_type text NOT NULL,
|
||||
person_type text DEFAULT 'company',
|
||||
founded_year integer,
|
||||
founded_date date,
|
||||
founded_date_precision text,
|
||||
headquarters_location text,
|
||||
website_url text,
|
||||
logo_url text,
|
||||
banner_image_url text,
|
||||
banner_image_id text,
|
||||
card_image_url text,
|
||||
card_image_id text,
|
||||
|
||||
UNIQUE(company_id, version_number)
|
||||
);
|
||||
|
||||
-- Ride Model Versions Table
|
||||
CREATE TABLE IF NOT EXISTS public.ride_model_versions (
|
||||
-- Version metadata
|
||||
version_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
ride_model_id uuid NOT NULL REFERENCES public.ride_models(id) ON DELETE CASCADE,
|
||||
version_number integer NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
created_by uuid,
|
||||
change_type version_change_type NOT NULL DEFAULT 'updated',
|
||||
change_reason text,
|
||||
submission_id uuid REFERENCES public.content_submissions(id) ON DELETE SET NULL,
|
||||
is_current boolean NOT NULL DEFAULT true,
|
||||
|
||||
-- Mirror of ride_models table structure
|
||||
name text NOT NULL,
|
||||
slug text NOT NULL,
|
||||
manufacturer_id uuid REFERENCES public.companies(id) ON DELETE SET NULL,
|
||||
category text NOT NULL,
|
||||
description text,
|
||||
technical_specs jsonb DEFAULT '{}'::jsonb,
|
||||
|
||||
UNIQUE(ride_model_id, version_number)
|
||||
);
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 2: Create Indexes for Performance
|
||||
-- ============================================================================
|
||||
|
||||
-- Park Versions Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_park_versions_park_id ON public.park_versions(park_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_park_versions_created_at ON public.park_versions(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_park_versions_current ON public.park_versions(park_id, is_current) WHERE is_current = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_park_versions_created_by ON public.park_versions(created_by) WHERE created_by IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_park_versions_submission_id ON public.park_versions(submission_id) WHERE submission_id IS NOT NULL;
|
||||
|
||||
-- Ride Versions Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_versions_ride_id ON public.ride_versions(ride_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_versions_created_at ON public.ride_versions(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_versions_current ON public.ride_versions(ride_id, is_current) WHERE is_current = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_versions_created_by ON public.ride_versions(created_by) WHERE created_by IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_versions_submission_id ON public.ride_versions(submission_id) WHERE submission_id IS NOT NULL;
|
||||
|
||||
-- Company Versions Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_company_versions_company_id ON public.company_versions(company_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_company_versions_created_at ON public.company_versions(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_company_versions_current ON public.company_versions(company_id, is_current) WHERE is_current = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_company_versions_created_by ON public.company_versions(created_by) WHERE created_by IS NOT NULL;
|
||||
|
||||
-- Ride Model Versions Indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_model_versions_model_id ON public.ride_model_versions(ride_model_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_model_versions_created_at ON public.ride_model_versions(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_ride_model_versions_current ON public.ride_model_versions(ride_model_id, is_current) WHERE is_current = true;
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 3: Create Universal Versioning Trigger Function
|
||||
-- ============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.create_relational_version()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_version_number integer;
|
||||
v_created_by uuid;
|
||||
v_change_type version_change_type;
|
||||
v_submission_id uuid;
|
||||
v_version_table text;
|
||||
v_entity_id_col text;
|
||||
BEGIN
|
||||
-- Determine version table name
|
||||
v_version_table := TG_TABLE_NAME || '_versions';
|
||||
v_entity_id_col := TG_TABLE_NAME || '_id';
|
||||
|
||||
-- Get user from session config (set by edge function)
|
||||
BEGIN
|
||||
v_created_by := current_setting('app.current_user_id', true)::uuid;
|
||||
EXCEPTION WHEN OTHERS THEN
|
||||
v_created_by := auth.uid();
|
||||
END;
|
||||
|
||||
-- Get submission ID if available
|
||||
BEGIN
|
||||
v_submission_id := current_setting('app.submission_id', true)::uuid;
|
||||
EXCEPTION WHEN OTHERS THEN
|
||||
v_submission_id := NULL;
|
||||
END;
|
||||
|
||||
-- Determine change type
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
v_change_type := 'created';
|
||||
v_version_number := 1;
|
||||
ELSIF TG_OP = 'UPDATE' THEN
|
||||
-- Only version if data actually changed (ignore updated_at, view counts, ratings)
|
||||
IF (OLD.name, OLD.slug, OLD.description, OLD.status) IS NOT DISTINCT FROM
|
||||
(NEW.name, NEW.slug, NEW.description, NEW.status) THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
v_change_type := 'updated';
|
||||
|
||||
-- Mark previous version as not current
|
||||
EXECUTE format('UPDATE %I SET is_current = false WHERE %I = $1 AND is_current = true',
|
||||
v_version_table, v_entity_id_col)
|
||||
USING NEW.id;
|
||||
|
||||
-- Get next version number
|
||||
EXECUTE format('SELECT COALESCE(MAX(version_number), 0) + 1 FROM %I WHERE %I = $1',
|
||||
v_version_table, v_entity_id_col)
|
||||
INTO v_version_number
|
||||
USING NEW.id;
|
||||
END IF;
|
||||
|
||||
-- Insert version record based on table type
|
||||
IF TG_TABLE_NAME = 'parks' THEN
|
||||
INSERT INTO public.park_versions (
|
||||
park_id, version_number, created_by, change_type, submission_id,
|
||||
name, slug, description, park_type, status, location_id, operator_id, property_owner_id,
|
||||
opening_date, closing_date, opening_date_precision, closing_date_precision,
|
||||
website_url, phone, email, banner_image_url, banner_image_id, card_image_url, card_image_id
|
||||
) VALUES (
|
||||
NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
|
||||
NEW.name, NEW.slug, NEW.description, NEW.park_type, NEW.status, NEW.location_id, NEW.operator_id, NEW.property_owner_id,
|
||||
NEW.opening_date, NEW.closing_date, NEW.opening_date_precision, NEW.closing_date_precision,
|
||||
NEW.website_url, NEW.phone, NEW.email, NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id
|
||||
);
|
||||
|
||||
ELSIF TG_TABLE_NAME = 'rides' THEN
|
||||
INSERT INTO public.ride_versions (
|
||||
ride_id, version_number, created_by, change_type, submission_id,
|
||||
name, slug, description, category, status, park_id, manufacturer_id, designer_id, ride_model_id,
|
||||
opening_date, closing_date, opening_date_precision, closing_date_precision,
|
||||
height_requirement_cm, max_speed_kmh, duration_seconds, capacity_per_hour, gforce_max,
|
||||
inversions_count, length_meters, height_meters, drop_meters, angle_degrees, former_names,
|
||||
banner_image_url, banner_image_id, card_image_url, card_image_id
|
||||
) VALUES (
|
||||
NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
|
||||
NEW.name, NEW.slug, NEW.description, NEW.category, NEW.status, NEW.park_id, NEW.manufacturer_id, NEW.designer_id, NEW.ride_model_id,
|
||||
NEW.opening_date, NEW.closing_date, NEW.opening_date_precision, NEW.closing_date_precision,
|
||||
NEW.height_requirement_cm, NEW.max_speed_kmh, NEW.duration_seconds, NEW.capacity_per_hour, NEW.gforce_max,
|
||||
NEW.inversions_count, NEW.length_meters, NEW.height_meters, NEW.drop_meters, NEW.angle_degrees, NEW.former_names,
|
||||
NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id
|
||||
);
|
||||
|
||||
ELSIF TG_TABLE_NAME = 'companies' THEN
|
||||
INSERT INTO public.company_versions (
|
||||
company_id, version_number, created_by, change_type, submission_id,
|
||||
name, slug, description, company_type, person_type, founded_year, founded_date, founded_date_precision,
|
||||
headquarters_location, website_url, logo_url, banner_image_url, banner_image_id, card_image_url, card_image_id
|
||||
) VALUES (
|
||||
NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
|
||||
NEW.name, NEW.slug, NEW.description, NEW.company_type, NEW.person_type, NEW.founded_year, NEW.founded_date, NEW.founded_date_precision,
|
||||
NEW.headquarters_location, NEW.website_url, NEW.logo_url, NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id
|
||||
);
|
||||
|
||||
ELSIF TG_TABLE_NAME = 'ride_models' THEN
|
||||
INSERT INTO public.ride_model_versions (
|
||||
ride_model_id, version_number, created_by, change_type, submission_id,
|
||||
name, slug, manufacturer_id, category, description, technical_specs
|
||||
) VALUES (
|
||||
NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
|
||||
NEW.name, NEW.slug, NEW.manufacturer_id, NEW.category, NEW.description, NEW.technical_specs
|
||||
);
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 4: Attach Triggers to Entity Tables
|
||||
-- ============================================================================
|
||||
|
||||
DROP TRIGGER IF EXISTS create_park_version_on_change ON public.parks;
|
||||
CREATE TRIGGER create_park_version_on_change
|
||||
AFTER INSERT OR UPDATE ON public.parks
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.create_relational_version();
|
||||
|
||||
DROP TRIGGER IF EXISTS create_ride_version_on_change ON public.rides;
|
||||
CREATE TRIGGER create_ride_version_on_change
|
||||
AFTER INSERT OR UPDATE ON public.rides
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.create_relational_version();
|
||||
|
||||
DROP TRIGGER IF EXISTS create_company_version_on_change ON public.companies;
|
||||
CREATE TRIGGER create_company_version_on_change
|
||||
AFTER INSERT OR UPDATE ON public.companies
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.create_relational_version();
|
||||
|
||||
DROP TRIGGER IF EXISTS create_ride_model_version_on_change ON public.ride_models;
|
||||
CREATE TRIGGER create_ride_model_version_on_change
|
||||
AFTER INSERT OR UPDATE ON public.ride_models
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.create_relational_version();
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 5: Create RLS Policies
|
||||
-- ============================================================================
|
||||
|
||||
-- Enable RLS on version tables
|
||||
ALTER TABLE public.park_versions ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.ride_versions ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.company_versions ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.ride_model_versions ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Public can view current versions
|
||||
CREATE POLICY "Public can view current park versions"
|
||||
ON public.park_versions FOR SELECT
|
||||
USING (is_current = true);
|
||||
|
||||
CREATE POLICY "Public can view current ride versions"
|
||||
ON public.ride_versions FOR SELECT
|
||||
USING (is_current = true);
|
||||
|
||||
CREATE POLICY "Public can view current company versions"
|
||||
ON public.company_versions FOR SELECT
|
||||
USING (is_current = true);
|
||||
|
||||
CREATE POLICY "Public can view current ride model versions"
|
||||
ON public.ride_model_versions FOR SELECT
|
||||
USING (is_current = true);
|
||||
|
||||
-- Moderators can view all versions
|
||||
CREATE POLICY "Moderators can view all park versions"
|
||||
ON public.park_versions FOR SELECT
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
CREATE POLICY "Moderators can view all ride versions"
|
||||
ON public.ride_versions FOR SELECT
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
CREATE POLICY "Moderators can view all company versions"
|
||||
ON public.company_versions FOR SELECT
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
CREATE POLICY "Moderators can view all ride model versions"
|
||||
ON public.ride_model_versions FOR SELECT
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
-- Users can view their own submitted versions
|
||||
CREATE POLICY "Users can view their own park versions"
|
||||
ON public.park_versions FOR SELECT
|
||||
USING (created_by = auth.uid());
|
||||
|
||||
CREATE POLICY "Users can view their own ride versions"
|
||||
ON public.ride_versions FOR SELECT
|
||||
USING (created_by = auth.uid());
|
||||
|
||||
CREATE POLICY "Users can view their own company versions"
|
||||
ON public.company_versions FOR SELECT
|
||||
USING (created_by = auth.uid());
|
||||
|
||||
-- ============================================================================
|
||||
-- STEP 6: Create Utility Functions
|
||||
-- ============================================================================
|
||||
|
||||
-- Function to clean up old versions (keep last N versions per entity)
|
||||
CREATE OR REPLACE FUNCTION public.cleanup_old_versions(
|
||||
entity_type text,
|
||||
keep_versions integer DEFAULT 50
|
||||
)
|
||||
RETURNS integer
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
deleted_count integer := 0;
|
||||
versions_table text;
|
||||
entity_id_col text;
|
||||
BEGIN
|
||||
versions_table := entity_type || '_versions';
|
||||
entity_id_col := entity_type || '_id';
|
||||
|
||||
EXECUTE format('
|
||||
DELETE FROM %I
|
||||
WHERE version_id IN (
|
||||
SELECT version_id
|
||||
FROM (
|
||||
SELECT
|
||||
version_id,
|
||||
ROW_NUMBER() OVER (PARTITION BY %I ORDER BY version_number DESC) as rn
|
||||
FROM %I
|
||||
) sub
|
||||
WHERE rn > $1
|
||||
)
|
||||
', versions_table, entity_id_col, versions_table)
|
||||
USING keep_versions;
|
||||
|
||||
GET DIAGNOSTICS deleted_count = ROW_COUNT;
|
||||
|
||||
RETURN deleted_count;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Function to get version comparison
|
||||
CREATE OR REPLACE FUNCTION public.get_version_diff(
|
||||
p_entity_type text,
|
||||
p_from_version_id uuid,
|
||||
p_to_version_id uuid
|
||||
)
|
||||
RETURNS jsonb
|
||||
LANGUAGE plpgsql
|
||||
STABLE SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_table text;
|
||||
v_from_record jsonb;
|
||||
v_to_record jsonb;
|
||||
v_diff jsonb := '{}'::jsonb;
|
||||
BEGIN
|
||||
v_table := p_entity_type || '_versions';
|
||||
|
||||
-- Fetch both versions as JSONB for comparison
|
||||
EXECUTE format('SELECT row_to_json(t)::jsonb FROM %I t WHERE version_id = $1', v_table)
|
||||
INTO v_from_record
|
||||
USING p_from_version_id;
|
||||
|
||||
EXECUTE format('SELECT row_to_json(t)::jsonb FROM %I t WHERE version_id = $1', v_table)
|
||||
INTO v_to_record
|
||||
USING p_to_version_id;
|
||||
|
||||
-- Build diff object (simplified - just show changed fields)
|
||||
SELECT jsonb_object_agg(key, jsonb_build_object('from', v_from_record->key, 'to', v_to_record->key))
|
||||
INTO v_diff
|
||||
FROM jsonb_each(v_to_record)
|
||||
WHERE key NOT IN ('version_id', 'version_number', 'created_at', 'created_by', 'is_current', 'change_type', 'change_reason', 'submission_id')
|
||||
AND v_from_record->key IS DISTINCT FROM v_to_record->key;
|
||||
|
||||
RETURN COALESCE(v_diff, '{}'::jsonb);
|
||||
END;
|
||||
$$;
|
||||
Reference in New Issue
Block a user