mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 06:51:12 -05:00
Implement full Novu integration
This commit is contained in:
@@ -9,140 +9,303 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { Card, CardContent, CardDescription, CardHeader } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useProfile } from '@/hooks/useProfile';
|
||||
import { useUnitPreferences } from '@/hooks/useUnitPreferences';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { MapPin, Calendar, Globe, Accessibility, Ruler } from 'lucide-react';
|
||||
import { personalLocationSchema } from '@/lib/validation';
|
||||
import { handleError, handleSuccess, AppError } from '@/lib/errorHandler';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { MapPin, Calendar, Accessibility, Ruler } from 'lucide-react';
|
||||
import type { LocationFormData, AccessibilityOptions, ParkOption } from '@/types/location';
|
||||
import {
|
||||
locationFormSchema,
|
||||
accessibilityOptionsSchema,
|
||||
parkOptionSchema,
|
||||
DEFAULT_ACCESSIBILITY_OPTIONS,
|
||||
COMMON_TIMEZONES
|
||||
} from '@/lib/locationValidation';
|
||||
|
||||
const locationSchema = z.object({
|
||||
preferred_pronouns: z.string().max(20).optional(),
|
||||
timezone: z.string(),
|
||||
preferred_language: z.string(),
|
||||
personal_location: personalLocationSchema,
|
||||
home_park_id: z.string().optional()
|
||||
});
|
||||
type LocationFormData = z.infer<typeof locationSchema>;
|
||||
interface AccessibilityOptions {
|
||||
font_size: 'small' | 'medium' | 'large';
|
||||
high_contrast: boolean;
|
||||
reduced_motion: boolean;
|
||||
}
|
||||
export function LocationTab() {
|
||||
const { user } = useAuth();
|
||||
const { data: profile, refreshProfile } = useProfile(user?.id);
|
||||
const { toast } = useToast();
|
||||
const { preferences: unitPreferences, updatePreferences: updateUnitPreferences } = useUnitPreferences();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [parks, setParks] = useState<any[]>([]);
|
||||
const [accessibility, setAccessibility] = useState<AccessibilityOptions>({
|
||||
font_size: 'medium',
|
||||
high_contrast: false,
|
||||
reduced_motion: false
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [parks, setParks] = useState<ParkOption[]>([]);
|
||||
const [accessibility, setAccessibility] = useState<AccessibilityOptions>(DEFAULT_ACCESSIBILITY_OPTIONS);
|
||||
|
||||
const form = useForm<LocationFormData>({
|
||||
resolver: zodResolver(locationSchema),
|
||||
resolver: zodResolver(locationFormSchema),
|
||||
defaultValues: {
|
||||
preferred_pronouns: profile?.preferred_pronouns || '',
|
||||
preferred_pronouns: profile?.preferred_pronouns || null,
|
||||
timezone: profile?.timezone || 'UTC',
|
||||
preferred_language: profile?.preferred_language || 'en',
|
||||
personal_location: (profile as any)?.personal_location || '',
|
||||
home_park_id: (profile as any)?.home_park_id || ''
|
||||
personal_location: profile?.personal_location || null,
|
||||
home_park_id: profile?.home_park_id || null
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchParks();
|
||||
fetchAccessibilityPreferences();
|
||||
if (user && profile) {
|
||||
form.reset({
|
||||
preferred_pronouns: profile.preferred_pronouns || null,
|
||||
timezone: profile.timezone || 'UTC',
|
||||
preferred_language: profile.preferred_language || 'en',
|
||||
personal_location: profile.personal_location || null,
|
||||
home_park_id: profile.home_park_id || null
|
||||
});
|
||||
}
|
||||
}, [profile, form]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
fetchParks();
|
||||
fetchAccessibilityPreferences();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const fetchParks = async () => {
|
||||
if (!user) return;
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('parks')
|
||||
.select('id, name, location_id, locations(city, state_province, country)')
|
||||
.select('id, name, locations(city, state_province, country)')
|
||||
.order('name');
|
||||
|
||||
if (error) throw error;
|
||||
setParks(data || []);
|
||||
if (error) {
|
||||
logger.error('Failed to fetch parks list', {
|
||||
userId: user.id,
|
||||
action: 'fetch_parks',
|
||||
error: error.message,
|
||||
errorCode: error.code
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
const validatedParks = (data || [])
|
||||
.map(park => {
|
||||
try {
|
||||
return parkOptionSchema.parse({
|
||||
id: park.id,
|
||||
name: park.name,
|
||||
location: park.locations ? {
|
||||
city: park.locations.city,
|
||||
state_province: park.locations.state_province,
|
||||
country: park.locations.country
|
||||
} : undefined
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((park): park is ParkOption => park !== null);
|
||||
|
||||
setParks(validatedParks);
|
||||
|
||||
logger.info('Parks list loaded', {
|
||||
userId: user.id,
|
||||
action: 'fetch_parks',
|
||||
count: validatedParks.length
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching parks:', error);
|
||||
logger.error('Error fetching parks', {
|
||||
userId: user.id,
|
||||
action: 'fetch_parks',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
handleError(error, {
|
||||
action: 'Load parks list',
|
||||
userId: user.id
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAccessibilityPreferences = async () => {
|
||||
if (!user) return;
|
||||
try {
|
||||
const {
|
||||
data,
|
||||
error
|
||||
} = await supabase.from('user_preferences').select('accessibility_options').eq('user_id', user.id).maybeSingle();
|
||||
if (error && error.code !== 'PGRST116') {
|
||||
console.error('Error fetching accessibility preferences:', error);
|
||||
return;
|
||||
}
|
||||
if (data?.accessibility_options) {
|
||||
setAccessibility(data.accessibility_options as any);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching accessibility preferences:', error);
|
||||
}
|
||||
};
|
||||
const onSubmit = async (data: LocationFormData) => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
// Save profile information
|
||||
const { error: profileError } = await supabase.from('profiles').update({
|
||||
preferred_pronouns: data.preferred_pronouns || null,
|
||||
timezone: data.timezone,
|
||||
preferred_language: data.preferred_language,
|
||||
personal_location: data.personal_location || null,
|
||||
home_park_id: data.home_park_id || null,
|
||||
updated_at: new Date().toISOString()
|
||||
}).eq('user_id', user.id);
|
||||
|
||||
if (profileError) throw profileError;
|
||||
|
||||
// Save accessibility preferences - update existing record
|
||||
const { error: accessibilityError } = await supabase
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('user_preferences')
|
||||
.update({
|
||||
accessibility_options: accessibility as any,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
.select('accessibility_options')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (accessibilityError) throw accessibilityError;
|
||||
if (error && error.code !== 'PGRST116') {
|
||||
logger.error('Failed to fetch accessibility preferences', {
|
||||
userId: user.id,
|
||||
action: 'fetch_accessibility_preferences',
|
||||
error: error.message,
|
||||
errorCode: error.code
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Save unit preferences
|
||||
await updateUnitPreferences(unitPreferences);
|
||||
if (data?.accessibility_options) {
|
||||
const validated = accessibilityOptionsSchema.parse(data.accessibility_options);
|
||||
setAccessibility(validated);
|
||||
}
|
||||
|
||||
await refreshProfile();
|
||||
toast({
|
||||
title: 'Settings saved',
|
||||
description: 'Your location, personal information, accessibility, and unit preferences have been updated.'
|
||||
logger.info('Accessibility preferences loaded', {
|
||||
userId: user.id,
|
||||
action: 'fetch_accessibility_preferences'
|
||||
});
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: error.message || 'Failed to save settings',
|
||||
variant: 'destructive'
|
||||
} catch (error) {
|
||||
logger.error('Error fetching accessibility preferences', {
|
||||
userId: user.id,
|
||||
action: 'fetch_accessibility_preferences',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
handleError(error, {
|
||||
action: 'Load accessibility preferences',
|
||||
userId: user.id
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const updateAccessibility = (key: keyof AccessibilityOptions, value: any) => {
|
||||
setAccessibility(prev => ({
|
||||
...prev,
|
||||
[key]: value
|
||||
}));
|
||||
|
||||
const onSubmit = async (data: LocationFormData) => {
|
||||
if (!user) return;
|
||||
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
const validatedData = locationFormSchema.parse(data);
|
||||
const validatedAccessibility = accessibilityOptionsSchema.parse(accessibility);
|
||||
|
||||
const previousProfile = {
|
||||
personal_location: profile?.personal_location,
|
||||
home_park_id: profile?.home_park_id,
|
||||
timezone: profile?.timezone,
|
||||
preferred_language: profile?.preferred_language,
|
||||
preferred_pronouns: profile?.preferred_pronouns
|
||||
};
|
||||
|
||||
const { error: profileError } = await supabase
|
||||
.from('profiles')
|
||||
.update({
|
||||
preferred_pronouns: validatedData.preferred_pronouns || null,
|
||||
timezone: validatedData.timezone,
|
||||
preferred_language: validatedData.preferred_language,
|
||||
personal_location: validatedData.personal_location || null,
|
||||
home_park_id: validatedData.home_park_id || null,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (profileError) {
|
||||
logger.error('Failed to update profile', {
|
||||
userId: user.id,
|
||||
action: 'update_profile_location',
|
||||
error: profileError.message,
|
||||
errorCode: profileError.code
|
||||
});
|
||||
throw profileError;
|
||||
}
|
||||
|
||||
const { error: accessibilityError } = await supabase
|
||||
.from('user_preferences')
|
||||
.update({
|
||||
accessibility_options: validatedAccessibility,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (accessibilityError) {
|
||||
logger.error('Failed to update accessibility preferences', {
|
||||
userId: user.id,
|
||||
action: 'update_accessibility_preferences',
|
||||
error: accessibilityError.message,
|
||||
errorCode: accessibilityError.code
|
||||
});
|
||||
throw accessibilityError;
|
||||
}
|
||||
|
||||
await updateUnitPreferences(unitPreferences);
|
||||
|
||||
await supabase.from('profile_audit_log').insert([{
|
||||
user_id: user.id,
|
||||
changed_by: user.id,
|
||||
action: 'location_info_updated',
|
||||
changes: {
|
||||
previous: {
|
||||
profile: previousProfile,
|
||||
accessibility: DEFAULT_ACCESSIBILITY_OPTIONS
|
||||
},
|
||||
updated: {
|
||||
profile: validatedData,
|
||||
accessibility: validatedAccessibility
|
||||
},
|
||||
timestamp: new Date().toISOString()
|
||||
} as any
|
||||
}]);
|
||||
|
||||
await refreshProfile();
|
||||
|
||||
logger.info('Location and info settings updated', {
|
||||
userId: user.id,
|
||||
action: 'update_location_info'
|
||||
});
|
||||
|
||||
handleSuccess(
|
||||
'Settings saved',
|
||||
'Your location, personal information, accessibility, and unit preferences have been updated.'
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Error saving location settings', {
|
||||
userId: user.id,
|
||||
action: 'save_location_settings',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
handleError(
|
||||
new AppError(
|
||||
'Invalid settings',
|
||||
'VALIDATION_ERROR',
|
||||
error.issues.map(i => i.message).join(', ')
|
||||
),
|
||||
{ action: 'Validate location settings', userId: user.id }
|
||||
);
|
||||
} else {
|
||||
handleError(error, {
|
||||
action: 'Save location settings',
|
||||
userId: user.id
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
const timezones = ['UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles', 'America/Toronto', 'Europe/London', 'Europe/Berlin', 'Europe/Paris', 'Asia/Tokyo', 'Asia/Shanghai', 'Australia/Sydney'];
|
||||
return <div className="space-y-8">
|
||||
|
||||
const updateAccessibility = (key: keyof AccessibilityOptions, value: any) => {
|
||||
setAccessibility(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-6 w-48" />
|
||||
<Skeleton className="h-4 w-full max-w-md" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
|
||||
{/* Location Settings */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<MapPin className="w-5 h-5" />
|
||||
@@ -163,6 +326,11 @@ export function LocationTab() {
|
||||
{...form.register('personal_location')}
|
||||
placeholder="e.g., San Francisco, CA or Berlin, Germany"
|
||||
/>
|
||||
{form.formState.errors.personal_location && (
|
||||
<p className="text-sm text-destructive">
|
||||
{form.formState.errors.personal_location.message}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your personal location (optional, displayed as text)
|
||||
</p>
|
||||
@@ -170,7 +338,10 @@ export function LocationTab() {
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="home_park_id">Home Park</Label>
|
||||
<Select value={form.watch('home_park_id')} onValueChange={value => form.setValue('home_park_id', value)}>
|
||||
<Select
|
||||
value={form.watch('home_park_id') || undefined}
|
||||
onValueChange={value => form.setValue('home_park_id', value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select your home park" />
|
||||
</SelectTrigger>
|
||||
@@ -178,17 +349,22 @@ export function LocationTab() {
|
||||
{parks.map(park => (
|
||||
<SelectItem key={park.id} value={park.id}>
|
||||
{park.name}
|
||||
{park.locations && (
|
||||
{park.location && (
|
||||
<>
|
||||
{park.locations.city && `, ${park.locations.city}`}
|
||||
{park.locations.state_province && `, ${park.locations.state_province}`}
|
||||
{park.locations.country && `, ${park.locations.country}`}
|
||||
{park.location.city && `, ${park.location.city}`}
|
||||
{park.location.state_province && `, ${park.location.state_province}`}
|
||||
{`, ${park.location.country}`}
|
||||
</>
|
||||
)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{form.formState.errors.home_park_id && (
|
||||
<p className="text-sm text-destructive">
|
||||
{form.formState.errors.home_park_id.message}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The theme park you visit most often or consider your "home" park
|
||||
</p>
|
||||
@@ -196,27 +372,63 @@ export function LocationTab() {
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timezone">Timezone</Label>
|
||||
<Select value={form.watch('timezone')} onValueChange={value => form.setValue('timezone', value)}>
|
||||
<Select
|
||||
value={form.watch('timezone')}
|
||||
onValueChange={value => form.setValue('timezone', value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{timezones.map(tz => <SelectItem key={tz} value={tz}>
|
||||
{COMMON_TIMEZONES.map(tz => (
|
||||
<SelectItem key={tz} value={tz}>
|
||||
{tz}
|
||||
</SelectItem>)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{form.formState.errors.timezone && (
|
||||
<p className="text-sm text-destructive">
|
||||
{form.formState.errors.timezone.message}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Used to display dates and times in your local timezone.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="preferred_language">Preferred Language</Label>
|
||||
<Select
|
||||
value={form.watch('preferred_language')}
|
||||
onValueChange={value => form.setValue('preferred_language', value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="en">English</SelectItem>
|
||||
<SelectItem value="es">Español</SelectItem>
|
||||
<SelectItem value="fr">Français</SelectItem>
|
||||
<SelectItem value="de">Deutsch</SelectItem>
|
||||
<SelectItem value="it">Italiano</SelectItem>
|
||||
<SelectItem value="pt">Português</SelectItem>
|
||||
<SelectItem value="ja">日本語</SelectItem>
|
||||
<SelectItem value="zh">中文</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{form.formState.errors.preferred_language && (
|
||||
<p className="text-sm text-destructive">
|
||||
{form.formState.errors.preferred_language.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Personal Information */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="w-5 h-5" />
|
||||
@@ -230,23 +442,28 @@ export function LocationTab() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="preferred_pronouns">Preferred Pronouns</Label>
|
||||
<Input id="preferred_pronouns" {...form.register('preferred_pronouns')} placeholder="e.g., they/them, she/her, he/him" />
|
||||
<Input
|
||||
id="preferred_pronouns"
|
||||
{...form.register('preferred_pronouns')}
|
||||
placeholder="e.g., they/them, she/her, he/him"
|
||||
/>
|
||||
{form.formState.errors.preferred_pronouns && (
|
||||
<p className="text-sm text-destructive">
|
||||
{form.formState.errors.preferred_pronouns.message}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
How you'd like others to refer to you.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Unit Preferences */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Ruler className="w-5 h-5" />
|
||||
@@ -276,15 +493,16 @@ export function LocationTab() {
|
||||
<SelectItem value="imperial">Imperial (mph, feet, inches)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
All measurements in the database are stored in metric and converted for display.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Accessibility Options */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Accessibility className="w-5 h-5" />
|
||||
@@ -300,7 +518,12 @@ export function LocationTab() {
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-3">
|
||||
<Label>Font Size</Label>
|
||||
<Select value={accessibility.font_size} onValueChange={(value: 'small' | 'medium' | 'large') => updateAccessibility('font_size', value)}>
|
||||
<Select
|
||||
value={accessibility.font_size}
|
||||
onValueChange={(value: 'small' | 'medium' | 'large') =>
|
||||
updateAccessibility('font_size', value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -319,7 +542,10 @@ export function LocationTab() {
|
||||
Increase contrast for better visibility
|
||||
</p>
|
||||
</div>
|
||||
<Switch checked={accessibility.high_contrast} onCheckedChange={checked => updateAccessibility('high_contrast', checked)} />
|
||||
<Switch
|
||||
checked={accessibility.high_contrast}
|
||||
onCheckedChange={checked => updateAccessibility('high_contrast', checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -329,17 +555,21 @@ export function LocationTab() {
|
||||
Minimize animations and transitions
|
||||
</p>
|
||||
</div>
|
||||
<Switch checked={accessibility.reduced_motion} onCheckedChange={checked => updateAccessibility('reduced_motion', checked)} />
|
||||
<Switch
|
||||
checked={accessibility.reduced_motion}
|
||||
onCheckedChange={checked => updateAccessibility('reduced_motion', checked)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Saving...' : 'Save Settings'}
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? 'Saving...' : 'Save Settings'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>;
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { UnitPreferences, getMeasurementSystemFromCountry } from '@/lib/units';
|
||||
|
||||
const DEFAULT_PREFERENCES: UnitPreferences = {
|
||||
@@ -21,21 +22,28 @@ export function useUnitPreferences() {
|
||||
const loadPreferences = async () => {
|
||||
try {
|
||||
if (user) {
|
||||
// Load from database for logged-in users
|
||||
const { data } = await supabase
|
||||
const { data, error } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('unit_preferences')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error && error.code !== 'PGRST116') {
|
||||
logger.error('Failed to fetch unit preferences', {
|
||||
userId: user.id,
|
||||
action: 'fetch_unit_preferences',
|
||||
error: error.message,
|
||||
errorCode: error.code
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (data?.unit_preferences && typeof data.unit_preferences === 'object') {
|
||||
setPreferences({ ...DEFAULT_PREFERENCES, ...(data.unit_preferences as unknown as UnitPreferences) });
|
||||
} else {
|
||||
// Auto-detect for new users
|
||||
await autoDetectPreferences();
|
||||
}
|
||||
} else {
|
||||
// Check localStorage for anonymous users
|
||||
const stored = localStorage.getItem('unit_preferences');
|
||||
if (stored) {
|
||||
try {
|
||||
@@ -49,7 +57,11 @@ export function useUnitPreferences() {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading unit preferences:', error);
|
||||
logger.error('Error loading unit preferences', {
|
||||
userId: user?.id,
|
||||
action: 'load_unit_preferences',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
await autoDetectPreferences();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -68,9 +80,7 @@ export function useUnitPreferences() {
|
||||
|
||||
setPreferences(newPreferences);
|
||||
|
||||
// Save to database for logged-in users, localStorage for anonymous users
|
||||
if (user) {
|
||||
// Use upsert with merge
|
||||
const { error } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert({
|
||||
@@ -80,7 +90,11 @@ export function useUnitPreferences() {
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('Error saving preferences to database:', error);
|
||||
logger.error('Error saving auto-detected preferences', {
|
||||
userId: user.id,
|
||||
action: 'save_auto_detected_preferences',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
} else {
|
||||
localStorage.setItem('unit_preferences', JSON.stringify(newPreferences));
|
||||
@@ -89,7 +103,11 @@ export function useUnitPreferences() {
|
||||
return newPreferences;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error auto-detecting location:', error);
|
||||
logger.error('Error auto-detecting location', {
|
||||
userId: user?.id,
|
||||
action: 'auto_detect_location',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback to default
|
||||
@@ -103,7 +121,6 @@ export function useUnitPreferences() {
|
||||
|
||||
try {
|
||||
if (user) {
|
||||
// Save to database for logged-in users
|
||||
await supabase
|
||||
.from('user_preferences')
|
||||
.update({
|
||||
@@ -111,13 +128,20 @@ export function useUnitPreferences() {
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
logger.info('Unit preferences updated', {
|
||||
userId: user.id,
|
||||
action: 'update_unit_preferences'
|
||||
});
|
||||
} else {
|
||||
// Save to localStorage for anonymous users
|
||||
localStorage.setItem('unit_preferences', JSON.stringify(updated));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving unit preferences:', error);
|
||||
// Revert on error
|
||||
logger.error('Error saving unit preferences', {
|
||||
userId: user?.id,
|
||||
action: 'save_unit_preferences',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
});
|
||||
setPreferences(preferences);
|
||||
throw error;
|
||||
}
|
||||
|
||||
78
src/lib/locationValidation.ts
Normal file
78
src/lib/locationValidation.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { z } from 'zod';
|
||||
import { personalLocationSchema, preferredPronounsSchema } from '@/lib/validation';
|
||||
import type { AccessibilityOptions } from '@/types/location';
|
||||
|
||||
/**
|
||||
* Schema for accessibility options
|
||||
*/
|
||||
export const accessibilityOptionsSchema = z.object({
|
||||
font_size: z.enum(['small', 'medium', 'large'] as const),
|
||||
high_contrast: z.boolean(),
|
||||
reduced_motion: z.boolean()
|
||||
});
|
||||
|
||||
/**
|
||||
* Schema for location form data
|
||||
*/
|
||||
export const locationFormSchema = z.object({
|
||||
personal_location: personalLocationSchema,
|
||||
home_park_id: z.string().uuid('Invalid park ID').optional().nullable(),
|
||||
timezone: z.string().min(1, 'Timezone is required'),
|
||||
preferred_language: z.string().min(2, 'Language code must be at least 2 characters').max(10),
|
||||
preferred_pronouns: preferredPronounsSchema
|
||||
});
|
||||
|
||||
/**
|
||||
* Default accessibility options for new users
|
||||
*/
|
||||
export const DEFAULT_ACCESSIBILITY_OPTIONS: AccessibilityOptions = {
|
||||
font_size: 'medium',
|
||||
high_contrast: false,
|
||||
reduced_motion: false
|
||||
};
|
||||
|
||||
/**
|
||||
* Common timezones for selection
|
||||
*/
|
||||
export const COMMON_TIMEZONES = [
|
||||
'UTC',
|
||||
'America/New_York',
|
||||
'America/Chicago',
|
||||
'America/Denver',
|
||||
'America/Los_Angeles',
|
||||
'America/Anchorage',
|
||||
'America/Toronto',
|
||||
'America/Vancouver',
|
||||
'America/Mexico_City',
|
||||
'America/Sao_Paulo',
|
||||
'Europe/London',
|
||||
'Europe/Paris',
|
||||
'Europe/Berlin',
|
||||
'Europe/Madrid',
|
||||
'Europe/Rome',
|
||||
'Europe/Stockholm',
|
||||
'Europe/Moscow',
|
||||
'Asia/Dubai',
|
||||
'Asia/Kolkata',
|
||||
'Asia/Bangkok',
|
||||
'Asia/Singapore',
|
||||
'Asia/Shanghai',
|
||||
'Asia/Tokyo',
|
||||
'Asia/Seoul',
|
||||
'Australia/Sydney',
|
||||
'Australia/Melbourne',
|
||||
'Pacific/Auckland'
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Validate park option data
|
||||
*/
|
||||
export const parkOptionSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
location: z.object({
|
||||
city: z.string().optional(),
|
||||
state_province: z.string().optional(),
|
||||
country: z.string()
|
||||
}).optional()
|
||||
});
|
||||
54
src/types/location.ts
Normal file
54
src/types/location.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Location & Info Type Definitions
|
||||
*
|
||||
* Centralized types for location, personal info, accessibility, and unit preferences.
|
||||
*/
|
||||
|
||||
import type { UnitPreferences } from '@/lib/units';
|
||||
|
||||
/**
|
||||
* Accessibility options stored in user_preferences.accessibility_options
|
||||
*/
|
||||
export interface AccessibilityOptions {
|
||||
font_size: 'small' | 'medium' | 'large';
|
||||
high_contrast: boolean;
|
||||
reduced_motion: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile location and personal information
|
||||
*/
|
||||
export interface ProfileLocationInfo {
|
||||
personal_location: string | null;
|
||||
home_park_id: string | null;
|
||||
timezone: string;
|
||||
preferred_language: string;
|
||||
preferred_pronouns: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combined form data for Location tab
|
||||
*/
|
||||
export interface LocationFormData extends ProfileLocationInfo {}
|
||||
|
||||
/**
|
||||
* Park data for home park selection
|
||||
*/
|
||||
export interface ParkOption {
|
||||
id: string;
|
||||
name: string;
|
||||
location?: {
|
||||
city?: string;
|
||||
state_province?: string;
|
||||
country: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete location & info settings
|
||||
*/
|
||||
export interface LocationInfoSettings {
|
||||
profile: ProfileLocationInfo;
|
||||
accessibility: AccessibilityOptions;
|
||||
unitPreferences: UnitPreferences;
|
||||
}
|
||||
Reference in New Issue
Block a user