Compare commits

..

No commits in common. "c411142840782851e4aa60d9f46c7acf931e7a11" and "46cd1fa0fa872c12f92d76e71aff6733b831de76" have entirely different histories.

13 changed files with 500 additions and 1690 deletions

View File

@ -1,7 +0,0 @@
node_modules
.git
.gitignore
Dockerfile
.dockerignore
dist
npm-debug.log

View File

@ -31,10 +31,7 @@
"reactflow": "^11.11.4",
"recharts": "^2.15.1",
"socket.io-client": "^4.8.1",
"vite-plugin-svgr": "^4.3.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@dnd-kit/core": "^6.3.1"
"vite-plugin-svgr": "^4.3.0"
},
"devDependencies": {
"@eslint/js": "^9.17.0",

View File

@ -16,13 +16,13 @@ const formatXAxis = (tickItem) => {
};
const formatTooltip = (value, name, props) => {
return [`${value.toFixed(2)}`, `Устройство ${name}`];
return [`${value.toFixed(2)}`, ` ${name}`];
};
const LineChartComponent = ({
data = [],
multipleLines = true, // По умолчанию включаем множественные линии
lineKey = 'device', // Ключ для разделения линий
multipleLines = false,
lineKey = 'device',
title,
description,
height = 400,
@ -30,25 +30,27 @@ const LineChartComponent = ({
}) => {
if (!data || data.length === 0) return <div>Нет данных для отображения</div>;
// Создаем массив уникальных устройств
const devices = [...new Set(data.map(item => item.device))];
// Создаем массив уникальных линий
const lineKeys = [...new Set(data.map(item => item[lineKey] || 'default'))];
// Группируем данные по timestamp для правильного отображения
const timestamps = [...new Set(data.map(item => item.timestamp))].sort();
// Преобразуем данные в формат, удобный для Recharts
const chartData = data.reduce((acc, item) => {
const timestamp = item.timestamp;
const existingPoint = acc.find(p => p.timestamp === timestamp);
const chartData = timestamps.map(timestamp => {
const point = { timestamp };
// Для каждого устройства находим значение в этот timestamp
devices.forEach(device => {
const deviceData = data.find(item =>
item.timestamp === timestamp && item.device === device
if (existingPoint) {
return acc.map(p =>
p.timestamp === timestamp
? { ...p, [item[lineKey] || 'default']: item.value }
: p
);
point[`device_${device}`] = deviceData ? deviceData.value : null;
});
}
return point;
});
return [...acc, {
timestamp,
[item[lineKey] || 'default']: item.value
}];
}, []).sort((a, b) => a.timestamp - b.timestamp);
return (
<div style={{ width: '100%', height: `${height}px` }}>
@ -61,27 +63,39 @@ const LineChartComponent = ({
dataKey="timestamp"
tickFormatter={formatXAxis}
/>
<YAxis />
<YAxis domain={[0, 25]} />
<Tooltip
formatter={formatTooltip}
labelFormatter={(label) => format(new Date(label), 'yyyy-MM-dd HH:mm:ss')}
/>
<Legend />
{devices.map(device => (
{multipleLines ? (
lineKeys.map(key => (
<Line
key={`line-${key}`}
type="monotone"
dataKey={key}
name={` ${key}`}
stroke={lineColors[key] || lineColors.default}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
isAnimationActive={false}
/>
))
) : (
<Line
key={`line-${device}`}
type="monotone"
dataKey={`device_${device}`}
name={`Устройство ${device}`}
stroke={lineColors[device] || lineColors.default}
dataKey={lineKeys[0] || 'value'}
name={title}
stroke={lineColors.default}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
isAnimationActive={false}
connectNulls={true}
/>
))}
)}
{/* Добавляем диапазоны если они есть */}
{ranges.map((range, idx) => (

View File

@ -1,8 +1,8 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import LineChartComponent from './LineChartComponent';
import DateRangeSelector from '../Charts2/Components/DateRangeSelector';
import metricsService from '../Charts2/Components/metricsService';
import { Button, Radio, message, Tag } from 'antd';
import { Button, Radio, message, Tag, Spin } from 'antd';
import moment from 'moment';
import StatusLogTable from '../Charts2/Components/StatusLogTable';
import { Box, IconButton, Tooltip as MuiTooltip } from '@mui/material';
@ -15,12 +15,14 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
title = metricName,
description,
context = {},
ranges = []
ranges = [],
multipleLines = false,
lineKey = 'device'
} = metricInfo || {};
const { device, source_id } = context;
const [chartData, setChartData] = useState([]);
const [rawData, setRawData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [metricMeta, setMetricMeta] = useState({});
@ -30,96 +32,43 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const [isLiveUpdating, setIsLiveUpdating] = useState(false);
const [showLogs, setShowLogs] = useState(false);
const [statusLogs, setStatusLogs] = useState([]);
const MAX_POINTS = 50;
const MAX_POINTS = 1000;
const TIME_WINDOW_MS = 3600 * 1000;
// Эта функция может больше не понадобиться, так как
// сервис сам генерирует ключи, но оставьте для совместимости
const getSubscriptionKey = () => {
const subscriptionKey = useMemo(() => {
const filterParts = [];
if (device) filterParts.push(`device=${encodeURIComponent(device)}`);
if (source_id) filterParts.push(`source_id=${encodeURIComponent(source_id)}`);
return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`;
};
}, [metricName, device, source_id]);
const getStatusFromRanges = (value, ranges) => {
if (!ranges || ranges.length === 0) return 1;
for (const r of ranges) {
if (value >= r.min && value <= r.max) {
return r.status;
}
}
return 1;
};
const formatMetricData = (responseData) => {
const dataArray = Array.isArray(responseData) ? responseData : responseData.data;
const formatMetricData = (dataArray) => {
if (!Array.isArray(dataArray)) {
console.error('Expected array in formatMetricData, got:', typeof dataArray);
console.error('Expected array but got:', responseData);
return [];
}
return dataArray.map(item => {
if (item.timestamp === undefined || item.value === undefined) {
console.warn('Invalid metric item:', item);
return null;
}
return {
...item,
timestamp: Number(item.timestamp),
value: parseFloat(item.value),
status: getStatusFromRanges(parseFloat(item.value), ranges),
name: item.__name__ || metricName,
device: item.device?.trim() || null,
source_id: item.source_id || null,
description: item.description || description
};
}).filter(Boolean)
.sort((a, b) => a.timestamp - b.timestamp);
return dataArray.map(item => ({
...item,
timestamp: item.timestamp,
value: parseFloat(item.value),
name: item.__name__ || metricName,
status: parseInt(item.status) || 0,
device: item.device?.trim() || null,
source_id: item.source_id || null,
description: item.description || description,
lineId: item[lineKey] || 'default'
}));
};
const calculateStep = (startTime, endTime, maxPoints = 10000) => {
const durationSeconds = (endTime.getTime() - startTime.getTime()) / 1000;
return Math.max(Math.ceil(durationSeconds / maxPoints), 1);
const calculateStep = (start, end) => {
const duration = end.getTime() - start.getTime();
return Math.max(Math.floor(duration / (MAX_POINTS * 1000)), 1);
};
const downsampleData = (data, maxPoints = MAX_POINTS) => {
if (data.length <= maxPoints) return [...data];
const sortedData = [...data].sort((a, b) => a.timestamp - b.timestamp);
const step = Math.max(1, Math.floor(sortedData.length / maxPoints));
const result = [];
for (let i = 0; i < sortedData.length; i += step) {
if (result.length >= maxPoints) break;
result.push(sortedData[i]);
}
if (result.length > 0) {
const lastOriginalPoint = sortedData[sortedData.length - 1];
if (result[result.length - 1].timestamp !== lastOriginalPoint.timestamp) {
result[result.length - 1] = lastOriginalPoint;
}
}
return result;
};
useEffect(() => {
if (chartData.length > 0) {
const newLogs = chartData.reduce((acc, point, index) => {
if (index === 0 || point.status !== chartData[index - 1].status) {
return [...acc, point];
}
return acc;
}, []);
setStatusLogs(newLogs);
}
}, [chartData]);
const fetchHistoricalData = async (start, end) => {
setIsLoading(true);
setError(null);
@ -133,23 +82,19 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const step = calculateStep(start, end);
// Используем новый метод для исторических данных
const data = await metricsService.fetchMetricsRange(
metricName,
start.getTime(), // Теперь передаем timestamp в миллисекундах
end.getTime(),
Math.floor(start.getTime() / 1000),
Math.floor(end.getTime() / 1000),
step,
extendedFilters
);
const formattedData = formatMetricData(data)
.sort((a, b) => a.timestamp - b.timestamp);
const responseData = Array.isArray(data) ? data : data.data;
const formattedData = formatMetricData(responseData);
setRawData(formattedData);
const limitedData = formattedData.length > MAX_POINTS
? downsampleData(formattedData, MAX_POINTS)
: formattedData;
if (limitedData.length > 0) {
if (formattedData.length > 0) {
setMetricMeta({
type: data[0]?.type,
description: data[0]?.description || description,
@ -157,8 +102,6 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
job: data[0]?.job
});
}
setChartData(limitedData);
} catch (err) {
console.error(`Error loading historical data for ${metricName}:`, err);
setError(err.message);
@ -174,55 +117,42 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const end = new Date();
const start = new Date(end.getTime() - TIME_WINDOW_MS);
const cutoffTime = Date.now() - TIME_WINDOW_MS;
fetchHistoricalData(start, end).finally(() => setIsLoading(false));
// Изменяем параметры подписки
return metricsService.subscribeToMetric(
metricName, // Теперь передаем просто имя метрики
{ ...filters, device, source_id }, // Фильры отдельным параметром
(update) => { // Колбэк получает объект с данными
console.log('Received WS update:', update);
if (!update || !Array.isArray(update.data)) {
console.error('Invalid update format:', update);
return;
}
setChartData(prev => {
const now = Date.now();
const cutoffTime = now - TIME_WINDOW_MS;
const formattedNew = formatMetricData(update.data)
subscriptionKey,
(newData) => {
setRawData(prev => {
const actualData = Array.isArray(newData) ? newData : newData.data;
const formattedNewData = formatMetricData(actualData)
.filter(point => point.timestamp >= cutoffTime);
const filteredPrev = prev.filter(point =>
point.timestamp >= cutoffTime
);
const filteredPrev = prev.filter(point => point.timestamp >= cutoffTime);
const merged = [...filteredPrev, ...formattedNew]
const merged = [...filteredPrev, ...formattedNewData]
.filter((v, i, a) =>
a.findIndex(t => t.timestamp === v.timestamp) === i
)
.sort((a, b) => a.timestamp - b.timestamp);
a.findIndex(t =>
t.timestamp === v.timestamp &&
t[lineKey] === v[lineKey]
) === i
);
return merged.length > MAX_POINTS
? merged.slice(-MAX_POINTS)
: merged;
return merged;
});
},
5000 // Интервал обновления (можно настроить)
5000,
{
...filters,
...(device && { device }),
...(source_id && { source_id })
}
);
};
const stopRealtimeUpdates = () => {
setIsLiveUpdating(false);
// Теперь отписываемся по метрике и фильтрам
metricsService.unsubscribeFromMetric(
metricName,
{ ...filters, device, source_id }
);
metricsService.unsubscribeFromMetric(subscriptionKey);
};
const handleCustomRangeApply = () => {
@ -232,29 +162,45 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
};
useEffect(() => {
console.log('Metric changed:', { metricName, device, source_id, filters });
if (rawData.length > 0) {
const logs = [];
const devices = [...new Set(rawData.map(item => item[lineKey]))];
devices.forEach(dev => {
const deviceData = rawData
.filter(item => item[lineKey] === dev)
.sort((a, b) => a.timestamp - b.timestamp);
if (deviceData.length > 0) {
logs.push(deviceData[0]); // Первая точка
for (let i = 1; i < deviceData.length; i++) {
if (deviceData[i].status !== deviceData[i - 1].status) {
logs.push(deviceData[i]);
}
}
}
});
setStatusLogs(logs.sort((a, b) => b.timestamp - a.timestamp));
}
}, [rawData, lineKey]);
useEffect(() => {
let unsubscribe;
const init = async () => {
if (mode === 'realtime') {
unsubscribe = startRealtimeUpdates();
} else {
await fetchHistoricalData(startDate, endDate);
}
};
init();
if (mode === 'realtime') {
unsubscribe = startRealtimeUpdates();
} else {
stopRealtimeUpdates();
fetchHistoricalData(startDate, endDate);
}
return () => {
if (unsubscribe) {
unsubscribe(); // Вызываем функцию отписки
}
if (mode === 'realtime') {
stopRealtimeUpdates(); // Дополнительная очистка
}
if (unsubscribe) unsubscribe();
stopRealtimeUpdates();
};
}, [mode, metricName, device, source_id, JSON.stringify(filters)]); // Добавляем JSON.stringify для фильтров
}, [mode, metricName, device, source_id]);
const metaInfo = [
metricMeta.instance && `Instance: ${metricMeta.instance}`,
@ -263,7 +209,7 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
].filter(Boolean).join(' | ');
return (
<div>
<div style={{ position: 'relative' }}>
<div style={{ marginBottom: 16 }}>
<Radio.Group
value={mode}
@ -285,15 +231,10 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
/>
)}
{mode === 'realtime' && isLiveUpdating && (
<Button
type="primary"
danger
onClick={() => setMode('historical')}
style={{ marginTop: 10 }}
>
Остановить обновление
</Button>
{mode === 'realtime' && (
<Tag color={isLiveUpdating ? 'green' : 'red'}>
{isLiveUpdating ? 'Обновление в реальном времени' : 'Режим реального времени остановлен'}
</Tag>
)}
</div>
@ -318,28 +259,26 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
</MuiTooltip>
{isLoading ? (
<div>Загрузка графика...</div>
<div style={{ height: chartHeight, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Spin size="large" tip="Загрузка данных..." />
</div>
) : error ? (
<div>Ошибка: {error}</div>
) : chartData.length === 0 ? (
<div>Нет данных для метрики: {metricName}</div>
<div style={{ color: 'red', padding: 20 }}>Ошибка: {error}</div>
) : rawData.length === 0 ? (
<div style={{ padding: 20 }}>Нет данных для метрики: {metricName}</div>
) : (
<>
<LineChartComponent
data={chartData}
data={rawData}
title={title}
description={description}
multipleLines={multipleLines}
lineKey={lineKey}
metaInfo={metaInfo}
height={chartHeight}
additionalFilters={{
device,
source_id
}}
ranges={ranges}
/>
{showLogs && (
<StatusLogTable logs={statusLogs} />
)}
{showLogs && <StatusLogTable logs={statusLogs} />}
</>
)}
</Box>

View File

@ -2,28 +2,16 @@ class MetricsService {
constructor() {
this.baseUrl = '/metrics-ws';
this.socket = null;
this.subscriptions = new Map(); // Хранит подписки на real-time данные
this.pendingRequests = new Map(); // Для разовых запросов
this.subscriptions = new Map();
this.pendingRequests = new Map();
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectDelay = 5000;
this.connectionCallbacks = new Set(); // Колбэки для событий подключения
window.addEventListener('beforeunload', () => this.cleanupAll());
window.addEventListener('pagehide', () => this.cleanupAll());
}
// Новый метод для отслеживания состояния подключения
onConnectionChange(callback) {
this.connectionCallbacks.add(callback);
return () => this.connectionCallbacks.delete(callback);
}
// Уведомление всех подписчиков о изменении состояния
notifyConnectionChange(connected) {
this.connectionCallbacks.forEach(cb => cb(connected));
}
handleServerMessage(msg) {
try {
if (!msg || typeof msg !== 'object') {
@ -34,25 +22,25 @@ class MetricsService {
const { event, data, requestId } = msg;
switch (event) {
case 'connected':
console.log('Server connection confirmed:', data);
this.notifyConnectionChange(true);
case 'metrics-data':
if (requestId && this.pendingRequests.has(requestId)) {
const { resolve } = this.pendingRequests.get(requestId);
resolve(data);
this.pendingRequests.delete(requestId);
} else {
const metricKey = data.metric;
const callbacks = this.subscriptions.get(metricKey) || [];
callbacks.forEach(cb => cb(data));
}
break;
case 'realtime-data':
this.handleRealtimeData(data, requestId);
break;
case 'historical-data':
this.handleHistoricalData(data, requestId);
break;
case 'current-data':
this.handleCurrentData(data, requestId);
break;
case 'error':
this.handleError(data, requestId);
case 'metrics-error':
if (requestId && this.pendingRequests.has(requestId)) {
const { reject } = this.pendingRequests.get(requestId);
reject(new Error(data.error));
this.pendingRequests.delete(requestId);
}
break;
default:
@ -63,54 +51,6 @@ class MetricsService {
}
}
handleRealtimeData(data, requestId) {
const { metric, filters, data: metricsData, type } = data;
const metricKey = this.getMetricKey(metric, filters);
if (requestId && this.pendingRequests.has(requestId)) {
// Это ответ на разовый запрос
const { resolve } = this.pendingRequests.get(requestId);
resolve(metricsData);
this.pendingRequests.delete(requestId);
} else {
// Это обновление по подписке
const callbacks = this.subscriptions.get(metricKey) || [];
callbacks.forEach(cb => cb({
data: metricsData,
type: type || 'update',
metric,
filters,
timestamp: Date.now()
}));
}
}
handleHistoricalData(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { resolve } = this.pendingRequests.get(requestId);
resolve(data.data || data);
this.pendingRequests.delete(requestId);
}
}
handleCurrentData(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { resolve } = this.pendingRequests.get(requestId);
resolve(data.data || data);
this.pendingRequests.delete(requestId);
}
}
handleError(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { reject } = this.pendingRequests.get(requestId);
reject(new Error(data.error || 'Unknown error'));
this.pendingRequests.delete(requestId);
} else {
console.error('Server error:', data.error);
}
}
connectWebSocket() {
if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) {
return;
@ -118,27 +58,25 @@ class MetricsService {
console.log('Connecting WebSocket...');
this.socket = new WebSocket(this.baseUrl);
this.notifyConnectionChange(false);
this.socket.addEventListener('open', () => {
console.log('WebSocket connected');
this.reconnectAttempts = 0;
this.notifyConnectionChange(true);
// Переподписываемся на все активные подписки
this.resubscribeAll();
this.subscriptions.forEach((_, metricKey) => {
const filters = this.parseFiltersFromKey(metricKey);
const [metric] = metricKey.split('?');
this.sendMessage('subscribe-metric', { metric, filters });
});
});
this.socket.addEventListener('close', (event) => {
console.log('WebSocket disconnected', event.code, event.reason);
this.socket.addEventListener('close', () => {
console.log('WebSocket disconnected');
this.socket = null;
this.notifyConnectionChange(false);
this.scheduleReconnect();
});
this.socket.addEventListener('error', (err) => {
console.error('WebSocket error:', err);
this.notifyConnectionChange(false);
});
this.socket.addEventListener('message', (event) => {
@ -151,18 +89,6 @@ class MetricsService {
});
}
// Переподписка на все активные подписки после переподключения
resubscribeAll() {
this.subscriptions.forEach((_, metricKey) => {
const { metric, filters } = this.parseMetricKey(metricKey);
this.sendMessage('subscribe-realtime', {
metric,
filters,
interval: 10000 // Дефолтный интервал
});
});
}
scheduleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.warn('Max reconnect attempts reached');
@ -178,13 +104,12 @@ class MetricsService {
}, delay);
}
sendMessage(event, data, requestId) {
sendMessage(event, data) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
if (this.socket && this.socket.readyState === WebSocket.CONNECTING) {
// Ждем открытия соединения
const waitForOpen = () => {
if (this.socket.readyState === WebSocket.OPEN) {
this.doSendMessage(event, data, requestId);
this.socket.send(JSON.stringify({ event, data }));
} else if (this.socket.readyState === WebSocket.CONNECTING) {
setTimeout(waitForOpen, 100);
}
@ -193,188 +118,95 @@ class MetricsService {
} else {
console.warn('WebSocket not connected, cannot send:', event);
this.connectWebSocket();
// Сохраняем сообщение для отправки после подключения
setTimeout(() => {
if (this.socket?.readyState === WebSocket.OPEN) {
this.doSendMessage(event, data, requestId);
}
}, 1000);
}
return;
}
this.doSendMessage(event, data, requestId);
this.socket.send(JSON.stringify({ event, data }));
}
doSendMessage(event, data, requestId) {
const message = requestId ? { event, data, requestId } : { event, data };
this.socket.send(JSON.stringify(message));
async fetchMetricsRange(metric, start, end, step = 15, filters = {}) {
return new Promise((resolve, reject) => {
this.connectWebSocket();
const requestId = `range-${Date.now()}`;
// Таймаут для очистки
const timeout = setTimeout(() => {
reject(new Error('Request timeout'));
this.pendingRequests.delete(requestId);
}, 12000);
this.pendingRequests.set(requestId, {
resolve: (responseData) => {
clearTimeout(timeout);
const data = Array.isArray(responseData) ? responseData :
(responseData?.data || []);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-metrics', {
metric, start, end, step, filters, isRangeQuery: true, requestId
});
});
}
// ============ ПУБЛИЧНЫЕ МЕТОДЫ ============
// Подписка на real-time данные
subscribeToMetric(metric, filters = {}, callback, interval = 10000) {
subscribeToMetric(metricKey, callback, interval = 5000, filters = {}) {
this.connectWebSocket();
const metricKey = this.getMetricKey(metric, filters);
if (!this.subscriptions.has(metricKey)) {
this.subscriptions.set(metricKey, []);
this.sendMessage('subscribe-realtime', {
metric,
filters,
interval
});
const [metric] = metricKey.split('?');
this.sendMessage('subscribe-metric', { metric, interval, filters });
}
const callbacks = this.subscriptions.get(metricKey);
callbacks.push(callback);
// Возвращаем функцию для отписки
return () => this.unsubscribeFromMetric(metric, filters, callback);
return () => this.unsubscribeFromMetric(metricKey, callback);
}
// Отписка от real-time данных
unsubscribeFromMetric(metric, filters = {}, callback) {
const metricKey = this.getMetricKey(metric, filters);
unsubscribeFromMetric(metricKey, callback) {
const callbacks = this.subscriptions.get(metricKey) || [];
const filtered = callbacks.filter(cb => cb !== callback);
if (filtered.length === 0) {
this.subscriptions.delete(metricKey);
this.sendMessage('unsubscribe-realtime', { metric, filters });
const [metric] = metricKey.split('?');
this.sendMessage('unsubscribe-metric', { metric });
} else {
this.subscriptions.set(metricKey, filtered);
}
}
// Запрос исторических данных (разовый)
async fetchMetricsRange(metric, start, end, step = 60, filters = {}) {
return new Promise((resolve, reject) => {
this.connectWebSocket();
const requestId = `historical-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const timeout = setTimeout(() => {
reject(new Error('Historical data request timeout'));
this.pendingRequests.delete(requestId);
}, 30000); // 30 секунд таймаут для historical данных
this.pendingRequests.set(requestId, {
resolve: (data) => {
clearTimeout(timeout);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-historical', {
metric,
start: Math.floor(start / 1000) * 1000, // Ensure milliseconds
end: Math.floor(end / 1000) * 1000,
step,
filters
}, requestId);
});
}
// Запрос текущих данных (разовый)
async fetchCurrentMetrics(metric, filters = {}) {
return new Promise((resolve, reject) => {
this.connectWebSocket();
const requestId = `current-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const timeout = setTimeout(() => {
reject(new Error('Current data request timeout'));
this.pendingRequests.delete(requestId);
}, 10000); // 10 секунд таймаут
this.pendingRequests.set(requestId, {
resolve: (data) => {
clearTimeout(timeout);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-current', {
metric,
filters
}, requestId);
});
}
// Отписка от всех подписок
unsubscribeAll() {
this.sendMessage('unsubscribe-all', {});
this.subscriptions.clear();
}
// ============ ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ ============
getMetricKey(metric, filters) {
const sortedKeys = Object.keys(filters).sort();
const filterString = sortedKeys
.map(key => `${key}=${encodeURIComponent(filters[key])}`)
.join('&');
return filterString ? `${metric}?${filterString}` : metric;
}
parseMetricKey(metricKey) {
const [metric, query] = metricKey.split('?');
const filters = {};
if (query) {
query.split('&').forEach(pair => {
const [key, value] = pair.split('=');
if (key && value) {
filters[decodeURIComponent(key)] = decodeURIComponent(value);
}
});
}
return { metric, filters };
parseFiltersFromKey(metricKey) {
const parts = metricKey.split('?');
if (parts.length < 2) return {};
return parts[1].split('&').reduce((acc, pair) => {
const [key, value] = pair.split('=');
if (key && value) acc[key] = value;
return acc;
}, {});
}
cleanupAll() {
this.unsubscribeAll();
this.sendMessage('unsubscribe-all', {});
this.subscriptions.clear();
this.disconnectWebSocket();
}
disconnectWebSocket() {
if (this.socket) {
this.socket.close(1000, 'Client disconnected');
this.socket.close();
this.socket = null;
}
this.notifyConnectionChange(false);
}
// Проверка состояния подключения
isConnected() {
return this.socket?.readyState === WebSocket.OPEN;
}
// Получение текущего состояния
getConnectionState() {
return this.socket ? this.socket.readyState : WebSocket.CLOSED;
}
}
// Создаем глобальный экземпляр
const metricsService = new MetricsService();
// Экспорт для использования в модульной системе
export default metricsService;
// Глобальный экспорт для прямого использования в браузере
if (typeof window !== 'undefined') {
window.MetricsService = metricsService;
}

View File

@ -34,8 +34,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
const TIME_WINDOW_MS = 3600 * 1000;
// Эта функция может больше не понадобиться, так как
// сервис сам генерирует ключи, но оставьте для совместимости
const getSubscriptionKey = () => {
const filterParts = [];
if (device) filterParts.push(`device=${encodeURIComponent(device)}`);
@ -43,16 +41,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`;
};
const getStatusFromRanges = (value, ranges) => {
if (!ranges || ranges.length === 0) return 1;
for (const r of ranges) {
if (value >= r.min && value <= r.max) {
return r.status;
}
}
return 1;
};
const formatMetricData = (dataArray) => {
if (!Array.isArray(dataArray)) {
console.error('Expected array in formatMetricData, got:', typeof dataArray);
@ -69,7 +57,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
...item,
timestamp: Number(item.timestamp),
value: parseFloat(item.value),
status: getStatusFromRanges(parseFloat(item.value), ranges),
status: parseInt(item.status || '0'),
name: item.__name__ || metricName,
device: item.device?.trim() || null,
source_id: item.source_id || null,
@ -132,12 +120,10 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
};
const step = calculateStep(start, end);
// Используем новый метод для исторических данных
const data = await metricsService.fetchMetricsRange(
metricName,
start.getTime(), // Теперь передаем timestamp в миллисекундах
end.getTime(),
Math.floor(start.getTime() / 1000),
Math.floor(end.getTime() / 1000),
step,
extendedFilters
);
@ -146,7 +132,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
.sort((a, b) => a.timestamp - b.timestamp);
const limitedData = formattedData.length > MAX_POINTS
? downsampleData(formattedData, MAX_POINTS)
? formattedData.slice(-MAX_POINTS)
: formattedData;
if (limitedData.length > 0) {
@ -177,15 +163,12 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
fetchHistoricalData(start, end).finally(() => setIsLoading(false));
// Изменяем параметры подписки
return metricsService.subscribeToMetric(
metricName, // Теперь передаем просто имя метрики
{ ...filters, device, source_id }, // Фильры отдельным параметром
(update) => { // Колбэк получает объект с данными
console.log('Received WS update:', update);
if (!update || !Array.isArray(update.data)) {
console.error('Invalid update format:', update);
getSubscriptionKey(),
(newData) => {
console.log('Received WS update:', newData);
if (!Array.isArray(newData)) {
console.error('Expected array in WS update, got:', typeof newData);
return;
}
@ -193,7 +176,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
const now = Date.now();
const cutoffTime = now - TIME_WINDOW_MS;
const formattedNew = formatMetricData(update.data)
const formattedNew = formatMetricData(newData)
.filter(point => point.timestamp >= cutoffTime);
const filteredPrev = prev.filter(point =>
@ -211,18 +194,15 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
: merged;
});
},
5000 // Интервал обновления (можно настроить)
1000,
{ ...filters, device, source_id }
);
};
const stopRealtimeUpdates = () => {
setIsLiveUpdating(false);
// Теперь отписываемся по метрике и фильтрам
metricsService.unsubscribeFromMetric(
metricName,
{ ...filters, device, source_id }
);
metricsService.unsubscribeFromMetric(getSubscriptionKey());
};
const handleCustomRangeApply = () => {
@ -235,7 +215,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
console.log('Metric changed:', { metricName, device, source_id, filters });
let unsubscribe;
const init = async () => {
if (mode === 'realtime') {
unsubscribe = startRealtimeUpdates();
@ -247,14 +226,10 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
init();
return () => {
if (unsubscribe) {
unsubscribe(); // Вызываем функцию отписки
}
if (mode === 'realtime') {
stopRealtimeUpdates(); // Дополнительная очистка
}
if (unsubscribe) unsubscribe();
stopRealtimeUpdates();
};
}, [mode, metricName, device, source_id, JSON.stringify(filters)]); // Добавляем JSON.stringify для фильтров
}, [mode, metricName, device, source_id, filters]);
const metaInfo = [
metricMeta.instance && `Instance: ${metricMeta.instance}`,

View File

@ -1,303 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
Box,
Typography,
List,
ListItem,
ListItemText,
ListItemSecondaryAction,
IconButton,
TextField,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Chip,
Collapse,
CircularProgress
} from '@mui/material';
import {
Edit as EditIcon,
Delete as DeleteIcon,
ExpandMore as ExpandMoreIcon,
ExpandLess as ExpandLessIcon
} from '@mui/icons-material';
import axios from 'axios';
const MenuItemComponent = ({ item, level = 0, onEdit, onDelete }) => {
const [expanded, setExpanded] = useState(false);
const hasChildren = item.items && item.items.length > 0;
const handleToggle = () => {
if (hasChildren) {
setExpanded(!expanded);
}
};
return (
<>
<ListItem
sx={{
pl: level * 4,
borderBottom: '1px solid',
borderColor: 'divider'
}}
>
<ListItemText
primary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body1">{item.title}</Typography>
{item.isDynamic && (
<Chip
label="Динамический"
size="small"
color="info"
variant="outlined"
/>
)}
</Box>
}
secondary={item.id}
/>
<ListItemSecondaryAction>
{/* */}
<>
<IconButton
edge="end"
aria-label="edit"
onClick={() => onEdit(item)}
sx={{ mr: 1 }}
>
<EditIcon />
</IconButton>
<IconButton
edge="end"
aria-label="delete"
onClick={() => onDelete(item)}
color="error"
>
<DeleteIcon />
</IconButton>
</>
{hasChildren && (
<IconButton
edge="end"
aria-label="expand"
onClick={handleToggle}
sx={{ ml: 1 }}
>
{expanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</IconButton>
)}
</ListItemSecondaryAction>
</ListItem>
{hasChildren && (
<Collapse in={expanded} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{item.items.map((child) => (
<MenuItemComponent
key={child.id}
item={child}
level={level + 1}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</List>
</Collapse>
)}
</>
);
};
const EditDialog = ({ open, item, onClose, onSave }) => {
const [title, setTitle] = useState(item?.title || '');
useEffect(() => {
setTitle(item?.title || '');
}, [item]);
const handleSave = () => {
onSave(item.id, { title });
onClose();
};
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>Редактировать элемент меню</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
label="Название"
fullWidth
variant="outlined"
value={title}
onChange={(e) => setTitle(e.target.value)}
sx={{ mt: 2 }}
/>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Отмена</Button>
<Button onClick={handleSave} variant="contained">
Сохранить
</Button>
</DialogActions>
</Dialog>
);
};
const MenuEditor = ({ onSave }) => {
const [menuData, setMenuData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [selectedItem, setSelectedItem] = useState(null);
const [hasChanges, setHasChanges] = useState(false);
useEffect(() => {
fetchMenuData();
}, []);
const fetchMenuData = async () => {
try {
setLoading(true);
const response = await axios.get('/api/menu/full');
setMenuData(response.data);
setError(null);
} catch (err) {
setError('Ошибка загрузки меню');
console.error('Error fetching menu:', err);
} finally {
setLoading(false);
}
};
const handleEdit = (item) => {
setSelectedItem(item);
setEditDialogOpen(true);
};
const handleDelete = (item) => {
setSelectedItem(item);
setDeleteDialogOpen(true);
};
const handleEditSave = async (id, updates) => {
try {
await axios.put(`/api/menu/${id}`, updates);
setHasChanges(true);
fetchMenuData();
} catch (err) {
console.error('Error updating menu item:', err);
alert('Ошибка при сохранении изменений');
}
};
const handleDeleteConfirm = async () => {
try {
await axios.delete(`/api/menu/items/${selectedItem.id}`);
setHasChanges(true);
setDeleteDialogOpen(false);
fetchMenuData();
} catch (err) {
console.error('Error deleting menu item:', err);
alert('Ошибка при удалении элемента');
}
};
const handleSave = async () => {
if (hasChanges) {
onSave({
hasChanges: true, saveChanges: async () => {
// Принудительно обновляем кэш
try {
await axios.post('/api/menu/invalidate-cache');
return true;
} catch (err) {
console.error('Error invalidating cache:', err);
return false;
}
}
});
setHasChanges(false);
}
};
if (loading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
<CircularProgress />
</Box>
);
}
if (error) {
return (
<Box sx={{ p: 3 }}>
<Typography color="error">{error}</Typography>
</Box>
);
}
return (
<Box>
<Typography variant="h6" gutterBottom>
Редактирование меню
</Typography>
<Typography variant="body2" color="text.secondary" paragraph>
Вы можете редактировать названия и удалять элементы меню. Динамические элементы (помечены синим) нельзя редактировать.
</Typography>
<List>
{menuData.items.map((item) => (
<MenuItemComponent
key={item.id}
item={item}
onEdit={handleEdit}
onDelete={handleDelete}
/>
))}
</List>
<EditDialog
open={editDialogOpen}
item={selectedItem}
onClose={() => setEditDialogOpen(false)}
onSave={handleEditSave}
/>
<Dialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
>
<DialogTitle>Подтверждение удаления</DialogTitle>
<DialogContent>
<Typography>
Вы уверены, что хотите удалить элемент "{selectedItem?.title}"?
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)}>Отмена</Button>
<Button onClick={handleDeleteConfirm} color="error" variant="contained">
Удалить
</Button>
</DialogActions>
</Dialog>
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
<Button
variant="contained"
onClick={handleSave}
disabled={!hasChanges}
>
Применить изменения
</Button>
</Box>
</Box>
);
};
export default MenuEditor;

View File

@ -21,7 +21,6 @@ import CloseIcon from '@mui/icons-material/Close';
import SaveIcon from '@mui/icons-material/Save';
import MetricRangeEditor from './SettingsComponents/MetricRangeEditor';
import UserManagement from './SettingsComponents/UserManagement';
import MenuEditor from './SettingsComponents/MenuEditor'
const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
@ -65,10 +64,6 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
hasChanges: false,
save: () => { }
});
const [menuEditorState, setMenuEditorState] = useState({
hasChanges: false,
save: () => Promise.resolve(true)
});
const handleTabChange = (event, newValue) => {
if (hasChanges) {
@ -78,22 +73,12 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
}
};
const handleMenuEditorChange = ({ hasChanges, saveChanges }) => {
setMenuEditorState({ hasChanges, save: saveChanges });
setHasChanges(hasChanges);
};
const handleSave = async () => {
setIsSaving(true);
try {
let success = true;
if (tabValue === 0 && menuEditorState.hasChanges) {
success = await menuEditorState.save();
}
if (tabValue === 1 && metricEditorState.hasChanges) {
success = success && await metricEditorState.save();
success = await metricEditorState.save();
}
if (success) {
@ -128,6 +113,7 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
}
};
// Пример обработчика изменений
const handleSettingChange = () => {
setHasChanges(true);
};
@ -163,13 +149,14 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
<Tab label="Меню" id="settings-tab-0" aria-controls="settings-tabpanel-0" />
<Tab label="Границы метрик" id="settings-tab-1" aria-controls="settings-tabpanel-1" />
<Tab label="Управление пользователями" id="settings-tab-2" aria-controls="settings-tabpanel-2" />
{/* Добавить новые вкладки здесь */}
{/* Добавляйте новые вкладки здесь */}
</Tabs>
</Box>
<DialogContent dividers>
<TabPanel value={tabValue} index={0}>
<MenuEditor onSave={handleMenuEditorChange} />
<Typography variant="h6">Настройки меню</Typography>
{/* Добавьте содержимое для вкладки меню */}
</TabPanel>
<TabPanel value={tabValue} index={1}>

View File

@ -1,4 +1,5 @@
import { useState, useEffect } from "react";
// SidebarMenu.jsx
import React, { useState, useEffect } from "react";
import {
Drawer,
List,
@ -6,30 +7,14 @@ import {
IconButton,
Tooltip,
Box,
alpha
} from "@mui/material";
import MenuItem from "./SidebarMenuComponents/MenuItem";
import SidebarFooter from "./SidebarMenuComponents/SidebarFooter";
import useSidebarResize from "../hooks/useSidebarResize";
import ChevronLeft from "@mui/icons-material/ChevronLeft";
import ChevronRight from "@mui/icons-material/ChevronRight";
import LogoFull from "../../assets/images/logo.svg?react";
import LogoSmall from "../../assets/images/system_monitor_icon.svg?react";
import {
DndContext,
closestCenter,
PointerSensor,
useSensor,
useSensors,
DragOverlay,
MeasuringStrategy
} from "@dnd-kit/core";
import {
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import SortableMenuItem from "./SidebarMenuComponents/SortableMenuItem";
import ChevronLeft from '@mui/icons-material/ChevronLeft';
import ChevronRight from '@mui/icons-material/ChevronRight';
import LogoFull from '../../assets/images/logo.svg?react';
import LogoSmall from '../../assets/images/system_monitor_icon.svg?react';
const SidebarMenu = ({
data,
@ -37,385 +22,107 @@ const SidebarMenu = ({
setIsDarkMode,
onSelectItem,
forceRefreshMenu,
user,
user
}) => {
const [collapsed, setCollapsed] = useState(false);
const { sidebarWidth, startResizing } = useSidebarResize(320); // Увеличил минимальную ширину
const [menuItems, setMenuItems] = useState(data.items || []);
const [activeItem, setActiveItem] = useState(null);
const [hoveredItem, setHoveredItem] = useState(null);
const [dropIndicator, setDropIndicator] = useState({ show: false, position: null, targetId: null });
const sensors = useSensors(useSensor(PointerSensor, {
activationConstraint: {
distance: 4,
},
}));
useEffect(() => {
const cached = localStorage.getItem("menuTree");
if (cached) {
try {
setMenuItems(JSON.parse(cached));
} catch {
setMenuItems(data.items || []);
}
} else {
setMenuItems(data.items || []);
}
}, [data]);
const { sidebarWidth, startResizing } = useSidebarResize(290);
const [hovered, setHovered] = useState(false);
const handleToggleCollapse = () => {
setCollapsed(!collapsed);
setHoveredItem(null);
};
// Функции для работы с деревом (остаются без изменений)
const findItemInTree = (items, id) => {
for (const item of items) {
if (item.id === id) return item;
if (item.items) {
const found = findItemInTree(item.items, id);
if (found) return found;
}
}
return null;
};
const removeItemFromTree = (items, id) => {
return items.filter(item => {
if (item.id === id) return false;
if (item.items) {
item.items = removeItemFromTree(item.items, id);
}
return true;
});
};
const addItemToFolder = (items, folderId, newItem) => {
return items.map(item => {
if (item.id === folderId) {
return {
...item,
items: [...(item.items || []), newItem]
};
}
if (item.items) {
return {
...item,
items: addItemToFolder(item.items, folderId, newItem)
};
}
return item;
});
};
const findParent = (items, childId, parent = null) => {
for (const item of items) {
if (item.id === childId) return parent;
if (item.items) {
const found = findParent(item.items, childId, item);
if (found) return found;
}
}
return null;
};
const addItemAtSameLevel = (items, parentId, newItem, afterId = null) => {
return items.map(item => {
if (item.id === parentId) {
const children = item.items || [];
const insertIndex = afterId ? children.findIndex(i => i.id === afterId) + 1 : children.length;
const newChildren = [
...children.slice(0, insertIndex),
newItem,
...children.slice(insertIndex)
];
return { ...item, items: newChildren };
}
if (item.items) {
return { ...item, items: addItemAtSameLevel(item.items, parentId, newItem, afterId) };
}
return item;
});
};
const handleDragStart = (event) => {
const { active } = event;
const item = findItemInTree(menuItems, active.id);
setActiveItem(item);
setDropIndicator({ show: false, position: null, targetId: null });
};
const handleDragEnd = (event) => {
const { active, over } = event;
setActiveItem(null);
setHoveredItem(null);
setDropIndicator({ show: false, position: null, targetId: null });
if (!over) return;
if (active.id === over.id) return;
const draggedItem = findItemInTree(menuItems, active.id);
if (!draggedItem) return;
const overItem = findItemInTree(menuItems, over.id);
// Проверяем, не пытаемся ли переместить элемент в его же потомка
if (isDescendant(draggedItem, overItem)) {
return;
}
let newTree;
if (dropIndicator.position === 'inside' && overItem && Array.isArray(overItem.items)) {
// Вставка внутрь папки
newTree = removeItemFromTree([...menuItems], active.id);
newTree = addItemToFolder(newTree, over.id, draggedItem);
} else {
// Вставка на том же уровне
const overParent = findParent(menuItems, over.id);
if (!overParent) return;
newTree = removeItemFromTree([...menuItems], active.id);
// Определяем позицию для вставки
let insertAfterId = null;
if (dropIndicator.position === 'below') {
insertAfterId = over.id;
} else if (dropIndicator.position === 'above') {
const siblings = overParent.items || [];
const overIndex = siblings.findIndex(item => item.id === over.id);
if (overIndex > 0) {
insertAfterId = siblings[overIndex - 1].id;
}
}
newTree = addItemAtSameLevel(newTree, overParent.id, draggedItem, insertAfterId);
}
setMenuItems(newTree);
localStorage.setItem("menuTree", JSON.stringify(newTree));
};
const handleDragOver = (event) => {
const { active, over } = event;
if (!over) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
const overItem = findItemInTree(menuItems, over.id);
const activeItem = findItemInTree(menuItems, active.id);
if (!overItem || !activeItem || active.id === over.id) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
// Проверяем, можно ли перемещать элемент
if (isDescendant(activeItem, overItem)) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
const overRect = over.rect.current;
if (!overRect) return;
const relativeY = event.delta.y;
const isOverFolder = overItem && Array.isArray(overItem.items);
const isTopHalf = relativeY < overRect.height * 0.4;
const isBottomHalf = relativeY > overRect.height * 0.6;
if (isOverFolder && !isTopHalf && !isBottomHalf) {
// Показываем индикатор для вставки в папку
setDropIndicator({
show: true,
position: 'inside',
targetId: over.id
});
setHoveredItem(over.id);
} else if (isTopHalf) {
// Показываем индикатор для вставки выше
setDropIndicator({
show: true,
position: 'above',
targetId: over.id
});
setHoveredItem(null);
} else if (isBottomHalf) {
// Показываем индикатор для вставки ниже
setDropIndicator({
show: true,
position: 'below',
targetId: over.id
});
setHoveredItem(null);
} else {
setDropIndicator({ show: false, position: null, targetId: null });
setHoveredItem(null);
}
};
const isDescendant = (parent, child) => {
if (!parent || !child || !parent.items) return false;
const checkChildren = (items, targetId) => {
for (const item of items) {
if (item.id === targetId) return true;
if (item.items && checkChildren(item.items, targetId)) return true;
}
return false;
};
return checkChildren(parent.items, child.id);
};
const SidebarResizer = styled("div")(({ theme }) => ({
width: "3px",
cursor: "col-resize",
backgroundColor: alpha(theme.palette.primary.main, 0.3),
"&:hover": {
backgroundColor: theme.palette.primary.main,
const SidebarResizer = styled('div')(({ theme }) => ({
width: '4px',
cursor: 'ew-resize',
backgroundColor: 'transparent',
'&:hover': {
backgroundColor: theme.palette.action.hover,
},
height: "100%",
position: "absolute",
height: '100%',
position: 'absolute',
top: 0,
right: 0,
zIndex: 1000,
transition: "background-color 0.2s ease",
}));
const DropIndicator = ({ position, targetId }) => {
if (!targetId) return null;
return (
<Box
sx={{
position: 'absolute',
left: 0,
right: 0,
height: '2px',
backgroundColor: 'primary.main',
zIndex: 1001,
...(position === 'above' && { top: 0 }),
...(position === 'below' && { bottom: 0 }),
'&::before': {
content: '""',
position: 'absolute',
top: '-3px',
left: '10%',
width: '80%',
height: '8px',
backgroundColor: 'primary.main',
borderRadius: '2px',
}
}}
/>
);
};
return (
<Box
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
sx={{
position: "relative",
width: collapsed ? 72 : sidebarWidth,
transition: "width 0.2s ease",
height: "100vh",
position: 'relative',
width: collapsed ? 64 : sidebarWidth,
transition: 'width 0.3s ease',
}}
>
<Drawer
variant="permanent"
sx={{
width: collapsed ? 72 : sidebarWidth,
width: collapsed ? 64 : sidebarWidth,
flexShrink: 0,
"& .MuiDrawer-paper": {
width: collapsed ? 72 : sidebarWidth,
'& .MuiDrawer-paper': {
width: collapsed ? 64 : sidebarWidth,
boxSizing: "border-box",
display: "flex",
flexDirection: "column",
backgroundColor: "background.paper",
color: "text.primary",
transition: "width 0.2s ease, background-color 0.2s ease",
overflowX: "hidden",
borderRight: "1px solid",
borderColor: "divider",
boxShadow: "0 2px 12px rgba(0, 0, 0, 0.08)",
backgroundColor: 'custom.sidebar',
color: 'custom.sidebarText',
transition: 'width 0.3s ease',
overflowX: 'hidden',
borderRight: 'none'
},
}}
>
{/* Заголовок с логотипом */}
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
borderBottom: "1px solid",
borderColor: "divider",
backgroundColor: "background.paper",
height: 80,
position: "relative",
transition: "all 0.2s ease",
minHeight: 80,
}}
>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "100%",
height: "100%",
transition: "all 0.2s ease",
"& svg": {
width: "auto",
height: "40px", // Фиксированная высота для лого
objectFit: "contain",
transition: "all 0.2s ease",
},
}}
>
<Box sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center', // Центрируем содержимое
p: 1,
borderBottom: '1px solid',
borderColor: 'divider',
backgroundColor: 'custom.sidebar',
height: 80, // Фиксированная высота
position: 'relative' // Для позиционирования кнопки
}}>
{/* Логотип (занимает все пространство) */}
<Box sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: '100%',
'& svg': {
width: '100%',
height: '100%',
padding: collapsed ? '8px' : '12px',
objectFit: 'contain'
}
}}>
{collapsed ? (
<LogoSmall style={{
color: "inherit",
filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.1))",
width: "32px",
height: "32px"
color: 'inherit' // Наследует цвет темы
}} />
) : (
<LogoFull style={{
color: "inherit",
filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.1))",
maxWidth: "180px",
height: "40px"
color: 'inherit' // Наследует цвет темы
}} />
)}
</Box>
<Tooltip
title={collapsed ? "Развернуть меню" : "Свернуть меню"}
placement="right"
>
{/* Кнопка сворачивания (абсолютное позиционирование) */}
<Tooltip title={collapsed ? "Развернуть меню" : "Свернуть меню"}>
<IconButton
onClick={handleToggleCollapse}
size="small"
sx={{
color: "text.secondary",
"&:hover": {
backgroundColor: "action.hover",
color: "text.primary"
},
position: "absolute",
right: 12,
top: "50%",
transform: "translateY(-50%)",
transition: "all 0.2s ease",
width: 32,
height: 32,
color: 'custom.sidebarText',
'&:hover': { backgroundColor: 'custom.sidebarHover' },
position: 'absolute',
right: 8,
top: '50%',
transform: 'translateY(-50%)'
}}
>
{collapsed ? <ChevronRight /> : <ChevronLeft />}
@ -424,97 +131,18 @@ const SidebarMenu = ({
</Box>
{/* Основное содержимое меню */}
<Box
sx={{
flexGrow: 1,
display: "flex",
flexDirection: "column",
overflow: "hidden",
position: "relative",
}}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragOver={handleDragOver}
measuring={{
droppable: {
strategy: MeasuringStrategy.Always
}
}}
>
<SortableContext items={menuItems.map((i) => i.id)} strategy={verticalListSortingStrategy}>
<List
sx={{
overflowY: "auto",
flex: "1 1 auto",
py: 1,
px: 1,
position: 'relative',
'&::-webkit-scrollbar': {
width: '6px',
},
'&::-webkit-scrollbar-track': {
background: 'transparent',
},
'&::-webkit-scrollbar-thumb': {
background: 'text.disabled',
borderRadius: '3px',
},
'&::-webkit-scrollbar-thumb:hover': {
background: 'text.secondary',
},
}}
>
{menuItems.map((item) => (
<Box key={item.id} position="relative">
{dropIndicator.show && dropIndicator.targetId === item.id &&
dropIndicator.position !== 'inside' && (
<DropIndicator
position={dropIndicator.position}
targetId={dropIndicator.targetId}
/>
)}
<SortableMenuItem
item={item}
collapsed={collapsed}
onSelectItem={onSelectItem}
isHovered={hoveredItem === item.id}
showDropIndicator={dropIndicator.show && dropIndicator.targetId === item.id && dropIndicator.position === 'inside'}
sidebarWidth={sidebarWidth}
/>
</Box>
))}
</List>
</SortableContext>
<Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
<List sx={{ overflowY: 'auto', overflowX: 'hidden', flex: '1 1 auto' }}>
{data && (
<MenuItem
item={data}
collapsed={collapsed}
level={0}
<DragOverlay>
{activeItem ? (
<Box
sx={{
backgroundColor: 'primary.main',
color: 'white',
padding: '8px 12px',
borderRadius: '8px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.15)',
maxWidth: 250,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontSize: '0.875rem',
fontWeight: 500,
backdropFilter: 'blur(10px)',
border: '1px solid rgba(255, 255, 255, 0.1)',
transform: 'rotate(5deg)',
}}
>
{activeItem.title}
</Box>
) : null}
</DragOverlay>
</DndContext>
onSelectItem={onSelectItem}
/>
)}
</List>
<SidebarFooter
collapsed={collapsed}
@ -524,11 +152,8 @@ const SidebarMenu = ({
user={user}
/>
</Box>
{!collapsed && (
<Tooltip title="Изменить ширину" placement="top">
<SidebarResizer onMouseDown={startResizing} />
</Tooltip>
<SidebarResizer onMouseDown={startResizing} />
)}
</Drawer>
</Box>

View File

@ -1,121 +1,121 @@
// // MenuItem.jsx
// import React, { useState } from "react";
// import {
// ListItem,
// ListItemIcon,
// ListItemText,
// Collapse,
// List,
// styled,
// Menu,
// MenuItem as MuiMenuItem
// } from "@mui/material";
// import { ExpandLess, ExpandMore, Folder, FolderOpen } from "@mui/icons-material";
// import StatusIndicator from "./StatusIndicator";
// MenuItem.jsx
import React, { useState } from "react";
import {
ListItem,
ListItemIcon,
ListItemText,
Collapse,
List,
styled,
Menu,
MenuItem as MuiMenuItem
} from "@mui/material";
import { ExpandLess, ExpandMore, Folder, FolderOpen } from "@mui/icons-material";
import StatusIndicator from "./StatusIndicator";
// const StyledListItem = styled(ListItem)(({ theme, level }) => ({
// cursor: "pointer",
// paddingLeft: theme.spacing(2 + level * 2),
// position: 'relative',
// '&:hover': {
// backgroundColor: theme.palette.action.hover,
// },
// '&.Mui-selected': {
// backgroundColor: theme.palette.custom.sidebarHover,
// },
// }));
const StyledListItem = styled(ListItem)(({ theme, level }) => ({
cursor: "pointer",
paddingLeft: theme.spacing(2 + level * 2),
position: 'relative',
'&:hover': {
backgroundColor: theme.palette.action.hover,
},
'&.Mui-selected': {
backgroundColor: theme.palette.custom.sidebarHover,
},
}));
// const MenuItem = ({ item, onSelectItem, level = 0, collapsed, onEdit }) => {
// const [isOpen, setIsOpen] = useState(false);
// const [contextMenu, setContextMenu] = useState(null);
// const hasChildren = Array.isArray(item.items) && item.items.length > 0;
const MenuItem = ({ item, onSelectItem, level = 0, collapsed, onEdit }) => {
const [isOpen, setIsOpen] = useState(false);
const [contextMenu, setContextMenu] = useState(null);
const hasChildren = Array.isArray(item.items) && item.items.length > 0;
// const handleContextMenu = (e) => {
// e.preventDefault();
// setContextMenu(
// contextMenu === null
// ? { mouseX: e.clientX - 2, mouseY: e.clientY - 4 }
// : null
// );
// };
const handleContextMenu = (e) => {
e.preventDefault();
setContextMenu(
contextMenu === null
? { mouseX: e.clientX - 2, mouseY: e.clientY - 4 }
: null
);
};
// const handleCloseContextMenu = () => {
// setContextMenu(null);
// };
const handleCloseContextMenu = () => {
setContextMenu(null);
};
// const handleToggle = (e) => {
// e.stopPropagation();
// setIsOpen(!isOpen);
// };
const handleToggle = (e) => {
e.stopPropagation();
setIsOpen(!isOpen);
};
// const handleClick = () => {
// if (onSelectItem) {
// onSelectItem(item);
// }
// };
const handleClick = () => {
if (onSelectItem) {
onSelectItem(item);
}
};
// return (
// <>
// <StyledListItem
// component="div"
// onClick={hasChildren ? handleToggle : handleClick}
// onContextMenu={handleContextMenu}
// level={level}
// sx={{
// pl: collapsed ? 2 : 2 + level * 2,
// justifyContent: collapsed ? 'center' : 'flex-start',
// }}
// >
// {!collapsed && <StatusIndicator status={item.status} />}
return (
<>
<StyledListItem
component="div"
onClick={hasChildren ? handleToggle : handleClick}
onContextMenu={handleContextMenu}
level={level}
sx={{
pl: collapsed ? 2 : 2 + level * 2,
justifyContent: collapsed ? 'center' : 'flex-start',
}}
>
{!collapsed && <StatusIndicator status={item.status} />}
// <ListItemIcon sx={{ minWidth: collapsed ? 'auto' : 56 }}>
// {hasChildren ? (isOpen ? <FolderOpen /> : <Folder />) : <Folder />}
// </ListItemIcon>
<ListItemIcon sx={{ minWidth: collapsed ? 'auto' : 56 }}>
{hasChildren ? (isOpen ? <FolderOpen /> : <Folder />) : <Folder />}
</ListItemIcon>
// {!collapsed && (
// <>
// <ListItemText
// primary={item.title}
// primaryTypographyProps={{
// color: 'custom.sidebarText'
// }}
// />
// {hasChildren && (isOpen ? <ExpandLess /> : <ExpandMore />)}
// </>
// )}
// </StyledListItem>
{!collapsed && (
<>
<ListItemText
primary={item.title}
primaryTypographyProps={{
color: 'custom.sidebarText'
}}
/>
{hasChildren && (isOpen ? <ExpandLess /> : <ExpandMore />)}
</>
)}
</StyledListItem>
// <Menu
// open={contextMenu !== null}
// onClose={handleCloseContextMenu}
// anchorReference="anchorPosition"
// anchorPosition={
// contextMenu !== null
// ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
// : undefined
// }
// >
<Menu
open={contextMenu !== null}
onClose={handleCloseContextMenu}
anchorReference="anchorPosition"
anchorPosition={
contextMenu !== null
? { top: contextMenu.mouseY, left: contextMenu.mouseX }
: undefined
}
>
// </Menu>
</Menu>
// {hasChildren && !collapsed && (
// <Collapse in={isOpen} timeout="auto" unmountOnExit>
// <List component="div" disablePadding>
// {item.items.map((child, index) => (
// <MenuItem
// key={child.id ?? index}
// item={child}
// onSelectItem={onSelectItem}
// onEdit={onEdit}
// level={level + 1}
// collapsed={collapsed}
// />
// ))}
// </List>
// </Collapse>
// )}
// </>
// );
// };
{hasChildren && !collapsed && (
<Collapse in={isOpen} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{item.items.map((child, index) => (
<MenuItem
key={child.id ?? index}
item={child}
onSelectItem={onSelectItem}
onEdit={onEdit}
level={level + 1}
collapsed={collapsed}
/>
))}
</List>
</Collapse>
)}
</>
);
};
// export default MenuItem;
export default MenuItem;

View File

@ -1,24 +1,20 @@
import React, { useState } from "react";
import { Brightness4, Brightness7, Settings, Help } from "@mui/icons-material";
import {
IconButton,
Tooltip,
Box,
Button,
alpha
} from "@mui/material";
import { Brightness4, Brightness7 } from "@mui/icons-material";
import { IconButton, Tooltip } from "@mui/material";
import {
List,
ListItem,
ListItemText,
styled,
Switch,
Box,
Button
} from "@mui/material";
import SettingsModal from "../SettingsModal";
import { RoleBasedRender } from "../../UI/RoleBasedRender";
const FooterList = styled(List)(({ theme }) => ({
backgroundColor: 'background.paper',
backgroundColor: theme.palette.custom.sidebar,
padding: theme.spacing(1, 0),
borderTop: `1px solid ${theme.palette.divider}`,
marginTop: 'auto'
@ -26,15 +22,12 @@ const FooterList = styled(List)(({ theme }) => ({
const FooterListItem = styled(ListItem)(({ theme }) => ({
'&:hover': {
backgroundColor: alpha(theme.palette.action.hover, 0.4),
backgroundColor: theme.palette.custom.sidebarHover,
},
padding: theme.spacing(1, 2),
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
borderRadius: '8px',
margin: '0 8px 4px',
transition: 'all 0.2s ease',
alignItems: 'center'
}));
const SidebarFooter = ({
@ -53,93 +46,72 @@ const SidebarFooter = ({
const handleSettingsClose = () => {
setSettingsOpen(false);
};
/*console.log('SidebarFooter user with role:', {
...user,
hasRole: 'role' in user,
roleValue: user?.role
}); */
return (
<>
<FooterList>
{!collapsed ? (
<>
<FooterListItem>
<Button
onClick={handleSettingsOpen}
startIcon={<Settings />}
sx={{
color: 'text.secondary',
textTransform: 'none',
fontSize: '0.875rem',
fontWeight: 500,
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
}
}}
>
Настройки
</Button>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Tooltip title="Переключить тему">
<IconButton
size="small"
onClick={() => setIsDarkMode(!isDarkMode)}
sx={{
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: alpha('#000000', 0.1)
}
}}
>
{isDarkMode ? <Brightness4 /> : <Brightness7 />}
</IconButton>
</Tooltip>
<Switch
checked={isDarkMode}
onChange={() => setIsDarkMode(!isDarkMode)}
size="small"
color="primary"
/>
</Box>
</FooterListItem>
<FooterListItem button>
<Button
startIcon={<Help />}
sx={{
color: 'text.secondary',
textTransform: 'none',
fontSize: '0.875rem',
fontWeight: 500,
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
}
}}
>
Помощь
</Button>
</FooterListItem>
</>
) : (
<FooterListItem sx={{ justifyContent: 'center' }}>
<Tooltip title="Настройки" placement="right">
<IconButton
onClick={handleSettingsOpen}
sx={{
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: alpha('#000000', 0.1)
}
}}
>
<Settings />
</IconButton>
</Tooltip>
{!collapsed && (
<FooterListItem button>
<ListItemText
primary="Помощь"
primaryTypographyProps={{
color: 'custom.sidebarText',
variant: 'body2'
}}
/>
</FooterListItem>
)}
<FooterListItem>
{/* кнопка настроек */}
<RoleBasedRender user={user} allowedRoles={['admin']}>
{!collapsed && (
<Button
onClick={handleSettingsOpen}
sx={{
color: 'custom.sidebarText',
textTransform: 'none',
minWidth: 0,
padding: 0,
marginRight: 'auto'
}}
>
<ListItemText
primary="Настройки"
primaryTypographyProps={{
color: 'custom.sidebarText',
variant: 'body2'
}}
/>
</Button>
)}
</RoleBasedRender>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Tooltip title="Переключить тему">
<IconButton
size="small"
onClick={() => setIsDarkMode(!isDarkMode)}
sx={{ color: 'custom.sidebarText' }}
>
{isDarkMode ? <Brightness4 /> : <Brightness7 />}
</IconButton>
</Tooltip>
{!collapsed && (
<Switch
checked={isDarkMode}
onChange={() => setIsDarkMode(!isDarkMode)}
size="small"
/>
)}
</Box>
</FooterListItem>
</FooterList>
{/* Используем RoleBasedRender для модального окна */}
<RoleBasedRender user={user} allowedRoles={['admin']}>
<SettingsModal
open={settingsOpen}

View File

@ -1,222 +0,0 @@
import { useState } from "react";
import {
ListItem,
ListItemIcon,
ListItemText,
Collapse,
List,
IconButton,
Box,
alpha,
Typography,
Tooltip
} from "@mui/material";
import { ChevronRight, DragIndicator, Folder, FolderOpen } from "@mui/icons-material";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
const SortableMenuItem = ({
item,
collapsed,
onSelectItem,
level = 0,
isHovered = false,
showDropIndicator = false,
sidebarWidth = 300
}) => {
const [isOpen, setIsOpen] = useState(false);
const [isLocalHovered, setIsLocalHovered] = useState(false);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
isOver
} = useSortable({
id: item.id,
data: {
type: 'menu-item',
item,
level
}
});
const style = {
transform: CSS.Transform.toString(transform),
transition: transition || 'all 0.2s ease',
opacity: isDragging ? 0.6 : 1,
zIndex: isDragging ? 1000 : 1,
};
const hasChildren = Array.isArray(item.items) && item.items.length > 0;
const isFolder = hasChildren;
const isHighlighted = isHovered || isOver;
// Рассчитываем максимальную ширину текста в зависимости от уровня вложенности
const calculateMaxTextWidth = () => {
const baseWidth = sidebarWidth - 40; // Отступы и иконки
const levelOffset = level * 24; // Отступ для каждого уровня
return baseWidth - levelOffset - 60; // Оставляем место для иконок и отступов
};
const handleClick = (e) => {
e.stopPropagation();
if (hasChildren) {
setIsOpen(!isOpen);
} else {
onSelectItem?.(item);
}
};
const handleMouseEnter = () => {
setIsLocalHovered(true);
};
const handleMouseLeave = () => {
setIsLocalHovered(false);
};
const getBackgroundColor = (theme) => {
if (isDragging) return alpha(theme.palette.primary.main, 0.1);
if (isHighlighted) return alpha(theme.palette.primary.main, 0.08);
if (isLocalHovered) return alpha(theme.palette.action.hover, 0.4);
return 'transparent';
};
return (
<Box
ref={setNodeRef}
style={style}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
sx={{
position: 'relative',
'&::before': isHighlighted ? {
content: '""',
position: 'absolute',
left: 0,
top: 4,
bottom: 4,
width: 3,
backgroundColor: 'primary.main',
borderRadius: '0 2px 2px 0',
} : {},
...(showDropIndicator && {
backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.1),
border: (theme) => `2px dashed ${theme.palette.primary.main}`,
borderRadius: '8px',
})
}}
>
<ListItem
button
sx={{
pl: collapsed ? 1 : Math.max(0.1, 0.1 + level * 0.1),
pr: 0.5,
py: 0.25,
minHeight: 32,
justifyContent: collapsed ? "center" : "flex-start",
backgroundColor: (theme) => getBackgroundColor(theme),
borderRadius: '6px',
margin: '1px 4px',
transition: 'all 0.2s ease',
}}
onClick={handleClick}
>
{!collapsed && (
<IconButton
{...attributes}
{...listeners}
size="small"
sx={{
cursor: isDragging ? "grabbing" : "grab",
mr: 1,
opacity: isLocalHovered || isDragging ? 1 : 0.4,
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
},
flexShrink: 0
}}
>
<DragIndicator fontSize="small" />
</IconButton>
)}
{!collapsed && (
<>
<Tooltip title={item.title} placement="right" enterDelay={400} arrow>
<ListItemText
primary={
<Typography
variant="body2"
sx={{
fontWeight: isFolder ? 600 : 400,
color: isFolder ? 'text.primary' : 'text.secondary',
maxWidth: calculateMaxTextWidth(),
display: "-webkit-box",
WebkitLineClamp: 2, // максимум 2 строки
WebkitBoxOrient: "vertical",
overflow: "hidden",
lineHeight: 1.2,
fontSize: "0.85rem", // компактнее текст
}}
>
{item.title}
</Typography>
}
sx={{ mr: 0.5, flex: '1 1 auto', minWidth: 0 }}
/>
</Tooltip>
{hasChildren && (
<ChevronRight
sx={{
fontSize: 18,
color: 'text.disabled',
transform: isOpen ? 'rotate(90deg)' : 'none',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
/>
)}
</>
)}
</ListItem>
{hasChildren && !collapsed && (
<Collapse in={isOpen} timeout="auto" unmountOnExit>
<List
disablePadding
sx={{
pl: 1.5,
borderLeft: (theme) => `1px solid ${alpha(theme.palette.divider, 0.1)}`,
marginLeft: 2,
position: 'relative',
}}
>
{item.items.map((child) => (
<Box key={child.id} position="relative">
<SortableMenuItem
item={child}
collapsed={collapsed}
onSelectItem={onSelectItem}
level={level + 1}
isHovered={isHovered}
showDropIndicator={showDropIndicator}
sidebarWidth={sidebarWidth}
/>
</Box>
))}
</List>
</Collapse>
)}
</Box>
);
};
export default SortableMenuItem;

View File

@ -14,12 +14,13 @@ export default defineConfig({
rewrite: (path) => path.replace(/^\/ai-api/, ''),
},
'/metrics-ws': {
target: 'ws://192.168.2.39:3001',
target: 'ws://localhost:3001',
ws: true,
changeOrigin: true,
},
'/api': {
target: 'http://192.168.2.39:3000',
target: 'http://localhost:3000',
ws: true,
changeOrigin: true,
bypass(req, res, options) {
console.log('Proxying request:', req.url);