Bulk close can close the osTicket tickets; Alerts top-level, Records group

Closing several alerts together can now also close their osTicket tickets
(one by one, each written on its incident and in the audit log; one that
fails does not stop the rest; Undo does not reopen tickets). The single
and bulk close share one helper. Alerts moves to the top of the sidebar,
and Monthly report and Change log move to a new Records group. Docs updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-26 20:20:28 +01:00
1 parent 215c0de8bf
commit 78822346b1
13 files changed
+234 -37

No files matched your search

+4 -14
View File
@@ -8,8 +8,8 @@ import { AckError, assignableUsers, attentionCounts, clearAck, loadAcks, MAX_HOU
import { recordAudit } from "../services/audit.js";
import { addNote, openIncidentIds } from "../services/incidents.js";
import { buildNoiseReport, NOISE_DAYS } from "../services/alertNoise.js";
import { closeTicketForAlert, ticketsForAlerts, type AlertTicketInfo, type TicketCloseOutcome } from "../services/alertTickets.js";
import { CloseError } from "../integrations/osticket/closeTicket.js";
import { ticketsForAlerts, type AlertTicketInfo } from "../services/alertTickets.js";
import { closeTicketAndRecord, type TicketResult } from "../services/closeAlertTicket.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const alertsRouter = Router();
@@ -159,20 +159,10 @@ alertsRouter.put("/close", requireRole("operator"), asyncHandler(async (req, res
await recordAudit({ actor, category: "alert", action: "close", ...auditTargetOf(alert), detail: { alertId: alert.id, message: alert.message, note: closed.note } });
invalidateAlertsCache();
// The ticket, if asked for. The alert is closed either way: a ticket that could not be closed is said, not hidden, and does not undo the closing.
let ticket: { number: string | null; result: TicketCloseOutcome["result"] | "failed"; message: string | null } | null = null;
let ticket: TicketResult | null = null;
if (parsed.data.closeTicket) {
const number = (await ticketsForAlerts([alert.id])).get(alert.id)?.number ?? null;
try {
const outcome = await closeTicketForAlert(alert.id, { closedBy: who, reason: closed.note });
ticket = { number: outcome.number, result: outcome.result, message: null };
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket", ...auditTargetOf(alert), detail: { alertId: alert.id, number: outcome.number, result: outcome.result } });
if (incidentId) await addNote(incidentId, who, outcome.result === "closed" ? "osTicket ticket " + outcome.number + " closed." : "osTicket ticket " + outcome.number + " was already closed.");
} catch (err) {
const message = err instanceof CloseError ? err.message : "Closing the ticket failed: " + (err instanceof Error ? err.message : String(err));
ticket = { number, result: "failed", message };
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket_failed", ...auditTargetOf(alert), detail: { alertId: alert.id, number, message } });
if (incidentId) await addNote(incidentId, who, "osTicket ticket" + (number ? " " + number : "") + " could not be closed: " + message);
}
ticket = await closeTicketAndRecord({ alert, number, actor, who, reason: closed.note, incidentId });
}
res.json({ closed: { by: closed.snoozedBy, at: closed.snoozedAt, note: closed.note }, ticket });
} catch (err) {
+12 -3
View File
@@ -6,6 +6,8 @@ import { SnoozeError } from "../services/alertSnoozes.js";
import { recordAudit } from "../services/audit.js";
import { acknowledgeAlerts, BulkInputError, changeAssets, closeAlerts, reopenAlerts, changeServerTag, MAX_BULK, restoreAcks, restoreAssets, restoreServerParents, restoreSnoozes, setServerParents, setServerTags, silenceTargets, snoozeAlerts, targetsOfAlerts, undoSilence, unacknowledgeAlerts, unsnoozeAlerts } from "../services/bulkActions.js";
import { addNote, openIncidentIds } from "../services/incidents.js";
import { closeTicketsOfAlerts, type BulkTicketResult } from "../services/closeAlertTicket.js";
import { getAlerts } from "../services/alerts.js";
import { InvalidTagError } from "../services/serverTags.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -111,7 +113,7 @@ const alertsBody = z.discriminatedUnion("action", [
z.object({ action: z.literal("snooze"), alertIds: stringIds, until: z.string().min(1).max(40) }),
z.object({ action: z.literal("unsnooze"), alertIds: stringIds }),
/** "Dealt with, or accepted": hidden with no end, until each gets worse. The note is written on each one's incident. */
z.object({ action: z.literal("close"), alertIds: stringIds, note: z.string().max(500).nullable().optional() }),
z.object({ action: z.literal("close"), alertIds: stringIds, note: z.string().max(500).nullable().optional(), /** Also close the osTicket tickets of those that have one that can be closed from here. Not undone by Undo. */ closeTickets: z.boolean().optional() }),
z.object({ action: z.literal("reopen"), alertIds: stringIds }),
z.object({ action: z.literal("restore_snoozes"), items: z.array(z.object({ alertId: z.string().min(1).max(600), previous: snoozeRecord.nullable() })).min(1).max(MAX_BULK), closed: z.boolean().optional() }),
z.object({ action: z.literal("acknowledge"), alertIds: stringIds, note: z.string().max(MAX_NOTE).default(""), assigneeId: z.number().int().positive().nullable().default(null), hours: z.number().int().min(1).max(MAX_HOURS).nullable().default(null) }),
@@ -166,8 +168,15 @@ alertsBulkRouter.post("/", asyncHandler(async (req, res) => {
const incidentId = open.get(item.alertId);
if (incidentId) await addNote(incidentId, who, (note ? "Closed: " + note : "Closed without a note.") + together);
}
await recordAudit({ actor, category: "alert", action: "bulk_close", detail: { changed: r.changed, note, alerts: detailIds(body.alertIds) } });
return res.json(r);
// The tickets, if asked for. The alerts are closed either way; what could not be closed is said, with why.
let tickets: BulkTicketResult | null = null;
if (body.closeTickets && r.undo) {
const closedIds = new Set(r.undo.items.map((i) => i.alertId));
const here = (await getAlerts(false)).alerts.filter((a) => closedIds.has(a.id));
tickets = await closeTicketsOfAlerts(here, { actor, who, reason: note, incidentIds: open });
}
await recordAudit({ actor, category: "alert", action: "bulk_close", detail: { changed: r.changed, note, alerts: detailIds(body.alertIds), ...(tickets ? { tickets: { closed: tickets.closed, alreadyClosed: tickets.alreadyClosed, failed: tickets.failed.length, notClosable: tickets.notClosable } } : {}) } });
return res.json({ ...r, tickets });
}
case "reopen": {
const who = nameOf(req);
+68
View File
@@ -0,0 +1,68 @@
/**
* Closing the osTicket ticket that belongs to an alert, and writing down that it was: the same for one alert (Close, with the tick) and for several at once (Close, picked on the
* Alerts page). The alert is closed either way — a ticket that could not be closed is said, never hidden, and never undoes the closing. Closing a ticket cannot be undone from here:
* osTicket keeps it closed even if the alert is opened again.
*/
import { recordAudit } from "./audit.js";
import { addNote } from "./incidents.js";
import { closeTicketForAlert, ticketsForAlerts, type TicketCloseOutcome } from "./alertTickets.js";
import { CloseError } from "../integrations/osticket/closeTicket.js";
type Actor = Parameters<typeof recordAudit>[0]["actor"];
export interface TicketResult {
number: string | null;
result: TicketCloseOutcome["result"] | "failed";
message: string | null;
}
const targetOf = (alert: { target: { type: string; id: number } | null }) => (alert.target ? { targetType: alert.target.type, targetId: alert.target.id } : {});
/** Closes the ticket of one alert and records it in the audit log and, when there is one, on the alert's incident. Never throws for a ticket that cannot be closed. */
export async function closeTicketAndRecord(input: { alert: { id: string; target: { type: string; id: number } | null }; number: string | null; actor: Actor; who: string; reason: string | null; incidentId?: number }): Promise<TicketResult> {
const { alert, number, actor, who, reason, incidentId } = input;
try {
const outcome = await closeTicketForAlert(alert.id, { closedBy: who, reason });
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket", ...targetOf(alert), detail: { alertId: alert.id, number: outcome.number, result: outcome.result } });
if (incidentId) await addNote(incidentId, who, outcome.result === "closed" ? "osTicket ticket " + outcome.number + " closed." : "osTicket ticket " + outcome.number + " was already closed.");
return { number: outcome.number, result: outcome.result, message: null };
} catch (err) {
const message = err instanceof CloseError ? err.message : "Closing the ticket failed: " + (err instanceof Error ? err.message : String(err));
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket_failed", ...targetOf(alert), detail: { alertId: alert.id, number, message } });
if (incidentId) await addNote(incidentId, who, "osTicket ticket" + (number ? " " + number : "") + " could not be closed: " + message);
return { number, result: "failed", message };
}
}
export interface BulkTicketResult {
/** Closed in osTicket now. */
closed: number;
/** Not open any more in osTicket, so nothing was changed. */
alreadyClosed: number;
/** Could be closed from here but was not: why, for each. */
failed: { alertId: string; number: string | null; message: string }[];
/** Has a ticket that is not closed from here: a summary ticket for several alerts, one already closed from here, or an osTicket with no login for closing. */
notClosable: number;
}
/**
* Closes the tickets of these alerts, one after another, for those that have a ticket that can be closed from here (the others are counted, not tried). `incidentIds` is the open
* incident of each alert, if it has one. One that fails does not stop the rest.
*/
export async function closeTicketsOfAlerts(alerts: { id: string; target: { type: string; id: number } | null }[], ctx: { actor: Actor; who: string; reason: string | null; incidentIds: Map<string, number> }): Promise<BulkTicketResult> {
const result: BulkTicketResult = { closed: 0, alreadyClosed: 0, failed: [], notClosable: 0 };
const tickets = await ticketsForAlerts(alerts.map((a) => a.id));
for (const alert of alerts) {
const ticket = tickets.get(alert.id);
if (!ticket || !ticket.number) continue;
if (!ticket.canClose) {
result.notClosable++;
continue;
}
const r = await closeTicketAndRecord({ alert, number: ticket.number, actor: ctx.actor, who: ctx.who, reason: ctx.reason, incidentId: ctx.incidentIds.get(alert.id) });
if (r.result === "closed") result.closed++;
else if (r.result === "already_closed") result.alreadyClosed++;
else result.failed.push({ alertId: alert.id, number: r.number, message: r.message ?? "it could not be closed" });
}
return result;
}
+81 -1
View File
@@ -28,6 +28,7 @@ const { runMigrations } = await import("../src/db/migrate.js");
const closer = await import("../src/integrations/osticket/closeTicket.js");
const svc = await import("../src/services/alertTickets.js");
const { alertsRouter } = await import("../src/routes/alerts.js");
const { alertsBulkRouter } = await import("../src/routes/bulk.js");
const { alertTicketsRouter } = await import("../src/routes/alertTickets.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { getIncident, openIncidentIds } = await import("../src/services/incidents.js");
@@ -247,13 +248,14 @@ describe("closing the ticket of an alert", () => {
integrationId = (await db.insert(integrations).values({ type: "osticket", name: "osTicket", baseUrl: "", config: JSON.stringify({ host: "db.lan", database: "osticket", username: "ro", password: "x", apiUrl: "https://os.lan/", closeUsername: "hm_close", closePassword: "pw" }) }).returning({ id: integrations.id }))[0].id;
readOnlyId = (await db.insert(integrations).values({ type: "osticket", name: "osTicket (read only)", baseUrl: "", config: JSON.stringify({ host: "db2.lan", database: "osticket", username: "ro", password: "x", apiUrl: "https://os2.lan/" }) }).returning({ id: integrations.id }))[0].id;
const old = "2026-01-01 00:00:00";
for (const name of ["tkA", "tkB", "tkC", "tkD"]) await db.insert(heartbeats).values({ name, token: `hb_${name}`.padEnd(24, "x"), periodMinutes: 60, graceMinutes: 5, serverId: null, createdAt: old });
for (const name of ["tkA", "tkB", "tkC", "tkD", "tkE", "tkF", "tkG", "tkH", "tkI", "tkJ", "tkK"]) await db.insert(heartbeats).values({ name, token: `hb_${name}`.padEnd(24, "x"), periodMinutes: 60, graceMinutes: 5, serverId: null, createdAt: old });
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/alerts/bulk", alertsBulkRouter);
a.use("/api/alerts", alertsRouter);
a.use("/api/alert-tickets", alertTicketsRouter);
app = await new Promise<Server>((resolve) => {
@@ -346,6 +348,84 @@ describe("closing the ticket of an alert", () => {
await assert.rejects(() => svc.closeTicketForAlert(a.id, { closedBy: "Olga", reason: null }), /already been closed/);
});
describe("closing several alerts, with their tickets", () => {
const bulk = (body: unknown) => call("POST", "/alerts/bulk", body);
const incidentNotes = async (alertId: string) => (await getIncident((await openIncidentIds([alertId])).get(alertId)!))!.notes.map((n) => n.body);
let undoBody: unknown = null;
const statusOf = (number: string) => fake.state.tickets.find((x) => x.number === number)!.statusId;
test("with the tick, each ticket that can be closed from here is closed and written down; a summary ticket, one with no closing login and an alert with no ticket are not tried", async () => {
fake = pretend({ tickets: [{ id: 11, number: "100011", statusId: 1 }, { id: 12, number: "100012", statusId: 1 }, { id: 13, number: "100013", statusId: 1 }] });
const e = await alertOf("tkE");
const f = await alertOf("tkF");
const g = await alertOf("tkG");
const h = await alertOf("tkH");
await ticketFor(e.id, { ticketNumber: "100011" });
await ticketFor(f.id, { ticketNumber: "100012", grouped: true });
await ticketFor(h.id, { ticketNumber: "100013", integrationId: readOnlyId });
const r = await bulk({ action: "close", alertIds: [e.id, f.id, g.id, h.id], note: "Retired with the old host", closeTickets: true });
assert.equal(r.status, 200);
assert.equal(r.body.changed, 4);
undoBody = r.body.undo;
assert.deepEqual(r.body.tickets, { closed: 1, alreadyClosed: 0, failed: [], notClosable: 2 });
assert.deepEqual([statusOf("100011"), statusOf("100012"), statusOf("100013")], [3, 1, 1]);
assert.match(String(fake.state.entries[0].body), /Retired with the old host\n\nClosed from Homelab Manager by Olga\./);
assert.deepEqual(await incidentNotes(e.id), ["Closed: Retired with the old host (closed together with 3 others)", "osTicket ticket 100011 closed."]);
assert.deepEqual(await incidentNotes(g.id), ["Closed: Retired with the old host (closed together with 3 others)"], "an alert with no ticket says nothing of one");
const entries = await db.select().from(auditLog);
assert.ok(entries.some((x) => x.category === "alert_ticket" && x.action === "close_ticket"));
const summary = entries.filter((x) => x.action === "bulk_close").pop()!;
assert.match(String(summary.detail), /"tickets":\{"closed":1,"alreadyClosed":0,"failed":0,"notClosable":2\}/);
for (const a of [e, f, g, h]) assert.equal((await alertOf(a.message.split(" ")[0])).closed?.by, "Olga", "all four alerts are closed");
});
test("Undo opens the alerts again, but the ticket stays closed and the page no longer offers it", async () => {
assert.equal((await bulk(undoBody)).status, 200);
const e = await alertOf("tkE");
assert.equal(e.closed ?? null, null, "the alert is open again");
const info = (await svc.ticketsForAlerts([e.id])).get(e.id)!;
assert.deepEqual([info.canClose, statusOf("100011")], [false, 3]);
});
test("without the tick the tickets are left alone, and the answer says no tickets were touched", async () => {
fake = pretend({ tickets: [{ id: 14, number: "100014", statusId: 1 }] });
const i = await alertOf("tkI");
await ticketFor(i.id, { ticketNumber: "100014" });
const r = await bulk({ action: "close", alertIds: [i.id], note: null });
assert.equal(r.body.tickets, null);
assert.equal(statusOf("100014"), 1);
});
test("one ticket that cannot be closed does not stop the others: the alerts are all closed and the failure is said, with its number and why", async () => {
fake = pretend({ tickets: [{ id: 15, number: "100015", statusId: 1 }, { id: 16, number: "100016", statusId: 1 }, { id: 17, number: "100017", statusId: 3 }] });
svc.setTicketCloserForTests((config, input) => (input.number === "100015" ? Promise.reject(new closer.CloseError("failed", "osTicket said no")) : closer.closeTicket(config, input, fake.deps)));
try {
const j = await alertOf("tkJ");
const k = await alertOf("tkK");
const l = await alertOf("tkA"); // already closed from here above; it has no open ticket row any more
await ticketFor(j.id, { ticketNumber: "100015" });
await ticketFor(k.id, { ticketNumber: "100016" });
await db.delete(alertTickets).where(eq(alertTickets.alertKey, l.id));
await ticketFor(l.id, { ticketNumber: "100017" });
const r = await bulk({ action: "close", alertIds: [j.id, k.id, l.id], closeTickets: true });
assert.equal(r.body.changed, 3);
assert.deepEqual([r.body.tickets.closed, r.body.tickets.alreadyClosed, r.body.tickets.failed.map((x: { number: string; message: string }) => [x.number, x.message])], [1, 1, [["100015", "osTicket said no"]]]);
assert.deepEqual([statusOf("100015"), statusOf("100016"), statusOf("100017")], [1, 3, 3]);
assert.deepEqual((await incidentNotes(j.id)).slice(-1), ["osTicket ticket 100015 could not be closed: osTicket said no"]);
assert.ok((await db.select().from(auditLog)).some((x) => x.action === "close_ticket_failed" && /100015/.test(String(x.detail))));
} finally {
svc.setTicketCloserForTests((config, input) => closer.closeTicket(config, input, fake.deps));
}
});
test("a viewer cannot close alerts or their tickets in bulk", async () => {
who = "viewer";
const a = await alertOf("tkA");
assert.equal((await bulk({ action: "close", alertIds: [a.id], closeTickets: true })).status, 403);
who = "operator";
});
});
test("an administrator can test closing for an integration; others cannot; a viewer cannot close an alert at all", async () => {
who = "operator";
assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId })).status, 403);