Skip to content

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

Check for active subscriptions when removing parameters (#74591)

Nick Fitzpatrick2c58286958e2
diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
index 2c8abc21f80..e8ebadaee27 100644
--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js
@@ -7,6 +7,7 @@ import {
ORDERS_DASHBOARD_ID,
ORDERS_QUESTION_ID,
} from "e2e/support/cypress_sample_instance_data";
+import { createMockDashboardCard } from "metabase-types/api/mocks";
const { admin } = USERS;
const {
@@ -1053,3 +1054,141 @@ describe("issue 49525", { tags: "@external" }, () => {
});
});
});
+
+describe("issue 54603", () => {
+ const FILTER_PARAMETER = {
+ id: "54603-cat",
+ name: "Category",
+ slug: "category",
+ type: "category",
+ };
+
+ const PRODUCT_CATEGORY_FIELD_REF = [
+ "field",
+ PRODUCTS.CATEGORY,
+ { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },
+ ];
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+
+ H.createDashboard({
+ name: "Dashboard 54603",
+ parameters: [FILTER_PARAMETER],
+ }).then(({ body: dashboard }) => {
+ H.updateDashboardCards({
+ dashboard_id: dashboard.id,
+ cards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: ORDERS_QUESTION_ID,
+ parameter_mappings: [
+ {
+ parameter_id: FILTER_PARAMETER.id,
+ card_id: ORDERS_QUESTION_ID,
+ target: [
+ "dimension",
+ PRODUCT_CATEGORY_FIELD_REF,
+ { "stage-number": 0 },
+ ],
+ },
+ ],
+ }),
+ ],
+ });
+
+ // Subscription bound to the Category filter — removing it should warn.
+ cy.request("POST", "/api/pulse", {
+ name: "Weekly Category Roundup",
+ dashboard_id: dashboard.id,
+ cards: [
+ {
+ id: ORDERS_QUESTION_ID,
+ include_csv: false,
+ include_xls: false,
+ },
+ ],
+ channels: [
+ {
+ enabled: true,
+ channel_type: "slack",
+ schedule_type: "hourly",
+ },
+ ],
+ parameters: [FILTER_PARAMETER],
+ });
+
+ H.visitDashboard(dashboard.id);
+ });
+ });
+
+ it("warns before removing a filter that has active subscriptions (metabase#54603)", () => {
+ H.editDashboard();
+
+ cy.findByTestId("fixed-width-filters").findByText("Category").click();
+
+ // The Remove button stays disabled until the subscriptions query resolves;
+ // Cypress retries until it's clickable.
+ H.dashboardParameterSidebar()
+ .findByRole("button", { name: "Remove" })
+ .should("be.enabled")
+ .click();
+
+ H.modal().within(() => {
+ cy.findByText("Remove this filter?").should("be.visible");
+ cy.findByText(/active subscription/i).should("be.visible");
+ cy.findByText(/archive/i).should("be.visible");
+
+ // Cancel keeps the filter.
+ cy.findByRole("button", { name: "Cancel" }).click();
+ });
+
+ cy.findByTestId("fixed-width-filters")
+ .findByText("Category")
+ .should("be.visible");
+
+ // Try again and confirm — filter is removed.
+ H.dashboardParameterSidebar()
+ .findByRole("button", { name: "Remove" })
+ .click();
+ H.modal().findByRole("button", { name: "Remove filter" }).click();
+
+ // The sidebar closes when the parameter is removed.
+ cy.findByTestId("dashboard-parameter-sidebar").should("not.exist");
+
+ // Saving triggers server-side archival of any subscription referencing
+ // the removed parameter. updateDashboard's invalidatesTags includes the
+ // subscription list so the panel reflects the archive without a refresh.
+ H.saveDashboard();
+
+ H.openDashboardMenu("Subscriptions");
+ H.sidebar().findByText("Weekly Category Roundup").should("not.exist");
+ });
+
+ it("removes a filter immediately when no subscription references it (metabase#54603)", () => {
+ // Replace the existing subscription with one that does NOT include the filter.
+ cy.request("GET", "/api/pulse").then(({ body: pulses }) => {
+ pulses.forEach((pulse) => {
+ cy.request("PUT", `/api/pulse/${pulse.id}`, {
+ ...pulse,
+ parameters: [],
+ });
+ });
+ });
+
+ H.editDashboard();
+
+ cy.findByTestId("fixed-width-filters").findByText("Category").click();
+ H.dashboardParameterSidebar()
+ .findByRole("button", { name: "Remove" })
+ .should("be.enabled")
+ .click();
+
+ // No modal — the filter is gone right away (sidebar closes too).
+ cy.findByRole("dialog", { name: /remove this filter/i }).should(
+ "not.exist",
+ );
+ cy.findByTestId("dashboard-parameter-sidebar").should("not.exist");
+ });
+});
diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.ts
index 9ca1ee90142..dedf6010de8 100644
--- a/frontend/src/metabase/api/dashboard.ts
+++ b/frontend/src/metabase/api/dashboard.ts
@@ -154,12 +154,15 @@ export const dashboardApi = Api.injectEndpoints({
url: `/api/dashboard/${id}`,
body,
}),
+ // Subscriptions can be archived server-side when a referenced
+ // parameter is removed, so invalidate the subscription list too.
invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [
listTag("dashboard"),
idTag("dashboard", id),
tag("parameter-values"),
listTag("revision"),
+ listTag("subscription"),
]),
}),
deleteDashboard: builder.mutation<void, DashboardId>({
diff --git a/frontend/src/metabase/common/components/Sidebar/Sidebar.tsx b/frontend/src/metabase/common/components/Sidebar/Sidebar.tsx
index 7f0cadfa02c..7a5fedf19c5 100644
--- a/frontend/src/metabase/common/components/Sidebar/Sidebar.tsx
+++ b/frontend/src/metabase/common/components/Sidebar/Sidebar.tsx
@@ -12,6 +12,8 @@ interface SidebarProps {
onRemove?: () => void;
isCloseDisabled?: boolean;
closeTooltip?: string;
+ isRemoveDisabled?: boolean;
+ removeTooltip?: string;
"data-testid"?: string;
}
@@ -23,6 +25,8 @@ export function Sidebar({
onCancel,
onRemove,
closeTooltip,
+ isRemoveDisabled,
+ removeTooltip,
"data-testid": dataTestId,
}: SidebarProps) {
return (
@@ -45,16 +49,22 @@ export function Sidebar({
className={S.ButtonContainer}
>
{onRemove && (
- <Button
- leftSection={<Icon name="trash" />}
- variant="subtle"
- color="error"
- onClick={onRemove}
- style={{ paddingLeft: 0, paddingRight: 0 }}
- size="compact-md"
- role="button"
- aria-label={t`Remove`}
- >{t`Remove`}</Button>
+ <Tooltip label={removeTooltip} disabled={!removeTooltip}>
+ {/* without a div we will need hacks to make tooltip work */}
+ <div>
+ <Button
+ leftSection={<Icon name="trash" />}
+ variant="subtle"
+ color="error"
+ disabled={isRemoveDisabled}
+ onClick={onRemove}
+ style={{ paddingLeft: 0, paddingRight: 0 }}
+ size="compact-md"
+ role="button"
+ aria-label={t`Remove`}
+ >{t`Remove`}</Button>
+ </div>
+ </Tooltip>
)}
{onCancel && (
<Button
@@ -65,7 +75,7 @@ export function Sidebar({
>{t`Cancel`}</Button>
)}
{onClose && (
- <Tooltip label={closeTooltip} hidden={!closeTooltip}>
+ <Tooltip label={closeTooltip} disabled={!closeTooltip}>
{/* without a div we will need hacks to make tooltip work */}
<div>
<Button
diff --git a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.tsx b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.tsx
index 6c5cbe32111..6f38f38d0b7 100644
--- a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.tsx
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { usePrevious } from "react-use";
-import { t } from "ttag";
+import { c, msgid, t } from "ttag";
+import { skipToken, useListSubscriptionsQuery } from "metabase/api";
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { Sidebar } from "metabase/common/components/Sidebar";
import { hasMapping } from "metabase/parameters/utils/dashboards";
import { canUseLinkedFilters } from "metabase/parameters/utils/linked-filters";
@@ -71,8 +73,28 @@ export const ParameterSidebar = (): JSX.Element | null => {
const [tab, setTab] = useState<"filters" | "settings">(
tabs[0]?.value || "settings",
);
+ const [isRemoveConfirmOpen, setIsRemoveConfirmOpen] = useState(false);
const prevParameterId = usePrevious(parameterId);
+ // Active dashboard subscriptions may bind values to this parameter. Deleting
+ // the filter will archive any such subscription and email its recipients,
+ // so we warn before letting that happen.
+ const { data: subscriptions } = useListSubscriptionsQuery(
+ dashboard ? { dashboard_id: dashboard.id, archived: false } : skipToken,
+ );
+ const areSubscriptionsLoaded = subscriptions !== undefined;
+ const affectedSubscriptions = useMemo(
+ () =>
+ parameterId && subscriptions
+ ? subscriptions.filter(
+ (subscription) =>
+ !subscription.archived &&
+ subscription.parameters.some((p) => p.id === parameterId),
+ )
+ : [],
+ [parameterId, subscriptions],
+ );
+
const embeddedParameterVisibility = useSelector((state) =>
parameter ? getEmbeddedParameterVisibility(state, parameter.slug) : null,
);
@@ -155,13 +177,33 @@ export const ParameterSidebar = (): JSX.Element | null => {
[parameterId, setParameterFilteringParameters],
);
- const handleRemove = useCallback(() => {
+ const performRemove = useCallback(() => {
if (parameterId) {
removeParameter(parameterId);
closeSidebar();
}
}, [parameterId, removeParameter, closeSidebar]);
+ const handleRemove = useCallback(() => {
+ if (!parameterId) {
+ return;
+ }
+ if (affectedSubscriptions.length > 0) {
+ setIsRemoveConfirmOpen(true);
+ } else {
+ performRemove();
+ }
+ }, [parameterId, affectedSubscriptions.length, performRemove]);
+
+ const handleConfirmRemove = useCallback(() => {
+ setIsRemoveConfirmOpen(false);
+ performRemove();
+ }, [performRemove]);
+
+ const handleCancelRemove = useCallback(() => {
+ setIsRemoveConfirmOpen(false);
+ }, []);
+
const isParameterSlugUsed = useCallback(
(value: string) =>
otherParameters.some((parameter) => parameter.slug === slugify(value)),
@@ -206,6 +248,10 @@ export const ParameterSidebar = (): JSX.Element | null => {
: undefined
}
onRemove={handleRemove}
+ isRemoveDisabled={!areSubscriptionsLoaded}
+ removeTooltip={
+ !areSubscriptionsLoaded ? t`Checking subscriptions…` : undefined
+ }
data-testid="dashboard-parameter-sidebar"
>
<Tabs radius={0} value={tab} onChange={handleTabChange}>
@@ -253,6 +299,21 @@ export const ParameterSidebar = (): JSX.Element | null => {
/>
</Tabs.Panel>
</Tabs>
+ <ConfirmModal
+ opened={isRemoveConfirmOpen}
+ title={t`Remove this filter?`}
+ message={c(
+ "Warning shown when deleting a dashboard filter that has active subscriptions referencing it. The number can be 1 or more.",
+ ).ngettext(
+ msgid`${affectedSubscriptions.length} active subscription uses this filter. Removing it will archive the subscription and email its recipients.`,
+ `${affectedSubscriptions.length} active subscriptions use this filter. Removing it will archive these subscriptions and email their recipients.`,
+ affectedSubscriptions.length,
+ )}
+ confirmButtonText={t`Remove filter`}
+ closeButtonText={t`Cancel`}
+ onConfirm={handleConfirmRemove}
+ onClose={handleCancelRemove}
+ />
</Sidebar>
);
};
diff --git a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx
index 0b22f475800..cd9aa2f146c 100644
--- a/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/ParameterSidebar/ParameterSidebar.unit.spec.tsx
@@ -1,13 +1,17 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { useState } from "react";
-import { act, renderWithProviders, screen } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
+import type { DashboardSubscription } from "metabase-types/api";
import {
createMockDashboard,
createMockDashboardCard,
+ createMockDashboardSubscription,
+ createMockParameter,
} from "metabase-types/api/mocks";
import { ParameterSidebar } from "./ParameterSidebar";
@@ -17,6 +21,8 @@ interface SetupOpts {
nextParameter?: UiParameter;
otherParameters: UiParameter[];
hasMapping?: boolean;
+ subscriptions?: DashboardSubscription[];
+ removeParameter?: (parameterId: string) => Promise<any>;
}
const setup = ({
@@ -24,9 +30,13 @@ const setup = ({
nextParameter,
otherParameters,
hasMapping,
+ subscriptions = [],
+ removeParameter,
}: SetupOpts): {
clickNextParameterButton: () => Promise<void>;
} => {
+ fetchMock.get("path:/api/pulse", subscriptions);
+
const NEXT_PARAMETER_BUTTON_ID = "parameter-sidebar-test-change";
const TestWrapper = ({
@@ -63,6 +73,7 @@ const setup = ({
})}
parameters={[parameter, ...otherParameters]}
editingParameter={parameter}
+ removeParameter={removeParameter}
>
<ParameterSidebar />
</MockDashboardContext>
@@ -90,6 +101,12 @@ async function fillValue(input: HTMLElement, value: string) {
await userEvent.type(input, value);
}
+async function clickRemove() {
+ const button = await screen.findByRole("button", { name: "Remove" });
+ await waitFor(() => expect(button).toBeEnabled());
+ await userEvent.click(button);
+}
+
describe("ParameterSidebar", () => {
it("should not update the label if the slug is duplicated with another parameter", async () => {
setup({
@@ -205,6 +222,119 @@ describe("ParameterSidebar", () => {
});
});
+ describe("removing a parameter that affects active subscriptions (metabase#54603)", () => {
+ const filterParameter = createMockUiParameter({
+ id: "filter-id",
+ name: "Category",
+ slug: "category",
+ sectionId: "string",
+ });
+
+ it("removes the parameter immediately when no active subscriptions reference it", async () => {
+ const removeParameter = jest.fn();
+ setup({
+ initialParameter: filterParameter,
+ otherParameters: [],
+ subscriptions: [],
+ removeParameter,
+ });
+
+ await clickRemove();
+ expect(removeParameter).toHaveBeenCalledWith("filter-id");
+ expect(
+ screen.queryByRole("dialog", { name: /remove this filter/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("warns before removing a parameter that is used by an active subscription", async () => {
+ const removeParameter = jest.fn();
+ const subscription = createMockDashboardSubscription({
+ id: 42,
+ name: "Weekly email",
+ dashboard_id: 1,
+ parameters: [createMockParameter({ id: "filter-id" })],
+ });
+
+ setup({
+ initialParameter: filterParameter,
+ otherParameters: [],
+ subscriptions: [subscription],
+ removeParameter,
+ });
+
+ await clickRemove();
+
+ // The remove is not called yet — a confirmation modal appears first
+ expect(removeParameter).not.toHaveBeenCalled();
+ const dialog = await screen.findByRole("dialog");
+ expect(dialog).toHaveTextContent(/active subscription/i);
+ expect(dialog).toHaveTextContent(/archive/i);
+ });
+
+ it("removes the parameter when the user confirms in the warning dialog", async () => {
+ const removeParameter = jest.fn();
+ const subscription = createMockDashboardSubscription({
+ parameters: [createMockParameter({ id: "filter-id" })],
+ });
+
+ setup({
+ initialParameter: filterParameter,
+ otherParameters: [],
+ subscriptions: [subscription],
+ removeParameter,
+ });
+
+ await clickRemove();
+ const dialog = await screen.findByRole("dialog");
+ await userEvent.click(
+ await screen.findByRole("button", { name: /^Remove filter$/i }),
+ );
+
+ expect(removeParameter).toHaveBeenCalledWith("filter-id");
+ expect(dialog).not.toBeInTheDocument();
+ });
+
+ it("does not remove the parameter when the user cancels the warning dialog", async () => {
+ const removeParameter = jest.fn();
+ const subscription = createMockDashboardSubscription({
+ parameters: [createMockParameter({ id: "filter-id" })],
+ });
+
+ setup({
+ initialParameter: filterParameter,
+ otherParameters: [],
+ subscriptions: [subscription],
+ removeParameter,
+ });
+
+ await clickRemove();
+ await screen.findByRole("dialog");
+ await userEvent.click(screen.getByRole("button", { name: /cancel/i }));
+
+ expect(removeParameter).not.toHaveBeenCalled();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("ignores archived subscriptions when deciding whether to warn", async () => {
+ const removeParameter = jest.fn();
+ const archivedSubscription = createMockDashboardSubscription({
+ archived: true,
+ parameters: [createMockParameter({ id: "filter-id" })],
+ });
+
+ setup({
+ initialParameter: filterParameter,
+ otherParameters: [],
+ subscriptions: [archivedSubscription],
+ removeParameter,
+ });
+
+ await clickRemove();
+ expect(removeParameter).toHaveBeenCalledWith("filter-id");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+ });
+
describe("disconnect from cards", () => {
it("renders button when there is mapping", () => {
const initialParameter = createMockUiParameter({