mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 06:31:13 -05:00
feat: Implement comprehensive validation system
This commit is contained in:
@@ -6,6 +6,9 @@ import { type SubmissionItemWithDeps } from '@/lib/submissionItemsService';
|
|||||||
import { useIsMobile } from '@/hooks/use-mobile';
|
import { useIsMobile } from '@/hooks/use-mobile';
|
||||||
import { PhotoSubmissionDisplay } from './PhotoSubmissionDisplay';
|
import { PhotoSubmissionDisplay } from './PhotoSubmissionDisplay';
|
||||||
import { SubmissionChangesDisplay } from './SubmissionChangesDisplay';
|
import { SubmissionChangesDisplay } from './SubmissionChangesDisplay';
|
||||||
|
import { ValidationSummary } from './ValidationSummary';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { ValidationResult } from '@/lib/entityValidationSchemas';
|
||||||
|
|
||||||
interface ItemReviewCardProps {
|
interface ItemReviewCardProps {
|
||||||
item: SubmissionItemWithDeps;
|
item: SubmissionItemWithDeps;
|
||||||
@@ -16,6 +19,7 @@ interface ItemReviewCardProps {
|
|||||||
|
|
||||||
export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: ItemReviewCardProps) {
|
export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: ItemReviewCardProps) {
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
|
const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
|
||||||
|
|
||||||
const getItemIcon = () => {
|
const getItemIcon = () => {
|
||||||
switch (item.item_type) {
|
switch (item.item_type) {
|
||||||
@@ -40,6 +44,20 @@ export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: I
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getValidationBadgeVariant = (): "default" | "secondary" | "destructive" | "outline" => {
|
||||||
|
if (!validationResult) return 'outline';
|
||||||
|
if (validationResult.blockingErrors.length > 0) return 'destructive';
|
||||||
|
if (validationResult.warnings.length > 0) return 'outline';
|
||||||
|
return 'secondary';
|
||||||
|
};
|
||||||
|
|
||||||
|
const getValidationBadgeLabel = () => {
|
||||||
|
if (!validationResult) return 'Validating...';
|
||||||
|
if (validationResult.blockingErrors.length > 0) return '❌ Errors';
|
||||||
|
if (validationResult.warnings.length > 0) return '⚠️ Warnings';
|
||||||
|
return '✓ Valid';
|
||||||
|
};
|
||||||
|
|
||||||
const renderItemPreview = () => {
|
const renderItemPreview = () => {
|
||||||
// Use detailed view for review manager with photo detection
|
// Use detailed view for review manager with photo detection
|
||||||
return (
|
return (
|
||||||
@@ -71,6 +89,9 @@ export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: I
|
|||||||
<Badge variant={getStatusColor()} className={isMobile ? "text-xs" : ""}>
|
<Badge variant={getStatusColor()} className={isMobile ? "text-xs" : ""}>
|
||||||
{item.status}
|
{item.status}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
<Badge variant={getValidationBadgeVariant()} className={isMobile ? "text-xs" : ""}>
|
||||||
|
{getValidationBadgeLabel()}
|
||||||
|
</Badge>
|
||||||
{item.status === 'pending' && (
|
{item.status === 'pending' && (
|
||||||
<Button
|
<Button
|
||||||
size={isMobile ? "default" : "sm"}
|
size={isMobile ? "default" : "sm"}
|
||||||
@@ -88,6 +109,19 @@ export function ItemReviewCard({ item, onEdit, onStatusChange, submissionId }: I
|
|||||||
<CardContent className={isMobile ? "p-4 pt-0" : ""}>
|
<CardContent className={isMobile ? "p-4 pt-0" : ""}>
|
||||||
{renderItemPreview()}
|
{renderItemPreview()}
|
||||||
|
|
||||||
|
{/* Validation Summary */}
|
||||||
|
<div className="border-t pt-4 mt-4">
|
||||||
|
<ValidationSummary
|
||||||
|
item={{
|
||||||
|
item_type: item.item_type,
|
||||||
|
item_data: item.item_data,
|
||||||
|
id: item.id,
|
||||||
|
}}
|
||||||
|
onValidationChange={setValidationResult}
|
||||||
|
compact={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{item.depends_on && (
|
{item.depends_on && (
|
||||||
<div className="mt-3 pt-3 border-t">
|
<div className="mt-3 pt-3 border-t">
|
||||||
<p className={`text-muted-foreground ${isMobile ? 'text-xs' : 'text-xs'}`}>
|
<p className={`text-muted-foreground ${isMobile ? 'text-xs' : 'text-xs'}`}>
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ interface ModerationItem {
|
|||||||
locked_until?: string;
|
locked_until?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
import { ValidationSummary } from './ValidationSummary';
|
||||||
|
|
||||||
interface QueueItemProps {
|
interface QueueItemProps {
|
||||||
item: ModerationItem;
|
item: ModerationItem;
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
@@ -152,6 +154,14 @@ export const QueueItem = memo(({
|
|||||||
Claimed by You
|
Claimed by You
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
|
<ValidationSummary
|
||||||
|
item={{
|
||||||
|
item_type: item.submission_type || 'submission',
|
||||||
|
item_data: item.content,
|
||||||
|
id: item.id,
|
||||||
|
}}
|
||||||
|
compact={true}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className={`flex items-center gap-2 text-muted-foreground ${isMobile ? 'text-xs' : 'text-sm'}`}>
|
<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"} />
|
<Calendar className={isMobile ? "w-3 h-3" : "w-4 h-4"} />
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ import { ConflictResolutionDialog } from './ConflictResolutionDialog';
|
|||||||
import { EscalationDialog } from './EscalationDialog';
|
import { EscalationDialog } from './EscalationDialog';
|
||||||
import { RejectionDialog } from './RejectionDialog';
|
import { RejectionDialog } from './RejectionDialog';
|
||||||
import { ItemEditDialog } from './ItemEditDialog';
|
import { ItemEditDialog } from './ItemEditDialog';
|
||||||
|
import { ValidationBlockerDialog } from './ValidationBlockerDialog';
|
||||||
|
import { WarningConfirmDialog } from './WarningConfirmDialog';
|
||||||
|
import { validateMultipleItems, ValidationResult } from '@/lib/entityValidationSchemas';
|
||||||
|
|
||||||
interface SubmissionReviewManagerProps {
|
interface SubmissionReviewManagerProps {
|
||||||
submissionId: string;
|
submissionId: string;
|
||||||
@@ -53,6 +56,10 @@ export function SubmissionReviewManager({
|
|||||||
const [editingItem, setEditingItem] = useState<SubmissionItemWithDeps | null>(null);
|
const [editingItem, setEditingItem] = useState<SubmissionItemWithDeps | null>(null);
|
||||||
const [activeTab, setActiveTab] = useState<'items' | 'dependencies'>('items');
|
const [activeTab, setActiveTab] = useState<'items' | 'dependencies'>('items');
|
||||||
const [submissionType, setSubmissionType] = useState<string>('submission');
|
const [submissionType, setSubmissionType] = useState<string>('submission');
|
||||||
|
const [showValidationBlockerDialog, setShowValidationBlockerDialog] = useState(false);
|
||||||
|
const [showWarningConfirmDialog, setShowWarningConfirmDialog] = useState(false);
|
||||||
|
const [validationResults, setValidationResults] = useState<Map<string, ValidationResult>>(new Map());
|
||||||
|
const [userConfirmedWarnings, setUserConfirmedWarnings] = useState(false);
|
||||||
|
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { isAdmin, isSuperuser } = useUserRole();
|
const { isAdmin, isSuperuser } = useUserRole();
|
||||||
@@ -147,10 +154,47 @@ export function SubmissionReviewManager({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectedItems = items.filter(item => selectedItemIds.has(item.id));
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
|
// Run validation on all selected items
|
||||||
|
const validationResultsMap = await validateMultipleItems(
|
||||||
|
selectedItems.map(item => ({
|
||||||
|
item_type: item.item_type,
|
||||||
|
item_data: item.item_data,
|
||||||
|
id: item.id
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
|
||||||
|
setValidationResults(validationResultsMap);
|
||||||
|
|
||||||
|
// Check for blocking errors
|
||||||
|
const itemsWithBlockingErrors = selectedItems.filter(item => {
|
||||||
|
const result = validationResultsMap.get(item.id);
|
||||||
|
return result && result.blockingErrors.length > 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (itemsWithBlockingErrors.length > 0 && !userConfirmedWarnings) {
|
||||||
|
setShowValidationBlockerDialog(true);
|
||||||
|
setLoading(false);
|
||||||
|
return; // Block approval
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for warnings
|
||||||
|
const itemsWithWarnings = selectedItems.filter(item => {
|
||||||
|
const result = validationResultsMap.get(item.id);
|
||||||
|
return result && result.warnings.length > 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (itemsWithWarnings.length > 0 && !userConfirmedWarnings) {
|
||||||
|
setShowWarningConfirmDialog(true);
|
||||||
|
setLoading(false);
|
||||||
|
return; // Ask for confirmation
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proceed with approval
|
||||||
const { supabase } = await import('@/integrations/supabase/client');
|
const { supabase } = await import('@/integrations/supabase/client');
|
||||||
const selectedItems = items.filter(item => selectedItemIds.has(item.id));
|
|
||||||
|
|
||||||
// Call the edge function for backend processing
|
// Call the edge function for backend processing
|
||||||
const { data, error } = await supabase.functions.invoke('process-selective-approval', {
|
const { data, error } = await supabase.functions.invoke('process-selective-approval', {
|
||||||
|
|||||||
67
src/components/moderation/ValidationBlockerDialog.tsx
Normal file
67
src/components/moderation/ValidationBlockerDialog.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { AlertCircle } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/components/ui/alert-dialog';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import { ValidationError } from '@/lib/entityValidationSchemas';
|
||||||
|
|
||||||
|
interface ValidationBlockerDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
blockingErrors: ValidationError[];
|
||||||
|
itemNames: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ValidationBlockerDialog({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
blockingErrors,
|
||||||
|
itemNames,
|
||||||
|
}: ValidationBlockerDialogProps) {
|
||||||
|
return (
|
||||||
|
<AlertDialog open={open} onOpenChange={onClose}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle className="flex items-center gap-2 text-destructive">
|
||||||
|
<AlertCircle className="w-5 h-5" />
|
||||||
|
Cannot Approve: Validation Errors
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
The following items have blocking validation errors that must be fixed before approval:
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-3 my-4">
|
||||||
|
{itemNames.map((name, index) => (
|
||||||
|
<div key={index} className="space-y-2">
|
||||||
|
<div className="font-medium text-sm">{name}</div>
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription className="space-y-1">
|
||||||
|
{blockingErrors
|
||||||
|
.filter((_, i) => i === index || itemNames.length === 1)
|
||||||
|
.map((error, errIndex) => (
|
||||||
|
<div key={errIndex} className="text-sm">
|
||||||
|
• <span className="font-medium">{error.field}:</span> {error.message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogAction onClick={onClose}>
|
||||||
|
Close
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
187
src/components/moderation/ValidationSummary.tsx
Normal file
187
src/components/moderation/ValidationSummary.tsx
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { AlertCircle, CheckCircle, Info, AlertTriangle } from 'lucide-react';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||||
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||||
|
import { validateEntityData, ValidationResult } from '@/lib/entityValidationSchemas';
|
||||||
|
|
||||||
|
interface ValidationSummaryProps {
|
||||||
|
item: {
|
||||||
|
item_type: string;
|
||||||
|
item_data: any;
|
||||||
|
id?: string;
|
||||||
|
};
|
||||||
|
onValidationChange?: (result: ValidationResult) => void;
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ValidationSummary({ item, onValidationChange, compact = false }: ValidationSummaryProps) {
|
||||||
|
const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [isExpanded, setIsExpanded] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function validate() {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await validateEntityData(
|
||||||
|
item.item_type as any,
|
||||||
|
{ ...item.item_data, id: item.id }
|
||||||
|
);
|
||||||
|
setValidationResult(result);
|
||||||
|
onValidationChange?.(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Validation error:', error);
|
||||||
|
setValidationResult({
|
||||||
|
isValid: false,
|
||||||
|
blockingErrors: [{ field: 'validation', message: 'Failed to validate', severity: 'blocking' }],
|
||||||
|
warnings: [],
|
||||||
|
suggestions: [],
|
||||||
|
allErrors: [{ field: 'validation', message: 'Failed to validate', severity: 'blocking' }],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validate();
|
||||||
|
}, [item.item_type, item.item_data, item.id, onValidationChange]);
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<div className="animate-spin rounded-full h-4 w-4 border-2 border-primary border-t-transparent" />
|
||||||
|
<span>Validating...</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validationResult) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasBlockingErrors = validationResult.blockingErrors.length > 0;
|
||||||
|
const hasWarnings = validationResult.warnings.length > 0;
|
||||||
|
const hasSuggestions = validationResult.suggestions.length > 0;
|
||||||
|
const hasAnyIssues = hasBlockingErrors || hasWarnings || hasSuggestions;
|
||||||
|
|
||||||
|
// Compact view (for queue items)
|
||||||
|
if (compact) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{validationResult.isValid && !hasWarnings && !hasSuggestions && (
|
||||||
|
<Badge variant="secondary" className="bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 border-green-300 dark:border-green-700">
|
||||||
|
<CheckCircle className="w-3 h-3 mr-1" />
|
||||||
|
Valid
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasBlockingErrors && (
|
||||||
|
<Badge variant="destructive">
|
||||||
|
<AlertCircle className="w-3 h-3 mr-1" />
|
||||||
|
{validationResult.blockingErrors.length} Error{validationResult.blockingErrors.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasWarnings && !hasBlockingErrors && (
|
||||||
|
<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">
|
||||||
|
<AlertTriangle className="w-3 h-3 mr-1" />
|
||||||
|
{validationResult.warnings.length} Warning{validationResult.warnings.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasSuggestions && !hasBlockingErrors && !hasWarnings && (
|
||||||
|
<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">
|
||||||
|
<Info className="w-3 h-3 mr-1" />
|
||||||
|
{validationResult.suggestions.length} Suggestion{validationResult.suggestions.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detailed view (for review manager)
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* Summary Badge */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{validationResult.isValid && !hasWarnings && !hasSuggestions && (
|
||||||
|
<Badge variant="secondary" className="bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 border-green-300 dark:border-green-700">
|
||||||
|
<CheckCircle className="w-4 h-4 mr-1" />
|
||||||
|
All Valid
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasBlockingErrors && (
|
||||||
|
<Badge variant="destructive" className="text-sm">
|
||||||
|
<AlertCircle className="w-4 h-4 mr-1" />
|
||||||
|
{validationResult.blockingErrors.length} Blocking Error{validationResult.blockingErrors.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasWarnings && (
|
||||||
|
<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 text-sm">
|
||||||
|
<AlertTriangle className="w-4 h-4 mr-1" />
|
||||||
|
{validationResult.warnings.length} Warning{validationResult.warnings.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{hasSuggestions && (
|
||||||
|
<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 text-sm">
|
||||||
|
<Info className="w-4 h-4 mr-1" />
|
||||||
|
{validationResult.suggestions.length} Suggestion{validationResult.suggestions.length !== 1 ? 's' : ''}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Detailed Issues */}
|
||||||
|
{hasAnyIssues && (
|
||||||
|
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
|
||||||
|
<CollapsibleTrigger className="text-sm text-muted-foreground hover:text-foreground transition-colors">
|
||||||
|
{isExpanded ? 'Hide' : 'Show'} validation details
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent className="space-y-2 mt-2">
|
||||||
|
{/* Blocking Errors */}
|
||||||
|
{hasBlockingErrors && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertTitle>Blocking Errors</AlertTitle>
|
||||||
|
<AlertDescription className="space-y-1 mt-2">
|
||||||
|
{validationResult.blockingErrors.map((error, index) => (
|
||||||
|
<div key={index} className="text-sm">
|
||||||
|
<span className="font-medium">{error.field}:</span> {error.message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Warnings */}
|
||||||
|
{hasWarnings && (
|
||||||
|
<Alert className="border-yellow-300 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-900/20">
|
||||||
|
<AlertTriangle className="h-4 w-4 text-yellow-800 dark:text-yellow-300" />
|
||||||
|
<AlertTitle className="text-yellow-800 dark:text-yellow-300">Warnings</AlertTitle>
|
||||||
|
<AlertDescription className="space-y-1 mt-2 text-yellow-800 dark:text-yellow-300">
|
||||||
|
{validationResult.warnings.map((warning, index) => (
|
||||||
|
<div key={index} className="text-sm">
|
||||||
|
<span className="font-medium">{warning.field}:</span> {warning.message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Suggestions */}
|
||||||
|
{hasSuggestions && (
|
||||||
|
<Alert className="border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20">
|
||||||
|
<Info className="h-4 w-4 text-blue-800 dark:text-blue-300" />
|
||||||
|
<AlertTitle className="text-blue-800 dark:text-blue-300">Suggestions</AlertTitle>
|
||||||
|
<AlertDescription className="space-y-1 mt-2 text-blue-800 dark:text-blue-300">
|
||||||
|
{validationResult.suggestions.map((suggestion, index) => (
|
||||||
|
<div key={index} className="text-sm">
|
||||||
|
<span className="font-medium">{suggestion.field}:</span> {suggestion.message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
73
src/components/moderation/WarningConfirmDialog.tsx
Normal file
73
src/components/moderation/WarningConfirmDialog.tsx
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { AlertTriangle } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/components/ui/alert-dialog';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import { ValidationError } from '@/lib/entityValidationSchemas';
|
||||||
|
|
||||||
|
interface WarningConfirmDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onProceed: () => void;
|
||||||
|
warnings: ValidationError[];
|
||||||
|
itemNames: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WarningConfirmDialog({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
onProceed,
|
||||||
|
warnings,
|
||||||
|
itemNames,
|
||||||
|
}: WarningConfirmDialogProps) {
|
||||||
|
return (
|
||||||
|
<AlertDialog open={open} onOpenChange={onClose}>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle className="flex items-center gap-2 text-yellow-800 dark:text-yellow-300">
|
||||||
|
<AlertTriangle className="w-5 h-5" />
|
||||||
|
Validation Warnings
|
||||||
|
</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
The following items have validation warnings. You can proceed with approval, but fixing these issues will improve content quality:
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-3 my-4">
|
||||||
|
{itemNames.map((name, index) => (
|
||||||
|
<div key={index} className="space-y-2">
|
||||||
|
<div className="font-medium text-sm">{name}</div>
|
||||||
|
<Alert className="border-yellow-300 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-900/20">
|
||||||
|
<AlertDescription className="space-y-1 text-yellow-800 dark:text-yellow-300">
|
||||||
|
{warnings
|
||||||
|
.filter((_, i) => i === index || itemNames.length === 1)
|
||||||
|
.map((warning, warnIndex) => (
|
||||||
|
<div key={warnIndex} className="text-sm">
|
||||||
|
• <span className="font-medium">{warning.field}:</span> {warning.message}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel onClick={onClose}>
|
||||||
|
Go Back to Edit
|
||||||
|
</AlertDialogCancel>
|
||||||
|
<AlertDialogAction onClick={onProceed}>
|
||||||
|
Proceed with Approval
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
288
src/lib/entityValidationSchemas.ts
Normal file
288
src/lib/entityValidationSchemas.ts
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// CENTRALIZED VALIDATION SCHEMAS
|
||||||
|
// Single source of truth for all entity validation
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
|
||||||
|
// Park Schema
|
||||||
|
export const parkValidationSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Park name is required').max(200, 'Name must be less than 200 characters'),
|
||||||
|
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||||
|
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||||
|
park_type: z.string().min(1, 'Park type is required'),
|
||||||
|
status: z.string().min(1, 'Status is required'),
|
||||||
|
opening_date: z.string().optional().refine((val) => {
|
||||||
|
if (!val) return true;
|
||||||
|
const date = new Date(val);
|
||||||
|
return date <= new Date();
|
||||||
|
}, 'Opening date cannot be in the future'),
|
||||||
|
closing_date: z.string().optional(),
|
||||||
|
location_id: z.string().uuid().optional(),
|
||||||
|
website_url: z.string().url('Invalid URL format').optional().or(z.literal('')),
|
||||||
|
phone: z.string().max(50, 'Phone must be less than 50 characters').optional(),
|
||||||
|
email: z.string().email('Invalid email format').optional().or(z.literal('')),
|
||||||
|
operator_id: z.string().uuid().optional(),
|
||||||
|
property_owner_id: z.string().uuid().optional(),
|
||||||
|
}).refine((data) => {
|
||||||
|
if (data.closing_date && data.opening_date) {
|
||||||
|
return new Date(data.closing_date) >= new Date(data.opening_date);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}, {
|
||||||
|
message: 'Closing date must be after opening date',
|
||||||
|
path: ['closing_date'],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ride Schema
|
||||||
|
export const rideValidationSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Ride name is required').max(200, 'Name must be less than 200 characters'),
|
||||||
|
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||||
|
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||||
|
category: z.string().min(1, 'Category is required'),
|
||||||
|
ride_sub_type: z.string().max(100, 'Sub type must be less than 100 characters').optional(),
|
||||||
|
status: z.string().min(1, 'Status is required'),
|
||||||
|
opening_date: z.string().optional(),
|
||||||
|
closing_date: z.string().optional(),
|
||||||
|
height_requirement: z.number().min(0, 'Height requirement must be positive').max(300, 'Height requirement must be less than 300cm').optional(),
|
||||||
|
age_requirement: z.number().min(0, 'Age requirement must be positive').max(100, 'Age requirement must be less than 100').optional(),
|
||||||
|
capacity_per_hour: z.number().min(0, 'Capacity must be positive').optional(),
|
||||||
|
duration_seconds: z.number().min(0, 'Duration must be positive').optional(),
|
||||||
|
max_speed_kmh: z.number().min(0, 'Speed must be positive').max(300, 'Speed must be less than 300 km/h').optional(),
|
||||||
|
max_height_meters: z.number().min(0, 'Height must be positive').max(200, 'Height must be less than 200 meters').optional(),
|
||||||
|
length_meters: z.number().min(0, 'Length must be positive').optional(),
|
||||||
|
inversions: z.number().min(0, 'Inversions must be positive').optional(),
|
||||||
|
manufacturer_id: z.string().uuid().optional(),
|
||||||
|
ride_model_id: z.string().uuid().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Company Schema (Manufacturer, Designer, Operator, Property Owner)
|
||||||
|
export const companyValidationSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Company name is required').max(200, 'Name must be less than 200 characters'),
|
||||||
|
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||||
|
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||||
|
company_type: z.string().min(1, 'Company type is required'),
|
||||||
|
person_type: z.enum(['company', 'individual', 'firm', 'organization']).optional(),
|
||||||
|
founded_year: z.number().min(1800, 'Founded year must be after 1800').max(currentYear, `Founded year cannot be in the future`).optional(),
|
||||||
|
headquarters_location: z.string().max(200, 'Location must be less than 200 characters').optional(),
|
||||||
|
website_url: z.string().url('Invalid URL format').optional().or(z.literal('')),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ride Model Schema
|
||||||
|
export const rideModelValidationSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Model name is required').max(200, 'Name must be less than 200 characters'),
|
||||||
|
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||||
|
category: z.string().min(1, 'Category is required'),
|
||||||
|
ride_type: z.string().min(1, 'Ride type is required').max(100, 'Ride type must be less than 100 characters'),
|
||||||
|
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||||
|
manufacturer_id: z.string().uuid('Invalid manufacturer ID').optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Photo Schema
|
||||||
|
export const photoValidationSchema = z.object({
|
||||||
|
cloudflare_image_id: z.string().min(1, 'Image ID is required'),
|
||||||
|
cloudflare_image_url: z.string().url('Invalid image URL'),
|
||||||
|
entity_type: z.string().min(1, 'Entity type is required'),
|
||||||
|
entity_id: z.string().uuid('Invalid entity ID'),
|
||||||
|
caption: z.string().max(500, 'Caption must be less than 500 characters').optional(),
|
||||||
|
photographer_credit: z.string().max(200, 'Credit must be less than 200 characters').optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// SCHEMA REGISTRY
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
export const entitySchemas = {
|
||||||
|
park: parkValidationSchema,
|
||||||
|
ride: rideValidationSchema,
|
||||||
|
manufacturer: companyValidationSchema,
|
||||||
|
designer: companyValidationSchema,
|
||||||
|
operator: companyValidationSchema,
|
||||||
|
property_owner: companyValidationSchema,
|
||||||
|
ride_model: rideModelValidationSchema,
|
||||||
|
photo: photoValidationSchema,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// VALIDATION RESULT TYPES
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
export interface ValidationError {
|
||||||
|
field: string;
|
||||||
|
message: string;
|
||||||
|
severity: 'blocking' | 'warning' | 'suggestion';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ValidationResult {
|
||||||
|
isValid: boolean;
|
||||||
|
blockingErrors: ValidationError[];
|
||||||
|
warnings: ValidationError[];
|
||||||
|
suggestions: ValidationError[];
|
||||||
|
allErrors: ValidationError[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// VALIDATION HELPERS
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate entity data against its schema
|
||||||
|
* Returns detailed validation result with errors categorized by severity
|
||||||
|
*/
|
||||||
|
export async function validateEntityData(
|
||||||
|
entityType: keyof typeof entitySchemas,
|
||||||
|
data: any
|
||||||
|
): Promise<ValidationResult> {
|
||||||
|
const schema = entitySchemas[entityType];
|
||||||
|
|
||||||
|
if (!schema) {
|
||||||
|
return {
|
||||||
|
isValid: false,
|
||||||
|
blockingErrors: [{ field: 'entity_type', message: `Unknown entity type: ${entityType}`, severity: 'blocking' }],
|
||||||
|
warnings: [],
|
||||||
|
suggestions: [],
|
||||||
|
allErrors: [{ field: 'entity_type', message: `Unknown entity type: ${entityType}`, severity: 'blocking' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = schema.safeParse(data);
|
||||||
|
const blockingErrors: ValidationError[] = [];
|
||||||
|
const warnings: ValidationError[] = [];
|
||||||
|
const suggestions: ValidationError[] = [];
|
||||||
|
|
||||||
|
// Process Zod errors
|
||||||
|
if (!result.success) {
|
||||||
|
const zodError = result.error as z.ZodError;
|
||||||
|
zodError.issues.forEach((issue) => {
|
||||||
|
const field = issue.path.join('.');
|
||||||
|
blockingErrors.push({
|
||||||
|
field: field || 'unknown',
|
||||||
|
message: issue.message,
|
||||||
|
severity: 'blocking',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add warnings for optional but recommended fields
|
||||||
|
if (data.description && data.description.length < 50) {
|
||||||
|
warnings.push({
|
||||||
|
field: 'description',
|
||||||
|
message: 'Description is short. Recommended: 50+ characters',
|
||||||
|
severity: 'warning',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entityType === 'park' || entityType === 'ride') {
|
||||||
|
if (!data.description || data.description.trim() === '') {
|
||||||
|
warnings.push({
|
||||||
|
field: 'description',
|
||||||
|
message: 'No description provided. Adding a description improves content quality',
|
||||||
|
severity: 'warning',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check slug uniqueness (async)
|
||||||
|
if (data.slug) {
|
||||||
|
const isSlugUnique = await checkSlugUniqueness(entityType, data.slug, data.id);
|
||||||
|
if (!isSlugUnique) {
|
||||||
|
blockingErrors.push({
|
||||||
|
field: 'slug',
|
||||||
|
message: 'This slug is already in use. Please choose a unique slug',
|
||||||
|
severity: 'blocking',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allErrors = [...blockingErrors, ...warnings, ...suggestions];
|
||||||
|
const isValid = blockingErrors.length === 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
isValid,
|
||||||
|
blockingErrors,
|
||||||
|
warnings,
|
||||||
|
suggestions,
|
||||||
|
allErrors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if slug is unique for the entity type
|
||||||
|
*/
|
||||||
|
async function checkSlugUniqueness(
|
||||||
|
entityType: keyof typeof entitySchemas,
|
||||||
|
slug: string,
|
||||||
|
excludeId?: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
const tableName = getTableNameFromEntityType(entityType);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from(tableName as any)
|
||||||
|
.select('id')
|
||||||
|
.eq('slug', slug)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error checking slug uniqueness:', error);
|
||||||
|
return true; // Assume unique on error to avoid blocking
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if excludeId matches
|
||||||
|
if (excludeId && data && data.length > 0 && data[0]) {
|
||||||
|
return (data[0] as any).id === excludeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return !data || data.length === 0;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error checking slug uniqueness:', error);
|
||||||
|
return true; // Assume unique on error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get database table name from entity type
|
||||||
|
*/
|
||||||
|
function getTableNameFromEntityType(entityType: keyof typeof entitySchemas): string {
|
||||||
|
switch (entityType) {
|
||||||
|
case 'park':
|
||||||
|
return 'parks';
|
||||||
|
case 'ride':
|
||||||
|
return 'rides';
|
||||||
|
case 'manufacturer':
|
||||||
|
case 'designer':
|
||||||
|
case 'operator':
|
||||||
|
case 'property_owner':
|
||||||
|
return 'companies';
|
||||||
|
case 'ride_model':
|
||||||
|
return 'ride_models';
|
||||||
|
case 'photo':
|
||||||
|
return 'photos';
|
||||||
|
default:
|
||||||
|
return entityType + 's';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch validate multiple items
|
||||||
|
*/
|
||||||
|
export async function validateMultipleItems(
|
||||||
|
items: Array<{ item_type: string; item_data: any; id?: string }>
|
||||||
|
): Promise<Map<string, ValidationResult>> {
|
||||||
|
const results = new Map<string, ValidationResult>();
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
items.map(async (item) => {
|
||||||
|
const result = await validateEntityData(
|
||||||
|
item.item_type as keyof typeof entitySchemas,
|
||||||
|
{ ...item.item_data, id: item.id }
|
||||||
|
);
|
||||||
|
results.set(item.id || item.item_data.slug || '', result);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user