From 983b003abf1c3edc9bb99a63b0a43979cf4e309c Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Fri, 26 Jun 2026 21:00:51 +0300 Subject: [PATCH] updated users page --- src/api/users.ts | 8 +- src/components/CopyRolesModal.tsx | 123 ++++++++++++ src/components/UserEditModal.tsx | 269 +++++++++++++++++---------- src/features/users/hooks/useUsers.ts | 24 +++ src/pages/users/UsersPage.tsx | 133 ++++++++++--- src/types/api.ts | 10 +- 6 files changed, 441 insertions(+), 126 deletions(-) create mode 100644 src/components/CopyRolesModal.tsx diff --git a/src/api/users.ts b/src/api/users.ts index bda6280..4c09721 100644 --- a/src/api/users.ts +++ b/src/api/users.ts @@ -8,25 +8,27 @@ export interface UsersListParams { is_fired?: boolean department_id?: number full_name?: string + role_ids?: number[] } export interface UpdateUserRequest { id: number + full_name?: string department_id?: number | null is_blocked?: boolean is_fired?: boolean } export const usersApi = { - // Получить список пользователей с пагинацией и фильтрами getList: (params: UsersListParams = {}) => apiClient.get>('/users', { params }), - // Получить пользователя по ID getById: (id: number) => apiClient.get(`/users/${id}`), - // Обновить пользователя update: (data: UpdateUserRequest) => apiClient.put('/users', data), + + delete: (id: number) => + apiClient.delete(`/users/${id}`), } \ No newline at end of file diff --git a/src/components/CopyRolesModal.tsx b/src/components/CopyRolesModal.tsx new file mode 100644 index 0000000..96f4f85 --- /dev/null +++ b/src/components/CopyRolesModal.tsx @@ -0,0 +1,123 @@ +import { useState } from 'react' +import { + Modal, + Stack, + TextInput, + Text, + Button, + Group, + Loader, + Center, + Paper, + Badge, + ScrollArea, + Box, +} from '@mantine/core' +import { IconSearch, IconCopy } from '@tabler/icons-react' +import { useUsers } from '@/features/users/hooks/useUsers' + +interface CopyRolesModalProps { + opened: boolean + onClose: () => void + onCopy: (roleIds: number[]) => void + currentUserId: number | null +} + +export default function CopyRolesModal({ opened, onClose, onCopy, currentUserId }: CopyRolesModalProps) { + const [search, setSearch] = useState('') + const [selectedUserId, setSelectedUserId] = useState(null) + + const { data, isLoading } = useUsers({ + offset: 0, + limit: 100, + ...(search && { full_name: search }), + }) + + const users = Array.isArray(data?.data) ? data.data : [] + + const handleSelectUser = (userId: number) => { + setSelectedUserId(userId) + } + + const handleCopy = () => { + if (!selectedUserId) return + + const selectedUser = users.find(u => u.id === selectedUserId) + if (selectedUser && Array.isArray(selectedUser.user_roles)) { + const roleIds = selectedUser.user_roles + .map(ur => ur.role_id) + .filter((id): id is number => !!id) + onCopy(roleIds) + } + } + + return ( + + + } + value={search} + onChange={(e) => setSearch(e.currentTarget.value)} + /> + + {isLoading ? ( +
+ +
+ ) : ( + + + {users + .filter(u => u.id !== currentUserId) + .map((user) => ( + handleSelectUser(user.id!)} + > + + + {user.full_name} + + {user.username ? `@${user.username}` : user.telegram_id} + + + + {Array.isArray(user.user_roles) ? user.user_roles.length : 0} ролей + + + + ))} + + + )} + + + + + +
+
+ ) +} \ No newline at end of file diff --git a/src/components/UserEditModal.tsx b/src/components/UserEditModal.tsx index 8498d5a..1fe1d8f 100644 --- a/src/components/UserEditModal.tsx +++ b/src/components/UserEditModal.tsx @@ -1,4 +1,4 @@ -import { useEffect } from 'react' +import { useEffect, useState } from 'react' import { Modal, Stack, @@ -14,12 +14,18 @@ import { Center, Badge, Paper, + Tabs, + ActionIcon, + Tooltip, + Box, } from '@mantine/core' +import { IconTrash, IconCopy, IconUser, IconSettings, IconShield } from '@tabler/icons-react' import { useForm } from '@mantine/form' import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers' import { useDepartments } from '@/features/users/hooks/useDepartments' import { useRoles } from '@/features/users/hooks/useRoles' import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles' +import CopyRolesModal from './CopyRolesModal' interface UserEditModalProps { userId: number | null @@ -36,8 +42,11 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal const updateUser = useUpdateUser() const assignRoles = useBulkAssignRoles() + const [copyRolesOpened, setCopyRolesOpened] = useState(false) + const form = useForm({ initialValues: { + full_name: '', department_id: null as number | null, is_blocked: false, is_fired: false, @@ -45,10 +54,10 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal }, }) - // Заполняем форму данными пользователя useEffect(() => { if (user) { form.setValues({ + full_name: user.full_name || '', department_id: user.department_id || null, is_blocked: user.is_blocked || false, is_fired: user.is_fired || false, @@ -57,7 +66,6 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal } }, [user]) - // Заполняем роли из отдельного запроса useEffect(() => { if (userRoles && userRoles.length > 0) { const roleIds = userRoles @@ -70,15 +78,14 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal const handleSubmit = async (values: typeof form.values) => { if (!userId) return - // Обновляем пользователя await updateUser.mutateAsync({ id: userId, + full_name: values.full_name, department_id: values.department_id, is_blocked: values.is_blocked, is_fired: values.is_fired, }) - // Обновляем роли await assignRoles.mutateAsync({ user_id: userId, role_ids: values.role_ids, @@ -87,6 +94,15 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal onClose() } + const handleClearAllRoles = () => { + form.setFieldValue('role_ids', []) + } + + const handleCopyRoles = (roleIds: number[]) => { + form.setFieldValue('role_ids', roleIds) + setCopyRolesOpened(false) + } + const departmentOptions = departments?.map((d) => ({ value: String(d.id), label: d.name || '', @@ -102,97 +118,151 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal const isSubmitting = updateUser.isPending || assignRoles.isPending return ( - - Редактирование пользователя - {user && ID: {user.id}} - - } - size="lg" - > - {isLoading ? ( -
- -
- ) : user ? ( -
- - {/* Информация о пользователе (только для чтения) */} - - - - Имя: - {user.full_name} - - - Telegram ID: - {user.telegram_id} - - {user.username && ( + <> + + Редактирование пользователя + {user && ID: {user.id}} + + } + size="xl" + > + {isLoading ? ( +
+ +
+ ) : user ? ( + + + + }> + Информация + + }> + Роли ({form.values.role_ids.length}) + + }> + Настройки + + + + {/* Вкладка: Информация */} + + + + + + Telegram ID: + {user.telegram_id} + + {user.username && ( + + Username: + @{user.username} + + )} + {user.last_login && ( + + Последний вход: + + {new Date(user.last_login).toLocaleString('ru-RU')} + + + )} + + + + form.setFieldValue('full_name', e.currentTarget.value)} + required + /> + + form.setFieldValue('department_id', v ? Number(v) : null)} - clearable - /> + {/* Вкладка: Настройки */} + + + form.setFieldValue('is_blocked', e.currentTarget.checked)} + color="red" + /> - {/* Роли */} - form.setFieldValue('role_ids', v.map(Number))} - searchable - clearable - description="Пользователь может иметь несколько ролей" - /> + form.setFieldValue('is_fired', e.currentTarget.checked)} + color="gray" + /> + + + - + - {/* Статусы */} - form.setFieldValue('is_blocked', e.currentTarget.checked)} - color="red" - /> - - form.setFieldValue('is_fired', e.currentTarget.checked)} - color="gray" - /> - - {/* Кнопки */} - + @@ -200,13 +270,20 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal Сохранить -
- - ) : ( -
- Пользователь не найден -
- )} -
+ + ) : ( +
+ Пользователь не найден +
+ )} + + + setCopyRolesOpened(false)} + onCopy={handleCopyRoles} + currentUserId={userId} + /> + ) } \ No newline at end of file diff --git a/src/features/users/hooks/useUsers.ts b/src/features/users/hooks/useUsers.ts index c8e97a1..a63409d 100644 --- a/src/features/users/hooks/useUsers.ts +++ b/src/features/users/hooks/useUsers.ts @@ -47,4 +47,28 @@ export function useUpdateUser() { }) }, }) +} + +// ✅ Новый хук для удаления пользователя +export function useDeleteUser() { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: (id: number) => usersApi.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [USERS_QUERY_KEY] }) + notifications.show({ + title: 'Успешно', + message: 'Пользователь удален', + color: 'green', + }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Ошибка', + message: error.response?.data?.error_description || 'Не удалось удалить пользователя', + color: 'red', + }) + }, + }) } \ No newline at end of file diff --git a/src/pages/users/UsersPage.tsx b/src/pages/users/UsersPage.tsx index 6acb359..cac7857 100644 --- a/src/pages/users/UsersPage.tsx +++ b/src/pages/users/UsersPage.tsx @@ -8,26 +8,36 @@ import { Text, TextInput, Select, + MultiSelect, // ✅ Добавлен Pagination, Loader, Center, Tooltip, Box, Stack, + Modal, + Button, } from '@mantine/core' -import { IconPencil, IconSearch, IconRefresh } from '@tabler/icons-react' -import { useUsers } from '@/features/users/hooks/useUsers' +import { IconPencil, IconSearch, IconTrash } from '@tabler/icons-react' +import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers' import { useDepartments } from '@/features/users/hooks/useDepartments' -import UserEditModal from "@/components/UserEditModal.tsx"; +import { useRoles } from '@/features/users/hooks/useRoles' // ✅ Добавлен +import UserEditModal from "@/components/UserEditModal.tsx" +import { useAuth } from '@/hooks/useAuth' const LIMIT = 20 export default function UsersPage() { const [page, setPage] = useState(1) const [search, setSearch] = useState('') + const [selectedRoleIds, setSelectedRoleIds] = useState([]) // ✅ Массив ID ролей const [departmentFilter, setDepartmentFilter] = useState(null) const [statusFilter, setStatusFilter] = useState(null) const [editUserId, setEditUserId] = useState(null) + const [deleteUserId, setDeleteUserId] = useState(null) + + const { user: currentUser } = useAuth() + const isRootAdmin = currentUser?.is_root === true const { data, isLoading, isFetching } = useUsers({ offset: (page - 1) * LIMIT, @@ -37,11 +47,13 @@ export default function UsersPage() { ...(statusFilter === 'fired' && { is_fired: true }), ...(statusFilter === 'active' && { is_blocked: false, is_fired: false }), ...(search && { full_name: search }), + ...(selectedRoleIds.length > 0 && { role_ids: selectedRoleIds }), // ✅ Передаём массив }) const { data: departments } = useDepartments() + const { data: allRoles } = useRoles({ limit: 1000 }) // ✅ Получаем все роли + const deleteUser = useDeleteUser() - // ✅ Безопасная нормализация отделов const departmentOptions = useMemo(() => { if (!Array.isArray(departments)) return [] return departments.map((d) => ({ @@ -50,9 +62,24 @@ export default function UsersPage() { })) }, [departments]) - // ✅ Безопасная нормализация списка пользователей + // ✅ Опции для мультивыбора ролей + const roleOptions = useMemo(() => { + if (!Array.isArray(allRoles)) return [] + return allRoles.map((r) => ({ + value: String(r.id), + label: r.name || '', + })) + }, [allRoles]) + const users = Array.isArray(data?.data) ? data.data : [] const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1 + const hasSelected = selectedRoleIds.length > 0; + + const handleDelete = async () => { + if (!deleteUserId) return + await deleteUser.mutateAsync(deleteUserId) + setDeleteUserId(null) + } return ( @@ -77,6 +104,35 @@ export default function UsersPage() { style={{ flex: 1 }} /> + + { + setSelectedRoleIds(v.map(Number)) + setPage(1) + }} + searchable + clearable + maxDropdownHeight={400} + limit={15} + styles={{ + input: { + minHeight: 36, + }, + pill: { + display: 'none', + }, + pillsList: { + display: 'none', + }, + }} + /> + +