updated users page
Deploy Frontend / build-and-deploy (push) Successful in 27s
Details
Deploy Frontend / build-and-deploy (push) Successful in 27s
Details
This commit is contained in:
parent
48cd2450ea
commit
983b003abf
|
|
@ -8,25 +8,27 @@ export interface UsersListParams {
|
||||||
is_fired?: boolean
|
is_fired?: boolean
|
||||||
department_id?: number
|
department_id?: number
|
||||||
full_name?: string
|
full_name?: string
|
||||||
|
role_ids?: number[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateUserRequest {
|
export interface UpdateUserRequest {
|
||||||
id: number
|
id: number
|
||||||
|
full_name?: string
|
||||||
department_id?: number | null
|
department_id?: number | null
|
||||||
is_blocked?: boolean
|
is_blocked?: boolean
|
||||||
is_fired?: boolean
|
is_fired?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export const usersApi = {
|
export const usersApi = {
|
||||||
// Получить список пользователей с пагинацией и фильтрами
|
|
||||||
getList: (params: UsersListParams = {}) =>
|
getList: (params: UsersListParams = {}) =>
|
||||||
apiClient.get<ApiResponse<User[]>>('/users', { params }),
|
apiClient.get<ApiResponse<User[]>>('/users', { params }),
|
||||||
|
|
||||||
// Получить пользователя по ID
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
apiClient.get<User>(`/users/${id}`),
|
apiClient.get<User>(`/users/${id}`),
|
||||||
|
|
||||||
// Обновить пользователя
|
|
||||||
update: (data: UpdateUserRequest) =>
|
update: (data: UpdateUserRequest) =>
|
||||||
apiClient.put<User>('/users', data),
|
apiClient.put<User>('/users', data),
|
||||||
|
|
||||||
|
delete: (id: number) =>
|
||||||
|
apiClient.delete(`/users/${id}`),
|
||||||
}
|
}
|
||||||
|
|
@ -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<number | null>(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 (
|
||||||
|
<Modal
|
||||||
|
opened={opened}
|
||||||
|
onClose={onClose}
|
||||||
|
title="Скопировать роли от пользователя"
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<Stack gap="md">
|
||||||
|
<TextInput
|
||||||
|
placeholder="Поиск по имени..."
|
||||||
|
leftSection={<IconSearch size={16} />}
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<Center p={40}>
|
||||||
|
<Loader />
|
||||||
|
</Center>
|
||||||
|
) : (
|
||||||
|
<ScrollArea.Autosize mah={400}>
|
||||||
|
<Stack gap="xs">
|
||||||
|
{users
|
||||||
|
.filter(u => u.id !== currentUserId)
|
||||||
|
.map((user) => (
|
||||||
|
<Paper
|
||||||
|
key={user.id}
|
||||||
|
withBorder
|
||||||
|
p="sm"
|
||||||
|
style={{
|
||||||
|
cursor: 'pointer',
|
||||||
|
backgroundColor: selectedUserId === user.id
|
||||||
|
? 'var(--mantine-color-blue-0)'
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
onClick={() => handleSelectUser(user.id!)}
|
||||||
|
>
|
||||||
|
<Group justify="space-between">
|
||||||
|
<Box>
|
||||||
|
<Text fw={500} size="sm">{user.full_name}</Text>
|
||||||
|
<Text size="xs" c="dimmed">
|
||||||
|
{user.username ? `@${user.username}` : user.telegram_id}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Badge variant="light" size="sm">
|
||||||
|
{Array.isArray(user.user_roles) ? user.user_roles.length : 0} ролей
|
||||||
|
</Badge>
|
||||||
|
</Group>
|
||||||
|
</Paper>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</ScrollArea.Autosize>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Group justify="flex-end">
|
||||||
|
<Button variant="default" onClick={onClose}>
|
||||||
|
Отмена
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleCopy}
|
||||||
|
disabled={!selectedUserId}
|
||||||
|
leftSection={<IconCopy size={16} />}
|
||||||
|
>
|
||||||
|
Скопировать роли
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -14,12 +14,18 @@ import {
|
||||||
Center,
|
Center,
|
||||||
Badge,
|
Badge,
|
||||||
Paper,
|
Paper,
|
||||||
|
Tabs,
|
||||||
|
ActionIcon,
|
||||||
|
Tooltip,
|
||||||
|
Box,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
|
import { IconTrash, IconCopy, IconUser, IconSettings, IconShield } from '@tabler/icons-react'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
import { useUser, useUpdateUser } from '@/features/users/hooks/useUsers'
|
||||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||||
import { useRoles } from '@/features/users/hooks/useRoles'
|
import { useRoles } from '@/features/users/hooks/useRoles'
|
||||||
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
import { useUserRoles, useBulkAssignRoles } from '@/features/users/hooks/useUserRoles'
|
||||||
|
import CopyRolesModal from './CopyRolesModal'
|
||||||
|
|
||||||
interface UserEditModalProps {
|
interface UserEditModalProps {
|
||||||
userId: number | null
|
userId: number | null
|
||||||
|
|
@ -36,8 +42,11 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
const updateUser = useUpdateUser()
|
const updateUser = useUpdateUser()
|
||||||
const assignRoles = useBulkAssignRoles()
|
const assignRoles = useBulkAssignRoles()
|
||||||
|
|
||||||
|
const [copyRolesOpened, setCopyRolesOpened] = useState(false)
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
initialValues: {
|
initialValues: {
|
||||||
|
full_name: '',
|
||||||
department_id: null as number | null,
|
department_id: null as number | null,
|
||||||
is_blocked: false,
|
is_blocked: false,
|
||||||
is_fired: false,
|
is_fired: false,
|
||||||
|
|
@ -45,10 +54,10 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// Заполняем форму данными пользователя
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
form.setValues({
|
form.setValues({
|
||||||
|
full_name: user.full_name || '',
|
||||||
department_id: user.department_id || null,
|
department_id: user.department_id || null,
|
||||||
is_blocked: user.is_blocked || false,
|
is_blocked: user.is_blocked || false,
|
||||||
is_fired: user.is_fired || false,
|
is_fired: user.is_fired || false,
|
||||||
|
|
@ -57,7 +66,6 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
}
|
}
|
||||||
}, [user])
|
}, [user])
|
||||||
|
|
||||||
// Заполняем роли из отдельного запроса
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (userRoles && userRoles.length > 0) {
|
if (userRoles && userRoles.length > 0) {
|
||||||
const roleIds = userRoles
|
const roleIds = userRoles
|
||||||
|
|
@ -70,15 +78,14 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
const handleSubmit = async (values: typeof form.values) => {
|
const handleSubmit = async (values: typeof form.values) => {
|
||||||
if (!userId) return
|
if (!userId) return
|
||||||
|
|
||||||
// Обновляем пользователя
|
|
||||||
await updateUser.mutateAsync({
|
await updateUser.mutateAsync({
|
||||||
id: userId,
|
id: userId,
|
||||||
|
full_name: values.full_name,
|
||||||
department_id: values.department_id,
|
department_id: values.department_id,
|
||||||
is_blocked: values.is_blocked,
|
is_blocked: values.is_blocked,
|
||||||
is_fired: values.is_fired,
|
is_fired: values.is_fired,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Обновляем роли
|
|
||||||
await assignRoles.mutateAsync({
|
await assignRoles.mutateAsync({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
role_ids: values.role_ids,
|
role_ids: values.role_ids,
|
||||||
|
|
@ -87,6 +94,15 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleClearAllRoles = () => {
|
||||||
|
form.setFieldValue('role_ids', [])
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCopyRoles = (roleIds: number[]) => {
|
||||||
|
form.setFieldValue('role_ids', roleIds)
|
||||||
|
setCopyRolesOpened(false)
|
||||||
|
}
|
||||||
|
|
||||||
const departmentOptions = departments?.map((d) => ({
|
const departmentOptions = departments?.map((d) => ({
|
||||||
value: String(d.id),
|
value: String(d.id),
|
||||||
label: d.name || '',
|
label: d.name || '',
|
||||||
|
|
@ -102,97 +118,151 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<>
|
||||||
opened={opened}
|
<Modal
|
||||||
onClose={onClose}
|
opened={opened}
|
||||||
title={
|
onClose={onClose}
|
||||||
<Group>
|
title={
|
||||||
<Text fw={700}>Редактирование пользователя</Text>
|
<Group>
|
||||||
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
<Text fw={700}>Редактирование пользователя</Text>
|
||||||
</Group>
|
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
||||||
}
|
</Group>
|
||||||
size="lg"
|
}
|
||||||
>
|
size="xl"
|
||||||
{isLoading ? (
|
>
|
||||||
<Center p={40}>
|
{isLoading ? (
|
||||||
<Loader />
|
<Center p={40}>
|
||||||
</Center>
|
<Loader />
|
||||||
) : user ? (
|
</Center>
|
||||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
) : user ? (
|
||||||
<Stack gap="md">
|
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||||
{/* Информация о пользователе (только для чтения) */}
|
<Tabs defaultValue="info" variant="outline">
|
||||||
<Paper withBorder p="md" bg="gray.0">
|
<Tabs.List mb="md">
|
||||||
<Stack gap="xs">
|
<Tabs.Tab value="info" leftSection={<IconUser size={14} />}>
|
||||||
<Group justify="space-between">
|
Информация
|
||||||
<Text size="sm" c="dimmed">Имя:</Text>
|
</Tabs.Tab>
|
||||||
<Text fw={500}>{user.full_name}</Text>
|
<Tabs.Tab value="roles" leftSection={<IconShield size={14} />}>
|
||||||
</Group>
|
Роли ({form.values.role_ids.length})
|
||||||
<Group justify="space-between">
|
</Tabs.Tab>
|
||||||
<Text size="sm" c="dimmed">Telegram ID:</Text>
|
<Tabs.Tab value="settings" leftSection={<IconSettings size={14} />}>
|
||||||
<Text ff="monospace">{user.telegram_id}</Text>
|
Настройки
|
||||||
</Group>
|
</Tabs.Tab>
|
||||||
{user.username && (
|
</Tabs.List>
|
||||||
|
|
||||||
|
{/* Вкладка: Информация */}
|
||||||
|
<Tabs.Panel value="info">
|
||||||
|
<Stack gap="md">
|
||||||
|
<Paper withBorder p="md" bg="gray.0">
|
||||||
|
<Stack gap="xs">
|
||||||
|
<Group justify="space-between">
|
||||||
|
<Text size="sm" c="dimmed">Telegram ID:</Text>
|
||||||
|
<Text ff="monospace">{user.telegram_id}</Text>
|
||||||
|
</Group>
|
||||||
|
{user.username && (
|
||||||
|
<Group justify="space-between">
|
||||||
|
<Text size="sm" c="dimmed">Username:</Text>
|
||||||
|
<Text>@{user.username}</Text>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
{user.last_login && (
|
||||||
|
<Group justify="space-between">
|
||||||
|
<Text size="sm" c="dimmed">Последний вход:</Text>
|
||||||
|
<Text size="sm">
|
||||||
|
{new Date(user.last_login).toLocaleString('ru-RU')}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
<TextInput
|
||||||
|
label="ФИО"
|
||||||
|
placeholder="Иванов Иван Иванович"
|
||||||
|
value={form.values.full_name}
|
||||||
|
onChange={(e) => form.setFieldValue('full_name', e.currentTarget.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Select
|
||||||
|
label="Отдел"
|
||||||
|
placeholder="Не назначен"
|
||||||
|
data={departmentOptions}
|
||||||
|
value={form.values.department_id ? String(form.values.department_id) : null}
|
||||||
|
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
||||||
|
clearable
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Tabs.Panel>
|
||||||
|
|
||||||
|
{/* Вкладка: Роли */}
|
||||||
|
<Tabs.Panel value="roles">
|
||||||
|
<Stack gap="md">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="sm" c="dimmed">Username:</Text>
|
<Text size="sm" fw={500}>
|
||||||
<Text>@{user.username}</Text>
|
Выбрано ролей: {form.values.role_ids.length}
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
{user.last_login && (
|
|
||||||
<Group justify="space-between">
|
|
||||||
<Text size="sm" c="dimmed">Последний вход:</Text>
|
|
||||||
<Text size="sm">
|
|
||||||
{new Date(user.last_login).toLocaleString('ru-RU')}
|
|
||||||
</Text>
|
</Text>
|
||||||
|
<Group gap="xs">
|
||||||
|
<Tooltip label="Снять все роли">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="red"
|
||||||
|
onClick={handleClearAllRoles}
|
||||||
|
disabled={form.values.role_ids.length === 0}
|
||||||
|
>
|
||||||
|
<IconTrash size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip label="Скопировать роли от другого пользователя">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="blue"
|
||||||
|
onClick={() => setCopyRolesOpened(true)}
|
||||||
|
>
|
||||||
|
<IconCopy size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Divider label="Настройки" labelPosition="center" />
|
<MultiSelect
|
||||||
|
label="Роли"
|
||||||
|
placeholder="Выберите роли"
|
||||||
|
data={roleOptions}
|
||||||
|
value={form.values.role_ids.map(String)}
|
||||||
|
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
|
||||||
|
searchable
|
||||||
|
clearable
|
||||||
|
description="Пользователь может иметь несколько ролей"
|
||||||
|
maxDropdownHeight={300}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Tabs.Panel>
|
||||||
|
|
||||||
{/* Отдел */}
|
{/* Вкладка: Настройки */}
|
||||||
<Select
|
<Tabs.Panel value="settings">
|
||||||
label="Отдел"
|
<Stack gap="md">
|
||||||
placeholder="Не назначен"
|
<Switch
|
||||||
data={departmentOptions}
|
label="Заблокирован"
|
||||||
value={form.values.department_id ? String(form.values.department_id) : null}
|
description="Пользователь не сможет пользоваться системой"
|
||||||
onChange={(v) => form.setFieldValue('department_id', v ? Number(v) : null)}
|
checked={form.values.is_blocked}
|
||||||
clearable
|
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
||||||
/>
|
color="red"
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Роли */}
|
<Switch
|
||||||
<MultiSelect
|
label="Уволен"
|
||||||
label="Роли"
|
description="Пользователь больше не работает в компании"
|
||||||
placeholder="Выберите роли"
|
checked={form.values.is_fired}
|
||||||
data={roleOptions}
|
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
||||||
value={form.values.role_ids.map(String)}
|
color="gray"
|
||||||
onChange={(v) => form.setFieldValue('role_ids', v.map(Number))}
|
/>
|
||||||
searchable
|
</Stack>
|
||||||
clearable
|
</Tabs.Panel>
|
||||||
description="Пользователь может иметь несколько ролей"
|
</Tabs>
|
||||||
/>
|
|
||||||
|
|
||||||
<Divider />
|
<Divider my="md" />
|
||||||
|
|
||||||
{/* Статусы */}
|
<Group justify="flex-end">
|
||||||
<Switch
|
|
||||||
label="Заблокирован"
|
|
||||||
description="Пользователь не сможет пользоваться системой"
|
|
||||||
checked={form.values.is_blocked}
|
|
||||||
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
|
||||||
color="red"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Switch
|
|
||||||
label="Уволен"
|
|
||||||
description="Пользователь больше не работает в компании"
|
|
||||||
checked={form.values.is_fired}
|
|
||||||
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
|
||||||
color="gray"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Кнопки */}
|
|
||||||
<Group justify="flex-end" mt="md">
|
|
||||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||||
Отмена
|
Отмена
|
||||||
</Button>
|
</Button>
|
||||||
|
|
@ -200,13 +270,20 @@ export default function UserEditModal({ userId, opened, onClose }: UserEditModal
|
||||||
Сохранить
|
Сохранить
|
||||||
</Button>
|
</Button>
|
||||||
</Group>
|
</Group>
|
||||||
</Stack>
|
</form>
|
||||||
</form>
|
) : (
|
||||||
) : (
|
<Center p={40}>
|
||||||
<Center p={40}>
|
<Text c="dimmed">Пользователь не найден</Text>
|
||||||
<Text c="dimmed">Пользователь не найден</Text>
|
</Center>
|
||||||
</Center>
|
)}
|
||||||
)}
|
</Modal>
|
||||||
</Modal>
|
|
||||||
|
<CopyRolesModal
|
||||||
|
opened={copyRolesOpened}
|
||||||
|
onClose={() => setCopyRolesOpened(false)}
|
||||||
|
onCopy={handleCopyRoles}
|
||||||
|
currentUserId={userId}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -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',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -8,26 +8,36 @@ import {
|
||||||
Text,
|
Text,
|
||||||
TextInput,
|
TextInput,
|
||||||
Select,
|
Select,
|
||||||
|
MultiSelect, // ✅ Добавлен
|
||||||
Pagination,
|
Pagination,
|
||||||
Loader,
|
Loader,
|
||||||
Center,
|
Center,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Box,
|
Box,
|
||||||
Stack,
|
Stack,
|
||||||
|
Modal,
|
||||||
|
Button,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { IconPencil, IconSearch, IconRefresh } from '@tabler/icons-react'
|
import { IconPencil, IconSearch, IconTrash } from '@tabler/icons-react'
|
||||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers'
|
||||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
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
|
const LIMIT = 20
|
||||||
|
|
||||||
export default function UsersPage() {
|
export default function UsersPage() {
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
|
const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([]) // ✅ Массив ID ролей
|
||||||
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
const [departmentFilter, setDepartmentFilter] = useState<string | null>(null)
|
||||||
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
const [statusFilter, setStatusFilter] = useState<string | null>(null)
|
||||||
const [editUserId, setEditUserId] = useState<number | null>(null)
|
const [editUserId, setEditUserId] = useState<number | null>(null)
|
||||||
|
const [deleteUserId, setDeleteUserId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const { user: currentUser } = useAuth()
|
||||||
|
const isRootAdmin = currentUser?.is_root === true
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useUsers({
|
const { data, isLoading, isFetching } = useUsers({
|
||||||
offset: (page - 1) * LIMIT,
|
offset: (page - 1) * LIMIT,
|
||||||
|
|
@ -37,11 +47,13 @@ export default function UsersPage() {
|
||||||
...(statusFilter === 'fired' && { is_fired: true }),
|
...(statusFilter === 'fired' && { is_fired: true }),
|
||||||
...(statusFilter === 'active' && { is_blocked: false, is_fired: false }),
|
...(statusFilter === 'active' && { is_blocked: false, is_fired: false }),
|
||||||
...(search && { full_name: search }),
|
...(search && { full_name: search }),
|
||||||
|
...(selectedRoleIds.length > 0 && { role_ids: selectedRoleIds }), // ✅ Передаём массив
|
||||||
})
|
})
|
||||||
|
|
||||||
const { data: departments } = useDepartments()
|
const { data: departments } = useDepartments()
|
||||||
|
const { data: allRoles } = useRoles({ limit: 1000 }) // ✅ Получаем все роли
|
||||||
|
const deleteUser = useDeleteUser()
|
||||||
|
|
||||||
// ✅ Безопасная нормализация отделов
|
|
||||||
const departmentOptions = useMemo(() => {
|
const departmentOptions = useMemo(() => {
|
||||||
if (!Array.isArray(departments)) return []
|
if (!Array.isArray(departments)) return []
|
||||||
return departments.map((d) => ({
|
return departments.map((d) => ({
|
||||||
|
|
@ -50,9 +62,24 @@ export default function UsersPage() {
|
||||||
}))
|
}))
|
||||||
}, [departments])
|
}, [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 users = Array.isArray(data?.data) ? data.data : []
|
||||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
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 (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
|
|
@ -77,6 +104,35 @@ export default function UsersPage() {
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Box style={{ width: 250 }}>
|
||||||
|
<MultiSelect
|
||||||
|
label="Роли"
|
||||||
|
// ✅ Меняем placeholder в зависимости от количества выбранных
|
||||||
|
placeholder={hasSelected ? `Выбрано: ${selectedRoleIds.length}` : "Все роли"}
|
||||||
|
data={roleOptions}
|
||||||
|
value={selectedRoleIds.map(String)}
|
||||||
|
onChange={(v) => {
|
||||||
|
setSelectedRoleIds(v.map(Number))
|
||||||
|
setPage(1)
|
||||||
|
}}
|
||||||
|
searchable
|
||||||
|
clearable
|
||||||
|
maxDropdownHeight={400}
|
||||||
|
limit={15}
|
||||||
|
styles={{
|
||||||
|
input: {
|
||||||
|
minHeight: 36,
|
||||||
|
},
|
||||||
|
pill: {
|
||||||
|
display: 'none',
|
||||||
|
},
|
||||||
|
pillsList: {
|
||||||
|
display: 'none',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
label="Отдел"
|
label="Отдел"
|
||||||
placeholder="Все отделы"
|
placeholder="Все отделы"
|
||||||
|
|
@ -126,7 +182,7 @@ export default function UsersPage() {
|
||||||
<Table.Th>Отдел</Table.Th>
|
<Table.Th>Отдел</Table.Th>
|
||||||
<Table.Th>Роли</Table.Th>
|
<Table.Th>Роли</Table.Th>
|
||||||
<Table.Th>Статус</Table.Th>
|
<Table.Th>Статус</Table.Th>
|
||||||
<Table.Th style={{ width: 60 }}>Действия</Table.Th>
|
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
</Table.Thead>
|
</Table.Thead>
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
|
|
@ -156,7 +212,6 @@ export default function UsersPage() {
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Group gap={4}>
|
<Group gap={4}>
|
||||||
{/* ✅ Безопасный рендер ролей */}
|
|
||||||
{Array.isArray(user.user_roles) ? (
|
{Array.isArray(user.user_roles) ? (
|
||||||
<>
|
<>
|
||||||
{user.user_roles.slice(0, 3).map((ur) => (
|
{user.user_roles.slice(0, 3).map((ur) => (
|
||||||
|
|
@ -182,15 +237,28 @@ export default function UsersPage() {
|
||||||
/>
|
/>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Tooltip label="Редактировать">
|
<Group gap={4}>
|
||||||
<ActionIcon
|
<Tooltip label="Редактировать">
|
||||||
variant="light"
|
<ActionIcon
|
||||||
color="blue"
|
variant="light"
|
||||||
onClick={() => setEditUserId(user.id!)}
|
color="blue"
|
||||||
>
|
onClick={() => setEditUserId(user.id!)}
|
||||||
<IconPencil size={16} />
|
>
|
||||||
</ActionIcon>
|
<IconPencil size={16} />
|
||||||
</Tooltip>
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
{isRootAdmin && (
|
||||||
|
<Tooltip label="Удалить пользователя">
|
||||||
|
<ActionIcon
|
||||||
|
variant="light"
|
||||||
|
color="red"
|
||||||
|
onClick={() => setDeleteUserId(user.id!)}
|
||||||
|
>
|
||||||
|
<IconTrash size={16} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
))
|
))
|
||||||
|
|
@ -228,17 +296,36 @@ export default function UsersPage() {
|
||||||
opened={editUserId !== null}
|
opened={editUserId !== null}
|
||||||
onClose={() => setEditUserId(null)}
|
onClose={() => setEditUserId(null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
opened={deleteUserId !== null}
|
||||||
|
onClose={() => setDeleteUserId(null)}
|
||||||
|
title="Подтверждение удаления"
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<Stack gap="md">
|
||||||
|
<Text>
|
||||||
|
Вы уверены, что хотите удалить пользователя? Это действие нельзя отменить.
|
||||||
|
</Text>
|
||||||
|
<Group justify="flex-end">
|
||||||
|
<Button variant="default" onClick={() => setDeleteUserId(null)}>
|
||||||
|
Отмена
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
color="red"
|
||||||
|
onClick={handleDelete}
|
||||||
|
loading={deleteUser.isPending}
|
||||||
|
>
|
||||||
|
Удалить
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
</Modal>
|
||||||
</Stack>
|
</Stack>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function UserStatusBadge({
|
function UserStatusBadge({ isBlocked, isFired }: { isBlocked?: boolean; isFired?: boolean }) {
|
||||||
isBlocked,
|
|
||||||
isFired
|
|
||||||
}: {
|
|
||||||
isBlocked?: boolean
|
|
||||||
isFired?: boolean
|
|
||||||
}) {
|
|
||||||
if (isFired) return <Badge color="gray" variant="filled">Уволен</Badge>
|
if (isFired) return <Badge color="gray" variant="filled">Уволен</Badge>
|
||||||
if (isBlocked) return <Badge color="red" variant="filled">Заблокирован</Badge>
|
if (isBlocked) return <Badge color="red" variant="filled">Заблокирован</Badge>
|
||||||
return <Badge color="green" variant="light">Активен</Badge>
|
return <Badge color="green" variant="light">Активен</Badge>
|
||||||
|
|
|
||||||
|
|
@ -51,14 +51,16 @@ export interface UserRole {
|
||||||
export interface Admin {
|
export interface Admin {
|
||||||
id?: number
|
id?: number
|
||||||
login: string
|
login: string
|
||||||
password_hash?: string
|
name?: string
|
||||||
is_blocked?: boolean
|
is_root?: boolean
|
||||||
|
created_at?: string
|
||||||
last_login?: string
|
last_login?: string
|
||||||
last_ip_login?: string
|
last_ip_login?: string
|
||||||
created_at?: string
|
is_blocked?: boolean
|
||||||
updated_at?: string
|
password?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 🆕 Типы для заявок
|
// 🆕 Типы для заявок
|
||||||
export interface ApprovalFile {
|
export interface ApprovalFile {
|
||||||
id?: number
|
id?: number
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue