mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-23 00:51:12 -05:00
Add photo upload functionality
This commit is contained in:
338
src/components/admin/ParkForm.tsx
Normal file
338
src/components/admin/ParkForm.tsx
Normal file
@@ -0,0 +1,338 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import * as z from 'zod';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { PhotoUpload } from '@/components/upload/PhotoUpload';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { toast } from '@/hooks/use-toast';
|
||||||
|
import { MapPin, Save, X } from 'lucide-react';
|
||||||
|
|
||||||
|
const parkSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Park name is required'),
|
||||||
|
slug: z.string().min(1, 'Slug is required'),
|
||||||
|
description: z.string().optional(),
|
||||||
|
park_type: z.string().min(1, 'Park type is required'),
|
||||||
|
status: z.string().min(1, 'Status is required'),
|
||||||
|
opening_date: z.string().optional(),
|
||||||
|
closing_date: z.string().optional(),
|
||||||
|
website_url: z.string().url().optional().or(z.literal('')),
|
||||||
|
phone: z.string().optional(),
|
||||||
|
email: z.string().email().optional().or(z.literal(''))
|
||||||
|
});
|
||||||
|
|
||||||
|
type ParkFormData = z.infer<typeof parkSchema>;
|
||||||
|
|
||||||
|
interface ParkFormProps {
|
||||||
|
onSubmit: (data: ParkFormData & { banner_image_url?: string; card_image_url?: string }) => Promise<void>;
|
||||||
|
onCancel?: () => void;
|
||||||
|
initialData?: Partial<ParkFormData & { banner_image_url?: string; card_image_url?: string }>;
|
||||||
|
isEditing?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parkTypes = [
|
||||||
|
'Theme Park',
|
||||||
|
'Amusement Park',
|
||||||
|
'Water Park',
|
||||||
|
'Family Entertainment Center',
|
||||||
|
'Adventure Park',
|
||||||
|
'Safari Park',
|
||||||
|
'Carnival',
|
||||||
|
'Fair'
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusOptions = [
|
||||||
|
'Operating',
|
||||||
|
'Seasonal',
|
||||||
|
'Closed Temporarily',
|
||||||
|
'Closed Permanently',
|
||||||
|
'Under Construction',
|
||||||
|
'Planned'
|
||||||
|
];
|
||||||
|
|
||||||
|
export function ParkForm({ onSubmit, onCancel, initialData, isEditing = false }: ParkFormProps) {
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [bannerImage, setBannerImage] = useState<string>(initialData?.banner_image_url || '');
|
||||||
|
const [cardImage, setCardImage] = useState<string>(initialData?.card_image_url || '');
|
||||||
|
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
setValue,
|
||||||
|
watch,
|
||||||
|
formState: { errors }
|
||||||
|
} = useForm<ParkFormData>({
|
||||||
|
resolver: zodResolver(parkSchema),
|
||||||
|
defaultValues: {
|
||||||
|
name: initialData?.name || '',
|
||||||
|
slug: initialData?.slug || '',
|
||||||
|
description: initialData?.description || '',
|
||||||
|
park_type: initialData?.park_type || '',
|
||||||
|
status: initialData?.status || 'Operating',
|
||||||
|
opening_date: initialData?.opening_date || '',
|
||||||
|
closing_date: initialData?.closing_date || '',
|
||||||
|
website_url: initialData?.website_url || '',
|
||||||
|
phone: initialData?.phone || '',
|
||||||
|
email: initialData?.email || ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateSlug = (name: string) => {
|
||||||
|
return name
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9\s-]/g, '')
|
||||||
|
.replace(/\s+/g, '-')
|
||||||
|
.replace(/-+/g, '-')
|
||||||
|
.trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const name = e.target.value;
|
||||||
|
const slug = generateSlug(name);
|
||||||
|
setValue('slug', slug);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (data: ParkFormData) => {
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await onSubmit({
|
||||||
|
...data,
|
||||||
|
banner_image_url: bannerImage || undefined,
|
||||||
|
card_image_url: cardImage || undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: isEditing ? "Park Updated" : "Park Created",
|
||||||
|
description: isEditing
|
||||||
|
? "The park information has been updated successfully."
|
||||||
|
: "The new park has been created successfully."
|
||||||
|
});
|
||||||
|
} catch (error: any) {
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: error.message || "Failed to save park information.",
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="w-full max-w-4xl mx-auto">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<MapPin className="w-5 h-5" />
|
||||||
|
{isEditing ? 'Edit Park' : 'Create New Park'}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
|
||||||
|
{/* Basic Information */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Park Name *</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
{...register('name')}
|
||||||
|
onChange={(e) => {
|
||||||
|
register('name').onChange(e);
|
||||||
|
handleNameChange(e);
|
||||||
|
}}
|
||||||
|
placeholder="Enter park name"
|
||||||
|
/>
|
||||||
|
{errors.name && (
|
||||||
|
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="slug">URL Slug *</Label>
|
||||||
|
<Input
|
||||||
|
id="slug"
|
||||||
|
{...register('slug')}
|
||||||
|
placeholder="park-url-slug"
|
||||||
|
/>
|
||||||
|
{errors.slug && (
|
||||||
|
<p className="text-sm text-destructive">{errors.slug.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="description">Description</Label>
|
||||||
|
<Textarea
|
||||||
|
id="description"
|
||||||
|
{...register('description')}
|
||||||
|
placeholder="Describe the park..."
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Park Type and Status */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Park Type *</Label>
|
||||||
|
<Select onValueChange={(value) => setValue('park_type', value)} defaultValue={initialData?.park_type}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select park type" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{parkTypes.map((type) => (
|
||||||
|
<SelectItem key={type} value={type}>
|
||||||
|
{type}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{errors.park_type && (
|
||||||
|
<p className="text-sm text-destructive">{errors.park_type.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Status *</Label>
|
||||||
|
<Select onValueChange={(value) => setValue('status', value)} defaultValue={initialData?.status || 'Operating'}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select status" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{statusOptions.map((status) => (
|
||||||
|
<SelectItem key={status} value={status}>
|
||||||
|
{status}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{errors.status && (
|
||||||
|
<p className="text-sm text-destructive">{errors.status.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Dates */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="opening_date">Opening Date</Label>
|
||||||
|
<Input
|
||||||
|
id="opening_date"
|
||||||
|
type="date"
|
||||||
|
{...register('opening_date')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="closing_date">Closing Date (if applicable)</Label>
|
||||||
|
<Input
|
||||||
|
id="closing_date"
|
||||||
|
type="date"
|
||||||
|
{...register('closing_date')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Contact Information */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="website_url">Website URL</Label>
|
||||||
|
<Input
|
||||||
|
id="website_url"
|
||||||
|
type="url"
|
||||||
|
{...register('website_url')}
|
||||||
|
placeholder="https://..."
|
||||||
|
/>
|
||||||
|
{errors.website_url && (
|
||||||
|
<p className="text-sm text-destructive">{errors.website_url.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="phone">Phone Number</Label>
|
||||||
|
<Input
|
||||||
|
id="phone"
|
||||||
|
{...register('phone')}
|
||||||
|
placeholder="+1 (555) 123-4567"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
{...register('email')}
|
||||||
|
placeholder="contact@park.com"
|
||||||
|
/>
|
||||||
|
{errors.email && (
|
||||||
|
<p className="text-sm text-destructive">{errors.email.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Images */}
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Banner Image</Label>
|
||||||
|
<PhotoUpload
|
||||||
|
maxFiles={1}
|
||||||
|
variant="default"
|
||||||
|
existingPhotos={bannerImage ? [bannerImage] : []}
|
||||||
|
onUploadComplete={(urls) => setBannerImage(urls[0] || '')}
|
||||||
|
onError={(error) => {
|
||||||
|
toast({
|
||||||
|
title: "Upload Error",
|
||||||
|
description: error,
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
High-resolution banner image for the park detail page (recommended: 1200x400px)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Card Image</Label>
|
||||||
|
<PhotoUpload
|
||||||
|
maxFiles={1}
|
||||||
|
variant="default"
|
||||||
|
existingPhotos={cardImage ? [cardImage] : []}
|
||||||
|
onUploadComplete={(urls) => setCardImage(urls[0] || '')}
|
||||||
|
onError={(error) => {
|
||||||
|
toast({
|
||||||
|
title: "Upload Error",
|
||||||
|
description: error,
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Square or rectangular image for park cards and listings (recommended: 400x300px)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form Actions */}
|
||||||
|
<div className="flex gap-4 pt-6">
|
||||||
|
<Button type="submit" disabled={submitting} className="flex-1">
|
||||||
|
<Save className="w-4 h-4 mr-2" />
|
||||||
|
{submitting ? 'Saving...' : (isEditing ? 'Update Park' : 'Create Park')}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{onCancel && (
|
||||||
|
<Button type="button" variant="outline" onClick={onCancel}>
|
||||||
|
<X className="w-4 h-4 mr-2" />
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
397
src/components/admin/RideForm.tsx
Normal file
397
src/components/admin/RideForm.tsx
Normal file
@@ -0,0 +1,397 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import * as z from 'zod';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { PhotoUpload } from '@/components/upload/PhotoUpload';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { toast } from '@/hooks/use-toast';
|
||||||
|
import { Zap, Save, X } from 'lucide-react';
|
||||||
|
|
||||||
|
const rideSchema = z.object({
|
||||||
|
name: z.string().min(1, 'Ride name is required'),
|
||||||
|
slug: z.string().min(1, 'Slug is required'),
|
||||||
|
description: z.string().optional(),
|
||||||
|
category: z.string().min(1, 'Category is required'),
|
||||||
|
ride_sub_type: z.string().optional(),
|
||||||
|
status: z.string().min(1, 'Status is required'),
|
||||||
|
opening_date: z.string().optional(),
|
||||||
|
closing_date: z.string().optional(),
|
||||||
|
height_requirement: z.number().optional(),
|
||||||
|
age_requirement: z.number().optional(),
|
||||||
|
capacity_per_hour: z.number().optional(),
|
||||||
|
duration_seconds: z.number().optional(),
|
||||||
|
max_speed_kmh: z.number().optional(),
|
||||||
|
max_height_meters: z.number().optional(),
|
||||||
|
length_meters: z.number().optional(),
|
||||||
|
inversions: z.number().optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
type RideFormData = z.infer<typeof rideSchema>;
|
||||||
|
|
||||||
|
interface RideFormProps {
|
||||||
|
onSubmit: (data: RideFormData & { image_url?: string }) => Promise<void>;
|
||||||
|
onCancel?: () => void;
|
||||||
|
initialData?: Partial<RideFormData & { image_url?: string }>;
|
||||||
|
isEditing?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const categories = [
|
||||||
|
'roller_coaster',
|
||||||
|
'flat_ride',
|
||||||
|
'water_ride',
|
||||||
|
'dark_ride',
|
||||||
|
'kiddie_ride',
|
||||||
|
'transportation'
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusOptions = [
|
||||||
|
'Operating',
|
||||||
|
'Seasonal',
|
||||||
|
'Closed Temporarily',
|
||||||
|
'Closed Permanently',
|
||||||
|
'Under Construction',
|
||||||
|
'Planned',
|
||||||
|
'SBNO' // Standing But Not Operating
|
||||||
|
];
|
||||||
|
|
||||||
|
export function RideForm({ onSubmit, onCancel, initialData, isEditing = false }: RideFormProps) {
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [rideImage, setRideImage] = useState<string>(initialData?.image_url || '');
|
||||||
|
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
setValue,
|
||||||
|
watch,
|
||||||
|
formState: { errors }
|
||||||
|
} = useForm<RideFormData>({
|
||||||
|
resolver: zodResolver(rideSchema),
|
||||||
|
defaultValues: {
|
||||||
|
name: initialData?.name || '',
|
||||||
|
slug: initialData?.slug || '',
|
||||||
|
description: initialData?.description || '',
|
||||||
|
category: initialData?.category || '',
|
||||||
|
ride_sub_type: initialData?.ride_sub_type || '',
|
||||||
|
status: initialData?.status || 'Operating',
|
||||||
|
opening_date: initialData?.opening_date || '',
|
||||||
|
closing_date: initialData?.closing_date || '',
|
||||||
|
height_requirement: initialData?.height_requirement || undefined,
|
||||||
|
age_requirement: initialData?.age_requirement || undefined,
|
||||||
|
capacity_per_hour: initialData?.capacity_per_hour || undefined,
|
||||||
|
duration_seconds: initialData?.duration_seconds || undefined,
|
||||||
|
max_speed_kmh: initialData?.max_speed_kmh || undefined,
|
||||||
|
max_height_meters: initialData?.max_height_meters || undefined,
|
||||||
|
length_meters: initialData?.length_meters || undefined,
|
||||||
|
inversions: initialData?.inversions || undefined
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateSlug = (name: string) => {
|
||||||
|
return name
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9\s-]/g, '')
|
||||||
|
.replace(/\s+/g, '-')
|
||||||
|
.replace(/-+/g, '-')
|
||||||
|
.trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const name = e.target.value;
|
||||||
|
const slug = generateSlug(name);
|
||||||
|
setValue('slug', slug);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (data: RideFormData) => {
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await onSubmit({
|
||||||
|
...data,
|
||||||
|
image_url: rideImage || undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: isEditing ? "Ride Updated" : "Ride Created",
|
||||||
|
description: isEditing
|
||||||
|
? "The ride information has been updated successfully."
|
||||||
|
: "The new ride has been created successfully."
|
||||||
|
});
|
||||||
|
} catch (error: any) {
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: error.message || "Failed to save ride information.",
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="w-full max-w-4xl mx-auto">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Zap className="w-5 h-5" />
|
||||||
|
{isEditing ? 'Edit Ride' : 'Create New Ride'}
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
|
||||||
|
{/* Basic Information */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Ride Name *</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
{...register('name')}
|
||||||
|
onChange={(e) => {
|
||||||
|
register('name').onChange(e);
|
||||||
|
handleNameChange(e);
|
||||||
|
}}
|
||||||
|
placeholder="Enter ride name"
|
||||||
|
/>
|
||||||
|
{errors.name && (
|
||||||
|
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="slug">URL Slug *</Label>
|
||||||
|
<Input
|
||||||
|
id="slug"
|
||||||
|
{...register('slug')}
|
||||||
|
placeholder="ride-url-slug"
|
||||||
|
/>
|
||||||
|
{errors.slug && (
|
||||||
|
<p className="text-sm text-destructive">{errors.slug.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="description">Description</Label>
|
||||||
|
<Textarea
|
||||||
|
id="description"
|
||||||
|
{...register('description')}
|
||||||
|
placeholder="Describe the ride experience..."
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Category and Status */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Category *</Label>
|
||||||
|
<Select onValueChange={(value) => setValue('category', value)} defaultValue={initialData?.category}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select category" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{categories.map((category) => (
|
||||||
|
<SelectItem key={category} value={category}>
|
||||||
|
{category.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{errors.category && (
|
||||||
|
<p className="text-sm text-destructive">{errors.category.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="ride_sub_type">Sub Type</Label>
|
||||||
|
<Input
|
||||||
|
id="ride_sub_type"
|
||||||
|
{...register('ride_sub_type')}
|
||||||
|
placeholder="e.g. Inverted Coaster, Log Flume"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Status *</Label>
|
||||||
|
<Select onValueChange={(value) => setValue('status', value)} defaultValue={initialData?.status || 'Operating'}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select status" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{statusOptions.map((status) => (
|
||||||
|
<SelectItem key={status} value={status}>
|
||||||
|
{status}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{errors.status && (
|
||||||
|
<p className="text-sm text-destructive">{errors.status.message}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Dates */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="opening_date">Opening Date</Label>
|
||||||
|
<Input
|
||||||
|
id="opening_date"
|
||||||
|
type="date"
|
||||||
|
{...register('opening_date')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="closing_date">Closing Date (if applicable)</Label>
|
||||||
|
<Input
|
||||||
|
id="closing_date"
|
||||||
|
type="date"
|
||||||
|
{...register('closing_date')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Requirements */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="height_requirement">Height Requirement (cm)</Label>
|
||||||
|
<Input
|
||||||
|
id="height_requirement"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
{...register('height_requirement', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 120"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="age_requirement">Minimum Age</Label>
|
||||||
|
<Input
|
||||||
|
id="age_requirement"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
{...register('age_requirement', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 8"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Technical Specifications */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">Technical Specifications</h3>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="capacity_per_hour">Capacity per Hour</Label>
|
||||||
|
<Input
|
||||||
|
id="capacity_per_hour"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
{...register('capacity_per_hour', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 1200"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="duration_seconds">Duration (seconds)</Label>
|
||||||
|
<Input
|
||||||
|
id="duration_seconds"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
{...register('duration_seconds', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 180"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="max_speed_kmh">Max Speed (km/h)</Label>
|
||||||
|
<Input
|
||||||
|
id="max_speed_kmh"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.1"
|
||||||
|
{...register('max_speed_kmh', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 80.5"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="max_height_meters">Max Height (meters)</Label>
|
||||||
|
<Input
|
||||||
|
id="max_height_meters"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.1"
|
||||||
|
{...register('max_height_meters', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 65.2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="length_meters">Length (meters)</Label>
|
||||||
|
<Input
|
||||||
|
id="length_meters"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.1"
|
||||||
|
{...register('length_meters', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 1200.5"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="inversions">Inversions</Label>
|
||||||
|
<Input
|
||||||
|
id="inversions"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
{...register('inversions', { valueAsNumber: true })}
|
||||||
|
placeholder="e.g. 7"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Image */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Ride Image</Label>
|
||||||
|
<PhotoUpload
|
||||||
|
maxFiles={1}
|
||||||
|
variant="default"
|
||||||
|
existingPhotos={rideImage ? [rideImage] : []}
|
||||||
|
onUploadComplete={(urls) => setRideImage(urls[0] || '')}
|
||||||
|
onError={(error) => {
|
||||||
|
toast({
|
||||||
|
title: "Upload Error",
|
||||||
|
description: error,
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
High-quality image of the ride (recommended: 800x600px)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form Actions */}
|
||||||
|
<div className="flex gap-4 pt-6">
|
||||||
|
<Button type="submit" disabled={submitting} className="flex-1">
|
||||||
|
<Save className="w-4 h-4 mr-2" />
|
||||||
|
{submitting ? 'Saving...' : (isEditing ? 'Update Ride' : 'Create Ride')}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
{onCancel && (
|
||||||
|
<Button type="button" variant="outline" onClick={onCancel}>
|
||||||
|
<X className="w-4 h-4 mr-2" />
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,13 +11,15 @@ import { Star, Send } from 'lucide-react';
|
|||||||
import { useAuth } from '@/hooks/useAuth';
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
import { toast } from '@/hooks/use-toast';
|
import { toast } from '@/hooks/use-toast';
|
||||||
|
import { PhotoUpload } from '@/components/upload/PhotoUpload';
|
||||||
|
|
||||||
const reviewSchema = z.object({
|
const reviewSchema = z.object({
|
||||||
rating: z.number().min(1).max(5),
|
rating: z.number().min(1).max(5),
|
||||||
title: z.string().optional(),
|
title: z.string().optional(),
|
||||||
content: z.string().min(10, 'Review must be at least 10 characters long'),
|
content: z.string().min(10, 'Review must be at least 10 characters long'),
|
||||||
visit_date: z.string().optional(),
|
visit_date: z.string().optional(),
|
||||||
wait_time_minutes: z.number().optional()
|
wait_time_minutes: z.number().optional(),
|
||||||
|
photos: z.array(z.string()).optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
type ReviewFormData = z.infer<typeof reviewSchema>;
|
type ReviewFormData = z.infer<typeof reviewSchema>;
|
||||||
@@ -33,6 +35,7 @@ export function ReviewForm({ entityType, entityId, entityName, onReviewSubmitted
|
|||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [rating, setRating] = useState(0);
|
const [rating, setRating] = useState(0);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [photos, setPhotos] = useState<string[]>([]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -68,6 +71,7 @@ export function ReviewForm({ entityType, entityId, entityName, onReviewSubmitted
|
|||||||
content: data.content,
|
content: data.content,
|
||||||
visit_date: data.visit_date || null,
|
visit_date: data.visit_date || null,
|
||||||
wait_time_minutes: data.wait_time_minutes || null,
|
wait_time_minutes: data.wait_time_minutes || null,
|
||||||
|
photos: photos.length > 0 ? photos : null,
|
||||||
moderation_status: 'pending' as const,
|
moderation_status: 'pending' as const,
|
||||||
...(entityType === 'park' ? { park_id: entityId } : { ride_id: entityId })
|
...(entityType === 'park' ? { park_id: entityId } : { ride_id: entityId })
|
||||||
};
|
};
|
||||||
@@ -85,6 +89,7 @@ export function ReviewForm({ entityType, entityId, entityName, onReviewSubmitted
|
|||||||
|
|
||||||
reset();
|
reset();
|
||||||
setRating(0);
|
setRating(0);
|
||||||
|
setPhotos([]);
|
||||||
onReviewSubmitted();
|
onReviewSubmitted();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error submitting review:', error);
|
console.error('Error submitting review:', error);
|
||||||
@@ -201,6 +206,27 @@ export function ReviewForm({ entityType, entityId, entityName, onReviewSubmitted
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Photo Upload */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Photos (Optional)</Label>
|
||||||
|
<PhotoUpload
|
||||||
|
maxFiles={5}
|
||||||
|
onUploadComplete={setPhotos}
|
||||||
|
onError={(error) => {
|
||||||
|
toast({
|
||||||
|
title: "Upload Error",
|
||||||
|
description: error,
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
variant="compact"
|
||||||
|
className="max-w-full"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Add up to 5 photos to share your experience
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button type="submit" disabled={submitting} className="w-full">
|
<Button type="submit" disabled={submitting} className="w-full">
|
||||||
<Send className="w-4 h-4 mr-2" />
|
<Send className="w-4 h-4 mr-2" />
|
||||||
{submitting ? 'Submitting...' : 'Submit Review'}
|
{submitting ? 'Submitting...' : 'Submit Review'}
|
||||||
|
|||||||
384
src/components/upload/PhotoUpload.tsx
Normal file
384
src/components/upload/PhotoUpload.tsx
Normal file
@@ -0,0 +1,384 @@
|
|||||||
|
import { useState, useRef, useCallback } from 'react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Progress } from '@/components/ui/progress';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import {
|
||||||
|
Upload,
|
||||||
|
X,
|
||||||
|
Image as ImageIcon,
|
||||||
|
AlertCircle,
|
||||||
|
Camera,
|
||||||
|
FileImage
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
|
||||||
|
interface PhotoUploadProps {
|
||||||
|
onUploadComplete?: (urls: string[]) => void;
|
||||||
|
onUploadStart?: () => void;
|
||||||
|
onError?: (error: string) => void;
|
||||||
|
maxFiles?: number;
|
||||||
|
existingPhotos?: string[];
|
||||||
|
className?: string;
|
||||||
|
variant?: 'default' | 'compact' | 'avatar';
|
||||||
|
accept?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UploadedImage {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
filename: string;
|
||||||
|
thumbnailUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PhotoUpload({
|
||||||
|
onUploadComplete,
|
||||||
|
onUploadStart,
|
||||||
|
onError,
|
||||||
|
maxFiles = 5,
|
||||||
|
existingPhotos = [],
|
||||||
|
className,
|
||||||
|
variant = 'default',
|
||||||
|
accept = 'image/jpeg,image/png,image/webp'
|
||||||
|
}: PhotoUploadProps) {
|
||||||
|
const [uploadedImages, setUploadedImages] = useState<UploadedImage[]>([]);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [uploadProgress, setUploadProgress] = useState(0);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const isAvatar = variant === 'avatar';
|
||||||
|
const isCompact = variant === 'compact';
|
||||||
|
const totalImages = uploadedImages.length + existingPhotos.length;
|
||||||
|
const canUploadMore = totalImages < maxFiles;
|
||||||
|
|
||||||
|
const validateFile = (file: File): string | null => {
|
||||||
|
// Check file size (10MB limit)
|
||||||
|
const maxSize = 10 * 1024 * 1024;
|
||||||
|
if (file.size > maxSize) {
|
||||||
|
return 'File size must be less than 10MB';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check file type
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
return 'Only JPEG, PNG, and WebP images are allowed';
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadFile = async (file: File): Promise<UploadedImage> => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
formData.append('metadata', JSON.stringify({
|
||||||
|
filename: file.name,
|
||||||
|
size: file.size,
|
||||||
|
type: file.type,
|
||||||
|
uploadedAt: new Date().toISOString()
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { data, error } = await supabase.functions.invoke('upload-image', {
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(error.message || 'Upload failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!data.success) {
|
||||||
|
throw new Error(data.error || 'Upload failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: data.id,
|
||||||
|
url: data.urls.original,
|
||||||
|
filename: data.filename,
|
||||||
|
thumbnailUrl: data.urls.thumbnail
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFiles = async (files: FileList) => {
|
||||||
|
if (!canUploadMore) {
|
||||||
|
setError(`Maximum ${maxFiles} ${maxFiles === 1 ? 'image' : 'images'} allowed`);
|
||||||
|
onError?.(`Maximum ${maxFiles} ${maxFiles === 1 ? 'image' : 'images'} allowed`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const filesToUpload = Array.from(files).slice(0, maxFiles - totalImages);
|
||||||
|
|
||||||
|
// Validate all files first
|
||||||
|
for (const file of filesToUpload) {
|
||||||
|
const validationError = validateFile(file);
|
||||||
|
if (validationError) {
|
||||||
|
setError(validationError);
|
||||||
|
onError?.(validationError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploading(true);
|
||||||
|
setError(null);
|
||||||
|
onUploadStart?.();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const uploadPromises = filesToUpload.map(async (file, index) => {
|
||||||
|
setUploadProgress((index / filesToUpload.length) * 100);
|
||||||
|
return uploadFile(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = await Promise.all(uploadPromises);
|
||||||
|
setUploadedImages(prev => [...prev, ...results]);
|
||||||
|
|
||||||
|
// Call completion callback with all image URLs
|
||||||
|
const allUrls = [...existingPhotos, ...uploadedImages.map(img => img.url), ...results.map(img => img.url)];
|
||||||
|
onUploadComplete?.(allUrls);
|
||||||
|
|
||||||
|
setUploadProgress(100);
|
||||||
|
} catch (error: any) {
|
||||||
|
const errorMessage = error.message || 'Upload failed';
|
||||||
|
setError(errorMessage);
|
||||||
|
onError?.(errorMessage);
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
setUploadProgress(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeImage = (imageId: string) => {
|
||||||
|
setUploadedImages(prev => prev.filter(img => img.id !== imageId));
|
||||||
|
const updatedUrls = [...existingPhotos, ...uploadedImages.filter(img => img.id !== imageId).map(img => img.url)];
|
||||||
|
onUploadComplete?.(updatedUrls);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
|
||||||
|
if (!canUploadMore || uploading) return;
|
||||||
|
|
||||||
|
const files = e.dataTransfer.files;
|
||||||
|
if (files.length > 0) {
|
||||||
|
handleFiles(files);
|
||||||
|
}
|
||||||
|
}, [canUploadMore, uploading]);
|
||||||
|
|
||||||
|
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const files = e.target.files;
|
||||||
|
if (files && files.length > 0) {
|
||||||
|
handleFiles(files);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const triggerFileSelect = () => {
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isAvatar) {
|
||||||
|
return (
|
||||||
|
<div className={cn('space-y-4', className)}>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="relative">
|
||||||
|
{uploadedImages.length > 0 ? (
|
||||||
|
<img
|
||||||
|
src={uploadedImages[0].thumbnailUrl}
|
||||||
|
alt="Avatar"
|
||||||
|
className="w-24 h-24 rounded-full object-cover border-2 border-border"
|
||||||
|
/>
|
||||||
|
) : existingPhotos.length > 0 ? (
|
||||||
|
<img
|
||||||
|
src={existingPhotos[0]}
|
||||||
|
alt="Avatar"
|
||||||
|
className="w-24 h-24 rounded-full object-cover border-2 border-border"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="w-24 h-24 rounded-full bg-muted border-2 border-border flex items-center justify-center">
|
||||||
|
<Camera className="w-8 h-8 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{uploading && (
|
||||||
|
<div className="absolute inset-0 bg-background/80 rounded-full flex items-center justify-center">
|
||||||
|
<Progress value={uploadProgress} className="w-16" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Button
|
||||||
|
onClick={triggerFileSelect}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={uploading}
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4 mr-2" />
|
||||||
|
{uploadedImages.length > 0 || existingPhotos.length > 0 ? 'Change Avatar' : 'Upload Avatar'}
|
||||||
|
</Button>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
JPEG, PNG, WebP up to 10MB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept={accept}
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('space-y-4', className)}>
|
||||||
|
{/* Upload Area */}
|
||||||
|
<Card
|
||||||
|
className={cn(
|
||||||
|
'border-2 border-dashed transition-colors cursor-pointer',
|
||||||
|
dragOver && 'border-primary bg-primary/5',
|
||||||
|
!canUploadMore && 'opacity-50 cursor-not-allowed',
|
||||||
|
isCompact && 'p-2'
|
||||||
|
)}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
onClick={canUploadMore && !uploading ? triggerFileSelect : undefined}
|
||||||
|
>
|
||||||
|
<CardContent className={cn('p-8 text-center', isCompact && 'p-4')}>
|
||||||
|
{uploading ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="animate-pulse">
|
||||||
|
<Upload className="w-8 h-8 text-primary mx-auto" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm font-medium">Uploading...</p>
|
||||||
|
<Progress value={uploadProgress} className="w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
{dragOver ? (
|
||||||
|
<FileImage className="w-12 h-12 text-primary" />
|
||||||
|
) : (
|
||||||
|
<ImageIcon className="w-12 h-12 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-lg font-medium">
|
||||||
|
{canUploadMore ? 'Upload Photos' : 'Maximum Photos Reached'}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{canUploadMore ? (
|
||||||
|
<>Drag & drop or click to browse<br />JPEG, PNG, WebP up to 10MB each</>
|
||||||
|
) : (
|
||||||
|
`Maximum ${maxFiles} ${maxFiles === 1 ? 'photo' : 'photos'} allowed`
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canUploadMore && (
|
||||||
|
<Badge variant="outline">
|
||||||
|
{totalImages}/{maxFiles} {maxFiles === 1 ? 'photo' : 'photos'}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept={accept}
|
||||||
|
multiple={maxFiles > 1}
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
className="hidden"
|
||||||
|
disabled={!canUploadMore || uploading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Error Display */}
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Uploaded Images Preview */}
|
||||||
|
{uploadedImages.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="text-sm font-medium">Uploaded Photos</h4>
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||||
|
{uploadedImages.map((image) => (
|
||||||
|
<div key={image.id} className="relative group">
|
||||||
|
<img
|
||||||
|
src={image.thumbnailUrl}
|
||||||
|
alt={image.filename}
|
||||||
|
className="w-full aspect-square object-cover rounded-lg border"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
size="icon"
|
||||||
|
className="absolute -top-2 -right-2 w-6 h-6 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||||
|
onClick={() => removeImage(image.id)}
|
||||||
|
>
|
||||||
|
<X className="w-3 h-3" />
|
||||||
|
</Button>
|
||||||
|
<div className="absolute bottom-2 left-2 right-2">
|
||||||
|
<Badge variant="secondary" className="text-xs truncate">
|
||||||
|
{image.filename}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Existing Photos Display */}
|
||||||
|
{existingPhotos.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h4 className="text-sm font-medium">Existing Photos</h4>
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||||
|
{existingPhotos.map((url, index) => (
|
||||||
|
<div key={index} className="relative">
|
||||||
|
<img
|
||||||
|
src={url}
|
||||||
|
alt={`Existing photo ${index + 1}`}
|
||||||
|
className="w-full aspect-square object-cover rounded-lg border"
|
||||||
|
/>
|
||||||
|
<Badge variant="outline" className="absolute bottom-2 left-2 text-xs">
|
||||||
|
Existing
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
import { Profile as ProfileType } from '@/types/database';
|
import { Profile as ProfileType } from '@/types/database';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
import { PhotoUpload } from '@/components/upload/PhotoUpload';
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
const { username } = useParams<{ username?: string }>();
|
const { username } = useParams<{ username?: string }>();
|
||||||
@@ -38,8 +39,8 @@ export default function Profile() {
|
|||||||
const [editForm, setEditForm] = useState({
|
const [editForm, setEditForm] = useState({
|
||||||
display_name: '',
|
display_name: '',
|
||||||
bio: '',
|
bio: '',
|
||||||
avatar_url: ''
|
|
||||||
});
|
});
|
||||||
|
const [avatarUrl, setAvatarUrl] = useState<string>('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getCurrentUser();
|
getCurrentUser();
|
||||||
@@ -70,8 +71,8 @@ export default function Profile() {
|
|||||||
setEditForm({
|
setEditForm({
|
||||||
display_name: data.display_name || '',
|
display_name: data.display_name || '',
|
||||||
bio: data.bio || '',
|
bio: data.bio || '',
|
||||||
avatar_url: data.avatar_url || ''
|
|
||||||
});
|
});
|
||||||
|
setAvatarUrl(data.avatar_url || '');
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('Error fetching profile:', error);
|
console.error('Error fetching profile:', error);
|
||||||
@@ -107,8 +108,8 @@ export default function Profile() {
|
|||||||
setEditForm({
|
setEditForm({
|
||||||
display_name: data.display_name || '',
|
display_name: data.display_name || '',
|
||||||
bio: data.bio || '',
|
bio: data.bio || '',
|
||||||
avatar_url: data.avatar_url || ''
|
|
||||||
});
|
});
|
||||||
|
setAvatarUrl(data.avatar_url || '');
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('Error fetching profile:', error);
|
console.error('Error fetching profile:', error);
|
||||||
@@ -131,7 +132,7 @@ export default function Profile() {
|
|||||||
.update({
|
.update({
|
||||||
display_name: editForm.display_name,
|
display_name: editForm.display_name,
|
||||||
bio: editForm.bio,
|
bio: editForm.bio,
|
||||||
avatar_url: editForm.avatar_url
|
avatar_url: avatarUrl
|
||||||
})
|
})
|
||||||
.eq('user_id', currentUser.id);
|
.eq('user_id', currentUser.id);
|
||||||
|
|
||||||
@@ -141,7 +142,7 @@ export default function Profile() {
|
|||||||
...prev,
|
...prev,
|
||||||
display_name: editForm.display_name,
|
display_name: editForm.display_name,
|
||||||
bio: editForm.bio,
|
bio: editForm.bio,
|
||||||
avatar_url: editForm.avatar_url
|
avatar_url: avatarUrl
|
||||||
} : null);
|
} : null);
|
||||||
|
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
@@ -207,12 +208,20 @@ export default function Profile() {
|
|||||||
<CardContent className="p-8">
|
<CardContent className="p-8">
|
||||||
<div className="flex flex-col md:flex-row gap-6">
|
<div className="flex flex-col md:flex-row gap-6">
|
||||||
<div className="flex flex-col items-center md:items-start">
|
<div className="flex flex-col items-center md:items-start">
|
||||||
<Avatar className="w-32 h-32 mb-4">
|
<PhotoUpload
|
||||||
<AvatarImage src={profile.avatar_url || ''} alt={profile.display_name || profile.username} />
|
variant="avatar"
|
||||||
<AvatarFallback className="text-2xl">
|
maxFiles={1}
|
||||||
{(profile.display_name || profile.username).charAt(0).toUpperCase()}
|
existingPhotos={profile.avatar_url ? [profile.avatar_url] : []}
|
||||||
</AvatarFallback>
|
onUploadComplete={(urls) => setAvatarUrl(urls[0] || '')}
|
||||||
</Avatar>
|
onError={(error) => {
|
||||||
|
toast({
|
||||||
|
title: "Upload Error",
|
||||||
|
description: error,
|
||||||
|
variant: "destructive"
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className="mb-4"
|
||||||
|
/>
|
||||||
|
|
||||||
{isOwnProfile && !editing && (
|
{isOwnProfile && !editing && (
|
||||||
<Button
|
<Button
|
||||||
@@ -251,16 +260,6 @@ export default function Profile() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="avatar_url">Avatar URL</Label>
|
|
||||||
<Input
|
|
||||||
id="avatar_url"
|
|
||||||
value={editForm.avatar_url}
|
|
||||||
onChange={(e) => setEditForm(prev => ({ ...prev, avatar_url: e.target.value }))}
|
|
||||||
placeholder="https://..."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Button onClick={handleSaveProfile} size="sm">
|
<Button onClick={handleSaveProfile} size="sm">
|
||||||
<Save className="w-4 h-4 mr-2" />
|
<Save className="w-4 h-4 mr-2" />
|
||||||
|
|||||||
141
supabase/functions/upload-image/index.ts
Normal file
141
supabase/functions/upload-image/index.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
}
|
||||||
|
|
||||||
|
serve(async (req) => {
|
||||||
|
// Handle CORS preflight requests
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
return new Response(null, { headers: corsHeaders })
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const CLOUDFLARE_ACCOUNT_ID = Deno.env.get('CLOUDFLARE_ACCOUNT_ID')
|
||||||
|
const CLOUDFLARE_IMAGES_API_TOKEN = Deno.env.get('CLOUDFLARE_IMAGES_API_TOKEN')
|
||||||
|
|
||||||
|
if (!CLOUDFLARE_ACCOUNT_ID || !CLOUDFLARE_IMAGES_API_TOKEN) {
|
||||||
|
throw new Error('Missing Cloudflare credentials')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method !== 'POST') {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: 'Method not allowed' }),
|
||||||
|
{
|
||||||
|
status: 405,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = await req.formData()
|
||||||
|
const file = formData.get('file') as File
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: 'No file provided' }),
|
||||||
|
{
|
||||||
|
status: 400,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file size (10MB limit)
|
||||||
|
const maxSize = 10 * 1024 * 1024 // 10MB
|
||||||
|
if (file.size > maxSize) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: 'File size exceeds 10MB limit' }),
|
||||||
|
{
|
||||||
|
status: 400,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file type
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: 'Invalid file type. Only JPEG, PNG, and WebP are allowed.' }),
|
||||||
|
{
|
||||||
|
status: 400,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create FormData for Cloudflare Images API
|
||||||
|
const cloudflareFormData = new FormData()
|
||||||
|
cloudflareFormData.append('file', file)
|
||||||
|
|
||||||
|
// Optional metadata
|
||||||
|
const metadata = formData.get('metadata')
|
||||||
|
if (metadata) {
|
||||||
|
cloudflareFormData.append('metadata', metadata.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload to Cloudflare Images
|
||||||
|
const uploadResponse = await fetch(
|
||||||
|
`https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/images/v1`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${CLOUDFLARE_IMAGES_API_TOKEN}`,
|
||||||
|
},
|
||||||
|
body: cloudflareFormData,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const uploadResult = await uploadResponse.json()
|
||||||
|
|
||||||
|
if (!uploadResponse.ok) {
|
||||||
|
console.error('Cloudflare upload error:', uploadResult)
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: 'Failed to upload image',
|
||||||
|
details: uploadResult.errors || uploadResult.error
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the upload result with image URLs
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
id: uploadResult.result.id,
|
||||||
|
filename: uploadResult.result.filename,
|
||||||
|
uploaded: uploadResult.result.uploaded,
|
||||||
|
variants: uploadResult.result.variants,
|
||||||
|
// Provide convenient URLs for different sizes
|
||||||
|
urls: {
|
||||||
|
original: uploadResult.result.variants[0], // First variant is usually the original
|
||||||
|
thumbnail: `${uploadResult.result.variants[0]}/w=400,h=400,fit=crop`, // 400x400 thumbnail
|
||||||
|
medium: `${uploadResult.result.variants[0]}/w=800,h=600,fit=cover`, // 800x600 medium
|
||||||
|
large: `${uploadResult.result.variants[0]}/w=1200,h=900,fit=cover`, // 1200x900 large
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Upload error:', error)
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: 'Internal server error',
|
||||||
|
message: error.message
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 500,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user