Flapping alerts, a noise report and bulk actions with undo
Flapping: an alert raised three times within an hour is announced once as flapping, its further raise/clear messages are held until it has been calm for an hour, and one message then says whether it is still active. Event webhooks still hear everything. The state survives restarts. Alerts > Noise lists the alerts that keep coming back (7-180 days): how often, how long, most in an hour, and a hint on what helps. Bulk actions on Alerts (acknowledge, remove acknowledgement, silence), Servers (tag, silence, runs on) and Inventory (location and dates, print labels). Each reports what it left alone and why, and has an Undo on the toast. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
be6c5552bd
commit
73a06ebe63
35 files changed
+2546
-17
No files matched your search
@@ -510,6 +510,8 @@ export interface HealthCheckSettings {
|
||||
restoreTestDays: number;
|
||||
/** A server that starts listening on a TCP port it did not at first, and that is not noted on its Ports card, is a warning. */
|
||||
newPortAlerts: boolean;
|
||||
/** An alert raised this many times within an hour is "flapping": one message says so and its further messages are held until it has been quiet for an hour. 0 is off. */
|
||||
flapRaises: number;
|
||||
}
|
||||
|
||||
/** The monthly report: last month's availability, incidents, updates and renewals, in one message on a day of the month. */
|
||||
@@ -1244,6 +1246,48 @@ export interface AlertItem {
|
||||
ack?: AlertAck | null;
|
||||
/** The incident record this alert is part of, while it lasts. */
|
||||
incidentId?: number | null;
|
||||
/** Raised and cleared over and over: its raised/cleared messages are being held back. */
|
||||
flapping?: boolean;
|
||||
}
|
||||
|
||||
/** What a bulk action did: how many it changed, what it left alone and why, and the body that puts it back (to send to the same address). */
|
||||
export interface BulkResult {
|
||||
changed: number;
|
||||
skipped: { id: string | number; name: string; reason: string }[];
|
||||
undo: Record<string, unknown> | null;
|
||||
silenced?: { type: string; id: number; name: string }[];
|
||||
}
|
||||
|
||||
/** One alert that fires often, from the incident record. */
|
||||
export interface NoiseRow {
|
||||
alertId: string;
|
||||
message: string;
|
||||
category: AlertCategory;
|
||||
source: string;
|
||||
where: string;
|
||||
fired: number;
|
||||
totalMinutes: number;
|
||||
averageMinutes: number;
|
||||
longestMinutes: number;
|
||||
mostInAnHour: number;
|
||||
flapped: boolean;
|
||||
flappingNow: boolean;
|
||||
openNow: boolean;
|
||||
lastAt: string;
|
||||
link: string | null;
|
||||
hint: string;
|
||||
}
|
||||
export interface NoiseReport {
|
||||
days: number;
|
||||
from: string;
|
||||
to: string;
|
||||
incidents: number;
|
||||
distinctAlerts: number;
|
||||
repeating: number;
|
||||
flapped: number;
|
||||
totalMinutes: number;
|
||||
byCategory: { category: string; incidents: number; repeating: number }[];
|
||||
rows: NoiseRow[];
|
||||
}
|
||||
|
||||
export interface AlertAck {
|
||||
@@ -2049,6 +2093,11 @@ export const api = {
|
||||
start: (data: UpdateRunInput) => request<{ run: UpdateRun }>("/api/update-runs", { method: "POST", body: JSON.stringify(data) }),
|
||||
cancel: (id: number) => request<{ status: string }>(`/api/update-runs/${id}/cancel`, { method: "POST" }),
|
||||
},
|
||||
bulk: {
|
||||
servers: (body: Record<string, unknown>) => request<BulkResult>("/api/servers/bulk", { method: "POST", body: JSON.stringify(body) }),
|
||||
alerts: (body: Record<string, unknown>) => request<BulkResult>("/api/alerts/bulk", { method: "POST", body: JSON.stringify(body) }),
|
||||
inventory: (body: Record<string, unknown>) => request<BulkResult>("/api/inventory/bulk", { method: "POST", body: JSON.stringify(body) }),
|
||||
},
|
||||
patchPlans: {
|
||||
list: () => request<{ plans: PatchPlan[]; runs: PatchPlanRun[]; servers: { id: number; name: string; tags: string[] }[]; tags: string[] }>("/api/patch-plans"),
|
||||
create: (data: PatchPlanInput) => request<{ plan: PatchPlan }>("/api/patch-plans", { method: "POST", body: JSON.stringify(data) }),
|
||||
@@ -2254,6 +2303,7 @@ export const api = {
|
||||
assignees: () => request<{ users: { id: number; name: string; role: string }[] }>("/api/alerts/assignees"),
|
||||
ack: (data: AckInput) => request<{ ack: AlertAck }>("/api/alerts/ack", { method: "PUT", body: JSON.stringify(data) }),
|
||||
unack: (alertId: string) => request<void>(`/api/alerts/ack?alertId=${encodeURIComponent(alertId)}`, { method: "DELETE" }),
|
||||
noise: (days: number) => request<NoiseReport>(`/api/alerts/noise?days=${days}`),
|
||||
},
|
||||
incidents: {
|
||||
list: () => request<{ incidents: IncidentSummary[] }>("/api/incidents"),
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type NoiseReport, type NoiseRow } from "../api/client";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import { usePagination } from "../hooks/usePagination";
|
||||
import SortableTh from "./SortableTh";
|
||||
import Pagination from "./Pagination";
|
||||
import TableToolbar from "./TableToolbar";
|
||||
import TimeAgo from "./TimeAgo";
|
||||
import { BlockSkeleton } from "./Skeleton";
|
||||
import { ErrorNotice } from "./Notice";
|
||||
import { EmptyRow } from "./EmptyState";
|
||||
import { CATEGORY_NAMES, durationWords } from "./IncidentHistory";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { readableError } from "../utils/errors";
|
||||
|
||||
const PERIODS = [
|
||||
{ days: 7, label: "Last 7 days" },
|
||||
{ days: 30, label: "Last 30 days" },
|
||||
{ days: 90, label: "Last 90 days" },
|
||||
{ days: 180, label: "Last 180 days" },
|
||||
];
|
||||
|
||||
const minutesWords = (minutes: number) => durationWords(minutes * 60_000);
|
||||
|
||||
/**
|
||||
* The Noise side of the Alerts page: which alerts were raised again and again over the last weeks, how long each lasted and how many times it came in a single
|
||||
* hour — the ones worth fixing at the source or giving a longer grace time. Worked out from the incident record.
|
||||
*/
|
||||
export default function AlertNoise() {
|
||||
const [days, setDays] = useState(30);
|
||||
const [report, setReport] = useState<NoiseReport | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setReport(null);
|
||||
api.alerts
|
||||
.noise(days)
|
||||
.then((res) => {
|
||||
if (alive) {
|
||||
setReport(res);
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
.catch((err) => alive && setError(readableError(err)));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [days]);
|
||||
|
||||
const rows = report?.rows ?? [];
|
||||
const tableSearch = useTableSearch(rows);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "fired", "desc");
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
|
||||
const cards = useMemo(
|
||||
() => [
|
||||
{ label: "Alerts raised", value: report ? report.incidents : "…", note: report ? `${report.distinctAlerts} different` : "" },
|
||||
{ label: "Raised more than once", value: report ? report.repeating : "…", note: "", color: report && report.repeating > 0 ? "text-yellow" : "" },
|
||||
{ label: "Flapped", value: report ? report.flapped : "…", note: "three or more times within an hour", color: report && report.flapped > 0 ? "text-red" : "" },
|
||||
{ label: "Time spent alerting", value: report ? minutesWords(report.totalMinutes) : "…", note: "" },
|
||||
],
|
||||
[report],
|
||||
);
|
||||
|
||||
function exportCsv() {
|
||||
downloadCsv(
|
||||
"alert-noise.csv",
|
||||
["Alert", "Kind", "Where", "Raised", "Total (minutes)", "Average (minutes)", "Longest (minutes)", "Most within an hour", "Flapped", "Last raised"],
|
||||
(sorted ?? []).map((r) => [r.message, CATEGORY_NAMES[r.category] ?? r.category, r.where, r.fired, r.totalMinutes, r.averageMinutes, r.longestMinutes, r.mostInAnHour, r.flapped ? "yes" : "no", r.lastAt]),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-secondary">
|
||||
The alerts that keep coming back. Each time one is raised and later goes away counts once; only those raised at least twice are listed. The last column says what usually helps — a longer grace time, a different threshold,
|
||||
or fixing the thing itself. An alert raised and cleared often enough in an hour is called <strong>flapping</strong> and its messages are held back until it has been calm for an hour (set under Settings → Notifications).
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<select className="form-select w-auto" aria-label="Period" value={days} onChange={(e) => setDays(Number(e.target.value))}>
|
||||
{PERIODS.map((p) => (
|
||||
<option key={p.days} value={p.days}>
|
||||
{p.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{report && report.byCategory.length > 0 && (
|
||||
<div className="d-flex flex-wrap gap-1">
|
||||
{report.byCategory.map((c) => (
|
||||
<span key={c.category} className="badge bg-secondary-lt text-secondary" title={`${c.incidents} raised, ${c.repeating} of them by alerts that came back`}>
|
||||
{CATEGORY_NAMES[c.category as keyof typeof CATEGORY_NAMES] ?? c.category}: {c.incidents}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="row row-cards mb-3">
|
||||
{cards.map((c) => (
|
||||
<div className="col-6 col-lg-3" key={c.label}>
|
||||
<div className="card card-sm">
|
||||
<div className="card-body">
|
||||
<div className={`h2 mb-0 ${c.color ?? ""}`}>{c.value}</div>
|
||||
<div className="text-secondary">{c.label}</div>
|
||||
{c.note && <div className="text-secondary small">{c.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<TableToolbar
|
||||
search={tableSearch.query}
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search noisy alerts…"
|
||||
shown={sorted?.length}
|
||||
total={rows.length}
|
||||
onExport={exportCsv}
|
||||
exportDisabled={!sorted || sorted.length === 0}
|
||||
/>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<thead>
|
||||
<tr>
|
||||
<SortableTh<NoiseRow> label="Alert" sortKeyName="message" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Raised" sortKeyName="fired" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Time in total" sortKeyName="totalMinutes" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Average" sortKeyName="averageMinutes" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Longest" sortKeyName="longestMinutes" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Most in an hour" sortKeyName="mostInAnHour" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<NoiseRow> label="Last" sortKeyName="lastAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{!report && !error && (
|
||||
<tr>
|
||||
<td colSpan={7}>
|
||||
<BlockSkeleton lines={4} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{(pageItems ?? []).map((r) => (
|
||||
<tr key={r.alertId}>
|
||||
<td className="stack-wide">
|
||||
{r.link ? <Link to={r.link}>{r.message}</Link> : r.message}
|
||||
{r.flappingNow && (
|
||||
<span className="badge bg-red-lt text-red ms-2" title="Its messages are being held back right now">
|
||||
flapping now
|
||||
</span>
|
||||
)}
|
||||
{!r.flappingNow && r.flapped && (
|
||||
<span className="badge bg-yellow-lt text-yellow ms-2" title="Raised and cleared often enough within an hour to count as flapping">
|
||||
flapped
|
||||
</span>
|
||||
)}
|
||||
{r.openNow && <span className="badge bg-secondary-lt text-secondary ms-2">active now</span>}
|
||||
<div className="text-secondary small">
|
||||
{CATEGORY_NAMES[r.category] ?? r.category} · {r.where}
|
||||
</div>
|
||||
<div className="text-secondary small">{r.hint}</div>
|
||||
</td>
|
||||
<td className="stack-label" data-label="Raised">{r.fired}×</td>
|
||||
<td className="stack-label text-nowrap" data-label="Time in total">
|
||||
{minutesWords(r.totalMinutes)}
|
||||
</td>
|
||||
<td className="stack-label text-nowrap" data-label="Average">
|
||||
{minutesWords(r.averageMinutes)}
|
||||
</td>
|
||||
<td className="stack-label text-nowrap" data-label="Longest">
|
||||
{minutesWords(r.longestMinutes)}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Most in an hour">{r.mostInAnHour}</td>
|
||||
<td className="stack-label text-nowrap" data-label="Last">
|
||||
<TimeAgo value={r.lastAt} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{report && (sorted ?? []).length === 0 && (
|
||||
<EmptyRow
|
||||
colSpan={7}
|
||||
{...(tableSearch.active
|
||||
? { filtered: () => tableSearch.setQuery("") }
|
||||
: { title: "Nothing keeps coming back", hint: "No alert was raised more than once in this period. That is how it should look." })}
|
||||
/>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* The bar at the foot of a list that appears when some rows are picked: how many, what can be done to all of them, and a way to let go. It sits over the bottom of the
|
||||
* page, so the list stays where it is; the page gives its last row room with the `has-bulk-bar` class.
|
||||
*/
|
||||
export default function BulkBar({ count, noun, onClear, children }: { count: number; noun: string; onClear: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<div className="bulk-bar no-print" role="region" aria-label={`What to do with the ${noun} picked`}>
|
||||
<strong>
|
||||
{count} {noun} picked
|
||||
</strong>
|
||||
<div className="d-flex flex-wrap gap-2">{children}</div>
|
||||
<button type="button" className="btn btn-sm ms-auto" onClick={onClear}>
|
||||
Let go
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { api } from "../api/client";
|
||||
import DetailDrawer from "./DetailDrawer";
|
||||
|
||||
/** The little forms behind the bulk bar: each says what will be done and to how many, collects the one or two answers it needs, and hands them back. */
|
||||
|
||||
function Shell({ title, subtitle, onClose, onSubmit, submitLabel, busy, disabled, children }: { title: string; subtitle: string; onClose: () => void; onSubmit: () => void; submitLabel: string; busy: boolean; disabled?: boolean; children: ReactNode }) {
|
||||
return (
|
||||
<DetailDrawer title={title} subtitle={subtitle} onClose={onClose}>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || disabled}>
|
||||
{busy ? "Working…" : submitLabel}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
<div className="text-secondary small mt-2">Afterwards there is an Undo button for a little while; it puts back what was changed.</div>
|
||||
</form>
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
const MINUTES = [
|
||||
{ minutes: 30, label: "30 minutes" },
|
||||
{ minutes: 60, label: "1 hour" },
|
||||
{ minutes: 180, label: "3 hours" },
|
||||
{ minutes: 480, label: "8 hours" },
|
||||
{ minutes: 1440, label: "1 day" },
|
||||
{ minutes: 4320, label: "3 days" },
|
||||
];
|
||||
|
||||
/** Maintenance on everything picked: for how long, and why. */
|
||||
export function SilenceBulkDrawer({ noun, count, canSilenceDependents, onSubmit, onClose }: { noun: string; count: number; canSilenceDependents: boolean; onSubmit: (v: { minutes: number; reason: string; withDependents: boolean }) => Promise<void>; onClose: () => void }) {
|
||||
const [minutes, setMinutes] = useState(60);
|
||||
const [reason, setReason] = useState("");
|
||||
const [withDependents, setWithDependents] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Shell
|
||||
title="Put under maintenance"
|
||||
subtitle={`${count} ${noun}`}
|
||||
onClose={onClose}
|
||||
busy={busy}
|
||||
submitLabel="Start maintenance"
|
||||
onSubmit={async () => {
|
||||
setBusy(true);
|
||||
await onSubmit({ minutes, reason: reason.trim(), withDependents });
|
||||
setBusy(false);
|
||||
}}
|
||||
>
|
||||
<p className="text-secondary">Alerts about each are held back for this long; anything still wrong when it ends alerts then. One already under maintenance has its time restarted.</p>
|
||||
<label className="form-label" htmlFor="bulk-min">
|
||||
For
|
||||
</label>
|
||||
<select id="bulk-min" className="form-select mb-3" value={minutes} onChange={(e) => setMinutes(Number(e.target.value))}>
|
||||
{MINUTES.map((m) => (
|
||||
<option key={m.minutes} value={m.minutes}>
|
||||
{m.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="form-label" htmlFor="bulk-reason">
|
||||
Why <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<input id="bulk-reason" className="form-control mb-3" maxLength={200} value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. Firmware update" />
|
||||
{canSilenceDependents && (
|
||||
<label className="form-check">
|
||||
<input type="checkbox" className="form-check-input" checked={withDependents} onChange={(e) => setWithDependents(e.target.checked)} />
|
||||
<span className="form-check-label">Also silence what depends on them (a guest that runs on one, a service that needs one)</span>
|
||||
</label>
|
||||
)}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
const LENGTHS: { hours: number | null; label: string }[] = [
|
||||
{ hours: null, label: "Until the alert is gone" },
|
||||
{ hours: 1, label: "1 hour" },
|
||||
{ hours: 4, label: "4 hours" },
|
||||
{ hours: 24, label: "1 day" },
|
||||
{ hours: 72, label: "3 days" },
|
||||
{ hours: 168, label: "1 week" },
|
||||
];
|
||||
|
||||
/** "I'm on these": the same note, person and length for every alert picked. */
|
||||
export function AckBulkDrawer({ count, onSubmit, onClose }: { count: number; onSubmit: (v: { note: string; assigneeId: number | null; hours: number | null }) => Promise<void>; onClose: () => void }) {
|
||||
const [note, setNote] = useState("");
|
||||
const [assignee, setAssignee] = useState("");
|
||||
const [hours, setHours] = useState("");
|
||||
const [people, setPeople] = useState<{ id: number; name: string }[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api.alerts
|
||||
.assignees()
|
||||
.then((res) => alive && setPeople(res.users))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<Shell
|
||||
title="Acknowledge"
|
||||
subtitle={`${count} alert${count === 1 ? "" : "s"}`}
|
||||
onClose={onClose}
|
||||
busy={busy}
|
||||
submitLabel="Acknowledge them"
|
||||
onSubmit={async () => {
|
||||
setBusy(true);
|
||||
await onSubmit({ note: note.trim(), assigneeId: assignee === "" ? null : Number(assignee), hours: hours === "" ? null : Number(hours) });
|
||||
setBusy(false);
|
||||
}}
|
||||
>
|
||||
<p className="text-secondary">Says that somebody has seen them. The alerts stay, and are still counted by /metrics, but they are no longer ones nobody has looked at. One that was already acknowledged has its note replaced.</p>
|
||||
<label className="form-label" htmlFor="bulk-note">
|
||||
Note <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<textarea id="bulk-note" className="form-control mb-3" rows={3} maxLength={500} value={note} onChange={(e) => setNote(e.target.value)} placeholder="e.g. The UPS is being swapped on Saturday" />
|
||||
<label className="form-label" htmlFor="bulk-assignee">
|
||||
Who has them
|
||||
</label>
|
||||
<select id="bulk-assignee" className="form-select mb-3" value={assignee} onChange={(e) => setAssignee(e.target.value)}>
|
||||
<option value="">Nobody in particular</option>
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="form-label" htmlFor="bulk-hours">
|
||||
For how long
|
||||
</label>
|
||||
<select id="bulk-hours" className="form-select" value={hours} onChange={(e) => setHours(e.target.value)}>
|
||||
{LENGTHS.map((l) => (
|
||||
<option key={l.label} value={l.hours ?? ""}>
|
||||
{l.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
/** Add a tag to, or take one off, every server picked. */
|
||||
export function TagBulkDrawer({ count, tags, onSubmit, onClose }: { count: number; tags: string[]; onSubmit: (v: { mode: "add" | "remove"; tag: string }) => Promise<void>; onClose: () => void }) {
|
||||
const [mode, setMode] = useState<"add" | "remove">("add");
|
||||
const [tag, setTag] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Shell
|
||||
title="Tags"
|
||||
subtitle={`${count} server${count === 1 ? "" : "s"}`}
|
||||
onClose={onClose}
|
||||
busy={busy}
|
||||
disabled={tag.trim() === ""}
|
||||
submitLabel={mode === "add" ? "Add the tag" : "Take the tag off"}
|
||||
onSubmit={async () => {
|
||||
setBusy(true);
|
||||
await onSubmit({ mode, tag: tag.trim() });
|
||||
setBusy(false);
|
||||
}}
|
||||
>
|
||||
<div className="btn-group mb-3" role="group" aria-label="Add or take off">
|
||||
<button type="button" className={`btn ${mode === "add" ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={mode === "add"} onClick={() => setMode("add")}>
|
||||
Add a tag
|
||||
</button>
|
||||
<button type="button" className={`btn ${mode === "remove" ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={mode === "remove"} onClick={() => setMode("remove")}>
|
||||
Take a tag off
|
||||
</button>
|
||||
</div>
|
||||
<label className="form-label" htmlFor="bulk-tag">
|
||||
Tag
|
||||
</label>
|
||||
<input id="bulk-tag" className="form-control" list="bulk-tags" maxLength={30} value={tag} onChange={(e) => setTag(e.target.value)} placeholder="e.g. lab" autoFocus />
|
||||
<datalist id="bulk-tags">
|
||||
{tags.map((t) => (
|
||||
<option key={t} value={t} />
|
||||
))}
|
||||
</datalist>
|
||||
<div className="form-hint text-secondary small mt-2">Written the way tags always are (lower case, no spaces). A server that already has it, or lacks it, is left as it is.</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
/** Which server every server picked runs on (or back to working it out). */
|
||||
export function RunsOnBulkDrawer({ count, servers, onSubmit, onClose }: { count: number; servers: { id: number; name: string }[]; onSubmit: (parentServerId: number | null) => Promise<void>; onClose: () => void }) {
|
||||
const [choice, setChoice] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Shell
|
||||
title="Runs on"
|
||||
subtitle={`${count} server${count === 1 ? "" : "s"}`}
|
||||
onClose={onClose}
|
||||
busy={busy}
|
||||
disabled={choice === ""}
|
||||
submitLabel="Set it"
|
||||
onSubmit={async () => {
|
||||
setBusy(true);
|
||||
await onSubmit(choice === "auto" ? null : Number(choice));
|
||||
setBusy(false);
|
||||
}}
|
||||
>
|
||||
<p className="text-secondary">When the server they run on is down, their own offline alerts are folded under its alert instead of adding to the noise. A change that would make a loop is left out.</p>
|
||||
<label className="form-label" htmlFor="bulk-parent">
|
||||
They run on
|
||||
</label>
|
||||
<select id="bulk-parent" className="form-select" value={choice} onChange={(e) => setChoice(e.target.value)}>
|
||||
<option value="">Choose…</option>
|
||||
<option value="auto">Work it out from the Proxmox node (the default)</option>
|
||||
{servers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
type Field = { mode: "keep" | "set" | "clear"; value: string };
|
||||
const KEEP: Field = { mode: "keep", value: "" };
|
||||
|
||||
function FieldChange({ id, label, type, value, onChange }: { id: string; label: string; type: "text" | "date"; value: Field; onChange: (v: Field) => void }) {
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor={id}>
|
||||
{label}
|
||||
</label>
|
||||
<div className="d-flex gap-2">
|
||||
<select aria-label={`${label}: what to do`} className="form-select w-auto" value={value.mode} onChange={(e) => onChange({ ...value, mode: e.target.value as Field["mode"] })}>
|
||||
<option value="keep">Leave as it is</option>
|
||||
<option value="set">Set to…</option>
|
||||
<option value="clear">Clear</option>
|
||||
</select>
|
||||
{value.mode === "set" && <input id={id} type={type} className="form-control" maxLength={120} value={value.value} onChange={(e) => onChange({ ...value, value: e.target.value })} required />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Where it is, and when it is covered and supported — for every piece of hardware picked. */
|
||||
export function HardwareBulkDrawer({ count, onSubmit, onClose }: { count: number; onSubmit: (v: { location?: string | null; warrantyUntil?: string | null; endOfSupport?: string | null }) => Promise<void>; onClose: () => void }) {
|
||||
const [location, setLocation] = useState<Field>(KEEP);
|
||||
const [warranty, setWarranty] = useState<Field>(KEEP);
|
||||
const [support, setSupport] = useState<Field>(KEEP);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const apply = (f: Field) => (f.mode === "keep" ? undefined : f.mode === "clear" ? null : f.value.trim());
|
||||
const nothing = location.mode === "keep" && warranty.mode === "keep" && support.mode === "keep";
|
||||
return (
|
||||
<Shell
|
||||
title="Change hardware"
|
||||
subtitle={`${count} piece${count === 1 ? "" : "s"}`}
|
||||
onClose={onClose}
|
||||
busy={busy}
|
||||
disabled={nothing}
|
||||
submitLabel="Change them"
|
||||
onSubmit={async () => {
|
||||
setBusy(true);
|
||||
const change: { location?: string | null; warrantyUntil?: string | null; endOfSupport?: string | null } = {};
|
||||
const l = apply(location);
|
||||
const w = apply(warranty);
|
||||
const s = apply(support);
|
||||
if (l !== undefined) change.location = l;
|
||||
if (w !== undefined) change.warrantyUntil = w;
|
||||
if (s !== undefined) change.endOfSupport = s;
|
||||
await onSubmit(change);
|
||||
setBusy(false);
|
||||
}}
|
||||
>
|
||||
<p className="text-secondary">Whatever is left as it is stays the way each one has it.</p>
|
||||
<FieldChange id="bulk-location" label="Where it is" type="text" value={location} onChange={setLocation} />
|
||||
<FieldChange id="bulk-warranty" label="Warranty until" type="date" value={warranty} onChange={setWarranty} />
|
||||
<FieldChange id="bulk-support" label="End of support" type="date" value={support} onChange={setSupport} />
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { IconAlertTriangle, IconCircleCheck, IconInfoCircle, IconX } from "@tabl
|
||||
import { dismissToast, subscribeToasts, type ToastItem } from "../utils/toast";
|
||||
|
||||
const LIFETIME_MS = { success: 4_500, info: 6_000, error: 9_000 } as const;
|
||||
/** A toast with a button stays long enough to decide to press it. */
|
||||
const ACTION_LIFETIME_MS = 15_000;
|
||||
|
||||
function ToastView({ item }: { item: ToastItem }) {
|
||||
const [paused, setPaused] = useState(false);
|
||||
@@ -11,9 +13,9 @@ function ToastView({ item }: { item: ToastItem }) {
|
||||
// Goes away by itself — unless the pointer is on it, so a long message can be read.
|
||||
useEffect(() => {
|
||||
if (paused) return;
|
||||
const timer = setTimeout(() => dismissToast(item.id), LIFETIME_MS[item.kind]);
|
||||
const timer = setTimeout(() => dismissToast(item.id), item.action ? ACTION_LIFETIME_MS : LIFETIME_MS[item.kind]);
|
||||
return () => clearTimeout(timer);
|
||||
}, [paused, item.id, item.kind]);
|
||||
}, [paused, item.id, item.kind, item.action]);
|
||||
|
||||
const Icon = item.kind === "success" ? IconCircleCheck : item.kind === "error" ? IconAlertTriangle : IconInfoCircle;
|
||||
return (
|
||||
@@ -25,6 +27,18 @@ function ToastView({ item }: { item: ToastItem }) {
|
||||
>
|
||||
<Icon size={18} className="flex-shrink-0 mt-1" />
|
||||
<div className="flex-fill">{item.message}</div>
|
||||
{item.action && (
|
||||
<button
|
||||
type="button"
|
||||
className="toast-action"
|
||||
onClick={() => {
|
||||
dismissToast(item.id);
|
||||
void item.action!.onClick();
|
||||
}}
|
||||
>
|
||||
{item.action.label}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="toast-close" aria-label="Dismiss" onClick={() => dismissToast(item.id)}>
|
||||
<IconX size={16} />
|
||||
</button>
|
||||
|
||||
@@ -20,6 +20,10 @@ import { summariseAlerts } from "../utils/alertSummary";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
import IncidentHistory, { incidentPath } from "../components/IncidentHistory";
|
||||
import ViewTabs from "../components/ViewTabs";
|
||||
import AlertNoise from "../components/AlertNoise";
|
||||
import BulkBar from "../components/BulkBar";
|
||||
import { AckBulkDrawer, SilenceBulkDrawer } from "../components/BulkDrawers";
|
||||
import { doBulk, plural } from "../utils/bulk";
|
||||
|
||||
const SEVERITY: Record<AlertSeverity, { label: string; badge: string; rank: number }> = {
|
||||
critical: { label: "Critical", badge: "bg-red-lt text-red", rank: 0 },
|
||||
@@ -42,27 +46,29 @@ const CATEGORY_LABELS: Record<AlertCategory, string> = {
|
||||
|
||||
type Row = AlertItem & { rank: number };
|
||||
|
||||
/** Now and History: what is wrong right now, and every time something was raised and went away. The same page, switched by `?view=history`. */
|
||||
const alertTabs = (view: "now" | "history") => (
|
||||
/** Now, History and Noise: what is wrong right now, every time something was raised and went away, and which alerts keep coming back. The same page, switched by `?view=`. */
|
||||
const alertTabs = (view: "now" | "history" | "noise") => (
|
||||
<ViewTabs
|
||||
label="Alerts view"
|
||||
tabs={[
|
||||
{ to: "/alerts", label: "Now", active: view === "now" },
|
||||
{ to: "/alerts?view=history", label: "History", active: view === "history" },
|
||||
{ to: "/alerts?view=noise", label: "Noise", active: view === "noise" },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
export default function Alerts({ user }: { user: CurrentUser }) {
|
||||
const [params] = useSearchParams();
|
||||
if (params.get("view") === "history") {
|
||||
const view = params.get("view");
|
||||
if (view === "history" || view === "noise") {
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex align-items-center mb-2">
|
||||
<h2 className="page-title mb-0">Alerts</h2>
|
||||
</div>
|
||||
{alertTabs("history")}
|
||||
<IncidentHistory />
|
||||
{alertTabs(view)}
|
||||
{view === "history" ? <IncidentHistory /> : <AlertNoise />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -88,6 +94,9 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
// Which alerts to show by whether somebody is on them, and the one whose acknowledgement is being edited.
|
||||
const [attention, setAttention] = useState<"all" | "unacknowledged" | "acknowledged" | "mine">("all");
|
||||
const [acking, setAcking] = useState<AlertItem | null>(null);
|
||||
// Alerts ticked for a bulk action, and which bulk form is open.
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [bulkForm, setBulkForm] = useState<"ack" | "silence" | null>(null);
|
||||
// Held-back alerts are nested under the one that explains them (on by default; remembered), and each parent opens to show them.
|
||||
const [grouped, setGrouped] = useState(() => {
|
||||
try {
|
||||
@@ -167,6 +176,44 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
);
|
||||
}
|
||||
|
||||
// Only alerts that are still there can be picked (one that cleared since the last look just drops out).
|
||||
const pickedIds = useMemo(() => {
|
||||
const here = new Set((report?.alerts ?? []).map((a) => a.id));
|
||||
return [...picked].filter((id) => here.has(id));
|
||||
}, [picked, report]);
|
||||
const shownIds = useMemo(() => (sorted ?? []).filter((a) => !a.silenced).map((a) => a.id), [sorted]);
|
||||
const allShownPicked = shownIds.length > 0 && shownIds.every((id) => picked.has(id));
|
||||
function togglePicked(id: string) {
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function afterBulk() {
|
||||
void load(true);
|
||||
reloadBadge();
|
||||
}
|
||||
async function bulkAck(v: { note: string; assigneeId: number | null; hours: number | null }) {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "acknowledge", alertIds: pickedIds, ...v }, done: (r) => `${plural(r.changed, "alert")} acknowledged.`, reload: afterBulk });
|
||||
if (ok) {
|
||||
setBulkForm(null);
|
||||
setPicked(new Set());
|
||||
}
|
||||
}
|
||||
async function bulkUnack() {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "unacknowledge", alertIds: pickedIds }, done: (r) => `${plural(r.changed, "acknowledgement")} removed.`, reload: afterBulk });
|
||||
if (ok) setPicked(new Set());
|
||||
}
|
||||
async function bulkSilence(v: { minutes: number; reason: string }) {
|
||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "silence", alertIds: pickedIds, minutes: v.minutes, reason: v.reason }, done: (r) => `${plural(r.changed, "thing")} put under maintenance.`, reload: afterBulk });
|
||||
if (ok) {
|
||||
setBulkForm(null);
|
||||
setPicked(new Set());
|
||||
}
|
||||
}
|
||||
|
||||
const counts = report?.counts;
|
||||
const nothingFound = report !== null && report.alerts.length === 0;
|
||||
const cards: { label: string; value: number | undefined; color: string }[] = [
|
||||
@@ -321,6 +368,26 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
<option value="mine">Handed to me</option>
|
||||
</select>
|
||||
)}
|
||||
{canSilence && shownIds.length > 0 && (
|
||||
<label className="form-check mb-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
checked={allShownPicked}
|
||||
onChange={(e) =>
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const id of shownIds) {
|
||||
if (e.target.checked) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="form-check-label">Pick all {shownIds.length} shown</span>
|
||||
</label>
|
||||
)}
|
||||
{(counts?.grouped ?? 0) > 0 && (
|
||||
<label className="form-check mb-0">
|
||||
<input type="checkbox" className="form-check-input" checked={grouped} onChange={(e) => chooseGrouped(e.target.checked)} />
|
||||
@@ -356,12 +423,20 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
<Fragment key={a.id}>
|
||||
<tr className={`alert-row alert-row-${a.severity}${a.silenced ? " text-secondary" : ""}`} style={a.silenced ? { opacity: 0.65 } : undefined}>
|
||||
<td>
|
||||
{canSilence && (
|
||||
<input type="checkbox" className="form-check-input me-2 align-middle" aria-label={`Pick: ${a.message}`} checked={picked.has(a.id)} onChange={() => togglePicked(a.id)} />
|
||||
)}
|
||||
<span className={`badge ${SEVERITY[a.severity].badge}`}>{SEVERITY[a.severity].label}</span>
|
||||
</td>
|
||||
<td>{CATEGORY_LABELS[a.category]}</td>
|
||||
<td>{a.link ? <Link to={a.link}>{a.source}</Link> : a.source}</td>
|
||||
<td className="stack-wide">
|
||||
{a.message}
|
||||
{a.flapping && (
|
||||
<span className="badge bg-red-lt text-red ms-2" title="Raised and cleared again and again within an hour — its messages are held back until it has been calm for an hour">
|
||||
flapping
|
||||
</span>
|
||||
)}
|
||||
{a.causedBy ? (
|
||||
<span className="badge bg-secondary-lt text-secondary ms-2" title={`${a.causedBy.name} is down too, which explains this — notifications for this are held back. If ${a.causedBy.name} comes back and this stays down, it alerts then.`}>
|
||||
caused by {a.causedBy.name}
|
||||
@@ -473,6 +548,25 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
||||
</>
|
||||
)}
|
||||
|
||||
{canSilence && pickedIds.length > 0 && (
|
||||
<>
|
||||
<div className="has-bulk-bar" />
|
||||
<BulkBar count={pickedIds.length} noun={pickedIds.length === 1 ? "alert" : "alerts"} onClear={() => setPicked(new Set())}>
|
||||
<button type="button" className="btn btn-sm btn-primary" onClick={() => setBulkForm("ack")}>
|
||||
Acknowledge…
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => void bulkUnack()}>
|
||||
Remove acknowledgement
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setBulkForm("silence")}>
|
||||
Silence…
|
||||
</button>
|
||||
</BulkBar>
|
||||
</>
|
||||
)}
|
||||
{bulkForm === "ack" && <AckBulkDrawer count={pickedIds.length} onSubmit={bulkAck} onClose={() => setBulkForm(null)} />}
|
||||
{bulkForm === "silence" && <SilenceBulkDrawer noun={pickedIds.length === 1 ? "alert" : "alerts"} count={pickedIds.length} canSilenceDependents={false} onSubmit={bulkSilence} onClose={() => setBulkForm(null)} />}
|
||||
|
||||
{acking && <AckDrawer alert={acking} me={user} onClose={() => setAcking(null)} onSaved={() => {
|
||||
void load(true);
|
||||
reloadBadge();
|
||||
|
||||
@@ -16,6 +16,9 @@ import { readableError } from "../utils/errors";
|
||||
import { KIND_HINTS, KIND_LABELS, money, warrantyDays, warrantyState, yearlyCost, yearlyKwh } from "../utils/inventory";
|
||||
import { toast } from "../utils/toast";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
import BulkBar from "../components/BulkBar";
|
||||
import { HardwareBulkDrawer } from "../components/BulkDrawers";
|
||||
import { doBulk, plural } from "../utils/bulk";
|
||||
|
||||
const KINDS = Object.keys(KIND_LABELS) as AssetKind[];
|
||||
|
||||
@@ -114,6 +117,9 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [priceText, setPriceText] = useState("");
|
||||
const [currencyText, setCurrencyText] = useState("");
|
||||
// Hardware ticked for a change in one go, and whether that form is open.
|
||||
const [picked, setPicked] = useState<Set<number>>(new Set());
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
|
||||
const [params, setParams] = useSearchParams();
|
||||
const kind = (KINDS as string[]).includes(params.get("kind") ?? "") ? (params.get("kind") as AssetKind) : "";
|
||||
@@ -166,6 +172,25 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
}
|
||||
|
||||
const pickedIds = (assets ?? []).filter((a) => picked.has(a.id)).map((a) => a.id);
|
||||
const shownIds = (sorted ?? []).map((a) => a.id);
|
||||
const allShownPicked = shownIds.length > 0 && shownIds.every((id) => picked.has(id));
|
||||
function togglePicked(id: number) {
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async function bulkChange(change: { location?: string | null; warrantyUntil?: string | null; endOfSupport?: string | null }) {
|
||||
const r = await doBulk({ call: api.bulk.inventory, body: { action: "change", ids: pickedIds, ...change }, done: (res) => `${plural(res.changed, "piece")} of hardware changed.`, reload: load });
|
||||
if (r) {
|
||||
setBulkOpen(false);
|
||||
setPicked(new Set());
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(a: Asset) {
|
||||
if (!(await confirmDialog({ title: "Remove from the inventory", message: `Remove "${a.name}"?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
@@ -459,6 +484,27 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search hardware…"
|
||||
filters={
|
||||
<>
|
||||
{canEdit && shownIds.length > 0 && (
|
||||
<label className="form-check mb-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
checked={allShownPicked}
|
||||
onChange={(e) =>
|
||||
setPicked((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const id of shownIds) {
|
||||
if (e.target.checked) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return next;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="form-check-label">Pick all {shownIds.length} shown</span>
|
||||
</label>
|
||||
)}
|
||||
<select
|
||||
className="form-select form-select-sm w-auto"
|
||||
aria-label="Show hardware of kind"
|
||||
@@ -482,6 +528,7 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</>
|
||||
}
|
||||
shown={sorted?.length}
|
||||
total={all.length}
|
||||
@@ -512,6 +559,7 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
{page.pageItems?.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td className="stack-wide">
|
||||
{canEdit && <input type="checkbox" className="form-check-input me-2 align-middle" aria-label={`Pick ${a.name}`} checked={picked.has(a.id)} onChange={() => togglePicked(a.id)} />}
|
||||
{a.name}
|
||||
{(a.manufacturer || a.model) && <div className="text-secondary small">{[a.manufacturer, a.model].filter(Boolean).join(" ")}</div>}
|
||||
{a.server && (
|
||||
@@ -565,6 +613,21 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
|
||||
</div>
|
||||
|
||||
{canEdit && pickedIds.length > 0 && (
|
||||
<>
|
||||
<div className="has-bulk-bar" />
|
||||
<BulkBar count={pickedIds.length} noun={pickedIds.length === 1 ? "piece" : "pieces"} onClear={() => setPicked(new Set())}>
|
||||
<button type="button" className="btn btn-sm btn-primary" onClick={() => setBulkOpen(true)}>
|
||||
Change where / dates…
|
||||
</button>
|
||||
<Link to={`/inventory/labels?only=${pickedIds.join(",")}`} className="btn btn-sm">
|
||||
Print labels
|
||||
</Link>
|
||||
</BulkBar>
|
||||
</>
|
||||
)}
|
||||
{bulkOpen && <HardwareBulkDrawer count={pickedIds.length} onSubmit={bulkChange} onClose={() => setBulkOpen(false)} />}
|
||||
|
||||
{isAdmin && (
|
||||
<form className="card" onSubmit={saveConfig}>
|
||||
<div className="card-header">
|
||||
|
||||
@@ -30,14 +30,16 @@ export default function InventoryLabels() {
|
||||
const [showBorder, setShowBorder] = useState(true);
|
||||
// From the command palette (?only=ID): start with just that piece of hardware ticked.
|
||||
const [params] = useSearchParams();
|
||||
const only = /^\d+$/.test(params.get("only") ?? "") ? Number(params.get("only")) : null;
|
||||
// ?only=1,2,3 starts with those ticked (the Inventory page's "Print labels" for the pieces picked there).
|
||||
const only = (params.get("only") ?? "").split(",").filter((v) => /^\d+$/.test(v)).map(Number);
|
||||
|
||||
useEffect(() => {
|
||||
api.inventory
|
||||
.list()
|
||||
.then((res) => {
|
||||
setAssets(res.assets);
|
||||
setChosen(new Set(only !== null && res.assets.some((a) => a.id === only) ? [only] : res.assets.map((a) => a.id)));
|
||||
const wanted = res.assets.filter((a) => only.includes(a.id)).map((a) => a.id);
|
||||
setChosen(new Set(wanted.length > 0 ? wanted : res.assets.map((a) => a.id)));
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
|
||||
+126
-1
@@ -23,6 +23,9 @@ import SaveViewButton from "../components/SaveViewButton";
|
||||
import { agentState } from "../utils/agent";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import EmptyState, { EmptyRow, LoadingRow } from "../components/EmptyState";
|
||||
import BulkBar from "../components/BulkBar";
|
||||
import { RunsOnBulkDrawer, SilenceBulkDrawer, TagBulkDrawer } from "../components/BulkDrawers";
|
||||
import { doBulk, plural } from "../utils/bulk";
|
||||
|
||||
function typeBadgeStyle(colors: Record<string, string>, type: string): CSSProperties {
|
||||
const color = colors[type];
|
||||
@@ -53,6 +56,10 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
// Picking servers to compare their trends side by side.
|
||||
const [comparing, setComparing] = useState(false);
|
||||
const [picked, setPicked] = useState<number[]>([]);
|
||||
// Picking servers to change several at once (tags, maintenance, what they run on), and which form is open.
|
||||
const [selecting, setSelecting] = useState(false);
|
||||
const [chosen, setChosen] = useState<Set<number>>(new Set());
|
||||
const [bulkForm, setBulkForm] = useState<"tag" | "silence" | "runson" | null>(null);
|
||||
const tagColors = useTagColors();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -188,6 +195,8 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
changeParams((next) => (value ? next.set("status", value) : next.delete("status")));
|
||||
}
|
||||
|
||||
// Operators and administrators can change several servers at once; a viewer only looks.
|
||||
const canChange = user.role === "admin" || user.role === "operator";
|
||||
const MAX_COMPARE = 4;
|
||||
function togglePicked(id: number) {
|
||||
setPicked((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : prev.length >= MAX_COMPARE ? prev : [...prev, id]));
|
||||
@@ -196,6 +205,27 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
setComparing(false);
|
||||
setPicked([]);
|
||||
}
|
||||
function stopSelecting() {
|
||||
setSelecting(false);
|
||||
setChosen(new Set());
|
||||
setBulkForm(null);
|
||||
}
|
||||
function toggleChosen(id: number) {
|
||||
setChosen((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
const chosenIds = servers.filter((s) => chosen.has(s.id)).map((s) => s.id);
|
||||
async function runBulk(body: Record<string, unknown>, done: (changed: number) => string): Promise<void> {
|
||||
const r = await doBulk({ call: api.bulk.servers, body, done: (res) => done(res.changed), reload: () => void loadServers() });
|
||||
if (r) {
|
||||
setBulkForm(null);
|
||||
setChosen(new Set());
|
||||
}
|
||||
}
|
||||
|
||||
const cardBody = (s: ServerRecord) => (
|
||||
<div className="card-body">
|
||||
@@ -505,10 +535,37 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
<div className="ms-auto d-flex flex-wrap gap-2">
|
||||
<SaveViewButton />
|
||||
{servers.length > 1 && (
|
||||
<button type="button" className={`btn btn-sm ${comparing ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={comparing} onClick={() => (comparing ? stopComparing() : setComparing(true))}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${comparing ? "btn-primary" : "btn-outline-secondary"}`}
|
||||
aria-pressed={comparing}
|
||||
onClick={() => {
|
||||
if (comparing) stopComparing();
|
||||
else {
|
||||
stopSelecting();
|
||||
setComparing(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Compare
|
||||
</button>
|
||||
)}
|
||||
{canChange && (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${selecting ? "btn-primary" : "btn-outline-secondary"}`}
|
||||
aria-pressed={selecting}
|
||||
onClick={() => {
|
||||
if (selecting) stopSelecting();
|
||||
else {
|
||||
stopComparing();
|
||||
setSelecting(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{comparing && (
|
||||
@@ -532,6 +589,19 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{selecting && (
|
||||
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2" role="status">
|
||||
<span>Pick the servers to change together, then choose what to do from the bar at the foot of the page. {chosenIds.length} picked.</span>
|
||||
<div className="ms-auto d-flex gap-2">
|
||||
<button type="button" className="btn btn-sm" onClick={() => setChosen(new Set(visibleServers.map((s) => s.id)))} disabled={visibleServers.length === 0}>
|
||||
Pick all {visibleServers.length} shown
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={stopSelecting}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{allTags.length > 0 && (
|
||||
<div className="d-flex flex-wrap align-items-center gap-1 mb-3">
|
||||
<span className="text-secondary small me-1">Tags</span>
|
||||
@@ -579,6 +649,15 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
>
|
||||
{cardBody(s)}
|
||||
</button>
|
||||
) : selecting ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`card card-sm text-reset text-start w-100 compare-card ${chosen.has(s.id) ? "compare-card-on" : ""}`}
|
||||
aria-pressed={chosen.has(s.id)}
|
||||
onClick={() => toggleChosen(s.id)}
|
||||
>
|
||||
{cardBody(s)}
|
||||
</button>
|
||||
) : (
|
||||
<Link to={`/servers/${s.id}`} className="card card-sm text-reset text-decoration-none">
|
||||
{cardBody(s)}
|
||||
@@ -589,6 +668,52 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{selecting && chosenIds.length > 0 && (
|
||||
<>
|
||||
<div className="has-bulk-bar" />
|
||||
<BulkBar count={chosenIds.length} noun={chosenIds.length === 1 ? "server" : "servers"} onClear={() => setChosen(new Set())}>
|
||||
<button type="button" className="btn btn-sm btn-primary" onClick={() => setBulkForm("tag")}>
|
||||
Tag…
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setBulkForm("silence")}>
|
||||
Silence…
|
||||
</button>
|
||||
{isAdmin && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => setBulkForm("runson")}>
|
||||
Runs on…
|
||||
</button>
|
||||
)}
|
||||
</BulkBar>
|
||||
</>
|
||||
)}
|
||||
{bulkForm === "tag" && (
|
||||
<TagBulkDrawer
|
||||
count={chosenIds.length}
|
||||
tags={allTags}
|
||||
onClose={() => setBulkForm(null)}
|
||||
onSubmit={(v) =>
|
||||
runBulk({ action: v.mode === "add" ? "add_tag" : "remove_tag", ids: chosenIds, tag: v.tag }, (n) => (v.mode === "add" ? `Tagged ${plural(n, "server")} ${v.tag}.` : `Took ${v.tag} off ${plural(n, "server")}.`))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{bulkForm === "silence" && (
|
||||
<SilenceBulkDrawer
|
||||
noun={chosenIds.length === 1 ? "server" : "servers"}
|
||||
count={chosenIds.length}
|
||||
canSilenceDependents
|
||||
onClose={() => setBulkForm(null)}
|
||||
onSubmit={(v) => runBulk({ action: "silence", ids: chosenIds, ...v }, (n) => `${plural(n, "server")} put under maintenance.`)}
|
||||
/>
|
||||
)}
|
||||
{bulkForm === "runson" && (
|
||||
<RunsOnBulkDrawer
|
||||
count={chosenIds.length}
|
||||
servers={servers.filter((s) => !chosen.has(s.id)).map((s) => ({ id: s.id, name: s.name }))}
|
||||
onClose={() => setBulkForm(null)}
|
||||
onSubmit={(parentServerId) => runBulk({ action: "set_parent", ids: chosenIds, parentServerId }, (n) => `${plural(n, "server")} changed.`)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ const DIGEST_DAYS: { value: number; label: string }[] = [
|
||||
{ value: 6, label: "Saturday" },
|
||||
{ value: 0, label: "Sunday" },
|
||||
];
|
||||
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true };
|
||||
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3 };
|
||||
const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, day: 1, time: "08:00" };
|
||||
|
||||
type TestResult = { ok: boolean; message: string } | null;
|
||||
@@ -745,6 +745,17 @@ export default function NotificationSettings() {
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<div className="mt-3">
|
||||
<NumberField
|
||||
label="Call an alert flapping after"
|
||||
value={healthChecks.flapRaises}
|
||||
min={0}
|
||||
max={20}
|
||||
unit="raises in an hour"
|
||||
hint="An alert that is raised and clears this many times within an hour sends one “flapping” message and then stays quiet until it has been calm for an hour, when one message says whether it is still active. Webhooks that receive every event still get every raise and clear. 0 turns it off."
|
||||
onChange={(v) => setHealthChecks((h) => ({ ...h, flapRaises: v }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1391,6 +1391,74 @@ a.map-node:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.toast-action {
|
||||
flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
padding: 0.1rem 0.6rem;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
border: 1px solid rgba(255, 255, 255, 0.35);
|
||||
border-radius: var(--tblr-border-radius, 4px);
|
||||
}
|
||||
|
||||
.toast-action:hover {
|
||||
background: rgba(255, 255, 255, 0.26);
|
||||
}
|
||||
|
||||
/* The bar that appears at the foot of a list when some rows are picked: what to do to all of them. */
|
||||
.bulk-bar {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 1032;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
padding: 0.6rem 1rem;
|
||||
color: var(--tblr-body-color);
|
||||
background: var(--tblr-bg-surface);
|
||||
border-top: 2px solid var(--tblr-primary, #206bc4);
|
||||
box-shadow: 0 -6px 20px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
.bulk-bar {
|
||||
left: var(--tblr-sidebar-width, 15rem);
|
||||
}
|
||||
}
|
||||
|
||||
/* On a phone: the count and "Let go" share the first row, the actions take the one under it. */
|
||||
@media (max-width: 575.98px) {
|
||||
.bulk-bar {
|
||||
gap: 0.35rem 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
.bulk-bar > strong {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
.bulk-bar > button {
|
||||
order: 1;
|
||||
}
|
||||
.bulk-bar > div {
|
||||
order: 2;
|
||||
flex: 1 0 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* A page with the bar showing leaves room under its last row. */
|
||||
.has-bulk-bar {
|
||||
padding-bottom: 5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.has-bulk-bar {
|
||||
padding-bottom: 10rem;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes toast-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { api, type BulkResult } from "../api/client";
|
||||
import { readableError } from "./errors";
|
||||
import { toast } from "./toast";
|
||||
|
||||
type Call = (body: Record<string, unknown>) => Promise<BulkResult>;
|
||||
|
||||
/**
|
||||
* Runs a bulk action and says how it went, with an Undo button that sends back the body the server handed over with its answer. What was left alone is said too,
|
||||
* with why — so "12 of 14" is never a mystery. `reload` is called after the action and after an undo, so the page shows what is true.
|
||||
*/
|
||||
export async function doBulk(options: { call: Call; body: Record<string, unknown>; done: (r: BulkResult) => string; reload: () => void }): Promise<BulkResult | null> {
|
||||
try {
|
||||
const r = await options.call(options.body);
|
||||
const why = [...new Set(r.skipped.map((s) => s.reason))];
|
||||
const skipped = r.skipped.length > 0 ? ` ${r.skipped.length} left alone: ${why.slice(0, 2).join("; ")}${why.length > 2 ? "…" : ""}.` : "";
|
||||
const message = r.changed > 0 ? options.done(r) + skipped : `Nothing changed.${skipped}`;
|
||||
const undo = r.undo;
|
||||
toast.success(
|
||||
message,
|
||||
undo
|
||||
? {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
try {
|
||||
await options.call(undo);
|
||||
toast.info("Undone.");
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
options.reload();
|
||||
}
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
options.reload();
|
||||
return r;
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const bulk = api.bulk;
|
||||
|
||||
export const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
||||
+10
-3
@@ -4,10 +4,17 @@
|
||||
|
||||
export type ToastKind = "success" | "error" | "info";
|
||||
|
||||
/** A button on the toast — "Undo" after something that can be taken back. Pressing it closes the toast and does the thing. */
|
||||
export interface ToastAction {
|
||||
label: string;
|
||||
onClick: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface ToastItem {
|
||||
id: number;
|
||||
kind: ToastKind;
|
||||
message: string;
|
||||
action?: ToastAction;
|
||||
}
|
||||
|
||||
let nextId = 1;
|
||||
@@ -31,18 +38,18 @@ export function dismissToast(id: number): void {
|
||||
emit();
|
||||
}
|
||||
|
||||
function show(kind: ToastKind, message: string): void {
|
||||
function show(kind: ToastKind, message: string, action?: ToastAction): void {
|
||||
const text = message.trim();
|
||||
if (!text) return;
|
||||
// The same message twice in a row is one toast, not two.
|
||||
if (items.some((t) => t.kind === kind && t.message === text)) return;
|
||||
// A handful at most: the newest few are what matter.
|
||||
items = [...items, { id: nextId++, kind, message: text }].slice(-4);
|
||||
items = [...items, { id: nextId++, kind, message: text, ...(action ? { action } : {}) }].slice(-4);
|
||||
emit();
|
||||
}
|
||||
|
||||
export const toast = {
|
||||
success: (message: string) => show("success", message),
|
||||
success: (message: string, action?: ToastAction) => show("success", message, action),
|
||||
error: (message: string) => show("error", message),
|
||||
info: (message: string) => show("info", message),
|
||||
};
|
||||
Reference in new issue
Block a user