Added admin action history page
Deploy Frontend / build-and-deploy (push) Successful in 29s Details

This commit is contained in:
romanskijdev 2026-07-28 11:40:00 +03:00
parent 54919969f4
commit 2531e830b8
6 changed files with 514 additions and 0 deletions

View File

@ -21,6 +21,7 @@ import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx";
import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage'
import NotificationsPage from "@/pages/notifications/NotificationsPage.tsx";
import {ModalsProvider} from "@mantine/modals";
import AdminLogsPage from './pages/adminLogs/AdminLogsPage'
const Placeholder = ({ title }: { title: string }) => (
<div style={{ padding: 40 }}>
@ -70,6 +71,7 @@ function App() {
<Route path="/hierarchies" element={<HierarchiesPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/admins" element={<AdminsPage />} />
<Route path="/logs" element={<AdminLogsPage />} />
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
</Route>

35
src/api/adminLogs.ts Normal file
View File

@ -0,0 +1,35 @@
import apiClient from './client'
import type { ApiResponse } from '@/types/api'
export interface AdminActionLog {
id: number
admin_id: number
admin_login: string
action: 'create' | 'update' | 'delete'
entity_type: string
entity_id?: number
description: string
metadata?: string
created_at: string
}
export interface AdminLogsListParams {
offset?: number
limit?: number
admin_id?: number
admin_login?: string
action?: string
entity_type?: string
entity_id?: number
date_from?: string
date_to?: string
search?: string
}
export const adminLogsApi = {
getList: (params: AdminLogsListParams = {}) =>
apiClient.get<ApiResponse<AdminActionLog[]>>('/admin-logs', { params }),
delete: (id: number) =>
apiClient.delete<boolean>(`/admin-logs/${id}`),
}

View File

@ -18,6 +18,7 @@ import {
IconCheck,
IconBellRinging,
IconBlocks,
IconHistory,
} from '@tabler/icons-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '@/hooks/useAuth'
@ -34,6 +35,7 @@ const menuItems: MenuItem[] = [
{ label: 'Обзор', icon: IconDashboard, path: '/' },
{ label: 'Администраторы', icon: IconUserCog, path: '/admins', adminOnly: true },
{ label: 'Уведомления', icon: IconBellRinging, path: '/notifications', adminOnly: true },
{ label: 'Журнал действий', icon: IconHistory, path: '/logs', adminOnly: true },
{
label: 'Система согласований',
icon: IconFileCheck,

View File

@ -0,0 +1,38 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { adminLogsApi, type AdminLogsListParams } from '@/api/adminLogs'
import { notifications } from '@mantine/notifications'
export const ADMIN_LOGS_QUERY_KEY = 'admin-logs'
export function useAdminLogs(params: AdminLogsListParams = {}) {
return useQuery({
queryKey: [ADMIN_LOGS_QUERY_KEY, params],
queryFn: async () => {
const response = await adminLogsApi.getList(params)
return response.data
},
})
}
export function useDeleteAdminLog() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (id: number) => adminLogsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [ADMIN_LOGS_QUERY_KEY] })
notifications.show({
title: 'Успешно',
message: 'Запись журнала удалена',
color: 'green',
})
},
onError: (error: any) => {
notifications.show({
title: 'Ошибка',
message: error.response?.data?.error_description || 'Не удалось удалить запись (доступно только root-администратору)',
color: 'red',
})
},
})
}

View File

@ -0,0 +1,332 @@
import { useState } from 'react'
import {
Paper,
Table,
Group,
ActionIcon,
Text,
TextInput,
Select,
Pagination,
Loader,
Center,
Tooltip,
Box,
Stack,
Badge,
} from '@mantine/core'
import { DatePickerInput } from '@mantine/dates'
import { IconTrash, IconSearch, IconX, IconEye } from '@tabler/icons-react'
import { modals } from '@mantine/modals'
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'
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 ENTITY_TYPE_OPTIONS = [
{ value: 'user', label: 'Пользователь' },
{ value: 'admin', label: 'Администратор' },
{ value: 'department', label: 'Отдел' },
{ value: 'role', label: 'Роль' },
{ 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() {
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 [selectedLog, setSelectedLog] = 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') }),
})
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)
setPage(1)
}
const handleDelete = (entry: AdminActionLog) => {
modals.openConfirmModal({
title: 'Удалить запись журнала?',
children: (
<Text size="sm">
Это действие доступно только root-администратору и необратимо.
Обычно записи журнала не удаляют — используйте только если запись
ошибочна или содержит чувствительные данные, которые нужно убрать.
</Text>
),
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>
<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)
}}
/>
<Select
label="Действие"
placeholder="Все"
data={[
{ value: 'create', label: 'Создание' },
{ value: 'update', label: 'Изменение' },
{ value: 'delete', label: 'Удаление' },
]}
value={action}
onChange={(v) => {
setAction(v)
setPage(1)
}}
clearable
/>
<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">
{dayjs(entry.created_at).format('DD.MM.YYYY HH:mm')}
</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
log={selectedLog}
opened={selectedLog !== null}
onClose={() => setSelectedLog(null)}
/>
</Stack>
)
}

View File

@ -0,0 +1,105 @@
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>
)
}