Files
Homelab-manager/web/src/pages/ComingUp.tsx
T
bobbanandClaude Sonnet 5.5 f86661f6c9 Speedtest Tracker, Costs, "Having trouble" on status pages, grouped Integrations and Dashboard
- Speedtest Tracker integration: charts, alerts for a slow line (median of the
  last three tests under a share of what is paid for) and for failing tests.
- Costs page (Records): things paid for by hand plus Hetzner's estimate, totals
  per currency, bills rolled forward into Coming up as Renewals.
- Status pages: a "Having trouble" state for things that answer but have an open
  alert; Speedtest reads as the internet.
- Integrations page and kind picker grouped like the sidebar (one shared types
  file); Notifications "What to send" shown one group at a time; Dashboard
  integration sections follow the menu groups, with tiles for integrations that
  have no widget.
- Docs, tests, and ROLES.md menu table brought up to date.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-26 23:23:46 +01:00

322 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type Agenda, type AgendaItem, type AgendaKind, type CurrentUser } from "../api/client";
import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton";
import EmptyState from "../components/EmptyState";
import { downloadCsv } from "../utils/csv";
import { formatDate, formatTime } from "../utils/date";
import { readableError } from "../utils/errors";
const KINDS: { id: AgendaKind; label: string }[] = [
{ id: "secret", label: "Secrets" },
{ id: "certificate", label: "Certificates" },
{ id: "domain", label: "Domains" },
{ id: "tailscale", label: "Tailscale keys" },
{ id: "warranty", label: "Warranties" },
{ id: "support", label: "End of support" },
{ id: "maintenance", label: "Maintenance" },
{ id: "restore", label: "Restore tests" },
{ id: "updates", label: "Updates waiting" },
{ id: "todo", label: "To do" },
{ id: "renewal", label: "Renewals" },
];
const KIND_LABEL = Object.fromEntries(KINDS.map((k) => [k.id, k.label])) as Record<AgendaKind, string>;
const RANGES: { days: number; label: string }[] = [
{ days: 30, label: "Next 30 days" },
{ days: 90, label: "Next 3 months" },
{ days: 180, label: "Next 6 months" },
{ days: 400, label: "Next year" },
];
/** "today", "tomorrow", "in 5 days", "3 days ago". */
function relative(daysLeft: number): string {
if (daysLeft === 0) return "today";
if (daysLeft === 1) return "tomorrow";
if (daysLeft === -1) return "yesterday";
return daysLeft > 0 ? `in ${daysLeft} days` : `${-daysLeft} days ago`;
}
/** A day as the app's date format writes it (the string is a plain day, so it is read as one, not shifted by the viewer's zone). */
const dayOf = (ymd: string) => {
const [y, m, d] = ymd.split("-").map(Number);
return new Date(y, m - 1, d);
};
const weekday = (ymd: string) => dayOf(ymd).toLocaleDateString(undefined, { weekday: "short" });
interface Section {
id: string;
title: string;
hint?: string;
items: AgendaItem[];
}
function sectionsOf(items: AgendaItem[]): Section[] {
const now = items.filter((i) => i.daysLeft < 0 || i.kind === "updates");
const rest = items.filter((i) => !(i.daysLeft < 0 || i.kind === "updates"));
return [
{ id: "now", title: "Needs attention now", hint: "Already past its date, or waiting", items: now },
{ id: "today", title: "Today", items: rest.filter((i) => i.daysLeft === 0) },
{ id: "week", title: "This week", items: rest.filter((i) => i.daysLeft >= 1 && i.daysLeft <= 7) },
{ id: "month", title: "The rest of the month", hint: "8 to 30 days away", items: rest.filter((i) => i.daysLeft >= 8 && i.daysLeft <= 30) },
{ id: "later", title: "Further ahead", items: rest.filter((i) => i.daysLeft > 30) },
].filter((s) => s.items.length > 0);
}
function When({ item }: { item: AgendaItem }) {
if (item.allDay) {
return (
<>
<div>
{weekday(item.at)} {formatDate(dayOf(item.at))}
</div>
{item.kind !== "updates" && <div className="text-secondary small">{relative(item.daysLeft)}</div>}
</>
);
}
const start = new Date(item.at);
const end = item.endsAt ? new Date(item.endsAt) : null;
return (
<>
<div>
{start.toLocaleDateString(undefined, { weekday: "short" })} {formatDate(start)}
</div>
<div className="text-secondary small">
{formatTime(start, false)}
{end ? `–${formatTime(end, false)}` : ""} · {relative(item.daysLeft)}
</div>
</>
);
}
/**
* Everything with a date ahead in one list: secrets, domains and certificates that expire, Tailscale keys, warranties, end of support, planned and recurring
* maintenance, restore tests that are due, and updates that have been waiting — nearest first. Narrow it by kind, by how far ahead, or by server. The same list
* can be put in a phone's calendar (Settings → Share links → a calendar feed).
*/
export default function ComingUp({ user }: { user: CurrentUser }) {
const [params, setParams] = useSearchParams();
const days = RANGES.some((r) => r.days === Number(params.get("days"))) ? Number(params.get("days")) : 90;
const chosen = useMemo(() => new Set((params.get("kinds") ?? "").split(",").filter((k): k is AgendaKind => KINDS.some((x) => x.id === k))), [params]);
const serverId = /^\d+$/.test(params.get("server") ?? "") ? Number(params.get("server")) : null;
const [everyOccurrence, setEveryOccurrence] = useState(false);
const [agenda, setAgenda] = useState<Agenda | null>(null);
const [servers, setServers] = useState<Map<number, string>>(new Map());
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
const load = () =>
api.agenda
.get(400)
.then((res) => alive && (setAgenda(res), setError(null)))
.catch((err) => alive && setError(readableError(err)));
load();
api.servers
.list()
.then((res) => alive && setServers(new Map(res.servers.map((s) => [s.id, s.name]))))
.catch(() => {});
const t = setInterval(load, 5 * 60_000);
return () => {
alive = false;
clearInterval(t);
};
}, []);
const setParam = (key: string, value: string | null) =>
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (value) next.set(key, value);
else next.delete(key);
return next;
},
{ replace: true },
);
const toggleKind = (id: AgendaKind) => {
const next = new Set(chosen);
if (next.has(id)) next.delete(id);
else next.add(id);
setParam("kinds", [...next].join(",") || null);
};
const withinRange = useMemo(() => (agenda?.items ?? []).filter((i) => i.kind === "updates" || i.daysLeft <= days), [agenda, days]);
// A schedule that happens every week would take a line a week: by default only its next time is listed, and the rest can be asked for.
const { inRange, hiddenRecurring } = useMemo(() => {
if (everyOccurrence) return { inRange: withinRange, hiddenRecurring: 0 };
const seen = new Set<string>();
let hidden = 0;
const kept = withinRange.filter((i) => {
const m = /^(schedule|plan):(\d+):/.exec(i.id);
const schedule = m ? `${m[1]}:${m[2]}` : null;
if (!schedule) return true;
if (seen.has(schedule)) {
hidden++;
return false;
}
seen.add(schedule);
return true;
});
return { inRange: kept, hiddenRecurring: hidden };
}, [withinRange, everyOccurrence]);
const counts = useMemo(() => {
const out = new Map<AgendaKind, number>();
for (const i of inRange) out.set(i.kind, (out.get(i.kind) ?? 0) + 1);
return out;
}, [inRange]);
const serversWithItems = useMemo(() => [...new Set(inRange.map((i) => i.serverId).filter((s): s is number => s !== null))].sort((a, b) => (servers.get(a) ?? "").localeCompare(servers.get(b) ?? "")), [inRange, servers]);
const shown = inRange.filter((i) => (chosen.size === 0 || chosen.has(i.kind)) && (serverId === null || i.serverId === serverId));
const sections = sectionsOf(shown);
const filtered = chosen.size > 0 || serverId !== null;
const needNow = inRange.filter((i) => i.daysLeft < 0 && i.kind !== "updates").length;
const thisWeek = inRange.filter((i) => i.daysLeft >= 0 && i.daysLeft <= 7 && i.kind !== "updates").length;
const cards = [
{ label: "Past their date", value: agenda ? String(needNow) : "…", color: needNow > 0 ? "text-red" : "text-green" },
{ label: "In the next 7 days", value: agenda ? String(thisWeek) : "…", color: thisWeek > 0 ? "text-yellow" : "" },
{ label: "In the list", value: agenda ? String(shown.length) : "…", color: "" },
];
function exportCsv() {
downloadCsv(
"coming-up.csv",
["Date", "Ends", "What", "Kind", "Details", "Days from today", "Page"],
shown.map((i) => [i.at, i.endsAt ?? "", i.title, KIND_LABEL[i.kind], i.detail ?? "", i.daysLeft, i.link]),
);
}
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">Coming up</h2>
<button className="btn btn-outline-secondary ms-auto" onClick={exportCsv} disabled={shown.length === 0}>
Export CSV
</button>
</div>
<p className="text-secondary">
What is about to need attention, nearest first: things that expire, hardware that ages out, planned maintenance, restore tests that are due. Each also raises its own alert when it gets close.
{user.role === "admin" ? (
<>
{" "}
To have it in your phone&rsquo;s calendar, make a <Link to="/settings/share">calendar feed</Link>.
</>
) : (
" An administrator can make a calendar feed of it for your phone."
)}
</p>
<ErrorNotice error={error} />
{agenda && agenda.notes.length > 0 && (
<div className="alert alert-warning" role="status">
Something couldn&rsquo;t be read, so this list may be missing entries: {agenda.notes.join(" · ")}
</div>
)}
<div className="row row-cards mb-3">
{cards.map((c) => (
<div className="col-6 col-md-4" 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>
<div className="card mb-3">
<div className="card-body">
<div className="d-flex flex-wrap gap-2 align-items-center mb-2">
<select className="form-select w-auto" aria-label="How far ahead" value={days} onChange={(e) => setParam("days", e.target.value === "90" ? null : e.target.value)}>
{RANGES.map((r) => (
<option key={r.days} value={r.days}>
{r.label}
</option>
))}
</select>
{serversWithItems.length > 0 && (
<select className="form-select w-auto" aria-label="Server" value={serverId ?? ""} onChange={(e) => setParam("server", e.target.value || null)}>
<option value="">Every server</option>
{serversWithItems.map((id) => (
<option key={id} value={id}>
{servers.get(id) ?? `Server ${id}`}
</option>
))}
</select>
)}
{(hiddenRecurring > 0 || everyOccurrence) && (
<label className="form-check mb-0 ms-2">
<input type="checkbox" className="form-check-input" checked={everyOccurrence} onChange={(e) => setEveryOccurrence(e.target.checked)} />
<span className="form-check-label">Every time a recurring maintenance happens{hiddenRecurring > 0 ? ` (${hiddenRecurring} more)` : ""}</span>
</label>
)}
{filtered && (
<button className="btn btn-sm btn-link" onClick={() => setParams(new URLSearchParams(days === 90 ? {} : { days: String(days) }), { replace: true })}>
Clear filters
</button>
)}
</div>
<div className="d-flex flex-wrap gap-2" role="group" aria-label="Kinds of things">
{KINDS.map((k) => {
const n = counts.get(k.id) ?? 0;
const on = chosen.has(k.id);
return (
<button key={k.id} type="button" className={`btn btn-sm ${on ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={on} disabled={n === 0 && !on} onClick={() => toggleKind(k.id)}>
{k.label} <span className={`ms-1 ${on ? "" : "text-secondary"}`}>{n}</span>
</button>
);
})}
</div>
</div>
</div>
{agenda === null && !error && <BlockSkeleton lines={5} />}
{agenda !== null && sections.length === 0 && (
<div className="card">
{filtered ? (
<EmptyState filtered title="Nothing matches that" hint="Nothing with a date fits the kinds and server chosen. Try a longer range, or fewer filters." action={{ label: "Clear filters", onClick: () => setParams(new URLSearchParams(days === 90 ? {} : { days: String(days) }), { replace: true }) }} />
) : (
<EmptyState title="Nothing is coming up" hint={`Nothing expires, ends or is planned in the next ${days} days. Dates come from Secrets, Domains, Inventory (warranty and end of support), Maintenance and the endpoint checks' certificates.`} />
)}
</div>
)}
{sections.map((s) => (
<div className="card mb-3" key={s.id}>
<div className="card-header">
<h3 className="card-title">{s.title}</h3>
<div className="card-subtitle text-secondary ms-2">{s.hint ?? ""}</div>
</div>
<div className="list-group list-group-flush">
{s.items.map((i) => (
<div className="list-group-item" key={i.id}>
<div className="row align-items-center g-2">
<div className="col-5 col-md-3 col-lg-2">
<When item={i} />
</div>
<div className="col" style={{ minWidth: 0 }}>
<div className="text-break">
<Link to={i.link}>{i.title}</Link>
{i.serverId !== null && servers.has(i.serverId) && (
<span className="text-secondary small">
{" "}
· <Link to={`/servers/${i.serverId}`}>{servers.get(i.serverId)}</Link>
</span>
)}
</div>
{i.detail && <div className="text-secondary small text-break">{i.detail}</div>}
</div>
<div className="col-auto">
<span className={`badge ${i.daysLeft < 0 && i.kind !== "updates" ? "bg-red-lt text-red" : i.daysLeft <= 7 && i.kind !== "maintenance" && i.kind !== "updates" ? "bg-yellow-lt text-yellow" : "bg-secondary-lt text-secondary"}`}>{KIND_LABEL[i.kind]}</span>
</div>
</div>
</div>
))}
</div>
</div>
))}
</>
);
}