/** * The to-do list and notes: who may write, what is checked, ticking off and bringing back, what shows in Coming up and My work. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; import type { Server } from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-todos-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); process.env.HEALTH_STARTUP_GRACE_MS = "0"; const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, servers, notes, todos, auditLog } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { todosRouter, notesRouter } = await import("../src/routes/todos.js"); const { loadAgendaData, agendaFromData } = await import("../src/services/agenda.js"); const { buildMyWork } = await import("../src/services/myWork.js"); const { isRealDay } = await import("../src/services/todos.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); let app: Server; let base = ""; let who = "operator"; const ids: Record = {}; const send = async (method: string, path: string, body?: unknown) => { const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: res.status, body: res.status === 204 ? null : ((await res.json().catch(() => null)) as any) }; }; const day = (offset: number) => new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10); before(async () => { const rows = await db .insert(users) .values([ { oidcSub: "admin", name: "Ada", role: "admin" }, { oidcSub: "operator", name: "Olga", role: "operator" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]) .returning({ id: users.id, oidcSub: users.oidcSub }); for (const r of rows) ids[r.oidcSub] = r.id; ids.web = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w" }).returning({ id: servers.id }))[0].id; const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: who } }; next(); }); a.use("/api/todos", todosRouter); a.use("/api/notes", notesRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows may still hold the database file } }); describe("the to-do list", () => { let jobId = 0; test("a real day is a real day", () => { assert.equal(isRealDay("2026-10-20"), true); assert.equal(isRealDay("2026-02-30"), false); assert.equal(isRealDay("next week"), false); }); test("everyone signed in reads it; only an operator writes", async () => { who = "viewer"; assert.equal((await send("GET", "/todos")).status, 200); assert.equal((await send("POST", "/todos", { title: "x" })).status, 403); assert.equal((await send("PATCH", "/todos/1", { done: true })).status, 403); assert.equal((await send("DELETE", "/todos/1")).status, 403); }); test("a job needs a title; the day must be a day; it can be about a server and handed to an operator, and not to a viewer", async () => { who = "operator"; assert.equal((await send("POST", "/todos", { title: " " })).status, 400); assert.equal((await send("POST", "/todos", { title: "x", dueDate: "tomorrow" })).body.error, "invalid_date"); assert.equal((await send("POST", "/todos", { title: "x", assigneeId: ids.viewer })).body.error, "invalid_assignee"); assert.equal((await send("POST", "/todos", { title: "x", targetType: "server", targetId: 9999 })).body.error, "unknown_target"); assert.equal((await send("POST", "/todos", { title: "x".repeat(200) })).body.error, "too_long"); const made = await send("POST", "/todos", { title: "Replace the UPS battery", detail: "APC, model in the rack", dueDate: day(1), assigneeId: ids.operator, targetType: "server", targetId: ids.web }); assert.equal(made.status, 201); jobId = made.body.todo.id; assert.deepEqual([made.body.todo.title, made.body.todo.assignee.name, made.body.todo.target.name, made.body.todo.doneAt], ["Replace the UPS battery", "Olga", "web", null]); }); test("open jobs come soonest-due first, with those without a day last; ticking one off keeps it, and it comes back", async () => { await send("POST", "/todos", { title: "Someday" }); await send("POST", "/todos", { title: "Next week", dueDate: day(7) }); const open = (await send("GET", "/todos")).body.todos.map((t: any) => t.title); assert.deepEqual(open, ["Replace the UPS battery", "Next week", "Someday"]); const done = await send("PATCH", `/todos/${jobId}`, { done: true }); assert.ok(done.body.todo.doneAt && done.body.todo.doneBy === "Olga"); const after = (await send("GET", "/todos")).body.todos; assert.deepEqual(after.map((t: any) => [t.title, t.doneAt !== null]), [["Next week", false], ["Someday", false], ["Replace the UPS battery", true]], "done ones after the open ones"); const back = await send("PATCH", `/todos/${jobId}`, { done: false }); assert.equal(back.body.todo.doneAt, null); }); test("a job can be changed, and removed; one that is not there is a 404", async () => { const changed = await send("PATCH", `/todos/${jobId}`, { title: "Replace the UPS battery (APC)", dueDate: null, assigneeId: null }); assert.deepEqual([changed.body.todo.title, changed.body.todo.dueDate, changed.body.todo.assignee], ["Replace the UPS battery (APC)", null, null]); assert.equal((await send("PATCH", "/todos/99999", { done: true })).status, 404); assert.equal((await send("DELETE", `/todos/${jobId}`)).status, 204); assert.equal((await send("DELETE", `/todos/${jobId}`)).status, 404); const kinds = (await db.select().from(auditLog).where(eq(auditLog.category, "todo"))).map((e) => e.action); assert.ok(["create", "done", "reopen", "update", "delete"].every((a) => kinds.includes(a)), "each is written down"); }); test("a job about a server that is later removed is still there, about nothing", async () => { const gone = (await db.insert(servers).values({ name: "temp", apiTokenHash: "t", apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id; const made = await send("POST", "/todos", { title: "About temp", targetType: "server", targetId: gone }); await db.delete(servers).where(eq(servers.id, gone)); const found = (await send("GET", "/todos")).body.todos.find((t: any) => t.id === made.body.todo.id); assert.equal(found.target, null); await send("DELETE", `/todos/${made.body.todo.id}`); }); test("an open job with a day is in Coming up (overdue ones too), a done one is not; one handed to somebody is in their My work", async () => { const soon = (await send("POST", "/todos", { title: "Move the NAS", dueDate: day(3), assigneeId: ids.operator })).body.todo; const late = (await send("POST", "/todos", { title: "Order a spare disk", dueDate: day(-2), assigneeId: ids.operator })).body.todo; const finished = (await send("POST", "/todos", { title: "Already done", dueDate: day(2) })).body.todo; await send("PATCH", `/todos/${finished.id}`, { done: true }); const agenda = agendaFromData(await loadAgendaData(), new Date(), "UTC", 30); const titles = agenda.items.filter((i) => i.kind === "todo").map((i) => i.title); assert.ok(titles.includes("To do: Move the NAS") && titles.includes("Overdue: Order a spare disk")); assert.ok(!titles.some((t) => t.includes("Already done"))); const mine = await buildMyWork({ id: ids.operator, name: "Olga", email: null, oidcSub: "operator" }); assert.deepEqual(mine.todos.map((t) => [t.title, t.overdue, t.dueSoon]), [["Order a spare disk", true, false], ["Move the NAS", false, false]], "overdue first; three days off is not yet soon"); assert.ok(mine.needsAttention >= 1, "an overdue job wants a look"); const theirs = await buildMyWork({ id: ids.admin, name: "Ada", email: null, oidcSub: "admin" }); assert.equal(theirs.todos.length, 0); await db.delete(todos); assert.ok(soon && late); }); }); describe("notes", () => { test("read by everyone; written by an operator; an empty text takes it away", async () => { who = "viewer"; assert.equal((await send("GET", `/notes?targetType=server&targetId=${ids.web}`)).body.note, null); assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "x" })).status, 403); who = "operator"; const saved = await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "Lives in the **rack**.\n\n- PSU is on the left" }); assert.deepEqual([saved.status, saved.body.note.updatedBy, saved.body.note.body.includes("**rack**")], [200, "Olga", true]); const again = await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "Replaced." }); assert.equal((await db.select().from(notes)).length, 1, "one text per thing"); assert.equal(again.body.note.body, "Replaced."); who = "viewer"; assert.equal((await send("GET", `/notes?targetType=server&targetId=${ids.web}`)).body.note.body, "Replaced."); who = "operator"; assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: " \n " })).body.note, null); assert.equal((await db.select().from(notes)).length, 0); }); test("a note for nothing, or too long, or about something unknown, is refused", async () => { who = "operator"; assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: 99999, body: "x" })).status, 404); assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "x".repeat(9000) })).body.error, "too_long"); assert.equal((await send("PUT", "/notes", { targetType: "rack", targetId: 1, body: "x" })).status, 400); assert.equal((await send("GET", "/notes?targetType=server")).status, 400); }); });