UniFi: servers plugged into switches; server page in sections; My work; settings search and undo
UniFi: the controller's client list is matched to servers by IP address, so a server is connected through a switch or access point (and port). That is a dependency made by itself, shown on the server page, the Network devices page and the Connections map. IP Addresses can sync the devices' addresses. A server's page is split into Overview, Health, Network, History, Tasks and Settings, by ?view=; alerts link to the section they are about. My work lists what has your name on it: alerts you have, maintenance you started (extend, end with undo) and update runs you started, with a badge. Settings has a search box (and the command palette lists every setting). Removing a dependency, admin link, runbook, hand-made IP address, port opening or restore test is undone from the message instead of asked about first. Two backup tests used a fixed date and failed as days passed; they follow the real clock now. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
396e074108
commit
5e26e77340
45 files changed
+6224
-194
No files matched your search
@@ -7,6 +7,7 @@ import Users from "./pages/Users";
|
||||
import Secrets from "./pages/Secrets";
|
||||
import Ipam from "./pages/Ipam";
|
||||
import NetworkDevices from "./pages/NetworkDevices";
|
||||
import MyWorkPage from "./pages/MyWork";
|
||||
import Ports from "./pages/Ports";
|
||||
import Dns from "./pages/Dns";
|
||||
import Servers from "./pages/Servers";
|
||||
@@ -134,6 +135,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<AppShell user={user}>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard user={user} />} />
|
||||
<Route path="/my-work" element={<MyWorkPage user={user} />} />
|
||||
<Route path="/map" element={<MapPage user={user} />} />
|
||||
<Route path="/servers" element={<Servers user={user} />} />
|
||||
<Route path="/servers/compare" element={<ServerCompare />} />
|
||||
|
||||
+17
-1
@@ -276,7 +276,7 @@ export interface SecretInput {
|
||||
|
||||
export interface MapNode {
|
||||
id: string;
|
||||
kind: "host" | "server" | "dns" | "monitor";
|
||||
kind: "host" | "server" | "dns" | "monitor" | "device";
|
||||
label: string;
|
||||
sub: string | null;
|
||||
status: "ok" | "bad" | "warn" | "unknown";
|
||||
@@ -1156,6 +1156,14 @@ export interface DependenciesResponse {
|
||||
nodes: DependencyNode[];
|
||||
}
|
||||
|
||||
/** What one person has taken on (GET /api/my-work). */
|
||||
export interface MyWork {
|
||||
alerts: { alertId: string; message: string; severity: string; source: string; link: string | null; note: string; role: "handed" | "acked"; ackedBy: string; ackedAt: string; until: string | null; endsSoon: boolean }[];
|
||||
windows: { id: number; targetType: string; targetId: number; targetName: string; targetKind: string; reason: string | null; startedAt: string; endsAt: string; endsSoon: boolean }[];
|
||||
updateRuns: { id: number; serverId: number; serverName: string; templateName: string; status: string; message: string | null; startedAt: string; finishedAt: string | null; running: boolean; updatesBefore: number | null; updatesAfter: number | null; rebootRequired: boolean }[];
|
||||
needsAttention: number;
|
||||
}
|
||||
|
||||
export type NetworkDeviceKind = "gateway" | "switch" | "access_point" | "other";
|
||||
export type NetworkDeviceState = "online" | "offline" | "updating" | "pending" | "other";
|
||||
|
||||
@@ -1183,6 +1191,8 @@ export interface NetworkDevice {
|
||||
dependents: number;
|
||||
needs: number;
|
||||
inMaintenance: boolean;
|
||||
/** The servers plugged into it, as the controller says. */
|
||||
servers: { serverId: number; serverName: string; port: number | null; wired: boolean }[];
|
||||
}
|
||||
|
||||
/** A network (VLAN) or a Wi-Fi name a controller has set up. */
|
||||
@@ -1215,6 +1225,8 @@ export interface UnifiSyncStatus {
|
||||
}
|
||||
|
||||
export interface NetworkOverview {
|
||||
/** Which server is plugged into which device. */
|
||||
serverLinks: { serverId: number; serverName: string; deviceId: number; deviceName: string; port: number | null; wired: boolean }[];
|
||||
integrations: { id: number; name: string; enabled: boolean; status: UnifiSyncStatus | null }[];
|
||||
devices: NetworkDevice[];
|
||||
networks: NetworkSegment[];
|
||||
@@ -2223,6 +2235,9 @@ export const api = {
|
||||
request<{ minSeverity: string | null; categories: AlertCategory[] | null }>(`/api/push/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
test: () => request<{ sent: number; removed: number; failed: number }>("/api/push/test", { method: "POST" }),
|
||||
},
|
||||
myWork: {
|
||||
get: () => request<MyWork>("/api/my-work"),
|
||||
},
|
||||
network: {
|
||||
overview: () => request<NetworkOverview>("/api/network"),
|
||||
sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }),
|
||||
@@ -2360,6 +2375,7 @@ export const api = {
|
||||
syncTailscale: () => request<IpamSyncResult>("/api/ipam/sync-tailscale", { method: "POST" }),
|
||||
syncProxmox: () => request<IpamSyncResult>("/api/ipam/sync-proxmox", { method: "POST" }),
|
||||
syncPhpIpam: () => request<IpamSyncResult>("/api/ipam/sync-phpipam", { method: "POST" }),
|
||||
syncUnifi: () => request<IpamSyncResult>("/api/ipam/sync-unifi", { method: "POST" }),
|
||||
},
|
||||
generator: {
|
||||
themes: () => request<{ themes: NameTheme[]; builtinIds: string[] }>("/api/generator/themes"),
|
||||
|
||||
@@ -22,6 +22,7 @@ import { SHOW_SHORTCUTS_EVENT, shortcutHintFor } from "../layout/shortcuts";
|
||||
import { DENSITIES, type Density } from "../utils/density";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
import { SETTINGS_INDEX } from "../utils/settingsIndex";
|
||||
import { SHOW_SETUP_EVENT } from "./SetupGuide";
|
||||
|
||||
const SECRET_TYPE_LABELS: Record<SecretType, string> = {
|
||||
@@ -323,6 +324,10 @@ export default function CommandPalette({
|
||||
}
|
||||
items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" });
|
||||
if (user.role === "admin") {
|
||||
// Each setting, so "quiet hours" or "flapping" finds the place it is set.
|
||||
for (const [i, s] of SETTINGS_INDEX.entries()) {
|
||||
items.push({ key: `setting-${i}`, category: "Settings", title: s.title, subtitle: s.where, path: s.to, keywords: `settings ${s.words}` });
|
||||
}
|
||||
items.push({
|
||||
key: "act-setup",
|
||||
category: "Actions",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type NetworkOverview } from "../api/client";
|
||||
|
||||
/**
|
||||
* What a server is plugged into, as a UniFi controller says (matched by the server's IP address): the switch and port, or the access point it is on over Wi-Fi.
|
||||
* Says nothing when there is no UniFi controller; says so, plainly, when there is one and the server is not on its list.
|
||||
*/
|
||||
export default function ConnectedThrough({ serverId }: { serverId: number }) {
|
||||
const [data, setData] = useState<NetworkOverview | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api.network
|
||||
.overview()
|
||||
.then((res) => alive && setData(res))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!data || data.integrations.length === 0) return null;
|
||||
const mine = data.serverLinks.filter((l) => l.serverId === serverId);
|
||||
const device = (id: number) => data.devices.find((d) => d.id === id);
|
||||
|
||||
return (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Connected through</h3>
|
||||
<div className="card-actions">
|
||||
<Link to="/network/devices" className="small">
|
||||
Network devices
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{mine.length === 0 ? (
|
||||
<div className="text-secondary">
|
||||
The UniFi controller does not list anything with this server’s IP address as connected, so it is not known which switch or access point it is on. (A server is matched by an address it reports; one that is
|
||||
off, or on a network the controller does not manage, will not be.)
|
||||
</div>
|
||||
) : (
|
||||
<ul className="list-unstyled mb-0">
|
||||
{mine.map((l) => {
|
||||
const d = device(l.deviceId);
|
||||
return (
|
||||
<li key={`${l.deviceId}-${l.port ?? "x"}`} className="mb-1">
|
||||
<Link to="/network/devices">{l.deviceName}</Link>
|
||||
<span className="text-secondary">
|
||||
{" "}
|
||||
— {l.port !== null ? `port ${l.port}` : l.wired ? "wired" : "Wi-Fi"}
|
||||
{d ? ` · ${d.kind.replace("_", " ")}${d.model ? `, ${d.model}` : ""}` : ""}
|
||||
</span>
|
||||
{d && d.state !== "online" && <span className="badge bg-red-lt text-red ms-2">{d.state === "offline" ? "offline" : d.state}</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{mine.length > 0 && <div className="text-secondary small mt-2">If it goes down, this server’s own offline alert is folded under the device’s.</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
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";
|
||||
@@ -85,14 +85,16 @@ export default function RunbookPanel({
|
||||
}
|
||||
|
||||
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);
|
||||
const changed = () => {
|
||||
load();
|
||||
window.dispatchEvent(new Event(RUNBOOKS_CHANGED));
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
};
|
||||
await removeWithUndo({
|
||||
remove: () => api.runbooks.remove(n.id),
|
||||
restore: () => api.runbooks.create({ targetType: n.targetType, targetId: n.targetId, title: n.title, body: n.body, category: n.category }),
|
||||
message: `Removed the runbook "${n.title}".`,
|
||||
reload: changed,
|
||||
});
|
||||
}
|
||||
|
||||
if (failed) return <div className="text-secondary">Couldn't load the runbooks.</div>;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { api, type MyWork } from "../api/client";
|
||||
|
||||
/**
|
||||
* What the signed-in person has taken on, shared by everything that shows it (the menu badge, the dashboard strip, the My work page), so one request every
|
||||
* couple of minutes serves them all. Asked again at once when something that changes it is done (an acknowledgement, a maintenance window).
|
||||
*/
|
||||
let current: MyWork | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
let inFlight = false;
|
||||
|
||||
const POLL_MS = 120_000;
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
if (inFlight) return;
|
||||
inFlight = true;
|
||||
try {
|
||||
current = await api.myWork.get();
|
||||
for (const l of listeners) l();
|
||||
} catch {
|
||||
// keep what there was: a failed look is not "nothing to do"
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Looks again now — after something was acknowledged, handed over, extended or ended. */
|
||||
export function refreshMyWork(): void {
|
||||
if (listeners.size > 0) void refresh();
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("maintenance-changed", refreshMyWork);
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
if (listeners.size === 1) {
|
||||
void refresh();
|
||||
timer = setInterval(() => void refresh(), POLL_MS);
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0 && timer) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The current "My work", or null until it has been read (and always null when `enabled` is false: viewers have no work to follow). */
|
||||
export function useMyWork(enabled = true): { work: MyWork | null; reload: () => void } {
|
||||
const work = useSyncExternalStore(
|
||||
(listener) => (enabled ? subscribe(listener) : () => {}),
|
||||
() => (enabled ? current : null),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (enabled) refreshMyWork();
|
||||
}, [enabled]);
|
||||
return { work, reload: refreshMyWork };
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { DENSITIES, getDensity, setDensity, type Density } from "../utils/densit
|
||||
import CommandPalette from "../components/CommandPalette";
|
||||
import { isLightColor, useEnvironment } from "../utils/environment";
|
||||
import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport";
|
||||
import { useMyWork } from "../hooks/useMyWork";
|
||||
import { useStackedTables } from "../hooks/useStackedTables";
|
||||
import { useShortcuts } from "../hooks/useShortcuts";
|
||||
import { useFormLabels } from "../hooks/useFormLabels";
|
||||
@@ -87,6 +88,8 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
|
||||
const firstRoute = useRef(true);
|
||||
const breadcrumbTail = useBreadcrumbTailValue();
|
||||
const { report } = useAlertsReport();
|
||||
// Viewers have nothing to follow, so nothing is asked for them.
|
||||
const { work: myWork } = useMyWork(user.role === "admin" || user.role === "operator");
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -186,6 +189,13 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
|
||||
title: `${alerts.count} active alert${alerts.count === 1 ? "" : "s"}`,
|
||||
};
|
||||
}
|
||||
if (myWork && myWork.needsAttention > 0) {
|
||||
badges["/my-work"] = {
|
||||
text: String(myWork.needsAttention),
|
||||
className: "bg-blue text-blue-fg",
|
||||
title: `${myWork.needsAttention} ${myWork.needsAttention === 1 ? "thing" : "things"} of yours want a look: handed to you, about to run out, or still going`,
|
||||
};
|
||||
}
|
||||
if (maintenance.length > 0) {
|
||||
badges["/maintenance"] = {
|
||||
text: String(maintenance.length),
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
IconWorld,
|
||||
IconNetwork,
|
||||
IconRouter,
|
||||
IconChecklist,
|
||||
IconKey,
|
||||
IconPlugConnected,
|
||||
IconBrandDocker,
|
||||
@@ -63,6 +64,7 @@ export const isGroup = (entry: NavEntry): entry is NavGroup => "items" in entry;
|
||||
|
||||
export const NAV: NavEntry[] = [
|
||||
{ to: "/", label: "Dashboard", icon: <IconLayoutDashboard size={20} /> },
|
||||
{ to: "/my-work", label: "My work", icon: <IconChecklist size={20} />, minRole: "operator" },
|
||||
{
|
||||
id: "infrastructure",
|
||||
label: "Infrastructure",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type AdminLink, type CurrentUser, type PortEntry, type ServerRecord } from "../api/client";
|
||||
@@ -5,7 +6,6 @@ import { useSortable } from "../hooks/useSortable";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import { EmptyRow, LoadingRow } from "../components/EmptyState";
|
||||
@@ -137,14 +137,14 @@ export default function AdminLinks({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
async function remove(link: AdminLink) {
|
||||
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link from ${link.serverName}?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
setError(null);
|
||||
try {
|
||||
await api.servers.removeLink(link.serverId, link.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.servers.removeLink(link.serverId, link.id),
|
||||
restore: () => api.servers.addLink(link.serverId, { label: link.label, url: link.url }),
|
||||
message: `Removed the "${link.label}" link from ${link.serverName}.`,
|
||||
reload: load,
|
||||
onError: setError,
|
||||
});
|
||||
}
|
||||
|
||||
const showForm = adding || editing;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus, type CurrentUser, type RestoreInfo, type RestoreResult, type RestoreStatus, type RestoreTestEntry } from "../api/client";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { toast } from "../utils/toast";
|
||||
import Pagination from "../components/Pagination";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
@@ -96,14 +96,16 @@ export default function Backups({ user }: { user?: CurrentUser }) {
|
||||
}
|
||||
|
||||
async function removeTest(t: RestoreTestEntry) {
|
||||
if (!(await confirmDialog({ title: "Remove a restore test", message: `Remove the test of "${t.label}" from ${t.testedAt}?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.backups.removeRestoreTest(t.id);
|
||||
loadTests();
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.backups.removeRestoreTest(t.id),
|
||||
restore: () => api.backups.recordRestoreTest({ key: t.subjectKey, label: t.label, testedAt: t.testedAt, result: t.result, note: t.note ?? undefined }),
|
||||
message: `Removed the test of "${t.label}" from ${t.testedAt}.`,
|
||||
reload: () => {
|
||||
loadTests();
|
||||
load();
|
||||
},
|
||||
onError: setError,
|
||||
});
|
||||
}
|
||||
|
||||
const [params, setParams] = useSearchParams();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMyWork } from "../hooks/useMyWork";
|
||||
import { isValidElement, useEffect, useState, type ReactNode } from "react";
|
||||
import { IconArrowLeft, IconArrowRight, IconEye, IconEyeOff } from "@tabler/icons-react";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
@@ -324,6 +325,22 @@ function formatBytes(bytes: number | null): string {
|
||||
return `${value.toFixed(1)} ${units[unit]}`;
|
||||
}
|
||||
|
||||
/** One line above the cards for those who follow things: how many of theirs want a look, and where to see them. Says nothing when none do. */
|
||||
function MyWorkStrip() {
|
||||
const { work } = useMyWork();
|
||||
if (!work || work.needsAttention === 0) return null;
|
||||
return (
|
||||
<div className="alert alert-info d-flex flex-wrap align-items-center gap-2 py-2" role="status">
|
||||
<span>
|
||||
<strong>{work.needsAttention}</strong> {work.needsAttention === 1 ? "thing" : "things"} of yours {work.needsAttention === 1 ? "wants" : "want"} a look — alerts handed to you or about to run out, maintenance about to end, update runs still going.
|
||||
</span>
|
||||
<Link to="/my-work" className="btn btn-sm btn-primary ms-auto">
|
||||
My work
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Dashboard({ user }: { user: CurrentUser }) {
|
||||
const { editing } = useDashboardLayout();
|
||||
const problemsFirst = useProblemsFirst();
|
||||
@@ -687,6 +704,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) {
|
||||
Welcome back, {user.name ?? user.email ?? user.sub}.
|
||||
</p>
|
||||
<StatusStrip />
|
||||
{(user.role === "admin" || user.role === "operator") && <MyWorkStrip />}
|
||||
<WhatChanged role={user.role} />
|
||||
{isAdmin && integrations !== null && dnsStats !== null && serverSummary !== null && secrets !== null && notifyConfigured !== null && (
|
||||
<SetupGuide steps={setupSteps} />
|
||||
|
||||
+45
-11
@@ -1,3 +1,5 @@
|
||||
import { toast } from "../utils/toast";
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client";
|
||||
@@ -33,7 +35,7 @@ export default function Ipam({ user }: { user: CurrentUser }) {
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [form, setForm] = useState<IpamInput>(emptyForm);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | null>(null);
|
||||
const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | "unifi" | null>(null);
|
||||
const [syncResult, setSyncResult] = useState<string | null>(null);
|
||||
const selection = useSelection<number>();
|
||||
const [bulkDeleting, setBulkDeleting] = useState(false);
|
||||
@@ -146,47 +148,76 @@ export default function Ipam({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
}
|
||||
|
||||
/** What is needed to make an entry again; one that a sync made would come back as a hand-made one, so those are still asked about. */
|
||||
const asInput = (e: IpamEntry): IpamInput => ({ ipAddress: e.ipAddress, label: e.label ?? undefined, vendor: e.vendor ?? undefined, location: e.location ?? undefined, notes: e.notes ?? undefined });
|
||||
|
||||
async function remove(entry: IpamEntry) {
|
||||
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"?`, confirmLabel: "Delete", danger: true }))) return;
|
||||
setError(null);
|
||||
try {
|
||||
await api.ipam.remove(entry.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
if (entry.source) {
|
||||
if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"? A sync can bring it back.`, confirmLabel: "Delete", danger: true }))) return;
|
||||
try {
|
||||
await api.ipam.remove(entry.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
return;
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.ipam.remove(entry.id),
|
||||
restore: () => api.ipam.create(asInput(entry)),
|
||||
message: `Deleted ${entry.ipAddress}.`,
|
||||
reload: load,
|
||||
onError: setError,
|
||||
});
|
||||
}
|
||||
|
||||
async function bulkDelete() {
|
||||
const ids = Array.from(selection.selected);
|
||||
if (ids.length === 0) return;
|
||||
if (!(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}?`, confirmLabel: "Delete", danger: true }))) return;
|
||||
const picked = (entries ?? []).filter((e) => ids.includes(e.id));
|
||||
const plain = picked.length === ids.length && picked.every((e) => !e.source);
|
||||
if (!plain && !(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}? Those a sync made can be brought back by it.`, confirmLabel: "Delete", danger: true }))) return;
|
||||
setError(null);
|
||||
setBulkDeleting(true);
|
||||
try {
|
||||
const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id)));
|
||||
const failed = results.filter((r) => r.status === "rejected").length;
|
||||
if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`);
|
||||
const gone = picked.filter((_, i) => results[ids.indexOf(picked[i].id)]?.status === "fulfilled");
|
||||
selection.clear();
|
||||
load();
|
||||
if (plain && gone.length > 0) {
|
||||
toast.success(`Deleted ${gone.length} IP address${gone.length !== 1 ? "es" : ""}.`, {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
const back = await Promise.allSettled(gone.map((e) => api.ipam.create(asInput(e))));
|
||||
const lost = back.filter((r) => r.status === "rejected").length;
|
||||
if (lost > 0) toast.error(`${lost} could not be put back.`);
|
||||
else toast.info("Put back.");
|
||||
load();
|
||||
},
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setBulkDeleting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam", string> = {
|
||||
const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam" | "unifi", string> = {
|
||||
tailscale: "Tailscale",
|
||||
proxmox: "Proxmox",
|
||||
phpipam: "phpIPAM",
|
||||
unifi: "UniFi",
|
||||
};
|
||||
|
||||
async function runSync(source: "tailscale" | "proxmox" | "phpipam") {
|
||||
async function runSync(source: "tailscale" | "proxmox" | "phpipam" | "unifi") {
|
||||
setError(null);
|
||||
setSyncResult(null);
|
||||
setSyncing(source);
|
||||
try {
|
||||
const res =
|
||||
source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : await api.ipam.syncPhpIpam();
|
||||
source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : source === "unifi" ? await api.ipam.syncUnifi() : await api.ipam.syncPhpIpam();
|
||||
const parts = [`${res.added} added`, `${res.updated} updated`];
|
||||
if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`);
|
||||
setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`);
|
||||
@@ -378,6 +409,9 @@ export default function Ipam({ user }: { user: CurrentUser }) {
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("phpipam")} disabled={!!syncing}>
|
||||
{syncing === "phpipam" ? "Syncing…" : "Sync from phpIPAM"}
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => runSync("unifi")} disabled={!!syncing}>
|
||||
{syncing === "unifi" ? "Syncing…" : "Sync from UniFi"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
+14
-7
@@ -15,7 +15,7 @@ const COL_GAP = 130;
|
||||
|
||||
const STATUS_SYMBOL: Record<MapNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" };
|
||||
const STATUS_WORD: Record<MapNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" };
|
||||
const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor" };
|
||||
const KIND_WORD: Record<MapNode["kind"], string> = { host: "Proxmox host", server: "Server", dns: "DNS name", monitor: "Uptime Kuma monitor", device: "Network device" };
|
||||
|
||||
interface Placed extends MapNode {
|
||||
x: number;
|
||||
@@ -30,15 +30,22 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
|
||||
neighbours.set(e.to, [...(neighbours.get(e.to) ?? []), e.from]);
|
||||
}
|
||||
const byKind = (kinds: MapNode["kind"][]) => data.nodes.filter((n) => kinds.includes(n.kind));
|
||||
const hosts = byKind(["host"]).sort((a, b) => a.label.localeCompare(b.label));
|
||||
// Proxmox hosts and the switches and access points servers are plugged into share the left-hand column.
|
||||
const hosts = byKind(["host", "device"]).sort((a, b) => a.label.localeCompare(b.label));
|
||||
const serverNodes = byKind(["server"]);
|
||||
const rightNodes = byKind(["dns", "monitor"]);
|
||||
|
||||
// Servers grouped under their host, then those with none.
|
||||
const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:"));
|
||||
const hostOf = (s: MapNode) => (neighbours.get(s.id) ?? []).find((id) => id.startsWith("host:")) ?? (neighbours.get(s.id) ?? []).find((id) => id.startsWith("device:"));
|
||||
const servers: MapNode[] = [];
|
||||
for (const h of hosts) servers.push(...serverNodes.filter((s) => hostOf(s) === h.id).sort((a, b) => a.label.localeCompare(b.label)));
|
||||
servers.push(...serverNodes.filter((s) => !hostOf(s)).sort((a, b) => a.label.localeCompare(b.label)));
|
||||
const placedServers = new Set<string>();
|
||||
for (const h of hosts) {
|
||||
for (const s of serverNodes.filter((s) => hostOf(s) === h.id && !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label))) {
|
||||
servers.push(s);
|
||||
placedServers.add(s.id);
|
||||
}
|
||||
}
|
||||
servers.push(...serverNodes.filter((s) => !placedServers.has(s.id)).sort((a, b) => a.label.localeCompare(b.label)));
|
||||
|
||||
const step = NODE_H + GAP_Y;
|
||||
const placed = new Map<string, Placed>();
|
||||
@@ -69,7 +76,7 @@ function layout(data: MapData): { placed: Map<string, Placed>; width: number; he
|
||||
const height = all.length ? Math.max(...all.map((p) => p.y)) + NODE_H : 0;
|
||||
const width = Math.max(...all.map((p) => p.x), 0) + NODE_W;
|
||||
const columns = [
|
||||
...(hasHosts ? [{ x: colX[0], title: "Proxmox hosts" }] : []),
|
||||
...(hasHosts ? [{ x: colX[0], title: byKind(["host"]).length > 0 && byKind(["device"]).length > 0 ? "Proxmox hosts & network devices" : byKind(["device"]).length > 0 ? "Network devices" : "Proxmox hosts" }] : []),
|
||||
...(servers.length > 0 ? [{ x: colX[1], title: "Servers" }] : []),
|
||||
...(hasRight ? [{ x: colX[2], title: "DNS names & monitors" }] : []),
|
||||
];
|
||||
@@ -146,7 +153,7 @@ function ConnectionsMap() {
|
||||
return (
|
||||
<>
|
||||
<p className="text-secondary">
|
||||
How things connect: which Proxmox host a server runs on, which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is
|
||||
How things connect: which Proxmox host a server runs on, which switch or access point it is plugged into (from a UniFi controller), which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is
|
||||
connected to.
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type AlertItem, type CurrentUser, type MyWork } from "../api/client";
|
||||
import AckDrawer from "../components/AckDrawer";
|
||||
import EmptyState from "../components/EmptyState";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { useAlertsReport } from "../hooks/useAlertsReport";
|
||||
import { useMyWork } from "../hooks/useMyWork";
|
||||
import { formatRemaining } from "../utils/duration";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
const SEVERITY: Record<string, string> = { critical: "bg-red-lt text-red", warning: "bg-yellow-lt text-yellow", info: "bg-blue-lt text-blue" };
|
||||
|
||||
type Win = MyWork["windows"][number];
|
||||
|
||||
/**
|
||||
* Everything with your name on it, in one place: the alerts you have taken or been handed, the acknowledgements about to run out, the maintenance you started that
|
||||
* is about to end, and the update runs you are following. What is about to run out is marked, and comes first.
|
||||
*/
|
||||
export default function MyWorkPage({ user }: { user: CurrentUser }) {
|
||||
const { work, reload } = useMyWork();
|
||||
const { report, reload: reloadAlerts } = useAlertsReport();
|
||||
const [acking, setAcking] = useState<AlertItem | null>(null);
|
||||
const [busy, setBusy] = useState<number | null>(null);
|
||||
|
||||
const alertById = new Map((report?.alerts ?? []).map((a) => [a.id, a]));
|
||||
|
||||
function changed() {
|
||||
reload();
|
||||
reloadAlerts();
|
||||
window.dispatchEvent(new Event("maintenance-changed"));
|
||||
}
|
||||
|
||||
/** Minutes from now that a window should last to end `extra` minutes later than it does now (the server restarts the clock from now). */
|
||||
const minutesFor = (w: Win, extra: number) => Math.min(7 * 24 * 60, Math.max(5, Math.ceil((Date.parse(w.endsAt) - Date.now()) / 60_000)) + extra);
|
||||
|
||||
async function extend(w: Win, extra: number, words: string) {
|
||||
setBusy(w.id);
|
||||
try {
|
||||
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, extra), reason: w.reason ?? undefined });
|
||||
toast.success(`${w.targetName}: ${words} more.`);
|
||||
changed();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function end(w: Win) {
|
||||
setBusy(w.id);
|
||||
try {
|
||||
await api.maintenance.end(w.id);
|
||||
toast.success(`Maintenance on ${w.targetName} ended.`, {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.maintenance.start({ targetType: w.targetType as never, targetId: w.targetId, minutes: minutesFor(w, 0), reason: w.reason ?? undefined });
|
||||
toast.info("Put back.");
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
changed();
|
||||
}
|
||||
},
|
||||
});
|
||||
changed();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
const nothing = work !== null && work.alerts.length === 0 && work.windows.length === 0 && work.updateRuns.length === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
||||
<h2 className="page-title mb-0">My work</h2>
|
||||
</div>
|
||||
<div className="text-secondary mb-3">
|
||||
What has your name on it: alerts you acknowledged or were handed, maintenance you started and update runs you started. Whatever is about to run out is marked, and listed first.
|
||||
</div>
|
||||
|
||||
{work === null && <BlockSkeleton lines={4} />}
|
||||
|
||||
{nothing && (
|
||||
<div className="card">
|
||||
<EmptyState title="Nothing on your plate" hint="When you acknowledge an alert, are handed one, put something under maintenance or start an update run, it is listed here until it is done." />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{work && work.alerts.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Alerts you have</h3>
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<tbody>
|
||||
{work.alerts.map((a) => {
|
||||
const full = alertById.get(a.alertId);
|
||||
return (
|
||||
<tr key={a.alertId}>
|
||||
<td className="w-1">
|
||||
<span className={`badge ${SEVERITY[a.severity] ?? ""}`}>{a.severity}</span>
|
||||
</td>
|
||||
<td className="stack-wide">
|
||||
{a.link ? <Link to={a.link}>{a.message}</Link> : a.message}
|
||||
<div className="small text-secondary">
|
||||
{a.role === "handed" ? (a.ackedBy === (user.name ?? user.email ?? user.sub) ? "You took it" : `Handed to you by ${a.ackedBy}`) : "You acknowledged it"}
|
||||
{a.note ? ` — ${a.note}` : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="stack-label text-nowrap" data-label="Lasts">
|
||||
{a.until ? (
|
||||
<span className={a.endsSoon ? "text-yellow" : "text-secondary"} title="When the acknowledgement runs out and the alert counts as nobody's again">
|
||||
{a.endsSoon ? "Runs out " : "Until "}
|
||||
<TimeAgo value={a.until} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-secondary">until the alert is gone</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="stack-wide text-nowrap">
|
||||
<div className="btn-list flex-nowrap">
|
||||
{full && (
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => setAcking(full)}>
|
||||
Change…
|
||||
</button>
|
||||
)}
|
||||
<Link to="/alerts" className="btn btn-sm btn-outline-secondary">
|
||||
Alerts
|
||||
</Link>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{work && work.windows.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Maintenance you started</h3>
|
||||
<div className="card-actions">
|
||||
<Link to="/maintenance" className="small">
|
||||
Maintenance
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<tbody>
|
||||
{work.windows.map((w) => (
|
||||
<tr key={w.id}>
|
||||
<td className="stack-wide">
|
||||
<strong>{w.targetName}</strong> <span className="text-secondary small">{w.targetKind}</span>
|
||||
{w.reason && <div className="small text-secondary">{w.reason}</div>}
|
||||
</td>
|
||||
<td className="stack-label text-nowrap" data-label="Ends">
|
||||
<span className={w.endsSoon ? "text-yellow" : "text-secondary"}>
|
||||
Ends in {formatRemaining(w.endsAt)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="stack-wide text-nowrap">
|
||||
<div className="btn-list flex-nowrap">
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 60, "1 hour")}>
|
||||
+1 h
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" disabled={busy === w.id} onClick={() => void extend(w, 240, "4 hours")}>
|
||||
+4 h
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-outline-danger" disabled={busy === w.id} onClick={() => void end(w)}>
|
||||
End now
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{work && work.updateRuns.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Update runs you started</h3>
|
||||
<div className="card-actions">
|
||||
<Link to="/updates" className="small">
|
||||
Updates
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<tbody>
|
||||
{work.updateRuns.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td className="stack-wide">
|
||||
<Link to={`/servers/${r.serverId}`}>{r.serverName}</Link> <span className="text-secondary small">{r.templateName}</span>
|
||||
{r.message && !r.running && <div className="small text-secondary">{r.message}</div>}
|
||||
</td>
|
||||
<td className="stack-label" data-label="State">
|
||||
{r.running ? (
|
||||
<span className="badge bg-blue-lt text-blue">Running</span>
|
||||
) : r.status === "done" ? (
|
||||
<span className="badge bg-green-lt text-green">Done</span>
|
||||
) : (
|
||||
<span className="badge bg-red-lt text-red">{r.status}</span>
|
||||
)}
|
||||
{!r.running && r.updatesBefore !== null && r.updatesAfter !== null && (
|
||||
<span className="text-secondary small ms-2">
|
||||
{r.updatesBefore} → {r.updatesAfter} waiting{r.rebootRequired ? ", restart needed" : ""}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="stack-label text-nowrap" data-label="Started">
|
||||
<TimeAgo value={r.startedAt} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{acking && <AckDrawer alert={acking} me={user} onClose={() => setAcking(null)} onSaved={changed} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -277,6 +277,18 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
|
||||
{d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""}
|
||||
</div>
|
||||
{d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>}
|
||||
{d.servers.length > 0 && (
|
||||
<div className="small" title="Servers the controller says are plugged into this, matched by their IP address">
|
||||
Plugged in:{" "}
|
||||
{d.servers.map((s, i) => (
|
||||
<span key={`${s.serverId}-${i}`}>
|
||||
{i > 0 && ", "}
|
||||
<Link to={`/servers/${s.serverId}`}>{s.serverName}</Link>
|
||||
{s.port !== null ? ` (port ${s.port})` : s.wired ? "" : " (Wi-Fi)"}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="stack-label" data-label="IP address">
|
||||
{d.ip ? (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { Link } from "react-router-dom";
|
||||
@@ -15,7 +16,6 @@ import { usePagination } from "../hooks/usePagination";
|
||||
import Pagination from "../components/Pagination";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { formatAgo } from "../utils/duration";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { EmptyRow, LoadingRow } from "../components/EmptyState";
|
||||
|
||||
@@ -167,14 +167,15 @@ export default function Ports({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
async function remove(fwd: PortForward) {
|
||||
if (!(await confirmDialog({ title: "Delete port opening", message: `Delete port opening "${fwd.label}"?`, confirmLabel: "Delete", danger: true }))) return;
|
||||
setForwardError(null);
|
||||
try {
|
||||
await api.ports.forwards.remove(fwd.id);
|
||||
loadForwards();
|
||||
} catch (err) {
|
||||
setForwardError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.ports.forwards.remove(fwd.id),
|
||||
restore: () =>
|
||||
api.ports.forwards.create({ label: fwd.label, externalPort: fwd.externalPort, protocol: fwd.protocol, serverId: fwd.serverId, destination: fwd.destination, internalPort: fwd.internalPort, source: fwd.source, comment: fwd.comment }),
|
||||
message: `Deleted the port opening "${fwd.label}".`,
|
||||
reload: loadForwards,
|
||||
onError: setForwardError,
|
||||
});
|
||||
}
|
||||
|
||||
const showForm = adding || editing;
|
||||
|
||||
+161
-109
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { Link, useParams, useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
api,
|
||||
type CurrentUser,
|
||||
@@ -32,9 +32,12 @@ import ServerTaskTable, { SCHEDULE_TYPE_LABELS } from "../components/ServerTaskT
|
||||
import { formatDateTime } from "../utils/date";
|
||||
import { guessAdminUrl, portOptionLabel } from "../utils/adminLinkUrl";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { useBreadcrumbTail } from "../utils/breadcrumb";
|
||||
import { PageSkeleton } from "../components/Skeleton";
|
||||
import ViewTabs from "../components/ViewTabs";
|
||||
import ConnectedThrough from "../components/ConnectedThrough";
|
||||
|
||||
const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map(
|
||||
([value, label]) => ({ value: value as ScheduleType, label }),
|
||||
@@ -101,8 +104,22 @@ const emptyTaskForm = {
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
/** The sections of a server's page, switched by `?view=`: what it is, how it is doing, how it is connected, how it has been, what runs on it, and how it is set up. */
|
||||
const SECTIONS = [
|
||||
{ key: "overview", label: "Overview" },
|
||||
{ key: "health", label: "Health" },
|
||||
{ key: "network", label: "Network" },
|
||||
{ key: "history", label: "History" },
|
||||
{ key: "tasks", label: "Tasks" },
|
||||
{ key: "settings", label: "Settings" },
|
||||
] as const;
|
||||
type SectionKey = (typeof SECTIONS)[number]["key"];
|
||||
|
||||
export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const requested = searchParams.get("view");
|
||||
const view: SectionKey = SECTIONS.some((t) => t.key === requested) ? (requested as SectionKey) : "overview";
|
||||
const serverId = Number(id);
|
||||
const isAdmin = user.role === "admin";
|
||||
const canEditTasks = user.role === "admin" || user.role === "operator";
|
||||
@@ -349,13 +366,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
async function removeAdminLink(link: ServerLink) {
|
||||
if (!(await confirmDialog({ title: "Remove admin link", message: `Remove the "${link.label}" link?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.servers.removeLink(serverId, link.id);
|
||||
await loadDetail();
|
||||
} catch (err) {
|
||||
setAdminLinkError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.servers.removeLink(serverId, link.id),
|
||||
restore: () => api.servers.addLink(serverId, { label: link.label, url: link.url }),
|
||||
message: `Removed the "${link.label}" link.`,
|
||||
reload: () => void loadDetail(),
|
||||
onError: setAdminLinkError,
|
||||
});
|
||||
}
|
||||
|
||||
if (loading) return <PageSkeleton />;
|
||||
@@ -418,6 +435,13 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
onSaved={(tags) => setDetail((d) => (d ? { ...d, server: { ...d.server, tags } } : d))}
|
||||
/>
|
||||
|
||||
<ViewTabs
|
||||
label="Sections of this server's page"
|
||||
tabs={SECTIONS.map((t) => ({ to: t.key === "overview" ? `/servers/${serverId}` : `/servers/${serverId}?view=${t.key}`, label: t.key === "tasks" && tasks && tasks.length > 0 ? `Tasks (${tasks.length})` : t.label, active: view === t.key }))}
|
||||
/>
|
||||
|
||||
{view === "overview" && (
|
||||
<>
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Admin Links</h3>
|
||||
@@ -510,91 +534,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Proxmox link</h3>
|
||||
{!server.proxmoxIntegrationId && (
|
||||
<div className="card-actions">
|
||||
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
|
||||
Not a VM? Hide this
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{server.proxmoxIntegrationId ? (
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
<span className="text-secondary">
|
||||
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
|
||||
{server.proxmoxNode}
|
||||
</span>
|
||||
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
|
||||
Unlink
|
||||
</button>
|
||||
</div>
|
||||
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
|
||||
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
|
||||
) : (
|
||||
<div className="row g-2 align-items-end">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label">Proxmox integration</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={pickedIntegrationId ?? ""}
|
||||
onChange={(e) => {
|
||||
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
|
||||
setPickedGuestKey("");
|
||||
}}
|
||||
>
|
||||
<option value="">Choose…</option>
|
||||
{proxmoxIntegrations?.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-5">
|
||||
<label className="form-label">VM / LXC</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={pickedGuestKey}
|
||||
disabled={!proxmoxGuests}
|
||||
onChange={(e) => setPickedGuestKey(e.target.value)}
|
||||
>
|
||||
<option value="">Choose…</option>
|
||||
{proxmoxGuests?.map((g) => (
|
||||
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
|
||||
{g.name} ({g.type} #{g.vmid} on {g.node})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
|
||||
{linking ? "Linking…" : "Link"}
|
||||
</button>
|
||||
</div>
|
||||
{linkError && (
|
||||
<div className="col-12">
|
||||
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
isAdmin && (
|
||||
<div className="mb-3">
|
||||
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
|
||||
+ Show Proxmox link options
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="row row-cards mb-3">
|
||||
<div className="col-lg-7">
|
||||
<div className="card h-100">
|
||||
@@ -604,7 +543,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
<div className="card-body">
|
||||
{hardware.source === "none" && (
|
||||
<div className="text-secondary">
|
||||
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC above.
|
||||
No hardware data yet. Install the agent on this server, or link it to a Proxmox VM/LXC (under Settings).
|
||||
</div>
|
||||
)}
|
||||
{hardware.error && <div className="alert alert-danger">{hardware.error}</div>}
|
||||
@@ -812,6 +751,19 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "health" && (
|
||||
<>
|
||||
<HostHealthCard
|
||||
health={server.hostHealth}
|
||||
ignored={server.thresholds?.ignoreServices ?? []}
|
||||
@@ -831,17 +783,30 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
/>
|
||||
<AgentDiagnostics notes={detail.diagnostics ?? []} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "network" && (
|
||||
<>
|
||||
<ConnectedThrough serverId={serverId} />
|
||||
<ServerPorts
|
||||
serverId={serverId}
|
||||
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
|
||||
canEdit={canEditTasks}
|
||||
/>
|
||||
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "history" && (
|
||||
<>
|
||||
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
|
||||
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
|
||||
{(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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "tasks" && (
|
||||
<>
|
||||
{canEditTasks && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
@@ -853,12 +818,6 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ServerPorts
|
||||
serverId={serverId}
|
||||
addresses={[...ipAddresses, ...(server.hostname && !ipAddresses.includes(server.hostname) ? [server.hostname] : [])]}
|
||||
canEdit={canEditTasks}
|
||||
/>
|
||||
|
||||
<div className="d-flex align-items-center mb-3">
|
||||
<h3 className="mb-0">Tasks</h3>
|
||||
{canEditTasks && (
|
||||
@@ -956,6 +915,99 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
<ServerTaskTable tasks={tasks} canEditTasks={canEditTasks} onEdit={openEditTask} onDelete={deleteTask} />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "settings" && (
|
||||
<>
|
||||
{isAdmin && (server.proxmoxIntegrationId || !server.hideProxmoxLink) ? (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Proxmox link</h3>
|
||||
{!server.proxmoxIntegrationId && (
|
||||
<div className="card-actions">
|
||||
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(true)}>
|
||||
Not a VM? Hide this
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{server.proxmoxIntegrationId ? (
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
<span className="text-secondary">
|
||||
Linked to {hardware.integrationName ?? "a Proxmox integration"} — {server.proxmoxGuestType}/{server.proxmoxVmid} on{" "}
|
||||
{server.proxmoxNode}
|
||||
</span>
|
||||
<button className="btn btn-outline-danger btn-sm ms-auto" onClick={unlinkProxmox} disabled={linking}>
|
||||
Unlink
|
||||
</button>
|
||||
</div>
|
||||
) : (proxmoxIntegrations?.length ?? 0) === 0 ? (
|
||||
<div className="text-secondary">No enabled Proxmox integrations configured yet.</div>
|
||||
) : (
|
||||
<div className="row g-2 align-items-end">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label">Proxmox integration</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={pickedIntegrationId ?? ""}
|
||||
onChange={(e) => {
|
||||
setPickedIntegrationId(e.target.value ? Number(e.target.value) : null);
|
||||
setPickedGuestKey("");
|
||||
}}
|
||||
>
|
||||
<option value="">Choose…</option>
|
||||
{proxmoxIntegrations?.map((i) => (
|
||||
<option key={i.id} value={i.id}>
|
||||
{i.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-5">
|
||||
<label className="form-label">VM / LXC</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={pickedGuestKey}
|
||||
disabled={!proxmoxGuests}
|
||||
onChange={(e) => setPickedGuestKey(e.target.value)}
|
||||
>
|
||||
<option value="">Choose…</option>
|
||||
{proxmoxGuests?.map((g) => (
|
||||
<option key={`${g.node}/${g.type}/${g.vmid}`} value={`${g.node}/${g.type}/${g.vmid}`}>
|
||||
{g.name} ({g.type} #{g.vmid} on {g.node})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<button className="btn btn-primary w-100" onClick={linkProxmox} disabled={linking || !pickedGuestKey}>
|
||||
{linking ? "Linking…" : "Link"}
|
||||
</button>
|
||||
</div>
|
||||
{linkError && (
|
||||
<div className="col-12">
|
||||
<div className="alert alert-danger mb-0 mt-2">{linkError}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
isAdmin && (
|
||||
<div className="mb-3">
|
||||
<button className="btn btn-link btn-sm p-0" onClick={() => toggleHideProxmoxLink(false)}>
|
||||
+ Show Proxmox link options
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
<ServerThresholds key={JSON.stringify(server.thresholds)} server={server} defaults={detail.thresholdDefaults} disks={(hardware.disks ?? []).map((d) => d.mount)} canEdit={isAdmin} onChanged={() => void loadDetail()} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import { NavLink, Outlet } from "react-router-dom";
|
||||
import { useMemo, useState, type CSSProperties } from "react";
|
||||
import { Link, NavLink, Outlet } from "react-router-dom";
|
||||
import { searchSettings } from "../utils/settingsIndex";
|
||||
|
||||
const SUB_NAV = [
|
||||
{ to: "/settings/notifications", label: "Notifications" },
|
||||
@@ -12,10 +13,44 @@ const SUB_NAV = [
|
||||
{ to: "/settings/data", label: "Data" },
|
||||
];
|
||||
|
||||
/** A box that finds a setting by what it does ("quiet hours", "prometheus", "disk full") and goes to where it is set. */
|
||||
function SettingsSearch() {
|
||||
const [query, setQuery] = useState("");
|
||||
const results = useMemo(() => searchSettings(query), [query]);
|
||||
return (
|
||||
<div className="mb-3 position-relative" style={{ maxWidth: 520 }}>
|
||||
<input
|
||||
type="search"
|
||||
className="form-control"
|
||||
placeholder="Find a setting…"
|
||||
aria-label="Find a setting"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Escape" && setQuery("")}
|
||||
/>
|
||||
{query.trim() !== "" && (
|
||||
<div className="list-group position-absolute w-100 shadow" style={{ zIndex: 20, top: "100%" }} role="listbox" aria-label="Matching settings">
|
||||
{results.length === 0 ? (
|
||||
<div className="list-group-item text-secondary">No setting matches that.</div>
|
||||
) : (
|
||||
results.map((r) => (
|
||||
<Link key={r.title + r.to} to={r.to} className="list-group-item list-group-item-action" role="option" aria-selected={false} onClick={() => setQuery("")}>
|
||||
<div>{r.title}</div>
|
||||
<div className="small text-secondary">{r.where}</div>
|
||||
</Link>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Settings() {
|
||||
return (
|
||||
<>
|
||||
<h2 className="page-title mb-3">Settings</h2>
|
||||
<SettingsSearch />
|
||||
<div className="row">
|
||||
<div className="col-12 col-md-3 col-lg-2 mb-3 mb-md-0">
|
||||
<div className="card">
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Every setting worth looking for, and where it is: used by the search box on the Settings page and by the command palette. It is kept by hand — add a line when a
|
||||
* setting is added — and `words` are the other ways somebody might ask for it (what it does, what it is called elsewhere).
|
||||
*/
|
||||
export interface SettingsEntry {
|
||||
title: string;
|
||||
/** Where it is, in words: "Notifications › What to send". */
|
||||
where: string;
|
||||
/** The address that opens it. */
|
||||
to: string;
|
||||
words: string;
|
||||
}
|
||||
|
||||
const N = "/settings/notifications";
|
||||
|
||||
export const SETTINGS_INDEX: SettingsEntry[] = [
|
||||
// Notifications
|
||||
{ title: "Gotify, ntfy, email and webhook channels", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "gotify ntfy smtp email mail webhook push channel test send where notifications go" },
|
||||
{ title: "Browser and phone push", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "web push browser phone device subscribe pwa notify vapid" },
|
||||
{ title: "Server offline after (minutes)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "offline stopped reporting silent agent threshold limit minutes" },
|
||||
{ title: "Disk usage alert at (percent)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "disk full storage percent threshold space" },
|
||||
{ title: "Warn when a disk will fill within (days)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "disk forecast fill growth trend days" },
|
||||
{ title: "Warn when a server starts listening on a new port", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "new port baseline listening tcp monitoring" },
|
||||
{ title: "Call an alert flapping after (raises in an hour)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "flapping flap noise repeat raised cleared again hold back" },
|
||||
{ title: "Alert when a network device is offline for (minutes)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "unifi network device switch access point gateway offline" },
|
||||
{ title: "Secret, Tailscale key and domain expiry reminders", where: "Notifications › What to send › Secrets, keys and domains", to: `${N}?tab=events`, words: "expiry expire secrets certificate tailscale key domain renew warn days" },
|
||||
{ title: "Backups too old, and restore tests", where: "Notifications › What to send › Backups and updates", to: `${N}?tab=events`, words: "backup stale old restore test guest proxmox updates docker image" },
|
||||
{ title: "Integration, automation and ticket alerts", where: "Notifications › What to send › Integrations and automation", to: `${N}?tab=events`, words: "integration failing semaphore gitea automation failed osticket tickets uptime kuma" },
|
||||
{ title: "DNS change notifications", where: "Notifications › What to send › DNS changes", to: `${N}?tab=events`, words: "dns changes record added removed" },
|
||||
{ title: "Routing rules: which channel gets which alert", where: "Notifications › Who hears what", to: `${N}?tab=routing`, words: "routing rules route channel tags severity kinds mute" },
|
||||
{ title: "Escalation: tell more people if nobody acts", where: "Notifications › Who hears what", to: `${N}?tab=routing`, words: "escalation escalate unacknowledged steps neglected" },
|
||||
{ title: "Time zone and daily reminders", where: "Notifications › When", to: `${N}?tab=when`, words: "timezone time zone daily reminder time of day" },
|
||||
{ title: "Quiet hours", where: "Notifications › When", to: `${N}?tab=when`, words: "quiet hours night hold queue do not disturb" },
|
||||
{ title: "Monthly report", where: "Notifications › When", to: `${N}?tab=when`, words: "monthly report day of month send availability" },
|
||||
{ title: "Weekly digest", where: "Notifications › When", to: `${N}?tab=when`, words: "weekly digest summary email day" },
|
||||
{ title: "Open osTicket tickets from alerts", where: "Notifications › Alert tickets", to: `${N}?view=tickets`, words: "osticket ticket alert open api key which problems" },
|
||||
// Sign-in
|
||||
{ title: "Roles from groups", where: "Sign-in", to: "/settings/sign-in", words: "roles groups authentik oidc admin operator viewer claim map" },
|
||||
{ title: "Profile pictures (Gravatar)", where: "Sign-in", to: "/settings/sign-in", words: "profile picture avatar gravatar photo identity provider" },
|
||||
// Display
|
||||
{ title: "Date and time format", where: "Display › Dates, times and tables", to: "/settings/display", words: "date time format 24 hour 12 hour locale clock" },
|
||||
{ title: "Table pagination (rows per page)", where: "Display › Dates, times and tables", to: "/settings/display", words: "table rows per page pagination size" },
|
||||
{ title: "Badge colours for integrations and DNS providers", where: "Display › Badge colours", to: "/settings/display?view=badges", words: "badge colour color integration dns provider" },
|
||||
// Names, tags, share
|
||||
{ title: "Name lists for the name generator", where: "Names", to: "/settings/names", words: "names generator themes list server names" },
|
||||
{ title: "Tags and tag colours", where: "Tags", to: "/settings/tags", words: "tags colour color label add delete" },
|
||||
{ title: "Share links: wall display, status page, calendar", where: "Share links", to: "/settings/share", words: "share link public wall status page calendar ics token address" },
|
||||
// API and webhooks
|
||||
{ title: "Metrics for Prometheus (tokens)", where: "API and webhooks", to: "/settings/api", words: "prometheus metrics token scrape grafana /metrics" },
|
||||
{ title: "Event webhooks", where: "API and webhooks", to: "/settings/api", words: "webhook event alert opened resolved maintenance hmac secret home assistant" },
|
||||
// Data
|
||||
{ title: "Export and import configuration", where: "Data › Backup", to: "/settings/data", words: "backup export import configuration move restore database self backup" },
|
||||
{ title: "Log retention and purge", where: "Data › Logs", to: "/settings/data?view=logs", words: "logs purge retention diagnostic audit delete old days" },
|
||||
{ title: "DNS record cache", where: "Data › Cache", to: "/settings/data?view=cache", words: "dns cache clear zones records resync" },
|
||||
];
|
||||
|
||||
const norm = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "");
|
||||
|
||||
/** The settings that match every word typed, best first (a word in the title beats one only in the description). */
|
||||
export function searchSettings(query: string, limit = 8): SettingsEntry[] {
|
||||
const words = norm(query).split(/\s+/).filter(Boolean);
|
||||
if (words.length === 0) return [];
|
||||
const scored: { entry: SettingsEntry; score: number }[] = [];
|
||||
for (const entry of SETTINGS_INDEX) {
|
||||
const title = norm(entry.title);
|
||||
const where = norm(entry.where);
|
||||
const rest = norm(entry.words);
|
||||
let score = 0;
|
||||
let all = true;
|
||||
for (const w of words) {
|
||||
if (title.includes(w)) score += title.startsWith(w) || title.includes(` ${w}`) ? 4 : 3;
|
||||
else if (where.includes(w)) score += 2;
|
||||
else if (rest.includes(w)) score += 1;
|
||||
else {
|
||||
all = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (all) scored.push({ entry, score });
|
||||
}
|
||||
return scored.sort((a, b) => b.score - a.score || a.entry.title.localeCompare(b.entry.title)).slice(0, limit).map((s) => s.entry);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readableError } from "./errors";
|
||||
import { toast } from "./toast";
|
||||
|
||||
/**
|
||||
* "Removed — Undo": take something away at once and offer to put it back, instead of asking first. Only for things that can be put back as they were by making them
|
||||
* again from what is on screen (a link, a note, a written dependency) — not for anything whose history, secret or address would not come back with it.
|
||||
*
|
||||
* Returns whether it was removed. `reload` is called after the removal and again after an undo, so the page shows what is true.
|
||||
*/
|
||||
export async function removeWithUndo(options: { remove: () => Promise<unknown>; restore: () => Promise<unknown>; message: string; reload: () => void; onError?: (message: string) => void }): Promise<boolean> {
|
||||
try {
|
||||
await options.remove();
|
||||
} catch (err) {
|
||||
(options.onError ?? toast.error)(readableError(err));
|
||||
return false;
|
||||
}
|
||||
toast.success(options.message, {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
try {
|
||||
await options.restore();
|
||||
toast.info("Put back.");
|
||||
} catch (err) {
|
||||
toast.error(`Couldn't put it back: ${readableError(err)}`);
|
||||
} finally {
|
||||
options.reload();
|
||||
}
|
||||
},
|
||||
});
|
||||
options.reload();
|
||||
return true;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Link } from "react-router-dom";
|
||||
import { api, type CurrentUser, type DependenciesResponse, type DependencyNode } from "../api/client";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
@@ -84,13 +84,13 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
|
||||
async function remove(d: DependenciesResponse["dependencies"][number]) {
|
||||
if (!(await confirmDialog({ title: "Remove a dependency", message: `${d.from.name} no longer needs ${d.to.name}?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.dependencies.remove(d.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
await removeWithUndo({
|
||||
remove: () => api.dependencies.remove(d.id),
|
||||
restore: () => api.dependencies.create({ fromType: d.from.type, fromId: d.from.id, toType: d.to.type, toId: d.to.id }),
|
||||
message: `${d.from.name} no longer needs ${d.to.name}.`,
|
||||
reload: load,
|
||||
onError: setError,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -174,7 +174,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
|
||||
<h3 className="card-title">Set elsewhere</h3>
|
||||
</div>
|
||||
<div className="card-body text-secondary small pb-0">
|
||||
A server’s “runs on” is set on the server itself, or worked out from the Proxmox node it is a guest of. A network device’s “connected through” is what its UniFi controller says. They count here too.
|
||||
A server’s “runs on” is set on the server itself, or worked out from the Proxmox node it is a guest of. What a network device or a server is “connected through” is what its UniFi controller says (a server is matched by its IP address). They count here too.
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
@@ -182,7 +182,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
|
||||
{data.runsOn.map((r) => (
|
||||
<tr key={`${r.from.key}>${r.to.key}`}>
|
||||
<td>{r.from.name}</td>
|
||||
<td className="text-secondary">{r.from.key.startsWith("device:") && r.to.key.startsWith("device:") ? "is connected through" : "runs on"}</td>
|
||||
<td className="text-secondary">{r.to.key.startsWith("device:") ? "is connected through" : "runs on"}</td>
|
||||
<td>{r.to.name}</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
Reference in new issue
Block a user