Files
Homelab-manager/web/src/pages/Synology.tsx
T
bobbanandClaude Sonnet 5 f4274c1ad8 Make every table sortable and exportable to CSV
Applies the useSortable/SortableTh infrastructure introduced in the
Diagnostic Log commit to the rest of the app's tables: Audit Log,
Users, Servers (manage table), server task tables (grouped by
schedule type, on both the all-servers and per-server views), DNS
providers/zones/records, Docker containers, Gitea repos, Integrations
(manage table), IP Addresses, Proxmox guests, Secrets (already had
CSV, gained sorting), Semaphore templates, Synology volumes/disks, and
Tailscale devices.

Every column header is now click-to-sort (again on the raw field, not
its formatted display -- a byte count sorts numerically even though
the cell shows "1.2 GB", a date sorts chronologically even though the
cell shows "5d 15h 2m"), and every table got an "Export CSV" button
next to its Refresh button, exporting whatever's currently
sorted/filtered via the existing downloadCsv util.

Grouped tables (ServerTaskTable renders one sub-table per schedule
type) can't call the useSortable hook per group without breaking the
Rules of Hooks, so extracted its comparison core as a standalone
sortItems() function, driven by one shared sort-state pair at the
component's top level and applied per group.

Deliberately left two small (1-6 row) tables embedded inside stat
cards unsorted -- Proxmox's per-node storage list and ServerDetail's
agent-reported disk list -- since they're secondary detail inside an
already-scannable card, not primary list content; happy to add if
useful in practice.

Verified the shared sort core (sortItems) directly: numeric-aware
string compare (so "item2" sorts before "item10"), numbers, booleans,
and that null/undefined always sort to the end regardless of
direction.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 21:54:36 +02:00

396 lines
16 KiB
TypeScript

import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
api,
type CurrentUser,
type IntegrationSummary,
type SynologyStorageResponse,
type SynologySystemInfo,
type SynologyVolume,
type SynologyDisk,
} from "../api/client";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { downloadCsv } from "../utils/csv";
function healthBadge(status: string) {
return status === "normal" ? (
<span className="badge bg-green-lt text-green">Normal</span>
) : (
<span className="badge bg-red-lt text-red">{status}</span>
);
}
function formatBytes(bytes: number | null): string {
if (bytes === null) return "—";
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${value.toFixed(1)} ${units[unit]}`;
}
// DSM reports uptime as the raw output of the Linux `uptime` command (e.g.
// "20:13:21 up 5 days, 15:02, 0 users, load average: ..."); pull out the
// day/hour/minute portion and fall back to the raw string if the format
// doesn't match what we expect.
function formatUptime(raw: string | null): string {
if (!raw) return "—";
const match = raw.match(/up\s+(?:(\d+)\s+days?,\s+)?(?:(\d+):(\d+)|(\d+)\s*min)/);
if (!match) return raw;
const days = match[1] ? Number(match[1]) : 0;
const hours = match[2] ? Number(match[2]) : 0;
const minutes = match[3] ? Number(match[3]) : match[4] ? Number(match[4]) : 0;
const parts: string[] = [];
if (days) parts.push(`${days}d`);
if (days || hours) parts.push(`${hours}h`);
parts.push(`${minutes}m`);
return parts.join(" ");
}
export default function Synology({ user: _user }: { user: CurrentUser }) {
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<SynologyStorageResponse | null>(null);
const [loading, setLoading] = useState(false);
const [system, setSystem] = useState<SynologySystemInfo | null>(null);
const [systemError, setSystemError] = useState<string | null>(null);
const [loadingSystem, setLoadingSystem] = useState(false);
useEffect(() => {
api.integrations
.list()
.then((res) => {
const synologyIntegrations = res.integrations.filter((i) => i.type === "synology");
setIntegrations(synologyIntegrations);
if (!selectedId && synologyIntegrations.length > 0) setSelectedId(synologyIntegrations[0].id);
})
.catch((err) => setError(err instanceof Error ? err.message : String(err)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selected = integrations?.find((i) => i.id === selectedId) ?? null;
function loadStorage(id: number) {
setLoading(true);
setError(null);
api.integrations.synology
.storage(id)
.then((res) => setData(res))
.catch((err) => setError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false));
}
function loadSystem(id: number) {
setLoadingSystem(true);
setSystemError(null);
api.integrations.synology
.system(id)
.then((res) => setSystem(res))
.catch((err) => setSystemError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoadingSystem(false));
}
useEffect(() => {
if (selected?.enabled) {
loadStorage(selected.id);
loadSystem(selected.id);
} else {
setData(null);
setSystem(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedId]);
const { sorted: sortedVolumes, sortKey: volumeSortKey, sortDir: volumeSortDir, requestSort: requestVolumeSort } = useSortable(
data?.volumes,
);
const { sorted: sortedDisks, sortKey: diskSortKey, sortDir: diskSortDir, requestSort: requestDiskSort } = useSortable(data?.disks);
function exportVolumesCsv() {
if (!sortedVolumes) return;
downloadCsv(
"synology-volumes.csv",
["Volume", "Type", "Used", "Total", "Status"],
sortedVolumes.map((v) => [v.id, v.deviceType, formatBytes(v.sizeUsed), formatBytes(v.sizeTotal), v.status]),
);
}
function exportDisksCsv() {
if (!sortedDisks) return;
downloadCsv(
"synology-disks.csv",
["Disk", "Device", "Temp", "S.M.A.R.T.", "Status"],
sortedDisks.map((d) => [d.name, d.device, d.temp ?? "", d.smartStatus, d.status]),
);
}
return (
<>
<h2 className="page-title mb-3">Synology</h2>
{error && <div className="alert alert-danger">{error}</div>}
{integrations?.length === 0 ? (
<div className="card">
<div className="card-body text-secondary">
No Synology integration configured yet. <Link to="/integrations">Add one under Integrations</Link>.
</div>
</div>
) : (
<>
{integrations && integrations.length > 1 && (
<div className="mb-3" style={{ maxWidth: 320 }}>
<select
className="form-select"
value={selectedId ?? ""}
onChange={(e) => setSelectedId(Number(e.target.value))}
>
{integrations.map((i) => (
<option key={i.id} value={i.id} disabled={!i.enabled}>
{i.name}
{!i.enabled ? " — disabled" : ""}
</option>
))}
</select>
</div>
)}
{selected && !selected.enabled ? (
<div className="card">
<div className="card-body text-secondary">
"{selected.name}" is disabled. Enable it under Integrations → Manage integrations to see its
storage.
</div>
</div>
) : (
<div className="row g-3">
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">System</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadSystem(selected.id)}
disabled={loadingSystem}
>
{loadingSystem ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="card-body">
{systemError ? (
<div className="text-danger">{systemError}</div>
) : (
<div className="row g-3">
<div className="col-6 col-md-3">
<div className="text-secondary">Hostname</div>
<div>{system?.hostname ?? "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Model</div>
<div>{system?.model ?? "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Uptime</div>
<div>{formatUptime(system?.uptime ?? null)}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">IP addresses</div>
<div>{system?.ipAddresses.length ? system.ipAddresses.join(", ") : "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">CPU</div>
<div>
{system?.cpu.loadPercent !== null && system?.cpu.loadPercent !== undefined
? `${system.cpu.loadPercent.toFixed(0)}%`
: "—"}
{system?.cpu.cores ? (
<span className="text-secondary">
{" "}
({system.cpu.cores} cores
{system.cpu.clockSpeedMHz ? ` @ ${(system.cpu.clockSpeedMHz / 1000).toFixed(1)} GHz` : ""})
</span>
) : null}
</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Memory</div>
<div>
{formatBytes(system?.memory.usedBytes ?? null)} / {formatBytes(system?.memory.totalBytes ?? null)}
</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Serial</div>
<div>{system?.serial ?? "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Firmware</div>
<div>{system?.firmwareVersion ?? "—"}</div>
</div>
</div>
)}
</div>
</div>
</div>
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Volumes</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={exportVolumesCsv}
disabled={!sortedVolumes || sortedVolumes.length === 0}
>
Export CSV
</button>
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadStorage(selected.id)}
disabled={loading}
>
{loading ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<SynologyVolume> label="Volume" sortKeyName="id" activeKey={volumeSortKey} direction={volumeSortDir} onSort={requestVolumeSort} />
<SortableTh<SynologyVolume>
label="Type"
sortKeyName="deviceType"
activeKey={volumeSortKey}
direction={volumeSortDir}
onSort={requestVolumeSort}
/>
<SortableTh<SynologyVolume>
label="Used"
sortKeyName="sizeUsed"
activeKey={volumeSortKey}
direction={volumeSortDir}
onSort={requestVolumeSort}
/>
<SortableTh<SynologyVolume>
label="Status"
sortKeyName="status"
activeKey={volumeSortKey}
direction={volumeSortDir}
onSort={requestVolumeSort}
/>
</tr>
</thead>
<tbody>
{sortedVolumes?.map((v) => (
<tr key={v.id}>
<td>{v.id}</td>
<td className="text-secondary">{v.deviceType}</td>
<td className="text-secondary">
{formatBytes(v.sizeUsed)} / {formatBytes(v.sizeTotal)}
</td>
<td>{healthBadge(v.status)}</td>
</tr>
))}
{sortedVolumes?.length === 0 && (
<tr>
<td colSpan={4} className="text-secondary text-center">
No volumes found.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Disks</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={exportDisksCsv}
disabled={!sortedDisks || sortedDisks.length === 0}
>
Export CSV
</button>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<SynologyDisk> label="Disk" sortKeyName="name" activeKey={diskSortKey} direction={diskSortDir} onSort={requestDiskSort} />
<SortableTh<SynologyDisk>
label="Device"
sortKeyName="device"
activeKey={diskSortKey}
direction={diskSortDir}
onSort={requestDiskSort}
/>
<SortableTh<SynologyDisk>
label="Temp"
sortKeyName="temp"
activeKey={diskSortKey}
direction={diskSortDir}
onSort={requestDiskSort}
/>
<SortableTh<SynologyDisk>
label="S.M.A.R.T."
sortKeyName="smartStatus"
activeKey={diskSortKey}
direction={diskSortDir}
onSort={requestDiskSort}
/>
<SortableTh<SynologyDisk>
label="Status"
sortKeyName="status"
activeKey={diskSortKey}
direction={diskSortDir}
onSort={requestDiskSort}
/>
</tr>
</thead>
<tbody>
{sortedDisks?.map((d) => (
<tr key={d.id}>
<td>{d.name}</td>
<td className="text-secondary">{d.device}</td>
<td className="text-secondary">{d.temp !== null ? `${d.temp}°C` : "—"}</td>
<td>{healthBadge(d.smartStatus)}</td>
<td>
{healthBadge(d.status)}
{d.exceedBadSectorThreshold && <span className="badge bg-yellow-lt text-yellow ms-1">Bad sectors</span>}
{d.belowRemainLifeThreshold && <span className="badge bg-yellow-lt text-yellow ms-1">Low life</span>}
</td>
</tr>
))}
{sortedDisks?.length === 0 && (
<tr>
<td colSpan={5} className="text-secondary text-center">
No disks found.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
)}
</>
)}
</>
);
}