import { Router } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { db } from "../db/client.js"; import { integrations } from "../db/schema.js"; import { recordAudit } from "../services/audit.js"; import { getAlertTicketStatus, resetBaseline, runAlertTicketCheck, sendTestTicket } from "../services/alertTickets.js"; import { getSettings, updateSettings } from "../services/settingsStore.js"; import { describeSettingsChanges } from "../services/settingsDiff.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { hasTicketApi, type OsTicketApiConfig } from "../integrations/osticket/ticketApi.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const alertTicketsRouter = Router(); alertTicketsRouter.use(requireAuth, requireRole("admin")); // What an alert can be about, as the Alerts page names it. "tickets" (osTicket's own overdue tickets) is never offered: a ticket // about tickets helps nobody. const CATEGORIES = [ { value: "offline", label: "Server down" }, { value: "disk", label: "Disk & storage" }, { value: "backup", label: "Backups" }, { value: "updates", label: "Updates" }, { value: "expiry", label: "Expiry" }, { value: "automation", label: "Automation" }, { value: "integration", label: "Integration failing" }, { value: "monitoring", label: "Monitoring" }, ] as const; async function overview() { const rows = await db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "osticket")); const osticket = []; for (const row of rows) { let ready = false; try { const loaded = await loadIntegrationConfig(row.id); ready = loaded ? hasTicketApi(loaded.config as OsTicketApiConfig) : false; } catch { ready = false; } osticket.push({ id: row.id, name: row.name, enabled: row.enabled, ticketApiReady: ready }); } return { settings: (await getSettings()).alertTickets, integrations: osticket, categories: CATEGORIES, status: await getAlertTicketStatus() }; } alertTicketsRouter.get("/", asyncHandler(async (_req, res) => { res.json(await overview()); })); const updateSchema = z .object({ enabled: z.boolean(), integrationId: z.number().int().positive().nullable(), severities: z.array(z.enum(["critical", "warning", "info"])).max(3), categories: z.array(z.enum(CATEGORIES.map((c) => c.value) as [string, ...string[]])).max(20), requesterName: z.string().max(100), requesterEmail: z.string().max(200).refine((v) => v === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), "That isn't an email address."), topicId: z.number().int().positive().nullable(), priorityId: z.number().int().positive().nullable(), notifyStaff: z.boolean(), existingProblems: z.enum(["ignore", "ticket"]), confirmChecks: z.number().int().min(1).max(10), summaryAbove: z.number().int().min(1).max(50), reopenAfterMinutes: z.number().int().min(0).max(1440), }) .partial(); alertTicketsRouter.put("/", asyncHandler(async (req, res) => { const parsed = updateSchema.safeParse(req.body); if (!parsed.success) { const message = parsed.error.issues[0]?.message ?? "Those settings aren't valid."; return res.status(400).json({ error: "invalid_body", message, details: parsed.error.flatten() }); } const before = (await getSettings()).alertTickets; const after = { ...before, ...parsed.data }; // Switching it on needs everything it uses to be there, so it can't be left "on" and silently doing nothing. if (after.enabled) { if (!after.integrationId) return res.status(400).json({ error: "invalid_settings", message: "Choose which osTicket integration to open tickets in." }); const [row] = await db.select({ type: integrations.type }).from(integrations).where(eq(integrations.id, after.integrationId)).limit(1); if (!row || row.type !== "osticket") return res.status(400).json({ error: "invalid_settings", message: "The chosen integration isn't an osTicket integration." }); const loaded = await loadIntegrationConfig(after.integrationId); if (!loaded || !hasTicketApi(loaded.config as OsTicketApiConfig)) { return res.status(400).json({ error: "invalid_settings", message: "That osTicket integration has no ticket API address and key yet. Add them under Integrations first." }); } if (after.severities.length === 0) return res.status(400).json({ error: "invalid_settings", message: "Choose at least one severity." }); if (!after.requesterEmail.trim()) return res.status(400).json({ error: "invalid_settings", message: "Enter the email the tickets should come from — osTicket needs one for every ticket." }); } await updateSettings({ alertTickets: parsed.data }); // Switched on (or off and on again): what is wrong at that moment is the starting point, not a pile of new tickets. if (!before.enabled !== !after.enabled || parsed.data.existingProblems !== undefined) await resetBaseline(); await recordAudit({ actor: req.currentUser!, category: "settings", action: "update_alert_tickets", targetType: "settings", detail: { changes: describeSettingsChanges({ alertTickets: before }, { alertTickets: parsed.data }).alertTickets ?? {} }, }); res.json(await overview()); })); alertTicketsRouter.post("/test", asyncHandler(async (req, res) => { try { const created = await sendTestTicket(req.currentUser!); res.json({ ok: true, ticketNumber: created.number }); } catch (err) { res.status(502).json({ error: "ticket_failed", message: err instanceof Error ? err.message : String(err) }); } })); alertTicketsRouter.post("/run", asyncHandler(async (req, res) => { const summary = await runAlertTicketCheck({ actor: req.currentUser! }); res.json({ summary, status: await getAlertTicketStatus() }); }));