File size: 6,314 Bytes
6711fd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { UserVerification, Permission, VerificationType, canAccessDashboard, canManageVerifications, canManageDevelopers } from '@/types/verification';
import { toast } from 'sonner';
export const useVerification = (userId?: string) => {
const { user } = useAuth();
const queryClient = useQueryClient();
const targetUserId = userId || user?.id;
// جلب بيانات التوثيق
const { data: verification, isLoading, error } = useQuery({
queryKey: ['verification', targetUserId],
queryFn: async () => {
if (!targetUserId) return null;
const { data, error } = await supabase
.from('user_verifications' as any)
.select('*')
.eq('user_id', targetUserId)
.maybeSingle();
if (error && error.code !== 'PGRST116') throw error;
return (data || null) as unknown as UserVerification | null;
},
enabled: !!targetUserId,
});
// تحديث التوثيق (للمالك فقط)
const updateVerification = useMutation({
mutationFn: async ({ userId, verificationType, reason }: {
userId: string;
verificationType: VerificationType;
reason?: string;
}) => {
if (!user) throw new Error('يجب تسجيل الدخول أولاً');
// التحقق من أن المستخدم الحالي هو المالك
const { data: currentVerification } = await supabase
.from('user_verifications' as any)
.select('*')
.eq('user_id', user.id)
.maybeSingle();
if ((currentVerification as any)?.verification_type !== 'owner') {
throw new Error('ليس لديك صلاحية لتعديل التوثيق');
}
// جلب بيانات المستخدم المراد توثيقه
const { data: targetUser } = await supabase
.from('profiles')
.select('username')
.eq('user_id', userId)
.single();
if (!targetUser) throw new Error('المستخدم غير موجود');
// تحديث أو إنشاء التوثيق
const { data, error } = await supabase
.from('user_verifications' as any)
.upsert({
user_id: userId,
username: targetUser.username,
verification_type: verificationType,
verified_at: new Date().toISOString(),
verified_by: user.id,
reason,
is_active: true,
permissions: getPermissionsForType(verificationType)
})
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['verification', (data as any).user_id] });
queryClient.invalidateQueries({ queryKey: ['developers'] });
toast.success('✓ تم تحديث التوثيق بنجاح');
},
onError: (error: any) => {
toast.error(error.message || 'حدث خطأ أثناء تحديث التوثيق');
}
});
// إلغاء التوثيق (للمالك فقط)
const revokeVerification = useMutation({
mutationFn: async (userId: string) => {
if (!user) throw new Error('يجب تسجيل الدخول أولاً');
// التحقق من أن المستخدم الحالي هو المالك
const { data: currentVerification } = await supabase
.from('user_verifications' as any)
.select('*')
.eq('user_id', user.id)
.maybeSingle();
if ((currentVerification as any)?.verification_type !== 'owner') {
throw new Error('ليس لديك صلاحية لإلغاء التوثيق');
}
const { error } = await supabase
.from('user_verifications' as any)
.update({ is_active: false })
.eq('user_id', userId);
if (error) throw error;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['verification'] });
queryClient.invalidateQueries({ queryKey: ['developers'] });
toast.success('✓ تم إلغاء التوثيق');
},
onError: (error: any) => {
toast.error(error.message || 'حدث خطأ أثناء إلغاء التوثيق');
}
});
// جلب قائمة المطورين (للمالك والمطورين فقط)
const { data: developers, isLoading: developersLoading } = useQuery({
queryKey: ['developers'],
queryFn: async () => {
if (!verification || !canAccessDashboard(verification)) {
return [];
}
const { data, error } = await supabase
.from('user_verifications' as any)
.select('*')
.eq('is_active', true)
.in('verification_type', ['owner', 'developer', 'addon_developer']);
if (error) throw error;
return data || [];
},
enabled: !!verification,
});
// التحقق من الصلاحيات
const hasPermission = (permission: Permission): boolean => {
return verification?.permissions.includes(permission) ?? false;
};
const canAccessDash = (): boolean => canAccessDashboard(verification);
const canManageVerif = (): boolean => canManageVerifications(verification);
const canManageDev = (): boolean => canManageDevelopers(verification);
return {
verification,
isLoading,
error,
developers,
developersLoading,
updateVerification,
revokeVerification,
hasPermission,
canAccessDash,
canManageVerif,
canManageDev,
};
};
// دالة مساعدة لجلب الصلاحيات حسب نوع التوثيق
function getPermissionsForType(type: VerificationType): Permission[] {
const permissionMap: Record<VerificationType, Permission[]> = {
owner: [
'manage_developers',
'manage_verifications',
'access_dashboard',
'manage_addons',
'manage_reviews',
'manage_users',
'view_analytics',
],
developer: [
'manage_verifications',
'access_dashboard',
'manage_addons',
'manage_reviews',
'view_analytics',
'view_dashboard'
],
addon_developer: [
'edit_addon_info',
'upload_addon',
'view_dashboard'
],
user: []
};
return permissionMap[type];
}
|