The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Count webhook channels in alert management (#75379)
Ngoc Khuatc13ba1bcc864
diff --git a/frontend/src/metabase-types/api/mocks/notification.ts b/frontend/src/metabase-types/api/mocks/notification.tsindex 6e66d234d91..089c1a054eb 100644--- a/frontend/src/metabase-types/api/mocks/notification.ts+++ b/frontend/src/metabase-types/api/mocks/notification.ts@@ -3,6 +3,7 @@ import type {Notification,NotificationCronSubscription,NotificationHandlerEmail,+ NotificationHandlerHttp,NotificationHandlerSlack,NotificationRecipientUser,} from "metabase-types/api";@@ -93,6 +94,23 @@ export const createMockNotificationHandlerSlack = (...opts,});+export const createMockNotificationHandlerHttp = (+ opts?: Partial<NotificationHandlerHttp>,+): NotificationHandlerHttp => ({+ template_id: null,+ channel_id: 1,+ channel_type: "channel/http",+ channel: null,+ template: null,+ recipients: [],+ updated_at: "2025-01-07T18:40:47.245205+03:00",+ notification_id: 10,+ active: true,+ id: 14,+ created_at: "2025-01-07T18:40:47.245205+03:00",+ ...opts,+});+export const createMockNotificationCronSubscription = (opts?: Partial<NotificationCronSubscription>,): NotificationCronSubscription => ({diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsxindex 27a20d00bee..1dbf54a5995 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx@@ -15,14 +15,14 @@ export const DetailsSection = ({notification,emailRecipientCount,slackChannelCount,- httpHandler,+ webhookCount,}: DetailsSectionProps) => {const cardId = notification.payload?.card_id;const cardName = notification.payload?.card?.name;const channelSummary = formatChannelSummary({emailRecipientCount,slackChannelCount,- httpHandler,+ webhookCount,});const creator = notification.creator;const ownerName = creator?.common_name ?? creator?.email ?? t`Unknown`;diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsxindex cb652d4bd63..cd617524104 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx@@ -1,11 +1,7 @@import { t } from "ttag";+import { summarizeChannels } from "metabase/admin/tools/notifications/utils";import { Flex, Stack, Text } from "metabase/ui";-import type {- NotificationHandlerEmail,- NotificationHandlerHttp,- NotificationHandlerSlack,-} from "metabase-types/api";import { trackAlertsManagementRunHistoryViewAllClicked } from "../analytics";@@ -25,21 +21,12 @@ export const SidebarBody = ({isDetailFetching,detail,}: SidebarBodyProps) => {- const handlers = notification.handlers ?? [];- const emailHandler = handlers.find(- (handler): handler is NotificationHandlerEmail =>- handler.channel_type === "channel/email",- );- const slackHandler = handlers.find(- (handler): handler is NotificationHandlerSlack =>- handler.channel_type === "channel/slack",- );- const httpHandler = handlers.find(- (handler): handler is NotificationHandlerHttp =>- handler.channel_type === "channel/http",- );- const emailRecipientCount = emailHandler?.recipients.length ?? 0;- const slackChannelCount = slackHandler?.recipients.length ?? 0;+ const channelSummaries = summarizeChannels(notification);+ const emailSummary = channelSummaries["channel/email"];+ const slackSummary = channelSummaries["channel/slack"];+ const emailRecipientCount = emailSummary.count;+ const slackChannelCount = slackSummary.count;+ const webhookCount = channelSummaries["channel/http"].count;const cardId = notification.payload?.card_id;@@ -49,7 +36,7 @@ export const SidebarBody = ({notification={notification}emailRecipientCount={emailRecipientCount}slackChannelCount={slackChannelCount}- httpHandler={httpHandler}+ webhookCount={webhookCount}/><NotificationRunSummaryLogtitle={t`Check history`}@@ -69,10 +56,10 @@ export const SidebarBody = ({trackAlertsManagementRunHistoryViewAllClicked(cardId, "send")}/>- {emailHandler && emailRecipientCount > 0 && (+ {emailRecipientCount > 0 && (<SidebarSection title={getEmailRecipientLabel(emailRecipientCount)}><DetailsTable>- {emailHandler.recipients.map((recipient, index) => {+ {emailSummary.recipients.map((recipient, index) => {const { name, email } = getEmailRowText(recipient);return (<Flex@@ -97,13 +84,13 @@ export const SidebarBody = ({</DetailsTable></SidebarSection>)}- {slackHandler && slackChannelCount > 0 && (+ {slackChannelCount > 0 && (<SidebarSection title={getSlackChannelLabel(slackChannelCount)}><DetailsTable>- {slackHandler.recipients.map((recipient, index) => (+ {slackSummary.recipients.map((recipient, index) => (<Flex key={recipient.id ?? index} align="center" px="md" py="sm"><Text size="md" c="text-primary">- {recipient.details?.value ?? ""}+ {recipient.details.value}</Text></Flex>))}diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.tsindex 43bcc63a374..318993da115 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.ts+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.ts@@ -5,7 +5,6 @@ import type {AdminNotificationDetail,CardId,NotificationChannelType,- NotificationHandlerHttp,NotificationId,NotificationRunSummary,NotificationTickSendEntry,@@ -42,7 +41,7 @@ export type DetailsSectionProps = {notification: AdminNotification;emailRecipientCount: number;slackChannelCount: number;- httpHandler: NotificationHandlerHttp | undefined;+ webhookCount: number;};export type NotificationRunSummaryLogProps = {diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.tsindex fa41462a73b..2e2c69b2183 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.ts+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.ts@@ -1,9 +1,6 @@import { t } from "ttag";-import type {- NotificationHandlerHttp,- NotificationRecipient,-} from "metabase-types/api";+import type { NotificationRecipient } from "metabase-types/api";export const getEmailRowText = (recipient: NotificationRecipient,@@ -37,13 +34,13 @@ export const getWebhookLabel = (count: number): string =>type ChannelSummaryInput = {emailRecipientCount: number;slackChannelCount: number;- httpHandler: NotificationHandlerHttp | undefined;+ webhookCount: number;};export const formatChannelSummary = ({emailRecipientCount,slackChannelCount,- httpHandler,+ webhookCount,}: ChannelSummaryInput): string => {const parts: string[] = [];if (emailRecipientCount > 0) {@@ -52,8 +49,8 @@ export const formatChannelSummary = ({if (slackChannelCount > 0) {parts.push(getSlackChannelLabel(slackChannelCount));}- if (httpHandler && httpHandler.recipients.length > 0) {- parts.push(getWebhookLabel(httpHandler.recipients.length));+ if (webhookCount > 0) {+ parts.push(getWebhookLabel(webhookCount));}return parts.join(", ");};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsxindex 2b16d876c3f..a6bf3200319 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx@@ -28,6 +28,10 @@ import {createMockAdminNotification,createMockCard,createMockCardQueryMetadata,+ createMockNotificationHandlerEmail,+ createMockNotificationHandlerHttp,+ createMockNotificationHandlerSlack,+ createMockNotificationRecipientUser,createMockUserInfo,createMockUserListResult,} from "metabase-types/api/mocks";@@ -52,6 +56,70 @@ const BOB = createMockUserInfo({const notification1 = createMockAdminNotification({ id: 1, creator: ANN });const notification2 = createMockAdminNotification({ id: 2, creator: BOB });+const webhookNotification = createMockAdminNotification({+ id: 99,+ creator: ANN,+ handlers: [createMockNotificationHandlerHttp()],+ payload: {+ id: 7,+ card_id: 1,+ card: createMockCard({ id: 1, name: "Webhook Alert" }),+ send_once: false,+ send_condition: "has_result",+ },+});+const multiHandlerNotification = createMockAdminNotification({+ id: 50,+ creator: ANN,+ handlers: [+ createMockNotificationHandlerEmail({+ id: 21,+ recipients: [+ createMockNotificationRecipientUser({+ id: 1,+ user_id: 3,+ user: createMockUserInfo({+ id: 3,+ common_name: "Carol Carter",+ email: "[email protected]",+ }),+ }),+ ],+ }),+ createMockNotificationHandlerEmail({+ id: 22,+ recipients: [+ createMockNotificationRecipientUser({+ id: 2,+ user_id: 4,+ user: createMockUserInfo({+ id: 4,+ common_name: "Dave Diaz",+ email: "[email protected]",+ }),+ }),+ ],+ }),+ createMockNotificationHandlerSlack({+ id: 23,+ recipients: [+ {+ type: "notification-recipient/raw-value",+ id: 3,+ details: { value: "#alerts" },+ },+ ],+ }),+ createMockNotificationHandlerHttp({ id: 24 }),+ ],+ payload: {+ id: 8,+ card_id: 1,+ card: createMockCard({ id: 1, name: "Multi Channel Alert" }),+ send_once: false,+ send_condition: "has_result",+ },+});type SetupOpts = {notifications?: AdminNotification[];@@ -163,6 +231,41 @@ describe("NotificationsAdminPage", () => {expect(within(row2).getByText("Bob Boss")).toBeInTheDocument();});+ it("counts webhook handlers as configured channels", async () => {+ setup({ notifications: [webhookNotification] });+ await waitForLoaderToBeRemoved();++ const row = await screen.findByTestId("notification-row-99");+ expect(within(row).getByText("Webhook Alert")).toBeInTheDocument();+ expect(within(row).getByText("1")).toBeInTheDocument();+ expect(within(row).queryByText("0")).not.toBeInTheDocument();++ await userEvent.click(row);++ expect(await screen.findByText("1 webhook")).toBeInTheDocument();+ expect(screen.queryByText("No channels")).not.toBeInTheDocument();+ });++ it("merges multiple handlers across and within channels", async () => {+ setup({ notifications: [multiHandlerNotification] });+ await waitForLoaderToBeRemoved();++ const row = await screen.findByTestId("notification-row-50");+ expect(within(row).getByText("Multi Channel Alert")).toBeInTheDocument();+ expect(within(row).getByText("2")).toBeInTheDocument();++ await userEvent.click(row);++ expect(+ await screen.findByText(+ "2 email recipients, 1 Slack channel, 1 webhook",+ ),+ ).toBeInTheDocument();+ expect(screen.getByText("Carol Carter")).toBeInTheDocument();+ expect(screen.getByText("Dave Diaz")).toBeInTheDocument();+ expect(screen.getByText("#alerts")).toBeInTheDocument();+ });+it("shows an empty state when there are no notifications", async () => {setup({ notifications: [] });await waitForLoaderToBeRemoved();diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsxindex d4b5bff479c..55c382e7c52 100644--- a/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsx+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsx@@ -2,6 +2,7 @@ import type { Row, SortingState, Updater } from "@tanstack/react-table";import { useCallback, useEffect, useMemo } from "react";import { t } from "ttag";+import { listChannelSummaries } from "metabase/admin/tools/notifications/utils";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import type { SelectionState, TreeTableColumnDef } from "metabase/ui";import {@@ -17,11 +18,7 @@ import {} from "metabase/ui";import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";import { getUserLabel } from "metabase/utils/user";-import type {- AdminNotification,- NotificationChannelType,- NotificationId,-} from "metabase-types/api";+import type { AdminNotification, NotificationId } from "metabase-types/api";import { NotificationSummary } from "../NotificationSummary";import {@@ -44,26 +41,6 @@ type Props = {const getNodeId = (notification: AdminNotification) => String(notification.id);-type ChannelSummary = {- channel: NotificationChannelType;- count: number;-};--const summarizeChannels = (- notification: AdminNotification,-): ChannelSummary[] => {- const handlers = notification.handlers ?? [];- const map = new Map<NotificationChannelType, number>();- for (const handler of handlers) {- const prev = map.get(handler.channel_type) ?? 0;- map.set(handler.channel_type, prev + handler.recipients.length);- }- return Array.from(map.entries()).map(([channel, count]) => ({- channel,- count,- }));-};-export const NotificationsTable = ({notifications,error,@@ -169,11 +146,11 @@ export const NotificationsTable = ({width: "auto",enableSorting: false,accessorFn: (notification) =>- summarizeChannels(notification)+ listChannelSummaries(notification).map(({ channel, count }) => `${channel}${count}`).join(" "),cell: ({ row }) => {- const summaries = summarizeChannels(row.original);+ const summaries = listChannelSummaries(row.original);if (summaries.length === 0) {return EMPTY_CELL_PLACEHOLDER;}diff --git a/frontend/src/metabase/admin/tools/notifications/utils.ts b/frontend/src/metabase/admin/tools/notifications/utils.tsnew file mode 100644index 00000000000..012e81209a9--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/utils.ts@@ -0,0 +1,105 @@+import type {+ AdminNotification,+ NotificationChannelType,+ NotificationHandler,+ NotificationHandlerEmail,+ NotificationHandlerHttp,+ NotificationHandlerSlack,+} from "metabase-types/api";++export type ChannelSummary<TChannel extends NotificationChannelType> = {+ channel: TChannel;+ count: number;+ recipients: Extract<+ NotificationHandler,+ { channel_type: TChannel }+ >["recipients"];+};++export type ChannelSummaries = {+ [TChannel in NotificationChannelType]: ChannelSummary<TChannel>;+};++type AnyChannelSummary = ChannelSummaries[NotificationChannelType];++const CHANNEL_TYPES: NotificationChannelType[] = [+ "channel/email",+ "channel/slack",+ "channel/http",+];++export const getHandlerTargetCount = (+ handler: NotificationHandler | undefined,+): number => {+ if (!handler) {+ return 0;+ }+ if (handler.channel_type === "channel/http") {+ // Webhook handlers target the configured HTTP channel via channel_id, not recipients.+ return 1;+ }+ return handler.recipients.length;+};++const buildSummary = <TChannel extends NotificationChannelType>(+ channel: TChannel,+ handlers: NotificationHandler[],+ recipients: ChannelSummary<TChannel>["recipients"],+): ChannelSummary<TChannel> => ({+ channel,+ count: handlers.reduce(+ (total, handler) => total + getHandlerTargetCount(handler),+ 0,+ ),+ recipients,+});++const isEmailHandler = (+ handler: NotificationHandler,+): handler is NotificationHandlerEmail =>+ handler.channel_type === "channel/email";++const isSlackHandler = (+ handler: NotificationHandler,+): handler is NotificationHandlerSlack =>+ handler.channel_type === "channel/slack";++const isHttpHandler = (+ handler: NotificationHandler,+): handler is NotificationHandlerHttp =>+ handler.channel_type === "channel/http";++export const summarizeChannels = (+ notification: AdminNotification,+): ChannelSummaries => {+ const handlers = notification.handlers ?? [];+ const email = handlers.filter(isEmailHandler);+ const slack = handlers.filter(isSlackHandler);+ const http = handlers.filter(isHttpHandler);+ return {+ "channel/email": buildSummary(+ "channel/email",+ email,+ email.flatMap((handler) => handler.recipients),+ ),+ "channel/slack": buildSummary(+ "channel/slack",+ slack,+ slack.flatMap((handler) => handler.recipients),+ ),+ "channel/http": buildSummary(+ "channel/http",+ http,+ http.flatMap((handler) => handler.recipients),+ ),+ };+};++export const listChannelSummaries = (+ notification: AdminNotification,+): AnyChannelSummary[] => {+ const summaries = summarizeChannels(notification);+ return CHANNEL_TYPES.map((channel) => summaries[channel]).filter(+ (summary) => summary.count > 0,+ );+};