mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-24 08:51:16 -05:00
Reverted to commit 0091584677
This commit is contained in:
@@ -1,28 +1,78 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { PhotoGrid } from '@/components/common/PhotoGrid';
|
||||
import { usePhotoSubmission } from '@/hooks/moderation/usePhotoSubmission';
|
||||
import type { PhotoSubmissionItem } from '@/types/photo-submissions';
|
||||
import type { PhotoItem } from '@/types/photos';
|
||||
import { getErrorMessage } from '@/lib/errorHandler';
|
||||
|
||||
interface PhotoSubmissionDisplayProps {
|
||||
submissionId: string;
|
||||
}
|
||||
|
||||
export function PhotoSubmissionDisplay({ submissionId }: PhotoSubmissionDisplayProps) {
|
||||
const { data: photos, isLoading, error } = usePhotoSubmission(submissionId);
|
||||
const [photos, setPhotos] = useState<PhotoSubmissionItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (isLoading) {
|
||||
useEffect(() => {
|
||||
fetchPhotos();
|
||||
}, [submissionId]);
|
||||
|
||||
const fetchPhotos = async () => {
|
||||
try {
|
||||
// Step 1: Get photo_submission_id from submission_id
|
||||
const { data: photoSubmission, error: photoSubmissionError } = await supabase
|
||||
.from('photo_submissions')
|
||||
.select('id, entity_type, title')
|
||||
.eq('submission_id', submissionId)
|
||||
.maybeSingle();
|
||||
|
||||
if (photoSubmissionError) {
|
||||
throw photoSubmissionError;
|
||||
}
|
||||
|
||||
if (!photoSubmission) {
|
||||
setPhotos([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 2: Get photo items using photo_submission_id
|
||||
const { data, error } = await supabase
|
||||
.from('photo_submission_items')
|
||||
.select('*')
|
||||
.eq('photo_submission_id', photoSubmission.id)
|
||||
.order('order_index');
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
setPhotos(data || []);
|
||||
} catch (error: unknown) {
|
||||
const errorMsg = getErrorMessage(error);
|
||||
setPhotos([]);
|
||||
setError(errorMsg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-sm text-muted-foreground">Loading photos...</div>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-sm text-destructive">
|
||||
Error loading photos: {error.message}
|
||||
Error loading photos: {error}
|
||||
<br />
|
||||
<span className="text-xs">Submission ID: {submissionId}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!photos || photos.length === 0) {
|
||||
if (photos.length === 0) {
|
||||
return (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
No photos found for this submission
|
||||
@@ -32,5 +82,15 @@ export function PhotoSubmissionDisplay({ submissionId }: PhotoSubmissionDisplayP
|
||||
);
|
||||
}
|
||||
|
||||
return <PhotoGrid photos={photos} />;
|
||||
// Convert PhotoSubmissionItem[] to PhotoItem[] for PhotoGrid
|
||||
const photoItems: PhotoItem[] = photos.map(photo => ({
|
||||
id: photo.id,
|
||||
url: photo.cloudflare_image_url,
|
||||
filename: photo.filename || `Photo ${photo.order_index + 1}`,
|
||||
caption: photo.caption,
|
||||
title: photo.title,
|
||||
date_taken: photo.date_taken,
|
||||
}));
|
||||
|
||||
return <PhotoGrid photos={photoItems} />;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,171 @@
|
||||
import { forwardRef, useImperativeHandle } from 'react';
|
||||
import { useRecentActivity } from '@/hooks/moderation/useRecentActivity';
|
||||
import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { handleError } from '@/lib/errorHandler';
|
||||
import { ActivityCard } from './ActivityCard';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Activity as ActivityIcon } from 'lucide-react';
|
||||
import { smartMergeArray } from '@/lib/smartStateUpdate';
|
||||
import { useAdminSettings } from '@/hooks/useAdminSettings';
|
||||
|
||||
interface ActivityItem {
|
||||
id: string;
|
||||
type: 'submission' | 'report' | 'review';
|
||||
action: 'approved' | 'rejected' | 'reviewed' | 'dismissed' | 'flagged';
|
||||
entity_type?: string;
|
||||
entity_name?: string;
|
||||
timestamp: string;
|
||||
moderator_id?: string;
|
||||
moderator?: {
|
||||
username: string;
|
||||
display_name?: string;
|
||||
avatar_url?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface RecentActivityRef {
|
||||
refresh: () => void;
|
||||
}
|
||||
|
||||
export const RecentActivity = forwardRef<RecentActivityRef>((props, ref) => {
|
||||
const { data: activities = [], isLoading: loading, refetch } = useRecentActivity();
|
||||
const [activities, setActivities] = useState<ActivityItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isSilentRefresh, setIsSilentRefresh] = useState(false);
|
||||
const { user } = useAuth();
|
||||
const { getAutoRefreshStrategy } = useAdminSettings();
|
||||
const refreshStrategy = getAutoRefreshStrategy();
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
refresh: refetch
|
||||
refresh: () => fetchRecentActivity(false)
|
||||
}));
|
||||
|
||||
const fetchRecentActivity = async (silent = false) => {
|
||||
if (!user) return;
|
||||
|
||||
try {
|
||||
if (!silent) {
|
||||
setLoading(true);
|
||||
} else {
|
||||
setIsSilentRefresh(true);
|
||||
}
|
||||
|
||||
// Fetch recent approved/rejected submissions
|
||||
const { data: submissions, error: submissionsError } = await supabase
|
||||
.from('content_submissions')
|
||||
.select('id, status, reviewed_at, reviewer_id, submission_type')
|
||||
.in('status', ['approved', 'rejected'])
|
||||
.not('reviewed_at', 'is', null)
|
||||
.order('reviewed_at', { ascending: false })
|
||||
.limit(15);
|
||||
|
||||
if (submissionsError) throw submissionsError;
|
||||
|
||||
// Fetch recent report resolutions
|
||||
const { data: reports, error: reportsError } = await supabase
|
||||
.from('reports')
|
||||
.select('id, status, reviewed_at, reviewed_by, reported_entity_type')
|
||||
.in('status', ['reviewed', 'dismissed'])
|
||||
.not('reviewed_at', 'is', null)
|
||||
.order('reviewed_at', { ascending: false })
|
||||
.limit(15);
|
||||
|
||||
if (reportsError) throw reportsError;
|
||||
|
||||
// Fetch recent review moderations
|
||||
const { data: reviews, error: reviewsError } = await supabase
|
||||
.from('reviews')
|
||||
.select('id, moderation_status, moderated_at, moderated_by, park_id, ride_id')
|
||||
.in('moderation_status', ['approved', 'rejected', 'flagged'])
|
||||
.not('moderated_at', 'is', null)
|
||||
.order('moderated_at', { ascending: false })
|
||||
.limit(15);
|
||||
|
||||
if (reviewsError) throw reviewsError;
|
||||
|
||||
// Get unique moderator IDs
|
||||
const moderatorIds = [
|
||||
...(submissions?.map(s => s.reviewer_id).filter(Boolean) || []),
|
||||
...(reports?.map(r => r.reviewed_by).filter(Boolean) || []),
|
||||
...(reviews?.map(r => r.moderated_by).filter(Boolean) || []),
|
||||
].filter((id, index, arr) => id && arr.indexOf(id) === index);
|
||||
|
||||
// Fetch moderator profiles
|
||||
const { data: profiles } = await supabase
|
||||
.from('profiles')
|
||||
.select('user_id, username, display_name, avatar_url')
|
||||
.in('user_id', moderatorIds);
|
||||
|
||||
const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []);
|
||||
|
||||
// Combine all activities
|
||||
const allActivities: ActivityItem[] = [
|
||||
...(submissions?.map(s => ({
|
||||
id: s.id,
|
||||
type: 'submission' as const,
|
||||
action: s.status as 'approved' | 'rejected',
|
||||
entity_type: s.submission_type,
|
||||
timestamp: s.reviewed_at!,
|
||||
moderator_id: s.reviewer_id,
|
||||
moderator: s.reviewer_id ? profileMap.get(s.reviewer_id) : undefined,
|
||||
})) || []),
|
||||
...(reports?.map(r => ({
|
||||
id: r.id,
|
||||
type: 'report' as const,
|
||||
action: r.status as 'reviewed' | 'dismissed',
|
||||
entity_type: r.reported_entity_type,
|
||||
timestamp: r.reviewed_at!,
|
||||
moderator_id: r.reviewed_by,
|
||||
moderator: r.reviewed_by ? profileMap.get(r.reviewed_by) : undefined,
|
||||
})) || []),
|
||||
...(reviews?.map(r => ({
|
||||
id: r.id,
|
||||
type: 'review' as const,
|
||||
action: r.moderation_status as 'approved' | 'rejected' | 'flagged',
|
||||
timestamp: r.moderated_at!,
|
||||
moderator_id: r.moderated_by,
|
||||
moderator: r.moderated_by ? profileMap.get(r.moderated_by) : undefined,
|
||||
})) || []),
|
||||
];
|
||||
|
||||
// Sort by timestamp (newest first)
|
||||
allActivities.sort((a, b) =>
|
||||
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
|
||||
);
|
||||
|
||||
const recentActivities = allActivities.slice(0, 20); // Keep top 20 most recent
|
||||
|
||||
// Use smart merging for silent refreshes if strategy is 'merge'
|
||||
if (silent && refreshStrategy === 'merge') {
|
||||
const mergeResult = smartMergeArray(activities, recentActivities, {
|
||||
compareFields: ['timestamp', 'action'],
|
||||
preserveOrder: false,
|
||||
addToTop: true,
|
||||
});
|
||||
|
||||
if (mergeResult.hasChanges) {
|
||||
setActivities(mergeResult.items);
|
||||
}
|
||||
} else {
|
||||
// Full replacement for non-silent refreshes or 'replace' strategy
|
||||
setActivities(recentActivities);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
handleError(error, {
|
||||
action: 'Load Recent Activity',
|
||||
userId: user?.id
|
||||
});
|
||||
} finally {
|
||||
if (!silent) {
|
||||
setLoading(false);
|
||||
}
|
||||
setIsSilentRefresh(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchRecentActivity(false);
|
||||
}, [user]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
@@ -19,8 +19,10 @@ import {
|
||||
} from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useReportMutation } from '@/hooks/reports/useReportMutation';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { getErrorMessage } from '@/lib/errorHandler';
|
||||
|
||||
interface ReportButtonProps {
|
||||
entityType: 'review' | 'profile' | 'content_submission';
|
||||
@@ -40,23 +42,42 @@ export function ReportButton({ entityType, entityId, className }: ReportButtonPr
|
||||
const [open, setOpen] = useState(false);
|
||||
const [reportType, setReportType] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { user } = useAuth();
|
||||
|
||||
const reportMutation = useReportMutation();
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
if (!user || !reportType) return;
|
||||
|
||||
reportMutation.mutate(
|
||||
{ entityType, entityId, reportType, reason },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setOpen(false);
|
||||
setReportType('');
|
||||
setReason('');
|
||||
},
|
||||
}
|
||||
);
|
||||
setLoading(true);
|
||||
try {
|
||||
const { error } = await supabase.from('reports').insert({
|
||||
reporter_id: user.id,
|
||||
reported_entity_type: entityType,
|
||||
reported_entity_id: entityId,
|
||||
report_type: reportType,
|
||||
reason: reason.trim() || null,
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
toast({
|
||||
title: "Report Submitted",
|
||||
description: "Thank you for your report. We'll review it shortly.",
|
||||
});
|
||||
|
||||
setOpen(false);
|
||||
setReportType('');
|
||||
setReason('');
|
||||
} catch (error: unknown) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: getErrorMessage(error),
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!user) return null;
|
||||
@@ -115,10 +136,10 @@ export function ReportButton({ entityType, entityId, className }: ReportButtonPr
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!reportType || reportMutation.isPending}
|
||||
disabled={!reportType || loading}
|
||||
variant="destructive"
|
||||
>
|
||||
{reportMutation.isPending ? 'Submitting...' : 'Submit Report'}
|
||||
{loading ? 'Submitting...' : 'Submit Report'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -24,7 +24,6 @@ import { useAuth } from '@/hooks/useAuth';
|
||||
import { useIsMobile } from '@/hooks/use-mobile';
|
||||
import { smartMergeArray } from '@/lib/smartStateUpdate';
|
||||
import { handleError, handleSuccess } from '@/lib/errorHandler';
|
||||
import { useReportActionMutation } from '@/hooks/reports/useReportActionMutation';
|
||||
|
||||
// Type-safe reported content interfaces
|
||||
interface ReportedReview {
|
||||
@@ -116,7 +115,6 @@ export const ReportsQueue = forwardRef<ReportsQueueRef>((props, ref) => {
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||
const [newReportsCount, setNewReportsCount] = useState(0);
|
||||
const { user } = useAuth();
|
||||
const { resolveReport, isResolving } = useReportActionMutation();
|
||||
|
||||
// Pagination state
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
@@ -348,29 +346,67 @@ export const ReportsQueue = forwardRef<ReportsQueueRef>((props, ref) => {
|
||||
};
|
||||
}, [user, refreshMode, pollInterval, isInitialLoad]);
|
||||
|
||||
const handleReportAction = (reportId: string, action: 'reviewed' | 'dismissed') => {
|
||||
const handleReportAction = async (reportId: string, action: 'reviewed' | 'dismissed') => {
|
||||
setActionLoading(reportId);
|
||||
|
||||
resolveReport.mutate(
|
||||
{ reportId, action },
|
||||
{
|
||||
onSuccess: () => {
|
||||
// Remove report from queue
|
||||
setReports(prev => {
|
||||
const newReports = prev.filter(r => r.id !== reportId);
|
||||
// If last item on page and not page 1, go to previous page
|
||||
if (newReports.length === 0 && currentPage > 1) {
|
||||
setCurrentPage(prev => prev - 1);
|
||||
try {
|
||||
// Fetch full report details including reporter_id for audit log
|
||||
const { data: reportData } = await supabase
|
||||
.from('reports')
|
||||
.select('reporter_id, reported_entity_type, reported_entity_id, reason')
|
||||
.eq('id', reportId)
|
||||
.single();
|
||||
|
||||
const { error } = await supabase
|
||||
.from('reports')
|
||||
.update({
|
||||
status: action,
|
||||
reviewed_by: user?.id,
|
||||
reviewed_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', reportId);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
// Log audit trail for report resolution
|
||||
if (user && reportData) {
|
||||
try {
|
||||
await supabase.rpc('log_admin_action', {
|
||||
_admin_user_id: user.id,
|
||||
_target_user_id: reportData.reporter_id,
|
||||
_action: action === 'reviewed' ? 'report_resolved' : 'report_dismissed',
|
||||
_details: {
|
||||
report_id: reportId,
|
||||
reported_entity_type: reportData.reported_entity_type,
|
||||
reported_entity_id: reportData.reported_entity_id,
|
||||
report_reason: reportData.reason,
|
||||
action: action
|
||||
}
|
||||
return newReports;
|
||||
});
|
||||
setActionLoading(null);
|
||||
},
|
||||
onError: () => {
|
||||
setActionLoading(null);
|
||||
} catch (auditError) {
|
||||
console.error('Failed to log report action audit:', auditError);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
handleSuccess(`Report ${action}`, `The report has been marked as ${action}`);
|
||||
|
||||
// Remove report from queue
|
||||
setReports(prev => {
|
||||
const newReports = prev.filter(r => r.id !== reportId);
|
||||
// If last item on page and not page 1, go to previous page
|
||||
if (newReports.length === 0 && currentPage > 1) {
|
||||
setCurrentPage(prev => prev - 1);
|
||||
}
|
||||
return newReports;
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
handleError(error, {
|
||||
action: `${action === 'reviewed' ? 'Resolve' : 'Dismiss'} Report`,
|
||||
userId: user?.id,
|
||||
metadata: { reportId, action }
|
||||
});
|
||||
} finally {
|
||||
setActionLoading(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Sort reports function
|
||||
|
||||
@@ -9,11 +9,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useUserRole } from '@/hooks/useUserRole';
|
||||
import { handleError, getErrorMessage } from '@/lib/errorHandler';
|
||||
import { handleError, handleSuccess, getErrorMessage } from '@/lib/errorHandler';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { useUserRoles } from '@/hooks/users/useUserRoles';
|
||||
import { useUserSearch } from '@/hooks/users/useUserSearch';
|
||||
import { useRoleMutations } from '@/hooks/users/useRoleMutations';
|
||||
|
||||
// Type-safe role definitions
|
||||
const VALID_ROLES = ['admin', 'moderator', 'user'] as const;
|
||||
@@ -55,36 +52,175 @@ interface UserRole {
|
||||
};
|
||||
}
|
||||
export function UserRoleManager() {
|
||||
const [userRoles, setUserRoles] = useState<UserRole[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [newUserSearch, setNewUserSearch] = useState('');
|
||||
const [newRole, setNewRole] = useState('');
|
||||
const [selectedUsers, setSelectedUsers] = useState<ProfileSearchResult[]>([]);
|
||||
|
||||
const { user } = useAuth();
|
||||
const { isAdmin, isSuperuser } = useUserRole();
|
||||
const { data: userRoles = [], isLoading: loading } = useUserRoles();
|
||||
const { data: searchResults = [] } = useUserSearch(newUserSearch);
|
||||
const { grantRole, revokeRole } = useRoleMutations();
|
||||
const handleGrantRole = () => {
|
||||
const selectedUser = selectedUsers[0];
|
||||
if (!selectedUser || !newRole || !isValidRole(newRole)) return;
|
||||
const [searchResults, setSearchResults] = useState<ProfileSearchResult[]>([]);
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||
const {
|
||||
user
|
||||
} = useAuth();
|
||||
const {
|
||||
isAdmin,
|
||||
isSuperuser,
|
||||
permissions
|
||||
} = useUserRole();
|
||||
const fetchUserRoles = async () => {
|
||||
try {
|
||||
const {
|
||||
data,
|
||||
error
|
||||
} = await supabase.from('user_roles').select(`
|
||||
id,
|
||||
user_id,
|
||||
role,
|
||||
granted_at
|
||||
`).order('granted_at', {
|
||||
ascending: false
|
||||
});
|
||||
if (error) throw error;
|
||||
|
||||
grantRole.mutate(
|
||||
{ userId: selectedUser.user_id, role: newRole },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setNewUserSearch('');
|
||||
setNewRole('');
|
||||
setSelectedUsers([]);
|
||||
},
|
||||
// Get unique user IDs
|
||||
const userIds = [...new Set((data || []).map(r => r.user_id))];
|
||||
|
||||
// Fetch user profiles with emails (for admins)
|
||||
let profiles: Array<{ user_id: string; username: string; display_name?: string }> | null = null;
|
||||
const { data: allProfiles, error: rpcError } = await supabase
|
||||
.rpc('get_users_with_emails');
|
||||
|
||||
if (rpcError) {
|
||||
logger.warn('Failed to fetch users with emails, using basic profiles', { error: getErrorMessage(rpcError) });
|
||||
const { data: basicProfiles } = await supabase
|
||||
.from('profiles')
|
||||
.select('user_id, username, display_name')
|
||||
.in('user_id', userIds);
|
||||
profiles = basicProfiles as typeof profiles;
|
||||
} else {
|
||||
profiles = allProfiles?.filter(p => userIds.includes(p.user_id)) || null;
|
||||
}
|
||||
);
|
||||
};
|
||||
const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []);
|
||||
|
||||
const handleRevokeRole = (roleId: string) => {
|
||||
revokeRole.mutate({ roleId });
|
||||
// Combine data with profiles
|
||||
const userRolesWithProfiles = (data || []).map(role => ({
|
||||
...role,
|
||||
profiles: profileMap.get(role.user_id)
|
||||
}));
|
||||
setUserRoles(userRolesWithProfiles);
|
||||
} catch (error: unknown) {
|
||||
handleError(error, {
|
||||
action: 'Load User Roles',
|
||||
userId: user?.id
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const searchUsers = async (search: string) => {
|
||||
if (!search.trim()) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let data;
|
||||
const { data: allUsers, error: rpcError } = await supabase
|
||||
.rpc('get_users_with_emails');
|
||||
|
||||
if (rpcError) {
|
||||
logger.warn('Failed to fetch users with emails, using basic profiles', { error: getErrorMessage(rpcError) });
|
||||
const { data: basicProfiles, error: profilesError } = await supabase
|
||||
.from('profiles')
|
||||
.select('user_id, username, display_name')
|
||||
.ilike('username', `%${search}%`);
|
||||
|
||||
if (profilesError) throw profilesError;
|
||||
data = basicProfiles?.slice(0, 10);
|
||||
} else {
|
||||
// Filter by search term
|
||||
data = allUsers?.filter(user =>
|
||||
user.username.toLowerCase().includes(search.toLowerCase()) ||
|
||||
user.display_name?.toLowerCase().includes(search.toLowerCase())
|
||||
).slice(0, 10);
|
||||
}
|
||||
|
||||
// Filter out users who already have roles
|
||||
const existingUserIds = userRoles.map(ur => ur.user_id);
|
||||
const filteredResults = (data || []).filter(profile => !existingUserIds.includes(profile.user_id));
|
||||
setSearchResults(filteredResults);
|
||||
} catch (error: unknown) {
|
||||
logger.error('User search failed', { error: getErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
fetchUserRoles();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const debounceTimer = setTimeout(() => {
|
||||
searchUsers(newUserSearch);
|
||||
}, 300);
|
||||
return () => clearTimeout(debounceTimer);
|
||||
}, [newUserSearch, userRoles]);
|
||||
const grantRole = async (userId: string, role: ValidRole) => {
|
||||
if (!isAdmin()) return;
|
||||
|
||||
// Double-check role validity before database operation
|
||||
if (!isValidRole(role)) {
|
||||
handleError(new Error('Invalid role'), {
|
||||
action: 'Grant Role',
|
||||
userId: user?.id,
|
||||
metadata: { targetUserId: userId, attemptedRole: role }
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setActionLoading('grant');
|
||||
try {
|
||||
const {
|
||||
error
|
||||
} = await supabase.from('user_roles').insert([{
|
||||
user_id: userId,
|
||||
role,
|
||||
granted_by: user?.id
|
||||
}]);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
handleSuccess('Role Granted', `User has been granted ${getRoleLabel(role)} role`);
|
||||
setNewUserSearch('');
|
||||
setNewRole('');
|
||||
setSearchResults([]);
|
||||
fetchUserRoles();
|
||||
} catch (error: unknown) {
|
||||
handleError(error, {
|
||||
action: 'Grant Role',
|
||||
userId: user?.id,
|
||||
metadata: { targetUserId: userId, role }
|
||||
});
|
||||
} finally {
|
||||
setActionLoading(null);
|
||||
}
|
||||
};
|
||||
const revokeRole = async (roleId: string) => {
|
||||
if (!isAdmin()) return;
|
||||
setActionLoading(roleId);
|
||||
try {
|
||||
const {
|
||||
error
|
||||
} = await supabase.from('user_roles').delete().eq('id', roleId);
|
||||
if (error) throw error;
|
||||
handleSuccess('Role Revoked', 'User role has been revoked');
|
||||
fetchUserRoles();
|
||||
} catch (error: unknown) {
|
||||
handleError(error, {
|
||||
action: 'Revoke Role',
|
||||
userId: user?.id,
|
||||
metadata: { roleId }
|
||||
});
|
||||
} finally {
|
||||
setActionLoading(null);
|
||||
}
|
||||
};
|
||||
if (!isAdmin()) {
|
||||
return <div className="text-center py-8">
|
||||
<Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||
@@ -99,17 +235,7 @@ export function UserRoleManager() {
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>;
|
||||
}
|
||||
// Filter existing user IDs for search results
|
||||
const existingUserIds = userRoles.map(ur => ur.user_id);
|
||||
const availableSearchResults = searchResults.filter(
|
||||
profile => !existingUserIds.includes(profile.user_id)
|
||||
);
|
||||
|
||||
const filteredRoles = userRoles.filter(
|
||||
role =>
|
||||
role.username?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
role.display_name?.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
const filteredRoles = userRoles.filter(role => role.profiles?.username?.toLowerCase().includes(searchTerm.toLowerCase()) || role.profiles?.display_name?.toLowerCase().includes(searchTerm.toLowerCase()) || role.role.toLowerCase().includes(searchTerm.toLowerCase()));
|
||||
return <div className="space-y-6">
|
||||
{/* Add new role */}
|
||||
<Card>
|
||||
@@ -123,10 +249,10 @@ export function UserRoleManager() {
|
||||
<Input id="user-search" placeholder="Search by username or display name..." value={newUserSearch} onChange={e => setNewUserSearch(e.target.value)} className="pl-10" />
|
||||
</div>
|
||||
|
||||
{availableSearchResults.length > 0 && <div className="mt-2 border rounded-lg bg-background">
|
||||
{availableSearchResults.map(profile => <div key={profile.user_id} className="p-3 hover:bg-muted/50 cursor-pointer border-b last:border-b-0" onClick={() => {
|
||||
{searchResults.length > 0 && <div className="mt-2 border rounded-lg bg-background">
|
||||
{searchResults.map(profile => <div key={profile.user_id} className="p-3 hover:bg-muted/50 cursor-pointer border-b last:border-b-0" onClick={() => {
|
||||
setNewUserSearch(profile.display_name || profile.username);
|
||||
setSelectedUsers([profile]);
|
||||
setSearchResults([profile]);
|
||||
}}>
|
||||
<div className="font-medium">
|
||||
{profile.display_name || profile.username}
|
||||
@@ -152,13 +278,23 @@ export function UserRoleManager() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGrantRole}
|
||||
disabled={!newRole || !isValidRole(newRole) || selectedUsers.length === 0 || grantRole.isPending}
|
||||
className="w-full md:w-auto"
|
||||
>
|
||||
<UserPlus className="w-4 h-4 mr-2" />
|
||||
{grantRole.isPending ? 'Granting...' : 'Grant Role'}
|
||||
<Button onClick={() => {
|
||||
const selectedUser = searchResults.find(p => (p.display_name || p.username) === newUserSearch);
|
||||
|
||||
// Type-safe validation before calling grantRole
|
||||
if (selectedUser && newRole && isValidRole(newRole)) {
|
||||
grantRole(selectedUser.user_id, newRole);
|
||||
} else if (selectedUser && newRole) {
|
||||
// This should never happen due to Select component constraints,
|
||||
// but provides safety in case of UI bugs
|
||||
handleError(new Error('Invalid role selected'), {
|
||||
action: 'Grant Role',
|
||||
userId: user?.id,
|
||||
metadata: { selectedUser: selectedUser?.user_id, newRole }
|
||||
});
|
||||
}
|
||||
}} disabled={!newRole || !isValidRole(newRole) || !searchResults.find(p => (p.display_name || p.username) === newUserSearch) || actionLoading === 'grant'} className="w-full md:w-auto">
|
||||
{actionLoading === 'grant' ? 'Granting...' : 'Grant Role'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -185,31 +321,21 @@ export function UserRoleManager() {
|
||||
<div className="flex items-center gap-3">
|
||||
<div>
|
||||
<div className="font-medium">
|
||||
{userRole.display_name || userRole.username}
|
||||
{userRole.profiles?.display_name || userRole.profiles?.username}
|
||||
</div>
|
||||
{userRole.display_name && <div className="text-sm text-muted-foreground">
|
||||
@{userRole.username}
|
||||
</div>}
|
||||
{userRole.email && <div className="text-xs text-muted-foreground">
|
||||
{userRole.email}
|
||||
{userRole.profiles?.display_name && <div className="text-sm text-muted-foreground">
|
||||
@{userRole.profiles.username}
|
||||
</div>}
|
||||
</div>
|
||||
<Badge variant={userRole.id === 'admin' ? 'default' : 'secondary'}>
|
||||
{getRoleLabel(userRole.id)}
|
||||
<Badge variant={userRole.role === 'admin' ? 'default' : 'secondary'}>
|
||||
{userRole.role}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Only show revoke button if current user can manage this role */}
|
||||
{(isSuperuser() || (isAdmin() && !['admin', 'superuser'].includes(userRole.id))) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleRevokeRole(userRole.id)}
|
||||
disabled={revokeRole.isPending}
|
||||
>
|
||||
{(isSuperuser() || isAdmin() && !['admin', 'superuser'].includes(userRole.role)) && <Button variant="outline" size="sm" onClick={() => revokeRole(userRole.id)} disabled={actionLoading === userRole.id}>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</Button>}
|
||||
</CardContent>
|
||||
</Card>)}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user