Open an osTicket ticket for an alert that lasts
With Settings -> Alert tickets switched on (off by default), every 15 minutes the problems on the Alerts page are looked at and one that is new and has lasted gets one ticket in osTicket, through its API (POST api/tickets.json, key in X-API-Key). One problem opens one ticket however many checks see it; the app remembers what it has seen in a new alert_tickets table (migration 0015). - Which: critical and warning by default, every kind; severities and kinds are settings. - A problem must be seen in 2 checks in a row first (1-4, a setting), so a blip that fixes itself, like one failed call to an integration, never opens a ticket. - One ticket per occurrence; a problem that clears and returns within 60 minutes is the same one. - More than 5 new problems in one check become a single summary ticket. - Never for alerts under a maintenance window, nor about osTicket itself or its overdue tickets. - Problems already there when it is switched on are left alone by default (the first check records them as a baseline); can be set to ticket them too. - If osTicket can't be reached nothing is recorded, so the next check retries; if a source couldn't be read, a problem isn't treated as gone. Every ticket is audited. The ticket API address, key (stored encrypted) and self-signed option are optional fields on the osTicket integration, which otherwise still only reads the database. The settings page can send a test ticket and run a check now; the Alerts page shows each alert's ticket number, linked to osTicket. osTicket's API can't close or update a ticket, so a ticket opened here is the end of this app's part in it. Tested against a stand-in osTicket, not a real one. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f71756b119
commit
467d1a1a06
14 files changed
+3455
-2
No files matched your search
@@ -0,0 +1,118 @@
|
||||
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() });
|
||||
}));
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Router } from "express";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import { getAlerts } from "../services/alerts.js";
|
||||
import { ticketsForAlerts, type AlertTicketInfo } from "../services/alertTickets.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const alertsRouter = Router();
|
||||
@@ -10,5 +11,13 @@ alertsRouter.use(requireAuth);
|
||||
// Everyone signed in can see it — it's the same server, disk and backup status the other pages already show.
|
||||
// `?refresh=1` asks for a fresh check instead of a recent one.
|
||||
alertsRouter.get("/", asyncHandler(async (req, res) => {
|
||||
res.json(await getAlerts(req.query.refresh === "1"));
|
||||
const report = await getAlerts(req.query.refresh === "1");
|
||||
// The ticket opened for each alert, if there is one. Never allowed to stop the page from loading.
|
||||
let tickets = new Map<string, AlertTicketInfo>();
|
||||
try {
|
||||
tickets = await ticketsForAlerts(report.alerts.map((a) => a.id));
|
||||
} catch (err) {
|
||||
console.error("[alerts] couldn't look up tickets:", err);
|
||||
}
|
||||
res.json({ ...report, alerts: report.alerts.map((a) => ({ ...a, ticket: tickets.get(a.id) ?? null })) });
|
||||
}));
|
||||
Reference in new issue
Block a user