Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

GDGT-232 fix: dashboard subscriptions should work even if Slack channels are renamed (#72223)

YBfd7d19895552
diff --git a/e2e/support/helpers/e2e-slack-helpers.js b/e2e/support/helpers/e2e-slack-helpers.js
index ad22e176092..800f3110dec 100644
--- a/e2e/support/helpers/e2e-slack-helpers.js
+++ b/e2e/support/helpers/e2e-slack-helpers.js
@@ -9,7 +9,10 @@ const mockedSlack = {
name: "channel",
type: "select",
displayName: "Post to",
- options: ["#work", "#play"],
+ options: [
+ { displayName: "#work", id: "C001" },
+ { displayName: "#play", id: "C002" },
+ ],
required: true,
},
],
diff --git a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
index 389a1b7a649..8ab97778c37 100644
--- a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
@@ -91,6 +91,33 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
cy.findByRole("button", { name: "Delete this alert" }).click();
});
+ it("should persist the immutable Slack channel_id alongside the channel name", () => {
+ H.mockSlackConfigured();
+
+ openAlertForQuestion(ORDERS_QUESTION_ID);
+
+ H.removeNotificationHandlerChannel("Email");
+ H.addNotificationHandlerChannel("Slack", { hasNoChannelsAdded: true });
+
+ H.modal()
+ .findByPlaceholderText(/Pick a user or channel/)
+ .click();
+ H.popover().findByText("#work").click();
+
+ H.modal().within(() => {
+ cy.button("Done").click();
+ });
+
+ cy.wait("@saveAlert").then(({ response: { body } }) => {
+ // The mocked channel `#work` has id `C001` in e2e-slack-helpers.js.
+ // Storing the immutable channel_id at save time is what makes the
+ // subscription survive future channel renames in Slack.
+ const slackDetails = body.handlers[0].recipients[0].details;
+ expect(slackDetails.value).to.eq("#work");
+ expect(slackDetails.channel_id).to.eq("C001");
+ });
+ });
+
it("should set up an email alert for newly created question", () => {
H.openTable({
table: PEOPLE_ID,
diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
index 3553de01fb4..32a0f88384e 100644
--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
@@ -514,6 +514,28 @@ describe("scenarios > dashboard > subscriptions", () => {
H.openDashboardMenu();
H.popover().findByText("Subscriptions").should("be.visible");
});
+
+ it("should persist the immutable Slack channel_id alongside the channel name", () => {
+ cy.intercept("POST", "/api/pulse").as("createPulse");
+
+ openSlackCreationForm();
+
+ cy.findByPlaceholderText("Pick a user or channel...").click();
+ H.popover().findByText("#work").click();
+
+ H.sidebar().findByRole("button", { name: "Done" }).click();
+
+ cy.wait("@createPulse").then(({ request: { body } }) => {
+ // The mocked channel `#work` has id `C001` in e2e-slack-helpers.js.
+ // Storing the immutable channel_id at save time is what makes the
+ // subscription survive future channel renames in Slack.
+ const slackChannel = body.channels.find(
+ (c) => c.channel_type === "slack",
+ );
+ expect(slackChannel.details.channel).to.eq("#work");
+ expect(slackChannel.details.channel_id).to.eq("C001");
+ });
+ });
});
describe("OSS email subscriptions", { tags: ["@OSS", "external"] }, () => {
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx
index 5eab6800039..b985324d542 100644
--- a/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/NotificationChannelConfigModal/NotificationChannelConfigModal.unit.spec.tsx
@@ -295,7 +295,11 @@ function setupWithRealHook({
{
name: "channel",
displayName: "Post to",
- options: ["#general", "#security", "#alerts"],
+ options: [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#security", id: "C002" },
+ { displayName: "#alerts", id: "C003" },
+ ],
required: true,
},
],
diff --git a/frontend/src/metabase-types/api/mocks/security-center.ts b/frontend/src/metabase-types/api/mocks/security-center.ts
index 15ca4bd0440..c497e9aff83 100644
--- a/frontend/src/metabase-types/api/mocks/security-center.ts
+++ b/frontend/src/metabase-types/api/mocks/security-center.ts
@@ -33,7 +33,10 @@ export function createMockSlackChannelSpec(
{
name: "channel",
displayName: "Post to",
- options: ["#general", "#security"],
+ options: [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#security", id: "C002" },
+ ],
required: true,
},
],
diff --git a/frontend/src/metabase-types/api/notification-channels.ts b/frontend/src/metabase-types/api/notification-channels.ts
index c6678f40002..ef693744045 100644
--- a/frontend/src/metabase-types/api/notification-channels.ts
+++ b/frontend/src/metabase-types/api/notification-channels.ts
@@ -5,10 +5,17 @@ import type {
import type { User } from "metabase-types/api/user";
import { isObject } from "metabase-types/guards";
+export type SlackChannelId = string;
+
+export type SlackChannelOption = {
+ displayName: string;
+ id: SlackChannelId;
+};
+
type ChannelField = {
name: string;
displayName: string;
- options?: string[];
+ options?: SlackChannelOption[];
required?: boolean;
};
diff --git a/frontend/src/metabase-types/api/notification.ts b/frontend/src/metabase-types/api/notification.ts
index 3bd1e4c30d9..679b71088db 100644
--- a/frontend/src/metabase-types/api/notification.ts
+++ b/frontend/src/metabase-types/api/notification.ts
@@ -1,5 +1,5 @@
import type { Card, CardId } from "./card";
-import type { Channel } from "./notification-channels";
+import type { Channel, SlackChannelId } from "./notification-channels";
import type { PaginationRequest } from "./pagination";
import type { ScheduleDisplayType } from "./settings";
import type { UserId, UserInfo } from "./user";
@@ -50,6 +50,7 @@ export type NotificationRecipientRawValue = {
type: "notification-recipient/raw-value";
details: {
value: string;
+ channel_id?: SlackChannelId;
};
id?: number;
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/tests/setup.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/tests/setup.tsx
index c2dd857ecc2..cd1aae59fb3 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/tests/setup.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/tests/setup.tsx
@@ -101,7 +101,11 @@ export const setup = async ({
name: "channel",
type: "select",
displayName: "Post to",
- options: ["#general", "#random", "#alerts"],
+ options: [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+ { displayName: "#alerts", id: "C003" },
+ ],
required: true,
},
],
diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx
index d5706880956..d8039c05c45 100644
--- a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx
+++ b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx
@@ -148,7 +148,11 @@ export function setup({
name: "channel",
type: "select",
displayName: "Post to",
- options: ["#general", "#random", "#alerts"],
+ options: [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+ { displayName: "#alerts", id: "C003" },
+ ],
required: true,
},
],
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx b/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
index a83f4b80ae1..d25470ca847 100644
--- a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
+++ b/frontend/src/metabase/notifications/channels/SlackChannelField.tsx
@@ -3,6 +3,10 @@ import { useState } from "react";
import { t } from "ttag";
import CS from "metabase/css/core/index.css";
+import {
+ findChannelId,
+ getDisplayNames,
+} from "metabase/notifications/channels/utils";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Autocomplete } from "metabase/ui";
import { useSelector } from "metabase/utils/redux";
@@ -17,7 +21,10 @@ const ALLOWED_PREFIXES = [CHANNEL_PREFIX, USER_PREFIX];
interface SlackChannelFieldProps {
channel: Channel;
channelSpec: ChannelSpec;
- onChannelPropertyChange: any;
+ onChannelPropertyChange: (
+ key: string,
+ value: Record<string, string | boolean>,
+ ) => void;
}
export const SlackChannelField = ({
@@ -31,13 +38,19 @@ export const SlackChannelField = ({
const channelField = channelSpec.fields?.find(
(field) => field.name === CHANNEL_FIELD_NAME,
);
+ const slackOptions = channelField?.options ?? [];
+ const displayNames = getDisplayNames(slackOptions);
const value = String(channel?.details?.[CHANNEL_FIELD_NAME] ?? "");
- const updateChannel = (value: string) =>
+ const updateChannel = (value: string) => {
+ const { channel_id: _, ...restDetails } = channel.details ?? {};
+ const newChannelId = findChannelId(slackOptions, value);
onChannelPropertyChange("details", {
- ...channel.details,
+ ...restDetails,
[CHANNEL_FIELD_NAME]: value,
+ ...(newChannelId && { channel_id: newChannelId }),
});
+ };
const handleChange = (value: string) => {
updateChannel(value);
@@ -55,8 +68,7 @@ export const SlackChannelField = ({
updateChannel(fullChannelName);
}
- const isPrivate =
- value.trim().length > 0 && !channelField?.options?.includes(value);
+ const isPrivate = value.trim().length > 0 && !displayNames.includes(value);
setHasPrivateChannelWarning(isPrivate);
};
@@ -69,7 +81,7 @@ export const SlackChannelField = ({
{channelField?.displayName}
</span>
<Autocomplete
- data={channelField?.options || []}
+ data={displayNames}
value={value}
placeholder={t`Pick a user or channel...`}
limit={300}
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx b/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx
new file mode 100644
index 00000000000..14a27a01ba2
--- /dev/null
+++ b/frontend/src/metabase/notifications/channels/SlackChannelField.unit.spec.tsx
@@ -0,0 +1,124 @@
+import userEvent from "@testing-library/user-event";
+import type { ComponentProps } from "react";
+import { useState } from "react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { SlackChannelField } from "metabase/notifications/channels/SlackChannelField";
+import type {
+ Channel,
+ ChannelSpec,
+ SlackChannelOption,
+} from "metabase-types/api";
+
+type OnChannelPropertyChange = ComponentProps<
+ typeof SlackChannelField
+>["onChannelPropertyChange"];
+
+const SLACK_OPTIONS: SlackChannelOption[] = [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+];
+
+const CHANNEL_SPEC: ChannelSpec = {
+ type: "slack",
+ name: "Slack",
+ schedules: ["hourly"],
+ schedule_type: null,
+ allows_recipients: false,
+ configured: true,
+ fields: [
+ {
+ name: "channel",
+ displayName: "Post to",
+ options: SLACK_OPTIONS,
+ required: true,
+ },
+ ],
+};
+
+function StatefulWrapper({
+ initialChannel,
+ spy,
+}: {
+ initialChannel: Channel;
+ spy: jest.MockedFunction<OnChannelPropertyChange>;
+}) {
+ const [channel, setChannel] = useState(initialChannel);
+ const onChannelPropertyChange: OnChannelPropertyChange = (prop, value) => {
+ spy(prop, value);
+ if (prop === "details") {
+ setChannel((prev) => ({ ...prev, details: value }));
+ }
+ };
+ return (
+ <SlackChannelField
+ channel={channel}
+ channelSpec={CHANNEL_SPEC}
+ onChannelPropertyChange={onChannelPropertyChange}
+ />
+ );
+}
+
+function setup({ channel }: { channel: Channel }) {
+ const spy = jest.fn<
+ ReturnType<OnChannelPropertyChange>,
+ Parameters<OnChannelPropertyChange>
+ >();
+ renderWithProviders(<StatefulWrapper initialChannel={channel} spy={spy} />);
+ return { spy };
+}
+
+describe("SlackChannelField channel_id storage", () => {
+ it("stores channel_id when user selects a known channel", async () => {
+ const { spy } = setup({
+ channel: { channel_type: "slack", details: { channel: "" } },
+ });
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.type(input, "#general");
+
+ const lastCall = spy.mock.calls[spy.mock.calls.length - 1];
+ const [propName, details] = lastCall;
+ expect(propName).toBe("details");
+ expect(details.channel).toBe("#general");
+ expect(details.channel_id).toBe("C001");
+ });
+
+ it("omits channel_id when user types an unknown channel name", async () => {
+ const { spy } = setup({
+ channel: {
+ channel_type: "slack",
+ details: { channel: "#general", channel_id: "C001" },
+ },
+ });
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.clear(input);
+ await userEvent.type(input, "#private-stuff");
+
+ const lastCall = spy.mock.calls[spy.mock.calls.length - 1];
+ const [propName, details] = lastCall;
+ expect(propName).toBe("details");
+ expect(details.channel).toBe("#private-stuff");
+ expect(details).not.toHaveProperty("channel_id");
+ });
+
+ it("updates channel_id when user switches from one known channel to another", async () => {
+ const { spy } = setup({
+ channel: {
+ channel_type: "slack",
+ details: { channel: "#general", channel_id: "C001" },
+ },
+ });
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.clear(input);
+ await userEvent.type(input, "#random");
+
+ const lastCall = spy.mock.calls[spy.mock.calls.length - 1];
+ const [propName, details] = lastCall;
+ expect(propName).toBe("details");
+ expect(details.channel).toBe("#random");
+ expect(details.channel_id).toBe("C002");
+ });
+});
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.tsx b/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.tsx
index 2922ddce954..54d6a435042 100644
--- a/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.tsx
+++ b/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.tsx
@@ -2,6 +2,10 @@ import { useState } from "react";
import { t } from "ttag";
import CS from "metabase/css/core/index.css";
+import {
+ findChannelId,
+ getDisplayNames,
+} from "metabase/notifications/channels/utils";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Autocomplete } from "metabase/ui";
import { useSelector } from "metabase/utils/redux";
@@ -31,9 +35,12 @@ export const SlackChannelFieldNew = ({
const channelField = channelSpec.fields?.find(
(field) => field.name === CHANNEL_FIELD_NAME,
);
+ const slackOptions = channelField?.options ?? [];
+ const displayNames = getDisplayNames(slackOptions);
const value = channel.recipients[0]?.details.value ?? "";
const updateChannel = (value: string) => {
+ const newChannelId = findChannelId(slackOptions, value);
onChange({
...channel,
recipients: [
@@ -41,6 +48,7 @@ export const SlackChannelFieldNew = ({
type: "notification-recipient/raw-value",
details: {
value,
+ ...(newChannelId != null && { channel_id: newChannelId }),
},
},
],
@@ -63,8 +71,7 @@ export const SlackChannelFieldNew = ({
updateChannel(fullChannelName);
}
- const isPrivate =
- value.trim().length > 0 && !channelField?.options?.includes(value);
+ const isPrivate = value.trim().length > 0 && !displayNames.includes(value);
setHasPrivateChannelWarning(isPrivate);
};
@@ -74,7 +81,7 @@ export const SlackChannelFieldNew = ({
return (
<div>
<Autocomplete
- data={channelField?.options || []}
+ data={displayNames}
value={value}
placeholder={t`Pick a user or channel...`}
limit={300}
diff --git a/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.unit.spec.tsx b/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.unit.spec.tsx
new file mode 100644
index 00000000000..bc3f0b5aabe
--- /dev/null
+++ b/frontend/src/metabase/notifications/channels/SlackChannelFieldNew.unit.spec.tsx
@@ -0,0 +1,116 @@
+import userEvent from "@testing-library/user-event";
+import type { ComponentProps } from "react";
+import { useState } from "react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { SlackChannelFieldNew } from "metabase/notifications/channels/SlackChannelFieldNew";
+import type {
+ ChannelSpec,
+ NotificationHandlerSlack,
+ SlackChannelOption,
+} from "metabase-types/api";
+import { createMockNotificationHandlerSlack } from "metabase-types/api/mocks";
+
+type OnChange = ComponentProps<typeof SlackChannelFieldNew>["onChange"];
+
+const SLACK_OPTIONS: SlackChannelOption[] = [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+];
+
+const CHANNEL_SPEC: ChannelSpec = {
+ type: "slack",
+ name: "Slack",
+ schedules: ["hourly"],
+ schedule_type: null,
+ allows_recipients: false,
+ configured: true,
+ fields: [
+ {
+ name: "channel",
+ displayName: "Post to",
+ options: SLACK_OPTIONS,
+ required: true,
+ },
+ ],
+};
+
+function StatefulWrapper({
+ initialChannel,
+ spy,
+}: {
+ initialChannel: NotificationHandlerSlack;
+ spy: jest.MockedFunction<OnChange>;
+}) {
+ const [channel, setChannel] = useState(initialChannel);
+ const onChange: OnChange = (newConfig) => {
+ spy(newConfig);
+ setChannel(newConfig);
+ };
+ return (
+ <SlackChannelFieldNew
+ channel={channel}
+ channelSpec={CHANNEL_SPEC}
+ onChange={onChange}
+ />
+ );
+}
+
+function setup({
+ channel = createMockNotificationHandlerSlack(),
+}: { channel?: NotificationHandlerSlack } = {}) {
+ const spy = jest.fn<ReturnType<OnChange>, Parameters<OnChange>>();
+ renderWithProviders(<StatefulWrapper initialChannel={channel} spy={spy} />);
+ return { spy };
+}
+
+function getLastDetails(spy: jest.MockedFunction<OnChange>) {
+ const lastCall = spy.mock.calls[spy.mock.calls.length - 1];
+ const [handler] = lastCall;
+ return handler.recipients[0]?.details;
+}
+
+describe("SlackChannelFieldNew channel_id storage", () => {
+ it("stores channel_id when user selects a known channel", async () => {
+ const { spy } = setup();
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.type(input, "#general");
+
+ const details = getLastDetails(spy);
+ expect(details?.value).toBe("#general");
+ expect(details?.channel_id).toBe("C001");
+ });
+
+ it("omits channel_id when user types an unknown channel name", async () => {
+ const { spy } = setup();
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.type(input, "#private-stuff");
+
+ const details = getLastDetails(spy);
+ expect(details?.value).toBe("#private-stuff");
+ expect(details).not.toHaveProperty("channel_id");
+ });
+
+ it("updates channel_id when user switches from one known channel to another", async () => {
+ const { spy } = setup({
+ channel: createMockNotificationHandlerSlack({
+ recipients: [
+ {
+ type: "notification-recipient/raw-value",
+ details: { value: "#general", channel_id: "C001" },
+ },
+ ],
+ }),
+ });
+
+ const input = screen.getByPlaceholderText("Pick a user or channel...");
+ await userEvent.clear(input);
+ await userEvent.type(input, "#random");
+
+ const details = getLastDetails(spy);
+ expect(details?.value).toBe("#random");
+ expect(details?.channel_id).toBe("C002");
+ });
+});
diff --git a/frontend/src/metabase/notifications/channels/utils.ts b/frontend/src/metabase/notifications/channels/utils.ts
new file mode 100644
index 00000000000..aa20179dd97
--- /dev/null
+++ b/frontend/src/metabase/notifications/channels/utils.ts
@@ -0,0 +1,12 @@
+import type { SlackChannelId, SlackChannelOption } from "metabase-types/api";
+
+export function getDisplayNames(options: SlackChannelOption[]): string[] {
+ return options.map((o) => o.displayName);
+}
+
+export function findChannelId(
+ options: SlackChannelOption[],
+ displayName: string,
+): SlackChannelId | undefined {
+ return options.find((o) => o.displayName === displayName)?.id;
+}
diff --git a/frontend/src/metabase/notifications/channels/utils.unit.spec.ts b/frontend/src/metabase/notifications/channels/utils.unit.spec.ts
new file mode 100644
index 00000000000..04be9182830
--- /dev/null
+++ b/frontend/src/metabase/notifications/channels/utils.unit.spec.ts
@@ -0,0 +1,44 @@
+import {
+ findChannelId,
+ getDisplayNames,
+} from "metabase/notifications/channels/utils";
+import type { SlackChannelOption } from "metabase-types/api";
+
+describe("getDisplayNames", () => {
+ it("extracts display names from enriched options", () => {
+ const options: SlackChannelOption[] = [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+ { displayName: "@user1", id: "U001" },
+ ];
+ expect(getDisplayNames(options)).toEqual(["#general", "#random", "@user1"]);
+ });
+
+ it("returns empty array for empty input", () => {
+ expect(getDisplayNames([])).toEqual([]);
+ });
+});
+
+describe("findChannelId", () => {
+ const options: SlackChannelOption[] = [
+ { displayName: "#general", id: "C001" },
+ { displayName: "#random", id: "C002" },
+ { displayName: "@user1", id: "U001" },
+ ];
+
+ it("returns the ID for a known channel name", () => {
+ expect(findChannelId(options, "#random")).toBe("C002");
+ });
+
+ it("returns undefined for an unknown channel name", () => {
+ expect(findChannelId(options, "#nonexistent")).toBeUndefined();
+ });
+
+ it("returns undefined for empty string", () => {
+ expect(findChannelId(options, "")).toBeUndefined();
+ });
+
+ it("returns undefined for empty options", () => {
+ expect(findChannelId([], "#general")).toBeUndefined();
+ });
+});
diff --git a/src/metabase/channel/impl/slack.clj b/src/metabase/channel/impl/slack.clj
index 47d9308b367..01dd8c847a4 100644
--- a/src/metabase/channel/impl/slack.clj
+++ b/src/metabase/channel/impl/slack.clj
@@ -15,9 +15,14 @@
[metabase.util.markdown :as markdown]))
(defn- notification-recipient->channel
+ "Returns the Slack channel target for a raw-value notification recipient.
+ Prefers the immutable `:channel_id` (e.g. \"C0ABC123\") over the display `:value`
+ (e.g. \"#my-channel\") so that delivery survives channel renames. Falls back to
+ `:value` for legacy subscriptions that pre-date channel ID storage."
[notification-recipient]
(when (= (:type notification-recipient) :notification-recipient/raw-value)
- (-> notification-recipient :details :value)))
+ (let [details (:details notification-recipient)]
+ (or (:channel_id details) (:value details)))))
(defn- escape-mkdwn
"Escapes slack mkdwn special characters in the string, as specified here:
diff --git a/src/metabase/notification/models.clj b/src/metabase/notification/models.clj
index c3c31a83d5c..55840ec7a03 100644
--- a/src/metabase/notification/models.clj
+++ b/src/metabase/notification/models.clj
@@ -352,7 +352,8 @@
[:notification-recipient/raw-value
[:map
[:details [:map {:closed true}
- [:value :any]]]
+ [:value :any]
+ [:channel_id {:optional true} [:maybe :string]]]]
[:user_id {:optional true} [:fn nil?]]
[:permissions_group_id {:optional true} [:fn nil?]]]]
[:notification-recipient/template
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 889ba69865c..00bf1002472 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -308,8 +308,10 @@
[:slack :fields 0 :options]
(->> (channel.settings/slack-cached-channels-and-usernames)
:channels
- (map :display-name)
- distinct))
+ (m/distinct-by :id)
+ (m/distinct-by :display-name)
+ (mapv (fn [{:keys [display-name id]}]
+ {:displayName display-name :id id}))))
(catch Throwable e
(assoc-in chan-types [:slack :error] (.getMessage e)))))}))
diff --git a/src/metabase/pulse/send.clj b/src/metabase/pulse/send.clj
index a82fa88265d..20d9eda0292 100644
--- a/src/metabase/pulse/send.clj
+++ b/src/metabase/pulse/send.clj
@@ -24,7 +24,11 @@
(case (keyword (:channel_type pulse-channel))
:slack
[{:type :notification-recipient/raw-value
- :details {:value (get-in pulse-channel [:details :channel])}}]
+ :details (let [details {:value (get-in pulse-channel [:details :channel])}
+ channel-id (get-in pulse-channel [:details :channel_id])]
+ (if channel-id
+ (assoc details :channel_id channel-id)
+ details))}]
:email
(for [recipient (:recipients pulse-channel)]
(if-not (:id recipient)
diff --git a/test/metabase/channel/impl/slack_test.clj b/test/metabase/channel/impl/slack_test.clj
index 2a95747c38f..1c6b45d5795 100644
--- a/test/metabase/channel/impl/slack_test.clj
+++ b/test/metabase/channel/impl/slack_test.clj
@@ -9,6 +9,27 @@
(set! *warn-on-reflection* true)
+(deftest notification-recipient->channel-prefers-channel-id-test
+ (testing "prefers channel_id over value when both are present"
+ (is (= "C0ABC123"
+ (#'channel.slack/notification-recipient->channel
+ {:type :notification-recipient/raw-value
+ :details {:value "#my-channel" :channel_id "C0ABC123"}}))))
+ (testing "falls back to value when channel_id is absent"
+ (is (= "#my-channel"
+ (#'channel.slack/notification-recipient->channel
+ {:type :notification-recipient/raw-value
+ :details {:value "#my-channel"}}))))
+ (testing "returns channel_id even when value is nil"
+ (is (= "C0ABC123"
+ (#'channel.slack/notification-recipient->channel
+ {:type :notification-recipient/raw-value
+ :details {:channel_id "C0ABC123"}}))))
+ (testing "returns nil for non-raw-value recipient types"
+ (is (nil? (#'channel.slack/notification-recipient->channel
+ {:type :notification-recipient/user
+ :details {:value "#my-channel" :channel_id "C0ABC123"}})))))
+
(deftest slack-post-receives-at-most-50-blocks-test
(let [block-inputs (atom [])]
(with-redefs [slack/post-chat-message! (fn [message-content] (swap! block-inputs conj (:blocks message-content)))]
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index 76cffdb6653..e9505567c83 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -1292,7 +1292,9 @@
:id "U1DYU9W3WZ2"
:display-name "@user1"}]}]
(is (= [{:name "channel", :type "select", :displayName "Post to",
- :options ["#foo" "#general" "@user1"], :required true}]
+ :options [{:displayName "#foo" :id "CAAS3DD9XND"}
+ {:displayName "#general" :id "C3MJRZ9EUVA"}
+ {:displayName "@user1" :id "U1DYU9W3WZ2"}], :required true}]
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields]))))))
@@ -1315,16 +1317,44 @@
:name "general"
:display-name "#general"
:id "C003"}]}]
- (is (= ["#channel" "#general"]
+ (is (= [{:displayName "#channel" :id "C001"}
+ {:displayName "#general" :id "C003"}]
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])
first
:options)))
(is (apply distinct?
- (-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
- (get-in [:channels :slack :fields])
- first
- :options)))))
+ (map :displayName
+ (-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
+ (get-in [:channels :slack :fields])
+ first
+ :options))))))
+
+ (testing "Duplicate Slack channel IDs are deduplicated, keeping the first entry"
+ (mt/with-temporary-setting-values [channel.settings/slack-channels-and-usernames-last-updated
+ (t/zoned-date-time)
+
+ channel.settings/slack-app-token "test-token"
+
+ channel.settings/slack-cached-channels-and-usernames
+ {:channels [{:type "channel"
+ :name "old-name"
+ :display-name "#old-name"
+ :id "C001"}
+ {:type "channel"
+ :name "new-name"
+ :display-name "#new-name"
+ :id "C001"}
+ {:type "channel"
+ :name "general"
+ :display-name "#general"
+ :id "C003"}]}]
+ (is (= [{:displayName "#old-name" :id "C001"}
+ {:displayName "#general" :id "C003"}]
+ (-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
+ (get-in [:channels :slack :fields])
+ first
+ :options)))))
(testing "When slack is not configured, `form_input` returns no channels"
(mt/with-temporary-setting-values [channel.settings/slack-app-token nil]
diff --git a/test/metabase/pulse/send_test.clj b/test/metabase/pulse/send_test.clj
index 09652e1d2a8..95f393d7a38 100644
--- a/test/metabase/pulse/send_test.clj
+++ b/test/metabase/pulse/send_test.clj
@@ -24,6 +24,26 @@
(testing "[PRO TIP] If this test fails, you may need to rebuild the bundle with `bun run build-static-viz`\n\n"
(thunk))))
+(deftest channel-recipients-includes-channel-id-test
+ (testing "Slack channel-recipients includes channel_id when present in pulse_channel details"
+ (is (= [{:type :notification-recipient/raw-value
+ :details {:value "#my-channel" :channel_id "C0ABC123"}}]
+ (#'pulse.send/channel-recipients
+ {:channel_type "slack"
+ :details {:channel "#my-channel" :channel_id "C0ABC123"}}))))
+ (testing "Slack channel-recipients omits channel_id when absent from pulse_channel details"
+ (is (= [{:type :notification-recipient/raw-value
+ :details {:value "#my-channel"}}]
+ (#'pulse.send/channel-recipients
+ {:channel_type "slack"
+ :details {:channel "#my-channel"}}))))
+ (testing "Email recipients are unaffected"
+ (is (= [{:type :notification-recipient/raw-value
+ :details {:value "[email protected]"}}]
+ (#'pulse.send/channel-recipients
+ {:channel_type "email"
+ :recipients [{:email "[email protected]"}]})))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Util Fns & Macros |
;;; +----------------------------------------------------------------------------------------------------------------+