The accumulated data starts predicting instead of just recording: - Time pattern (weekday x hour density grid): WHEN the site is dangerous, on one card - shift-change, post-lunch, Thursday-afternoon hotspots become visible. Bucketing runs in PHP on the server-local clock (site timezone) so the SQL stays portable (the sqlite harness has no FROM_UNIXTIME). - Precursor-spike alert: last-7-days count of precursor signals (near-miss, zone entries, occupancy violations - signals, not injuries) vs the prior 4-week weekly baseline. Ratio >= 1.5 with at least 5 samples raises a banner above the KPIs: an alarm on the PRECURSOR of an accident, with a concrete suggestion (staffing/route/rest review). Below the sample floor it never fires - a ratio over 2 events is noise, not statistics. - Period-over-period trends on every KPI: reportSummary gained an optional upper bound so the identical aggregation runs over the preceding window. Worsening turns red, improving turns accent - except the near-miss count, which stays NEUTRAL: more near-misses may mean better detection, not more danger, and the report must not editorialize that. Verified: PHPUnit 140 pass (2 new: window separation + pattern bucketing, spike ratio + sample floor) + Chrome real-render (alert banner, KPI trend lines, Thursday-afternoon hotspot readable in the grid).
241 lines
11 KiB
JavaScript
241 lines
11 KiB
JavaScript
/**
|
|
* Safety operations report: fetches GET /api/report?days=N and renders the management
|
|
* indicators a 안전관리자 takes into the weekly safety meeting. Read-only; the 인쇄 button
|
|
* prints the page (print CSS strips the app chrome).
|
|
*
|
|
* XSS-safe: every dynamic value goes through textContent; the only inline style is a
|
|
* numeric bar width.
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
|
|
var B = window.APP_BASE || '';
|
|
|
|
var TYPE_LABELS = {
|
|
fall: '넘어짐', no_motion: '넘어짐 후 미동 없음', immobility: '장시간 부동',
|
|
ghost: '위험 상태 소실', zone_warning: '경고구역 진입', zone_restricted: '제한구역 침입',
|
|
pinch: '협착구역 침입', monitoring_degraded: '감시 성능 저하', device_fault: '장치 이상',
|
|
lone_worker: '위험구역 단독 작업', overcapacity: '정원 초과', overstay: '체류 상한 초과',
|
|
near_fall: '넘어질 뻔함 (니어미스)', ergo_report: '작업자세 부담 리포트'
|
|
};
|
|
|
|
var root = document.getElementById('report-kpis');
|
|
if (!root) return;
|
|
|
|
var daysSel = document.getElementById('report-days');
|
|
var printBtn = document.getElementById('report-print');
|
|
var rangeEl = document.getElementById('report-range');
|
|
var typesEl = document.getElementById('report-types');
|
|
var camerasEl = document.getElementById('report-cameras');
|
|
var ergoEl = document.getElementById('report-ergo');
|
|
var rulesEl = document.getElementById('report-rules');
|
|
var footEl = document.getElementById('report-foot');
|
|
|
|
function el(tag, cls, text) {
|
|
var n = document.createElement(tag);
|
|
if (cls) n.className = cls;
|
|
if (text !== undefined && text !== null) n.textContent = text;
|
|
return n;
|
|
}
|
|
|
|
function fmtDuration(s) {
|
|
if (s === null || s === undefined) return '—';
|
|
if (s < 60) return Math.round(s) + '초';
|
|
if (s < 3600) return Math.floor(s / 60) + '분 ' + Math.round(s % 60) + '초';
|
|
return Math.floor(s / 3600) + '시간 ' + Math.floor((s % 3600) / 60) + '분';
|
|
}
|
|
|
|
function fmtHours(s) {
|
|
if (!s) return '0분';
|
|
if (s < 3600) return Math.round(s / 60) + '분';
|
|
return (s / 3600).toFixed(1) + '시간';
|
|
}
|
|
|
|
// KPI tile: the headline number plus the one-line reading of what it means.
|
|
function kpi(label, value, note, cls) {
|
|
var t = el('div', 'kpi' + (cls ? ' ' + cls : ''));
|
|
t.appendChild(el('span', 'kpi-label', label));
|
|
t.appendChild(el('strong', 'kpi-value', value));
|
|
if (note) t.appendChild(el('span', 'kpi-note', note));
|
|
return t;
|
|
}
|
|
|
|
// 전기간 대비 추이 한 줄. neutral: 니어미스처럼 증감의 좋고 나쁨을 단정할 수 없는 지표
|
|
// (감지가 늘어난 것일 수도, 위험이 늘어난 것일 수도) — 방향만 보여주고 색은 칠하지 않는다.
|
|
function trendLine(tile, prevVal, curVal, fmt, neutral) {
|
|
if (prevVal === null || prevVal === undefined) return;
|
|
var line = el('span', 'kpi-trend');
|
|
if (prevVal === curVal) {
|
|
line.textContent = '이전 기간과 동일';
|
|
} else {
|
|
var up = curVal > prevVal;
|
|
line.textContent = (up ? '▲ ' : '▼ ') + '이전 기간 ' + fmt(prevVal) + ' → ' + fmt(curVal);
|
|
if (!neutral) line.className = 'kpi-trend ' + (up ? 'is-worse' : 'is-better');
|
|
}
|
|
tile.appendChild(line);
|
|
}
|
|
|
|
function barRow(label, value, max, text, hot) {
|
|
var row = el('div', 'bar-row');
|
|
var head = el('div', 'bar-head');
|
|
head.appendChild(el('span', 'bar-label', label));
|
|
head.appendChild(el('span', 'bar-value' + (hot ? ' is-hot' : ''), text));
|
|
row.appendChild(head);
|
|
var track = el('div', 'bar-track');
|
|
var fill = el('div', 'bar-fill' + (hot ? ' is-hot' : ''));
|
|
fill.style.width = (max > 0 ? Math.max(2, Math.round(value / max * 100)) : 0) + '%';
|
|
track.appendChild(fill);
|
|
row.appendChild(track);
|
|
return row;
|
|
}
|
|
|
|
function render(r) {
|
|
var t = r.totals;
|
|
var severe = t.critical + t.high;
|
|
|
|
rangeEl.textContent = '최근 ' + r.days + '일 · '
|
|
+ new Date((r.generated_at - r.days * 86400) * 1000).toLocaleDateString('ko-KR')
|
|
+ ' ~ ' + new Date(r.generated_at * 1000).toLocaleDateString('ko-KR');
|
|
|
|
// 전조 급증 경보 — 사고가 아니라 사고의 전조에 거는 알람이라 리포트 최상단에 선다.
|
|
var alertEl = document.getElementById('report-alert');
|
|
if (alertEl) {
|
|
var sp = r.precursor_alert || {};
|
|
alertEl.hidden = !sp.alert;
|
|
alertEl.textContent = '';
|
|
if (sp.alert) {
|
|
var lead = el('strong', null, '⚠ 전조 급증');
|
|
alertEl.appendChild(lead);
|
|
alertEl.appendChild(document.createTextNode(
|
|
' — 최근 7일 니어미스·구역 신호 ' + sp.this_week + '건, 이전 4주 주평균 '
|
|
+ sp.baseline_weekly_avg + '건' + (sp.ratio ? ' (' + sp.ratio + '배)' : '')
|
|
+ '. 배치·동선·휴식 등 사전 개입을 검토하세요.'));
|
|
}
|
|
}
|
|
|
|
root.textContent = '';
|
|
var prev = r.previous || {};
|
|
var kSevere = kpi('중대 이벤트', String(severe),
|
|
'위급 ' + t.critical + ' · 높음 ' + t.high, severe > 0 ? 'is-severe' : '');
|
|
trendLine(kSevere, (prev.critical || 0) + (prev.high || 0), severe, String);
|
|
root.appendChild(kSevere);
|
|
var kTta = kpi('평균 대응 시간', fmtDuration(r.tta.avg_s),
|
|
r.tta.acked > 0 ? '중대 ' + r.tta.acked + '건 확인 · 최장 ' + fmtDuration(r.tta.max_s) : '확인된 중대 이벤트 없음');
|
|
if (r.tta.avg_s !== null) trendLine(kTta, prev.tta_avg_s, r.tta.avg_s, fmtDuration);
|
|
root.appendChild(kTta);
|
|
// 하인리히 지표: 니어미스가 사고보다 얼마나 앞서 잡히고 있나 — 예방이 작동한다는 증거.
|
|
var nm = r.near_miss;
|
|
var kNm = kpi('니어미스 : 사고', nm.near_fall + ' : ' + nm.incidents,
|
|
nm.near_fall > 0 ? '사고 전 신호가 먼저 잡히고 있습니다' : '기록된 니어미스 없음');
|
|
trendLine(kNm, prev.near_fall, nm.near_fall, String, true);
|
|
root.appendChild(kNm);
|
|
var fpPct = r.fp.total > 0 ? Math.round(r.fp.tagged / r.fp.total * 100) : 0;
|
|
var prevFpPct = prev.fp && prev.fp.total > 0 ? Math.round(prev.fp.tagged / prev.fp.total * 100) : null;
|
|
var kFp = kpi('오탐율', fpPct + '%',
|
|
'전체 ' + r.fp.total + '건 중 오탐 태그 ' + r.fp.tagged + '건', fpPct >= 30 ? 'is-warn' : '');
|
|
trendLine(kFp, prevFpPct, fpPct, function (v) { return v + '%'; });
|
|
root.appendChild(kFp);
|
|
|
|
typesEl.textContent = '';
|
|
var typeKeys = Object.keys(r.by_type);
|
|
if (typeKeys.length === 0) typesEl.appendChild(el('p', 'report-empty', '기간 내 감지가 없습니다.'));
|
|
var maxType = typeKeys.reduce(function (m, k) { return Math.max(m, r.by_type[k]); }, 0);
|
|
typeKeys.forEach(function (k) {
|
|
typesEl.appendChild(barRow(TYPE_LABELS[k] || k, r.by_type[k], maxType, r.by_type[k] + '건'));
|
|
});
|
|
|
|
camerasEl.textContent = '';
|
|
if (r.by_camera.length === 0) camerasEl.appendChild(el('p', 'report-empty', '기간 내 감지가 없습니다.'));
|
|
var maxCam = r.by_camera.reduce(function (m, c) { return Math.max(m, c.count); }, 0);
|
|
r.by_camera.forEach(function (c) {
|
|
camerasEl.appendChild(barRow(c.camera_id, c.count, maxCam,
|
|
c.count + '건 · 중대 ' + c.critical_high, c.critical_high > 0));
|
|
});
|
|
|
|
// 인체공학: 관측 시간 대비 각 밴드 노출 — 절대시간과 비율을 함께.
|
|
ergoEl.textContent = '';
|
|
var eg = r.ergo;
|
|
if (!eg.observed_s) {
|
|
ergoEl.appendChild(el('p', 'report-empty', '기간 내 자세 관측 데이터가 없습니다.'));
|
|
} else {
|
|
[['trunk_high_s', '허리 고위험 (60°+)', true],
|
|
['trunk_mod_s', '허리 중위험 (20~60°)', false],
|
|
['arm_high_s', '팔 거상 (90°+)', false],
|
|
['squat_s', '깊은 웅크림', false]].forEach(function (row) {
|
|
var v = eg[row[0]] || 0;
|
|
var pct = Math.round(v / eg.observed_s * 100);
|
|
ergoEl.appendChild(barRow(row[1], v, eg.observed_s,
|
|
fmtHours(v) + ' (' + pct + '%)', row[2] && pct >= 20));
|
|
});
|
|
ergoEl.appendChild(el('p', 'report-empty', '총 관측 ' + fmtHours(eg.observed_s)
|
|
+ ' — 비율은 관측 시간 대비입니다.'));
|
|
}
|
|
|
|
rulesEl.textContent = '';
|
|
var oc = r.occupancy;
|
|
var rules = el('div', 'rule-stats');
|
|
[['단독 작업', oc.lone_worker], ['정원 초과', oc.overcapacity], ['체류 상한 초과', oc.overstay],
|
|
['미확인 잔여', t.unacked]].forEach(function (pair) {
|
|
var box = el('div', 'rule-stat' + (pair[1] > 0 ? ' is-nonzero' : ''));
|
|
box.appendChild(el('strong', null, String(pair[1])));
|
|
box.appendChild(el('span', null, pair[0]));
|
|
rules.appendChild(box);
|
|
});
|
|
rulesEl.appendChild(rules);
|
|
|
|
// 시간 패턴: 요일×시간 발생 밀도 — "언제가 위험한가"를 한 장에.
|
|
var patternEl = document.getElementById('report-pattern');
|
|
if (patternEl) {
|
|
patternEl.textContent = '';
|
|
var pt = r.pattern || { grid: [], max: 0 };
|
|
if (!pt.max) {
|
|
patternEl.appendChild(el('p', 'report-empty', '기간 내 감지가 없습니다.'));
|
|
} else {
|
|
var DAYS = ['월', '화', '수', '목', '금', '토', '일'];
|
|
var table = el('div', 'pattern');
|
|
var head = el('div', 'pattern-row pattern-head');
|
|
head.appendChild(el('span', 'pattern-day', ''));
|
|
for (var h = 0; h < 24; h++) head.appendChild(el('span', 'pattern-hour', h % 6 === 0 ? String(h) : ''));
|
|
table.appendChild(head);
|
|
pt.grid.forEach(function (rowArr, d) {
|
|
var row = el('div', 'pattern-row');
|
|
row.appendChild(el('span', 'pattern-day', DAYS[d]));
|
|
rowArr.forEach(function (n, h) {
|
|
var cell = el('span', 'pattern-cell');
|
|
if (n > 0) {
|
|
cell.style.opacity = String(0.25 + 0.75 * (n / pt.max));
|
|
cell.classList.add('is-filled');
|
|
}
|
|
cell.title = DAYS[d] + ' ' + h + '시 · ' + n + '건';
|
|
cell.setAttribute('aria-label', cell.title);
|
|
row.appendChild(cell);
|
|
});
|
|
table.appendChild(row);
|
|
});
|
|
patternEl.appendChild(table);
|
|
patternEl.appendChild(el('p', 'report-empty', '진할수록 감지가 몰린 시간대입니다 (최대 ' + pt.max + '건).'));
|
|
}
|
|
}
|
|
|
|
footEl.textContent = '생성 ' + new Date(r.generated_at * 1000).toLocaleString('ko-KR')
|
|
+ ' · 본 리포트는 AI 감지 기반 보조 지표이며 공식 재해 통계를 대체하지 않습니다.';
|
|
}
|
|
|
|
function load() {
|
|
var days = daysSel ? daysSel.value : '7';
|
|
fetch(B + '/api/report?days=' + encodeURIComponent(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('report_failed:' + res.status);
|
|
return res.json();
|
|
})
|
|
.then(function (data) { if (data) render(data); })
|
|
.catch(function () {
|
|
rangeEl.textContent = '리포트를 불러오지 못했습니다. 새로고침해 주세요.';
|
|
});
|
|
}
|
|
|
|
if (daysSel) daysSel.addEventListener('change', load);
|
|
if (printBtn) printBtn.addEventListener('click', function () { window.print(); });
|
|
load();
|
|
})();
|