Updated admin log page
Deploy Frontend / build-and-deploy (push) Successful in 30s Details

This commit is contained in:
romanskijdev 2026-11-18 15:19:14 +03:00
parent ae43fdae60
commit ca9736af21
3 changed files with 359 additions and 389 deletions

View File

@ -1,47 +1,33 @@
import { useState } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Badge,
} from '@mantine/core'
import { useEffect, useMemo, useState } from 'react'
import { ActionIcon, Badge, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import { IconTrash, IconSearch, IconX, IconEye } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
import { useDebouncedValue } from '@mantine/hooks'
import { IconCalendar, IconSearch, IconTrash } from '@tabler/icons-react'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import { useAuth } from '@/hooks/useAuth'
import { useAdminLogs, useDeleteAdminLog } from '@/features/adminLogs/hooks/useAdminLogs'
import type { AdminActionLog } from '@/api/adminLogs'
import AdminLogDetailModal from './components/AdminLogDetailModal'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import {formatMsk} from "@/utils/date.ts";
import { formatMsk } from '@/utils/date'
import { PageHeader } from '@/components/ui/PageHeader'
import { FilterBar } from '@/components/ui/FilterBar'
import { DataTable, type Column } from '@/components/ui/DataTable'
import { ConfirmModal } from '@/components/ui/ConfirmModal'
import AdminLogDrawer from './components/AdminLogDrawer'
dayjs.locale('ru')
const LIMIT = 50
const ACTION_COLORS: Record<string, string> = {
create: 'green',
update: 'blue',
delete: 'red',
}
const ACTION_LABELS: Record<string, string> = {
create: 'Создание',
update: 'Изменение',
delete: 'Удаление',
const ACTION_META: Record<string, { label: string; color: string }> = {
create: { label: 'Создание', color: 'green' },
update: { label: 'Изменение', color: 'blue' },
delete: { label: 'Удаление', color: 'red' },
}
const ENTITY_TYPE_OPTIONS = [
const ENTITY_OPTIONS = [
{ value: 'user', label: 'Пользователь' },
{ value: 'admin', label: 'Администратор' },
{ value: 'department', label: 'Отдел' },
@ -49,285 +35,243 @@ const ENTITY_TYPE_OPTIONS = [
{ value: 'permission', label: 'Право' },
{ value: 'category', label: 'Категория' },
{ value: 'topic', label: 'Тема' },
{ value: 'topic_executor', label: 'Исполнитель темы' },
{ value: 'hierarchy', label: 'Иерархия' },
{ value: 'flow_node', label: 'Узел дерева' },
{ value: 'flow_tree', label: 'Дерево категории' },
{ value: 'user_role', label: 'Роль пользователя' },
{ value: 'user_roles', label: 'Роли пользователя (массово)' },
{ value: 'approval_task', label: 'Задача' },
{ value: 'notification', label: 'Рассылка' },
]
export default function AdminLogPage() {
interface Filters {
adminLogin: string
action: string | null
entityType: string | null
entityId: string
range: [Date | null, Date | null]
}
const EMPTY_FILTERS: Filters = {
adminLogin: '',
action: null,
entityType: null,
entityId: '',
range: [null, null],
}
const fmtDate = (d: Date) => dayjs(d).format('YYYY-MM-DD')
export default function AdminLogsPage() {
const { user: currentUser } = useAuth()
const isRoot = currentUser?.is_root === true
const [page, setPage] = useState(1)
const [adminLogin, setAdminLogin] = useState('')
const [action, setAction] = useState<string | null>(null)
const [entityType, setEntityType] = useState<string | null>(null)
const [entityId, setEntityId] = useState('')
const [search, setSearch] = useState('')
const [dateFrom, setDateFrom] = useState<Date | null>(null)
const [dateTo, setDateTo] = useState<Date | null>(null)
const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS)
const [searchInput, setSearchInput] = useState('')
const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400)
const [selectedLog, setSelectedLog] = useState<AdminActionLog | null>(null)
const [deleteTarget, setDeleteTarget] = useState<AdminActionLog | null>(null)
const { data, isLoading, isFetching } = useAdminLogs({
offset: (page - 1) * LIMIT,
limit: LIMIT,
...(adminLogin && { admin_login: adminLogin }),
...(action && { action }),
...(entityType && { entity_type: entityType }),
...(entityId && { entity_id: Number(entityId) }),
...(search && { search }),
...(dateFrom && { date_from: dayjs(dateFrom).format('YYYY-MM-DD') }),
...(dateTo && { date_to: dayjs(dateTo).format('YYYY-MM-DD') }),
})
// При изменении текстового поиска сбрасываем страницу на первую
useEffect(() => setPage(1), [debouncedSearch])
const deleteLog = useDeleteAdminLog()
const logs = data?.data || []
const totalCount = data?.total_count || 0
const totalPages = totalCount ? Math.ceil(totalCount / LIMIT) : 1
const hasActiveFilters = adminLogin || action || entityType || entityId || search || dateFrom || dateTo
const handleResetFilters = () => {
setAdminLogin('')
setAction(null)
setEntityType(null)
setEntityId('')
setSearch('')
setDateFrom(null)
setDateTo(null)
const updateFilter = (patch: Partial<Filters>) => {
setFilters((prev) => ({ ...prev, ...patch }))
setPage(1)
}
const handleDelete = (entry: AdminActionLog) => {
modals.openConfirmModal({
title: 'Удалить запись журнала?',
children: (
<Text size="sm">
Это действие доступно только root-администратору и необратимо.
Обычно записи журнала не удаляют — используйте только если запись
ошибочна или содержит чувствительные данные, которые нужно убрать.
</Text>
const requestParams = useMemo(() => {
const params: Record<string, any> = { offset: (page - 1) * LIMIT, limit: LIMIT }
if (filters.adminLogin) params.admin_login = filters.adminLogin
if (filters.action) params.action = filters.action
if (filters.entityType) params.entity_type = filters.entityType
if (filters.entityId) params.entity_id = Number(filters.entityId)
if (debouncedSearch.length >= 2) params.search = debouncedSearch
if (filters.range[0]) params.date_from = fmtDate(filters.range[0])
if (filters.range[1]) params.date_to = fmtDate(filters.range[1])
return params
}, [page, filters, debouncedSearch])
const { data, isLoading, isFetching } = useAdminLogs(requestParams)
const deleteLog = useDeleteAdminLog()
const total = data?.total_count ?? 0
const activeCount = [
filters.adminLogin,
filters.action,
filters.entityType,
filters.entityId,
debouncedSearch.length >= 2,
filters.range[0] || filters.range[1],
].filter(Boolean).length
const handleReset = () => {
setSearchInput('')
setFilters(EMPTY_FILTERS)
setPage(1)
}
const handleDelete = async () => {
if (!deleteTarget) return
await deleteLog.mutateAsync(deleteTarget.id)
setDeleteTarget(null)
}
const columns: Column<AdminActionLog>[] = [
{
key: 'created',
header: 'Когда',
width: 150,
cell: (r) => <Text size="sm" c="dimmed">{formatMsk(r.created_at)}</Text>,
},
{
key: 'admin',
header: 'Администратор',
cell: (r) => <Text size="sm" fw={500}>{r.admin_login}</Text>,
},
{
key: 'action',
header: 'Действие',
width: 140,
cell: (r) => {
const meta = ACTION_META[r.action]
return (
<Badge variant="light" color={meta?.color || 'gray'} size="sm">
{meta?.label || r.action}
</Badge>
)
},
},
{
key: 'entity',
header: 'Сущность',
width: 180,
cell: (r) => (
<Badge variant="outline" color="gray" size="sm" tt="none">
{r.entity_type}{r.entity_id ? ` #${r.entity_id}` : ''}
</Badge>
),
},
{
key: 'description',
header: 'Описание',
cell: (r) => <Text size="sm" lineClamp={2}>{r.description}</Text>,
},
]
if (isRoot) {
columns.push({
key: 'actions',
header: '',
width: 60,
align: 'right',
cell: (r) => (
<Tooltip label="Удалить (только root)">
<ActionIcon
variant="subtle"
color="red"
onClick={(e) => {
e.stopPropagation() // Чтобы не открывался Drawer просмотра
setDeleteTarget(r)
}}
>
<IconTrash size={16} />
</ActionIcon>
</Tooltip>
),
labels: { confirm: 'Удалить', cancel: 'Отмена' },
confirmProps: { color: 'red' },
onConfirm: () => deleteLog.mutate(entry.id),
})
}
return (
<Stack gap="md">
<Group justify="space-between">
<Text size="xl" fw={700}>Журнал действий администраторов</Text>
<Text c="dimmed" size="sm">Всего: {totalCount}</Text>
</Group>
<Stack gap="lg">
<PageHeader
title="Журнал действий администраторов"
description={isLoading ? undefined : `Всего записей: ${total}`}
/>
<Paper withBorder p="md">
<Stack gap="md">
<Group gap="md" align="flex-end" grow>
<TextInput
label="Администратор"
placeholder="Логин..."
leftSection={<IconSearch size={16} />}
value={adminLogin}
onChange={(e) => {
setAdminLogin(e.currentTarget.value)
setPage(1)
}}
/>
<FilterBar activeCount={activeCount} onReset={handleReset}>
<TextInput
placeholder="Поиск по описанию"
leftSection={<IconSearch size={16} />}
value={searchInput}
onChange={(e) => setSearchInput(e.currentTarget.value)}
w={220}
/>
<TextInput
placeholder="Администратор"
value={filters.adminLogin}
onChange={(e) => updateFilter({ adminLogin: e.currentTarget.value })}
w={150}
/>
<Select
placeholder="Действие"
data={[
{ value: 'create', label: 'Создание' },
{ value: 'update', label: 'Изменение' },
{ value: 'delete', label: 'Удаление' },
]}
value={filters.action}
onChange={(action) => updateFilter({ action })}
clearable
w={140}
/>
<Select
placeholder="Тип сущности"
data={ENTITY_OPTIONS}
value={filters.entityType}
onChange={(entityType) => updateFilter({ entityType })}
searchable
clearable
w={180}
/>
<TextInput
placeholder="ID сущности"
value={filters.entityId}
onChange={(e) => updateFilter({ entityId: e.currentTarget.value.replace(/\D/g, '') })}
w={110}
/>
<DatePickerInput
type="range"
placeholder="Период"
valueFormat="D MMM YYYY"
leftSection={<IconCalendar size={16} />}
value={filters.range}
onChange={(range) => updateFilter({ range: range as [Date | null, Date | null] })}
clearable
w={240}
/>
</FilterBar>
<Select
label="Действие"
placeholder="Все"
data={[
{ value: 'create', label: 'Создание' },
{ value: 'update', label: 'Изменение' },
{ value: 'delete', label: 'Удаление' },
]}
value={action}
onChange={(v) => {
setAction(v)
setPage(1)
}}
clearable
/>
<DataTable<AdminActionLog>
columns={columns}
rows={data?.data ?? []}
getRowId={(r) => r.id}
loading={isLoading}
refreshing={isFetching}
onRowClick={setSelectedLog}
empty={{
title: 'Записей не найдено',
description: activeCount > 0 ? 'Попробуйте смягчить фильтры' : undefined,
}}
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
/>
<Select
label="Тип сущности"
placeholder="Все"
data={ENTITY_TYPE_OPTIONS}
value={entityType}
onChange={(v) => {
setEntityType(v)
setPage(1)
}}
clearable
searchable
/>
<TextInput
label="ID сущности"
placeholder="Например, 19"
value={entityId}
onChange={(e) => {
setEntityId(e.currentTarget.value.replace(/\D/g, ''))
setPage(1)
}}
/>
</Group>
<Group gap="md" align="flex-end" grow>
<TextInput
label="Поиск по описанию"
placeholder="Введите текст..."
leftSection={<IconSearch size={16} />}
value={search}
onChange={(e) => {
setSearch(e.currentTarget.value)
setPage(1)
}}
rightSection={
search && (
<ActionIcon variant="subtle" onClick={() => setSearch('')}>
<IconX size={14} />
</ActionIcon>
)
}
/>
<DatePickerInput
label="С даты"
placeholder="Выберите дату"
value={dateFrom}
onChange={(val) => {
setDateFrom(val as Date | null)
setPage(1)
}}
clearable
maxDate={dateTo || undefined}
/>
<DatePickerInput
label="По дату"
placeholder="Выберите дату"
value={dateTo}
onChange={(val) => {
setDateTo(val as Date | null)
setPage(1)
}}
clearable
minDate={dateFrom || undefined}
/>
<Box>
{hasActiveFilters && (
<ActionIcon variant="light" color="gray" size="lg" onClick={handleResetFilters} title="Сбросить фильтры">
<IconX size={16} />
</ActionIcon>
)}
</Box>
</Group>
</Stack>
</Paper>
<Paper withBorder>
{isLoading ? (
<Center p={60}>
<Loader />
</Center>
) : (
<>
<Table striped highlightOnHover>
<Table.Thead>
<Table.Tr>
<Table.Th style={{ width: 160 }}>Когда</Table.Th>
<Table.Th>Администратор</Table.Th>
<Table.Th style={{ width: 120 }}>Действие</Table.Th>
<Table.Th style={{ width: 160 }}>Сущность</Table.Th>
<Table.Th>Описание</Table.Th>
<Table.Th style={{ width: 90 }}>—</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{logs.length === 0 ? (
<Table.Tr>
<Table.Td colSpan={6}>
<Center p={40}>
<Text c="dimmed">Записей не найдено</Text>
</Center>
</Table.Td>
</Table.Tr>
) : (
logs.map((entry) => (
<Table.Tr key={entry.id} style={{ cursor: 'pointer' }} onClick={() => setSelectedLog(entry)}>
<Table.Td>
<Text size="xs" c="dimmed">
{formatMsk(entry.created_at)}
</Text>
</Table.Td>
<Table.Td>
<Text size="sm" fw={500}>{entry.admin_login}</Text>
</Table.Td>
<Table.Td>
<Badge size="sm" color={ACTION_COLORS[entry.action] || 'gray'} variant="light">
{ACTION_LABELS[entry.action] || entry.action}
</Badge>
</Table.Td>
<Table.Td>
<Badge size="sm" variant="outline" color="gray">
{entry.entity_type}{entry.entity_id ? ` #${entry.entity_id}` : ''}
</Badge>
</Table.Td>
<Table.Td>
<Text size="sm" lineClamp={1}>{entry.description}</Text>
</Table.Td>
<Table.Td onClick={(e) => e.stopPropagation()}>
<Group gap="xs">
<Tooltip label="Детали">
<ActionIcon variant="light" color="blue" onClick={() => setSelectedLog(entry)}>
<IconEye size={14} />
</ActionIcon>
</Tooltip>
{isRoot && (
<Tooltip label="Удалить (только root)">
<ActionIcon variant="light" color="red" onClick={() => handleDelete(entry)}>
<IconTrash size={14} />
</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>
)}
<AdminLogDetailModal
<AdminLogDrawer
log={selectedLog}
opened={selectedLog !== null}
onClose={() => setSelectedLog(null)}
/>
<ConfirmModal
opened={deleteTarget !== null}
onClose={() => setDeleteTarget(null)}
onConfirm={handleDelete}
title="Удалить запись журнала?"
message="Это действие необратимо. Обычно записи журнала не удаляют — используйте это только если лог содержит чувствительные данные."
confirmLabel="Удалить безвозвратно"
danger
loading={deleteLog.isPending}
/>
</Stack>
)
}

View File

@ -1,105 +0,0 @@
import { useMemo } from 'react'
import { Modal, Stack, Text, Table, Badge, Group, Code, Center } from '@mantine/core'
import type { AdminActionLog } from '@/api/adminLogs'
interface FieldChange {
field: string
old: unknown
new: unknown
}
interface AdminLogDetailModalProps {
log: AdminActionLog | null
opened: boolean
onClose: () => void
}
function formatValue(v: unknown): string {
if (v === null || v === undefined || v === '') return '—'
if (typeof v === 'boolean') return v ? 'да' : 'нет'
if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
return String(v)
}
export default function AdminLogDetailModal({ log, opened, onClose }: AdminLogDetailModalProps) {
const parsed = useMemo(() => {
if (!log?.metadata) return null
try {
return JSON.parse(log.metadata) as {
changes?: FieldChange[]
snapshot?: Record<string, unknown>
[key: string]: unknown
}
} catch {
return null
}
}, [log])
return (
<Modal opened={opened} onClose={onClose} title="Детали действия" size="lg">
{!log ? null : (
<Stack gap="md">
<Group justify="space-between">
<Text size="sm" c="dimmed">{log.admin_login}</Text>
<Badge variant="light">{log.entity_type}</Badge>
</Group>
<Text>{log.description}</Text>
{parsed?.changes && parsed.changes.length > 0 && (
<Table striped withTableBorder>
<Table.Thead>
<Table.Tr>
<Table.Th>Поле</Table.Th>
<Table.Th>Было</Table.Th>
<Table.Th>Стало</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{parsed.changes.map((c, i) => (
<Table.Tr key={i}>
<Table.Td>
<Text size="sm" ff="monospace">{c.field}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="red">{formatValue(c.old)}</Text>
</Table.Td>
<Table.Td>
<Text size="sm" c="green">{formatValue(c.new)}</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
{parsed?.snapshot && (
<Table striped withTableBorder>
<Table.Tbody>
{Object.entries(parsed.snapshot).map(([key, value]) => (
<Table.Tr key={key}>
<Table.Td>
<Text size="sm" ff="monospace" c="dimmed">{key}</Text>
</Table.Td>
<Table.Td>
<Text size="sm">{formatValue(value)}</Text>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
)}
{!parsed?.changes && !parsed?.snapshot && parsed && (
<Code block>{JSON.stringify(parsed, null, 2)}</Code>
)}
{!log.metadata && (
<Center p="md">
<Text c="dimmed" size="sm">Дополнительных данных нет</Text>
</Center>
)}
</Stack>
)}
</Modal>
)
}

View File

@ -0,0 +1,131 @@
import { useMemo } from 'react'
import { Badge, Box, Code, Drawer, Group, Stack, Text } from '@mantine/core'
import { IconArrowRight } from '@tabler/icons-react'
import type { AdminActionLog } from '@/api/adminLogs'
import { InfoList, InfoRow } from '@/components/ui/InfoRow'
import { formatMsk } from '@/utils/date'
interface FieldChange {
field: string
old: unknown
new: unknown
}
interface Props {
log: AdminActionLog | null
opened: boolean
onClose: () => void
}
function formatValue(v: unknown): string {
if (v === null || v === undefined || v === '') return '—'
if (typeof v === 'boolean') return v ? 'Да' : 'Нет'
if (Array.isArray(v)) return v.length ? v.join(', ') : '—'
if (typeof v === 'object') return JSON.stringify(v)
return String(v)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<Box>
<Text size="sm" fw={600} mb="xs">{title}</Text>
{children}
</Box>
)
}
export default function AdminLogDrawer({ log, opened, onClose }: Props) {
const parsed = useMemo(() => {
if (!log?.metadata) return null
try {
return JSON.parse(log.metadata) as {
changes?: FieldChange[]
snapshot?: Record<string, unknown>
[key: string]: unknown
}
} catch {
return null
}
}, [log])
return (
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(600px, 100vw)">
<Drawer.Overlay backgroundOpacity={0.25} />
<Drawer.Content>
<Drawer.Header>
<Box style={{ minWidth: 0 }}>
<Group gap="sm" wrap="nowrap">
<Text fw={600}>Журнал: {log?.entity_type}</Text>
{log?.entity_id && <Badge variant="outline" color="gray" tt="none">#{log.entity_id}</Badge>}
</Group>
<Text size="xs" c="dimmed" mt={2}>
{log?.created_at ? formatMsk(log.created_at) : ''}
</Text>
</Box>
<Drawer.CloseButton />
</Drawer.Header>
<Drawer.Body pb="xl">
{!log ? null : (
<Stack gap="xl" mt="sm">
<InfoList>
<InfoRow label="Администратор">
<Text size="sm" fw={500}>{log.admin_login}</Text>
</InfoRow>
<InfoRow label="Тип действия">
<Text size="sm">{log.action}</Text>
</InfoRow>
<InfoRow label="Описание">
<Text size="sm" style={{ textAlign: 'right' }}>{log.description}</Text>
</InfoRow>
</InfoList>
{parsed?.changes && parsed.changes.length > 0 && (
<Section title="Измененные поля">
<Stack gap={0}>
{parsed.changes.map((c, i) => (
<Box key={i} py={8} style={{ borderBottom: '1px solid var(--mantine-color-default-border)' }}>
<Text size="sm" ff="monospace" mb={4}>{c.field}</Text>
<Group gap="sm" wrap="nowrap">
<Text size="sm" c="red" style={{ flex: 1, wordBreak: 'break-word' }}>
{formatValue(c.old)}
</Text>
<IconArrowRight size={14} color="var(--mantine-color-dimmed)" />
<Text size="sm" c="green" style={{ flex: 1, wordBreak: 'break-word' }}>
{formatValue(c.new)}
</Text>
</Group>
</Box>
))}
</Stack>
</Section>
)}
{parsed?.snapshot && (
<Section title="Снапшот объекта">
<InfoList>
{Object.entries(parsed.snapshot).map(([key, value]) => (
<InfoRow key={key} label={key}>
<Text size="sm" style={{ textAlign: 'right', wordBreak: 'break-word', maxWidth: 280 }}>
{formatValue(value)}
</Text>
</InfoRow>
))}
</InfoList>
</Section>
)}
{!parsed?.changes && !parsed?.snapshot && parsed && (
<Section title="Сырые метаданные (JSON)">
<Code block style={{ whiteSpace: 'pre-wrap' }}>
{JSON.stringify(parsed, null, 2)}
</Code>
</Section>
)}
</Stack>
)}
</Drawer.Body>
</Drawer.Content>
</Drawer.Root>
)
}