Add runbooks, backup coverage, inventory, roles from groups, Prometheus metrics and event webhooks

- Runbooks: notes per server/integration, shown next to matching alerts
- Backup coverage page across Proxmox and PBS, with a digest section
- Hardware inventory with warranty, power and running cost
- Authentik group to role mapping with preview and safeguards
- /metrics (bearer token) and signed outgoing event webhooks
- Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-17 20:41:00 +02:00
1 parent c36e2092c5
commit c17e9aa140
55 files changed
+7177 -27

No files matched your search

+473
View File
@@ -0,0 +1,473 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type Asset, type AssetInput, type AssetKind, type CurrentUser, type InventoryConfig } from "../api/client";
import SortableTh from "../components/SortableTh";
import TableToolbar from "../components/TableToolbar";
import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton";
import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination";
import { useSortable } from "../hooks/useSortable";
import { useTableSearch } from "../hooks/useTableSearch";
import { useSearchParams } from "react-router-dom";
import { downloadCsv } from "../utils/csv";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { KIND_HINTS, KIND_LABELS, money, warrantyDays, warrantyState, yearlyCost, yearlyKwh } from "../utils/inventory";
import { toast } from "../utils/toast";
const KINDS = Object.keys(KIND_LABELS) as AssetKind[];
interface Draft {
id: number | null;
name: string;
kind: AssetKind;
manufacturer: string;
model: string;
serial: string;
purchaseDate: string;
purchasePrice: string;
warrantyUntil: string;
location: string;
rackUnit: string;
powerWatts: string;
serverId: string;
notes: string;
}
const EMPTY: Draft = { id: null, name: "", kind: "server", manufacturer: "", model: "", serial: "", purchaseDate: "", purchasePrice: "", warrantyUntil: "", location: "", rackUnit: "", powerWatts: "", serverId: "", notes: "" };
function toDraft(a: Asset): Draft {
return {
id: a.id,
name: a.name,
kind: a.kind,
manufacturer: a.manufacturer ?? "",
model: a.model ?? "",
serial: a.serial ?? "",
purchaseDate: a.purchaseDate ?? "",
purchasePrice: a.purchasePrice === null ? "" : String(a.purchasePrice),
warrantyUntil: a.warrantyUntil ?? "",
location: a.location ?? "",
rackUnit: a.rackUnit ?? "",
powerWatts: a.powerWatts === null ? "" : String(a.powerWatts),
serverId: a.serverId === null ? "" : String(a.serverId),
notes: a.notes ?? "",
};
}
function toInput(d: Draft): AssetInput {
const num = (s: string) => (s.trim() === "" ? null : Number(s));
return {
name: d.name.trim(),
kind: d.kind,
manufacturer: d.manufacturer,
model: d.model,
serial: d.serial,
purchaseDate: d.purchaseDate || null,
purchasePrice: num(d.purchasePrice),
warrantyUntil: d.warrantyUntil || null,
location: d.location,
rackUnit: d.rackUnit,
powerWatts: num(d.powerWatts),
serverId: d.serverId === "" ? null : Number(d.serverId),
notes: d.notes,
};
}
function WarrantyBadge({ until }: { until: string | null }) {
const state = warrantyState(until);
const days = warrantyDays(until);
if (state === "none" || days === null) return <span className="text-secondary">—</span>;
if (state === "expired") return <span className="badge bg-red-lt text-red" title={until ?? undefined}>ended {Math.abs(days)} d ago</span>;
if (state === "expiring") return <span className="badge bg-yellow-lt text-yellow" title={until ?? undefined}>ends in {days} d</span>;
return <span className="text-secondary">until {until}</span>;
}
/**
* The hardware behind it all: what each machine is, when it was bought, how long it is covered, where it sits and what it draws —
* and, with a price of power, roughly what the lot costs to run. Everyone signed in can look; operators keep it up to date.
*/
export default function Inventory({ user }: { user: CurrentUser }) {
const canEdit = user.role === "admin" || user.role === "operator";
const isAdmin = user.role === "admin";
const [assets, setAssets] = useState<Asset[] | null>(null);
const [config, setConfig] = useState<InventoryConfig>({ currency: "", pricePerKwh: null });
const [servers, setServers] = useState<{ id: number; name: string }[]>([]);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [busy, setBusy] = useState(false);
const [priceText, setPriceText] = useState("");
const [currencyText, setCurrencyText] = useState("");
const [params, setParams] = useSearchParams();
const kind = (KINDS as string[]).includes(params.get("kind") ?? "") ? (params.get("kind") as AssetKind) : "";
function load() {
api.inventory
.list()
.then((res) => {
setAssets(res.assets);
setConfig(res.config);
setServers(res.servers);
setPriceText(res.config.pricePerKwh === null ? "" : String(res.config.pricePerKwh));
setCurrencyText(res.config.currency);
})
.catch((err) => setError(readableError(err)));
}
useEffect(load, []);
const ofKind = (assets ?? []).filter((a) => kind === "" || a.kind === kind);
const tableSearch = useTableSearch(ofKind);
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "name", "asc", { url: true });
const page = usePagination(sorted);
const all = assets ?? [];
const covered = all.filter((a) => warrantyState(a.warrantyUntil) === "ok").length;
const expiring = all.filter((a) => warrantyState(a.warrantyUntil) === "expiring").length;
const expired = all.filter((a) => warrantyState(a.warrantyUntil) === "expired").length;
const watts = all.reduce((n, a) => n + (a.powerWatts ?? 0), 0);
const cost = yearlyCost(watts, config.pricePerKwh);
const spent = all.reduce((n, a) => n + (a.purchasePrice ?? 0), 0);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!draft) return;
setBusy(true);
setError(null);
try {
if (draft.id === null) await api.inventory.create(toInput(draft));
else await api.inventory.update(draft.id, toInput(draft));
toast.success(draft.id === null ? `Added ${draft.name}.` : "Saved.");
setDraft(null);
load();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function remove(a: Asset) {
if (!(await confirmDialog({ title: "Remove from the inventory", message: `Remove "${a.name}"?`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.inventory.remove(a.id);
load();
} catch (err) {
setError(readableError(err));
}
}
async function saveConfig(e: React.FormEvent) {
e.preventDefault();
setError(null);
try {
const price = priceText.trim() === "" ? null : Number(priceText.replace(",", "."));
const res = await api.inventory.setConfig({ currency: currencyText.trim(), pricePerKwh: price });
setConfig(res.config);
toast.success("Saved.");
} catch (err) {
setError(readableError(err));
}
}
function exportCsv() {
if (!sorted) return;
downloadCsv(
"inventory.csv",
["Name", "Kind", "Manufacturer", "Model", "Serial", "Location", "Rack unit", "Purchased", "Price", "Warranty until", "Power (W)", "Server", "Notes"],
sorted.map((a) => [a.name, KIND_LABELS[a.kind], a.manufacturer ?? "", a.model ?? "", a.serial ?? "", a.location ?? "", a.rackUnit ?? "", a.purchaseDate ?? "", a.purchasePrice ?? "", a.warrantyUntil ?? "", a.powerWatts ?? "", a.server?.name ?? "", a.notes ?? ""]),
);
}
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [key]: value } : d));
const cards: { label: string; value: string; note?: string; color: string }[] = [
{ label: "Hardware", value: assets ? String(all.length) : "…", note: spent > 0 ? `${money(spent, config.currency)} paid` : undefined, color: "" },
{ label: "Under warranty", value: assets ? String(covered + expiring) : "…", note: expiring > 0 ? `${expiring} ending within 90 days` : expired > 0 ? `${expired} ended` : undefined, color: expiring > 0 ? "text-yellow" : "text-green" },
{ label: "Power draw", value: assets ? `${watts} W` : "…", note: watts > 0 ? `${yearlyKwh(watts).toLocaleString("sv-SE")} kWh a year` : undefined, color: "" },
{
label: "Running cost",
value: cost !== null ? `${money(cost, config.currency)} / year` : "—",
note: cost === null ? (config.pricePerKwh === null ? "set a price of power below" : "add power draws to see it") : undefined,
color: "",
},
];
return (
<>
<div className="d-flex align-items-center mb-3">
<h2 className="page-title mb-0">Inventory</h2>
{canEdit && !draft && (
<button className="btn btn-primary ms-auto" onClick={() => setDraft({ ...EMPTY })}>
Add hardware
</button>
)}
</div>
<ErrorNotice error={error} />
<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>
{draft && (
<form className="card mb-3" onSubmit={save}>
<div className="card-header">
<h3 className="card-title">{draft.id === null ? "Add hardware" : `Edit ${draft.name || "hardware"}`}</h3>
</div>
<div className="card-body row g-3">
<div className="col-md-5">
<label className="form-label" htmlFor="inv-name">
Name
</label>
<input id="inv-name" className="form-control" required maxLength={120} value={draft.name} onChange={(e) => set("name", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-kind">
Kind
</label>
<select id="inv-kind" className="form-select" value={draft.kind} onChange={(e) => set("kind", e.target.value as AssetKind)}>
{KINDS.map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]} — {KIND_HINTS[k]}
</option>
))}
</select>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-server">
Is the server
</label>
<select id="inv-server" className="form-select" value={draft.serverId} onChange={(e) => set("serverId", e.target.value)}>
<option value="">— not a server here —</option>
{servers.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-maker">
Manufacturer
</label>
<input id="inv-maker" className="form-control" maxLength={100} value={draft.manufacturer} onChange={(e) => set("manufacturer", e.target.value)} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-model">
Model
</label>
<input id="inv-model" className="form-control" maxLength={100} value={draft.model} onChange={(e) => set("model", e.target.value)} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-serial">
Serial number
</label>
<input id="inv-serial" className="form-control" maxLength={100} value={draft.serial} onChange={(e) => set("serial", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-bought">
Bought
</label>
<input id="inv-bought" type="date" className="form-control" value={draft.purchaseDate} onChange={(e) => set("purchaseDate", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-price">
Price {config.currency && <span className="text-secondary">({config.currency})</span>}
</label>
<input id="inv-price" type="number" min={0} step="any" className="form-control" value={draft.purchasePrice} onChange={(e) => set("purchasePrice", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-warranty">
Warranty until
</label>
<input id="inv-warranty" type="date" className="form-control" value={draft.warrantyUntil} onChange={(e) => set("warrantyUntil", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-power">
Typical power draw
</label>
<div className="input-group">
<input id="inv-power" type="number" min={0} max={100000} step={1} className="form-control" value={draft.powerWatts} onChange={(e) => set("powerWatts", e.target.value)} />
<span className="input-group-text">W</span>
</div>
</div>
<div className="col-md-5">
<label className="form-label" htmlFor="inv-location">
Where it is
</label>
<input id="inv-location" className="form-control" maxLength={120} placeholder="e.g. Rack in the cellar" value={draft.location} onChange={(e) => set("location", e.target.value)} />
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="inv-unit">
Rack unit
</label>
<input id="inv-unit" className="form-control" maxLength={30} placeholder="U12" value={draft.rackUnit} onChange={(e) => set("rackUnit", e.target.value)} />
</div>
<div className="col-md-5">
<label className="form-label" htmlFor="inv-notes">
Notes
</label>
<input id="inv-notes" className="form-control" maxLength={2000} value={draft.notes} onChange={(e) => set("notes", e.target.value)} />
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || draft.name.trim() === ""}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
<div className="card mb-3">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search hardware…"
filters={
<select
className="form-select form-select-sm w-auto"
aria-label="Show hardware of kind"
value={kind}
onChange={(e) =>
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (e.target.value) next.set("kind", e.target.value);
else next.delete("kind");
return next;
},
{ replace: true },
)
}
>
<option value="">Every kind</option>
{KINDS.map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]}
</option>
))}
</select>
}
shown={sorted?.length}
total={all.length}
onExport={exportCsv}
exportDisabled={!sorted || sorted.length === 0}
/>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<Asset> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Where" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Bought" sortKeyName="purchaseDate" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Warranty" sortKeyName="warrantyUntil" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Power" sortKeyName="powerWatts" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
{canEdit && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{assets === null && !error && (
<tr>
<td colSpan={canEdit ? 7 : 6}>
<BlockSkeleton lines={3} />
</td>
</tr>
)}
{page.pageItems?.map((a) => (
<tr key={a.id}>
<td>
{a.name}
{(a.manufacturer || a.model) && <div className="text-secondary small">{[a.manufacturer, a.model].filter(Boolean).join(" ")}</div>}
{a.server && (
<div className="small">
is <Link to={`/servers/${a.server.id}`}>{a.server.name}</Link>
</div>
)}
</td>
<td>{KIND_LABELS[a.kind]}</td>
<td>
{a.location ?? "—"}
{a.rackUnit && <span className="text-secondary"> · {a.rackUnit}</span>}
</td>
<td className="text-secondary">
{a.purchaseDate ?? "—"}
{a.purchasePrice !== null && <div className="small">{money(a.purchasePrice, config.currency)}</div>}
</td>
<td>
<WarrantyBadge until={a.warrantyUntil} />
</td>
<td>{a.powerWatts === null ? <span className="text-secondary">—</span> : `${a.powerWatts} W`}</td>
{canEdit && (
<td>
<div className="btn-list flex-nowrap">
<button className="btn btn-sm btn-outline-secondary" onClick={() => setDraft(toDraft(a))}>
Edit
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(a)}>
Remove
</button>
</div>
</td>
)}
</tr>
))}
{assets !== null && sorted?.length === 0 && (
<tr>
<td colSpan={canEdit ? 7 : 6} className="text-secondary text-center">
{tableSearch.active || kind ? "Nothing matches that." : `Nothing in the inventory yet.${canEdit ? " Add the first piece of hardware." : ""}`}
</td>
</tr>
)}
</tbody>
</table>
</div>
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
</div>
{isAdmin && (
<form className="card" onSubmit={saveConfig}>
<div className="card-header">
<h3 className="card-title">Price of power</h3>
</div>
<div className="card-body row g-3 align-items-end">
<div className="col-md-3">
<label className="form-label" htmlFor="inv-kwh">
Price per kWh
</label>
<input id="inv-kwh" type="number" min={0} step="any" className="form-control" value={priceText} onChange={(e) => setPriceText(e.target.value)} />
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="inv-cur">
Currency
</label>
<input id="inv-cur" className="form-control" maxLength={8} placeholder="SEK" value={currencyText} onChange={(e) => setCurrencyText(e.target.value)} />
</div>
<div className="col-md-7 text-secondary small">
Used for the running cost above: each machine's typical draw, all day, all year, at this price. It is a rough guide — a machine rarely draws its typical figure all the time.
</div>
</div>
<div className="card-footer">
<button type="submit" className="btn btn-primary">
Save
</button>
</div>
</form>
)}
</>
);
}