mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 08:11:13 -05:00
445 lines
18 KiB
TypeScript
445 lines
18 KiB
TypeScript
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();
|
|
|
|
// ============================================
|
|
// SHARED IMAGE UPLOAD SCHEMA
|
|
// ============================================
|
|
|
|
const imageAssignmentSchema = z.object({
|
|
uploaded: z.array(z.any()),
|
|
banner_assignment: z.number().int().min(0).nullable().optional(),
|
|
card_assignment: z.number().int().min(0).nullable().optional()
|
|
}).optional().default({ uploaded: [], banner_assignment: null, card_assignment: null });
|
|
|
|
// ============================================
|
|
// PARK SCHEMA
|
|
// ============================================
|
|
|
|
export const parkValidationSchema = z.object({
|
|
name: z.string().trim().min(1, 'Park name is required').max(200, 'Name must be less than 200 characters'),
|
|
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
|
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
|
park_type: z.string().min(1, 'Park type is required'),
|
|
status: z.string().min(1, 'Status is required'),
|
|
opening_date: z.string().optional().or(z.literal('')).refine((val) => {
|
|
if (!val) return true;
|
|
const date = new Date(val);
|
|
return date <= new Date();
|
|
}, 'Opening date cannot be in the future'),
|
|
opening_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
closing_date: z.string().optional().or(z.literal('')),
|
|
closing_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
location_id: z.string().uuid().optional().nullable(),
|
|
website_url: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
|
if (!val || val === '') return true;
|
|
return z.string().url().safeParse(val).success;
|
|
}, 'Invalid URL format'),
|
|
phone: z.string().trim().max(50, 'Phone must be less than 50 characters').optional().or(z.literal('')),
|
|
email: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
|
if (!val || val === '') return true;
|
|
return z.string().email().safeParse(val).success;
|
|
}, 'Invalid email format'),
|
|
operator_id: z.string().uuid().optional().nullable(),
|
|
property_owner_id: z.string().uuid().optional().nullable(),
|
|
banner_image_id: z.string().optional(),
|
|
banner_image_url: z.string().optional(),
|
|
card_image_id: z.string().optional(),
|
|
card_image_url: z.string().optional(),
|
|
images: imageAssignmentSchema,
|
|
}).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().trim().min(1, 'Ride name is required').max(200, 'Name must be less than 200 characters'),
|
|
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
|
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
|
category: z.string().min(1, 'Category is required'),
|
|
ride_sub_type: z.string().trim().max(100, 'Sub type must be less than 100 characters').optional().or(z.literal('')),
|
|
status: z.string().min(1, 'Status is required'),
|
|
park_id: z.string().uuid().optional().nullable(),
|
|
designer_id: z.string().uuid().optional().nullable(),
|
|
opening_date: z.string().optional().or(z.literal('')),
|
|
opening_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
closing_date: z.string().optional().or(z.literal('')),
|
|
closing_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
height_requirement: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(0, 'Height requirement must be positive').max(300, 'Height requirement must be less than 300cm').optional()
|
|
),
|
|
age_requirement: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(0, 'Age requirement must be positive').max(100, 'Age requirement must be less than 100').optional()
|
|
),
|
|
capacity_per_hour: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(1, 'Capacity must be positive').max(99999, 'Capacity must be less than 100,000').optional()
|
|
),
|
|
duration_seconds: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(1, 'Duration must be positive').max(86400, 'Duration must be less than 24 hours').optional()
|
|
),
|
|
max_speed_kmh: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().min(0, 'Speed must be positive').max(500, 'Speed must be less than 500 km/h').optional()
|
|
),
|
|
max_height_meters: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().min(0, 'Height must be positive').max(200, 'Height must be less than 200 meters').optional()
|
|
),
|
|
length_meters: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().min(0, 'Length must be positive').max(10000, 'Length must be less than 10km').optional()
|
|
),
|
|
inversions: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(0, 'Inversions must be positive').max(20, 'Inversions must be less than 20').optional()
|
|
),
|
|
drop_height_meters: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().min(0, 'Drop height must be positive').max(200, 'Drop height must be less than 200 meters').optional()
|
|
),
|
|
max_g_force: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().min(-10, 'G-force must be greater than -10').max(10, 'G-force must be less than 10').optional()
|
|
),
|
|
manufacturer_id: z.string().uuid().optional().nullable(),
|
|
ride_model_id: z.string().uuid().optional().nullable(),
|
|
coaster_type: z.string().optional(),
|
|
seating_type: z.string().optional(),
|
|
intensity_level: z.string().optional(),
|
|
track_material: z.enum(['wood', 'steel', 'hybrid', 'aluminum', 'other']).optional(),
|
|
banner_image_id: z.string().optional(),
|
|
banner_image_url: z.string().optional(),
|
|
card_image_id: z.string().optional(),
|
|
card_image_url: z.string().optional(),
|
|
images: imageAssignmentSchema,
|
|
});
|
|
|
|
// ============================================
|
|
// COMPANY SCHEMA (Manufacturer, Designer, Operator, Property Owner)
|
|
// ============================================
|
|
|
|
export const companyValidationSchema = z.object({
|
|
name: z.string().trim().min(1, 'Company name is required').max(200, 'Name must be less than 200 characters'),
|
|
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
|
company_type: z.enum(['manufacturer', 'designer', 'operator', 'property_owner']),
|
|
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
|
person_type: z.enum(['company', 'individual', 'firm', 'organization']),
|
|
founded_date: z.string().optional().or(z.literal('')),
|
|
founded_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
founded_year: z.preprocess(
|
|
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
|
z.number().int().min(1800, 'Founded year must be after 1800').max(currentYear, `Founded year cannot be after ${currentYear}`).optional()
|
|
),
|
|
headquarters_location: z.string().trim().max(200, 'Location must be less than 200 characters').optional().or(z.literal('')),
|
|
website_url: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
|
if (!val || val === '') return true;
|
|
return z.string().url().safeParse(val).success;
|
|
}, 'Invalid URL format'),
|
|
banner_image_id: z.string().optional(),
|
|
banner_image_url: z.string().optional(),
|
|
card_image_id: z.string().optional(),
|
|
card_image_url: z.string().optional(),
|
|
images: imageAssignmentSchema,
|
|
});
|
|
|
|
// ============================================
|
|
// RIDE MODEL SCHEMA
|
|
// ============================================
|
|
|
|
export const rideModelValidationSchema = z.object({
|
|
name: z.string().trim().min(1, 'Model name is required').max(200, 'Name must be less than 200 characters'),
|
|
slug: z.string().trim().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().trim().min(1, 'Ride type is required').max(100, 'Ride type must be less than 100 characters'),
|
|
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
|
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().trim().max(500, 'Caption must be less than 500 characters').optional().or(z.literal('')),
|
|
photographer_credit: z.string().trim().max(200, 'Credit must be less than 200 characters').optional().or(z.literal('')),
|
|
});
|
|
|
|
// ============================================
|
|
// MILESTONE/TIMELINE EVENT SCHEMA
|
|
// ============================================
|
|
|
|
export const milestoneValidationSchema = z.object({
|
|
title: z.string().trim().min(1, 'Event title is required').max(200, 'Title must be less than 200 characters'),
|
|
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
|
event_type: z.string().min(1, 'Event type is required'),
|
|
event_date: z.string().min(1, 'Event date is required'),
|
|
event_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
|
entity_type: z.string().min(1, 'Entity type is required'),
|
|
entity_id: z.string().uuid('Invalid entity ID'),
|
|
is_public: z.boolean().optional(),
|
|
display_order: z.number().optional(),
|
|
from_value: z.string().optional(),
|
|
to_value: z.string().optional(),
|
|
from_entity_id: z.string().uuid().optional().nullable(),
|
|
to_entity_id: z.string().uuid().optional().nullable(),
|
|
from_location_id: z.string().uuid().optional().nullable(),
|
|
to_location_id: z.string().uuid().optional().nullable(),
|
|
});
|
|
|
|
// ============================================
|
|
// SCHEMA REGISTRY
|
|
// ============================================
|
|
|
|
export const entitySchemas = {
|
|
park: parkValidationSchema,
|
|
ride: rideValidationSchema,
|
|
manufacturer: companyValidationSchema,
|
|
designer: companyValidationSchema,
|
|
operator: companyValidationSchema,
|
|
property_owner: companyValidationSchema,
|
|
ride_model: rideModelValidationSchema,
|
|
photo: photoValidationSchema,
|
|
milestone: milestoneValidationSchema,
|
|
};
|
|
|
|
// ============================================
|
|
// 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: unknown
|
|
): 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
|
|
const validData = data as Record<string, unknown>;
|
|
if (validData.description && typeof validData.description === 'string' && validData.description.length < 50) {
|
|
warnings.push({
|
|
field: 'description',
|
|
message: 'Description is short. Recommended: 50+ characters',
|
|
severity: 'warning',
|
|
});
|
|
}
|
|
|
|
if (entityType === 'park' || entityType === 'ride') {
|
|
if (!validData.description || (typeof validData.description === 'string' && validData.description.trim() === '')) {
|
|
warnings.push({
|
|
field: 'description',
|
|
message: 'No description provided. Adding a description improves content quality',
|
|
severity: 'warning',
|
|
});
|
|
}
|
|
}
|
|
|
|
// Check slug uniqueness (async)
|
|
if (validData.slug && typeof validData.slug === 'string') {
|
|
const isSlugUnique = await checkSlugUniqueness(
|
|
entityType,
|
|
validData.slug,
|
|
typeof validData.id === 'string' ? validData.id : undefined
|
|
);
|
|
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 {
|
|
console.log(`Checking slug uniqueness for "${slug}" in ${tableName}, excludeId: ${excludeId}`);
|
|
|
|
// Query with explicit table name - use simple approach to avoid type instantiation issues
|
|
let result;
|
|
|
|
switch (tableName) {
|
|
case 'parks':
|
|
result = await supabase.from('parks').select('id').eq('slug', slug).limit(1);
|
|
break;
|
|
case 'rides':
|
|
result = await supabase.from('rides').select('id').eq('slug', slug).limit(1);
|
|
break;
|
|
case 'companies':
|
|
result = await supabase.from('companies').select('id').eq('slug', slug).limit(1);
|
|
break;
|
|
case 'ride_models':
|
|
result = await supabase.from('ride_models').select('id').eq('slug', slug).limit(1);
|
|
break;
|
|
default:
|
|
console.error(`Invalid table name: ${tableName}`);
|
|
return true; // Assume unique on invalid table
|
|
}
|
|
|
|
const { data, error } = result;
|
|
|
|
if (error) {
|
|
console.error(`Slug uniqueness check failed for ${entityType}:`, error);
|
|
return true; // Assume unique on error to avoid blocking
|
|
}
|
|
|
|
// If no data, slug is unique
|
|
if (!data || data.length === 0) {
|
|
console.log(`Slug "${slug}" is unique in ${tableName}`);
|
|
return true;
|
|
}
|
|
|
|
// If excludeId provided and matches, it's the same entity (editing)
|
|
if (excludeId && data[0] && data[0].id === excludeId) {
|
|
console.log(`Slug "${slug}" matches current entity (editing mode)`);
|
|
return true;
|
|
}
|
|
|
|
// Slug is in use by a different entity
|
|
console.log(`Slug "${slug}" already exists in ${tableName}`);
|
|
return false;
|
|
} catch (error) {
|
|
console.error(`Exception during slug uniqueness check:`, error);
|
|
return true; // Assume unique on error to avoid false positives
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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: unknown; 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 as object), id: item.id }
|
|
);
|
|
const validData = item.item_data as Record<string, unknown>;
|
|
results.set(
|
|
item.id || (typeof validData.slug === 'string' ? validData.slug : ''),
|
|
result
|
|
);
|
|
})
|
|
);
|
|
|
|
return results;
|
|
}
|