UI/UX 점검에서 시작해 "이 제품이 안전 시스템으로서 무엇이 없나"까지 내려간 작업. 두 덩어리를 한 커밋으로 둔다 — 뒤쪽 기능들이 앞쪽에서 고친 화면 위에 얹혀 있다. ━━ 1부: UI/UX 감사 21건 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 동선 — 확인(ack) 경로가 위험했다 - 스트림 정렬을 '미확인 우선'에서 엄격 시간순으로 되돌린다. 확인 상태가 연대기를 뒤집어 사고 재구성이 불가능했고, 확인하면 그 행이 목록 밖으로 사라지며 아래 행이 밀려 올라와 같은 좌표를 두 번 누르면 다른 이벤트가 확인 처리됐다. 이제 제자리에서 '확인됨'으로 전환되고 확정 토스트가 뜬다. 처리 큐는 정렬이 아니라 뷰모드 필터로 분리 (전환해도 행끼리 상대 순서는 절대 안 바뀐다). - 실행취소는 넣지 않았다. acknowledged_by는 감사로그가 함께 남는 추가 전용 기록이라 무음 되돌리기가 안전 시스템에서 더 나쁜 속성이다. 대신 오탐·구역삭제를 2단계 확정으로. - 이벤트 상세에 확인/오탐 신설. 판단하는 화면에 판단 도구가 없었다. - 구역 설정에 장치·카메라 선택기. 시스템이 아는 값을 사람에게 묻고 있었고, 플레이스홀더(device-01)마저 실제와 다른 포맷을 가르쳤다. - 날짜 조회(키셋 커서 시딩). 사고 조사 진입로가 아예 없어 '더 보기'를 반복해야 했다. - 경보음 세션 음소거(새 위급 도착 시 자동 해제). 끌 수 없는 반복음은 안전 콘솔이 통째로 꺼지는 경로다. 전달 — 같은 단어가 화면마다 다른 숫자를 가리켰다 - KPI '미확인'(최근 200건)과 24시간 브리프 '미확인'이 40px 간격으로 충돌했다. KPI에 실제 집계 범위를 명시. 중대=위급+높음을 인라인 정의. - 페이지 명칭 3종·날짜 포맷 3종 통일. '확인 필요' 칩을 전 심각도로 확장 (그전엔 확인 여부가 먼 컬럼의 버튼 유무로만 구분됐다). - 표본 게이트: 오탐율 '100% (1/1)'이 '33% (5/15)'보다 위에 뜨던 것, 최다 3건짜리 시간패턴 히트맵, 6→8건에 붙던 빨간 ▲33%. 개선조치 효과는 푸아송 잡음 범위(√before)를 넘어야 방향을 주장한다 — 안전회의에서 한 번 반박당하면 카드 전체가 신뢰를 잃는다. - 카메라 위험 순위가 중대>0이면 전부 빨강이라 순위 노릇을 못 했다. 상대 기준으로. 시각 — 화면마다 완성도가 달랐다 - 구역 설정·이벤트 상세를 카드 셸로 재구성. 둘 다 스타일 없는 기본 폼이었고, 납품 심사에서 "덜 만든 티"는 정확히 거기서 났다. - 히트맵 토글은 aria-pressed만 있고 CSS 규칙이 없어 켜졌는지 눈으로 알 수 없었다. - 존 색을 팔레트와 정합(팔레트 어디에도 없던 보라 제거), 채움+라벨칩+협착 점선. 캔버스에 1px 외곽선만 그리면 실제 공장 프레임에서 사라진다. ━━ 2부: 안전 플랫폼 (마이그레이션 2026-08-09-safety-platform.sql) ━━━ 통보 — 이 제품의 정의에 해당하는 구멍 지금까지 감지는 브라우저 탭이 열려 있고 사람이 보고 있어야만 전달됐다. 새벽 3시에 넘어진 작업자는 DB에 행 하나를 남기고 아침을 맞았다. - 엣지 GPIO 경광등(edge/beacon.py). 인터넷·서버 없이 동작하는 유일한 경로라 어떤 현장이든 이것부터 설정한다. /api/config의 beacons로 배선을 받고, 하드웨어가 없거나 핀이 안 열리면 NullBeacon으로 떨어지되 그 사실은 반드시 로그로 남긴다. - 메일·웹훅 채널 + 크론 디스패처(tools/dispatch_alerts.php). 중복 발송은 읽고-쓰기가 아니라 (event,channel) UNIQUE로 막는다 — 크론 중첩 실행은 공유호스팅의 상수다. - 미확인 위급은 unacked_escalation 이벤트가 되어 상위 채널로 올라간다(event_uuid로 멱등). '아무도 보지 않았다'는 사실 자체를 사건으로 만든다. - 통보에 이미지는 싣지 않는다. 스냅샷은 PIPA 대상이고 메일링 리스트로 나가는 순간 인증 프록시가 지키던 통제를 벗어난다 — 링크만 보낸다. 조용한 실패 제거 - 카메라 화각 이동·가림·조도 저하 감지(detectors/integrity.py). 존 판정은 화각 고정을 전제로 서 있는데, 삼각대를 스치면 제한구역이 엉뚱한 바닥을 가리키면서 시스템은 계속 초록불이었다. numpy만 사용하고, 지나가는 사람과 구분하기 위해 지속시간을 요구한다. - 스토리지 여유 감시. 디스크가 차면 이미지 저장만 조용히 실패하고 보드는 멀쩡해 보인다. 끊겨 있던 배선 2건 - thresholds_from_config()가 정의만 있고 어디서도 호출되지 않았다. 서버에 표가 있고 /api/config가 성실히 실어 보내고 엣지가 파싱한 뒤 버렸다 — 관리자가 무엇을 바꿔도 장비는 부팅 시 edge.env 값으로 영원히 돌았다(edge/tuning.py). - 존·임계값 저장이 config_version을 올리지 않아 '설정 지연' 표시가 애초에 켜질 수 없었다. 지표는 있는데 그것을 켜는 사건이 없었다. 관리 화면 (그전에는 phpMyAdmin이 유일한 방법이었다) - 임계값 편집: 자유 텍스트가 아니라 카탈로그(범위·단위·설명)로 렌더한다. 범위 밖 값은 엣지가 기동 시 거부하는데 그때는 이미 공장 안 장비가 재시작 루프다. 키보드 앞에서 막는다. 목록에 없는 키는 저장 불가 — 장비가 조용히 무시할 값이 '설정됨'으로 보이면 안 된다. - 정비 억제: 사유 필수, 최대 8시간(한 교대), 자동 만료. 감지와 기록은 그대로 계속되고 통보만 보류되며 그 보류도 원장에 status='suppressed'로 남는다 — 조사에서 '경보가 났지만 의도적으로 withheld됐다'를 볼 수 있어야 한다. - 교대 인수인계, 위험성평가, 설비 성능 추이, 설치 점검(/setup — 실제 상태 조회 기반). 증거·규정 - 감사로그 해시체인. 공유호스팅은 append-only 권한을 줄 수 없으니 '막는' 대신 '숨길 수 없게' 만든다. 수정·삭제·우회삽입이 전부 탐지되고(tools/verify_audit_chain.php, 손상 시 exit 1), 체인 이전 행은 손상이 아니라 '검증 불가 구간'으로 따로 센다 — 정상 시스템이 매번 빨간불을 켜면 아무도 이 도구를 안 본다. - 사고조사 패키지 1클릭: 전후 타임라인 + 통보 이력(누구에게 닿았는가) + 위험요인 + 조치 이력 + 서명란. 인쇄 CSS로 그대로 제출 가능. 사고 다음 날 반나절을 쓸 사람은 없다. - 이벤트→조치 직접 기록, 현장별 롤업(전역 계정만). 운영 - 일괄 확인(위급은 의도적으로 제외·2단계 확정), 키보드 트리아지(J/K/A/F/Enter), 모바일 레이아웃(44px 타깃), 보존기간 정리(tools/maintain.php), 백업/복구(tools/backup.php — www 안 출력은 거부), 데모 시드(tools/seed_demo.php). - tools/는 전부 CLI 전용이고 납품 시 move_detect_app/tools/에 www 밖으로 배치된다. 미착수 4건 (모델·하드웨어가 선행 조건) - 보호구·중장비 근접·화재 감지는 AGPL 아닌 가중치 확보 + HEF 컴파일이 관문이다. 감지기 배선·이벤트 계약·심각도·쿨다운·테스트까지 만들고 기본 비활성으로 둔다 (edge/detectors/pending.py). enabled=True인데 model=None이면 아무것도 하지 않도록 명시적으로 막았다 — "곧 됩니다" 상태로 켜 두면 현장은 감지되고 있다고 믿는다. - PLC 접점 협착 게이팅도 같은 이유로 인터페이스만. 검증: pytest 통과(skip 3 = 하드웨어·환경) / PHPUnit 221 (skip 0, +59). Chrome 실렌더로 신규 4화면 + 임계값 저장→config_version 증가→감사 기록→체인 검증→ 행 변조→탐지(exit 1) 전 경로 확인. cafe24 번들 + Pi 오프라인 번들(aarch64 휠 11개) 재생성, 소스 패리티 통과. 보안 자체점검: SQL 문자열 보간 0, innerHTML 0, 상태 변경 핸들러 전부 CSRF+RBAC.
535 lines
24 KiB
JavaScript
535 lines
24 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.
|
|
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 = '';
|
|
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);
|
|
});
|
|
}
|
|
|
|
// --- 장치 · 카메라 선택기 ---------------------------------------------------------
|
|
// 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) {
|
|
if (!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 = [];
|
|
renderZoneList();
|
|
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; }
|
|
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 = [];
|
|
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 = []; 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 = [];
|
|
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(); }
|
|
})();
|