Files
Homelab-manager/web/src/components/RecurringMaintenance.tsx
T
bobbanandClaude Sonnet 5.5 645816d5a8 Add a Swedish interface with a per-person language switch
A small translation system (the English text is its own key, so anything
without a Swedish entry stays English) and a Language switch in the user menu,
saved on the account (users.language) and following the browser when no choice
has been made. Swedish covers the menu, shared parts (search, tables, dialogs,
relative times), the sign-in page and the everyday pages: Dashboard, Alerts,
Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the
display settings. Server-written messages stay English for now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:49:49 +01:00

355 lines
15 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, useState } from "react";
import ImpactNote from "./ImpactNote";
import { api, type MaintenanceSchedule, type MaintenanceTargetType, type MaintenanceTargets } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import TimeAgo from "./TimeAgo";
import { ErrorNotice } from "./Notice";
import ExportTableButton from "./ExportTableButton";
import { EmptyRow, LoadingRow } from "./EmptyState";
import { t } from "../i18n";
// Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday).
const DAYS: { value: number; short: string }[] = [
{ value: 1, short: "Mon" },
{ value: 2, short: "Tue" },
{ value: 3, short: "Wed" },
{ value: 4, short: "Thu" },
{ value: 5, short: "Fri" },
{ value: 6, short: "Sat" },
{ value: 0, short: "Sun" },
];
const LENGTHS: { minutes: number; label: string }[] = [
{ minutes: 30, label: "30 minutes" },
{ minutes: 60, label: "1 hour" },
{ minutes: 120, label: "2 hours" },
{ minutes: 180, label: "3 hours" },
{ minutes: 240, label: "4 hours" },
{ minutes: 360, label: "6 hours" },
{ minutes: 480, label: "8 hours" },
{ minutes: 720, label: "12 hours" },
{ minutes: 1440, label: "24 hours" },
];
function daysWords(days: number[]): string {
if (days.length === 7) return "Every day";
const set = new Set(days);
if ([1, 2, 3, 4, 5].every((d) => set.has(d)) && days.length === 5) return "Weekdays";
if (days.length === 2 && set.has(6) && set.has(0)) return "Weekends";
return DAYS.filter((d) => set.has(d.value)).map((d) => d.short).join(", ");
}
/** "02:00–04:00", with "(+1 d)" when it runs into the next day. */
function timeWords(start: string, minutes: number): string {
const [h, m] = start.split(":").map(Number);
const end = h * 60 + m + minutes;
const clock = (t: number) => `${String(Math.floor((t % 1440) / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`;
return `${start}–${clock(end)}${end >= 1440 ? ` (+${Math.floor(end / 1440)} d)` : ""}`;
}
function namesWords(names: string[]): string {
return names.length <= 3 ? names.join(", ") : `${names.slice(0, 3).join(", ")} and ${names.length - 3} more`;
}
/**
* Maintenance that comes back by itself — "every Sunday 02:00–04:00 on these servers". Each time is made into an ordinary maintenance
* window a week ahead, so it shows on the timeline and in Scheduled, silences alerts while it runs, and any single one can be cancelled.
*/
export default function RecurringMaintenance({ canEdit, targets, onChanged }: { canEdit: boolean; targets: MaintenanceTargets | null; onChanged: () => void }) {
const [schedules, setSchedules] = useState<MaintenanceSchedule[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
// The schedule being changed, if the form is open to change one rather than to add one.
const [editingId, setEditingId] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
// A schedule keeps the zone it was made in when it is changed; a new one uses this browser's.
const [scheduleZone, setScheduleZone] = useState<string | null>(null);
const timezone = scheduleZone ?? browserTimezone;
const [name, setName] = useState("");
const [reason, setReason] = useState("");
const [days, setDays] = useState<number[]>([0]);
const [startTime, setStartTime] = useState("02:00");
const [minutes, setMinutes] = useState(120);
const [picked, setPicked] = useState<Set<string>>(new Set());
function load() {
api.maintenance.schedules
.list()
.then((res) => setSchedules(res.schedules))
.catch((err) => setError(readableError(err)));
}
useEffect(load, []);
const key = (type: MaintenanceTargetType, id: number) => `${type}:${id}`;
const groups: { label: string; type: MaintenanceTargetType; items: { id: number; name: string }[] }[] = [
{ label: "Servers", type: "server", items: targets?.servers ?? [] },
{ label: "Integrations", type: "integration", items: targets?.integrations ?? [] },
{ label: "Network devices", type: "device", items: targets?.devices ?? [] },
{ label: "DNS providers", type: "dns_provider", items: targets?.dnsProviders ?? [] },
];
function toggleGroup(type: MaintenanceTargetType, items: { id: number }[]) {
setPicked((prev) => {
const next = new Set(prev);
const all = items.every((i) => next.has(key(type, i.id)));
for (const i of items) (all ? next.delete(key(type, i.id)) : next.add(key(type, i.id)));
return next;
});
}
function closeForm() {
setAdding(false);
setEditingId(null);
setScheduleZone(null);
setName("");
setReason("");
setDays([0]);
setStartTime("02:00");
setMinutes(120);
setPicked(new Set());
}
function startEditing(s: MaintenanceSchedule) {
setError(null);
setEditingId(s.id);
setScheduleZone(s.timezone);
setName(s.name);
setReason(s.reason ?? "");
setDays(s.days);
setStartTime(s.startTime);
setMinutes(s.durationMinutes);
setPicked(new Set(s.targets.map((t) => key(t.type, t.id))));
setAdding(true);
}
async function create(e: React.FormEvent) {
e.preventDefault();
setError(null);
setBusy(true);
try {
const chosen = [...picked].map((k) => {
const [type, id] = k.split(":");
return { type: type as MaintenanceTargetType, id: Number(id) };
});
const input = { name: name.trim(), reason: reason.trim() || undefined, targets: chosen, days, startTime, durationMinutes: minutes, timezone };
const res = editingId === null ? await api.maintenance.schedules.create(input) : await api.maintenance.schedules.update(editingId, input);
toast.success(`Saved. ${res.windowsMade} maintenance window${res.windowsMade === 1 ? "" : "s"} made for the coming week.`);
closeForm();
load();
onChanged();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function toggle(s: MaintenanceSchedule) {
try {
await api.maintenance.schedules.setEnabled(s.id, !s.enabled);
load();
onChanged();
} catch (err) {
setError(readableError(err));
}
}
async function remove(s: MaintenanceSchedule) {
if (!(await confirmDialog({ title: t("Remove recurring maintenance"), message: `Remove "${s.name}"? Windows it made that haven't begun are taken back; one already under way ends on its own.`, confirmLabel: "Remove", danger: true }))) return;
try {
await api.maintenance.schedules.remove(s.id);
toast.success(`Removed ${s.name}.`);
load();
onChanged();
} catch (err) {
setError(readableError(err));
}
}
if (schedules !== null && schedules.length === 0 && !canEdit) return null;
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">{t("Recurring")}</h3>
<div className="card-actions">
<ExportTableButton filename="maintenance-recurring" />
{canEdit && !adding && (
<button type="button" className="btn btn-sm btn-primary" onClick={() => { setError(null); setAdding(true); }}>
{t("Add recurring maintenance")}
</button>
)}
</div>
</div>
{adding && (
<form onSubmit={create}>
<div className="card-body row g-3">
<div className="col-md-4">
<label className="form-label" htmlFor="rec-name">
{t("Name")}
</label>
<input id="rec-name" className="form-control" required maxLength={80} placeholder="e.g. Patch night" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="col-md-8">
<label className="form-label" htmlFor="rec-reason">
{t("Reason (optional)")}
</label>
<input id="rec-reason" className="form-control" maxLength={200} placeholder="e.g. OS updates and restarts" value={reason} onChange={(e) => setReason(e.target.value)} />
</div>
<div className="col-12">
<div className="form-label" id="rec-days">
{t("Days")}
</div>
<div className="btn-group" role="group" aria-labelledby="rec-days">
{DAYS.map((d) => {
const on = days.includes(d.value);
return (
<button key={d.value} type="button" className={`btn btn-sm ${on ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={on} onClick={() => setDays((prev) => (on ? prev.filter((x) => x !== d.value) : [...prev, d.value]))}>
{d.short}
</button>
);
})}
</div>
</div>
<div className="col-sm-6 col-md-3">
<label className="form-label" htmlFor="rec-start">
{t("Starts at")}
</label>
<input id="rec-start" type="time" className="form-control" required value={startTime} onChange={(e) => setStartTime(e.target.value)} />
<div className="form-hint text-secondary small mt-1">{t("Clock in")} {timezone}</div>
</div>
<div className="col-sm-6 col-md-3">
<label className="form-label" htmlFor="rec-length">
{t("For")}
</label>
<select id="rec-length" className="form-select" value={minutes} onChange={(e) => setMinutes(Number(e.target.value))}>
{/* A schedule made some other way (or before these choices) keeps whatever length it has. */}
{!LENGTHS.some((l) => l.minutes === minutes) && <option value={minutes}>{minutes} minutes</option>}
{LENGTHS.map((l) => (
<option key={l.minutes} value={l.minutes}>
{l.label}
</option>
))}
</select>
</div>
<div className="col-12">
<div className="form-label">{t("What it covers")}</div>
<div className="border rounded p-2" style={{ maxHeight: 220, overflowY: "auto" }}>
{groups.map(
(g) =>
g.items.length > 0 && (
<fieldset key={g.type} className="mb-2">
<legend className="form-label small text-secondary mb-1">
{g.label}{" "}
<button type="button" className="btn btn-link btn-sm p-0 ms-1" onClick={() => toggleGroup(g.type, g.items)}>
{g.items.every((i) => picked.has(key(g.type, i.id))) ? "none" : "all"}
</button>
</legend>
<div className="d-flex flex-wrap gap-3">
{g.items.map((i) => (
<label key={i.id} className="form-check mb-0">
<input
type="checkbox"
className="form-check-input"
checked={picked.has(key(g.type, i.id))}
onChange={(e) =>
setPicked((prev) => {
const next = new Set(prev);
if (e.target.checked) next.add(key(g.type, i.id));
else next.delete(key(g.type, i.id));
return next;
})
}
/>
<span className="form-check-label">{i.name}</span>
</label>
))}
</div>
</fieldset>
),
)}
</div>
</div>
{picked.size > 0 && (
<div className="col-12">
<ImpactNote
targets={[...picked].map((k) => ({ type: k.split(":")[0], id: Number(k.split(":")[1]) }))}
verb="will look down while they are"
onAdd={(items) => setPicked((prev) => new Set([...prev, ...items.map((i) => key(i.type, i.id))]))}
/>
</div>
)}
<div className="col-12">
<ErrorNotice error={error} />
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || picked.size === 0 || days.length === 0 || name.trim() === ""}>
{busy ? "Saving…" : editingId === null ? t("Save") : t("Save changes")}
</button>
<button type="button" className="btn" onClick={closeForm}>
{t("Cancel")}
</button>
</div>
</form>
)}
{!adding && <ErrorNotice error={error} />}
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>{t("Name")}</th>
<th>Covers</th>
<th>{t("When")}</th>
<th>{t("Next")}</th>
{canEdit && <th className="w-1">{t("Actions")}</th>}
</tr>
</thead>
<tbody>
{schedules?.map((s) => (
<tr key={s.id} className={s.enabled ? undefined : "text-secondary"}>
<td>
{s.name}
{!s.enabled && <span className="badge bg-secondary-lt text-secondary ms-2">off</span>}
{s.reason && <div className="text-secondary small">{s.reason}</div>}
</td>
<td>{namesWords(s.targets.map((t) => t.name))}</td>
<td>
{daysWords(s.days)} {timeWords(s.startTime, s.durationMinutes)}
{s.timezone !== browserTimezone && <span className="text-secondary small"> ({s.timezone})</span>}
</td>
<td>{s.nextStart ? <TimeAgo value={s.nextStart} /> : "—"}</td>
{canEdit && (
<td>
<div className="btn-list flex-nowrap">
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => startEditing(s)} disabled={editingId === s.id}>
{t("Edit")}
</button>
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void toggle(s)}>
{s.enabled ? t("Turn off") : t("Turn on")}
</button>
<button type="button" className="btn btn-sm btn-outline-danger" onClick={() => void remove(s)}>
{t("Remove")}
</button>
</div>
</td>
)}
</tr>
))}
{schedules === null && <LoadingRow colSpan={canEdit ? 5 : 4} />}
{schedules?.length === 0 && (
<EmptyRow colSpan={canEdit ? 5 : 4} title={t("No recurring maintenance")} hint={t("Add one for the night you patch, and its windows appear a week ahead, so alerts stay quiet without anyone remembering to.")} action={canEdit ? { label: "Add recurring maintenance", onClick: () => { setError(null); setAdding(true); } } : undefined} />
)}
</tbody>
</table>
</div>
</div>
);
}