/** * The to-do list and notes. A to-do is a small job with a title, maybe a day it is due, a person it is handed to and a server or network device it is about; ticking it * off keeps it (so what was done is still there to read) and un-ticking brings it back. A note is one free-form text about a server or a device. */ import { and, desc, eq, isNull, isNotNull } from "drizzle-orm"; import { db } from "../db/client.js"; import { networkDevices, notes, servers, todos, users } from "../db/schema.js"; export const TARGET_TYPES = ["server", "device"] as const; export type TargetType = (typeof TARGET_TYPES)[number]; export const MAX_TITLE = 160; export const MAX_DETAIL = 2000; export const MAX_NOTE_BODY = 8000; export class TodoError extends Error { constructor( readonly status: number, readonly code: string, message: string, ) { super(message); } } /** A real calendar day, written YYYY-MM-DD. */ export const isRealDay = (v: unknown): v is string => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) && new Date(`${v}T00:00:00Z`).toISOString().startsWith(v); export async function targetName(type: TargetType, id: number): Promise { if (type === "server") return (await db.select({ name: servers.name }).from(servers).where(eq(servers.id, id)).limit(1))[0]?.name ?? null; return (await db.select({ name: networkDevices.name }).from(networkDevices).where(eq(networkDevices.id, id)).limit(1))[0]?.name ?? null; } export interface TodoItem { id: number; title: string; detail: string | null; dueDate: string | null; assignee: { id: number | null; name: string } | null; target: { type: TargetType; id: number; name: string } | null; createdBy: string | null; createdAt: string; doneAt: string | null; doneBy: string | null; } type Row = typeof todos.$inferSelect; async function shape(rows: Row[]): Promise { const serverNames = new Map((await db.select({ id: servers.id, name: servers.name }).from(servers)).map((s) => [s.id, s.name])); const deviceNames = new Map((await db.select({ id: networkDevices.id, name: networkDevices.name }).from(networkDevices)).map((d) => [d.id, d.name])); return rows.map((r) => { const name = r.targetType && r.targetId !== null ? (r.targetType === "server" ? serverNames.get(r.targetId) : deviceNames.get(r.targetId)) : undefined; return { id: r.id, title: r.title, detail: r.detail, dueDate: r.dueDate, assignee: r.assigneeName ? { id: r.assigneeUserId, name: r.assigneeName } : null, // What it was about, if that is still there. target: r.targetType && r.targetId !== null && name ? { type: r.targetType, id: r.targetId, name } : null, createdBy: r.createdBy, createdAt: r.createdAt, doneAt: r.doneAt, doneBy: r.doneBy, }; }); } /** Open ones first, the soonest due first (those with no day last); done ones after, the latest done first. */ export async function listTodos(about?: { type: TargetType; id: number }): Promise { const only = about ? and(eq(todos.targetType, about.type), eq(todos.targetId, about.id)) : undefined; const open = await shape(await db.select().from(todos).where(and(isNull(todos.doneAt), only))); open.sort((a, b) => (a.dueDate ?? "9999-99-99").localeCompare(b.dueDate ?? "9999-99-99") || a.createdAt.localeCompare(b.createdAt) || a.id - b.id); const done = await shape(await db.select().from(todos).where(and(isNotNull(todos.doneAt), only)).orderBy(desc(todos.doneAt)).limit(200)); return [...open, ...done]; } export interface TodoInput { title: string; detail?: string | null; dueDate?: string | null; assigneeId?: number | null; targetType?: TargetType | null; targetId?: number | null; } async function resolveAssignee(id: number | null | undefined): Promise<{ id: number | null; name: string | null }> { if (id === null || id === undefined) return { id: null, name: null }; const [u] = await db.select().from(users).where(eq(users.id, id)).limit(1); if (!u || (u.role !== "admin" && u.role !== "operator")) throw new TodoError(400, "invalid_assignee", "A job can be handed to an administrator or an operator."); return { id: u.id, name: u.name ?? u.email ?? u.oidcSub }; } async function resolveTarget(type: TargetType | null | undefined, id: number | null | undefined): Promise<{ type: TargetType | null; id: number | null }> { if (!type || id === null || id === undefined) return { type: null, id: null }; if (!(await targetName(type, id))) throw new TodoError(400, "unknown_target", "That server or network device is not there."); return { type, id }; } function checked(input: TodoInput) { const title = input.title.trim(); if (!title) throw new TodoError(400, "invalid_body", "Say what is to be done."); if (title.length > MAX_TITLE) throw new TodoError(400, "too_long", `Keep the title under ${MAX_TITLE} characters.`); const detail = (input.detail ?? "").trim(); if (detail.length > MAX_DETAIL) throw new TodoError(400, "too_long", `Keep the details under ${MAX_DETAIL} characters.`); if (input.dueDate !== null && input.dueDate !== undefined && input.dueDate !== "" && !isRealDay(input.dueDate)) throw new TodoError(400, "invalid_date", "That is not a date."); return { title, detail: detail || null, dueDate: input.dueDate ? input.dueDate : null }; } export async function createTodo(input: TodoInput, actor: string, now: Date = new Date()): Promise { const base = checked(input); const who = await resolveAssignee(input.assigneeId); const target = await resolveTarget(input.targetType, input.targetId); const [row] = await db .insert(todos) .values({ ...base, assigneeUserId: who.id, assigneeName: who.name, targetType: target.type, targetId: target.id, createdBy: actor, createdAt: now.toISOString() }) .returning(); return (await shape([row]))[0]; } /** Changes what is given; "done" ticks it off or brings it back. Null if there is no such job. */ export async function updateTodo(id: number, input: Partial & { done?: boolean }, actor: string, now: Date = new Date()): Promise<{ before: TodoItem; after: TodoItem } | null> { const [existing] = await db.select().from(todos).where(eq(todos.id, id)).limit(1); if (!existing) return null; const before = (await shape([existing]))[0]; const set: Partial = {}; if (input.title !== undefined || input.detail !== undefined || input.dueDate !== undefined) { const c = checked({ title: input.title ?? existing.title, detail: input.detail === undefined ? existing.detail : input.detail, dueDate: input.dueDate === undefined ? existing.dueDate : input.dueDate }); Object.assign(set, c); } if (input.assigneeId !== undefined) { const who = await resolveAssignee(input.assigneeId); set.assigneeUserId = who.id; set.assigneeName = who.name; } if (input.targetType !== undefined || input.targetId !== undefined) { const t = await resolveTarget(input.targetType === undefined ? existing.targetType : input.targetType, input.targetId === undefined ? existing.targetId : input.targetId); set.targetType = t.type; set.targetId = t.id; } if (input.done === true && !existing.doneAt) Object.assign(set, { doneAt: now.toISOString(), doneBy: actor }); if (input.done === false) Object.assign(set, { doneAt: null, doneBy: null }); if (Object.keys(set).length > 0) await db.update(todos).set(set).where(eq(todos.id, id)); const [after] = await db.select().from(todos).where(eq(todos.id, id)).limit(1); return { before, after: (await shape([after]))[0] }; } export async function removeTodo(id: number): Promise { const [row] = await db.select().from(todos).where(eq(todos.id, id)).limit(1); if (!row) return null; const item = (await shape([row]))[0]; await db.delete(todos).where(eq(todos.id, id)); return item; } /** Open jobs handed to a person, for My work. */ export async function openTodosFor(userId: number): Promise { const rows = await db.select().from(todos).where(and(isNull(todos.doneAt), eq(todos.assigneeUserId, userId))); const items = await shape(rows); return items.sort((a, b) => (a.dueDate ?? "9999-99-99").localeCompare(b.dueDate ?? "9999-99-99") || a.id - b.id); } // ─── Notes ───────────────────────────────────────────────────────────────── export interface NoteItem { targetType: TargetType; targetId: number; body: string; updatedBy: string | null; updatedAt: string; } export async function getNote(type: TargetType, id: number): Promise { const [row] = await db.select().from(notes).where(and(eq(notes.targetType, type), eq(notes.targetId, id))).limit(1); return row ? { targetType: row.targetType, targetId: row.targetId, body: row.body, updatedBy: row.updatedBy, updatedAt: row.updatedAt } : null; } /** Writes the note of something; an empty text takes it away. Returns what is there now (null when there is none). */ export async function setNote(type: TargetType, id: number, body: string, actor: string, now: Date = new Date()): Promise { const text = body.replace(/\r\n/g, "\n").trimEnd(); if (text.length > MAX_NOTE_BODY) throw new TodoError(400, "too_long", `Keep the note under ${MAX_NOTE_BODY} characters.`); if (!(await targetName(type, id))) throw new TodoError(404, "unknown_target", "That server or network device is not there."); if (text.trim() === "") { await db.delete(notes).where(and(eq(notes.targetType, type), eq(notes.targetId, id))); return null; } const values = { body: text, updatedBy: actor, updatedAt: now.toISOString() }; await db.insert(notes).values({ targetType: type, targetId: id, ...values }).onConflictDoUpdate({ target: [notes.targetType, notes.targetId], set: values }); return getNote(type, id); }