move_detect/server/public/assets/zone-draw.js
유창욱 a203c42bf3 feat(zones): occupancy rule engine - lone-worker / capacity / dwell limits
Per-zone declarative safety rules, set in the zone editor and enforced on the
edge from the tracking the pipeline already does (no new geometry, no new model):

- min_workers (2인 1조): 0 < count < minimum sustained 30s -> lone_worker/HIGH.
  A solo worker in a buddy-rule zone is a compliance violation and a rescue-
  delay risk, so it outranks the other two.
- max_workers: count > limit sustained 10s -> overcapacity/WARNING.
- max_dwell_s: one track's continuous stay past the limit -> overstay/WARNING.
  A short detection dropout (<=5s grace) does NOT reset the dwell timer -
  without that, run_once's stale-track filter would quietly neuter every
  10-minute rule at real-world detection rates.

Edge: detectors/occupancy.py consumes Zone.rules; the engine flips the zone
detector's per-track membership into per-zone headcounts (stale tracks already
excluded), so counts always match what was actually detected this tick. Fired
states clear on condition recovery - re-alerts need a fresh violation, not a
cooldown expiry. Malformed rules_json keeps the zone's intrusion detection
alive and logs the rules as inactive (never fail dark).

Server: move_zones.rules_json (nullable JSON, migration included) validated
strictly in ZoneConfigController (bounds, min<=max, unknown keys rejected -
a silently dropped rule is one the operator believes is active). Delivered to
the edge unchanged via GET /api/config. EventValidator accepts the 3 new types.

UI: zone editor gains the three rule fields (dwell entered in minutes, wired
in seconds) and shows each zone's rules in its list row; the events console
and detail view now render every event type in Korean (wire codes fall back).

Verified: pytest 216 pass / PHPUnit 123 pass + real-render harness in Chrome
(editor save payload, list labels, console type labels).
2026-08-06 19:33:12 +09:00

272 lines
11 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 LEVEL_STYLE = {
warning: { stroke: '#eab308', label: '경고' },
restricted: { stroke: '#dc2626', label: '제한' },
pinch: { stroke: '#a855f7', label: '협착' }
};
var backgroundImage = null;
var existingZones = []; // [{zone_id, level, points: [[x,y],...]}]
var currentPoints = []; // in-progress polygon being drawn
var csrfToken = null;
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, strokeStyle, label, closed) {
if (points.length === 0) return;
ctx.strokeStyle = strokeStyle;
ctx.fillStyle = strokeStyle;
ctx.lineWidth = 2;
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();
ctx.stroke();
points.forEach(function (p) {
ctx.beginPath();
ctx.arc(p[0], p[1], 3, 0, Math.PI * 2);
ctx.fill();
});
if (label) {
ctx.font = '14px sans-serif';
ctx.fillText(label, points[0][0] + 6, points[0][1] - 6);
}
}
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (backgroundImage) {
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
}
existingZones.forEach(function (z) {
var style = LEVEL_STYLE[z.level] || { stroke: '#9ca3af', label: z.level };
drawPolygon(z.points, style.stroke, style.label, true);
});
var current = LEVEL_STYLE[levelSelect.value] || { stroke: '#38bdf8', label: '' };
drawPolygon(currentPoints, current.stroke, currentPoints.length ? '편집중' : '', false);
}
// 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.
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;
if (maxW > 0) rules.max_workers = maxW;
if (dwellMin > 0) rules.max_dwell_s = dwellMin * 60;
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.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 = '';
existingZones.forEach(function (z) {
var li = document.createElement('li');
var style = LEVEL_STYLE[z.level] || { label: z.level };
var label = document.createElement('span');
label.textContent = style.label + ' (' + z.points.length + '점)' + rulesLabel(z);
li.appendChild(label);
var del = document.createElement('button');
del.type = 'button';
del.textContent = '삭제';
del.addEventListener('click', function () { deleteZone(z.zone_id); });
li.appendChild(del);
listEl.appendChild(li);
});
}
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('카메라 ID를 입력하세요.'); 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() {
var camera = cameraInput.value.trim();
if (!camera) { setStatus('카메라 ID를 입력하세요.'); 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 = [];
renderZoneList();
redraw();
setStatus('구역 ' + existingZones.length + '개를 불러왔습니다.');
})
.catch(function () { setStatus('불러오기에 실패했습니다.'); });
}
function saveZone() {
var camera = cameraInput.value.trim();
var device = deviceInput.value.trim();
if (!camera) { setStatus('카메라 ID를 입력하세요.'); return; }
if (currentPoints.length < 3) { setStatus('폴리곤 점을 3개 이상 클릭하세요.'); 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 = [];
setStatus('저장되었습니다.');
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', loadZones);
if (frameBtn) frameBtn.addEventListener('click', loadLatestFrame);
clearBtn.addEventListener('click', function () { currentPoints = []; redraw(); setStatus('현재 폴리곤을 지웠습니다.'); });
saveBtn.addEventListener('click', saveZone);
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');
loadBackground(params.get('snapshot'));
loadCsrfToken();
if (cameraInput.value) loadZones();
})();