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>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-25 21:27:38 +01:00
1 parent a94899865e
commit 5ae61a1ece
21 files changed
+8405 -23

No files matched your search

+74 -2
View File
@@ -3,7 +3,7 @@
*
* The Alerts page already works out everything that is wrong right now. This looks at that list every 15 minutes and, for a
* problem that is new and has lasted, opens one ticket — then remembers it, so the same problem never opens a second one however
* many checks see it. What it deliberately does not do: close, reopen or comment on a ticket (osTicket's API can't), or open one
* many checks see it. Closing is separate and by hand (closeTicketForAlert, from the Close drawer, through a login of its own that writes to osTicket's database, since its API cannot); it never reopens or comments on a ticket, and does not open one
* for something under a maintenance window.
*
* planTicketRun() is the decision, a pure function of "the alerts now", "what was remembered" and the settings. Everything else
@@ -19,6 +19,7 @@ import { recordAudit } from "./audit.js";
import { getInternalFlag, getSettings, setInternalFlag, type AlertTicketSettings } from "./settingsStore.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createOsTicketTicketApi, hasTicketApi, ticketUrl, type CreatedTicket, type NewTicket, type OsTicketApiConfig } from "../integrations/osticket/ticketApi.js";
import { CloseError, closeTicket, hasCloseAccess, testCloseAccess, type CloseAccessReport, type CloseResult, type OsTicketCloseConfig } from "../integrations/osticket/closeTicket.js";
type CurrentUser = typeof users.$inferSelect;
export type TicketRow = typeof alertTickets.$inferSelect;
@@ -374,6 +375,10 @@ export interface AlertTicketInfo {
/** Part of a summary ticket that covers several alerts. */
grouped: boolean;
openedAt: string | null;
/** When this app closed it in osTicket (or found it already closed when asked to). */
closedAt: string | null;
/** Whether it can be closed from here: there is a login for it, it is not a summary ticket and it has not been closed. */
canClose: boolean;
}
/** The ticket opened for each of these alerts that has one and is still active, by alert id. */
@@ -403,14 +408,81 @@ export async function ticketsForAlerts(alertIds: string[]): Promise<Map<string,
return apiUrls.get(integrationId) ?? null;
}
const closeReady = new Map<number, boolean>();
async function canCloseVia(integrationId: number | null): Promise<boolean> {
if (integrationId === null) return false;
if (!closeReady.has(integrationId)) {
try {
const loaded = await loadIntegrationConfig(integrationId);
closeReady.set(integrationId, !!loaded && loaded.integration.enabled && hasCloseAccess(loaded.config as OsTicketCloseConfig));
} catch {
closeReady.set(integrationId, false);
}
}
return closeReady.get(integrationId) ?? false;
}
for (const row of rows) {
if (result.has(row.alertKey)) continue;
const base = await apiUrlOf(row.integrationId);
result.set(row.alertKey, { number: row.ticketNumber, url: base && row.ticketNumber ? ticketUrl(base, row.ticketNumber) : null, grouped: row.grouped, openedAt: row.ticketedAt });
result.set(row.alertKey, {
number: row.ticketNumber,
url: base && row.ticketNumber ? ticketUrl(base, row.ticketNumber) : null,
grouped: row.grouped,
openedAt: row.ticketedAt,
closedAt: row.ticketClosedAt,
canClose: !row.grouped && !row.ticketClosedAt && !!row.ticketNumber && (await canCloseVia(row.integrationId)),
});
}
return result;
}
let closerForTests: typeof closeTicket | null = null;
/** Tests put a pretend osTicket in place of the database (and take it away with null). */
export function setTicketCloserForTests(closer: typeof closeTicket | null): void {
closerForTests = closer;
}
export interface TicketCloseOutcome {
number: string;
/** closed: now closed in osTicket. already_closed: it was not open (so nothing was changed). */
result: CloseResult["result"];
}
/**
* Closes the osTicket ticket that was opened for this alert, if there is one, it can be closed from here (see canClose) and nobody has already. Records that it was, so the
* page does not offer it again. Throws a CloseError, with a sentence that says why, when it cannot — and then osTicket was not changed.
*/
export async function closeTicketForAlert(alertId: string, input: { closedBy: string; reason: string | null }, deps: { closer?: typeof closeTicket; now?: () => Date } = {}): Promise<TicketCloseOutcome> {
const [row] = await db
.select()
.from(alertTickets)
.where(and(eq(alertTickets.alertKey, alertId), eq(alertTickets.status, "open"), isNull(alertTickets.clearedAt)))
.orderBy(desc(alertTickets.id))
.limit(1);
if (!row || !row.ticketNumber) throw new CloseError("ticket_not_found", "No ticket was opened for this alert.");
if (row.grouped) throw new CloseError("failed", "It is part of a summary ticket that covers several alerts, so it is not closed from here.");
if (row.ticketClosedAt) throw new CloseError("failed", "That ticket has already been closed from here.");
if (row.integrationId === null) throw new CloseError("not_configured", "The osTicket integration that opened it is gone.");
const loaded = await loadIntegrationConfig(row.integrationId);
if (!loaded || loaded.integration.type !== "osticket") throw new CloseError("not_configured", "The osTicket integration that opened it is gone.");
if (!loaded.integration.enabled) throw new CloseError("not_configured", "The osTicket integration is switched off.");
const config = loaded.config as OsTicketCloseConfig;
if (!hasCloseAccess(config)) throw new CloseError("not_configured", "This osTicket has no login for closing tickets — add one under Integrations.");
const closed = await (deps.closer ?? closerForTests ?? closeTicket)(config, { number: row.ticketNumber, closedBy: input.closedBy, reason: input.reason });
await db.update(alertTickets).set({ ticketClosedAt: (deps.now?.() ?? new Date()).toISOString(), ticketClosedBy: input.closedBy }).where(eq(alertTickets.id, row.id));
return { number: row.ticketNumber, result: closed.result };
}
/** "Test closing" for one osTicket integration: the login, the tables, and the writes tried inside a transaction that is rolled back. */
export async function testClosing(integrationId: number, deps: { tester?: typeof testCloseAccess } = {}): Promise<CloseAccessReport> {
const loaded = await loadIntegrationConfig(integrationId);
if (!loaded || loaded.integration.type !== "osticket") return { ok: false, problems: ["That osTicket integration does not exist."], notes: [] };
const config = loaded.config as OsTicketCloseConfig;
if (!hasCloseAccess(config)) return { ok: false, problems: ["There is no login for closing tickets on this integration yet. Edit it under Integrations and fill in the database username and password for closing."], notes: [] };
return (deps.tester ?? testCloseAccess)(config);
}
export interface AlertTicketStatus {
lastRun: RunSummary | null;
/** Active problems with a ticket / waiting to last long enough / already there when this was switched on. */
+4
View File
@@ -223,6 +223,10 @@ export function describeChange(category: string, action: string, detail: Record<
return { title: `Alert rule removed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "alert/snooze":
return { title: `Alert snoozed${typeof detail.message === "string" ? `: ${detail.message}` : ""}`, tone: "neutral", detail: str(detail.until) ? `until ${str(detail.until)}` : null };
case "alert_ticket/close_ticket":
return { title: `osTicket ticket ${str(detail.number) ?? ""} ${detail.result === "closed" ? "closed from here" : "was already closed"}`.replace(" ", " "), tone: "neutral", detail: null };
case "alert_ticket/close_ticket_failed":
return { title: `osTicket ticket ${str(detail.number) ?? ""} could not be closed`.replace(" ", " "), tone: "bad", detail: str(detail.message) };
case "alert/close":
return { title: `Alert closed${typeof detail.message === "string" ? `: ${detail.message}` : ""}`, tone: "neutral", detail: str(detail.note) };
case "alert/reopen":