mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 08:31:12 -05:00
Implement admin settings system
This commit is contained in:
@@ -19,6 +19,7 @@ import Terms from "./pages/Terms";
|
||||
import Privacy from "./pages/Privacy";
|
||||
import SubmissionGuidelines from "./pages/SubmissionGuidelines";
|
||||
import Admin from "./pages/Admin";
|
||||
import AdminSettings from "./pages/AdminSettings";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
@@ -42,6 +43,7 @@ const App = () => (
|
||||
<Route path="/profile" element={<Profile />} />
|
||||
<Route path="/profile/:username" element={<Profile />} />
|
||||
<Route path="/admin" element={<Admin />} />
|
||||
<Route path="/admin/settings" element={<AdminSettings />} />
|
||||
<Route path="/terms" element={<Terms />} />
|
||||
<Route path="/privacy" element={<Privacy />} />
|
||||
<Route path="/submission-guidelines" element={<SubmissionGuidelines />} />
|
||||
|
||||
@@ -27,9 +27,11 @@ export function AdminHeader() {
|
||||
|
||||
{/* Right Section - Admin actions */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm">
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link to="/admin/settings">
|
||||
<Settings className="w-4 h-4" />
|
||||
<span className="hidden sm:ml-2 sm:inline">Settings</span>
|
||||
</Link>
|
||||
</Button>
|
||||
<ThemeToggle />
|
||||
<AuthButtons />
|
||||
|
||||
134
src/hooks/useAdminSettings.ts
Normal file
134
src/hooks/useAdminSettings.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuth } from './useAuth';
|
||||
import { useToast } from './use-toast';
|
||||
|
||||
interface AdminSetting {
|
||||
id: string;
|
||||
setting_key: string;
|
||||
setting_value: any;
|
||||
category: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export function useAdminSettings() {
|
||||
const { user } = useAuth();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const {
|
||||
data: settings,
|
||||
isLoading,
|
||||
error
|
||||
} = useQuery({
|
||||
queryKey: ['admin-settings'],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from('admin_settings')
|
||||
.select('*')
|
||||
.order('category', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data as AdminSetting[];
|
||||
},
|
||||
enabled: !!user
|
||||
});
|
||||
|
||||
const updateSettingMutation = useMutation({
|
||||
mutationFn: async ({ key, value }: { key: string; value: any }) => {
|
||||
const { error } = await supabase
|
||||
.from('admin_settings')
|
||||
.update({
|
||||
setting_value: value,
|
||||
updated_by: user?.id,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('setting_key', key);
|
||||
|
||||
if (error) throw error;
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-settings'] });
|
||||
toast({
|
||||
title: "Setting Updated",
|
||||
description: "The setting has been saved successfully.",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error.message || "Failed to update setting",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const getSetting = (key: string) => {
|
||||
return settings?.find(s => s.setting_key === key);
|
||||
};
|
||||
|
||||
const getSettingValue = (key: string, defaultValue: any = null) => {
|
||||
const setting = getSetting(key);
|
||||
return setting ? setting.setting_value : defaultValue;
|
||||
};
|
||||
|
||||
const getSettingsByCategory = (category: string) => {
|
||||
return settings?.filter(s => s.category === category) || [];
|
||||
};
|
||||
|
||||
const updateSetting = async (key: string, value: any) => {
|
||||
return updateSettingMutation.mutateAsync({ key, value });
|
||||
};
|
||||
|
||||
// Helper functions for common settings
|
||||
const getAutoFlagThreshold = () => {
|
||||
return parseInt(getSettingValue('moderation.auto_flag_threshold', '3'));
|
||||
};
|
||||
|
||||
const getRequireApproval = () => {
|
||||
const value = getSettingValue('moderation.require_approval', 'true');
|
||||
return value === true || value === 'true';
|
||||
};
|
||||
|
||||
const getBanDurations = () => {
|
||||
const value = getSettingValue('moderation.ban_durations', ['1d', '7d', '30d', 'permanent']);
|
||||
return Array.isArray(value) ? value : JSON.parse(value || '[]');
|
||||
};
|
||||
|
||||
const getEmailAlertsEnabled = () => {
|
||||
const value = getSettingValue('notifications.email_alerts', 'true');
|
||||
return value === true || value === 'true';
|
||||
};
|
||||
|
||||
const getReportThreshold = () => {
|
||||
return parseInt(getSettingValue('notifications.report_threshold', '5'));
|
||||
};
|
||||
|
||||
const getAuditRetentionDays = () => {
|
||||
return parseInt(getSettingValue('system.audit_retention_days', '365'));
|
||||
};
|
||||
|
||||
const getAutoCleanupEnabled = () => {
|
||||
const value = getSettingValue('system.auto_cleanup', 'false');
|
||||
return value === true || value === 'true';
|
||||
};
|
||||
|
||||
return {
|
||||
settings,
|
||||
isLoading,
|
||||
error,
|
||||
updateSetting,
|
||||
isUpdating: updateSettingMutation.isPending,
|
||||
getSetting,
|
||||
getSettingValue,
|
||||
getSettingsByCategory,
|
||||
// Helper functions
|
||||
getAutoFlagThreshold,
|
||||
getRequireApproval,
|
||||
getBanDurations,
|
||||
getEmailAlertsEnabled,
|
||||
getReportThreshold,
|
||||
getAuditRetentionDays,
|
||||
getAutoCleanupEnabled,
|
||||
};
|
||||
}
|
||||
@@ -41,6 +41,39 @@ export type Database = {
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
admin_settings: {
|
||||
Row: {
|
||||
category: string
|
||||
created_at: string
|
||||
description: string | null
|
||||
id: string
|
||||
setting_key: string
|
||||
setting_value: Json
|
||||
updated_at: string
|
||||
updated_by: string | null
|
||||
}
|
||||
Insert: {
|
||||
category: string
|
||||
created_at?: string
|
||||
description?: string | null
|
||||
id?: string
|
||||
setting_key: string
|
||||
setting_value: Json
|
||||
updated_at?: string
|
||||
updated_by?: string | null
|
||||
}
|
||||
Update: {
|
||||
category?: string
|
||||
created_at?: string
|
||||
description?: string | null
|
||||
id?: string
|
||||
setting_key?: string
|
||||
setting_value?: Json
|
||||
updated_at?: string
|
||||
updated_by?: string | null
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
companies: {
|
||||
Row: {
|
||||
average_rating: number | null
|
||||
|
||||
296
src/pages/AdminSettings.tsx
Normal file
296
src/pages/AdminSettings.tsx
Normal file
@@ -0,0 +1,296 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { AdminHeader } from '@/components/layout/AdminHeader';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useUserRole } from '@/hooks/useUserRole';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { Loader2, Save } from 'lucide-react';
|
||||
|
||||
interface AdminSetting {
|
||||
id: string;
|
||||
setting_key: string;
|
||||
setting_value: any;
|
||||
category: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export default function AdminSettings() {
|
||||
const { user } = useAuth();
|
||||
const { permissions, loading: roleLoading } = useUserRole();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
|
||||
// Fetch admin settings
|
||||
const { data: settings, isLoading } = useQuery({
|
||||
queryKey: ['admin-settings'],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from('admin_settings')
|
||||
.select('*')
|
||||
.order('category', { ascending: true });
|
||||
|
||||
if (error) throw error;
|
||||
return data as AdminSetting[];
|
||||
},
|
||||
enabled: !!user && permissions?.role_level !== 'user'
|
||||
});
|
||||
|
||||
// Update settings mutation
|
||||
const updateSettingMutation = useMutation({
|
||||
mutationFn: async ({ key, value }: { key: string; value: any }) => {
|
||||
const { error } = await supabase
|
||||
.from('admin_settings')
|
||||
.update({
|
||||
setting_value: value,
|
||||
updated_by: user?.id,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('setting_key', key);
|
||||
|
||||
if (error) throw error;
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-settings'] });
|
||||
setHasChanges(false);
|
||||
toast({
|
||||
title: "Settings Updated",
|
||||
description: "Admin settings have been saved successfully.",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error.message || "Failed to update settings",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (roleLoading || isLoading) {
|
||||
return (
|
||||
<>
|
||||
<AdminHeader />
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Loader2 className="w-8 h-8 animate-spin" />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user || permissions?.role_level === 'user') {
|
||||
return (
|
||||
<>
|
||||
<AdminHeader />
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold mb-4">Access Denied</h1>
|
||||
<p className="text-muted-foreground">You don't have permission to access admin settings.</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const getSettingsByCategory = (category: string) => {
|
||||
return settings?.filter(s => s.category === category) || [];
|
||||
};
|
||||
|
||||
const handleSettingChange = (key: string, value: any) => {
|
||||
setHasChanges(true);
|
||||
// You could implement local state management here for real-time updates
|
||||
};
|
||||
|
||||
const handleSave = async (key: string, value: any) => {
|
||||
await updateSettingMutation.mutateAsync({ key, value });
|
||||
};
|
||||
|
||||
const SettingInput = ({ setting }: { setting: AdminSetting }) => {
|
||||
const [localValue, setLocalValue] = useState(setting.setting_value);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
await handleSave(setting.setting_key, localValue);
|
||||
};
|
||||
|
||||
if (setting.setting_key.includes('threshold') || setting.setting_key.includes('retention_days')) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={setting.setting_key}>{setting.description}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id={setting.setting_key}
|
||||
type="number"
|
||||
value={localValue}
|
||||
onChange={(e) => {
|
||||
setLocalValue(parseInt(e.target.value));
|
||||
handleSettingChange(setting.setting_key, parseInt(e.target.value));
|
||||
}}
|
||||
/>
|
||||
<Button onClick={handleSubmit} disabled={updateSettingMutation.isPending}>
|
||||
<Save className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (setting.setting_key.includes('email_alerts') || setting.setting_key.includes('require_approval') || setting.setting_key.includes('auto_cleanup')) {
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>{setting.description}</Label>
|
||||
</div>
|
||||
<Switch
|
||||
checked={localValue === true || localValue === 'true'}
|
||||
onCheckedChange={(checked) => {
|
||||
setLocalValue(checked);
|
||||
handleSave(setting.setting_key, checked);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (setting.setting_key === 'moderation.ban_durations') {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={setting.setting_key}>{setting.description}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
id={setting.setting_key}
|
||||
value={JSON.stringify(localValue, null, 2)}
|
||||
onChange={(e) => {
|
||||
try {
|
||||
const parsed = JSON.parse(e.target.value);
|
||||
setLocalValue(parsed);
|
||||
handleSettingChange(setting.setting_key, parsed);
|
||||
} catch (err) {
|
||||
// Invalid JSON, don't update
|
||||
}
|
||||
}}
|
||||
rows={4}
|
||||
/>
|
||||
<Button onClick={handleSubmit} disabled={updateSettingMutation.isPending}>
|
||||
<Save className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={setting.setting_key}>{setting.description}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id={setting.setting_key}
|
||||
value={localValue}
|
||||
onChange={(e) => {
|
||||
setLocalValue(e.target.value);
|
||||
handleSettingChange(setting.setting_key, e.target.value);
|
||||
}}
|
||||
/>
|
||||
<Button onClick={handleSubmit} disabled={updateSettingMutation.isPending}>
|
||||
<Save className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<AdminHeader />
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold mb-2">Admin Settings</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Configure system-wide settings and preferences
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="moderation" className="space-y-4">
|
||||
<TabsList className="grid w-full grid-cols-4">
|
||||
<TabsTrigger value="moderation">Moderation</TabsTrigger>
|
||||
<TabsTrigger value="user_management">User Management</TabsTrigger>
|
||||
<TabsTrigger value="notifications">Notifications</TabsTrigger>
|
||||
<TabsTrigger value="system">System</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="moderation">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Moderation Settings</CardTitle>
|
||||
<CardDescription>
|
||||
Configure content moderation rules and thresholds
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{getSettingsByCategory('moderation').map((setting) => (
|
||||
<SettingInput key={setting.id} setting={setting} />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="user_management">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>User Management</CardTitle>
|
||||
<CardDescription>
|
||||
Configure user management policies and options
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{getSettingsByCategory('user_management').map((setting) => (
|
||||
<SettingInput key={setting.id} setting={setting} />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="notifications">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Notifications</CardTitle>
|
||||
<CardDescription>
|
||||
Configure notification preferences and alert thresholds
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{getSettingsByCategory('notifications').map((setting) => (
|
||||
<SettingInput key={setting.id} setting={setting} />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="system">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System Configuration</CardTitle>
|
||||
<CardDescription>
|
||||
Configure system-wide settings and maintenance options
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{getSettingsByCategory('system').map((setting) => (
|
||||
<SettingInput key={setting.id} setting={setting} />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Create admin settings table
|
||||
CREATE TABLE public.admin_settings (
|
||||
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
setting_key TEXT NOT NULL UNIQUE,
|
||||
setting_value JSONB NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||
updated_by UUID REFERENCES auth.users(id)
|
||||
);
|
||||
|
||||
-- Enable RLS
|
||||
ALTER TABLE public.admin_settings ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Create policies for admin settings
|
||||
CREATE POLICY "Admins can manage settings"
|
||||
ON public.admin_settings
|
||||
FOR ALL
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
-- Create trigger for updated_at
|
||||
CREATE TRIGGER update_admin_settings_updated_at
|
||||
BEFORE UPDATE ON public.admin_settings
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.update_updated_at_column();
|
||||
|
||||
-- Insert default settings
|
||||
INSERT INTO public.admin_settings (setting_key, setting_value, category, description) VALUES
|
||||
('moderation.auto_flag_threshold', '3', 'moderation', 'Number of reports needed to automatically flag content'),
|
||||
('moderation.require_approval', 'true', 'moderation', 'Require admin approval for new reviews'),
|
||||
('moderation.ban_durations', '["1d", "7d", "30d", "permanent"]', 'user_management', 'Available ban duration options'),
|
||||
('notifications.email_alerts', 'true', 'notifications', 'Send email alerts for new reports'),
|
||||
('notifications.report_threshold', '5', 'notifications', 'Minimum reports to trigger alert'),
|
||||
('system.audit_retention_days', '365', 'system', 'How long to keep audit logs (days)'),
|
||||
('system.auto_cleanup', 'false', 'system', 'Automatically clean up old data');
|
||||
Reference in New Issue
Block a user