Skip to content

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

Update strings in metric view (#71912)

Nick Fitzpatrick122500f230dd
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx
index 77b00603e3a..8c151725880 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx
@@ -62,6 +62,7 @@ const InvalidateNowFormBody = ({
.with("dashboard", () => t`Clear cache for this dashboard`)
.with("question", () => t`Clear cache for this question`)
.with("database", () => t`Clear cache for this database`)
+ .with("metric", () => t`Clear cache for this metric`)
.exhaustive(),
[targetModel],
);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx b/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx
index 1ead3257726..c61dbc79ecc 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx
@@ -51,7 +51,7 @@ export function MetricCachingPage({
return { savedStrategy };
}, [configs, cardId]);
- const saveStrategy = useSaveStrategy(cardId ?? null, "question");
+ const saveStrategy = useSaveStrategy(cardId ?? null, "metric");
const { confirmationModal, setIsStrategyFormDirty } =
useConfirmIfFormIsDirty();
@@ -80,7 +80,7 @@ export function MetricCachingPage({
<Card withBorder flex={1} p={0}>
<StrategyForm
targetId={question.id()}
- targetModel="question"
+ targetModel="metric"
targetName={getItemName("question", question)}
setIsDirty={setIsStrategyFormDirty}
saveStrategy={saveStrategy}
diff --git a/frontend/src/metabase-types/api/performance.ts b/frontend/src/metabase-types/api/performance.ts
index 62cb918ad1d..bdd6917fe48 100644
--- a/frontend/src/metabase-types/api/performance.ts
+++ b/frontend/src/metabase-types/api/performance.ts
@@ -3,7 +3,12 @@ import type { CollectionEssentials } from "metabase-types/api/search";
import type { SortDirection } from "./sorting";
/** 'Model' as in 'type of object' */
-export type CacheableModel = "root" | "database" | "dashboard" | "question";
+export type CacheableModel =
+ | "root"
+ | "database"
+ | "dashboard"
+ | "question"
+ | "metric";
export type CacheStrategyType =
| "nocache"
diff --git a/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
index 2114899054b..565682dd740 100644
--- a/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.tsx
@@ -18,10 +18,11 @@ export const useInvalidateTarget = (
if (targetId === null) {
return;
}
+ const apiModel = targetModel === "metric" ? "question" : targetModel;
try {
const invalidate = invalidateCacheConfigs({
include: "overrides",
- [targetModel]: targetId,
+ [apiModel]: targetId,
}).unwrap();
if (smooth) {
await resolveSmoothly([invalidate]);
diff --git a/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.unit.spec.tsx b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.unit.spec.tsx
new file mode 100644
index 00000000000..86908df345d
--- /dev/null
+++ b/frontend/src/metabase/admin/performance/hooks/useInvalidateTarget.unit.spec.tsx
@@ -0,0 +1,54 @@
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders } from "__support__/ui";
+import type { CacheableModel } from "metabase-types/api";
+
+import { useInvalidateTarget } from "./useInvalidateTarget";
+
+function setup(targetId: number, targetModel: CacheableModel) {
+ let invalidateTarget: () => Promise<void>;
+
+ const TestComponent = () => {
+ invalidateTarget = useInvalidateTarget(targetId, targetModel, {
+ smooth: false,
+ });
+ return null;
+ };
+
+ fetchMock.post("glob:*/api/cache/invalidate*", {});
+
+ renderWithProviders(<TestComponent />);
+
+ return { getInvalidateTarget: () => invalidateTarget! };
+}
+
+async function getInvalidateRequestUrl(): Promise<URL> {
+ await fetchMock.callHistory.flush();
+ const calls = fetchMock.callHistory.calls();
+ const invalidateCall = calls.find((call) =>
+ call.url?.includes("/api/cache/invalidate"),
+ );
+ return new URL(invalidateCall!.url!);
+}
+
+describe("useInvalidateTarget", () => {
+ it('should send "question" as the query param when model is "question"', async () => {
+ const { getInvalidateTarget } = setup(1, "question");
+
+ await getInvalidateTarget()();
+
+ const url = await getInvalidateRequestUrl();
+ expect(url.searchParams.get("question")).toBe("1");
+ expect(url.searchParams.has("metric")).toBe(false);
+ });
+
+ it('should map "metric" to "question" in the query param', async () => {
+ const { getInvalidateTarget } = setup(1, "metric");
+
+ await getInvalidateTarget()();
+
+ const url = await getInvalidateRequestUrl();
+ expect(url.searchParams.get("question")).toBe("1");
+ expect(url.searchParams.has("metric")).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.tsx b/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.tsx
index e0c39dc7960..927c01f43bf 100644
--- a/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.tsx
@@ -35,8 +35,9 @@ export const useSaveStrategy = (
const { strategies } = PLUGIN_CACHING;
const isRoot = targetId === rootId;
+ const apiModel = model === "metric" ? "question" : model;
const baseConfig: Pick<CacheConfig, "model" | "model_id"> = {
- model: isRoot ? "root" : model,
+ model: isRoot ? "root" : apiModel,
model_id: targetId,
};
const shouldDeleteStrategy =
diff --git a/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.unit.spec.tsx b/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.unit.spec.tsx
new file mode 100644
index 00000000000..98fd1e2a340
--- /dev/null
+++ b/frontend/src/metabase/admin/performance/hooks/useSaveStrategy.unit.spec.tsx
@@ -0,0 +1,67 @@
+import { setupPerformanceEndpoints } from "__support__/server-mocks/performance";
+import { findRequests } from "__support__/server-mocks/util";
+import { renderWithProviders } from "__support__/ui";
+import type { CacheConfig, CacheStrategy } from "metabase-types/api";
+import { createMockCacheConfig } from "metabase-types/api/mocks";
+
+import { useSaveStrategy } from "./useSaveStrategy";
+
+function setup(targetId: number, model: "question" | "metric") {
+ let saveStrategy: (values: CacheStrategy) => Promise<void>;
+
+ const TestComponent = () => {
+ saveStrategy = useSaveStrategy(targetId, model);
+ return null;
+ };
+
+ renderWithProviders(<TestComponent />);
+
+ return { getSaveStrategy: () => saveStrategy! };
+}
+
+describe("useSaveStrategy", () => {
+ it('should send model="question" to the API when deleting with model "question"', async () => {
+ const configs: CacheConfig[] = [
+ createMockCacheConfig({ model: "question", model_id: 1 }),
+ ];
+ setupPerformanceEndpoints(configs);
+
+ const { getSaveStrategy } = setup(1, "question");
+
+ await getSaveStrategy()({ type: "inherit" });
+
+ const deleteRequests = await findRequests("DELETE");
+ expect(deleteRequests).toHaveLength(1);
+ expect(deleteRequests[0].body.model).toBe("question");
+ });
+
+ it('should map "metric" to "question" when deleting via the API', async () => {
+ const configs: CacheConfig[] = [
+ createMockCacheConfig({ model: "question", model_id: 1 }),
+ ];
+ setupPerformanceEndpoints(configs);
+
+ const { getSaveStrategy } = setup(1, "metric");
+
+ await getSaveStrategy()({ type: "inherit" });
+
+ const deleteRequests = await findRequests("DELETE");
+ expect(deleteRequests).toHaveLength(1);
+ expect(deleteRequests[0].body.model).toBe("question");
+ });
+
+ it('should map "metric" to "question" when updating via the API', async () => {
+ setupPerformanceEndpoints([]);
+
+ const { getSaveStrategy } = setup(1, "metric");
+
+ await getSaveStrategy()({
+ type: "nocache",
+ });
+
+ const putRequests = await findRequests("PUT");
+ expect(putRequests).toHaveLength(1);
+ expect(putRequests[0].body.model).toBe("question");
+ expect(putRequests[0].body.model_id).toBe(1);
+ });
+});
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index a6df564542c..21eecce96b3 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -60,29 +60,27 @@ import { AlertModalSettingsBlock } from "./components/AlertModalSettingsBlock/Al
import { NotificationSchedule } from "./components/NotificationSchedule/NotificationSchedule";
import type { NotificationTriggerOption } from "./types";
-const ALERT_TRIGGER_OPTIONS_MAP: Record<
- NotificationCardSendCondition,
- NotificationTriggerOption
-> = {
- has_result: {
- value: "has_result" as const,
- get label() {
- return t`When this question has results`;
+function getAlertTriggerOptionsMap(
+ question: Question | undefined,
+): Record<NotificationCardSendCondition, NotificationTriggerOption> {
+ const isMetric = question?.type() === "metric";
+ return {
+ has_result: {
+ value: "has_result" as const,
+ label: isMetric
+ ? t`When this metric has results`
+ : t`When this question has results`,
},
- },
- goal_above: {
- value: "goal_above" as const,
- get label() {
- return t`When results go above the goal`;
+ goal_above: {
+ value: "goal_above" as const,
+ label: t`When results go above the goal`,
},
- },
- goal_below: {
- value: "goal_below" as const,
- get label() {
- return t`When results go below the goal`;
+ goal_below: {
+ value: "goal_below" as const,
+ label: t`When results go below the goal`,
},
- },
-};
+ };
+}
const ALERT_SCHEDULE_OPTIONS: ScheduleType[] = [
"every_n_minutes",
@@ -174,14 +172,13 @@ export const CreateOrEditQuestionAlertModal = ({
const hasConfiguredEmailOrSlackChannel =
getHasConfiguredEmailOrSlackChannel(channelSpec);
- const triggerOptions = useMemo(
- () =>
- getAlertTriggerOptions({
- question,
- visualizationSettings,
- }).map((trigger) => ALERT_TRIGGER_OPTIONS_MAP[trigger]),
- [question, visualizationSettings],
- );
+ const triggerOptions = useMemo(() => {
+ const optionsMap = getAlertTriggerOptionsMap(question);
+ return getAlertTriggerOptions({
+ question,
+ visualizationSettings,
+ }).map((trigger) => optionsMap[trigger]);
+ }, [question, visualizationSettings]);
const hasSingleTriggerOption = triggerOptions.length === 1;
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 9f45d7b5a63..e1a6aa217cd 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -43,6 +43,22 @@ const expectNotConfigured = async (channel: string) =>
).not.toBeInTheDocument();
describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
+ it("should show 'When this question has results' for question cards", async () => {
+ setup({ isAdmin: true });
+
+ expect(await screen.findByTestId("alert-create")).toBeInTheDocument();
+ const goalSelect = screen.getByTestId("alert-goal-select");
+ expect(goalSelect).toHaveValue("When this question has results");
+ });
+
+ it("should show 'When this metric has results' for metric cards", async () => {
+ setup({ isAdmin: true, cardType: "metric" });
+
+ expect(await screen.findByTestId("alert-create")).toBeInTheDocument();
+ const goalSelect = screen.getByTestId("alert-goal-select");
+ expect(goalSelect).toHaveValue("When this metric has results");
+ });
+
it("should display first available channel by default - Email", async () => {
setup({ isAdmin: true });
@@ -391,6 +407,7 @@ function setup({
editingNotification,
onAlertCreatedMock = jest.fn(),
onAlertUpdatedMock = jest.fn(),
+ cardType = "question",
}: {
userCanAccessSettings?: boolean;
isAdmin?: boolean;
@@ -401,6 +418,7 @@ function setup({
editingNotification?: Notification;
onAlertCreatedMock?: jest.Mock;
onAlertUpdatedMock?: jest.Mock;
+ cardType?: "question" | "model" | "metric";
}) {
const settings = mockSettings({
"token-features": createMockTokenFeatures({
@@ -412,6 +430,7 @@ function setup({
setupEnterpriseOnlyPlugin("application_permissions");
const mockCard = createMockCard({
+ type: cardType,
display: "line",
visualization_settings: createMockVisualizationSettings({
"graph.show_goal": true,
diff --git a/frontend/src/metabase/questions/components/ArchiveCardModal/ArchiveCardModal.tsx b/frontend/src/metabase/questions/components/ArchiveCardModal/ArchiveCardModal.tsx
index bb42f1cdc37..3e918328b3e 100644
--- a/frontend/src/metabase/questions/components/ArchiveCardModal/ArchiveCardModal.tsx
+++ b/frontend/src/metabase/questions/components/ArchiveCardModal/ArchiveCardModal.tsx
@@ -88,8 +88,8 @@ function getLabels(card: Card) {
if (type === "metric") {
return {
- title: t`Archive this metric?`,
- message: t`This metric will be removed from any dashboards or pulses using it.`,
+ title: t`Move this metric to trash?`,
+ message: t`This metric will be removed from any dashboards or alerts using it.`,
};
}