Files
thrilltrack-explorer/src/components/moderation/QueueItem.tsx
2025-10-10 00:38:04 +00:00

655 lines
29 KiB
TypeScript

import { memo, useState } from 'react';
import { CheckCircle, XCircle, Eye, Calendar, MessageSquare, FileText, Image, ListTree, RefreshCw, AlertCircle, Lock, Trash2, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { format } from 'date-fns';
import { SubmissionItemsList } from './SubmissionItemsList';
import { MeasurementDisplay } from '@/components/ui/measurement-display';
interface ModerationItem {
id: string;
type: 'review' | 'content_submission';
content: any;
created_at: string;
updated_at?: string;
user_id: string;
status: string;
submission_type?: string;
user_profile?: {
username: string;
display_name?: string;
avatar_url?: string;
};
entity_name?: string;
park_name?: string;
reviewed_at?: string;
reviewed_by?: string;
reviewer_notes?: string;
reviewer_profile?: {
username: string;
display_name?: string;
avatar_url?: string;
};
escalated?: boolean;
assigned_to?: string;
locked_until?: string;
}
import { ValidationSummary } from './ValidationSummary';
import type { ValidationResult } from '@/lib/entityValidationSchemas';
interface QueueItemProps {
item: ModerationItem;
isMobile: boolean;
actionLoading: string | null;
lockedSubmissions: Set<string>;
currentLockSubmissionId?: string;
notes: Record<string, string>;
isAdmin: boolean;
isSuperuser: boolean;
queueIsLoading: boolean;
onNoteChange: (id: string, value: string) => void;
onApprove: (item: ModerationItem, action: 'approved' | 'rejected', notes?: string) => void;
onResetToPending: (item: ModerationItem) => void;
onRetryFailed: (item: ModerationItem) => void;
onOpenPhotos: (photos: any[], index: number) => void;
onOpenReviewManager: (submissionId: string) => void;
onClaimSubmission: (submissionId: string) => void;
onDeleteSubmission: (item: ModerationItem) => void;
onInteractionFocus: (id: string) => void;
onInteractionBlur: (id: string) => void;
}
const getStatusBadgeVariant = (status: string): "default" | "secondary" | "destructive" | "outline" => {
switch (status) {
case 'pending': return 'default';
case 'approved': return 'secondary';
case 'rejected': return 'destructive';
case 'flagged': return 'destructive';
case 'partially_approved': return 'outline';
default: return 'outline';
}
};
export const QueueItem = memo(({
item,
isMobile,
actionLoading,
lockedSubmissions,
currentLockSubmissionId,
notes,
isAdmin,
isSuperuser,
queueIsLoading,
onNoteChange,
onApprove,
onResetToPending,
onRetryFailed,
onOpenPhotos,
onOpenReviewManager,
onClaimSubmission,
onDeleteSubmission,
onInteractionFocus,
onInteractionBlur
}: QueueItemProps) => {
const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
return (
<Card
key={item.id}
className={`border-l-4 transition-opacity duration-200 ${
validationResult?.blockingErrors && validationResult.blockingErrors.length > 0 ? 'border-l-red-600' :
item.status === 'flagged' ? 'border-l-red-500' :
item.status === 'approved' ? 'border-l-green-500' :
item.status === 'rejected' ? 'border-l-red-400' :
item.status === 'partially_approved' ? 'border-l-yellow-500' :
'border-l-amber-500'
}`}
style={{
opacity: actionLoading === item.id ? 0.5 : 1,
pointerEvents: actionLoading === item.id ? 'none' : 'auto'
}}
>
<CardHeader className={isMobile ? "pb-3 p-4" : "pb-4"}>
<div className={`flex gap-3 ${isMobile ? 'flex-col' : 'items-center justify-between'}`}>
<div className="flex items-center gap-2 flex-wrap">
<Badge variant={getStatusBadgeVariant(item.status)} className={isMobile ? "text-xs" : ""}>
{item.type === 'review' ? (
<>
<MessageSquare className="w-3 h-3 mr-1" />
Review
</>
) : item.submission_type === 'photo' ? (
<>
<Image className="w-3 h-3 mr-1" />
Photo
</>
) : (
<>
<FileText className="w-3 h-3 mr-1" />
Submission
</>
)}
</Badge>
<Badge variant={getStatusBadgeVariant(item.status)} className={isMobile ? "text-xs" : ""}>
{item.status === 'partially_approved' ? 'Partially Approved' :
item.status.charAt(0).toUpperCase() + item.status.slice(1)}
</Badge>
{item.status === 'partially_approved' && (
<Badge variant="outline" className="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700">
<AlertCircle className="w-3 h-3 mr-1" />
Needs Retry
</Badge>
)}
{lockedSubmissions.has(item.id) && item.type === 'content_submission' && (
<Badge variant="outline" className="bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300 border-orange-300 dark:border-orange-700">
<Lock className="w-3 h-3 mr-1" />
Locked by Another Moderator
</Badge>
)}
{currentLockSubmissionId === item.id && item.type === 'content_submission' && (
<Badge variant="outline" className="bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 border-blue-300 dark:border-blue-700">
<Lock className="w-3 h-3 mr-1" />
Claimed by You
</Badge>
)}
{item.submission_type && (
<ValidationSummary
item={{
item_type: item.submission_type,
item_data: item.content,
id: item.id,
}}
compact={true}
onValidationChange={setValidationResult}
/>
)}
</div>
<div className={`flex items-center gap-2 text-muted-foreground ${isMobile ? 'text-xs' : 'text-sm'}`}>
<Calendar className={isMobile ? "w-3 h-3" : "w-4 h-4"} />
{format(new Date(item.created_at), isMobile ? 'MMM d, yyyy' : 'MMM d, yyyy HH:mm')}
</div>
</div>
{item.user_profile && (
<div className={`flex items-center gap-3 ${isMobile ? 'text-xs' : 'text-sm'}`}>
<Avatar className={isMobile ? "h-7 w-7" : "h-8 w-8"}>
<AvatarImage src={item.user_profile.avatar_url} />
<AvatarFallback className={isMobile ? "text-xs" : ""}>
{(item.user_profile.display_name || item.user_profile.username)?.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<span className="font-medium">
{item.user_profile.display_name || item.user_profile.username}
</span>
{item.user_profile.display_name && (
<span className={`text-muted-foreground block ${isMobile ? 'text-xs' : 'text-xs'}`}>
@{item.user_profile.username}
</span>
)}
</div>
</div>
)}
</CardHeader>
<CardContent className={`space-y-4 ${isMobile ? 'p-4 pt-0' : ''}`}>
<div className={`bg-muted/50 rounded-lg ${isMobile ? 'p-3' : 'p-4'}`}>
{item.type === 'review' ? (
<div>
{item.content.title && (
<h4 className="font-semibold mb-2">{item.content.title}</h4>
)}
{item.content.content && (
<p className="text-sm mb-2">{item.content.content}</p>
)}
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-2">
<span>Rating: {item.content.rating}/5</span>
</div>
{/* Entity Names for Reviews */}
{(item.entity_name || item.park_name) && (
<div className="space-y-1 mb-2">
{item.entity_name && (
<div className="text-sm text-muted-foreground">
<span className="text-xs">{item.park_name ? 'Ride:' : 'Park:'} </span>
<span className="text-base font-medium text-foreground">{item.entity_name}</span>
</div>
)}
{item.park_name && (
<div className="text-sm text-muted-foreground">
<span className="text-xs">Park: </span>
<span className="text-base font-medium text-foreground">{item.park_name}</span>
</div>
)}
</div>
)}
{item.content.photos && item.content.photos.length > 0 && (
<div className="mt-3">
<div className="text-sm font-medium mb-2">Attached Photos:</div>
<div className="grid grid-cols-2 md:grid-cols-3 gap-2">
{item.content.photos.map((photo: any, index: number) => (
<div key={index} className="relative cursor-pointer" onClick={() => {
onOpenPhotos(item.content.photos.map((p: any, i: number) => ({
id: `${item.id}-${i}`,
url: p.url,
filename: `Review photo ${i + 1}`,
caption: p.caption
})), index);
}}>
<img
src={photo.url}
alt={`Review photo ${index + 1}`}
className="w-full h-20 object-cover rounded border bg-muted/30 hover:opacity-80 transition-opacity"
onError={(e) => {
console.error('Failed to load review photo:', photo.url);
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 text-white text-xs opacity-0 hover:opacity-100 transition-opacity rounded">
<Eye className="w-4 h-4" />
</div>
</div>
))}
</div>
</div>
)}
</div>
) : item.submission_type === 'photo' ? (
<div>
<div className="text-sm text-muted-foreground mb-3">
Photo Submission
</div>
{/* Submission Title */}
{item.content.title && (
<div className="mb-3">
<div className="text-sm font-medium mb-1">Title:</div>
<p className="text-sm">{item.content.title}</p>
</div>
)}
{/* Submission Caption */}
{item.content.content?.caption && (
<div className="mb-3">
<div className="text-sm font-medium mb-1">Caption:</div>
<p className="text-sm">{item.content.content.caption}</p>
</div>
)}
{/* Photos */}
{item.content.content?.photos && item.content.content.photos.length > 0 ? (
<div className="space-y-4">
<div className="text-sm font-medium">Photos ({item.content.content.photos.length}):</div>
{item.content.content.photos.map((photo: any, index: number) => (
<div key={index} className="border rounded-lg p-3 space-y-2">
<div className="relative min-h-[100px] bg-muted/30 rounded border overflow-hidden cursor-pointer" onClick={() => {
onOpenPhotos(item.content.content.photos.map((p: any, i: number) => ({
id: `${item.id}-${i}`,
url: p.url,
filename: p.filename,
caption: p.caption
})), index);
}}>
<img
src={photo.url}
alt={`Photo ${index + 1}: ${photo.filename}`}
className="w-full max-h-64 object-contain rounded hover:opacity-80 transition-opacity"
onError={(e) => {
console.error('Failed to load photo submission:', photo);
const target = e.target as HTMLImageElement;
target.style.display = 'none';
const parent = target.parentElement;
if (parent) {
// Create elements safely using DOM API to prevent XSS
const errorContainer = document.createElement('div');
errorContainer.className = 'absolute inset-0 flex flex-col items-center justify-center text-destructive text-xs';
const errorIcon = document.createElement('div');
errorIcon.textContent = '⚠️ Image failed to load';
const urlDisplay = document.createElement('div');
urlDisplay.className = 'mt-1 font-mono text-xs break-all px-2';
// Use textContent to prevent XSS - it escapes HTML automatically
urlDisplay.textContent = photo.url;
errorContainer.appendChild(errorIcon);
errorContainer.appendChild(urlDisplay);
parent.appendChild(errorContainer);
}
}}
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 text-white opacity-0 hover:opacity-100 transition-opacity rounded">
<Eye className="w-5 h-5" />
</div>
</div>
<div className="space-y-1 text-xs text-muted-foreground">
<div className="flex justify-between">
<span className="font-medium">URL:</span>
<span className="font-mono text-xs break-all">{photo.url}</span>
</div>
<div className="flex justify-between">
<span className="font-medium">Filename:</span>
<span>{photo.filename || 'Unknown'}</span>
</div>
<div className="flex justify-between">
<span className="font-medium">Size:</span>
<span>{photo.size ? `${Math.round(photo.size / 1024)} KB` : 'Unknown'}</span>
</div>
<div className="flex justify-between">
<span className="font-medium">Type:</span>
<span>{photo.type || 'Unknown'}</span>
</div>
{photo.caption && (
<div className="pt-1">
<div className="font-medium">Caption:</div>
<div className="text-sm text-foreground mt-1">{photo.caption}</div>
</div>
)}
</div>
</div>
))}
</div>
) : (
<div className="text-sm text-muted-foreground">
No photos found in submission
</div>
)}
{/* Context Information */}
{item.content.content?.context && (
<div className="mt-3 pt-3 border-t text-xs text-muted-foreground">
<div className="flex justify-between">
<span className="font-medium">Context:</span>
<span className="capitalize">
{typeof item.content.content.context === 'object'
? (item.content.content.context.ride_id ? 'ride' :
item.content.content.context.park_id ? 'park' : 'unknown')
: item.content.content.context}
</span>
</div>
{item.entity_name && (
<div className="flex justify-between">
<span className="font-medium text-xs">
{(typeof item.content.content.context === 'object'
? (item.content.content.context.ride_id ? 'ride' : 'park')
: item.content.content.context) === 'ride' ? 'Ride:' : 'Park:'}
</span>
<span className="font-medium text-foreground text-base">{item.entity_name}</span>
</div>
)}
{item.park_name &&
(typeof item.content.content.context === 'object'
? !!item.content.content.context.ride_id
: item.content.content.context === 'ride') && (
<div className="flex justify-between">
<span className="font-medium text-xs">Park:</span>
<span className="font-medium text-foreground text-base">{item.park_name}</span>
</div>
)}
</div>
)}
</div>
) : (
<div>
{/* Composite Submissions or Standard Submissions */}
<SubmissionItemsList
submissionId={item.id}
view="detailed"
showImages={true}
/>
</div>
)}
</div>
{/* Action buttons based on status */}
{(item.status === 'pending' || item.status === 'flagged') && (
<>
{/* Claim button for unclaimed submissions */}
{!lockedSubmissions.has(item.id) && currentLockSubmissionId !== item.id && (
<div className="mb-4">
<Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950/20">
<AlertCircle className="h-4 w-4 text-blue-600" />
<AlertTitle className="text-blue-900 dark:text-blue-100">Unclaimed Submission</AlertTitle>
<AlertDescription className="text-blue-800 dark:text-blue-200">
<div className="flex items-center justify-between mt-2">
<span className="text-sm">Claim this submission to lock it for 15 minutes while you review</span>
<Button
onClick={() => onClaimSubmission(item.id)}
disabled={queueIsLoading}
size="sm"
className="ml-4"
>
<Lock className="w-4 h-4 mr-2" />
Claim Submission
</Button>
</div>
</AlertDescription>
</Alert>
</div>
)}
<div className="space-y-2">
<Label htmlFor={`notes-${item.id}`}>Moderation Notes (optional)</Label>
<Textarea
id={`notes-${item.id}`}
placeholder="Add notes about your moderation decision..."
value={notes[item.id] || ''}
onChange={(e) => onNoteChange(item.id, e.target.value)}
onFocus={() => onInteractionFocus(item.id)}
onBlur={() => onInteractionBlur(item.id)}
rows={2}
disabled={lockedSubmissions.has(item.id) || currentLockSubmissionId !== item.id}
/>
</div>
<div className={`flex gap-2 pt-2 ${isMobile ? 'flex-col' : 'flex-col sm:flex-row'}`}>
{/* Show Review Items button for content submissions */}
{item.type === 'content_submission' && (
<Button
onClick={() => onOpenReviewManager(item.id)}
disabled={actionLoading === item.id || lockedSubmissions.has(item.id) || currentLockSubmissionId !== item.id}
variant="outline"
className={`flex-1 ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<ListTree className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Review Items
</Button>
)}
<Button
onClick={() => onApprove(item, 'approved', notes[item.id])}
disabled={actionLoading === item.id || lockedSubmissions.has(item.id) || currentLockSubmissionId !== item.id}
className={`flex-1 ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<CheckCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Approve
</Button>
<Button
variant="destructive"
onClick={() => onApprove(item, 'rejected', notes[item.id])}
disabled={actionLoading === item.id || lockedSubmissions.has(item.id) || currentLockSubmissionId !== item.id}
className={`flex-1 ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<XCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Reject
</Button>
</div>
</>
)}
{/* Reset button for rejected items */}
{item.status === 'rejected' && item.type === 'content_submission' && (
<div className="space-y-3 pt-4 border-t bg-red-50 dark:bg-red-950/20 -mx-4 px-4 py-3 rounded-b-lg">
<div className="flex items-start gap-2 text-sm text-red-800 dark:text-red-300">
<AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
<div>
<p className="font-medium">This submission was rejected</p>
<p className="text-xs mt-1">You can reset it to pending to re-review and approve it.</p>
</div>
</div>
<Button
onClick={() => onResetToPending(item)}
disabled={actionLoading === item.id}
variant="outline"
className="w-full"
>
<RefreshCw className="w-4 h-4 mr-2" />
Reset to Pending
</Button>
</div>
)}
{/* Retry/Reset buttons for partially approved items */}
{item.status === 'partially_approved' && item.type === 'content_submission' && (
<div className="space-y-3 pt-4 border-t bg-yellow-50 dark:bg-yellow-950/20 -mx-4 px-4 py-3 rounded-b-lg">
<div className="flex items-start gap-2 text-sm text-yellow-800 dark:text-yellow-300">
<AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
<div>
<p className="font-medium">This submission was partially approved</p>
<p className="text-xs mt-1">Some items failed. You can retry them or reset everything to pending.</p>
</div>
</div>
<div className="flex gap-2">
<Button
onClick={() => onOpenReviewManager(item.id)}
disabled={actionLoading === item.id}
variant="outline"
className="flex-1"
>
<ListTree className="w-4 h-4 mr-2" />
Review Items
</Button>
<Button
onClick={() => onResetToPending(item)}
disabled={actionLoading === item.id}
variant="outline"
className="flex-1"
>
<RefreshCw className="w-4 h-4 mr-2" />
Reset All
</Button>
<Button
onClick={() => onRetryFailed(item)}
disabled={actionLoading === item.id}
className="flex-1 bg-yellow-600 hover:bg-yellow-700"
>
<RefreshCw className="w-4 h-4 mr-2" />
Retry Failed
</Button>
</div>
</div>
)}
{/* Reviewer Information for approved/rejected items */}
{(item.status === 'approved' || item.status === 'rejected') && (item.reviewed_at || item.reviewer_notes) && (
<div className="space-y-3 pt-4 border-t">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<span>Reviewed {item.reviewed_at ? format(new Date(item.reviewed_at), 'MMM d, yyyy HH:mm') : 'recently'}</span>
{item.reviewer_profile && (
<>
<span>by</span>
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
<AvatarImage src={item.reviewer_profile.avatar_url} />
<AvatarFallback className="text-xs">
{(item.reviewer_profile.display_name || item.reviewer_profile.username)?.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="font-medium">
{item.reviewer_profile.display_name || item.reviewer_profile.username}
</span>
</div>
</>
)}
</div>
{item.reviewer_notes && (
<div className="bg-muted/30 p-3 rounded-lg">
<p className="text-sm font-medium mb-1">Reviewer Notes:</p>
<p className="text-sm text-muted-foreground">{item.reviewer_notes}</p>
</div>
)}
{/* Reverse Decision Buttons */}
<div className="space-y-2">
<Label className="text-sm">Reverse Decision</Label>
<Textarea
placeholder="Add notes about reversing this decision..."
value={notes[`reverse-${item.id}`] || ''}
onChange={(e) => onNoteChange(`reverse-${item.id}`, e.target.value)}
onFocus={() => onInteractionFocus(item.id)}
onBlur={() => onInteractionBlur(item.id)}
rows={2}
/>
<div className={`flex gap-2 ${isMobile ? 'flex-col' : ''}`}>
{item.status === 'approved' && (
<Button
variant="destructive"
onClick={() => onApprove(item, 'rejected', notes[`reverse-${item.id}`])}
disabled={actionLoading === item.id}
className={`flex-1 ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<XCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Change to Rejected
</Button>
)}
{item.status === 'rejected' && (
<Button
onClick={() => onApprove(item, 'approved', notes[`reverse-${item.id}`])}
disabled={actionLoading === item.id}
className={`flex-1 ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<CheckCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Change to Approved
</Button>
)}
</div>
</div>
</div>
)}
{/* Delete button for rejected submissions (admin/superadmin only) */}
{item.status === 'rejected' && item.type === 'content_submission' && (isAdmin || isSuperuser) && (
<div className="pt-2">
<Button
variant="destructive"
onClick={() => onDeleteSubmission(item)}
disabled={actionLoading === item.id}
className={`w-full ${isMobile ? 'h-11' : ''}`}
size={isMobile ? "default" : "default"}
>
<Trash2 className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
Delete Submission
</Button>
</div>
)}
</CardContent>
</Card>
);
}, (prevProps, nextProps) => {
// Custom comparison to prevent re-renders
return (
prevProps.item.id === nextProps.item.id &&
prevProps.item.status === nextProps.item.status &&
prevProps.actionLoading === nextProps.actionLoading &&
prevProps.lockedSubmissions.has(prevProps.item.id) === nextProps.lockedSubmissions.has(nextProps.item.id) &&
prevProps.currentLockSubmissionId === nextProps.currentLockSubmissionId &&
prevProps.notes[prevProps.item.id] === nextProps.notes[nextProps.item.id] &&
prevProps.notes[`reverse-${prevProps.item.id}`] === nextProps.notes[`reverse-${nextProps.item.id}`]
);
});
QueueItem.displayName = 'QueueItem';