fx-1 / src /hooks /useVerification.ts
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
6.31 kB
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];
}