sozday-programmu-dlya-analiz/app.js

246 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var TYPE_NAMES = { conflict: "Драка", aggression: "Агрессия", smoking: "Курение" };
var TYPE_LEVELS = { conflict: "high", aggression: "medium", smoking: "medium" };
var LEVEL_NAMES = { high: "Критично", medium: "Внимание" };
var STATUS_NAMES = { new: "Новый", ok: "Подтверждён", dismissed: "Отклонён" };
var CAMS = [];
var INC = [];
var curType = "conflict";
var curTab = "cams";
function esc(s) {
return String(s == null ? "" : s)
.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function pad(n) { return String(n).length < 2 ? "0" + n : String(n); }
function fmtDate(iso) {
var d = new Date(iso);
return pad(d.getDate()) + "." + pad(d.getMonth() + 1) + "." + d.getFullYear();
}
function fmtTime(iso) {
var d = new Date(iso);
return pad(d.getHours()) + ":" + pad(d.getMinutes());
}
function statusPill(st) {
var map = { new: "risk", ok: "ok", dismissed: "info" };
return '<span class="kt-ai-status-pill" data-status="' + (map[st] || "risk") + '">' + (STATUS_NAMES[st] || st) + "</span>";
}
function levelPill(level) {
var st = level === "high" ? "risk" : "warn";
return '<span class="kt-ai-status-pill" data-status="' + st + '">' + (LEVEL_NAMES[level] || level) + "</span>";
}
function camName(id) {
var c = CAMS.find(function (x) { return x.id === id; });
return c ? c.name : id;
}
async function api(path, data) {
var opts = data ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) } : {};
var r = await fetch("api/" + path, opts);
return r.json();
}
function lastEvent(cam) { return cam.events && cam.events.length ? cam.events[cam.events.length - 1] : null; }
function renderCams() {
var grid = document.getElementById("camGrid");
if (!grid) return;
grid.innerHTML = CAMS.map(function (c) {
var last = lastEvent(c);
return "<article class='camera' data-cam='" + c.id + "'>" +
"<div class='cam-top'><span class='dot" + (last ? " crit" : " ok") + "'></span>" + esc(c.name) +
"<span class='cam-time'>" + (last ? fmtTime(last.at) : "сейчас") + "</span></div>" +
"<div class='cam-view'><canvas id='cv-" + c.id + "' width='300' height='170'></canvas>" +
(last ? "<div class='cam-alert'><svg class='kt-icon'><use href='#warning'></use></svg>" + esc(TYPE_NAMES[last.type] || last.type) + "</div>" : "") +
"</div></article>";
}).join("");
}
function drawCam(cam, hasAlert) {
var cv = document.getElementById("cv-" + cam.id);
if (!cv) return;
var w = cv.width, h = cv.height;
var ctx = cv.getContext("2d");
var t = Date.now() / 1000;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgba(12,10,9,0.05)";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "rgba(12,10,9,0.1)";
ctx.lineWidth = 1;
for (var i = 0; i < 4; i++) {
var yy = ((cam.id.charCodeAt(1) * (i + 3) * 17) % h) + Math.sin(t * 1.3 + i) * 3;
ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(w, yy); ctx.stroke();
}
ctx.fillStyle = "rgba(12,10,9,0.14)";
for (var j = 0; j < 6; j++) {
var xx = ((cam.id.charCodeAt(3) * 31 * (j + 1)) % w) + Math.cos(t * 0.9 + j) * 10;
ctx.fillRect(xx, 4, 1.5, h - 8);
}
if (hasAlert) {
var bx = w / 2 + Math.cos(t * 1.6) * 40;
var by = h / 2 + Math.sin(t * 1.2) * 18;
ctx.strokeStyle = "rgba(220,38,38,0.65)";
ctx.lineWidth = 2;
ctx.strokeRect(bx - 34, by - 26, 68, 52);
ctx.lineWidth = 1;
}
ctx.font = "10px monospace";
ctx.fillStyle = "rgba(12,10,9,0.4)";
ctx.fillText(cam.id.toUpperCase() + " · LIVE " + pad(new Date().getDate()) + "-" + pad(new Date().getMonth() + 1), 8, 14);
}
function renderKpiCams() {
var el = document.getElementById("kpiCams");
if (!el) return;
var alerts = CAMS.filter(function (c) { return lastEvent(c); }).length;
el.innerHTML =
"<div class='k'><b>" + CAMS.length + "</b>камер в сети</div>" +
"<div class='k'><b>" + alerts + "</b>камер с активными тревогами</div>" +
"<div class='k'><b>" + esc(TYPE_NAMES[curType]) + "</b>активный сценарий</div>";
}
function renderIncidents(list) {
var wrap = document.getElementById("incContent");
if (!wrap) return;
var s = document.getElementById("incSearch"), ft = document.getElementById("incFType"), fs_ = document.getElementById("incFStatus");
var q = (s && s.value ? s.value : "").toLowerCase();
var ty = ft ? ft.value : "all";
var st = fs_ ? fs_.value : "all";
var rows = (list || []).filter(function (i) {
if (st !== "all" && i.status !== st) return false;
if (ty !== "all" && i.type !== ty) return false;
if (q && (i.id + " " + camName(i.camId)).toLowerCase().indexOf(q) < 0) return false;
return true;
});
if (!rows.length) {
wrap.innerHTML = "<div class='kt-ai-empty' style='padding:24px'><div class='icon-spot'><svg class='kt-icon kt-icon-lg'><use href='#table'></use></svg></div><div class='title'>Ничего не найдено</div><div>Измените фильтры или дождитесь новой тревоги.</div></div>";
} else {
var body = rows.map(function (i) {
var act = "";
if (i.status !== "ok") act = "<button class='kt-ai-btn' data-variant='ghost' data-size='sm' onclick='setStatus(\"" + i.id + "\",\"ok\")'>Подтвердить</button>";
if (i.status !== "dismissed") act += (act ? " " : "") + "<button class='kt-ai-btn' data-variant='ghost' data-size='sm' onclick='setStatus(\"" + i.id + "\",\"dismissed\")'>Отклонить</button>";
return "<tr><td>" + esc(i.id) + "</td><td>" + esc(camName(i.camId)) + "</td><td>" + esc(TYPE_NAMES[i.type] || i.type) + "</td>" +
"<td>" + levelPill(i.level) + "</td><td>" + fmtDate(i.at) + " " + fmtTime(i.at) + "</td><td>" + statusPill(i.status) + "</td>" +
"<td class='row-actions'>" + act + "</td></tr>";
}).join("");
wrap.innerHTML = "<table class='kt-ai-table'><thead><tr>" +
"<th>ID</th><th>Камера</th><th>Событие</th><th>Уровень</th><th>Дата</th><th>Статус</th><th></th>" +
"</tr></thead><tbody>" + body + "</tbody></table>";
}
renderKpiInc();
}
function renderKpiInc() {
var el = document.getElementById("kpiInc");
if (!el) return;
var all = INC || [];
var nNew = all.filter(function (i) { return i.status === "new"; }).length;
var nOk = all.filter(function (i) { return i.status === "ok"; }).length;
var nDis = all.filter(function (i) { return i.status === "dismissed"; }).length;
el.innerHTML =
"<div class='kt-ai-kpi'><div class='value'>" + all.length + "</div><div class='label'>Всего инцидентов</div></div>" +
"<div class='kt-ai-kpi'><div class='value'>" + nNew + "</div><div class='label'>Новых</div></div>" +
"<div class='kt-ai-kpi'><div class='value'>" + nOk + "</div><div class='label'>Подтверждено</div></div>" +
"<div class='kt-ai-kpi'><div class='value'>" + nDis + "</div><div class='label'>Отклонено</div></div>";
}
function switchTab(tab) {
curTab = tab;
var camT = document.getElementById("camTab"), incT = document.getElementById("incTab"), pt = document.getElementById("pageTitle");
if (camT) camT.hidden = tab !== "cams";
if (incT) incT.hidden = tab !== "inc";
if (pt) pt.textContent = tab === "cams" ? "Камеры" : "Журнал инцидентов";
var items = document.querySelectorAll(".kt-ai-nav-item[data-tab]");
items.forEach(function (n) {
n.classList.toggle("is-active", n.getAttribute("data-tab") === tab);
});
if (tab === "inc" && !INC.length) loadIncidents();
}
function setType(t) {
curType = t;
var segs = document.querySelectorAll(".seg[data-type]");
segs.forEach(function (b) { b.classList.toggle("is-active", b.getAttribute("data-type") === t); });
renderKpiCams();
}
async function loadCams() {
CAMS = await api("cams");
renderCams();
renderKpiCams();
}
async function loadIncidents() {
INC = await api("incidents");
renderIncidents(INC);
}
function setStatus(id, status) {
api("incidents/status", { id: id, status: status }).then(loadIncidents);
}
function doExport() {
if (!INC.length) { alert("Пока нет инцидентов для выгрузки"); return; }
var head = ["ID", "Камера", "Событие", "Уровень", "Дата", "Статус"];
var body = INC.map(function (i) {
return [i.id, camName(i.camId), TYPE_NAMES[i.type] || i.type, LEVEL_NAMES[i.level] || i.level, fmtDate(i.at) + " " + fmtTime(i.at), STATUS_NAMES[i.status] || i.status];
});
var csv = "\uFEFF" + [head].concat(body).map(function (r) {
return r.map(function (v) { return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"'; }).join(";");
}).join("\n");
var a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8" }));
a.download = "visionguard-incidenty.csv";
a.click();
}
function toast(msg, tone) {
var stack = document.querySelector(".kt-ai-toast-stack");
if (!stack) { stack = document.createElement("div"); stack.className = "kt-ai-toast-stack"; document.body.appendChild(stack); }
var t = document.createElement("div");
t.className = "kt-ai-toast";
t.setAttribute("data-tone", tone || "risk");
t.innerHTML = msg;
stack.appendChild(t);
setTimeout(function () { t.remove(); }, 4500);
}
function simOnce() {
if (!CAMS.length) return;
var cam = CAMS[Math.floor(Math.random() * CAMS.length)];
api("incidents", { camId: cam.id, type: curType }).then(function () {
loadCams();
loadIncidents();
toast("<b>Тревога:</b> " + esc(TYPE_NAMES[curType]) + " · " + esc(cam.name), "risk");
});
}
function onFilter() {
if (INC) renderIncidents(INC);
}
document.addEventListener("DOMContentLoaded", function () {
var items = document.querySelectorAll(".kt-ai-nav-item[data-tab]");
items.forEach(function (n) {
n.addEventListener("click", function (e) {
e.preventDefault();
switchTab(n.getAttribute("data-tab"));
});
});
switchTab("cams");
loadCams().then(function () {
drawCams();
loadIncidents();
});
setInterval(function () {
loadCams();
if (curTab === "inc") loadIncidents();
}, 8000);
});
function drawCams() {
CAMS.forEach(function (c) { drawCam(c, !!lastEvent(c)); });
var next = Date.now() / 1000;
setTimeout(function () {
if (next - Date.now() / 1000 < 30) drawCams();
}, 100);
}