Files
Homelab-manager/web/src/pages/Alerts.tsx
T
bobbanandClaude Sonnet 5.5 96c93ef924 Add the Alert tickets settings page, and show each alert's ticket on the Alerts page
Settings -> Alert tickets: switch it on, choose the osTicket integration (only ones with a ticket API
set up can be chosen), who the tickets come from, help topic and priority, which severities and kinds,
how long a problem must last, when many become one summary ticket, how long a return counts as the
same problem, and what to do about problems already there. Buttons to send a test ticket and to check
now, and a line saying what the last check did. Server messages (a missing integration, a refused key)
are shown as they are.

The Alerts page shows "Ticket #123" on an alert that has one, linking to it in osTicket, and a Ticket
column in the CSV export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 23:41:46 +02:00

260 lines
12 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { api, type AlertCategory, type AlertItem, type AlertSeverity, type AlertsReport, type CurrentUser } from "../api/client";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv";
import { formatDateTime } from "../utils/date";
import { formatAgo } from "../utils/duration";
import { readableError } from "../utils/errors";
const SEVERITY: Record<AlertSeverity, { label: string; badge: string; rank: number }> = {
critical: { label: "Critical", badge: "bg-red-lt text-red", rank: 0 },
warning: { label: "Warning", badge: "bg-yellow-lt text-yellow", rank: 1 },
info: { label: "Info", badge: "bg-blue-lt text-blue", rank: 2 },
};
const CATEGORY_LABELS: Record<AlertCategory, string> = {
offline: "Server down",
disk: "Disk & storage",
backup: "Backups",
updates: "Updates",
expiry: "Expiry",
automation: "Automation",
integration: "Integration failing",
monitoring: "Monitoring",
tickets: "Tickets",
};
type Row = AlertItem & { rank: number };
export default function Alerts(_props: { user: CurrentUser }) {
const [report, setReport] = useState<AlertsReport | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [severity, setSeverity] = useState<"all" | AlertSeverity>("all");
const [category, setCategory] = useState<"all" | AlertCategory>("all");
const [search, setSearch] = useState("");
const [showSilenced, setShowSilenced] = useState(true);
function load(refresh = false) {
setLoading(true);
return api.alerts
.list(refresh)
.then((res) => {
setReport(res);
setError(null);
})
.catch((err) => setError(readableError(err)))
.finally(() => setLoading(false));
}
useEffect(() => {
void load();
}, []);
const rows: Row[] = useMemo(() => {
if (!report) return [];
const q = search.trim().toLowerCase();
return report.alerts
.filter((a) => (severity === "all" || a.severity === severity) && (category === "all" || a.category === category) && (showSilenced || !a.silenced))
.filter((a) => !q || [a.message, a.source, CATEGORY_LABELS[a.category]].some((v) => v.toLowerCase().includes(q)))
.map((a) => ({ ...a, rank: SEVERITY[a.severity].rank }));
}, [report, severity, category, search, showSilenced]);
// No initial sort: the server already puts active problems first, worst first.
const { sorted, sortKey, sortDir, requestSort } = useSortable(rows);
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
const presentCategories = useMemo(() => [...new Set((report?.alerts ?? []).map((a) => a.category))], [report]);
function exportCsv() {
downloadCsv(
"alerts.csv",
["Severity", "Category", "Source", "Alert", "Silenced", "Ticket"],
(sorted ?? []).map((a) => [SEVERITY[a.severity].label, CATEGORY_LABELS[a.category], a.source, a.message, a.silenced ? "yes" : "no", a.ticket ? (a.ticket.number ?? "opened") : ""]),
);
}
const counts = report?.counts;
const nothingFound = report !== null && report.alerts.length === 0;
const cards: { label: string; value: number | undefined; color: string }[] = [
{ label: "Critical", value: counts?.critical, color: "text-red" },
{ label: "Warnings", value: counts?.warning, color: "text-yellow" },
{ label: "Info", value: counts?.info, color: "text-blue" },
{ label: "Silenced (maintenance)", value: counts?.silenced, color: "text-secondary" },
];
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">Alerts</h2>
<div className="ms-auto btn-list">
<button className="btn btn-outline-secondary" onClick={exportCsv} disabled={!sorted?.length}>
Export CSV
</button>
<button className="btn btn-outline-secondary" onClick={() => void load(true)} disabled={loading}>
{loading ? "Checking…" : "Check now"}
</button>
</div>
</div>
<div className="text-secondary mb-3">
What's wrong right now across your servers and integrations — full disks, servers that stopped reporting, failed backups, updates waiting,
things about to expire. It runs the same checks that send notifications, whether or not those notifications are switched on.
{report && (
<>
{" "}
<span title={formatDateTime(new Date(report.generatedAt))}>
Checked {formatAgo(report.generatedAt)}
{report.cached ? " (a recent result, reused)" : ""}.
</span>
</>
)}
</div>
{error && <div className="alert alert-danger">{error}</div>}
{!report && !error && (
<div className="card">
<div className="card-body text-secondary">Checking everything — this can take a few seconds…</div>
</div>
)}
{report && (
<>
<div className="row g-3 mb-3">
{cards.map((c) => (
<div className="col-6 col-md-3" key={c.label}>
<div className="card card-sm">
<div className="card-body">
<div className="text-secondary">{c.label}</div>
<div className={`h2 mb-0 ${c.value ? c.color : ""}`}>{c.value ?? "—"}</div>
</div>
</div>
</div>
))}
</div>
{report.couldntCheck.length > 0 && (
<div className="alert alert-warning">
<div>
<div className="fw-bold mb-1">Couldn't check everything — what's missing below isn't necessarily fine</div>
<ul className="mb-0">
{report.couldntCheck.map((c) => (
<li key={c.name}>
<strong>{c.name}</strong> — {c.error}
{c.affects.length > 0 && <span className="text-secondary"> (affects: {c.affects.join(", ")})</span>}
</li>
))}
</ul>
</div>
</div>
)}
{report.notes.map((n) => (
<div className="alert alert-info" key={n}>
{n}
</div>
))}
{nothingFound ? (
<div className="card">
<div className="card-body text-center py-5">
{report.couldntCheck.length === 0 ? (
<>
<div className="h3 text-green mb-1">All clear</div>
<div className="text-secondary">Nothing needs attention right now.</div>
</>
) : (
<div className="text-secondary">No problems found in what could be checked — see the warning above for what couldn't.</div>
)}
</div>
</div>
) : (
<div className="card">
<div className="card-header">
<div className="d-flex flex-wrap gap-2 align-items-center w-100">
<input className="form-control" style={{ maxWidth: 260 }} placeholder="Search alerts…" value={search} onChange={(e) => setSearch(e.target.value)} />
<select className="form-select w-auto" value={severity} onChange={(e) => setSeverity(e.target.value as "all" | AlertSeverity)}>
<option value="all">All severities</option>
<option value="critical">Critical</option>
<option value="warning">Warning</option>
<option value="info">Info</option>
</select>
<select className="form-select w-auto" value={category} onChange={(e) => setCategory(e.target.value as "all" | AlertCategory)}>
<option value="all">All kinds</option>
{presentCategories.map((c) => (
<option key={c} value={c}>
{CATEGORY_LABELS[c]}
</option>
))}
</select>
{(counts?.silenced ?? 0) > 0 && (
<label className="form-check mb-0">
<input type="checkbox" className="form-check-input" checked={showSilenced} onChange={(e) => setShowSilenced(e.target.checked)} />
<span className="form-check-label">Show silenced</span>
</label>
)}
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<Row> label="Severity" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Kind" sortKeyName="category" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Source" sortKeyName="source" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Alert" sortKeyName="message" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
</tr>
</thead>
<tbody>
{(pageItems ?? []).map((a) => (
<tr key={a.id} className={a.silenced ? "text-secondary" : undefined} style={a.silenced ? { opacity: 0.65 } : undefined}>
<td>
<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>
{a.message}
{a.silenced && (
<span className="badge bg-secondary-lt text-secondary ms-2" title="Under a maintenance window — notifications for this are held back">
silenced
</span>
)}
{a.ticket &&
(() => {
const label = a.ticket.number ? `Ticket #${a.ticket.number}` : "Ticket opened";
const title = a.ticket.grouped ? "Part of one ticket that covers several problems that appeared together" : "A ticket was opened for this in osTicket";
return a.ticket.url ? (
<a className="badge bg-blue-lt text-blue ms-2" href={a.ticket.url} target="_blank" rel="noopener noreferrer" title={title}>
{label}
</a>
) : (
<span className="badge bg-blue-lt text-blue ms-2" title={title}>
{label}
</span>
);
})()}
</td>
</tr>
))}
{(sorted ?? []).length === 0 && (
<tr>
<td colSpan={4} className="text-secondary text-center">
Nothing matches these filters.
</td>
</tr>
)}
</tbody>
</table>
</div>
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
</div>
)}
</>
)}
</>
);
}