From ca9736af219921a0f2943f64e455234f12e402f1 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Wed, 18 Nov 2026 15:19:14 +0300 Subject: [PATCH] Updated admin log page --- src/pages/adminLogs/AdminLogsPage.tsx | 512 ++++++++---------- .../components/AdminLogDetailModal.tsx | 105 ---- .../adminLogs/components/AdminLogDrawer.tsx | 131 +++++ 3 files changed, 359 insertions(+), 389 deletions(-) delete mode 100644 src/pages/adminLogs/components/AdminLogDetailModal.tsx create mode 100644 src/pages/adminLogs/components/AdminLogDrawer.tsx diff --git a/src/pages/adminLogs/AdminLogsPage.tsx b/src/pages/adminLogs/AdminLogsPage.tsx index f4c6f1f..5a77dad 100644 --- a/src/pages/adminLogs/AdminLogsPage.tsx +++ b/src/pages/adminLogs/AdminLogsPage.tsx @@ -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 = { - create: 'green', - update: 'blue', - delete: 'red', -} -const ACTION_LABELS: Record = { - create: 'Создание', - update: 'Изменение', - delete: 'Удаление', +const ACTION_META: Record = { + 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(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 [filters, setFilters] = useState(EMPTY_FILTERS) + const [searchInput, setSearchInput] = useState('') + const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400) + const [selectedLog, setSelectedLog] = useState(null) + const [deleteTarget, setDeleteTarget] = 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') }), - }) + // При изменении текстового поиска сбрасываем страницу на первую + 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) => { + setFilters((prev) => ({ ...prev, ...patch })) setPage(1) } - const handleDelete = (entry: AdminActionLog) => { - modals.openConfirmModal({ - title: 'Удалить запись журнала?', - children: ( - - Это действие доступно только root-администратору и необратимо. - Обычно записи журнала не удаляют — используйте только если запись - ошибочна или содержит чувствительные данные, которые нужно убрать. - + const requestParams = useMemo(() => { + const params: Record = { 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[] = [ + { + key: 'created', + header: 'Когда', + width: 150, + cell: (r) => {formatMsk(r.created_at)}, + }, + { + key: 'admin', + header: 'Администратор', + cell: (r) => {r.admin_login}, + }, + { + key: 'action', + header: 'Действие', + width: 140, + cell: (r) => { + const meta = ACTION_META[r.action] + return ( + + {meta?.label || r.action} + + ) + }, + }, + { + key: 'entity', + header: 'Сущность', + width: 180, + cell: (r) => ( + + {r.entity_type}{r.entity_id ? ` #${r.entity_id}` : ''} + + ), + }, + { + key: 'description', + header: 'Описание', + cell: (r) => {r.description}, + }, + ] + + if (isRoot) { + columns.push({ + key: 'actions', + header: '', + width: 60, + align: 'right', + cell: (r) => ( + + { + e.stopPropagation() // Чтобы не открывался Drawer просмотра + setDeleteTarget(r) + }} + > + + + ), - labels: { confirm: 'Удалить', cancel: 'Отмена' }, - confirmProps: { color: 'red' }, - onConfirm: () => deleteLog.mutate(entry.id), }) } return ( - - - Журнал действий администраторов - Всего: {totalCount} - + + - - - - } - value={adminLogin} - onChange={(e) => { - setAdminLogin(e.currentTarget.value) - setPage(1) - }} - /> + + } + value={searchInput} + onChange={(e) => setSearchInput(e.currentTarget.value)} + w={220} + /> + updateFilter({ adminLogin: e.currentTarget.value })} + w={150} + /> + updateFilter({ entityType })} + searchable + clearable + w={180} + /> + updateFilter({ entityId: e.currentTarget.value.replace(/\D/g, '') })} + w={110} + /> + } + value={filters.range} + onChange={(range) => updateFilter({ range: range as [Date | null, Date | null] })} + clearable + w={240} + /> + - { - 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)}> - - - {formatMsk(entry.created_at)} - - - - {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)} /> + + setDeleteTarget(null)} + onConfirm={handleDelete} + title="Удалить запись журнала?" + message="Это действие необратимо. Обычно записи журнала не удаляют — используйте это только если лог содержит чувствительные данные." + confirmLabel="Удалить безвозвратно" + danger + loading={deleteLog.isPending} + />
) } \ No newline at end of file diff --git a/src/pages/adminLogs/components/AdminLogDetailModal.tsx b/src/pages/adminLogs/components/AdminLogDetailModal.tsx deleted file mode 100644 index 9a4f299..0000000 --- a/src/pages/adminLogs/components/AdminLogDetailModal.tsx +++ /dev/null @@ -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 - [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 diff --git a/src/pages/adminLogs/components/AdminLogDrawer.tsx b/src/pages/adminLogs/components/AdminLogDrawer.tsx new file mode 100644 index 0000000..a0ebc52 --- /dev/null +++ b/src/pages/adminLogs/components/AdminLogDrawer.tsx @@ -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 ( + + {title} + {children} + + ) +} + +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 + [key: string]: unknown + } + } catch { + return null + } + }, [log]) + + return ( + + + + + + + Журнал: {log?.entity_type} + {log?.entity_id && #{log.entity_id}} + + + {log?.created_at ? formatMsk(log.created_at) : ''} + + + + + + + {!log ? null : ( + + + + {log.admin_login} + + + {log.action} + + + {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]) => ( + + + {formatValue(value)} + + + ))} + +
+ )} + + {!parsed?.changes && !parsed?.snapshot && parsed && ( +
+ + {JSON.stringify(parsed, null, 2)} + +
+ )} +
+ )} +
+
+
+ ) +} \ No newline at end of file