Добавил фронтенд

This commit is contained in:
2024-03-25 11:52:11 +00:00
parent 49034436a6
commit cbafcf1336
14 changed files with 607 additions and 0 deletions
@@ -0,0 +1,59 @@
class GetAnomalyLogs extends ControllerBase {
// Конструктор
constructor(url) {
super("anomaly_logs");
this.last_id = -1;
}
// Отправка запроса на сервер
SendRequest() {
let parameters = {
'last_id': this.last_id
};
super.Get(parameters);
}
// Обработка ответа от сервера
// respone -- ответ сервера
ProcessResponse(response) {
this.UpdateData(response);
}
// Обновление данных
// respone -- ответ от сервера
UpdateData(response) {
let logs = response["result"];
if (logs == null)
return;
let last_id = this.last_id;
for (const item of logs) {
let row = window.anomaly_logs_table.insertRow();
const id = Number(item["id"]);
let cell = row.insertCell(0);
cell.innerHTML = String(id);
cell = row.insertCell(1);
cell.innerHTML = item["data"];
cell = row.insertCell(2);
const cluster_id = Number(item["cluster_id"]);
cell.innerHTML = window.get_logs_clusters.clusters[cluster_id]["name"];
DecorateClusterCell(id, cluster_id, cell);
if (id > last_id)
last_id = id;
}
this.last_id = last_id;
}
}
function UpdateAnomalyLogs() {
window.get_anomaly_logs.SendRequest()
}
+5
View File
@@ -0,0 +1,5 @@
function InitAnomalyLogs() {
window.get_anomaly_logs = new GetAnomalyLogs();
window.update_cluster_id = new UpdateClusterIdInAnomalyLog();
window.anomaly_logs_table = document.getElementById("anomaly-logs-table");
}
@@ -0,0 +1,24 @@
class UpdateClusterIdInAnomalyLog extends ControllerBase {
// Конструктор
constructor(url) {
super("anomaly_logs/update_cluster_id");
}
// Отправка запроса на сервер
async SendRequest(log_id, cluster_id, cell) {
let parameters = {
'id': Number(log_id),
'cluster_id': Number(cluster_id)
};
await super.Any(parameters, "post");
this.UpdateCell(cluster_id, cell);
}
ProcessResponse(response) {}
UpdateCell(cluster_id, cell) {
cell.innerHTML = window.get_logs_clusters.clusters[cluster_id]["name"];
}
}
+21
View File
@@ -0,0 +1,21 @@
function DecorateClusterCell(log_id, cluster_id, cell) {
if (cluster_id == 0) {
cell.innerHTML = "";
let select_cluster = window.select_cluster.cloneNode(true);
select_cluster.addEventListener("change", async (event) => {
let new_cluster_id = event.target.value;
await window.update_cluster_id.SendRequest(log_id, new_cluster_id, cell);
cell.innerHTML = window.get_logs_clusters.clusters[new_cluster_id]["name"];
});
select_cluster.addEventListener("click", (event) => {
console.log("updating selector");
UpdateClusterSelector(select_cluster);
});
cell.appendChild(select_cluster);
} else {
cell.innerHTML = window.get_logs_clusters.clusters[cluster_id]["name"];
}
}
+52
View File
@@ -0,0 +1,52 @@
class ControllerBase {
ProcessResponse(response) {
alert("Вызов нереализованного метода. Сообщите об этой ошибке разработчикам");
}
constructor(path) {
this.path = path;
}
JsonToUrlParameters(data) {
return new URLSearchParams(data).toString();
}
async Get(parameters) {
let path = this.path + "?" + this.JsonToUrlParameters(parameters);
console.log(`['${path}', 'get'] requesting`);
const response = await fetch(path, {
method: "GET"
});
const response_body = await response.json();
console.log(`['${this.path}', 'get'] response: '${JSON.stringify(response_body)}'`)
this.ProcessResponseImpl(response_body);
}
async Any(request, method) {
request = JSON.stringify(request);
console.log(`['${this.path}', '${method}'] sending: '${request}'`);
const response = await fetch(this.path, {
method: method,
// mode: 'cors',
// headers: { 'Content-Type': 'application/json' },
body: request
});
const response_body = await response.json();
console.log(`['${this.path}', '${method}'] response: '${JSON.stringify(response_body)}'`)
this.ProcessResponseImpl(response_body);
}
async ProcessResponseImpl(response) {
if (response["status"] != "ok") {
alert('Возникла ошибка. Сообщите о ней разработчикам');
} else {
this.ProcessResponse(response);
}
}
}
@@ -0,0 +1,62 @@
class CreateLogsCluster extends ControllerBase {
// Конструктор
constructor() {
super("logs_clusters");
}
// Отправка запроса на сервер
async SendRequest(name, description, recommendation) {
let cluster = {
"id": window.get_logs_clusters.clusters.length,
"name": name,
"description": description,
"recommendation": recommendation
};
await super.Any(cluster, 'post');
let row = window.logs_cluters_table.insertRow();
this.FillClusterRow(row, cluster);
window.get_logs_clusters.clusters.push(cluster);
window.get_logs_clusters.AddCluster(window.select_cluster, cluster);
}
// Обработка ответа от сервера
// respone -- ответ сервера
ProcessResponse(response) {}
FillClusterRow(row, cluster) {
let cell = row.insertCell(0);
cell.innerHTML = String(cluster["id"]);
cell = row.insertCell(1);
cell.innerHTML = cluster["name"];
cell = row.insertCell(2);
cell.innerHTML = cluster["description"];
cell = row.insertCell(3);
cell.innerHTML = cluster["recommendation"];
}
}
async function CreateCluster() {
const name = document.getElementById("cluster-name").value;
if (name.length == 0) {
alert("Название кластера не может быть пустым");
return;
}
const description = document.getElementById("cluster-description").value;
const recommendation = document.getElementById("cluster-recommendation").value;
await window.create_logs_cluster.SendRequest(name, description, recommendation);
}
function UpdateClusterSelector(selector) {
for (let index = selector.options.length; index < window.select_cluster.options.length; index++) {
let option = window.select_cluster.options[index];
selector.add(option.cloneNode(true));
}
}
+61
View File
@@ -0,0 +1,61 @@
class GetLogsClusters extends ControllerBase {
// Конструктор
constructor() {
super("logs_clusters");
this.clusters = null
}
// Отправка запроса на сервер
async SendRequest() {
await super.Get({});
}
// Обработка ответа от сервера
// respone -- ответ сервера
ProcessResponse(response) {
this.clusters = response["result"];
for (const cluster of this.clusters) {
let row = window.logs_cluters_table.insertRow();
let cell = row.insertCell(0);
cell.innerHTML = cluster["id"];
cell = row.insertCell(1);
cell.innerHTML = cluster["name"];
cell = row.insertCell(2);
cell.innerHTML = cluster["description"];
cell = row.insertCell(3);
cell.innerHTML = cluster["recommendation"];
}
// Формирование списка кластеров
let select_cluster = document.createElement("select");
let option = document.createElement("option");
option.text = "Неизвестный кластер. Выберите один из существующих";
select_cluster.add(option);
for (let index of Array.from({length: this.clusters.length - 1}, (_, i) => i + 1)) {
const cluster = this.clusters[index];
this.AddCluster(select_cluster, cluster)
}
window.select_cluster = select_cluster;
}
AddCluster(select_cluster, cluster) {
let option = document.createElement("option");
option.value = cluster["id"];
option.text = cluster["name"];
select_cluster.add(option);
}
}
async function UpdateClusters() {
await window.get_logs_clusters.SendRequest()
}
@@ -0,0 +1,5 @@
function InitLogsClusters() {
window.create_logs_cluster = new CreateLogsCluster();
window.get_logs_clusters = new GetLogsClusters();
window.logs_cluters_table = document.getElementById("logs-clusters-table");
}
+33
View File
@@ -0,0 +1,33 @@
function InitStatisticsChart(labels, colors) {
// Создаём чарт
let chart = new Chart(
document.getElementById("statistics-chart"), {
type: 'pie',
data: {
labels: labels,
datasets: [{
label: "Количество",
data: [0, 0],
backgroundColor: colors
}]
},
options: {
plugins: {
legend: {
display: false
}
}
}
}
);
// Отображаем чарт
chart.update();
return chart;
}
function InitStatistics() {
window.get_statistics = new GetStatistics();
window.total_logs_amount = document.getElementById("total-logs-amount");
}
@@ -0,0 +1,48 @@
class GetStatistics extends ControllerBase {
// Конструктор
constructor(url) {
super("statistics");
this.labels = [ "Аномальные", "Не аномальные" ];
this.colors = [ "#E96479", "#7DB9B6" ];
this.keys = [ "anomaly", "not anomaly" ];
this.total_amount_key = "total";
this.is_dataset_visible = [true, true];
this.chart = InitStatisticsChart(this.labels, this.colors);
this.context = {
keys: [],
datasets: {}
};
}
// Поля
chart;
context;
// Отправка запроса на сервер
SendRequest() {
super.Get({});
}
// Обработка ответа от сервера
// respone -- ответ сервера
ProcessResponse(response) {
this.UpdateChart(response);
}
// Обновление чарта
// respone -- ответ от сервера
UpdateChart(response) {
let statistics = response["result"];
let statistics_data = [ statistics[this.keys[0]], statistics[this.keys[1]] ];
window.total_logs_amount.innerHTML = "Общее количество: " + statistics[this.total_amount_key];
this.chart.data.datasets[0].data = statistics_data;
this.chart.update();
}
}
function UpdateStatistics() {
window.get_statistics.SendRequest()
}
+48
View File
@@ -0,0 +1,48 @@
function InitSummaryChart() {
// Summary чарт
window.summary_chart = new Chart(
document.getElementById('summary-chart'), {
type: 'pie',
data: {
labels: [],
datasets: []
},
options: {
scales: {
x: {
title: {
display: true,
text: "Категория"
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: "Количество"
}
}
}
}
}
);
window.summary_chart.render();
}
// Инициализация документа
document.addEventListener("DOMContentLoaded", async function() {
InitLogsClusters();
await UpdateClusters();
InitAnomalyLogs();
UpdateAnomalyLogs();
InitStatistics();
UpdateStatistics();
let intervalId = setInterval(function() {
UpdateAnomalyLogs();
UpdateStatistics();
}, 2000);
});