mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 18:31:12 -05:00
feat: Implement comprehensive validation system
This commit is contained in:
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