Skip to content

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

feat(sdk, embed-js): Add an alerts support to modular embeddings (#68777)

Mahatthana (Kelvin) Nomsawadi64fb9ea2595f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e8360e5f6ab..1632c44e281 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -880,6 +880,7 @@
config
dashboards
driver
+ embedding
events
models
parameters
diff --git a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx
index b199759b96c..d8dedfd8e93 100644
--- a/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx
+++ b/e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-question-helpers.tsx
@@ -1,9 +1,10 @@
import {
InteractiveQuestion,
+ type InteractiveQuestionProps,
type MetabaseProviderProps,
StaticQuestion,
+ type StaticQuestionProps,
} from "@metabase/embedding-sdk-react";
-import type { ComponentProps } from "react";
import {
type MountSdkContentOptions,
@@ -16,7 +17,7 @@ interface MountQuestionOptions extends MountSdkContentOptions {
}
export function mountInteractiveQuestion(
- extraProps: Partial<ComponentProps<typeof InteractiveQuestion>> = {},
+ extraProps: Partial<InteractiveQuestionProps> = {},
{ shouldAssertCardQuery, ...mountSdkContentOptions }: MountQuestionOptions = {
shouldAssertCardQuery: true,
},
@@ -39,7 +40,7 @@ export function mountInteractiveQuestion(
}
export function mountStaticQuestion(
- extraProps: Partial<ComponentProps<typeof StaticQuestion>> = {},
+ extraProps: Partial<StaticQuestionProps> = {},
{ shouldAssertCardQuery, sdkProviderProps }: MountQuestionOptions = {
shouldAssertCardQuery: true,
},
diff --git a/e2e/test-component/scenarios/embedding-sdk/data-picker.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/data-picker.cy.spec.tsx
index 3f810bc4326..e2ea77a8fdd 100644
--- a/e2e/test-component/scenarios/embedding-sdk/data-picker.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/data-picker.cy.spec.tsx
@@ -33,7 +33,7 @@ describe("scenarios > embedding-sdk > interactive-question > creating a question
// Should be able to go back to the editor view
// TODO: SDK: make this accessible
- cy.findByRole("button", { name: "pencil_lines icon" }).click();
+ cy.findByRole("button", { name: "Edit question" }).click();
// Should be able to visualize the question again
cy.findByRole("button", { name: "Visualize" }).click();
@@ -79,7 +79,7 @@ describe("scenarios > embedding-sdk > interactive-question > creating a question
// Should be able to go back to the editor view
// TODO: SDK: make this accessible
- cy.findByRole("button", { name: "pencil_lines icon" }).click();
+ cy.findByRole("button", { name: "Edit question" }).click();
// Should be able to visualize the question again
cy.findByRole("button", { name: "Visualize" }).click();
diff --git a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
index 77761e8a58a..44ad89a265b 100644
--- a/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/interactive-question.cy.spec.tsx
@@ -1,6 +1,7 @@
const { H } = cy;
import { InteractiveQuestion } from "@metabase/embedding-sdk-react";
+import { modal, popover } from "e2e/support/helpers";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";
import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
@@ -26,7 +27,7 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
});
it("should be able to drill SQL question (EMB-273)", () => {
- cy.get("@sqlQuestionId").then((sqlQuestionId) => {
+ cy.get<number>("@sqlQuestionId").then((sqlQuestionId) => {
mountSdkContent(
<InteractiveQuestion questionId={sqlQuestionId} withParameters />,
);
@@ -102,4 +103,65 @@ describe("scenarios > embedding-sdk > interactive-question", () => {
H.assertTableRowsCount(10);
});
});
+
+ describe("alerts button", () => {
+ beforeEach(() => {
+ cy.signInAsAdmin();
+ H.setupSMTP();
+ cy.signOut();
+ });
+
+ it("should be able to create, edit, and delete alerts", () => {
+ cy.get<number>("@sqlQuestionId").then((sqlQuestionId) => {
+ mountSdkContent(
+ <InteractiveQuestion questionId={sqlQuestionId} withAlerts />,
+ );
+ });
+
+ cy.log("alerts button is visible and clickable");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+
+ cy.log("alerts modal is open");
+ modal().within(() => {
+ cy.findByRole("heading", { name: "New alert" }).should("be.visible");
+ cy.button("Done").click();
+ });
+ modal().should("not.exist");
+
+ cy.log("alerts list modal");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+ modal().within(() => {
+ cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
+ cy.findByText("Alert when this has results").should("be.visible");
+ cy.findByText("[email protected]").should("be.visible");
+ cy.findByText("Check daily at 8:00 AM").should("be.visible").click();
+
+ cy.findByRole("heading", { name: "Edit alert" }).should("be.visible");
+ // The second input is a hidden input, so we need to ignore it.
+ cy.findAllByDisplayValue("daily").first().click();
+ });
+
+ popover().findByRole("option", { name: "weekly" }).click();
+ modal().within(() => {
+ cy.button("Save changes").click();
+ cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
+ cy.findByText("Check on Monday at 8:00 AM").should("be.visible");
+ });
+
+ cy.log("delete the alert");
+ modal().within(() => {
+ cy.findByText("Check on Monday at 8:00 AM").realHover();
+ cy.button("Delete this alert").click();
+
+ cy.findByRole("heading", { name: "Delete this alert?" }).should(
+ "be.visible",
+ );
+ cy.button("Delete it").click();
+ });
+
+ cy.log("the alert is deleted");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+ modal().findByRole("heading", { name: "New alert" }).should("be.visible");
+ });
+ });
});
diff --git a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
index 57cbe9a2508..34a9e93525b 100644
--- a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
@@ -1,5 +1,7 @@
+const { H } = cy;
+
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-import { createQuestion } from "e2e/support/helpers";
+import { createQuestion, modal, popover } from "e2e/support/helpers";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
import { mountStaticQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";
import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
@@ -87,7 +89,7 @@ describe("scenarios > embedding-sdk > static-question", () => {
successTestCases.forEach(({ name, questionIdAlias }) => {
it(`should load question content for ${name}`, () => {
- cy.get(questionIdAlias).then((questionId) => {
+ cy.get<number>(questionIdAlias).then((questionId) => {
mountStaticQuestion({ questionId });
});
@@ -111,4 +113,63 @@ describe("scenarios > embedding-sdk > static-question", () => {
});
});
});
+
+ describe("alerts button", () => {
+ beforeEach(() => {
+ cy.signInAsAdmin();
+ H.setupSMTP();
+ cy.signOut();
+ });
+
+ it("should be able to create, edit, and delete alerts", () => {
+ mountStaticQuestion({
+ withAlerts: true,
+ });
+
+ cy.log("alerts button is visible and clickable");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+
+ cy.log("alerts modal is open");
+ modal().within(() => {
+ cy.findByRole("heading", { name: "New alert" }).should("be.visible");
+ cy.button("Done").click();
+ });
+ modal().should("not.exist");
+
+ cy.log("alerts list modal");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+ modal().within(() => {
+ cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
+ cy.findByText("Alert when this has results").should("be.visible");
+ cy.findByText("[email protected]").should("be.visible");
+ cy.findByText("Check daily at 8:00 AM").should("be.visible").click();
+
+ cy.findByRole("heading", { name: "Edit alert" }).should("be.visible");
+ // The second input is a hidden input, so we need to ignore it.
+ cy.findAllByDisplayValue("daily").first().click();
+ });
+
+ popover().findByRole("option", { name: "weekly" }).click();
+ modal().within(() => {
+ cy.button("Save changes").click();
+ cy.findByRole("heading", { name: "Edit alerts" }).should("be.visible");
+ cy.findByText("Check on Monday at 8:00 AM").should("be.visible");
+ });
+
+ cy.log("delete the alert");
+ modal().within(() => {
+ cy.findByText("Check on Monday at 8:00 AM").realHover();
+ cy.button("Delete this alert").click();
+
+ cy.findByRole("heading", { name: "Delete this alert?" }).should(
+ "be.visible",
+ );
+ cy.button("Delete it").click();
+ });
+
+ cy.log("the alert is deleted");
+ getSdkRoot().button("Alerts").should("be.visible").click();
+ modal().findByRole("heading", { name: "New alert" }).should("be.visible");
+ });
+ });
});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts
index 8f8114996f0..76f31502a00 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-ee.cy.spec.ts
@@ -208,7 +208,7 @@ describe("scenarios > embedding > sdk iframe embed setup > guest-embed", () => {
H.expectUnstructuredSnowplowEvent({
event: "embed_wizard_options_completed",
event_detail:
- 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=false,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',
+ 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=false,withAlerts=false,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',
});
// Get code step
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts
index aa630c62596..65305d4db6e 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/guest-embed-oss.cy.spec.ts
@@ -226,7 +226,7 @@ describe(
H.expectUnstructuredSnowplowEvent({
event: "embed_wizard_options_completed",
event_detail:
- 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=true,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',
+ 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=true,withAlerts=false,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":1,"enabled":0},theme=default',
});
// Get code step
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
index 1280d2e573d..92200860d38 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding-setup/select-embed-options.cy.spec.ts
@@ -43,6 +43,15 @@ describe("OSS", { tags: "@OSS" }, () => {
getEmbedSidebar().findByTestId("upsell-card").should("be.visible");
});
+
+ it("should show upsell for Allow alerts option", () => {
+ navigateToEmbedOptionsStep({
+ experience: "chart",
+ resourceName: QUESTION_NAME,
+ });
+
+ getEmbedSidebar().findByTestId("upsell-card").should("be.visible");
+ });
});
});
@@ -471,7 +480,7 @@ describe(suiteTitle, () => {
H.expectUnstructuredSnowplowEvent({
event: "embed_wizard_options_completed",
event_detail:
- 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=true,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":0,"enabled":0},theme=default',
+ 'settings=custom,experience=chart,guestEmbedEnabled=true,guestEmbedType=guest-embed,authType=guest-embed,drills=false,withDownloads=true,withAlerts=false,withTitle=true,isSaveEnabled=false,params={"disabled":0,"locked":0,"enabled":0},theme=default',
});
codeBlock().should("contain", 'with-downloads="true"');
@@ -538,6 +547,140 @@ describe(suiteTitle, () => {
.should("be.visible");
});
+ it("cannot select alerts for question when email is not set up", () => {
+ navigateToEmbedOptionsStep({
+ experience: "chart",
+ resourceName: QUESTION_NAME,
+ });
+
+ getEmbedSidebar()
+ .findByLabelText("Allow alerts")
+ .should("not.be.checked")
+ .and("be.disabled");
+
+ cy.log("Email warning should only be shown on non-guest embedding");
+ getEmbedSidebar()
+ .findByLabelText("Allow alerts")
+ .closest("[data-testid=tooltip-warning]")
+ .icon("info")
+ .realHover();
+ H.tooltip().should(
+ "contain.text",
+ "Not available if Guest Mode is selected",
+ );
+
+ H.getSimpleEmbedIframeContent()
+ .findByRole("button", { name: "Alerts" })
+ .should("not.exist");
+
+ cy.log("snippet should show alerts as false");
+ getEmbedSidebar().findByText("Get code").click();
+
+ H.expectUnstructuredSnowplowEvent({
+ event: "embed_wizard_options_completed",
+ event_detail: "settings=default",
+ });
+
+ cy.log("test non-guest embeds");
+ getEmbedSidebar().within(() => {
+ cy.button("Back").click();
+ cy.button("Back").click();
+ cy.button("Back").click();
+
+ cy.findByLabelText("Metabase account (SSO)").click();
+ });
+
+ embedModalEnableEmbedding();
+
+ getEmbedSidebar().within(() => {
+ cy.button("Next").click();
+ cy.button("Next").click();
+
+ cy.findByLabelText("Allow alerts")
+ .closest("[data-testid=tooltip-warning]")
+ .icon("info")
+ .realHover();
+ });
+ H.hovercard().should(
+ "contain.text",
+ "To allow alerts, set up email in admin settings",
+ );
+ });
+
+ it("toggles alerts for question when email is set up", () => {
+ H.setupSMTP();
+
+ navigateToEmbedOptionsStep({
+ experience: "chart",
+ resourceName: QUESTION_NAME,
+ preselectSso: true,
+ });
+
+ getEmbedSidebar().findByLabelText("Allow alerts").should("not.be.checked");
+
+ H.getSimpleEmbedIframeContent()
+ .findByRole("button", { name: "Alerts" })
+ .should("not.exist");
+
+ cy.log("turn on alerts");
+ getEmbedSidebar()
+ .findByLabelText("Allow alerts")
+ .click()
+ .should("be.checked");
+
+ cy.log("assert that alert button appears in preview");
+ H.getSimpleEmbedIframeContent()
+ .findByRole("button", { name: "Alerts" })
+ .should("be.visible");
+
+ cy.log(
+ "test that with drills off, alerts still work because it will now render <StaticQuestion /> (from <SdkQuestion />)",
+ );
+ getEmbedSidebar()
+ .findByLabelText("Allow people to drill through on data points")
+ .should("be.checked")
+ .click()
+ .should("not.be.checked");
+ H.getSimpleEmbedIframeContent()
+ .findByRole("button", { name: "Alerts" })
+ .should("be.visible");
+
+ cy.log("assert that unchecking alerts will close the alert modal");
+ const newAlertModalTitle = "New alert";
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByRole("button", { name: "Alerts" }).should("be.visible").click();
+
+ cy.findByRole("heading", { name: newAlertModalTitle }).should(
+ "be.visible",
+ );
+ });
+
+ getEmbedSidebar()
+ .findByLabelText("Allow alerts")
+ .click()
+ .should("not.be.checked");
+ H.getSimpleEmbedIframeContent()
+ .findByRole("heading", { name: newAlertModalTitle })
+ .should("not.exist");
+
+ cy.log("toggle alerts back on");
+ getEmbedSidebar()
+ .findByLabelText("Allow alerts")
+ .click()
+ .should("be.checked");
+
+ cy.log("snippet should be updated");
+ getEmbedSidebar().findByText("Get code").click();
+
+ H.expectUnstructuredSnowplowEvent({
+ event: "embed_wizard_options_completed",
+ event_detail:
+ "settings=custom,experience=chart,authType=sso,drills=false,withDownloads=false,withAlerts=true,withTitle=true,isSaveEnabled=false,theme=default",
+ });
+
+ codeBlock().should("contain", 'with-alerts="true"');
+ });
+
["exploration", "chart"].forEach((experience) => {
it(`toggles save button for ${experience}`, () => {
navigateToEmbedOptionsStep(
@@ -590,7 +733,7 @@ describe(suiteTitle, () => {
event: "embed_wizard_options_completed",
event_detail:
experience === "chart"
- ? "settings=custom,experience=chart,authType=sso,drills=true,withDownloads=false,withTitle=true,isSaveEnabled=true,theme=default"
+ ? "settings=custom,experience=chart,authType=sso,drills=true,withDownloads=false,withAlerts=false,withTitle=true,isSaveEnabled=true,theme=default"
: "settings=custom,experience=exploration,authType=sso,isSaveEnabled=true,theme=default",
});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
index 7807a51b89e..3d2d1030eb2 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts
@@ -396,6 +396,10 @@ describe("scenarios > embedding > Modular embedding", () => {
false: 1,
true: 0,
},
+ with_alerts: {
+ false: 1,
+ true: 0,
+ },
},
exploration: {
is_save_enabled: {
diff --git a/enterprise/frontend/src/embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx
similarity index 96%
rename from enterprise/frontend/src/embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton.tsx
rename to enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx
index 6436b442f60..11260c25163 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.tsx
@@ -1,6 +1,6 @@
import { t } from "ttag";
-import type { DashboardSubscriptionsButtonProps } from "embedding-sdk-bundle/components/public/subscriptions";
+import type { DashboardSubscriptionsButtonProps } from "embedding-sdk-bundle/components/public/notifications";
import { ToolbarButton } from "metabase/common/components/ToolbarButton";
import { useHasEmailSetup } from "metabase/common/hooks";
import { toggleSharing } from "metabase/dashboard/actions";
diff --git a/enterprise/frontend/src/embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsx
similarity index 100%
rename from enterprise/frontend/src/embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton.unit.spec.tsx
rename to enterprise/frontend/src/embedding-sdk-ee/notifications/DashboardSubscriptionsButton.unit.spec.tsx
diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx
new file mode 100644
index 00000000000..5918be58d60
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/QuestionAlertsButton.tsx
@@ -0,0 +1,58 @@
+import { useEffect } from "react";
+import { t } from "ttag";
+
+import { SdkActionIcon } from "embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon";
+import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
+import { useQuestionAlertModalContext } from "embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider";
+import type { QuestionAlertsButtonProps } from "embedding-sdk-bundle/components/public/notifications";
+import { useSdkSelector } from "embedding-sdk-bundle/store";
+import { useHasEmailSetup } from "metabase/common/hooks";
+import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/selectors/user";
+import { isInstanceAnalyticsCollection } from "metabase-enterprise/collections/utils";
+
+/**
+ * @internal Do not import this component directly, use either SDK or EAJS EE plugins instead.
+ */
+export const QuestionAlertsButton = (props: QuestionAlertsButtonProps) => {
+ const { withAlerts, question } = useSdkQuestionContext();
+ const canManageSubscriptions = useSdkSelector(canManageSubscriptionsSelector);
+ const { toggle: toggleModal, close: closeModal } =
+ useQuestionAlertModalContext();
+
+ const isSaved = question?.isSaved();
+ const isModel = question?.type() === "model";
+ const isAnalytics = isInstanceAnalyticsCollection(question?.collection());
+ const hasEmailSetup = useHasEmailSetup();
+
+ const shouldRenderAlertsButton =
+ hasEmailSetup &&
+ withAlerts &&
+ isSaved &&
+ canManageSubscriptions &&
+ !isModel &&
+ !isAnalytics;
+
+ useEffect(() => {
+ if (!shouldRenderAlertsButton) {
+ closeModal();
+ }
+
+ return closeModal;
+ }, [closeModal, shouldRenderAlertsButton]);
+ /**
+ * Use the same logic as in the core app. But we don't need `isAdmin` because it's already included in `canManageSubscriptions`.
+ * @see {@link https://github.com/metabase/metabase/blob/363baef1d937078ecc1efe9710cbe883f830c819/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/QuestionMoreActionsMenu.tsx#L131}
+ */
+ if (shouldRenderAlertsButton) {
+ return (
+ <SdkActionIcon
+ tooltip={t`Alerts`}
+ icon="alert"
+ onClick={toggleModal}
+ {...props}
+ />
+ );
+ }
+
+ return null;
+};
diff --git a/enterprise/frontend/src/embedding-sdk-ee/notifications/index.ts b/enterprise/frontend/src/embedding-sdk-ee/notifications/index.ts
new file mode 100644
index 00000000000..963c6e9447f
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-ee/notifications/index.ts
@@ -0,0 +1,14 @@
+import { PLUGIN_NOTIFICATIONS_SDK } from "embedding-sdk-bundle/components/public/notifications";
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { DashboardSubscriptionsButton } from "./DashboardSubscriptionsButton";
+import { QuestionAlertsButton } from "./QuestionAlertsButton";
+
+export function initializePlugin() {
+ if (hasPremiumFeature(EMBEDDING_SDK_CONFIG.tokenFeatureKey)) {
+ PLUGIN_NOTIFICATIONS_SDK.DashboardSubscriptionsButton =
+ DashboardSubscriptionsButton;
+ PLUGIN_NOTIFICATIONS_SDK.QuestionAlertsButton = QuestionAlertsButton;
+ }
+}
diff --git a/enterprise/frontend/src/embedding-sdk-ee/subscriptions/index.ts b/enterprise/frontend/src/embedding-sdk-ee/subscriptions/index.ts
deleted file mode 100644
index 93acb59a4f2..00000000000
--- a/enterprise/frontend/src/embedding-sdk-ee/subscriptions/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK } from "embedding-sdk-bundle/components/public/subscriptions";
-import { hasPremiumFeature } from "metabase-enterprise/settings";
-
-import { DashboardSubscriptionsButton } from "./DashboardSubscriptionsButton";
-
-export function initializePlugin() {
- if (hasPremiumFeature("embedding_sdk")) {
- PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK.DashboardSubscriptionsButton =
- DashboardSubscriptionsButton;
- }
-}
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx
index 7c53029a63b..462b40a589d 100644
--- a/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx
@@ -112,6 +112,11 @@ const subComponents: InteractiveQuestionComponents = {
getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestion
?.DownloadWidgetDropdown,
),
+ AlertsButton: createComponent(
+ () =>
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestion
+ ?.AlertsButton,
+ ),
VisualizationButton: createComponent(
() =>
getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestion
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx
index 34e5f19cb38..cefb53e981c 100644
--- a/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx
@@ -73,6 +73,10 @@ const subComponents: StaticQuestionComponents = {
getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion
?.DownloadWidgetDropdown,
),
+ AlertsButton: createComponent(
+ () =>
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion?.AlertsButton,
+ ),
SqlParametersList: createComponent(
() =>
getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts
index 0cc13879820..5603f5e5cd2 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/index.ts
@@ -1,12 +1,8 @@
import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-import { DashboardSubscriptionsButton } from "../../embedding-sdk-ee/subscriptions/DashboardSubscriptionsButton";
-
export function initializePlugin() {
if (hasPremiumFeature("embedding_simple")) {
PLUGIN_EMBEDDING_IFRAME_SDK.isEnabled = () => true;
- PLUGIN_EMBEDDING_IFRAME_SDK.DashboardSubscriptionsButton =
- DashboardSubscriptionsButton;
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts
index 4d3e4fba71b..738b75fef99 100644
--- a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts
+++ b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts
@@ -5,8 +5,6 @@ PLUGIN_IS_EE_BUILD.isEEBuild = () => true;
import "./shared";
-import { initializePlugin as initializeSubscriptions } from "../embedding-sdk-ee/subscriptions";
-
// CORE APP PLUGINS THAT USE hasPremiumFeature (import initialization functions):
import { initializePlugin as initializeContentTranslation } from "./content_translation";
import { initializePlugin as initializeEmbedding } from "./embedding";
@@ -17,6 +15,9 @@ import { initializePlugin as initializeTenants } from "./tenants";
import { initializePlugin as initializeWhitelabelPlugin } from "./whitelabel";
import { initializePlugin as initializeWhitelabelOverridePlugin } from "./whitelabel/sdk-overrides";
+// eslint-disable-next-line import/order -- This needs to be imported after Metabot plugin, otherwise it will initialize reducers before the Metabot plugin has set a reducer.
+import { initializePlugin as initializeNotifications } from "../embedding-sdk-ee/notifications";
+
/**
* Initialize all SDK enterprise plugins that use hasPremiumFeature.
* Must be called after token features are available.
@@ -29,7 +30,7 @@ export function initializePlugins() {
initializeWhitelabelPlugin?.();
initializeWhitelabelOverridePlugin?.();
initializeContentTranslation?.();
- initializeSubscriptions();
+ initializeNotifications();
initializeSharing();
}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidgetDropdown.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidgetDropdown.tsx
index b414c864536..d5337f9fddc 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidgetDropdown.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidgetDropdown.tsx
@@ -1,7 +1,9 @@
-import { Center, Icon, Popover, type PopoverProps } from "metabase/ui";
+import { t } from "ttag";
+
+import { Popover, type PopoverProps } from "metabase/ui";
import { useSdkQuestionContext } from "../../context";
-import { ToolbarButton } from "../util/ToolbarButton";
+import { SdkActionIcon } from "../util/SdkActionIcon";
import { DownloadWidget } from "./DownloadWidget";
@@ -22,6 +24,10 @@ export const DownloadWidgetDropdown = ({
...popoverProps
}: InteractiveQuestionDownloadWidgetDropdownProps) => {
const { withDownloads } = useSdkQuestionContext();
+ if (!withDownloads) {
+ return null;
+ }
+
return (
<Popover
{...popoverProps}
@@ -31,16 +37,9 @@ export const DownloadWidgetDropdown = ({
position="bottom-end"
>
<Popover.Target>
- <ToolbarButton
- isHighlighted={false}
- variant="default"
- px="sm"
- disabled={!withDownloads}
- label={
- <Center>
- <Icon c="inherit" size={16} name="download" />
- </Center>
- }
+ <SdkActionIcon
+ tooltip={t`Download results`}
+ icon="download"
data-testid="question-download-widget-button"
/>
</Popover.Target>
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
index a25355e226c..28bd1420167 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.tsx
@@ -1,11 +1,12 @@
import type { HTMLAttributes, MouseEventHandler } from "react";
+import { t } from "ttag";
import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
-import { ActionIcon, type ActionIconProps, Icon } from "metabase/ui";
+import type { ActionIconProps } from "metabase/ui";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
-import S from "./EditorButton.module.css";
+import { SdkActionIcon } from "../util/SdkActionIcon";
/**
* @interface
@@ -60,16 +61,13 @@ export const EditorButton = ({
question,
isActionListVisible: true,
}) && (
- <ActionIcon
+ <SdkActionIcon
+ tooltip={t`Edit question`}
+ icon="pencil_lines"
data-testid="notebook-button"
- size="lg"
- className={S.EditorButton}
data-active={isOpen}
- variant="default"
{...actionIconProps}
- >
- <Icon name="pencil_lines" />
- </ActionIcon>
+ />
)
);
};
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx
index abd6549de32..ce7db78d870 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx
@@ -1,23 +1,24 @@
-import type { PropsWithChildren } from "react";
+import type { HTMLAttributes, PropsWithChildren } from "react";
import { Group } from "metabase/ui";
-type Props = {
+type Props = HTMLAttributes<HTMLDivElement> & {
"data-testid"?: string;
};
export const ResultToolbar = ({
children,
"data-testid": dataTestId,
+ ...divProps
}: PropsWithChildren<Props>) => (
<Group
- justify="space-between"
p="sm"
style={{
borderRadius: "0.5rem",
backgroundColor: "var(--mb-color-bg-sdk-question-toolbar)",
}}
data-testid={dataTestId}
+ {...divProps}
>
{children}
</Group>
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.module.css b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.module.css
similarity index 73%
rename from frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.module.css
rename to frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.module.css
index 7c86023cde4..b42df695be4 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/EditorButton/EditorButton.module.css
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.module.css
@@ -1,6 +1,7 @@
-.EditorButton:not([data-css-specificity-hack]) {
+.sdkActionIcon:not([data-css-specificity-hack]) {
color: var(--mb-color-text-primary);
background: var(--mb-color-background-primary);
+ border: 1px solid var(--mb-color-border);
&:hover {
background: var(--mb-color-background-hover);
@@ -9,6 +10,7 @@
&[data-active="true"] {
color: var(--mb-color-text-primary-inverse);
background: var(--mb-color-brand);
+ border-color: var(--mb-color-brand);
&:hover {
background: color-mix(in srgb, var(--mb-color-brand), transparent 20%);
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.tsx
new file mode 100644
index 00000000000..a2c056b0cf7
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/SdkActionIcon.tsx
@@ -0,0 +1,65 @@
+import cx from "classnames";
+import { type ReactElement, forwardRef } from "react";
+
+import type { IconName } from "metabase/embedding-sdk/types/icon";
+import {
+ ActionIcon,
+ type ActionIconProps,
+ Icon,
+ type PolymorphicComponentProps,
+ Tooltip,
+} from "metabase/ui";
+
+import S from "./SdkActionIcon.module.css";
+
+type OwnSdkActionIconProps = {
+ icon: IconName;
+ active?: boolean;
+ "data-testid"?: string;
+} & (
+ | {
+ tooltipAriaLabel: string;
+ tooltip?: ReactElement;
+ }
+ | {
+ // When tooltip is a string, use it as both the label and aria-label, so we don't need to provide the same string twice.
+ tooltipAriaLabel?: string;
+ tooltip: string;
+ }
+);
+
+export const SdkActionIcon = forwardRef<
+ HTMLButtonElement,
+ PolymorphicComponentProps<"button", ActionIconProps> & OwnSdkActionIconProps
+>(function SdkActionIcon(
+ {
+ icon,
+ "data-testid": dataTestId,
+ tooltip,
+ tooltipAriaLabel,
+ active,
+ className,
+ ...actionIconProps
+ },
+ ref,
+) {
+ return (
+ <Tooltip label={tooltip} aria-label={tooltipAriaLabel} disabled={!tooltip}>
+ <ActionIcon
+ ref={ref}
+ data-testid={dataTestId}
+ data-active={active}
+ aria-label={
+ tooltipAriaLabel ??
+ (typeof tooltip === "string" ? tooltip : undefined)
+ }
+ size="lg"
+ className={cx(S.sdkActionIcon, className)}
+ variant="default"
+ {...actionIconProps}
+ >
+ <Icon name={icon} />
+ </ActionIcon>
+ </Tooltip>
+ );
+});
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/index.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/index.ts
new file mode 100644
index 00000000000..28d37eeca76
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/util/SdkActionIcon/index.ts
@@ -0,0 +1 @@
+export { SdkActionIcon } from "./SdkActionIcon";
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
index e980a6473b9..d9fb70c235d 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
@@ -2,6 +2,8 @@ import { createContext, useContext, useEffect, useMemo } from "react";
import { t } from "ttag";
import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
+import { SdkQuestionAlertListModal } from "embedding-sdk-bundle/components/private/notifications/SdkQuestionAlertListModal";
+import { QuestionAlertModalProvider } from "embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider";
import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";
import { useLoadQuestion } from "embedding-sdk-bundle/hooks/private/use-load-question";
import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";
@@ -57,6 +59,7 @@ export const SdkQuestionProvider = ({
initialSqlParameters,
hiddenParameters,
withDownloads,
+ withAlerts,
targetDashboardId,
backToDashboard,
getClickActionMode: userGetClickActionMode,
@@ -194,6 +197,7 @@ export const SdkQuestionProvider = ({
isSaveEnabled,
targetCollection,
withDownloads,
+ withAlerts,
onRun,
backToDashboard,
hiddenParameters,
@@ -233,7 +237,10 @@ export const SdkQuestionProvider = ({
return (
<SdkQuestionContext.Provider value={questionContext}>
<EmbeddingEntityContextProvider uuid={null} token={token}>
- {children}
+ <QuestionAlertModalProvider>
+ {children}
+ <SdkQuestionAlertListModal />
+ </QuestionAlertModalProvider>
</EmbeddingEntityContextProvider>
</SdkQuestionContext.Provider>
);
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
index c5693d813c8..cf6da2d96ee 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/types.ts
@@ -46,6 +46,11 @@ type SdkQuestionConfig = {
*/
withDownloads?: boolean;
+ /**
+ * Enables the ability to set up alerts on the question.
+ */
+ withAlerts?: boolean;
+
/**
* The collection to save the question to. This will hide the collection picker from the save modal. Only applicable to interactive questions.
*/
@@ -142,6 +147,7 @@ export type SdkQuestionContextType = Omit<
| "isSaveEnabled"
| "targetCollection"
| "withDownloads"
+ | "withAlerts"
| "backToDashboard"
| "hiddenParameters"
| "onVisualizationChange"
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
index 9dc2018985f..85b6b157d89 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
@@ -1,7 +1,7 @@
import { useDisclosure } from "@mantine/hooks";
import cx from "classnames";
import type { ReactElement } from "react";
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { t } from "ttag";
import {
@@ -11,7 +11,9 @@ import {
} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
import { QuestionVisualization } from "embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization";
import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";
+import { QuestionAlertsButton } from "embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton";
import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
+import { useHideEmptyElement } from "embedding-sdk-bundle/hooks/private/use-hide-empty-element";
import { useQuestionEditorSync } from "embedding-sdk-bundle/hooks/private/use-question-editor-sync";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import { shouldRunCardQuery } from "embedding-sdk-bundle/lib/sdk-question";
@@ -87,7 +89,6 @@ export const SdkQuestionDefaultView = ({
isQuestionLoading,
originalQuestion,
isSaveEnabled,
- withDownloads,
targetCollection,
onReset,
onNavigateBack,
@@ -164,6 +165,9 @@ export const SdkQuestionDefaultView = ({
{ skipCollectionFetching: !isSaveEnabled },
);
+ const hideEmptyParentRef = useRef<HTMLDivElement>(null);
+ useHideEmptyElement("[data-hide-empty]", hideEmptyParentRef);
+
if (
!isEditorOpen &&
(isLocaleLoading || isQuestionLoading || isQueryResultLoading)
@@ -193,15 +197,26 @@ export const SdkQuestionDefaultView = ({
className={cx(InteractiveQuestionS.Container, className)}
style={style}
>
- <Stack className={InteractiveQuestionS.TopBar} gap="sm" p="md">
+ <Stack
+ ref={hideEmptyParentRef}
+ className={InteractiveQuestionS.TopBar}
+ gap="sm"
+ p="md"
+ data-hide-empty
+ >
<Group
justify="space-between"
align="flex-end"
data-testid="interactive-question-top-toolbar"
+ data-hide-empty
>
- <Group gap="xs">
- <Box className={InteractiveQuestionS.BackButtonWrapper} mr="sm">
- <BackButton />
+ <Group gap="xs" data-hide-empty>
+ <Box
+ className={InteractiveQuestionS.BackButtonWrapper}
+ mr="sm"
+ data-hide-empty
+ >
+ <BackButton data-hide-empty />
</Box>
<DefaultViewTitle
title={title}
@@ -211,8 +226,11 @@ export const SdkQuestionDefaultView = ({
{showSaveButton && <SaveButton onClick={openSaveModal} />}
</Group>
{queryResults && (
- <ResultToolbar data-testid="interactive-question-result-toolbar">
- <Group gap="xs">
+ <ResultToolbar
+ data-testid="interactive-question-result-toolbar"
+ data-hide-empty
+ >
+ <Group gap="xs" data-hide-empty>
{isEditorOpen ? (
<PopoverBackButton
onClick={toggleEditor}
@@ -253,8 +271,13 @@ export const SdkQuestionDefaultView = ({
</>
)}
</Group>
- <Group gap="sm">
- {withDownloads && <DownloadWidgetDropdown />}
+ <Group gap="sm" ml="auto" data-hide-empty>
+ {!isEditorOpen && (
+ <>
+ <DownloadWidgetDropdown />
+ <QuestionAlertsButton />
+ </>
+ )}
<EditorButton isOpen={isEditorOpen} onClick={toggleEditor} />
</Group>
</ResultToolbar>
diff --git a/frontend/src/embedding-sdk-bundle/components/private/notifications/SdkQuestionAlertListModal.tsx b/frontend/src/embedding-sdk-bundle/components/private/notifications/SdkQuestionAlertListModal.tsx
new file mode 100644
index 00000000000..eb82a10114c
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/notifications/SdkQuestionAlertListModal.tsx
@@ -0,0 +1,16 @@
+import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
+import { QuestionAlertListModal } from "metabase/notifications/modals";
+
+import { useQuestionAlertModalContext } from "./context/QuestionAlertModalProvider";
+
+export function SdkQuestionAlertListModal() {
+ const { question } = useSdkQuestionContext();
+ const { isOpen: isModalOpen, close: closeModal } =
+ useQuestionAlertModalContext();
+
+ if (!question || !isModalOpen) {
+ return null;
+ }
+
+ return <QuestionAlertListModal question={question} onClose={closeModal} />;
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider.tsx
new file mode 100644
index 00000000000..04359bf243c
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/private/notifications/context/QuestionAlertModalProvider.tsx
@@ -0,0 +1,33 @@
+import { useDisclosure } from "@mantine/hooks";
+import { type PropsWithChildren, createContext, useContext } from "react";
+
+interface QuestionAlertModalContext {
+ isOpen: boolean;
+ toggle: () => void;
+ close: () => void;
+}
+
+const DEFAULT_CONTEXT_VALUE: QuestionAlertModalContext = {
+ isOpen: false,
+ toggle: () => {},
+ close: () => {},
+};
+
+const questionAlertModalContext = createContext<QuestionAlertModalContext>(
+ DEFAULT_CONTEXT_VALUE,
+);
+
+export function QuestionAlertModalProvider({
+ children,
+}: PropsWithChildren): JSX.Element {
+ const [isOpen, { close, toggle }] = useDisclosure(false);
+ return (
+ <questionAlertModalContext.Provider value={{ isOpen, toggle, close }}>
+ {children}
+ </questionAlertModalContext.Provider>
+ );
+}
+
+export function useQuestionAlertModalContext() {
+ return useContext(questionAlertModalContext);
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
index f9ac43d42f0..5fd39189722 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
@@ -39,6 +39,7 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionProps> = Yup.object({
width: Yup.mixed().optional(),
withChartTypeSelector: Yup.mixed().optional(),
withDownloads: Yup.mixed().optional(),
+ withAlerts: Yup.mixed().optional(),
withResetButton: Yup.mixed().optional(),
onVisualizationChange: Yup.mixed().optional(),
}).noUnknown();
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.stories.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.stories.tsx
new file mode 100644
index 00000000000..e2c82d453c4
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.stories.tsx
@@ -0,0 +1,75 @@
+import type { Meta, StoryFn } from "@storybook/react";
+import type { ComponentProps } from "react";
+
+import { CommonSdkStoryWrapper } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";
+import {
+ questionIdArgType,
+ questionIds,
+} from "embedding-sdk-bundle/test/storybook-id-args";
+import { Box } from "metabase/ui";
+
+import { InteractiveQuestion } from "./InteractiveQuestion";
+
+const QUESTION_ID = (window as any).QUESTION_ID || questionIds.numberId;
+
+type InteractiveQuestionComponentProps = ComponentProps<
+ typeof InteractiveQuestion
+>;
+export default {
+ title: "EmbeddingSDK/InteractiveQuestion",
+ component: InteractiveQuestion,
+ parameters: {
+ layout: "fullscreen",
+ },
+ decorators: [CommonSdkStoryWrapper],
+ argTypes: {
+ questionId: questionIdArgType,
+ },
+ args: {
+ isSaveEnabled: true,
+ },
+} satisfies Meta<typeof InteractiveQuestion>;
+
+const Template: StoryFn<InteractiveQuestionComponentProps> = (args) => {
+ return (
+ <Box p="md">
+ <InteractiveQuestion {...args} />
+ </Box>
+ );
+};
+
+export const Default = {
+ render: Template,
+
+ args: {
+ questionId: QUESTION_ID,
+ title: false,
+ withAlerts: false,
+ withDownloads: false,
+ withChartTypeSelector: false,
+ },
+};
+
+export const WithCustomTitle = {
+ render: Template,
+
+ args: {
+ questionId: QUESTION_ID,
+ title: "Acme Inc. Sales Report",
+ withAlerts: false,
+ withDownloads: false,
+ withChartTypeSelector: false,
+ },
+};
+
+export const WithAdditionalElements = {
+ render: Template,
+
+ args: {
+ questionId: QUESTION_ID,
+ title: "Acme Inc. Sales Report",
+ withAlerts: false,
+ withDownloads: true,
+ withChartTypeSelector: true,
+ },
+};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
index dd3e29d1b7e..43da1a8c95b 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
@@ -28,6 +28,8 @@ import {
type SdkQuestionProps,
} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";
+import { QuestionAlertsButton } from "../notifications/QuestionAlertsButton";
+
import { interactiveQuestionSchema } from "./InteractiveQuestion.schema";
/**
@@ -69,6 +71,7 @@ export type InteractiveQuestionComponents = {
BreakoutDropdown: typeof BreakoutDropdown;
DownloadWidget: typeof DownloadWidget;
DownloadWidgetDropdown: typeof DownloadWidgetDropdown;
+ AlertsButton: typeof QuestionAlertsButton;
SqlParametersList: typeof SqlParametersList;
};
@@ -99,6 +102,7 @@ const subComponents: InteractiveQuestionComponents = {
ChartTypeDropdown: ChartTypeDropdown,
DownloadWidget: DownloadWidget,
DownloadWidgetDropdown: DownloadWidgetDropdown,
+ AlertsButton: QuestionAlertsButton,
VisualizationButton: VisualizationButton,
SqlParametersList: SqlParametersList,
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
new file mode 100644
index 00000000000..313a49e8fe6
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
@@ -0,0 +1,561 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import {
+ findRequests,
+ setupAlertsEndpoints,
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
+ setupDatabaseEndpoints,
+ setupDatabaseListEndpoint,
+ setupNotificationChannelsEndpoints,
+ setupSearchEndpoints,
+ setupTableEndpoints,
+ setupUserRecipientsEndpoint,
+} from "__support__/server-mocks";
+import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";
+import {
+ setupCreateNotificationEndpoint,
+ setupListNotificationEndpoints,
+} from "__support__/server-mocks/notification";
+import {
+ mockGetBoundingClientRect,
+ screen,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import { reinitialize } from "metabase/plugins";
+import type { CardId, CollectionType, TokenFeatures } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockCollection,
+ createMockColumn,
+ createMockDatabase,
+ createMockDataset,
+ createMockDatasetData,
+ createMockTable,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createMockNotification } from "metabase-types/api/mocks/notification";
+
+import { InteractiveQuestion } from "./InteractiveQuestion";
+
+const TEST_DB_ID = 1;
+const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
+
+const TEST_TABLE_ID = 1;
+const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });
+
+const TEST_COLUMN = createMockColumn({
+ display_name: "Test Column",
+ name: "Test Column",
+});
+
+const TEST_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"]],
+ }),
+});
+
+const TEST_CARD_ID: CardId = 1 as const;
+
+const USER_ID = 999;
+
+interface SetupOpts {
+ title?: string | boolean;
+ withChartTypeSelector?: boolean;
+ withDownloads?: boolean;
+ withAlerts?: boolean;
+ isEmailSetup?: boolean;
+ canManageSubscriptions?: boolean;
+ isSuperuser?: boolean;
+ isModel?: boolean;
+ notifications?: ReturnType<typeof createMockNotification>[];
+ collectionType?: CollectionType;
+ tokenFeatures?: Partial<TokenFeatures>;
+ enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
+ children?: React.ReactNode;
+}
+
+const setup = async ({
+ title,
+ withChartTypeSelector,
+ withDownloads,
+ withAlerts,
+ isEmailSetup = true,
+ canManageSubscriptions = true,
+ isSuperuser = true,
+ isModel = false,
+ notifications = [],
+ collectionType,
+ tokenFeatures,
+ enterprisePlugins,
+ children,
+}: SetupOpts = {}) => {
+ setupNotificationChannelsEndpoints({
+ email: { configured: isEmailSetup },
+ } as any);
+
+ const user = createMockUser({
+ id: USER_ID,
+ is_superuser: isSuperuser,
+ });
+
+ const { state } = setupSdkState({
+ currentUser: {
+ ...user,
+ permissions: {
+ can_access_subscription: canManageSubscriptions,
+ },
+ },
+ tokenFeatures: tokenFeatures
+ ? createMockTokenFeatures(tokenFeatures)
+ : undefined,
+ });
+
+ if (enterprisePlugins) {
+ enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
+ }
+
+ const COLLECTION_ID = 1;
+ const TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: COLLECTION_ID,
+ location: "/",
+ name: "Test collection",
+ personal_owner_id: 100,
+ type: collectionType,
+ });
+
+ const cardType = isModel ? "model" : "question";
+ const card = createMockCard({
+ id: TEST_CARD_ID,
+ name: "My Question",
+ type: cardType,
+ collection_id: COLLECTION_ID,
+ collection: TEST_COLLECTION,
+ });
+
+ setupCardEndpoints(card);
+ setupCardQueryMetadataEndpoint(
+ card,
+ createMockCardQueryMetadata({
+ databases: [TEST_DB],
+ tables: [TEST_TABLE],
+ }),
+ );
+ setupAlertsEndpoints(card, []);
+ setupDatabaseEndpoints(TEST_DB);
+ setupTableEndpoints(TEST_TABLE);
+ setupCardQueryEndpoints(card, TEST_DATASET);
+
+ setupCollectionByIdEndpoint({
+ collections: [TEST_COLLECTION],
+ });
+
+ setupListNotificationEndpoints({ card_id: card.id }, notifications);
+ /**
+ * We don't care about these endpoints' results.
+ * We only want to avoid getting fetch-mock's unmocked endpoints error.
+ */
+ setupUserRecipientsEndpoint({ users: [] });
+ setupWebhookChannelsEndpoint();
+ setupCreateNotificationEndpoint();
+
+ /**
+ * These endpoints are used in query editor, we don't care about their values,
+ * we just need to mock them to not fail fetch-mock's unmocked responses error.
+ */
+ setupSearchEndpoints([]);
+ setupDatabaseListEndpoint([]);
+
+ renderWithSDKProviders(
+ <InteractiveQuestion
+ questionId={TEST_CARD_ID}
+ title={title}
+ withChartTypeSelector={withChartTypeSelector}
+ withDownloads={withDownloads}
+ withAlerts={withAlerts}
+ >
+ {children}
+ </InteractiveQuestion>,
+ {
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ storeInitialState: state,
+ },
+ );
+
+ await waitForLoaderToBeRemoved();
+};
+
+describe("InteractiveQuestion", () => {
+ beforeAll(() => {
+ mockGetBoundingClientRect();
+ });
+
+ it("should render an interactive question with the mocked data", async () => {
+ await setup();
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ });
+
+ describe("toolbar visibility", () => {
+ it("should hide the chart type selector when it is disabled", async () => {
+ await setup({
+ withChartTypeSelector: false,
+ });
+
+ expect(
+ screen.queryByTestId("chart-type-selector-button"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should show the chart type selector when it is enabled", async () => {
+ await setup({
+ withChartTypeSelector: true,
+ });
+
+ expect(screen.getByTestId("chart-type-selector-button")).toBeVisible();
+ });
+
+ it("should show the download widget when downloads are enabled", async () => {
+ await setup({
+ withDownloads: true,
+ });
+
+ expect(
+ screen.getByRole("button", { name: "Download results" }),
+ ).toBeVisible();
+ });
+
+ it("should not show the download widget when downloads are disabled", async () => {
+ await setup({
+ withDownloads: false,
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Download results" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("alerts button with different Metabase version configurations", () => {
+ beforeEach(() => {
+ reinitialize();
+ });
+
+ // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("OSS (Open Source Software)", () => {
+ it("should not show the alert button in OSS regardless of settings", async () => {
+ // Don't setup enterprise plugin for OSS
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("EE (Enterprise Edition) without embedding_sdk token feature", () => {
+ it("should not show the alert button when plugin is enabled but token feature is missing", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("EE with embedding_sdk token feature", () => {
+ it("should show the alert button when plugin and token feature are both enabled", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
+ });
+
+ it("should show the alert button for custom layouts when withAlerts is true", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <InteractiveQuestion.AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
+ });
+
+ it("should not show the alert button for custom layouts when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <InteractiveQuestion.AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when email is not configured", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: false,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when user cannot manage subscriptions and is not admin", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ isSuperuser: false,
+ canManageSubscriptions: false,
+ enterprisePlugins: ["sdk_notifications", "application_permissions"],
+ tokenFeatures: { embedding_sdk: true, advanced_permissions: true },
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for models", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for analytics collection", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ collectionType: "instance-analytics",
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+ });
+
+ it("should not show alerts and downloads buttons when editing the question", async () => {
+ await setup({
+ withDownloads: true,
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ // Both buttons are visible in view mode
+ expect(screen.queryByRole("button", { name: "Alerts" })).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Download results" }),
+ ).toBeVisible();
+
+ expect(
+ screen.queryByRole("button", { name: "Back" }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole("button", { name: "Edit question" }),
+ );
+
+ // This button only shows on edit mode
+ expect(screen.queryByRole("button", { name: "Back" })).toBeVisible();
+ // Both buttons are hidden in edit mode
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Download results" }),
+ ).not.toBeInTheDocument();
+ });
+
+ describe("alert modal", () => {
+ it("should show alert list modal when there are existing alerts", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ notifications: [createMockNotification()],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+
+ await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
+
+ // Verify the alert list modal appears, not the create modal
+ const withinModal = within(await findModal());
+
+ // Show the alert list modal title
+ expect(
+ await withinModal.findByRole("heading", { name: "Edit alerts" }),
+ ).toBeVisible();
+
+ // Should show the button to create a new alert in the list modal
+ expect(withinModal.getByText("New alert")).toBeVisible();
+
+ // Should NOT show the create alert form fields
+ expect(
+ withinModal.queryByText("What do you want to be alerted about?"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show email selector on the SDK and use current logged in user as the recipient", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
+
+ const withinModal = within(await findModal());
+ expect(
+ withinModal.getByRole("heading", { name: "New alert" }),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("What do you want to be alerted about?"),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("When do you want to check this?"),
+ ).toBeVisible();
+ // Email selector is within this section, checking only the header is fine
+ expect(
+ withinModal.queryByText("Where do you want to send the results?"),
+ ).not.toBeInTheDocument();
+ expect(withinModal.getByText("More options")).toBeVisible();
+ await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
+
+ const createNotificationRequest = (await findRequests("POST")).find(
+ (postRequest) =>
+ postRequest.url === "http://localhost/api/notification",
+ );
+ // Checks that we're using the current logged in user as the sole recipient
+ expect(createNotificationRequest?.body).toMatchObject({
+ handlers: [
+ {
+ channel_type: "channel/email",
+ recipients: [
+ {
+ details: null,
+ type: "notification-recipient/user",
+ user_id: USER_ID,
+ },
+ ],
+ },
+ ],
+ });
+ // So that when we assert this value, we know we won't accidentally match the default mock ID
+ expect(USER_ID).not.toBe(1);
+ });
+ });
+});
+
+async function findModal() {
+ return await screen.findByRole("dialog");
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
index ed2e3e7a020..bd9cf15070e 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx
@@ -34,6 +34,8 @@ import {
type SdkQuestionDefaultViewProps,
} from "embedding-sdk-bundle/components/private/SdkQuestionDefaultView";
+import { QuestionAlertsButton } from "../notifications/QuestionAlertsButton";
+
import type { SdkQuestionIdProps } from "./types";
/**
@@ -110,6 +112,8 @@ export type SdkQuestionComponents = {
BreakoutDropdown: typeof BreakoutDropdown;
DownloadWidget: typeof DownloadWidget;
DownloadWidgetDropdown: typeof DownloadWidgetDropdown;
+ AlertsButton: typeof QuestionAlertsButton;
+
SqlParametersList: typeof SqlParametersList;
};
@@ -130,6 +134,7 @@ export const _SdkQuestion = ({
initialSqlParameters,
hiddenParameters,
withDownloads = false,
+ withAlerts = false,
targetDashboardId,
backToDashboard,
getClickActionMode,
@@ -160,6 +165,7 @@ export const _SdkQuestion = ({
initialSqlParameters={initialSqlParameters}
hiddenParameters={hiddenParameters}
withDownloads={withDownloads}
+ withAlerts={withAlerts}
targetDashboardId={targetDashboardId}
backToDashboard={backToDashboard}
getClickActionMode={getClickActionMode}
@@ -203,6 +209,7 @@ const subComponents: SdkQuestionComponents = {
ChartTypeDropdown: ChartTypeDropdown,
DownloadWidget: DownloadWidget,
DownloadWidgetDropdown: DownloadWidgetDropdown,
+ AlertsButton: QuestionAlertsButton,
VisualizationButton: VisualizationButton,
SqlParametersList: SqlParametersList,
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
index 9d5f52e2f00..a0e69cd22ed 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
@@ -21,6 +21,7 @@ const propsSchema: Yup.SchemaOf<StaticQuestionProps> = Yup.object({
width: Yup.mixed().optional(),
withChartTypeSelector: Yup.mixed().optional(),
withDownloads: Yup.mixed().optional(),
+ withAlerts: Yup.mixed().optional(),
}).noUnknown();
export const staticQuestionSchema: FunctionSchema = {
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.stories.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.stories.tsx
index b13597f12c8..fbeb0a2e34a 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.stories.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.stories.tsx
@@ -1,4 +1,4 @@
-import type { StoryFn } from "@storybook/react";
+import type { Meta, StoryFn } from "@storybook/react";
import type { ComponentProps } from "react";
import { CommonSdkStoryWrapper } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";
@@ -23,16 +23,8 @@ export default {
decorators: [CommonSdkStoryWrapper],
argTypes: {
questionId: questionIdArgType,
- withDownloads: {
- control: "boolean",
- defaultValue: false,
- },
- withChartTypeSelector: {
- control: "boolean",
- defaultValue: false,
- },
},
-};
+} satisfies Meta<typeof StaticQuestion>;
const Template: StoryFn<StaticQuestionComponentProps> = (args) => {
return (
@@ -47,8 +39,8 @@ export const Default = {
args: {
questionId: QUESTION_ID,
- isSaveEnabled: true,
title: false,
+ withAlerts: false,
withDownloads: false,
withChartTypeSelector: false,
},
@@ -60,6 +52,7 @@ export const WithCustomTitle = {
args: {
questionId: QUESTION_ID,
title: "Acme Inc. Sales Report",
+ withAlerts: false,
withDownloads: false,
withChartTypeSelector: false,
},
@@ -71,6 +64,7 @@ export const WithAdditionalElements = {
args: {
questionId: QUESTION_ID,
title: "Acme Inc. Sales Report",
+ withAlerts: false,
withDownloads: true,
withChartTypeSelector: true,
},
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
index f0b0ab7c5bf..6780b4b6ec8 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
@@ -1,4 +1,4 @@
-import type { PropsWithChildren } from "react";
+import { type PropsWithChildren, useRef } from "react";
import { FlexibleSizeComponent } from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";
import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
@@ -27,11 +27,13 @@ import {
SdkQuestion,
type SdkQuestionProps,
} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";
+import { QuestionAlertsButton } from "embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton";
+import { useHideEmptyElement } from "embedding-sdk-bundle/hooks/private/use-hide-empty-element";
import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";
import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";
-import { Box, Stack } from "metabase/ui";
+import { Box, Group, Stack } from "metabase/ui";
import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";
import { EmbeddingSdkStaticMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode";
import type { ClickActionModeGetter } from "metabase/visualizations/types";
@@ -55,6 +57,7 @@ export type StaticQuestionProps = PropsWithChildren<
| "initialSqlParameters"
| "hiddenParameters"
| "withDownloads"
+ | "withAlerts"
| "title"
>
> &
@@ -79,6 +82,7 @@ export type StaticQuestionComponents = {
BreakoutDropdown: typeof BreakoutDropdown;
DownloadWidget: typeof DownloadWidget;
DownloadWidgetDropdown: typeof DownloadWidgetDropdown;
+ AlertsButton: typeof QuestionAlertsButton;
SqlParametersList: typeof SqlParametersList;
};
@@ -100,6 +104,7 @@ const StaticQuestionInner = (
initialSqlParameters,
hiddenParameters,
withDownloads,
+ withAlerts,
title = false, // Hidden by default for backwards-compatibility.
children,
} = normalizedProps;
@@ -120,8 +125,8 @@ const StaticQuestionInner = (
);
};
- const hasResultToolbar = withChartTypeSelector || withDownloads;
- const hasTopBar = Boolean(title || hasResultToolbar || isGuestEmbed);
+ const hideEmptyParentRef = useRef<HTMLDivElement>(null);
+ useHideEmptyElement("[data-hide-empty]", hideEmptyParentRef);
return (
<SdkQuestion
@@ -132,6 +137,7 @@ const StaticQuestionInner = (
initialSqlParameters={initialSqlParameters}
hiddenParameters={hiddenParameters}
withDownloads={withDownloads}
+ withAlerts={withAlerts}
>
{children ?? (
<FlexibleSizeComponent
@@ -145,21 +151,27 @@ const StaticQuestionInner = (
w="100%"
h="100%"
gap="xs"
+ ref={hideEmptyParentRef}
>
- {hasTopBar && (
- <Stack className={InteractiveQuestionS.TopBar} gap="sm" p="md">
- {title && <DefaultViewTitle title={title} />}
+ <Stack
+ className={InteractiveQuestionS.TopBar}
+ gap="sm"
+ p="md"
+ data-hide-empty
+ data-testid="static-question-top-bar"
+ >
+ {title && <DefaultViewTitle title={title} />}
+ <ResultToolbar data-hide-empty data-testid="result-toolbar">
+ {withChartTypeSelector && <SdkQuestion.ChartTypeDropdown />}
+ {/* This container is always shown on the right */}
+ <Group gap="sm" ml="auto" data-hide-empty>
+ <SdkQuestion.DownloadWidgetDropdown />
+ <QuestionAlertsButton />
+ </Group>
+ </ResultToolbar>
- {hasResultToolbar && (
- <ResultToolbar>
- {withChartTypeSelector && <SdkQuestion.ChartTypeDropdown />}
- {withDownloads && <SdkQuestion.DownloadWidgetDropdown />}
- </ResultToolbar>
- )}
-
- {isGuestEmbed && <SdkQuestion.SqlParametersList />}
- </Stack>
- )}
+ {isGuestEmbed && <SdkQuestion.SqlParametersList />}
+ </Stack>
<Box className={InteractiveQuestionS.Main} w="100%" h="100%">
<Box className={InteractiveQuestionS.Content}>
@@ -194,6 +206,7 @@ const subComponents: StaticQuestionComponents = {
BreakoutDropdown: BreakoutDropdown,
DownloadWidget: DownloadWidget,
DownloadWidgetDropdown: DownloadWidgetDropdown,
+ AlertsButton: QuestionAlertsButton,
SqlParametersList: SqlParametersList,
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
new file mode 100644
index 00000000000..3343ea57d7d
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
@@ -0,0 +1,556 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
+import {
+ findRequests,
+ setupAlertsEndpoints,
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
+ setupDatabaseEndpoints,
+ setupNotificationChannelsEndpoints,
+ setupTableEndpoints,
+ setupUserRecipientsEndpoint,
+} from "__support__/server-mocks";
+import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";
+import {
+ setupCreateNotificationEndpoint,
+ setupListNotificationEndpoints,
+} from "__support__/server-mocks/notification";
+import {
+ mockGetBoundingClientRect,
+ screen,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import { reinitialize } from "metabase/plugins";
+import type { CardId, CollectionType, TokenFeatures } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockCollection,
+ createMockColumn,
+ createMockDatabase,
+ createMockDataset,
+ createMockDatasetData,
+ createMockTable,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createMockNotification } from "metabase-types/api/mocks/notification";
+
+import { StaticQuestion } from "./StaticQuestion";
+
+const TEST_DB_ID = 1;
+const TEST_DB = createMockDatabase({ id: TEST_DB_ID });
+
+const TEST_TABLE_ID = 1;
+const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });
+
+const TEST_COLUMN = createMockColumn({
+ display_name: "Test Column",
+ name: "Test Column",
+});
+
+const TEST_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"]],
+ }),
+});
+
+const TEST_CARD_ID: CardId = 1 as const;
+
+const USER_ID = 999;
+
+interface SetupOpts {
+ title?: string | boolean;
+ withChartTypeSelector?: boolean;
+ withDownloads?: boolean;
+ withAlerts?: boolean;
+ isEmailSetup?: boolean;
+ canManageSubscriptions?: boolean;
+ isSuperuser?: boolean;
+ isModel?: boolean;
+ notifications?: ReturnType<typeof createMockNotification>[];
+ collectionType?: CollectionType;
+ tokenFeatures?: Partial<TokenFeatures>;
+ enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][];
+ children?: React.ReactNode;
+}
+
+const setup = async ({
+ title,
+ withChartTypeSelector,
+ withDownloads,
+ withAlerts,
+ isEmailSetup = true,
+ canManageSubscriptions = true,
+ isSuperuser = true,
+ isModel = false,
+ notifications = [],
+ collectionType,
+ tokenFeatures,
+ enterprisePlugins,
+ children,
+}: SetupOpts = {}) => {
+ setupNotificationChannelsEndpoints({
+ email: { configured: isEmailSetup },
+ } as any);
+
+ const user = createMockUser({
+ id: USER_ID,
+ is_superuser: isSuperuser,
+ });
+
+ const { state } = setupSdkState({
+ currentUser: {
+ ...user,
+ permissions: {
+ can_access_subscription: canManageSubscriptions,
+ },
+ },
+ tokenFeatures: tokenFeatures
+ ? createMockTokenFeatures(tokenFeatures)
+ : undefined,
+ });
+
+ if (enterprisePlugins) {
+ enterprisePlugins.forEach(setupEnterpriseOnlyPlugin);
+ }
+
+ const COLLECTION_ID = 1;
+ const TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: COLLECTION_ID,
+ location: "/",
+ name: "Test collection",
+ type: collectionType,
+ });
+
+ const cardType = isModel ? "model" : "question";
+ const card = createMockCard({
+ id: TEST_CARD_ID,
+ name: "My Question",
+ type: cardType,
+ collection_id: COLLECTION_ID,
+ collection: TEST_COLLECTION,
+ });
+
+ setupCardEndpoints(card);
+ setupCardQueryMetadataEndpoint(
+ card,
+ createMockCardQueryMetadata({
+ databases: [TEST_DB],
+ }),
+ );
+ setupAlertsEndpoints(card, []);
+ setupDatabaseEndpoints(TEST_DB);
+ setupTableEndpoints(TEST_TABLE);
+ setupCardQueryEndpoints(card, TEST_DATASET);
+
+ setupCollectionByIdEndpoint({
+ collections: [TEST_COLLECTION],
+ });
+
+ setupListNotificationEndpoints({ card_id: card.id }, notifications);
+ /**
+ * We don't care about these endpoints' results.
+ * We only want to avoid getting fetch-mock's unmocked endpoints error.
+ */
+ setupUserRecipientsEndpoint({ users: [] });
+ setupWebhookChannelsEndpoint();
+ setupCreateNotificationEndpoint();
+
+ renderWithSDKProviders(
+ <StaticQuestion
+ questionId={TEST_CARD_ID}
+ title={title}
+ withChartTypeSelector={withChartTypeSelector}
+ withDownloads={withDownloads}
+ withAlerts={withAlerts}
+ >
+ {children}
+ </StaticQuestion>,
+ {
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ storeInitialState: state,
+ },
+ );
+
+ await waitForLoaderToBeRemoved();
+};
+
+describe("StaticQuestion", () => {
+ beforeAll(() => {
+ mockGetBoundingClientRect();
+ });
+
+ it("should render a static question with the mocked data", async () => {
+ await setup();
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ });
+
+ describe("toolbar visibility", () => {
+ it("should hide the TopBar when no UI elements are provided", async () => {
+ await setup({
+ title: false,
+ withChartTypeSelector: false,
+ withDownloads: false,
+ withAlerts: false,
+ });
+
+ const topBar = screen.getByTestId("static-question-top-bar");
+
+ expect(topBar).not.toBeVisible();
+ expect(topBar).toHaveStyle({ display: "none" });
+ });
+
+ it("should show the TopBar when title is provided", async () => {
+ await setup({
+ title: "My Custom Title",
+ withChartTypeSelector: false,
+ withDownloads: false,
+ withAlerts: false,
+ });
+
+ const topBar = screen.getByTestId("static-question-top-bar");
+
+ expect(topBar).toBeVisible();
+ expect(topBar).not.toHaveStyle({ display: "none" });
+ expect(screen.getByText("My Custom Title")).toBeVisible();
+ });
+
+ it("should show the TopBar when withChartTypeSelector is true", async () => {
+ await setup({
+ title: false,
+ withChartTypeSelector: true,
+ withDownloads: false,
+ withAlerts: false,
+ });
+
+ const topBar = screen.getByTestId("static-question-top-bar");
+
+ expect(topBar).toBeVisible();
+ expect(topBar).not.toHaveStyle({ display: "none" });
+ expect(screen.getByTestId("chart-type-selector-button")).toBeVisible();
+ });
+
+ it("should show the TopBar when withDownloads is true", async () => {
+ await setup({
+ title: false,
+ withChartTypeSelector: false,
+ withDownloads: true,
+ withAlerts: false,
+ });
+
+ const topBar = screen.getByTestId("static-question-top-bar");
+
+ expect(topBar).toBeVisible();
+ expect(topBar).not.toHaveStyle({ display: "none" });
+ expect(
+ screen.getByRole("button", { name: "Download results" }),
+ ).toBeVisible();
+ });
+
+ describe("alerts button with different Metabase version configurations", () => {
+ beforeEach(() => {
+ reinitialize();
+ });
+
+ // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("OSS (Open Source Software)", () => {
+ it("should not show the alert button in OSS regardless of settings", async () => {
+ // Don't setup enterprise plugin for OSS
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ // eslint-disable-next-line jest/no-disabled-tests -- Fix this in EMB-1184, when we can test SDK with API keys
+ describe.skip("EE (Enterprise Edition) without embedding_sdk token feature", () => {
+ it("should not show the alert button when plugin is enabled but token feature is missing", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ tokenFeatures: {}, // No embedding_sdk feature
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe("EE with embedding_sdk token feature", () => {
+ it("should show the alert button when plugin and token feature are both enabled", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
+ });
+
+ it("should show the alert button for custom layouts when withAlerts is true", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <StaticQuestion.AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();
+ });
+
+ it("should not show the alert button for custom layouts when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ children: (
+ <div>
+ <span>Custom Layout</span>
+ <StaticQuestion.AlertsButton />
+ </div>
+ ),
+ });
+
+ expect(screen.getByText("Custom Layout")).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when withAlerts is false", async () => {
+ await setup({
+ withAlerts: false,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when email is not configured", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: false,
+ canManageSubscriptions: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button when user cannot manage subscriptions and is not admin", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ isSuperuser: false,
+ canManageSubscriptions: false,
+ enterprisePlugins: ["sdk_notifications", "application_permissions"],
+ tokenFeatures: { embedding_sdk: true, advanced_permissions: true },
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for models", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: true,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show the alert button for analytics collection", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ collectionType: "instance-analytics",
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Alerts" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+ });
+
+ it("should show the TopBar when multiple UI elements are provided", async () => {
+ await setup({
+ title: "My Title",
+ withChartTypeSelector: true,
+ withDownloads: true,
+ withAlerts: true,
+ });
+
+ const topBar = screen.getByTestId("static-question-top-bar");
+
+ expect(topBar).toBeVisible();
+ expect(topBar).not.toHaveStyle({ display: "none" });
+ expect(screen.getByText("My Title")).toBeVisible();
+ expect(screen.getByTestId("chart-type-selector-button")).toBeVisible();
+ });
+ });
+
+ describe("alert modal", () => {
+ it("should show alert list modal when there are existing alerts", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ notifications: [createMockNotification()],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+
+ await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
+
+ // Verify the alert list modal appears, not the create modal
+ const withinModal = within(await findModal());
+
+ // Show the alert list modal title
+ expect(
+ await withinModal.findByRole("heading", { name: "Edit alerts" }),
+ ).toBeVisible();
+
+ // Should show the button to create a new alert in the list modal
+ expect(withinModal.getByText("New alert")).toBeVisible();
+
+ // Should NOT show the create alert form fields
+ expect(
+ withinModal.queryByText("What do you want to be alerted about?"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show email selector on the SDK and use current logged in user as the recipient", async () => {
+ await setup({
+ withAlerts: true,
+ isEmailSetup: true,
+ canManageSubscriptions: true,
+ isModel: false,
+ enterprisePlugins: ["sdk_notifications"],
+ });
+
+ expect(
+ within(screen.getByRole("gridcell")).getByText("Test Row"),
+ ).toBeVisible();
+ await userEvent.click(screen.getByRole("button", { name: "Alerts" }));
+
+ const withinModal = within(await findModal());
+ expect(
+ withinModal.getByRole("heading", { name: "New alert" }),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("What do you want to be alerted about?"),
+ ).toBeVisible();
+ expect(
+ withinModal.getByText("When do you want to check this?"),
+ ).toBeVisible();
+ // Email selector is within this section, checking only the header is fine
+ expect(
+ withinModal.queryByText("Where do you want to send the results?"),
+ ).not.toBeInTheDocument();
+ expect(withinModal.getByText("More options")).toBeVisible();
+ await userEvent.click(withinModal.getByRole("button", { name: "Done" }));
+
+ const createNotificationRequest = (await findRequests("POST")).find(
+ (postRequest) =>
+ postRequest.url === "http://localhost/api/notification",
+ );
+ // Checks that we're using the current logged in user as the sole recipient
+ expect(createNotificationRequest?.body).toMatchObject({
+ handlers: [
+ {
+ channel_type: "channel/email",
+ recipients: [
+ {
+ details: null,
+ type: "notification-recipient/user",
+ user_id: USER_ID,
+ },
+ ],
+ },
+ ],
+ });
+ // So that when we assert this value, we know we won't accidentally match the default mock ID
+ expect(USER_ID).not.toBe(1);
+ });
+ });
+});
+
+async function findModal() {
+ return await screen.findByRole("dialog");
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx
index ffe41d78e38..cad9c002764 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/enterprise.unit.spec.tsx
@@ -23,7 +23,7 @@ const setupEnterprise = async (
) => {
return setupSdkDashboard({
...options,
- enterprisePlugins: ["sdk_subscriptions", "embedding"],
+ enterprisePlugins: ["sdk_notifications", "embedding"],
component: EditableDashboard,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/premium.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/premium.unit.spec.tsx
index 0d79dd70024..4f04e31f103 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/premium.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/premium.unit.spec.tsx
@@ -26,7 +26,7 @@ const setupPremium = async (
tokenFeatures: {
embedding_sdk: true,
},
- enterprisePlugins: ["sdk_subscriptions", "embedding"],
+ enterprisePlugins: ["sdk_notifications", "embedding"],
component: EditableDashboard,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/enterprise.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/enterprise.unit.spec.tsx
index 46906453e9f..74b04e79110 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/enterprise.unit.spec.tsx
@@ -10,7 +10,7 @@ const setupEnterprise = async (
) => {
return setupSdkDashboard({
...options,
- enterprisePlugins: ["sdk_subscriptions"],
+ enterprisePlugins: ["sdk_notifications"],
component: InteractiveDashboard,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/premium.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/premium.unit.spec.tsx
index a9ac431cf2f..5eaaff8f04c 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/premium.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/tests/premium.unit.spec.tsx
@@ -13,7 +13,7 @@ const setupPremium = async (
tokenFeatures: {
embedding_sdk: true,
},
- enterprisePlugins: ["sdk_subscriptions"],
+ enterprisePlugins: ["sdk_notifications"],
component: InteractiveDashboard,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/enterprise.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/enterprise.unit.spec.tsx
index b73f2296032..2e218644fb4 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/enterprise.unit.spec.tsx
@@ -20,7 +20,7 @@ const setupEnterprise = async (
) => {
return setupSdkDashboard({
...options,
- enterprisePlugins: ["sdk_subscriptions"],
+ enterprisePlugins: ["sdk_notifications"],
component: StaticDashboard as ComponentType<SdkDashboardProps>,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/premium.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/premium.unit.spec.tsx
index 52044ba9f6e..530d7a882d5 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/premium.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/tests/premium.unit.spec.tsx
@@ -21,7 +21,7 @@ const setupPremium = async (
tokenFeatures: {
embedding_sdk: true,
},
- enterprisePlugins: ["sdk_subscriptions"],
+ enterprisePlugins: ["sdk_notifications"],
component: StaticDashboard as ComponentType<SdkDashboardProps>,
});
};
diff --git a/frontend/src/embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton.tsx b/frontend/src/embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton.tsx
new file mode 100644
index 00000000000..7d28c229fd7
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton.tsx
@@ -0,0 +1,5 @@
+import { PLUGIN_NOTIFICATIONS_SDK } from "embedding-sdk-bundle/components/public/notifications";
+
+export function QuestionAlertsButton() {
+ return <PLUGIN_NOTIFICATIONS_SDK.QuestionAlertsButton />;
+}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/subscriptions/index.tsx b/frontend/src/embedding-sdk-bundle/components/public/notifications/index.tsx
similarity index 55%
rename from frontend/src/embedding-sdk-bundle/components/public/subscriptions/index.tsx
rename to frontend/src/embedding-sdk-bundle/components/public/notifications/index.tsx
index 1e0eca0e601..7b19fc6872a 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/subscriptions/index.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/notifications/index.tsx
@@ -5,23 +5,25 @@ import type { ActionIconProps } from "metabase/ui";
export type DashboardSubscriptionsButtonProps = ActionIconProps &
ButtonHTMLAttributes<HTMLButtonElement>;
-function getDefaultPluginDashboardSubscriptionsSdk() {
+export type QuestionAlertsButtonProps = ActionIconProps &
+ ButtonHTMLAttributes<HTMLButtonElement>;
+
+function getDefaultPluginNotificationsSdk() {
return {
DashboardSubscriptionsButton: (
_props: DashboardSubscriptionsButtonProps,
): JSX.Element | null => null,
+ QuestionAlertsButton: (
+ _props: QuestionAlertsButtonProps,
+ ): JSX.Element | null => null,
};
}
-export const PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK =
- getDefaultPluginDashboardSubscriptionsSdk();
+export const PLUGIN_NOTIFICATIONS_SDK = getDefaultPluginNotificationsSdk();
/**
* @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.
*/
export function reinitialize() {
- Object.assign(
- PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK,
- getDefaultPluginDashboardSubscriptionsSdk(),
- );
+ Object.assign(PLUGIN_NOTIFICATIONS_SDK, getDefaultPluginNotificationsSdk());
}
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.ts
new file mode 100644
index 00000000000..7e0a0846dfd
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.ts
@@ -0,0 +1,83 @@
+import { useEffect } from "react";
+
+/**
+ * The reason we need to use JavaScript to detect the emptiness of nested elements is that
+ * we can't easily determine if an element would be empty because each element has its own logic
+ * to decide whether it will render content or not. And we need to expose all those logics to the
+ * parent component which would make the code more complex and less maintainable.
+ */
+
+/**
+ * A hook that hides elements matching the given selector if they are empty
+ * @param {string} selector - CSS selector targeting elements we want to hide if empty
+ * @param {React.RefObject<HTMLDivElement>} parentElementRef - The parent element ref within which to search for elements to hide
+ */
+export function useHideEmptyElement(
+ selector: string,
+ parentElementRef: React.RefObject<HTMLDivElement>,
+) {
+ /**
+ * This hook will traverse the DOM tree starting from the children and going up to the parent.
+ * This ensures MutationObserver captures changes in child elements before evaluating parent elements
+ * in case a parent component uses this hook as well.
+ */
+ useEffect(() => {
+ const parentElement = parentElementRef.current;
+ if (!parentElement) {
+ return;
+ }
+
+ const updateVisibility = () => {
+ const elements: Element[] = [
+ parentElement as Element,
+ ...Array.from(parentElement.querySelectorAll(selector)),
+ ];
+
+ // Bottom-up recursion
+ for (let index = elements.length - 1; index >= 0; index--) {
+ const element = elements[index];
+ const hasText = element.textContent?.trim().length > 0;
+ const hasMeaningfulChildren = Array.from(element.children).some(
+ (child) => {
+ return isElementVisible(child as HTMLElement);
+ },
+ );
+
+ (element as HTMLElement).style.display =
+ !hasText && !hasMeaningfulChildren ? "none" : "";
+ }
+ };
+
+ // Initial check
+ updateVisibility();
+
+ // Set up MutationObserver to watch for DOM changes
+ const observer = new MutationObserver(() => {
+ updateVisibility();
+ });
+
+ observer.observe(parentElement, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [selector, parentElementRef]);
+}
+
+function isElementVisible(element: HTMLElement): boolean {
+ if (element.style.display === "none") {
+ return false;
+ }
+
+ if (element.children.length === 0) {
+ return true;
+ }
+
+ return Array.from(element.children).some((child) =>
+ isElementVisible(child as HTMLElement),
+ );
+}
diff --git a/frontend/src/embedding-sdk-bundle/test/storybook-id-args.ts b/frontend/src/embedding-sdk-bundle/test/storybook-id-args.ts
index 36737b72f6d..959300f61d9 100644
--- a/frontend/src/embedding-sdk-bundle/test/storybook-id-args.ts
+++ b/frontend/src/embedding-sdk-bundle/test/storybook-id-args.ts
@@ -1,9 +1,11 @@
-const QUESTION_ENTITY_ID = "_GiVL6zYmsnBb1oqLCp4u";
+import type { InputType } from "storybook/internal/types";
+
+const QUESTION_ENTITY_ID = "VFCGVYPVtLzCtt4teeoW4";
const DASHBOARD_ENTITY_ID = "xBLdW9FsgRuB2HGhWiBa_";
const COLLECTION_ENTITY_ID = "HyB3nRtqb7pBPhFG26evI";
export const questionIds = generateIds(QUESTION_ENTITY_ID);
-export const questionIdArgType = {
+export const questionIdArgType: InputType = {
options: [
questionIds.entityId,
questionIds.oneToManyEntityId,
@@ -74,7 +76,7 @@ function generateIds(entityId: string) {
wrongEntityId:
entityId.slice(0, -1) +
String.fromCharCode((entityId.at(-1)?.charCodeAt(0) || ZERO_CODE) + 1),
- numberId: 1,
+ numberId: 12,
wrongNumberId: 99999999,
};
}
diff --git a/frontend/src/metabase-types/analytics/embedded-analytics-js.ts b/frontend/src/metabase-types/analytics/embedded-analytics-js.ts
index d4027743b85..7403b1fb6f2 100644
--- a/frontend/src/metabase-types/analytics/embedded-analytics-js.ts
+++ b/frontend/src/metabase-types/analytics/embedded-analytics-js.ts
@@ -14,6 +14,7 @@ export type EmbeddedAnalyticsJsEventSchema = {
with_downloads: BOOLEAN_COUNT;
with_title: BOOLEAN_COUNT;
is_save_enabled: BOOLEAN_COUNT;
+ with_alerts: BOOLEAN_COUNT;
};
exploration?: {
is_save_enabled: BOOLEAN_COUNT;
@@ -78,6 +79,7 @@ type EmbeddedAnalyticsJsSetupEvent = ValidateEvent<{
with_downloads: BOOLEAN_COUNT;
with_title: BOOLEAN_COUNT;
is_save_enabled: BOOLEAN_COUNT;
+ with_alerts: BOOLEAN_COUNT;
};
exploration?: {
is_save_enabled: BOOLEAN_COUNT;
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
index ed8d9c63968..fabaa4c0fa0 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
@@ -2,7 +2,7 @@ import cx from "classnames";
import { useMemo } from "react";
import { t } from "ttag";
-import { PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK } from "embedding-sdk-bundle/components/public/subscriptions";
+import { PLUGIN_NOTIFICATIONS_SDK } from "embedding-sdk-bundle/components/public/notifications";
import { DashboardArchivedEntityBanner } from "metabase/archive/components/ArchivedEntityBanner/DashboardArchivedEntityBanner";
import DashboardS from "metabase/css/dashboard.module.css";
import { DashboardHeader } from "metabase/dashboard/components/DashboardHeader";
@@ -142,7 +142,7 @@ type DashboardComponentType = typeof DashboardDefaultView & {
ParametersList: typeof ParametersList;
FullscreenButton: typeof FullscreenToggle;
ExportAsPdfButton: typeof ExportAsPdfButton;
- SubscriptionsButton: typeof PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK.DashboardSubscriptionsButton;
+ SubscriptionsButton: typeof PLUGIN_NOTIFICATIONS_SDK.DashboardSubscriptionsButton;
InfoButton: typeof DashboardInfoButton;
RefreshPeriod: typeof RefreshWidget;
};
@@ -156,7 +156,7 @@ DashboardComponent.ParametersList = ParametersList;
DashboardComponent.FullscreenButton = FullscreenToggle;
DashboardComponent.ExportAsPdfButton = ExportAsPdfButton;
DashboardComponent.SubscriptionsButton =
- PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK.DashboardSubscriptionsButton;
+ PLUGIN_NOTIFICATIONS_SDK.DashboardSubscriptionsButton;
DashboardComponent.InfoButton = DashboardInfoButton;
DashboardComponent.RefreshPeriod = RefreshWidget;
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx
index 8bd740f6e7c..68eb638b5d2 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardSubscriptionsButton.tsx
@@ -1,16 +1,5 @@
-import { PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK } from "embedding-sdk-bundle/components/public/subscriptions";
-import { isEmbeddingEajs, isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";
+import { PLUGIN_NOTIFICATIONS_SDK } from "embedding-sdk-bundle/components/public/notifications";
export function DashboardSubscriptionsButton() {
- if (isEmbeddingEajs()) {
- return <PLUGIN_EMBEDDING_IFRAME_SDK.DashboardSubscriptionsButton />;
- }
-
- // This flag isn't exclusive it could mean we're on either modular embedding or modular embedding SDK
- if (isEmbeddingSdk()) {
- return <PLUGIN_DASHBOARD_SUBSCRIPTIONS_SDK.DashboardSubscriptionsButton />;
- }
-
- return null;
+ return <PLUGIN_NOTIFICATIONS_SDK.DashboardSubscriptionsButton />;
}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts
index a6a123adb3e..6b1862a2ab4 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/analytics.ts
@@ -37,6 +37,7 @@ const EMBED_SETTINGS_TO_TRACK: SdkIframeEmbedSettingKey[] = [
"withTitle",
"withDownloads",
"withSubscriptions",
+ "withAlerts",
"isSaveEnabled",
"readOnly",
"layout",
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
index 3d7a470c853..735f38d7c70 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/SelectEmbedOptionsStep.tsx
@@ -55,7 +55,9 @@ const BehaviorSection = () => {
disabled={settings.isGuest}
checked={settings.isSaveEnabled}
onChange={(e) =>
- updateSettings({ isSaveEnabled: e.target.checked })
+ updateSettings({
+ isSaveEnabled: e.target.checked,
+ } satisfies Partial<typeof settings>)
}
/>
),
@@ -70,7 +72,11 @@ const BehaviorSection = () => {
label={t`Allow people to drill through on data points`}
disabled={disabled}
checked={settings.drills}
- onChange={(e) => updateSettings({ drills: e.target.checked })}
+ onChange={(e) =>
+ updateSettings({
+ drills: e.target.checked,
+ } satisfies Partial<typeof settings>)
+ }
/>
)}
</WithNotAvailableForOssOrGuestEmbedsGuard>
@@ -80,7 +86,9 @@ const BehaviorSection = () => {
disabled={!isSimpleEmbedFeatureAvailable}
checked={settings.withDownloads}
onChange={(e) =>
- updateSettings({ withDownloads: e.target.checked })
+ updateSettings({
+ withDownloads: e.target.checked,
+ } satisfies Partial<typeof settings>)
}
/>
@@ -91,11 +99,57 @@ const BehaviorSection = () => {
disabled={disabled}
checked={settings.isSaveEnabled}
onChange={(e) =>
- updateSettings({ isSaveEnabled: e.target.checked })
+ updateSettings({
+ isSaveEnabled: e.target.checked,
+ } satisfies Partial<typeof settings>)
}
/>
)}
</WithNotAvailableForOssOrGuestEmbedsGuard>
+
+ <WithNotAvailableForOssOrGuestEmbedsGuard>
+ {({ disabled: disabledInGuestEmbedding }) => {
+ return (
+ <Flex align="center" gap="xs">
+ <Checkbox
+ disabled={!hasEmailSetup || disabledInGuestEmbedding}
+ label={t`Allow alerts`}
+ checked={settings.withAlerts}
+ onChange={(e) =>
+ updateSettings({
+ withAlerts: e.target.checked,
+ } satisfies Partial<typeof settings>)
+ }
+ />
+ {!hasEmailSetup && !disabledInGuestEmbedding && (
+ <HoverCard>
+ <HoverCard.Target>
+ <Icon name="info" size={14} c="text-secondary" />
+ </HoverCard.Target>
+ <HoverCard.Dropdown p="sm">
+ <Text>{c(
+ "{0} is a link to email settings page with text 'admin settings'",
+ ).jt`To allow alerts, set up email in ${(
+ <Link
+ key="admin-settings-link"
+ to="/admin/settings/email"
+ >
+ <Text
+ display="inline"
+ c="text-brand"
+ fw="bold"
+ >{c(
+ "is a link in a sentence 'To allow alerts, set up email in admin settings'",
+ ).t`admin settings`}</Text>
+ </Link>
+ )}`}</Text>
+ </HoverCard.Dropdown>
+ </HoverCard>
+ )}
+ </Flex>
+ );
+ }}
+ </WithNotAvailableForOssOrGuestEmbedsGuard>
</Stack>
),
)
@@ -109,7 +163,11 @@ const BehaviorSection = () => {
label={t`Allow people to drill through on data points`}
disabled={disabled}
checked={settings.drills}
- onChange={(e) => updateSettings({ drills: e.target.checked })}
+ onChange={(e) =>
+ updateSettings({
+ drills: e.target.checked,
+ } satisfies Partial<typeof settings>)
+ }
/>
)}
</WithNotAvailableForOssOrGuestEmbedsGuard>
@@ -119,7 +177,9 @@ const BehaviorSection = () => {
disabled={!isSimpleEmbedFeatureAvailable}
checked={settings.withDownloads}
onChange={(e) =>
- updateSettings({ withDownloads: e.target.checked })
+ updateSettings({
+ withDownloads: e.target.checked,
+ } satisfies Partial<typeof settings>)
}
/>
@@ -132,7 +192,9 @@ const BehaviorSection = () => {
label={t`Allow subscriptions`}
checked={settings.withSubscriptions}
onChange={(e) =>
- updateSettings({ withSubscriptions: e.target.checked })
+ updateSettings({
+ withSubscriptions: e.target.checked,
+ } satisfies Partial<typeof settings>)
}
/>
{!hasEmailSetup && !disabledInGuestEmbedding && (
@@ -174,7 +236,11 @@ const BehaviorSection = () => {
label={t`Allow editing dashboards and questions`}
disabled={settings.isGuest}
checked={!settings.readOnly}
- onChange={(e) => updateSettings({ readOnly: !e.target.checked })}
+ onChange={(e) =>
+ updateSettings({
+ readOnly: !e.target.checked,
+ } satisfies Partial<typeof settings>)
+ }
/>
),
)
@@ -228,7 +294,7 @@ const AppearanceSection = () => {
const updateThemePreset = useCallback(
(preset: MetabaseThemePreset) => {
- updateSettings({ theme: { preset } });
+ updateSettings({ theme: { preset } } satisfies Partial<typeof settings>);
},
[updateSettings],
);
@@ -237,7 +303,7 @@ const AppearanceSection = () => {
(nextColors: Partial<MetabaseColors>) => {
updateSettings({
theme: { ...theme, colors: { ...theme?.colors, ...nextColors } },
- });
+ } satisfies Partial<typeof settings>);
},
[theme, updateSettings],
);
@@ -257,7 +323,11 @@ const AppearanceSection = () => {
<Checkbox
label={label}
checked={settings.withTitle}
- onChange={(e) => updateSettings({ withTitle: e.target.checked })}
+ onChange={(e) =>
+ updateSettings({
+ withTitle: e.target.checked,
+ } satisfies Partial<typeof settings>)
+ }
/>
);
},
@@ -270,7 +340,11 @@ const AppearanceSection = () => {
<ColorCustomizationSection
theme={theme}
onColorChange={updateColors}
- onColorReset={() => updateSettings({ theme: undefined })}
+ onColorReset={() =>
+ updateSettings({ theme: undefined } satisfies Partial<
+ typeof settings
+ >)
+ }
/>
) : (
<SimpleThemeSwitcherSection
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts
index 626c1bbe8bc..2fe22d56693 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/utils/get-default-sdk-iframe-embed-setting.ts
@@ -61,6 +61,7 @@ export const getDefaultSdkIframeEmbedSettings = ({
questionId: resourceId,
drills: true,
withDownloads: false,
+ withAlerts: false,
withTitle: true,
isSaveEnabled: false,
initialSqlParameters: {},
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
index 2bf71f658f2..3bb4fc67ea4 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.ts
@@ -35,6 +35,8 @@ const DEFAULT_VALUES: DefaultValues = {
with_title: true,
/** @see {@link https://github.com/metabase/metabase/blob/9e62f8c2b7d3739670d9f4259e1d4e28f5b654cc/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx#L256} */
is_save_enabled: false,
+ /** @see {@link https://github.com/metabase/metabase/blob/c1b57eeb3f6f99126cc52e3a960b98f5c8bbc109/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx#L137} */
+ with_alerts: false,
},
exploration: {
/** @see {@link https://github.com/metabase/metabase/blob/9e62f8c2b7d3739670d9f4259e1d4e28f5b654cc/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx#L256} */
@@ -157,6 +159,7 @@ export function createEmbeddedAnalyticsJsUsage(
with_downloads: { true: 0, false: 0 },
with_title: { true: 0, false: 0 },
is_save_enabled: { true: 0, false: 0 },
+ with_alerts: { true: 0, false: 0 },
} satisfies EmbeddedAnalyticsJsEvent["question"]);
}
usage = incrementComponentPropertyCount(
@@ -182,6 +185,11 @@ export function createEmbeddedAnalyticsJsUsage(
properties.isSaveEnabled,
usage,
);
+ usage = incrementComponentPropertyCount(
+ "question.with_alerts",
+ properties.withAlerts,
+ usage,
+ );
},
)
.with({ componentName: "metabase-browser" }, (properties) => {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.unit.spec.tsx
index 1e71c7e150d..0367bccfd58 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.unit.spec.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/analytics.unit.spec.tsx
@@ -203,6 +203,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
with_downloads: { true: 0, false: 1 },
with_title: { true: 1, false: 0 },
is_save_enabled: { true: 0, false: 1 },
+ with_alerts: { true: 0, false: 1 },
},
}),
);
@@ -219,6 +220,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
"with-downloads": false,
"with-title": true,
"is-save-enabled": false,
+ "with-alerts": false,
}),
]),
),
@@ -229,6 +231,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
with_downloads: { true: 0, false: 1 },
with_title: { true: 1, false: 0 },
is_save_enabled: { true: 0, false: 1 },
+ with_alerts: { true: 0, false: 1 },
},
}),
);
@@ -243,6 +246,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
"with-downloads": true,
"with-title": false,
"is-save-enabled": true,
+ "with-alerts": true,
}),
]),
),
@@ -253,6 +257,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
with_downloads: { true: 1, false: 0 },
with_title: { true: 0, false: 1 },
is_save_enabled: { true: 1, false: 0 },
+ with_alerts: { true: 1, false: 0 },
},
}),
);
@@ -268,6 +273,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
"with-downloads": true,
"with-title": false,
"is-save-enabled": true,
+ "with-alerts": true,
}),
]),
),
@@ -278,6 +284,7 @@ describe("createEmbeddedAnalyticsJsUsage", () => {
with_downloads: { true: 1, false: 2 },
with_title: { true: 2, false: 1 },
is_save_enabled: { true: 1, false: 2 },
+ with_alerts: { true: 1, false: 2 },
},
}),
);
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
index ecd75073280..c2278e0d205 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
@@ -232,6 +232,7 @@ const SdkIframeEmbedView = ({
key={rerenderKey}
{...entityProps}
withDownloads={settings.withDownloads}
+ withAlerts={settings.withAlerts}
height="100%"
initialSqlParameters={settings.initialSqlParameters}
hiddenParameters={settings.hiddenParameters}
@@ -253,6 +254,7 @@ const SdkIframeEmbedView = ({
questionId={settings.questionId ?? null}
token={settings.token}
withDownloads={settings.withDownloads}
+ withAlerts={settings.withAlerts}
height="100%"
initialSqlParameters={settings.initialSqlParameters}
hiddenParameters={settings.hiddenParameters}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
index d2196226b74..da28df138c6 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
@@ -42,6 +42,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {
"isSaveEnabled",
"withTitle",
"withDownloads",
+ "withAlerts",
"initialSqlParameters",
"hiddenParameters",
"drills",
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
index ffaa43dd77f..88beff4ef55 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts
@@ -510,6 +510,7 @@ const MetabaseQuestionElement = createCustomElement("metabase-question", [
"token",
"with-title",
"with-downloads",
+ "with-alerts",
"drills",
"initial-sql-parameters",
"hidden-parameters",
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index 3dc50244992..133f3e939a3 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -95,6 +95,7 @@ export type QuestionEmbedOptions = StrictUnion<
drills?: boolean;
withTitle?: boolean;
withDownloads?: boolean;
+ withAlerts?: boolean;
targetCollection?: CollectionId;
entityTypes?: EntityTypeFilterKeys[];
isSaveEnabled?: boolean;
diff --git a/frontend/src/metabase/lib/analytics.ts b/frontend/src/metabase/lib/analytics.ts
index a80b541ec2e..402c7a24706 100644
--- a/frontend/src/metabase/lib/analytics.ts
+++ b/frontend/src/metabase/lib/analytics.ts
@@ -23,7 +23,7 @@ const VERSIONS: Record<SchemaType, SchemaVersion> = {
downloads: "1-0-0",
embed_flow: "1-0-3",
embed_share: "1-0-1",
- embedded_analytics_js: "2-0-0",
+ embedded_analytics_js: "2-0-1",
embedding_homepage: "1-0-0",
simple_event: "1-0-0",
invite: "1-0-1",
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index fdf9877ebf8..a6df564542c 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -11,6 +11,7 @@ import {
} from "metabase/api";
import { ActionButton } from "metabase/common/components/ActionButton";
import CS from "metabase/css/core/index.css";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { getResponseErrorMessage } from "metabase/lib/errors";
import {
alertIsValid,
@@ -40,6 +41,7 @@ import {
Text,
rem,
} from "metabase/ui";
+import type Question from "metabase-lib/v1/Question";
import type {
CreateAlertNotificationRequest,
Notification,
@@ -91,7 +93,7 @@ const ALERT_SCHEDULE_OPTIONS: ScheduleType[] = [
"cron",
];
-type CreateOrEditQuestionAlertModalProps = {
+type CreateOrEditQuestionAlertModalWithQuestionProps = {
onClose: () => void;
} & (
| {
@@ -106,14 +108,47 @@ type CreateOrEditQuestionAlertModalProps = {
}
);
+type CreateOrEditQuestionAlertModalProps =
+ CreateOrEditQuestionAlertModalWithQuestionProps & {
+ question?: Question;
+ };
+
+export const CreateOrEditQuestionAlertModalWithQuestion = ({
+ editingNotification,
+ onAlertCreated,
+ onAlertUpdated,
+ onClose,
+}: CreateOrEditQuestionAlertModalWithQuestionProps) => {
+ const question = useSelector(getQuestion);
+
+ if (editingNotification) {
+ return (
+ <CreateOrEditQuestionAlertModal
+ question={question}
+ editingNotification={editingNotification}
+ onAlertUpdated={onAlertUpdated}
+ onClose={onClose}
+ />
+ );
+ } else {
+ return (
+ <CreateOrEditQuestionAlertModal
+ question={question}
+ onAlertCreated={onAlertCreated}
+ onClose={onClose}
+ />
+ );
+ }
+};
+
export const CreateOrEditQuestionAlertModal = ({
editingNotification,
onAlertCreated,
onAlertUpdated,
onClose,
+ question,
}: CreateOrEditQuestionAlertModalProps) => {
const dispatch = useDispatch();
- const question = useSelector(getQuestion);
const visualizationSettings = useSelector(getVisualizationSettings);
const user = useSelector(getUser);
const userCanAccessSettings = useSelector(canAccessSettings);
@@ -336,26 +371,29 @@ export const CreateOrEditQuestionAlertModal = ({
onScheduleChange={handleScheduleChange}
/>
</AlertModalSettingsBlock>
- <AlertModalSettingsBlock
- title={t`Where do you want to send the results?`}
- >
- <NotificationChannelsPicker
- notificationHandlers={notification.handlers}
- channels={channelSpec ? channelSpec.channels : undefined}
- onChange={(newHandlers: NotificationHandler[]) => {
- setNotification({
- ...notification,
- handlers: newHandlers,
- });
- }}
- emailRecipientText={t`Email alerts to:`}
- getInvalidRecipientText={(domains) =>
- userCanAccessSettings
- ? t`You're only allowed to email alerts to addresses ending in ${domains}`
- : t`You're only allowed to email alerts to allowed domains`
- }
- />
- </AlertModalSettingsBlock>
+ {!isEmbeddingSdk() && (
+ <AlertModalSettingsBlock
+ title={t`Where do you want to send the results?`}
+ >
+ <NotificationChannelsPicker
+ notificationHandlers={notification.handlers}
+ channels={channelSpec ? channelSpec.channels : undefined}
+ onChange={(newHandlers: NotificationHandler[]) => {
+ setNotification({
+ ...notification,
+ handlers: newHandlers,
+ });
+ }}
+ emailRecipientText={t`Email alerts to:`}
+ getInvalidRecipientText={(domains) =>
+ userCanAccessSettings
+ ? t`You're only allowed to email alerts to addresses ending in ${domains}`
+ : t`You're only allowed to email alerts to allowed domains`
+ }
+ />
+ </AlertModalSettingsBlock>
+ )}
+
<AlertModalSettingsBlock title={t`More options`}>
<Switch
label={t`Delete this Alert after it's triggered`}
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
index 03c2236c18b..578d4ae29b3 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -10,7 +10,7 @@ import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
-import { CreateOrEditQuestionAlertModal } from "metabase/notifications/modals";
+import { CreateOrEditQuestionAlertModalWithQuestion } from "metabase/notifications/modals";
import type {
ChannelApiResponse,
Notification,
@@ -30,7 +30,7 @@ import {
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
import { createMockQueryBuilderState } from "metabase-types/store/mocks";
-describe("CreateOrEditQuestionAlertModal", () => {
+describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
it("should display first available channel by default - Email", async () => {
setup({
isAdmin: true,
@@ -454,7 +454,7 @@ function setup({
if (editingNotification) {
renderWithProviders(
- <CreateOrEditQuestionAlertModal
+ <CreateOrEditQuestionAlertModalWithQuestion
editingNotification={editingNotification}
onAlertUpdated={onAlertUpdatedMock}
onClose={jest.fn()}
@@ -465,7 +465,7 @@ function setup({
}
renderWithProviders(
- <CreateOrEditQuestionAlertModal
+ <CreateOrEditQuestionAlertModalWithQuestion
onAlertCreated={onAlertCreatedMock}
onClose={jest.fn()}
/>,
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts
index 93062e53783..4953a5ea318 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts
@@ -1 +1,4 @@
-export { CreateOrEditQuestionAlertModal } from "./CreateOrEditQuestionAlertModal";
+export {
+ CreateOrEditQuestionAlertModal,
+ CreateOrEditQuestionAlertModalWithQuestion,
+} from "./CreateOrEditQuestionAlertModal";
diff --git a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx
index 54af3cf4738..0ee52d300f5 100644
--- a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx
+++ b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { usePreviousDistinct } from "react-use";
import { t } from "ttag";
@@ -43,12 +43,24 @@ export const QuestionAlertListModal = ({
const [updateNotification] = useUpdateNotificationMutation();
const [unsubscribe] = useUnsubscribeFromNotificationMutation();
- const [activeModal, setActiveModal] = useState<AlertModalMode>(
- !questionNotifications || questionNotifications.length === 0
- ? "create-modal"
- : "list-modal",
+ const [activeModal, setActiveModal] = useState<AlertModalMode | null>(
+ questionNotifications ? getDefaultActiveModal(questionNotifications) : null,
);
+ useEffect(() => {
+ /**
+ * Attempt to set the active modal only once when it's null.
+ *
+ * In the core app, this is a noop because the data is already
+ * loaded and activeModal will not be null. However, in the SDK,
+ * we'll need to wait for the data to load, so the activeModal
+ * will be null at first.
+ */
+ if (questionNotifications && activeModal === null) {
+ setActiveModal(getDefaultActiveModal(questionNotifications));
+ }
+ }, [activeModal, questionNotifications]);
+
const previousActiveModal = usePreviousDistinct(activeModal);
const handleInternalModalClose = () => {
@@ -135,6 +147,7 @@ export const QuestionAlertListModal = ({
{(activeModal === "create-modal" || activeModal === "update-modal") && (
<CreateOrEditQuestionAlertModal
+ question={question}
editingNotification={
activeModal === "update-modal" && editingItem
? editingItem
@@ -162,3 +175,9 @@ export const QuestionAlertListModal = ({
</>
);
};
+
+function getDefaultActiveModal(
+ questionNotifications: Notification[],
+): AlertModalMode {
+ return questionNotifications.length === 0 ? "create-modal" : "list-modal";
+}
diff --git a/frontend/src/metabase/notifications/modals/index.ts b/frontend/src/metabase/notifications/modals/index.ts
index 8de81c6ddea..8f8489affd2 100644
--- a/frontend/src/metabase/notifications/modals/index.ts
+++ b/frontend/src/metabase/notifications/modals/index.ts
@@ -1,2 +1,5 @@
-export { CreateOrEditQuestionAlertModal } from "./CreateOrEditQuestionAlertModal";
+export {
+ CreateOrEditQuestionAlertModal,
+ CreateOrEditQuestionAlertModalWithQuestion,
+} from "./CreateOrEditQuestionAlertModal";
export { QuestionAlertListModal } from "./QuestionAlertListModal";
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index cdb3f5a3b26..8762587a6e9 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -150,7 +150,7 @@ export type {
} from "./types";
// Export a single reinitialize function that calls all individual reinitialize functions
-import { reinitialize as reinitializeDashboardSubscriptionsSdk } from "../../embedding-sdk-bundle/components/public/subscriptions";
+import { reinitialize as reinitializeNotificationsSdk } from "../../embedding-sdk-bundle/components/public/notifications";
import { reinitialize as reinitializeAi } from "./oss/ai";
import { reinitialize as reinitializeApi } from "./oss/api";
@@ -190,7 +190,7 @@ import { reinitialize as reinitializeWhitelabel } from "./oss/whitelabel";
* so reinitializing them all ensures that dependencies are correctly set up.
*/
export function reinitialize() {
- reinitializeDashboardSubscriptionsSdk();
+ reinitializeNotificationsSdk();
reinitializeAi();
reinitializeApi();
diff --git a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
index f55a39e9e3d..a9c1c4ef016 100644
--- a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
+++ b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
@@ -1,10 +1,5 @@
-import type { DashboardSubscriptionsButtonProps } from "embedding-sdk-bundle/components/public/subscriptions";
-
const getDefaultPluginEmbeddingIframeSdk = () => ({
isEnabled: () => false,
- DashboardSubscriptionsButton: (
- _props: DashboardSubscriptionsButtonProps,
- ): JSX.Element | null => null,
});
export const PLUGIN_EMBEDDING_IFRAME_SDK = getDefaultPluginEmbeddingIframeSdk();
diff --git a/frontend/src/metabase/query_builder/components/VisualizationResult.jsx b/frontend/src/metabase/query_builder/components/VisualizationResult.jsx
index 37732846fcd..8c0032c4d35 100644
--- a/frontend/src/metabase/query_builder/components/VisualizationResult.jsx
+++ b/frontend/src/metabase/query_builder/components/VisualizationResult.jsx
@@ -8,7 +8,7 @@ import { ErrorMessage } from "metabase/common/components/ErrorMessage";
import ButtonsS from "metabase/css/components/buttons.module.css";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { CreateOrEditQuestionAlertModal } from "metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal";
+import { CreateOrEditQuestionAlertModalWithQuestion } from "metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal";
import Visualization from "metabase/visualizations/components/Visualization";
import * as Lib from "metabase-lib";
import { ALERT_TYPE_ROWS } from "metabase-lib/v1/Alert";
@@ -113,7 +113,7 @@ export class VisualizationResult extends Component {
}
/>
{showCreateAlertModal && (
- <CreateOrEditQuestionAlertModal
+ <CreateOrEditQuestionAlertModalWithQuestion
onClose={this.onCloseCreateAlertModal}
onAlertCreated={this.onCloseCreateAlertModal}
/>
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/QuestionMoreActionsMenu.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/QuestionMoreActionsMenu.tsx
index 93226df8b87..bc8662f685d 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/QuestionMoreActionsMenu.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionActions/QuestionMoreActionsMenu/QuestionMoreActionsMenu.tsx
@@ -22,10 +22,7 @@ import {
type QueryModalType,
} from "metabase/query_builder/constants";
import { getQuestionWithoutComposing } from "metabase/query_builder/selectors";
-import {
- canManageSubscriptions as canManageSubscriptionsSelector,
- getUserIsAdmin,
-} from "metabase/selectors/user";
+import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/selectors/user";
import { Icon, Menu } from "metabase/ui";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -62,7 +59,6 @@ export const QuestionMoreActionsMenu = ({
const underlyingQuestion = useSelector(getQuestionWithoutComposing);
const dispatch = useDispatch();
- const isAdmin = useSelector(getUserIsAdmin);
const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);
const isQuestion = question.type() === "question";
@@ -128,7 +124,7 @@ export const QuestionMoreActionsMenu = ({
{t`Add to dashboard`}
</Menu.Item>
),
- (isAdmin || canManageSubscriptions) && !isModel && !isAnalytics && (
+ canManageSubscriptions && !isModel && !isAnalytics && (
<QuestionAlertsMenuItem
key="alerts"
question={question}
diff --git a/frontend/test/__support__/enterprise-typed.ts b/frontend/test/__support__/enterprise-typed.ts
index 2a9e4c2c1f3..50293f7ace6 100644
--- a/frontend/test/__support__/enterprise-typed.ts
+++ b/frontend/test/__support__/enterprise-typed.ts
@@ -54,7 +54,7 @@ export const ENTERPRISE_PLUGIN_NAME_MAPPING = {
tenants: "metabase-enterprise/tenants",
// Embedding SDK specific plugins
- sdk_subscriptions: "embedding-sdk-ee/subscriptions",
+ sdk_notifications: "embedding-sdk-ee/notifications",
};
export type ENTERPRISE_PLUGIN_NAME =
diff --git a/frontend/test/__support__/server-mocks/notification.ts b/frontend/test/__support__/server-mocks/notification.ts
index f392bd4175a..97115d7e27f 100644
--- a/frontend/test/__support__/server-mocks/notification.ts
+++ b/frontend/test/__support__/server-mocks/notification.ts
@@ -4,6 +4,7 @@ import type {
ListNotificationsRequest,
Notification,
} from "metabase-types/api";
+import { createMockNotification } from "metabase-types/api/mocks";
export const setupListNotificationEndpoints = (
{ card_id }: Partial<ListNotificationsRequest>,
@@ -16,3 +17,9 @@ export const setupListNotificationEndpoints = (
},
});
};
+
+export const setupCreateNotificationEndpoint = () => {
+ fetchMock.post("path:/api/notification", ({ options }) => {
+ return createMockNotification(JSON.parse(options.body as string));
+ });
+};
diff --git a/resources/migrations/059_update_migrations.yaml b/resources/migrations/059_update_migrations.yaml
index 8b7264ca788..003dcd30ba1 100644
--- a/resources/migrations/059_update_migrations.yaml
+++ b/resources/migrations/059_update_migrations.yaml
@@ -979,6 +979,26 @@ databaseChangeLog:
tableName: analysis_finding
indexName: idx_analysis_finding_stale
+ - changeSet:
+ id: v59.2026-01-28T10:00:02
+ author: winlost
+ comment: Add disable_links column to notification_card table
+ changes:
+ - addColumn:
+ tableName: notification_card
+ columns:
+ - column:
+ name: disable_links
+ type: ${boolean.type}
+ remarks: "Whether to disable alert email links"
+ defaultValueBoolean: false
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: notification_card
+ columnName: disable_links
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/2-0-1 b/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/2-0-1
new file mode 100644
index 00000000000..14bce9e1b7e
--- /dev/null
+++ b/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/2-0-1
@@ -0,0 +1,357 @@
+{
+ "$schema": "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",
+ "description": "Modular embedding configuration",
+ "self": {
+ "vendor": "com.metabase",
+ "name": "embedded_analytics_js",
+ "format": "jsonschema",
+ "version": "2-0-1"
+ },
+ "type": "object",
+ "properties": {
+ "event": {
+ "description": "The type of event being recorded. For example, when the modular embedding is initialized, or when the Metabase configuration is updated.",
+ "type": "string",
+ "enum": [
+ "setup"
+ ],
+ "maxLength": 1024
+ },
+ "global": {
+ "description": "Global configuration for modular embedding.",
+ "type": "object",
+ "properties": {
+ "auth_method": {
+ "description": "Authentication method used for the modular embedding.",
+ "type": [
+ "string",
+ "null"
+ ],
+ "enum": [
+ "session",
+ "api_key",
+ "sso",
+ "guest"
+ ],
+ "maxLength": 1024
+ }
+ }
+ },
+ "dashboard": {
+ "description": "Aggregated configuration counts for <metabase-dashboard>",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "drills": {
+ "description": "Counts of dashboards with drills enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of dashboards with drills enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of dashboards with drills disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_downloads": {
+ "description": "Counts of dashboards with downloads enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of dashboards with downloads enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of dashboards with downloads disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_title": {
+ "description": "Counts of dashboards with title visible or hidden.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of dashboards with title visible.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of dashboards with title hidden.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_subscriptions": {
+ "description": "Counts of dashboards with subscriptions enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of dashboards with subscriptions enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of dashboards with subscriptions disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ }
+ }
+ },
+ "question": {
+ "description": "Aggregated configuration counts for <metabase-question>",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "drills": {
+ "description": "Counts of questions with drills enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of questions with drills enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of questions with drills disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_downloads": {
+ "description": "Counts of questions with downloads enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of questions with downloads enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of questions with downloads disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_title": {
+ "description": "Counts of questions with title visible or hidden.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of questions with title visible.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of questions with title hidden.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "is_save_enabled": {
+ "description": "Counts of questions with save enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of questions with save enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of questions with save disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ },
+ "with_alerts": {
+ "description": "Counts of questions with alerts enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of questions with alerts enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of questions with alerts disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ }
+ }
+ },
+ "exploration": {
+ "description": "Aggregated configuration counts for <metabase-question> with question-id=\"new\"",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "is_save_enabled": {
+ "description": "Counts of explorations with save enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of explorations with save enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of explorations with save disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ }
+ }
+ },
+ "browser": {
+ "description": "Aggregated configuration counts for <metabase-browser>",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "read_only": {
+ "description": "Counts of browsers with read-only mode enabled or disabled.",
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "true": {
+ "description": "Number of browsers with read-only mode enabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "false": {
+ "description": "Number of browsers with read-only mode disabled.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 2147483647
+ }
+ },
+ "required": [
+ "true",
+ "false"
+ ]
+ }
+ }
+ }
+ },
+ "required": [
+ "event",
+ "global"
+ ],
+ "additionalProperties": true
+}
diff --git a/src/metabase/channel/email/dashboard_subscription.hbs b/src/metabase/channel/email/dashboard_subscription.hbs
index d22f9267a9c..60309e3fcec 100644
--- a/src/metabase/channel/email/dashboard_subscription.hbs
+++ b/src/metabase/channel/email/dashboard_subscription.hbs
@@ -5,7 +5,7 @@
<td>
<div class="container" style="background-color: white; max-width: 555px; border-radius: 24px; margin: 0 auto; padding: 30px;">
{{#if context.include_branding}}
- <a {{#unless payload.disable_links}}href="https://www.metabase.com?utm_source=product&utm_medium=export&utm_campaign=exports_branding&utm_content=dashboard_subscription"{{/unless}}>
+ <a {{#unless payload.dashboard_subscription.disable_links}}href="https://www.metabase.com?utm_source=product&utm_medium=export&utm_campaign=exports_branding&utm_content=dashboard_subscription"{{/unless}}>
<div style="text-align: right; height: 28px; margin-bottom: 16px; color: {{payload.style.color_text_dark}};">
<span style="font-size: 12px; vertical-align: middle;">Made with</span>
<img width="22.4" height="28" src="{{context.application_logo_url}}" style="vertical-align: middle; margin-inline: 4px;"/>
@@ -19,7 +19,7 @@
<img class="icon" style="padding-top: 4px; padding-right: 16px; width: 100%; height: auto; max-width: 20px" src="cid:{{computed.icon_cid}}"/>
</td>
<td>
- <a class="title" {{#unless payload.disable_links}}href="{{{dashboard-url payload.dashboard.id payload.parameters}}}"{{/unless}} style="font-size: 20px; font-weight: 700; padding-bottom: 4px;">
+ <a class="title" {{#unless payload.dashboard_subscription.disable_links}}href="{{{dashboard-url payload.dashboard.id payload.parameters}}}"{{/unless}} style="font-size: 20px; font-weight: 700; padding-bottom: 4px;">
{{payload.dashboard.name}}
</a>
</td>
@@ -55,7 +55,7 @@
<hr>
{{/unless}}
{{{computed.dashboard_content}}}
- {{#unless payload.disable_links}}
+ {{#unless payload.dashboard_subscription.disable_links}}
<hr>
<div class="footer" style="font-size: 11px; width: max-content; margin: 0 auto">
Sent from <a href="{{context.site_url}}" style="color: {{context.application_color}}">{{context.site_url}}</a>.
diff --git a/src/metabase/channel/email/notification_card.hbs b/src/metabase/channel/email/notification_card.hbs
index 48205967338..0bb7c512188 100644
--- a/src/metabase/channel/email/notification_card.hbs
+++ b/src/metabase/channel/email/notification_card.hbs
@@ -5,7 +5,7 @@
<td>
<div class="container" style="background-color: white; max-width: 555px; border-radius: 24px; margin: 0 auto; padding: 30px;">
{{#if context.include_branding}}
- <a href="https://www.metabase.com?utm_source=product&utm_medium=export&utm_campaign=exports_branding&utm_content=alert">
+ <a {{#unless payload.notification_card.disable_links}}href="https://www.metabase.com?utm_source=product&utm_medium=export&utm_campaign=exports_branding&utm_content=alert"{{/unless}}>
<div style="text-align: right; height: 28px; margin-bottom: 16px; color: {{payload.style.color_text_dark}};">
<span style="font-size: 12px; vertical-align: middle;">Made with</span>
<img width="22.4" height="28" src="{{context.application_logo_url}}" style="vertical-align: middle; margin-inline: 4px;"/>
@@ -19,7 +19,7 @@
<img class="icon" style="padding-top: 4px; padding-right: 16px; width: 100%; height: auto; max-width: 20px" src="cid:{{computed.icon_cid}}"/>
</td>
<td>
- <a class="title" href="{{{card-url payload.card.id}}}" style="font-size: 20px; font-weight: 700; padding-bottom: 4px;">
+ <a class="title" {{#unless payload.notification_card.disable_links}}href="{{{card-url payload.card.id}}}"{{/unless}} style="font-size: 20px; font-weight: 700; padding-bottom: 4px;">
{{payload.card.name}}
</a>
</td>
@@ -56,11 +56,13 @@
We’ll stop sending you alerts about this question now.
</p>
{{/if}}
- <hr>
- <div class="footer" style="font-size: 11px; width: max-content; margin: 0 auto">
- Sent from <a href="{{context.site_url}}" style="color: {{context.application_color}}">{{context.site_url}}</a>.
- <a href="{{{computed.management_url}}}" style="color: {{context.application_color}}">{{computed.management_text}}</a>
- </div>
+ {{#unless payload.notification_card.disable_links}}
+ <hr>
+ <div class="footer" style="font-size: 11px; width: max-content; margin: 0 auto">
+ Sent from <a href="{{context.site_url}}" style="color: {{context.application_color}}">{{context.site_url}}</a>.
+ <a href="{{{computed.management_url}}}" style="color: {{context.application_color}}">{{computed.management_text}}</a>
+ </div>
+ {{/unless}}
</div>
</td>
</tr>
diff --git a/src/metabase/channel/impl/email.clj b/src/metabase/channel/impl/email.clj
index 684ffe1e0c1..30e21121864 100644
--- a/src/metabase/channel/impl/email.clj
+++ b/src/metabase/channel/impl/email.clj
@@ -203,7 +203,8 @@
card]} payload
template (or template (payload-type->default-template payload_type))
timezone (channel.render/defaulted-timezone card)
- rendered-card (render-part timezone card_part {:channel.render/include-title? true})
+ rendered-card (render-part timezone card_part {:channel.render/include-title? true
+ :channel.render/disable-links? (boolean (:disable_links notification_card))})
icon-attachment (apply make-message-attachment (icon-bundle :bell))
card-attachments (map make-message-attachment (:attachments rendered-card))
result-attachments (email.result-attachment/result-attachment
diff --git a/src/metabase/embedding/util.clj b/src/metabase/embedding/util.clj
index f200c6f4cd1..a6bd4dd6a4c 100644
--- a/src/metabase/embedding/util.clj
+++ b/src/metabase/embedding/util.clj
@@ -20,8 +20,8 @@
(or (has-react-sdk-header? request)
(has-embedded-analytics-js-header? request)))
-(defn modular-embedding-or-modular-embedding-sdk-context?
+(defn is-modular-embedding-or-modular-embedding-sdk-request?
"Check if the client is in modular embedding context."
- [client]
- (or (= client embedding-sdk-client)
- (= client embedded-analytics-js-client)))
+ [request]
+ (contains? #{embedding-sdk-client embedded-analytics-js-client}
+ (get-in request [:headers "x-metabase-client"])))
diff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.clj
index 1d4a1abab52..c43a6609e22 100644
--- a/src/metabase/notification/api/notification.clj
+++ b/src/metabase/notification/api/notification.clj
@@ -8,6 +8,7 @@
[metabase.api.macros :as api.macros]
[metabase.channel.email.messages :as messages]
[metabase.channel.settings :as channel.settings]
+ [metabase.embedding.util :as embed.util]
[metabase.events.core :as events]
[metabase.models.interface :as mi]
[metabase.notification.core :as notification]
@@ -152,14 +153,16 @@
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/"
"Create a new notification, return the created notification."
- [_route _query body :- ::models.notification/FullyHydratedNotification]
+ [_route _query body :- ::models.notification/FullyHydratedNotification request]
(api/create-check :model/Notification body)
(let [notification (models.notification/hydrate-notification
(models.notification/create-notification!
(-> body
(update :payload_type keyword)
(assoc :creator_id api/*current-user-id*)
- (dissoc :handlers :subscriptions))
+ (dissoc :handlers :subscriptions)
+ (assoc-in [:payload :disable_links]
+ (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)))
(:subscriptions body)
(:handlers body)))]
(when (card-notification? notification)
@@ -245,11 +248,13 @@
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/send"
"Send an unsaved notification."
- [_route _query body :- ::models.notification/FullyHydratedNotification]
+ [_route _query body :- ::models.notification/FullyHydratedNotification request]
(api/create-check :model/Notification body)
(models.notification/validate-email-handlers! (:handlers body))
(let [notification (-> body
(assoc :creator_id api/*current-user-id*)
+ (assoc-in [:payload :disable_links]
+ (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request))
promote-to-t2-instance)]
(notification/send-notification! notification :notification/sync? true)))
diff --git a/src/metabase/notification/payload/impl/dashboard.clj b/src/metabase/notification/payload/impl/dashboard.clj
index 97286d57be9..7c1b05ec84a 100644
--- a/src/metabase/notification/payload/impl/dashboard.clj
+++ b/src/metabase/notification/payload/impl/dashboard.clj
@@ -42,8 +42,7 @@
:color_text_light channel.render/color-text-light
:color_text_medium channel.render/color-text-medium}
:parameters parameters
- :dashboard_subscription dashboard_subscription
- :disable_links (:disable_links dashboard_subscription)})))
+ :dashboard_subscription dashboard_subscription})))
(mu/defmethod notification.payload/skip-reason :notification/dashboard
[{:keys [payload] :as _noti-payload}]
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 7ce618dac45..0388df6d9ec 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -170,8 +170,7 @@
:collection_position collection-position
:dashboard_id dashboard-id
:parameters parameters
- :disable_links (embed.util/modular-embedding-or-modular-embedding-sdk-context?
- (get-in request [:headers "x-metabase-client"]))}]
+ :disable_links (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)}]
(api/create-check :model/Pulse (assoc pulse-data :cards cards))
(t2/with-transaction [_conn]
;; Adding a new pulse at `collection_position` could cause other pulses in this collection to change position,
@@ -460,8 +459,7 @@
(let [pulse (-> body
(assoc :creator_id api/*current-user-id*)
(assoc :disable_links
- (embed.util/modular-embedding-or-modular-embedding-sdk-context?
- (get-in request [:headers "x-metabase-client"]))))]
+ (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)))]
(notification/with-default-options {:notification/sync? true}
(pulse.send/send-pulse! pulse)))
{:ok true})
diff --git a/test/metabase/notification/api/notification_test.clj b/test/metabase/notification/api/notification_test.clj
index a1614a2bf44..6cd103d7ed5 100644
--- a/test/metabase/notification/api/notification_test.clj
+++ b/test/metabase/notification/api/notification_test.clj
@@ -435,7 +435,36 @@
:send_condition :has_result
:send_once false}
:subscriptions [{:type :notification-subscription/cron
- :cron_schedule "0 0 0 * * ?"}]}))))))))
+ :cron_schedule "0 0 0 * * ?"}]}))))))
+
+ (testing "links disabled/enabled based on x-metabase-client header"
+ (let [notification-body {:handlers [{:channel_type :channel/email
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}]
+ :payload_type :notification/card
+ :payload {:card_id card-id
+ :send_condition :has_result
+ :send_once false}
+ :subscriptions [{:type :notification-subscription/cron
+ :cron_schedule "0 0 0 * * ?"}]}
+ has-link? (fn [client-header]
+ (->> (notification.tu/with-captured-channel-send!
+ (if client-header
+ (mt/user-http-request :crowberto :post 204 "notification/send"
+ {:request-options {:headers
+ {"x-metabase-client" client-header}}}
+ notification-body)
+ (mt/user-http-request :crowberto :post 204 "notification/send"
+ notification-body)))
+ :channel/email first :message first :content
+ (re-find #"href=")
+ (= "href=")))]
+ (testing "x-metabase-client header is embedding-sdk-react (modular embedding SDK): result email has no links"
+ (is (false? (has-link? "embedding-sdk-react"))))
+ (testing "x-metabase-client header is embedding-simple (modular embedding): result email has no links"
+ (is (false? (has-link? "embedding-simple"))))
+ (testing "no x-metabase-client header: result email has links"
+ (is (true? (has-link? nil))))))))
(deftest get-notification-permissions-test
(mt/with-temp
diff --git a/test/metabase/notification/send_test.clj b/test/metabase/notification/send_test.clj
index fa6258fa07d..d74b388a0ac 100644
--- a/test/metabase/notification/send_test.clj
+++ b/test/metabase/notification/send_test.clj
@@ -79,6 +79,30 @@
:recipients [{:type :notification-recipient/user :user_id (mt/user->id :rasta)}]}]
@renders)))))))))
+(deftest notification-disable-links-test
+ (testing "Card notification with links disabled based on disable_links flag"
+ (notification.tu/with-notification-testing-setup!
+ (notification.tu/with-card-notification
+ [notification {:card {:name "Orders question"
+ :dataset_query (mt/mbql-query orders {:limit 1})}
+ :subscriptions [{:type :notification-subscription/cron
+ :cron_schedule "0 0 0 * * ? *"}]
+ :handlers [{:channel_type :channel/email
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}]}]
+ (let [has-link? (fn [notification]
+ (->> (notification.tu/with-captured-channel-send!
+ (#'notification.send/send-notification-sync! notification))
+ :channel/email first :message first :content
+ (re-find #"href=")
+ (= "href=")))]
+ (testing "test that disable_links: false will keep links in the alert email"
+ (is (true? (has-link? (assoc-in notification [:payload :disable_links] false)))))
+ (testing "test that disable_links: nil will keep links in the alert email"
+ (is (true? (has-link? (assoc-in notification [:payload :disable_links] nil)))))
+ (testing "test that disable_links: true will disable all links in the alert email"
+ (is (false? (has-link? (assoc-in notification [:payload :disable_links] true))))))))))
+
(defn- latest-task-history-entry
[task-name]
(t2/select-one-fn #(dissoc % :id :started_at :ended_at :duration)