diff --git a/src/App.tsx b/src/App.tsx index c298ccb..0f63c44 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 }) => (
@@ -70,6 +71,7 @@ function App() { } /> } /> } /> + } /> } /> } /> diff --git a/src/api/adminLogs.ts b/src/api/adminLogs.ts new file mode 100644 index 0000000..4a5841c --- /dev/null +++ b/src/api/adminLogs.ts @@ -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>('/admin-logs', { params }), + + delete: (id: number) => + apiClient.delete(`/admin-logs/${id}`), +} \ No newline at end of file diff --git a/src/components/Layout/Sidebar.tsx b/src/components/Layout/Sidebar.tsx index 502129f..42b3c86 100644 --- a/src/components/Layout/Sidebar.tsx +++ b/src/components/Layout/Sidebar.tsx @@ -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, diff --git a/src/features/adminLogs/hooks/useAdminLogs.ts b/src/features/adminLogs/hooks/useAdminLogs.ts new file mode 100644 index 0000000..6fc5b19 --- /dev/null +++ b/src/features/adminLogs/hooks/useAdminLogs.ts @@ -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', + }) + }, + }) +} \ No newline at end of file diff --git a/src/pages/adminLogs/AdminLogsPage.tsx b/src/pages/adminLogs/AdminLogsPage.tsx new file mode 100644 index 0000000..a808e0d --- /dev/null +++ b/src/pages/adminLogs/AdminLogsPage.tsx @@ -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 = { + create: 'green', + update: 'blue', + delete: 'red', +} +const ACTION_LABELS: Record = { + 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(null) + const [entityType, setEntityType] = useState(null) + const [entityId, setEntityId] = useState('') + const [search, setSearch] = useState('') + const [dateFrom, setDateFrom] = useState(null) + const [dateTo, setDateTo] = useState(null) + const [selectedLog, setSelectedLog] = useState(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: ( + + Это действие доступно только root-администратору и необратимо. + Обычно записи журнала не удаляют — используйте только если запись + ошибочна или содержит чувствительные данные, которые нужно убрать. + + ), + labels: { confirm: 'Удалить', cancel: 'Отмена' }, + confirmProps: { color: 'red' }, + onConfirm: () => deleteLog.mutate(entry.id), + }) + } + + return ( + + + Журнал действий администраторов + Всего: {totalCount} + + + + + + } + value={adminLogin} + onChange={(e) => { + setAdminLogin(e.currentTarget.value) + setPage(1) + }} + /> + + { + setEntityType(v) + setPage(1) + }} + clearable + searchable + /> + + { + setEntityId(e.currentTarget.value.replace(/\D/g, '')) + setPage(1) + }} + /> + + + + } + value={search} + onChange={(e) => { + setSearch(e.currentTarget.value) + setPage(1) + }} + rightSection={ + search && ( + setSearch('')}> + + + ) + } + /> + { + setDateFrom(val as Date | null) + setPage(1) + }} + clearable + maxDate={dateTo || undefined} + /> + { + setDateTo(val as Date | null) + setPage(1) + }} + clearable + minDate={dateFrom || undefined} + /> + + {hasActiveFilters && ( + + + + )} + + + + + + + {isLoading ? ( +
+ +
+ ) : ( + <> + + + + Когда + Администратор + Действие + Сущность + Описание + — + + + + {logs.length === 0 ? ( + + +
+ Записей не найдено +
+
+
+ ) : ( + logs.map((entry) => ( + setSelectedLog(entry)}> + + + {dayjs(entry.created_at).format('DD.MM.YYYY HH:mm')} + + + + {entry.admin_login} + + + + {ACTION_LABELS[entry.action] || entry.action} + + + + + {entry.entity_type}{entry.entity_id ? ` #${entry.entity_id}` : ''} + + + + {entry.description} + + e.stopPropagation()}> + + + setSelectedLog(entry)}> + + + + {isRoot && ( + + handleDelete(entry)}> + + + + )} + + + + )) + )} +
+
+ + {totalPages > 1 && ( + + + Страница {page} из {totalPages} + + + + )} + + )} +
+ + {isFetching && !isLoading && ( + + + + )} + + setSelectedLog(null)} + /> +
+ ) +} \ No newline at end of file diff --git a/src/pages/adminLogs/components/AdminLogDetailModal.tsx b/src/pages/adminLogs/components/AdminLogDetailModal.tsx new file mode 100644 index 0000000..9a4f299 --- /dev/null +++ b/src/pages/adminLogs/components/AdminLogDetailModal.tsx @@ -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 + [key: string]: unknown + } + } catch { + return null + } + }, [log]) + + return ( + + {!log ? null : ( + + + {log.admin_login} + {log.entity_type} + + {log.description} + + {parsed?.changes && parsed.changes.length > 0 && ( + + + + Поле + Было + Стало + + + + {parsed.changes.map((c, i) => ( + + + {c.field} + + + {formatValue(c.old)} + + + {formatValue(c.new)} + + + ))} + +
+ )} + + {parsed?.snapshot && ( + + + {Object.entries(parsed.snapshot).map(([key, value]) => ( + + + {key} + + + {formatValue(value)} + + + ))} + +
+ )} + + {!parsed?.changes && !parsed?.snapshot && parsed && ( + {JSON.stringify(parsed, null, 2)} + )} + + {!log.metadata && ( +
+ Дополнительных данных нет +
+ )} +
+ )} +
+ ) +} \ No newline at end of file