4개 관점 병렬 감사 후 각 발견을 반증 시도해 확정. 반증 5건은 문서에 남겼다. 이번 감사의 요지: **구현도 단위테스트도 초록인데 납품 경로에서 동작하지 않는** 결함이 셋 있었다. 전부 같은 모양이다 — 테스트가 기본값이 아닌 설정을 썼거나, 값이 존재해도 되는지 결정하는 상류 허용 목록을 보지 않았다. CRITICAL 4건: R4-1 추락 승격이 기본 설정에서 한 번도 발화하지 않았다. link_s(3.0)를 now 기준으로 쟀는데 넘어짐은 prone_confirm_s(3.0) 지속 후 확정되므로 확정 시점에는 항상 3초 넘게 지나 있다. 다른 테스트가 전부 prone_confirm_s=0.5 를 써서 초록이었다. 착지(prone 시작) 시각과 비교하도록 고치고, 기본값 그대로 도는 회귀 테스트를 넣었다. R4-2 max_workers:0 이 상류 두 곳에서 막혀 있었다 — 서버 규칙 경계가 [1,50] 이라 저장이 400 이고, 엣지 파서가 v<=0 으로 규칙 전체를 무효화해 같이 넣은 2인1조까지 사라졌다. 앞 커밋에서 고친 네 곳은 전부 이 둘보다 하류라 도달 불가였다. R4-3 고소작업 프리셋(elevated)이 완전히 무동작이었다. 서버 경계에 키가 없어 400, 통과해도 엣지 파서가 침묵 삭제. 프리셋 안내문과 커밋 메시지가 시스템이 하지 않는 일을 약속하고 있었다. R4-4 동시 다발이 한 사람을 두 명으로 셀 수 있었다. 트래커는 1초 가려짐에 트랙을 버리고 새 id 를 주고(max_age=1.0) 누운 사람은 새 트랙에서도 즉시 prone 이라 두 번째 fall 이 난다. 그러면 다친 한 사람에게 "공기호흡기 없이 진입 금지"가 나가 구조가 늦어진다 — 기능의 가치가 정반대로 뒤집힌다. ghost 를 인원 집계에서 빼고, 거의 같은 자리의 사건은 같은 사람으로 본다. HIGH 5건: 구역 그룹핑 사문화(엣지가 zone_id 를 안 실어 카메라가 다른 두 희생자가 절대 안 묶였다 — 밀폐공간이 정확히 그 상황), 창 미끄러짐으로 한 사고가 매 분 새 위급 건으로 쏟아지고 인원이 줄면 앞선 알림을 스스로 뒤집던 문제, 무장 미만료·forget 누락·이중 발보, 업그레이드 안내의 마이그레이션 2개 누락(신규 유형 INSERT 가 전부 DB CHECK 에 걸린다), BUILD-INFO 커밋 스탬프. BUILD-INFO 는 1.1.0 에서 고친 R3-6 의 재발이다. 절차로 막으려다 두 번 실패했으므로 HEAD 일치를 검사하는 테스트로 막았다. README 마이그레이션 목록도 같은 이유로 테스트를 붙였다. MEDIUM 14건 중 눈에 띄는 것: 정비 억제가 SCBA 경고를 삼켰고(허가가 발급된 그 구역·그 시간이 질식이 일어나는 자리다) 위급 3종을 억제 예외로 뺐다. 데모 시더 심각도가 제품과 7종 어긋나 fall 이 위급으로 찍혀 1.2.0 의 요점인 넘어짐/추락 구분이 데모에서 지워져 있었다 — 라벨과 달리 화면이 안 깨져 눈으로는 못 잡으므로 엣지를 단일 출처로 강제하는 테스트를 붙였다. 문서의 "17종"은 실제 20종(엣지 16 + 서버 4)으로 정정하고 신규 2종을 소개서 감지 표에 넣었다. 검증: pytest 335 passed / phpunit 269 passed. 신규 테스트 30건. dist 는 이 커밋 이후 재생성한다(BUILD-INFO 가 HEAD 를 가리켜야 한다). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EBjuR7DW6PNNMows4KnbYU
630 lines
28 KiB
JavaScript
630 lines
28 KiB
JavaScript
/**
|
|
* Zone editor: canvas-based polygon drawing for camera zones.
|
|
* - Click the canvas to add points to the polygon currently being drawn.
|
|
* - Choose a level (warning/restricted/pinch), then Save -> POST /api/zones.
|
|
* - "Load" fetches existing zones for the camera via GET /api/zones/{camera}
|
|
* and redraws them; each has a Delete button -> POST /api/zones/{id}/delete.
|
|
* - "현재 화면 불러오기" fetches the camera's newest snapshot uuid via
|
|
* GET /api/cameras/{camera}/latest-snapshot and draws it as the canvas
|
|
* background, so zones are drawn over what the camera actually sees.
|
|
* - A `?snapshot={uuid}` query param does the same for one specific image
|
|
* (the event-detail page links here that way); otherwise the canvas keeps
|
|
* its plain dark backdrop.
|
|
*
|
|
* XSS-safe: all dynamic text is set via textContent, never innerHTML.
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
|
|
// Mount prefix: '' at the web root, '/move_detect' when the app shares a www/ with another
|
|
// site. Injected by src/View/layout.php from the server's SCRIPT_NAME.
|
|
var B = window.APP_BASE || '';
|
|
|
|
var canvas = document.getElementById('zone-canvas');
|
|
if (!canvas) return;
|
|
var ctx = canvas.getContext('2d');
|
|
|
|
var deviceInput = document.getElementById('device-id');
|
|
var cameraInput = document.getElementById('camera-id');
|
|
var levelSelect = document.getElementById('zone-level');
|
|
var loadBtn = document.getElementById('zone-load-btn');
|
|
var frameBtn = document.getElementById('zone-frame-btn');
|
|
var clearBtn = document.getElementById('zone-clear-btn');
|
|
var saveBtn = document.getElementById('zone-save-btn');
|
|
var listEl = document.getElementById('zone-list');
|
|
var statusEl = document.getElementById('zone-status');
|
|
var ruleMinInput = document.getElementById('rule-min-workers');
|
|
var ruleMaxInput = document.getElementById('rule-max-workers');
|
|
var ruleDwellInput = document.getElementById('rule-max-dwell');
|
|
var heatmapBtn = document.getElementById('heatmap-btn');
|
|
var heatmapDaysInput = document.getElementById('heatmap-days');
|
|
|
|
// Zone styling stays inside the app's severity ramp (app.css --warn/--crit/--high). The old
|
|
// table used a raw #a855f7 for 협착 — a purple that appears nowhere else in the product — and
|
|
// drew every zone as a bare 2px outline, which disappears against a real factory frame. Each
|
|
// level now carries a translucent FILL plus a stroke, and 협착 is separated by a dashed
|
|
// stroke rather than by an alien hue: shape does the work colour was being stretched to do.
|
|
var LEVEL_STYLE = {
|
|
warning: { stroke: '#b7820a', fill: 'rgba(183,130,10,.16)', label: '경고', dash: null },
|
|
restricted: { stroke: '#dc2626', fill: 'rgba(220,38,38,.16)', label: '제한', dash: null },
|
|
pinch: { stroke: '#e2560c', fill: 'rgba(226,86,12,.18)', label: '협착', dash: [9, 5] }
|
|
};
|
|
var DRAFT_STYLE = { stroke: '#0b6b7a', fill: 'rgba(11,107,122,.14)', label: '편집중', dash: [5, 4] };
|
|
|
|
var backgroundImage = null;
|
|
var existingZones = []; // [{zone_id, level, points: [[x,y],...]}]
|
|
var currentPoints = []; // in-progress polygon being drawn
|
|
var csrfToken = null;
|
|
var heatmapOn = false;
|
|
var heatmapPoints = []; // [{x, y, severity}] normalized 0..1 (same space as zones)
|
|
var heatmapLayer = null; // offscreen canvas, rebuilt when points change
|
|
|
|
function setStatus(msg) {
|
|
statusEl.textContent = msg;
|
|
}
|
|
|
|
function loadCsrfToken() {
|
|
return fetch(B + '/api/csrf', { headers: { Accept: 'application/json' } })
|
|
.then(function (res) { return res.ok ? res.json() : null; })
|
|
.then(function (data) { if (data && data.token) csrfToken = data.token; })
|
|
.catch(function () { /* save/delete will fail with 403 if the token is missing */ });
|
|
}
|
|
|
|
// WIRE CONTRACT: zone polygons are stored NORMALIZED (0..1 of the image), so the edge can
|
|
// compare them against a foot point normalized by the camera's own resolution regardless of
|
|
// how big the camera is. On this canvas we draw in canvas pixels, so convert at the two wire
|
|
// boundaries only: denormalize on load (here), normalize on save (saveZone).
|
|
function parsePolygon(zone) {
|
|
try {
|
|
var pts = JSON.parse(zone.polygon_json || '[]');
|
|
if (!Array.isArray(pts)) return [];
|
|
return pts.map(function (p) {
|
|
return [p[0] * canvas.width, p[1] * canvas.height];
|
|
});
|
|
} catch (e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function drawPolygon(points, style, label, closed) {
|
|
if (points.length === 0) return;
|
|
ctx.save();
|
|
ctx.beginPath();
|
|
ctx.moveTo(points[0][0], points[0][1]);
|
|
for (var i = 1; i < points.length; i++) ctx.lineTo(points[i][0], points[i][1]);
|
|
if (closed && points.length > 2) ctx.closePath();
|
|
// Fill first so the stroke sits on top of its own tint.
|
|
if (closed && points.length > 2 && style.fill) {
|
|
ctx.fillStyle = style.fill;
|
|
ctx.fill();
|
|
}
|
|
ctx.strokeStyle = style.stroke;
|
|
ctx.lineWidth = 2.5;
|
|
ctx.lineJoin = 'round';
|
|
if (style.dash) ctx.setLineDash(style.dash);
|
|
ctx.stroke();
|
|
ctx.setLineDash([]);
|
|
// Vertex handles: white-cored so they stay visible on both a bright floor and a dark shadow.
|
|
points.forEach(function (p) {
|
|
ctx.beginPath();
|
|
ctx.arc(p[0], p[1], 4, 0, Math.PI * 2);
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fill();
|
|
ctx.lineWidth = 2;
|
|
ctx.strokeStyle = style.stroke;
|
|
ctx.stroke();
|
|
});
|
|
if (label) drawLabelChip(label, points[0][0], points[0][1], style.stroke);
|
|
ctx.restore();
|
|
}
|
|
|
|
// A plain fillText label vanished into whatever the camera happened to be looking at.
|
|
// Draw it on its own solid chip so the level is legible over any frame.
|
|
function drawLabelChip(text, x, y, bg) {
|
|
ctx.save();
|
|
ctx.font = '600 13px system-ui, sans-serif';
|
|
ctx.textBaseline = 'middle';
|
|
var padX = 7, h = 20;
|
|
var w = ctx.measureText(text).width + padX * 2;
|
|
var cx = Math.min(Math.max(x + 8, 2), canvas.width - w - 2);
|
|
var cy = Math.min(Math.max(y - 14, h / 2 + 2), canvas.height - h / 2 - 2);
|
|
ctx.fillStyle = bg;
|
|
if (ctx.roundRect) {
|
|
ctx.beginPath();
|
|
ctx.roundRect(cx, cy - h / 2, w, h, 5);
|
|
ctx.fill();
|
|
} else {
|
|
ctx.fillRect(cx, cy - h / 2, w, h);
|
|
}
|
|
ctx.fillStyle = '#ffffff';
|
|
ctx.fillText(text, cx + padX, cy);
|
|
ctx.restore();
|
|
}
|
|
|
|
// ---- 위험 히트맵 오버레이 -------------------------------------------------------
|
|
// Density of everything this camera detected (incidents AND near-misses) over the window,
|
|
// drawn as additive radial blots UNDER the zone polygons. Severity weighs the alpha:
|
|
// a cluster of near-misses reads lighter than one confirmed fall at the same spot.
|
|
var HEAT_STYLE = {
|
|
critical: { color: '220,38,38', alpha: 0.34 },
|
|
high: { color: '220,38,38', alpha: 0.26 },
|
|
warning: { color: '217,119,6', alpha: 0.18 },
|
|
info: { color: '37,99,235', alpha: 0.11 }
|
|
};
|
|
|
|
function buildHeatmapLayer() {
|
|
var layer = document.createElement('canvas');
|
|
layer.width = canvas.width;
|
|
layer.height = canvas.height;
|
|
var lctx = layer.getContext('2d');
|
|
var radius = Math.round(canvas.width * 0.03); // ~29px at 960: a footprint, not a pin
|
|
heatmapPoints.forEach(function (p) {
|
|
var s = HEAT_STYLE[p.severity] || HEAT_STYLE.info;
|
|
var x = Math.min(1, Math.max(0, p.x)) * layer.width;
|
|
var y = Math.min(1, Math.max(0, p.y)) * layer.height;
|
|
var g = lctx.createRadialGradient(x, y, 0, x, y, radius);
|
|
g.addColorStop(0, 'rgba(' + s.color + ',' + s.alpha + ')');
|
|
g.addColorStop(1, 'rgba(' + s.color + ',0)');
|
|
lctx.fillStyle = g;
|
|
lctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
|
|
});
|
|
return layer;
|
|
}
|
|
|
|
function loadHeatmap() {
|
|
var camera = cameraInput.value.trim();
|
|
if (!camera) { setStatus('카메라를 먼저 선택하세요.'); return; }
|
|
var days = Math.max(1, Math.min(90, parseInt(heatmapDaysInput && heatmapDaysInput.value, 10) || 30));
|
|
setStatus('히트맵을 불러오는 중...');
|
|
fetch(B + '/api/heatmap/' + encodeURIComponent(camera) + '?days=' + days,
|
|
{ headers: { Accept: 'application/json' } })
|
|
.then(function (res) {
|
|
if (res.status === 401) { window.location.href = B + '/login'; return null; }
|
|
if (!res.ok) throw new Error('heatmap_failed:' + res.status);
|
|
return res.json();
|
|
})
|
|
.then(function (data) {
|
|
if (!data) return;
|
|
heatmapPoints = data.points || [];
|
|
heatmapLayer = buildHeatmapLayer();
|
|
redraw();
|
|
setStatus(heatmapPoints.length
|
|
? '최근 ' + data.days + '일 감지 ' + heatmapPoints.length + '건을 표시합니다.'
|
|
: '최근 ' + data.days + '일 동안 좌표가 기록된 감지가 없습니다.');
|
|
})
|
|
.catch(function () { setStatus('히트맵을 불러오지 못했습니다.'); });
|
|
}
|
|
|
|
function toggleHeatmap() {
|
|
heatmapOn = !heatmapOn;
|
|
if (heatmapBtn) heatmapBtn.setAttribute('aria-pressed', heatmapOn ? 'true' : 'false');
|
|
if (heatmapOn) loadHeatmap();
|
|
else { heatmapLayer = null; heatmapPoints = []; redraw(); setStatus('히트맵을 껐습니다.'); }
|
|
}
|
|
|
|
function redraw() {
|
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
if (backgroundImage) {
|
|
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
|
|
}
|
|
if (heatmapOn && heatmapLayer) {
|
|
ctx.drawImage(heatmapLayer, 0, 0);
|
|
}
|
|
existingZones.forEach(function (z) {
|
|
var style = LEVEL_STYLE[z.level] || { stroke: '#626a79', fill: 'rgba(98,106,121,.14)', label: z.level, dash: null };
|
|
drawPolygon(z.points, style, style.label, true);
|
|
});
|
|
drawPolygon(currentPoints, DRAFT_STYLE, currentPoints.length ? DRAFT_STYLE.label : '', false);
|
|
if (!backgroundImage && !existingZones.length && !currentPoints.length) drawCanvasHint();
|
|
}
|
|
|
|
// An empty black rectangle told the operator nothing about what to do with it.
|
|
function drawCanvasHint() {
|
|
ctx.save();
|
|
ctx.fillStyle = 'rgba(255,255,255,.5)';
|
|
ctx.font = '500 15px system-ui, sans-serif';
|
|
ctx.textAlign = 'center';
|
|
ctx.fillText('① 왼쪽에서 카메라를 고르고 "카메라 화면을 배경으로"를 누르세요.',
|
|
canvas.width / 2, canvas.height / 2 - 10);
|
|
ctx.fillText('② 그다음 이 위를 클릭해 구역 폴리곤을 그립니다.',
|
|
canvas.width / 2, canvas.height / 2 + 16);
|
|
ctx.restore();
|
|
}
|
|
|
|
// Occupancy rules the operator typed (dwell in MINUTES on screen, seconds on the wire).
|
|
// Only filled fields are sent; an empty form means "no rules" and stores NULL.
|
|
// 프리셋이 elevated 를 켜면 화면에 입력란이 없으므로 여기 들고 있는다(고소 구역 표시).
|
|
var elevated = false;
|
|
|
|
function resetPreset() {
|
|
elevated = false;
|
|
var sel = document.getElementById('zone-preset');
|
|
if (sel) sel.value = '';
|
|
var help = document.getElementById('zone-preset-help');
|
|
if (help) { help.hidden = true; help.textContent = ''; }
|
|
}
|
|
|
|
/** 입력값이 음수면 규칙을 조용히 버리지 않고 이유를 알린다. */
|
|
function invalidRuleInput() {
|
|
var pairs = [[ruleMinInput, '최소 인원'], [ruleMaxInput, '최대 인원'], [ruleDwellInput, '체류 상한']];
|
|
for (var i = 0; i < pairs.length; i++) {
|
|
var el = pairs[i][0];
|
|
if (!el || el.value === '') continue;
|
|
var n = parseInt(el.value, 10);
|
|
if (isNaN(n) || n < 0) return pairs[i][1] + ' 값이 올바르지 않습니다: ' + el.value;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function rulesFromInputs() {
|
|
var rules = {};
|
|
var minW = parseInt(ruleMinInput && ruleMinInput.value, 10);
|
|
var maxW = parseInt(ruleMaxInput && ruleMaxInput.value, 10);
|
|
var dwellMin = parseInt(ruleDwellInput && ruleDwellInput.value, 10);
|
|
if (minW > 0) rules.min_workers = minW;
|
|
// 최대 인원은 0 도 유효한 값이다 — "아무도 있으면 안 되는 구역"(크레인 짐 아래·선회 반경).
|
|
// `> 0` 으로 거르면 운영자가 0 을 넣어도 규칙이 저장되지 않는다.
|
|
if (maxW >= 0) rules.max_workers = maxW;
|
|
if (dwellMin > 0) rules.max_dwell_s = dwellMin * 60;
|
|
if (elevated) rules.elevated = true;
|
|
return rules;
|
|
}
|
|
|
|
function rulesLabel(z) {
|
|
var r;
|
|
try { r = JSON.parse(z.rules_json || 'null') || {}; } catch (e) { return ''; }
|
|
var parts = [];
|
|
if (r.min_workers) parts.push('최소 ' + r.min_workers + '인');
|
|
if (r.elevated) parts.push('고소');
|
|
if (r.max_workers === 0) parts.push('출입 금지');
|
|
else if (r.max_workers) parts.push('최대 ' + r.max_workers + '인');
|
|
if (r.max_dwell_s) parts.push('체류 ' + Math.round(r.max_dwell_s / 60) + '분');
|
|
return parts.length ? ' · ' + parts.join(' · ') : '';
|
|
}
|
|
|
|
function renderZoneList() {
|
|
listEl.textContent = '';
|
|
if (existingZones.length === 0) {
|
|
var none = document.createElement('li');
|
|
none.className = 'zone-empty';
|
|
none.textContent = '이 카메라에 저장된 구역이 없습니다.';
|
|
listEl.appendChild(none);
|
|
return;
|
|
}
|
|
existingZones.forEach(function (z) {
|
|
var li = document.createElement('li');
|
|
li.className = 'zone-item lv-' + z.level;
|
|
|
|
var label = document.createElement('span');
|
|
label.className = 'zone-item-label';
|
|
var swatch = document.createElement('span');
|
|
swatch.className = 'zone-swatch';
|
|
swatch.setAttribute('aria-hidden', 'true');
|
|
// Inline colour is the ONE place a raw hex belongs: it must match what the canvas drew.
|
|
swatch.style.background = (LEVEL_STYLE[z.level] || {}).fill || 'transparent';
|
|
swatch.style.borderColor = (LEVEL_STYLE[z.level] || {}).stroke || '#626a79';
|
|
label.appendChild(swatch);
|
|
label.appendChild(document.createTextNode(
|
|
(LEVEL_STYLE[z.level] || { label: z.level }).label + ' (' + z.points.length + '점)' + rulesLabel(z)));
|
|
li.appendChild(label);
|
|
|
|
// Two-step delete. A zone is what makes 침입 alarms fire; it takes minutes to draw and
|
|
// the server has no restore. A single unconfirmed click was the least reversible action
|
|
// in the product and also the cheapest one to trigger by accident.
|
|
var del = document.createElement('button');
|
|
del.type = 'button';
|
|
del.className = 'zone-del';
|
|
del.textContent = '삭제';
|
|
var armed = false, armTimer = null;
|
|
del.addEventListener('click', function () {
|
|
if (!armed) {
|
|
armed = true;
|
|
del.classList.add('is-armed');
|
|
del.textContent = '정말 삭제?';
|
|
setStatus('한 번 더 누르면 이 구역이 삭제됩니다. 되돌릴 수 없습니다.');
|
|
armTimer = setTimeout(function () {
|
|
armed = false; del.classList.remove('is-armed'); del.textContent = '삭제';
|
|
}, 4000);
|
|
return;
|
|
}
|
|
if (armTimer) clearTimeout(armTimer);
|
|
deleteZone(z.zone_id);
|
|
});
|
|
li.appendChild(del);
|
|
|
|
listEl.appendChild(li);
|
|
});
|
|
}
|
|
|
|
// --- 용도 프리셋 -------------------------------------------------------------------
|
|
//
|
|
// 밀폐공간 감시에 필요한 것(제한구역 + 2인1조 + 체류 상한)은 전부 이미 있었는데, 화면이
|
|
// "최소 인원을 넣으세요"라고만 물어서 아무도 그렇게 쓰지 못했다. 안전관리자는 min_workers 가
|
|
// 아니라 '밀폐공간'을 생각한다. 프리셋은 새 기능이 아니라 그 어휘를 붙인 것이다.
|
|
//
|
|
// 고른 뒤 값을 손으로 바꾸는 것은 그대로 허용한다 — 프리셋은 출발점이지 잠금이 아니다.
|
|
var presetSelect = document.getElementById('zone-preset');
|
|
var presetHelp = document.getElementById('zone-preset-help');
|
|
var presets = {};
|
|
|
|
function applyPreset(id) {
|
|
var p = presets[id];
|
|
if (!p) {
|
|
elevated = false;
|
|
if (presetHelp) { presetHelp.hidden = true; presetHelp.textContent = ''; }
|
|
return;
|
|
}
|
|
if (levelSelect) levelSelect.value = p.level;
|
|
var r = p.rules || {};
|
|
if (ruleMinInput) ruleMinInput.value = r.min_workers != null ? r.min_workers : '';
|
|
if (ruleMaxInput) ruleMaxInput.value = r.max_workers != null ? r.max_workers : '';
|
|
if (ruleDwellInput) ruleDwellInput.value = r.max_dwell_s != null ? Math.round(r.max_dwell_s / 60) : '';
|
|
elevated = !!r.elevated;
|
|
if (presetHelp) {
|
|
presetHelp.textContent = p.help + ' (잡는 것: ' + p.catches + ')';
|
|
presetHelp.hidden = false;
|
|
}
|
|
}
|
|
|
|
function loadPresets() {
|
|
if (!presetSelect) return Promise.resolve();
|
|
return fetch(B + '/api/zone-presets', { headers: { Accept: 'application/json' } })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (data) {
|
|
var list = (data && data.presets) || [];
|
|
list.forEach(function (p) {
|
|
presets[p.id] = p;
|
|
var o = document.createElement('option');
|
|
o.value = p.id;
|
|
o.textContent = p.label + ' — ' + p.catches;
|
|
presetSelect.appendChild(o);
|
|
});
|
|
presetSelect.addEventListener('change', function () { applyPreset(presetSelect.value); });
|
|
})
|
|
.catch(function () { /* 프리셋이 없어도 직접 설정으로 그대로 쓸 수 있다 */ });
|
|
}
|
|
|
|
loadPresets();
|
|
|
|
// --- 장치 · 카메라 선택기 ---------------------------------------------------------
|
|
// The editor used to demand two free-text ids the operator had to remember, while the
|
|
// events console already knew both. Devices come from /api/devices; the cameras under each
|
|
// device are derived from the events they have reported (there is no camera registry).
|
|
// A camera that has never sent an event cannot appear here, which is what the manual
|
|
// fallback in the view is for.
|
|
var deviceSelect = document.getElementById('device-select');
|
|
var cameraSelect = document.getElementById('camera-select');
|
|
var manualBox = document.getElementById('zone-manual');
|
|
var camerasByDevice = {};
|
|
|
|
function option(value, text) {
|
|
var o = document.createElement('option');
|
|
o.value = value;
|
|
o.textContent = text;
|
|
return o;
|
|
}
|
|
|
|
function fillCameraSelect(deviceId) {
|
|
if (!cameraSelect) return;
|
|
cameraSelect.textContent = '';
|
|
var cams = camerasByDevice[deviceId] || [];
|
|
if (!deviceId) { cameraSelect.appendChild(option('', '장치를 먼저 선택하세요')); return; }
|
|
if (cams.length === 0) {
|
|
cameraSelect.appendChild(option('', '이 장치가 보고한 카메라 없음'));
|
|
return;
|
|
}
|
|
cameraSelect.appendChild(option('', '카메라를 선택하세요'));
|
|
cams.forEach(function (c) { cameraSelect.appendChild(option(c, c)); });
|
|
}
|
|
|
|
function applySelection() {
|
|
if (deviceSelect) deviceInput.value = deviceSelect.value;
|
|
if (cameraSelect) cameraInput.value = cameraSelect.value;
|
|
}
|
|
|
|
function loadPickers() {
|
|
var devices = fetch(B + '/api/devices', { headers: { Accept: 'application/json' } })
|
|
.then(function (r) { return r.ok ? r.json() : null; });
|
|
var events = fetch(B + '/api/events?limit=200', { headers: { Accept: 'application/json' } })
|
|
.then(function (r) { return r.ok ? r.json() : null; });
|
|
return Promise.all([devices, events]).then(function (res) {
|
|
var devs = (res[0] && res[0].devices) || [];
|
|
var evs = (res[1] && res[1].events) || [];
|
|
evs.forEach(function (ev) {
|
|
// '__device__' is the sentinel on node-scope events (device_fault / monitoring_degraded),
|
|
// not a camera. Offering it here would let an operator draw zones onto nothing.
|
|
if (!ev.camera_id || DeviceScope.is(ev.camera_id)) return;
|
|
var d = String(ev.device_id || '');
|
|
if (!camerasByDevice[d]) camerasByDevice[d] = [];
|
|
if (camerasByDevice[d].indexOf(ev.camera_id) === -1) camerasByDevice[d].push(ev.camera_id);
|
|
});
|
|
Object.keys(camerasByDevice).forEach(function (d) { camerasByDevice[d].sort(); });
|
|
|
|
if (!deviceSelect) return;
|
|
deviceSelect.textContent = '';
|
|
if (devs.length === 0) {
|
|
deviceSelect.appendChild(option('', '등록된 장치가 없습니다'));
|
|
if (manualBox) manualBox.open = true;
|
|
return;
|
|
}
|
|
deviceSelect.appendChild(option('', '장치를 선택하세요'));
|
|
devs.forEach(function (d) {
|
|
deviceSelect.appendChild(option(d.device_id, (d.name || d.device_id) + ' · ' + d.device_id));
|
|
});
|
|
// Honour a deep link (?device=&camera=) or a value already typed into the manual fields.
|
|
if (deviceInput.value) {
|
|
deviceSelect.value = deviceInput.value;
|
|
fillCameraSelect(deviceInput.value);
|
|
if (cameraInput.value) cameraSelect.value = cameraInput.value;
|
|
}
|
|
});
|
|
}
|
|
|
|
function loadBackground(uuid) {
|
|
if (!uuid) { backgroundImage = null; redraw(); return; }
|
|
var img = new Image();
|
|
img.onload = function () { backgroundImage = img; redraw(); };
|
|
img.onerror = function () { backgroundImage = null; redraw(); };
|
|
img.src = B + '/snap/' + encodeURIComponent(uuid);
|
|
}
|
|
|
|
// Load the camera's most recent frame as the drawing background. The uuid comes from the
|
|
// API; the image itself still goes through /snap/{uuid}, which re-checks session + site scope.
|
|
function loadLatestFrame() {
|
|
var camera = cameraInput.value.trim();
|
|
if (!camera) { setStatus('카메라를 먼저 선택하세요.'); return; }
|
|
setStatus('현재 화면을 불러오는 중...');
|
|
fetch(B + '/api/cameras/' + encodeURIComponent(camera) + '/latest-snapshot', { credentials: 'same-origin' })
|
|
.then(function (r) {
|
|
if (r.status === 404) throw new Error('이 카메라의 저장된 화면이 아직 없습니다. 이벤트가 한 번 발생해야 배경이 생깁니다.');
|
|
if (!r.ok) throw new Error('불러오기 실패 (' + r.status + ')');
|
|
return r.json();
|
|
})
|
|
.then(function (data) { loadBackground(data.uuid); setStatus('현재 화면을 배경으로 불러왔습니다.'); })
|
|
.catch(function (e) { setStatus(e.message); });
|
|
}
|
|
|
|
function loadZones(doneMsg) {
|
|
var camera = cameraInput.value.trim();
|
|
if (!camera) { setStatus('카메라를 먼저 선택하세요.'); return; }
|
|
setStatus('불러오는 중...');
|
|
fetch(B + '/api/zones/' + encodeURIComponent(camera), { headers: { Accept: 'application/json' } })
|
|
.then(function (res) {
|
|
if (res.status === 401) { window.location.href = B + '/login'; return null; }
|
|
if (!res.ok) throw new Error('load_failed:' + res.status);
|
|
return res.json();
|
|
})
|
|
.then(function (data) {
|
|
if (!data) return;
|
|
existingZones = (data.zones || []).map(function (z) {
|
|
return { zone_id: z.zone_id, level: z.level, points: parsePolygon(z), rules_json: z.rules_json };
|
|
});
|
|
currentPoints = [];
|
|
// 프리셋은 '지금 그리는 구역'에만 적용된다. 저장 후 그대로 두면 다음 폴리곤이
|
|
redraw();
|
|
setStatus(doneMsg || (existingZones.length
|
|
? '저장된 구역 ' + existingZones.length + '개를 불러왔습니다.'
|
|
: '이 카메라에는 저장된 구역이 없습니다. 캔버스를 클릭해 새로 그리세요.'));
|
|
})
|
|
.catch(function () { setStatus('불러오기에 실패했습니다.'); });
|
|
}
|
|
|
|
function saveZone() {
|
|
var camera = cameraInput.value.trim();
|
|
var device = deviceInput.value.trim();
|
|
if (!camera) { setStatus('카메라를 먼저 선택하세요.'); return; }
|
|
if (currentPoints.length < 3) { setStatus('폴리곤 점을 3개 이상 클릭하세요.'); return; }
|
|
// 음수·비정상 입력을 조용히 버리면 운영자는 규칙이 저장된 줄 안다. 이 변경 전체가
|
|
// 없애려던 침묵이 바로 그것이므로 여기서 이유를 말하고 멈춘다.
|
|
var bad = invalidRuleInput();
|
|
if (bad) { setStatus(bad); return; }
|
|
setStatus('저장 중...');
|
|
fetch(B + '/api/zones', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', 'X-Csrf-Token': csrfToken || '' },
|
|
body: JSON.stringify({
|
|
device_id: device,
|
|
camera_id: camera,
|
|
level: levelSelect.value,
|
|
// Normalize canvas pixels -> 0..1 of the image (the edge un-normalizes with the
|
|
// camera's own resolution). See the parsePolygon contract note above.
|
|
polygon: currentPoints.map(function (p) {
|
|
return [p[0] / canvas.width, p[1] / canvas.height];
|
|
}),
|
|
rules: rulesFromInputs()
|
|
})
|
|
})
|
|
.then(function (res) {
|
|
if (res.status === 401) { window.location.href = B + '/login'; return null; }
|
|
if (!res.ok) throw new Error('save_failed:' + res.status);
|
|
return res.json();
|
|
})
|
|
.then(function (data) {
|
|
if (!data) return;
|
|
currentPoints = [];
|
|
// 프리셋은 '지금 그리는 구역'에만 적용된다. 저장 후 그대로 두면 다음 폴리곤이
|
|
// 보이지 않는 상태를 물려받는다 — elevated 는 화면에 표시가 없어 운영자가
|
|
// 켜져 있는지 알 수 없고, 평범한 바닥 구역이 전부 고소 구역이 되면 트랙이
|
|
// 사라질 때마다 최상위 심각도 추락 경보가 뜬다.
|
|
resetPreset();
|
|
loadZones('구역을 저장했습니다. 다음 설정 동기화 때 장치로 내려갑니다.');
|
|
})
|
|
.catch(function () { setStatus('저장에 실패했습니다.'); });
|
|
}
|
|
|
|
function deleteZone(zoneId) {
|
|
fetch(B + '/api/zones/' + encodeURIComponent(zoneId) + '/delete', {
|
|
method: 'POST',
|
|
headers: { 'X-Csrf-Token': csrfToken || '' }
|
|
})
|
|
.then(function (res) {
|
|
if (res.status === 401) { window.location.href = B + '/login'; return; }
|
|
if (!res.ok) throw new Error('delete_failed:' + res.status);
|
|
loadZones('구역을 삭제했습니다.');
|
|
})
|
|
.catch(function () { setStatus('삭제에 실패했습니다.'); });
|
|
}
|
|
|
|
canvas.addEventListener('click', function (evt) {
|
|
var rect = canvas.getBoundingClientRect();
|
|
var scaleX = canvas.width / rect.width;
|
|
var scaleY = canvas.height / rect.height;
|
|
var x = Math.round((evt.clientX - rect.left) * scaleX);
|
|
var y = Math.round((evt.clientY - rect.top) * scaleY);
|
|
currentPoints.push([x, y]);
|
|
redraw();
|
|
});
|
|
|
|
levelSelect.addEventListener('change', redraw);
|
|
loadBtn.addEventListener('click', function () { applySelection(); loadZones(); });
|
|
if (frameBtn) frameBtn.addEventListener('click', function () { applySelection(); loadLatestFrame(); });
|
|
if (heatmapBtn) heatmapBtn.addEventListener('click', function () { applySelection(); toggleHeatmap(); });
|
|
if (heatmapDaysInput) heatmapDaysInput.addEventListener('change', function () { if (heatmapOn) loadHeatmap(); });
|
|
clearBtn.addEventListener('click', function () {
|
|
currentPoints = [];
|
|
resetPreset();
|
|
redraw();
|
|
setStatus('그리던 폴리곤과 용도 선택을 지웠습니다.');
|
|
});
|
|
saveBtn.addEventListener('click', function () { applySelection(); saveZone(); });
|
|
|
|
if (deviceSelect) {
|
|
deviceSelect.addEventListener('change', function () {
|
|
deviceInput.value = deviceSelect.value;
|
|
fillCameraSelect(deviceSelect.value);
|
|
cameraInput.value = '';
|
|
setStatus(deviceSelect.value ? '카메라를 선택하세요.' : '장치를 선택하세요.');
|
|
});
|
|
}
|
|
if (cameraSelect) {
|
|
// Selecting a camera is the operator's intent to work on it: load its zones and its latest
|
|
// frame at once, instead of making them press two more buttons to see anything at all.
|
|
cameraSelect.addEventListener('change', function () {
|
|
cameraInput.value = cameraSelect.value;
|
|
if (!cameraSelect.value) return;
|
|
currentPoints = [];
|
|
resetPreset();
|
|
loadZones();
|
|
loadLatestFrame();
|
|
});
|
|
}
|
|
// Typing into the manual fields wins over the selects (and clears them, so the panel never
|
|
// shows a camera other than the one being edited).
|
|
[deviceInput, cameraInput].forEach(function (inp) {
|
|
inp.addEventListener('input', function () {
|
|
if (deviceSelect && deviceSelect.value !== deviceInput.value) deviceSelect.value = '';
|
|
if (cameraSelect && cameraSelect.value !== cameraInput.value) cameraSelect.value = '';
|
|
});
|
|
});
|
|
|
|
var params = new URLSearchParams(window.location.search);
|
|
if (params.get('camera')) cameraInput.value = params.get('camera');
|
|
if (params.get('device')) deviceInput.value = params.get('device');
|
|
if (params.get('camera') || params.get('device')) { if (manualBox) manualBox.open = false; }
|
|
loadBackground(params.get('snapshot'));
|
|
loadCsrfToken();
|
|
loadPickers();
|
|
renderZoneList(); // paint the "저장된 구역 없음" placeholder before any camera is chosen
|
|
redraw();
|
|
if (cameraInput.value) { loadZones(); loadLatestFrame(); }
|
|
})();
|