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:
1 parent
c36e2092c5
commit
c17e9aa140
55 files changed
+7177
-27
No files matched your search
@@ -29,6 +29,8 @@ import Alerts from "./pages/Alerts";
|
||||
import Generator from "./pages/Generator";
|
||||
import Maintenance from "./pages/Maintenance";
|
||||
import Updates from "./pages/Updates";
|
||||
import Inventory from "./pages/Inventory";
|
||||
import Backups from "./pages/Backups";
|
||||
import Domains from "./pages/Domains";
|
||||
import Consistency from "./pages/Consistency";
|
||||
import Privacy from "./pages/Privacy";
|
||||
@@ -43,6 +45,8 @@ import BackupSettings from "./pages/settings/BackupSettings";
|
||||
import NameSettings from "./pages/settings/NameSettings";
|
||||
import AlertTicketSettings from "./pages/settings/AlertTicketSettings";
|
||||
import ShareSettings from "./pages/settings/ShareSettings";
|
||||
import SignInSettings from "./pages/settings/SignInSettings";
|
||||
import ApiSettings from "./pages/settings/ApiSettings";
|
||||
import AppShell from "./layout/AppShell";
|
||||
import DialogHost from "./components/DialogHost";
|
||||
import Wall from "./pages/Wall";
|
||||
@@ -138,6 +142,8 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/domains" element={<Domains user={user} />} />
|
||||
<Route path="/maintenance" element={<Maintenance user={user} />} />
|
||||
<Route path="/updates" element={<Updates />} />
|
||||
<Route path="/inventory" element={<Inventory user={user} />} />
|
||||
<Route path="/backups" element={<Backups />} />
|
||||
<Route path="/docker" element={<Docker user={user} />} />
|
||||
<Route path="/tailscale" element={<Tailscale user={user} />} />
|
||||
<Route path="/semaphore" element={<Semaphore user={user} />} />
|
||||
@@ -192,11 +198,13 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route index element={<Navigate to="notifications" replace />} />
|
||||
<Route path="notifications" element={<NotificationSettings />} />
|
||||
<Route path="badges" element={<BadgeSettings />} />
|
||||
<Route path="sign-in" element={<SignInSettings />} />
|
||||
<Route path="display" element={<DisplaySettings />} />
|
||||
<Route path="tags" element={<TagSettings />} />
|
||||
<Route path="names" element={<NameSettings />} />
|
||||
<Route path="alert-tickets" element={<AlertTicketSettings />} />
|
||||
<Route path="share" element={<ShareSettings />} />
|
||||
<Route path="api" element={<ApiSettings />} />
|
||||
<Route path="cache" element={<CacheSettings />} />
|
||||
<Route path="logs" element={<LogSettings />} />
|
||||
<Route path="backup" element={<BackupSettings />} />
|
||||
|
||||
+172
-1
@@ -95,6 +95,24 @@ export interface UserRecord {
|
||||
role: UserRole;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
/** The groups the identity provider reported at their last sign-in; null until they have signed in with groups available. */
|
||||
groups: string[] | null;
|
||||
}
|
||||
|
||||
/** How roles are decided at sign-in: by hand on the Users page, or from the groups the identity provider reports. */
|
||||
export interface SignInSettings {
|
||||
roleFromGroups: boolean;
|
||||
groupsClaim: string;
|
||||
adminGroups: string[];
|
||||
operatorGroups: string[];
|
||||
otherwise: "viewer" | "keep";
|
||||
}
|
||||
|
||||
/** What each person would be under a draft of the group rules. */
|
||||
export interface GroupRolePreview {
|
||||
people: { id: number; name: string; role: UserRole; groups: string[] | null; wouldBe: UserRole | null }[];
|
||||
/** How many administrators there would be; 0 means the rules would lock everyone out of administration. */
|
||||
adminsAfter: number;
|
||||
}
|
||||
|
||||
export interface SessionSummary {
|
||||
@@ -423,6 +441,7 @@ export interface AppSettings {
|
||||
quietHours: QuietHoursSettings;
|
||||
healthChecks: HealthCheckSettings;
|
||||
digest: DigestSettings;
|
||||
signIn: SignInSettings;
|
||||
}
|
||||
|
||||
export type AppSettingsPatch = { [K in keyof AppSettings]?: Partial<AppSettings[K]> };
|
||||
@@ -586,6 +605,125 @@ export interface ServerDetail {
|
||||
agentLatest: AgentLatest;
|
||||
}
|
||||
|
||||
/** A token that opens /metrics for Prometheus, as the list shows it (never the secret). */
|
||||
export interface MetricsToken {
|
||||
id: number;
|
||||
label: string;
|
||||
tokenPrefix: string;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
lastUsedAt: string | null;
|
||||
}
|
||||
|
||||
export type WebhookEventName = "alert.opened" | "alert.resolved" | "maintenance.started" | "maintenance.ended";
|
||||
|
||||
/** A URL sent a signed JSON message when something happens. */
|
||||
export interface EventWebhook {
|
||||
id: number;
|
||||
label: string;
|
||||
url: string;
|
||||
hasSecret: boolean;
|
||||
events: WebhookEventName[];
|
||||
enabled: boolean;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
lastAttemptAt: string | null;
|
||||
/** "200", or what went wrong. */
|
||||
lastResult: string | null;
|
||||
}
|
||||
|
||||
export type CoverageStatus = "ok" | "stale" | "failed" | "none" | "unknown";
|
||||
|
||||
/** One Proxmox guest and how well it is backed up. */
|
||||
export interface CoverageGuest {
|
||||
integrationId: number;
|
||||
integrationName: string;
|
||||
node: string;
|
||||
vmid: number;
|
||||
name: string;
|
||||
type: "qemu" | "lxc";
|
||||
power: string;
|
||||
/** A backup job covers it. */
|
||||
inJob: boolean;
|
||||
lastBackupAt: string | null;
|
||||
lastSource: "pbs" | "task" | null;
|
||||
status: CoverageStatus;
|
||||
failure: string | null;
|
||||
server: { id: number; name: string } | null;
|
||||
}
|
||||
|
||||
export interface BackupCoverage {
|
||||
guests: CoverageGuest[];
|
||||
counts: Record<CoverageStatus, number> & { total: number };
|
||||
sources: { kind: "proxmox" | "pbs"; name: string; ok: boolean; error?: string }[];
|
||||
staleHours: number;
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export type AssetKind = "server" | "storage" | "network" | "power" | "client" | "other";
|
||||
|
||||
/** A piece of hardware in the inventory. */
|
||||
export interface Asset {
|
||||
id: number;
|
||||
name: string;
|
||||
kind: AssetKind;
|
||||
manufacturer: string | null;
|
||||
model: string | null;
|
||||
serial: string | null;
|
||||
purchaseDate: string | null;
|
||||
purchasePrice: number | null;
|
||||
warrantyUntil: string | null;
|
||||
location: string | null;
|
||||
rackUnit: string | null;
|
||||
powerWatts: number | null;
|
||||
serverId: number | null;
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
/** The server it is, when it is one and that server still exists. */
|
||||
server: { id: number; name: string } | null;
|
||||
}
|
||||
|
||||
/** What an entry is saved from: blank text and nulls mean "no value". */
|
||||
export interface AssetInput {
|
||||
name: string;
|
||||
kind: AssetKind;
|
||||
manufacturer?: string | null;
|
||||
model?: string | null;
|
||||
serial?: string | null;
|
||||
purchaseDate?: string | null;
|
||||
purchasePrice?: number | null;
|
||||
warrantyUntil?: string | null;
|
||||
location?: string | null;
|
||||
rackUnit?: string | null;
|
||||
powerWatts?: number | null;
|
||||
serverId?: number | null;
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
/** What the running cost is worked out with. */
|
||||
export interface InventoryConfig {
|
||||
currency: string;
|
||||
pricePerKwh: number | null;
|
||||
}
|
||||
|
||||
/** A note about what to do when something is wrong with a server, integration or DNS provider. */
|
||||
export interface Runbook {
|
||||
id: number;
|
||||
targetType: MaintenanceTargetType;
|
||||
targetId: number;
|
||||
title: string;
|
||||
body: string;
|
||||
/** An alert category it is for, or null for anything about the target. */
|
||||
category: AlertCategory | null;
|
||||
updatedBy: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** A runbook's title and what it is for, without its text. */
|
||||
export type RunbookSummary = Pick<Runbook, "id" | "targetType" | "targetId" | "category" | "title">;
|
||||
|
||||
export type AlertSeverity = "critical" | "warning" | "info";
|
||||
export type AlertCategory = "offline" | "disk" | "backup" | "updates" | "expiry" | "automation" | "integration" | "monitoring" | "tickets";
|
||||
|
||||
@@ -1279,6 +1417,37 @@ export const api = {
|
||||
uptime: {
|
||||
get: () => request<UptimeReport>("/api/uptime"),
|
||||
},
|
||||
metricsTokens: {
|
||||
list: () => request<{ tokens: MetricsToken[] }>("/api/metrics-tokens"),
|
||||
create: (label: string) => request<{ token: MetricsToken; secret: string }>("/api/metrics-tokens", { method: "POST", body: JSON.stringify({ label }) }),
|
||||
remove: (id: number) => request<void>(`/api/metrics-tokens/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
eventWebhooks: {
|
||||
list: () => request<{ webhooks: EventWebhook[]; events: WebhookEventName[] }>("/api/event-webhooks"),
|
||||
create: (data: { label: string; url: string; secret?: string; events: WebhookEventName[] }) => request<{ webhook: EventWebhook }>("/api/event-webhooks", { method: "POST", body: JSON.stringify(data) }),
|
||||
setEnabled: (id: number, enabled: boolean) => request<{ webhook: EventWebhook }>(`/api/event-webhooks/${id}`, { method: "PATCH", body: JSON.stringify({ enabled }) }),
|
||||
remove: (id: number) => request<void>(`/api/event-webhooks/${id}`, { method: "DELETE" }),
|
||||
test: (id: number) => request<{ ok: boolean; result: string }>(`/api/event-webhooks/${id}/test`, { method: "POST" }),
|
||||
},
|
||||
backups: {
|
||||
coverage: (staleDays: number, refresh = false) => request<BackupCoverage>(`/api/backups/coverage?staleDays=${staleDays}${refresh ? "&refresh=1" : ""}`),
|
||||
},
|
||||
inventory: {
|
||||
list: () => request<{ assets: Asset[]; config: InventoryConfig; servers: { id: number; name: string }[] }>("/api/inventory"),
|
||||
create: (data: AssetInput) => request<{ asset: Asset }>("/api/inventory", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: number, data: AssetInput) => request<{ asset: Asset }>(`/api/inventory/${id}`, { method: "PUT", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/inventory/${id}`, { method: "DELETE" }),
|
||||
setConfig: (data: InventoryConfig) => request<{ config: InventoryConfig }>("/api/inventory/config", { method: "PUT", body: JSON.stringify(data) }),
|
||||
},
|
||||
runbooks: {
|
||||
list: (targetType: MaintenanceTargetType, targetId: number) => request<{ runbooks: Runbook[] }>(`/api/runbooks?targetType=${targetType}&targetId=${targetId}`),
|
||||
summary: () => request<{ runbooks: RunbookSummary[] }>("/api/runbooks/summary"),
|
||||
create: (data: { targetType: MaintenanceTargetType; targetId: number; title: string; body: string; category: AlertCategory | null }) =>
|
||||
request<{ runbook: Runbook }>("/api/runbooks", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: number, data: { title: string; body: string; category: AlertCategory | null }) =>
|
||||
request<{ runbook: Runbook }>(`/api/runbooks/${id}`, { method: "PUT", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/runbooks/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
shareLinks: {
|
||||
list: () => request<{ links: ShareLink[] }>("/api/share-links"),
|
||||
create: (data: { label: string; detail: ShareLinkDetail; expiresInDays: number | null }) =>
|
||||
@@ -1297,7 +1466,9 @@ export const api = {
|
||||
query: (q: string) => request<SearchResponse>(`/api/search?q=${encodeURIComponent(q)}`),
|
||||
},
|
||||
users: {
|
||||
list: () => request<{ users: UserRecord[] }>("/api/users"),
|
||||
list: () => request<{ users: UserRecord[]; rolesFollowGroups: boolean }>("/api/users"),
|
||||
previewGroupRoles: (rules: Pick<SignInSettings, "groupsClaim" | "adminGroups" | "operatorGroups" | "otherwise">) =>
|
||||
request<GroupRolePreview>("/api/users/preview-group-roles", { method: "POST", body: JSON.stringify(rules) }),
|
||||
updateRole: (id: number, role: UserRole) =>
|
||||
request<{ user: UserRecord }>(`/api/users/${id}/role`, {
|
||||
method: "PATCH",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useState } from "react";
|
||||
import { IconBook } from "@tabler/icons-react";
|
||||
import type { AlertCategory, MaintenanceTargetType } from "../api/client";
|
||||
import { useRunbookSummary } from "../hooks/useRunbooks";
|
||||
import DetailDrawer from "./DetailDrawer";
|
||||
import RunbookPanel from "./RunbookPanel";
|
||||
|
||||
/**
|
||||
* A small "Runbook" link that opens what is written down about a server, integration or DNS provider in a side panel. Shown where there is
|
||||
* something to read — for an alert, only if a note fits that kind of alert — and, for those who can write them, where there isn't yet.
|
||||
*/
|
||||
export default function RunbookEntry({
|
||||
targetType,
|
||||
targetId,
|
||||
targetName,
|
||||
canEdit,
|
||||
forCategory,
|
||||
offerAdd = false,
|
||||
}: {
|
||||
targetType: MaintenanceTargetType;
|
||||
targetId: number;
|
||||
targetName: string;
|
||||
canEdit: boolean;
|
||||
forCategory?: AlertCategory;
|
||||
/** Show "Add a runbook" for those who can, when there is none. */
|
||||
offerAdd?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const summary = useRunbookSummary();
|
||||
const here = (summary ?? []).filter((r) => r.targetType === targetType && r.targetId === targetId);
|
||||
const fitting = forCategory ? here.filter((r) => r.category === null || r.category === forCategory) : here;
|
||||
if (fitting.length === 0 && !(offerAdd && canEdit && summary !== null)) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-link btn-sm p-0 d-inline-flex align-items-center gap-1 align-baseline"
|
||||
title={fitting.length > 0 ? fitting.map((r) => r.title).join(", ") : `Write down what to do about ${targetName}`}
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<IconBook size={14} aria-hidden="true" />
|
||||
{fitting.length > 0 ? (fitting.length === 1 ? "Runbook" : `Runbooks (${fitting.length})`) : "Add a runbook"}
|
||||
</button>
|
||||
{open && (
|
||||
<DetailDrawer title="Runbook" subtitle={targetName} onClose={() => setOpen(false)}>
|
||||
<RunbookPanel targetType={targetType} targetId={targetId} targetName={targetName} canEdit={canEdit} forCategory={forCategory} />
|
||||
</DetailDrawer>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type AlertCategory, type MaintenanceTargetType, type Runbook } from "../api/client";
|
||||
import { RUNBOOKS_CHANGED } from "../hooks/useRunbooks";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
import { BlockSkeleton } from "./Skeleton";
|
||||
import RunbookText from "./RunbookText";
|
||||
import TimeAgo from "./TimeAgo";
|
||||
|
||||
export const CATEGORY_WORDS: Record<AlertCategory, string> = {
|
||||
offline: "a server that stopped reporting",
|
||||
disk: "a disk filling up",
|
||||
backup: "a backup problem",
|
||||
updates: "updates waiting",
|
||||
expiry: "something expiring",
|
||||
automation: "a failed automation run",
|
||||
integration: "an integration failing",
|
||||
monitoring: "a monitoring problem",
|
||||
tickets: "tickets",
|
||||
};
|
||||
|
||||
interface Draft {
|
||||
id: number | null;
|
||||
title: string;
|
||||
body: string;
|
||||
category: AlertCategory | "";
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do when something is wrong with this server, integration or DNS provider, written down where whoever is on call will look:
|
||||
* on its page and next to its alerts. Everyone signed in reads them; operators write them. A note can be for one kind of alert (a disk
|
||||
* filling) or for anything about the thing, and when opened from an alert the notes that fit it come first.
|
||||
*/
|
||||
export default function RunbookPanel({
|
||||
targetType,
|
||||
targetId,
|
||||
targetName,
|
||||
canEdit,
|
||||
forCategory,
|
||||
}: {
|
||||
targetType: MaintenanceTargetType;
|
||||
targetId: number;
|
||||
targetName: string;
|
||||
canEdit: boolean;
|
||||
/** Opened from an alert of this kind: the notes that fit it are listed first and marked. */
|
||||
forCategory?: AlertCategory;
|
||||
}) {
|
||||
const [notes, setNotes] = useState<Runbook[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function load() {
|
||||
api.runbooks
|
||||
.list(targetType, targetId)
|
||||
.then((res) => setNotes(res.runbooks))
|
||||
.catch(() => setFailed(true));
|
||||
}
|
||||
useEffect(load, [targetType, targetId]);
|
||||
|
||||
const fits = (n: Runbook) => !forCategory || n.category === null || n.category === forCategory;
|
||||
const ordered = [...(notes ?? [])].sort((a, b) => Number(fits(b)) - Number(fits(a)) || a.title.localeCompare(b.title));
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!draft) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = { title: draft.title.trim(), body: draft.body, category: draft.category === "" ? null : draft.category };
|
||||
if (draft.id === null) await api.runbooks.create({ targetType, targetId, ...data });
|
||||
else await api.runbooks.update(draft.id, data);
|
||||
toast.success("Saved.");
|
||||
setDraft(null);
|
||||
load();
|
||||
window.dispatchEvent(new Event(RUNBOOKS_CHANGED));
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(n: Runbook) {
|
||||
if (!(await confirmDialog({ title: "Remove runbook", message: `Remove "${n.title}"?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.runbooks.remove(n.id);
|
||||
load();
|
||||
window.dispatchEvent(new Event(RUNBOOKS_CHANGED));
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
if (failed) return <div className="text-secondary">Couldn't load the runbooks.</div>;
|
||||
if (notes === null) return <BlockSkeleton lines={3} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{ordered.length === 0 && !draft && (
|
||||
<div className="text-secondary mb-3">
|
||||
Nothing written down for {targetName} yet.{canEdit ? " Add what to check first, who to call, how to bring it back." : ""}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ordered.map((n) => (
|
||||
<div key={n.id} className={`border rounded p-3 mb-3 ${fits(n) ? "" : "opacity-75"}`}>
|
||||
<div className="d-flex flex-wrap align-items-start gap-2 mb-2">
|
||||
<div className="fw-bold me-auto">{n.title}</div>
|
||||
{n.category ? (
|
||||
<span className={`badge ${forCategory && n.category === forCategory ? "bg-blue-lt text-blue" : "bg-secondary-lt text-secondary"}`}>for {CATEGORY_WORDS[n.category as AlertCategory] ?? n.category}</span>
|
||||
) : (
|
||||
<span className="badge bg-secondary-lt text-secondary">for anything about it</span>
|
||||
)}
|
||||
</div>
|
||||
<RunbookText text={n.body} />
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mt-2">
|
||||
<span className="text-secondary small">
|
||||
{n.updatedBy ? `${n.updatedBy}, ` : ""}
|
||||
<TimeAgo value={n.updatedAt} />
|
||||
</span>
|
||||
{canEdit && (
|
||||
<span className="ms-auto btn-list flex-nowrap">
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => setDraft({ id: n.id, title: n.title, body: n.body, category: (n.category as AlertCategory | null) ?? "" })}>
|
||||
Edit
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-outline-danger" onClick={() => void remove(n)}>
|
||||
Remove
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{draft ? (
|
||||
<form onSubmit={save} className="border rounded p-3">
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="rb-title">
|
||||
Title
|
||||
</label>
|
||||
<input id="rb-title" className="form-control" required maxLength={120} placeholder={`e.g. If ${targetName} is down`} value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="rb-for">
|
||||
For
|
||||
</label>
|
||||
<select id="rb-for" className="form-select" value={draft.category} onChange={(e) => setDraft({ ...draft, category: e.target.value as AlertCategory | "" })}>
|
||||
<option value="">Anything about it</option>
|
||||
{(Object.keys(CATEGORY_WORDS) as AlertCategory[]).map((c) => (
|
||||
<option key={c} value={c}>
|
||||
Only {CATEGORY_WORDS[c]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<label className="form-label" htmlFor="rb-body">
|
||||
What to do
|
||||
</label>
|
||||
<textarea id="rb-body" className="form-control" rows={9} required maxLength={20000} value={draft.body} onChange={(e) => setDraft({ ...draft, body: e.target.value })} />
|
||||
<div className="form-hint">
|
||||
Plain text. A blank line starts a new paragraph; <code>- </code> makes a list; <code>```</code> around lines makes a block of commands; <code>`like this`</code> is inline code; links are made clickable.
|
||||
</div>
|
||||
</div>
|
||||
{error && <div className="text-danger small mb-2">{error}</div>}
|
||||
<div className="btn-list">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || draft.title.trim() === ""}>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
canEdit && (
|
||||
<button type="button" className="btn btn-outline-secondary" onClick={() => setDraft({ id: null, title: "", body: "", category: forCategory ?? "" })}>
|
||||
Add a runbook
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* A runbook's text, drawn. A little formatting, written the way people already write notes — and never raw HTML: everything is built
|
||||
* as plain elements, so nothing typed into a note can run or restyle the page, and a link only becomes a link if it is http or https.
|
||||
*
|
||||
* blank line new paragraph - item / * item a list
|
||||
* 1. item a numbered list # Heading a small heading
|
||||
* ``` … ``` a block of commands \`code\` inline code
|
||||
* **bold** bold https://… a link, as is
|
||||
* [words](https://…) a link with words
|
||||
*/
|
||||
|
||||
const INLINE = /(`[^`\n]+`|\*\*[^*\n]+\*\*|\[[^\]\n]+\]\(https?:\/\/[^\s)]+\)|https?:\/\/[^\s<>"')]+)/g;
|
||||
|
||||
function inline(text: string, keyBase: string): ReactNode[] {
|
||||
return text.split(INLINE).map((part, i) => {
|
||||
const key = `${keyBase}-${i}`;
|
||||
if (!part) return null;
|
||||
if (part.startsWith("`") && part.endsWith("`") && part.length > 2) return <code key={key}>{part.slice(1, -1)}</code>;
|
||||
if (part.startsWith("**") && part.endsWith("**") && part.length > 4) return <strong key={key}>{part.slice(2, -2)}</strong>;
|
||||
const named = /^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(part);
|
||||
if (named) {
|
||||
return (
|
||||
<a key={key} href={named[2]} target="_blank" rel="noopener noreferrer">
|
||||
{named[1]}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
if (/^https?:\/\//.test(part)) {
|
||||
return (
|
||||
<a key={key} href={part} target="_blank" rel="noopener noreferrer">
|
||||
{part}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return <Fragment key={key}>{part}</Fragment>;
|
||||
});
|
||||
}
|
||||
|
||||
interface Block {
|
||||
kind: "p" | "ul" | "ol" | "h" | "code";
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
function parse(text: string): Block[] {
|
||||
const blocks: Block[] = [];
|
||||
const lines = text.replace(/\r\n/g, "\n").split("\n");
|
||||
let current: Block | null = null;
|
||||
const flush = () => {
|
||||
if (current) blocks.push(current);
|
||||
current = null;
|
||||
};
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (line.trimStart().startsWith("```")) {
|
||||
flush();
|
||||
const code: string[] = [];
|
||||
for (i++; i < lines.length && !lines[i].trimStart().startsWith("```"); i++) code.push(lines[i]);
|
||||
blocks.push({ kind: "code", lines: code });
|
||||
continue;
|
||||
}
|
||||
if (line.trim() === "") {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
const heading = /^#{1,3}\s+(.*)$/.exec(line);
|
||||
if (heading) {
|
||||
flush();
|
||||
blocks.push({ kind: "h", lines: [heading[1]] });
|
||||
continue;
|
||||
}
|
||||
const bullet = /^\s*[-*]\s+(.*)$/.exec(line);
|
||||
const numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line);
|
||||
const kind = bullet ? "ul" : numbered ? "ol" : "p";
|
||||
const content = bullet ? bullet[1] : numbered ? numbered[1] : line;
|
||||
if (current && (current as Block).kind === kind) (current as Block).lines.push(content);
|
||||
else {
|
||||
flush();
|
||||
current = { kind, lines: [content] };
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return blocks;
|
||||
}
|
||||
|
||||
export default function RunbookText({ text }: { text: string }) {
|
||||
const blocks = parse(text);
|
||||
return (
|
||||
<div className="runbook-text">
|
||||
{blocks.map((b, i) => {
|
||||
const key = `b${i}`;
|
||||
if (b.kind === "code") {
|
||||
return (
|
||||
<pre key={key} className="border rounded p-2 mb-2">
|
||||
{b.lines.join("\n")}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
if (b.kind === "h") return <h5 key={key}>{inline(b.lines[0], key)}</h5>;
|
||||
if (b.kind === "ul" || b.kind === "ol") {
|
||||
const Tag = b.kind;
|
||||
return (
|
||||
<Tag key={key} className="mb-2">
|
||||
{b.lines.map((l, j) => (
|
||||
<li key={j}>{inline(l, `${key}-${j}`)}</li>
|
||||
))}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p key={key} className="mb-2">
|
||||
{b.lines.map((l, j) => (
|
||||
<Fragment key={j}>
|
||||
{j > 0 && <br />}
|
||||
{inline(l, `${key}-${j}`)}
|
||||
</Fragment>
|
||||
))}
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { api, type RunbookSummary } from "../api/client";
|
||||
|
||||
// The list of runbook titles, by what they are about — shared by every page that shows a "runbook" button, fetched once, and fetched
|
||||
// again whenever one is added, changed or removed (RUNBOOKS_CHANGED).
|
||||
export const RUNBOOKS_CHANGED = "runbooks-changed";
|
||||
|
||||
let items: RunbookSummary[] | null = null;
|
||||
let loading = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function load(force = false): void {
|
||||
if (loading || (items !== null && !force)) return;
|
||||
loading = true;
|
||||
api.runbooks
|
||||
.summary()
|
||||
.then((res) => {
|
||||
items = res.runbooks;
|
||||
listeners.forEach((l) => l());
|
||||
})
|
||||
.catch(() => {
|
||||
// Only a convenience on top of the pages: without it they simply show no runbook buttons.
|
||||
})
|
||||
.finally(() => {
|
||||
loading = false;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") window.addEventListener(RUNBOOKS_CHANGED, () => load(true));
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Every runbook's title and what it is for; null until loaded. */
|
||||
export function useRunbookSummary(): RunbookSummary[] | null {
|
||||
useEffect(() => load(), []);
|
||||
return useSyncExternalStore(subscribe, () => items);
|
||||
}
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
IconListCheck,
|
||||
IconRefresh,
|
||||
IconDownload,
|
||||
IconActivityHeartbeat,
|
||||
IconBox,
|
||||
IconShieldCheck,
|
||||
IconActivityHeartbeat,
|
||||
IconCopyCheck,
|
||||
IconTicket,
|
||||
IconPlug,
|
||||
IconExternalLink,
|
||||
@@ -70,7 +72,9 @@ export const NAV: NavEntry[] = [
|
||||
{ to: "/pbs", label: "Proxmox Backup", icon: <IconShieldCheck size={20} /> },
|
||||
{ to: "/docker", label: "Docker", icon: <IconBrandDocker size={20} /> },
|
||||
{ to: "/tailscale", label: "Tailscale", icon: <IconAffiliate size={20} /> },
|
||||
{ to: "/backups", label: "Backup coverage", icon: <IconCopyCheck size={20} /> },
|
||||
{ to: "/map", label: "Map", icon: <IconSitemap size={20} /> },
|
||||
{ to: "/inventory", label: "Inventory", icon: <IconBox size={20} /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ErrorNotice } from "../components/Notice";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import SilenceButton from "../components/SilenceButton";
|
||||
import RunPlaybookButton from "../components/RunPlaybookButton";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
|
||||
const SEVERITY: Record<AlertSeverity, { label: string; badge: string; rank: number }> = {
|
||||
critical: { label: "Critical", badge: "bg-red-lt text-red", rank: 0 },
|
||||
@@ -243,6 +244,11 @@ export default function Alerts({ user }: { user: CurrentUser }) {
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
{a.target && (
|
||||
<div>
|
||||
<RunbookEntry targetType={a.target.type} targetId={a.target.id} targetName={a.target.name} canEdit={canSilence} forCategory={a.category} />
|
||||
</div>
|
||||
)}
|
||||
{a.affects && a.affects.length > 0 && (
|
||||
<div className="text-secondary small">
|
||||
Also takes down {a.affects.length} {a.affects.length === 1 ? "server" : "servers"}: {a.affects.join(", ")}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus } from "../api/client";
|
||||
import Pagination from "../components/Pagination";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { usePagination } from "../hooks/usePagination";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { readableError } from "../utils/errors";
|
||||
|
||||
interface Row extends CoverageGuest {
|
||||
/** Worst first, so a default sort puts what needs attention at the top. */
|
||||
rank: number;
|
||||
}
|
||||
|
||||
const RANK: Record<CoverageStatus, number> = { failed: 0, none: 1, stale: 2, unknown: 3, ok: 4 };
|
||||
|
||||
const STATUS: Record<CoverageStatus, { label: string; badge: string; hint: string }> = {
|
||||
ok: { label: "Recent backup", badge: "bg-green-lt text-green", hint: "Backed up within the limit, and nothing failed." },
|
||||
stale: { label: "Stale", badge: "bg-yellow-lt text-yellow", hint: "Its newest backup is older than the limit." },
|
||||
failed: { label: "Failed", badge: "bg-red-lt text-red", hint: "The latest backup didn't succeed, or the newest snapshot failed verification." },
|
||||
none: { label: "No backup", badge: "bg-red-lt text-red", hint: "No backup found, and no backup job covers it." },
|
||||
unknown: { label: "Unknown", badge: "bg-secondary-lt text-secondary", hint: "A backup job covers it, but nothing here says when it last ran — typical when backups go somewhere other than a Backup Server." },
|
||||
};
|
||||
|
||||
const STALE_CHOICES = [1, 2, 3, 7, 14];
|
||||
|
||||
/**
|
||||
* What is and isn't backed up: every Proxmox guest, whether a backup job covers it, when it was last backed up (from Proxmox Backup Server
|
||||
* snapshots and Proxmox's own backup tasks), and whether that went well — one page instead of an alert per gap.
|
||||
*/
|
||||
export default function Backups() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const staleParam = Number(params.get("stale"));
|
||||
const staleDays = STALE_CHOICES.includes(staleParam) ? staleParam : 2;
|
||||
const statusParam = params.get("status");
|
||||
const status: CoverageStatus | "attention" | "" = statusParam === "attention" || (statusParam && statusParam in RANK) ? (statusParam as CoverageStatus | "attention") : "";
|
||||
|
||||
const [report, setReport] = useState<BackupCoverage | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
|
||||
function load(refresh = false) {
|
||||
setChecking(true);
|
||||
api.backups
|
||||
.coverage(staleDays, refresh)
|
||||
.then((r) => {
|
||||
setReport(r);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)))
|
||||
.finally(() => setChecking(false));
|
||||
}
|
||||
useEffect(() => load(), [staleDays]);
|
||||
|
||||
function setParam(key: string, value: string | null) {
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (value) next.set(key, value);
|
||||
else next.delete(key);
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
const rows: Row[] = (report?.guests ?? []).map((g) => ({ ...g, rank: RANK[g.status] }));
|
||||
const shown = rows.filter((r) => (status === "" ? true : status === "attention" ? r.status === "failed" || r.status === "none" || r.status === "stale" : r.status === status));
|
||||
const tableSearch = useTableSearch(shown);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "rank", "asc", { url: true });
|
||||
const page = usePagination(sorted);
|
||||
const c = report?.counts;
|
||||
const trouble = (c?.failed ?? 0) + (c?.none ?? 0) + (c?.stale ?? 0);
|
||||
const badSources = (report?.sources ?? []).filter((s) => !s.ok);
|
||||
|
||||
function exportCsv() {
|
||||
if (!sorted) return;
|
||||
downloadCsv(
|
||||
"backup-coverage.csv",
|
||||
["Guest", "Type", "ID", "Node", "Cluster", "In a backup job", "Last backup", "Source", "Status", "Problem"],
|
||||
sorted.map((r) => [r.name, r.type === "qemu" ? "VM" : "Container", r.vmid, r.node, r.integrationName, r.inJob ? "yes" : "no", r.lastBackupAt ?? "", r.lastSource === "pbs" ? "Backup Server" : r.lastSource === "task" ? "Proxmox task" : "", STATUS[r.status].label, r.failure ?? ""]),
|
||||
);
|
||||
}
|
||||
|
||||
const cards: { label: string; value: string | number; color: string; note?: string }[] = [
|
||||
{ label: "Guests", value: report ? (c?.total ?? 0) : "…", color: "" },
|
||||
{ label: "Recent backup", value: report ? (c?.ok ?? 0) : "…", color: "text-green" },
|
||||
{ label: "Failed", value: report ? (c?.failed ?? 0) : "…", color: (c?.failed ?? 0) > 0 ? "text-red" : "" },
|
||||
{ label: "No backup", value: report ? (c?.none ?? 0) : "…", color: (c?.none ?? 0) > 0 ? "text-red" : "" },
|
||||
{ label: "Stale", value: report ? (c?.stale ?? 0) : "…", color: (c?.stale ?? 0) > 0 ? "text-yellow" : "", note: `older than ${staleDays} ${staleDays === 1 ? "day" : "days"}` },
|
||||
{ label: "Unknown", value: report ? (c?.unknown ?? 0) : "…", color: "text-secondary", note: (c?.unknown ?? 0) > 0 ? "in a job, last run not visible" : undefined },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<h2 className="page-title mb-0">Backup coverage</h2>
|
||||
<button className="btn btn-outline-secondary ms-auto" onClick={() => load(true)} disabled={checking}>
|
||||
{checking ? "Checking…" : "Check now"}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-secondary">
|
||||
Every Proxmox guest: is a backup job covering it, when was it last backed up, and did that go well. {report && trouble > 0 ? `${trouble} need a look.` : ""}
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
{badSources.length > 0 && (
|
||||
<div className="alert alert-warning">
|
||||
Couldn't read everything — what is missing below isn't necessarily wrong:{" "}
|
||||
{badSources.map((s) => `${s.kind === "pbs" ? "Backup Server" : "Proxmox"} “${s.name}” (${s.error})`).join("; ")}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="row row-cards mb-3">
|
||||
{cards.map((card) => (
|
||||
<div className="col-6 col-lg-2" key={card.label}>
|
||||
<div className="card card-sm">
|
||||
<div className="card-body">
|
||||
<div className={`h2 mb-0 ${card.color}`}>{card.value}</div>
|
||||
<div className="text-secondary">{card.label}</div>
|
||||
{card.note && <div className="text-secondary small">{card.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<TableToolbar
|
||||
search={tableSearch.query}
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search guests…"
|
||||
filters={
|
||||
<>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Show guests that are" value={status} onChange={(e) => setParam("status", e.target.value)}>
|
||||
<option value="">All guests</option>
|
||||
<option value="attention">Needing attention</option>
|
||||
{(Object.keys(RANK) as CoverageStatus[]).map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{STATUS[s].label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Stale after" value={staleDays} onChange={(e) => setParam("stale", e.target.value === "2" ? null : e.target.value)}>
|
||||
{STALE_CHOICES.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
Stale after {d} {d === 1 ? "day" : "days"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</>
|
||||
}
|
||||
shown={sorted?.length}
|
||||
total={rows.length}
|
||||
onExport={exportCsv}
|
||||
exportDisabled={!sorted || sorted.length === 0}
|
||||
/>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<SortableTh<Row> label="Guest" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="In a job" sortKeyName="inJob" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Last backup" sortKeyName="lastBackupAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Status" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report === null && !error && (
|
||||
<tr>
|
||||
<td colSpan={4}>
|
||||
<BlockSkeleton lines={4} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{page.pageItems?.map((r) => (
|
||||
<tr key={`${r.integrationId}:${r.type}:${r.vmid}`}>
|
||||
<td>
|
||||
{r.name}
|
||||
<div className="text-secondary small">
|
||||
{r.type === "qemu" ? "VM" : "Container"} {r.vmid} · {r.node}
|
||||
{report && report.sources.filter((s) => s.kind === "proxmox").length > 1 ? ` · ${r.integrationName}` : ""}
|
||||
</div>
|
||||
{r.server && (
|
||||
<div className="small">
|
||||
is <Link to={`/servers/${r.server.id}`}>{r.server.name}</Link>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td>{r.inJob ? <span className="text-green">yes</span> : <span className="text-red">no</span>}</td>
|
||||
<td>
|
||||
{r.lastBackupAt ? (
|
||||
<>
|
||||
<TimeAgo value={r.lastBackupAt} />
|
||||
<div className="text-secondary small">{r.lastSource === "pbs" ? "Backup Server" : "Proxmox task"}</div>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-secondary">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`badge ${STATUS[r.status].badge}`} title={STATUS[r.status].hint}>
|
||||
{STATUS[r.status].label}
|
||||
</span>
|
||||
{r.failure && <div className="text-secondary small">{r.failure}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{report !== null && sorted?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
{rows.length === 0 ? (
|
||||
<>
|
||||
No Proxmox guests to show. Connect a Proxmox integration under <Link to="/integrations">Integrations</Link>.
|
||||
</>
|
||||
) : (
|
||||
"Nothing matches that."
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
|
||||
<div className="card-footer text-secondary small">
|
||||
“Last backup” is the newest snapshot of the guest on a Proxmox Backup Server, or the last successful Proxmox backup task that names it. A task from an “all guests” job doesn't
|
||||
name its guests, so a guest backed up to something other than a Backup Server reads “Unknown” rather than being guessed at. The result is kept for a minute; “Check now” asks again.
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { confirmDialog } from "../utils/dialogs";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { toast } from "../utils/toast";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
|
||||
const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
tailscale: "Tailscale",
|
||||
@@ -74,6 +75,7 @@ function typeBadgeStyle(colors: Record<string, string>, type: IntegrationType):
|
||||
|
||||
export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
const isAdmin = user.role === "admin";
|
||||
const isOperator = user.role === "admin" || user.role === "operator";
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
|
||||
@@ -257,6 +259,9 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
<UptimeRibbon kind="integrations" id={i.id} name={i.name} />
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-3">
|
||||
<RunbookEntry targetType="integration" targetId={i.id} targetName={i.name} canEdit={isOperator} offerAdd />
|
||||
</div>
|
||||
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
|
||||
<div className="btn-list mt-auto">
|
||||
{i.enabled && (
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import TimeAgo from "../components/TimeAgo";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
import RunsOn from "../components/RunsOn";
|
||||
import RunPlaybook from "../components/RunPlaybook";
|
||||
import RunbookPanel from "../components/RunbookPanel";
|
||||
import UpdatesBadge from "../components/UpdatesBadge";
|
||||
import { agentState, agentVersionWords } from "../utils/agent";
|
||||
import ServerTags from "../components/ServerTags";
|
||||
@@ -808,6 +809,14 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
|
||||
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
|
||||
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Runbooks</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
|
||||
</div>
|
||||
</div>
|
||||
{canEditTasks && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
|
||||
@@ -4,11 +4,13 @@ import { NavLink, Outlet } from "react-router-dom";
|
||||
const SUB_NAV = [
|
||||
{ to: "/settings/notifications", label: "Notifications" },
|
||||
{ to: "/settings/badges", label: "Badges" },
|
||||
{ to: "/settings/sign-in", label: "Sign-in" },
|
||||
{ to: "/settings/display", label: "Display" },
|
||||
{ to: "/settings/tags", label: "Tags" },
|
||||
{ to: "/settings/alert-tickets", label: "Alert tickets" },
|
||||
{ to: "/settings/names", label: "Names" },
|
||||
{ to: "/settings/share", label: "Share links" },
|
||||
{ to: "/settings/api", label: "API and webhooks" },
|
||||
{ to: "/settings/cache", label: "Cache" },
|
||||
{ to: "/settings/logs", label: "Logs" },
|
||||
{ to: "/settings/backup", label: "Backup" },
|
||||
|
||||
+20
-3
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type UserRecord, type UserRole } from "../api/client";
|
||||
import { formatDateTime } from "../utils/date";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
@@ -14,11 +15,16 @@ export default function Users() {
|
||||
const [users, setUsers] = useState<UserRecord[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [savingId, setSavingId] = useState<number | null>(null);
|
||||
// Roles follow sign-in groups (Settings → Sign-in): they are shown, not set here.
|
||||
const [followGroups, setFollowGroups] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.users
|
||||
.list()
|
||||
.then((res) => setUsers(res.users))
|
||||
.then((res) => {
|
||||
setUsers(res.users);
|
||||
setFollowGroups(res.rolesFollowGroups);
|
||||
})
|
||||
.catch((err) => setError(String(err)));
|
||||
}
|
||||
|
||||
@@ -58,6 +64,12 @@ export default function Users() {
|
||||
</button>
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{followGroups && (
|
||||
<div className="alert alert-info">
|
||||
Roles are set from sign-in groups, so they can't be changed here: change a person's group in the identity provider, and their role follows at their next sign-in.{" "}
|
||||
<Link to="/settings/sign-in">Sign-in settings</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<SearchBox value={tableSearch.query} onChange={tableSearch.setQuery} />
|
||||
@@ -69,6 +81,7 @@ export default function Users() {
|
||||
<SortableTh<UserRecord> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<UserRecord> label="Email" sortKeyName="email" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<UserRecord> label="Role" sortKeyName="role" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<th>Groups at last sign-in</th>
|
||||
<SortableTh<UserRecord>
|
||||
label="Last login"
|
||||
sortKeyName="lastLoginAt"
|
||||
@@ -87,7 +100,8 @@ export default function Users() {
|
||||
<select
|
||||
className="form-select form-select-sm"
|
||||
value={u.role}
|
||||
disabled={savingId === u.id}
|
||||
disabled={savingId === u.id || followGroups}
|
||||
title={followGroups ? "Set from sign-in groups" : undefined}
|
||||
onChange={(e) => changeRole(u.id, e.target.value as UserRole)}
|
||||
>
|
||||
{ROLES.map((r) => (
|
||||
@@ -97,12 +111,15 @@ export default function Users() {
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
<td className="text-secondary small">
|
||||
{u.groups === null ? "—" : u.groups.length === 0 ? "none" : u.groups.length <= 3 ? u.groups.join(", ") : `${u.groups.slice(0, 3).join(", ")} and ${u.groups.length - 3} more`}
|
||||
</td>
|
||||
<td>{u.lastLoginAt ? formatDateTime(new Date(u.lastLoginAt)) : "never"}</td>
|
||||
</tr>
|
||||
))}
|
||||
{sorted?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
<td colSpan={5} className="text-secondary text-center">
|
||||
No users yet.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type EventWebhook, type MetricsToken, type WebhookEventName } from "../../api/client";
|
||||
import CopyButton from "../../components/CopyButton";
|
||||
import TimeAgo from "../../components/TimeAgo";
|
||||
import { ErrorNotice } from "../../components/Notice";
|
||||
import { confirmDialog } from "../../utils/dialogs";
|
||||
import { readableError } from "../../utils/errors";
|
||||
import { toast } from "../../utils/toast";
|
||||
|
||||
const EVENT_WORDS: Record<WebhookEventName, string> = {
|
||||
"alert.opened": "A problem begins",
|
||||
"alert.resolved": "A problem ends",
|
||||
"maintenance.started": "Maintenance begins",
|
||||
"maintenance.ended": "Maintenance ends",
|
||||
};
|
||||
|
||||
const hostOf = (address: string) => {
|
||||
try {
|
||||
return new URL(address).host;
|
||||
} catch {
|
||||
return address;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Two ways for other systems to work with this one: a read-only /metrics address for Prometheus (and so Grafana), opened with a token of
|
||||
* its own, and webhooks that are sent a signed JSON message when an alert begins or ends or maintenance starts or finishes.
|
||||
*/
|
||||
export default function ApiSettings() {
|
||||
const [tokens, setTokens] = useState<MetricsToken[] | null>(null);
|
||||
const [hooks, setHooks] = useState<EventWebhook[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [tokenLabel, setTokenLabel] = useState("");
|
||||
const [newSecret, setNewSecret] = useState<{ label: string; secret: string } | null>(null);
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [hookLabel, setHookLabel] = useState("");
|
||||
const [hookUrl, setHookUrl] = useState("");
|
||||
const [hookSecret, setHookSecret] = useState("");
|
||||
const [hookEvents, setHookEvents] = useState<Set<WebhookEventName>>(new Set(["alert.opened", "alert.resolved"]));
|
||||
const [testResults, setTestResults] = useState<Record<number, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.metricsTokens
|
||||
.list()
|
||||
.then((r) => setTokens(r.tokens))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
api.eventWebhooks
|
||||
.list()
|
||||
.then((r) => setHooks(r.webhooks))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
async function makeToken(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.metricsTokens.create(tokenLabel.trim());
|
||||
setNewSecret({ label: res.token.label, secret: res.secret });
|
||||
setTokenLabel("");
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeToken(t: MetricsToken) {
|
||||
if (!(await confirmDialog({ title: "Remove metrics token", message: `Remove "${t.label}"? Whatever scrapes with it stops working at once.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.metricsTokens.remove(t.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function makeHook(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.eventWebhooks.create({ label: hookLabel.trim(), url: hookUrl.trim(), secret: hookSecret || undefined, events: [...hookEvents] });
|
||||
toast.success(`Added ${hookLabel.trim()}.`);
|
||||
setHookLabel("");
|
||||
setHookUrl("");
|
||||
setHookSecret("");
|
||||
setAdding(false);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleHook(h: EventWebhook) {
|
||||
try {
|
||||
await api.eventWebhooks.setEnabled(h.id, !h.enabled);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function testHook(h: EventWebhook) {
|
||||
setTestResults((r) => ({ ...r, [h.id]: "Sending…" }));
|
||||
try {
|
||||
const res = await api.eventWebhooks.test(h.id);
|
||||
setTestResults((r) => ({ ...r, [h.id]: res.ok ? `✓ delivered (${res.result})` : `✕ ${res.result}` }));
|
||||
load();
|
||||
} catch (err) {
|
||||
setTestResults((r) => ({ ...r, [h.id]: `✕ ${readableError(err)}` }));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeHook(h: EventWebhook) {
|
||||
if (!(await confirmDialog({ title: "Remove webhook", message: `Remove "${h.label}"? It stops being sent anything.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.eventWebhooks.remove(h.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 className="mb-3">API and webhooks</h3>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Metrics for Prometheus</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
<code>{origin}/metrics</code> answers in Prometheus's text format — whether each server is up, its load, memory, disks and waiting updates, the alert counts, which integrations work, maintenance, and things about to expire — so a
|
||||
Grafana dashboard or Prometheus alert can use it. It is read-only and opens with a token sent as <code>Authorization: Bearer …</code>; a token in the address isn't accepted. It reads what the app already knows, so a scrape every 15 seconds is cheap.
|
||||
</p>
|
||||
{newSecret && (
|
||||
<div className="border border-success rounded p-3 mb-3">
|
||||
<div className="fw-bold mb-1">Token for {newSecret.label}</div>
|
||||
<div className="text-secondary mb-2">Copy it now — it can't be shown again. If it's lost, remove the token and make a new one.</div>
|
||||
<div className="input-group mb-2">
|
||||
<input className="form-control" readOnly value={newSecret.secret} aria-label="The metrics token" onFocus={(e) => e.currentTarget.select()} />
|
||||
<CopyButton text={newSecret.secret} />
|
||||
</div>
|
||||
<div className="text-secondary small mb-1">In prometheus.yml:</div>
|
||||
<pre className="border rounded p-2 mb-2" style={{ fontSize: "0.8125rem" }}>
|
||||
{`scrape_configs:
|
||||
- job_name: homelab-manager
|
||||
scheme: ${window.location.protocol === "https:" ? "https" : "http"}
|
||||
metrics_path: /metrics
|
||||
authorization:
|
||||
credentials: ${newSecret.secret}
|
||||
static_configs:
|
||||
- targets: ["${window.location.host}"]`}
|
||||
</pre>
|
||||
<button className="btn btn-sm" onClick={() => setNewSecret(null)}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<form className="d-flex flex-wrap gap-2 mb-3" onSubmit={makeToken}>
|
||||
<input className="form-control w-auto" style={{ minWidth: 220 }} required maxLength={60} placeholder="Name, e.g. Prometheus" aria-label="Name for the new token" value={tokenLabel} onChange={(e) => setTokenLabel(e.target.value)} />
|
||||
<button className="btn btn-primary" disabled={busy || tokenLabel.trim() === ""}>
|
||||
Make a token
|
||||
</button>
|
||||
</form>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Made</th>
|
||||
<th>Last used</th>
|
||||
<th className="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tokens?.map((t) => (
|
||||
<tr key={t.id}>
|
||||
<td>
|
||||
{t.label} <span className="text-secondary small">{t.tokenPrefix}…</span>
|
||||
</td>
|
||||
<td className="text-secondary">
|
||||
{t.createdBy ?? "—"}, <TimeAgo value={t.createdAt} fromDb />
|
||||
</td>
|
||||
<td className="text-secondary">{t.lastUsedAt ? <TimeAgo value={t.lastUsedAt} /> : "Never"}</td>
|
||||
<td>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeToken(t)}>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{tokens?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
No tokens yet, so /metrics refuses everyone.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Event webhooks</h3>
|
||||
{!adding && (
|
||||
<div className="card-actions">
|
||||
<button className="btn btn-sm btn-primary" onClick={() => setAdding(true)}>
|
||||
Add a webhook
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
A webhook is sent a JSON message when something happens, for Home Assistant, n8n or a status board. This is separate from the chat-style webhook under Notifications, which carries the sentence a person would read. A problem is announced on the same terms as a
|
||||
notification — one under maintenance isn't until it ends. If you give a secret, each message carries <code>X-HLM-Signature: sha256=…</code>, an HMAC of the body, so the receiver can tell it came from here. A failed delivery is tried once more.
|
||||
</p>
|
||||
{adding && (
|
||||
<form className="border rounded p-3 mb-3" onSubmit={makeHook}>
|
||||
<div className="row g-3">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="wh-label">
|
||||
Name
|
||||
</label>
|
||||
<input id="wh-label" className="form-control" required maxLength={60} placeholder="Home Assistant" value={hookLabel} onChange={(e) => setHookLabel(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-8">
|
||||
<label className="form-label" htmlFor="wh-url">
|
||||
Address
|
||||
</label>
|
||||
<input id="wh-url" type="url" className="form-control" required maxLength={500} placeholder="https://ha.example.lan/api/webhook/…" value={hookUrl} onChange={(e) => setHookUrl(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label" htmlFor="wh-secret">
|
||||
Secret (optional, signs each message)
|
||||
</label>
|
||||
<input id="wh-secret" type="password" className="form-control" maxLength={200} autoComplete="off" value={hookSecret} onChange={(e) => setHookSecret(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<div className="form-label">Send when</div>
|
||||
{(Object.keys(EVENT_WORDS) as WebhookEventName[]).map((ev) => (
|
||||
<label key={ev} className="form-check mb-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
checked={hookEvents.has(ev)}
|
||||
onChange={(e) =>
|
||||
setHookEvents((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (e.target.checked) next.add(ev);
|
||||
else next.delete(ev);
|
||||
return next;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="form-check-label">
|
||||
{EVENT_WORDS[ev]} <code className="small">{ev}</code>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="btn-list mt-3">
|
||||
<button className="btn btn-primary" disabled={busy || hookLabel.trim() === "" || hookUrl.trim() === "" || hookEvents.size === 0}>
|
||||
{busy ? "Adding…" : "Add"}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setAdding(false)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Sends</th>
|
||||
<th>Last</th>
|
||||
<th className="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{hooks?.map((h) => (
|
||||
<tr key={h.id} className={h.enabled ? undefined : "text-secondary"}>
|
||||
<td>
|
||||
{h.label} {!h.enabled && <span className="badge bg-secondary-lt text-secondary">off</span>} {h.hasSecret && <span className="badge bg-green-lt text-green">signed</span>}
|
||||
<div className="text-secondary small">{hostOf(h.url)}</div>
|
||||
</td>
|
||||
<td>
|
||||
<div className="d-flex flex-wrap gap-1">
|
||||
{h.events.map((ev) => (
|
||||
<span key={ev} className="badge bg-blue-lt text-blue">
|
||||
{ev}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td className="small">
|
||||
{testResults[h.id] ?? (h.lastAttemptAt ? (
|
||||
<>
|
||||
<span className={h.lastResult?.startsWith("2") ? "text-green" : "text-red"}>{h.lastResult}</span> <span className="text-secondary"><TimeAgo value={h.lastAttemptAt} /></span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-secondary">not sent yet</span>
|
||||
))}
|
||||
</td>
|
||||
<td>
|
||||
<div className="btn-list flex-nowrap">
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => void testHook(h)}>
|
||||
Test
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => void toggleHook(h)}>
|
||||
{h.enabled ? "Turn off" : "Turn on"}
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeHook(h)}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{hooks?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
No webhooks yet.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type GroupRolePreview, type SignInSettings as SignInSettingsData } from "../../api/client";
|
||||
import { ErrorNotice } from "../../components/Notice";
|
||||
import { PageSkeleton } from "../../components/Skeleton";
|
||||
import { readableError } from "../../utils/errors";
|
||||
import { toast } from "../../utils/toast";
|
||||
|
||||
const DEFAULTS: SignInSettingsData = { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" };
|
||||
|
||||
/** One name per line or separated by commas — whichever is easier to paste in. */
|
||||
const parseNames = (text: string): string[] => [...new Set(text.split(/[\n,]/).map((s) => s.trim()).filter(Boolean))];
|
||||
|
||||
/**
|
||||
* Who is an administrator, an operator or a viewer, decided from the groups the identity provider (Authentik) says a person is in, each
|
||||
* time they sign in — instead of by hand on the Users page. Off by default. "Check" shows what each person would become, from the
|
||||
* groups they had at their last sign-in, before it is switched on.
|
||||
*/
|
||||
export default function SignInSettings() {
|
||||
const [loaded, setLoaded] = useState<SignInSettingsData | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [claim, setClaim] = useState("groups");
|
||||
const [adminText, setAdminText] = useState("");
|
||||
const [operatorText, setOperatorText] = useState("");
|
||||
const [otherwise, setOtherwise] = useState<"viewer" | "keep">("viewer");
|
||||
const [preview, setPreview] = useState<GroupRolePreview | null>(null);
|
||||
const [busy, setBusy] = useState<"check" | "save" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.settings
|
||||
.get()
|
||||
.then((res) => {
|
||||
const s = res.settings.signIn ?? DEFAULTS;
|
||||
setLoaded(s);
|
||||
setEnabled(s.roleFromGroups);
|
||||
setClaim(s.groupsClaim);
|
||||
setAdminText(s.adminGroups.join("\n"));
|
||||
setOperatorText(s.operatorGroups.join("\n"));
|
||||
setOtherwise(s.otherwise);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}, []);
|
||||
|
||||
if (!loaded) return error ? <ErrorNotice error={error} /> : <PageSkeleton />;
|
||||
|
||||
const draft = (): SignInSettingsData => ({ roleFromGroups: enabled, groupsClaim: claim.trim() || "groups", adminGroups: parseNames(adminText), operatorGroups: parseNames(operatorText), otherwise });
|
||||
const dirty = JSON.stringify(draft()) !== JSON.stringify(loaded);
|
||||
|
||||
async function check() {
|
||||
setBusy("check");
|
||||
setError(null);
|
||||
try {
|
||||
const d = draft();
|
||||
setPreview(await api.users.previewGroupRoles({ groupsClaim: d.groupsClaim, adminGroups: d.adminGroups, operatorGroups: d.operatorGroups, otherwise: d.otherwise }));
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setBusy("save");
|
||||
setError(null);
|
||||
try {
|
||||
const d = draft();
|
||||
await api.settings.update({ signIn: d });
|
||||
setLoaded(d);
|
||||
toast.success(d.roleFromGroups ? "Saved. Roles now follow groups at each sign-in." : "Saved. Roles are set by hand on the Users page.");
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
const noAdmin = enabled && preview !== null && preview.adminsAfter === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex align-items-center justify-content-between mb-3">
|
||||
<h3 className="mb-0">Sign-in</h3>
|
||||
<button className="btn btn-primary" onClick={save} disabled={busy !== null || !dirty || noAdmin}>
|
||||
{busy === "save" ? "Saving…" : "Save"}
|
||||
</button>
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Roles from groups</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
By default a new person is a viewer until an administrator changes their role on the Users page. Here you can let the groups the identity provider reports decide it instead:
|
||||
at every sign-in a person is an administrator if they are in an admin group, an operator if they are in an operator group, and otherwise what you choose below.
|
||||
In Authentik the <code>groups</code> claim comes with the <em>profile</em> scope this app already asks for.
|
||||
</p>
|
||||
<label className="form-check mb-3">
|
||||
<input type="checkbox" className="form-check-input" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />
|
||||
<span className="form-check-label">Set roles from groups at each sign-in</span>
|
||||
</label>
|
||||
<div className="row g-3">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-claim">
|
||||
Claim that holds the groups
|
||||
</label>
|
||||
<input id="si-claim" className="form-control" value={claim} onChange={(e) => setClaim(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-admin">
|
||||
Admin groups
|
||||
</label>
|
||||
<textarea id="si-admin" className="form-control" rows={3} placeholder={"homelab-admins"} value={adminText} onChange={(e) => setAdminText(e.target.value)} />
|
||||
<div className="form-hint">One per line, or separated by commas. Case doesn't matter.</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-operator">
|
||||
Operator groups
|
||||
</label>
|
||||
<textarea id="si-operator" className="form-control" rows={3} placeholder={"homelab-ops"} value={operatorText} onChange={(e) => setOperatorText(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label" htmlFor="si-otherwise">
|
||||
Someone in none of those groups
|
||||
</label>
|
||||
<select id="si-otherwise" className="form-select" value={otherwise} onChange={(e) => setOtherwise(e.target.value as "viewer" | "keep")}>
|
||||
<option value="viewer">becomes a viewer</option>
|
||||
<option value="keep">keeps the role they already have</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="alert alert-info mt-3 mb-0">
|
||||
Safeguards: if a sign-in carries no groups at all (a wrong claim name, say) roles are left exactly as they are; the only administrator is never demoted by a group rule;
|
||||
and the very first person to sign in is still the administrator. While this is on, roles can't be set by hand — a role set on the Users page would be undone at the next sign-in.
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer d-flex flex-wrap align-items-center gap-2">
|
||||
<button className="btn btn-outline-secondary" onClick={check} disabled={busy !== null}>
|
||||
{busy === "check" ? "Checking…" : "Check against the groups people had last time"}
|
||||
</button>
|
||||
<span className="text-secondary small">Changes nothing — it shows what each person would be.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{preview && (
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">What these rules would do</h3>
|
||||
</div>
|
||||
{preview.adminsAfter === 0 && (
|
||||
<div className="alert alert-danger m-3 mb-0" role="alert">
|
||||
With these rules nobody would be an administrator. Add an admin group that someone is in before switching this on.
|
||||
</div>
|
||||
)}
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Person</th>
|
||||
<th>Groups at last sign-in</th>
|
||||
<th>Now</th>
|
||||
<th>Would be</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.people.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td>{p.name}</td>
|
||||
<td className="text-secondary">{p.groups === null ? "not known yet — they haven't signed in with groups" : p.groups.length === 0 ? "none" : p.groups.join(", ")}</td>
|
||||
<td>{p.role}</td>
|
||||
<td>
|
||||
{p.wouldBe === null ? (
|
||||
<span className="text-secondary">unchanged until they sign in</span>
|
||||
) : p.wouldBe === p.role ? (
|
||||
<span className="text-secondary">{p.wouldBe}</span>
|
||||
) : (
|
||||
<span className="fw-bold">{p.wouldBe}</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="card-footer text-secondary small">
|
||||
Groups are recorded at every sign-in, whether or not this is on, so people need to have signed in once since this was installed to show up here.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -671,6 +671,23 @@ main:focus {
|
||||
background-image: repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.45) 0 3px, transparent 3px 6px);
|
||||
}
|
||||
|
||||
/* A runbook's text: notes written plainly, so the headings stay small and the code blocks scroll rather than stretch the panel. */
|
||||
.runbook-text h5 {
|
||||
margin: 0.75rem 0 0.25rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.runbook-text pre {
|
||||
overflow-x: auto;
|
||||
white-space: pre;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.runbook-text ul,
|
||||
.runbook-text ol {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
/* Windows made from a recurring schedule get vertical stripes. */
|
||||
.timeline-bar-recurring {
|
||||
background-image: repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.5) 0 2px, transparent 2px 5px);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Asset } from "../api/client";
|
||||
|
||||
// The same arithmetic the server uses for the weekly digest, so a page and the digest never disagree about a warranty.
|
||||
|
||||
export type WarrantyState = "none" | "ok" | "expiring" | "expired";
|
||||
export const WARRANTY_WARN_DAYS = 90;
|
||||
|
||||
/** Whole days from today (UTC) to the end of a warranty; negative once it has ended. Null without one. */
|
||||
export function warrantyDays(warrantyUntil: string | null, now: Date = new Date()): number | null {
|
||||
if (!warrantyUntil) return null;
|
||||
const end = Date.parse(`${warrantyUntil}T00:00:00Z`);
|
||||
if (!Number.isFinite(end)) return null;
|
||||
const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
|
||||
return Math.round((end - today) / 86_400_000);
|
||||
}
|
||||
|
||||
export function warrantyState(warrantyUntil: string | null, now: Date = new Date()): WarrantyState {
|
||||
const days = warrantyDays(warrantyUntil, now);
|
||||
if (days === null) return "none";
|
||||
if (days < 0) return "expired";
|
||||
return days <= WARRANTY_WARN_DAYS ? "expiring" : "ok";
|
||||
}
|
||||
|
||||
export const yearlyKwh = (watts: number) => Math.round((watts / 1000) * 24 * 365 * 100) / 100;
|
||||
|
||||
export function yearlyCost(watts: number | null, pricePerKwh: number | null): number | null {
|
||||
if (watts === null || watts <= 0 || pricePerKwh === null || !(pricePerKwh > 0)) return null;
|
||||
return Math.round(yearlyKwh(watts) * pricePerKwh);
|
||||
}
|
||||
|
||||
export const KIND_LABELS: Record<Asset["kind"], string> = {
|
||||
server: "Server",
|
||||
storage: "Storage",
|
||||
network: "Network",
|
||||
power: "Power",
|
||||
client: "Client",
|
||||
other: "Other",
|
||||
};
|
||||
|
||||
export const KIND_HINTS: Record<Asset["kind"], string> = {
|
||||
server: "a server or mini PC",
|
||||
storage: "a NAS or disk shelf",
|
||||
network: "a switch, router or access point",
|
||||
power: "a UPS or power strip",
|
||||
client: "a PC, laptop or Raspberry Pi",
|
||||
other: "anything else",
|
||||
};
|
||||
|
||||
/** "12 340 kr" or "12 340": a figure in the chosen currency, which may be blank. */
|
||||
export function money(amount: number, currency: string): string {
|
||||
const n = new Intl.NumberFormat("sv-SE", { maximumFractionDigits: 0 }).format(amount);
|
||||
return currency ? `${n} ${currency}` : n;
|
||||
}
|
||||
@@ -2,10 +2,10 @@
|
||||
// search words, the status or tag chosen, the sort — so a view can also be bookmarked or sent to someone, and it needs no storage of its own.
|
||||
|
||||
/** The address parts that narrow or order a table. Anything else in an address (an id to edit, say) is not part of a view. */
|
||||
const VIEW_PARAMS = ["q", "status", "tag", "sort", "dir"] as const;
|
||||
const VIEW_PARAMS = ["q", "status", "kind", "tag", "sort", "dir"] as const;
|
||||
|
||||
/** Only these make a page worth saving as a view: sorting alone does, a lone `dir` doesn't. */
|
||||
const NARROWING = new Set(["q", "status", "tag", "sort"]);
|
||||
const NARROWING = new Set(["q", "status", "kind", "tag", "sort"]);
|
||||
|
||||
/** "/servers?q=elsa" → ["/servers", "?q=elsa"]; a plain page has an empty second part. */
|
||||
export function splitView(path: string): [string, string] {
|
||||
@@ -42,6 +42,8 @@ export function describeView(search: string): string {
|
||||
if (q) parts.push(`“${q}”`);
|
||||
const status = p.get("status");
|
||||
if (status) parts.push(STATUS_WORDS[status] ?? status);
|
||||
const kind = p.get("kind");
|
||||
if (kind) parts.push(kind);
|
||||
for (const t of p.getAll("tag")) parts.push(`tag ${t}`);
|
||||
const sort = p.get("sort");
|
||||
if (sort) parts.push(`by ${sort.replace(/([A-Z])/g, " $1").toLowerCase()} ${p.get("dir") === "desc" ? "↓" : "↑"}`);
|
||||
|
||||
Reference in new issue
Block a user