/** * 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'); 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; 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, 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); } } // ---- 위험 히트맵 오버레이 ------------------------------------------------------- // 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('카메라 ID를 입력하세요.'); 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: '#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); if (heatmapBtn) heatmapBtn.addEventListener('click', toggleHeatmap); if (heatmapDaysInput) heatmapDaysInput.addEventListener('change', function () { if (heatmapOn) loadHeatmap(); }); 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(); })();