Updated users editing UI
Deploy Frontend / build-and-deploy (push) Successful in 48s
Details
Deploy Frontend / build-and-deploy (push) Successful in 48s
Details
This commit is contained in:
parent
ca4e725bce
commit
63d93d6792
|
|
@ -1,123 +0,0 @@
|
|||
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>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
import { useMemo, useState } from 'react'
|
||||
import {
|
||||
ActionIcon,
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
Drawer,
|
||||
Group,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconArrowLeft, IconCheck, IconSearch } from '@tabler/icons-react'
|
||||
import { useUsers } from '@/features/users/hooks/useUsers'
|
||||
import classes from './UserDrawer.module.css'
|
||||
|
||||
type Mode = 'replace' | 'merge'
|
||||
|
||||
interface Props {
|
||||
currentUserId: number | null
|
||||
onBack: () => void
|
||||
onApply: (roleIds: number[], mode: Mode) => void
|
||||
}
|
||||
|
||||
interface Picked {
|
||||
id: number
|
||||
roleIds: number[]
|
||||
}
|
||||
|
||||
export default function CopyRolesPanel({ currentUserId, onBack, onApply }: Props) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [debounced] = useDebouncedValue(search.trim(), 300)
|
||||
const [picked, setPicked] = useState<Picked | null>(null)
|
||||
const [mode, setMode] = useState<Mode>('replace')
|
||||
|
||||
const { data, isLoading } = useUsers({
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
...(debounced && { full_name: debounced }),
|
||||
})
|
||||
|
||||
const users = useMemo(
|
||||
() => (Array.isArray(data?.data) ? data.data : []).filter((u) => u.id !== currentUserId),
|
||||
[data, currentUserId],
|
||||
)
|
||||
|
||||
const pick = (user: (typeof users)[number]) => {
|
||||
const roleIds = Array.isArray(user.user_roles)
|
||||
? user.user_roles.map((ur) => ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
setPicked({ id: user.id!, roleIds })
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Header>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ActionIcon onClick={onBack} aria-label="Назад">
|
||||
<IconArrowLeft size={18} />
|
||||
</ActionIcon>
|
||||
<Text fw={600}>Скопировать роли</Text>
|
||||
</Group>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
<Stack className={classes.section} gap="md">
|
||||
<TextInput
|
||||
placeholder="Поиск сотрудника по имени"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<SegmentedControl
|
||||
fullWidth
|
||||
value={mode}
|
||||
onChange={(v) => setMode(v as Mode)}
|
||||
data={[
|
||||
{ value: 'replace', label: 'Заменить текущие' },
|
||||
{ value: 'merge', label: 'Добавить к текущим' },
|
||||
]}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
<Stack gap="xs">
|
||||
{Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} h={52} />)}
|
||||
</Stack>
|
||||
) : users.length === 0 ? (
|
||||
<Text size="sm" c="dimmed" ta="center" py="lg">Никого не найдено</Text>
|
||||
) : (
|
||||
<ScrollArea.Autosize mah="calc(100dvh - 330px)" type="auto" mx={-6}>
|
||||
<Stack gap={2} px={6}>
|
||||
{users.map((u) => {
|
||||
const roles = (Array.isArray(u.user_roles) ? u.user_roles : [])
|
||||
.map((ur) => ur.role?.name)
|
||||
.filter(Boolean)
|
||||
const isPicked = picked?.id === u.id
|
||||
return (
|
||||
<UnstyledButton
|
||||
key={u.id}
|
||||
className={classes.pickRow}
|
||||
data-selected={isPicked || undefined}
|
||||
onClick={() => pick(u)}
|
||||
>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Avatar size={32} radius="xl" color="initials" name={u.full_name ?? ''} />
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Group justify="space-between" wrap="nowrap" gap="xs">
|
||||
<Text size="sm" fw={500} truncate>{u.full_name}</Text>
|
||||
<Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>
|
||||
{roles.length} ролей
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{roles.length > 0 ? roles.join(', ') : 'Без ролей'}
|
||||
</Text>
|
||||
</Box>
|
||||
{isPicked && <IconCheck size={16} color="var(--mantine-primary-color-filled)" />}
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
)
|
||||
})}
|
||||
</Stack>
|
||||
</ScrollArea.Autosize>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">Роли применятся после сохранения</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={onBack}>Назад</Button>
|
||||
<Button disabled={!picked} onClick={() => picked && onApply(picked.roleIds, mode)}>
|
||||
Применить
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</Drawer.Body>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: calc(100dvh - 68px);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.section {
|
||||
padding: var(--mantine-spacing-md) var(--mantine-spacing-lg);
|
||||
}
|
||||
|
||||
.tabsList {
|
||||
padding: 0 var(--mantine-spacing-lg);
|
||||
}
|
||||
|
||||
.footer {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
margin-top: auto;
|
||||
padding: var(--mantine-spacing-sm) var(--mantine-spacing-lg);
|
||||
background: var(--mantine-color-body);
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
.infoRow + .infoRow {
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
.pickRow {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
transition: background-color 120ms ease;
|
||||
}
|
||||
|
||||
.pickRow:hover {
|
||||
background-color: var(--mantine-color-default-hover);
|
||||
}
|
||||
|
||||
.pickRow[data-selected] {
|
||||
background-color: var(--mantine-primary-color-light);
|
||||
}
|
||||
|
|
@ -0,0 +1,398 @@
|
|||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
ActionIcon,
|
||||
Avatar,
|
||||
Box,
|
||||
Button,
|
||||
Checkbox,
|
||||
CopyButton,
|
||||
Drawer,
|
||||
Group,
|
||||
ScrollArea,
|
||||
Select,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Switch,
|
||||
Tabs,
|
||||
Text,
|
||||
TextInput,
|
||||
Tooltip,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { IconCheck, IconCopy, IconSearch } from '@tabler/icons-react'
|
||||
import dayjs from 'dayjs'
|
||||
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 { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import { StatusBadge, userStatusOf } from '@/components/ui/StatusBadge'
|
||||
import CopyRolesPanel from './CopyRolesPanel'
|
||||
import classes from './UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
userId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const EMPTY = {
|
||||
full_name: '',
|
||||
department_id: null as number | null,
|
||||
is_blocked: false,
|
||||
is_fired: false,
|
||||
role_ids: [] as number[],
|
||||
}
|
||||
|
||||
function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<Group justify="space-between" wrap="nowrap" py={8} className={classes.infoRow}>
|
||||
<Text size="sm" c="dimmed">{label}</Text>
|
||||
<Group gap={4} wrap="nowrap">{children}</Group>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
||||
export default function UserEditDrawer({ userId, opened, onClose }: Props) {
|
||||
const { data: user, isLoading: userLoading } = useUser(userId)
|
||||
const { data: departments } = useDepartments()
|
||||
const { data: allRoles } = useRoles({ limit: 1000 })
|
||||
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
||||
|
||||
const updateUser = useUpdateUser()
|
||||
const assignRoles = useBulkAssignRoles()
|
||||
|
||||
const [tab, setTab] = useState<string | null>('profile')
|
||||
const [view, setView] = useState<'edit' | 'copy'>('edit')
|
||||
const [roleQuery, setRoleQuery] = useState('')
|
||||
const [confirmClose, setConfirmClose] = useState(false)
|
||||
const initializedFor = useRef<number | null>(null)
|
||||
|
||||
const form = useForm({
|
||||
initialValues: EMPTY,
|
||||
validate: {
|
||||
full_name: (v) => (v.trim() ? null : 'Укажите ФИО'),
|
||||
},
|
||||
})
|
||||
|
||||
const isLoading = userLoading || rolesLoading
|
||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||
|
||||
// Инициализация формы: один раз за открытие, чтобы фоновые обновления данных не затирали правки
|
||||
useEffect(() => {
|
||||
if (!opened || isLoading || !user || initializedFor.current === userId) return
|
||||
|
||||
const fromApi = Array.isArray(userRoles)
|
||||
? userRoles.map((ur) => ur.role?.id || ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
const fromUser = Array.isArray(user.user_roles)
|
||||
? user.user_roles.map((ur) => ur.role_id).filter((id): id is number => !!id)
|
||||
: []
|
||||
|
||||
const values = {
|
||||
full_name: user.full_name || '',
|
||||
department_id: user.department_id || null,
|
||||
is_blocked: user.is_blocked || false,
|
||||
is_fired: user.is_fired || false,
|
||||
role_ids: fromApi.length > 0 ? fromApi : fromUser,
|
||||
}
|
||||
form.setValues(values)
|
||||
form.resetDirty(values)
|
||||
initializedFor.current = userId
|
||||
}, [opened, isLoading, user, userRoles, userId])
|
||||
|
||||
// Сброс локального состояния при закрытии
|
||||
useEffect(() => {
|
||||
if (!opened) {
|
||||
initializedFor.current = null
|
||||
setTab('profile')
|
||||
setView('edit')
|
||||
setRoleQuery('')
|
||||
setConfirmClose(false)
|
||||
}
|
||||
}, [opened])
|
||||
|
||||
const requestClose = () => (form.isDirty() ? setConfirmClose(true) : onClose())
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (!userId) return
|
||||
await updateUser.mutateAsync({
|
||||
id: userId,
|
||||
full_name: values.full_name.trim(),
|
||||
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 })
|
||||
onClose()
|
||||
}
|
||||
|
||||
const departmentOptions = useMemo(
|
||||
() => (Array.isArray(departments) ? departments.map((d) => ({ value: String(d.id), label: d.name || '' })) : []),
|
||||
[departments],
|
||||
)
|
||||
|
||||
const roleItems = useMemo(
|
||||
() =>
|
||||
Array.isArray(allRoles)
|
||||
? allRoles.map((r) => ({ id: r.id as number, name: r.name || '', description: r.description as string | undefined }))
|
||||
: [],
|
||||
[allRoles],
|
||||
)
|
||||
|
||||
const filteredRoles = useMemo(() => {
|
||||
const q = roleQuery.trim().toLowerCase()
|
||||
if (!q) return roleItems
|
||||
return roleItems.filter((r) => r.name.toLowerCase().includes(q) || (r.description ?? '').toLowerCase().includes(q))
|
||||
}, [roleItems, roleQuery])
|
||||
|
||||
const selected = useMemo(() => new Set(form.values.role_ids), [form.values.role_ids])
|
||||
|
||||
const toggleRole = (id: number) =>
|
||||
form.setFieldValue(
|
||||
'role_ids',
|
||||
selected.has(id) ? form.values.role_ids.filter((x) => x !== id) : [...form.values.role_ids, id],
|
||||
)
|
||||
|
||||
const applyCopiedRoles = (roleIds: number[], mode: 'replace' | 'merge') => {
|
||||
form.setFieldValue('role_ids', mode === 'merge' ? Array.from(new Set([...form.values.role_ids, ...roleIds])) : roleIds)
|
||||
setView('edit')
|
||||
setTab('roles')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Drawer.Root
|
||||
opened={opened}
|
||||
onClose={requestClose}
|
||||
position="right"
|
||||
size="min(560px, 100vw)"
|
||||
trapFocus
|
||||
>
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
{view === 'copy' ? (
|
||||
<CopyRolesPanel
|
||||
currentUserId={userId}
|
||||
onBack={() => setView('edit')}
|
||||
onApply={applyCopiedRoles}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Drawer.Header>
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<Avatar size={36} radius="xl" color="initials" name={user?.full_name ?? ''} />
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text fw={600} truncate>{user?.full_name || 'Пользователь'}</Text>
|
||||
<Group gap={8} wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">ID {userId}</Text>
|
||||
{user && <StatusBadge kind="user" status={userStatusOf(user)} />}
|
||||
</Group>
|
||||
</Box>
|
||||
</Group>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={32} />
|
||||
<Skeleton h={96} />
|
||||
<Skeleton h={36} />
|
||||
<Skeleton h={36} />
|
||||
</Stack>
|
||||
) : !user ? (
|
||||
<Text className={classes.section} c="dimmed" size="sm">Пользователь не найден</Text>
|
||||
) : (
|
||||
<form
|
||||
style={{ display: 'contents' }}
|
||||
onSubmit={form.onSubmit(handleSubmit, () => setTab('profile'))}
|
||||
>
|
||||
<Tabs value={tab} onChange={setTab}>
|
||||
<Tabs.List className={classes.tabsList}>
|
||||
<Tabs.Tab value="profile">Профиль</Tabs.Tab>
|
||||
<Tabs.Tab
|
||||
value="roles"
|
||||
rightSection={
|
||||
<Text span size="xs" c="dimmed">{form.values.role_ids.length}</Text>
|
||||
}
|
||||
>
|
||||
Роли
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab value="access">Доступ</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
<Tabs.Panel value="profile" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
<Box>
|
||||
<InfoRow label="Telegram ID">
|
||||
<Text size="sm" ff="monospace">{user.telegram_id}</Text>
|
||||
<CopyButton value={String(user.telegram_id)} timeout={1500}>
|
||||
{({ copied, copy }) => (
|
||||
<Tooltip label={copied ? 'Скопировано' : 'Копировать'}>
|
||||
<ActionIcon size="sm" onClick={copy} aria-label="Копировать Telegram ID">
|
||||
{copied ? <IconCheck size={14} /> : <IconCopy size={14} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
</CopyButton>
|
||||
</InfoRow>
|
||||
{user.username && (
|
||||
<InfoRow label="Username">
|
||||
<Text size="sm">@{user.username}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
{user.last_login && (
|
||||
<InfoRow label="Последний вход">
|
||||
<Text size="sm">{dayjs(user.last_login).format('D MMM YYYY, HH:mm')}</Text>
|
||||
</InfoRow>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<TextInput
|
||||
label="ФИО"
|
||||
placeholder="Иванов Иван Иванович"
|
||||
withAsterisk
|
||||
{...form.getInputProps('full_name')}
|
||||
/>
|
||||
|
||||
<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)}
|
||||
searchable
|
||||
clearable
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="roles" className={classes.section}>
|
||||
<Stack gap="sm">
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" c="dimmed">
|
||||
Выбрано {form.values.role_ids.length} из {roleItems.length}
|
||||
</Text>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
leftSection={<IconCopy size={14} />}
|
||||
onClick={() => setView('copy')}
|
||||
>
|
||||
Скопировать от…
|
||||
</Button>
|
||||
<Button
|
||||
size="compact-sm"
|
||||
variant="subtle"
|
||||
color="red"
|
||||
disabled={form.values.role_ids.length === 0}
|
||||
onClick={() => form.setFieldValue('role_ids', [])}
|
||||
>
|
||||
Снять все
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<TextInput
|
||||
placeholder="Поиск по ролям"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={roleQuery}
|
||||
onChange={(e) => setRoleQuery(e.currentTarget.value)}
|
||||
/>
|
||||
|
||||
<ScrollArea.Autosize mah="calc(100dvh - 330px)" type="auto" mx={-6}>
|
||||
<Stack gap={2} px={6}>
|
||||
{filteredRoles.map((r) => (
|
||||
<UnstyledButton
|
||||
key={r.id}
|
||||
className={classes.pickRow}
|
||||
data-selected={selected.has(r.id) || undefined}
|
||||
role="checkbox"
|
||||
aria-checked={selected.has(r.id)}
|
||||
onClick={() => toggleRole(r.id)}
|
||||
>
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<Checkbox
|
||||
checked={selected.has(r.id)}
|
||||
readOnly
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
mt={2}
|
||||
style={{ pointerEvents: 'none' }}
|
||||
/>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Text size="sm" fw={500}>{r.name}</Text>
|
||||
{r.description && (
|
||||
<Text size="xs" c="dimmed" lineClamp={2}>{r.description}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
{filteredRoles.length === 0 && (
|
||||
<Text size="sm" c="dimmed" ta="center" py="lg">Ничего не найдено</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea.Autosize>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
|
||||
<Tabs.Panel value="access" className={classes.section}>
|
||||
<Stack gap="lg">
|
||||
<Switch
|
||||
label="Заблокирован"
|
||||
description="Пользователь не сможет пользоваться системой"
|
||||
color="red"
|
||||
checked={form.values.is_blocked}
|
||||
onChange={(e) => form.setFieldValue('is_blocked', e.currentTarget.checked)}
|
||||
/>
|
||||
<Switch
|
||||
label="Уволен"
|
||||
description="Пользователь больше не работает в компании"
|
||||
color="gray"
|
||||
checked={form.values.is_fired}
|
||||
onChange={(e) => form.setFieldValue('is_fired', e.currentTarget.checked)}
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">
|
||||
{form.isDirty() ? 'Есть несохранённые изменения' : ''}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={requestClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting} disabled={!form.isDirty()}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</form>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</>
|
||||
)}
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
|
||||
<ConfirmModal
|
||||
opened={confirmClose}
|
||||
onClose={() => setConfirmClose(false)}
|
||||
onConfirm={() => {
|
||||
setConfirmClose(false)
|
||||
onClose()
|
||||
}}
|
||||
title="Закрыть без сохранения?"
|
||||
message="Внесённые изменения будут потеряны."
|
||||
confirmLabel="Закрыть"
|
||||
danger
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,295 +0,0 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Select,
|
||||
MultiSelect,
|
||||
Switch,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Divider,
|
||||
Loader,
|
||||
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
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function UserEditModal({ userId, opened, onClose }: UserEditModalProps) {
|
||||
const { data: user, isLoading: userLoading } = useUser(userId)
|
||||
const { data: departments } = useDepartments()
|
||||
const { data: allRoles } = useRoles({ limit: 1000 })
|
||||
const { data: userRoles, isLoading: rolesLoading } = useUserRoles(userId)
|
||||
|
||||
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,
|
||||
role_ids: [] as number[],
|
||||
},
|
||||
})
|
||||
|
||||
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,
|
||||
role_ids: Array.isArray(user.user_roles)
|
||||
? user.user_roles.map((ur) => ur.role_id!)
|
||||
: [],
|
||||
})
|
||||
}
|
||||
}, [user])
|
||||
|
||||
useEffect(() => {
|
||||
if (Array.isArray(userRoles) && userRoles.length > 0) {
|
||||
const roleIds = userRoles
|
||||
.map((ur) => ur.role?.id || ur.role_id)
|
||||
.filter((id): id is number => !!id)
|
||||
form.setFieldValue('role_ids', roleIds)
|
||||
}
|
||||
}, [userRoles])
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
onClose()
|
||||
}
|
||||
|
||||
const handleClearAllRoles = () => {
|
||||
form.setFieldValue('role_ids', [])
|
||||
}
|
||||
|
||||
const handleCopyRoles = (roleIds: number[]) => {
|
||||
form.setFieldValue('role_ids', roleIds)
|
||||
setCopyRolesOpened(false)
|
||||
}
|
||||
|
||||
const departmentOptions = Array.isArray(departments)
|
||||
? departments.map((d) => ({
|
||||
value: String(d.id),
|
||||
label: d.name || '',
|
||||
}))
|
||||
: []
|
||||
|
||||
const roleOptions = Array.isArray(allRoles)
|
||||
? allRoles.map((r) => ({
|
||||
value: String(r.id),
|
||||
label: r.name || '',
|
||||
description: r.description,
|
||||
}))
|
||||
: []
|
||||
|
||||
const isLoading = userLoading || rolesLoading
|
||||
const isSubmitting = updateUser.isPending || assignRoles.isPending
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>Редактирование пользователя</Text>
|
||||
{user && <Badge variant="light">ID: {user.id}</Badge>}
|
||||
</Group>
|
||||
}
|
||||
size="xl"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : user ? (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Tabs defaultValue="info" variant="outline">
|
||||
<Tabs.List mb="md">
|
||||
<Tabs.Tab value="info" leftSection={<IconUser size={14} />}>
|
||||
Информация
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab value="roles" leftSection={<IconShield size={14} />}>
|
||||
Роли ({form.values.role_ids.length})
|
||||
</Tabs.Tab>
|
||||
<Tabs.Tab value="settings" leftSection={<IconSettings size={14} />}>
|
||||
Настройки
|
||||
</Tabs.Tab>
|
||||
</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">
|
||||
<Text size="sm" fw={500}>
|
||||
Выбрано ролей: {form.values.role_ids.length}
|
||||
</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>
|
||||
|
||||
<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>
|
||||
|
||||
{/* Вкладка: Настройки */}
|
||||
<Tabs.Panel value="settings">
|
||||
<Stack gap="md">
|
||||
<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"
|
||||
/>
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
|
||||
<Divider my="md" />
|
||||
|
||||
<Group justify="flex-end">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Group>
|
||||
</form>
|
||||
) : (
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Пользователь не найден</Text>
|
||||
</Center>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<CopyRolesModal
|
||||
opened={copyRolesOpened}
|
||||
onClose={() => setCopyRolesOpened(false)}
|
||||
onCopy={handleCopyRoles}
|
||||
currentUserId={userId}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ import { IconDots, IconPencil, IconSearch, IconTrash } from '@tabler/icons-react
|
|||
import { useUsers, useDeleteUser } from '@/features/users/hooks/useUsers'
|
||||
import { useDepartments } from '@/features/users/hooks/useDepartments'
|
||||
import { useRoles } from '@/features/users/hooks/useRoles'
|
||||
import UserEditModal from '@/components/UserEditModal.tsx'
|
||||
import UserEditDrawer from '@/components/UserEditDrawer'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
|
|
@ -231,7 +231,7 @@ export default function UsersPage() {
|
|||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<UserEditModal
|
||||
<UserEditDrawer
|
||||
userId={editUserId}
|
||||
opened={editUserId !== null}
|
||||
onClose={() => setEditUserId(null)}
|
||||
|
|
|
|||
Loading…
Reference in New Issue