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(null); const [error, setError] = useState(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(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(null); const timezone = scheduleZone ?? browserTimezone; const [name, setName] = useState(""); const [reason, setReason] = useState(""); const [days, setDays] = useState([0]); const [startTime, setStartTime] = useState("02:00"); const [minutes, setMinutes] = useState(120); const [picked, setPicked] = useState>(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 (

{t("Recurring")}

{canEdit && !adding && ( )}
{adding && (
setName(e.target.value)} />
setReason(e.target.value)} />
{t("Days")}
{DAYS.map((d) => { const on = days.includes(d.value); return ( ); })}
setStartTime(e.target.value)} />
{t("Clock in")} {timezone}
{t("What it covers")}
{groups.map( (g) => g.items.length > 0 && (
{g.label}{" "}
{g.items.map((i) => ( ))}
), )}
{picked.size > 0 && (
({ 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))]))} />
)}
)} {!adding && }
{canEdit && } {schedules?.map((s) => ( {canEdit && ( )} ))} {schedules === null && } {schedules?.length === 0 && ( { setError(null); setAdding(true); } } : undefined} /> )}
{t("Name")} Covers {t("When")} {t("Next")}{t("Actions")}
{s.name} {!s.enabled && off} {s.reason &&
{s.reason}
}
{namesWords(s.targets.map((t) => t.name))} {daysWords(s.days)} {timeWords(s.startTime, s.durationMinutes)} {s.timezone !== browserTimezone && ({s.timezone})} {s.nextStart ? : "—"}
); }