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

@@ -0,0 +1,2 @@
ALTER TABLE `alert_tickets` ADD `ticket_closed_at` text;--> statement-breakpoint
ALTER TABLE `alert_tickets` ADD `ticket_closed_by` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -456,6 +456,13 @@
"when": 1792957211279,
"tag": "0064_soft_wildside",
"breakpoints": true
},
{
"idx": 65,
"version": "6",
"when": 1792958566629,
"tag": "0065_fine_the_enforcers",
"breakpoints": true
}
]
}
+2
View File
@@ -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)],
);
+3
View File
@@ -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";
+14 -2
View File
@@ -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() });
+21 -2
View File
@@ -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;
+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":
+363
View File
@@ -0,0 +1,363 @@
/**
* Closing an osTicket ticket from here: what is written (a status, a note, an event — all or none), that it is refused rather than guessed at when osTicket's tables are not
* what it was written for, that an open ticket only is closed and nobody else's change is overwritten, "Test closing" that tries it all and rolls back, and how it hangs on an alert.
*
* There is no osTicket database to try it on, so the database here is a pretend one that answers the exact statements the code sends (it understands transactions, missing
* columns and a login that may not write). What it cannot tell is whether osTicket's real tables are as published: the docs say that too.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-osclose-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, heartbeats, integrations, alertTickets, auditLog } = await import("../src/db/schema.js");
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 { 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");
const { getChangeLog } = await import("../src/services/changeLog.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
type Conn = import("../src/integrations/osticket/closeTicket.js").SqlConn;
/** A pretend osTicket database that answers what closing asks, with transactions. */
function pretend(opts: { missing?: Record<string, string[]>; noThread?: boolean; noEvent?: boolean; noClosedStatus?: boolean; denyWrite?: RegExp; tickets?: { id: number; number: string; statusId: number }[]; raceOnUpdate?: boolean; prefix?: string } = {}) {
const p = opts.prefix ?? "ost_";
const statuses = opts.noClosedStatus ? [{ id: 1, name: "Open", state: "open" }] : [{ id: 1, name: "Open", state: "open" }, { id: 2, name: "Resolved", state: "closed" }, { id: 3, name: "Closed", state: "closed" }, { id: 4, name: "Archived", state: "archived" }];
const state = {
tickets: (opts.tickets ?? [{ id: 10, number: "100001", statusId: 1 }]).map((t) => ({ ...t, deptId: 1, topicId: 2, closed: null as string | null, isanswered: 1, isoverdue: 1 })),
entries: [] as Record<string, unknown>[],
events: [] as Record<string, unknown>[],
};
let snapshot: string | null = null;
const log: { sql: string; params: unknown[] }[] = [];
const columns = Object.fromEntries(Object.entries(closer.REQUIRED_COLUMNS).map(([t, cols]) => [`${p}${t}`, (cols as string[]).filter((c) => !(opts.missing?.[t] ?? []).includes(c))]));
const conn: Conn & { ended: boolean } = {
ended: false,
async query(sql: string, params: unknown[] = []) {
log.push({ sql, params });
const s = sql.replace(/\s+/g, " ").trim();
if (/information_schema\.columns/.test(s)) {
const wanted = new Set(params.map(String));
return [Object.entries(columns).filter(([t]) => wanted.has(t)).flatMap(([t, cols]) => cols.map((c) => ({ t, c })))];
}
if (/^SELECT t\.ticket_id AS id/.test(s)) {
const t = state.tickets.find((x) => x.number === params[0]);
return [t ? [{ id: t.id, statusId: t.statusId, deptId: t.deptId, topicId: t.topicId, state: statuses.find((x) => x.id === t.statusId)!.state }] : []];
}
if (/FROM \S*thread WHERE object_id/.test(s)) return [opts.noThread ? [] : [{ id: 900 + Number(params[0]) }]];
if (/FROM \S*ticket_status WHERE state = 'closed'/.test(s)) {
const closed = statuses.filter((x) => x.state === "closed").sort((a, b) => Number(b.name === "Closed") - Number(a.name === "Closed") || a.id - b.id);
return [closed.length ? [closed[0]] : []];
}
if (/FROM \S*event WHERE name = 'closed'/.test(s)) return [opts.noEvent ? [] : [{ id: 7 }]];
if (/FROM \S*thread th JOIN/.test(s)) return [state.tickets.length ? [{ threadId: 900 + state.tickets[0].id, deptId: 1, topicId: 2 }] : []];
if (opts.denyWrite && opts.denyWrite.test(s)) throw new Error("INSERT command denied to user 'hm_close'@'%' for table");
if (/^UPDATE \S*ticket SET status_id = status_id/.test(s)) return [{ affectedRows: 0 }];
if (/^UPDATE \S*ticket SET status_id = \?/.test(s)) {
const t = state.tickets.find((x) => x.id === params[1] && x.statusId === params[2]);
if (!t || opts.raceOnUpdate) return [{ affectedRows: 0 }];
t.statusId = Number(params[0]);
t.closed = "now";
t.isanswered = 0;
t.isoverdue = 0;
return [{ affectedRows: 1 }];
}
if (/^INSERT INTO \S*thread_entry/.test(s)) {
state.entries.push({ threadId: params[0], poster: params[1], title: params[2], body: params[3] });
return [{ affectedRows: 1 }];
}
if (/^INSERT INTO \S*thread_event/.test(s)) {
state.events.push({ threadId: params[0], eventId: params[1], deptId: params[2], topicId: params[3], data: params[4], username: params[5] });
return [{ affectedRows: 1 }];
}
throw new Error(`pretend osTicket does not know: ${s.slice(0, 80)}`);
},
async beginTransaction() {
snapshot = JSON.stringify(state);
},
async commit() {
snapshot = null;
},
async rollback() {
if (snapshot !== null) Object.assign(state, JSON.parse(snapshot));
snapshot = null;
},
async end() {
conn.ended = true;
},
};
return { conn, state, log, deps: { connect: async () => conn } };
}
const CONFIG = { host: "db.lan", database: "osticket", closeUsername: "hm_close", closePassword: "pw" };
const writes = (log: { sql: string }[]) => log.filter((l) => /^\s*(UPDATE|INSERT)/i.test(l.sql));
describe("what closing writes", () => {
test("an open ticket is set to Closed, a note says who closed it and why, and the event is recorded — and the connection is let go", async () => {
const o = pretend();
const r = await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: "Fixed outside the app" }, o.deps);
assert.deepEqual(r, { result: "closed", statusName: "Closed" });
const t = o.state.tickets[0];
assert.deepEqual([t.statusId, t.closed, t.isanswered, t.isoverdue], [3, "now", 0, 0], "'Closed', not 'Resolved' (which has the lower id)");
assert.deepEqual(o.state.entries, [{ threadId: 910, poster: "Homelab Manager", title: "Closed from Homelab Manager", body: "Fixed outside the app\n\nClosed from Homelab Manager by Olga." }]);
assert.deepEqual(o.state.events, [{ threadId: 910, eventId: 7, deptId: 1, topicId: 2, data: JSON.stringify({ status: [3, "Closed"] }), username: "Homelab Manager" }]);
assert.equal(o.conn.ended, true);
});
test("without a reason the note still says who; with no status called Closed the first closed one is used", async () => {
const o = pretend();
await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps);
assert.equal(o.state.entries[0].body, "Closed from Homelab Manager by Olga.");
});
test("a ticket that is not open is left alone, with nothing written", async () => {
const o = pretend({ tickets: [{ id: 10, number: "100001", statusId: 3 }] });
assert.deepEqual(await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps), { result: "already_closed", statusName: null });
assert.equal(writes(o.log).length, 0);
});
test("a ticket somebody closes at the same moment is not overwritten: the update changes nothing, the transaction is undone and nothing is added to it", async () => {
const o = pretend({ raceOnUpdate: true });
const r = await closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps);
assert.equal(r.result, "already_closed");
assert.deepEqual([o.state.entries.length, o.state.events.length], [0, 0]);
});
test("if the note or the event cannot be written, nothing was changed: the status is put back", async () => {
const o = pretend({ denyWrite: /^INSERT INTO \S*thread_event/ });
await assert.rejects(
() => closer.closeTicket(CONFIG, { number: "100001", closedBy: "Olga", reason: null }, o.deps),
(err: unknown) => err instanceof closer.CloseError && err.code === "failed" && /denied/.test(err.message),
);
assert.deepEqual([o.state.tickets[0].statusId, o.state.tickets[0].closed, o.state.entries.length], [1, null, 0], "still open, no note");
assert.equal(o.conn.ended, true);
});
test("a table prefix other than ost_ is used, and one that could carry SQL is refused", async () => {
const o = pretend({ prefix: "helpdesk_" });
assert.equal((await closer.closeTicket({ ...CONFIG, tablePrefix: "helpdesk_" }, { number: "100001", closedBy: "Olga", reason: null }, o.deps)).result, "closed");
assert.ok(o.log.some((l) => /UPDATE helpdesk_ticket SET/.test(l.sql)));
await assert.rejects(() => closer.closeTicket({ ...CONFIG, tablePrefix: "ost_; DROP TABLE x" }, { number: "1", closedBy: "x", reason: null }, pretend().deps), /letters, numbers, and underscores/);
});
});
describe("what it refuses to do", () => {
const closeIt = (o: ReturnType<typeof pretend>, number = "100001") => closer.closeTicket(CONFIG, { number, closedBy: "Olga", reason: null }, o.deps);
const code = (c: string) => (err: unknown) => err instanceof closer.CloseError && err.code === c;
test("an osTicket whose tables are not the ones it was written for is refused, saying what is missing, before anything is written", async () => {
const o = pretend({ missing: { thread_event: ["annulled"], ticket: ["isoverdue", "closed"] } });
await assert.rejects(
() => closeIt(o),
(err: unknown) => err instanceof closer.CloseError && err.code === "schema_mismatch" && /ost_thread_event has no annulled/.test(err.message) && /ost_ticket has no closed, isoverdue/.test(err.message) && /Nothing was changed/.test(err.message),
);
assert.equal(writes(o.log).length, 0);
assert.equal(o.conn.ended, true);
});
test("a ticket number that is not there, a ticket with no thread, no closed status and no 'closed' event are each said plainly", async () => {
await assert.rejects(() => closeIt(pretend(), "999999"), code("ticket_not_found"));
await assert.rejects(() => closeIt(pretend({ noThread: true })), code("no_thread"));
await assert.rejects(() => closeIt(pretend({ noClosedStatus: true })), code("no_closed_status"));
await assert.rejects(() => closeIt(pretend({ noEvent: true })), code("schema_mismatch"));
});
test("without a login for it, nothing is attempted", async () => {
assert.equal(closer.hasCloseAccess({ host: "h", database: "d", closeUsername: "u", closePassword: "" }), false);
assert.equal(closer.hasCloseAccess(CONFIG), true);
await assert.rejects(() => closer.closeTicket({ host: "h", database: "d" }, { number: "1", closedBy: "x", reason: null }), code("not_configured"));
});
});
describe("Test closing", () => {
test("everything in order: the writes are tried and every one of them rolled back", async () => {
const o = pretend();
const r = await closer.testCloseAccess(CONFIG, o.deps);
assert.deepEqual([r.ok, r.problems], [true, []]);
assert.deepEqual([o.state.entries.length, o.state.events.length, o.state.tickets[0].statusId], [0, 0, 1], "nothing stayed");
assert.equal(writes(o.log).length, 3, "an update, a note and an event were tried");
assert.equal(o.conn.ended, true);
});
test("a login that may not write is found here, with what it needs", async () => {
const o = pretend({ denyWrite: /^INSERT INTO \S*thread_entry/ });
const r = await closer.testCloseAccess(CONFIG, o.deps);
assert.equal(r.ok, false);
assert.match(r.problems[0], /refused/);
assert.match(r.problems[0], /UPDATE on ost_ticket/);
assert.match(r.problems[0], /INSERT on ost_thread_entry and ost_thread_event/);
});
test("a different osTicket is reported as such; an osTicket with no ticket yet says what could not be tried; a login that cannot sign in is said", async () => {
const bad = await closer.testCloseAccess(CONFIG, pretend({ missing: { event: ["name"] } }).deps);
assert.equal(bad.ok, false);
assert.match(bad.problems[0], /not the osTicket the closing was written for/);
const empty = await closer.testCloseAccess(CONFIG, pretend({ tickets: [] }).deps);
assert.deepEqual([empty.ok, empty.notes.length], [true, 1]);
const refused = await closer.testCloseAccess(CONFIG, { connect: async () => Promise.reject(new Error("Access denied for user")) });
assert.equal(refused.ok, false);
assert.match(refused.problems[0], /Could not sign in to osTicket's database with that login: Access denied/);
assert.equal((await closer.testCloseAccess({ host: "h", database: "d" })).ok, false);
});
});
describe("closing the ticket of an alert", () => {
let app: Server;
let base = "";
let who = "operator";
let integrationId = 0;
let readOnlyId = 0;
const call = async (method: string, path: string, body?: unknown) => {
const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: res.status, body: (await res.json().catch(() => null)) as any };
};
const alertOf = async (name: string) => {
invalidateAlertsCache();
return (await getAlerts(true)).alerts.find((a) => a.message.startsWith(name))!;
};
const ticketFor = (alertKey: string, extra: Partial<typeof alertTickets.$inferInsert> = {}) =>
db.insert(alertTickets).values({ alertKey, status: "open", severity: "warning", message: "m", firstSeenAt: new Date().toISOString(), lastSeenAt: new Date().toISOString(), ticketedAt: new Date().toISOString(), ticketNumber: "100001", integrationId, ...extra });
let fake: ReturnType<typeof pretend>;
before(async () => {
await db.insert(users).values([
{ oidcSub: "operator", name: "Olga", role: "operator" },
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
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 });
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", alertsRouter);
a.use("/api/alert-tickets", alertTicketsRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
fake = pretend();
svc.setTicketCloserForTests((config, input) => closer.closeTicket(config, input, fake.deps));
});
after(() => {
svc.setTicketCloserForTests(null);
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("the alert says whether its ticket can be closed from here: only with a login for it, not a summary ticket, not one already closed", async () => {
const a = await alertOf("tkA");
const b = await alertOf("tkB");
const c = await alertOf("tkC");
await ticketFor(a.id);
await ticketFor(b.id, { integrationId: readOnlyId });
await ticketFor(c.id, { grouped: true });
const info = await svc.ticketsForAlerts([a.id, b.id, c.id]);
assert.deepEqual([info.get(a.id)?.canClose, info.get(b.id)?.canClose, info.get(c.id)?.canClose], [true, false, false]);
assert.equal(info.get(a.id)?.closedAt, null);
});
test("closing the alert with the tick closes its ticket, writes it on the incident and in the logs, and the page no longer offers it", async () => {
fake = pretend();
const a = await alertOf("tkA");
const r = await call("PUT", "/alerts/close", { alertId: a.id, note: "Replaced the job", closeTicket: true });
assert.equal(r.status, 200);
assert.deepEqual(r.body.ticket, { number: "100001", result: "closed", message: null });
assert.equal(fake.state.tickets[0].statusId, 3);
assert.match(String(fake.state.entries[0].body), /Replaced the job\n\nClosed from Homelab Manager by Olga\./);
const incidentId = (await openIncidentIds([a.id])).get(a.id)!;
assert.deepEqual((await getIncident(incidentId))!.notes.map((n) => n.body), ["Closed: Replaced the job", "osTicket ticket 100001 closed."]);
const info = (await svc.ticketsForAlerts([a.id])).get(a.id)!;
assert.deepEqual([info.canClose, info.closedAt === null], [false, false]);
const actions = (await db.select().from(auditLog)).map((e) => `${e.category}/${e.action}`);
assert.ok(actions.includes("alert_ticket/close_ticket"));
assert.ok((await getChangeLog({ days: 1, limit: 300 })).entries.some((e) => /^osTicket ticket 100001 closed from here$/.test(e.title)));
});
test("closing the alert without the tick leaves its ticket alone", async () => {
fake = pretend();
const b = await alertOf("tkD");
await ticketFor(b.id);
const r = await call("PUT", "/alerts/close", { alertId: b.id });
assert.equal(r.body.ticket, null);
assert.equal(fake.state.tickets[0].statusId, 1);
});
test("when the ticket cannot be closed the alert is closed all the same, and the reason is said and written down", async () => {
fake = pretend({ missing: { thread_event: ["annulled"] } });
const b = await alertOf("tkB");
const r = await call("PUT", "/alerts/close", { alertId: b.id, closeTicket: true });
assert.equal(r.status, 200);
assert.equal(r.body.ticket.result, "failed");
assert.match(r.body.ticket.message, /no login for closing tickets|not the osTicket/);
invalidateAlertsCache();
assert.equal((await alertOf("tkB")).closed?.by, "Olga", "the alert is closed");
const actions = (await db.select().from(auditLog)).map((e) => `${e.category}/${e.action}`);
assert.ok(actions.includes("alert_ticket/close_ticket_failed"));
});
test("a ticket that cannot be closed from here, asked for anyway, is said and the alert is still closed", async () => {
const c = await alertOf("tkC");
const r = await call("PUT", "/alerts/close", { alertId: c.id, closeTicket: true });
assert.equal(r.body.ticket.result, "failed");
assert.match(r.body.ticket.message, /summary ticket/);
});
test("an alert with no ticket, asked to close one, closes only the alert", async () => {
const d = await alertOf("tkD");
await call("DELETE", `/alerts/close?alertId=${encodeURIComponent(d.id)}`);
await db.delete(alertTickets).where(eq(alertTickets.alertKey, d.id));
const r = await call("PUT", "/alerts/close", { alertId: d.id, closeTicket: true });
assert.equal(r.status, 200);
assert.equal(r.body.ticket.result, "failed");
assert.match(r.body.ticket.message, /No ticket was opened/);
});
test("a ticket is closed once from here: asking again says so", async () => {
const a = await alertOf("tkA");
await assert.rejects(() => svc.closeTicketForAlert(a.id, { closedBy: "Olga", reason: null }), /already been closed/);
});
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);
who = "admin";
const noLogin = await call("POST", "/alert-tickets/test-close", { integrationId: readOnlyId });
assert.deepEqual([noLogin.body.ok, /no login for closing tickets/.test(noLogin.body.problems[0])], [false, true]);
const overview = await call("GET", "/alert-tickets");
assert.deepEqual(overview.body.integrations.map((i: { id: number; closeReady: boolean }) => [i.id, i.closeReady]), [[integrationId, true], [readOnlyId, false]]);
assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId: "x" })).status, 400);
who = "viewer";
const a = await alertOf("tkA");
assert.equal((await call("PUT", "/alerts/close", { alertId: a.id, closeTicket: true })).status, 403);
who = "operator";
});
});