Incidents stay separate until Alertmanager groups their alerts, but a bad
release can break the API, the connection pool and a dozen pods in
different groups, and three months later each incident on its own says
little. An event is the context they share: a release, a change, a
maintenance window or an outage. Incidents attach to it, many to many,
and one of them can be marked as the trigger. Incidents are never merged,
so each keeps its own timeline, assignee and metrics; merging would have
thrown that away and could not be undone.
Nothing attaches by itself. An incident's page and
GET /api/incidents/{id}/related-events suggest events within two hours of
it, and a person decides. Events are team-scoped like incidents, kind is
a closed set (a CHECK constraint, so the UI can colour and filter by it),
and they are hard-deleted: the incidents stay and each one's timeline
records the detach. A repeated external_id returns the event already
recorded, so CI can post a release marker and retry safely. Figures such
as time to first ack and the first alarm to last resolution are computed
when an event is read and never stored.
The web UI gets an Events page and an event page with a merged timeline,
an Events card on the incident, and a tag on queue rows. make dev seeds a
release and a maintenance window.
All of it is additive. Migration 004 only creates tables, so v0.53.1
reads the same database and ignores them. The incident JSON gains
event_count (always present) and events (omitted when empty, so clients
detect support from event_count). terdut-tui keeps working unchanged and
simply does not show events yet; no TUI version is required and none is
excluded. The operator's client is untouched. The Prometheus allowlist, the CSP and the
resource limits do not change.
746 lines
29 KiB
JavaScript
746 lines
29 KiB
JavaScript
// Events: a release, a change, a maintenance window or an outage, with the
|
||
// incidents it explains attached. The list is at /events and one event at
|
||
// /events/{id}; the incident page links here and attaches through the helpers
|
||
// at the bottom of this file.
|
||
|
||
import * as api from './api.js';
|
||
import * as poll from './poll.js';
|
||
import {
|
||
h, clear, icon, badge, severityBadge, openSheet, closeSheet, confirm, toast, spinner, emptyState,
|
||
} from './ui.js';
|
||
import {
|
||
ago, when, duration, localInput, isoDate, STATUS_LABEL,
|
||
} from './format.js';
|
||
import { state, myID } from './state.js';
|
||
import { navigate } from './app.js';
|
||
|
||
const view = () => document.getElementById('view-events');
|
||
|
||
export const KINDS = [
|
||
{ id: 'release', label: 'Release' },
|
||
{ id: 'change', label: 'Change' },
|
||
{ id: 'maintenance', label: 'Maintenance' },
|
||
{ id: 'outage', label: 'Outage' },
|
||
{ id: 'other', label: 'Other' },
|
||
];
|
||
const kindLabel = (id) => (KINDS.find((k) => k.id === id) || { label: id }).label;
|
||
|
||
// How far from an event an incident counts as "around" it when picking which to
|
||
// attach. The same two hours the server uses for its suggestions.
|
||
const AROUND = 2 * 60 * 60 * 1000;
|
||
const DAY = 24 * 60 * 60 * 1000;
|
||
|
||
// The list.
|
||
let kind = '';
|
||
let items = null;
|
||
let listError = null;
|
||
|
||
// One event.
|
||
let currentID = null;
|
||
let ev = null;
|
||
let entries = [];
|
||
let error = null;
|
||
let busy = false;
|
||
|
||
export function show(route) {
|
||
const id = route && route.event != null ? route.event : null;
|
||
// Coming back to the list from an incident keeps what it showed, and
|
||
// refreshes it underneath; a different event starts empty.
|
||
if (id !== currentID) {
|
||
currentID = id;
|
||
ev = null;
|
||
entries = [];
|
||
error = null;
|
||
listError = null;
|
||
if (id == null) items = null;
|
||
}
|
||
render();
|
||
refresh();
|
||
}
|
||
|
||
export async function refresh() {
|
||
const id = currentID;
|
||
try {
|
||
if (id == null) {
|
||
const requested = kind;
|
||
const query = { limit: 200, kind: requested };
|
||
if (state.selectedTeamID != null) query.team_id = state.selectedTeamID;
|
||
const result = await api.events(query);
|
||
if (id !== currentID || requested !== kind) return;
|
||
items = result;
|
||
listError = null;
|
||
} else {
|
||
const [e, t] = await Promise.all([api.event(id), api.eventTimeline(id)]);
|
||
if (id !== currentID) return;
|
||
ev = e;
|
||
entries = t;
|
||
error = null;
|
||
}
|
||
} catch (err) {
|
||
if (id !== currentID) return;
|
||
if (id == null) listError = err.status === 404 ? 'This server does not support events yet.' : err.message;
|
||
else error = err.status === 404 ? 'This event does not exist.' : err.message;
|
||
}
|
||
render();
|
||
}
|
||
|
||
function render() {
|
||
if (currentID == null) renderList();
|
||
else renderDetail();
|
||
}
|
||
|
||
// ---------- shared bits ----------
|
||
|
||
const kindBadge = (k) => h('span', { class: `badge plain ev-kind ev-${k}`, text: kindLabel(k) });
|
||
|
||
function isOwner(teamID) {
|
||
const t = (state.teams || []).find((x) => x.id === teamID);
|
||
return (t && t.role === 'owner') || Boolean(state.me?.user?.is_admin);
|
||
}
|
||
|
||
function figures(e) {
|
||
const out = [];
|
||
if (!e.incident_count) {
|
||
out.push(h('span', { class: 'faint', text: 'No incidents' }));
|
||
return out;
|
||
}
|
||
out.push(h('span', { text: `${e.incident_count} incident${e.incident_count === 1 ? '' : 's'}` }));
|
||
if (e.open_incident_count > 0) out.push(badge(`${e.open_incident_count} open`, 'st-triggered'));
|
||
else if (e.span_seconds != null) out.push(h('span', { text: `resolved in ${duration(e.span_seconds * 1000)}` }));
|
||
return out;
|
||
}
|
||
|
||
// ---------- the list ----------
|
||
|
||
const monthFmt = new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
|
||
|
||
function renderList() {
|
||
const chips = h('div', { class: 'chips', role: 'tablist', 'aria-label': 'Kind' },
|
||
[{ id: '', label: 'All' }, ...KINDS].map((k) => h('button', {
|
||
class: 'chip',
|
||
type: 'button',
|
||
role: 'tab',
|
||
'aria-selected': String(k.id === kind),
|
||
onclick: () => setKind(k.id),
|
||
text: k.label,
|
||
})));
|
||
|
||
let body;
|
||
if (listError && !items) body = h('div', { class: 'load-error', text: listError });
|
||
else if (!items) body = spinner();
|
||
else if (!items.length) {
|
||
body = emptyState('No events',
|
||
kind ? 'None of this kind yet.'
|
||
: 'Record a release, a change or an outage, then attach the incidents it caused.', 'timeline');
|
||
} else {
|
||
body = h('div', { class: 'ev-list' },
|
||
listError && h('div', { class: 'load-error', text: `Showing older data: ${listError}` }),
|
||
byMonth(items));
|
||
}
|
||
|
||
clear(view(),
|
||
h('div', { class: 'page-head' },
|
||
h('h2', { text: 'Events' }),
|
||
h('button', { class: 'btn btn-primary btn-sm', type: 'button', onclick: () => createEvent() }, icon('plus'), 'New event')),
|
||
chips,
|
||
body);
|
||
}
|
||
|
||
function setKind(id) {
|
||
if (id === kind) return;
|
||
kind = id;
|
||
items = null;
|
||
render();
|
||
refresh();
|
||
}
|
||
|
||
function byMonth(list) {
|
||
const groups = [];
|
||
for (const e of list) {
|
||
const label = monthFmt.format(new Date(e.started_at));
|
||
const last = groups[groups.length - 1];
|
||
if (last && last.label === label) last.events.push(e);
|
||
else groups.push({ label, events: [e] });
|
||
}
|
||
return groups.map((g) => h('section', { class: 'ev-month' },
|
||
h('h3', { class: 'ev-month-title', text: g.label }),
|
||
h('div', { class: 'ev-group' }, g.events.map(eventRow))));
|
||
}
|
||
|
||
function eventRow(e) {
|
||
const shown = e.incidents || [];
|
||
const more = e.incident_count - shown.length;
|
||
const team = state.teams.length > 1 && state.selectedTeamID == null && e.team_name
|
||
? h('span', { class: 'row-team', text: e.team_name })
|
||
: null;
|
||
return h('a', { class: `row ev-row ev-${e.kind}`, href: `/events/${e.id}` },
|
||
h('div', { class: 'row-title', text: e.title }),
|
||
h('div', { class: 'row-age', title: e.started_at, text: when(e.started_at) }),
|
||
h('div', { class: 'row-meta' },
|
||
kindBadge(e.kind),
|
||
team,
|
||
h('span', { text: e.source === 'api' ? 'recorded by API' : e.created_by ? `by ${e.created_by}` : 'manual' }),
|
||
...figures(e)),
|
||
shown.length > 0 && h('ul', { class: 'ev-incs' },
|
||
shown.map((i) => h('li', {},
|
||
i.is_trigger && h('span', { class: 'ev-trigger', title: 'Trigger', text: '★' }),
|
||
i.severity && severityBadge(i.severity),
|
||
h('span', { class: 'ev-inc-title', text: i.title }),
|
||
h('span', { class: 'faint', text: STATUS_LABEL[i.status] || i.status }))),
|
||
more > 0 && h('li', { class: 'faint', text: `+ ${more} more` })),
|
||
);
|
||
}
|
||
|
||
// ---------- one event ----------
|
||
|
||
function renderDetail() {
|
||
const head = h('div', { class: 'detail-head' },
|
||
h('a', { class: 'btn btn-ghost btn-icon back', href: '/events', 'aria-label': 'Back to events' }, icon('back')),
|
||
h('span', { class: 'crumb', text: `Event #${currentID}` }),
|
||
ev && h('div', { class: 'ev-head-actions' },
|
||
h('button', { class: 'btn btn-ghost btn-sm', type: 'button', onclick: editEvent, disabled: busy }, icon('note'), 'Edit'),
|
||
isOwner(ev.team_id) && h('button', {
|
||
class: 'btn btn-ghost btn-sm', type: 'button', onclick: removeEvent, disabled: busy, 'aria-label': 'Delete event',
|
||
}, icon('trash'))));
|
||
|
||
if (!ev) {
|
||
clear(view(), h('div', { class: 'ev-detail' }, head,
|
||
error ? h('div', { class: 'load-error', text: error }) : spinner()));
|
||
return;
|
||
}
|
||
|
||
clear(view(),
|
||
h('article', { class: 'ev-detail' },
|
||
head,
|
||
error && h('div', { class: 'load-error', text: `Showing older data: ${error}` }),
|
||
h('h1', { class: 'detail-title', text: ev.title }),
|
||
h('div', { class: 'detail-badges' }, detailBadges()),
|
||
facts(),
|
||
tiles(),
|
||
summarySection(),
|
||
incidentsSection(),
|
||
timelineSection()));
|
||
}
|
||
|
||
function detailBadges() {
|
||
const out = [kindBadge(ev.kind)];
|
||
if (ev.incident_count) {
|
||
out.push(ev.open_incident_count > 0
|
||
? badge(`${ev.open_incident_count} open`, 'st-triggered')
|
||
: badge('All resolved', 'st-resolved'));
|
||
}
|
||
if (ev.worst_severity) out.push(severityBadge(ev.worst_severity));
|
||
return out;
|
||
}
|
||
|
||
function recordedBy() {
|
||
if (ev.created_by) return ev.created_by === state.me?.user?.username ? 'you' : ev.created_by;
|
||
if (ev.created_by_service_account) return ev.created_by_service_account;
|
||
return ev.source === 'api' ? 'a service account' : 'someone who has since left';
|
||
}
|
||
|
||
function facts() {
|
||
const rows = [];
|
||
const add = (k, ...v) => rows.push(h('dt', { text: k }), h('dd', {}, ...v));
|
||
add('Started', when(ev.started_at), h('span', { class: 'sub', text: ` · ${ago(ev.started_at)}` }));
|
||
if (ev.ended_at) add('Ended', when(ev.ended_at), h('span', { class: 'sub', text: ` · lasted ${duration(Date.parse(ev.ended_at) - Date.parse(ev.started_at))}` }));
|
||
else {
|
||
add('Ended', h('span', { class: 'faint', text: 'No end recorded ' }),
|
||
h('button', { class: 'btn btn-sm', type: 'button', onclick: endNow, disabled: busy }, 'Mark ended now'));
|
||
}
|
||
if (state.teams.length > 1 && ev.team_name) add('Team', ev.team_name);
|
||
add('Recorded by', recordedBy(), h('span', { class: 'sub', text: ` · ${ago(ev.created_at)}` }));
|
||
// The server accepts http(s) only, so this cannot be a javascript: link; the
|
||
// check is here too so that stays true if that ever changes.
|
||
if (ev.external_url && /^https?:\/\//i.test(ev.external_url)) {
|
||
add('Link', h('a', { href: ev.external_url, target: '_blank', rel: 'noopener noreferrer' },
|
||
`${ev.external_id || 'Open'} ↗`));
|
||
}
|
||
return h('div', { class: 'card' }, h('dl', { class: 'facts' }, rows));
|
||
}
|
||
|
||
function tiles() {
|
||
if (!ev.incident_count) return null;
|
||
const tile = (value, label) => h('div', { class: 'ev-tile' }, h('strong', { text: value }), h('span', { text: label }));
|
||
return h('div', { class: 'ev-tiles' },
|
||
tile(String(ev.incident_count), ev.incident_count === 1 ? 'Incident' : 'Incidents'),
|
||
tile(ev.time_to_first_ack_seconds != null ? duration(ev.time_to_first_ack_seconds * 1000) : '–', 'To first ack'),
|
||
tile(ev.span_seconds != null ? duration(ev.span_seconds * 1000) : '–', ev.span_seconds != null ? 'First alarm to all resolved' : 'Still open'),
|
||
);
|
||
}
|
||
|
||
function summarySection() {
|
||
return h('section', { class: 'section' },
|
||
h('h2', { class: 'section-title' },
|
||
h('span', { text: 'Summary' }),
|
||
h('button', { class: 'btn btn-ghost btn-sm', type: 'button', onclick: editEvent, disabled: busy }, icon('note'), 'Edit')),
|
||
ev.summary
|
||
? h('div', { class: 'card card-pad ev-summary', text: ev.summary })
|
||
: h('div', { class: 'card card-pad faint', text: 'No summary yet. Say what happened and what was done, for whoever reads this in three months.' }));
|
||
}
|
||
|
||
function incidentsSection() {
|
||
const list = ev.incidents || [];
|
||
return h('section', { class: 'section' },
|
||
h('h2', { class: 'section-title' },
|
||
h('span', { text: `Incidents (${list.length})` }),
|
||
h('button', { class: 'btn btn-ghost btn-sm', type: 'button', onclick: attachIncidents, disabled: busy },
|
||
icon('plus'), 'Attach')),
|
||
list.length
|
||
? h('div', { class: 'card' }, list.map(incidentItem))
|
||
: h('div', { class: 'card card-pad faint', text: 'Nothing attached. Attach the incidents this explains.' }));
|
||
}
|
||
|
||
function incidentItem(i) {
|
||
return h('div', { class: 'ev-inc-row' },
|
||
h('button', {
|
||
class: `ev-star${i.is_trigger ? ' on' : ''}`,
|
||
type: 'button',
|
||
'aria-pressed': String(i.is_trigger),
|
||
title: i.is_trigger ? 'Trigger: the first domino. Click to clear.' : 'Mark as the trigger',
|
||
disabled: busy,
|
||
onclick: () => run(() => api.setEventTrigger(ev.id, i.is_trigger ? null : i.incident_id)),
|
||
}, icon('star')),
|
||
h('a', { class: 'ev-inc-link', href: `/incidents/${i.incident_id}` },
|
||
h('span', { class: 'ev-inc-title', text: i.title }),
|
||
h('span', { class: 'sub', text: `#${i.incident_id} · ${when(i.triggered_at)}` })),
|
||
i.severity && severityBadge(i.severity),
|
||
badge(STATUS_LABEL[i.status] || i.status, `st-${i.status}`),
|
||
h('button', {
|
||
class: 'btn btn-ghost btn-sm', type: 'button', 'aria-label': `Detach ${i.title}`, disabled: busy,
|
||
onclick: () => run(() => api.detachIncident(ev.id, i.incident_id), 'Detached'),
|
||
}, icon('trash')));
|
||
}
|
||
|
||
// ---------- timeline ----------
|
||
|
||
const INCIDENT_ACTION = {
|
||
triggered: 'triggered',
|
||
acknowledged: 'acknowledged',
|
||
unacknowledged: 'acknowledgement cleared',
|
||
assigned: 'assigned',
|
||
snoozed: 'snoozed',
|
||
unsnoozed: 'snooze ended',
|
||
resolved: 'resolved',
|
||
archived: 'archived',
|
||
unarchived: 'unarchived',
|
||
note: 'noted',
|
||
resolution_note: 'noted what fixed it',
|
||
escalated: 'escalated',
|
||
deadman_silent: 'heartbeat went silent',
|
||
};
|
||
|
||
const ENTRY_ICON = {
|
||
started: 'timeline', ended: 'checkCircle', note: 'note', resolution_note: 'note',
|
||
triggered: 'bell', acknowledged: 'check', unacknowledged: 'undo', assigned: 'user',
|
||
snoozed: 'clock', unsnoozed: 'clock', resolved: 'checkCircle', escalated: 'arrowUp',
|
||
archived: 'archive', unarchived: 'undo', deadman_silent: 'alertTriangle',
|
||
};
|
||
|
||
function entryActor(e) {
|
||
if (e.user_id != null) return e.user_id === myID() ? 'you' : (e.username || 'someone');
|
||
if (e.service_account_id != null) return e.service_account_name || 'a service account';
|
||
return null;
|
||
}
|
||
|
||
function entryText(e) {
|
||
const who = entryActor(e);
|
||
const strong = (t) => h('span', { class: 'who', text: t });
|
||
if (e.source === 'event') {
|
||
if (e.type === 'started') return ['Event started'];
|
||
if (e.type === 'ended') return ['Event ended'];
|
||
return [strong(who || 'someone'), ' added a note'];
|
||
}
|
||
const link = h('a', { href: `/incidents/${e.incident_id}`, text: `#${e.incident_id} ${e.incident_title}` });
|
||
const action = INCIDENT_ACTION[e.type] || e.type;
|
||
// On an 'assigned' entry the user is the assignee, not the actor.
|
||
if (e.type === 'assigned') return [link, ' assigned to ', strong(who || 'someone')];
|
||
return [link, ` ${action}`, who && !['triggered', 'deadman_silent'].includes(e.type) ? [' by ', strong(who)] : null];
|
||
}
|
||
|
||
function timelineSection() {
|
||
return h('section', { class: 'section' },
|
||
h('h2', { class: 'section-title' },
|
||
h('span', { text: 'Timeline' }),
|
||
h('button', { class: 'btn btn-ghost btn-sm', type: 'button', onclick: addNote, disabled: busy },
|
||
icon('note'), 'Add note')),
|
||
h('div', { class: 'card' },
|
||
h('ol', { class: 'timeline' }, entries.map(timelineItem))));
|
||
}
|
||
|
||
function timelineItem(e) {
|
||
const isNote = (e.source === 'event' && e.type === 'note') || e.type === 'note' || e.type === 'resolution_note';
|
||
const mine = e.source === 'event' && e.type === 'note' && e.user_id != null && e.user_id === myID();
|
||
const iconName = ENTRY_ICON[e.type];
|
||
return h('li', { class: `tl-item tl-${e.type} tl-from-${e.source}` },
|
||
h('span', { class: 'tl-dot' }, iconName && icon(iconName, 'icon tl-icon')),
|
||
h('div', { class: 'tl-body' },
|
||
h('div', { class: 'tl-text' }, entryText(e)),
|
||
h('div', { class: 'tl-time', title: e.created_at, text: `${when(e.created_at)} · ${ago(e.created_at)}` }),
|
||
isNote && e.detail && h('div', { class: e.type === 'resolution_note' ? 'note note-fix' : 'note', text: e.detail }),
|
||
mine && h('div', { class: 'note-actions' },
|
||
h('button', { class: 'btn btn-ghost btn-sm', type: 'button', onclick: () => deleteNote(e) }, icon('trash'), 'Delete'))));
|
||
}
|
||
|
||
// ---------- actions ----------
|
||
|
||
// run performs one change, then reloads the event.
|
||
async function run(fn, done) {
|
||
if (busy) return;
|
||
busy = true;
|
||
render();
|
||
try {
|
||
await fn();
|
||
if (done) toast(done);
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
} finally {
|
||
busy = false;
|
||
await refresh();
|
||
poll.now();
|
||
}
|
||
}
|
||
|
||
async function editEvent() {
|
||
const e = ev;
|
||
const body = await eventForm({ event: e });
|
||
if (body) await run(() => api.updateEvent(e.id, body), 'Saved');
|
||
}
|
||
|
||
function endNow() {
|
||
const id = ev.id;
|
||
return run(() => api.updateEvent(id, { ended_at: new Date().toISOString() }), 'Marked ended');
|
||
}
|
||
|
||
async function removeEvent() {
|
||
const e = ev;
|
||
const ok = await confirm({
|
||
title: 'Delete this event?',
|
||
text: e.incident_count
|
||
? `${e.incident_count} incident${e.incident_count === 1 ? '' : 's'} will be detached and stay as they are. The event, its summary and its notes are gone for good.`
|
||
: 'The event, its summary and its notes are gone for good.',
|
||
confirmLabel: 'Delete',
|
||
danger: true,
|
||
});
|
||
if (!ok) return;
|
||
try {
|
||
await api.deleteEvent(e.id);
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
return;
|
||
}
|
||
toast('Event deleted');
|
||
navigate('/events', { replace: true });
|
||
}
|
||
|
||
async function addNote() {
|
||
const id = ev.id;
|
||
const content = await openSheet(() => {
|
||
const textarea = h('textarea', {
|
||
name: 'content', required: true, autofocus: true, maxlength: '10000',
|
||
placeholder: 'What spans these incidents? What did you learn?',
|
||
});
|
||
const form = h('form', {
|
||
class: 'sheet-form',
|
||
onsubmit: (e) => {
|
||
e.preventDefault();
|
||
const v = textarea.value.trim();
|
||
if (v) closeSheet(v);
|
||
},
|
||
},
|
||
h('h2', { class: 'sheet-title', text: 'Add note to the event' }),
|
||
h('p', { class: 'sheet-text', text: 'For what is true of all of it. A note about one incident belongs on that incident.' }),
|
||
textarea,
|
||
h('div', { class: 'sheet-actions' },
|
||
h('button', { class: 'btn', type: 'button', onclick: () => closeSheet(null), text: 'Cancel' }),
|
||
h('button', { class: 'btn btn-primary', type: 'submit', text: 'Save note' })));
|
||
textarea.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) form.requestSubmit();
|
||
});
|
||
return form;
|
||
});
|
||
if (content) await run(() => api.addEventNote(id, content), 'Note added');
|
||
}
|
||
|
||
async function deleteNote(entry) {
|
||
const id = ev.id;
|
||
const ok = await confirm({ title: 'Delete this note?', text: entry.detail || '', confirmLabel: 'Delete', danger: true });
|
||
if (ok) await run(() => api.deleteEventNote(id, entry.id), 'Note deleted');
|
||
}
|
||
|
||
// ---------- the event form ----------
|
||
|
||
// eventForm asks for an event's fields and resolves with the request body, or
|
||
// null when dismissed. With `event` it edits (the body is a patch, where an
|
||
// emptied end or link is sent as null to clear it); without, it creates. For a
|
||
// new event `team` fixes the team, and `defaults` pre-fills fields.
|
||
export function eventForm({ event = null, team = null, defaults = {} } = {}) {
|
||
return openSheet(() => {
|
||
const src = event || defaults;
|
||
const kindSel = h('select', { name: 'kind', id: 'ev-kind' },
|
||
KINDS.map((k) => h('option', { value: k.id, selected: k.id === (src.kind || 'release'), text: k.label })));
|
||
const title = h('input', {
|
||
name: 'title', id: 'ev-title', required: true, maxlength: '200', autofocus: true, autocomplete: 'off',
|
||
value: src.title || '', placeholder: 'terdut-server 0.52.0 rollout',
|
||
});
|
||
const started = h('input', {
|
||
type: 'datetime-local', name: 'started', id: 'ev-started', required: true,
|
||
value: localInput(src.started_at || new Date().toISOString()),
|
||
});
|
||
const ended = h('input', {
|
||
type: 'datetime-local', name: 'ended', id: 'ev-ended', value: src.ended_at ? localInput(src.ended_at) : '',
|
||
});
|
||
const link = h('input', {
|
||
type: 'url', name: 'link', id: 'ev-link', placeholder: 'https://… (pipeline, status page)', value: src.external_url || '',
|
||
});
|
||
const summary = h('textarea', {
|
||
name: 'summary', id: 'ev-summary', maxlength: '20000',
|
||
placeholder: 'What happened, and what was done about it?',
|
||
});
|
||
summary.value = src.summary || '';
|
||
|
||
const teams = state.teams || [];
|
||
const pickTeam = !event && !team && teams.length > 1;
|
||
const teamSel = pickTeam && h('select', { name: 'team', id: 'ev-team' },
|
||
teams.map((t) => h('option', { value: String(t.id), selected: t.id === (state.selectedTeamID ?? teams[0].id), text: t.name })));
|
||
|
||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||
const form = h('form', {
|
||
class: 'sheet-form',
|
||
onsubmit: (e) => {
|
||
e.preventDefault();
|
||
const s = new Date(started.value);
|
||
const en = ended.value ? new Date(ended.value) : null;
|
||
if (en && en < s) {
|
||
err.textContent = 'The end is before the start.';
|
||
err.hidden = false;
|
||
return;
|
||
}
|
||
const body = {
|
||
kind: kindSel.value,
|
||
title: title.value.trim(),
|
||
summary: summary.value,
|
||
started_at: s.toISOString(),
|
||
};
|
||
if (event) {
|
||
body.ended_at = en ? en.toISOString() : null;
|
||
body.external_url = link.value.trim() || null;
|
||
} else {
|
||
if (en) body.ended_at = en.toISOString();
|
||
if (link.value.trim()) body.external_url = link.value.trim();
|
||
body.team_id = team != null ? team : pickTeam ? Number(teamSel.value) : (teams[0] && teams[0].id);
|
||
}
|
||
closeSheet(body);
|
||
},
|
||
},
|
||
h('h2', { class: 'sheet-title', text: event ? 'Edit event' : 'New event' }),
|
||
pickTeam && h('label', { class: 'ev-field', for: 'ev-team' }, 'Team', teamSel),
|
||
h('label', { class: 'ev-field', for: 'ev-kind' }, 'Kind', kindSel),
|
||
h('label', { class: 'ev-field', for: 'ev-title' }, 'Title', title),
|
||
h('label', { class: 'ev-field', for: 'ev-started' }, 'Started', started),
|
||
h('label', { class: 'ev-field', for: 'ev-ended' }, 'Ended (leave empty if unknown or still going)', ended),
|
||
h('label', { class: 'ev-field', for: 'ev-link' }, 'Link', link),
|
||
h('label', { class: 'ev-field', for: 'ev-summary' }, 'Summary', summary),
|
||
err,
|
||
h('div', { class: 'sheet-actions' },
|
||
h('button', { class: 'btn', type: 'button', onclick: () => closeSheet(null), text: 'Cancel' }),
|
||
h('button', { class: 'btn btn-primary', type: 'submit', text: event ? 'Save' : 'Create event' })));
|
||
return form;
|
||
});
|
||
}
|
||
|
||
async function createEvent() {
|
||
const body = await eventForm();
|
||
if (!body) return;
|
||
try {
|
||
const made = await api.createEvent(body);
|
||
toast('Event created');
|
||
navigate(`/events/${made.id}`);
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
}
|
||
}
|
||
|
||
// ---------- attaching incidents to this event ----------
|
||
|
||
// Incidents of the event's team that could be attached: the open ones, and the
|
||
// resolved or archived ones from shortly before it started, which is where an
|
||
// after-the-fact attach looks. Without the filters the server's defaults hide
|
||
// everything that has closed.
|
||
async function candidateIncidents(e) {
|
||
const base = { team_id: e.team_id, limit: 200 };
|
||
const from = isoDate(new Date(Date.parse(e.started_at) - 3 * DAY));
|
||
const lists = await Promise.all([
|
||
api.incidents(base),
|
||
api.incidents({ ...base, status: 'resolved', from }),
|
||
api.incidents({ ...base, status: 'resolved', archived: 'true', from }),
|
||
]);
|
||
const attached = new Set((e.incidents || []).map((i) => i.incident_id));
|
||
const seen = new Map();
|
||
for (const i of lists.flat()) if (!attached.has(i.id)) seen.set(i.id, i);
|
||
const at = Date.parse(e.started_at);
|
||
return [...seen.values()].sort((a, b) =>
|
||
Math.abs(Date.parse(a.triggered_at) - at) - Math.abs(Date.parse(b.triggered_at) - at));
|
||
}
|
||
|
||
async function attachIncidents() {
|
||
const e = ev;
|
||
let list;
|
||
try {
|
||
list = await candidateIncidents(e);
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
return;
|
||
}
|
||
const picked = await pickIncidents(e, list);
|
||
if (picked) await run(() => api.attachIncidents(e.id, picked.ids, picked.trigger), `Attached ${picked.ids.length}`);
|
||
}
|
||
|
||
// Resolves with { ids, trigger } or null. Incidents near the event's start come
|
||
// first and are the only ones ticked for you: nothing is attached by guessing.
|
||
function pickIncidents(e, list) {
|
||
const at = Date.parse(e.started_at);
|
||
const near = (i) => Math.abs(Date.parse(i.triggered_at) - at) <= AROUND;
|
||
return openSheet(() => {
|
||
const chosen = new Set();
|
||
let trigger = null;
|
||
let query = '';
|
||
const results = h('div', { class: 'ev-pick-list' });
|
||
const submit = h('button', { class: 'btn btn-primary', type: 'submit', disabled: true, text: 'Attach' });
|
||
|
||
const draw = () => {
|
||
const q = query.trim().toLowerCase();
|
||
const shown = list.filter((i) => !q || i.title.toLowerCase().includes(q));
|
||
const groups = [
|
||
['Around the event', shown.filter(near)],
|
||
['Other recent incidents', shown.filter((i) => !near(i))],
|
||
].filter(([, g]) => g.length);
|
||
clear(results, groups.length
|
||
? groups.map(([label, g]) => h('div', {},
|
||
h('div', { class: 'ev-pick-group', text: label }),
|
||
g.map(pickRow)))
|
||
: h('p', { class: 'faint', text: list.length ? 'No incident matches.' : 'No recent incidents to attach.' }));
|
||
submit.disabled = chosen.size === 0;
|
||
submit.textContent = chosen.size ? `Attach ${chosen.size}` : 'Attach';
|
||
};
|
||
|
||
const pickRow = (i) => h('div', { class: 'ev-pick-row' },
|
||
h('label', { class: 'ev-pick-main' },
|
||
h('input', {
|
||
type: 'checkbox',
|
||
checked: chosen.has(i.id),
|
||
onchange: (ev2) => {
|
||
if (ev2.target.checked) chosen.add(i.id);
|
||
else {
|
||
chosen.delete(i.id);
|
||
if (trigger === i.id) trigger = null;
|
||
}
|
||
draw();
|
||
},
|
||
}),
|
||
h('span', { class: 'ev-pick-text' },
|
||
h('span', { class: 'ev-inc-title', text: i.title }),
|
||
h('span', { class: 'sub', text: `#${i.id} · ${when(i.triggered_at)} · ${STATUS_LABEL[i.status] || i.status}` }))),
|
||
i.severity && severityBadge(i.severity),
|
||
chosen.has(i.id) && h('label', { class: 'ev-pick-trigger', title: 'The first domino' },
|
||
h('input', {
|
||
type: 'radio', name: 'trigger', checked: trigger === i.id,
|
||
onclick: () => {
|
||
// A second click on the chosen one clears it, since a radio cannot.
|
||
trigger = trigger === i.id ? null : i.id;
|
||
draw();
|
||
},
|
||
}), '★ trigger'));
|
||
|
||
const search = h('input', {
|
||
type: 'search', placeholder: 'Search by title…', autocomplete: 'off', 'aria-label': 'Search incidents',
|
||
oninput: (x) => {
|
||
query = x.target.value;
|
||
draw();
|
||
},
|
||
});
|
||
draw();
|
||
return h('form', {
|
||
class: 'sheet-form',
|
||
onsubmit: (x) => {
|
||
x.preventDefault();
|
||
if (chosen.size) closeSheet({ ids: [...chosen], trigger });
|
||
},
|
||
},
|
||
h('h2', { class: 'sheet-title', text: 'Attach incidents' }),
|
||
h('p', { class: 'sheet-text', text: `To ${e.title}. Mark one as the trigger if it started the chain.` }),
|
||
search,
|
||
results,
|
||
h('div', { class: 'sheet-actions' },
|
||
h('button', { class: 'btn', type: 'button', onclick: () => closeSheet(null), text: 'Cancel' }),
|
||
submit));
|
||
});
|
||
}
|
||
|
||
// ---------- from an incident ----------
|
||
|
||
// attachToEvent lets somebody file incident `inc` under an event: one of those
|
||
// close to it in time, a recent one, or a new one made from the incident.
|
||
// `related` are the server's suggestions. Resolves true when anything changed.
|
||
export async function attachToEvent(inc, related = []) {
|
||
const attachedIDs = new Set((inc.events || []).map((e) => e.id));
|
||
let recent = [];
|
||
try {
|
||
recent = await api.events({ team_id: inc.team_id, limit: 30 });
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
return false;
|
||
}
|
||
const near = related.filter((e) => !attachedIDs.has(e.id));
|
||
const nearIDs = new Set(near.map((e) => e.id));
|
||
const rest = recent.filter((e) => !attachedIDs.has(e.id) && !nearIDs.has(e.id));
|
||
|
||
const eventItem = (e) => h('li', {}, h('button', {
|
||
class: 'menu-item', type: 'button', onclick: () => closeSheet({ id: e.id }),
|
||
}, kindBadge(e.kind), h('span', { class: 'ev-inc-title', text: e.title }), h('span', { class: 'menu-sub', text: when(e.started_at) })));
|
||
|
||
const choice = await openSheet(() => [
|
||
h('h2', { class: 'sheet-title', text: 'Attach to an event' }),
|
||
h('ul', { class: 'menu' },
|
||
h('li', {}, h('button', { class: 'menu-item', type: 'button', onclick: () => closeSheet({ create: true }) },
|
||
icon('plus'), 'New event from this incident…')),
|
||
near.length > 0 && h('li', { class: 'menu-heading', text: 'Close in time' }),
|
||
near.map(eventItem),
|
||
rest.length > 0 && h('li', { class: 'menu-heading', text: 'Recent' }),
|
||
rest.map(eventItem)),
|
||
]);
|
||
if (!choice) return false;
|
||
|
||
try {
|
||
let id = choice.id;
|
||
if (choice.create) {
|
||
const body = await eventForm({
|
||
team: inc.team_id,
|
||
defaults: { title: inc.title, kind: 'other', started_at: inc.triggered_at },
|
||
});
|
||
if (!body) return false;
|
||
id = (await api.createEvent(body)).id;
|
||
}
|
||
await api.attachIncidents(id, [inc.id]);
|
||
toast('Attached to event', '', { action: { label: 'Open', run: () => navigate(`/events/${id}`) } });
|
||
return true;
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// attachOne files `inc` under one event the server suggested.
|
||
export async function attachOne(inc, eventID) {
|
||
try {
|
||
await api.attachIncidents(eventID, [inc.id]);
|
||
toast('Attached to event');
|
||
return true;
|
||
} catch (err) {
|
||
toast(err.message, 'error');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
export { kindBadge, kindLabel };
|