Route guards, WS lifecycle, ticket stats. Refs EventHub/EventHubFrontAdmin#3

This commit is contained in:
2026-07-07 21:03:46 +03:00
parent 896e3bcd35
commit ecfa1a66bb
18 changed files with 1331 additions and 955 deletions
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
if [ $# -lt 2 ]; then
echo "Usage: git-commit.sh message paths..." >&2
exit 1
fi
MSG=$1
shift
REPO_ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$REPO_ROOT"
git add "$@"
/usr/bin/git commit -m "$MSG"
git log -1 --oneline
+41 -19
View File
@@ -3,12 +3,16 @@ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Spin } from 'antd';
import ProtectedRoute from './components/ProtectedRoute';
import RoleGuard from './components/RoleGuard';
import AdminLayout from './layouts/AdminLayout';
import LoginPage from './pages/auth/LoginPage';
import ProfilePage from './pages/profile/ProfilePage';
import DashboardPage from './pages/dashboard/DashboardPage';
import MonitoringPage from './pages/monitoring/MonitoringPage';
import UserListPage from './pages/users/UserListPage';
import UserDetailPage from './pages/users/UserDetailPage';
import CalendarListPage from './pages/calendars/CalendarListPage';
import CalendarDetailPage from './pages/calendars/CalendarDetailPage';
import EventListPage from './pages/events/EventListPage';
import EventDetailPage from './pages/events/EventDetailPage';
import ReportListPage from './pages/reports/ReportListPage';
@@ -48,24 +52,42 @@ const App: React.FC = () => {
<Route path="/login" element={<LoginPage />} />
<Route element={<ProtectedRoute />}>
<Route element={<AdminLayout />}>
<Route path="/" element={<Navigate to="/dashboard" />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/users" element={<UserListPage />} />
<Route path="/users/:id" element={<UserDetailPage />} />
<Route path="/events" element={<EventListPage />} />
<Route path="/events/:id" element={<EventDetailPage />} />
<Route path="/reports" element={<ReportListPage />} />
<Route path="/reports/:id" element={<ReportDetailPage />} />
<Route path="/reviews" element={<ReviewListPage />} />
<Route path="/reviews/:id" element={<ReviewDetailPage />} />
<Route path="/banned-words" element={<BannedWordsPage />} />
<Route path="/tickets" element={<TicketListPage />} />
<Route path="/tickets/:id" element={<TicketDetailPage />} />
<Route path="/subscriptions" element={<SubscriptionListPage />} />
<Route path="/admins" element={<AdminListPage />} />
<Route path="/admins/:id" element={<AdminDetailPage />} />
<Route path="/audit" element={<AuditPage />} />
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route element={<RoleGuard />}>
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/monitoring" element={<MonitoringPage />} />
</Route>
<Route element={<RoleGuard allowedRoles={['superadmin', 'admin']} />}>
<Route path="/users" element={<UserListPage />} />
<Route path="/users/:id" element={<UserDetailPage />} />
<Route path="/calendars" element={<CalendarListPage />} />
<Route path="/calendars/:id" element={<CalendarDetailPage />} />
<Route path="/events" element={<EventListPage />} />
<Route path="/events/:id" element={<EventDetailPage />} />
<Route path="/banned-words" element={<BannedWordsPage />} />
<Route path="/subscriptions" element={<SubscriptionListPage />} />
</Route>
<Route element={<RoleGuard allowedRoles={['superadmin', 'admin', 'moderator']} />}>
<Route path="/reports" element={<ReportListPage />} />
<Route path="/reports/:id" element={<ReportDetailPage />} />
<Route path="/reviews" element={<ReviewListPage />} />
<Route path="/reviews/:id" element={<ReviewDetailPage />} />
</Route>
<Route element={<RoleGuard allowedRoles={['superadmin', 'admin', 'support']} />}>
<Route path="/tickets" element={<TicketListPage />} />
<Route path="/tickets/:id" element={<TicketDetailPage />} />
</Route>
<Route element={<RoleGuard allowedRoles={['superadmin']} />}>
<Route path="/admins" element={<AdminListPage />} />
<Route path="/admins/:id" element={<AdminDetailPage />} />
<Route path="/audit" element={<AuditPage />} />
</Route>
</Route>
</Route>
</Routes>
@@ -74,4 +96,4 @@ const App: React.FC = () => {
);
};
export default App;
export default App;
View File
View File
+33 -32
View File
@@ -1,32 +1,33 @@
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { Spin } from 'antd';
import { useAuthStore } from '../store/authStore';
interface Props {
allowedRoles?: string[];
}
const ProtectedRoute: React.FC<Props> = ({ allowedRoles }) => {
const { isAuthenticated, isInitialized, user } = useAuthStore();
if (!isInitialized) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<Spin size="large" />
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
if (allowedRoles && user && !allowedRoles.includes(user.role)) {
return <Navigate to="/dashboard" replace />;
}
return <Outlet />;
};
export default ProtectedRoute;
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { Spin } from 'antd';
import { useAuthStore } from '../store/authStore';
import ForbiddenPage from '../pages/errors/ForbiddenPage';
interface Props {
allowedRoles?: string[];
}
const ProtectedRoute: React.FC<Props> = ({ allowedRoles }) => {
const { isAuthenticated, isInitialized, user } = useAuthStore();
if (!isInitialized) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<Spin size="large" />
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
if (allowedRoles && user && !allowedRoles.includes(user.role)) {
return <ForbiddenPage />;
}
return <Outlet />;
};
export default ProtectedRoute;
+22
View File
@@ -0,0 +1,22 @@
import React from 'react';
import { Outlet } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import ForbiddenPage from '../pages/errors/ForbiddenPage';
import type { AdminRole } from '../config/adminAccess';
interface Props {
allowedRoles?: AdminRole[];
}
/** Ограничение вложенных маршрутов по роли (после аутентификации). */
const RoleGuard: React.FC<Props> = ({ allowedRoles }) => {
const user = useAuthStore((s) => s.user);
if (allowedRoles && user && !allowedRoles.includes(user.role as AdminRole)) {
return <ForbiddenPage />;
}
return <Outlet />;
};
export default RoleGuard;
+54
View File
@@ -0,0 +1,54 @@
/** Роли доступа к разделам админки (согласовано с меню и маршрутами). */
export type AdminRole = 'superadmin' | 'admin' | 'moderator' | 'support';
export const ROUTE_ACCESS: Record<string, AdminRole[] | undefined> = {
'/dashboard': undefined,
'/profile': undefined,
'/monitoring': undefined,
'/users': ['superadmin', 'admin'],
'/calendars': ['superadmin', 'admin'],
'/events': ['superadmin', 'admin'],
'/reports': ['superadmin', 'admin', 'moderator'],
'/reviews': ['superadmin', 'admin', 'moderator'],
'/banned-words': ['superadmin', 'admin'],
'/tickets': ['superadmin', 'admin', 'support'],
'/subscriptions': ['superadmin', 'admin'],
'/admins': ['superadmin'],
'/audit': ['superadmin'],
};
export const MENU_ITEMS: Array<{
key: string;
label: string;
roles?: AdminRole[];
}> = [
{ key: '/dashboard', label: 'Дашборд' },
{ key: '/users', label: 'Пользователи', roles: ['superadmin', 'admin'] },
{ key: '/calendars', label: 'Календари', roles: ['superadmin', 'admin'] },
{ key: '/events', label: 'События', roles: ['superadmin', 'admin'] },
{ key: '/reports', label: 'Жалобы', roles: ['superadmin', 'admin', 'moderator'] },
{ key: '/reviews', label: 'Отзывы', roles: ['superadmin', 'admin', 'moderator'] },
{ key: '/banned-words', label: 'Бан-слова', roles: ['superadmin', 'admin'] },
{ key: '/tickets', label: 'Тикеты', roles: ['superadmin', 'admin', 'support'] },
{ key: '/subscriptions', label: 'Подписки', roles: ['superadmin', 'admin'] },
{ key: '/admins', label: 'Администраторы', roles: ['superadmin'] },
{ key: '/audit', label: 'Аудит', roles: ['superadmin'] },
{ key: '/monitoring', label: 'Мониторинг' },
];
export function canAccessRoute(pathname: string, role: string | undefined): boolean {
if (!role) return false;
const base = pathname.split('/').slice(0, 2).join('/') || '/';
const allowed = ROUTE_ACCESS[base];
if (allowed === undefined) {
return ROUTE_ACCESS[pathname] === undefined || ROUTE_ACCESS[pathname]!.includes(role as AdminRole);
}
return allowed.includes(role as AdminRole);
}
export function filterMenuByRole<T extends { roles?: AdminRole[] }>(
items: T[],
role: string | undefined
): T[] {
return items.filter((item) => !item.roles || (role && item.roles.includes(role as AdminRole)));
}
+143 -100
View File
@@ -1,100 +1,143 @@
import { useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useAuthStore } from '../store/authStore';
type WsMessage = {
type: 'report_created' | 'ticket_created';
data?: {
report_id?: string;
ticket_id?: string;
target_type?: string;
target_id?: string;
reason?: string;
};
status?: string;
channel?: string;
timestamp?: number;
};
export const useAdminWebSocket = () => {
const queryClient = useQueryClient();
const accessToken = useAuthStore((s) => s.accessToken);
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const lastMessageTimestamp = useRef<number>(0);
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
if (!isAuthenticated || !accessToken) return;
let isMounted = true;
const connect = () => {
const wsUrl = import.meta.env.DEV
? `ws://localhost:5173/admin/ws?token=${accessToken}`
: `wss://${window.location.host}/admin/ws?token=${accessToken}`;
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
ws.onopen = () => {
if (!isMounted) return;
console.log('[WS] Connected');
ws.send(JSON.stringify({ action: 'subscribe', channel: 'reports' }));
ws.send(JSON.stringify({ action: 'subscribe', channel: 'tickets' }));
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ action: 'ping' }));
}
}, 30_000);
};
ws.onmessage = (event) => {
if (!isMounted) return;
try {
const msg: WsMessage = JSON.parse(event.data);
console.log('[WS] Message:', msg);
if (msg.timestamp && msg.timestamp === lastMessageTimestamp.current) {
return;
}
if (msg.timestamp) {
lastMessageTimestamp.current = msg.timestamp;
}
if (msg.type === 'report_created' || msg.type === 'ticket_created') {
window.dispatchEvent(
new CustomEvent('admin-ws-message', { detail: msg })
);
if (msg.type === 'report_created') {
queryClient.invalidateQueries({ queryKey: ['reports'] });
} else if (msg.type === 'ticket_created') {
queryClient.invalidateQueries({ queryKey: ['tickets'] });
queryClient.invalidateQueries({ queryKey: ['ticket-stats'] });
}
}
} catch (e) {
console.warn('[WS] Failed to parse message:', e);
}
};
ws.onclose = () => {
if (!isMounted) return;
console.log('[WS] Disconnected, will reconnect in 5s');
if (pingIntervalRef.current) clearInterval(pingIntervalRef.current);
reconnectTimeoutRef.current = setTimeout(connect, 5000);
};
// Не вызываем ws.close() при ошибке, браузер закроет сокет сам
};
connect();
return () => {
isMounted = false;
if (reconnectTimeoutRef.current) clearTimeout(reconnectTimeoutRef.current);
if (pingIntervalRef.current) clearInterval(pingIntervalRef.current);
// Никакого принудительного закрытия wsRef.current – браузер сам управится
};
}, [isAuthenticated, accessToken, queryClient]);
};
import { useEffect, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useAuthStore } from '../store/authStore';
import { useMetricsStore } from '../store/metricsStore';
type WsMessage = {
type: 'report_created' | 'ticket_created' | 'node_metric';
data?: any;
status?: string;
channel?: string;
timestamp?: number;
};
export const useAdminWebSocket = () => {
const queryClient = useQueryClient();
const accessToken = useAuthStore((s) => s.accessToken);
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
const setCurrentMetric = useMetricsStore((s) => s.setCurrent);
const addToAllHistory = useMetricsStore((s) => s.addToAllHistory);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const lastMessageTimestamp = useRef<number>(0);
const shouldReconnectRef = useRef(true);
const clearTimers = () => {
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
};
const closeSocket = () => {
clearTimers();
if (wsRef.current) {
wsRef.current.onclose = null;
wsRef.current.onerror = null;
wsRef.current.onmessage = null;
wsRef.current.onopen = null;
if (wsRef.current.readyState === WebSocket.OPEN ||
wsRef.current.readyState === WebSocket.CONNECTING) {
wsRef.current.close();
}
wsRef.current = null;
}
};
useEffect(() => {
if (!isAuthenticated || !accessToken) {
shouldReconnectRef.current = false;
closeSocket();
return;
}
shouldReconnectRef.current = true;
let isMounted = true;
const connect = () => {
if (!isMounted || !shouldReconnectRef.current) return;
closeSocket();
const wsUrl = import.meta.env.DEV
? `ws://localhost:5173/admin/ws?token=${accessToken}`
: `wss://${window.location.host}/admin/ws?token=${accessToken}`;
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
ws.onopen = () => {
if (!isMounted || !shouldReconnectRef.current) return;
console.log('[WS] Connected');
ws.send(JSON.stringify({ action: 'subscribe', channel: 'reports' }));
ws.send(JSON.stringify({ action: 'subscribe', channel: 'tickets' }));
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ action: 'ping' }));
}
}, 30_000);
};
ws.onmessage = (event) => {
if (!isMounted) return;
try {
const msg: WsMessage = JSON.parse(event.data);
console.log('[WS] Message:', msg);
if (msg.timestamp && msg.timestamp === lastMessageTimestamp.current) {
return;
}
if (msg.timestamp) {
lastMessageTimestamp.current = msg.timestamp;
}
if (msg.type === 'report_created' || msg.type === 'ticket_created') {
window.dispatchEvent(
new CustomEvent('admin-ws-message', { detail: msg })
);
if (msg.type === 'report_created') {
queryClient.invalidateQueries({ queryKey: ['reports'] });
} else if (msg.type === 'ticket_created') {
queryClient.invalidateQueries({ queryKey: ['tickets'] });
queryClient.invalidateQueries({ queryKey: ['ticket-stats'] });
}
} else if (msg.type === 'node_metric') {
setCurrentMetric(msg.data);
addToAllHistory(msg.data);
}
} catch (e) {
console.warn('[WS] Failed to parse message:', e);
}
};
ws.onclose = (event) => {
if (!isMounted || !shouldReconnectRef.current) return;
console.log('[WS] Disconnected:', event.reason);
clearTimers();
wsRef.current = null;
reconnectTimeoutRef.current = setTimeout(connect, 5000);
};
ws.onerror = (error) => {
if (!isMounted) return;
console.error('[WS] Error:', error);
ws.close();
};
};
connect();
return () => {
isMounted = false;
shouldReconnectRef.current = false;
closeSocket();
};
}, [isAuthenticated, accessToken, queryClient, setCurrentMetric, addToAllHistory]);
};
View File
+343 -280
View File
@@ -1,281 +1,344 @@
import React, { useEffect, useState } from 'react';
import { Layout, Menu, Button, theme, notification, Avatar, Dropdown, Space, Typography, Badge } from 'antd';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { useAdminWebSocket } from '../hooks/useAdminWebSocket';
import {
DashboardOutlined,
UserOutlined,
CalendarOutlined,
WarningOutlined,
StarOutlined,
StopOutlined,
BugOutlined,
DollarOutlined,
TeamOutlined,
AuditOutlined,
LogoutOutlined,
SettingOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons';
const { Header, Sider, Content } = Layout;
const { Text } = Typography;
const AdminLayout: React.FC = () => {
useAdminWebSocket();
const navigate = useNavigate();
const location = useLocation();
const { user, logout } = useAuthStore();
const { token: { colorBgContainer } } = theme.useToken();
const [collapsed, setCollapsed] = useState(false);
// Обработка WebSocket-уведомлений
useEffect(() => {
const handler = (event: CustomEvent) => {
const msg = event.detail;
if (msg.type === 'report_created') {
const { report_id, target_type, target_id, reason } = msg.data || {};
notification.info({
title: 'Новая жалоба',
description: (
<span>
Жалоба{' '}
{report_id ? (
<a
href={`/reports/${report_id}`}
onClick={(e) => {
e.preventDefault();
navigate(`/reports/${report_id}`);
}}
style={{ fontWeight: 600 }}
>
#{report_id}
</a>
) : (
'#?'
)}{' '}
на {target_type || 'неизвестный тип'}{' '}
{target_id ? (
<a
href={`/${target_type}s/${target_id}`}
onClick={(e) => {
e.preventDefault();
navigate(`/${target_type}s/${target_id}`);
}}
style={{ fontWeight: 600 }}
>
{target_id}
</a>
) : (
'?'
)}{' '}
{reason ? `(${reason})` : ''}
</span>
),
placement: 'topRight',
});
} else if (msg.type === 'ticket_created') {
const { ticket_id } = msg.data || {};
notification.info({
title: 'Новый тикет',
description: (
<span>
Тикет{' '}
{ticket_id ? (
<a
href={`/tickets/${ticket_id}`}
onClick={(e) => {
e.preventDefault();
navigate(`/tickets/${ticket_id}`);
}}
style={{ fontWeight: 600 }}
>
#{ticket_id}
</a>
) : (
'без ID'
)}{' '}
создан
</span>
),
placement: 'topRight',
});
}
};
window.addEventListener('admin-ws-message', handler as EventListener);
return () => window.removeEventListener('admin-ws-message', handler as EventListener);
}, [navigate]);
const menuItems = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: 'Дашборд' },
{ key: '/users', icon: <UserOutlined />, label: 'Пользователи', roles: ['superadmin', 'admin'] },
{ key: '/events', icon: <CalendarOutlined />, label: 'События', roles: ['superadmin', 'admin'] },
{ key: '/reports', icon: <WarningOutlined />, label: 'Жалобы', roles: ['superadmin', 'admin', 'moderator'] },
{ key: '/reviews', icon: <StarOutlined />, label: 'Отзывы', roles: ['superadmin', 'admin', 'moderator'] },
{ key: '/banned-words', icon: <StopOutlined />, label: 'Бан-слова', roles: ['superadmin', 'admin'] },
{ key: '/tickets', icon: <BugOutlined />, label: 'Тикеты', roles: ['superadmin', 'admin', 'support'] },
{ key: '/subscriptions', icon: <DollarOutlined />, label: 'Подписки', roles: ['superadmin', 'admin'] },
{ key: '/admins', icon: <TeamOutlined />, label: 'Администраторы', roles: ['superadmin'] },
{ key: '/audit', icon: <AuditOutlined />, label: 'Аудит', roles: ['superadmin'] },
];
const filteredMenu = menuItems.filter(
(item) => !item.roles || (user && item.roles.includes(user.role))
);
const handleLogout = async () => {
await logout();
navigate('/login');
};
const getDisplayName = () => {
const nick = user?.nickname;
const email = user?.email;
if (nick && nick !== '-' && nick !== 'undefined') return nick;
if (email && email !== '-' && email !== 'undefined') return email;
return user?.id ?? '—';
};
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider
collapsible
collapsed={collapsed}
onCollapse={setCollapsed}
trigger={null}
style={{
position: 'relative', // чтобы абсолютный блок считался от него
display: 'flex',
flexDirection: 'column',
height: '100vh',
// position: 'sticky',
top: 0,
left: 0,
}}
>
<div style={{ height: 32, margin: 16, color: 'white', textAlign: 'center', fontWeight: 'bold' }}>
{collapsed ? 'EH' : import.meta.env.VITE_APP_TITLE}
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={[location.pathname]}
items={filteredMenu}
onClick={({ key }) => navigate(key)}
style={{
flex: 1,
overflowY: 'auto',
overflowX: 'hidden',
marginBottom: 60, // отступ, чтобы меню не заходило под нижний блок
}}
/>
<div
style={{
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
display: 'flex',
alignItems: 'center',
justifyContent: collapsed ? 'center' : 'space-between',
padding: '12px 24px',
borderTop: '1px solid rgba(255,255,255,0.1)',
background: '#001529', // цвет сайдбара Ant Design
flexShrink: 0,
}}
>
<Dropdown
menu={{
items: [
{
key: 'profile',
icon: <SettingOutlined />,
label: 'Мой профиль',
onClick: () => navigate('/profile'),
},
{ type: 'divider' },
{
key: 'logout',
icon: <LogoutOutlined />,
label: 'Выйти',
onClick: handleLogout,
},
],
}}
trigger={['click']}
placement="topLeft"
>
<Button
type="text"
style={{
color: 'white',
display: 'flex',
alignItems: 'center',
padding: '4px 0',
border: 'none',
width: collapsed ? 'auto' : '100%',
}}
>
<Avatar icon={<UserOutlined />} src={user?.avatar_url} size="small" />
{!collapsed && (
<Text
style={{
color: 'white',
marginLeft: 8,
maxWidth: 100,
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
ellipsis
>
{getDisplayName()}
</Text>
)}
</Button>
</Dropdown>
<Button
type="text"
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={() => setCollapsed(!collapsed)}
style={{
color: 'white',
fontSize: '16px',
width: 32,
height: 32,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
/>
</div>
</Sider>
<Layout>
<Header
style={{
padding: '0 24px',
background: colorBgContainer,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Space size="large">
<Badge status="success" text="Онлайн: 12" />
<Badge status="processing" text="Заказов сегодня: 5" />
<Badge status="warning" text="Тикетов: 2" />
</Space>
<div>{/* Резерв */}</div>
</Header>
<Content style={{ margin: 24 }}>
<Outlet />
</Content>
</Layout>
</Layout>
);
};
import React, { useEffect, useState } from 'react';
import { Layout, Menu, Button, theme, notification, Avatar, Dropdown, Space, Typography, Badge, Tooltip, Progress } from 'antd';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { useAdminWebSocket } from '../hooks/useAdminWebSocket';
import { useMetricsStore } from '../store/metricsStore';
import {
DashboardOutlined,
UserOutlined,
CalendarOutlined,
WarningOutlined,
StarOutlined,
StopOutlined,
BugOutlined,
DollarOutlined,
TeamOutlined,
AuditOutlined,
LogoutOutlined,
SettingOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
CloudServerOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { MENU_ITEMS, filterMenuByRole } from '../config/adminAccess';
const { Header, Sider, Content } = Layout;
const { Text } = Typography;
const NODE_STATS_THRESHOLD = 5;
const AdminLayout: React.FC = () => {
useAdminWebSocket();
const navigate = useNavigate();
const location = useLocation();
const { user, logout } = useAuthStore();
const { token: { colorBgContainer } } = theme.useToken();
const [collapsed, setCollapsed] = useState(false);
const allHistory = useMetricsStore((s) => s.allHistory);
const current = useMetricsStore((s) => s.current);
const previous = useMetricsStore((s) => s.previous);
useEffect(() => {
const handler = (event: CustomEvent) => {
const msg = event.detail;
if (msg.type === 'report_created') {
const { report_id, target_type, target_id, reason } = msg.data || {};
notification.info({
title: 'Новая жалоба',
description: (
<span>
Жалоба{' '}
{report_id ? (
<a href={`/reports/${report_id}`} onClick={(e) => { e.preventDefault(); navigate(`/reports/${report_id}`); }} style={{ fontWeight: 600 }}>
#{report_id}
</a>
) : ('#?')}{' '}
на {target_type || 'неизвестный тип'}{' '}
{target_id ? (
<a href={`/${target_type}s/${target_id}`} onClick={(e) => { e.preventDefault(); navigate(`/${target_type}s/${target_id}`); }} style={{ fontWeight: 600 }}>
{target_id}
</a>
) : ('?')}{' '}
{reason ? `(${reason})` : ''}
</span>
),
placement: 'topRight',
});
} else if (msg.type === 'ticket_created') {
const { ticket_id } = msg.data || {};
notification.info({
title: 'Новый тикет',
description: (
<span>
Тикет{' '}
{ticket_id ? (
<a href={`/tickets/${ticket_id}`} onClick={(e) => { e.preventDefault(); navigate(`/tickets/${ticket_id}`); }} style={{ fontWeight: 600 }}>
#{ticket_id}
</a>
) : ('без ID')}{' '}
создан
</span>
),
placement: 'topRight',
});
}
};
window.addEventListener('admin-ws-message', handler as EventListener);
return () => window.removeEventListener('admin-ws-message', handler as EventListener);
}, [navigate]);
const onlineNodes = React.useMemo(() => {
const cutoff = dayjs().subtract(NODE_STATS_THRESHOLD, 'minute');
const recentMetrics = allHistory.filter(m => dayjs(m.timestamp).isAfter(cutoff));
const nodes = new Set(recentMetrics.map(m => m.node));
return Array.from(nodes);
}, [allHistory]);
const latestByNode = React.useMemo(() => {
const map = new Map<string, typeof current>();
const recent = allHistory.slice(-1000);
for (let i = recent.length - 1; i >= 0; i--) {
const m = recent[i];
if (!map.has(m.node)) {
map.set(m.node, m);
}
}
return map;
}, [allHistory]);
const menuIconByKey: Record<string, React.ReactNode> = {
'/dashboard': <DashboardOutlined />,
'/users': <UserOutlined />,
'/calendars': <CalendarOutlined />,
'/events': <CalendarOutlined />,
'/reports': <WarningOutlined />,
'/reviews': <StarOutlined />,
'/banned-words': <StopOutlined />,
'/tickets': <BugOutlined />,
'/subscriptions': <DollarOutlined />,
'/admins': <TeamOutlined />,
'/audit': <AuditOutlined />,
'/monitoring': <CloudServerOutlined />,
};
const menuItems = MENU_ITEMS.map((item) => ({
key: item.key,
icon: menuIconByKey[item.key],
label: item.label,
roles: item.roles,
}));
const filteredMenu = filterMenuByRole(menuItems, user?.role);
const handleLogout = async () => {
await logout();
navigate('/login');
};
const getDisplayName = () => {
const nick = user?.nickname;
const email = user?.email;
if (nick && nick !== '-' && nick !== 'undefined') return nick;
if (email && email !== '-' && email !== 'undefined') return email;
return user?.id ?? '—';
};
const NodeIndicator: React.FC<{ node: string; stats: any; prevStats?: any }> = ({ node, stats, prevStats }) => {
const cpu = stats?.cpu_utilization ?? 0;
const totalMemory = (stats?.memory_total ?? 0) + (stats?.memory_available ?? 0);
const usedMemory = stats?.memory_total ?? 0;
const memoryPercent = totalMemory > 0 ? (usedMemory / totalMemory) * 100 : 0;
const prevCpu = prevStats?.cpu_utilization;
const prevTotal = (prevStats?.memory_total ?? 0) + (prevStats?.memory_available ?? 0);
const prevUsed = prevStats?.memory_total ?? 0;
const prevMemoryPercent = prevTotal > 0 ? (prevUsed / prevTotal) * 100 : null;
const cpuColor = cpu > 80 ? '#ff4d4f' : '#52c41a';
const memColor = memoryPercent > 80 ? '#ff4d4f' : '#1890ff';
return (
<Tooltip
title={
<div>
<div>{node}</div>
<div>CPU: {cpu.toFixed(1)}% {prevCpu !== undefined ? `(было ${prevCpu.toFixed(1)}%)` : ''}</div>
<div>Память: {(usedMemory / 1048576).toFixed(0)} / {(totalMemory / 1048576).toFixed(0)} МБ ({memoryPercent.toFixed(1)}%)
{prevMemoryPercent !== null ? ` (было ${prevMemoryPercent.toFixed(1)}%)` : ''}</div>
</div>
}
>
<div style={{ position: 'relative', width: 48, height: 48, marginRight: 12 }}>
<Progress
type="circle"
percent={memoryPercent}
format={() => ''}
size={48}
strokeColor={memColor}
railColor="#f0f0f0"
strokeWidth={6}
style={{ position: 'absolute', top: 0, left: 0 }}
/>
<Progress
type="circle"
percent={cpu}
format={() => ''}
size={32}
strokeColor={cpuColor}
railColor="#f0f0f0"
strokeWidth={6}
style={{ position: 'absolute', top: 8, left: 8 }}
/>
<div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', fontSize: 10, fontWeight: 600 }}>
{cpu.toFixed(0)}%
</div>
</div>
</Tooltip>
);
};
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider
collapsible
collapsed={collapsed}
onCollapse={setCollapsed}
trigger={null}
style={{
display: 'flex',
flexDirection: 'column',
height: '100vh',
position: 'sticky',
top: 0,
left: 0,
}}
>
<div style={{ height: 32, margin: 16, color: 'white', textAlign: 'center', fontWeight: 'bold' }}>
{collapsed ? 'EH' : import.meta.env.VITE_APP_TITLE}
</div>
<Menu
theme="dark"
mode="inline"
selectedKeys={[location.pathname]}
items={filteredMenu}
onClick={({ key }) => navigate(key)}
style={{
flex: 1,
overflowY: 'auto',
overflowX: 'hidden',
}}
/>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: collapsed ? 'center' : 'space-between',
padding: '12px 24px',
borderTop: '1px solid rgba(255,255,255,0.1)',
background: 'rgba(0,0,0,0.1)',
marginTop: 'auto',
flexShrink: 0,
}}
>
<Dropdown
menu={{
items: [
{
key: 'profile',
icon: <SettingOutlined />,
label: 'Мой профиль',
onClick: () => navigate('/profile'),
},
{ type: 'divider' },
{
key: 'logout',
icon: <LogoutOutlined />,
label: 'Выйти',
onClick: handleLogout,
},
],
}}
trigger={['click']}
placement="topLeft"
>
<Button
type="text"
style={{
color: 'white',
display: 'flex',
alignItems: 'center',
padding: '4px 0',
border: 'none',
width: collapsed ? 'auto' : '100%',
}}
>
<Avatar icon={<UserOutlined />} src={user?.avatar_url} size="small" />
{!collapsed && (
<Text
style={{
color: 'white',
marginLeft: 8,
maxWidth: 100,
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
ellipsis
>
{getDisplayName()}
</Text>
)}
</Button>
</Dropdown>
<Button
type="text"
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={() => setCollapsed(!collapsed)}
style={{
color: 'white',
fontSize: '16px',
width: 32,
height: 32,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
/>
</div>
</Sider>
<Layout>
<Header
style={{
padding: '0 24px',
background: colorBgContainer,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Space size="large">
<Tooltip title={`Онлайн-ноды: ${onlineNodes.join(', ')}`}>
<Badge
status="processing"
text={`Ноды: ${onlineNodes.length}`}
/>
</Tooltip>
{onlineNodes.map(node => {
const stats = latestByNode.get(node);
const prevStats = previous?.node === node ? previous : undefined;
return <NodeIndicator key={node} node={node} stats={stats} prevStats={prevStats} />;
})}
</Space>
<div>{/* Резерв */}</div>
</Header>
<Content style={{ margin: 24 }}>
<Outlet />
</Content>
</Layout>
</Layout>
);
};
export default AdminLayout;
+21
View File
@@ -0,0 +1,21 @@
import React from 'react';
import { Button, Result } from 'antd';
import { useNavigate } from 'react-router-dom';
const ForbiddenPage: React.FC = () => {
const navigate = useNavigate();
return (
<Result
status="403"
title="403"
subTitle="У вас нет доступа к этому разделу."
extra={
<Button type="primary" onClick={() => navigate('/dashboard')}>
На дашборд
</Button>
}
/>
);
};
export default ForbiddenPage;
+167 -157
View File
@@ -1,158 +1,168 @@
import React, { useState } from 'react';
import { Table, Button, Tag, Popconfirm, Tooltip, Spin, Card, Col, Row, Statistic } from 'antd';
import { InfoCircleOutlined, DeleteOutlined, BugOutlined, ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useTickets, useDeleteTicket, useTicketStats } from '../../hooks/useTickets';
import { useAdmin } from '../../hooks/useAdmins';
import { Ticket, TicketListParams } from '../../types/api';
import type { ColumnsType, SorterResult } from 'antd/es/table/interface';
const TicketListPage: React.FC = () => {
const navigate = useNavigate();
const [params, setParams] = useState<TicketListParams>({ limit: 20, offset: 0, sort: 'last_seen', order: 'desc' });
const { data, isLoading } = useTickets(params);
const deleteTicket = useDeleteTicket();
const { data: stats } = useTicketStats();
const isBadValue = (val: any) =>
val === '-' || val === 'undefined' || val === '' || val === null || val === undefined;
// Резолвер администратора для колонки "Назначен"
const AssignedCell: React.FC<{ adminId: string | null }> = ({ adminId }) => {
const { data: admin, isLoading: loading } = useAdmin(adminId || '');
if (!adminId || adminId === '-' || adminId === 'undefined') return <span>-</span>;
if (loading) return <Spin size="small" />;
if (!admin) return <span>{adminId}</span>;
const name = !isBadValue(admin.nickname) ? admin.nickname : admin.email;
return <Link to={`/admins/${admin.id}`}>{!isBadValue(name) ? name : admin.id}</Link>;
};
const handleTableChange = (
pagination: any,
_filters: any,
sorter: SorterResult<Ticket> | SorterResult<Ticket>[]
) => {
const s = Array.isArray(sorter) ? sorter[0] : sorter;
setParams(prev => ({
...prev,
sort: s.field as string,
order: s.order === 'ascend' ? 'asc' : s.order === 'descend' ? 'desc' : undefined,
offset: ((pagination.current - 1) * pagination.pageSize) || 0,
limit: pagination.pageSize || prev.limit,
}));
};
const columns: ColumnsType<Ticket> = [
{
title: <InfoCircleOutlined />,
key: 'detail',
width: 48,
align: 'center',
render: (_, record) => (
<Tooltip title="Открыть страницу тикета">
<Button
icon={<InfoCircleOutlined />}
size="small"
type="link"
onClick={() => navigate(`/tickets/${record.id}`)}
/>
</Tooltip>
),
},
{
title: 'Ошибка',
dataIndex: 'error_message',
key: 'error_message',
ellipsis: true,
sorter: true,
render: (text: string) => isBadValue(text) ? '-' : text,
},
{
title: 'Статус',
dataIndex: 'status',
key: 'status',
width: 100,
sorter: true,
render: (status: string) => {
const color =
status === 'open' ? 'red' :
status === 'in_progress' ? 'blue' :
status === 'resolved' ? 'green' : 'default';
return <Tag color={color}>{status}</Tag>;
},
},
{
title: 'Назначен',
dataIndex: 'assigned_to',
key: 'assigned_to',
render: (assigned: string) => <AssignedCell adminId={assigned} />,
},
{ title: 'Повторов', dataIndex: 'count', key: 'count', width: 80, sorter: true },
{ title: 'Первый раз', dataIndex: 'first_seen', key: 'first_seen', sorter: true },
{ title: 'Последний', dataIndex: 'last_seen', key: 'last_seen', sorter: true },
{
title: 'Действия',
key: 'actions',
width: 80,
render: (_, record) => (
<Popconfirm
title="Удалить тикет?"
onConfirm={() => deleteTicket.mutate(record.id)}
>
<Tooltip title="Удалить">
<Button
icon={<DeleteOutlined />}
size="small"
danger
/>
</Tooltip>
</Popconfirm>
),
},
];
return (
<div>
<h2>Тикеты</h2>
{stats && (
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col xs={12} sm={6}>
<Card>
<Statistic title="Открыто" value={stats.open} prefix={<BugOutlined />} styles={{ content: { color: 'red' } }} />
</Card>
</Col>
<Col xs={12} sm={6}>
<Card>
<Statistic title="В работе" value={stats.in_progress} prefix={<ClockCircleOutlined />} styles={{ content: { color: 'blue' } }} />
</Card>
</Col>
<Col xs={12} sm={6}>
<Card>
<Statistic title="Решено" value={stats.resolved} prefix={<CheckCircleOutlined />} styles={{ content: { color: 'green' } }} />
</Card>
</Col>
<Col xs={12} sm={6}>
<Card>
<Statistic title="Закрыто" value={stats.closed} prefix={<CloseCircleOutlined />} />
</Card>
</Col>
</Row>
)}
<Table
columns={columns}
dataSource={data?.data}
rowKey="id"
loading={isLoading}
onChange={handleTableChange}
pagination={{
total: data?.total,
current: (params.offset || 0) / (params.limit || 20) + 1,
pageSize: params.limit || 20,
showSizeChanger: false,
}}
/>
</div>
);
};
import React, { useState } from 'react';
import { Table, Button, Tag, Popconfirm, Tooltip, Spin, Card, Col, Row, Statistic } from 'antd';
import { InfoCircleOutlined, DeleteOutlined, BugOutlined, ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useTickets, useDeleteTicket, useTicketStats } from '../../hooks/useTickets';
import { useAdmin } from '../../hooks/useAdmins';
import { Ticket, TicketListParams } from '../../types/api';
import type { ColumnsType, SorterResult } from 'antd/es/table/interface';
const TicketListPage: React.FC = () => {
const navigate = useNavigate();
const [params, setParams] = useState<TicketListParams>({ limit: 20, offset: 0, sort: 'last_seen', order: 'desc' });
const { data, isLoading } = useTickets(params);
const deleteTicket = useDeleteTicket();
const { data: stats } = useTicketStats();
const isBadValue = (val: any) =>
val === '-' || val === 'undefined' || val === '' || val === null || val === undefined;
// Резолвер администратора для колонки "Назначен"
const AssignedCell: React.FC<{ adminId: string | null }> = ({ adminId }) => {
const { data: admin, isLoading: loading } = useAdmin(adminId || '');
if (!adminId || adminId === '-' || adminId === 'undefined') return <span>-</span>;
if (loading) return <Spin size="small" />;
if (!admin) return <span>{adminId}</span>;
const name = !isBadValue(admin.nickname) ? admin.nickname : admin.email;
return <Link to={`/admins/${admin.id}`}>{!isBadValue(name) ? name : admin.id}</Link>;
};
const handleTableChange = (
pagination: any,
_filters: any,
sorter: SorterResult<Ticket> | SorterResult<Ticket>[]
) => {
const s = Array.isArray(sorter) ? sorter[0] : sorter;
setParams(prev => ({
...prev,
sort: s.field as string,
order: s.order === 'ascend' ? 'asc' : s.order === 'descend' ? 'desc' : undefined,
offset: ((pagination.current - 1) * pagination.pageSize) || 0,
limit: pagination.pageSize || prev.limit,
}));
};
const columns: ColumnsType<Ticket> = [
{
title: <InfoCircleOutlined />,
key: 'detail',
width: 48,
align: 'center',
render: (_, record) => (
<Tooltip title="Открыть страницу тикета">
<Button
icon={<InfoCircleOutlined />}
size="small"
type="link"
onClick={() => navigate(`/tickets/${record.id}`)}
/>
</Tooltip>
),
},
{
title: 'Ошибка',
dataIndex: 'error_message',
key: 'error_message',
ellipsis: true,
sorter: true,
render: (text: string) => isBadValue(text) ? '-' : text,
},
{
title: 'Статус',
dataIndex: 'status',
key: 'status',
width: 100,
sorter: true,
render: (status: string) => {
const color =
status === 'open' ? 'red' :
status === 'in_progress' ? 'blue' :
status === 'resolved' ? 'green' : 'default';
return <Tag color={color}>{status}</Tag>;
},
},
{
title: 'Назначен',
dataIndex: 'assigned_to',
key: 'assigned_to',
render: (assigned: string) => <AssignedCell adminId={assigned} />,
},
{ title: 'Повторов', dataIndex: 'count', key: 'count', width: 80, sorter: true },
{ title: 'Первый раз', dataIndex: 'first_seen', key: 'first_seen', sorter: true },
{ title: 'Последний', dataIndex: 'last_seen', key: 'last_seen', sorter: true },
{
title: 'Действия',
key: 'actions',
width: 80,
render: (_, record) => (
<Popconfirm
title="Удалить тикет?"
onConfirm={() => deleteTicket.mutate(record.id)}
>
<Tooltip title="Удалить">
<Button
icon={<DeleteOutlined />}
size="small"
danger
/>
</Tooltip>
</Popconfirm>
),
},
];
return (
<div>
<h2>Тикеты</h2>
{stats && (
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="Всего тикетов" value={stats.total_tickets} prefix={<BugOutlined />} />
</Card>
</Col>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="Открыто" value={stats.open} styles={{ content: { color: 'red' } }} />
</Card>
</Col>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="В работе" value={stats.in_progress} prefix={<ClockCircleOutlined />} styles={{ content: { color: 'blue' } }} />
</Card>
</Col>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="Решено" value={stats.resolved} prefix={<CheckCircleOutlined />} styles={{ content: { color: 'green' } }} />
</Card>
</Col>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="Закрыто" value={stats.closed} prefix={<CloseCircleOutlined />} />
</Card>
</Col>
<Col xs={12} sm={6} md={4}>
<Card>
<Statistic title="Всего ошибок" value={stats.total_errors} />
</Card>
</Col>
</Row>
)}
<Table
columns={columns}
dataSource={data?.data}
rowKey="id"
loading={isLoading}
onChange={handleTableChange}
pagination={{
total: data?.total,
current: (params.offset || 0) / (params.limit || 20) + 1,
pageSize: params.limit || 20,
showSizeChanger: false,
}}
/>
</div>
);
};
export default TicketListPage;
+71 -69
View File
@@ -1,70 +1,72 @@
import { create } from 'zustand';
import { Admin } from '../types/api';
import { authApi } from '../api/authApi';
import { ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../utils/constants';
interface AuthState {
user: Admin | null;
accessToken: string | null;
refreshToken: string | null;
isAuthenticated: boolean;
isInitialized: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkAuth: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
accessToken: localStorage.getItem(ACCESS_TOKEN_KEY),
refreshToken: localStorage.getItem(REFRESH_TOKEN_KEY),
isAuthenticated: false,
isInitialized: false,
login: async (email: string, password: string) => {
const { token, refresh_token, user } = await authApi.login(email, password);
localStorage.setItem(ACCESS_TOKEN_KEY, token);
localStorage.setItem(REFRESH_TOKEN_KEY, refresh_token);
set({
accessToken: token,
refreshToken: refresh_token,
user,
isAuthenticated: true,
isInitialized: true,
});
},
logout: async () => {
localStorage.removeItem(ACCESS_TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
set({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
isInitialized: true,
});
},
checkAuth: async () => {
const token = localStorage.getItem(ACCESS_TOKEN_KEY);
if (!token) {
set({ isInitialized: true });
return;
}
try {
const user = await authApi.getMe();
set({ user, isAuthenticated: true, isInitialized: true });
} catch {
localStorage.removeItem(ACCESS_TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
set({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
isInitialized: true,
});
}
},
import { create } from 'zustand';
import { Admin } from '../types/api';
import { authApi } from '../api/authApi';
import { ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../utils/constants';
import { useMetricsStore } from './metricsStore';
interface AuthState {
user: Admin | null;
accessToken: string | null;
refreshToken: string | null;
isAuthenticated: boolean;
isInitialized: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkAuth: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
accessToken: localStorage.getItem(ACCESS_TOKEN_KEY),
refreshToken: localStorage.getItem(REFRESH_TOKEN_KEY),
isAuthenticated: false,
isInitialized: false,
login: async (email: string, password: string) => {
const { token, refresh_token, user } = await authApi.login(email, password);
localStorage.setItem(ACCESS_TOKEN_KEY, token);
localStorage.setItem(REFRESH_TOKEN_KEY, refresh_token);
set({
accessToken: token,
refreshToken: refresh_token,
user,
isAuthenticated: true,
isInitialized: true,
});
},
logout: async () => {
localStorage.removeItem(ACCESS_TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
useMetricsStore.getState().reset();
set({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
isInitialized: true,
});
},
checkAuth: async () => {
const token = localStorage.getItem(ACCESS_TOKEN_KEY);
if (!token) {
set({ isInitialized: true });
return;
}
try {
const user = await authApi.getMe();
set({ user, isAuthenticated: true, isInitialized: true });
} catch {
localStorage.removeItem(ACCESS_TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
set({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
isInitialized: true,
});
}
},
}));
+89
View File
@@ -0,0 +1,89 @@
import { create } from 'zustand';
import dayjs from 'dayjs';
export interface NodeMetric {
active_sessions: number;
io_in: number;
io_out: number;
memory_atom: number;
memory_binary: number;
memory_ets: number;
memory_processes: number;
memory_total: number;
mnesia_commits: number;
mnesia_failures: number;
node: string;
process_count: number;
run_queue: number;
table_sizes: Record<string, number>;
timestamp: string;
ws_connections: number;
cpu_utilization: number;
memory_available: number;
}
interface MetricsState {
current: NodeMetric | null;
previous: NodeMetric | null;
allHistory: NodeMetric[];
visibleHistory: NodeMetric[];
setCurrent: (metric: NodeMetric) => void;
setAllHistory: (history: NodeMetric[]) => void;
addToAllHistory: (metric: NodeMetric) => void;
filterVisibleHistory: (minutes: number) => void;
reset: () => void;
}
const MAX_HISTORY = 500; // жесткий лимит, чтобы избежать ошибок памяти
export const useMetricsStore = create<MetricsState>((set, get) => ({
current: null,
previous: null,
allHistory: [],
visibleHistory: [],
setCurrent: (metric) =>
set((state) => ({
previous: state.current,
current: metric,
})),
setAllHistory: (history) =>
set({
allHistory: history.slice(-MAX_HISTORY),
visibleHistory: history.slice(-MAX_HISTORY),
}),
addToAllHistory: (metric) =>
set((state) => {
const newAll = [...state.allHistory, metric].slice(-MAX_HISTORY);
return { allHistory: newAll };
}),
filterVisibleHistory: (minutes) => {
const { allHistory } = get();
if (allHistory.length === 0) return;
const now = dayjs();
const from = now.subtract(minutes, 'minute');
const filtered = allHistory.filter((m) => {
const t = dayjs(m.timestamp);
return t.isAfter(from);
});
let step = 1;
if (filtered.length > 300) step = Math.ceil(filtered.length / 300);
const thinned = filtered.filter((_, i) => i % step === 0);
set({ visibleHistory: thinned });
},
reset: () =>
set({
current: null,
previous: null,
allHistory: [],
visibleHistory: [],
}),
}));
+331 -298
View File
@@ -1,299 +1,332 @@
// ===================== Event (Событие) =====================
export interface Event {
id: string;
calendar_id: string;
title: string;
description: string;
event_type: 'single' | 'recurring';
start_time: string; // ISO8601
duration: number;
recurrence: object | null;
master_id: string | null;
is_instance: boolean;
specialist_id: string | null;
location: object | null;
tags: string[];
capacity: number | null;
online_link: string | null;
status: 'active' | 'cancelled' | 'completed';
reason: string | null;
rating_avg: number;
rating_count: number;
attachments: string[] | null;
edit_history: object[] | null;
created_at: string; // ISO8601
updated_at: string; // ISO8601
}
export interface EventListParams {
from?: string;
to?: string;
status?: 'active' | 'cancelled' | 'completed';
calendar_id?: string;
title?: string;
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== User (Пользователь) =====================
export interface User {
id: string;
email: string;
role: 'user' | 'bot';
status: 'active' | 'frozen' | 'deleted';
reason: string | null;
nickname: string | null;
avatar_url: string | null;
timezone: string | null;
language: string | null;
social_links: string[] | null;
phone: string | null;
preferences: object | null;
last_login: string; // ISO8601
created_at: string; // ISO8601
updated_at: string; // ISO8601
}
export interface UserListParams {
role?: 'user' | 'bot';
status?: 'active' | 'frozen' | 'deleted';
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Report (Жалоба) =====================
export interface Report {
id: string;
reporter_id: string;
target_type: 'calendar' | 'event' | 'review';
target_id: string;
reason: string;
status: 'pending' | 'reviewed' | 'dismissed';
created_at: string;
resolved_at: string | null;
resolved_by: string | null;
}
export interface ReportListParams {
status?: 'pending' | 'reviewed' | 'dismissed';
target_type?: 'calendar' | 'event' | 'review';
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Review (Отзыв) =====================
export interface Review {
id: string;
user_id: string;
target_type: 'calendar' | 'event';
target_id: string;
rating: number; // 1-5
comment: string;
status: 'visible' | 'hidden' | 'deleted';
reason: string | null;
likes: number;
dislikes: number;
created_at: string;
updated_at: string;
}
export interface ReviewListParams {
target_type?: 'calendar' | 'event';
target_id?: string;
user_id?: string;
status?: 'visible' | 'hidden' | 'deleted';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Banned Word (Бан-слово) =====================
export interface BannedWord {
id: string;
word: string;
added_by: string | null;
added_at: string | null;
}
// ===================== Ticket (Тикет баг-трекера) =====================
export interface Ticket {
id: string;
reporter_id: string;
error_hash: string;
error_message: string;
stacktrace: string;
context: string;
count: number;
first_seen: string;
last_seen: string;
status: 'open' | 'in_progress' | 'resolved' | 'closed';
assigned_to: string | null;
resolution_note: string | null;
}
export interface TicketListParams {
status?: 'open' | 'in_progress' | 'resolved' | 'closed';
assigned_to?: string;
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
export interface TicketStats {
open: number;
in_progress: number;
resolved: number;
closed: number;
total: number;
}
// ===================== Subscription (Подписка) =====================
export interface Subscription {
id: string;
user_id: string;
plan: 'monthly' | 'quarterly' | 'biannual' | 'annual';
status: 'active' | 'expired' | 'cancelled';
trial_used: boolean;
started_at: string;
expires_at: string;
created_at: string;
updated_at: string;
}
export interface SubscriptionListParams {
plan?: 'monthly' | 'quarterly' | 'biannual' | 'annual';
status?: 'active' | 'expired' | 'cancelled';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Admin (Администратор) =====================
export interface Admin {
id: string;
email: string;
role: 'superadmin' | 'admin' | 'moderator' | 'support';
status: 'active' | 'blocked';
nickname: string | null;
avatar_url: string | null;
timezone: string | null;
language: string | null;
phone: string | null;
preferences: object | null;
last_login: string;
created_at: string;
updated_at: string;
}
export interface AdminListParams {
role?: 'superadmin' | 'admin' | 'moderator' | 'support';
status?: 'active' | 'blocked';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Audit (Запись аудита) =====================
export interface AuditRecord {
id: string;
admin_id: string;
email: string;
role: string;
action: string;
entity_type: string;
entity_id: string;
timestamp: string;
ip: string;
reason: string | null;
}
export interface AuditListParams {
admin_id?: string;
action?: string;
date_from?: string;
date_to?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Dashboard Stats =====================
export interface DashboardStats {
users_total: number;
events_total: number;
reviews_total: number;
calendars_total: number;
reports_total: number;
tickets_total: number;
tickets_open: number;
avg_ticket_resolution_h: number;
admin_activity: AdminActivity[];
events_by_day: DayCount[];
registrations_by_day: DayCount[];
}
export interface AdminActivity {
admin_id: string;
email: string;
role: string;
last_login: string;
nickname: string;
actions: number;
}
export interface DayCount {
date: string;
count: number;
}
// ===================== Moderation =====================
export type TargetType = 'calendar' | 'event' | 'review' | 'user';
export type ModerationAction = {
calendar: 'freeze' | 'unfreeze';
event: 'freeze' | 'unfreeze';
review: 'hide' | 'unhide';
user: 'block' | 'unblock';
};
export interface ModerationPayload {
action: string;
reason?: string;
}
// ===================== Auth =====================
export interface LoginRequest {
email: string;
password: string;
}
export interface LoginResponse {
access_token: string;
refresh_token: string;
}
export interface RefreshResponse {
access_token: string;
refresh_token: string;
}
// ===================== Pagination =====================
export interface PaginatedResponse<T> {
data: T[];
total: number;
// ===================== Calendar =====================
export interface Calendar {
id: string;
title: string;
description: string;
type: 'personal' | 'commercial';
category: string;
owner_id: string;
status: 'active' | 'frozen' | 'deleted';
reason: string | null;
tags: string[];
color: string;
image_url: string;
rating_avg: number;
rating_count: number;
short_name: string;
confirmation: string;
settings: object | null;
created_at: string;
updated_at: string;
}
export interface CalendarListParams {
q?: string;
status?: 'active' | 'frozen' | 'deleted';
type?: 'personal' | 'commercial';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Event (Событие) =====================
export interface Event {
id: string;
calendar_id: string;
title: string;
description: string;
event_type: 'single' | 'recurring';
start_time: string; // ISO8601
duration: number;
recurrence: object | null;
master_id: string | null;
is_instance: boolean;
specialist_id: string | null;
location: object | null;
tags: string[];
capacity: number | null;
online_link: string | null;
status: 'active' | 'cancelled' | 'completed';
reason: string | null;
rating_avg: number;
rating_count: number;
attachments: string[] | null;
edit_history: object[] | null;
created_at: string; // ISO8601
updated_at: string; // ISO8601
}
export interface EventListParams {
from?: string;
to?: string;
status?: 'active' | 'cancelled' | 'completed';
calendar_id?: string;
title?: string;
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== User (Пользователь) =====================
export interface User {
id: string;
email: string;
role: 'user' | 'bot';
status: 'active' | 'frozen' | 'deleted';
reason: string | null;
nickname: string | null;
avatar_url: string | null;
timezone: string | null;
language: string | null;
social_links: string[] | null;
phone: string | null;
preferences: object | null;
last_login: string; // ISO8601
created_at: string; // ISO8601
updated_at: string; // ISO8601
}
export interface UserListParams {
role?: 'user' | 'bot';
status?: 'active' | 'frozen' | 'deleted';
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Report (Жалоба) =====================
export interface Report {
id: string;
reporter_id: string;
target_type: 'calendar' | 'event' | 'review';
target_id: string;
reason: string;
status: 'pending' | 'reviewed' | 'dismissed';
created_at: string;
resolved_at: string | null;
resolved_by: string | null;
}
export interface ReportListParams {
status?: 'pending' | 'reviewed' | 'dismissed';
target_type?: 'calendar' | 'event' | 'review';
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Review (Отзыв) =====================
export interface Review {
id: string;
user_id: string;
target_type: 'calendar' | 'event';
target_id: string;
rating: number; // 1-5
comment: string;
status: 'visible' | 'hidden' | 'deleted';
reason: string | null;
likes: number;
dislikes: number;
created_at: string;
updated_at: string;
}
export interface ReviewListParams {
target_type?: 'calendar' | 'event';
target_id?: string;
user_id?: string;
status?: 'visible' | 'hidden' | 'deleted';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Banned Word (Бан-слово) =====================
export interface BannedWord {
id: string;
word: string;
added_by: string | null;
added_at: string | null;
}
// ===================== Ticket (Тикет баг-трекера) =====================
export interface Ticket {
id: string;
reporter_id: string;
error_hash: string;
error_message: string;
stacktrace: string;
context: string;
count: number;
first_seen: string;
last_seen: string;
status: 'open' | 'in_progress' | 'resolved' | 'closed';
assigned_to: string | null;
resolution_note: string | null;
}
export interface TicketListParams {
status?: 'open' | 'in_progress' | 'resolved' | 'closed';
assigned_to?: string;
q?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
export interface TicketStats {
open: number;
in_progress: number;
resolved: number;
closed: number;
total_tickets: number;
total_errors: number;
}
// ===================== Subscription (Подписка) =====================
export interface Subscription {
id: string;
user_id: string;
plan: 'monthly' | 'quarterly' | 'biannual' | 'annual';
status: 'active' | 'expired' | 'cancelled';
trial_used: boolean;
started_at: string;
expires_at: string;
created_at: string;
updated_at: string;
}
export interface SubscriptionListParams {
plan?: 'monthly' | 'quarterly' | 'biannual' | 'annual';
status?: 'active' | 'expired' | 'cancelled';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Admin (Администратор) =====================
export interface Admin {
id: string;
email: string;
role: 'superadmin' | 'admin' | 'moderator' | 'support';
status: 'active' | 'blocked';
nickname: string | null;
avatar_url: string | null;
timezone: string | null;
language: string | null;
phone: string | null;
preferences: object | null;
last_login: string;
created_at: string;
updated_at: string;
}
export interface AdminListParams {
role?: 'superadmin' | 'admin' | 'moderator' | 'support';
status?: 'active' | 'blocked';
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Audit (Запись аудита) =====================
export interface AuditRecord {
id: string;
admin_id: string;
email: string;
role: string;
action: string;
entity_type: string;
entity_id: string;
timestamp: string;
ip: string;
reason: string | null;
}
export interface AuditListParams {
admin_id?: string;
action?: string;
date_from?: string;
date_to?: string;
limit?: number;
offset?: number;
sort?: string;
order?: 'asc' | 'desc';
}
// ===================== Dashboard Stats =====================
export interface DashboardStats {
users_total: number;
events_total: number;
reviews_total: number;
calendars_total: number;
reports_total: number;
tickets_total: number;
tickets_open: number;
avg_ticket_resolution_h: number;
admin_activity: AdminActivity[];
events_by_day: DayCount[];
registrations_by_day: DayCount[];
}
export interface AdminActivity {
admin_id: string;
email: string;
role: string;
last_login: string;
nickname: string;
actions: number;
}
export interface DayCount {
date: string;
count: number;
}
// ===================== Moderation =====================
export type TargetType = 'calendar' | 'event' | 'review' | 'user';
export type ModerationAction = {
calendar: 'freeze' | 'unfreeze';
event: 'freeze' | 'unfreeze';
review: 'hide' | 'unhide';
user: 'block' | 'unblock';
};
export interface ModerationPayload {
action: string;
reason?: string;
}
// ===================== Auth =====================
export interface LoginRequest {
email: string;
password: string;
}
export interface LoginResponse {
access_token: string;
refresh_token: string;
}
export interface RefreshResponse {
access_token: string;
refresh_token: string;
}
// ===================== Pagination =====================
export interface PaginatedResponse<T> {
data: T[];
total: number;
}