Lint / Python (flake8) (push) Successful in 53s
Lint / JS (eslint) (push) Successful in 14s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m16s
Test / Python Tests (pytest) (push) Successful in 1m34s
Lint / JS (eslint) (pull_request) Successful in 14s
Lint / Python (flake8) (pull_request) Successful in 1m1s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m7s
Test / Python Tests (pytest) (pull_request) Successful in 1m20s
The BGW320 drops new incoming connections over 50 a second, even in IP Passthrough, with no setting to change it. From 2026-11-23 a crawler on the Gitea site kept that limit full: Sia was unreachable from the internet and outside users found Matrix and Jellyfin slow, while everything looked fine from inside. Gandalf already counted the drops but never acted on them. - modem.flood_saturation / flood_cleared: full when 2 complete hours in a row each log 1,500 or more flood drops (the log's ceiling is about 1,800), clear once a complete hour logs under 500. - monitor._process_inbound_flood raises "Modem dropping new incoming connections (flood limit)" (P2 ticket, Cleared note) and names the busiest inbound ports; Needs attention shows it too. - NAT check now counts incoming sessions to the public IP by port (modem.parse_inbound_ports), shown as "Busiest inbound port" on the panel. - Firewall drop counts are kept for 14 days instead of 24 hours, charted per hour on the WAN / Fiber panel with the full-limit line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
931 lines
41 KiB
JavaScript
931 lines
41 KiB
JavaScript
'use strict';
|
|
/* exported initDeviceSearch */
|
|
/* global DEVICE_NAME */
|
|
|
|
// ── Auto-redirect on auth timeout ─────────────────────────────────────
|
|
// Wraps fetch so a 401 (Authelia session expired) forces a full reload.
|
|
// lt.api uses fetch internally, so this covers all API calls too.
|
|
(function () {
|
|
const _fetch = window.fetch;
|
|
window.fetch = async function (...args) {
|
|
const resp = await _fetch(...args);
|
|
if (resp.status === 401) {
|
|
window.location.reload();
|
|
throw new Error('Session expired, reloading');
|
|
}
|
|
return resp;
|
|
};
|
|
})();
|
|
|
|
// ── Toast notifications: thin wrapper over lt.toast ──────────────────
|
|
function showToast(msg, type = 'success') {
|
|
if (type === 'error') return lt.toast.error(msg);
|
|
if (type === 'warning') return lt.toast.warning(msg);
|
|
if (type === 'info') return lt.toast.info(msg);
|
|
return lt.toast.success(msg);
|
|
}
|
|
|
|
// ── Normalise UTC timestamp string for Date() parsing ─────────────────
|
|
// Server returns "2026-03-14 14:14:21 UTC"; Date() needs ISO 8601.
|
|
function _toIso(s) {
|
|
if (!s) return s;
|
|
return s.replace(' UTC', 'Z').replace(' ', 'T');
|
|
}
|
|
|
|
// ── Dashboard auto-refresh ────────────────────────────────────────────
|
|
async function refreshAll() {
|
|
const refreshBtn = document.querySelector('[data-action="refresh"]');
|
|
const spinner = document.getElementById('refresh-spinner');
|
|
if (refreshBtn) refreshBtn.classList.add('is-loading');
|
|
if (spinner) spinner.style.display = '';
|
|
try {
|
|
const [netResult, statusResult] = await Promise.allSettled([
|
|
lt.api.get('/api/network'),
|
|
lt.api.get('/api/status'),
|
|
refreshModem(),
|
|
refreshAttention(),
|
|
]);
|
|
if (netResult.status === 'fulfilled') {
|
|
const net = netResult.value;
|
|
updateHostGrid(net.hosts || {});
|
|
updateUnifiTable(net.unifi || []);
|
|
} else {
|
|
showToast('Network data unavailable', 'warning');
|
|
}
|
|
if (statusResult.status === 'fulfilled') {
|
|
const status = statusResult.value;
|
|
updateEventsTable(status.events || [], status.total_active);
|
|
updateFollowUp(status.stale_tickets || []);
|
|
updateStatusBar(status.summary || {}, status.last_check || '', status.daemon_ok,
|
|
followUpCount(status.events || [], status.stale_tickets || []),
|
|
(status.stale_tickets || []).length > 0);
|
|
if (typeof window.gandalfNotifUpdate === 'function') window.gandalfNotifUpdate(status.events || []);
|
|
} else {
|
|
showToast('Status data unavailable', 'warning');
|
|
}
|
|
} finally {
|
|
if (refreshBtn) refreshBtn.classList.remove('is-loading');
|
|
if (spinner) spinner.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
// ── Needs attention ───────────────────────────────────────────────────
|
|
const ATTENTION_GROUPS = [
|
|
{ key: 'broken', title: 'Broken now', clear: 'Nothing broken' },
|
|
{ key: 'tidy', title: 'Tidy up', clear: 'Records match the network' },
|
|
];
|
|
|
|
async function refreshAttention() {
|
|
const body = document.getElementById('attention-body');
|
|
if (!body) return;
|
|
try {
|
|
renderAttention(body, await lt.api.get('/api/attention'));
|
|
} catch (e) {
|
|
body.innerHTML = `<p class="attention-empty">Couldn't gather the list: ${lt.escHtml(e.message || e)}</p>`;
|
|
}
|
|
}
|
|
|
|
function renderAttention(body, data) {
|
|
const esc = lt.escHtml;
|
|
body.innerHTML = ATTENTION_GROUPS.map(g => {
|
|
const rows = data[g.key] || [];
|
|
const list = rows.length
|
|
? `<ul class="attention-list">${rows.map(r => `
|
|
<li class="attention-item attention-${esc(r.severity)}">
|
|
<a class="attention-link" href="${esc(r.href)}">${esc(r.text)}</a>
|
|
${r.detail ? `<span class="attention-detail">${esc(r.detail)}</span>` : ''}
|
|
</li>`).join('')}</ul>`
|
|
: `<p class="attention-clear">✓ ${g.clear}</p>`;
|
|
return `<div class="attention-group attention-group-${g.key}">
|
|
<h3 class="attention-group-title">${g.title}${rows.length ? ` <span class="attention-count">${rows.length}</span>` : ''}</h3>
|
|
${list}
|
|
</div>`;
|
|
}).join('');
|
|
}
|
|
|
|
// Active alerts flagged stale or with a closed ticket, plus tickets left open after clearing
|
|
function followUpCount(events, staleTickets) {
|
|
const flagged = events.filter(e => e.severity !== 'info' &&
|
|
((e.stale_days !== null && e.stale_days !== undefined) || e.ticket_closed)).length;
|
|
return flagged + staleTickets.length;
|
|
}
|
|
|
|
function updateStatusBar(summary, lastCheck, daemonOk, followUps = 0, hasStaleTickets = false) {
|
|
const bar = document.querySelector('.status-chips');
|
|
if (!bar) return;
|
|
const chips = [];
|
|
if (daemonOk === false) chips.push('<span class="chip chip-critical">⚠ MONITOR OFFLINE</span>');
|
|
if (summary.critical) chips.push(`<span class="chip chip-critical">● ${summary.critical} CRITICAL</span>`);
|
|
if (summary.warning) chips.push(`<span class="chip chip-warning">● ${summary.warning} WARNING</span>`);
|
|
if (!summary.critical && !summary.warning && daemonOk !== false) chips.push('<span class="chip chip-ok">✔ ALL SYSTEMS NOMINAL</span>');
|
|
if (followUps) {
|
|
const href = hasStaleTickets ? '#followup' : '#events-table-wrap';
|
|
chips.push(`<a class="chip chip-warning chip-followup" href="${href}">⏳ ${followUps} TO FOLLOW UP</a>`);
|
|
}
|
|
bar.innerHTML = chips.join('');
|
|
|
|
const lc = document.getElementById('last-check');
|
|
if (lc && lastCheck) lc.textContent = lastCheck;
|
|
|
|
const critCount = summary.critical || 0;
|
|
const warnCount = summary.warning || 0;
|
|
if (critCount) document.title = `(${critCount} CRIT) GANDALF`;
|
|
else if (warnCount) document.title = `(${warnCount} WARN) GANDALF`;
|
|
else document.title = 'GANDALF';
|
|
|
|
const alertBadge = document.getElementById('alert-count-badge');
|
|
if (alertBadge) {
|
|
const total = critCount + warnCount;
|
|
alertBadge.textContent = total;
|
|
alertBadge.style.display = total ? '' : 'none';
|
|
}
|
|
|
|
// Stale data banner: warn if last_check is older than 15 minutes
|
|
let staleBanner = document.getElementById('stale-banner');
|
|
if (lastCheck) {
|
|
const checkAge = (Date.now() - new Date(_toIso(lastCheck))) / 1000;
|
|
if (checkAge > 900) {
|
|
if (!staleBanner) {
|
|
staleBanner = document.createElement('div');
|
|
staleBanner.id = 'stale-banner';
|
|
staleBanner.className = 'lt-alert lt-alert--warning';
|
|
staleBanner.innerHTML = '<span class="lt-alert-icon">⚠</span><div class="lt-alert-body"><div class="lt-alert-msg"></div></div>';
|
|
document.querySelector('.lt-main').prepend(staleBanner);
|
|
}
|
|
const mins = Math.floor(checkAge / 60);
|
|
staleBanner.querySelector('.lt-alert-msg').textContent =
|
|
`Monitoring data is stale: last check was ${mins} minute${mins !== 1 ? 's' : ''} ago. The monitor daemon may be down.`;
|
|
staleBanner.style.display = '';
|
|
} else if (staleBanner) {
|
|
staleBanner.style.display = 'none';
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateHostGrid(hosts) {
|
|
for (const [name, host] of Object.entries(hosts)) {
|
|
const card = document.querySelector(`.host-card[data-host="${CSS.escape(name)}"]`);
|
|
if (!card) continue;
|
|
|
|
card.className = card.className.replace(/host-card-(up|down|degraded|unknown)/g, '');
|
|
card.classList.add(`host-card-${host.status}`);
|
|
|
|
const dot = card.querySelector('.host-status-dot');
|
|
if (dot) dot.className = `host-status-dot dot-${host.status}`;
|
|
|
|
const ifaceList = card.querySelector('.iface-list');
|
|
if (ifaceList && host.interfaces && Object.keys(host.interfaces).length > 0) {
|
|
// NICs marked unused fold into one line, so the card shows what is cabled
|
|
const all = Object.entries(host.interfaces).sort(([a], [b]) => a.localeCompare(b));
|
|
const inUse = all.filter(([, state]) => state !== 'unused');
|
|
const unused = all.length - inUse.length;
|
|
ifaceList.innerHTML = inUse.map(([iface, state]) => `
|
|
<div class="iface-row">
|
|
<span class="iface-dot dot-${lt.escHtml(state)}"></span>
|
|
<span class="iface-name">${lt.escHtml(iface)}</span>
|
|
<span class="iface-state state-${lt.escHtml(state)}">${lt.escHtml(state)}</span>
|
|
</div>
|
|
`).join('') + (unused ? `<div class="iface-unused">+${unused} unused</div>` : '');
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── Device search ─────────────────────────────────────────────────────
|
|
function deviceUrl(name) {
|
|
return `/device/${encodeURIComponent(name)}`;
|
|
}
|
|
|
|
// All words must match somewhere; the device's name matching ranks first.
|
|
function rankDevices(devices, query) {
|
|
const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
if (!words.length) return [];
|
|
const scored = [];
|
|
for (const d of devices) {
|
|
if (!words.every(w => d.search.includes(w))) continue;
|
|
const name = d.name.toLowerCase();
|
|
let score = 3;
|
|
if (name === words[0]) score = 0;
|
|
else if (name.startsWith(words[0])) score = 1;
|
|
else if (name.includes(words[0]) || (d.ip || '').startsWith(words[0])) score = 2;
|
|
scored.push({ d, score });
|
|
}
|
|
return scored
|
|
.sort((a, b) => a.score - b.score || a.d.name.localeCompare(b.d.name))
|
|
.slice(0, 12)
|
|
.map(s => s.d);
|
|
}
|
|
|
|
function initDeviceSearch() {
|
|
const input = document.getElementById('device-search-input');
|
|
const results = document.getElementById('device-search-results');
|
|
if (!input || !results) return;
|
|
let devices = [];
|
|
let matches = [];
|
|
let active = 0;
|
|
|
|
async function loadDevices() {
|
|
try {
|
|
devices = (await lt.api.get('/api/devices')).devices || [];
|
|
} catch (err) {
|
|
console.warn('Device list unavailable', err);
|
|
}
|
|
}
|
|
|
|
function close() {
|
|
results.hidden = true;
|
|
input.setAttribute('aria-expanded', 'false');
|
|
input.removeAttribute('aria-activedescendant');
|
|
}
|
|
|
|
function render() {
|
|
matches = rankDevices(devices, input.value);
|
|
if (!input.value.trim()) { close(); return; }
|
|
active = Math.min(active, Math.max(matches.length - 1, 0));
|
|
results.hidden = false;
|
|
input.setAttribute('aria-expanded', 'true');
|
|
if (!matches.length) {
|
|
results.innerHTML = '<div class="device-search-empty">No devices match.</div>';
|
|
input.removeAttribute('aria-activedescendant');
|
|
return;
|
|
}
|
|
results.innerHTML = matches.map((d, i) => `
|
|
<a class="device-search-row${i === active ? ' is-active' : ''}" id="device-opt-${i}" role="option"
|
|
aria-selected="${i === active}" href="${lt.escHtml(d.url || deviceUrl(d.name))}">
|
|
<span class="dot-${lt.escHtml(d.status)}"></span>
|
|
<span class="device-search-name">${lt.escHtml(d.name)}</span>
|
|
<span class="device-search-kind">${lt.escHtml(d.kind)}</span>
|
|
<span class="device-search-meta">${lt.escHtml(d.ip || '')}</span>
|
|
<span class="device-search-meta">${lt.escHtml(d.model || '')}</span>
|
|
</a>`).join('');
|
|
input.setAttribute('aria-activedescendant', `device-opt-${active}`);
|
|
}
|
|
|
|
input.addEventListener('input', () => { active = 0; render(); });
|
|
input.addEventListener('focus', () => { loadDevices().then(render); });
|
|
input.addEventListener('keydown', e => {
|
|
if (e.key === 'Escape') { close(); return; }
|
|
if (!matches.length) return;
|
|
if (e.key === 'ArrowDown') { e.preventDefault(); active = (active + 1) % matches.length; render(); }
|
|
if (e.key === 'ArrowUp') { e.preventDefault(); active = (active - 1 + matches.length) % matches.length; render(); }
|
|
if (e.key === 'Enter') { e.preventDefault(); window.location.href = matches[active].url || deviceUrl(matches[active].name); }
|
|
});
|
|
document.addEventListener('click', e => {
|
|
if (!e.target.closest('#device-search')) close();
|
|
});
|
|
document.addEventListener('keydown', e => {
|
|
const typing = e.target.closest('input, textarea, select, [contenteditable]');
|
|
if (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey) {
|
|
e.preventDefault();
|
|
input.focus();
|
|
}
|
|
});
|
|
loadDevices();
|
|
}
|
|
|
|
// ── WAN modem / fiber panel ───────────────────────────────────────────
|
|
async function refreshModem() {
|
|
try {
|
|
updateModem(await lt.api.get('/api/modem'));
|
|
} catch (err) {
|
|
console.warn('Modem data unavailable', err);
|
|
}
|
|
}
|
|
|
|
function _modemUptime(seconds) {
|
|
if (seconds === null || seconds === undefined) return '-';
|
|
const d = Math.floor(seconds / 86400);
|
|
const h = Math.floor((seconds % 86400) / 3600);
|
|
const m = Math.floor((seconds % 3600) / 60);
|
|
return d ? `${d}d ${h}h` : `${h}h ${m}m`;
|
|
}
|
|
|
|
function _modemRate(bytesPerSec) {
|
|
if (bytesPerSec === null || bytesPerSec === undefined) return '-';
|
|
const mbps = bytesPerSec * 8 / 1e6;
|
|
return mbps >= 1000 ? `${(mbps / 1000).toFixed(2)} Gbps` : `${mbps.toFixed(1)} Mbps`;
|
|
}
|
|
|
|
function _modemStat(label, value, cls, note) {
|
|
return `
|
|
<div class="modem-stat">
|
|
<span class="modem-stat-label">${lt.escHtml(label)}</span>
|
|
<span class="modem-stat-value ${cls || ''}">${lt.escHtml(String(value))}</span>
|
|
${note ? `<span class="modem-stat-note">${lt.escHtml(note)}</span>` : ''}
|
|
</div>`;
|
|
}
|
|
|
|
function _modemOptic(label, metric, status, unit) {
|
|
if (!metric || metric.value === null || metric.value === undefined) return _modemStat(label, '-');
|
|
const cls = { alarm: 'lt-text-red', warning: 'lt-text-amber', ok: 'lt-text-green' }[status] || '';
|
|
return _modemStat(label, `${metric.value} ${unit}`, cls, `warn ${metric.warn_low} to ${metric.warn_high}`);
|
|
}
|
|
|
|
function _modemChart(history) {
|
|
const points = (history || []).filter(p => p.rx_avg !== null && p.rx_avg !== undefined);
|
|
if (points.length < 2) {
|
|
return '<div class="modem-chart-empty">Rx power trend appears after a few polls.</div>';
|
|
}
|
|
const W = 600, H = 70, PAD = 4;
|
|
const values = points.map(p => p.rx_avg);
|
|
const low = Math.min(...values) - 0.5, high = Math.max(...values) + 0.5;
|
|
const t0 = points[0].ts, tSpan = (points[points.length - 1].ts - t0) || 1;
|
|
const coord = p => `${((p.ts - t0) / tSpan * W).toFixed(1)},` +
|
|
`${(PAD + (high - p.rx_avg) / (high - low) * (H - 2 * PAD)).toFixed(1)}`;
|
|
|
|
// Break the line where samples are missing rather than drawing across an outage
|
|
const gaps = points.slice(1).map((p, i) => p.ts - points[i].ts).sort((a, b) => a - b);
|
|
const maxGap = gaps[Math.floor(gaps.length / 2)] * 3;
|
|
const segments = [[]];
|
|
points.forEach((p, i) => {
|
|
if (i && p.ts - points[i - 1].ts > maxGap) segments.push([]);
|
|
segments[segments.length - 1].push(coord(p));
|
|
});
|
|
const lines = segments
|
|
.map(s => `<polyline points="${s.join(' ')}" fill="none" vector-effect="non-scaling-stroke"/>`)
|
|
.join('');
|
|
const summary = `range ${Math.min(...values)} to ${Math.max(...values)} dBm`;
|
|
return `
|
|
<div class="modem-chart">
|
|
<div class="modem-chart-title">Rx power, last 7 days <span>${lt.escHtml(summary)}</span></div>
|
|
<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img"
|
|
aria-label="Rx power trend, ${lt.escHtml(summary)}">${lines}</svg>
|
|
</div>`;
|
|
}
|
|
|
|
function _modemWhen(epochSeconds) {
|
|
return new Date(epochSeconds * 1000).toLocaleString([], { dateStyle: 'short', timeStyle: 'short' });
|
|
}
|
|
|
|
function _modemLastRestart(history) {
|
|
const restarts = (history && history.restarts) || [];
|
|
if (!restarts.length) return '';
|
|
const last = restarts[restarts.length - 1];
|
|
return `restarted ${_modemWhen(last.at)}${last.by ? ` by ${last.by}` : ''}`;
|
|
}
|
|
|
|
function _modemUptimeStat(data) {
|
|
if (data.uptime_s !== null && data.uptime_s !== undefined) {
|
|
return _modemStat('Uptime', _modemUptime(data.uptime_s), '', _modemLastRestart(data.wan_history));
|
|
}
|
|
const restarts = (data.wan_history && data.wan_history.restarts) || [];
|
|
if (!restarts.length) return '';
|
|
const last = restarts[restarts.length - 1];
|
|
return _modemStat('Last restart', _modemWhen(last.at), '', last.by ? `by ${last.by}` : '');
|
|
}
|
|
|
|
const _PING_VERDICTS = {
|
|
upstream: "the modem's own ping is slow: the delay is past the router",
|
|
lan: 'the hop to the modem is slow: router, cable or modem LAN port',
|
|
gateway: "modem's own ping fine, ours slow: modem forwarding or the router's WAN side",
|
|
clear: 'fine',
|
|
};
|
|
|
|
// Logged-in checks: NAT sessions in use, and the latest ping run from the modem itself
|
|
function _modemChecks(c) {
|
|
if (!c) return '';
|
|
const ago = at => lt.time.ago(new Date(at * 1000));
|
|
let out = '';
|
|
if (c.nat && c.nat.available) {
|
|
const pct = Math.round(100 * c.nat.in_use / c.nat.available);
|
|
out += _modemStat('NAT sessions', `${c.nat.in_use.toLocaleString()} / ${c.nat.available.toLocaleString()}`,
|
|
pct >= 80 ? 'lt-text-amber' : '', `${pct}% in use, ${ago(c.nat.at)}`);
|
|
}
|
|
if (c.ping) {
|
|
const p = c.ping;
|
|
const value = p.avg_ms === null || p.avg_ms === undefined ? 'no reply' : `${Math.round(p.avg_ms)} ms`;
|
|
const verdict = _PING_VERDICTS[p.verdict] || '';
|
|
const ours = p.ours_ms === null || p.ours_ms === undefined ? '' : `; ours through the router ${Math.round(p.ours_ms)} ms`;
|
|
out += _modemStat("Modem's own ping", value, p.verdict === 'clear' ? '' : 'lt-text-amber',
|
|
`to ${p.target}${ours}, ${ago(p.at)}${verdict ? `: ${verdict}` : ''}`);
|
|
}
|
|
const fw = c.firewall && c.firewall.hours;
|
|
if (fw && Object.keys(fw).length) {
|
|
const day = Object.keys(fw).sort().slice(-24).map(k => fw[k]);
|
|
const sum = k => day.reduce((n, h) => n + (h[k] || 0), 0);
|
|
const flood = sum('flood'), invalid = sum('invalid'), total = flood + invalid + sum('other');
|
|
out += _modemStat('Firewall drops', `${total.toLocaleString()} in ${day.length} h`, '',
|
|
`${flood.toLocaleString()} incoming over the flood limit, ${invalid.toLocaleString()} invalid; ` +
|
|
'at least (the log keeps 1 per 2 s)');
|
|
}
|
|
const busiest = c.nat && (c.nat.inbound || [])[0];
|
|
if (busiest) {
|
|
out += _modemStat('Busiest inbound port', `${String(busiest.proto).toUpperCase()} ${busiest.port}`,
|
|
'', `${busiest.sessions.toLocaleString()} sessions from ${busiest.sources.toLocaleString()} addresses, ${ago(c.nat.at)}`);
|
|
}
|
|
const sp = c.speed;
|
|
if (sp && sp.down && sp.up) {
|
|
out += _modemStat('AT&T speed test', `↓ ${Math.round(sp.down.mbps)} ↑ ${Math.round(sp.up.mbps)} Mbps`, '',
|
|
`run by the modem ${sp.down.at}, ${Math.round(sp.down.latency_ms)} ms`);
|
|
}
|
|
if (c.error && c.error.login) {
|
|
out += _modemStat('Modem login', 'failed', 'lt-text-red', 'check modem.access_code');
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function _modemDuration(seconds) {
|
|
if (seconds < 60) return `${Math.round(seconds)}s`;
|
|
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
|
|
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
|
|
}
|
|
|
|
function _modemOutages(history) {
|
|
const outages = ((history && history.outages) || []).slice(-5).reverse();
|
|
if (!outages.length) return '';
|
|
const rows = outages.map(o => {
|
|
const length = o.restored_at === null || o.restored_at === undefined
|
|
? '<span class="lt-text-red">ongoing</span>'
|
|
: lt.escHtml(_modemDuration(o.restored_at - o.failed_at));
|
|
return `<li><span>${lt.escHtml(_modemWhen(o.failed_at))}</span><span>${length}</span></li>`;
|
|
}).join('');
|
|
return `
|
|
<div class="modem-outages">
|
|
<div class="modem-chart-title">Recent WAN outages</div>
|
|
<ul>${rows}</ul>
|
|
</div>`;
|
|
}
|
|
|
|
const _QUALITY_LABELS = { ok: 'fine', latency: 'high latency', loss: 'packet loss', down: 'down' };
|
|
|
|
// UniFi's own internet health timeline, one block per 5 minutes, worst flag wins
|
|
function _modemQuality(q) {
|
|
const periods = (q && q.periods) || [];
|
|
if (!periods.length) return '';
|
|
const counts = { ok: 0, latency: 0, loss: 0, down: 0 };
|
|
periods.forEach(p => { if (p.state in counts) counts[p.state] += 1; });
|
|
const t0 = periods[0].ts, span = Math.max(periods[periods.length - 1].ts + 300 - t0, 300);
|
|
const blocks = periods.map(p => {
|
|
const x = (p.ts - t0) / span * 1000, w = Math.max(300 / span * 1000, 1);
|
|
const tip = `${_modemWhen(p.ts)}: ${_QUALITY_LABELS[p.state] || p.state}`;
|
|
return `<rect class="wq-${lt.escHtml(p.state)}" x="${x.toFixed(1)}" y="0" width="${w.toFixed(2)}" height="20">` +
|
|
`<title>${lt.escHtml(tip)}</title></rect>`;
|
|
}).join('');
|
|
const flagged = ['latency', 'loss', 'down'].filter(s => counts[s])
|
|
.map(s => `${_QUALITY_LABELS[s]} ${counts[s]}`).join(', ');
|
|
const summary = flagged ? `${flagged} of ${periods.length} periods` : 'no problems';
|
|
const lat = Object.entries(q.latencies || {}).sort()
|
|
.map(([k, v]) => `${lt.escHtml(k)} ${lt.escHtml(String(v))} ms`).join(', ');
|
|
const legend = ['latency', 'loss', 'down']
|
|
.map(s => `<span><i class="wq-key wq-${s}"></i>${_QUALITY_LABELS[s]}</span>`).join('');
|
|
return `
|
|
<div class="modem-chart modem-quality">
|
|
<div class="modem-chart-title">Internet, last 24 hours (from UniFi) <span>${lt.escHtml(summary)}</span></div>
|
|
<svg viewBox="0 0 1000 20" preserveAspectRatio="none" role="img"
|
|
aria-label="Internet health over the last 24 hours: ${lt.escHtml(summary)}">${blocks}</svg>
|
|
<div class="wq-foot"><span>${lt.escHtml(_modemWhen(t0))}</span>
|
|
<span class="wq-legend">${legend}</span><span>now</span></div>
|
|
${lat ? `<div class="modem-stat-note">Latency now: ${lat}</div>` : ''}
|
|
</div>`;
|
|
}
|
|
|
|
// Flood limit: the modem drops new incoming connections over 50 a second and logs at most
|
|
// one every 2 s (about 1,800 an hour). Hours near that ceiling mean the limit was full.
|
|
const _FLOOD_FULL = 1500, _FLOOD_CEILING = 1800;
|
|
|
|
function _modemFloodChart(c) {
|
|
const hours = c && c.firewall && c.firewall.hours;
|
|
const keys = hours ? Object.keys(hours).sort() : [];
|
|
if (keys.length < 2) return '';
|
|
const counts = keys.map(k => hours[k].flood || 0);
|
|
let run = 0;
|
|
for (let i = counts.length - 2; i >= 0 && counts[i] >= _FLOOD_FULL; i--) run += 1; // the newest hour is still filling
|
|
const peak = Math.max(...counts);
|
|
const summary = run >= 2 ? `full for the last ${run} hours` : (peak >= _FLOOD_FULL ? `full at times, peak ${peak.toLocaleString()} an hour`
|
|
: `peak ${peak.toLocaleString()} an hour`);
|
|
const w = 1000 / keys.length;
|
|
const bars = counts.map((n, i) => {
|
|
const h = Math.min(n, _FLOOD_CEILING) / _FLOOD_CEILING * 40;
|
|
const tip = `${keys[i].replace('T', ' ')}:00 modem time: ${n.toLocaleString()} dropped`;
|
|
return `<rect class="${n >= _FLOOD_FULL ? 'fl-full' : 'fl-ok'}" x="${(i * w).toFixed(2)}" y="${(40 - h).toFixed(2)}" ` +
|
|
`width="${Math.max(w - 0.5, 0.5).toFixed(2)}" height="${h.toFixed(2)}"><title>${lt.escHtml(tip)}</title></rect>`;
|
|
}).join('');
|
|
const line = (40 - _FLOOD_FULL / _FLOOD_CEILING * 40).toFixed(2);
|
|
return `
|
|
<div class="modem-chart modem-flood">
|
|
<div class="modem-chart-title">New incoming connections dropped by the modem's flood limit, per hour
|
|
<span>${lt.escHtml(summary)}</span></div>
|
|
<svg viewBox="0 0 1000 40" preserveAspectRatio="none" role="img"
|
|
aria-label="Flood limit drops per hour: ${lt.escHtml(summary)}">${bars}
|
|
<line class="fl-limit" x1="0" x2="1000" y1="${line}" y2="${line}"/></svg>
|
|
<div class="wq-foot"><span>${lt.escHtml(keys[0].replace('T', ' '))}:00</span>
|
|
<span class="wq-legend"><span><i class="wq-key fl-key-full"></i>limit full (outside connections fail)</span></span>
|
|
<span>now</span></div>
|
|
</div>`;
|
|
}
|
|
|
|
// A restart from the Restart modem button: in progress, or finished in the last hour
|
|
function _modemRestartNote(r) {
|
|
if (!r || !r.at) return '';
|
|
const who = r.by ? ` by ${r.by}` : '';
|
|
const paused = (r.smart_power_paused || []).length;
|
|
if (!r.finished_at) {
|
|
const sp = paused ? ' Smart Power auto power-cycle is paused so it can\'t cut power mid-boot.' : '';
|
|
return `<div class="modem-restart-note">Restart requested${lt.escHtml(who)} ${lt.escHtml(_modemWhen(r.at))}. ` +
|
|
`Alerts are silenced${r.kuma ? ' here and in Uptime Kuma' : ''} until the modem is back.${sp}</div>`;
|
|
}
|
|
if (paused && !r.smart_power_restored) {
|
|
return `<div class="modem-restart-note modem-restart-warn">Restarted${lt.escHtml(who)} ` +
|
|
`${lt.escHtml(_modemWhen(r.at))}, but Smart Power auto power-cycle is still off. ` +
|
|
`Gandalf keeps trying to turn it back on.</div>`;
|
|
}
|
|
if (Date.now() / 1000 - r.finished_at > 3600) return '';
|
|
const how = r.back ? `back after ${_modemDuration(r.back_after_s)}` : 'did not come back within 30 minutes';
|
|
return `<div class="modem-restart-note">Restarted${lt.escHtml(who)} ${lt.escHtml(_modemWhen(r.at))}: ` +
|
|
`${lt.escHtml(how)}. Alerts are on again.</div>`;
|
|
}
|
|
|
|
async function restartModem(btn) {
|
|
const msg = 'Restart the AT&T modem?\n\nThe internet will be down for about 3 to 5 minutes. ' +
|
|
'Gandalf alerts, the Uptime Kuma maintenance window and a Smart Power auto power-cycle pause ' +
|
|
'are switched on first, and switched off again when the modem is back.';
|
|
if (!window.confirm(msg)) return;
|
|
btn.disabled = true;
|
|
try {
|
|
let res;
|
|
try {
|
|
res = await lt.api.post('/api/modem/restart', { confirm: true });
|
|
} catch (err) {
|
|
if (!String(err.message).startsWith('Uptime Kuma:')) throw err;
|
|
if (!window.confirm(`${err.message}\n\nRestart anyway? Uptime Kuma will report the outage.`)) {
|
|
btn.disabled = false;
|
|
return;
|
|
}
|
|
res = await lt.api.post('/api/modem/restart', { confirm: true, without_kuma: true });
|
|
}
|
|
showToast(res.result === 'accepted' ? 'Modem restarting' : 'Restart sent; the modem dropped the connection',
|
|
'success');
|
|
window.location.reload();
|
|
} catch (err) {
|
|
btn.disabled = false;
|
|
showToast(err.message || 'Could not restart the modem', 'error');
|
|
}
|
|
}
|
|
|
|
function updateModem(data) {
|
|
const section = document.getElementById('modem-section');
|
|
const body = document.getElementById('modem-body');
|
|
if (!section || !body) return;
|
|
section.hidden = !data.configured;
|
|
if (!data.configured) return;
|
|
|
|
const restartBtn = document.getElementById('modem-restart-btn');
|
|
if (restartBtn) {
|
|
const pending = data.modem_restart && !data.modem_restart.finished_at;
|
|
restartBtn.hidden = !data.can_restart;
|
|
restartBtn.disabled = Boolean(pending);
|
|
if (!restartBtn.dataset.bound) {
|
|
restartBtn.dataset.bound = '1';
|
|
restartBtn.addEventListener('click', () => restartModem(restartBtn));
|
|
}
|
|
}
|
|
const restartNote = _modemRestartNote(data.modem_restart);
|
|
|
|
// On the dashboard, link to the modem's page. On that page, it would link to itself.
|
|
const detailsLink = document.getElementById('modem-device-link');
|
|
if (detailsLink && typeof DEVICE_NAME === 'undefined' && data.name) {
|
|
detailsLink.href = deviceUrl(data.name);
|
|
detailsLink.hidden = false;
|
|
}
|
|
|
|
const title = document.getElementById('modem-title');
|
|
|
|
if (!data.reachable) {
|
|
body.innerHTML = `${restartNote}
|
|
<div class="modem-error">Modem status unavailable: ${lt.escHtml(data.error || 'unknown error')}
|
|
<span class="modem-stat-note">Last attempt ${lt.escHtml(data.updated || '-')}</span></div>
|
|
${_modemQuality(data.wan_quality)}
|
|
${_modemFloodChart(data.modem_checks)}
|
|
${_modemChart(data.history)}`;
|
|
return;
|
|
}
|
|
|
|
const problems = data.wan_problems || [];
|
|
const optics = data.optics || {};
|
|
const status = data.optics_status || {};
|
|
const counters = data.counters || {};
|
|
const rates = data.rates || {};
|
|
|
|
if (title) {
|
|
title.textContent = [data.model || 'AT&T Gateway', data.firmware && `fw ${data.firmware}`]
|
|
.filter(Boolean).join(' · ');
|
|
}
|
|
|
|
const errs = (counters.rx_errors || 0) + (counters.tx_errors || 0);
|
|
const drops = (counters.rx_drops || 0) + (counters.tx_drops || 0);
|
|
body.innerHTML = `${restartNote}
|
|
${problems.length ? `<div class="modem-error">WAN down: ${lt.escHtml(problems.join('; '))}</div>` : ''}
|
|
<div class="modem-stats">
|
|
${_modemStat('WAN', problems.length ? 'DOWN' : 'UP', problems.length ? 'lt-text-red' : 'lt-text-green',
|
|
data.wan_ip || '')}
|
|
${_modemStat('PON', data.pon_state || '-', '', data.wavelength || '')}
|
|
${_modemOptic('Rx power', optics.rx_power, status.rx_power, 'dBm')}
|
|
${_modemOptic('Tx power', optics.tx_power, status.tx_power, 'dBm')}
|
|
${_modemOptic('Optics temp', optics.temperature, status.temperature, '°C')}
|
|
${_modemStat('Throughput', `↓ ${_modemRate(rates.rx_bytes)}`, '', `↑ ${_modemRate(rates.tx_bytes)}`)}
|
|
${_modemStat('Errors / drops', `${errs} / ${drops}`, errs ? 'lt-text-amber' : '', 'since modem reboot')}
|
|
${_modemUptimeStat(data)}
|
|
${_modemChecks(data.modem_checks)}
|
|
</div>
|
|
${_modemQuality(data.wan_quality)}
|
|
${_modemChart(data.history)}
|
|
${_modemOutages(data.wan_history)}
|
|
<div class="modem-stat-note modem-updated">Updated ${lt.escHtml(data.updated || '-')}</div>`;
|
|
}
|
|
|
|
function updateUnifiTable(devices) {
|
|
const grid = document.getElementById('unifi-grid');
|
|
if (!grid || !devices.length) return;
|
|
const esc = lt.escHtml;
|
|
grid.innerHTML = devices.map(d => `
|
|
<li class="unifi-chip${d.connected ? '' : ' unifi-chip-down'}">
|
|
<span class="${d.connected ? 'dot-up' : 'dot-down'}" title="${d.connected ? 'Online' : 'Offline'}"></span>
|
|
<a class="device-link unifi-chip-name" href="${esc(deviceUrl(d.name))}">${esc(d.name)}</a>
|
|
<span class="unifi-chip-model">${esc(d.model)}</span>
|
|
${d.connected ? '' : `<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress" data-sup-type="unifi_device"
|
|
data-sup-name="${esc(d.name)}" data-sup-detail="" title="Suppress alerts for ${esc(d.name)}"
|
|
aria-label="Suppress alerts for ${esc(d.name)}">🔕</button>`}
|
|
</li>`).join('');
|
|
}
|
|
|
|
function updateEventsTable(events, totalActive) {
|
|
const wrap = document.getElementById('events-table-wrap');
|
|
if (!wrap) return;
|
|
|
|
const active = (events || []).filter(e => e.severity !== 'info');
|
|
if (!active.length) {
|
|
wrap.innerHTML = '<div class="lt-empty-state lt-empty-state--sm"><div class="lt-empty-state-icon">✔</div><div class="lt-empty-state-title">No active alerts</div></div>';
|
|
return;
|
|
}
|
|
|
|
const truncated = totalActive !== null && totalActive !== undefined && totalActive > active.length;
|
|
const countNotice = truncated
|
|
? `<div class="pagination-notice">Showing ${active.length} of ${totalActive} active alerts: <a href="/api/events?limit=1000">view all via API</a></div>`
|
|
: '';
|
|
|
|
const rows = active.map(e => {
|
|
const supType = e.event_type === 'unifi_device_offline' ? 'unifi_device'
|
|
: e.event_type === 'interface_down' ? 'interface'
|
|
: 'host';
|
|
const ticketBase = (typeof GANDALF_CONFIG !== 'undefined' && GANDALF_CONFIG.ticket_web_url)
|
|
? GANDALF_CONFIG.ticket_web_url : 'http://t.lotusguild.org/ticket/';
|
|
const ticket = e.ticket_id
|
|
? `<a href="${lt.escHtml(ticketBase)}${lt.escHtml(String(e.ticket_id))}" target="_blank"
|
|
class="ticket-link">#${lt.escHtml(String(e.ticket_id))}</a>`
|
|
: '-';
|
|
const supBadge = e.is_suppressed
|
|
? `<span class="lt-badge badge-suppressed" title="Alert suppressed">🔕 sup</span>`
|
|
: '';
|
|
const staleBadge = (e.stale_days !== null && e.stale_days !== undefined)
|
|
? `<span class="lt-badge badge-stale" title="Active for ${Number(e.stale_days)} days with no fix yet">⏳ ${Number(e.stale_days)}d</span>`
|
|
: '';
|
|
const closedBadge = e.ticket_closed
|
|
? `<span class="lt-badge badge-ticket-closed" title="Ticket #${lt.escHtml(String(e.ticket_id))} was closed in Tinker, but this alert is still active">ticket closed</span>`
|
|
: '';
|
|
return `
|
|
<tr class="row-${e.severity}${e.is_suppressed ? ' row-suppressed' : ''}">
|
|
<td data-label="Sev"><span class="lt-badge badge-${e.severity}">${e.severity}</span>${supBadge}${staleBadge}${closedBadge}</td>
|
|
<td data-label="Type">${lt.escHtml(e.event_type.replace(/_/g,' '))}</td>
|
|
<td data-label="Target"><strong>${lt.escHtml(e.target_name)}</strong></td>
|
|
<td data-label="Detail">${lt.escHtml(e.target_detail || '-')}</td>
|
|
<td data-label="Description" class="desc-cell" title="${lt.escHtml(e.description || '')}">${lt.escHtml((e.description||'').substring(0,60))}${(e.description||'').length>60?'…':''}</td>
|
|
<td data-label="First seen" class="ts-cell" title="${lt.escHtml(e.first_seen||'')}">${lt.time.ago(_toIso(e.first_seen))}</td>
|
|
<td data-label="Last seen" class="ts-cell" title="${lt.escHtml(e.last_seen||'')}">${lt.time.ago(_toIso(e.last_seen))}</td>
|
|
<td data-label="Failures">${e.consecutive_failures}</td>
|
|
<td data-label="Ticket">${ticket}</td>
|
|
<td data-label="Actions">
|
|
<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress"
|
|
data-sup-type="${lt.escHtml(supType)}"
|
|
data-sup-name="${lt.escHtml(e.target_name)}"
|
|
data-sup-detail="${lt.escHtml(e.target_detail||'')}"
|
|
aria-label="Suppress alert for ${lt.escHtml(e.target_name)}">🔕</button>
|
|
</td>
|
|
</tr>`;
|
|
}).join('');
|
|
|
|
wrap.innerHTML = `
|
|
${countNotice}
|
|
<div class="lt-table-wrap">
|
|
<table class="lt-table lt-table-responsive" id="events-table">
|
|
<caption class="lt-sr-only">Active network alerts</caption>
|
|
<thead>
|
|
<tr>
|
|
<th>Sev</th><th>Type</th><th>Target</th><th>Detail</th>
|
|
<th>Description</th><th>First Seen</th><th>Last Seen</th><th>Failures</th><th>Ticket</th><th>Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>${rows}</tbody>
|
|
</table>
|
|
</div>`;
|
|
}
|
|
|
|
// ── Needs follow-up: tickets left open after their alert cleared ──────
|
|
function updateFollowUp(tickets) {
|
|
const section = document.getElementById('followup');
|
|
const tbody = document.querySelector('#followup-table tbody');
|
|
if (!section || !tbody) return;
|
|
section.hidden = !tickets.length;
|
|
const badge = document.getElementById('followup-badge');
|
|
if (badge) badge.textContent = tickets.length;
|
|
const ticketBase = (typeof GANDALF_CONFIG !== 'undefined' && GANDALF_CONFIG.ticket_web_url)
|
|
? GANDALF_CONFIG.ticket_web_url : 'http://t.lotusguild.org/ticket/';
|
|
tbody.innerHTML = tickets.map(t => `
|
|
<tr>
|
|
<td><a href="${lt.escHtml(ticketBase)}${lt.escHtml(String(t.ticket_id))}" target="_blank" rel="noopener"
|
|
class="ticket-link">#${lt.escHtml(String(t.ticket_id))}</a></td>
|
|
<td><strong>${lt.escHtml(t.target_name || '')}</strong></td>
|
|
<td>${lt.escHtml((t.event_type || '').replace(/_/g, ' '))}${t.target_detail
|
|
? ` <span class="lt-text-muted">${lt.escHtml(t.target_detail)}</span>` : ''}</td>
|
|
<td class="ts-cell" title="${lt.escHtml(t.cleared_at || '')}">${lt.time.ago(_toIso(t.cleared_at))}</td>
|
|
<td>${Number(t.events) || 0}</td>
|
|
</tr>`).join('');
|
|
}
|
|
|
|
// ── Suppression modal ─────────────────────────────────────────────────
|
|
function openSuppressModal(type, name, detail) {
|
|
const modal = document.getElementById('suppress-modal');
|
|
if (!modal) return;
|
|
|
|
document.getElementById('sup-type').value = type;
|
|
document.getElementById('sup-name').value = name;
|
|
document.getElementById('sup-detail').value = detail;
|
|
document.getElementById('sup-reason').value = '';
|
|
document.getElementById('sup-expires').value = '';
|
|
|
|
updateSuppressForm();
|
|
lt.modal.open('suppress-modal');
|
|
|
|
document.querySelectorAll('#suppress-modal .pill').forEach(p => {
|
|
p.classList.remove('active');
|
|
p.setAttribute('aria-pressed', 'false');
|
|
});
|
|
const manualPill = document.querySelector('#suppress-modal .pill-manual');
|
|
if (manualPill) { manualPill.classList.add('active'); manualPill.setAttribute('aria-pressed', 'true'); }
|
|
const hint = document.getElementById('duration-hint');
|
|
if (hint) hint.textContent = 'Suppression will persist until manually removed.';
|
|
}
|
|
|
|
function closeSuppressModal() {
|
|
lt.modal.close('suppress-modal');
|
|
}
|
|
|
|
function updateSuppressForm() {
|
|
const type = document.getElementById('sup-type').value;
|
|
const nameGrp = document.getElementById('sup-name-group');
|
|
const detailGrp = document.getElementById('sup-detail-group');
|
|
const nameInput = document.getElementById('sup-name');
|
|
const detailInput = document.getElementById('sup-detail');
|
|
if (nameGrp) nameGrp.style.display = (type === 'all') ? 'none' : '';
|
|
if (detailGrp) detailGrp.style.display = (type === 'interface') ? '' : 'none';
|
|
if (nameInput) {
|
|
const req = (type !== 'all');
|
|
nameInput.required = req;
|
|
nameInput.setAttribute('aria-required', String(req));
|
|
}
|
|
if (detailInput) {
|
|
const req = (type === 'interface');
|
|
detailInput.required = req;
|
|
detailInput.setAttribute('aria-required', String(req));
|
|
}
|
|
}
|
|
|
|
function setDuration(mins, el, opts) {
|
|
const o = opts || {};
|
|
const expiresEl = document.getElementById(o.expiresId || 'sup-expires');
|
|
const pillSel = o.pillSel || '#suppress-modal .pill';
|
|
const hint = document.getElementById(o.hintId || 'duration-hint');
|
|
if (expiresEl) expiresEl.value = mins || '';
|
|
document.querySelectorAll(pillSel).forEach(p => {
|
|
p.classList.remove('active');
|
|
p.setAttribute('aria-pressed', 'false');
|
|
});
|
|
if (el) { el.classList.add('active'); el.setAttribute('aria-pressed', 'true'); }
|
|
if (hint) {
|
|
if (mins) {
|
|
const h = Math.floor(mins / 60), m = mins % 60;
|
|
hint.textContent = `Expires in ${h ? h + 'h ' : ''}${m ? m + 'm' : ''}.`;
|
|
} else {
|
|
hint.textContent = 'Suppression will persist until manually removed.';
|
|
}
|
|
}
|
|
}
|
|
|
|
async function submitSuppress(e) {
|
|
e.preventDefault();
|
|
const type = document.getElementById('sup-type').value;
|
|
const name = document.getElementById('sup-name').value;
|
|
const detail = document.getElementById('sup-detail').value;
|
|
const reason = document.getElementById('sup-reason').value;
|
|
const expires = document.getElementById('sup-expires').value;
|
|
|
|
if (!reason.trim()) { showToast('Reason is required', 'error'); return; }
|
|
if (type !== 'all' && !name.trim()) { showToast('Target name is required', 'error'); return; }
|
|
|
|
try {
|
|
await lt.api.post('/api/suppressions', {
|
|
target_type: type,
|
|
target_name: name,
|
|
target_detail: detail,
|
|
reason,
|
|
expires_minutes: expires ? parseInt(expires) : null,
|
|
});
|
|
closeSuppressModal();
|
|
showToast('Suppression applied ✔', 'success');
|
|
setTimeout(refreshAll, 500);
|
|
} catch (err) {
|
|
showToast(err.message || 'Failed to apply suppression', 'error');
|
|
}
|
|
}
|
|
|
|
// ── Suppress form: wired here so the modal works from any page ──────
|
|
document.getElementById('suppress-form')?.addEventListener('submit', submitSuppress);
|
|
document.getElementById('sup-type')?.addEventListener('change', updateSuppressForm);
|
|
|
|
// ── Global click delegation ───────────────────────────────────────────
|
|
document.addEventListener('click', e => {
|
|
// Refresh button
|
|
if (e.target.closest('[data-action="refresh"]')) {
|
|
lt.autoRefresh.now();
|
|
return;
|
|
}
|
|
|
|
// Duration pills (data-duration="" = manual/forever)
|
|
const pill = e.target.closest('.pill[data-duration]');
|
|
if (pill) {
|
|
const val = pill.dataset.duration;
|
|
setDuration(val ? parseInt(val) : null, pill);
|
|
return;
|
|
}
|
|
|
|
// Suppress buttons
|
|
const btn = e.target.closest('.btn-suppress[data-sup-type]');
|
|
if (btn) {
|
|
openSuppressModal(
|
|
btn.dataset.supType || '',
|
|
btn.dataset.supName || '',
|
|
btn.dataset.supDetail || '',
|
|
);
|
|
}
|
|
});
|
|
|
|
// ── Maintenance: pause every ticket for a while (a global suppression with an expiry) ──
|
|
(function () {
|
|
const until = document.querySelector('.maint-banner .maint-until');
|
|
if (until) {
|
|
const t = new Date(until.getAttribute('datetime'));
|
|
if (!isNaN(t)) {
|
|
const sameDay = t.toDateString() === new Date().toDateString();
|
|
until.textContent = sameDay
|
|
? t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
|
|
: t.toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' });
|
|
until.title = t.toLocaleString();
|
|
}
|
|
}
|
|
|
|
let minutes = 60;
|
|
document.addEventListener('click', async e => {
|
|
if (e.target.closest('[data-action="start-maintenance"]')) {
|
|
lt.modal.open('maint-modal');
|
|
document.getElementById('maint-reason')?.focus();
|
|
return;
|
|
}
|
|
const pill = e.target.closest('.maint-pill');
|
|
if (pill) {
|
|
minutes = parseInt(pill.dataset.minutes, 10);
|
|
document.querySelectorAll('.maint-pill').forEach(p => {
|
|
const on = p === pill;
|
|
p.classList.toggle('active', on);
|
|
p.setAttribute('aria-pressed', String(on));
|
|
});
|
|
return;
|
|
}
|
|
const end = e.target.closest('[data-action="end-maintenance"]');
|
|
if (end) {
|
|
end.disabled = true;
|
|
try {
|
|
await lt.api.delete(`/api/suppressions/${encodeURIComponent(end.dataset.supId)}`);
|
|
window.location.reload();
|
|
} catch (err) {
|
|
end.disabled = false;
|
|
showToast(err.message || 'Could not end maintenance', 'error');
|
|
}
|
|
}
|
|
});
|
|
|
|
document.getElementById('maint-form')?.addEventListener('submit', async e => {
|
|
e.preventDefault();
|
|
const reason = (document.getElementById('maint-reason').value || '').trim();
|
|
if (!reason) { showToast('Reason is required', 'error'); return; }
|
|
const submit = e.target.querySelector('[type="submit"]');
|
|
submit.disabled = true;
|
|
try {
|
|
await lt.api.post('/api/suppressions', {
|
|
target_type: 'all', target_name: '', reason, expires_minutes: minutes,
|
|
});
|
|
window.location.reload();
|
|
} catch (err) {
|
|
submit.disabled = false;
|
|
showToast(err.message || 'Could not start maintenance', 'error');
|
|
}
|
|
});
|
|
})();
|