import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import { fetchEditHistory } from '@/lib/submissionItemsService'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { EditHistoryEntry } from './EditHistoryEntry'; import { History, Loader2, AlertCircle } from 'lucide-react'; interface EditHistoryRecord { id: string; item_id: string; edited_at: string; edit_reason: string | null; changed_fields: string[]; field_changes?: Array<{ id: string; field_name: string; old_value: string | null; new_value: string | null; }>; editor?: { username: string; avatar_url?: string | null; } | null; } interface EditHistoryAccordionProps { submissionId: string; } const INITIAL_LOAD = 20; const LOAD_MORE_INCREMENT = 10; export function EditHistoryAccordion({ submissionId }: EditHistoryAccordionProps) { const [limit, setLimit] = useState(INITIAL_LOAD); const { data: editHistory, isLoading, error } = useQuery({ queryKey: ['edit-history', submissionId, limit], queryFn: async () => { const { supabase } = await import('@/integrations/supabase/client'); // Fetch edit history with user profiles const { data, error } = await supabase .from('item_edit_history') .select(` id, item_id, edited_at, edit_reason, changed_fields, field_changes:item_field_changes( id, field_name, old_value, new_value ), editor:profiles!item_edit_history_edited_by_fkey( username, avatar_url ) `) .eq('item_id', submissionId) .order('edited_at', { ascending: false }) .limit(limit); if (error) throw error; return (data || []) as unknown as EditHistoryRecord[]; }, staleTime: 5 * 60 * 1000, // 5 minutes }); const loadMore = () => { setLimit(prev => prev + LOAD_MORE_INCREMENT); }; const hasMore = editHistory && editHistory.length === limit; return (
Edit History {editHistory && editHistory.length > 0 && ( ({editHistory.length} edit{editHistory.length !== 1 ? 's' : ''}) )}
{isLoading && (
)} {error && ( Failed to load edit history: {error instanceof Error ? error.message : 'Unknown error'} )} {!isLoading && !error && editHistory && editHistory.length === 0 && ( No edit history found for this submission. )} {!isLoading && !error && editHistory && editHistory.length > 0 && (
{editHistory.map((entry: EditHistoryRecord) => { // Transform relational field_changes into beforeData/afterData objects const beforeData: Record = {}; const afterData: Record = {}; entry.field_changes?.forEach(change => { beforeData[change.field_name] = change.old_value; afterData[change.field_name] = change.new_value; }); return ( ); })}
{hasMore && (
)}
)}
); }