- FastAPI app med 7 bundled module-typer (proxmox, esxi, truenas, splunk, linux, windows, http-json) - Multi-instance support: flere instanser af samme modultype med adskilte assets - Community/Enterprise licensing med admin enterprise-toggle - Capacity forecasting, trends, what-if simulator, alert policies - MCP server + LLM copilot integration - Dockerfile + rune.yaml til Yggdrasil
2732 lines
155 KiB
JavaScript
2732 lines
155 KiB
JavaScript
/* ==========================================================================
|
||
Headroom frontend — no build step, ES modules only.
|
||
========================================================================== */
|
||
import { lineChart, ring, sparkline, bandColor } from './charts.js';
|
||
|
||
const app = document.getElementById('app');
|
||
const bootEl = document.getElementById('boot');
|
||
const modalRoot = document.getElementById('modal-root');
|
||
const toastRoot = document.getElementById('toast-root');
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Icons
|
||
-------------------------------------------------------------------------- */
|
||
const ICONS = {
|
||
dashboard: '<rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/>',
|
||
server: '<rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/>',
|
||
chart: '<path d="M3 3v18h18"/><path d="m7 14 4-4 3 3 5-6"/>',
|
||
bell: '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/>',
|
||
plug: '<path d="M12 22v-5"/><path d="M9 7V2"/><path d="M15 7V2"/><path d="M6 7h12v4a6 6 0 0 1-12 0Z"/>',
|
||
sparkles: '<path d="m12 3 1.9 4.6L18.5 9.5l-4.6 1.9L12 16l-1.9-4.6L5.5 9.5l4.6-1.9Z"/><path d="M18 15l.9 2.1L21 18l-2.1.9L18 21l-.9-2.1L15 18l2.1-.9Z"/>',
|
||
code: '<path d="m8 6-6 6 6 6"/><path d="m16 6 6 6-6 6"/>',
|
||
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.7 1.7 0 0 0-1.87-.34 1.7 1.7 0 0 0-1 1.55V21a2 2 0 1 1-4 0v-.09a1.7 1.7 0 0 0-1.11-1.55 1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.55-1H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 8.9a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-1.55V3a2 2 0 1 1 4 0v.09a1.7 1.7 0 0 0 1 1.55 1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.7 1.7 0 0 0 19.4 9c.14.6.66 1 1.28 1H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51 1Z"/>',
|
||
search: '<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>',
|
||
refresh: '<path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/>',
|
||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||
x: '<path d="M18 6 6 18M6 6l12 12"/>',
|
||
play: '<path d="m8 5 11 7-11 7Z"/>',
|
||
check: '<path d="m20 6-11 11-5-5"/>',
|
||
upload: '<path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/>',
|
||
trash: '<path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v5M14 11v5"/>',
|
||
logout: '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5"/><path d="M21 12H9"/>',
|
||
shield: '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-4"/>',
|
||
arrowRight: '<path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>',
|
||
arrowLeft: '<path d="M19 12H5"/><path d="m11 18-6-6 6-6"/>',
|
||
arrowUp: '<path d="M12 19V5"/><path d="m5 12 7-7 7 7"/>',
|
||
arrowDown: '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
|
||
menu: '<path d="M4 6h16M4 12h16M4 18h16"/>',
|
||
alert: '<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4M12 17h.01"/>',
|
||
info: '<circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/>',
|
||
database: '<ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"/><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/>',
|
||
layers: '<path d="m12 2 9 5-9 5-9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/>',
|
||
network: '<rect x="9" y="2" width="6" height="6" rx="1"/><rect x="2" y="16" width="6" height="6" rx="1"/><rect x="16" y="16" width="6" height="6" rx="1"/><path d="M12 8v4M5 16v-2h14v2"/>',
|
||
bolt: '<path d="M13 2 3 14h9l-1 8 10-12h-9l1-8Z"/>',
|
||
box: '<path d="M21 8v8a2 2 0 0 1-1 1.7l-7 4a2 2 0 0 1-2 0l-7-4A2 2 0 0 1 3 16V8a2 2 0 0 1 1-1.7l7-4a2 2 0 0 1 2 0l7 4A2 2 0 0 1 21 8Z"/><path d="m3.3 7 8.7 5 8.7-5M12 22V12"/>',
|
||
key: '<circle cx="7.5" cy="15.5" r="4.5"/><path d="m10.8 12.2 8.2-8.2M15 4l3 3M18 7l2-2"/>',
|
||
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
|
||
copy: '<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/>',
|
||
download: '<path d="M12 3v12"/><path d="m17 10-5 5-5-5"/><path d="M4 21h16"/>',
|
||
external: '<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5"/>',
|
||
cpu: '<rect x="6" y="6" width="12" height="12" rx="2"/><rect x="9" y="9" width="6" height="6" rx="1"/><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4"/>',
|
||
lock: '<rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
|
||
list: '<path d="M8 6h13M8 12h13M8 18h13"/><path d="M3 6h.01M3 12h.01M3 18h.01"/>',
|
||
cap: '<path d="M2 9h20M4 9v6a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1V9"/><path d="M7 5l5 4 5-4"/>',
|
||
chevronDown: '<path d="m6 9 6 6 6-6"/>',
|
||
minus: '<path d="M5 12h14"/>',
|
||
activity: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
|
||
filter: '<path d="M4 5h16l-6 7v5l-4 2v-7Z"/>',
|
||
dollar: '<path d="M12 2v20"/><path d="M17 6.5c0-2-2-3.5-5-3.5s-5 1.3-5 3.3c0 5 10 2.2 10 7.4 0 2.2-2 3.8-5 3.8s-5-1.5-5-3.5"/>',
|
||
mail: '<rect x="2" y="4" width="20" height="16" rx="2"/><path d="m2 7 10 6 10-6"/>',
|
||
git: '<circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M6 8.5V15a3 3 0 0 0 3 3h6.5"/>',
|
||
terminal: '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>',
|
||
spark: '<path d="M12 2v4M12 18v4M2 12h4M18 12h4M5 5l3 3M16 16l3 3M19 5l-3 3M8 16l-3 3"/>',
|
||
};
|
||
|
||
const BRAND_SVG = `<svg viewBox="0 0 64 64" aria-hidden="true"><path d="M12 44a20 20 0 0 1 40 0" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"/><path d="M32 44l11-15" stroke="#e8f0f4" stroke-width="4" stroke-linecap="round"/><circle cx="32" cy="44" r="4" fill="#e8f0f4"/></svg>`;
|
||
|
||
function icon(name, cls = 'ic') {
|
||
return `<svg class="${cls}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[name] || ICONS.plug}</svg>`;
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Utilities
|
||
-------------------------------------------------------------------------- */
|
||
const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
|
||
const META = () => state.boot?.meta || { metrics: {}, asset_types: {}, util_metrics: [] };
|
||
const METRICS = () => META().metrics || {};
|
||
const TYPES = () => META().asset_types || {};
|
||
|
||
const BAND_LABELS = { healthy: 'Healthy', watch: 'Watch', tight: 'Tight', critical: 'Critical', unknown: 'No data' };
|
||
|
||
function band(value) {
|
||
if (value == null || Number.isNaN(Number(value))) return 'unknown';
|
||
const n = Number(value);
|
||
if (n >= 90) return 'critical';
|
||
if (n >= 80) return 'tight';
|
||
if (n >= 60) return 'watch';
|
||
return 'healthy';
|
||
}
|
||
|
||
function trimNum(value, digits = 1) {
|
||
if (value == null || Number.isNaN(Number(value))) return '—';
|
||
const n = Number(value);
|
||
const fixed = n.toFixed(digits);
|
||
return fixed.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1');
|
||
}
|
||
|
||
function pct(value, digits = 1) {
|
||
if (value == null || Number.isNaN(Number(value))) return '—';
|
||
return `${trimNum(value, digits)}%`;
|
||
}
|
||
|
||
function gb(value) {
|
||
if (value == null || Number.isNaN(Number(value))) return '—';
|
||
const n = Number(value);
|
||
if (Math.abs(n) >= 1024) return `${trimNum(n / 1024, n >= 10240 ? 0 : 1)} TB`;
|
||
return `${trimNum(n, 0)} GB`;
|
||
}
|
||
|
||
function days(value) {
|
||
if (value == null || Number.isNaN(Number(value))) return '—';
|
||
const n = Number(value);
|
||
if (n < 1) return '<1 day';
|
||
if (n < 45) return `${Math.round(n)} days`;
|
||
if (n < 365) return `${trimNum(n / 30.44, 1)} months`;
|
||
return `${trimNum(n / 365, 1)} years`;
|
||
}
|
||
|
||
function timeAgo(value) {
|
||
if (!value) return 'never';
|
||
const t = new Date(value).getTime();
|
||
if (!Number.isFinite(t)) return '—';
|
||
const seconds = Math.max(0, Math.round((Date.now() - t) / 1000));
|
||
if (seconds < 60) return `${seconds}s ago`;
|
||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
||
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
||
if (seconds < 86400 * 30) return `${Math.floor(seconds / 86400)}d ago`;
|
||
return new Date(t).toLocaleDateString();
|
||
}
|
||
|
||
function fmtDate(value, withTime = false) {
|
||
if (!value) return '—';
|
||
const date = new Date(value);
|
||
if (Number.isNaN(date.getTime())) return String(value);
|
||
return date.toLocaleString([], withTime ? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' } : { year: 'numeric', month: 'short', day: 'numeric' });
|
||
}
|
||
|
||
function metricMeta(key) {
|
||
return METRICS()[key] || { label: key, unit: '', kind: 'other' };
|
||
}
|
||
|
||
function metricValue(key, value) {
|
||
if (value == null) return '—';
|
||
const meta = metricMeta(key);
|
||
const unit = meta.unit || '';
|
||
const n = Number(value);
|
||
if (unit === '%') return `${trimNum(n, 1)}%`;
|
||
const formatted = Math.abs(n) >= 1000 ? Math.round(n).toLocaleString() : trimNum(n, 2);
|
||
return unit ? `${formatted} ${unit}` : formatted;
|
||
}
|
||
|
||
function statusPill(status, label = '') {
|
||
const key = status || 'unknown';
|
||
return `<span class="pill ${esc(key)}" title="${esc(label)}">${esc(BAND_LABELS[key] || label || key)}</span>`;
|
||
}
|
||
|
||
const ASSET_ICON = { hypervisor: 'server', storage: 'database', nas: 'database', appliance: 'box', network: 'network', power: 'bolt', server: 'server', cluster: 'layers' };
|
||
const MODULE_ICON = { proxmox: 'layers', esxi: 'server', splunk: 'chart', truenas: 'database', linux: 'terminal', windows: 'server', 'http-json': 'code' };
|
||
const typeIcon = (type) => icon(ASSET_ICON[type] || 'server');
|
||
const assetHref = (id) => `#/assets/${encodeURIComponent(id)}`;
|
||
const trendCell = (asset) => {
|
||
const slope = Number(asset?.slope_per_day || 0);
|
||
if (Math.abs(slope) < 0.02) return `<span class="trend">${icon('minus')} stable</span>`;
|
||
const up = slope > 0;
|
||
return `<span class="trend ${up ? 'up' : 'down'}">${icon(up ? 'arrowUp' : 'arrowDown')} ${trimNum(Math.abs(slope), 2)} pp/d</span>`;
|
||
};
|
||
const moduleName = (id) => (state.boot?.meta ? id : id);
|
||
|
||
/* --------------------------------------------------------------------------
|
||
State
|
||
-------------------------------------------------------------------------- */
|
||
const state = {
|
||
boot: null,
|
||
route: { name: 'overview', id: null },
|
||
windowDays: 7,
|
||
renderToken: 0,
|
||
assetFilters: { q: '', type: '', module: '' },
|
||
alertResolved: false,
|
||
apiTab: 'rest',
|
||
settingsTab: 'general',
|
||
chat: [],
|
||
chatLoading: false,
|
||
simResult: null,
|
||
assetMetric: null,
|
||
pollTimer: null,
|
||
};
|
||
|
||
/* --------------------------------------------------------------------------
|
||
API
|
||
-------------------------------------------------------------------------- */
|
||
function parseError(data, status) {
|
||
const detail = data && data.detail;
|
||
if (detail && typeof detail === 'object') return { message: detail.message || `Request failed (${status})`, code: detail.code, feature: detail.feature, detail };
|
||
return { message: typeof detail === 'string' ? detail : `Request failed (${status})`, code: null, feature: null, detail };
|
||
}
|
||
|
||
async function request(path, options = {}) {
|
||
const opts = { credentials: 'same-origin', ...options };
|
||
const isForm = opts.body instanceof FormData;
|
||
opts.headers = { ...(isForm ? {} : { 'Content-Type': 'application/json' }), ...(options.headers || {}) };
|
||
const response = await fetch(`/api${path}`, opts);
|
||
const type = response.headers.get('content-type') || '';
|
||
const data = type.includes('json') ? await response.json().catch(() => null) : await response.text();
|
||
if (!response.ok) {
|
||
const error = parseError(data, response.status);
|
||
if (response.status === 401 && state.boot) showLogin();
|
||
if (response.status === 402) openUpgrade(error.feature);
|
||
const err = new Error(error.message);
|
||
err.status = response.status;
|
||
err.code = error.code;
|
||
err.feature = error.feature;
|
||
throw err;
|
||
}
|
||
return data;
|
||
}
|
||
|
||
const get = (path) => request(path);
|
||
const post = (path, body) => request(path, { method: 'POST', body: body === undefined ? undefined : JSON.stringify(body) });
|
||
const put = (path, body) => request(path, { method: 'PUT', body: JSON.stringify(body) });
|
||
const del = (path) => request(path, { method: 'DELETE' });
|
||
|
||
function toastError(error) {
|
||
if (!error || error.status === 402) return;
|
||
toast(error.message || 'Something went wrong', 'error');
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Toasts / modal
|
||
-------------------------------------------------------------------------- */
|
||
function toast(message, kind = 'ok', title = '') {
|
||
const icons = { ok: 'check', error: 'alert', warn: 'alert', info: 'info' };
|
||
const el = document.createElement('div');
|
||
el.className = `toast ${kind}`;
|
||
el.innerHTML = `${icon(icons[kind] || 'info')}<div>${title ? `<strong>${esc(title)}</strong>` : ''}${esc(message)}</div>`;
|
||
toastRoot.appendChild(el);
|
||
setTimeout(() => {
|
||
el.classList.add('leaving');
|
||
setTimeout(() => el.remove(), 200);
|
||
}, kind === 'error' ? 6200 : 4200);
|
||
}
|
||
|
||
let modalEscape = null;
|
||
|
||
function closeModal() {
|
||
modalRoot.innerHTML = '';
|
||
if (modalEscape) {
|
||
document.removeEventListener('keydown', modalEscape);
|
||
modalEscape = null;
|
||
}
|
||
}
|
||
|
||
function openModal({ title, sub = '', body = '', footer = '', wide = false, narrow = false, onMount = null, onClose = null }) {
|
||
closeModal();
|
||
const size = wide ? 'wide' : narrow ? 'narrow' : '';
|
||
modalRoot.innerHTML = `
|
||
<div class="modal-backdrop" data-backdrop>
|
||
<div class="modal ${size}" role="dialog" aria-modal="true" aria-label="${esc(title)}">
|
||
<div class="modal-head">
|
||
<div><h3>${title}</h3>${sub ? `<div class="sub">${sub}</div>` : ''}</div>
|
||
<button class="icon-btn" data-close aria-label="Close">${icon('x')}</button>
|
||
</div>
|
||
<div class="modal-body">${body}</div>
|
||
${footer ? `<div class="modal-foot">${footer}</div>` : ''}
|
||
</div>
|
||
</div>`;
|
||
const backdrop = modalRoot.querySelector('[data-backdrop]');
|
||
const close = () => { const callback = onClose; closeModal(); if (callback) callback(); };
|
||
backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close(); });
|
||
modalRoot.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', close));
|
||
modalEscape = (event) => { if (event.key === 'Escape') close(); };
|
||
document.addEventListener('keydown', modalEscape);
|
||
if (onMount) onMount(modalRoot.querySelector('.modal'), close);
|
||
return modalRoot.querySelector('.modal');
|
||
}
|
||
|
||
function confirmDialog({ title, message, confirmLabel = 'Confirm', danger = false }) {
|
||
return new Promise((resolve) => {
|
||
let settled = false;
|
||
const finish = (value) => { if (settled) return; settled = true; closeModal(); resolve(value); };
|
||
openModal({
|
||
title: esc(title),
|
||
narrow: true,
|
||
body: `<p style="color:var(--text-2);font-size:13px;line-height:1.6">${message}</p>`,
|
||
footer: `<button class="btn" data-cancel>Cancel</button><button class="btn ${danger ? 'danger' : 'primary'}" data-yes>${esc(confirmLabel)}</button>`,
|
||
onMount(modal) {
|
||
modal.querySelector('[data-cancel]').addEventListener('click', () => finish(false));
|
||
modal.querySelector('[data-yes]').addEventListener('click', () => finish(true));
|
||
},
|
||
onClose() { if (!settled) { settled = true; resolve(false); } },
|
||
});
|
||
});
|
||
}
|
||
|
||
async function copyText(text) {
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
toast('Copied to clipboard');
|
||
} catch {
|
||
const area = document.createElement('textarea');
|
||
area.value = text;
|
||
document.body.appendChild(area);
|
||
area.select();
|
||
document.execCommand('copy');
|
||
area.remove();
|
||
toast('Copied to clipboard');
|
||
}
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Boot / login
|
||
-------------------------------------------------------------------------- */
|
||
async function init() {
|
||
try {
|
||
const data = await get('/bootstrap');
|
||
state.boot = data;
|
||
startApp();
|
||
} catch (error) {
|
||
if (error.status === 401) {
|
||
showLogin();
|
||
} else {
|
||
showBootError(error.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
function showBootError(message) {
|
||
if (!bootEl) return;
|
||
bootEl.hidden = false;
|
||
app.hidden = true;
|
||
const sub = bootEl.querySelector('.boot-sub');
|
||
if (sub) sub.textContent = message;
|
||
bootEl.classList.add('boot-failed');
|
||
if (!bootEl.querySelector('.boot-error')) {
|
||
const div = document.createElement('div');
|
||
div.className = 'boot-error';
|
||
div.textContent = 'The API did not respond correctly. Verify the server log and reload.';
|
||
bootEl.appendChild(div);
|
||
}
|
||
}
|
||
|
||
function showLogin(message = '') {
|
||
state.boot = null;
|
||
state.renderToken += 1;
|
||
if (state.pollTimer) { clearInterval(state.pollTimer); state.pollTimer = null; }
|
||
if (bootEl) bootEl.hidden = true;
|
||
app.hidden = false;
|
||
document.title = 'Sign in — Headroom';
|
||
app.innerHTML = `
|
||
<div class="login-screen">
|
||
<section class="login-art">
|
||
<div class="login-brand">
|
||
<span class="brand-mark">${BRAND_SVG}</span>
|
||
<strong>HEADROOM</strong>
|
||
</div>
|
||
<div class="login-hero">
|
||
<div class="eyebrow">Capacity operations console</div>
|
||
<h1>Know your headroom.<br>Before you <em>run out.</em></h1>
|
||
<p>Modular capacity intelligence for Proxmox, ESXi, NAS, Splunk and every other corner of your homelab. Forecast exhaustion, simulate upgrades and let your fleet tell you what it needs next.</p>
|
||
<div class="login-points">
|
||
<div class="login-point"><span class="dot">${icon('chart')}</span><span>Days-to-full forecasts and pressure scoring across every asset.</span></div>
|
||
<div class="login-point"><span class="dot">${icon('plug')}</span><span>Seven bundled integrations, plus custom modules and push ingestion.</span></div>
|
||
<div class="login-point"><span class="dot">${icon('sparkles')}</span><span>What-if planning, local insights and an MCP server for AI agents.</span></div>
|
||
</div>
|
||
</div>
|
||
<div class="login-foot"><span>Community edition</span><span>Upgradeable to Enterprise</span><span>Self-hosted · SQLite</span></div>
|
||
</section>
|
||
<section class="login-panel">
|
||
<div class="login-card">
|
||
<div class="eyebrow">Secure sign-in</div>
|
||
<h2>Welcome back</h2>
|
||
<p>Sign in to your capacity console.</p>
|
||
<form id="login-form" autocomplete="on">
|
||
<div class="field">
|
||
<label for="login-user">Username</label>
|
||
<input class="input" id="login-user" name="username" autocomplete="username" value="admin" required>
|
||
</div>
|
||
<div class="field">
|
||
<label for="login-pass">Password</label>
|
||
<input class="input" id="login-pass" name="password" type="password" autocomplete="current-password" required autofocus>
|
||
</div>
|
||
<button class="btn primary" type="submit" id="login-submit">Sign in ${icon('arrowRight')}</button>
|
||
<div class="login-error" id="login-error">${esc(message)}</div>
|
||
</form>
|
||
<div class="login-hint">${icon('info')}<span>First run uses <code>admin / admin</code>. Change it in Settings.</span></div>
|
||
</div>
|
||
</section>
|
||
</div>`;
|
||
const form = app.querySelector('#login-form');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const button = app.querySelector('#login-submit');
|
||
const error = app.querySelector('#login-error');
|
||
error.textContent = '';
|
||
button.disabled = true;
|
||
button.innerHTML = `${icon('refresh')} Signing in…`;
|
||
const payload = Object.fromEntries(new FormData(form).entries());
|
||
try {
|
||
await post('/auth/login', payload);
|
||
await init();
|
||
} catch (err) {
|
||
error.textContent = err.message;
|
||
button.disabled = false;
|
||
button.innerHTML = `Sign in ${icon('arrowRight')}`;
|
||
app.querySelector('#login-pass').focus();
|
||
}
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Shell
|
||
-------------------------------------------------------------------------- */
|
||
const NAV = [
|
||
{ section: 'Operations' },
|
||
{ key: 'overview', label: 'Overview', icon: 'dashboard', href: '#/overview' },
|
||
{ key: 'assets', label: 'Assets', icon: 'server', href: '#/assets' },
|
||
{ key: 'capacity', label: 'Capacity & forecast', icon: 'chart', href: '#/capacity' },
|
||
{ key: 'alerts', label: 'Alerts', icon: 'bell', href: '#/alerts' },
|
||
{ section: 'Platform' },
|
||
{ key: 'modules', label: 'Modules', icon: 'plug', href: '#/modules' },
|
||
{ key: 'copilot', label: 'Copilot', icon: 'sparkles', href: '#/copilot' },
|
||
{ key: 'api', label: 'API & MCP', icon: 'code', href: '#/api' },
|
||
{ section: 'System' },
|
||
{ key: 'settings', label: 'Settings', icon: 'settings', href: '#/settings' },
|
||
];
|
||
|
||
function navKey(route) {
|
||
if (route.name === 'asset') return 'assets';
|
||
return route.name;
|
||
}
|
||
|
||
function startApp() {
|
||
if (!state.boot) return;
|
||
if (bootEl) bootEl.hidden = true;
|
||
app.hidden = false;
|
||
document.title = `${state.boot.site_name} — Headroom`;
|
||
const user = state.boot.user;
|
||
const initial = esc((user.username || '?').slice(0, 1).toUpperCase());
|
||
app.innerHTML = `
|
||
<div class="shell">
|
||
<aside class="sidebar" id="sidebar">
|
||
<a class="brand" href="#/overview">
|
||
<span class="brand-mark">${BRAND_SVG}</span>
|
||
<span><span class="brand-word">HEADROOM</span><span class="brand-sub">Capacity ops</span></span>
|
||
</a>
|
||
${NAV.map((item) => item.section
|
||
? `<div class="nav-section">${item.section}</div>`
|
||
: `<a class="nav-item" data-nav="${item.key}" href="${item.href}">${icon(item.icon)}<span>${item.label}</span>${item.key === 'alerts' ? '<span class="nav-count" id="nav-alert-count" hidden>0</span>' : ''}${item.key === 'copilot' || item.key === 'api' ? `<span class="nav-lock" data-lock="${item.key}" hidden>${icon('lock')}</span>` : ''}</a>`).join('')}
|
||
<div class="sidebar-foot" id="edition-slot"></div>
|
||
</aside>
|
||
<main class="main">
|
||
<header class="topbar">
|
||
<button class="icon-btn mobile-menu-btn" data-menu-toggle aria-label="Menu">${icon('menu')}</button>
|
||
<div class="topbar-title"><h1 id="tb-title">Overview</h1><span id="tb-sub"></span></div>
|
||
<div class="topbar-right">
|
||
<div class="topbar-status"><span class="live-dot"></span><span id="tb-sync">Live</span></div>
|
||
${state.boot.edition.edition !== 'community' ? `<span class="pill ${state.boot.edition.edition === 'trial' ? 'violet' : 'accent'}" title="${esc(state.boot.edition.label)}">${esc(state.boot.edition.label)}</span>` : ''}
|
||
<button class="btn sm" data-refresh title="Refresh this view">${icon('refresh')}<span class="refresh-label">Refresh</span></button>
|
||
<div style="position:relative">
|
||
<button class="user-chip" data-user-menu><span class="avatar">${initial}</span><span>${esc(user.username)}</span>${icon('chevronDown')}</button>
|
||
<div class="menu" id="user-menu" hidden>
|
||
<div class="menu-meta">${esc(user.role)} · ${esc(state.boot.edition.label)}</div>
|
||
<button class="menu-item" data-open-settings>${icon('settings')} Settings</button>
|
||
<a class="menu-item" href="/docs" target="_blank" rel="noopener">${icon('external')} API docs</a>
|
||
<div class="menu-sep"></div>
|
||
<button class="menu-item" data-logout>${icon('logout')} Sign out</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</header>
|
||
<div id="view" class="view"></div>
|
||
</main>
|
||
</div>`;
|
||
renderEditionCard();
|
||
updateNav();
|
||
bindShell();
|
||
location.hash = location.hash && location.hash !== '#/' ? location.hash : '#/overview';
|
||
renderRoute();
|
||
startPolling();
|
||
}
|
||
|
||
function renderEditionCard() {
|
||
const slot = document.getElementById('edition-slot');
|
||
if (!slot || !state.boot) return;
|
||
const edition = state.boot.edition;
|
||
const paid = edition.edition !== 'community';
|
||
const p = paid
|
||
? (edition.source === 'trial' ? `${edition.days_left ?? 0} days left in the Enterprise trial.` : `${esc(edition.customer || 'Licensed')} · ${edition.days_left ?? '—'} days remaining.`)
|
||
: 'Custom modules, LLM copilot, MCP server and 400-day retention.';
|
||
slot.innerHTML = `
|
||
<div class="edition-card">
|
||
<div class="row">
|
||
<span class="label">${esc(edition.label)}</span>
|
||
<span class="badge ${paid ? 'enterprise' : 'community'}">${paid ? (edition.source === 'trial' ? 'TRIAL' : 'PRO') : 'FREE'}</span>
|
||
</div>
|
||
<p>${p}</p>
|
||
<button class="btn sm ${paid ? '' : 'primary'}" data-open-settings>${paid ? 'Manage license' : 'Upgrade to Enterprise'}</button>
|
||
</div>`;
|
||
}
|
||
|
||
function updateNav() {
|
||
const key = navKey(state.route);
|
||
document.querySelectorAll('.nav-item').forEach((item) => item.classList.toggle('active', item.dataset.nav === key));
|
||
const count = Number(state.boot?.open_alerts || 0);
|
||
const badge = document.getElementById('nav-alert-count');
|
||
if (badge) {
|
||
badge.textContent = count > 99 ? '99+' : String(count);
|
||
badge.hidden = count === 0;
|
||
}
|
||
document.querySelectorAll('[data-lock]').forEach((lock) => {
|
||
const feature = lock.dataset.lock === 'copilot' ? 'llm_copilot' : 'mcp_server';
|
||
const unlocked = state.boot?.features?.[feature] || lock.dataset.lock === 'copilot';
|
||
lock.hidden = unlocked;
|
||
});
|
||
}
|
||
|
||
function setPage(title, sub = '') {
|
||
const titleEl = document.getElementById('tb-title');
|
||
const subEl = document.getElementById('tb-sub');
|
||
if (titleEl) titleEl.textContent = title;
|
||
if (subEl) subEl.textContent = sub;
|
||
}
|
||
|
||
function bindShell() {
|
||
document.addEventListener('click', (event) => {
|
||
const menuToggle = event.target.closest('[data-menu-toggle]');
|
||
if (menuToggle) {
|
||
document.getElementById('sidebar')?.classList.toggle('open');
|
||
return;
|
||
}
|
||
if (event.target.closest('.sidebar .nav-item')) {
|
||
document.getElementById('sidebar')?.classList.remove('open');
|
||
}
|
||
const userButton = event.target.closest('[data-user-menu]');
|
||
if (userButton) {
|
||
document.getElementById('user-menu')?.toggleAttribute('hidden');
|
||
return;
|
||
}
|
||
if (!event.target.closest('#user-menu')) {
|
||
document.getElementById('user-menu')?.setAttribute('hidden', '');
|
||
}
|
||
if (event.target.closest('[data-logout]')) {
|
||
event.preventDefault();
|
||
logout();
|
||
}
|
||
if (event.target.closest('[data-open-settings]')) {
|
||
location.hash = '#/settings';
|
||
}
|
||
const windowButton = event.target.closest('[data-window]');
|
||
if (windowButton) {
|
||
state.windowDays = Number(windowButton.dataset.window) || 7;
|
||
renderRoute();
|
||
}
|
||
if (event.target.closest('[data-refresh]')) {
|
||
renderRoute();
|
||
}
|
||
if (event.target.closest('[data-upgrade]')) {
|
||
openUpgrade(event.target.closest('[data-upgrade]').dataset.upgrade || '');
|
||
}
|
||
});
|
||
window.addEventListener('hashchange', () => {
|
||
if (!state.boot) return;
|
||
renderRoute();
|
||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||
});
|
||
}
|
||
|
||
async function logout() {
|
||
try { await post('/auth/logout'); } catch { /* ignore */ }
|
||
state.chat = [];
|
||
showLogin();
|
||
location.hash = '';
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Router
|
||
-------------------------------------------------------------------------- */
|
||
function parseHash() {
|
||
const raw = (location.hash || '').replace(/^#\/?/, '');
|
||
if (!raw) return { name: 'overview', id: null };
|
||
const parts = raw.split('/');
|
||
if (parts[0] === 'assets' && parts[1]) return { name: 'asset', id: decodeURIComponent(parts.slice(1).join('/')) };
|
||
const name = parts[0];
|
||
const known = ['overview', 'assets', 'capacity', 'alerts', 'modules', 'copilot', 'api', 'settings'];
|
||
return { name: known.includes(name) ? name : 'overview', id: null };
|
||
}
|
||
|
||
const VIEWS = {};
|
||
|
||
async function renderRoute(silent = false) {
|
||
if (!state.boot) return;
|
||
const route = parseHash();
|
||
state.route = route;
|
||
updateNav();
|
||
const token = ++state.renderToken;
|
||
const view = document.getElementById('view');
|
||
if (!view) return;
|
||
if (!silent) view.innerHTML = loadingHtml();
|
||
try {
|
||
const renderer = VIEWS[route.name];
|
||
if (!renderer) throw new Error('Unknown view');
|
||
await renderer({ route, view, token });
|
||
} catch (error) {
|
||
if (token !== state.renderToken) return;
|
||
if (error.status === 401) return;
|
||
view.innerHTML = errorState(error);
|
||
}
|
||
}
|
||
|
||
function loadingHtml() {
|
||
return `<div class="view-loading"><div class="skeleton bar-block"></div><div class="skeleton bar-block"></div><div class="skeleton bar-block"></div></div>`;
|
||
}
|
||
|
||
function errorState(error) {
|
||
return `<div class="panel"><div class="empty">
|
||
<div class="empty-icon">${icon('alert')}</div>
|
||
<strong>Could not load this view</strong>
|
||
<p>${esc(error?.message || 'Unexpected error')}</p>
|
||
<button class="btn" data-refresh>${icon('refresh')} Try again</button>
|
||
</div></div>`;
|
||
}
|
||
|
||
function pageHead({ eyebrow = '', title, sub = '', actions = '' }) {
|
||
return `<div class="page-head">
|
||
<div>${eyebrow ? `<div class="eyebrow">${esc(eyebrow)}</div>` : ''}<h2>${title}</h2>${sub ? `<p>${sub}</p>` : ''}</div>
|
||
${actions ? `<div class="page-actions">${actions}</div>` : ''}
|
||
</div>`;
|
||
}
|
||
|
||
function windowSeg() {
|
||
const options = [[1, '24h'], [7, '7d'], [30, '30d'], [90, '90d']];
|
||
return `<div class="seg" role="group" aria-label="Time window">${options.map(([value, label]) => `<button class="${state.windowDays === value ? 'on' : ''}" data-window="${value}">${label}</button>`).join('')}</div>`;
|
||
}
|
||
|
||
function refreshButton() {
|
||
return `<button class="btn sm" data-refresh>${icon('refresh')} Refresh</button>`;
|
||
}
|
||
|
||
function startPolling() {
|
||
if (state.pollTimer) clearInterval(state.pollTimer);
|
||
state.pollTimer = setInterval(async () => {
|
||
if (document.hidden || !state.boot || document.querySelector('.modal-backdrop')) return;
|
||
const active = document.activeElement;
|
||
if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) return;
|
||
await refreshBootstrap();
|
||
if (['overview', 'assets'].includes(state.route.name)) renderRoute(true);
|
||
}, 45000);
|
||
}
|
||
|
||
async function refreshBootstrap() {
|
||
try {
|
||
const data = await get('/bootstrap');
|
||
state.boot = data;
|
||
renderEditionCard();
|
||
updateNav();
|
||
return data;
|
||
} catch { return null; }
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Upgrade / trial
|
||
-------------------------------------------------------------------------- */
|
||
async function openUpgrade(feature = '') {
|
||
let editions = null;
|
||
try { editions = await get('/editions'); } catch { /* ignore */ }
|
||
const labels = state.boot?.feature_labels || {};
|
||
const enterpriseFeatures = [];
|
||
if (editions) {
|
||
for (const group of editions.matrix || []) {
|
||
for (const item of group.features) {
|
||
if (item.enterprise && !item.community) enterpriseFeatures.push(item.label);
|
||
}
|
||
}
|
||
}
|
||
const featureLabel = feature && labels[feature] ? labels[feature] : '';
|
||
const trialAvailable = editions ? editions.trial_available : false;
|
||
const body = `
|
||
${featureLabel ? `<div class="notice warn mb-16">${icon('lock')}<div><strong>${esc(featureLabel)}</strong> is an Enterprise capability.</div></div>` : ''}
|
||
<p style="color:var(--text-2);font-size:13px;line-height:1.65">Enterprise adds the tooling you need when the lab stops being just a lab: upload your own modules, talk to your fleet through an LLM, expose capacity data over MCP, and keep a year of history.</p>
|
||
<div class="upgrade-features">
|
||
${(enterpriseFeatures.length ? enterpriseFeatures : ['Custom module uploads', 'LLM copilot', 'MCP server for AI agents', 'Unlimited assets', '400-day retention', 'Audit export and webhooks']).map((item) => `<div class="upgrade-feature">${icon('check')}<span>${esc(item)}</span></div>`).join('')}
|
||
</div>
|
||
${trialAvailable ? `<div class="notice ok mb-16">${icon('sparkles')}<div><strong>30-day Enterprise trial</strong> — unlock everything now, no payment details.</div></div>` : `<div class="notice">${icon('info')}<div>A trial has already been used on this installation. Activate a license key to continue with Enterprise features.</div></div>`}
|
||
<div class="form-grid mt-16">
|
||
<div class="field span-2">
|
||
<label for="license-key">License key</label>
|
||
<input class="input" id="license-key" placeholder="HR1.…" autocomplete="off">
|
||
<span class="help">Keys are signed and verified locally. Contact <a href="mailto:[email protected]">[email protected]</a> for a key.</span>
|
||
</div>
|
||
</div>`;
|
||
openModal({
|
||
title: 'Unlock Headroom Enterprise',
|
||
sub: 'Upgrade the edition of this installation',
|
||
wide: true,
|
||
body,
|
||
footer: `
|
||
${trialAvailable ? `<button class="btn primary" data-trial>${icon('sparkles')} Start 30-day trial</button>` : ''}
|
||
<button class="btn" data-activate>${icon('key')} Activate key</button>
|
||
<button class="btn ghost" data-close>Not now</button>`,
|
||
onMount(modal, close) {
|
||
const trial = modal.querySelector('[data-trial]');
|
||
if (trial) trial.addEventListener('click', async () => {
|
||
trial.disabled = true;
|
||
try {
|
||
await post('/license/trial');
|
||
await refreshBootstrap();
|
||
close();
|
||
toast('Enterprise trial started — all features are unlocked', 'ok', 'Trial active');
|
||
renderRoute();
|
||
} catch (error) { trial.disabled = false; toastError(error); }
|
||
});
|
||
modal.querySelector('[data-activate]').addEventListener('click', async () => {
|
||
const key = modal.querySelector('#license-key').value.trim();
|
||
if (!key) { toast('Paste a license key first', 'warn'); return; }
|
||
try {
|
||
await post('/license/activate', { key });
|
||
await refreshBootstrap();
|
||
close();
|
||
toast('License activated. Welcome to Enterprise.', 'ok', 'Edition upgraded');
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Shared components
|
||
-------------------------------------------------------------------------- */
|
||
function emptyState(title, text, action = '') {
|
||
return `<div class="empty"><div class="empty-icon">${icon('database')}</div><strong>${esc(title)}</strong><p>${esc(text)}</p>${action}</div>`;
|
||
}
|
||
|
||
function resourceCard(key, label, data, accent = 'accent') {
|
||
const util = data?.util;
|
||
const b = band(util);
|
||
const unit = key === 'storage' ? gb : key === 'cpu' ? (v) => `${trimNum(v, 0)} cores` : gb;
|
||
const total = unit(data?.total ?? 0);
|
||
const used = unit(data?.used ?? 0);
|
||
const growth = key === 'storage' ? gb(data?.growth_per_day ?? 0) : key === 'cpu' ? `${trimNum(data?.growth_per_day ?? 0, 2)} cores` : gb(data?.growth_per_day ?? 0);
|
||
return `<div class="resource-card">
|
||
<div class="rc-top">
|
||
<div style="min-width:0">
|
||
<div class="rc-label">${esc(label)}</div>
|
||
<div class="rc-value">${used}<small> / ${total}</small></div>
|
||
<div class="mt-8" style="color:var(--muted);font-size:11px">${pct(util)} utilized</div>
|
||
</div>
|
||
${ring(util ?? 0, { size: 74, stroke: 7, band: b })}
|
||
</div>
|
||
<div class="bar lg" data-band="${b}" style="margin-top:13px"><span style="width:${Math.max(1, Math.min(100, util || 0))}%"></span></div>
|
||
<dl class="rc-meta">
|
||
<div><dt>Free</dt><dd>${unit(data?.free ?? 0)}</dd></div>
|
||
<div><dt>Growth / day</dt><dd>${growth}</dd></div>
|
||
<div><dt>Runway</dt><dd>${days(data?.days_to_full)}</dd></div>
|
||
</dl>
|
||
</div>`;
|
||
}
|
||
|
||
function alertRow(alert, options = {}) {
|
||
const open = alert.state === 'open';
|
||
return `<div class="alert-row ${open ? '' : 'resolved'}">
|
||
<span class="severity-dot ${esc(alert.severity || 'warning')}"></span>
|
||
<div class="a-main">
|
||
<div class="a-msg">${esc(alert.message)}</div>
|
||
<div class="a-meta">
|
||
<a href="${assetHref(alert.asset_id)}">${esc(alert.asset_name || alert.asset_id)}</a>
|
||
<span>·</span><span>${esc(alert.metric_label || alert.metric || '')}</span>
|
||
<span>·</span><span>${timeAgo(alert.created_at)}</span>
|
||
${open ? '' : '<span class="pill plain">resolved</span>'}
|
||
</div>
|
||
</div>
|
||
${options.resolve && open ? `<button class="btn sm" data-resolve="${alert.id}">${icon('check')} Resolve</button>` : ''}
|
||
</div>`;
|
||
}
|
||
|
||
function minModuleName(id) {
|
||
const modules = state.boot?.modules || [];
|
||
return modules.find((module) => module.id === id)?.name || id;
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Overview
|
||
-------------------------------------------------------------------------- */
|
||
VIEWS.overview = async ({ view, token }) => {
|
||
setPage('Fleet overview', 'Capacity posture across every integrated system');
|
||
const data = await get(`/overview?window=${state.windowDays}`);
|
||
if (token !== state.renderToken) return;
|
||
const k = data.kpis;
|
||
const storage = data.resources.storage;
|
||
const nearest = k.nearest_exhaustion;
|
||
const storageBand = band(storage.util);
|
||
const pressureBand = band(k.avg_pressure);
|
||
const timeline = data.timeline || {};
|
||
const series = [
|
||
{ key: 'cpu', label: 'CPU', color: 'var(--cyan)', points: timeline.cpu_pct || [] },
|
||
{ key: 'mem', label: 'Memory', color: 'var(--watch)', points: timeline.mem_pct || [] },
|
||
{ key: 'storage', label: 'Storage', color: 'var(--accent)', points: timeline.storage_pct || [], area: true },
|
||
].filter((item) => item.points.length);
|
||
const openAlerts = data.alerts || [];
|
||
const modules = data.modules || [];
|
||
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'Operations',
|
||
title: 'Fleet overview',
|
||
sub: `Live headroom across <strong>${k.asset_count}</strong> assets in <strong>${k.module_count}</strong> modules. ${k.last_collection ? `Last collection ${timeAgo(k.last_collection)}.` : 'Waiting for the first collection.'}`,
|
||
actions: `${windowSeg()}${refreshButton()}`,
|
||
})}
|
||
<div class="kpis">
|
||
<div class="kpi">
|
||
<div class="kpi-top"><span class="kpi-label">Managed assets</span><span class="kpi-icon">${icon('server')}</span></div>
|
||
<div class="kpi-value">${k.asset_count}<small>assets</small></div>
|
||
<div class="kpi-sub">${k.modules_online} of ${k.module_count} modules online</div>
|
||
<div class="kpi-foot"><span class="pill plain accent">${k.critical_assets} critical</span><span class="pill plain">${k.warning_assets} warning</span></div>
|
||
</div>
|
||
<div class="kpi ${pressureBand === 'critical' ? 'crit' : ''}">
|
||
<div class="kpi-top"><span class="kpi-label">Average pressure</span><span class="kpi-icon">${icon('activity')}</span></div>
|
||
<div class="kpi-value">${Math.round(k.avg_pressure)}<small>/ 100</small></div>
|
||
<div class="kpi-sub">${statusPill(pressureBand)}<span>weighted utilization + growth</span></div>
|
||
<div class="kpi-foot"><div class="bar" data-band="${pressureBand}"><span style="width:${k.avg_pressure}%"></span></div></div>
|
||
</div>
|
||
<div class="kpi ${storageBand === 'critical' ? 'crit' : storageBand === 'tight' ? 'tight' : ''}">
|
||
<div class="kpi-top"><span class="kpi-label">Storage headroom</span><span class="kpi-icon">${icon('database')}</span></div>
|
||
<div class="kpi-value">${pct(storage.util)}<small>used</small></div>
|
||
<div class="kpi-sub">${gb(storage.used)} of ${gb(storage.total)} · ${gb(storage.free)} free</div>
|
||
<div class="kpi-foot"><div class="bar" data-band="${storageBand}"><span style="width:${Math.max(1, storage.util || 0)}%"></span></div></div>
|
||
</div>
|
||
<div class="kpi ${k.open_alerts ? 'crit' : ''}">
|
||
<div class="kpi-top"><span class="kpi-label">Needs attention</span><span class="kpi-icon">${icon('bell')}</span></div>
|
||
<div class="kpi-value">${k.open_alerts}<small>open alerts</small></div>
|
||
<div class="kpi-sub">${nearest ? `Nearest exhaustion: <strong style="color:var(--text-2)">${esc(nearest.name)}</strong>` : 'No exhaustion projected'}</div>
|
||
<div class="kpi-foot">${nearest ? `<span class="pill tight">${days(nearest.days_to_full)} to full</span>` : '<span class="pill healthy">Runway healthy</span>'}</div>
|
||
</div>
|
||
</div>
|
||
${nearest ? `<a class="notice warn mb-16" href="${assetHref(nearest.asset_id)}" style="text-decoration:none">${icon('alert')}
|
||
<div><strong>${esc(nearest.name)}</strong> runs out of ${esc((metricMeta(nearest.metric).label || '').toLowerCase())} in <strong>${days(nearest.days_to_full)}</strong> (${fmtDate(nearest.eta_date)}). Currently ${pct(nearest.util)} used. <span style="color:var(--accent)">Open asset →</span></div>
|
||
</a>` : ''}
|
||
<div class="grid cols-main mb-16">
|
||
<section class="panel">
|
||
<div class="panel-head">
|
||
<div><h3>Fleet utilization</h3><div class="sub">Average utilization across active assets · last ${state.windowDays === 1 ? '24 hours' : `${state.windowDays} days`}</div></div>
|
||
<div class="actions"><div class="legend">
|
||
<span><i style="background:var(--cyan)"></i>CPU</span>
|
||
<span><i style="background:var(--watch)"></i>Memory</span>
|
||
<span><i style="background:var(--accent)"></i>Storage</span>
|
||
</div></div>
|
||
</div>
|
||
<div class="panel-body"><div id="fleet-chart"></div></div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Pressure leaders</h3><div class="sub">Highest risk first</div></div><div class="actions"><a class="btn sm ghost" href="#/assets">All assets ${icon('arrowRight')}</a></div></div>
|
||
<div class="list">
|
||
${(data.top_pressure || []).length ? data.top_pressure.map((asset) => `
|
||
<a class="list-row" href="${assetHref(asset.id)}">
|
||
<span class="type-icon t-${esc(asset.type)}">${typeIcon(asset.type)}</span>
|
||
<div class="lr-main">
|
||
<div class="name">${esc(asset.name)}</div>
|
||
<div class="sub">${esc(asset.module_name)} · ${esc(asset.type_label || asset.type)}</div>
|
||
<div class="bar" data-band="${band(asset.pressure)}"><span style="width:${Math.max(1, Math.min(100, asset.util || 0))}%"></span></div>
|
||
</div>
|
||
<div class="lr-value"><strong>${pct(asset.util)}</strong>${statusPill(asset.status, asset.status_label)}</div>
|
||
</a>`).join('') : emptyState('No assets yet', 'Enable a module to begin collecting capacity data.')}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<div class="grid cols-3 mb-16">
|
||
${resourceCard('storage', 'Storage pool', data.resources.storage)}
|
||
${resourceCard('cpu', 'Compute pool', data.resources.cpu)}
|
||
${resourceCard('mem', 'Memory pool', data.resources.mem)}
|
||
</div>
|
||
<div class="grid cols-main mb-16">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Fastest movers</h3><div class="sub">Largest utilization growth per day</div></div><div class="actions"><a class="btn sm ghost" href="#/capacity">Forecast ${icon('arrowRight')}</a></div></div>
|
||
<div class="table-wrap">
|
||
<table class="data">
|
||
<thead><tr><th>Asset</th><th>Utilization</th><th>Growth</th><th class="num">Runway</th></tr></thead>
|
||
<tbody>
|
||
${(data.movers || []).length ? data.movers.map((asset) => `
|
||
<tr class="clickable" data-href="${assetHref(asset.id)}">
|
||
<td><div class="cell-main"><span class="type-icon t-${esc(asset.type)}">${typeIcon(asset.type)}</span><div><div class="name">${esc(asset.name)}</div><div class="sub">${esc(asset.module_name)}</div></div></div></td>
|
||
<td><span class="mini-metric">${pct(asset.util)}</span></td>
|
||
<td>${trendCell(asset)}</td>
|
||
<td class="num">${days(asset.days_to_full)}</td>
|
||
</tr>`).join('') : `<tr><td colspan="4" class="table-empty"><strong>No growth detected</strong>Growth will appear here as utilization rises over time.</td></tr>`}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Open alerts</h3><div class="sub">${k.open_alerts} unresolved</div></div><div class="actions"><a class="btn sm ghost" href="#/alerts">All alerts ${icon('arrowRight')}</a></div></div>
|
||
<div>
|
||
${openAlerts.length ? openAlerts.map((alert) => alertRow(alert)).join('') : emptyState('No open alerts', 'Every policy is within its threshold.')}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Integrations</h3><div class="sub">Collection health</div></div><div class="actions"><a class="btn sm ghost" href="#/modules">Manage modules ${icon('arrowRight')}</a></div></div>
|
||
<div class="panel-body" style="display:flex;gap:9px;flex-wrap:wrap">
|
||
${modules.map((module) => `
|
||
<a class="pill plain ${module.enabled && module.status === 'ok' ? 'healthy' : module.status === 'error' ? 'critical' : 'muted'}" href="#/modules" style="height:auto;padding:6px 10px;gap:7px;text-decoration:none">
|
||
<span class="dot-status ${module.enabled ? (module.status === 'ok' ? 'ok' : module.status === 'error' ? 'error' : 'pending') : 'disabled'}"></span>
|
||
<span>${esc(module.name)}</span><span class="faint mono" style="font-size:10px">${module.asset_count}</span>
|
||
</a>`).join('') || '<span class="muted">No modules installed.</span>'}
|
||
</div>
|
||
</section>`;
|
||
if (series.length) {
|
||
lineChart(view.querySelector('#fleet-chart'), series, { height: 282, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Fleet utilization over time' });
|
||
} else {
|
||
view.querySelector('#fleet-chart').innerHTML = '<div class="chart-empty">No telemetry in this window yet.</div>';
|
||
}
|
||
view.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
|
||
};
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Assets
|
||
-------------------------------------------------------------------------- */
|
||
function assetFilteredRows(items) {
|
||
const filter = state.assetFilters;
|
||
const needle = filter.q.trim().toLowerCase();
|
||
return items.filter((asset) => {
|
||
if (filter.type && asset.type !== filter.type) return false;
|
||
if (filter.module && asset.module_id !== filter.module) return false;
|
||
if (!needle) return true;
|
||
return asset.name.toLowerCase().includes(needle)
|
||
|| asset.module_name.toLowerCase().includes(needle)
|
||
|| (asset.cluster || '').toLowerCase().includes(needle)
|
||
|| (asset.site || '').toLowerCase().includes(needle)
|
||
|| (asset.tags || []).some((tag) => tag.toLowerCase().includes(needle));
|
||
});
|
||
}
|
||
|
||
function assetRow(asset) {
|
||
return `<tr class="clickable" data-href="${assetHref(asset.id)}">
|
||
<td><div class="cell-main">
|
||
<span class="type-icon t-${esc(asset.type)}">${typeIcon(asset.type)}</span>
|
||
<div><div class="name">${esc(asset.name)}</div><div class="sub">${esc(asset.module_name)}${asset.cluster ? ` · ${esc(asset.cluster)}` : ''}</div></div>
|
||
</div></td>
|
||
<td><span class="mono" style="font-size:11.5px">${esc(asset.type_label || asset.type)}</span>${asset.site ? `<div class="sub" style="color:var(--faint);font-size:10px">${esc(asset.site)}</div>` : ''}</td>
|
||
<td><div class="util-cell"><div class="bar" data-band="${band(asset.util)}"><span style="width:${Math.max(1, Math.min(100, asset.util || 0))}%"></span></div><strong>${pct(asset.util)}</strong></div></td>
|
||
<td>${statusPill(asset.status, asset.status_label)}</td>
|
||
<td>${trendCell(asset)}</td>
|
||
<td class="num">${days(asset.days_to_full)}</td>
|
||
<td class="num faint">${timeAgo(asset.last_seen)}</td>
|
||
</tr>`;
|
||
}
|
||
|
||
VIEWS.assets = async ({ view, token }) => {
|
||
setPage('Asset inventory', 'Every monitored system in one list');
|
||
const data = await get('/assets');
|
||
if (token !== state.renderToken) return;
|
||
const items = data.items || [];
|
||
const types = TYPES();
|
||
const modules = [...new Map(items.map((asset) => [asset.module_id, asset.module_name])).entries()];
|
||
const filter = state.assetFilters;
|
||
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'Inventory',
|
||
title: 'Assets',
|
||
sub: `<strong>${items.length}</strong> active assets reported by ${modules.length} module${modules.length === 1 ? '' : 's'}. Click any row for forecasts and recommendations.`,
|
||
actions: `${windowSeg()}<a class="btn sm" href="/api/export/assets.csv">${icon('download')} Export CSV</a>${refreshButton()}`,
|
||
})}
|
||
<div class="toolbar">
|
||
<label class="search">${icon('search')}<input class="input" id="asset-search" placeholder="Search name, cluster, tag…" value="${esc(filter.q)}" autocomplete="off"></label>
|
||
<select class="select sm" id="filter-type" style="width:160px">
|
||
<option value="">All types</option>
|
||
${Object.entries(types).map(([key, meta]) => `<option value="${esc(key)}" ${filter.type === key ? 'selected' : ''}>${esc(meta.label || key)}</option>`).join('')}
|
||
</select>
|
||
<select class="select sm" id="filter-module" style="width:170px">
|
||
<option value="">All modules</option>
|
||
${modules.map(([id, name]) => `<option value="${esc(id)}" ${filter.module === id ? 'selected' : ''}>${esc(name)}</option>`).join('')}
|
||
</select>
|
||
<span class="spacer"></span>
|
||
<span class="toolbar-label" id="asset-count">Showing ${assetFilteredRows(items).length} of ${items.length}</span>
|
||
<button class="btn sm ghost" id="clear-filters">${icon('x')} Clear</button>
|
||
</div>
|
||
<section class="panel">
|
||
<div class="table-wrap">
|
||
<table class="data">
|
||
<thead><tr><th>Asset</th><th>Type</th><th>Utilization</th><th>Pressure</th><th>Trend</th><th class="num">Runway</th><th class="num">Last seen</th></tr></thead>
|
||
<tbody id="asset-tbody">${assetFilteredRows(items).map(assetRow).join('') || `<tr><td colspan="7" class="table-empty"><strong>No assets match</strong>Adjust the filters or enable another module.</td></tr>`}</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="panel-foot" id="asset-foot">${items.length ? `Auto-refreshes every 45 seconds · last collection ${timeAgo(state.boot?.scheduler?.last_run || state.boot?.meta?.generated_at || '')}` : 'No active assets.'}</div>
|
||
</section>`;
|
||
|
||
const tbody = view.querySelector('#asset-tbody');
|
||
const count = view.querySelector('#asset-count');
|
||
const refreshRows = () => {
|
||
const filtered = assetFilteredRows(items);
|
||
tbody.innerHTML = filtered.length ? filtered.map(assetRow).join('') : `<tr><td colspan="7" class="table-empty"><strong>No assets match</strong>Adjust the filters or enable another module.</td></tr>`;
|
||
count.textContent = `Showing ${filtered.length} of ${items.length}`;
|
||
tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
|
||
};
|
||
const bindRowClicks = () => tbody.querySelectorAll('tr[data-href]').forEach((row) => row.addEventListener('click', () => { location.hash = row.dataset.href; }));
|
||
bindRowClicks();
|
||
view.querySelector('#asset-search').addEventListener('input', (event) => {
|
||
state.assetFilters.q = event.target.value;
|
||
refreshRows();
|
||
});
|
||
view.querySelector('#filter-type').addEventListener('change', (event) => {
|
||
state.assetFilters.type = event.target.value;
|
||
refreshRows();
|
||
});
|
||
view.querySelector('#filter-module').addEventListener('change', (event) => {
|
||
state.assetFilters.module = event.target.value;
|
||
refreshRows();
|
||
});
|
||
view.querySelector('#clear-filters').addEventListener('click', () => {
|
||
state.assetFilters = { q: '', type: '', module: '' };
|
||
view.querySelector('#asset-search').value = '';
|
||
view.querySelector('#filter-type').value = '';
|
||
view.querySelector('#filter-module').value = '';
|
||
refreshRows();
|
||
});
|
||
};
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Asset detail
|
||
-------------------------------------------------------------------------- */
|
||
VIEWS.asset = async ({ view, token, route }) => {
|
||
const data = await get(`/assets/${encodeURIComponent(route.id)}?window=30`);
|
||
if (token !== state.renderToken) return;
|
||
const asset = data.asset;
|
||
const analysis = data.analysis || {};
|
||
const cards = data.cards || [];
|
||
const forecasts = data.forecasts || {};
|
||
const reco = data.recommendation || {};
|
||
const assetAlerts = data.alerts || [];
|
||
setPage(asset.name, `${asset.module_name} · ${asset.type_label}`);
|
||
|
||
const capacity = asset.capacity || {};
|
||
const capacityRows = [
|
||
['Primary metric', metricMeta(analysis.primary_metric).label || analysis.primary_metric],
|
||
['Headroom', pct(analysis.headroom_pct)],
|
||
['Growth', `${analysis.slope_per_day > 0 ? '+' : ''}${trimNum(analysis.slope_per_day, 2)} pp/day`],
|
||
['Days to full', days(analysis.days_to_full)],
|
||
['Projected full', analysis.eta_date ? fmtDate(analysis.eta_date) : '—'],
|
||
['Last sample', timeAgo(asset.last_seen)],
|
||
['First seen', fmtDate(asset.first_seen)],
|
||
['Module status', data.module?.status ? `${data.module.status}${data.module.enabled ? '' : ' · disabled'}` : 'unknown'],
|
||
];
|
||
if (capacity.cpu_cores != null) capacityRows.push(['CPU cores', trimNum(capacity.cpu_cores, 0)]);
|
||
if (capacity.mem_gb != null) capacityRows.push(['Memory', gb(capacity.mem_gb)]);
|
||
if (capacity.storage_gb != null) capacityRows.push(['Storage', gb(capacity.storage_gb)]);
|
||
Object.entries(asset.meta || {}).slice(0, 8).forEach(([key, value]) => capacityRows.push([key.replace(/_/g, ' '), String(value)]));
|
||
|
||
const selected = cards.some((card) => card.key === state.assetMetric) ? state.assetMetric : (cards[0]?.key || analysis.primary_metric);
|
||
const selectedCard = cards.find((card) => card.key === selected);
|
||
|
||
view.innerHTML = `
|
||
<a class="back-link" href="#/assets">${icon('arrowLeft')} All assets</a>
|
||
<div class="hero">
|
||
${ring(analysis.pressure ?? 0, { size: 96, stroke: 9 })}
|
||
<div class="hero-main">
|
||
<h2>${esc(asset.name)} ${statusPill(analysis.status, analysis.status_label)}</h2>
|
||
<div class="hero-sub">
|
||
<span class="badge bundled">${esc(asset.type_label || asset.type)}</span>
|
||
<span>${esc(asset.module_name)}</span>
|
||
${asset.cluster ? `<span>·</span><span>${esc(asset.cluster)}</span>` : ''}
|
||
${asset.site ? `<span>·</span><span>${esc(asset.site)}</span>` : ''}
|
||
<span>·</span><span>Last seen ${timeAgo(asset.last_seen)}</span>
|
||
${analysis.stale ? '<span class="pill critical">stale telemetry</span>' : ''}
|
||
</div>
|
||
<div class="hero-actions" style="margin-top:12px;justify-content:flex-start">
|
||
<button class="btn sm" data-run-module="${esc(asset.module_id)}">${icon('play')} Collect now</button>
|
||
<a class="btn sm ghost" href="#/modules">${icon('plug')} Module settings</a>
|
||
<a class="btn sm ghost" href="#/alerts">${icon('bell')} Alerts</a>
|
||
</div>
|
||
</div>
|
||
<div class="hero-actions">
|
||
<span class="pill plain ${analysis.trend === 'rising' ? 'tight' : analysis.trend === 'falling' ? 'healthy' : 'muted'}">${icon(analysis.trend === 'rising' ? 'arrowUp' : analysis.trend === 'falling' ? 'arrowDown' : 'minus')} ${esc(analysis.trend)}</span>
|
||
</div>
|
||
</div>
|
||
<div class="reco ${esc(reco.level || 'healthy')} mb-16">
|
||
<div class="reco-head"><span class="pill ${reco.level === 'critical' ? 'critical' : reco.level === 'warning' ? 'tight' : reco.level === 'info' ? 'info' : 'healthy'}">${esc(reco.level || 'info')}</span><h3>${esc(reco.title || 'Capacity assessment')}</h3></div>
|
||
<p>${esc(reco.detail || '')}</p>
|
||
${reco.action ? `<div class="action">${icon('arrowRight')}<span>${esc(reco.action)}</span></div>` : ''}
|
||
</div>
|
||
<div class="metric-grid">
|
||
${cards.map((card) => {
|
||
const meta = metricMeta(card.key);
|
||
const delta = card.delta_24h;
|
||
const color = meta.kind === 'util' ? bandColor(band(card.value)) : 'var(--cyan)';
|
||
return `<div class="metric-card">
|
||
<div class="mc-top">${esc(card.label)}<span class="faint" style="margin-left:auto;text-transform:none;letter-spacing:0">${esc(meta.unit || '')}</span></div>
|
||
<div class="mc-value">${esc(metricValue(card.key, card.value))} ${delta != null && delta !== 0 ? `<span class="mc-delta ${delta > 0 ? 'up' : 'down'}">${delta > 0 ? '+' : ''}${trimNum(delta, 1)}</span>` : ''}</div>
|
||
${sparkline(card.series, color)}
|
||
</div>`;
|
||
}).join('') || `<div class="notice">${icon('info')} No metric cards were reported for this asset.</div>`}
|
||
</div>
|
||
<div class="grid cols-main-rev mb-16">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Capacity & metadata</h3><div class="sub">Declared capacity and collection state</div></div></div>
|
||
<div class="panel-body">
|
||
<dl class="kv">${capacityRows.map(([label, value]) => `<div><dt>${esc(label)}</dt><dd>${esc(value)}</dd></div>`).join('')}</dl>
|
||
${(asset.tags || []).length ? `<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:12px">${asset.tags.map((tag) => `<span class="pill plain muted">${esc(tag)}</span>`).join('')}</div>` : ''}
|
||
<div class="mt-16" style="display:flex;gap:8px;flex-wrap:wrap">
|
||
<a class="btn sm" href="/api/export/assets.csv">${icon('download')} Export fleet CSV</a>
|
||
<button class="btn sm ghost" data-run-module="${esc(asset.module_id)}">${icon('refresh')} Refresh module</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head">
|
||
<div><h3>Trend & forecast</h3><div class="sub">Observed history plus projected trajectory</div></div>
|
||
<div class="actions"><span class="legend"><span><i style="background:var(--accent)"></i>Observed</span><span><i style="background:var(--violet)"></i>Forecast</span></span></div>
|
||
</div>
|
||
<div class="tabs" style="padding:0 16px">
|
||
${cards.map((card) => `<button class="tab ${card.key === selected ? 'on' : ''}" data-metric-tab="${esc(card.key)}">${esc(card.label)}</button>`).join('')}
|
||
</div>
|
||
<div class="panel-body">
|
||
<div id="asset-chart"></div>
|
||
<div id="forecast-callout" class="mt-16"></div>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<div class="grid cols-2">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Forecasts</h3><div class="sub">Linear projection over the next 90 days</div></div></div>
|
||
${Object.keys(forecasts).length ? `<div class="table-wrap"><table class="data">
|
||
<thead><tr><th>Metric</th><th>Current</th><th class="num">Growth</th><th class="num">Days to full</th></tr></thead>
|
||
<tbody>${Object.entries(forecasts).map(([key, forecast]) => `<tr>
|
||
<td>${esc(metricMeta(key).label || key)}</td>
|
||
<td class="num">${esc(metricValue(key, asset.metrics?.[key]))}</td>
|
||
<td class="num">${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} pp/d</td>
|
||
<td class="num">${days(forecast.days_to_full)}</td>
|
||
</tr>`).join('')}</tbody>
|
||
</table></div>` : `<div class="panel-body"><div class="notice">${icon('info')} No upward trend detected in the current window, so no exhaustion forecast is available.</div></div>`}
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Alert history</h3><div class="sub">${assetAlerts.filter((alert) => alert.state === 'open').length} open · ${assetAlerts.length} total</div></div></div>
|
||
<div>${assetAlerts.length ? assetAlerts.slice(0, 8).map((alert) => alertRow(alert)).join('') : emptyState('No alerts', 'This asset has never crossed a policy threshold.')}</div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const drawChart = (key) => {
|
||
const card = cards.find((item) => item.key === key);
|
||
const container = view.querySelector('#asset-chart');
|
||
if (!card || !container) return;
|
||
const meta = metricMeta(key);
|
||
const series = [{ label: card.label, color: 'var(--accent)', points: card.series, area: true, dot: true }];
|
||
const forecast = forecasts[key];
|
||
if (forecast) series.push({ label: 'Forecast', color: 'var(--violet)', points: forecast.points, dashed: true });
|
||
const isPct = meta.unit === '%';
|
||
lineChart(container, series, {
|
||
height: 272,
|
||
max: isPct ? 100 : undefined,
|
||
valueFormat: (value) => (isPct ? `${Math.round(value)}%` : `${trimNum(value, 0)}${meta.unit ? ` ${meta.unit}` : ''}`),
|
||
ariaLabel: `${card.label} trend`,
|
||
});
|
||
const callout = view.querySelector('#forecast-callout');
|
||
callout.innerHTML = forecast
|
||
? `<div class="notice ok">${icon('chart')}<div><strong>${esc(card.label)}</strong> is growing ${forecast.slope_per_day > 0 ? '+' : ''}${trimNum(forecast.slope_per_day, 2)} ${isPct ? 'pp' : meta.unit || 'units'}/day${forecast.days_to_full ? ` and reaches capacity in <strong>${days(forecast.days_to_full)}</strong>` : ''}. The dashed line projects 90 days at the current rate.</div></div>`
|
||
: `<div class="notice">${icon('info')}<div>No positive growth trend for this metric in the selected window.</div></div>`;
|
||
};
|
||
drawChart(selected);
|
||
view.querySelectorAll('[data-metric-tab]').forEach((button) => button.addEventListener('click', () => {
|
||
state.assetMetric = button.dataset.metricTab;
|
||
view.querySelectorAll('[data-metric-tab]').forEach((tab) => tab.classList.toggle('on', tab === button));
|
||
drawChart(button.dataset.metricTab);
|
||
}));
|
||
view.querySelectorAll('[data-run-module]').forEach((button) => button.addEventListener('click', async () => {
|
||
button.disabled = true;
|
||
button.classList.add('is-busy');
|
||
try {
|
||
const result = await post(`/modules/${encodeURIComponent(button.dataset.runModule)}/run`);
|
||
toast(`${result.assets} assets refreshed in ${result.duration_ms} ms`, 'ok', 'Collection complete');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
finally { button.disabled = false; button.classList.remove('is-busy'); }
|
||
}));
|
||
};
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Capacity & what-if
|
||
-------------------------------------------------------------------------- */
|
||
VIEWS.capacity = async ({ view, token }) => {
|
||
setPage('Capacity & forecast', 'Pools, groups and upgrade planning');
|
||
const [data, modulesData] = await Promise.all([get(`/capacity?window=${state.windowDays}`), get('/modules')]);
|
||
if (token !== state.renderToken) return;
|
||
const groups = data.groups || [];
|
||
const modules = (modulesData.items || []).filter((module) => module.enabled);
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'Planning',
|
||
title: 'Capacity & forecast',
|
||
sub: 'Aggregated pools, per-cluster pressure and a what-if simulator for the next hardware decision.',
|
||
actions: `${windowSeg()}${refreshButton()}`,
|
||
})}
|
||
<div class="grid cols-3 mb-16">
|
||
${resourceCard('storage', 'Storage pool', data.totals.storage)}
|
||
${resourceCard('cpu', 'Compute pool', data.totals.cpu)}
|
||
${resourceCard('mem', 'Memory pool', data.totals.mem)}
|
||
</div>
|
||
<section class="panel mb-16">
|
||
<div class="panel-head"><div><h3>Clusters & groups</h3><div class="sub">Grouped by cluster label, falling back to module</div></div><div class="actions"><span class="pill plain">${groups.length} groups</span></div></div>
|
||
<div class="table-wrap">
|
||
<table class="data">
|
||
<thead><tr><th>Group</th><th>Module</th><th class="num">Assets</th><th>Peak utilization</th><th>Pressure</th><th class="num">Storage runway</th><th>Storage</th></tr></thead>
|
||
<tbody>
|
||
${groups.length ? groups.map((group) => {
|
||
const storage = group.resources?.storage || {};
|
||
return `<tr>
|
||
<td><div class="cell-main"><span class="type-icon t-cluster">${icon('layers')}</span><div><div class="name">${esc(group.name)}</div><div class="sub">${esc(group.site || group.types.join(', '))}</div></div></div></td>
|
||
<td class="muted">${esc(group.module_name)}</td>
|
||
<td class="num">${group.asset_count}</td>
|
||
<td><div class="util-cell"><div class="bar" data-band="${band(group.util)}"><span style="width:${Math.max(1, group.util || 0)}%"></span></div><strong>${pct(group.util)}</strong></div></td>
|
||
<td>${statusPill(group.status, group.status_label)}</td>
|
||
<td class="num">${days(group.days_to_full)}</td>
|
||
<td style="min-width:110px"><div class="bar" data-band="${band(storage.util)}"><span style="width:${Math.max(1, storage.util || 0)}%"></span></div><span class="faint mono" style="font-size:10px">${pct(storage.util)}</span></td>
|
||
</tr>`;
|
||
}).join('') : `<tr><td colspan="7" class="table-empty"><strong>No groups yet</strong>Enable at least one module to build capacity groups.</td></tr>`}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>What-if simulator</h3><div class="sub">Model growth and added capacity before you buy hardware</div></div><div class="actions"><span class="pill info">${icon('sparkles')} local model</span></div></div>
|
||
<div class="panel-body">
|
||
<form id="sim-form" class="sim-form">
|
||
<div class="field"><label for="sim-horizon">Planning horizon</label>
|
||
<select class="select" id="sim-horizon" name="horizon_days">
|
||
<option value="30">30 days</option><option value="90" selected>90 days</option><option value="180">6 months</option><option value="365">12 months</option>
|
||
</select>
|
||
</div>
|
||
<div class="field"><label for="sim-growth">Growth multiplier</label>
|
||
<input class="input" id="sim-growth" name="growth_multiplier" type="number" min="0" max="5" step="0.1" value="1">
|
||
<span class="help">1 = current trend, 2 = twice as fast, 0 = no growth.</span>
|
||
</div>
|
||
<div class="field"><label for="sim-storage">Add storage (GB)</label>
|
||
<input class="input" id="sim-storage" name="add_storage_gb" type="number" min="0" step="100" value="0" placeholder="0">
|
||
</div>
|
||
<div class="field"><label for="sim-cpu">Add CPU (cores)</label>
|
||
<input class="input" id="sim-cpu" name="add_cpu_cores" type="number" min="0" step="1" value="0" placeholder="0">
|
||
</div>
|
||
<div class="field"><label for="sim-mem">Add memory (GB)</label>
|
||
<input class="input" id="sim-mem" name="add_mem_gb" type="number" min="0" step="8" value="0" placeholder="0">
|
||
</div>
|
||
<div class="field"><label>Exclude modules</label>
|
||
<div style="display:flex;gap:10px;flex-wrap:wrap;min-height:36px;align-items:center">
|
||
${modules.length ? modules.map((module) => `<label class="check"><input type="checkbox" name="disable_modules" value="${esc(module.id)}"> ${esc(module.name)}</label>`).join('') : '<span class="faint">No enabled modules</span>'}
|
||
</div>
|
||
</div>
|
||
<div class="span-3" style="display:flex;gap:8px;align-items:center">
|
||
<button class="btn primary" type="submit">${icon('play')} Run simulation</button>
|
||
<button class="btn ghost" type="reset">Reset</button>
|
||
<span class="faint" style="font-size:11px">Uses linear growth from the selected window. Results are directional, not a purchase order.</span>
|
||
</div>
|
||
</form>
|
||
<div id="sim-output" class="mt-16">
|
||
<div class="notice">${icon('info')}<div>Set a horizon and growth assumption, add planned capacity, then run the model. The simulator also projects every resource pool at the end of the horizon.</div></div>
|
||
</div>
|
||
</div>
|
||
</section>`;
|
||
|
||
const form = view.querySelector('#sim-form');
|
||
const output = view.querySelector('#sim-output');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const button = form.querySelector('button[type="submit"]');
|
||
button.disabled = true;
|
||
button.classList.add('is-busy');
|
||
const formData = new FormData(form);
|
||
const payload = {
|
||
horizon_days: Number(formData.get('horizon_days') || 90),
|
||
growth_multiplier: Number(formData.get('growth_multiplier') || 1),
|
||
add_storage_gb: Number(formData.get('add_storage_gb') || 0),
|
||
add_cpu_cores: Number(formData.get('add_cpu_cores') || 0),
|
||
add_mem_gb: Number(formData.get('add_mem_gb') || 0),
|
||
disable_modules: formData.getAll('disable_modules'),
|
||
};
|
||
try {
|
||
const result = await post('/capacity/simulate', payload);
|
||
state.simResult = result;
|
||
renderSimulation(output, result);
|
||
} catch (error) { toastError(error); }
|
||
finally { button.disabled = false; button.classList.remove('is-busy'); }
|
||
});
|
||
form.addEventListener('reset', () => {
|
||
setTimeout(() => {
|
||
output.innerHTML = `<div class="notice">${icon('info')}<div>Set a horizon and growth assumption, add planned capacity, then run the model.</div></div>`;
|
||
}, 0);
|
||
});
|
||
if (state.simResult) renderSimulation(output, state.simResult);
|
||
};
|
||
|
||
function renderSimulation(output, result) {
|
||
const verdictMap = {
|
||
healthy: ['healthy', 'Comfortable headroom', 'The fleet stays below 60% on all modeled resources.'],
|
||
watch: ['watch', 'Keep watching', 'The plan keeps everything below 80%, but headroom is shrinking.'],
|
||
tight: ['tight', 'Tight after the plan', 'At least one resource exceeds 80% at the end of the horizon.'],
|
||
critical: ['critical', 'Exceeds safe capacity', 'At least one resource is projected above 90%. Add capacity or reduce growth.'],
|
||
};
|
||
const [vClass, vTitle, vText] = verdictMap[result.verdict] || verdictMap.watch;
|
||
const resourceLabels = { storage: 'Storage', cpu: 'Compute', mem: 'Memory' };
|
||
const resourceUnits = { storage: 'GB', cpu: 'cores', mem: 'GB' };
|
||
output.innerHTML = `
|
||
<div class="verdict mb-16">
|
||
${ring(result.verdict === 'healthy' ? 42 : result.verdict === 'watch' ? 68 : result.verdict === 'tight' ? 85 : 96, { size: 58, stroke: 6, band: vClass })}
|
||
<div><strong>${vTitle}</strong><span>${vText}</span></div>
|
||
<span class="pill ${vClass}" style="margin-left:auto">${esc(result.verdict)}</span>
|
||
</div>
|
||
<div class="grid cols-3 mb-16">
|
||
${['storage', 'cpu', 'mem'].map((key) => {
|
||
const resource = result.resources[key];
|
||
return `<div class="sim-resource">
|
||
<div class="sr-head"><strong>${resourceLabels[key]}</strong><span class="pill ${band(resource.util_after)}">${pct(resource.util_after)} after</span></div>
|
||
<div class="bar lg" data-band="${band(resource.util_before)}"><span style="width:${Math.max(1, resource.util_before || 0)}%"></span></div>
|
||
<div class="sim-compare">
|
||
<div class="${resource.util_before > 90 ? 'warn' : ''}">Before<strong>${pct(resource.util_before)}</strong></div>
|
||
<div class="after">After plan<strong>${pct(resource.util_after)}</strong></div>
|
||
<div>Projected use<strong>${trimNum(resource.projected_used, 0)} ${resourceUnits[key]}</strong></div>
|
||
<div>Headroom<strong>${trimNum(resource.headroom_after, 0)} ${resourceUnits[key]}</strong></div>
|
||
</div>
|
||
</div>`;
|
||
}).join('')}
|
||
</div>
|
||
<div class="grid cols-main-rev">
|
||
<div>
|
||
<div class="notice mb-16">${icon('info')}<div>${result.asset_count} assets included${result.disabled_modules.length ? ` · excluded: ${result.disabled_modules.map(esc).join(', ')}` : ''} · horizon ${result.horizon_days} days · growth ×${result.growth_multiplier}</div></div>
|
||
<ul class="findings">${result.findings.map((finding) => `<li>${icon('arrowRight')}<span>${esc(finding)}</span></li>`).join('')}</ul>
|
||
</div>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Projected utilization</h3><div class="sub">Current plan vs. added capacity</div></div>
|
||
<div class="actions"><div class="seg" id="sim-resource-seg">
|
||
${['storage', 'cpu', 'mem'].map((key) => `<button class="${key === 'storage' ? 'on' : ''}" data-sim-resource="${key}">${resourceLabels[key]}</button>`).join('')}
|
||
</div></div>
|
||
</div>
|
||
<div class="panel-body"><div id="sim-chart"></div><div class="legend mt-16"><span><i style="background:var(--crit)"></i>Current plan</span><span><i style="background:var(--accent)"></i>With additions</span></div></div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const drawSim = (resource) => {
|
||
const before = result.series.before.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 }));
|
||
const after = result.series.after.map((point) => ({ t: point.t, v: point.values[resource] ?? 0 }));
|
||
lineChart(output.querySelector('#sim-chart'), [
|
||
{ label: 'Current plan', color: 'var(--crit)', points: before, dashed: true },
|
||
{ label: 'With additions', color: 'var(--accent)', points: after, area: true, dot: true },
|
||
], { height: 240, max: 100, valueFormat: (value) => `${Math.round(value)}%`, ariaLabel: 'Projected utilization' });
|
||
};
|
||
drawSim('storage');
|
||
output.querySelectorAll('[data-sim-resource]').forEach((button) => button.addEventListener('click', () => {
|
||
output.querySelectorAll('[data-sim-resource]').forEach((item) => item.classList.toggle('on', item === button));
|
||
drawSim(button.dataset.simResource);
|
||
}));
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Alerts & policies
|
||
-------------------------------------------------------------------------- */
|
||
VIEWS.alerts = async ({ view, token }) => {
|
||
setPage('Alerts', 'Policy breaches and threshold history');
|
||
const [data, policiesData] = await Promise.all([get(`/alerts?include_resolved=${state.alertResolved}`), get('/policies')]);
|
||
if (token !== state.renderToken) return;
|
||
const items = data.items || [];
|
||
const policies = policiesData.items || [];
|
||
const canOperate = ['admin', 'operator'].includes(state.boot.user.role);
|
||
const utilMetrics = META().util_metrics || ['cpu_pct', 'mem_pct', 'storage_pct'];
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'Operations',
|
||
title: 'Alerts',
|
||
sub: `<strong>${data.open}</strong> open · ${data.critical} critical · ${data.warning} warning`,
|
||
actions: `<label class="switch"><input type="checkbox" id="show-resolved" ${state.alertResolved ? 'checked' : ''}><span class="track"></span> Include resolved</label><a class="btn sm" href="/api/export/alerts.csv">${icon('download')} Export</a>${refreshButton()}`,
|
||
})}
|
||
<div class="grid cols-main mb-16">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>${state.alertResolved ? 'Alert history' : 'Open alerts'}</h3><div class="sub">Ordered by severity, then newest first</div></div><div class="actions"><span class="pill ${data.critical ? 'critical' : 'healthy'}">${data.critical} critical</span></div></div>
|
||
<div>${items.length ? items.map((alert) => alertRow(alert, { resolve: canOperate })).join('') : emptyState('No alerts', state.alertResolved ? 'No alerts have been recorded yet.' : 'Everything is within policy thresholds.')}</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Policy coverage</h3><div class="sub">Thresholds evaluated after every collection</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="insight">
|
||
<h4>How it works</h4>
|
||
<p>Each enabled policy is evaluated against every asset that reports the metric. Crossing the warning threshold opens a warning; crossing critical updates it. Values below warning resolve it automatically.</p>
|
||
<ul><li>Warning and critical are percentages.</li><li>One open alert per asset, metric and policy.</li><li>Resolve manually to close it without waiting for the next collection.</li></ul>
|
||
</div>
|
||
<div class="mt-16" style="display:flex;gap:8px">
|
||
${canOperate ? `<button class="btn sm primary" data-new-policy>${icon('plus')} New policy</button>` : ''}
|
||
<a class="btn sm ghost" href="#/settings">${icon('bell')} Webhook settings</a>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Policies</h3><div class="sub">${policies.length} configured</div></div><div class="actions">${canOperate ? `<button class="btn sm" data-new-policy>${icon('plus')} Add policy</button>` : ''}</div></div>
|
||
<div class="table-wrap">
|
||
<table class="data">
|
||
<thead><tr><th>Policy</th><th>Metric</th><th class="num">Warning</th><th class="num">Critical</th><th>Enabled</th><th class="num">Actions</th></tr></thead>
|
||
<tbody>
|
||
${policies.length ? policies.map((policy) => `<tr>
|
||
<td><div class="cell-main"><div><div class="name">${esc(policy.name)}</div><div class="sub">created ${fmtDate(policy.created_at)}</div></div></div></td>
|
||
<td><span class="mono" style="font-size:11.5px">${esc(metricMeta(policy.metric).label || policy.metric)}</span></td>
|
||
<td class="num">${trimNum(policy.warn, 0)}%</td>
|
||
<td class="num">${trimNum(policy.crit, 0)}%</td>
|
||
<td><label class="switch"><input type="checkbox" data-policy-toggle="${policy.id}" ${policy.enabled ? 'checked' : ''} ${canOperate ? '' : 'disabled'}><span class="track"></span></label></td>
|
||
<td class="num">${canOperate ? `<button class="icon-btn" data-policy-edit="${policy.id}" title="Edit">${icon('settings')}</button><button class="icon-btn danger" data-policy-delete="${policy.id}" title="Delete">${icon('trash')}</button>` : '<span class="faint">—</span>'}</td>
|
||
</tr>`).join('') : `<tr><td colspan="6" class="table-empty"><strong>No policies</strong>Add a threshold to start generating alerts.</td></tr>`}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</section>`;
|
||
|
||
view.querySelector('#show-resolved').addEventListener('change', (event) => {
|
||
state.alertResolved = event.target.checked;
|
||
renderRoute();
|
||
});
|
||
|
||
const policyById = (id) => policies.find((policy) => String(policy.id) === String(id));
|
||
view.querySelectorAll('[data-resolve]').forEach((button) => button.addEventListener('click', async () => {
|
||
button.disabled = true;
|
||
try {
|
||
await post(`/alerts/${button.dataset.resolve}/resolve`);
|
||
toast('Alert resolved');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); button.disabled = false; }
|
||
}));
|
||
view.querySelectorAll('[data-new-policy]').forEach((button) => button.addEventListener('click', () => openPolicyModal(null, utilMetrics)));
|
||
view.querySelectorAll('[data-policy-edit]').forEach((button) => button.addEventListener('click', () => openPolicyModal(policyById(button.dataset.policyEdit), utilMetrics)));
|
||
view.querySelectorAll('[data-policy-toggle]').forEach((input) => input.addEventListener('change', async () => {
|
||
const policy = policyById(input.dataset.policyToggle);
|
||
if (!policy) return;
|
||
try {
|
||
await put(`/policies/${policy.id}`, { name: policy.name, metric: policy.metric, warn: policy.warn, crit: policy.crit, enabled: input.checked });
|
||
toast(`Policy ${input.checked ? 'enabled' : 'disabled'}`);
|
||
renderRoute();
|
||
} catch (error) { toastError(error); input.checked = !input.checked; }
|
||
}));
|
||
view.querySelectorAll('[data-policy-delete]').forEach((button) => button.addEventListener('click', async () => {
|
||
const policy = policyById(button.dataset.policyDelete);
|
||
if (!policy) return;
|
||
if (!(await confirmDialog({ title: 'Delete policy', message: `Delete <strong>${esc(policy.name)}</strong>? Open alerts from this policy will be resolved.`, confirmLabel: 'Delete policy', danger: true }))) return;
|
||
try {
|
||
await del(`/policies/${policy.id}`);
|
||
toast('Policy deleted');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
}));
|
||
};
|
||
|
||
function openPolicyModal(policy, utilMetrics) {
|
||
const isEdit = Boolean(policy);
|
||
const metricOptions = [...new Set([...(utilMetrics || []), ...(policy ? [policy.metric] : [])])];
|
||
openModal({
|
||
title: isEdit ? 'Edit policy' : 'New capacity policy',
|
||
sub: isEdit ? esc(policy.name) : 'Alerts are evaluated after every module run',
|
||
body: `<form id="policy-form" class="form-grid">
|
||
<div class="field span-2"><label for="policy-name">Policy name</label><input class="input" id="policy-name" name="name" value="${esc(policy?.name || '')}" placeholder="Storage warning" required></div>
|
||
<div class="field span-2"><label for="policy-metric">Metric</label>
|
||
<select class="select" id="policy-metric" name="metric">${metricOptions.map((metric) => `<option value="${esc(metric)}" ${policy?.metric === metric ? 'selected' : ''}>${esc(metricMeta(metric).label || metric)} (${esc(metricMeta(metric).unit || '')})</option>`).join('')}</select>
|
||
</div>
|
||
<div class="field"><label for="policy-warn">Warning threshold (%)</label><input class="input" id="policy-warn" name="warn" type="number" min="0" max="100" step="1" value="${esc(policy?.warn ?? 80)}" required></div>
|
||
<div class="field"><label for="policy-crit">Critical threshold (%)</label><input class="input" id="policy-crit" name="crit" type="number" min="1" max="100" step="1" value="${esc(policy?.crit ?? 90)}" required></div>
|
||
<div class="field span-2"><label class="check"><input type="checkbox" name="enabled" ${!policy || policy.enabled ? 'checked' : ''}> Evaluate this policy after each collection</label></div>
|
||
</form>`,
|
||
footer: `<button class="btn" data-close>Cancel</button><button class="btn primary" type="submit" form="policy-form">${icon('check')} ${isEdit ? 'Save changes' : 'Create policy'}</button>`,
|
||
onMount(modal, close) {
|
||
const form = modal.querySelector('#policy-form');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(form);
|
||
const payload = {
|
||
name: String(formData.get('name') || '').trim(),
|
||
metric: String(formData.get('metric') || 'storage_pct'),
|
||
warn: Number(formData.get('warn')),
|
||
crit: Number(formData.get('crit')),
|
||
enabled: formData.get('enabled') === 'on',
|
||
};
|
||
if (payload.warn >= payload.crit) { toast('Warning must be below critical', 'warn'); return; }
|
||
try {
|
||
if (isEdit) await put(`/policies/${policy.id}`, payload);
|
||
else await post('/policies', payload);
|
||
close();
|
||
toast(isEdit ? 'Policy updated' : 'Policy created');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Modules
|
||
-------------------------------------------------------------------------- */
|
||
function moduleStatusText(module) {
|
||
if (!module.enabled) return 'Disabled';
|
||
if (module.status === 'ok') return 'Connected';
|
||
if (module.status === 'error') return 'Collection failed';
|
||
if (module.status === 'pending') return 'Awaiting first run';
|
||
if (module.status === 'missing') return 'Files missing';
|
||
return module.status || 'Unknown';
|
||
}
|
||
|
||
function moduleDot(module) {
|
||
if (!module.enabled) return 'disabled';
|
||
if (module.status === 'ok') return 'ok';
|
||
if (module.status === 'error') return 'error';
|
||
if (module.status === 'pending') return 'pending';
|
||
return 'disabled';
|
||
}
|
||
|
||
VIEWS.modules = async ({ view, token }) => {
|
||
setPage('Modules', 'Integrations, collector health and custom plugins');
|
||
const data = await get('/modules');
|
||
if (token !== state.renderToken) return;
|
||
const modules = data.items || [];
|
||
const isAdmin = state.boot.user.role === 'admin';
|
||
const canOperate = ['admin', 'operator'].includes(state.boot.user.role);
|
||
const customAllowed = Boolean(state.boot.features.custom_modules);
|
||
const limit = Number(state.boot.limits?.assets ?? -1);
|
||
const limitWarning = limit > 0 && state.boot.asset_count >= limit;
|
||
const types = [...new Map(modules.map((m) => [m.module_type, m])).values()];
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'Platform',
|
||
title: 'Modules',
|
||
sub: 'Toggle collectors, tune connections and upload your own integrations. Multiple instances of the same module type are supported.',
|
||
actions: `${isAdmin ? `<button class="btn sm" id="add-module-instance">${icon('plus')} Add instance</button>` : ''}${customAllowed ? `<button class="btn sm primary" id="upload-module">${icon('upload')} Upload module</button>` : `<button class="btn sm" data-upgrade="custom_modules">${icon('lock')} Upload unavailable</button>`}${refreshButton()}`,
|
||
})}
|
||
${limitWarning ? `<div class="notice warn mb-16">${icon('alert')}<div><strong>Community asset limit reached (${limit}).</strong> New assets will not be stored until the limit is raised. <button class="btn sm ghost" data-upgrade="unlimited_assets">Upgrade for unlimited assets ${icon('arrowRight')}</button></div></div>` : ''}
|
||
<div class="toolbar">
|
||
<span class="toolbar-label">${modules.length} instances · ${types.length} types · ${modules.filter((module) => module.enabled).length} enabled · ${modules.reduce((sum, module) => sum + (module.asset_count || 0), 0)} assets</span>
|
||
<span class="spacer"></span>
|
||
<span class="pill plain bundled">${modules.filter((module) => module.source === 'bundled').length} bundled instances</span>
|
||
<span class="pill plain violet">${modules.filter((module) => module.source === 'custom').length} custom instances</span>
|
||
${!isAdmin ? `<span class="pill plain muted">${icon('lock')} read-only</span>` : ''}
|
||
</div>
|
||
<div class="modules-grid">
|
||
${modules.map((module) => {
|
||
const isCustom = module.source === 'custom';
|
||
const instanceCount = module.instance_count || 1;
|
||
const canDelete = isAdmin && (isCustom || instanceCount > 1);
|
||
return `<article class="module-card ${module.enabled ? '' : 'disabled'}">
|
||
<div class="module-top">
|
||
<span class="module-icon">${icon(MODULE_ICON[module.icon] || MODULE_ICON[module.module_type] || MODULE_ICON[module.id] || 'plug')}</span>
|
||
<div class="module-title">
|
||
<h3>${esc(module.name || module.instance_name)} <span class="badge ${isCustom ? 'custom' : 'bundled'}">${isCustom ? 'custom' : 'bundled'}</span>${instanceCount > 1 ? ` <span class="badge">x${instanceCount}</span>` : ''}</h3>
|
||
<div class="sub">${esc(module.type_name || module.vendor || 'Community')} · ${esc(module.module_type || module.id)} · v${esc(module.version || '—')} · ${esc(module.category || 'other')}</div>
|
||
</div>
|
||
<label class="switch" title="${isAdmin ? 'Enable or disable instance' : 'Admin required'}"><input type="checkbox" data-module-toggle="${esc(module.id)}" ${module.enabled ? 'checked' : ''} ${isAdmin ? '' : 'disabled'}><span class="track"></span></label>
|
||
</div>
|
||
<p class="module-desc">${esc(module.description || 'No description provided.')}</p>
|
||
<div class="module-status"><span class="dot-status ${moduleDot(module)}"></span><span>${esc(moduleStatusText(module))}</span>${module.message ? `<span class="faint" title="${esc(module.message)}">· ${esc(module.message.length > 62 ? `${module.message.slice(0, 62)}…` : module.message)}</span>` : ''}</div>
|
||
<dl class="module-stats">
|
||
<div><dt>Assets</dt><dd>${module.asset_count || 0}</dd></div>
|
||
<div><dt>Interval</dt><dd>${module.interval_seconds || 300}s</dd></div>
|
||
<div><dt>Last run</dt><dd title="${esc(module.last_run || '')}">${timeAgo(module.last_run)}</dd></div>
|
||
<div><dt>Instance</dt><dd>${esc(module.id)}</dd></div>
|
||
</dl>
|
||
<div class="module-foot">
|
||
<button class="btn sm" data-module-run="${esc(module.id)}" ${canOperate && module.enabled ? '' : 'disabled'}>${icon('play')} Run</button>
|
||
<button class="btn sm ghost" data-module-test="${esc(module.id)}" ${canOperate && module.enabled ? '' : 'disabled'}>Test</button>
|
||
<button class="btn sm ghost" data-module-config="${esc(module.id)}" ${isAdmin ? '' : 'disabled'}>Configure</button>
|
||
<button class="btn sm ghost" data-module-logs="${esc(module.id)}">Logs</button>
|
||
${isAdmin ? `<button class="btn sm ghost" data-module-clone="${esc(module.id)}" title="Add another instance">${icon('plus')} Add another</button>` : ''}
|
||
${canDelete ? `<button class="icon-btn danger" data-module-delete="${esc(module.id)}" title="Delete instance">${icon('trash')}</button>` : ''}
|
||
</div>
|
||
</article>`;
|
||
}).join('')}
|
||
</div>
|
||
${modules.length ? '' : `<section class="panel">${emptyState('No modules installed', 'Add an instance or upload a module package.', customAllowed ? `<button class="btn primary" data-upload-again>${icon('upload')} Upload module</button>` : '')}</section>`}`;
|
||
|
||
const moduleById = (id) => modules.find((module) => module.id === id);
|
||
view.querySelectorAll('[data-module-toggle]').forEach((input) => input.addEventListener('change', async () => {
|
||
const module = moduleById(input.dataset.moduleToggle);
|
||
if (!module) return;
|
||
input.disabled = true;
|
||
try {
|
||
await put(`/modules/${encodeURIComponent(module.id)}`, { enabled: input.checked });
|
||
toast(`${module.name} ${input.checked ? 'enabled — first collection is starting' : 'disabled'}`);
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
if (input.checked) setTimeout(() => { if (state.route.name === 'modules') renderRoute(true); }, 3200);
|
||
} catch (error) { toastError(error); input.checked = !input.checked; input.disabled = false; }
|
||
}));
|
||
|
||
view.querySelectorAll('[data-module-run]').forEach((button) => button.addEventListener('click', async () => {
|
||
const module = moduleById(button.dataset.moduleRun);
|
||
button.disabled = true;
|
||
button.classList.add('is-busy');
|
||
try {
|
||
const result = await post(`/modules/${encodeURIComponent(module.id)}/run`);
|
||
toast(`${result.assets} assets · ${result.metrics} metrics · ${result.duration_ms} ms`, 'ok', `${module.name} collected`);
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
finally { button.disabled = false; button.classList.remove('is-busy'); }
|
||
}));
|
||
|
||
view.querySelectorAll('[data-module-test]').forEach((button) => button.addEventListener('click', async () => {
|
||
const module = moduleById(button.dataset.moduleTest);
|
||
button.disabled = true;
|
||
button.classList.add('is-busy');
|
||
try {
|
||
const result = await post(`/modules/${encodeURIComponent(module.id)}/test`);
|
||
toast(result.message || 'Connection test completed', result.ok ? 'ok' : 'warn', `${module.name} test`);
|
||
} catch (error) { toastError(error); }
|
||
finally { button.disabled = false; button.classList.remove('is-busy'); }
|
||
}));
|
||
|
||
view.querySelectorAll('[data-module-config]').forEach((button) => button.addEventListener('click', () => openModuleConfig(moduleById(button.dataset.moduleConfig))));
|
||
view.querySelectorAll('[data-module-logs]').forEach((button) => button.addEventListener('click', () => openModuleLogs(moduleById(button.dataset.moduleLogs))));
|
||
view.querySelectorAll('[data-module-delete]').forEach((button) => button.addEventListener('click', async () => {
|
||
const module = moduleById(button.dataset.moduleDelete);
|
||
if (!module) return;
|
||
if (!(await confirmDialog({ title: 'Delete instance', message: `Delete instance <strong>${esc(module.name)}</strong> and remove its assets and metric history? This cannot be undone.`, confirmLabel: 'Delete instance', danger: true }))) return;
|
||
try {
|
||
await del(`/modules/${encodeURIComponent(module.id)}`);
|
||
toast(`${module.name} removed`);
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
}));
|
||
|
||
view.querySelectorAll('[data-module-clone]').forEach((button) => button.addEventListener('click', async () => {
|
||
const module = moduleById(button.dataset.moduleClone);
|
||
if (!module || !(state.boot.user && state.boot.user.role === 'admin')) return;
|
||
try {
|
||
const label = prompt(`Name for new ${module.type_name || module.name} instance`, `${module.name} 2`);
|
||
if (label === null) return;
|
||
await post('/modules/instances', { module_type: module.module_type, name: label, copy_from: module.id });
|
||
toast('Instance added', 'ok');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
}));
|
||
|
||
const addInstance = view.querySelector('#add-module-instance');
|
||
if (addInstance) {
|
||
addInstance.addEventListener('click', async () => {
|
||
if (!(state.boot.user && state.boot.user.role === 'admin')) return;
|
||
const choices = types.map((m) => `<option value="${esc(m.module_type)}">${esc(m.type_name || m.name)} (${esc(m.module_type)})</option>`).join('');
|
||
openModal({
|
||
title: 'Add module instance',
|
||
sub: 'Create another collector instance for the same module type',
|
||
body: `<form id="add-instance-form" class="form-grid">
|
||
<div class="field span-2"><label for="ai-type">Module type</label><select class="select" id="ai-type" name="module_type">${choices}</select></div>
|
||
<div class="field span-2"><label for="ai-name">Instance label</label><input class="input" id="ai-name" name="name" placeholder="e.g. Proxmox Atlas"></div>
|
||
</form>`,
|
||
footer: `<button class="btn" data-close>Cancel</button><button class="btn primary" type="submit" form="add-instance-form">${icon('plus')} Add instance</button>`,
|
||
onMount(modal, close) {
|
||
const form = modal.querySelector('#add-instance-form');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(form);
|
||
try {
|
||
await post('/modules/instances', { module_type: String(formData.get('module_type') || ''), name: String(formData.get('name') || '') });
|
||
close();
|
||
toast('Instance added', 'ok');
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
});
|
||
}
|
||
|
||
const upload = view.querySelector('#upload-module');
|
||
if (upload) upload.addEventListener('click', openUploadModal);
|
||
const uploadAgain = view.querySelector('[data-upload-again]');
|
||
if (uploadAgain) uploadAgain.addEventListener('click', openUploadModal);
|
||
};
|
||
|
||
function openModuleConfig(module) {
|
||
if (!module) return;
|
||
if (state.boot.user.role !== 'admin') { toast('Administrator role required', 'warn'); return; }
|
||
const config = module.config || {};
|
||
const secretSet = module.secret_set || {};
|
||
const fields = (module.settings_schema || []).map((item) => {
|
||
const key = item.key;
|
||
const label = item.label || key;
|
||
const type = item.type || 'text';
|
||
const value = config[key];
|
||
const help = item.help ? `<span class="help">${esc(item.help)}</span>` : '';
|
||
if (type === 'boolean') {
|
||
return `<div class="field"><label class="check"><input type="checkbox" name="${esc(key)}" ${value ? 'checked' : ''}> ${esc(label)}</label>${help}</div>`;
|
||
}
|
||
if (type === 'select') {
|
||
const options = (item.options || []).map((option) => {
|
||
const optionValue = typeof option === 'object' ? option.value : option;
|
||
const optionLabel = typeof option === 'object' ? (option.label || option.value) : option;
|
||
return `<option value="${esc(optionValue)}" ${String(value) === String(optionValue) ? 'selected' : ''}>${esc(optionLabel)}</option>`;
|
||
}).join('');
|
||
return `<div class="field"><label for="cfg-${esc(key)}">${esc(label)}</label><select class="select" id="cfg-${esc(key)}" name="${esc(key)}">${options}</select>${help}</div>`;
|
||
}
|
||
if (type === 'textarea') {
|
||
return `<div class="field span-2"><label for="cfg-${esc(key)}">${esc(label)}</label><textarea class="textarea" id="cfg-${esc(key)}" name="${esc(key)}" placeholder="${esc(item.placeholder || '')}">${esc(value || '')}</textarea>${help}</div>`;
|
||
}
|
||
if (type === 'password') {
|
||
const placeholder = secretSet[key] ? 'Saved — leave blank to keep the current value' : (item.placeholder || '');
|
||
return `<div class="field"><label for="cfg-${esc(key)}">${esc(label)}</label><input class="input" type="password" id="cfg-${esc(key)}" name="${esc(key)}" value="" placeholder="${esc(placeholder)}" autocomplete="new-password">${help}</div>`;
|
||
}
|
||
const inputType = type === 'number' ? 'number' : 'text';
|
||
const step = type === 'number' ? ' step="any"' : '';
|
||
return `<div class="field"><label for="cfg-${esc(key)}">${esc(label)}</label><input class="input" type="${inputType}"${step} id="cfg-${esc(key)}" name="${esc(key)}" value="${esc(value ?? '')}" placeholder="${esc(item.placeholder || '')}">${help}</div>`;
|
||
}).join('');
|
||
const demo = config.demo;
|
||
openModal({
|
||
title: `Configure ${module.name}`,
|
||
sub: `${module.source} module · v${esc(module.version || '—')}`,
|
||
wide: true,
|
||
body: `<form id="module-config-form" class="form-grid">
|
||
${demo ? `<div class="span-2 notice">${icon('info')}<div><strong>Demo mode is on.</strong> The module generates realistic local data. Turn it off and add connection details to collect from the real system.</div></div>` : ''}
|
||
${fields || `<div class="span-2 notice">${icon('info')}<div>This module exposes no configurable settings.</div></div>`}
|
||
</form>
|
||
<div class="notice mt-16">${icon('shield')}<div>Secrets are masked in the UI and stored in the local SQLite database. Module code runs in an isolated subprocess with a 90-second timeout.</div></div>`,
|
||
footer: `<button class="btn" data-close>Cancel</button><button class="btn primary" type="submit" form="module-config-form">${icon('check')} Save configuration</button>`,
|
||
onMount(modal, close) {
|
||
const form = modal.querySelector('#module-config-form');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const payload = {};
|
||
for (const item of module.settings_schema || []) {
|
||
const element = form.elements.namedItem(item.key);
|
||
if (!element) continue;
|
||
if ((item.type || 'text') === 'boolean') payload[item.key] = element.checked;
|
||
else if ((item.type || 'text') === 'number') payload[item.key] = element.value === '' ? (config[item.key] ?? 0) : Number(element.value);
|
||
else payload[item.key] = element.value;
|
||
}
|
||
try {
|
||
await put(`/modules/${encodeURIComponent(module.id)}`, { config: payload });
|
||
close();
|
||
toast(`${module.name} configuration saved`);
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
function openModuleLogs(module) {
|
||
if (!module) return;
|
||
openModal({
|
||
title: `${module.name} logs`,
|
||
sub: 'Most recent collector output',
|
||
wide: true,
|
||
body: `<div id="module-logs-body"><div class="notice">${icon('refresh')}<div>Loading logs…</div></div></div>`,
|
||
footer: `<button class="btn" data-close>Close</button><button class="btn" id="reload-logs">${icon('refresh')} Reload</button>`,
|
||
onMount(modal) {
|
||
const load = async () => {
|
||
const body = modal.querySelector('#module-logs-body');
|
||
body.innerHTML = `<div class="notice">${icon('refresh')}<div>Loading logs…</div></div>`;
|
||
try {
|
||
const data = await get(`/modules/${encodeURIComponent(module.id)}/logs`);
|
||
body.innerHTML = data.logs ? `<pre class="log-box">${esc(data.logs)}</pre>` : `<div class="notice">${icon('info')}<div>No log output yet. Run the module once to collect diagnostics.</div></div>`;
|
||
} catch (error) {
|
||
body.innerHTML = `<div class="notice crit">${icon('alert')}<div>${esc(error.message)}</div></div>`;
|
||
}
|
||
};
|
||
load();
|
||
modal.querySelector('#reload-logs').addEventListener('click', load);
|
||
},
|
||
});
|
||
}
|
||
|
||
function openUploadModal() {
|
||
if (!state.boot.features.custom_modules) { openUpgrade('custom_modules'); return; }
|
||
openModal({
|
||
title: 'Upload a module',
|
||
sub: 'Signed-out-of-the-box: a zip with manifest.json and module.py',
|
||
wide: true,
|
||
body: `<div class="upload-drop" id="upload-drop">
|
||
${icon('upload')}
|
||
<strong>Drop a module zip here</strong>
|
||
<span>or click to choose a file · max 2 MB</span>
|
||
<input type="file" id="upload-file" accept=".zip,application/zip" hidden>
|
||
</div>
|
||
<div id="upload-selected"></div>
|
||
<div class="notice mt-16">${icon('shield')}<div>Uploads are validated: manifest schema, module id, package paths and size. Module code executes in a subprocess with resource limits. Review third-party code before enabling it.</div></div>
|
||
<div class="notice mt-16">${icon('code')}<div>The package must contain <code>manifest.json</code> and <code>module.py</code> at the root (or inside one top-level folder).</div></div>`,
|
||
footer: `<button class="btn" data-close>Cancel</button><button class="btn primary" id="upload-submit" disabled>${icon('upload')} Upload & register</button>`,
|
||
onMount(modal, close) {
|
||
let file = null;
|
||
const drop = modal.querySelector('#upload-drop');
|
||
const input = modal.querySelector('#upload-file');
|
||
const selected = modal.querySelector('#upload-selected');
|
||
const submit = modal.querySelector('#upload-submit');
|
||
const choose = (chosen) => {
|
||
if (!chosen) return;
|
||
file = chosen;
|
||
selected.innerHTML = `<div class="upload-file">${icon('box')}<span>${esc(chosen.name)}</span><span class="faint" style="margin-left:auto">${(chosen.size / 1024).toFixed(1)} KB</span></div>`;
|
||
submit.disabled = false;
|
||
};
|
||
drop.addEventListener('click', () => input.click());
|
||
input.addEventListener('change', () => choose(input.files[0]));
|
||
drop.addEventListener('dragover', (event) => { event.preventDefault(); drop.style.borderColor = 'var(--accent)'; });
|
||
drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; });
|
||
drop.addEventListener('drop', (event) => {
|
||
event.preventDefault();
|
||
drop.style.borderColor = '';
|
||
choose(event.dataTransfer.files[0]);
|
||
});
|
||
submit.addEventListener('click', async () => {
|
||
if (!file) return;
|
||
submit.disabled = true;
|
||
submit.classList.add('is-busy');
|
||
const formData = new FormData();
|
||
formData.append('file', file);
|
||
try {
|
||
const result = await request('/modules/upload', { method: 'POST', body: formData });
|
||
close();
|
||
toast(`${result.name} v${result.version} registered. Configure and enable it to collect.`, 'ok', 'Module uploaded');
|
||
renderRoute();
|
||
} catch (error) {
|
||
toastError(error);
|
||
submit.disabled = false;
|
||
submit.classList.remove('is-busy');
|
||
}
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Copilot
|
||
-------------------------------------------------------------------------- */
|
||
function inlineMarkdown(text) {
|
||
return text
|
||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||
.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||
}
|
||
|
||
function markdown(text) {
|
||
const lines = esc(text || '').split('\n');
|
||
const out = [];
|
||
let inList = false;
|
||
for (const raw of lines) {
|
||
const line = raw.trimEnd();
|
||
if (/^\s*[-*]\s+/.test(line)) {
|
||
if (!inList) { out.push('<ul>'); inList = true; }
|
||
out.push(`<li>${inlineMarkdown(line.replace(/^\s*[-*]\s+/, ''))}</li>`);
|
||
continue;
|
||
}
|
||
if (inList) { out.push('</ul>'); inList = false; }
|
||
if (!line.trim()) continue;
|
||
out.push(`<p>${inlineMarkdown(line)}</p>`);
|
||
}
|
||
if (inList) out.push('</ul>');
|
||
return out.join('');
|
||
}
|
||
|
||
VIEWS.copilot = async ({ view, token }) => {
|
||
setPage('Copilot', 'Capacity analysis and conversational planning');
|
||
let aiConfig = { config: {}, suggested_questions: [] };
|
||
try { aiConfig = await get('/ai/config'); } catch { /* ignore */ }
|
||
if (token !== state.renderToken) return;
|
||
const features = state.boot.features || {};
|
||
const config = aiConfig.config || {};
|
||
const suggestions = aiConfig.suggested_questions || [];
|
||
const edition = state.boot.edition;
|
||
const llm = features.llm_copilot;
|
||
view.innerHTML = `
|
||
${pageHead({
|
||
eyebrow: 'AI operations',
|
||
title: 'Capacity copilot',
|
||
sub: 'Ask about risk, growth or the next upgrade. Local analysis works on every edition; conversational answers unlock with Enterprise.',
|
||
actions: `<span class="pill ${llm ? 'accent' : 'muted'}">${llm ? (config.configured ? 'LLM connected' : 'LLM not configured') : 'Local analysis'}</span><button class="btn sm" data-clear-chat>${icon('trash')} Clear chat</button>`,
|
||
})}
|
||
<div class="grid cols-main">
|
||
<section class="panel chat-panel">
|
||
<div class="panel-head"><div><h3>Ask Headroom</h3><div class="sub">Grounded in your live fleet data</div></div><div class="actions">${llm && config.configured ? '<span class="pill plain accent">live context</span>' : '<span class="pill plain">deterministic insights</span>'}</div></div>
|
||
<div class="chat-log" id="chat-log"></div>
|
||
<div style="padding:0 14px 12px"><div class="chat-suggest" id="chat-suggest">
|
||
${suggestions.map((question) => `<button data-question="${esc(question)}">${esc(question)}</button>`).join('')}
|
||
</div></div>
|
||
<form class="chat-input" id="chat-form">
|
||
<textarea class="textarea" id="chat-text" placeholder="Ask about capacity, growth or an upgrade…" rows="1"></textarea>
|
||
<button class="btn primary" type="submit" id="chat-send">${icon('sparkles')} Send</button>
|
||
</form>
|
||
</section>
|
||
<aside class="grid" style="gap:16px;align-content:start">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Fleet context</h3><div class="sub">What the copilot can see</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="kv-list">
|
||
<div><dt>Managed assets</dt><dd>${state.boot.asset_count}</dd></div>
|
||
<div><dt>Open alerts</dt><dd>${state.boot.open_alerts}</dd></div>
|
||
<div><dt>Modules online</dt><dd>${state.boot.scheduler?.modules_ran ?? '—'}</dd></div>
|
||
<div><dt>Edition</dt><dd>${esc(edition.label)}</dd></div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Copilot modes</h3><div class="sub">Graceful degradation by edition</div></div></div>
|
||
<div class="panel-body" style="display:grid;gap:12px">
|
||
<div class="upgrade-feature">${icon('check')}<div><strong>Local analysis</strong><div class="faint" style="font-size:11.5px">Deterministic capacity briefing from live metrics. Included in Community.</div></div></div>
|
||
<div class="upgrade-feature">${icon(llm ? 'check' : 'lock')}<div><strong>LLM narrative</strong><div class="faint" style="font-size:11.5px">Conversational answers through any OpenAI-compatible endpoint.</div></div></div>
|
||
<div class="upgrade-feature">${icon('code')}<div><strong>MCP agents</strong><div class="faint" style="font-size:11.5px">Expose the same data to Claude Desktop or another MCP client. <a href="#/api" style="color:var(--accent)">Setup →</a></div></div></div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Provider</h3><div class="sub">${llm ? (config.configured ? esc(config.model) : 'Not configured') : 'Enterprise capability'}</div></div></div>
|
||
<div class="panel-body">
|
||
${llm
|
||
? `<div class="kv-list"><div><dt>Base URL</dt><dd>${esc(config.base_url || '—')}</dd></div><div><dt>Model</dt><dd>${esc(config.model || '—')}</dd></div><div><dt>API key</dt><dd>${config.key_set ? 'saved' : 'not set'}</dd></div></div>
|
||
<button class="btn sm mt-16" data-ai-config>${icon('settings')} Configure provider</button>`
|
||
: `<p style="color:var(--muted);font-size:12px;line-height:1.55">Connect OpenAI, Azure OpenAI, Ollama, LM Studio or LiteLLM. Without a provider, Headroom still gives you the full local analysis.</p>
|
||
<button class="btn sm primary mt-16" data-upgrade="llm_copilot">${icon('sparkles')} Unlock LLM copilot</button>`}
|
||
</div>
|
||
</section>
|
||
</aside>
|
||
</div>`;
|
||
|
||
const log = view.querySelector('#chat-log');
|
||
const form = view.querySelector('#chat-form');
|
||
const input = view.querySelector('#chat-text');
|
||
const send = view.querySelector('#chat-send');
|
||
|
||
const renderLog = () => {
|
||
log.innerHTML = `
|
||
${state.chat.map((message) => {
|
||
const isUser = message.role === 'user';
|
||
return `<div class="msg ${isUser ? 'user' : ''}">
|
||
<div class="msg-avatar">${icon(isUser ? 'server' : 'sparkles')}</div>
|
||
<div>
|
||
<div class="bubble">${markdown(message.content)}</div>
|
||
${message.note ? `<div class="msg-note">${esc(message.note)}</div>` : ''}
|
||
${message.upgrade ? `<div class="notice warn mt-8">${icon('lock')}<div>Enterprise unlocks conversational answers with your own LLM provider. <button class="btn sm ghost" data-upgrade="llm_copilot">Start trial ${icon('arrowRight')}</button></div></div>` : ''}
|
||
${message.mode ? `<div class="msg-note">${message.mode === 'llm' ? icon('sparkles') : icon('activity')} ${message.mode === 'llm' ? 'LLM narrative' : 'Local analysis'}</div>` : ''}
|
||
</div>
|
||
</div>`;
|
||
}).join('')}
|
||
${state.chatLoading ? `<div class="msg"><div class="msg-avatar">${icon('sparkles')}</div><div class="bubble"><span class="typing"><i></i><i></i><i></i></span></div></div>` : ''}`;
|
||
log.scrollTop = log.scrollHeight;
|
||
};
|
||
|
||
const appendError = (error) => {
|
||
state.chat.push({ role: 'assistant', content: `I could not complete that request: ${error.message}`, error: true });
|
||
};
|
||
|
||
const ask = async (text, { hidden = false } = {}) => {
|
||
if (state.chatLoading) return;
|
||
if (!hidden) state.chat.push({ role: 'user', content: text });
|
||
state.chatLoading = true;
|
||
renderLog();
|
||
send.disabled = true;
|
||
try {
|
||
const messages = state.chat.filter((message) => !message.hidden && !message.error && message.role !== 'system').map((message) => ({ role: message.role, content: message.content }));
|
||
const response = await post('/ai/chat', { messages });
|
||
state.chat.push({
|
||
role: 'assistant',
|
||
content: response.message || 'No response',
|
||
note: response.note,
|
||
mode: response.mode,
|
||
upgrade: Boolean(response.upgrade_required),
|
||
});
|
||
} catch (error) {
|
||
appendError(error);
|
||
} finally {
|
||
state.chatLoading = false;
|
||
send.disabled = false;
|
||
renderLog();
|
||
}
|
||
};
|
||
|
||
renderLog();
|
||
if (!state.chat.length && !state.chatLoading) {
|
||
ask('Give me a capacity briefing for this fleet.', { hidden: true });
|
||
}
|
||
|
||
form.addEventListener('submit', (event) => {
|
||
event.preventDefault();
|
||
const text = input.value.trim();
|
||
if (!text || state.chatLoading) return;
|
||
input.value = '';
|
||
input.style.height = '42px';
|
||
ask(text);
|
||
});
|
||
input.addEventListener('keydown', (event) => {
|
||
if (event.key === 'Enter' && !event.shiftKey) {
|
||
event.preventDefault();
|
||
form.requestSubmit();
|
||
}
|
||
});
|
||
input.addEventListener('input', () => {
|
||
input.style.height = '42px';
|
||
input.style.height = `${Math.min(150, input.scrollHeight)}px`;
|
||
});
|
||
view.querySelectorAll('[data-question]').forEach((button) => button.addEventListener('click', () => ask(button.dataset.question)));
|
||
view.querySelector('[data-clear-chat]').addEventListener('click', () => {
|
||
state.chat = [];
|
||
renderLog();
|
||
ask('Give me a capacity briefing for this fleet.', { hidden: true });
|
||
});
|
||
const configButton = view.querySelector('[data-ai-config]');
|
||
if (configButton) configButton.addEventListener('click', () => openAiConfigModal(config));
|
||
if (llm && !config.configured) {
|
||
// Keep the local briefing visible and make configuration discoverable.
|
||
if (!state.chat.some((message) => message.note)) {
|
||
// no-op: response note will explain the fallback
|
||
}
|
||
}
|
||
};
|
||
|
||
function openAiConfigModal(config) {
|
||
if (!state.boot.features.llm_copilot) { openUpgrade('llm_copilot'); return; }
|
||
openModal({
|
||
title: 'LLM provider',
|
||
sub: 'Any OpenAI-compatible chat completions endpoint',
|
||
wide: true,
|
||
body: `<form id="ai-config-form" class="form-grid">
|
||
<div class="field span-2"><label for="ai-base">Base URL</label>
|
||
<input class="input" id="ai-base" name="base_url" value="${esc(config.base_url || '')}" placeholder="http://127.0.0.1:11434/v1">
|
||
<span class="help">Headroom appends <code>/chat/completions</code>. Works with OpenAI, Azure, Ollama, LM Studio and LiteLLM.</span>
|
||
</div>
|
||
<div class="field"><label for="ai-model">Model</label><input class="input" id="ai-model" name="model" value="${esc(config.model || '')}" placeholder="gpt-4o-mini / llama3.1"></div>
|
||
<div class="field"><label for="ai-key">API key</label><input class="input" type="password" id="ai-key" name="api_key" value="" placeholder="${config.key_set ? 'Saved — leave blank to keep' : 'Optional for local endpoints'}" autocomplete="new-password"></div>
|
||
<div class="span-2 notice">${icon('shield')}<div>The key is stored server-side in SQLite and never returned to the browser. Only fleet aggregates and alert messages are sent to the provider — no credentials.</div></div>
|
||
</form>`,
|
||
footer: `<button class="btn" data-close>Cancel</button><button class="btn primary" type="submit" form="ai-config-form">${icon('check')} Save provider</button>`,
|
||
onMount(modal, close) {
|
||
const form = modal.querySelector('#ai-config-form');
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(form);
|
||
const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') };
|
||
const key = String(formData.get('api_key') || '');
|
||
if (key) payload.api_key = key;
|
||
try {
|
||
await put('/ai/config', payload);
|
||
close();
|
||
toast('LLM provider saved');
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
}
|
||
|
||
/* --------------------------------------------------------------------------
|
||
API & MCP
|
||
-------------------------------------------------------------------------- */
|
||
const API_ENDPOINTS = [
|
||
['GET', '/api/overview', 'Fleet KPIs, pools, leaders and timeline'],
|
||
['GET', '/api/assets', 'Asset inventory with pressure and forecasts'],
|
||
['GET', '/api/assets/{id}', 'Timeseries, forecast and recommendation'],
|
||
['GET', '/api/capacity', 'Groups and aggregated resource pools'],
|
||
['POST', '/api/capacity/simulate', 'What-if simulation'],
|
||
['GET', '/api/alerts', 'Open or resolved alerts'],
|
||
['GET', '/api/modules', 'Collector health and configuration'],
|
||
['POST', '/api/modules/{id}/run', 'Trigger a collection'],
|
||
['POST', '/api/ingest/{module_id}', 'Push assets and metrics'],
|
||
['POST', '/api/mcp', 'MCP JSON-RPC endpoint'],
|
||
];
|
||
|
||
VIEWS.api = async ({ view, token }) => {
|
||
setPage('API & MCP', 'Automation surface for scripts and AI agents');
|
||
const [mcpCatalog, keysData, aiConfig] = await Promise.all([
|
||
get('/mcp').catch(() => null),
|
||
state.boot.user.role === 'admin' ? get('/keys').catch(() => null) : Promise.resolve(null),
|
||
get('/ai/config').catch(() => null),
|
||
]);
|
||
if (token !== state.renderToken) return;
|
||
const tab = state.apiTab;
|
||
const base = location.origin;
|
||
const keys = keysData?.items || [];
|
||
const cat = mcpCatalog || { enabled: false, tools: [], resources: [], example: {} };
|
||
const config = aiConfig?.config || {};
|
||
const tabs = [['rest', 'REST API'], ['keys', 'API keys'], ['mcp', 'MCP server'], ['ai', 'AI provider']];
|
||
|
||
const restPanel = `
|
||
<div class="grid cols-main-rev">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Authenticate</h3><div class="sub">Two supported methods</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="notice">${icon('shield')}<div><strong>Session cookie</strong> — used by this UI. <strong>X-API-Key</strong> — create a key for scripts and agents. Keys inherit the role you assign.</div></div>
|
||
<div class="kv-list mt-16">
|
||
<div><dt>Base URL</dt><dd>${esc(base)}</dd></div>
|
||
<div><dt>Auth header</dt><dd>X-API-Key: hr_…</dd></div>
|
||
<div><dt>OpenAPI</dt><dd><a href="/docs" target="_blank" rel="noopener">/docs</a></dd></div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Endpoints</h3><div class="sub">${API_ENDPOINTS.length} commonly used routes</div></div><div class="actions"><a class="btn sm ghost" href="/docs" target="_blank" rel="noopener">Swagger ${icon('external')}</a></div></div>
|
||
<div class="panel-body"><div class="endpoint-list">${API_ENDPOINTS.map(([method, path, desc]) => `<div class="endpoint"><span class="method ${method.toLowerCase()}">${method}</span><code>${path}</code><span>${desc}</span></div>`).join('')}</div></div>
|
||
</section>
|
||
</div>
|
||
<section class="panel mt-16">
|
||
<div class="panel-head"><div><h3>Quick start</h3><div class="sub">Read the fleet with an API key</div></div><div class="actions"><button class="btn sm ghost" data-copy-target="rest-example">${icon('copy')} Copy</button></div></div>
|
||
<div class="panel-body"><pre class="code-block" id="rest-example">curl -s ${esc(base)}/api/overview \\
|
||
-H "X-API-Key: hr_your_key_here"
|
||
|
||
curl -s ${esc(base)}/api/assets \\
|
||
-H "X-API-Key: hr_your_key_here"</pre>
|
||
<div class="notice mt-16">${icon('code')}<div>Push custom telemetry into an enabled module: <code>POST /api/ingest/http-json</code> with <code>{"assets":[{ "external_id":"ups-1", "name":"UPS", "type":"power", "metrics":{"load_pct":42} }]}</code>.</div></div></div>
|
||
</section>`;
|
||
|
||
const keysPanel = keysData === null
|
||
? `<section class="panel"><div class="panel-body"><div class="notice warn">${icon('lock')}<div>Administrator role required to manage API keys.</div></div></div></section>`
|
||
: `<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>API keys</h3><div class="sub">${keys.length} active</div></div></div>
|
||
<div class="table-wrap"><table class="data">
|
||
<thead><tr><th>Name</th><th>Prefix</th><th>Role</th><th class="num">Last used</th><th class="num">Actions</th></tr></thead>
|
||
<tbody>${keys.length ? keys.map((key) => `<tr>
|
||
<td><div class="name">${esc(key.name)}</div><div class="sub" style="color:var(--faint);font-size:10.5px">created ${fmtDate(key.created_at)}</div></td>
|
||
<td><code class="mono" style="font-size:11px">${esc(key.prefix)}…</code></td>
|
||
<td><span class="pill plain ${key.role === 'admin' ? 'critical' : key.role === 'operator' ? 'watch' : 'muted'}">${esc(key.role)}</span></td>
|
||
<td class="num faint">${key.last_used ? timeAgo(key.last_used) : 'never'}</td>
|
||
<td class="num"><button class="icon-btn danger" data-key-delete="${key.id}" title="Revoke key">${icon('trash')}</button></td>
|
||
</tr>`).join('') : `<tr><td colspan="5" class="table-empty"><strong>No API keys</strong>Create one to automate Headroom.</td></tr>`}</tbody>
|
||
</table></div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Create a key</h3><div class="sub">Shown once, stored hashed</div></div></div>
|
||
<div class="panel-body">
|
||
<form id="key-form" class="form-grid" style="grid-template-columns:1fr">
|
||
<div class="field"><label for="key-name">Name</label><input class="input" id="key-name" name="name" placeholder="Grafana exporter" required></div>
|
||
<div class="field"><label for="key-role">Role</label><select class="select" id="key-role" name="role"><option value="viewer">Viewer — read only</option><option value="operator" selected>Operator — run modules</option><option value="admin">Admin — full control</option></select></div>
|
||
<button class="btn primary" type="submit">${icon('plus')} Create API key</button>
|
||
</form>
|
||
<div class="notice mt-16">${icon('shield')}<div>Revoke unused keys regularly. The plaintext key is never stored and cannot be recovered.</div></div>
|
||
</div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const mcpPanel = `
|
||
${cat.enabled ? '' : `<div class="upgrade-cta mb-16">
|
||
<h3>MCP server is an Enterprise capability</h3>
|
||
<p>Give Claude Desktop, Cursor or a custom agent read access to capacity data and the ability to run collectors. Uses the same signed API keys as the REST API.</p>
|
||
<button class="btn primary mt-16" data-upgrade="mcp_server">${icon('sparkles')} Start a trial</button>
|
||
</div>`}
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Connection</h3><div class="sub">Streamable HTTP · JSON-RPC 2.0</div></div><div class="actions"><span class="pill ${cat.enabled ? 'healthy' : 'muted'}">${cat.enabled ? 'enabled' : 'locked'}</span></div></div>
|
||
<div class="panel-body">
|
||
<div class="kv-list">
|
||
<div><dt>Endpoint</dt><dd>${esc(base)}/api/mcp</dd></div>
|
||
<div><dt>Protocol</dt><dd>${esc(cat.protocol_version || '2024-11-05')}</dd></div>
|
||
<div><dt>Auth</dt><dd>X-API-Key</dd></div>
|
||
<div><dt>Tools</dt><dd>${cat.tools?.length || 0}</dd></div>
|
||
</div>
|
||
<div class="mt-16" style="display:flex;gap:8px;flex-wrap:wrap">
|
||
<button class="btn sm" id="mcp-ping">${icon('activity')} Ping MCP</button>
|
||
<button class="btn sm ghost" data-copy-target="mcp-example">${icon('copy')} Copy client config</button>
|
||
</div>
|
||
<pre class="code-block mt-16" id="mcp-result" hidden></pre>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Client config</h3><div class="sub">Claude Desktop example</div></div></div>
|
||
<div class="panel-body"><pre class="code-block" id="mcp-example">${esc(JSON.stringify(cat.example || {}, null, 2))}</pre></div>
|
||
</section>
|
||
</div>
|
||
<div class="grid cols-main-rev mt-16">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Resources</h3><div class="sub">Read-only context objects</div></div></div>
|
||
<div class="table-wrap"><table class="data"><thead><tr><th>URI</th><th>Description</th></tr></thead><tbody>
|
||
${(cat.resources || []).map((resource) => `<tr><td><code class="mono" style="font-size:11px">${esc(resource.uri)}</code></td><td class="muted">${esc(resource.description || resource.name)}</td></tr>`).join('')}
|
||
</tbody></table></div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Tools</h3><div class="sub">${cat.tools?.length || 0} capabilities</div></div></div>
|
||
<div class="table-wrap"><table class="data"><thead><tr><th>Tool</th><th>Description</th></tr></thead><tbody>
|
||
${(cat.tools || []).map((tool) => `<tr><td><code class="mono" style="font-size:11px">${esc(tool.name)}</code></td><td class="muted">${esc(tool.description)}</td></tr>`).join('')}
|
||
</tbody></table></div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const aiPanel = `
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Provider configuration</h3><div class="sub">${state.boot.features.llm_copilot ? 'Enterprise enabled' : 'Enterprise capability'}</div></div></div>
|
||
<div class="panel-body">
|
||
${state.boot.features.llm_copilot
|
||
? `<form id="ai-page-form" class="form-grid">
|
||
<div class="field span-2"><label for="ai-page-base">Base URL</label><input class="input" id="ai-page-base" name="base_url" value="${esc(config.base_url || '')}" placeholder="http://127.0.0.1:11434/v1"></div>
|
||
<div class="field"><label for="ai-page-model">Model</label><input class="input" id="ai-page-model" name="model" value="${esc(config.model || '')}" placeholder="llama3.1"></div>
|
||
<div class="field"><label for="ai-page-key">API key</label><input class="input" type="password" id="ai-page-key" name="api_key" value="" placeholder="${config.key_set ? 'Saved — leave blank to keep' : 'Optional'}" autocomplete="new-password"></div>
|
||
<div class="span-2"><button class="btn primary" type="submit">${icon('check')} Save provider</button></div>
|
||
</form>`
|
||
: `<div class="notice warn">${icon('lock')}<div>LLM copilot requires Enterprise. The local deterministic analysis remains available in the copilot view.</div></div><button class="btn primary mt-16" data-upgrade="llm_copilot">${icon('sparkles')} Unlock LLM copilot</button>`}
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Provider status</h3><div class="sub">OpenAI-compatible</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="kv-list">
|
||
<div><dt>Configured</dt><dd>${config.configured ? 'yes' : 'no'}</dd></div>
|
||
<div><dt>Base URL</dt><dd>${esc(config.base_url || '—')}</dd></div>
|
||
<div><dt>Model</dt><dd>${esc(config.model || '—')}</dd></div>
|
||
<div><dt>Key</dt><dd>${config.key_set ? 'saved' : 'not set'}</dd></div>
|
||
</div>
|
||
<div class="notice mt-16">${icon('info')}<div>${esc(config.provider_hint || 'Any OpenAI-compatible chat completions endpoint.')}</div></div>
|
||
<a class="btn sm mt-16" href="#/copilot">${icon('sparkles')} Open copilot</a>
|
||
</div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const panels = { rest: restPanel, keys: keysPanel, mcp: mcpPanel, ai: aiPanel };
|
||
view.innerHTML = `
|
||
${pageHead({ eyebrow: 'Platform', title: 'API & MCP', sub: 'Everything in Headroom is available over the REST API. Enterprise adds an MCP server, API keys with roles and an LLM provider.', actions: `<a class="btn sm" href="/docs" target="_blank" rel="noopener">${icon('external')} API docs</a>${refreshButton()}` })}
|
||
<div class="tabs" style="margin-bottom:16px;border:1px solid var(--line);border-radius:10px;background:var(--surface)">
|
||
${tabs.map(([key, label]) => `<button class="tab ${tab === key ? 'on' : ''}" data-api-tab="${key}">${label}</button>`).join('')}
|
||
</div>
|
||
${panels[tab] || restPanel}`;
|
||
|
||
view.querySelectorAll('[data-api-tab]').forEach((button) => button.addEventListener('click', () => {
|
||
state.apiTab = button.dataset.apiTab;
|
||
renderRoute();
|
||
}));
|
||
view.querySelectorAll('[data-copy-target]').forEach((button) => button.addEventListener('click', () => {
|
||
const target = view.querySelector(`#${button.dataset.copyTarget}`);
|
||
if (target) copyText(target.textContent);
|
||
}));
|
||
|
||
if (tab === 'keys' && keysData !== null) {
|
||
view.querySelectorAll('[data-key-delete]').forEach((button) => button.addEventListener('click', async () => {
|
||
if (!(await confirmDialog({ title: 'Revoke API key', message: 'Any client using this key will lose access immediately.', confirmLabel: 'Revoke key', danger: true }))) return;
|
||
try {
|
||
await del(`/keys/${button.dataset.keyDelete}`);
|
||
toast('API key revoked');
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
}));
|
||
const form = view.querySelector('#key-form');
|
||
form?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(form);
|
||
try {
|
||
const result = await post('/keys', { name: String(formData.get('name') || ''), role: String(formData.get('role') || 'viewer') });
|
||
openModal({
|
||
title: 'API key created',
|
||
sub: 'Copy it now — it is shown only once',
|
||
body: `<div class="notice ok mb-16">${icon('key')}<div><strong>${esc(result.name)}</strong> · ${esc(result.role)}</div></div>
|
||
<pre class="code-block" id="new-key-value">${esc(result.key)}</pre>`,
|
||
footer: `<button class="btn primary" data-copy-key>${icon('copy')} Copy key</button><button class="btn" data-close>Done</button>`,
|
||
onMount(modal, close) {
|
||
modal.querySelector('[data-copy-key]').addEventListener('click', () => copyText(result.key));
|
||
modal.querySelector('[data-close]').addEventListener('click', () => { close(); renderRoute(); });
|
||
},
|
||
});
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
}
|
||
|
||
if (tab === 'mcp') {
|
||
const ping = view.querySelector('#mcp-ping');
|
||
ping?.addEventListener('click', async () => {
|
||
const output = view.querySelector('#mcp-result');
|
||
output.hidden = false;
|
||
output.textContent = 'Calling initialize…';
|
||
try {
|
||
const result = await post('/mcp', { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} });
|
||
output.textContent = JSON.stringify(result, null, 2);
|
||
if (result.error) toast(result.error.message || 'MCP call returned an error', 'warn');
|
||
else toast('MCP server responded', 'ok');
|
||
} catch (error) {
|
||
output.textContent = error.message;
|
||
toastError(error);
|
||
}
|
||
});
|
||
}
|
||
|
||
if (tab === 'ai') {
|
||
const form = view.querySelector('#ai-page-form');
|
||
form?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(form);
|
||
const payload = { base_url: String(formData.get('base_url') || ''), model: String(formData.get('model') || '') };
|
||
const key = String(formData.get('api_key') || '');
|
||
if (key) payload.api_key = key;
|
||
try {
|
||
await put('/ai/config', payload);
|
||
toast('LLM provider saved');
|
||
renderRoute();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
}
|
||
};
|
||
|
||
/* --------------------------------------------------------------------------
|
||
Settings
|
||
-------------------------------------------------------------------------- */
|
||
VIEWS.settings = async ({ view, token }) => {
|
||
setPage('Settings', 'Edition, security and platform configuration');
|
||
const isAdmin = state.boot.user.role === 'admin';
|
||
const [settings, license, editions, auditData] = await Promise.all([
|
||
get('/settings'),
|
||
get('/license'),
|
||
get('/editions').catch(() => null),
|
||
isAdmin ? get('/audit?limit=100').catch(() => null) : Promise.resolve(null),
|
||
]);
|
||
if (token !== state.renderToken) return;
|
||
|
||
const tabs = [['general', 'General'], ['license', 'Edition & license'], ['security', 'Security'], ['audit', 'Audit log'], ['about', 'About']];
|
||
const tab = tabs.some(([key]) => key === state.settingsTab) ? state.settingsTab : 'general';
|
||
const paid = license.edition !== 'community';
|
||
const matrix = editions?.matrix || [];
|
||
const audit = auditData?.items || [];
|
||
const sched = settings.scheduler || {};
|
||
const assetLimit = Number(license.limits?.assets ?? 40);
|
||
const assetCount = Number(state.boot.asset_count || 0);
|
||
const assetUsage = assetLimit > 0 ? Math.min(100, Math.round((assetCount / assetLimit) * 100)) : 0;
|
||
const maxRetention = Number(license.limits?.retention_days || 30);
|
||
const trialAvailable = Boolean(license.trial_available) && !paid;
|
||
const canModify = isAdmin;
|
||
const disabled = canModify ? '' : 'disabled';
|
||
|
||
const currentLicense = paid
|
||
? `<div class="license-current mb-16">
|
||
${license.source === 'trial'
|
||
? ring(Math.max(0, Math.min(100, ((Number(license.days_left) || 0) / 30) * 100)), { size: 62, stroke: 7, suffix: 'days' })
|
||
: `<span class="module-icon">${icon('shield')}</span>`}
|
||
<div class="lc-main">
|
||
<strong>${esc(license.label)}</strong>
|
||
<span>${license.customer ? `${esc(license.customer)} · ` : ''}${license.expires ? `Valid until ${fmtDate(license.expires)}` : 'Open-ended license'}${license.days_left != null ? ` · ${license.days_left} days left` : ''}</span>
|
||
</div>
|
||
<span class="badge ${license.source === 'trial' ? 'custom' : 'enterprise'}">${license.source === 'trial' ? 'TRIAL' : 'ACTIVE'}</span>
|
||
</div>`
|
||
: `<div class="license-current mb-16">
|
||
<span class="module-icon">${icon('layers')}</span>
|
||
<div class="lc-main">
|
||
<strong>Community edition</strong>
|
||
<span>Free forever · ${license.limits?.assets ?? 40} assets · ${license.limits?.retention_days ?? 30}-day retention · bundled modules only</span>
|
||
</div>
|
||
<button class="btn sm primary" data-upgrade>${icon('sparkles')} Upgrade</button>
|
||
</div>`;
|
||
|
||
const matrixRows = matrix.map((group) => `
|
||
<tr class="group-row"><td colspan="3">${esc(group.group)}</td></tr>
|
||
${group.features.map((feature) => `<tr>
|
||
<td>${esc(feature.label)}</td>
|
||
<td class="${feature.community ? 'yes' : 'no'}">${feature.community ? icon('check') : icon('minus')}</td>
|
||
<td class="yes">${icon('check')}</td>
|
||
</tr>`).join('')}
|
||
`).join('');
|
||
|
||
const generalPanel = `
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Site & retention</h3><div class="sub">Applied to dashboards, exports and the API</div></div><div class="actions">${canModify ? '' : '<span class="pill muted">read only</span>'}</div></div>
|
||
<div class="panel-body">
|
||
${canModify ? '' : `<div class="notice mb-16">${icon('lock')}<div>Administrator role required to change these settings.</div></div>`}
|
||
<form id="settings-form" class="form-grid">
|
||
<div class="field span-2">
|
||
<label for="set-site">Site name</label>
|
||
<input class="input" id="set-site" name="site_name" maxlength="80" value="${esc(settings.site_name)}" ${disabled} required>
|
||
<span class="help">Shown in the browser title, sign-in screen and reports.</span>
|
||
</div>
|
||
<div class="field">
|
||
<label for="set-retention">Metric retention (days)</label>
|
||
<input class="input" type="number" id="set-retention" name="retention_days" min="7" max="${maxRetention}" value="${esc(settings.retention_days)}" ${disabled}>
|
||
<span class="help">Effective retention: <strong>${settings.effective_retention_days} days</strong>.${paid ? '' : ' Enterprise extends this to 400 days.'}</span>
|
||
</div>
|
||
<div class="field">
|
||
<label for="set-webhook">Alert webhook</label>
|
||
<input class="input" id="set-webhook" name="alert_webhook" placeholder="https://hooks.example.com/headroom" value="${esc(settings.alert_webhook || '')}" ${disabled}>
|
||
<span class="help">${state.boot.features.alert_webhooks ? 'New alerts are POSTed as JSON.' : 'Enterprise feature — the URL is stored now and used after an upgrade.'}</span>
|
||
</div>
|
||
<div class="span-2"><button class="btn primary" type="submit" ${disabled}>${icon('check')} Save settings</button></div>
|
||
</form>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Runtime</h3><div class="sub">This installation</div></div><div class="actions"><span class="pill ${sched.running ? 'healthy' : 'muted'}">${sched.running ? 'scheduler running' : 'scheduler stopped'}</span></div></div>
|
||
<div class="panel-body">
|
||
<div class="kv-list">
|
||
<div><dt>Tick interval</dt><dd>${esc(String(sched.interval_seconds ?? '—'))}s</dd></div>
|
||
<div><dt>Collections run</dt><dd>${esc(String(sched.runs ?? 0))}</dd></div>
|
||
<div><dt>Last tick duration</dt><dd>${sched.last_tick_ms != null ? `${esc(String(sched.last_tick_ms))} ms` : '—'}</dd></div>
|
||
<div><dt>Database</dt><dd title="${esc(settings.db_path)}">${esc(settings.db_path)}</dd></div>
|
||
<div><dt>Modules directory</dt><dd title="${esc(settings.modules_dir)}">${esc(settings.modules_dir)}</dd></div>
|
||
<div><dt>Admin account</dt><dd>${esc(settings.admin_user)}</dd></div>
|
||
</div>
|
||
${sched.last_error ? `<div class="notice crit mt-16">${icon('alert')}<div><strong>Last scheduler error</strong><br>${esc(sched.last_error)}</div></div>` : ''}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<div class="grid cols-2 mt-16">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Asset allowance</h3><div class="sub">${assetLimit > 0 ? 'Community cap' : 'Enterprise — unlimited'}</div></div><div class="actions"><span class="pill ${assetLimit > 0 && assetCount >= assetLimit ? 'tight' : 'plain accent'}">${assetCount}${assetLimit > 0 ? ` / ${assetLimit}` : ''}</span></div></div>
|
||
<div class="panel-body">
|
||
<div class="bar lg" data-band="${assetUsage >= 100 ? 'tight' : assetUsage >= 75 ? 'watch' : 'healthy'}"><span style="width:${assetLimit > 0 ? Math.max(2, assetUsage) : 2}%"></span></div>
|
||
<div class="mt-8" style="color:var(--muted);font-size:11.5px">
|
||
${assetLimit > 0
|
||
? `${Math.max(0, assetLimit - assetCount)} asset slot${assetLimit - assetCount === 1 ? '' : 's'} remaining. The oldest idle assets are never evicted automatically.`
|
||
: `No hard limit. ${assetCount} assets are currently tracked across ${state.boot.edition.features?.length || 0} enabled capabilities.`}
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="panel danger-zone">
|
||
<div class="panel-head"><div><h3>Maintenance</h3><div class="sub">Destructive operations</div></div></div>
|
||
<div class="panel-body">
|
||
<p style="color:var(--muted);font-size:12px;line-height:1.55">Re-seed the installation with the realistic demo fleet. This clears assets, telemetry, alerts and the audit trail before loading a fresh dataset.</p>
|
||
<div class="mt-16" style="display:flex;gap:8px;flex-wrap:wrap">
|
||
<button class="btn danger" data-reseed ${disabled}>${icon('refresh')} Re-seed demo data</button>
|
||
<a class="btn ghost" href="/api/health" target="_blank" rel="noopener">${icon('activity')} Health check</a>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const licensePanel = `
|
||
${currentLicense}
|
||
${license.invalid_license ? `<div class="notice crit mb-16">${icon('alert')}<div><strong>Stored license could not be verified.</strong> It may have been issued by another installation or has been tampered with. Activate a valid key to restore Enterprise features.</div></div>` : ''}
|
||
${license.trial_expired ? `<div class="notice warn mb-16">${icon('clock')}<div>The 30-day trial has ended. Your data is intact; Enterprise capabilities are locked until you activate a license.</div></div>` : ''}
|
||
<section class="panel mb-16">
|
||
<div class="panel-head"><div><h3>Administrator unlock</h3><div class="sub">Enable Enterprise features without a license key</div></div><span class="badge ${license.admin_override ? 'enterprise' : 'community'}">${license.admin_override ? 'ENABLED' : 'DISABLED'}</span></div>
|
||
<div class="panel-body">
|
||
<div class="row space-between wrap" style="gap:12px;align-items:center">
|
||
<div>
|
||
<div style="font-weight:600">Enterprise mode</div>
|
||
<div class="sub">Unlock all Enterprise features across this installation (paid service toggle).</div>
|
||
</div>
|
||
<label class="switch">
|
||
<input type="checkbox" id="enterprise-toggle" ${license.admin_override ? 'checked' : ''} ${canModify ? '' : 'disabled'}>
|
||
<span class="track"></span>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Activate a license</h3><div class="sub">Signed locally with HMAC — no phone home</div></div></div>
|
||
<div class="panel-body">
|
||
<form id="license-form" class="form-grid" style="grid-template-columns:minmax(0,1fr)">
|
||
<div class="field">
|
||
<label for="license-input">License key</label>
|
||
<textarea class="input" id="license-input" name="key" rows="3" placeholder="HR1.…" autocomplete="off" spellcheck="false" ${disabled}></textarea>
|
||
<span class="help">Paste the key exactly as issued. ${canModify ? 'Activation takes effect immediately.' : 'Administrator role required.'}</span>
|
||
</div>
|
||
<button class="btn primary" type="submit" ${disabled}>${icon('key')} Activate license</button>
|
||
</form>
|
||
${trialAvailable ? `<div class="notice ok mt-16">${icon('sparkles')}<div><strong>30-day Enterprise trial</strong> — no payment details, no phone home. One trial per installation.</div></div>
|
||
<button class="btn mt-16" data-start-trial ${disabled}>${icon('sparkles')} Start trial</button>` : ''}
|
||
${paid ? `<button class="btn ghost mt-16" data-deactivate-license ${disabled}>${icon('x')} Deactivate license</button>` : ''}
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Plan comparison</h3><div class="sub">${matrix.reduce((sum, group) => sum + group.features.length, 0)} capabilities</div></div></div>
|
||
<div class="table-wrap">
|
||
<table class="matrix">
|
||
<thead><tr><th>Capability</th><th>Community</th><th>Enterprise</th></tr></thead>
|
||
<tbody>${matrixRows || `<tr><td colspan="3" class="table-empty">Could not load the edition matrix.</td></tr>`}</tbody>
|
||
</table>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
${state.boot.dev_license_enabled ? `<section class="panel mt-16">
|
||
<div class="panel-head"><div><h3>Development license issuer</h3><div class="sub">Visible because HEADROOM_ALLOW_DEV_LICENSE is enabled</div></div><span class="badge custom">DEV</span></div>
|
||
<div class="panel-body">
|
||
<div class="notice warn mb-16">${icon('alert')}<div>Never enable this on a shared installation. Keys are signed with this installation's secret; revoke the environment variable afterwards.</div></div>
|
||
<form id="dev-license-form" class="form-grid">
|
||
<div class="field"><label for="dev-customer">Customer</label><input class="input" id="dev-customer" name="customer" value="Homelab" maxlength="80" ${disabled}></div>
|
||
<div class="field"><label for="dev-days">Valid for (days)</label><input class="input" type="number" id="dev-days" name="days" min="1" max="3650" value="365" ${disabled}></div>
|
||
<div class="span-2"><button class="btn" type="submit" ${disabled}>${icon('key')} Issue license key</button></div>
|
||
</form>
|
||
</div>
|
||
</section>` : ''}`;
|
||
|
||
const securityPanel = `
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Change password</h3><div class="sub">${esc(state.boot.user.username)} · ${esc(state.boot.user.role)}</div></div></div>
|
||
<div class="panel-body">
|
||
<form id="password-form" class="form-grid">
|
||
<div class="field span-2"><label for="pw-current">Current password</label><input class="input" type="password" id="pw-current" name="current_password" autocomplete="current-password" required></div>
|
||
<div class="field"><label for="pw-new">New password</label><input class="input" type="password" id="pw-new" name="new_password" autocomplete="new-password" minlength="8" required><span class="help">At least 8 characters.</span></div>
|
||
<div class="field"><label for="pw-confirm">Confirm new password</label><input class="input" type="password" id="pw-confirm" name="confirm_password" autocomplete="new-password" minlength="8" required></div>
|
||
<div class="span-2"><button class="btn primary" type="submit">${icon('lock')} Update password</button></div>
|
||
</form>
|
||
<div class="notice mt-16">${icon('shield')}<div>Passwords are stored as salted PBKDF2 hashes. Existing API keys are not affected by a password change.</div></div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Access</h3><div class="sub">Session and credentials</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="kv-list">
|
||
<div><dt>Signed in as</dt><dd>${esc(state.boot.user.username)}</dd></div>
|
||
<div><dt>Role</dt><dd>${esc(state.boot.user.role)}</dd></div>
|
||
<div><dt>Session</dt><dd>HttpOnly cookie</dd></div>
|
||
<div><dt>API keys</dt><dd>${isAdmin ? 'manageable' : 'admin only'}</dd></div>
|
||
<div><dt>Edition</dt><dd>${esc(license.label)}</dd></div>
|
||
</div>
|
||
<div class="mt-16" style="display:flex;gap:8px;flex-wrap:wrap">
|
||
<button class="btn sm" data-goto-api-keys>${icon('key')} Manage API keys</button>
|
||
<button class="btn sm ghost" data-logout>${icon('logout')} Sign out</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</div>`;
|
||
|
||
const auditPanel = !isAdmin
|
||
? `<section class="panel"><div class="panel-body"><div class="notice warn">${icon('lock')}<div>The audit trail is visible to administrators only.</div></div></div></section>`
|
||
: `<section class="panel">
|
||
<div class="panel-head">
|
||
<div><h3>Audit trail</h3><div class="sub">Latest ${audit.length} recorded actions</div></div>
|
||
<div class="actions">
|
||
${state.boot.features.audit_export
|
||
? `<button class="btn sm" data-audit-export>${icon('download')} Export CSV</button>`
|
||
: `<button class="btn sm" data-upgrade="audit_export">${icon('lock')} Export with Enterprise</button>`}
|
||
${refreshButton()}
|
||
</div>
|
||
</div>
|
||
<div class="table-wrap"><table class="data">
|
||
<thead><tr><th>When</th><th>Actor</th><th>Action</th><th>Target</th><th>Detail</th></tr></thead>
|
||
<tbody>${audit.length ? audit.map((item) => `<tr>
|
||
<td class="faint" style="white-space:nowrap">${esc(fmtDate(item.ts, true))}</td>
|
||
<td><span class="pill plain">${esc(item.actor)}</span></td>
|
||
<td><code class="mono" style="font-size:11px">${esc(item.action)}</code></td>
|
||
<td class="muted">${esc(item.target || '—')}</td>
|
||
<td class="faint" style="max-width:420px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(item.detail || '')}">${esc(item.detail || '—')}</td>
|
||
</tr>`).join('') : `<tr><td colspan="5" class="table-empty"><strong>No audit entries yet</strong>Administrative actions will appear here.</td></tr>`}</tbody>
|
||
</table></div>
|
||
</section>`;
|
||
|
||
const enabledFeatures = state.boot.edition.features || [];
|
||
const aboutPanel = `
|
||
<div class="grid cols-main">
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>About Headroom</h3><div class="sub">Know your headroom. Before you run out.</div></div><span class="pill plain accent">v${esc(state.boot.version)}</span></div>
|
||
<div class="panel-body">
|
||
<p style="color:var(--text-2);font-size:13px;line-height:1.65">Headroom is a modular capacity-management console for homelabs and small fleets. It collects utilisation from hypervisors, storage, log platforms and bare-metal hosts, forecasts exhaustion, evaluates policies and lets you simulate upgrades before you buy hardware.</p>
|
||
<div class="kv-list mt-16">
|
||
<div><dt>Edition</dt><dd>${esc(license.label)}</dd></div>
|
||
<div><dt>Source</dt><dd>${esc(license.source)}</dd></div>
|
||
<div><dt>Assets tracked</dt><dd>${assetCount}</dd></div>
|
||
<div><dt>Open alerts</dt><dd>${state.boot.open_alerts ?? 0}</dd></div>
|
||
<div><dt>API version</dt><dd>v1</dd></div>
|
||
<div><dt>Storage</dt><dd>SQLite (WAL)</dd></div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
<section class="panel">
|
||
<div class="panel-head"><div><h3>Resources</h3><div class="sub">Documentation and integration points</div></div></div>
|
||
<div class="panel-body">
|
||
<div class="endpoint-list">
|
||
<a class="endpoint" href="/docs" target="_blank" rel="noopener"><span class="method get">GET</span><code>/docs</code><span>OpenAPI explorer</span></a>
|
||
<a class="endpoint" href="/api/health" target="_blank" rel="noopener"><span class="method get">GET</span><code>/api/health</code><span>Liveness and scheduler state</span></a>
|
||
<a class="endpoint" href="#/api"><span class="method post">API</span><code>/api/mcp</code><span>MCP server and client config</span></a>
|
||
<a class="endpoint" href="#/modules"><span class="method put">MOD</span><code>modules/</code><span>Bundled and custom collectors</span></a>
|
||
</div>
|
||
<div class="notice mt-16">${icon('info')}<div><strong>MCI / AI integration</strong> is implemented as MCP (JSON-RPC over HTTP) plus an OpenAI-compatible copilot provider, so agents and local LLMs can read capacity data with the same API keys.</div></div>
|
||
<div class="notice mt-16">${icon('terminal')}<div>The installation is fully self-hosted. No telemetry leaves this machine; the only outbound calls are to the integrations and LLM provider you configure yourself.</div></div>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
${paid ? '' : `<div class="upgrade-cta mt-16">
|
||
<h3>Ready for the next rack?</h3>
|
||
<p>Enterprise removes the 40-asset cap, keeps 400 days of history, unlocks custom module uploads, webhooks, audit export and the MCP server.</p>
|
||
<div class="upgrade-features">
|
||
<div class="upgrade-feature">${icon('check')}<span>Unlimited assets</span></div>
|
||
<div class="upgrade-feature">${icon('check')}<span>Custom modules</span></div>
|
||
<div class="upgrade-feature">${icon('check')}<span>LLM copilot</span></div>
|
||
<div class="upgrade-feature">${icon('check')}<span>MCP server</span></div>
|
||
</div>
|
||
<button class="btn primary" data-upgrade>${icon('sparkles')} Unlock Enterprise</button>
|
||
</div>`}`;
|
||
|
||
const panels = { general: generalPanel, license: licensePanel, security: securityPanel, audit: auditPanel, about: aboutPanel };
|
||
|
||
view.innerHTML = `
|
||
${pageHead({ eyebrow: 'System', title: 'Settings', sub: 'Edition, security, retention and platform maintenance.', actions: refreshButton() })}
|
||
<div class="tabs" style="margin-bottom:16px;border:1px solid var(--line);border-radius:10px;background:var(--surface)">
|
||
${tabs.map(([key, label]) => `<button class="tab ${tab === key ? 'on' : ''}" data-settings-tab="${key}">${label}</button>`).join('')}
|
||
</div>
|
||
${panels[tab] || generalPanel}`;
|
||
|
||
view.querySelectorAll('[data-settings-tab]').forEach((button) => button.addEventListener('click', () => {
|
||
state.settingsTab = button.dataset.settingsTab;
|
||
renderRoute();
|
||
}));
|
||
|
||
const refreshAll = async () => {
|
||
await refreshBootstrap();
|
||
renderRoute();
|
||
};
|
||
|
||
if (tab === 'general' && canModify) {
|
||
view.querySelector('#settings-form')?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(event.target);
|
||
const retention = Number(formData.get('retention_days'));
|
||
if (!Number.isFinite(retention)) { toast('Enter a retention period', 'warn'); return; }
|
||
try {
|
||
await put('/settings', {
|
||
site_name: String(formData.get('site_name') || ''),
|
||
retention_days: retention,
|
||
alert_webhook: String(formData.get('alert_webhook') || ''),
|
||
});
|
||
toast('Settings saved');
|
||
await refreshAll();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
view.querySelector('[data-reseed]')?.addEventListener('click', async () => {
|
||
const ok = await confirmDialog({
|
||
title: 'Re-seed demo data',
|
||
message: 'This deletes every asset, sample, alert, policy and audit entry, then installs the demo fleet again. API keys and users are preserved. Continue?',
|
||
confirmLabel: 'Re-seed installation',
|
||
danger: true,
|
||
});
|
||
if (!ok) return;
|
||
try {
|
||
const result = await post('/admin/reseed');
|
||
toast(`${result.assets} assets restored`, 'ok', 'Demo data re-seeded');
|
||
await refreshAll();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
}
|
||
|
||
if (tab === 'license') {
|
||
view.querySelector('#enterprise-toggle')?.addEventListener('change', async (event) => {
|
||
if (!(state.boot.user && state.boot.user.role === 'admin')) {
|
||
event.target.checked = !event.target.checked;
|
||
return;
|
||
}
|
||
try {
|
||
await post('/license/enterprise', { enabled: event.target.checked });
|
||
toast(event.target.checked ? 'Enterprise mode enabled' : 'Enterprise mode disabled', 'ok');
|
||
await refreshAll();
|
||
} catch (error) {
|
||
toastError(error);
|
||
await refreshAll();
|
||
}
|
||
});
|
||
view.querySelector('#license-form')?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(event.target);
|
||
const key = String(formData.get('key') || '').trim();
|
||
if (!key) { toast('Paste a license key first', 'warn'); return; }
|
||
try {
|
||
await post('/license/activate', { key });
|
||
toast('License activated. Enterprise features are unlocked.', 'ok', 'Edition upgraded');
|
||
await refreshAll();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
view.querySelector('[data-start-trial]')?.addEventListener('click', async (event) => {
|
||
const button = event.currentTarget;
|
||
button.disabled = true;
|
||
try {
|
||
await post('/license/trial');
|
||
toast('30-day Enterprise trial started', 'ok', 'Trial active');
|
||
await refreshAll();
|
||
} catch (error) { button.disabled = false; toastError(error); }
|
||
});
|
||
view.querySelector('[data-deactivate-license]')?.addEventListener('click', async () => {
|
||
const ok = await confirmDialog({
|
||
title: 'Deactivate license',
|
||
message: 'The installation returns to the Community edition. Existing data stays, but Enterprise features become unavailable immediately.',
|
||
confirmLabel: 'Deactivate',
|
||
danger: true,
|
||
});
|
||
if (!ok) return;
|
||
try {
|
||
await del('/license');
|
||
toast('License deactivated');
|
||
await refreshAll();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
view.querySelector('#dev-license-form')?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(event.target);
|
||
try {
|
||
const result = await post('/license/dev-issue', {
|
||
customer: String(formData.get('customer') || 'Homelab'),
|
||
days: Number(formData.get('days') || 365),
|
||
});
|
||
openModal({
|
||
title: 'Development license issued',
|
||
sub: `${esc(result.customer)} · ${esc(String(result.days))} days`,
|
||
body: `<div class="notice ok mb-16">${icon('key')}<div>This key is signed for <strong>this installation only</strong>.</div></div>
|
||
<pre class="code-block" id="dev-key-value">${esc(result.key)}</pre>`,
|
||
footer: `<button class="btn" data-copy-dev-key>${icon('copy')} Copy</button><button class="btn primary" data-activate-dev-key>${icon('check')} Activate now</button><button class="btn ghost" data-close>Close</button>`,
|
||
onMount(modal, close) {
|
||
modal.querySelector('[data-copy-dev-key]').addEventListener('click', () => copyText(result.key));
|
||
modal.querySelector('[data-activate-dev-key]').addEventListener('click', async () => {
|
||
try {
|
||
await post('/license/activate', { key: result.key });
|
||
close();
|
||
toast('Development license activated', 'ok', 'Enterprise');
|
||
await refreshAll();
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
},
|
||
});
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
}
|
||
|
||
if (tab === 'security') {
|
||
view.querySelector('#password-form')?.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const formData = new FormData(event.target);
|
||
const next = String(formData.get('new_password') || '');
|
||
if (next !== String(formData.get('confirm_password') || '')) {
|
||
toast('New passwords do not match', 'warn');
|
||
return;
|
||
}
|
||
try {
|
||
await put('/auth/password', {
|
||
current_password: String(formData.get('current_password') || ''),
|
||
new_password: next,
|
||
});
|
||
event.target.reset();
|
||
toast('Password updated');
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
view.querySelector('[data-goto-api-keys]')?.addEventListener('click', () => {
|
||
state.apiTab = 'keys';
|
||
location.hash = '#/api';
|
||
});
|
||
}
|
||
|
||
if (tab === 'audit' && isAdmin) {
|
||
view.querySelector('[data-audit-export]')?.addEventListener('click', async () => {
|
||
try {
|
||
const csv = await request('/export/audit.csv');
|
||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement('a');
|
||
link.href = url;
|
||
link.download = 'headroom-audit.csv';
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
URL.revokeObjectURL(url);
|
||
toast('Audit log exported');
|
||
} catch (error) { toastError(error); }
|
||
});
|
||
}
|
||
};
|
||
|
||
init();
|