admin-users: implement complete admin users management
- Add admin users CRUD operations (list, create, edit, delete) - Implement proper API response structure handling (admin_user vs user) - Add form validation with conditional password requirement (optional in edit mode) - Create reusable hooks and request functions following established pattern - Add TypeScript interfaces and proper error handling - Include debug logging for API responses
This commit is contained in:
parent
174452d65d
commit
3f4aefb112
|
|
@ -0,0 +1,220 @@
|
|||
import React, { useEffect } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import * as yup from 'yup';
|
||||
import { useAdminUser, useCreateAdminUser, useUpdateAdminUser } from '../core/_hooks';
|
||||
import { AdminUserFormData } from '../core/_models';
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Input } from "@/components/ui/Input";
|
||||
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
|
||||
import { ArrowRight } from "lucide-react";
|
||||
|
||||
const adminUserSchema = yup.object({
|
||||
first_name: yup.string().required('نام الزامی است').min(2, 'نام باید حداقل 2 کاراکتر باشد'),
|
||||
last_name: yup.string().required('نام خانوادگی الزامی است').min(2, 'نام خانوادگی باید حداقل 2 کاراکتر باشد'),
|
||||
username: yup.string().required('نام کاربری الزامی است').min(3, 'نام کاربری باید حداقل 3 کاراکتر باشد'),
|
||||
password: yup.string().when('isEdit', {
|
||||
is: false,
|
||||
then: (schema) => schema.required('رمز عبور الزامی است').min(8, 'رمز عبور باید حداقل 8 کاراکتر باشد'),
|
||||
otherwise: (schema) => schema.notRequired().test('min-length', 'رمز عبور باید حداقل 8 کاراکتر باشد', function (value) {
|
||||
return !value || value.length >= 8;
|
||||
})
|
||||
}),
|
||||
status: yup.string().required('وضعیت الزامی است').oneOf(['active', 'deactive'], 'وضعیت نامعتبر است'),
|
||||
isEdit: yup.boolean().default(false)
|
||||
});
|
||||
|
||||
const AdminUserFormPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const isEdit = !!id;
|
||||
|
||||
const { data: user, isLoading: isLoadingUser } = useAdminUser(id || '', isEdit);
|
||||
const { mutate: createUser, isPending: isCreating } = useCreateAdminUser();
|
||||
const { mutate: updateUser, isPending: isUpdating } = useUpdateAdminUser();
|
||||
|
||||
const isLoading = isCreating || isUpdating;
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isValid, isDirty },
|
||||
setValue,
|
||||
watch
|
||||
} = useForm<AdminUserFormData>({
|
||||
resolver: yupResolver(adminUserSchema) as any,
|
||||
mode: 'onChange',
|
||||
defaultValues: {
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
username: '',
|
||||
password: '',
|
||||
status: 'active' as 'active' | 'deactive',
|
||||
isEdit: isEdit
|
||||
}
|
||||
});
|
||||
|
||||
// Debug form state
|
||||
const formValues = watch();
|
||||
console.log('🔍 Current form values:', formValues);
|
||||
console.log('🔍 Form isValid:', isValid);
|
||||
console.log('🔍 Form isDirty:', isDirty);
|
||||
console.log('🔍 Form errors:', errors);
|
||||
|
||||
// Populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEdit && user) {
|
||||
setValue('first_name', user.first_name, { shouldValidate: true });
|
||||
setValue('last_name', user.last_name, { shouldValidate: true });
|
||||
setValue('username', user.username, { shouldValidate: true });
|
||||
setValue('status', user.status, { shouldValidate: true });
|
||||
setValue('isEdit', true, { shouldValidate: true });
|
||||
}
|
||||
}, [isEdit, user, setValue]);
|
||||
|
||||
const onSubmit = (data: AdminUserFormData) => {
|
||||
if (isEdit && id) {
|
||||
updateUser({
|
||||
id,
|
||||
userData: {
|
||||
id: parseInt(id),
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name,
|
||||
username: data.username,
|
||||
password: data.password && data.password.trim() ? data.password : undefined,
|
||||
status: data.status
|
||||
}
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
navigate('/admin-users');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log('🚀 Creating new admin user...');
|
||||
createUser({
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name,
|
||||
username: data.username,
|
||||
password: data.password || '',
|
||||
status: data.status
|
||||
}, {
|
||||
onSuccess: (result) => {
|
||||
console.log('✅ Admin user created successfully:', result);
|
||||
console.log('🔄 Navigating to admin users list...');
|
||||
navigate('/admin-users');
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('❌ Error in component onError:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
navigate('/admin-users');
|
||||
};
|
||||
|
||||
if (isEdit && isLoadingUser) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={handleBack}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
بازگشت
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
{isEdit ? 'ویرایش کاربر ادمین' : 'ایجاد کاربر ادمین جدید'}
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">
|
||||
{isEdit ? 'ویرایش اطلاعات کاربر ادمین' : 'اطلاعات کاربر ادمین جدید را وارد کنید'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<Input
|
||||
label="نام"
|
||||
{...register('first_name')}
|
||||
error={errors.first_name?.message}
|
||||
placeholder="نام کاربر"
|
||||
/>
|
||||
<Input
|
||||
label="نام خانوادگی"
|
||||
{...register('last_name')}
|
||||
error={errors.last_name?.message}
|
||||
placeholder="نام خانوادگی کاربر"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="نام کاربری"
|
||||
{...register('username')}
|
||||
error={errors.username?.message}
|
||||
placeholder="نام کاربری"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={isEdit ? "رمز عبور (اختیاری)" : "رمز عبور"}
|
||||
type="password"
|
||||
{...register('password')}
|
||||
error={errors.password?.message}
|
||||
placeholder={isEdit ? "رمز عبور جدید (در صورت تمایل به تغییر)" : "رمز عبور"}
|
||||
/>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
وضعیت
|
||||
</label>
|
||||
<select
|
||||
{...register('status')}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
|
||||
>
|
||||
<option value="active">فعال</option>
|
||||
<option value="deactive">غیرفعال</option>
|
||||
</select>
|
||||
{errors.status && (
|
||||
<p className="text-red-500 text-sm mt-1">{errors.status.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-4 space-x-reverse pt-6 border-t border-gray-200 dark:border-gray-600">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handleBack}
|
||||
disabled={isLoading}
|
||||
>
|
||||
انصراف
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={isLoading}
|
||||
disabled={!isValid || isLoading}
|
||||
>
|
||||
{isEdit ? 'بهروزرسانی' : 'ایجاد'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminUserFormPage;
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAdminUsers, useDeleteAdminUser } from '../core/_hooks';
|
||||
import { AdminUserInfo } from '../core/_models';
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { LoadingSpinner } from "@/components/ui/LoadingSpinner";
|
||||
import { Trash2, Edit3, Plus, Eye, Users, UserPlus } from "lucide-react";
|
||||
import { Modal } from "@/components/ui/Modal";
|
||||
|
||||
const AdminUsersListPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const [deleteUserId, setDeleteUserId] = useState<string | null>(null);
|
||||
const [filters, setFilters] = useState({
|
||||
search: '',
|
||||
status: ''
|
||||
});
|
||||
|
||||
const { data: users, isLoading, error } = useAdminUsers(filters);
|
||||
const { mutate: deleteUser, isPending: isDeleting } = useDeleteAdminUser();
|
||||
|
||||
const handleCreate = () => {
|
||||
navigate('/admin-users/create');
|
||||
};
|
||||
|
||||
const handleView = (userId: number) => {
|
||||
navigate(`/admin-users/${userId}`);
|
||||
};
|
||||
|
||||
const handleEdit = (userId: number) => {
|
||||
navigate(`/admin-users/${userId}/edit`);
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = () => {
|
||||
if (deleteUserId) {
|
||||
deleteUser(deleteUserId, {
|
||||
onSuccess: () => {
|
||||
setDeleteUserId(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFilters(prev => ({ ...prev, search: e.target.value }));
|
||||
};
|
||||
|
||||
const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
setFilters(prev => ({ ...prev, status: e.target.value }));
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-red-600 dark:text-red-400">خطا در بارگذاری کاربران ادمین</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
مدیریت کاربران ادمین
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">
|
||||
مدیریت کاربران ادمین سیستم
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleCreate}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<UserPlus className="h-4 w-4" />
|
||||
کاربر جدید
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white dark:bg-gray-800 p-4 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
جستجو
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={filters.search}
|
||||
onChange={handleSearchChange}
|
||||
placeholder="نام، نام کاربری یا نام خانوادگی..."
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
وضعیت
|
||||
</label>
|
||||
<select
|
||||
value={filters.status}
|
||||
onChange={handleStatusChange}
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
|
||||
>
|
||||
<option value="">همه</option>
|
||||
<option value="active">فعال</option>
|
||||
<option value="deactive">غیرفعال</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Users Table */}
|
||||
<div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
{(users || []).length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<Users className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
|
||||
هیچ کاربر ادمین یافت نشد
|
||||
</h3>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-4">
|
||||
شما هنوز هیچ کاربر ادمین ایجاد نکردهاید
|
||||
</p>
|
||||
<Button onClick={handleCreate}>
|
||||
<UserPlus className="h-4 w-4 ml-2" />
|
||||
اولین کاربر ادمین را ایجاد کنید
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50 dark:bg-gray-700">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
کاربر
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
نام کاربری
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
وضعیت
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
نقشها
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
تاریخ ایجاد
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
|
||||
عملیات
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{(users || []).map((user: AdminUserInfo) => (
|
||||
<tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="flex items-center">
|
||||
<div className="h-10 w-10 rounded-full bg-primary-100 dark:bg-primary-800 flex items-center justify-center">
|
||||
<span className="text-sm font-medium text-primary-600 dark:text-primary-300">
|
||||
{user.first_name?.[0]}{user.last_name?.[0]}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mr-4">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
{user.first_name} {user.last_name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
|
||||
{user.username}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${user.status === 'active'
|
||||
? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100'
|
||||
: 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100'
|
||||
}`}>
|
||||
{user.status === 'active' ? 'فعال' : 'غیرفعال'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-100">
|
||||
{user.roles?.length || 0} نقش
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
||||
{new Date(user.created_at).toLocaleDateString('fa-IR')}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2 space-x-reverse">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => handleView(user.id)}
|
||||
className="ml-2"
|
||||
>
|
||||
<Eye className="h-4 w-4 ml-1" />
|
||||
مشاهده
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(user.id)}
|
||||
className="ml-2"
|
||||
>
|
||||
<Edit3 className="h-4 w-4 ml-1" />
|
||||
ویرایش
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => setDeleteUserId(user.id.toString())}
|
||||
className="ml-2"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 ml-1" />
|
||||
حذف
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Delete Confirmation Modal */}
|
||||
<Modal
|
||||
isOpen={!!deleteUserId}
|
||||
onClose={() => setDeleteUserId(null)}
|
||||
title="حذف کاربر ادمین"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
آیا از حذف این کاربر ادمین اطمینان دارید؟ این عمل قابل بازگشت نیست.
|
||||
</p>
|
||||
<div className="flex justify-end space-x-2 space-x-reverse">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
disabled={isDeleting}
|
||||
>
|
||||
انصراف
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={handleDeleteConfirm}
|
||||
loading={isDeleting}
|
||||
>
|
||||
حذف
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminUsersListPage;
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
import { QUERY_KEYS } from "@/utils/query-key";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
getAdminUsers,
|
||||
getAdminUser,
|
||||
createAdminUser,
|
||||
updateAdminUser,
|
||||
deleteAdminUser,
|
||||
} from "./_requests";
|
||||
import {
|
||||
CreateAdminUserRequest,
|
||||
UpdateAdminUserRequest,
|
||||
AdminUserFilters,
|
||||
} from "./_models";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
export const useAdminUsers = (filters?: AdminUserFilters) => {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEYS.GET_ADMIN_USERS, filters],
|
||||
queryFn: () => getAdminUsers(filters),
|
||||
});
|
||||
};
|
||||
|
||||
export const useAdminUser = (id: string, enabled: boolean = true) => {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEYS.GET_ADMIN_USER, id],
|
||||
queryFn: () => getAdminUser(id),
|
||||
enabled: enabled && !!id,
|
||||
});
|
||||
};
|
||||
|
||||
export const useCreateAdminUser = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: [QUERY_KEYS.CREATE_ADMIN_USER],
|
||||
mutationFn: (userData: CreateAdminUserRequest) => createAdminUser(userData),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_USERS] });
|
||||
toast.success("کاربر ادمین با موفقیت ایجاد شد");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Create admin user error:", error);
|
||||
toast.error(error?.message || "خطا در ایجاد کاربر ادمین");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateAdminUser = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: [QUERY_KEYS.UPDATE_ADMIN_USER],
|
||||
mutationFn: ({
|
||||
id,
|
||||
userData,
|
||||
}: {
|
||||
id: string;
|
||||
userData: UpdateAdminUserRequest;
|
||||
}) => updateAdminUser(id, userData),
|
||||
onSuccess: (data, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_USERS] });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [QUERY_KEYS.GET_ADMIN_USER, variables.id],
|
||||
});
|
||||
toast.success("کاربر ادمین با موفقیت بهروزرسانی شد");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Update admin user error:", error);
|
||||
toast.error(error?.message || "خطا در بهروزرسانی کاربر ادمین");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useDeleteAdminUser = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationKey: [QUERY_KEYS.DELETE_ADMIN_USER],
|
||||
mutationFn: (id: string) => deleteAdminUser(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_ADMIN_USERS] });
|
||||
toast.success("کاربر ادمین با موفقیت حذف شد");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Delete admin user error:", error);
|
||||
toast.error(error?.message || "خطا در حذف کاربر ادمین");
|
||||
},
|
||||
});
|
||||
};
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import {
|
||||
AdminUserInfo,
|
||||
CreateAdminUserRequest,
|
||||
UpdateAdminUserRequest,
|
||||
} from "@/types/auth";
|
||||
|
||||
export interface AdminUserFormData {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
username: string;
|
||||
password?: string;
|
||||
status: "active" | "deactive";
|
||||
isEdit: boolean;
|
||||
}
|
||||
|
||||
export interface AdminUserFilters {
|
||||
search?: string;
|
||||
status?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface AdminUsersResponse {
|
||||
users: AdminUserInfo[] | null;
|
||||
}
|
||||
|
||||
export interface AdminUserResponse {
|
||||
user: AdminUserInfo;
|
||||
}
|
||||
|
||||
export interface CreateAdminUserResponse {
|
||||
user: AdminUserInfo;
|
||||
}
|
||||
|
||||
export interface UpdateAdminUserResponse {
|
||||
user: AdminUserInfo;
|
||||
}
|
||||
|
||||
export interface DeleteAdminUserResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Export types for easier access
|
||||
export type {
|
||||
AdminUserInfo,
|
||||
CreateAdminUserRequest,
|
||||
UpdateAdminUserRequest,
|
||||
} from "@/types/auth";
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
import {
|
||||
httpGetRequest,
|
||||
httpPostRequest,
|
||||
httpPutRequest,
|
||||
httpDeleteRequest,
|
||||
APIUrlGenerator,
|
||||
} from "@/utils/baseHttpService";
|
||||
import { API_ROUTES } from "@/constant/routes";
|
||||
import {
|
||||
AdminUserInfo,
|
||||
CreateAdminUserRequest,
|
||||
UpdateAdminUserRequest,
|
||||
AdminUsersResponse,
|
||||
AdminUserResponse,
|
||||
CreateAdminUserResponse,
|
||||
UpdateAdminUserResponse,
|
||||
DeleteAdminUserResponse,
|
||||
AdminUserFilters,
|
||||
} from "./_models";
|
||||
|
||||
export const getAdminUsers = async (filters?: AdminUserFilters) => {
|
||||
try {
|
||||
const queryParams: Record<string, string | number | null> = {};
|
||||
|
||||
if (filters?.search) queryParams.search = filters.search;
|
||||
if (filters?.status) queryParams.status = filters.status;
|
||||
if (filters?.page) queryParams.page = filters.page;
|
||||
if (filters?.limit) queryParams.limit = filters.limit;
|
||||
|
||||
const url = APIUrlGenerator(API_ROUTES.GET_ADMIN_USERS, queryParams);
|
||||
console.log("🔍 Admin Users URL:", url);
|
||||
console.log("🔍 API_ROUTES.GET_ADMIN_USERS:", API_ROUTES.GET_ADMIN_USERS);
|
||||
|
||||
const response = await httpGetRequest<AdminUsersResponse>(url);
|
||||
|
||||
console.log("Admin Users API Response:", response);
|
||||
console.log("Admin Users data:", response.data);
|
||||
|
||||
// Handle different response structures
|
||||
if (response.data && (response.data as any).admin_users) {
|
||||
return Array.isArray((response.data as any).admin_users)
|
||||
? (response.data as any).admin_users
|
||||
: [];
|
||||
}
|
||||
|
||||
if (response.data && response.data.users) {
|
||||
return Array.isArray(response.data.users) ? response.data.users : [];
|
||||
}
|
||||
|
||||
if (response.data && Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error("Error fetching admin users:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getAdminUser = async (id: string) => {
|
||||
try {
|
||||
const response = await httpGetRequest<AdminUserResponse>(
|
||||
APIUrlGenerator(API_ROUTES.GET_ADMIN_USER(id))
|
||||
);
|
||||
|
||||
console.log("Get Admin User API Response:", response);
|
||||
console.log("Get Admin User data:", response.data);
|
||||
|
||||
if (response.data && (response.data as any).admin_user) {
|
||||
return (response.data as any).admin_user;
|
||||
}
|
||||
|
||||
if (response.data && response.data.user) {
|
||||
return response.data.user;
|
||||
}
|
||||
|
||||
throw new Error("Failed to get admin user");
|
||||
} catch (error) {
|
||||
console.error("Error getting admin user:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const createAdminUser = async (userData: CreateAdminUserRequest) => {
|
||||
try {
|
||||
console.log("🚀 Creating admin user with data:", userData);
|
||||
|
||||
const response = await httpPostRequest<CreateAdminUserResponse>(
|
||||
APIUrlGenerator(API_ROUTES.CREATE_ADMIN_USER),
|
||||
userData
|
||||
);
|
||||
|
||||
console.log("✅ Create Admin User API Response:", response);
|
||||
console.log("📊 Response data:", response.data);
|
||||
|
||||
if (response.data && (response.data as any).admin_user) {
|
||||
console.log("✅ Returning admin_user from response");
|
||||
return (response.data as any).admin_user;
|
||||
}
|
||||
|
||||
if (response.data && response.data.user) {
|
||||
console.log("✅ Returning user from response");
|
||||
return response.data.user;
|
||||
}
|
||||
|
||||
console.log("⚠️ Response structure unexpected, throwing error");
|
||||
throw new Error("Failed to create admin user");
|
||||
} catch (error) {
|
||||
console.error("❌ Error creating admin user:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateAdminUser = async (
|
||||
id: string,
|
||||
userData: UpdateAdminUserRequest
|
||||
) => {
|
||||
try {
|
||||
const response = await httpPutRequest<UpdateAdminUserResponse>(
|
||||
APIUrlGenerator(API_ROUTES.UPDATE_ADMIN_USER(id)),
|
||||
userData
|
||||
);
|
||||
|
||||
console.log("Update Admin User API Response:", response);
|
||||
console.log("Update Admin User data:", response.data);
|
||||
|
||||
if (response.data && (response.data as any).admin_user) {
|
||||
return (response.data as any).admin_user;
|
||||
}
|
||||
|
||||
if (response.data && response.data.user) {
|
||||
return response.data.user;
|
||||
}
|
||||
|
||||
throw new Error("Failed to update admin user");
|
||||
} catch (error) {
|
||||
console.error("Error updating admin user:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteAdminUser = async (id: string) => {
|
||||
try {
|
||||
const response = await httpDeleteRequest<DeleteAdminUserResponse>(
|
||||
APIUrlGenerator(API_ROUTES.DELETE_ADMIN_USER(id))
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Error deleting admin user:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
Loading…
Reference in New Issue