SPB Git

Repository Public

calendar.test.ts 11.9 KB 188 lines typescript

1import { describe, expect, it } from "vitest";2import type { Schemas } from "@/api/client";3import { addDays, addMonths, dayBounds, dayKeyOf, diffDays, layoutLanes, localInputToUtc, monthGrid, segmentsByDay, shiftAnchor, splitHighlight, startOfWeek, utcOffsetLabel, utcToLocalInput, visibleRange, weekDays, weekStartFor, weekdayOf, zoneLabel, zoneOffsetMs, zonedParts, zonedToUtc, type Occurrence } from "./calendar";4import { emptyForm, formToCreate, formToUpdate, hasErrors, localOverlaps, validateWindowForm, windowToForm } from "./windowForm";56const TOR = "America/Toronto";7const win = (over: Partial<Schemas["MaintenanceWindow"]> = {}): Schemas["MaintenanceWindow"] => ({8  id: "w1", title: "Updates", description: "", category: "update", starts_at: "2026-11-22T07:00:00Z", ends_at: "2026-11-22T08:00:00Z", timezone: TOR, recurrence: "none",9  scope: { node_ids: ["n1"] }, set_maintenance_mode: true, silence_alerts: true, status: "scheduled", created_at: "2026-11-18T00:00:00Z", updated_at: "2026-11-18T00:00:00Z", ...over,10});11const occ = (start: string, end: string, w: Partial<Schemas["MaintenanceWindow"]> = {}): Occurrence => ({ window: win(w), occurrence_start: start, occurrence_end: end, note_count: 0 });1213describe("zone maths", () => {14  it("reads wall-clock time and offsets in a zone, summer and winter", () => {15    expect(zonedParts(Date.parse("2026-07-01T16:30:00Z"), TOR)).toMatchObject({ y: 2026, m: 7, d: 1, h: 12, mi: 30 });16    expect(zoneOffsetMs(Date.parse("2026-07-01T12:00:00Z"), TOR)).toBe(-4 * 3600_000);17    expect(zoneOffsetMs(Date.parse("2026-12-01T12:00:00Z"), TOR)).toBe(-5 * 3600_000);18    expect(zoneOffsetMs(Date.parse("2026-12-01T12:00:00Z"), "Asia/Kolkata")).toBe(5.5 * 3600_000);19    expect(utcOffsetLabel(TOR, Date.parse("2026-12-01T12:00:00Z"))).toBe("UTC−5");20    expect(utcOffsetLabel("Asia/Kolkata", 0)).toBe("UTC+5:30");21    expect(zoneLabel("UTC", 0)).toBe("UTC");22    expect(zoneLabel(TOR, Date.parse("2026-07-01T12:00:00Z"))).toBe("America/Toronto (UTC−4)");23  });24  it("converts wall-clock time to an instant, both sides of DST", () => {25    expect(new Date(zonedToUtc({ y: 2026, m: 7, d: 1, h: 9, mi: 0 }, TOR)).toISOString()).toBe("2026-07-01T13:00:00.000Z");26    expect(new Date(zonedToUtc({ y: 2026, m: 12, d: 1, h: 9, mi: 0 }, TOR)).toISOString()).toBe("2026-12-01T14:00:00.000Z");27    expect(new Date(zonedToUtc({ y: 2026, m: 3, d: 28, h: 23, mi: 30 }, "Europe/Paris")).toISOString()).toBe("2026-03-28T22:30:00.000Z");28  });29  it("resolves a skipped time after the jump and a repeated time to its first occurrence", () => {30    // 2026-03-08 02:30 does not exist in Toronto (02:00 → 03:00)31    expect(new Date(zonedToUtc({ y: 2026, m: 3, d: 8, h: 2, mi: 30 }, TOR)).toISOString()).toBe("2026-03-08T07:30:00.000Z");32    // 2026-11-01 01:30 happens twice (EDT then EST): first one33    expect(new Date(zonedToUtc({ y: 2026, m: 11, d: 1, h: 1, mi: 30 }, TOR)).toISOString()).toBe("2026-11-01T05:30:00.000Z");34  });35  it("round-trips datetime-local values in an arbitrary zone", () => {36    for (const zone of [TOR, "UTC", "Asia/Tokyo", "Australia/Lord_Howe", "Asia/Kathmandu"]) {37      for (const v of ["2026-01-15T00:00", "2026-06-30T23:59", "2026-11-22T02:00"]) {38        const iso = localInputToUtc(v, zone);39        expect(iso).not.toBeNull();40        expect(utcToLocalInput(iso as string, zone)).toBe(v);41      }42    }43    expect(localInputToUtc("2026-11-22T02:00", TOR)).toBe("2026-11-22T07:00:00.000Z");44    expect(localInputToUtc("nope", TOR)).toBeNull();45    expect(localInputToUtc("2026-13-01T00:00", TOR)).toBeNull();46  });47});4849describe("civil days", () => {50  it("does day and month arithmetic without a zone", () => {51    expect(addDays("2026-02-28", 1)).toBe("2026-03-01");52    expect(addDays("2026-01-01", -1)).toBe("2025-12-31");53    expect(addMonths("2026-01-31", 1)).toBe("2026-02-28");54    expect(addMonths("2026-03-15", -3)).toBe("2025-12-15");55    expect(weekdayOf("2026-11-18")).toBe(3); // Wednesday56    expect(diffDays("2026-11-18", "2026-12-01")).toBe(13);57  });58  it("gives the day of an instant per zone", () => {59    const t = Date.parse("2026-11-19T03:30:00Z");60    expect(dayKeyOf(t, TOR)).toBe("2026-11-18");61    expect(dayKeyOf(t, "UTC")).toBe("2026-11-19");62    expect(dayKeyOf(t, "Asia/Tokyo")).toBe("2026-11-19");63  });64  it("bounds days of 23, 24 and 25 hours", () => {65    const len = (k: string) => { const [a, b] = dayBounds(k, TOR); return (b - a) / 3600_000; };66    expect(len("2026-03-08")).toBe(23);67    expect(len("2026-07-01")).toBe(24);68    expect(len("2026-11-01")).toBe(25);69    expect(new Date(dayBounds("2026-11-18", TOR)[0]).toISOString()).toBe("2026-11-18T05:00:00.000Z");70  });71  it("starts the week by locale", () => {72    expect(weekStartFor("fr-CA")).toBe(0);73    expect(weekStartFor("en-CA")).toBe(0);74    expect(weekStartFor("fr-FR")).toBe(1);75    expect(weekStartFor("en-GB")).toBe(1);76    expect(startOfWeek("2026-11-18", 0)).toBe("2026-11-15");77    expect(startOfWeek("2026-11-18", 1)).toBe("2026-11-16");78    expect(weekDays("2026-11-18", 1)).toEqual(["2026-11-16", "2026-11-17", "2026-11-18", "2026-11-19", "2026-11-20", "2026-11-21", "2026-11-22"]);79  });80  it("builds a month grid of whole weeks containing the month", () => {81    const g = monthGrid("2026-11-18", 0);82    expect(g[0]?.[0]).toBe("2026-11-01"); // Nov 1, 2026 is a Sunday83    expect(g.length).toBe(5);84    expect(g[4]?.[6]).toBe("2026-12-05");85    const feb = monthGrid("2026-02-10", 1);86    expect(feb[0]?.[0]).toBe("2026-01-26");87    expect(feb.every((w) => w.length === 7)).toBe(true);88    expect(feb.flat()).toContain("2026-02-28");89  });90  it("computes the fetched range and navigation per view", () => {91    expect(visibleRange("week", "2026-11-18", 0, TOR)).toEqual({ from: "2026-11-15T05:00:00.000Z", to: "2026-11-22T05:00:00.000Z" });92    expect(visibleRange("month", "2026-11-18", 0, "UTC")).toEqual({ from: "2026-11-01T00:00:00.000Z", to: "2026-12-06T00:00:00.000Z" });93    expect(shiftAnchor("month", "2026-01-31", 1)).toBe("2026-02-28");94    expect(shiftAnchor("week", "2026-11-18", -1)).toBe("2026-11-11");95    expect(shiftAnchor("agenda", "2026-11-18", 1)).toBe("2026-12-18");96  });97});9899describe("occurrence layout", () => {100  it("splits a multi-day occurrence into one clipped segment per day, in the display zone", () => {101    const o = occ("2026-11-18T22:00:00Z", "2026-11-20T10:00:00Z"); // 17:00 Wed → 05:00 Fri in Toronto102    const days = ["2026-11-17", "2026-11-18", "2026-11-19", "2026-11-20", "2026-11-21"];103    const m = segmentsByDay([o], days, TOR);104    expect(m.get("2026-11-17")).toEqual([]);105    expect(m.get("2026-11-18")?.[0]).toMatchObject({ continuesBefore: false, continuesAfter: true, end: 1 });106    expect(m.get("2026-11-18")?.[0]?.start).toBeCloseTo(17 / 24);107    expect(m.get("2026-11-19")?.[0]).toMatchObject({ continuesBefore: true, continuesAfter: true, start: 0, end: 1 });108    expect(m.get("2026-11-20")?.[0]?.end).toBeCloseTo(5 / 24);109    expect(m.get("2026-11-21")).toEqual([]);110    // the same instant falls on other days in UTC111    expect(segmentsByDay([o], days, "UTC").get("2026-11-18")?.[0]?.start).toBeCloseTo(22 / 24);112  });113  it("an occurrence ending at midnight does not spill into the next day", () => {114    const m = segmentsByDay([occ("2026-11-18T03:00:00Z", "2026-11-19T00:00:00Z")], ["2026-11-18", "2026-11-19"], "UTC");115    expect(m.get("2026-11-18")?.length).toBe(1);116    expect(m.get("2026-11-19")?.length).toBe(0);117  });118  it("assigns lanes to overlapping intervals and reuses them", () => {119    const items = [{ id: "a", start: 0.1, end: 0.3 }, { id: "b", start: 0.2, end: 0.4 }, { id: "c", start: 0.3, end: 0.5 }, { id: "d", start: 0.7, end: 0.8 }];120    const out = Object.fromEntries(layoutLanes(items).map((l) => [l.item.id, [l.lane, l.lanes]]));121    expect(out).toEqual({ a: [0, 2], b: [1, 2], c: [0, 2], d: [0, 1] });122    expect(layoutLanes([])).toEqual([]);123    const three = layoutLanes([{ start: 0, end: 1 }, { start: 0, end: 1 }, { start: 0, end: 1 }]);124    expect(three.map((l) => l.lane).sort()).toEqual([0, 1, 2]);125    expect(three.every((l) => l.lanes === 3)).toBe(true);126  });127});128129describe("window form", () => {130  it("maps a window to the form in its own zone and back to the same instants", () => {131    const w = win({ recurrence: "weekly", recurrence_until: "2026-12-31T05:00:00Z" });132    const f = windowToForm(w);133    expect(f.start).toBe("2026-11-22T02:00");134    expect(f.end).toBe("2026-11-22T03:00");135    expect(f.until).toBe("2026-12-30");136    const req = formToCreate(f);137    expect(req.starts_at).toBe("2026-11-22T07:00:00.000Z");138    expect(req.ends_at).toBe("2026-11-22T08:00:00.000Z");139    expect(req.recurrence_until).toBe("2026-12-31T05:00:00.000Z");140    expect(formToUpdate(f, w)).toEqual({});141  });142  it("creates a request with UTC instants, omitting empty optional fields", () => {143    const f = { ...emptyForm(TOR, "2026-07-01", 9), title: "  Swap SSD ", nodeIds: ["n1", "n2"] };144    expect(f.start).toBe("2026-07-01T09:00");145    expect(f.end).toBe("2026-07-01T10:00");146    expect(formToCreate(f)).toEqual({ title: "Swap SSD", category: "planned", starts_at: "2026-07-01T13:00:00.000Z", ends_at: "2026-07-01T14:00:00.000Z", timezone: TOR, recurrence: "none", scope: { node_ids: ["n1", "n2"] }, set_maintenance_mode: true, silence_alerts: true });147    expect(emptyForm(TOR, "2026-07-01", 23).end).toBe("2026-07-01T23:00");148  });149  it("sends only changed fields on update", () => {150    const w = win();151    const f = { ...windowToForm(w), title: "Updates v2", end: "2026-11-22T04:00", nodeIds: ["n1", "n9"], silenceAlerts: false };152    expect(formToUpdate(f, w)).toEqual({ title: "Updates v2", starts_at: "2026-11-22T07:00:00.000Z", ends_at: "2026-11-22T09:00:00.000Z", scope: { node_ids: ["n1", "n9"] }, silence_alerts: false });153  });154  it("validates title, order, zone and recurrence end", () => {155    const ok = { ...emptyForm(TOR, "2026-07-01"), title: "x" };156    expect(hasErrors(validateWindowForm(ok))).toBe(false);157    expect(validateWindowForm({ ...ok, title: " " }).title).toBe("titleRequired");158    expect(validateWindowForm({ ...ok, title: "x".repeat(161) }).title).toBe("titleTooLong");159    expect(validateWindowForm({ ...ok, end: ok.start }).end).toBe("endBeforeStart");160    expect(validateWindowForm({ ...ok, start: "" }).start).toBe("startInvalid");161    expect(validateWindowForm({ ...ok, timezone: "Mars/Olympus" }).timezone).toBe("zoneInvalid");162    expect(validateWindowForm({ ...ok, recurrence: "daily", until: "2026-06-30" }).until).toBe("untilBeforeStart");163    expect(validateWindowForm({ ...ok, recurrence: "none", until: "2026-06-30" }).until).toBeUndefined();164  });165  it("hints overlaps only for other open windows sharing a node", () => {166    const f = { ...emptyForm("UTC", "2026-11-22", 7), title: "x", nodeIds: ["n1"] };167    const loaded = [168      occ("2026-11-22T07:30:00Z", "2026-11-22T09:00:00Z", { id: "other" }),169      occ("2026-11-22T07:30:00Z", "2026-11-22T09:00:00Z", { id: "self" }),170      occ("2026-11-22T07:30:00Z", "2026-11-22T09:00:00Z", { id: "elsewhere", scope: { node_ids: ["n2"] } }),171      occ("2026-11-22T07:30:00Z", "2026-11-22T09:00:00Z", { id: "cancelled", status: "cancelled" }),172      occ("2026-11-22T08:00:00Z", "2026-11-22T09:00:00Z", { id: "touching" }),173    ];174    expect(localOverlaps(f, loaded, "self").map((o) => o.window.id)).toEqual(["other"]);175    expect(localOverlaps({ ...f, nodeIds: [] }, loaded)).toEqual([]);176  });177});178179describe("note search highlight", () => {180  it("splits text around case-insensitive matches", () => {181    expect(splitHighlight("Reboot du NAS, nas-01 OK", "nas")).toEqual([{ text: "Reboot du ", match: false }, { text: "NAS", match: true }, { text: ", ", match: false }, { text: "nas", match: true }, { text: "-01 OK", match: false }]);182    expect(splitHighlight("abc", "")).toEqual([{ text: "abc", match: false }]);183    expect(splitHighlight("abc", "zzz")).toEqual([{ text: "abc", match: false }]);184    expect(splitHighlight("<b>x</b>", "<b>")).toEqual([{ text: "<b>", match: true }, { text: "x</b>", match: false }]);185    expect(splitHighlight("", "a")).toEqual([]);186  });187});188
Files main
Menu

Theme