Repository Public
1// Maintenance window form ↔ API requests. Start / end are wall-clock values (datetime-local) in the form's IANA2// zone; they are converted to UTC instants here, including across DST changes.3import type { Schemas } from "@/api/client";4import { addDays, dayBounds, dayKeyOf, isValidZone, localInputToUtc, utcToLocalInput, type DayKey, type Occurrence } from "./calendar";56export type Window = Schemas["MaintenanceWindow"];7export type Category = Schemas["MaintenanceCategory"];8export type Recurrence = Schemas["MaintenanceRecurrence"];9export const CATEGORIES: readonly Category[] = ["planned", "update", "hardware", "inspection", "emergency"];10export const RECURRENCES: readonly Recurrence[] = ["none", "daily", "weekly", "monthly"];1112export interface WindowForm {13 title: string;14 description: string;15 category: Category;16 start: string; // datetime-local in `timezone`17 end: string;18 timezone: string;19 recurrence: Recurrence;20 until: string; // date (YYYY-MM-DD) in `timezone`, inclusive; "" = no end21 nodeIds: string[];22 setMaintenanceMode: boolean;23 silenceAlerts: boolean;24}2526export type WindowFormError = "titleRequired" | "titleTooLong" | "descriptionTooLong" | "startInvalid" | "endInvalid" | "endBeforeStart" | "zoneInvalid" | "untilBeforeStart";27export type WindowFormErrors = Partial<Record<"title" | "description" | "start" | "end" | "timezone" | "until", WindowFormError>>;2829export function emptyForm(zone: string, day: DayKey, hour = 9): WindowForm {30 const h = String(Math.max(0, Math.min(22, hour))).padStart(2, "0");31 const h2 = String(Math.max(0, Math.min(22, hour)) + 1).padStart(2, "0");32 return { title: "", description: "", category: "planned", start: `${day}T${h}:00`, end: `${day}T${h2}:00`, timezone: zone, recurrence: "none", until: "", nodeIds: [], setMaintenanceMode: true, silenceAlerts: true };33}3435export function windowToForm(w: Window): WindowForm {36 const zone = isValidZone(w.timezone) ? w.timezone : "UTC";37 return {38 title: w.title,39 description: w.description,40 category: w.category,41 start: utcToLocalInput(w.starts_at, zone),42 end: utcToLocalInput(w.ends_at, zone),43 timezone: zone,44 recurrence: w.recurrence,45 // `recurrence_until` is an instant: the form shows the civil day it falls on in the window's zone46 until: w.recurrence_until ? dayKeyOf(Date.parse(w.recurrence_until) - 1, zone) : "",47 nodeIds: [...w.scope.node_ids],48 setMaintenanceMode: w.set_maintenance_mode,49 silenceAlerts: w.silence_alerts,50 };51}5253export function validateWindowForm(f: WindowForm): WindowFormErrors {54 const e: WindowFormErrors = {};55 const title = f.title.trim();56 if (title.length === 0) e.title = "titleRequired";57 else if (title.length > 160) e.title = "titleTooLong";58 if (f.description.length > 8000) e.description = "descriptionTooLong";59 if (!isValidZone(f.timezone)) {60 e.timezone = "zoneInvalid";61 return e;62 }63 const s = localInputToUtc(f.start, f.timezone), en = localInputToUtc(f.end, f.timezone);64 if (!s) e.start = "startInvalid";65 if (!en) e.end = "endInvalid";66 if (s && en && Date.parse(en) <= Date.parse(s)) e.end = "endBeforeStart";67 if (f.recurrence !== "none" && f.until && s && f.until < dayKeyOf(Date.parse(s), f.timezone)) e.until = "untilBeforeStart";68 return e;69}70export const hasErrors = (e: WindowFormErrors): boolean => Object.keys(e).length > 0;7172/** End of the inclusive "until" day in the zone, as an instant. */73function untilInstant(until: string, zone: string): string {74 return new Date(dayBounds(until, zone)[1]).toISOString();75}7677/** Call only with a form that passed `validateWindowForm`. */78export function formToCreate(f: WindowForm): Schemas["CreateMaintenanceWindowRequest"] {79 const description = f.description.trim();80 return {81 title: f.title.trim(),82 ...(description ? { description } : {}),83 category: f.category,84 starts_at: localInputToUtc(f.start, f.timezone) ?? "",85 ends_at: localInputToUtc(f.end, f.timezone) ?? "",86 timezone: f.timezone,87 recurrence: f.recurrence,88 ...(f.recurrence !== "none" && f.until ? { recurrence_until: untilInstant(f.until, f.timezone) } : {}),89 scope: { node_ids: [...f.nodeIds] },90 set_maintenance_mode: f.setMaintenanceMode,91 silence_alerts: f.silenceAlerts,92 };93}9495const sameSet = (a: readonly string[], b: readonly string[]) => a.length === b.length && [...a].sort().join() === [...b].sort().join();9697/** Only the fields that differ from the stored window (PATCH). Empty object = nothing to save. */98export function formToUpdate(f: WindowForm, w: Window): Schemas["UpdateMaintenanceWindowRequest"] {99 const next = formToCreate(f);100 const out: Schemas["UpdateMaintenanceWindowRequest"] = {};101 if (next.title !== w.title) out.title = next.title;102 if ((next.description ?? "") !== w.description) out.description = next.description ?? "";103 if (next.category !== w.category) out.category = f.category;104 const moved = Date.parse(next.starts_at) !== Date.parse(w.starts_at) || Date.parse(next.ends_at) !== Date.parse(w.ends_at);105 if (moved) {106 out.starts_at = next.starts_at;107 out.ends_at = next.ends_at;108 }109 if (next.timezone !== w.timezone) out.timezone = f.timezone;110 if (f.recurrence !== w.recurrence) out.recurrence = f.recurrence;111 const until = next.recurrence_until;112 const had = w.recurrence_until;113 if (until && (!had || Date.parse(until) !== Date.parse(had))) out.recurrence_until = until;114 if (!sameSet(f.nodeIds, w.scope.node_ids)) out.scope = { node_ids: [...f.nodeIds] };115 if (f.setMaintenanceMode !== w.set_maintenance_mode) out.set_maintenance_mode = f.setMaintenanceMode;116 if (f.silenceAlerts !== w.silence_alerts) out.silence_alerts = f.silenceAlerts;117 return out;118}119120/**121 * Local hint only (the API reports no overlap): already-loaded occurrences of OTHER windows that intersect the122 * chosen period and share at least one node. It only knows the occurrences currently on screen.123 */124export function localOverlaps(f: WindowForm, loaded: readonly Occurrence[], selfId?: string): Occurrence[] {125 if (!isValidZone(f.timezone)) return [];126 const s = localInputToUtc(f.start, f.timezone), e = localInputToUtc(f.end, f.timezone);127 if (!s || !e || f.nodeIds.length === 0) return [];128 const a = Date.parse(s), b = Date.parse(e);129 const nodes = new Set(f.nodeIds);130 return loaded.filter((o) => o.window.id !== selfId && o.window.status !== "cancelled" && o.window.status !== "completed" && Date.parse(o.occurrence_start) < b && Date.parse(o.occurrence_end) > a && o.window.scope.node_ids.some((n) => nodes.has(n)));131}132133export { addDays };134