Bulk close can close the osTicket tickets; Alerts top-level, Records group
Closing several alerts together can now also close their osTicket tickets (one by one, each written on its incident and in the audit log; one that fails does not stop the rest; Undo does not reopen tickets). The single and bulk close share one helper. Alerts moves to the top of the sidebar, and Monthly report and Change log move to a new Records group. Docs updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
215c0de8bf
commit
78822346b1
13 files changed
+234
-37
No files matched your search
@@ -253,6 +253,7 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
|||||||
else closes at the same moment is left as they left it. A ticket that was opened as part of a **summary ticket** (many problems at once) is not closed from here, because it covers other alerts.
|
else closes at the same moment is left as they left it. A ticket that was opened as part of a **summary ticket** (many problems at once) is not closed from here, because it covers other alerts.
|
||||||
- **Test closing** (Settings → Notifications → Alert tickets, next to *Send a test ticket*; administrators): signs in with the login, checks the tables and columns, and then **tries every write a close makes inside a transaction that is rolled back** — so a missing grant is found there and not on the first real ticket. Nothing stays (a counter or two
|
- **Test closing** (Settings → Notifications → Alert tickets, next to *Send a test ticket*; administrators): signs in with the login, checks the tables and columns, and then **tries every write a close makes inside a transaction that is rolled back** — so a missing grant is found there and not on the first real ticket. Nothing stays (a counter or two
|
||||||
inside the database moves on).
|
inside the database moves on).
|
||||||
|
- **Closing several alerts at once:** pick them on the Alerts page and choose *Close*; when some of them have a ticket that can be closed from here, the drawer offers *Also close N osTicket tickets* (with their numbers), and it is closed one ticket after another, each written on its alert's incident and in the audit log as above. One that cannot be closed does not stop the others: the alerts are closed all the same and the message says how many tickets were closed, were already closed, or could not be (with the first reason). Summary tickets and an osTicket with no closing login are counted and left open. **Undo opens the alerts again but cannot reopen the tickets** — the message says so.
|
||||||
- **What the alert shows:** the ticket badge says *(closed)* once it has been closed from here, and the Close drawer says so instead of offering it again. If the ticket cannot be closed, the alert is **still closed** and you are told why; the reason is also written on the incident and in the audit log (`alert_ticket/close_ticket`, `close_ticket_failed`).
|
- **What the alert shows:** the ticket badge says *(closed)* once it has been closed from here, and the Close drawer says so instead of offering it again. If the ticket cannot be closed, the alert is **still closed** and you are told why; the reason is also written on the incident and in the audit log (`alert_ticket/close_ticket`, `close_ticket_failed`).
|
||||||
- **Not verified against a live osTicket — and this is the least verified part of the app.** There was no MySQL/MariaDB server to run it on; it is built from osTicket's published schema and tried only against a pretend database that answers the exact statements it sends. For opening tickets, a real osTicket showed two mistakes that a
|
- **Not verified against a live osTicket — and this is the least verified part of the app.** There was no MySQL/MariaDB server to run it on; it is built from osTicket's published schema and tried only against a pretend database that answers the exact statements it sends. For opening tickets, a real osTicket showed two mistakes that a
|
||||||
stand-in server had hidden, and the same can happen here (a column that is called something else in your version, a status or event that is set up differently). That is what *Test closing* is for: **run it first**, and try the first real close on a ticket that does not matter. If something is wrong the error says what; tell me and I'll adjust.
|
stand-in server had hidden, and the same can happen here (a column that is called something else in your version, a status or event that is set up differently). That is what *Test closing* is for: **run it first**, and try the first real close on a ticket that does not matter. If something is wrong the error says what; tell me and I'll adjust.
|
||||||
|
|||||||
+1
-1
@@ -268,7 +268,7 @@ what it would say right now and *Send it now* sends it at once (through the chan
|
|||||||
|
|
||||||
## The Alerts page
|
## The Alerts page
|
||||||
|
|
||||||
**Operations → Alerts** (the *Now* view; *History* lists every incident that has come and gone) shows what these notifications are about — the problems that exist *right now* — as a list you can look at, filter, and
|
**Alerts** (the *Now* view; *History* lists every incident that has come and gone) shows what these notifications are about — the problems that exist *right now* — as a list you can look at, filter, and
|
||||||
export. It uses the same checks as the notifications above, so a problem appears there for exactly the reason it would be notified, but it differs
|
export. It uses the same checks as the notifications above, so a problem appears there for exactly the reason it would be notified, but it differs
|
||||||
in a few ways:
|
in a few ways:
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ Authentik (OIDC), with local admin/operator/viewer roles.
|
|||||||
|
|
||||||
All modules from the original plan are built:
|
All modules from the original plan are built:
|
||||||
|
|
||||||
- Monorepo scaffold, Tabler-themed app shell with a grouped sidebar (Infrastructure, Apps, Backups, Network, Monitoring, Automation, Operations, Reference, Administration; groups open on demand, the one holding the current page is always open, and what you leave open is remembered)
|
- Monorepo scaffold, Tabler-themed app shell with a grouped sidebar (Infrastructure, Apps, Backups, Network, Monitoring, Automation, Operations, Records, Reference, Administration; groups open on demand, the one holding the current page is always open, and what you leave open is remembered)
|
||||||
- Authentik OIDC login, roles (first user to sign in becomes admin), audit log
|
- Authentik OIDC login, roles (first user to sign in becomes admin), audit log
|
||||||
(changes made in the app, sign-ins and sign-outs with the IP they came from, new accounts, and the log's own
|
(changes made in the app, sign-ins and sign-outs with the IP they came from, new accounts, and the log's own
|
||||||
automatic trimming — attributed to "system"; settings changes show what changed, but never credentials)
|
automatic trimming — attributed to "system"; settings changes show what changed, but never credentials)
|
||||||
@@ -309,7 +309,7 @@ already failing, so old failures aren't announced. Toggle it under Settings →
|
|||||||
Notifications. For Gitea this follows the repo's most recent run on any
|
Notifications. For Gitea this follows the repo's most recent run on any
|
||||||
workflow or branch, the same as the Gitea page shows.
|
workflow or branch, the same as the Gitea page shows.
|
||||||
|
|
||||||
**Alerts** (Operations → Alerts, visible to every role) opens with one line on where things stand — how many problems need attention and, when some are
|
**Alerts** (near the top of the sidebar, visible to every role) opens with one line on where things stand — how many problems need attention and, when some are
|
||||||
held back, which problem explains how many ("nasbox accounts for 3") — and marks each row with a coloured edge by severity. Held-back alerts are nested under
|
held back, which problem explains how many ("nasbox accounts for 3") — and marks each row with a coloured edge by severity. Held-back alerts are nested under
|
||||||
the alert that explains them (switch "Group under their cause" off for the flat list; the choice is remembered): the cause says "Show the 3 alerts held back
|
the alert that explains them (switch "Group under their cause" off for the flat list; the choice is remembered): the cause says "Show the 3 alerts held back
|
||||||
under this" and opens them. It lists everything that's
|
under this" and opens them. It lists everything that's
|
||||||
@@ -344,7 +344,7 @@ problems on the Alerts page are looked at, and one that is new and has lasted tw
|
|||||||
and never one for something under a maintenance window or about osTicket itself. You choose which severities and kinds count (critical and warning by
|
and never one for something under a maintenance window or about osTicket itself. You choose which severities and kinds count (critical and warning by
|
||||||
default), and the Alerts page shows the ticket number on each alert that has one. If many problems appear at once — a network drop that makes thirty
|
default), and the Alerts page shows the ticket number on each alert that has one. If many problems appear at once — a network drop that makes thirty
|
||||||
things look down — they become one summary ticket instead of thirty. Problems already there when you switch it on are left alone unless you ask for
|
things look down — they become one summary ticket instead of thirty. Problems already there when you switch it on are left alone unless you ask for
|
||||||
tickets for them too. osTicket's API can't close or update a ticket, so once it's open it's yours to close — in osTicket, or, if you give the integration a **separate database login that may update tickets**, from the Alerts page: the Close drawer then offers *Also close the osTicket ticket* (it sets the ticket to Closed and writes a note in its thread saying who closed it and why;
|
tickets for them too. osTicket's API can't close or update a ticket, so once it's open it's yours to close — in osTicket, or, if you give the integration a **separate database login that may update tickets**, from the Alerts page: the Close drawer then offers *Also close the osTicket ticket* — for one alert, or for several picked together (the tickets are closed one after another; Undo opens the alerts again but not the tickets) (it sets the ticket to Closed and writes a note in its thread saying who closed it and why;
|
||||||
this writes to osTicket's database, so it checks the tables first, does it all in one transaction, and **Test closing** tries every write and rolls it back). It needs an API key made in osTicket (tied to
|
this writes to osTicket's database, so it checks the tables first, does it all in one transaction, and **Test closing** tries every write and rolls it back). It needs an API key made in osTicket (tied to
|
||||||
this server's IP address, allowed to create tickets), entered on the osTicket integration; "Send a test ticket" checks the whole chain.
|
this server's IP address, allowed to create tickets), entered on the osTicket integration; "Send a test ticket" checks the whole chain.
|
||||||
|
|
||||||
@@ -445,7 +445,7 @@ ask to be reminded: a guest that has backups but no passing test within that man
|
|||||||
0, the default, leaves the reminder off. A guest marked *no need to test* never is. Operators record tests, administrators can remove a mistaken one; the history is
|
0, the default, leaves the reminder off. A guest marked *no need to test* never is. Operators record tests, administrators can remove a mistaken one; the history is
|
||||||
kept, `/metrics` has each subject's age and result, and everything is in the change log.
|
kept, `/metrics` has each subject's age and result, and everything is in the change log.
|
||||||
|
|
||||||
**The change log** (Operations → Change log, operators and administrators) is one list of what has changed, newest first and grouped by day: agents updated,
|
**The change log** (Records → Change log, operators and administrators) is one list of what has changed, newest first and grouped by day: agents updated,
|
||||||
settings changed (with what to what), maintenance started and ended, dependencies edited, hardware added, endpoint checks and restore tests, alerts raised and cleared —
|
settings changed (with what to what), maintenance started and ended, dependencies edited, hardware added, endpoint checks and restore tests, alerts raised and cleared —
|
||||||
each as a sentence. Narrow it by kind of change, by server, by how far back (a day to everything kept), or by a word; "Show older" goes on from where it stopped; CSV
|
each as a sentence. Narrow it by kind of change, by server, by how far back (a day to everything kept), or by a word; "Show older" goes on from where it stopped; CSV
|
||||||
export. A server's Activity card links to its slice of it. Sign-ins and people's own data exports aren't changes and are left out. The raw audit log is the other tab of the same page (Change log → *Raw audit log*).
|
export. A server's Activity card links to its slice of it. Sign-ins and people's own data exports aren't changes and are left out. The raw audit log is the other tab of the same page (Change log → *Raw audit log*).
|
||||||
@@ -510,7 +510,7 @@ the alert back among the unattended; it goes by itself once the alert has been g
|
|||||||
the same problem returning next month is not "still being dealt with". It is in the audit log and in the
|
the same problem returning next month is not "still being dealt with". It is in the audit log and in the
|
||||||
server's history.
|
server's history.
|
||||||
|
|
||||||
**Incidents** (Operations → Alerts → **History**; the Alerts page has two views, *Now* and *History*, and an incident's own page is under it). Each time an alert is raised and later goes away is recorded as an
|
**Incidents** (Alerts → **History**; the Alerts page has two views, *Now* and *History*, and an incident's own page is under it). Each time an alert is raised and later goes away is recorded as an
|
||||||
incident, with when it began and ended and how bad it got, so "what happened on Tuesday night?" has an answer
|
incident, with when it began and ended and how bad it got, so "what happened on Tuesday night?" has an answer
|
||||||
after the alert is gone. Open one for the whole story in order: the alert, who acknowledged it and why, the
|
after the alert is gone. Open one for the whole story in order: the alert, who acknowledged it and why, the
|
||||||
maintenance windows, what was changed on the server, update runs, other alerts about the same thing that
|
maintenance windows, what was changed on the server, update runs, other alerts about the same thing that
|
||||||
@@ -732,7 +732,7 @@ coming back, to the minute), and is measured over calendar months in the notific
|
|||||||
pace so far would end the month), and how each of the last six months went. When **80 %** of the budget is used it is a warning, and when it is overspent a critical alert, until the month turns over — switchable per target. Planned maintenance is
|
pace so far would end the month), and how each of the last six months went. When **80 %** of the budget is used it is a warning, and when it is overspent a critical alert, until the month turns over — switchable per target. Planned maintenance is
|
||||||
**not** taken out: down is down. A target with nothing recorded for the period says so rather than guessing. `/metrics` has the target, the figure and the minutes left; administrators set targets, everyone sees them.
|
**not** taken out: down is down. A target with nothing recorded for the period says so rather than guessing. `/metrics` has the target, the figure and the minutes left; administrators set targets, everyone sees them.
|
||||||
|
|
||||||
**Monthly, quarterly and annual reports** (Operations → Monthly report; and, if switched on, a message on a day of the month). How a calendar month went, on one page that can be read, printed and copied as text:
|
**Monthly, quarterly and annual reports** (Records → Monthly report; and, if switched on, a message on a day of the month). How a calendar month went, on one page that can be read, printed and copied as text:
|
||||||
**availability** (servers, from when each stopped reporting and reported again; endpoints, from every check's answers, kept day by day for years; integrations), **incidents** (how many began and
|
**availability** (servers, from when each stopped reporting and reported again; endpoints, from every check's answers, kept day by day for years; integrations), **incidents** (how many began and
|
||||||
ended, how long they took, the longest, by kind, and which are still open), **updates** (update runs and patch plan runs, how many updates were installed, by server), **restore tests** recorded in the
|
ended, how long they took, the longest, by kind, and which are still open), **updates** (update runs and patch plan runs, how many updates were installed, by server), **restore tests** recorded in the
|
||||||
month and the **backups as they are now**, and what was **renewed** (a certificate or a domain whose expiry moved clearly later — noticed when the app re-reads the date). The month is on the clock of the notification time zone;
|
month and the **backups as they are now**, and what was **renewed** (a certificate or a domain whose expiry moved clearly later — noticed when the app re-reads the date). The month is on the clock of the notification time zone;
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ even further, to admin only:
|
|||||||
- **Alert tickets**: everyone sees which alerts have an osTicket ticket (a
|
- **Alert tickets**: everyone sees which alerts have an osTicket ticket (a
|
||||||
badge on the Alerts page, linking to the ticket in osTicket); switching the
|
badge on the Alerts page, linking to the ticket in osTicket); switching the
|
||||||
feature on, choosing what opens a ticket, and sending a test ticket are
|
feature on, choosing what opens a ticket, and sending a test ticket are
|
||||||
under Settings → Notifications → Alert tickets, which is admin-only. **Closing a ticket** along with an alert (the tick box in the Close drawer) is an operator's, like closing the alert; the login it writes with, and **Test closing**, are administrators'.
|
under Settings → Notifications → Alert tickets, which is admin-only. **Closing a ticket** along with an alert (the tick box in the Close drawer, for one alert or several picked together) is an operator's, like closing the alert; the login it writes with, and **Test closing**, are administrators'.
|
||||||
- **Runbooks**: everyone reads them (on a server's page, an integration's card,
|
- **Runbooks**: everyone reads them (on a server's page, an integration's card,
|
||||||
next to an alert); writing, editing and removing one needs operator.
|
next to an alert); writing, editing and removing one needs operator.
|
||||||
- **Inventory**: everyone can see the hardware (and print its labels); adding, editing and removing needs
|
- **Inventory**: everyone can see the hardware (and print its labels); adding, editing and removing needs
|
||||||
|
|||||||
+1
-1
@@ -485,7 +485,7 @@ maintenance with it. A silenced problem is **not remembered as known**, so one s
|
|||||||
|
|
||||||
Every time an alert was raised and later went away is an **incident**: when it opened and closed, how bad it got, what it was about, what explained it, who acknowledged or was handed it, and — on its
|
Every time an alert was raised and later went away is an **incident**: when it opened and closed, how bad it got, what it was about, what explained it, who acknowledged or was handed it, and — on its
|
||||||
timeline — what was done to the thing in the hour around it (maintenance, a restart, a settings change). People can add notes. The recorder looks at the alerts **every five minutes** whether or not anyone has
|
timeline — what was done to the thing in the hour around it (maintenance, a restart, a settings change). People can add notes. The recorder looks at the alerts **every five minutes** whether or not anyone has
|
||||||
the page open; the same alert coming back is a **new** incident. Resolved incidents are kept **400 days**. They are on **Operations → Alerts → History**, in the read API (`/api/v1/incidents`) and in the
|
the page open; the same alert coming back is a **new** incident. Resolved incidents are kept **400 days**. They are on **Alerts → History**, in the read API (`/api/v1/incidents`) and in the
|
||||||
monthly report.
|
monthly report.
|
||||||
|
|
||||||
### What changed before an incident
|
### What changed before an incident
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import { AckError, assignableUsers, attentionCounts, clearAck, loadAcks, MAX_HOU
|
|||||||
import { recordAudit } from "../services/audit.js";
|
import { recordAudit } from "../services/audit.js";
|
||||||
import { addNote, openIncidentIds } from "../services/incidents.js";
|
import { addNote, openIncidentIds } from "../services/incidents.js";
|
||||||
import { buildNoiseReport, NOISE_DAYS } from "../services/alertNoise.js";
|
import { buildNoiseReport, NOISE_DAYS } from "../services/alertNoise.js";
|
||||||
import { closeTicketForAlert, ticketsForAlerts, type AlertTicketInfo, type TicketCloseOutcome } from "../services/alertTickets.js";
|
import { ticketsForAlerts, type AlertTicketInfo } from "../services/alertTickets.js";
|
||||||
import { CloseError } from "../integrations/osticket/closeTicket.js";
|
import { closeTicketAndRecord, type TicketResult } from "../services/closeAlertTicket.js";
|
||||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
|
||||||
export const alertsRouter = Router();
|
export const alertsRouter = Router();
|
||||||
@@ -159,20 +159,10 @@ alertsRouter.put("/close", requireRole("operator"), asyncHandler(async (req, res
|
|||||||
await recordAudit({ actor, category: "alert", action: "close", ...auditTargetOf(alert), detail: { alertId: alert.id, message: alert.message, note: closed.note } });
|
await recordAudit({ actor, category: "alert", action: "close", ...auditTargetOf(alert), detail: { alertId: alert.id, message: alert.message, note: closed.note } });
|
||||||
invalidateAlertsCache();
|
invalidateAlertsCache();
|
||||||
// The ticket, if asked for. The alert is closed either way: a ticket that could not be closed is said, not hidden, and does not undo the closing.
|
// The ticket, if asked for. The alert is closed either way: a ticket that could not be closed is said, not hidden, and does not undo the closing.
|
||||||
let ticket: { number: string | null; result: TicketCloseOutcome["result"] | "failed"; message: string | null } | null = null;
|
let ticket: TicketResult | null = null;
|
||||||
if (parsed.data.closeTicket) {
|
if (parsed.data.closeTicket) {
|
||||||
const number = (await ticketsForAlerts([alert.id])).get(alert.id)?.number ?? null;
|
const number = (await ticketsForAlerts([alert.id])).get(alert.id)?.number ?? null;
|
||||||
try {
|
ticket = await closeTicketAndRecord({ alert, number, actor, who, reason: closed.note, incidentId });
|
||||||
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 });
|
res.json({ closed: { by: closed.snoozedBy, at: closed.snoozedAt, note: closed.note }, ticket });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { SnoozeError } from "../services/alertSnoozes.js";
|
|||||||
import { recordAudit } from "../services/audit.js";
|
import { recordAudit } from "../services/audit.js";
|
||||||
import { acknowledgeAlerts, BulkInputError, changeAssets, closeAlerts, reopenAlerts, changeServerTag, MAX_BULK, restoreAcks, restoreAssets, restoreServerParents, restoreSnoozes, setServerParents, setServerTags, silenceTargets, snoozeAlerts, targetsOfAlerts, undoSilence, unacknowledgeAlerts, unsnoozeAlerts } from "../services/bulkActions.js";
|
import { acknowledgeAlerts, BulkInputError, changeAssets, closeAlerts, reopenAlerts, changeServerTag, MAX_BULK, restoreAcks, restoreAssets, restoreServerParents, restoreSnoozes, setServerParents, setServerTags, silenceTargets, snoozeAlerts, targetsOfAlerts, undoSilence, unacknowledgeAlerts, unsnoozeAlerts } from "../services/bulkActions.js";
|
||||||
import { addNote, openIncidentIds } from "../services/incidents.js";
|
import { addNote, openIncidentIds } from "../services/incidents.js";
|
||||||
|
import { closeTicketsOfAlerts, type BulkTicketResult } from "../services/closeAlertTicket.js";
|
||||||
|
import { getAlerts } from "../services/alerts.js";
|
||||||
import { InvalidTagError } from "../services/serverTags.js";
|
import { InvalidTagError } from "../services/serverTags.js";
|
||||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
|
|
||||||
@@ -111,7 +113,7 @@ const alertsBody = z.discriminatedUnion("action", [
|
|||||||
z.object({ action: z.literal("snooze"), alertIds: stringIds, until: z.string().min(1).max(40) }),
|
z.object({ action: z.literal("snooze"), alertIds: stringIds, until: z.string().min(1).max(40) }),
|
||||||
z.object({ action: z.literal("unsnooze"), alertIds: stringIds }),
|
z.object({ action: z.literal("unsnooze"), alertIds: stringIds }),
|
||||||
/** "Dealt with, or accepted": hidden with no end, until each gets worse. The note is written on each one's incident. */
|
/** "Dealt with, or accepted": hidden with no end, until each gets worse. The note is written on each one's incident. */
|
||||||
z.object({ action: z.literal("close"), alertIds: stringIds, note: z.string().max(500).nullable().optional() }),
|
z.object({ action: z.literal("close"), alertIds: stringIds, note: z.string().max(500).nullable().optional(), /** Also close the osTicket tickets of those that have one that can be closed from here. Not undone by Undo. */ closeTickets: z.boolean().optional() }),
|
||||||
z.object({ action: z.literal("reopen"), alertIds: stringIds }),
|
z.object({ action: z.literal("reopen"), alertIds: stringIds }),
|
||||||
z.object({ action: z.literal("restore_snoozes"), items: z.array(z.object({ alertId: z.string().min(1).max(600), previous: snoozeRecord.nullable() })).min(1).max(MAX_BULK), closed: z.boolean().optional() }),
|
z.object({ action: z.literal("restore_snoozes"), items: z.array(z.object({ alertId: z.string().min(1).max(600), previous: snoozeRecord.nullable() })).min(1).max(MAX_BULK), closed: z.boolean().optional() }),
|
||||||
z.object({ action: z.literal("acknowledge"), alertIds: stringIds, note: z.string().max(MAX_NOTE).default(""), assigneeId: z.number().int().positive().nullable().default(null), hours: z.number().int().min(1).max(MAX_HOURS).nullable().default(null) }),
|
z.object({ action: z.literal("acknowledge"), alertIds: stringIds, note: z.string().max(MAX_NOTE).default(""), assigneeId: z.number().int().positive().nullable().default(null), hours: z.number().int().min(1).max(MAX_HOURS).nullable().default(null) }),
|
||||||
@@ -166,8 +168,15 @@ alertsBulkRouter.post("/", asyncHandler(async (req, res) => {
|
|||||||
const incidentId = open.get(item.alertId);
|
const incidentId = open.get(item.alertId);
|
||||||
if (incidentId) await addNote(incidentId, who, (note ? "Closed: " + note : "Closed without a note.") + together);
|
if (incidentId) await addNote(incidentId, who, (note ? "Closed: " + note : "Closed without a note.") + together);
|
||||||
}
|
}
|
||||||
await recordAudit({ actor, category: "alert", action: "bulk_close", detail: { changed: r.changed, note, alerts: detailIds(body.alertIds) } });
|
// The tickets, if asked for. The alerts are closed either way; what could not be closed is said, with why.
|
||||||
return res.json(r);
|
let tickets: BulkTicketResult | null = null;
|
||||||
|
if (body.closeTickets && r.undo) {
|
||||||
|
const closedIds = new Set(r.undo.items.map((i) => i.alertId));
|
||||||
|
const here = (await getAlerts(false)).alerts.filter((a) => closedIds.has(a.id));
|
||||||
|
tickets = await closeTicketsOfAlerts(here, { actor, who, reason: note, incidentIds: open });
|
||||||
|
}
|
||||||
|
await recordAudit({ actor, category: "alert", action: "bulk_close", detail: { changed: r.changed, note, alerts: detailIds(body.alertIds), ...(tickets ? { tickets: { closed: tickets.closed, alreadyClosed: tickets.alreadyClosed, failed: tickets.failed.length, notClosable: tickets.notClosable } } : {}) } });
|
||||||
|
return res.json({ ...r, tickets });
|
||||||
}
|
}
|
||||||
case "reopen": {
|
case "reopen": {
|
||||||
const who = nameOf(req);
|
const who = nameOf(req);
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
/**
|
||||||
|
* Closing the osTicket ticket that belongs to an alert, and writing down that it was: the same for one alert (Close, with the tick) and for several at once (Close, picked on the
|
||||||
|
* Alerts page). The alert is closed either way — a ticket that could not be closed is said, never hidden, and never undoes the closing. Closing a ticket cannot be undone from here:
|
||||||
|
* osTicket keeps it closed even if the alert is opened again.
|
||||||
|
*/
|
||||||
|
import { recordAudit } from "./audit.js";
|
||||||
|
import { addNote } from "./incidents.js";
|
||||||
|
import { closeTicketForAlert, ticketsForAlerts, type TicketCloseOutcome } from "./alertTickets.js";
|
||||||
|
import { CloseError } from "../integrations/osticket/closeTicket.js";
|
||||||
|
|
||||||
|
type Actor = Parameters<typeof recordAudit>[0]["actor"];
|
||||||
|
|
||||||
|
export interface TicketResult {
|
||||||
|
number: string | null;
|
||||||
|
result: TicketCloseOutcome["result"] | "failed";
|
||||||
|
message: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetOf = (alert: { target: { type: string; id: number } | null }) => (alert.target ? { targetType: alert.target.type, targetId: alert.target.id } : {});
|
||||||
|
|
||||||
|
/** Closes the ticket of one alert and records it in the audit log and, when there is one, on the alert's incident. Never throws for a ticket that cannot be closed. */
|
||||||
|
export async function closeTicketAndRecord(input: { alert: { id: string; target: { type: string; id: number } | null }; number: string | null; actor: Actor; who: string; reason: string | null; incidentId?: number }): Promise<TicketResult> {
|
||||||
|
const { alert, number, actor, who, reason, incidentId } = input;
|
||||||
|
try {
|
||||||
|
const outcome = await closeTicketForAlert(alert.id, { closedBy: who, reason });
|
||||||
|
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket", ...targetOf(alert), detail: { alertId: alert.id, number: outcome.number, result: outcome.result } });
|
||||||
|
if (incidentId) await addNote(incidentId, who, outcome.result === "closed" ? "osTicket ticket " + outcome.number + " closed." : "osTicket ticket " + outcome.number + " was already closed.");
|
||||||
|
return { number: outcome.number, result: outcome.result, message: null };
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof CloseError ? err.message : "Closing the ticket failed: " + (err instanceof Error ? err.message : String(err));
|
||||||
|
await recordAudit({ actor, category: "alert_ticket", action: "close_ticket_failed", ...targetOf(alert), detail: { alertId: alert.id, number, message } });
|
||||||
|
if (incidentId) await addNote(incidentId, who, "osTicket ticket" + (number ? " " + number : "") + " could not be closed: " + message);
|
||||||
|
return { number, result: "failed", message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BulkTicketResult {
|
||||||
|
/** Closed in osTicket now. */
|
||||||
|
closed: number;
|
||||||
|
/** Not open any more in osTicket, so nothing was changed. */
|
||||||
|
alreadyClosed: number;
|
||||||
|
/** Could be closed from here but was not: why, for each. */
|
||||||
|
failed: { alertId: string; number: string | null; message: string }[];
|
||||||
|
/** Has a ticket that is not closed from here: a summary ticket for several alerts, one already closed from here, or an osTicket with no login for closing. */
|
||||||
|
notClosable: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closes the tickets of these alerts, one after another, for those that have a ticket that can be closed from here (the others are counted, not tried). `incidentIds` is the open
|
||||||
|
* incident of each alert, if it has one. One that fails does not stop the rest.
|
||||||
|
*/
|
||||||
|
export async function closeTicketsOfAlerts(alerts: { id: string; target: { type: string; id: number } | null }[], ctx: { actor: Actor; who: string; reason: string | null; incidentIds: Map<string, number> }): Promise<BulkTicketResult> {
|
||||||
|
const result: BulkTicketResult = { closed: 0, alreadyClosed: 0, failed: [], notClosable: 0 };
|
||||||
|
const tickets = await ticketsForAlerts(alerts.map((a) => a.id));
|
||||||
|
for (const alert of alerts) {
|
||||||
|
const ticket = tickets.get(alert.id);
|
||||||
|
if (!ticket || !ticket.number) continue;
|
||||||
|
if (!ticket.canClose) {
|
||||||
|
result.notClosable++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const r = await closeTicketAndRecord({ alert, number: ticket.number, actor: ctx.actor, who: ctx.who, reason: ctx.reason, incidentId: ctx.incidentIds.get(alert.id) });
|
||||||
|
if (r.result === "closed") result.closed++;
|
||||||
|
else if (r.result === "already_closed") result.alreadyClosed++;
|
||||||
|
else result.failed.push({ alertId: alert.id, number: r.number, message: r.message ?? "it could not be closed" });
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ const { runMigrations } = await import("../src/db/migrate.js");
|
|||||||
const closer = await import("../src/integrations/osticket/closeTicket.js");
|
const closer = await import("../src/integrations/osticket/closeTicket.js");
|
||||||
const svc = await import("../src/services/alertTickets.js");
|
const svc = await import("../src/services/alertTickets.js");
|
||||||
const { alertsRouter } = await import("../src/routes/alerts.js");
|
const { alertsRouter } = await import("../src/routes/alerts.js");
|
||||||
|
const { alertsBulkRouter } = await import("../src/routes/bulk.js");
|
||||||
const { alertTicketsRouter } = await import("../src/routes/alertTickets.js");
|
const { alertTicketsRouter } = await import("../src/routes/alertTickets.js");
|
||||||
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
|
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
|
||||||
const { getIncident, openIncidentIds } = await import("../src/services/incidents.js");
|
const { getIncident, openIncidentIds } = await import("../src/services/incidents.js");
|
||||||
@@ -247,13 +248,14 @@ describe("closing the ticket of an alert", () => {
|
|||||||
integrationId = (await db.insert(integrations).values({ type: "osticket", name: "osTicket", baseUrl: "", config: JSON.stringify({ host: "db.lan", database: "osticket", username: "ro", password: "x", apiUrl: "https://os.lan/", closeUsername: "hm_close", closePassword: "pw" }) }).returning({ id: integrations.id }))[0].id;
|
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;
|
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";
|
const old = "2026-01-01 00:00:00";
|
||||||
for (const name of ["tkA", "tkB", "tkC", "tkD"]) await db.insert(heartbeats).values({ name, token: `hb_${name}`.padEnd(24, "x"), periodMinutes: 60, graceMinutes: 5, serverId: null, createdAt: old });
|
for (const name of ["tkA", "tkB", "tkC", "tkD", "tkE", "tkF", "tkG", "tkH", "tkI", "tkJ", "tkK"]) await db.insert(heartbeats).values({ name, token: `hb_${name}`.padEnd(24, "x"), periodMinutes: 60, graceMinutes: 5, serverId: null, createdAt: old });
|
||||||
const a = express();
|
const a = express();
|
||||||
a.use(express.json());
|
a.use(express.json());
|
||||||
a.use((req, _res, next) => {
|
a.use((req, _res, next) => {
|
||||||
(req as unknown as { session: unknown }).session = { user: { sub: who } };
|
(req as unknown as { session: unknown }).session = { user: { sub: who } };
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
a.use("/api/alerts/bulk", alertsBulkRouter);
|
||||||
a.use("/api/alerts", alertsRouter);
|
a.use("/api/alerts", alertsRouter);
|
||||||
a.use("/api/alert-tickets", alertTicketsRouter);
|
a.use("/api/alert-tickets", alertTicketsRouter);
|
||||||
app = await new Promise<Server>((resolve) => {
|
app = await new Promise<Server>((resolve) => {
|
||||||
@@ -346,6 +348,84 @@ describe("closing the ticket of an alert", () => {
|
|||||||
await assert.rejects(() => svc.closeTicketForAlert(a.id, { closedBy: "Olga", reason: null }), /already been closed/);
|
await assert.rejects(() => svc.closeTicketForAlert(a.id, { closedBy: "Olga", reason: null }), /already been closed/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("closing several alerts, with their tickets", () => {
|
||||||
|
const bulk = (body: unknown) => call("POST", "/alerts/bulk", body);
|
||||||
|
const incidentNotes = async (alertId: string) => (await getIncident((await openIncidentIds([alertId])).get(alertId)!))!.notes.map((n) => n.body);
|
||||||
|
let undoBody: unknown = null;
|
||||||
|
const statusOf = (number: string) => fake.state.tickets.find((x) => x.number === number)!.statusId;
|
||||||
|
|
||||||
|
test("with the tick, each ticket that can be closed from here is closed and written down; a summary ticket, one with no closing login and an alert with no ticket are not tried", async () => {
|
||||||
|
fake = pretend({ tickets: [{ id: 11, number: "100011", statusId: 1 }, { id: 12, number: "100012", statusId: 1 }, { id: 13, number: "100013", statusId: 1 }] });
|
||||||
|
const e = await alertOf("tkE");
|
||||||
|
const f = await alertOf("tkF");
|
||||||
|
const g = await alertOf("tkG");
|
||||||
|
const h = await alertOf("tkH");
|
||||||
|
await ticketFor(e.id, { ticketNumber: "100011" });
|
||||||
|
await ticketFor(f.id, { ticketNumber: "100012", grouped: true });
|
||||||
|
await ticketFor(h.id, { ticketNumber: "100013", integrationId: readOnlyId });
|
||||||
|
const r = await bulk({ action: "close", alertIds: [e.id, f.id, g.id, h.id], note: "Retired with the old host", closeTickets: true });
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal(r.body.changed, 4);
|
||||||
|
undoBody = r.body.undo;
|
||||||
|
assert.deepEqual(r.body.tickets, { closed: 1, alreadyClosed: 0, failed: [], notClosable: 2 });
|
||||||
|
assert.deepEqual([statusOf("100011"), statusOf("100012"), statusOf("100013")], [3, 1, 1]);
|
||||||
|
assert.match(String(fake.state.entries[0].body), /Retired with the old host\n\nClosed from Homelab Manager by Olga\./);
|
||||||
|
assert.deepEqual(await incidentNotes(e.id), ["Closed: Retired with the old host (closed together with 3 others)", "osTicket ticket 100011 closed."]);
|
||||||
|
assert.deepEqual(await incidentNotes(g.id), ["Closed: Retired with the old host (closed together with 3 others)"], "an alert with no ticket says nothing of one");
|
||||||
|
const entries = await db.select().from(auditLog);
|
||||||
|
assert.ok(entries.some((x) => x.category === "alert_ticket" && x.action === "close_ticket"));
|
||||||
|
const summary = entries.filter((x) => x.action === "bulk_close").pop()!;
|
||||||
|
assert.match(String(summary.detail), /"tickets":\{"closed":1,"alreadyClosed":0,"failed":0,"notClosable":2\}/);
|
||||||
|
for (const a of [e, f, g, h]) assert.equal((await alertOf(a.message.split(" ")[0])).closed?.by, "Olga", "all four alerts are closed");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Undo opens the alerts again, but the ticket stays closed and the page no longer offers it", async () => {
|
||||||
|
assert.equal((await bulk(undoBody)).status, 200);
|
||||||
|
const e = await alertOf("tkE");
|
||||||
|
assert.equal(e.closed ?? null, null, "the alert is open again");
|
||||||
|
const info = (await svc.ticketsForAlerts([e.id])).get(e.id)!;
|
||||||
|
assert.deepEqual([info.canClose, statusOf("100011")], [false, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("without the tick the tickets are left alone, and the answer says no tickets were touched", async () => {
|
||||||
|
fake = pretend({ tickets: [{ id: 14, number: "100014", statusId: 1 }] });
|
||||||
|
const i = await alertOf("tkI");
|
||||||
|
await ticketFor(i.id, { ticketNumber: "100014" });
|
||||||
|
const r = await bulk({ action: "close", alertIds: [i.id], note: null });
|
||||||
|
assert.equal(r.body.tickets, null);
|
||||||
|
assert.equal(statusOf("100014"), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("one ticket that cannot be closed does not stop the others: the alerts are all closed and the failure is said, with its number and why", async () => {
|
||||||
|
fake = pretend({ tickets: [{ id: 15, number: "100015", statusId: 1 }, { id: 16, number: "100016", statusId: 1 }, { id: 17, number: "100017", statusId: 3 }] });
|
||||||
|
svc.setTicketCloserForTests((config, input) => (input.number === "100015" ? Promise.reject(new closer.CloseError("failed", "osTicket said no")) : closer.closeTicket(config, input, fake.deps)));
|
||||||
|
try {
|
||||||
|
const j = await alertOf("tkJ");
|
||||||
|
const k = await alertOf("tkK");
|
||||||
|
const l = await alertOf("tkA"); // already closed from here above; it has no open ticket row any more
|
||||||
|
await ticketFor(j.id, { ticketNumber: "100015" });
|
||||||
|
await ticketFor(k.id, { ticketNumber: "100016" });
|
||||||
|
await db.delete(alertTickets).where(eq(alertTickets.alertKey, l.id));
|
||||||
|
await ticketFor(l.id, { ticketNumber: "100017" });
|
||||||
|
const r = await bulk({ action: "close", alertIds: [j.id, k.id, l.id], closeTickets: true });
|
||||||
|
assert.equal(r.body.changed, 3);
|
||||||
|
assert.deepEqual([r.body.tickets.closed, r.body.tickets.alreadyClosed, r.body.tickets.failed.map((x: { number: string; message: string }) => [x.number, x.message])], [1, 1, [["100015", "osTicket said no"]]]);
|
||||||
|
assert.deepEqual([statusOf("100015"), statusOf("100016"), statusOf("100017")], [1, 3, 3]);
|
||||||
|
assert.deepEqual((await incidentNotes(j.id)).slice(-1), ["osTicket ticket 100015 could not be closed: osTicket said no"]);
|
||||||
|
assert.ok((await db.select().from(auditLog)).some((x) => x.action === "close_ticket_failed" && /100015/.test(String(x.detail))));
|
||||||
|
} finally {
|
||||||
|
svc.setTicketCloserForTests((config, input) => closer.closeTicket(config, input, fake.deps));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a viewer cannot close alerts or their tickets in bulk", async () => {
|
||||||
|
who = "viewer";
|
||||||
|
const a = await alertOf("tkA");
|
||||||
|
assert.equal((await bulk({ action: "close", alertIds: [a.id], closeTickets: true })).status, 403);
|
||||||
|
who = "operator";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test("an administrator can test closing for an integration; others cannot; a viewer cannot close an alert at all", async () => {
|
test("an administrator can test closing for an integration; others cannot; a viewer cannot close an alert at all", async () => {
|
||||||
who = "operator";
|
who = "operator";
|
||||||
assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId })).status, 403);
|
assert.equal((await call("POST", "/alert-tickets/test-close", { integrationId })).status, 403);
|
||||||
|
|||||||
@@ -2047,6 +2047,8 @@ export interface BulkResult {
|
|||||||
skipped: { id: string | number; name: string; reason: string }[];
|
skipped: { id: string | number; name: string; reason: string }[];
|
||||||
undo: Record<string, unknown> | null;
|
undo: Record<string, unknown> | null;
|
||||||
silenced?: { type: string; id: number; name: string }[];
|
silenced?: { type: string; id: number; name: string }[];
|
||||||
|
/** Closing several alerts with "also close their osTicket tickets": how the tickets went (not undone by Undo). */
|
||||||
|
tickets?: { closed: number; alreadyClosed: number; failed: { alertId: string; number: string | null; message: string }[]; notClosable: number } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One alert that fires often, from the incident record. */
|
/** One alert that fires often, from the incident record. */
|
||||||
|
|||||||
@@ -79,20 +79,43 @@ export default function CloseDrawer({ alert, onClose, onSaved }: { alert: AlertI
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The same for several alerts at once: one reason for all, written on each one's incident. `onSubmit` does it (and says how it went); the tickets of these alerts are not closed from here. */
|
/**
|
||||||
export function CloseBulkDrawer({ count, onSubmit, onClose }: { count: number; onSubmit: (note: string | null) => Promise<void>; onClose: () => void }) {
|
* The same for several alerts at once: one reason for all, written on each one's incident. `onSubmit` does it (and says how it went). `tickets` says what the picked alerts have in
|
||||||
|
* osTicket: the numbers that can be closed from here, and how many more have a ticket that cannot (a summary ticket, or an osTicket with no login for closing).
|
||||||
|
*/
|
||||||
|
export function CloseBulkDrawer({ count, tickets, onSubmit, onClose }: { count: number; tickets: { closable: string[]; other: number }; onSubmit: (note: string | null, closeTickets: boolean) => Promise<void>; onClose: () => void }) {
|
||||||
const [note, setNote] = useState("");
|
const [note, setNote] = useState("");
|
||||||
|
const [closeTickets, setCloseTickets] = useState(false);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const shown = tickets.closable.slice(0, 8).map((n) => "#" + n).join(", ") + (tickets.closable.length > 8 ? " and " + (tickets.closable.length - 8) + " more" : "");
|
||||||
return (
|
return (
|
||||||
<DetailDrawer title={`Close ${count} alert${count === 1 ? "" : "s"}`} onClose={onClose}>
|
<DetailDrawer title={`Close ${count} alert${count === 1 ? "" : "s"}`} onClose={onClose}>
|
||||||
<div className="text-secondary mb-3">
|
<div className="text-secondary mb-3">
|
||||||
Hide them, with no end. Each comes back only if it <strong>gets worse</strong> than it is now, or if its problem goes away for half an hour and then returns. Until then they are not counted and nothing is sent about them. The reason goes on each one’s
|
Hide them, with no end. Each comes back only if it <strong>gets worse</strong> than it is now, or if its problem goes away for half an hour and then returns. Until then they are not counted and nothing is sent about them. The reason goes on each one’s
|
||||||
incident. Nothing about the things themselves is promised — use <em>Silence</em> for planned work. Their osTicket tickets are not closed from here; close an alert on its own for that.
|
incident. Nothing about the things themselves is promised — use <em>Silence</em> for planned work.
|
||||||
</div>
|
</div>
|
||||||
<label className="form-label" htmlFor="close-bulk-note">
|
<label className="form-label" htmlFor="close-bulk-note">
|
||||||
Why? (optional)
|
Why? (optional)
|
||||||
</label>
|
</label>
|
||||||
<textarea id="close-bulk-note" className="form-control mb-3" rows={3} maxLength={500} value={note} onChange={(e) => setNote(e.target.value)} placeholder="All retired with the old host · accepted · fixed outside the app…" autoFocus />
|
<textarea id="close-bulk-note" className="form-control mb-3" rows={3} maxLength={500} value={note} onChange={(e) => setNote(e.target.value)} placeholder="All retired with the old host · accepted · fixed outside the app…" autoFocus />
|
||||||
|
{tickets.closable.length > 0 && (
|
||||||
|
<div className="mb-3">
|
||||||
|
<label className="form-check">
|
||||||
|
<input type="checkbox" className="form-check-input" checked={closeTickets} onChange={(e) => setCloseTickets(e.target.checked)} />
|
||||||
|
<span className="form-check-label">
|
||||||
|
Also close {tickets.closable.length === 1 ? "osTicket ticket" : `${tickets.closable.length} osTicket tickets`} <strong>{shown}</strong>
|
||||||
|
<span className="d-block text-secondary small">
|
||||||
|
Each is set to Closed in osTicket, with a note in its thread saying who closed it from here and why (your reason above). <strong>Undo opens the alerts again but cannot reopen the tickets.</strong>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{tickets.other > 0 && (
|
||||||
|
<div className="text-secondary small mb-3">
|
||||||
|
{tickets.other === 1 ? "One more has a ticket that stays open" : `${tickets.other} more have tickets that stay open`}: a summary ticket that covers several alerts, or an osTicket with no login for closing tickets (an administrator adds one under Integrations).
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="d-flex gap-2">
|
<div className="d-flex gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -100,7 +123,7 @@ export function CloseBulkDrawer({ count, onSubmit, onClose }: { count: number; o
|
|||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
void onSubmit(note.trim() === "" ? null : note.trim()).finally(() => setBusy(false));
|
void onSubmit(note.trim() === "" ? null : note.trim(), closeTickets && tickets.closable.length > 0).finally(() => setBusy(false));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{busy ? "Closing…" : `Close ${count === 1 ? "the alert" : `all ${count}`}`}
|
{busy ? "Closing…" : `Close ${count === 1 ? "the alert" : `all ${count}`}`}
|
||||||
|
|||||||
+10
-2
@@ -37,6 +37,7 @@ import {
|
|||||||
IconListCheck,
|
IconListCheck,
|
||||||
IconRefresh,
|
IconRefresh,
|
||||||
IconApps,
|
IconApps,
|
||||||
|
IconHistory,
|
||||||
IconBooks,
|
IconBooks,
|
||||||
IconDownload,
|
IconDownload,
|
||||||
IconBox,
|
IconBox,
|
||||||
@@ -82,6 +83,7 @@ export const isGroup = (entry: NavEntry): entry is NavGroup => "items" in entry;
|
|||||||
|
|
||||||
export const NAV: NavEntry[] = [
|
export const NAV: NavEntry[] = [
|
||||||
{ to: "/", label: "Dashboard", icon: <IconLayoutDashboard size={20} /> },
|
{ to: "/", label: "Dashboard", icon: <IconLayoutDashboard size={20} /> },
|
||||||
|
{ to: "/alerts", label: "Alerts", icon: <IconAlertTriangle size={20} /> },
|
||||||
{ to: "/my-work", label: "My work", icon: <IconChecklist size={20} />, minRole: "operator" },
|
{ to: "/my-work", label: "My work", icon: <IconChecklist size={20} />, minRole: "operator" },
|
||||||
{
|
{
|
||||||
id: "infrastructure",
|
id: "infrastructure",
|
||||||
@@ -163,14 +165,20 @@ export const NAV: NavEntry[] = [
|
|||||||
label: "Operations",
|
label: "Operations",
|
||||||
icon: <IconTool size={20} />,
|
icon: <IconTool size={20} />,
|
||||||
items: [
|
items: [
|
||||||
{ to: "/alerts", label: "Alerts", icon: <IconAlertTriangle size={20} /> },
|
|
||||||
{ to: "/maintenance", label: "Maintenance", icon: <IconTool size={20} /> },
|
{ to: "/maintenance", label: "Maintenance", icon: <IconTool size={20} /> },
|
||||||
{ to: "/updates", label: "Updates", icon: <IconDownload size={20} /> },
|
{ to: "/updates", label: "Updates", icon: <IconDownload size={20} /> },
|
||||||
{ to: "/coming-up", label: "Coming up", icon: <IconCalendarEvent size={20} /> },
|
{ to: "/coming-up", label: "Coming up", icon: <IconCalendarEvent size={20} /> },
|
||||||
{ to: "/todo", label: "To do", icon: <IconListDetails size={20} /> },
|
{ to: "/todo", label: "To do", icon: <IconListDetails size={20} /> },
|
||||||
|
{ to: "/osticket", label: "osTicket", icon: <IconTicket size={20} /> },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "records",
|
||||||
|
label: "Records",
|
||||||
|
icon: <IconHistory size={20} />,
|
||||||
|
items: [
|
||||||
{ to: "/reports", label: "Monthly report", icon: <IconReportAnalytics size={20} /> },
|
{ to: "/reports", label: "Monthly report", icon: <IconReportAnalytics size={20} /> },
|
||||||
{ to: "/changes", label: "Change log", icon: <IconGitCommit size={20} />, minRole: "operator" },
|
{ to: "/changes", label: "Change log", icon: <IconGitCommit size={20} />, minRole: "operator" },
|
||||||
{ to: "/osticket", label: "osTicket", icon: <IconTicket size={20} /> },
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Fragment, useEffect, useMemo, useState } from "react";
|
import { Fragment, useEffect, useMemo, useState } from "react";
|
||||||
import { Link, useSearchParams } from "react-router-dom";
|
import { Link, useSearchParams } from "react-router-dom";
|
||||||
import { api, type AlertCategory, type AlertItem, type AlertSeverity, type AlertsReport, type CurrentUser } from "../api/client";
|
import { api, type AlertCategory, type BulkResult, type AlertItem, type AlertSeverity, type AlertsReport, type CurrentUser } from "../api/client";
|
||||||
import { useSortable } from "../hooks/useSortable";
|
import { useSortable } from "../hooks/useSortable";
|
||||||
import SortableTh from "../components/SortableTh";
|
import SortableTh from "../components/SortableTh";
|
||||||
import { usePagination } from "../hooks/usePagination";
|
import { usePagination } from "../hooks/usePagination";
|
||||||
@@ -61,6 +61,16 @@ const alertTabs = (view: "now" | "history" | "noise") => (
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/** What happened to the osTicket tickets when several alerts were closed with them, as a sentence to follow "N alerts closed." */
|
||||||
|
function ticketSentence(t: BulkResult["tickets"]): string {
|
||||||
|
if (!t) return "";
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (t.closed > 0) parts.push(`${plural(t.closed, "osTicket ticket")} closed too — Undo opens the alerts again, not the tickets.`);
|
||||||
|
if (t.alreadyClosed > 0) parts.push(`${plural(t.alreadyClosed, "ticket")} ${t.alreadyClosed === 1 ? "was" : "were"} already closed.`);
|
||||||
|
if (t.failed.length > 0) parts.push(`${plural(t.failed.length, "ticket")} could not be closed (${t.failed[0].message}${t.failed.length > 1 ? "…" : ""}).`);
|
||||||
|
return parts.length > 0 ? " " + parts.join(" ") : "";
|
||||||
|
}
|
||||||
|
|
||||||
export default function Alerts({ user }: { user: CurrentUser }) {
|
export default function Alerts({ user }: { user: CurrentUser }) {
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const view = params.get("view");
|
const view = params.get("view");
|
||||||
@@ -186,6 +196,12 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
|||||||
const here = new Set((report?.alerts ?? []).map((a) => a.id));
|
const here = new Set((report?.alerts ?? []).map((a) => a.id));
|
||||||
return [...picked].filter((id) => here.has(id));
|
return [...picked].filter((id) => here.has(id));
|
||||||
}, [picked, report]);
|
}, [picked, report]);
|
||||||
|
// What the picked alerts have in osTicket: the tickets that can be closed from here, and how many more have one that cannot.
|
||||||
|
const ticketsOfPicked = useMemo(() => {
|
||||||
|
const ids = new Set(pickedIds);
|
||||||
|
const withTicket = (report?.alerts ?? []).filter((a) => ids.has(a.id) && a.ticket?.number && !a.ticket.closedAt);
|
||||||
|
return { closable: withTicket.filter((a) => a.ticket?.canClose).map((a) => a.ticket!.number as string), other: withTicket.filter((a) => !a.ticket?.canClose).length };
|
||||||
|
}, [pickedIds, report]);
|
||||||
const shownIds = useMemo(() => (sorted ?? []).filter((a) => !a.silenced).map((a) => a.id), [sorted]);
|
const shownIds = useMemo(() => (sorted ?? []).filter((a) => !a.silenced).map((a) => a.id), [sorted]);
|
||||||
const allShownPicked = shownIds.length > 0 && shownIds.every((id) => picked.has(id));
|
const allShownPicked = shownIds.length > 0 && shownIds.every((id) => picked.has(id));
|
||||||
function togglePicked(id: string) {
|
function togglePicked(id: string) {
|
||||||
@@ -239,8 +255,8 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
|||||||
setPicked(new Set());
|
setPicked(new Set());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function bulkClose(note: string | null) {
|
async function bulkClose(note: string | null, closeTickets: boolean) {
|
||||||
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "close", alertIds: pickedIds, note }, done: (r) => `${plural(r.changed, "alert")} closed.`, reload: afterBulk });
|
const ok = await doBulk({ call: api.bulk.alerts, body: { action: "close", alertIds: pickedIds, note, ...(closeTickets ? { closeTickets: true } : {}) }, done: (r) => `${plural(r.changed, "alert")} closed.${ticketSentence(r.tickets)}`, reload: afterBulk });
|
||||||
if (ok) {
|
if (ok) {
|
||||||
setBulkForm(null);
|
setBulkForm(null);
|
||||||
setPicked(new Set());
|
setPicked(new Set());
|
||||||
@@ -653,7 +669,7 @@ function AlertsNow({ user, tabs }: { user: CurrentUser; tabs: React.ReactNode })
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{bulkForm === "ack" && <AckBulkDrawer count={pickedIds.length} onSubmit={bulkAck} onClose={() => setBulkForm(null)} />}
|
{bulkForm === "ack" && <AckBulkDrawer count={pickedIds.length} onSubmit={bulkAck} onClose={() => setBulkForm(null)} />}
|
||||||
{bulkForm === "close" && <CloseBulkDrawer count={pickedIds.length} onSubmit={bulkClose} onClose={() => setBulkForm(null)} />}
|
{bulkForm === "close" && <CloseBulkDrawer count={pickedIds.length} tickets={ticketsOfPicked} onSubmit={bulkClose} onClose={() => setBulkForm(null)} />}
|
||||||
{bulkForm === "snooze" && <SnoozeBulkDrawer count={pickedIds.length} onSubmit={bulkSnooze} onClose={() => setBulkForm(null)} />}
|
{bulkForm === "snooze" && <SnoozeBulkDrawer count={pickedIds.length} onSubmit={bulkSnooze} onClose={() => setBulkForm(null)} />}
|
||||||
{bulkForm === "silence" && <SilenceBulkDrawer noun={pickedIds.length === 1 ? "alert" : "alerts"} count={pickedIds.length} canSilenceDependents={false} onSubmit={bulkSilence} onClose={() => setBulkForm(null)} />}
|
{bulkForm === "silence" && <SilenceBulkDrawer noun={pickedIds.length === 1 ? "alert" : "alerts"} count={pickedIds.length} canSilenceDependents={false} onSubmit={bulkSilence} onClose={() => setBulkForm(null)} />}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user