Files
Homelab-manager/server/src/routes/alertTickets.ts
T
bobbanandClaude Sonnet 5.5 5ae61a1ece Close the osTicket ticket along with an alert
The Close drawer can also close the alert's osTicket ticket. osTicket's API
cannot, so this writes to its database with a separate, optional login: the
ticket is set to Closed, a note in its thread says who closed it and why, and
the closed event is recorded, in one transaction. Tables and columns are
checked first, only an open ticket is closed, and a ticket closed by somebody
else at the same moment is left alone. Summary tickets are not closed from here.

"Test closing" (Alert tickets settings) tries every write and rolls it back.
If the ticket cannot be closed the alert is still closed and the reason is
said, noted on the incident and audited.

Not run against a real osTicket: tested against a pretend database only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 21:27:38 +01:00

132 lines
6.8 KiB
TypeScript

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, testClosing } from "../services/alertTickets.js";
import { hasCloseAccess, type OsTicketCloseConfig } from "../integrations/osticket/closeTicket.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: "services", label: "Failing services" },
{ 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;
let closeReady = false;
try {
const loaded = await loadIntegrationConfig(row.id);
ready = loaded ? hasTicketApi(loaded.config as OsTicketApiConfig) : false;
closeReady = loaded ? hasCloseAccess(loaded.config as OsTicketCloseConfig) : false;
} catch {
ready = false;
}
osticket.push({ id: row.id, name: row.name, enabled: row.enabled, ticketApiReady: ready, closeReady });
}
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) });
}
}));
// "Test closing": the login, the tables and the writes a close makes, tried inside a transaction that is rolled back. Changes nothing that stays.
alertTicketsRouter.post("/test-close", asyncHandler(async (req, res) => {
const parsed = z.object({ integrationId: z.number().int().positive() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say which osTicket integration." });
const report = await testClosing(parsed.data.integrationId);
await recordAudit({ actor: req.currentUser!, category: "alert_ticket", action: "test_close", targetType: "integration", targetId: parsed.data.integrationId, detail: { ok: report.ok } });
res.json(report);
}));
alertTicketsRouter.post("/run", asyncHandler(async (req, res) => {
const summary = await runAlertTicketCheck({ actor: req.currentUser! });
res.json({ summary, status: await getAlertTicketStatus() });
}));