Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant
- Racks page and a network diagram (UniFi tree with servers, printable) - Notes on servers and devices; To do list shown in Coming up and My work - Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert - Suggested dependencies from where a service is reached - Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks - Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts - TimeChart gets a "value" scale that fits negatives; docs updated Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
68b41b5586
commit
18ceed62e8
77 files changed
+20432
-35
No files matched your search
@@ -7,8 +7,12 @@ import Users from "./pages/Users";
|
||||
import Secrets from "./pages/Secrets";
|
||||
import Ipam from "./pages/Ipam";
|
||||
import NetworkDevices from "./pages/NetworkDevices";
|
||||
import ProxyHosts from "./pages/ProxyHosts";
|
||||
import HomeAssistant from "./pages/HomeAssistant";
|
||||
import MyWorkPage from "./pages/MyWork";
|
||||
import ApiTokens from "./pages/ApiTokens";
|
||||
import Todo from "./pages/Todo";
|
||||
import InventoryRacks from "./pages/InventoryRacks";
|
||||
import Ports from "./pages/Ports";
|
||||
import Dns from "./pages/Dns";
|
||||
import Servers from "./pages/Servers";
|
||||
@@ -138,6 +142,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/" element={<Dashboard user={user} />} />
|
||||
<Route path="/my-work" element={<MyWorkPage user={user} />} />
|
||||
<Route path="/api-tokens" element={<ApiTokens />} />
|
||||
<Route path="/todo" element={<Todo user={user} />} />
|
||||
<Route path="/map" element={<MapPage user={user} />} />
|
||||
<Route path="/servers" element={<Servers user={user} />} />
|
||||
<Route path="/servers/compare" element={<ServerCompare />} />
|
||||
@@ -145,6 +150,8 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/dns" element={<Dns user={user} />} />
|
||||
<Route path="/ipam" element={<Ipam user={user} />} />
|
||||
<Route path="/network/devices" element={<NetworkDevices user={user} />} />
|
||||
<Route path="/proxy-hosts" element={<ProxyHosts user={user} />} />
|
||||
<Route path="/home-assistant" element={<HomeAssistant user={user} />} />
|
||||
<Route path="/ports" element={<Ports user={user} />} />
|
||||
<Route path="/secrets" element={<Secrets user={user} />} />
|
||||
<Route path="/integrations" element={<Integrations user={user} />} />
|
||||
@@ -155,6 +162,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/maintenance" element={<Maintenance user={user} />} />
|
||||
<Route path="/updates" element={<Updates user={user} />} />
|
||||
<Route path="/inventory" element={<Inventory user={user} />} />
|
||||
<Route path="/inventory/racks" element={<InventoryRacks />} />
|
||||
<Route path="/inventory/labels" element={<InventoryLabels />} />
|
||||
<Route path="/inventory/lifecycle" element={<InventoryLifecycle />} />
|
||||
{/* These were pages of their own; they are sections of other pages now, and old links, bookmarks and notifications still arrive. */}
|
||||
|
||||
+159
-2
@@ -517,6 +517,8 @@ export interface HealthCheckSettings {
|
||||
flapRaises: number;
|
||||
/** Minutes a UniFi device may be offline before it is raised. */
|
||||
deviceOfflineMinutes: number;
|
||||
/** Days before an operating system's support ends that a server is flagged (0 = off). */
|
||||
osSupportWarnDays: number;
|
||||
}
|
||||
|
||||
/** The monthly report: last month's availability, incidents, updates and renewals, in one message on a day of the month. */
|
||||
@@ -780,7 +782,19 @@ export interface ServerLink {
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** What a server runs and when that release stops being supported (from what its agent says). */
|
||||
export interface ServerOs {
|
||||
id: string;
|
||||
name: string | null;
|
||||
version: string | null;
|
||||
product: string;
|
||||
endsOn: string | null;
|
||||
state: "ended" | "soon" | "ok" | "unknown";
|
||||
daysLeft: number | null;
|
||||
}
|
||||
|
||||
export interface ServerDetail {
|
||||
os: ServerOs | null;
|
||||
server: ServerRecord;
|
||||
ipAddresses: string[];
|
||||
hardware: ServerHardware;
|
||||
@@ -1081,7 +1095,36 @@ export interface HeartbeatInput {
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export type AgendaKind = "secret" | "certificate" | "domain" | "tailscale" | "warranty" | "support" | "maintenance" | "restore" | "updates";
|
||||
export type AgendaKind = "secret" | "certificate" | "domain" | "tailscale" | "warranty" | "support" | "maintenance" | "restore" | "updates" | "todo";
|
||||
|
||||
/** One job on the to-do list. */
|
||||
export interface TodoItem {
|
||||
id: number;
|
||||
title: string;
|
||||
detail: string | null;
|
||||
dueDate: string | null;
|
||||
assignee: { id: number | null; name: string } | null;
|
||||
target: { type: "server" | "device"; id: number; name: string } | null;
|
||||
createdBy: string | null;
|
||||
createdAt: string;
|
||||
doneAt: string | null;
|
||||
doneBy: string | null;
|
||||
}
|
||||
export interface TodoInput {
|
||||
title: string;
|
||||
detail?: string | null;
|
||||
dueDate?: string | null;
|
||||
assigneeId?: number | null;
|
||||
targetType?: "server" | "device" | null;
|
||||
targetId?: number | null;
|
||||
}
|
||||
export interface NoteItem {
|
||||
targetType: "server" | "device";
|
||||
targetId: number;
|
||||
body: string;
|
||||
updatedBy: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
export interface AgendaItem {
|
||||
id: string;
|
||||
kind: AgendaKind;
|
||||
@@ -1172,6 +1215,18 @@ export interface DependencyNode {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
/** A dependency the app offers to write, from what it already knows. */
|
||||
export interface DependencySuggestion {
|
||||
key: string;
|
||||
from: { type: "integration"; id: number; name: string };
|
||||
to: { type: "server"; id: number; name: string };
|
||||
reason: string;
|
||||
}
|
||||
export interface DependencySuggestions {
|
||||
suggestions: DependencySuggestion[];
|
||||
dismissed: DependencySuggestion[];
|
||||
}
|
||||
|
||||
export interface DependenciesResponse {
|
||||
/** "A needs B", written here. */
|
||||
dependencies: { id: number; from: { type: DependencyNodeType; id: number; name: string }; to: { type: DependencyNodeType; id: number; name: string }; createdAt: string }[];
|
||||
@@ -1185,6 +1240,8 @@ 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 }[];
|
||||
/** Open jobs from the to-do list handed to this person. */
|
||||
todos: { id: number; title: string; detail: string | null; dueDate: string | null; overdue: boolean; dueSoon: boolean; target: { type: string; id: number; name: string } | null }[];
|
||||
needsAttention: number;
|
||||
}
|
||||
|
||||
@@ -1257,6 +1314,68 @@ export interface NetworkOverview {
|
||||
ssids: NetworkSegment[];
|
||||
}
|
||||
|
||||
export interface NpmHost {
|
||||
id: number;
|
||||
domains: string[];
|
||||
forwardScheme: string;
|
||||
forwardHost: string;
|
||||
forwardPort: number | null;
|
||||
enabled: boolean;
|
||||
sslForced: boolean;
|
||||
certificate: { id: number; name: string; expiresAt: string | null } | null;
|
||||
online: boolean;
|
||||
error: string | null;
|
||||
/** The server the address it forwards to belongs to, when the app knows it. */
|
||||
server: { id: number; name: string } | null;
|
||||
}
|
||||
|
||||
export interface NpmCertificate {
|
||||
id: number;
|
||||
name: string;
|
||||
provider: string;
|
||||
domains: string[];
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
export interface IntegrationProblem {
|
||||
key: string;
|
||||
kind: string;
|
||||
severity: "critical" | "warning";
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface NpmOverview {
|
||||
integrations: { id: number; name: string; readAt: string; error: string | null; version: string | null; hosts: NpmHost[]; certificates: NpmCertificate[]; problems: IntegrationProblem[] }[];
|
||||
}
|
||||
|
||||
export interface HaSyncStatus {
|
||||
at: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
entities: number;
|
||||
}
|
||||
|
||||
export interface HaWatchedEntity {
|
||||
entityId: string;
|
||||
name: string | null;
|
||||
above: number | null;
|
||||
below: number | null;
|
||||
entity: { friendlyName: string | null; state: string; value: number | null; unit: string | null; deviceClass: string | null; lastChanged: string | null; unavailableSince: string | null; updatedAt: string } | null;
|
||||
}
|
||||
|
||||
export interface HaOverview {
|
||||
integrations: { id: number; name: string; enabled: boolean; status: HaSyncStatus | null; fresh: boolean; watched: HaWatchedEntity[]; problems: IntegrationProblem[] }[];
|
||||
}
|
||||
|
||||
export interface HaEntityChoice {
|
||||
entityId: string;
|
||||
name: string;
|
||||
state: string;
|
||||
unit: string | null;
|
||||
deviceClass: string | null;
|
||||
watched: boolean;
|
||||
}
|
||||
|
||||
/** A piece of hardware in the inventory. */
|
||||
export interface Asset {
|
||||
id: number;
|
||||
@@ -1671,7 +1790,7 @@ export interface ManualTaskInput {
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi";
|
||||
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant";
|
||||
|
||||
export interface IntegrationField {
|
||||
key: string;
|
||||
@@ -2268,18 +2387,56 @@ export const api = {
|
||||
myWork: {
|
||||
get: () => request<MyWork>("/api/my-work"),
|
||||
},
|
||||
todos: {
|
||||
list: () => request<{ todos: TodoItem[]; people: { id: number; name: string; role: string }[] }>("/api/todos"),
|
||||
create: (data: TodoInput) => request<{ todo: TodoItem }>("/api/todos", { method: "POST", body: JSON.stringify(data) }),
|
||||
update: (id: number, data: Partial<TodoInput> & { done?: boolean }) => request<{ todo: TodoItem }>(`/api/todos/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/todos/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
notes: {
|
||||
get: (targetType: "server" | "device", targetId: number) => request<{ note: NoteItem | null }>(`/api/notes?targetType=${targetType}&targetId=${targetId}`),
|
||||
save: (targetType: "server" | "device", targetId: number, body: string) => request<{ note: NoteItem | null }>("/api/notes", { method: "PUT", body: JSON.stringify({ targetType, targetId, body }) }),
|
||||
},
|
||||
network: {
|
||||
overview: () => request<NetworkOverview>("/api/network"),
|
||||
sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }),
|
||||
},
|
||||
npm: {
|
||||
overview: (refresh = false) => request<NpmOverview>(`/api/npm${refresh ? "?refresh=1" : ""}`),
|
||||
},
|
||||
homeAssistant: {
|
||||
overview: () => request<HaOverview>("/api/home-assistant"),
|
||||
entities: (id: number, q: string) => request<{ total: number; entities: HaEntityChoice[] }>(`/api/home-assistant/${id}/entities?q=${encodeURIComponent(q)}`),
|
||||
watch: (id: number, body: { entityId: string; name?: string | null; above?: number | null; below?: number | null }) =>
|
||||
request<{ ok: boolean; status: HaSyncStatus }>(`/api/home-assistant/${id}/watched`, { method: "PUT", body: JSON.stringify(body) }),
|
||||
unwatch: (id: number, entityId: string) => request<void>(`/api/home-assistant/${id}/watched/${encodeURIComponent(entityId)}`, { method: "DELETE" }),
|
||||
history: (id: number, entityId: string, days: number) =>
|
||||
request<{ days: number; points: { t: string; v: number }[] }>(`/api/home-assistant/${id}/history?entity=${encodeURIComponent(entityId)}&days=${days}`),
|
||||
sync: () => request<{ statuses: Record<number, HaSyncStatus> }>("/api/home-assistant/sync", { method: "POST", body: "{}" }),
|
||||
},
|
||||
dependencies: {
|
||||
list: () => request<DependenciesResponse>("/api/dependencies"),
|
||||
impact: (type: DependencyNodeType, id: number) => request<DependencyImpact>(`/api/dependencies/impact?type=${type}&id=${id}`),
|
||||
graph: () => request<DependencyGraph>("/api/dependencies/graph"),
|
||||
suggestions: () => request<DependencySuggestions>("/api/dependencies/suggestions"),
|
||||
addSuggestions: (keys: string[]) => request<DependencySuggestions & { added: { id: number; from: string; to: string }[] }>("/api/dependencies/suggestions/add", { method: "POST", body: JSON.stringify({ keys }) }),
|
||||
dismissSuggestions: (keys: string[]) => request<DependencySuggestions>("/api/dependencies/suggestions/dismiss", { method: "POST", body: JSON.stringify({ keys }) }),
|
||||
restoreSuggestions: () => request<DependencySuggestions>("/api/dependencies/suggestions/restore", { method: "POST" }),
|
||||
create: (data: { fromType: DependencyNodeType; fromId: number; toType: DependencyNodeType; toId: number }) => request<{ id: number }>("/api/dependencies", { method: "POST", body: JSON.stringify(data) }),
|
||||
remove: (id: number) => request<void>(`/api/dependencies/${id}`, { method: "DELETE" }),
|
||||
},
|
||||
inventory: {
|
||||
racks: () =>
|
||||
request<{
|
||||
racks: {
|
||||
name: string;
|
||||
units: number;
|
||||
slots: { assetId: number; name: string; kind: string; model: string | null; from: number; to: number; powerWatts: number | null; serverId: number | null; clash: boolean }[];
|
||||
unplaced: { assetId: number; name: string; kind: string }[];
|
||||
usedUnits: number;
|
||||
watts: number;
|
||||
}[];
|
||||
}>("/api/inventory/racks"),
|
||||
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) }),
|
||||
|
||||
@@ -44,6 +44,8 @@ const INTEGRATION_TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
pbs: "Proxmox Backup Server",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
const DNS_PROVIDER_LABELS: Record<DnsProviderType, string> = {
|
||||
|
||||
@@ -15,6 +15,8 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
pbs: "Proxmox Backup Server",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
export default function IntegrationEditForm({
|
||||
|
||||
@@ -14,6 +14,8 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
pbs: "Proxmox Backup Server",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () => void; onCancel: () => void }) {
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useMemo } from "react";
|
||||
import type { NetworkDevice } from "../api/client";
|
||||
|
||||
const KIND_WORDS: Record<NetworkDevice["kind"], string> = { gateway: "Gateway", switch: "Switch", access_point: "Access point", other: "Device" };
|
||||
const STATE_COLOR: Record<NetworkDevice["state"], string> = { online: "#2fb344", offline: "#f03e3e", updating: "#f59f00", pending: "#4299e1", other: "#8896ab" };
|
||||
|
||||
const NODE_W = 168;
|
||||
const SLOT_W = 188;
|
||||
const HEAD_H = 46;
|
||||
const LINE_H = 14;
|
||||
const MAX_SERVERS = 4;
|
||||
const ROW_GAP = 46;
|
||||
|
||||
interface Node {
|
||||
id: string;
|
||||
device: NetworkDevice | null; // null: the internet, or "unknown uplink"
|
||||
label: string;
|
||||
children: Node[];
|
||||
width: number; // in slots
|
||||
x: number; // centre, in px
|
||||
y: number; // top, in px
|
||||
h: number;
|
||||
}
|
||||
|
||||
const heightOf = (d: NetworkDevice | null) => (d ? HEAD_H + Math.min(d.servers.length, MAX_SERVERS + (d.servers.length > MAX_SERVERS ? 1 : 0)) * LINE_H + (d.servers.length > 0 ? 6 : 0) : 30);
|
||||
|
||||
/**
|
||||
* How the network hangs together, from what the UniFi controller says each device is connected through: the internet, the gateway, the switches below it, the access
|
||||
* points below those, and the servers plugged into each. A tree drawn top-down; a device whose state is not online is red, and a device whose uplink is not known sits
|
||||
* apart under "Unknown uplink". Print it for the cabinet door.
|
||||
*/
|
||||
export default function NetworkDiagram({ devices }: { devices: NetworkDevice[] }) {
|
||||
const layout = useMemo(() => {
|
||||
const childrenOf = new Map<number, NetworkDevice[]>();
|
||||
const roots: NetworkDevice[] = [];
|
||||
const orphans: NetworkDevice[] = [];
|
||||
for (const d of devices) {
|
||||
if (d.uplink) {
|
||||
const parent = devices.find((p) => p.id === d.uplink!.id);
|
||||
if (parent) {
|
||||
childrenOf.set(parent.id, [...(childrenOf.get(parent.id) ?? []), d]);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
(d.kind === "gateway" ? roots : orphans).push(d);
|
||||
}
|
||||
const build = (d: NetworkDevice, seen: Set<number>): Node => {
|
||||
const kids = (childrenOf.get(d.id) ?? []).filter((k) => !seen.has(k.id)).sort((a, b) => a.name.localeCompare(b.name));
|
||||
const next = new Set(seen).add(d.id);
|
||||
const children = kids.map((k) => build(k, next));
|
||||
return { id: `d${d.id}`, device: d, label: d.name, children, width: Math.max(1, children.reduce((n, c) => n + c.width, 0)), x: 0, y: 0, h: heightOf(d) };
|
||||
};
|
||||
const virtual = (id: string, label: string, kids: NetworkDevice[]): Node => {
|
||||
const children = kids.sort((a, b) => a.name.localeCompare(b.name)).map((k) => build(k, new Set()));
|
||||
return { id, device: null, label, children, width: Math.max(1, children.reduce((n, c) => n + c.width, 0)), x: 0, y: 0, h: heightOf(null) };
|
||||
};
|
||||
const top: Node[] = [];
|
||||
if (roots.length > 0) top.push(virtual("internet", "Internet", roots));
|
||||
if (orphans.length > 0) top.push(virtual("unknown", "Unknown uplink", orphans));
|
||||
// Position: each node is centred over its children; a leaf takes one slot; the top-level groups sit side by side.
|
||||
let cursor = 0;
|
||||
const levelBottom: number[] = [];
|
||||
const place = (n: Node, depth: number, left: number) => {
|
||||
let at = left;
|
||||
for (const c of n.children) {
|
||||
place(c, depth + 1, at);
|
||||
at += c.width * SLOT_W;
|
||||
}
|
||||
n.x = n.children.length > 0 ? (n.children[0].x + n.children[n.children.length - 1].x) / 2 : left + (n.width * SLOT_W) / 2;
|
||||
levelBottom[depth] = Math.max(levelBottom[depth] ?? 0, n.h);
|
||||
(n as Node & { depth: number }).depth = depth;
|
||||
};
|
||||
for (const t of top) {
|
||||
place(t, 0, cursor);
|
||||
cursor += t.width * SLOT_W + SLOT_W / 2;
|
||||
}
|
||||
// Rows: each level is as tall as its tallest node, then a gap.
|
||||
const rowTop: number[] = [];
|
||||
levelBottom.reduce((y, h, i) => {
|
||||
rowTop[i] = y;
|
||||
return y + h + ROW_GAP;
|
||||
}, 8);
|
||||
const all: Node[] = [];
|
||||
const walk = (n: Node) => {
|
||||
n.y = rowTop[(n as Node & { depth: number }).depth];
|
||||
all.push(n);
|
||||
n.children.forEach(walk);
|
||||
};
|
||||
top.forEach(walk);
|
||||
const width = Math.max(cursor - SLOT_W / 2, SLOT_W);
|
||||
const height = (rowTop[rowTop.length - 1] ?? 0) + (levelBottom[levelBottom.length - 1] ?? 0) + 8;
|
||||
return { all, width, height };
|
||||
}, [devices]);
|
||||
|
||||
if (devices.length === 0) return <div className="text-secondary">No devices to draw yet.</div>;
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-body" style={{ overflowX: "auto" }}>
|
||||
<svg viewBox={`0 0 ${layout.width} ${layout.height}`} width={layout.width} height={layout.height} role="img" aria-label={`Network diagram: ${devices.length} devices, by what each is connected through`} style={{ maxWidth: "none", color: "var(--tblr-body-color)" }}>
|
||||
{layout.all.flatMap((n) =>
|
||||
n.children.map((c) => {
|
||||
const x1 = n.x;
|
||||
const y1 = n.y + n.h;
|
||||
const x2 = c.x;
|
||||
const y2 = c.y;
|
||||
const mid = (y1 + y2) / 2;
|
||||
return <path key={`${n.id}-${c.id}`} d={`M${x1},${y1} V${mid} H${x2} V${y2}`} fill="none" stroke="currentColor" strokeOpacity="0.35" strokeWidth="1.5" />;
|
||||
}),
|
||||
)}
|
||||
{layout.all.map((n) => {
|
||||
const d = n.device;
|
||||
if (!d) {
|
||||
return (
|
||||
<g key={n.id}>
|
||||
<rect x={n.x - 60} y={n.y} width="120" height={n.h} rx="15" fill="currentColor" fillOpacity="0.08" stroke="currentColor" strokeOpacity="0.4" />
|
||||
<text x={n.x} y={n.y + 19} textAnchor="middle" fontSize="12" fill="currentColor" fontWeight="600">
|
||||
{n.label}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
const shown = d.servers.slice(0, MAX_SERVERS);
|
||||
return (
|
||||
<g key={n.id}>
|
||||
<title>{`${d.name} — ${KIND_WORDS[d.kind]}${d.model ? `, ${d.model}` : ""}${d.ip ? `, ${d.ip}` : ""} — ${d.state}${d.servers.length > 0 ? `\nPlugged in: ${d.servers.map((s) => s.serverName).join(", ")}` : ""}`}</title>
|
||||
<rect x={n.x - NODE_W / 2} y={n.y} width={NODE_W} height={n.h} rx="6" fill="var(--tblr-bg-surface, #fff)" stroke={STATE_COLOR[d.state]} strokeWidth="2" />
|
||||
<circle cx={n.x - NODE_W / 2 + 12} cy={n.y + 14} r="5" fill={STATE_COLOR[d.state]} />
|
||||
<text x={n.x - NODE_W / 2 + 24} y={n.y + 18} fontSize="12" fill="currentColor" fontWeight="600">
|
||||
{d.name.length > 20 ? `${d.name.slice(0, 19)}…` : d.name}
|
||||
</text>
|
||||
<text x={n.x - NODE_W / 2 + 10} y={n.y + 35} fontSize="10.5" fill="currentColor" fillOpacity="0.7">
|
||||
{[KIND_WORDS[d.kind], d.ip].filter(Boolean).join(" · ")}
|
||||
</text>
|
||||
{shown.map((s, i) => (
|
||||
<text key={s.serverId} x={n.x - NODE_W / 2 + 10} y={n.y + HEAD_H + 8 + i * LINE_H} fontSize="10.5" fill="currentColor">
|
||||
▪ {s.serverName}
|
||||
{s.port !== null ? ` (${s.port})` : s.wired ? "" : " (Wi-Fi)"}
|
||||
</text>
|
||||
))}
|
||||
{d.servers.length > MAX_SERVERS && (
|
||||
<text x={n.x - NODE_W / 2 + 10} y={n.y + HEAD_H + 8 + MAX_SERVERS * LINE_H} fontSize="10.5" fill="currentColor" fillOpacity="0.7">
|
||||
+ {d.servers.length - MAX_SERVERS} more
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
<div className="card-footer text-secondary small d-flex flex-wrap gap-3">
|
||||
<span style={{ color: STATE_COLOR.online }}>● online</span>
|
||||
<span style={{ color: STATE_COLOR.offline }}>● offline</span>
|
||||
<span style={{ color: STATE_COLOR.updating }}>● updating</span>
|
||||
<span>▪ a server plugged in (the port, or Wi-Fi)</span>
|
||||
<span className="ms-auto">As the UniFi controller reports what each device is connected through.</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type NoteItem } from "../api/client";
|
||||
import { BlockSkeleton } from "./Skeleton";
|
||||
import RunbookText from "./RunbookText";
|
||||
import TimeAgo from "./TimeAgo";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
/**
|
||||
* Free-form notes about a server or a network device — what it is, where it sits, what was done to it last time. One text, written with the same small formatting
|
||||
* as a runbook (lists, **bold**, `code`, links). Everyone signed in reads it; operators write it. Emptying it takes the note away.
|
||||
*/
|
||||
export default function NotesCard({ targetType, targetId, canEdit, bare = false }: { targetType: "server" | "device"; targetId: number; canEdit: boolean; /** Without the card round it (inside a drawer). */ bare?: boolean }) {
|
||||
const [note, setNote] = useState<NoteItem | null | undefined>(undefined);
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setNote(undefined);
|
||||
setDraft(null);
|
||||
api.notes
|
||||
.get(targetType, targetId)
|
||||
.then((res) => alive && setNote(res.note))
|
||||
.catch(() => alive && setFailed(true));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [targetType, targetId]);
|
||||
|
||||
async function save() {
|
||||
if (draft === null) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.notes.save(targetType, targetId, draft);
|
||||
setNote(res.note);
|
||||
setDraft(null);
|
||||
toast.success(res.note ? "Saved." : "Note removed.");
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const body = failed ? (
|
||||
<div className="text-secondary">Couldn’t load the note.</div>
|
||||
) : note === undefined ? (
|
||||
<BlockSkeleton lines={2} />
|
||||
) : draft !== null ? (
|
||||
<>
|
||||
<textarea className="form-control mb-2" rows={8} maxLength={8000} value={draft} onChange={(e) => setDraft(e.target.value)} aria-label="The note" placeholder={"What is it, where does it sit, what was done to it last time?\n\n- lists, **bold**, `code` and links work"} autoFocus />
|
||||
<div className="d-flex gap-2">
|
||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={() => void save()}>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={busy} onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : note ? (
|
||||
<>
|
||||
<RunbookText text={note.body} />
|
||||
<div className="text-secondary small mt-2">
|
||||
{note.updatedBy ? `${note.updatedBy}, ` : ""}
|
||||
<TimeAgo value={note.updatedAt} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-secondary">Nothing written down yet.{canEdit ? " Add what is worth knowing about it." : ""}</div>
|
||||
);
|
||||
|
||||
const edit =
|
||||
canEdit && draft === null && note !== undefined && !failed ? (
|
||||
<button type="button" className="btn btn-sm btn-primary" onClick={() => setDraft(note?.body ?? "")}>
|
||||
{note ? "Edit" : "Write a note"}
|
||||
</button>
|
||||
) : null;
|
||||
|
||||
if (bare) {
|
||||
return (
|
||||
<>
|
||||
{body}
|
||||
{edit && <div className="mt-3">{edit}</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Notes</h3>
|
||||
{edit && <div className="card-actions">{edit}</div>}
|
||||
</div>
|
||||
<div className="card-body">{body}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -57,7 +57,8 @@ export default function TimeChart({
|
||||
to: number;
|
||||
/** Read out by screen readers in place of the picture. */
|
||||
label: string;
|
||||
unit?: "%" | "ms";
|
||||
/** "%" is a 0–100 scale; "ms" starts at zero and fits the data; "value" fits the data from its lowest to its highest, so negatives (a freezer's temperature) are drawn too. */
|
||||
unit?: "%" | "ms" | "value";
|
||||
compact?: boolean;
|
||||
/** One bar per point instead of a line (daily availability). */
|
||||
bars?: boolean;
|
||||
@@ -70,19 +71,30 @@ export default function TimeChart({
|
||||
// Where the cursor is, as a time (null: nowhere), and whether the keyboard put it there.
|
||||
const [cursor, setCursor] = useState<number | null>(null);
|
||||
|
||||
const fmt = format ?? ((v: number) => (unit === "%" ? `${Math.round(v * 10) / 10}%` : `${Math.round(v)} ms`));
|
||||
const fmt = format ?? ((v: number) => (unit === "%" ? `${Math.round(v * 10) / 10}%` : unit === "value" ? `${Math.round(v * 10) / 10}` : `${Math.round(v)} ms`));
|
||||
const parsed = useMemo(() => series.map((s) => ({ ...s, pts: s.points.map((p) => ({ ...p, x: Date.parse(p.t) })).filter((p) => Number.isFinite(p.x)) })), [series]);
|
||||
const any = parsed.some((s) => s.pts.length > 0);
|
||||
|
||||
const top = unit === "%" ? 100 : niceCeil(Math.max(0, ...parsed.flatMap((s) => s.pts.map((p) => p.hi ?? p.v))) * 1.05);
|
||||
const [bottom, top] = (() => {
|
||||
if (unit === "%") return [0, 100];
|
||||
const values = parsed.flatMap((s) => s.pts.flatMap((p) => [p.lo ?? p.v, p.hi ?? p.v]));
|
||||
if (unit !== "value") return [0, niceCeil(Math.max(0, ...values) * 1.05)];
|
||||
if (values.length === 0) return [0, 1];
|
||||
const lo = Math.min(...values);
|
||||
const hi = Math.max(...values);
|
||||
const span = hi - lo || Math.abs(hi) * 0.2 || 1;
|
||||
const step = niceCeil((span * 1.1) / 4);
|
||||
const low = Math.floor((lo - span * 0.05) / step) * step;
|
||||
return [low, Math.max(Math.ceil((hi + span * 0.05) / step) * step, low + step)];
|
||||
})();
|
||||
const x = (t: number) => PAD.left + ((t - from) / Math.max(to - from, 1)) * (W - PAD.left - PAD.right);
|
||||
const y = (v: number) => PAD.top + (1 - Math.min(top, Math.max(0, v)) / top) * (H - PAD.top - PAD.bottom);
|
||||
const y = (v: number) => PAD.top + (1 - (Math.min(top, Math.max(bottom, v)) - bottom) / (top - bottom)) * (H - PAD.top - PAD.bottom);
|
||||
|
||||
const spanDays = (to - from) / 86_400_000;
|
||||
const tickLabel = (t: number) =>
|
||||
spanDays <= 1.5 ? formatTime(new Date(t), false) : spanDays <= 45 ? new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" }) : new Date(t).toLocaleDateString(undefined, { month: "short", year: "2-digit" });
|
||||
const ticks = (compact ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1]).map((f) => from + f * (to - from));
|
||||
const grid = compact ? [0, top / 2, top] : [0, top / 4, top / 2, (3 * top) / 4, top];
|
||||
const grid = (compact ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75, 1]).map((f) => bottom + f * (top - bottom));
|
||||
|
||||
// Every moment any series has a point, for the arrow keys to step through.
|
||||
const moments = useMemo(() => [...new Set(parsed.flatMap((s) => s.pts.map((p) => p.x)))].sort((a, b) => a - b), [parsed]);
|
||||
@@ -149,7 +161,7 @@ export default function TimeChart({
|
||||
<g key={v}>
|
||||
<line x1={PAD.left} x2={W - PAD.right} y1={y(v)} y2={y(v)} stroke="currentColor" strokeOpacity={v === 0 ? 0.4 : 0.15} />
|
||||
<text x={PAD.left - 6} y={y(v) + 4} textAnchor="end" fontSize="11" fill="currentColor" fillOpacity="0.7">
|
||||
{unit === "%" ? `${v}%` : `${Math.round(v)}`}
|
||||
{unit === "%" ? `${v}%` : unit === "value" ? `${Math.round(v * 10) / 10}` : `${Math.round(v)}`}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
|
||||
@@ -16,6 +16,8 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
pbs: "Proxmox Backup",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
export type WallLevel = "critical" | "warning" | "ok" | "unsure";
|
||||
|
||||
@@ -5,7 +5,10 @@ import {
|
||||
IconWorld,
|
||||
IconNetwork,
|
||||
IconRouter,
|
||||
IconArrowsSplit2,
|
||||
IconHome2,
|
||||
IconChecklist,
|
||||
IconListDetails,
|
||||
IconKey,
|
||||
IconPlugConnected,
|
||||
IconBrandDocker,
|
||||
@@ -96,6 +99,7 @@ export const NAV: NavEntry[] = [
|
||||
items: [
|
||||
{ to: "/dns", label: "DNS", icon: <IconWorld size={20} /> },
|
||||
{ to: "/network/devices", label: "Network devices", icon: <IconRouter size={20} /> },
|
||||
{ to: "/proxy-hosts", label: "Proxy hosts", icon: <IconArrowsSplit2 size={20} /> },
|
||||
{ to: "/ipam", label: "IP Addresses", icon: <IconNetwork size={20} /> },
|
||||
{ to: "/ports", label: "Ports", icon: <IconPlug size={20} /> },
|
||||
{ to: "/consistency", label: "Consistency", icon: <IconListCheck size={20} /> },
|
||||
@@ -109,6 +113,7 @@ export const NAV: NavEntry[] = [
|
||||
{ to: "/endpoints", label: "Endpoints", icon: <IconHeartbeat size={20} /> },
|
||||
{ to: "/heartbeats", label: "Heartbeats", icon: <IconHeartRateMonitor size={20} /> },
|
||||
{ to: "/uptime-kuma", label: "Uptime Kuma", icon: <IconActivityHeartbeat size={20} /> },
|
||||
{ to: "/home-assistant", label: "Home Assistant", icon: <IconHome2 size={20} /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -131,6 +136,7 @@ export const NAV: NavEntry[] = [
|
||||
{ to: "/maintenance", label: "Maintenance", icon: <IconTool size={20} /> },
|
||||
{ to: "/updates", label: "Updates", icon: <IconDownload size={20} /> },
|
||||
{ to: "/coming-up", label: "Coming up", icon: <IconCalendarEvent size={20} /> },
|
||||
{ to: "/todo", label: "To do", icon: <IconListDetails size={20} /> },
|
||||
{ to: "/reports", label: "Monthly report", icon: <IconReportAnalytics size={20} /> },
|
||||
{ to: "/changes", label: "Change log", icon: <IconGitCommit size={20} />, minRole: "operator" },
|
||||
],
|
||||
|
||||
@@ -18,6 +18,7 @@ const KINDS: { id: AgendaKind; label: string }[] = [
|
||||
{ id: "maintenance", label: "Maintenance" },
|
||||
{ id: "restore", label: "Restore tests" },
|
||||
{ id: "updates", label: "Updates waiting" },
|
||||
{ id: "todo", label: "To do" },
|
||||
];
|
||||
const KIND_LABEL = Object.fromEntries(KINDS.map((k) => [k.id, k.label])) as Record<AgendaKind, string>;
|
||||
|
||||
|
||||
@@ -332,7 +332,7 @@ function MyWorkStrip() {
|
||||
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.
|
||||
<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, jobs that are due.
|
||||
</span>
|
||||
<Link to="/my-work" className="btn btn-sm btn-primary ms-auto">
|
||||
My work
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { api, type CurrentUser, type HaEntityChoice, type HaOverview, type HaWatchedEntity } from "../api/client";
|
||||
import DetailDrawer from "../components/DetailDrawer";
|
||||
import RangeSelect from "../components/RangeSelect";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import TimeChart from "../components/TimeChart";
|
||||
import EmptyState from "../components/EmptyState";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { useChartRange } from "../utils/chartRanges";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
type Integration = HaOverview["integrations"][number];
|
||||
|
||||
const shownName = (w: HaWatchedEntity) => w.name ?? w.entity?.friendlyName ?? w.entityId;
|
||||
const numberWords = (v: number, unit: string | null) => `${Math.round(v * 100) / 100}${unit ? ` ${unit}` : ""}`;
|
||||
|
||||
function StateCell({ w, problem }: { w: HaWatchedEntity; problem: boolean }) {
|
||||
const e = w.entity;
|
||||
if (!e) return <span className="text-secondary">not read yet</span>;
|
||||
if (e.unavailableSince !== null || e.state === "missing") {
|
||||
return (
|
||||
<span className="badge bg-yellow-lt text-yellow" title={`Since ${e.unavailableSince ?? "?"}`}>
|
||||
{e.state === "missing" ? "Not in Home Assistant" : e.state}
|
||||
{e.unavailableSince ? <> · <TimeAgo value={e.unavailableSince} /></> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <strong className={problem ? "text-red" : ""}>{e.value !== null ? numberWords(e.value, e.unit) : e.state}</strong>;
|
||||
}
|
||||
|
||||
function limitsWords(w: HaWatchedEntity): string {
|
||||
const unit = w.entity?.unit ? ` ${w.entity.unit}` : "";
|
||||
if (w.below !== null && w.above !== null) return `${w.below}–${w.above}${unit}`;
|
||||
if (w.below !== null) return `not under ${w.below}${unit}`;
|
||||
if (w.above !== null) return `not over ${w.above}${unit}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
/** A watched number over time, from what this app has kept (up to 35 days). */
|
||||
function HistoryDrawer({ integrationId, w, onClose }: { integrationId: number; w: HaWatchedEntity; onClose: () => void }) {
|
||||
const [days, setDays] = useChartRange(7);
|
||||
const shown = days > 30 ? 30 : days;
|
||||
const [points, setPoints] = useState<{ t: string; v: number }[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [to, setTo] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api.homeAssistant
|
||||
.history(integrationId, w.entityId, shown)
|
||||
.then((res) => {
|
||||
if (!alive) return;
|
||||
setPoints(res.points);
|
||||
setTo(Date.now());
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => alive && setError(readableError(err)));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [integrationId, w.entityId, shown]);
|
||||
|
||||
const unit = w.entity?.unit ?? "";
|
||||
const series = useMemo(() => [{ name: shownName(w), color: "#4299e1", points: points ?? [] }], [points, w]);
|
||||
return (
|
||||
<DetailDrawer title={shownName(w)} subtitle={w.entityId} onClose={onClose}>
|
||||
<div className="mb-3">
|
||||
<RangeSelect value={shown} onChange={setDays} only={[1, 7, 30]} />
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{!points && !error && <BlockSkeleton lines={5} />}
|
||||
{points && <TimeChart series={series} unit="value" from={to - shown * 86_400_000} to={to} label={`${shownName(w)} over time`} format={(v) => numberWords(v, unit)} empty="Nothing kept for this in this stretch yet — a reading is added every few minutes." />}
|
||||
<div className="text-secondary small mt-2">Readings are kept for 35 days.</div>
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
/** Change what is said about an entity already watched: its name and its limits. */
|
||||
function EditDrawer({ integrationId, w, onClose, onSaved }: { integrationId: number; w: HaWatchedEntity; onClose: () => void; onSaved: () => void }) {
|
||||
const numeric = w.entity?.value !== null && w.entity?.value !== undefined;
|
||||
const [name, setName] = useState(w.name ?? "");
|
||||
const [below, setBelow] = useState(w.below === null ? "" : String(w.below));
|
||||
const [above, setAbove] = useState(w.above === null ? "" : String(w.above));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function save() {
|
||||
const parse = (s: string) => (s.trim() === "" ? null : Number(s));
|
||||
const b = parse(below);
|
||||
const a = parse(above);
|
||||
if ((b !== null && !Number.isFinite(b)) || (a !== null && !Number.isFinite(a))) return setError("The limits have to be numbers.");
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.homeAssistant.watch(integrationId, { entityId: w.entityId, name: name.trim() || null, below: b, above: a });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DetailDrawer title={shownName(w)} subtitle={w.entityId} onClose={onClose}>
|
||||
<ErrorNotice error={error} />
|
||||
<div className="mb-3">
|
||||
<label className="form-label" htmlFor="ha-name">
|
||||
Name shown here
|
||||
</label>
|
||||
<input id="ha-name" className="form-control" value={name} maxLength={80} placeholder={w.entity?.friendlyName ?? w.entityId} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
{numeric ? (
|
||||
<div className="row g-2 mb-3">
|
||||
<div className="col-6">
|
||||
<label className="form-label" htmlFor="ha-below">
|
||||
Alert when under{w.entity?.unit ? ` (${w.entity.unit})` : ""}
|
||||
</label>
|
||||
<input id="ha-below" className="form-control" inputMode="decimal" value={below} onChange={(e) => setBelow(e.target.value)} placeholder="no limit" />
|
||||
</div>
|
||||
<div className="col-6">
|
||||
<label className="form-label" htmlFor="ha-above">
|
||||
Alert when over{w.entity?.unit ? ` (${w.entity.unit})` : ""}
|
||||
</label>
|
||||
<input id="ha-above" className="form-control" inputMode="decimal" value={above} onChange={(e) => setAbove(e.target.value)} placeholder="no limit" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-secondary mb-3">This one isn’t a number, so there are no limits to set. It is an alert when it has been unavailable for 15 minutes.</div>
|
||||
)}
|
||||
<button className="btn btn-primary" onClick={() => void save()} disabled={busy}>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
</button>
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
/** Pick entities to watch: search what Home Assistant has, read live. */
|
||||
function PickDrawer({ integration, onClose, onChanged }: { integration: Integration; onClose: () => void; onChanged: () => void }) {
|
||||
const [q, setQ] = useState("");
|
||||
const [found, setFound] = useState<{ total: number; entities: HaEntityChoice[] } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const timer = setTimeout(() => {
|
||||
api.homeAssistant
|
||||
.entities(integration.id, q)
|
||||
.then((res) => {
|
||||
if (!alive) return;
|
||||
setFound(res);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => alive && setError(readableError(err)));
|
||||
}, 250);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [integration.id, q]);
|
||||
|
||||
async function watch(e: HaEntityChoice) {
|
||||
setBusy(e.entityId);
|
||||
try {
|
||||
await api.homeAssistant.watch(integration.id, { entityId: e.entityId });
|
||||
setFound((f) => (f ? { ...f, entities: f.entities.map((x) => (x.entityId === e.entityId ? { ...x, watched: true } : x)) } : f));
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DetailDrawer title="Watch something" subtitle={integration.name} onClose={onClose}>
|
||||
<div className="text-secondary mb-2">Search by name or id, like “battery” or “freezer”. Limits are set afterwards, from the list.</div>
|
||||
<input className="form-control mb-3" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search Home Assistant…" aria-label="Search entities" autoFocus />
|
||||
<ErrorNotice error={error} />
|
||||
{!found && !error && <BlockSkeleton lines={4} />}
|
||||
{found && (
|
||||
<>
|
||||
<div className="list-group list-group-flush">
|
||||
{found.entities.map((e) => (
|
||||
<div className="list-group-item d-flex align-items-center gap-2 px-0" key={e.entityId}>
|
||||
<div className="flex-fill" style={{ minWidth: 0 }}>
|
||||
<div className="text-truncate">{e.name}</div>
|
||||
<div className="text-secondary small font-monospace text-truncate">
|
||||
{e.entityId} · {e.state}
|
||||
{e.unit ? ` ${e.unit}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
{e.watched ? (
|
||||
<span className="badge bg-green-lt text-green">Watching</span>
|
||||
) : (
|
||||
<button className="btn btn-sm btn-outline-primary" disabled={busy === e.entityId} onClick={() => void watch(e)}>
|
||||
Watch
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{found.entities.length === 0 && <div className="text-secondary">Nothing matches.</div>}
|
||||
<div className="text-secondary small mt-2">
|
||||
{found.entities.length >= 60 ? "The first 60 of " : ""}
|
||||
{found.total} in Home Assistant.
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DetailDrawer>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The few things worth watching in Home Assistant — a UPS battery, a freezer, a door sensor, a pump — chosen here, not all several hundred entities. Each is read every
|
||||
* few minutes and kept with its history; it is an alert when it has said nothing for 15 minutes, or a number goes past a limit that was set. Nothing is ever written
|
||||
* to Home Assistant.
|
||||
*/
|
||||
export default function HomeAssistant({ user }: { user: CurrentUser }) {
|
||||
const canAct = user.role === "admin" || user.role === "operator";
|
||||
const [data, setData] = useState<HaOverview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reading, setReading] = useState(false);
|
||||
const [picking, setPicking] = useState<Integration | null>(null);
|
||||
const [editing, setEditing] = useState<{ id: number; w: HaWatchedEntity } | null>(null);
|
||||
const [charting, setCharting] = useState<{ id: number; w: HaWatchedEntity } | null>(null);
|
||||
|
||||
const load = useCallback(
|
||||
() =>
|
||||
api.homeAssistant
|
||||
.overview()
|
||||
.then((res) => {
|
||||
setData(res);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(readableError(err))),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const timer = setInterval(() => void load(), 60_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [load]);
|
||||
|
||||
async function readNow() {
|
||||
setReading(true);
|
||||
try {
|
||||
const res = await api.homeAssistant.sync();
|
||||
const failed = Object.values(res.statuses).filter((s) => !s.ok);
|
||||
if (failed.length > 0) toast.error(`Couldn't read Home Assistant: ${failed[0].error ?? "no answer"}`);
|
||||
else toast.success("Read from Home Assistant.");
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setReading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function stop(id: number, w: HaWatchedEntity) {
|
||||
try {
|
||||
await api.homeAssistant.unwatch(id, w.entityId);
|
||||
toast.success(`No longer watching ${shownName(w)}.`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
const live = data?.integrations ?? [];
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
||||
<h2 className="page-title mb-0">Home Assistant</h2>
|
||||
{canAct && live.length > 0 && (
|
||||
<div className="ms-auto btn-list">
|
||||
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
|
||||
{reading ? "Reading…" : "Read now"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-secondary mb-3">
|
||||
The few things worth an alert in Home Assistant — a UPS battery, a freezer, a pump — chosen here rather than every entity it has. Each is read every five minutes and its history is kept for 35 days. It only
|
||||
reads; nothing is ever sent to Home Assistant.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{data === null && !error && <BlockSkeleton lines={4} />}
|
||||
{data && live.length === 0 && (
|
||||
<div className="card">
|
||||
<EmptyState
|
||||
title="No Home Assistant connected"
|
||||
hint="Add a Home Assistant integration with a long-lived access token (made at the bottom of your profile page in Home Assistant), then choose what to watch."
|
||||
action={user.role === "admin" ? { label: "Add Home Assistant", to: "/integrations" } : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{live.map((i) => (
|
||||
<div className="card mb-3" key={i.id}>
|
||||
<div className="card-header">
|
||||
<div>
|
||||
<h3 className="card-title">{i.name}</h3>
|
||||
<div className={`small ${i.status && !i.status.ok ? "text-red" : "text-secondary"}`}>
|
||||
{!i.enabled ? (
|
||||
"Switched off"
|
||||
) : !i.status ? (
|
||||
"Not read yet"
|
||||
) : i.status.ok ? (
|
||||
<>
|
||||
Read <TimeAgo value={i.status.at} /> · watching {i.status.entities}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Couldn’t be read: {i.status.error}. Showing what was read <TimeAgo value={i.status.at} />; its alerts are held until it can be read again.
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{canAct && i.enabled && (
|
||||
<div className="card-actions">
|
||||
<button className="btn btn-primary btn-sm" onClick={() => setPicking(i)}>
|
||||
Watch something
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{i.watched.length === 0 ? (
|
||||
<EmptyState title="Nothing is being watched yet" hint="Pick the entities that matter — a battery level, a temperature, a switch — and set the limits that should raise an alert." action={canAct && i.enabled ? { label: "Watch something", onClick: () => setPicking(i) } : undefined} />
|
||||
) : (
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Now</th>
|
||||
<th>Alert when</th>
|
||||
<th>Last changed</th>
|
||||
<th className="w-1">
|
||||
<span className="visually-hidden">Actions</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{i.watched.map((w) => {
|
||||
const problem = i.problems.some((p) => p.key.endsWith(`:${w.entityId}`));
|
||||
return (
|
||||
<tr key={w.entityId}>
|
||||
<td className="stack-wide">
|
||||
<strong>{shownName(w)}</strong>
|
||||
<div className="text-secondary small font-monospace">{w.entityId}</div>
|
||||
</td>
|
||||
<td className="stack-label" data-label="Now">
|
||||
<StateCell w={w} problem={problem} />
|
||||
</td>
|
||||
<td className="stack-label" data-label="Alert when">
|
||||
{limitsWords(w) || <span className="text-secondary">unavailable for 15 min</span>}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Last changed">
|
||||
{w.entity?.lastChanged ? <TimeAgo value={w.entity.lastChanged} /> : <span className="text-secondary">—</span>}
|
||||
</td>
|
||||
<td className="text-nowrap stack-wide">
|
||||
<div className="btn-list flex-nowrap">
|
||||
{w.entity?.value !== null && w.entity?.value !== undefined && (
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => setCharting({ id: i.id, w })}>
|
||||
History
|
||||
</button>
|
||||
)}
|
||||
{canAct && (
|
||||
<>
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => setEditing({ id: i.id, w })}>
|
||||
Limits
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void stop(i.id, w)} aria-label={`Stop watching ${shownName(w)}`}>
|
||||
Stop
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{picking && <PickDrawer integration={picking} onClose={() => setPicking(null)} onChanged={() => void load()} />}
|
||||
{editing && <EditDrawer integrationId={editing.id} w={editing.w} onClose={() => setEditing(null)} onSaved={() => void load()} />}
|
||||
{charting && <HistoryDrawer integrationId={charting.id} w={charting.w} onClose={() => setCharting(null)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,8 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
pbs: "Proxmox Backup Server",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
/** The page each kind of integration gets once it is connected. */
|
||||
@@ -41,6 +43,8 @@ const TYPE_PAGES: Record<IntegrationType, string> = {
|
||||
pbs: "/pbs",
|
||||
osticket: "/osticket",
|
||||
unifi: "/network/devices",
|
||||
npm: "/proxy-hosts",
|
||||
homeassistant: "/home-assistant",
|
||||
};
|
||||
|
||||
/** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */
|
||||
|
||||
@@ -268,6 +268,9 @@ export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
<div className="d-flex align-items-center mb-3">
|
||||
<h2 className="page-title mb-0">Inventory</h2>
|
||||
<div className="ms-auto d-flex gap-2">
|
||||
<Link to="/inventory/racks" className="btn">
|
||||
Racks
|
||||
</Link>
|
||||
<Link to="/inventory/lifecycle" className="btn">
|
||||
Lifecycle
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api } from "../api/client";
|
||||
import EmptyState from "../components/EmptyState";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { KIND_LABELS } from "../utils/inventory";
|
||||
|
||||
type Rack = Awaited<ReturnType<typeof api.inventory.racks>>["racks"][number];
|
||||
|
||||
const UNIT_H = 24;
|
||||
const KIND_COLOR: Record<string, string> = { server: "#4299e1", storage: "#38b2ac", network: "#48bb78", power: "#f59f00", client: "#a78bfa", other: "#8896ab" };
|
||||
|
||||
/** One rack, from the bottom (unit 1) up, as it stands: each piece where it says it sits, empty units between, a clash in red. */
|
||||
function RackDrawing({ rack }: { rack: Rack }) {
|
||||
const height = rack.units * UNIT_H;
|
||||
const yOf = (unit: number) => height - unit * UNIT_H; // top edge of a unit
|
||||
return (
|
||||
<div className="rack-drawing">
|
||||
<svg viewBox={`0 0 260 ${height + 4}`} width="100%" role="img" aria-label={`${rack.name}: ${rack.slots.length} pieces in ${rack.units} units${rack.slots.some((s) => s.clash) ? ", with a clash" : ""}`} style={{ maxWidth: 300 }}>
|
||||
<rect x="26" y="1" width="228" height={height + 2} fill="none" stroke="currentColor" strokeOpacity="0.5" strokeWidth="2" rx="3" />
|
||||
{Array.from({ length: rack.units }, (_, i) => i + 1).map((u) => (
|
||||
<g key={u}>
|
||||
<line x1="26" x2="254" y1={yOf(u) + 1} y2={yOf(u) + 1} stroke="currentColor" strokeOpacity="0.1" />
|
||||
<text x="22" y={yOf(u) + UNIT_H / 2 + 4} textAnchor="end" fontSize="10" fill="currentColor" fillOpacity="0.55">
|
||||
{u}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{rack.slots.map((s) => {
|
||||
const h = (s.to - s.from + 1) * UNIT_H;
|
||||
const y = yOf(s.to);
|
||||
return (
|
||||
<g key={s.assetId}>
|
||||
<title>{`${s.name}${s.model ? ` — ${s.model}` : ""} (${KIND_LABELS[s.kind as keyof typeof KIND_LABELS] ?? s.kind}, ${s.from === s.to ? `unit ${s.from}` : `units ${s.from}–${s.to}`}${s.powerWatts !== null ? `, ${s.powerWatts} W` : ""})${s.clash ? " — another piece is in the same unit" : ""}`}</title>
|
||||
<rect x="29" y={y + 2} width="222" height={h - 3} rx="3" fill={KIND_COLOR[s.kind] ?? KIND_COLOR.other} fillOpacity="0.28" stroke={s.clash ? "#f03e3e" : KIND_COLOR[s.kind] ?? KIND_COLOR.other} strokeWidth={s.clash ? 2.5 : 1.5} />
|
||||
<text x="38" y={y + Math.min(h, UNIT_H) / 2 + 4} fontSize="12" fill="currentColor" fontWeight="600">
|
||||
{s.name.length > 30 ? `${s.name.slice(0, 29)}…` : s.name}
|
||||
</text>
|
||||
{h >= UNIT_H * 2 && s.model && (
|
||||
<text x="38" y={y + UNIT_H / 2 + 20} fontSize="10.5" fill="currentColor" fillOpacity="0.75">
|
||||
{s.model.length > 34 ? `${s.model.slice(0, 33)}…` : s.model}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The racks, drawn from the inventory: each piece of hardware that says which unit it sits in (U12, or U12-13) and where (the rack's name in its location). Edit a
|
||||
* piece's location and unit on the Inventory page and it moves here. Print it for the door of the cabinet.
|
||||
*/
|
||||
export default function InventoryRacks() {
|
||||
const [racks, setRacks] = useState<Rack[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.inventory
|
||||
.racks()
|
||||
.then((res) => setRacks(res.racks))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
||||
<h2 className="page-title mb-0">Racks</h2>
|
||||
<div className="ms-auto btn-list no-print">
|
||||
<button type="button" className="btn btn-outline-secondary" onClick={() => window.print()} disabled={!racks || racks.length === 0}>
|
||||
Print
|
||||
</button>
|
||||
<Link to="/inventory" className="btn btn-outline-secondary">
|
||||
Hardware
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-secondary mb-3 no-print">
|
||||
Each piece of hardware that gives a unit (“U12”, or “U12-13” for a tall one) and the rack’s name as its location is drawn where it sits, from the bottom up. Two pieces in the same unit are shown in red.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{racks === null && !error && <BlockSkeleton lines={4} />}
|
||||
{racks !== null && racks.length === 0 && (
|
||||
<div className="card">
|
||||
<EmptyState title="No racks to draw yet" hint={<>On the <Link to="/inventory">Hardware</Link> page, give a piece a location (the rack’s name) and a rack unit such as U12, and it appears here.</>} />
|
||||
</div>
|
||||
)}
|
||||
<div className="row row-cards">
|
||||
{racks?.map((rack) => (
|
||||
<div className="col-md-6 col-xl-4" key={rack.name}>
|
||||
<div className="card h-100">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{rack.name}</h3>
|
||||
<div className="card-actions text-secondary small">
|
||||
{rack.slots.length} {rack.slots.length === 1 ? "piece" : "pieces"} · {rack.usedUnits} of {rack.units} units{rack.watts > 0 ? ` · ${rack.watts} W` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<RackDrawing rack={rack} />
|
||||
{rack.slots.some((s) => s.clash) && (
|
||||
<div className="alert alert-danger mt-3 mb-0">
|
||||
Clash: {rack.slots.filter((s) => s.clash).map((s) => `${s.name} (${s.from === s.to ? `U${s.from}` : `U${s.from}-${s.to}`})`).join(", ")} claim the same unit. Correct one of them on the Hardware page.
|
||||
</div>
|
||||
)}
|
||||
{rack.unplaced.length > 0 && (
|
||||
<div className="mt-3 small">
|
||||
<span className="text-secondary">Named here but not in a unit: </span>
|
||||
{rack.unplaced.map((u, i) => (
|
||||
<span key={u.assetId}>
|
||||
{i > 0 && ", "}
|
||||
<Link to={`/inventory?asset=${u.assetId}`}>{u.name}</Link>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<ul className="list-unstyled small mt-3 mb-0 d-print-none">
|
||||
{[...rack.slots].reverse().map((s) => (
|
||||
<li key={s.assetId}>
|
||||
<span className="text-secondary">{s.from === s.to ? `U${s.from}` : `U${s.from}–${s.to}`}</span> <Link to={`/inventory?asset=${s.assetId}`}>{s.name}</Link>
|
||||
{s.serverId !== null && (
|
||||
<>
|
||||
{" "}
|
||||
· <Link to={`/servers/${s.serverId}`}>server</Link>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -74,7 +74,28 @@ export default function MyWorkPage({ user }: { user: CurrentUser }) {
|
||||
}
|
||||
}
|
||||
|
||||
const nothing = work !== null && work.alerts.length === 0 && work.windows.length === 0 && work.updateRuns.length === 0;
|
||||
const nothing = work !== null && work.alerts.length === 0 && work.windows.length === 0 && work.updateRuns.length === 0 && work.todos.length === 0;
|
||||
|
||||
async function finish(t: MyWork["todos"][number]) {
|
||||
try {
|
||||
await api.todos.update(t.id, { done: true });
|
||||
toast.success(`Done: ${t.title}`, {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.todos.update(t.id, { done: false });
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
reload();
|
||||
}
|
||||
},
|
||||
});
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -82,7 +103,7 @@ export default function MyWorkPage({ user }: { user: CurrentUser }) {
|
||||
<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.
|
||||
What has your name on it: alerts you acknowledged or were handed, maintenance you started and update runs you started, and jobs handed to you. Whatever is about to run out is marked, and listed first.
|
||||
</div>
|
||||
|
||||
{work === null && <BlockSkeleton lines={4} />}
|
||||
@@ -146,6 +167,32 @@ export default function MyWorkPage({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{work && work.todos.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Jobs handed to you</h3>
|
||||
<div className="card-actions">
|
||||
<Link to="/todo?who=me" className="small">
|
||||
To do
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="list-group list-group-flush">
|
||||
{work.todos.map((t) => (
|
||||
<li key={t.id} className="list-group-item d-flex gap-3 align-items-start">
|
||||
<input type="checkbox" className="form-check-input mt-1" aria-label={`Done: ${t.title}`} checked={false} onChange={() => void finish(t)} />
|
||||
<div className="me-auto">
|
||||
<div className="fw-bold">{t.title}</div>
|
||||
{t.detail && <div className="text-secondary small">{t.detail}</div>}
|
||||
{t.target && <div className="small text-secondary">about {t.target.name}</div>}
|
||||
</div>
|
||||
{t.dueDate && <span className={`small ${t.overdue ? "text-red" : t.dueSoon ? "text-yellow" : "text-secondary"}`}>{t.overdue ? "overdue · " : ""}{t.dueDate}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{work && work.windows.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
|
||||
@@ -8,6 +8,9 @@ import TimeAgo from "../components/TimeAgo";
|
||||
import ViewTabs from "../components/ViewTabs";
|
||||
import SilenceButton from "../components/SilenceButton";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
import NetworkDiagram from "../components/NetworkDiagram";
|
||||
import NotesCard from "../components/NotesCard";
|
||||
import DetailDrawer from "../components/DetailDrawer";
|
||||
import CopyButton from "../components/CopyButton";
|
||||
import EmptyState, { EmptyRow } from "../components/EmptyState";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
@@ -62,12 +65,14 @@ function StateBadge({ d }: { d: NetworkDevice }) {
|
||||
export default function NetworkDevices({ user }: { user: CurrentUser }) {
|
||||
const canAct = user.role === "admin" || user.role === "operator";
|
||||
const [params] = useSearchParams();
|
||||
const view = params.get("view") === "wifi" ? "wifi" : "devices";
|
||||
const asked = params.get("view");
|
||||
const view = asked === "wifi" ? "wifi" : asked === "diagram" ? "diagram" : "devices";
|
||||
const [data, setData] = useState<NetworkOverview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reading, setReading] = useState(false);
|
||||
const [kind, setKind] = useState<"all" | NetworkDeviceKind>("all");
|
||||
const [status, setStatus] = useState<"all" | "problem">("all");
|
||||
const [noting, setNoting] = useState<NetworkDevice | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
return api.network
|
||||
@@ -120,6 +125,7 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
|
||||
label="Network devices view"
|
||||
tabs={[
|
||||
{ to: "/network/devices", label: "Devices", active: view === "devices" },
|
||||
{ to: "/network/devices?view=diagram", label: "Diagram", active: view === "diagram" },
|
||||
{ to: "/network/devices?view=wifi", label: "Networks & Wi-Fi", active: view === "wifi" },
|
||||
]}
|
||||
/>
|
||||
@@ -324,6 +330,9 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
|
||||
<div className="btn-list flex-nowrap align-items-center">
|
||||
{!d.inMaintenance && <SilenceButton target={{ type: "device", id: d.id, name: d.name }} onDone={() => void load()} />}
|
||||
<RunbookEntry targetType="device" targetId={d.id} targetName={d.name} canEdit={canAct} offerAdd />
|
||||
<button type="button" className="btn btn-link btn-sm p-0" onClick={() => setNoting(d)}>
|
||||
Notes
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
@@ -345,7 +354,22 @@ export default function NetworkDevices({ user }: { user: CurrentUser }) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{data && data.integrations.length > 0 && view === "diagram" && (
|
||||
<>
|
||||
<div className="mb-2 no-print">
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => window.print()}>
|
||||
Print
|
||||
</button>
|
||||
</div>
|
||||
<NetworkDiagram devices={devices} />
|
||||
</>
|
||||
)}
|
||||
{data && data.integrations.length > 0 && view === "wifi" && <NetworksAndWifi data={data} />}
|
||||
{noting && (
|
||||
<DetailDrawer title={noting.name} subtitle="Notes" onClose={() => setNoting(null)}>
|
||||
<NotesCard targetType="device" targetId={noting.id} canEdit={canAct} bare />
|
||||
</DetailDrawer>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type CurrentUser, type IntegrationProblem, type NpmHost, type NpmOverview } from "../api/client";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
import Pagination from "../components/Pagination";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import EmptyState, { EmptyRow } from "../components/EmptyState";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import { usePagination } from "../hooks/usePagination";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { formatDate } from "../utils/date";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
type Row = NpmHost & { integrationName: string; domain: string; target: string; certDays: number | null; certName: string; statusRank: number; serverName: string };
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const daysLeft = (iso: string | null): number | null => (iso && Number.isFinite(Date.parse(iso)) ? Math.floor((Date.parse(iso) - Date.now()) / DAY_MS) : null);
|
||||
|
||||
function StatusBadge({ h }: { h: Row }) {
|
||||
if (!h.enabled) return <span className="badge bg-secondary-lt text-secondary">Switched off</span>;
|
||||
if (!h.online)
|
||||
return (
|
||||
<span className="badge bg-red-lt text-red" title={h.error ?? "Nginx Proxy Manager could not set this host up"}>
|
||||
Not working
|
||||
</span>
|
||||
);
|
||||
return <span className="badge bg-green-lt text-green">Working</span>;
|
||||
}
|
||||
|
||||
function CertBadge({ h }: { h: Row }) {
|
||||
if (!h.certificate) return <span className="text-secondary">{h.sslForced ? "—" : "No certificate"}</span>;
|
||||
const d = h.certDays;
|
||||
const color = d === null ? "secondary" : d < 0 ? "red" : d <= 3 ? "red" : d <= 14 ? "yellow" : "green";
|
||||
const words = d === null ? "no end date" : d < 0 ? `ran out ${-d} ${d === -1 ? "day" : "days"} ago` : d === 0 ? "ends today" : `${d} ${d === 1 ? "day" : "days"} left`;
|
||||
return (
|
||||
<span title={h.certificate.expiresAt ? `${h.certificate.name} — ends ${formatDate(new Date(h.certificate.expiresAt))}` : h.certificate.name}>
|
||||
<span className={`badge bg-${color}-lt text-${color}`}>{words}</span>
|
||||
<div className="text-secondary small">{h.certificate.name}</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What Nginx Proxy Manager proxies: each name people use, where it forwards to (and which server that is), its certificate and whether NPM could set it up. Read
|
||||
* from NPM when the page is opened (and at most once a minute); nothing here changes anything in NPM.
|
||||
*/
|
||||
export default function ProxyHosts({ user }: { user: CurrentUser }) {
|
||||
const [data, setData] = useState<NpmOverview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reading, setReading] = useState(false);
|
||||
|
||||
const load = useCallback(
|
||||
(refresh = false) =>
|
||||
api.npm
|
||||
.overview(refresh)
|
||||
.then((res) => {
|
||||
setData(res);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(readableError(err))),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const timer = setInterval(() => void load(), 60_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [load]);
|
||||
|
||||
async function readNow() {
|
||||
setReading(true);
|
||||
await load(true);
|
||||
setReading(false);
|
||||
toast.success("Read from Nginx Proxy Manager.");
|
||||
}
|
||||
|
||||
const rows: Row[] = useMemo(
|
||||
() =>
|
||||
(data?.integrations ?? []).flatMap((i) =>
|
||||
i.hosts.map((h) => ({
|
||||
...h,
|
||||
integrationName: i.name,
|
||||
domain: h.domains.join(", "),
|
||||
target: `${h.forwardScheme}://${h.forwardHost}${h.forwardPort !== null ? `:${h.forwardPort}` : ""}`,
|
||||
certDays: daysLeft(h.certificate?.expiresAt ?? null),
|
||||
certName: h.certificate?.name ?? "",
|
||||
statusRank: !h.enabled ? 2 : h.online ? 1 : 0,
|
||||
serverName: h.server?.name ?? "",
|
||||
})),
|
||||
),
|
||||
[data],
|
||||
);
|
||||
const tableSearch = useTableSearch(rows);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "statusRank", "asc", { url: true });
|
||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
||||
|
||||
const problems: (IntegrationProblem & { integration: string })[] = (data?.integrations ?? []).flatMap((i) => i.problems.map((p) => ({ ...p, integration: i.name })));
|
||||
const soon = rows.filter((h) => h.enabled && h.certDays !== null && h.certDays <= 14).length;
|
||||
const noNpm = data !== null && data.integrations.length === 0;
|
||||
|
||||
function exportCsv() {
|
||||
downloadCsv(
|
||||
"proxy-hosts.csv",
|
||||
["Names", "Forwards to", "Server", "Status", "Certificate", "Certificate ends", "Force HTTPS", "Nginx Proxy Manager"],
|
||||
(sorted ?? []).map((h) => [h.domain, h.target, h.serverName, !h.enabled ? "switched off" : h.online ? "working" : "not working", h.certName, h.certificate?.expiresAt ?? "", h.sslForced ? "yes" : "no", h.integrationName]),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
||||
<h2 className="page-title mb-0">Proxy hosts</h2>
|
||||
{(user.role === "admin" || user.role === "operator") && data && data.integrations.length > 0 && (
|
||||
<div className="ms-auto btn-list">
|
||||
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
|
||||
{reading ? "Reading…" : "Read now"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-secondary mb-3">
|
||||
What Nginx Proxy Manager serves: the name, where it forwards to, the certificate and whether NPM could set it up. It only reads — nothing here changes anything in NPM. A certificate in its last
|
||||
two weeks, or a host NPM can’t set up, is an alert.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{data === null && !error && <BlockSkeleton lines={4} />}
|
||||
|
||||
{noNpm && (
|
||||
<div className="card">
|
||||
<EmptyState
|
||||
title="No Nginx Proxy Manager connected"
|
||||
hint="Add an Nginx Proxy Manager integration — a user that may only view proxy hosts and certificates is enough — and what it serves appears here."
|
||||
action={user.role === "admin" ? { label: "Add Nginx Proxy Manager", to: "/integrations" } : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data && data.integrations.length > 0 && (
|
||||
<div className="mb-3 small">
|
||||
{data.integrations.map((i) => (
|
||||
<div key={i.id} className={i.error ? "text-red" : "text-secondary"}>
|
||||
<strong>{i.name}</strong>
|
||||
{i.error ? <> — couldn’t be read: {i.error}</> : <> — read <TimeAgo value={i.readAt} />{i.version ? ` · version ${i.version}` : ""} · {i.hosts.length} {i.hosts.length === 1 ? "host" : "hosts"}</>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data && data.integrations.some((i) => !i.error) && (
|
||||
<>
|
||||
<div className="row row-cards mb-3">
|
||||
{[
|
||||
{ label: "Proxy hosts", value: rows.length, color: "" },
|
||||
{ label: "Not working", value: rows.filter((h) => h.enabled && !h.online).length, color: rows.some((h) => h.enabled && !h.online) ? "text-red" : "text-green" },
|
||||
{ label: "Certificates ending within 14 days", value: soon, color: soon > 0 ? "text-yellow" : "text-green" },
|
||||
{ label: "Switched off", value: rows.filter((h) => !h.enabled).length, color: "" },
|
||||
].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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{problems.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Needs attention</h3>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{problems.map((p) => (
|
||||
<div className="list-group-item d-flex align-items-center gap-2" key={p.key}>
|
||||
<span className={`badge ${p.severity === "critical" ? "bg-red-lt text-red" : "bg-yellow-lt text-yellow"}`}>{p.severity === "critical" ? "Critical" : "Warning"}</span>
|
||||
<span>{p.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card">
|
||||
<TableToolbar search={tableSearch.query} onSearch={tableSearch.setQuery} placeholder="Search names, targets, servers…" shown={sorted?.length} total={rows.length} onExport={exportCsv} exportDisabled={!sorted || sorted.length === 0} />
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<thead>
|
||||
<tr>
|
||||
<SortableTh<Row> label="Status" sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Name" sortKeyName="domain" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Forwards to" sortKeyName="target" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(pageItems ?? []).length === 0 && <EmptyRow colSpan={4} title="No proxy hosts" filtered={tableSearch.active ? () => tableSearch.setQuery("") : undefined} />}
|
||||
{(pageItems ?? []).map((h) => (
|
||||
<tr key={`${h.integrationName}-${h.id}`}>
|
||||
<td>
|
||||
<StatusBadge h={h} />
|
||||
{h.error && h.enabled && <div className="text-secondary small">{h.error.slice(0, 120)}</div>}
|
||||
</td>
|
||||
<td className="stack-wide">
|
||||
{h.domains.map((d, i) => (
|
||||
<div key={i}>
|
||||
<a href={`${h.sslForced || h.certificate ? "https" : "http"}://${d}`} target="_blank" rel="noopener noreferrer">
|
||||
<strong>{d}</strong>
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
{data && data.integrations.length > 1 && <div className="text-secondary small">{h.integrationName}</div>}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Forwards to">
|
||||
<span className="font-monospace">{h.target}</span>
|
||||
{h.server && (
|
||||
<div className="small">
|
||||
<Link to={`/servers/${h.server.id}`}>{h.server.name}</Link>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Certificate">
|
||||
<CertBadge h={h} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import ServerPorts from "../components/ServerPorts";
|
||||
import ServerTrends from "../components/ServerTrends";
|
||||
import UptimeHistory from "../components/UptimeHistory";
|
||||
import NotesCard from "../components/NotesCard";
|
||||
import ServerActivity from "../components/ServerActivity";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
@@ -705,6 +706,17 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
<dd className="col-7">
|
||||
<UptimeRibbon kind="servers" id={server.id} name={server.name} />
|
||||
</dd>
|
||||
{detail.os && (
|
||||
<>
|
||||
<dt className="col-5">System</dt>
|
||||
<dd className="col-7">
|
||||
{detail.os.product}
|
||||
{detail.os.state === "ended" && <span className="badge bg-red-lt text-red ms-2" title={`Support ended on ${detail.os.endsOn}`}>support ended</span>}
|
||||
{detail.os.state === "soon" && <span className="badge bg-yellow-lt text-yellow ms-2" title={`Support ends on ${detail.os.endsOn}`}>support ends in {detail.os.daysLeft} {detail.os.daysLeft === 1 ? "day" : "days"}</span>}
|
||||
{detail.os.state === "ok" && detail.os.endsOn && <div className="text-secondary small">supported until {detail.os.endsOn}</div>}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="col-5">Runs on</dt>
|
||||
<dd className="col-7">
|
||||
<RunsOn serverId={server.id} parent={detail.relations.parent} noParent={server.noParent} canEdit={isAdmin} onChanged={() => void loadDetail()} />
|
||||
@@ -752,6 +764,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NotesCard targetType="server" targetId={server.id} canEdit={canEditTasks} />
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Runbooks</h3>
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type CurrentUser, type TodoInput, type TodoItem } from "../api/client";
|
||||
import DetailDrawer from "../components/DetailDrawer";
|
||||
import EmptyState from "../components/EmptyState";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { refreshMyWork } from "../hooks/useMyWork";
|
||||
import { formatDate } from "../utils/date";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
|
||||
type Person = { id: number; name: string; role: string };
|
||||
type Place = { type: "server" | "device"; id: number; name: string };
|
||||
|
||||
const today = () => new Date().toISOString().slice(0, 10);
|
||||
|
||||
function dueWords(t: TodoItem): { text: string; className: string } | null {
|
||||
if (!t.dueDate) return null;
|
||||
const days = Math.round((Date.parse(`${t.dueDate}T00:00:00Z`) - Date.parse(`${today()}T00:00:00Z`)) / 86_400_000);
|
||||
if (t.doneAt) return { text: formatDate(new Date(`${t.dueDate}T12:00:00Z`)), className: "text-secondary" };
|
||||
if (days < 0) return { text: `${-days} ${days === -1 ? "day" : "days"} overdue`, className: "text-red" };
|
||||
if (days === 0) return { text: "due today", className: "text-yellow" };
|
||||
if (days === 1) return { text: "due tomorrow", className: "text-yellow" };
|
||||
return { text: `due ${formatDate(new Date(`${t.dueDate}T12:00:00Z`))}`, className: days <= 7 ? "text-yellow" : "text-secondary" };
|
||||
}
|
||||
|
||||
/** The same form to make a job and to change one. */
|
||||
function JobForm({ initial, people, places, busy, submitLabel, onSubmit, onCancel }: { initial: TodoInput & { targetKey?: string }; people: Person[]; places: Place[]; busy: boolean; submitLabel: string; onSubmit: (v: TodoInput) => void; onCancel?: () => void }) {
|
||||
const [title, setTitle] = useState(initial.title);
|
||||
const [detail, setDetail] = useState(initial.detail ?? "");
|
||||
const [due, setDue] = useState(initial.dueDate ?? "");
|
||||
const [who, setWho] = useState(initial.assigneeId ? String(initial.assigneeId) : "");
|
||||
const [about, setAbout] = useState(initial.targetType && initial.targetId ? `${initial.targetType}:${initial.targetId}` : "");
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const [type, id] = about.split(":");
|
||||
onSubmit({ title: title.trim(), detail: detail.trim() || null, dueDate: due || null, assigneeId: who ? Number(who) : null, targetType: about ? (type as "server" | "device") : null, targetId: about ? Number(id) : null });
|
||||
}}
|
||||
>
|
||||
<div className="row g-3">
|
||||
<div className="col-12">
|
||||
<label className="form-label" htmlFor="todo-title">
|
||||
What is to be done
|
||||
</label>
|
||||
<input id="todo-title" className="form-control" maxLength={160} required value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Replace the UPS battery" autoFocus />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="todo-due">
|
||||
By <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<input id="todo-due" type="date" className="form-control" value={due} onChange={(e) => setDue(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="todo-who">
|
||||
For <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<select id="todo-who" className="form-select" value={who} onChange={(e) => setWho(e.target.value)}>
|
||||
<option value="">Nobody in particular</option>
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="todo-about">
|
||||
About <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<select id="todo-about" className="form-select" value={about} onChange={(e) => setAbout(e.target.value)}>
|
||||
<option value="">Nothing in particular</option>
|
||||
<optgroup label="Servers">
|
||||
{places.filter((p) => p.type === "server").map((p) => (
|
||||
<option key={`s${p.id}`} value={`server:${p.id}`}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
{places.some((p) => p.type === "device") && (
|
||||
<optgroup label="Network devices">
|
||||
{places.filter((p) => p.type === "device").map((p) => (
|
||||
<option key={`d${p.id}`} value={`device:${p.id}`}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<label className="form-label" htmlFor="todo-detail">
|
||||
Details <span className="text-secondary">(optional)</span>
|
||||
</label>
|
||||
<textarea id="todo-detail" className="form-control" rows={3} maxLength={2000} value={detail} onChange={(e) => setDetail(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || title.trim() === ""}>
|
||||
{busy ? "Saving…" : submitLabel}
|
||||
</button>
|
||||
{onCancel && (
|
||||
<button type="button" className="btn" onClick={onCancel}>
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The small jobs of a homelab, written down: what, by when, for whom and about which server or device. A job with a day is in Coming up; one handed to somebody is in
|
||||
* their My work. Ticking one off keeps it (under Done), and it can be brought back.
|
||||
*/
|
||||
export default function Todo({ user }: { user: CurrentUser }) {
|
||||
const canEdit = user.role === "admin" || user.role === "operator";
|
||||
const [params, setParams] = useSearchParams();
|
||||
const mineOnly = params.get("who") === "me";
|
||||
const [list, setList] = useState<TodoItem[] | null>(null);
|
||||
const [people, setPeople] = useState<Person[]>([]);
|
||||
const [places, setPlaces] = useState<Place[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [editing, setEditing] = useState<TodoItem | null>(null);
|
||||
const [showDone, setShowDone] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.todos
|
||||
.list()
|
||||
.then((res) => {
|
||||
setList(res.todos);
|
||||
setPeople(res.people);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
refreshMyWork();
|
||||
}
|
||||
useEffect(load, []);
|
||||
useEffect(() => {
|
||||
// What a job can be about: the servers, and the network devices when there are any.
|
||||
Promise.all([api.servers.list().catch(() => null), api.network.overview().catch(() => null)]).then(([s, n]) =>
|
||||
setPlaces([...(s?.servers ?? []).map((x) => ({ type: "server" as const, id: x.id, name: x.name })), ...(n?.devices ?? []).map((x) => ({ type: "device" as const, id: x.id, name: x.name }))]),
|
||||
);
|
||||
}, []);
|
||||
|
||||
const visible = useMemo(() => (list ?? []).filter((t) => !mineOnly || t.assignee?.id === user.id), [list, mineOnly, user.id]);
|
||||
const open = visible.filter((t) => !t.doneAt);
|
||||
const done = visible.filter((t) => t.doneAt);
|
||||
|
||||
async function create(v: TodoInput) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.todos.create(v);
|
||||
toast.success("Added.");
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(t: TodoItem, v: TodoInput) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.todos.update(t.id, v);
|
||||
setEditing(null);
|
||||
toast.success("Saved.");
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function tick(t: TodoItem, finished: boolean) {
|
||||
try {
|
||||
await api.todos.update(t.id, { done: finished });
|
||||
if (finished) {
|
||||
toast.success(`Done: ${t.title}`, {
|
||||
label: "Undo",
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.todos.update(t.id, { done: false });
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
} finally {
|
||||
load();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(t: TodoItem) {
|
||||
setEditing(null);
|
||||
await removeWithUndo({
|
||||
remove: () => api.todos.remove(t.id),
|
||||
restore: () => api.todos.create({ title: t.title, detail: t.detail, dueDate: t.dueDate, assigneeId: t.assignee?.id ?? null, targetType: t.target?.type ?? null, targetId: t.target?.id ?? null }).then((r) => (t.doneAt ? api.todos.update(r.todo.id, { done: true }) : r)),
|
||||
message: `Removed "${t.title}".`,
|
||||
reload: load,
|
||||
});
|
||||
}
|
||||
|
||||
const row = (t: TodoItem) => {
|
||||
const due = dueWords(t);
|
||||
return (
|
||||
<li key={t.id} className="list-group-item d-flex gap-3 align-items-start">
|
||||
<input type="checkbox" className="form-check-input mt-1" aria-label={t.doneAt ? `Bring back: ${t.title}` : `Done: ${t.title}`} checked={!!t.doneAt} disabled={!canEdit} onChange={() => void tick(t, !t.doneAt)} />
|
||||
<div className="me-auto">
|
||||
<div className={t.doneAt ? "text-decoration-line-through text-secondary" : "fw-bold"}>{t.title}</div>
|
||||
{t.detail && <div className="text-secondary small" style={{ whiteSpace: "pre-wrap" }}>{t.detail}</div>}
|
||||
<div className="small d-flex flex-wrap gap-2 mt-1">
|
||||
{due && <span className={due.className}>{due.text}</span>}
|
||||
{t.assignee && <span className="badge bg-blue-lt text-blue">{t.assignee.name}</span>}
|
||||
{t.target && <Link to={t.target.type === "server" ? `/servers/${t.target.id}` : "/network/devices"}>{t.target.name}</Link>}
|
||||
{t.doneAt && (
|
||||
<span className="text-secondary">
|
||||
done <TimeAgo value={t.doneAt} />
|
||||
{t.doneBy ? ` by ${t.doneBy}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => setEditing(t)}>
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
||||
<h2 className="page-title mb-0">To do</h2>
|
||||
<div className="ms-auto btn-group btn-group-sm" role="group" aria-label="Whose jobs">
|
||||
<button type="button" className={`btn ${!mineOnly ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={!mineOnly} onClick={() => setParams({})}>
|
||||
Everyone’s
|
||||
</button>
|
||||
<button type="button" className={`btn ${mineOnly ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={mineOnly} onClick={() => setParams({ who: "me" })}>
|
||||
Handed to me
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-secondary mb-3">
|
||||
The small jobs: replace the battery, move the NAS to the new switch. A job with a day is in <Link to="/coming-up?kinds=todo">Coming up</Link>; one handed to somebody is in their <Link to="/my-work">My work</Link>.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
{canEdit && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Add a job</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<JobForm key={list?.length ?? 0} initial={{ title: "" }} people={people} places={places} busy={busy} submitLabel="Add" onSubmit={(v) => void create(v)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{list === null && !error && <BlockSkeleton lines={3} />}
|
||||
{list !== null && open.length === 0 && (
|
||||
<div className="card mb-3">
|
||||
<EmptyState title={mineOnly ? "Nothing is handed to you" : "Nothing to do"} hint={canEdit ? "Add a job above, and give it a day if it has one." : "Nothing has been written down."} />
|
||||
</div>
|
||||
)}
|
||||
{open.length > 0 && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">To do ({open.length})</h3>
|
||||
</div>
|
||||
<ul className="list-group list-group-flush">{open.map(row)}</ul>
|
||||
</div>
|
||||
)}
|
||||
{done.length > 0 && (
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Done ({done.length})</h3>
|
||||
<div className="card-actions">
|
||||
<button type="button" className="btn btn-sm" onClick={() => setShowDone((v) => !v)}>
|
||||
{showDone ? "Hide" : "Show"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{showDone && <ul className="list-group list-group-flush">{done.map(row)}</ul>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing && (
|
||||
<DetailDrawer title="Edit the job" subtitle={editing.title} onClose={() => setEditing(null)}>
|
||||
<JobForm
|
||||
initial={{ title: editing.title, detail: editing.detail, dueDate: editing.dueDate, assigneeId: editing.assignee?.id ?? null, targetType: editing.target?.type ?? null, targetId: editing.target?.id ?? null }}
|
||||
people={people}
|
||||
places={places}
|
||||
busy={busy}
|
||||
submitLabel="Save"
|
||||
onSubmit={(v) => void save(editing, v)}
|
||||
onCancel={() => setEditing(null)}
|
||||
/>
|
||||
<hr />
|
||||
<button type="button" className="btn btn-outline-danger" onClick={() => void remove(editing)}>
|
||||
Remove it
|
||||
</button>
|
||||
</DetailDrawer>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,8 @@ const INTEGRATION_NAMES: Record<string, string> = {
|
||||
pbs: "Proxmox Backup Server",
|
||||
osticket: "osTicket",
|
||||
unifi: "UniFi",
|
||||
npm: "Nginx Proxy Manager",
|
||||
homeassistant: "Home Assistant",
|
||||
};
|
||||
|
||||
function ColorList({
|
||||
|
||||
@@ -82,7 +82,7 @@ const DIGEST_DAYS: { value: number; label: string }[] = [
|
||||
{ value: 6, label: "Saturday" },
|
||||
{ value: 0, label: "Sunday" },
|
||||
];
|
||||
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10 };
|
||||
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10, osSupportWarnDays: 90 };
|
||||
const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, day: 1, time: "08:00" };
|
||||
|
||||
type TestResult = { ok: boolean; message: string } | null;
|
||||
@@ -735,6 +735,15 @@ export default function NotificationSettings() {
|
||||
hint="From each agent server's own history, shown on the Alerts page and dashboard (not sent as a notification). Needs a few days of steady growth to say anything. 0 turns it off."
|
||||
onChange={(v) => setHealthChecks((h) => ({ ...h, diskForecastDays: v }))}
|
||||
/>
|
||||
<NumberField
|
||||
label="Flag an operating system whose support ends within"
|
||||
value={healthChecks.osSupportWarnDays}
|
||||
min={0}
|
||||
max={365}
|
||||
unit="days"
|
||||
hint="From what each agent says it runs (Linux agent 7, Windows agent 6, or later) and the vendors' published end-of-support dates. Shown on the Alerts page and the server's page (not sent as a notification); one whose support has ended is a warning. 0 turns it off."
|
||||
onChange={(v) => setHealthChecks((h) => ({ ...h, osSupportWarnDays: v }))}
|
||||
/>
|
||||
<NumberField
|
||||
label="Alert when a network device is offline for"
|
||||
value={healthChecks.deviceOfflineMinutes}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type CurrentUser, type DependenciesResponse, type DependencyNode } from "../api/client";
|
||||
import { api, type CurrentUser, type DependenciesResponse, type DependencyNode, type DependencySuggestions } from "../api/client";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { removeWithUndo } from "../utils/undoable";
|
||||
@@ -49,12 +49,48 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
|
||||
const [from, setFrom] = useState("");
|
||||
const [to, setTo] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [offered, setOffered] = useState<DependencySuggestions | null>(null);
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.dependencies
|
||||
.list()
|
||||
.then(setData)
|
||||
.catch((err) => setError(readableError(err)));
|
||||
api.dependencies
|
||||
.suggestions()
|
||||
.then(setOffered)
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
async function addOffered(keys: string[]) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.dependencies.addSuggestions(keys);
|
||||
toast.success(res.added.length === 1 ? `${res.added[0].from} now needs ${res.added[0].to}.` : `Added ${res.added.length} dependencies.`);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function hideOffered(keys: string[]) {
|
||||
try {
|
||||
setOffered(await api.dependencies.dismissSuggestions(keys));
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreOffered() {
|
||||
try {
|
||||
setOffered(await api.dependencies.restoreSuggestions());
|
||||
setShowHidden(false);
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
@@ -101,6 +137,69 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
{offered && (offered.suggestions.length > 0 || offered.dismissed.length > 0) && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Suggested</h3>
|
||||
{canEdit && offered.suggestions.length > 1 && (
|
||||
<div className="card-actions">
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={busy} onClick={() => void addOffered(offered.suggestions.map((s) => s.key))}>
|
||||
Add all {offered.suggestions.length}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-body text-secondary small pb-0">Worked out from where each service is reached: when that is a server’s own address, the service most likely runs there. Nothing is written until you add it.</div>
|
||||
{offered.suggestions.length > 0 ? (
|
||||
<ul className="list-group list-group-flush">
|
||||
{offered.suggestions.map((s) => (
|
||||
<li key={s.key} className="list-group-item d-flex flex-wrap align-items-center gap-2">
|
||||
<div className="me-auto">
|
||||
<strong>{s.from.name}</strong> <span className="text-secondary">needs</span> <strong>{s.to.name}</strong>
|
||||
<div className="text-secondary small">{s.reason}</div>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<>
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={busy} onClick={() => void addOffered([s.key])}>
|
||||
Add
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={() => void hideOffered([s.key])}>
|
||||
Not that
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<div className="card-body text-secondary">Nothing more to suggest.</div>
|
||||
)}
|
||||
{offered.dismissed.length > 0 && (
|
||||
<div className="card-footer small">
|
||||
<button type="button" className="btn btn-link btn-sm p-0" onClick={() => setShowHidden((v) => !v)}>
|
||||
{showHidden ? "Hide" : "Show"} the {offered.dismissed.length} you said no to
|
||||
</button>
|
||||
{showHidden && (
|
||||
<>
|
||||
<ul className="mb-2 mt-2">
|
||||
{offered.dismissed.map((s) => (
|
||||
<li key={s.key}>
|
||||
{s.from.name} needs {s.to.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{canEdit && (
|
||||
<button type="button" className="btn btn-sm" onClick={() => void restoreOffered()}>
|
||||
Offer them again
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canEdit && (
|
||||
<form className="card mb-3" onSubmit={add}>
|
||||
<div className="card-header">
|
||||
|
||||
Reference in new issue
Block a user