admin_ruspet/src/pages/admins/AdminsPage.tsx

368 lines
18 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState } from 'react'
import {
Paper,
Table,
Badge,
Group,
ActionIcon,
Button,
Text,
TextInput,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Switch,
} from '@mantine/core'
import {
IconTrash,
IconPlus,
IconSearch,
IconLock,
IconLockOpen,
IconPencil,
IconShield,
} from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications'
import {
useAdmins,
useDeleteAdmin,
useUpdateAdmin
} from '@/features/admins/hooks/useAdmins'
import { useAuth } from '@/hooks/useAuth'
import CreateAdminModal from './components/CreateAdminModal'
import EditAdminModal from './components/EditAdminModal'
import type { Admin } from '@/types/api'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
dayjs.locale('ru')
const LIMIT = 20
export default function AdminsPage() {
const [page, setPage] = useState(1)
const [search, setSearch] = useState('')
const [blockedFilter, setBlockedFilter] = useState<boolean | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false)
const [editAdmin, setEditAdmin] = useState<Admin | null>(null)
const { user: currentUser } = useAuth()
const { data, isLoading, isFetching } = useAdmins({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(search && { login: search }),
...(blockedFilter !== null && { is_blocked: blockedFilter }),
})
const deleteAdmin = useDeleteAdmin()
const updateAdmin = useUpdateAdmin()
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
// 🆕 Проверка, является ли текущий пользователь root
const isRoot = currentUser?.is_root === true
const handleDelete = (id: number, login: string, isAdminRoot: boolean) => {
// Нельзя удалить себя
if (currentUser?.id === id) {
notifications.show({
title: 'Ошибка',
message: 'Вы не можете удалить свой собственный аккаунт',
color: 'red',
})
return
}
// Нельзя удалить root-админа (если текущий не root)
if (isAdminRoot && !isRoot) {
notifications.show({
title: 'Ошибка',
message: 'Только root-администратор может удалять других root-администраторов',
color: 'red',
})
return
}
modals.openConfirmModal({
title: 'Подтвердите удаление',
children: (
<Text size="sm">
Вы уверены, что хотите удалить администратора <b>{login}</b>?
Это действие нельзя отменить.
</Text>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteAdmin.mutate(id),
})
}
const handleToggleBlock = (id: number, login: string, isBlocked: boolean, isAdminRoot: boolean) => {
// Нельзя заблокировать себя
if (currentUser?.id === id) {
notifications.show({
title: 'Ошибка',
message: 'Вы не можете заблокировать свой собственный аккаунт',
color: 'red',
})
return
}
// Нельзя заблокировать root-админа (если текущий не root)
if (isAdminRoot && !isRoot) {
notifications.show({
title: 'Ошибка',
message: 'Только root-администратор может блокировать других root-администраторов',
color: 'red',
})
return
}
const action = isBlocked ? 'разблокировать' : 'заблокировать'
modals.openConfirmModal({
title: 'Подтвердите действие',
children: (
<Text size="sm">
Вы уверены, что хотите {action} администратора <b>{login}</b>?
</Text>
),
labels: { confirm: action.charAt(0).toUpperCase() + action.slice(1), cancel: 'Отмена' },
confirmProps: { color: isBlocked ? 'green' : 'red' },
onConfirm: () => updateAdmin.mutate({ id, is_blocked: !isBlocked }),
})
}
return (
<Stack gap="md">
{/* Заголовок */}
<Group justify="space-between">
<Text size="xl" fw={700}>Администраторы</Text>
<Group>
<Text c="dimmed" size="sm">
Всего: {data?.total_count || 0}
</Text>
{isRoot && (
<Button
leftSection={<IconPlus size={16} />}
onClick={() => setCreateModalOpened(true)}
>
Создать администратора
</Button>
)}
</Group>
</Group>
{/* Предупреждение для не-root пользователей */}
{!isRoot && (
<Paper withBorder p="md" bg="yellow.0">
<Text size="sm">
⚠️ Создание новых администраторов доступно только для root-администратора.
</Text>
</Paper>
)}
{/* Фильтры */}
<Paper withBorder p="md">
<Group gap="md" align="flex-end">
<TextInput
label="Поиск по логину"
placeholder="admin_user..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
style={{ flex: 1 }}
/>
<Switch
label="Только заблокированные"
checked={blockedFilter === true}
onChange={(e) => {
setBlockedFilter(e.currentTarget.checked ? true : null)
setPage(1)
}}
/>
</Group>
</Paper>
{/* Таблица */}
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 60 }}>ID</Table.Th>
<Table.Th>Логин</Table.Th>
<Table.Th>Имя</Table.Th>
<Table.Th>Создан</Table.Th>
<Table.Th>Последний вход</Table.Th>
<Table.Th>Последний IP</Table.Th>
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
<Table.Th style={{ width: 140 }}>Действия</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{data?.data?.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={8}>
<Center p={40}>
<Text c="dimmed">Администраторы не найдены</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
(data?.data || []).map((admin) => {
const isCurrentUser = currentUser?.id === admin.id
const isAdminRoot = admin.is_root === true
return (
<Table.Tr key={admin.id}>
<Table.Td>{admin.id}</Table.Td>
<Table.Td>
<Group gap="xs">
<Text fw={500}>{admin.login}</Text>
{isCurrentUser && (
<Badge size="xs" color="blue" variant="light">
Вы
</Badge>
)}
{isAdminRoot && (
<Badge
size="xs"
color="red"
variant="filled"
leftSection={<IconShield size={10} />}
>
ROOT
</Badge>
)}
</Group>
</Table.Td>
<Table.Td>
<Text size="sm">{admin.name || '—'}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{admin.created_at
? dayjs(admin.created_at).format('DD.MM.YYYY')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="dimmed">
{admin.last_login
? dayjs(admin.last_login).format('DD.MM.YYYY HH:mm')
: '—'}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">
{admin.last_ip_login || '—'}
</Text>
</Table.Td>
<Table.Td>
<Badge
color={admin.is_blocked ? 'red' : 'green'}
variant={admin.is_blocked ? 'filled' : 'light'}
>
{admin.is_blocked ? 'Заблокирован' : 'Активен'}
</Badge>
</Table.Td>
<Table.Td>
<Group gap="xs">
<Tooltip label="Редактировать">
<ActionIcon
variant="light"
color="blue"
onClick={() => setEditAdmin(admin)}
>
<IconPencil size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label={admin.is_blocked ? 'Разблокировать' : 'Заблокировать'}>
<ActionIcon
variant="light"
color={admin.is_blocked ? 'green' : 'orange'}
onClick={() => handleToggleBlock(
admin.id!,
admin.login,
admin.is_blocked || false,
isAdminRoot
)}
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
>
{admin.is_blocked ? <IconLockOpen size={16} /> : <IconLock size={16} />}
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon
variant="light"
color="red"
onClick={() => handleDelete(admin.id!, admin.login, isAdminRoot)}
disabled={isCurrentUser || (isAdminRoot && !isRoot)}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
</Group>
</Table.Td>
</Table.Tr>
)
})
)}
</Table.Tbody>
</Table>
{/* Пагинация */}
{totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between">
<Text size="sm" c="dimmed">
Страница {page} из {totalPages}
</Text>
<Pagination
value={page}
onChange={setPage}
total={totalPages}
withEdges
/>
</Group>
</Box>
)}
</>
)}
</Paper>
{/* Индикатор обновления */}
{isFetching && !isLoading && (
<Box style={{ position: 'fixed', top: 70, right: 20, zIndex: 1000 }}>
<Loader size="xs" />
</Box>
)}
{/* Модальные окна */}
<CreateAdminModal
opened={createModalOpened}
onClose={() => setCreateModalOpened(false)}
/>
<EditAdminModal
admin={editAdmin}
opened={editAdmin !== null}
onClose={() => setEditAdmin(null)}
/>
</Stack>
)
}