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:
1 parent
a94899865e
commit
5ae61a1ece
21 files changed
+8405
-23
No files matched your search
@@ -781,6 +781,8 @@ export const alertTickets = sqliteTable(
|
||||
lastSeenAt: text("last_seen_at").notNull(), // ISO
|
||||
ticketedAt: text("ticketed_at"), // ISO; when the ticket was opened
|
||||
clearedAt: text("cleared_at"), // ISO; null while the alert is still active
|
||||
ticketClosedAt: text("ticket_closed_at"), // ISO; when this app closed the ticket in osTicket (or found it already closed when asked to)
|
||||
ticketClosedBy: text("ticket_closed_by"), // who asked, as a name
|
||||
},
|
||||
(t) => [index("alert_tickets_key_idx").on(t.alertKey)],
|
||||
);
|
||||
|
||||
@@ -170,6 +170,9 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
||||
},
|
||||
{ key: "apiKey", label: "Ticket API key (optional)", secret: true, optional: true, type: "password" },
|
||||
{ key: "apiInsecure", label: "Allow self-signed certificate (ticket API)", secret: false, type: "checkbox" },
|
||||
// Only for closing a ticket from the Alerts page. osTicket's API cannot close tickets, so this writes to its database (src/integrations/osticket/closeTicket.ts): a separate login, never the read-only one above.
|
||||
{ key: "closeUsername", label: "Database username for closing tickets (optional)", secret: false, optional: true, placeholder: "a separate user that may update tickets — see INTEGRATIONS.md" },
|
||||
{ key: "closePassword", label: "Database password for closing tickets (optional)", secret: true, optional: true, type: "password" },
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Closing a ticket in osTicket — by writing to its database, because its API cannot.
|
||||
*
|
||||
* osTicket's REST API only creates tickets; nothing closes, reopens or comments. So this is the one place in the app that writes to another application's database, and it is
|
||||
* built to be careful about that:
|
||||
*
|
||||
* - It uses its **own login** (closeUsername / closePassword), separate from the read-only one the rest of the integration uses, so closing can be granted to the one account and
|
||||
* never widens what reading is allowed. Without it nothing here runs.
|
||||
* - Before anything is written it **checks that the tables and columns it will touch are there** (information_schema). A different osTicket than the one this was written for
|
||||
* (1.14–1.18) is refused with the list of what is missing, not guessed at.
|
||||
* - What it writes is what osTicket's own "close" does, and nothing else: the ticket's status becomes a *closed* one (the one called "Closed", else the first closed status), its
|
||||
* closed / last-update times are set and it is no longer marked answered or overdue; a **note** in the ticket's thread says it was closed from here, by whom and why; and a
|
||||
* **"closed" event** is recorded so the ticket's history reads like any other. All three in one transaction: all or none.
|
||||
* - It only closes a ticket that is **open**, and only if its status has not changed since it was read (a second person closing it at the same moment is not overwritten).
|
||||
*
|
||||
* It has not been run against a live osTicket by the people who wrote it; the table and column names are osTicket's published schema. "Test closing" (see testCloseAccess)
|
||||
* tries every write inside a transaction it then rolls back, so the first real close need not be the first try.
|
||||
*/
|
||||
import mysql from "mysql2/promise";
|
||||
|
||||
export interface OsTicketCloseConfig {
|
||||
host?: string | boolean;
|
||||
port?: string | boolean;
|
||||
database?: string | boolean;
|
||||
tablePrefix?: string | boolean;
|
||||
closeUsername?: string | boolean;
|
||||
closePassword?: string | boolean;
|
||||
}
|
||||
|
||||
/** The little of a MySQL connection this needs, so it can be tried against a pretend one. */
|
||||
export interface SqlConn {
|
||||
query(sql: string, params?: unknown[]): Promise<[unknown, unknown?]>;
|
||||
beginTransaction(): Promise<unknown>;
|
||||
commit(): Promise<unknown>;
|
||||
rollback(): Promise<unknown>;
|
||||
end(): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface CloseDeps {
|
||||
connect?: () => Promise<SqlConn>;
|
||||
}
|
||||
|
||||
export class CloseError extends Error {
|
||||
constructor(
|
||||
readonly code: "not_configured" | "schema_mismatch" | "ticket_not_found" | "no_thread" | "no_closed_status" | "failed",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface CloseResult {
|
||||
/** closed: it was open and is now closed. already_closed: it was not open (or was closed by somebody at the same moment), so nothing was changed. */
|
||||
result: "closed" | "already_closed";
|
||||
statusName: string | null;
|
||||
}
|
||||
|
||||
const asString = (v: unknown) => (typeof v === "string" ? v.trim() : "");
|
||||
const SAFE_PREFIX = /^[A-Za-z0-9_]*$/;
|
||||
/** The writer's name as osTicket's thread shows it. */
|
||||
export const POSTER = "Homelab Manager";
|
||||
|
||||
/** Whether the integration has a login to close tickets with. */
|
||||
export function hasCloseAccess(config: OsTicketCloseConfig): boolean {
|
||||
return asString(config.closeUsername) !== "" && asString(config.closePassword) !== "" && asString(config.host) !== "" && asString(config.database) !== "";
|
||||
}
|
||||
|
||||
/** What closing touches, table by table (without the prefix): if any of these columns is missing it is not the osTicket this was written for. */
|
||||
export const REQUIRED_COLUMNS: Record<string, string[]> = {
|
||||
ticket: ["ticket_id", "number", "status_id", "dept_id", "topic_id", "closed", "lastupdate", "updated", "isanswered", "isoverdue"],
|
||||
ticket_status: ["id", "name", "state"],
|
||||
thread: ["id", "object_id", "object_type"],
|
||||
thread_entry: ["thread_id", "staff_id", "user_id", "type", "poster", "title", "body", "format", "created", "updated"],
|
||||
thread_event: ["thread_id", "thread_type", "event_id", "staff_id", "team_id", "dept_id", "topic_id", "data", "username", "uid_type", "annulled", "timestamp"],
|
||||
event: ["id", "name"],
|
||||
};
|
||||
|
||||
function prefixOf(config: OsTicketCloseConfig): string {
|
||||
const prefix = asString(config.tablePrefix) || "ost_";
|
||||
// The prefix is spliced into table names (MySQL cannot parameterize an identifier), so it may only be what an identifier is made of.
|
||||
if (!SAFE_PREFIX.test(prefix)) throw new CloseError("failed", "Table prefix may only contain letters, numbers, and underscores");
|
||||
return prefix;
|
||||
}
|
||||
|
||||
async function connect(config: OsTicketCloseConfig): Promise<SqlConn> {
|
||||
if (!hasCloseAccess(config)) throw new CloseError("not_configured", "This osTicket has no login for closing tickets — add one under Integrations.");
|
||||
const conn = await mysql.createConnection({
|
||||
host: asString(config.host),
|
||||
port: Number(asString(config.port)) || 3306,
|
||||
database: asString(config.database),
|
||||
user: asString(config.closeUsername),
|
||||
password: asString(config.closePassword),
|
||||
connectTimeout: 10_000,
|
||||
});
|
||||
return conn as unknown as SqlConn;
|
||||
}
|
||||
|
||||
const rowsOf = (result: [unknown, unknown?]) => result[0] as Record<string, unknown>[];
|
||||
|
||||
/** What is missing from this database for closing to work: empty when it is all there. */
|
||||
export async function schemaProblems(conn: SqlConn, prefix: string): Promise<string[]> {
|
||||
const tables = Object.keys(REQUIRED_COLUMNS).map((t) => `${prefix}${t}`.toLowerCase());
|
||||
const found = rowsOf(await conn.query(`SELECT LOWER(table_name) AS t, LOWER(column_name) AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND LOWER(table_name) IN (${tables.map(() => "?").join(", ")})`, tables));
|
||||
const have = new Map<string, Set<string>>();
|
||||
for (const r of found) {
|
||||
const t = String(r.t);
|
||||
if (!have.has(t)) have.set(t, new Set());
|
||||
have.get(t)!.add(String(r.c));
|
||||
}
|
||||
const problems: string[] = [];
|
||||
for (const [table, columns] of Object.entries(REQUIRED_COLUMNS)) {
|
||||
const name = `${prefix}${table}`.toLowerCase();
|
||||
const cols = have.get(name);
|
||||
if (!cols) {
|
||||
problems.push(`the table ${prefix}${table} is missing or this login cannot see it`);
|
||||
continue;
|
||||
}
|
||||
const missing = columns.filter((c) => !cols.has(c));
|
||||
if (missing.length > 0) problems.push(`${prefix}${table} has no ${missing.join(", ")}`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** The note and the event, the same two inserts for a real close and for the test that is rolled back. */
|
||||
async function insertThreadRecords(conn: SqlConn, p: string, t: { threadId: number; deptId: number; topicId: number; statusId: number; statusName: string; eventId: number }, text: { title: string; body: string }): Promise<void> {
|
||||
await conn.query(
|
||||
`INSERT INTO ${p}thread_entry (thread_id, staff_id, user_id, type, poster, title, body, format, created, updated) VALUES (?, 0, 0, 'N', ?, ?, ?, 'text', NOW(), NOW())`,
|
||||
[t.threadId, POSTER, text.title, text.body],
|
||||
);
|
||||
await conn.query(
|
||||
`INSERT INTO ${p}thread_event (thread_id, thread_type, event_id, staff_id, team_id, dept_id, topic_id, data, username, uid, uid_type, annulled, timestamp) VALUES (?, 'T', ?, 0, 0, ?, ?, ?, ?, NULL, 'S', 0, NOW())`,
|
||||
[t.threadId, t.eventId, t.deptId, t.topicId, JSON.stringify({ status: [t.statusId, t.statusName] }), POSTER],
|
||||
);
|
||||
}
|
||||
|
||||
async function closedStatusAndEvent(conn: SqlConn, p: string): Promise<{ statusId: number; statusName: string; eventId: number }> {
|
||||
const [status] = rowsOf(await conn.query(`SELECT id, name FROM ${p}ticket_status WHERE state = 'closed' ORDER BY (name = 'Closed') DESC, id ASC LIMIT 1`));
|
||||
if (!status) throw new CloseError("no_closed_status", "osTicket has no ticket status in the closed state to move the ticket to.");
|
||||
const [event] = rowsOf(await conn.query(`SELECT id FROM ${p}event WHERE name = 'closed' LIMIT 1`));
|
||||
if (!event) throw new CloseError("schema_mismatch", `${p}event has no "closed" event, so the ticket's history could not be written.`);
|
||||
return { statusId: Number(status.id), statusName: String(status.name), eventId: Number(event.id) };
|
||||
}
|
||||
|
||||
function describeProblems(problems: string[]): string {
|
||||
return `This is not the osTicket the closing was written for (1.14–1.18): ${problems.join("; ")}. Nothing was changed.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the ticket with this number (osTicket's own number, as people see it). `closedBy` and `reason` go into the note. Throws CloseError when it cannot (and then nothing was written).
|
||||
*/
|
||||
export async function closeTicket(config: OsTicketCloseConfig, input: { number: string; closedBy: string; reason: string | null }, deps: CloseDeps = {}): Promise<CloseResult> {
|
||||
const p = prefixOf(config);
|
||||
const conn = await (deps.connect ? deps.connect() : connect(config));
|
||||
try {
|
||||
const problems = await schemaProblems(conn, p);
|
||||
if (problems.length > 0) throw new CloseError("schema_mismatch", describeProblems(problems));
|
||||
|
||||
const [ticket] = rowsOf(
|
||||
await conn.query(`SELECT t.ticket_id AS id, t.status_id AS statusId, t.dept_id AS deptId, t.topic_id AS topicId, ts.state AS state FROM ${p}ticket t JOIN ${p}ticket_status ts ON ts.id = t.status_id WHERE t.number = ? LIMIT 1`, [input.number]),
|
||||
);
|
||||
if (!ticket) throw new CloseError("ticket_not_found", `osTicket has no ticket numbered ${input.number}.`);
|
||||
if (ticket.state !== "open") return { result: "already_closed", statusName: null };
|
||||
|
||||
const [thread] = rowsOf(await conn.query(`SELECT id FROM ${p}thread WHERE object_id = ? AND object_type = 'T' LIMIT 1`, [ticket.id]));
|
||||
if (!thread) throw new CloseError("no_thread", `Ticket ${input.number} has no conversation thread, which closing needs to note it in.`);
|
||||
const closed = await closedStatusAndEvent(conn, p);
|
||||
|
||||
const reason = (input.reason ?? "").trim();
|
||||
const text = { title: "Closed from Homelab Manager", body: `${reason ? `${reason}\n\n` : ""}Closed from Homelab Manager by ${input.closedBy}.` };
|
||||
|
||||
await conn.beginTransaction();
|
||||
try {
|
||||
// Only if it is still as it was read: a ticket somebody else has just closed (or moved on) is left as they left it.
|
||||
const [update] = (await conn.query(`UPDATE ${p}ticket SET status_id = ?, closed = NOW(), lastupdate = NOW(), updated = NOW(), isanswered = 0, isoverdue = 0 WHERE ticket_id = ? AND status_id = ?`, [closed.statusId, ticket.id, ticket.statusId])) as [{ affectedRows?: number }];
|
||||
if (update.affectedRows !== 1) {
|
||||
await conn.rollback();
|
||||
return { result: "already_closed", statusName: null };
|
||||
}
|
||||
await insertThreadRecords(conn, p, { threadId: Number(thread.id), deptId: Number(ticket.deptId ?? 0), topicId: Number(ticket.topicId ?? 0), statusId: closed.statusId, statusName: closed.statusName, eventId: closed.eventId }, text);
|
||||
await conn.commit();
|
||||
} catch (err) {
|
||||
await conn.rollback().catch(() => undefined);
|
||||
throw err;
|
||||
}
|
||||
return { result: "closed", statusName: closed.statusName };
|
||||
} catch (err) {
|
||||
if (err instanceof CloseError) throw err;
|
||||
throw new CloseError("failed", `osTicket's database refused it: ${err instanceof Error ? err.message : String(err)}`);
|
||||
} finally {
|
||||
await conn.end().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export interface CloseAccessReport {
|
||||
ok: boolean;
|
||||
/** What is wrong, in words; empty when ok. */
|
||||
problems: string[];
|
||||
/** What could not be tried (an osTicket with no ticket in it has no thread to note in). */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries closing without closing: the login, the tables and columns, and then the same writes a close makes — against a ticket's thread, inside a transaction that is rolled back
|
||||
* (nothing stays; a counter or two inside the database moves on). So a missing grant is found here, not on the first real ticket.
|
||||
*/
|
||||
export async function testCloseAccess(config: OsTicketCloseConfig, deps: CloseDeps = {}): Promise<CloseAccessReport> {
|
||||
const problems: string[] = [];
|
||||
const notes: string[] = [];
|
||||
let p: string;
|
||||
try {
|
||||
p = prefixOf(config);
|
||||
} catch (err) {
|
||||
return { ok: false, problems: [err instanceof Error ? err.message : String(err)], notes };
|
||||
}
|
||||
let conn: SqlConn;
|
||||
try {
|
||||
conn = await (deps.connect ? deps.connect() : connect(config));
|
||||
} catch (err) {
|
||||
return { ok: false, problems: [err instanceof CloseError ? err.message : `Could not sign in to osTicket's database with that login: ${err instanceof Error ? err.message : String(err)}`], notes };
|
||||
}
|
||||
try {
|
||||
const missing = await schemaProblems(conn, p);
|
||||
if (missing.length > 0) return { ok: false, problems: [describeProblems(missing)], notes };
|
||||
let closed: Awaited<ReturnType<typeof closedStatusAndEvent>>;
|
||||
try {
|
||||
closed = await closedStatusAndEvent(conn, p);
|
||||
} catch (err) {
|
||||
return { ok: false, problems: [err instanceof Error ? err.message : String(err)], notes };
|
||||
}
|
||||
const [sample] = rowsOf(await conn.query(`SELECT th.id AS threadId, t.dept_id AS deptId, t.topic_id AS topicId FROM ${p}thread th JOIN ${p}ticket t ON t.ticket_id = th.object_id WHERE th.object_type = 'T' LIMIT 1`));
|
||||
if (!sample) {
|
||||
notes.push("There is no ticket in osTicket yet, so the writes could not be tried; reading and the tables are fine.");
|
||||
return { ok: true, problems, notes };
|
||||
}
|
||||
await conn.beginTransaction();
|
||||
try {
|
||||
// The ticket update on a ticket that does not exist changes nothing but proves the grant.
|
||||
await conn.query(`UPDATE ${p}ticket SET status_id = status_id, closed = closed, lastupdate = lastupdate, updated = updated, isanswered = isanswered, isoverdue = isoverdue WHERE ticket_id = -1`);
|
||||
await insertThreadRecords(conn, p, { threadId: Number(sample.threadId), deptId: Number(sample.deptId ?? 0), topicId: Number(sample.topicId ?? 0), statusId: closed.statusId, statusName: closed.statusName, eventId: closed.eventId }, { title: "Test", body: "Test of closing access; rolled back." });
|
||||
} catch (err) {
|
||||
problems.push(`The writes were refused: ${err instanceof Error ? err.message : String(err)}. The login needs UPDATE on ${p}ticket (status_id, closed, lastupdate, updated, isanswered, isoverdue) and INSERT on ${p}thread_entry and ${p}thread_event.`);
|
||||
} finally {
|
||||
await conn.rollback().catch(() => undefined);
|
||||
}
|
||||
return { ok: problems.length === 0, problems, notes };
|
||||
} catch (err) {
|
||||
return { ok: false, problems: [`Could not check: ${err instanceof Error ? err.message : String(err)}`], notes };
|
||||
} finally {
|
||||
await conn.end().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
* key is tied to an IP address — osTicket refuses it from anywhere else — and needs "can create tickets". Both are the most
|
||||
* common reason this fails, so the error for a refused key says so.
|
||||
*
|
||||
* What the API can't do is close, reopen or comment on a ticket, so a ticket opened here is the end of this app's part in it.
|
||||
* What the API can't do is close, reopen or comment on a ticket; closing one is done by closeTicket.js, which writes to osTicket's database with a login of its own.
|
||||
*/
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
|
||||
@@ -5,7 +5,8 @@ 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 { 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";
|
||||
@@ -34,13 +35,15 @@ async function overview() {
|
||||
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 });
|
||||
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() };
|
||||
}
|
||||
@@ -113,6 +116,15 @@ alertTicketsRouter.post("/test", asyncHandler(async (req, res) => {
|
||||
}
|
||||
}));
|
||||
|
||||
// "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() });
|
||||
|
||||
@@ -8,7 +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 { ticketsForAlerts, type AlertTicketInfo } from "../services/alertTickets.js";
|
||||
import { closeTicketForAlert, ticketsForAlerts, type AlertTicketInfo, type TicketCloseOutcome } from "../services/alertTickets.js";
|
||||
import { CloseError } from "../integrations/osticket/closeTicket.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const alertsRouter = Router();
|
||||
@@ -138,6 +139,8 @@ const closeSchema = z.object({
|
||||
alertId: z.string().min(1).max(600),
|
||||
/** Why — shown on the alert and written into its incident. */
|
||||
note: z.string().max(MAX_CLOSE_NOTE).nullable().optional(),
|
||||
/** Also close the osTicket ticket opened for it, if there is one that can be closed from here. */
|
||||
closeTicket: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// "I have dealt with it, or I accept it": the alert is hidden with no end, until it gets worse or has gone for half an hour. The reason goes on the incident, so the history says why.
|
||||
@@ -155,7 +158,23 @@ alertsRouter.put("/close", requireRole("operator"), asyncHandler(async (req, res
|
||||
if (incidentId) await addNote(incidentId, who, closed.note ? "Closed: " + closed.note : "Closed without a note.");
|
||||
await recordAudit({ actor, category: "alert", action: "close", ...auditTargetOf(alert), detail: { alertId: alert.id, message: alert.message, note: closed.note } });
|
||||
invalidateAlertsCache();
|
||||
res.json({ closed: { by: closed.snoozedBy, at: closed.snoozedAt, note: closed.note } });
|
||||
// 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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
res.json({ closed: { by: closed.snoozedBy, at: closed.snoozedAt, note: closed.note }, ticket });
|
||||
} catch (err) {
|
||||
if (err instanceof SnoozeError) return res.status(err.status).json({ error: err.code, message: err.message });
|
||||
throw err;
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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":
|
||||
|
||||
Reference in new issue
Block a user