Skip to content

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

Add Metric Dimensions (#76623)

Denis Berezin7eaf406eb118
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 92614612de5..91c43b0a887 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -630,6 +630,7 @@
metabase.lib.test-util.macros/mbql-query hooks.metabase.test.data/mbql-query
metabase.lib.test-util.macros/mbql-5-query hooks.metabase.test.data/mbql-query
metabase.lib.test-util.macros/with-testing-against-standard-queries hooks.metabase.lib.test-util.macros/with-testing-against-standard-queries
+ metabase.metrics.api-dimension-test/with-seeded-metric hooks.common/with-one-binding
metabase.model-persistence.api-test/with-persistence-setup! hooks.common/with-one-top-level-binding
metabase.model-persistence.api-test/with-setup! hooks.common/with-one-top-level-binding
metabase.model-persistence.test-util/with-persistence-enabled! hooks.metabase.model-persistence.test-util/with-persistence-enabled!
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 95465725343..cdbf541fd4b 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1378,21 +1378,18 @@
metabase.metrics.core}
:uses #{api
collections
+ events
lib
lib-be
lib-metric
models
parameters
permissions
- premium-features
query-processor
request
server
util}
- :model-imports #{:model/Card
- :model/Field
- :model/Measure
- :model/Table}}
+ :model-imports #{:model/Card :model/Field :model/Measure}}
model-persistence
{:team "Graphy"
@@ -1585,6 +1582,7 @@
{:team "UX West"
:api #{metabase.permissions.core
metabase.permissions.init
+ metabase.permissions.metric
metabase.permissions.schema}
:uses #{api
app-db
@@ -1609,6 +1607,7 @@
:model/PermissionsRevision}
:model-imports #{:model/Collection
:model/Database
+ :model/Field
:model/Table
:model/User}}
@@ -1911,6 +1910,7 @@
legacy-mbql
lib
lib-be
+ lib-metric
model-persistence
models
parameters
diff --git a/e2e/support/helpers/e2e-metric-page-helpers.ts b/e2e/support/helpers/e2e-metric-page-helpers.ts
index 4c8cc18527d..164c8cf430d 100644
--- a/e2e/support/helpers/e2e-metric-page-helpers.ts
+++ b/e2e/support/helpers/e2e-metric-page-helpers.ts
@@ -1,11 +1,13 @@
const metricAboutPage = () => cy.findByTestId("metric-about-page");
const metricOverviewPage = () => cy.findByTestId("metric-overview-page");
const metricQueryEditor = () => cy.findByTestId("metric-query-editor");
+const metricDimensionsPage = () => cy.findByTestId("metric-dimensions-page");
export const MetricPage = {
aboutPage: metricAboutPage,
overviewPage: metricOverviewPage,
queryEditor: metricQueryEditor,
+ dimensionsPage: metricDimensionsPage,
nameInput: () => metricQueryEditor().findByPlaceholderText("New metric"),
saveButton: () => metricQueryEditor().findByRole("button", { name: "Save" }),
cancelButton: () =>
@@ -15,6 +17,7 @@ export const MetricPage = {
aboutTab: () => MetricPage.header().findByText("About"),
overviewTab: () => MetricPage.header().findByText("Overview"),
definitionTab: () => MetricPage.header().findByText("Definition"),
+ dimensionsTab: () => MetricPage.header().findByText("Dimensions"),
dependenciesTab: () => MetricPage.header().findByText("Dependencies"),
historyTab: () => MetricPage.header().findByText("History"),
aboutPageDescriptionSidebar: () =>
diff --git a/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js b/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
index dd72769b6db..02a2229222f 100644
--- a/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
+++ b/e2e/test/scenarios/dashboard-filters/temporal-unit-parameters.cy.spec.js
@@ -356,7 +356,12 @@ describe("scenarios > dashboard > temporal unit parameters", () => {
});
it("should connect a parameter to a metric", () => {
- H.createQuestion({ ...singleBreakoutQuestionDetails, type: "metric" });
+ H.createQuestion({
+ ...singleBreakoutQuestionDetails,
+ type: "metric",
+ }).then(({ body: metric }) => {
+ cy.request("GET", `/api/metric/${metric.id}`);
+ });
H.createDashboard(dashboardDetails).then(({ body: dashboard }) =>
H.visitDashboard(dashboard.id),
);
@@ -366,7 +371,7 @@ describe("scenarios > dashboard > temporal unit parameters", () => {
addQuestion(singleBreakoutQuestionDetails.name);
editParameter(parameterDetails.name);
H.getDashboardCard().findByText("Select…").click();
- H.popover().findByText("Created At: Month").click();
+ H.popover().findByText("Created At").click();
H.saveDashboard();
H.filterWidget().click();
H.popover().findByText("Year").click();
diff --git a/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
index 22b67f4e9c3..addd22e38d1 100644
--- a/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/source-replacement.cy.spec.ts
@@ -1,5 +1,9 @@
import { USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";
-import type { ConcreteFieldReference } from "metabase-types/api";
+import type {
+ ConcreteFieldReference,
+ Dataset,
+ MetricDatasetRequest,
+} from "metabase-types/api";
const { H } = cy;
const { SourceReplacement } = H.DataModel;
@@ -194,8 +198,18 @@ describe(
cy.log("metric now aggregates data from the new table");
cy.get<Cypress.Response<{ id: number }>>("@metric").then(({ body }) => {
+ cy.intercept("POST", "/api/metric/dataset").as("metricDataset");
H.visitMetric(body.id);
- H.main().findByText("800").should("be.visible");
+ cy.wait<MetricDatasetRequest, Dataset>("@metricDataset").then(
+ ({ response }) => {
+ expect(response?.statusCode).to.equal(202);
+ const total = response?.body.data.rows.reduce((sum, row) => {
+ return sum + Number(row[row.length - 1]);
+ }, 0);
+ expect(total).to.equal(800);
+ },
+ );
+ H.echartsContainer().should("be.visible");
});
});
diff --git a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts
index 50854ef479e..2744093239f 100644
--- a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts
@@ -43,12 +43,6 @@ describe("scenarios > data studio > library > metrics", () => {
H.miniPickerBrowseAll().click();
H.pickEntity({ path: ["Databases", /Sample Database/, "Orders"] });
- H.getNotebookStep("summarize")
- .findByText("Pick a column to group by")
- .click();
-
- H.popover().findByText("Created At").click();
-
H.DataStudio.Metrics.saveButton().should("be.enabled").click();
H.modal().within(() => {
@@ -101,9 +95,7 @@ describe("scenarios > data studio > library > metrics", () => {
cy.log("Verify notebook state");
H.DataStudio.Metrics.queryEditor().should("be.visible");
H.getNotebookStep("data").findByText("Orders").should("be.visible");
- H.getNotebookStep("summarize")
- .findByText("Created At: Month")
- .should("be.visible");
+ H.getNotebookStep("summarize").findByText("Count").should("be.visible");
H.runButtonInOverlay().click();
cy.log("Ensure chart is visible");
diff --git a/e2e/test/scenarios/metrics/metric-page.cy.spec.ts b/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
index f548f647958..7c7245cad2b 100644
--- a/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
+++ b/e2e/test/scenarios/metrics/metric-page.cy.spec.ts
@@ -5,7 +5,7 @@ import {
TRUSTED_ORDERS_METRIC,
createLibraryWithItems,
} from "e2e/support/test-library-data";
-import type { Card } from "metabase-types/api";
+import type { Card, ListMetricDimensionsResponse } from "metabase-types/api";
const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;
@@ -38,6 +38,48 @@ const ORDERS_TIMESERIES_METRIC = {
display: "line" as const,
};
+const OVERVIEW_DIMENSIONS_TO_ADD = [
+ ["Product", "Category"],
+ ["Product", "Price"],
+ ["Product", "Rating"],
+ ["Product", "Title"],
+ ["Product", "Vendor"],
+ ["User", "City"],
+ ["User", "Source"],
+ ["User", "State"],
+] as const;
+
+function addOverviewDimensions(metricId: number) {
+ return cy
+ .request("GET", `/api/metric/${metricId}`)
+ .then(() =>
+ cy.request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension?with-addable=true`,
+ ),
+ )
+ .then(({ body }) => {
+ const dimensions = OVERVIEW_DIMENSIONS_TO_ADD.flatMap(
+ ([groupName, dimensionName]) => {
+ const group = body.addable.find(
+ (candidate) => candidate.group.display_name === groupName,
+ );
+ const dimension = group?.dimensions.find(
+ (candidate) => candidate.display_name === dimensionName,
+ );
+
+ expect(dimension, `${groupName} - ${dimensionName}`).to.exist;
+ return dimension ? [dimension] : [];
+ },
+ );
+
+ expect(dimensions).to.have.length(OVERVIEW_DIMENSIONS_TO_ADD.length);
+ cy.request("POST", `/api/metric/${metricId}/dimension/add`, {
+ dimensions,
+ });
+ });
+}
+
describe("scenarios > metrics > metric page", () => {
beforeEach(() => {
H.restore();
@@ -196,8 +238,9 @@ describe("scenarios > metrics > metric page", () => {
H.MetricPage.aboutPage().should("be.visible");
});
- it("should render dimension charts on the overview tab and show more", () => {
+ it("should render curated dimension charts in order and load more", () => {
H.createQuestion(ORDERS_TIMESERIES_METRIC).then(({ body: metric }) => {
+ addOverviewDimensions(metric.id);
H.visitMetric(metric.id);
});
@@ -205,26 +248,43 @@ describe("scenarios > metrics > metric page", () => {
H.MetricPage.overviewPage().should("be.visible");
H.MetricPage.overviewPage().within(() => {
- cy.findByText("By Created At").should("exist");
- cy.findByText("By State").should("exist");
- cy.findByText("By Category").should("exist");
- cy.findByText("By City").should("exist");
- cy.findAllByText(/^By /).should("have.length", 4);
+ cy.findAllByText(/^By /).then(($cards) => {
+ expect($cards.map((_, card) => card.textContent).get()).to.deep.equal([
+ "By Subtotal",
+ "By Tax",
+ "By Total",
+ "By Discount",
+ ]);
+ });
+ });
+
+ H.MetricPage.overviewPage().realMouseWheel({ deltaY: 100 });
+
+ H.MetricPage.overviewPage().within(() => {
+ cy.findAllByText(/^By /).should("have.length", 10);
+
+ cy.findAllByText(/^By /).then(($cards) => {
+ expect($cards.map((_, card) => card.textContent).get()).to.deep.equal([
+ "By Subtotal",
+ "By Tax",
+ "By Total",
+ "By Discount",
+ "By Created At",
+ "By Quantity",
+ "By Category",
+ "By Price",
+ "By Rating",
+ "By Title",
+ ]);
+ });
cy.findByText("Show more").scrollIntoView().click();
+ cy.findAllByText(/^By /).should("have.length", 14);
});
H.expectUnstructuredSnowplowEvent({
event: "metric_page_show_more_clicked",
});
-
- H.MetricPage.overviewPage().within(() => {
- cy.findByText("By Name").should("exist");
- cy.findByText("By Source").should("exist");
- cy.findByText("By Title").should("exist");
- cy.findByText("By Vendor").should("exist");
- cy.findAllByText(/^By /).should("have.length", 8);
- });
});
it("should edit, save, and cancel metric definition changes", () => {
diff --git a/e2e/test/scenarios/metrics/metrics-collection.cy.spec.js b/e2e/test/scenarios/metrics/metrics-collection.cy.spec.js
index 1f1219e3fdd..324bf172524 100644
--- a/e2e/test/scenarios/metrics/metrics-collection.cy.spec.js
+++ b/e2e/test/scenarios/metrics/metrics-collection.cy.spec.js
@@ -49,7 +49,7 @@ describe("scenarios > metrics > collection", () => {
.findByText("18,760")
.should("be.visible");
cy.findByText(ORDERS_TIMESERIES_METRIC.name).should("be.visible");
- H.echartsContainer().should("be.visible");
+ H.tableInteractive().should("be.visible");
});
});
diff --git a/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js b/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js
index 354818481c0..10dd39c7fb2 100644
--- a/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js
+++ b/e2e/test/scenarios/metrics/metrics-dashboard.cy.spec.js
@@ -58,6 +58,33 @@ const PRODUCTS_TIMESERIES_METRIC = {
display: "line",
};
+function curateMetricDimension(metricId, displayName) {
+ cy.request("GET", `/api/metric/${metricId}`);
+ return cy
+ .request({
+ method: "GET",
+ url: `/api/metric/${metricId}/dimension`,
+ qs: { "with-addable": true },
+ })
+ .then(({ body }) => {
+ const dimension = body.addable
+ .flatMap(({ dimensions }) => dimensions)
+ .find(({ display_name }) => display_name === displayName);
+
+ expect(dimension, `${displayName} metric dimension`).not.to.be.undefined;
+
+ return cy
+ .request("POST", `/api/metric/${metricId}/dimension/remove`, {
+ dimension_ids: body.added.map(({ id }) => id),
+ })
+ .then(() =>
+ cy.request("POST", `/api/metric/${metricId}/dimension/add`, {
+ dimensions: [dimension],
+ }),
+ );
+ });
+}
+
describe("scenarios > metrics > dashboard", () => {
beforeEach(() => {
H.restore();
@@ -146,12 +173,24 @@ describe("scenarios > metrics > dashboard", () => {
"eq",
`/dashboard/${ORDERS_DASHBOARD_ID}-orders-in-a-dashboard`,
);
- cy.findByTestId("scalar-value").should("have.text", "18,760");
+ H.getDashboardCard(1).within(() => {
+ cy.findByText(ORDERS_SCALAR_METRIC.name).should("be.visible");
+ cy.findByTestId("visualization-root")
+ .should("be.visible")
+ .and("have.attr", "data-viz-ui-name", "Line");
+ H.echartsContainer().should("be.visible");
+ });
cy.log("Assert we can save the dashboard with the metric");
H.saveDashboard();
H.getDashboardCards().should("have.length", 2);
- cy.findByTestId("scalar-value").should("have.text", "18,760");
+ H.getDashboardCard(1).within(() => {
+ cy.findByText(ORDERS_SCALAR_METRIC.name).should("be.visible");
+ cy.findByTestId("visualization-root")
+ .should("be.visible")
+ .and("have.attr", "data-viz-ui-name", "Line");
+ H.echartsContainer().should("be.visible");
+ });
},
);
});
@@ -179,20 +218,27 @@ describe("scenarios > metrics > dashboard", () => {
});
});
- it("should be able to add a filter and drill thru", () => {
+ it("should use curated metric dimensions for dashboard filters (UXW-4770)", () => {
+ cy.signIn("normal", { skipCache: true });
H.createDashboardWithQuestions({
questions: [ORDERS_SCALAR_METRIC],
- }).then(({ dashboard }) => {
+ }).then(({ dashboard, questions: [metric] }) => {
+ curateMetricDimension(metric.id, "Category");
H.visitDashboard(dashboard.id);
});
- H.getDashboardCard().findByText("18,760").should("be.visible");
+ H.getDashboardCard().findByTestId("chart-container").should("be.visible");
cy.findByTestId("dashboard-header").within(() => {
cy.findByLabelText("Edit dashboard").click();
cy.findByLabelText("Add a filter or parameter").click();
});
H.popover().findByText("Text or Category").click();
H.getDashboardCard().findByText("Select…").click();
- H.popover().findByText("Category").click();
+ H.popover().within(() => {
+ cy.findByText("Category").should("be.visible");
+ cy.findByText("Title").should("not.exist");
+ cy.findByText("Product").should("not.exist");
+ cy.findByText("Category").click();
+ });
H.saveDashboard();
H.filterWidget().click();
H.popover().within(() => {
@@ -267,3 +313,75 @@ describe("scenarios > metrics > dashboard", () => {
H.assertQueryBuilderRowCount(8);
});
});
+
+describe("scenarios > metrics > dashboard default dimension", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signIn("admin", { skipCache: true });
+ });
+
+ it("uses the visualization type for the default curated dimension", () => {
+ const metricDefinition = {
+ ...ORDERS_TIMESERIES_METRIC,
+ visualization_settings: {
+ "graph.dimensions": ["CREATED_AT"],
+ "graph.metrics": ["count"],
+ },
+ };
+
+ H.createQuestion(metricDefinition).then(({ body: metric }) => {
+ cy.request("GET", `/api/metric/${metric.id}`)
+ .then(() => cy.request("GET", `/api/metric/${metric.id}/dimension`))
+ .then(({ body }) => {
+ const totalDimension = body.added.find(
+ (dimension) => dimension.display_name === "Total",
+ );
+
+ expect(totalDimension, "Total metric dimension").not.to.be.undefined;
+ if (!totalDimension) {
+ return;
+ }
+
+ return cy.request(
+ "POST",
+ `/api/metric/${metric.id}/dimension/set-default`,
+ { dimension_id: totalDimension.id },
+ );
+ })
+ .then(() => H.createDashboard())
+ .then(({ body: dashboard }) => {
+ cy.intercept("POST", `/api/card/${metric.id}/query`).as(
+ "newMetricQuery",
+ );
+
+ H.visitDashboard(dashboard.id);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+ cy.findByTestId("add-card-sidebar")
+ .findByText(ORDERS_TIMESERIES_METRIC.name)
+ .click();
+
+ cy.wait("@newMetricQuery").then(({ request, response }) => {
+ expect(request.body.dashboard_id).to.equal(dashboard.id);
+ expect(response?.body.data.cols[0].name).to.equal("TOTAL");
+ });
+
+ H.getDashboardCard().within(() => {
+ cy.findByText(ORDERS_TIMESERIES_METRIC.name).should("be.visible");
+ cy.findByTestId("visualization-root").should(
+ "have.attr",
+ "data-viz-ui-name",
+ "Bar",
+ );
+ });
+
+ H.saveDashboard();
+ cy.reload();
+
+ H.getDashboardCard()
+ .findByTestId("visualization-root")
+ .should("have.attr", "data-viz-ui-name", "Bar");
+ });
+ });
+ });
+});
diff --git a/e2e/test/scenarios/metrics/metrics-dimensions.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-dimensions.cy.spec.ts
new file mode 100644
index 00000000000..13a7eb8469e
--- /dev/null
+++ b/e2e/test/scenarios/metrics/metrics-dimensions.cy.spec.ts
@@ -0,0 +1,188 @@
+const { H } = cy;
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { ListMetricDimensionsResponse } from "metabase-types/api";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+const ORDERS_SCALAR_METRIC = {
+ name: "Orders count",
+ type: "metric" as const,
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ display: "scalar" as const,
+};
+
+// ID, User ID, Product ID, Subtotal, Tax, Total, Discount, Created At, Quantity
+const SEEDED_DIMENSIONS_COUNT = 9;
+
+const dimensionList = () => cy.findByTestId("metric-dimension-list");
+const dimensionRow = (name: string) => cy.findByTestId(`dimension-row-${name}`);
+const allDimensionRows = () => cy.findAllByTestId(/^dimension-row-/);
+const addDimensionsPanel = () => cy.findByTestId("add-dimensions-panel");
+const settingsPanel = () => cy.findByTestId("dimension-settings-panel");
+
+describe("scenarios > metrics > dimensions", () => {
+ let metricId: number;
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+
+ // Dimension ids are UUIDs, which keeps this from also matching the
+ // fixed-word routes below.
+ cy.intercept("POST", /\/api\/metric\/\d+\/dimension\/[0-9a-f-]{36}$/).as(
+ "updateDimension",
+ );
+ cy.intercept("POST", "/api/metric/*/dimension/add").as("addDimensions");
+ cy.intercept("POST", "/api/metric/*/dimension/remove").as(
+ "removeDimensions",
+ );
+ cy.intercept("POST", "/api/metric/*/dimension/reorder").as(
+ "reorderDimensions",
+ );
+ cy.intercept("POST", "/api/metric/*/dimension/set-default").as(
+ "setDefaultDimension",
+ );
+ cy.intercept("GET", "/api/metric/*/dimension*").as("listDimensions");
+
+ H.createQuestion(ORDERS_SCALAR_METRIC).then(({ body }) => {
+ metricId = body.id;
+ // Reading a metric seeds its curated dimension list with the
+ // metric's own table columns.
+ cy.request("GET", `/api/metric/${body.id}`);
+ });
+ });
+
+ it("curates the dimension list: seeded columns, add, rename, set default, and remove", () => {
+ H.visitMetric(metricId);
+ H.MetricPage.dimensionsTab().click();
+ H.MetricPage.dimensionsPage().should("be.visible");
+
+ cy.log(
+ "seeding added the metric's own table columns, but none from connected tables",
+ );
+ allDimensionRows().should("have.length", SEEDED_DIMENSIONS_COUNT);
+ dimensionList()
+ .should("contain", "Created At")
+ .and("contain", "Total")
+ .and("contain", "Quantity")
+ .and("not.contain", "Vendor");
+
+ cy.log("add a dimension from a connected table");
+ dimensionList()
+ .findByRole("button", { name: "Available dimensions" })
+ .click();
+ addDimensionsPanel().should("contain", "Product").and("contain", "User");
+ addDimensionsPanel().findByText("Category").click();
+ cy.wait("@addDimensions");
+ dimensionRow("Product - Category").scrollIntoView().should("be.visible");
+ addDimensionsPanel().findByRole("button", { name: "Done" }).click();
+ allDimensionRows().should("have.length", SEEDED_DIMENSIONS_COUNT + 1);
+ addDimensionsPanel().should("not.exist");
+
+ cy.log("rename the added dimension from its settings panel");
+ dimensionRow("Product - Category").findByText("Product - Category").click();
+ settingsPanel().should("contain", "Settings for Product - Category");
+ settingsPanel()
+ .findByLabelText("Display name")
+ .clear()
+ .type("Product type")
+ .blur();
+ cy.wait("@updateDimension");
+ dimensionRow("Product type").scrollIntoView().should("be.visible");
+ settingsPanel().should("contain", "Settings for Product type");
+
+ cy.log("give it a description");
+ settingsPanel()
+ .findByLabelText("Description")
+ .type("Category of the ordered product")
+ .blur();
+ cy.wait("@updateDimension");
+
+ cy.log("make it the default dimension");
+ dimensionRow("Created At").findByText("Default").should("be.visible");
+ dimensionList().findAllByText("Default").should("have.length", 1);
+ settingsPanel().findByRole("button", { name: "Set as default" }).click();
+ cy.wait("@setDefaultDimension");
+ dimensionRow("Product type")
+ .scrollIntoView()
+ .findByText("Default")
+ .should("be.visible");
+ dimensionRow("Created At").findByText("Default").should("not.exist");
+ settingsPanel().findByText("Default dimension").should("be.visible");
+ dimensionList().findAllByText("Default").should("have.length", 1);
+
+ cy.log("the edits are persisted");
+ cy.request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension`,
+ ).then(({ body }) => {
+ const renamed = body.added.find(
+ (dimension) => dimension.display_name === "Product type",
+ );
+ expect(renamed?.description).to.equal("Category of the ordered product");
+ expect(renamed?.default).to.equal(true);
+ });
+
+ cy.log("bulk remove checked dimensions");
+ dimensionRow("Product type").findByLabelText("Product type").click();
+ dimensionRow("Tax").findByLabelText("Tax").click();
+ dimensionList()
+ .findByRole("button", { name: "Available dimensions" })
+ .should("be.disabled");
+ dimensionList().findByLabelText("Remove").click();
+ cy.wait("@removeDimensions");
+ allDimensionRows().should("have.length", SEEDED_DIMENSIONS_COUNT - 1);
+ dimensionList()
+ .should("not.contain", "Product type")
+ .and("not.contain", "Tax");
+ });
+
+ it("filters with search and persists a drag-and-drop reorder", () => {
+ cy.visit(`/metric/${metricId}/dimensions`);
+ cy.wait("@listDimensions");
+ allDimensionRows().should("have.length", SEEDED_DIMENSIONS_COUNT);
+
+ cy.log("search filters the added dimensions");
+ dimensionList().findByPlaceholderText("Search…").type("Disc");
+ allDimensionRows().should("have.length", 1);
+ dimensionRow("Discount").should("be.visible");
+ dimensionList().findByPlaceholderText("Search…").clear();
+ allDimensionRows().should("have.length", SEEDED_DIMENSIONS_COUNT);
+
+ cy.log("drag Quantity to the top of the list");
+ allDimensionRows().first().should("not.contain", "Quantity");
+ // Scoped through the list: during a drag the DragOverlay portal renders a
+ // clone of the row with the same test ids, and re-running an unscoped
+ // query would match both.
+ dimensionList()
+ .findByTestId("dimension-row-Quantity")
+ .findByTestId("dimension-drag-handle")
+ .as("dragHandle");
+ allDimensionRows()
+ .first()
+ .then(($firstRow) => {
+ dimensionRow("Quantity").then(($sourceRow) => {
+ // Overshoot past the first row's top so the dragged row's center
+ // clearly crosses above it.
+ const vertical =
+ $firstRow[0].getBoundingClientRect().top -
+ $sourceRow[0].getBoundingClientRect().top -
+ 30;
+ H.moveDnDKitElementByAlias("@dragHandle", { vertical });
+ });
+ });
+ cy.wait("@reorderDimensions");
+ allDimensionRows().first().should("contain", "Quantity");
+
+ cy.log("the new order is persisted");
+ cy.request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension`,
+ )
+ .its("body.added.0.display_name")
+ .should("equal", "Quantity");
+ });
+});
diff --git a/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js b/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js
index 5e69518c80f..46166f36b4d 100644
--- a/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js
+++ b/e2e/test/scenarios/metrics/metrics-editing.cy.spec.js
@@ -110,12 +110,6 @@ function startNewAggregation({ stageIndex } = {}) {
.within(() => getPlusButton().click());
}
-function startNewBreakout({ stageIndex } = {}) {
- H.getNotebookStep("summarize", { stage: stageIndex })
- .findByTestId("breakout-step")
- .within(() => getPlusButton().click());
-}
-
function addStringCategoryFilter({ tableName, columnName, values }) {
startNewFilter();
H.popover().within(() => {
@@ -128,31 +122,42 @@ function addStringCategoryFilter({ tableName, columnName, values }) {
});
}
-function addBreakout({ tableName, columnName, bucketName, stageIndex }) {
- startNewBreakout({ stageIndex });
- if (tableName) {
- H.popover().findByText(tableName).click();
- }
- if (bucketName) {
- H.changeBinningForDimension({
- name: columnName,
- fromBinning: "by month",
- toBinning: bucketName,
- });
- } else {
- H.popover().findByText(columnName).click();
- }
-}
-
function verifyScalarValue(value) {
cy.findByTestId("scalar-value").should("have.text", value).and("be.visible");
}
-function verifyLineAreaBarChart({ xAxis, yAxis }) {
+function verifyLineChart({ yAxis }) {
H.echartsContainer().within(() => {
cy.findByText(yAxis).should("be.visible");
- cy.findByText(xAxis).should("be.visible");
});
+ cy.findByTestId("visualization-root").should(
+ "have.attr",
+ "data-viz-ui-name",
+ "Line",
+ );
+}
+
+function verifyMetricAboutTimeseries({ yAxis }) {
+ H.MetricPage.aboutPage().within(() => {
+ cy.findByRole("button", { name: "Select dimension: Created At" })
+ .should("be.visible")
+ .and("contain.text", "Created At");
+ cy.findByTestId("metric-value-preview").should("be.visible");
+ cy.findByTestId("visualization-root")
+ .should("be.visible")
+ .and("have.attr", "data-viz-ui-name", "Line");
+ H.echartsContainer().findByText(yAxis).should("be.visible");
+ });
+}
+
+function verifyMetricDefinitionChart({ yAxis }) {
+ H.MetricPage.definitionTab().click();
+ H.MetricPage.queryEditor().should("be.visible");
+ H.getNotebookStep("summarize").findByText(yAxis).should("be.visible");
+ cy.intercept("POST", "/api/dataset").as("dataset");
+ H.runButtonInOverlay().click();
+ cy.wait("@dataset");
+ verifyLineChart({ yAxis });
}
describe("scenarios > metrics > editing", () => {
@@ -184,14 +189,15 @@ describe("scenarios > metrics > editing", () => {
cy.visit(`/metric/${card.id}/query`),
);
H.MetricPage.queryEditor().should("be.visible");
- addBreakout({ tableName: "Product", columnName: "Created At" });
+ H.getNotebookStep("summarize").button("Count").click();
+ H.popover().within(() => {
+ cy.findByText("Sum of ...").click();
+ cy.findByText("Total").click();
+ });
H.MetricPage.saveButton().click();
H.MetricPage.saveButton().should("not.exist");
H.MetricPage.aboutTab().click();
- verifyLineAreaBarChart({
- xAxis: "Product → Created At: Month",
- yAxis: "Count",
- });
+ verifyMetricAboutTimeseries({ yAxis: "Sum of Total" });
});
it("should pin new metrics automatically", () => {
@@ -211,7 +217,7 @@ describe("scenarios > metrics > editing", () => {
cy.findByText("Sample Database").click();
cy.findByText("Orders").click();
});
- saveNewMetric();
+ saveNewMetric({ name: "Pinned metric" });
H.expectUnstructuredSnowplowEvent({
event: "metric_created",
@@ -224,7 +230,14 @@ describe("scenarios > metrics > editing", () => {
cy.findByTestId("pinned-items").within(() => {
cy.findByRole("heading", { name: "Metrics" }).should("be.visible");
- verifyScalarValue("18,760");
+ cy.findByText("Pinned metric")
+ .closest("a")
+ .within(() => {
+ cy.findByTestId("visualization-root")
+ .should("be.visible")
+ .and("have.attr", "data-viz-ui-name", "Line");
+ H.echartsContainer().should("be.visible");
+ });
});
});
@@ -238,7 +251,11 @@ describe("scenarios > metrics > editing", () => {
cy.visit(`/metric/${card.id}/query`),
);
H.MetricPage.queryEditor().should("be.visible");
- addBreakout({ tableName: "Product", columnName: "Created At" });
+ H.getNotebookStep("summarize").button("Count").click();
+ H.popover().within(() => {
+ cy.findByText("Sum of ...").click();
+ cy.findByText("Total").click();
+ });
H.MetricPage.cancelButton().click();
H.getNotebookStep("summarize").findByText("Count").should("be.visible");
});
@@ -253,12 +270,14 @@ describe("scenarios > metrics > editing", () => {
values: ["Gadget"],
});
saveNewMetric();
- verifyScalarValue("4,939");
+ verifyMetricAboutTimeseries({ yAxis: "Count" });
});
it("should not allow to create a multi-stage metric", () => {
startNewMetricWithSavedItem("Our analytics", "Orders Model");
- getActionButton("Summarize").should("not.exist");
+ H.MetricPage.queryEditor()
+ .findByRole("button", { name: "Summarize" })
+ .should("not.exist");
});
it("should allow to run the query from the metric empty state", () => {
@@ -266,7 +285,7 @@ describe("scenarios > metrics > editing", () => {
cy.intercept("POST", "/api/dataset").as("dataset");
H.runButtonInOverlay().click();
cy.wait("@dataset");
- verifyScalarValue("18,760");
+ verifyLineChart({ yAxis: "Count" });
});
});
@@ -286,7 +305,7 @@ describe("scenarios > metrics > editing", () => {
cy.button("Add filter").click();
});
saveNewMetric();
- verifyScalarValue("613");
+ verifyMetricAboutTimeseries({ yAxis: "Count" });
});
it("should not be possible to join a metric", () => {
@@ -337,7 +356,7 @@ describe("scenarios > metrics > editing", () => {
cy.findByText("Total2").click();
});
saveNewMetric();
- verifyScalarValue("755,310.84");
+ verifyMetricDefinitionChart({ yAxis: "Sum of Total2" });
cy.log("custom column from implicitly joined table");
startNewMetricWithTable("Sample Database", "Orders");
@@ -353,7 +372,7 @@ describe("scenarios > metrics > editing", () => {
cy.findByText("Price2").click();
});
saveNewMetric();
- verifyScalarValue("111.38");
+ verifyMetricDefinitionChart({ yAxis: "Average of Price2" });
});
});
@@ -365,12 +384,8 @@ describe("scenarios > metrics > editing", () => {
cy.findByText("Sum of ...").click();
cy.findByText("Total").click();
});
- addBreakout({ columnName: "Created At" });
saveNewMetric();
- verifyLineAreaBarChart({
- xAxis: "Created At: Month",
- yAxis: "Sum of Total",
- });
+ verifyMetricAboutTimeseries({ yAxis: "Sum of Total" });
});
});
@@ -396,7 +411,7 @@ describe("scenarios > metrics > editing", () => {
});
H.popover().button("Update").should("not.be.disabled").click();
saveNewMetric();
- verifyScalarValue("9,380");
+ verifyMetricAboutTimeseries({ yAxis: "Orders metric" });
});
it("should have metric-specific summarize step copy", () => {
@@ -407,18 +422,14 @@ describe("scenarios > metrics > editing", () => {
H.getNotebookStep("summarize").within(() => {
cy.findByText("Formula").should("be.visible");
- cy.findAllByText("Default time dimension")
- .filter(":visible")
- .should("have.length", 1);
+ cy.findByText("Default time dimension").should("not.exist");
});
cy.viewport(800, 600);
H.getNotebookStep("summarize").within(() => {
// We need the scroll because of the viewport change, the next findByText is technically off the screen without it
cy.findByText("Formula").should("be.visible").scrollIntoView({});
- cy.findAllByText("Default time dimension")
- .filter(":visible")
- .should("have.length", 1);
+ cy.findByText("Default time dimension").should("not.exist");
});
});
});
diff --git a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
index d9dbcf342a6..da6b3592765 100644
--- a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
+++ b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts
@@ -9,9 +9,17 @@ import {
ORDERS_MODEL_ID,
} from "e2e/support/cypress_sample_instance_data";
import type { StructuredQuestionDetails } from "e2e/support/helpers";
-
-const { ORDERS_ID, ORDERS, PRODUCTS_ID, PRODUCTS, ACCOUNTS_ID, FEEDBACK_ID } =
- SAMPLE_DATABASE;
+import type { ListMetricDimensionsResponse } from "metabase-types/api";
+
+const {
+ ORDERS_ID,
+ ORDERS,
+ PRODUCTS_ID,
+ PRODUCTS,
+ ACCOUNTS_ID,
+ FEEDBACK_ID,
+ PEOPLE_ID,
+} = SAMPLE_DATABASE;
type StructuredQuestionDetailsWithName = StructuredQuestionDetails & {
name: string;
@@ -317,6 +325,15 @@ const selectDimensionBreakout = (
}
};
+const getExpandedMetricAccordion = (metricName: string) => {
+ return H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: metricName })
+ .scrollIntoView()
+ .should("be.visible")
+ .and("have.attr", "aria-expanded", "true")
+ .parent();
+};
+
const showColumnLabels = () => {
H.MetricsViewer.getMetricControls()
.findByLabelText("Column label options")
@@ -487,6 +504,14 @@ describe("scenarios > metrics > explorer", () => {
cy.signInAsAdmin();
createMetrics(ALL_MODELS);
createTestMeasure();
+ cy.then(() => {
+ const ordersMetricId = createdMetricIds[ORDERS_SCALAR_METRIC.name];
+ seedMetricDimensions(ordersMetricId);
+ addConnectionDimension(ordersMetricId, "Product", "Category");
+ addConnectionDimension(ordersMetricId, "User", "Source");
+ addConnectionDimension(ordersMetricId, "User", "State");
+ addConnectionDimension(ordersMetricId, "User", "Birth Date");
+ });
H.snapshot(SNAPSHOT_NAME);
});
@@ -631,7 +656,7 @@ describe("scenarios > metrics > explorer", () => {
H.miniPicker().should("contain.text", "Test Measure");
});
- it("should not show me measures that live in tables I do not have permissions to see", () => {
+ it("should hide measures without data permissions and run readable metrics", () => {
cy.signIn("nodata");
H.MetricsViewer.goToViewer();
H.MetricsViewer.searchInput().type("Test Measure", {
@@ -640,12 +665,7 @@ describe("scenarios > metrics > explorer", () => {
H.miniPicker().should("contain.text", "No search results");
addMetric("Count of orders", { clearInput: true });
- cy.log(
- "even though we can see the metric, we don't have permissions to run the query",
- );
- cy.findByRole("heading", {
- name: /You do not have permissions to run this query/i,
- }).should("be.visible");
+ H.cartesianChartCircle().should("have.length.at.least", 1);
});
});
@@ -761,9 +781,7 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Breakout legend should be visible with Source values");
H.MetricsViewer.breakoutLegend().should("be.visible");
H.MetricsViewer.breakoutLegend().within(() => {
- cy.findByRole("heading", { name: "User → Source" }).should(
- "be.visible",
- );
+ cy.findByRole("heading", { name: "Source" }).should("be.visible");
cy.findByText("Twitter").should("be.visible");
cy.findByText("Facebook").should("be.visible");
cy.findByText("Organic").should("be.visible");
@@ -836,9 +854,7 @@ describe("scenarios > metrics > explorer", () => {
);
H.MetricsViewer.breakoutLegend().should("be.visible");
H.MetricsViewer.breakoutLegend().within(() => {
- cy.findByRole("heading", { name: "User → Source" }).should(
- "be.visible",
- );
+ cy.findByRole("heading", { name: "Source" }).should("be.visible");
});
cy.log("First pill should have single color (breakout removed)");
@@ -907,9 +923,7 @@ describe("scenarios > metrics > explorer", () => {
cy.log("Breakout legend should still be visible");
H.MetricsViewer.breakoutLegend().should("be.visible");
H.MetricsViewer.breakoutLegend().within(() => {
- cy.findByRole("heading", { name: "User → Source" }).should(
- "be.visible",
- );
+ cy.findByRole("heading", { name: "Source" }).should("be.visible");
});
cy.log("Newly added third pill should have single color (no breakout)");
@@ -1270,14 +1284,23 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.getMetricVisualization().should("be.visible");
});
- it("should open and close from the viewer controls", () => {
+ it("should show all curated dimensions for a standalone metric", () => {
H.MetricsViewer.getMetricVisualization().should("be.visible");
+ H.MetricsViewer.getColumnPickerButton()
+ .should("contain.text", "Time")
+ .and("not.contain.text", "Created At");
H.MetricsViewer.openDimensionPickerSidebar().within(() => {
cy.findByRole("heading", { name: "Break out" }).should("be.visible");
cy.findByLabelText("Search fields").should("be.visible");
- cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.findByText("Dimensions").should("be.visible");
+ cy.findByRole("button", { name: "See all" }).should("not.exist");
+ cy.findByRole("button", { name: "Created At" }).should("be.visible");
cy.findByRole("button", { name: "Category" }).should("be.visible");
+ cy.findByRole("button", { name: "Source" })
+ .scrollIntoView()
+ .should("be.visible");
+ cy.findByRole("button", { name: "No breakout" }).should("be.visible");
cy.findByRole("button", { name: "Totals" }).should("not.exist");
});
@@ -1332,7 +1355,17 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.assertVizType("Line");
- selectDimensionBreakout("State", { seeAll: true });
+ H.MetricsViewer.openDimensionPickerSidebar();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "See all" })
+ .click();
+ getExpandedMetricAccordion("Test Measure")
+ .findByRole("button", { name: "State" })
+ .scrollIntoView()
+ .should("be.visible")
+ .click();
+ H.MetricsViewer.closeDimensionPickerSidebar();
+ cy.wait("@dataset");
H.expectUnstructuredSnowplowEvent({
event: "metrics_viewer_dimension_selected",
});
@@ -1346,34 +1379,39 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.assertVizType("Line");
});
- it("should keep all fields available while selecting dimensions from See all", () => {
+ it("should replace the selected curated dimension", () => {
H.MetricsViewer.openDimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "See all" }).click();
- cy.findByRole("heading", { name: "All fields" }).should("be.visible");
- cy.findByRole("button", { name: "Address" }).should("be.visible");
- cy.findByRole("button", { name: "City" }).should("be.visible");
- cy.findByRole("button", { name: "Address" }).click();
+ cy.findByRole("button", { name: "Category" }).should("be.visible");
+ cy.findByRole("button", { name: "Source" }).should("be.visible");
+ cy.findByRole("button", { name: "Category" }).click();
});
cy.wait("@dataset");
H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "Address" })
+ cy.findByRole("button", { name: "Category" })
.scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" })
+ .should("be.visible")
+ .and("have.attr", "aria-pressed", "true");
+ cy.findByRole("button", { name: "Source" })
.scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" }).click();
+ .should("be.visible")
+ .and("have.attr", "aria-pressed", "false");
+ cy.findByRole("button", { name: "Source" }).click();
});
cy.wait("@dataset");
+ H.MetricsViewer.getColumnPickerButton()
+ .should("contain.text", "Source")
+ .and("not.contain.text", "Category");
H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("button", { name: "Address" })
+ cy.findByRole("button", { name: "Category" })
.scrollIntoView()
- .should("be.visible");
- cy.findByRole("button", { name: "City" })
+ .should("be.visible")
+ .and("have.attr", "aria-pressed", "false");
+ cy.findByRole("button", { name: "Source" })
.scrollIntoView()
- .should("be.visible");
+ .should("be.visible")
+ .and("have.attr", "aria-pressed", "true");
});
});
@@ -1390,13 +1428,13 @@ describe("scenarios > metrics > explorer", () => {
.findByRole("button", { name: "See all" })
.click();
- H.MetricsViewer.dimensionPickerSidebar().within(() => {
- cy.findByRole("heading", { name: "All fields" }).should("be.visible");
- cy.findAllByRole("button", { name: "Rating" }).should(
- "have.length.at.least",
- 1,
- );
- });
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("heading", { name: "All fields" })
+ .should("be.visible");
+ getExpandedMetricAccordion("Count of feedback")
+ .findByRole("button", { name: "Rating" })
+ .scrollIntoView()
+ .should("be.visible");
});
it("should configure per-metric dimensions for a shared category", () => {
@@ -1478,7 +1516,7 @@ describe("scenarios > metrics > explorer", () => {
});
it("should serialize only the selected dimension breakout in the URL", () => {
- selectDimensionBreakout("State", { seeAll: true });
+ selectDimensionBreakout("State");
selectDimensionBreakout("Category");
getMetricsViewerUrlState().then((state) => {
@@ -1529,12 +1567,10 @@ describe("scenarios > metrics > explorer", () => {
cy.findByRole("button", { name: "Count of products" })
.scrollIntoView()
.should("be.visible")
- .and("have.attr", "aria-expanded", "false")
- .click();
- cy.findAllByRole("button", { name: "Category" }).should(
- "have.length.at.least",
- 1,
- );
+ .and("have.attr", "aria-expanded", "true");
+ cy.findAllByRole("button", { name: "Category" })
+ .should("be.visible")
+ .and("have.length", 2);
});
cy.log(
@@ -1662,7 +1698,7 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.getAllMetricVisualizations().should("have.length", 1);
cy.log("add a breakout to create multiple series");
- selectDimensionBreakout("Time", { waitForDataset: false });
+ selectDimensionBreakout("Created At", { waitForDataset: false });
selectBreakout("Count of orders", "Source");
cy.log("line supports multiple series, so should remain unified");
@@ -1683,7 +1719,7 @@ describe("scenarios > metrics > explorer", () => {
addMetric("Count of orders");
});
- it("should apply a categorical filter to a metric", () => {
+ it("should apply a categorical filter to a metric (UXW-4849)", () => {
selectBreakout("Count of orders", "Category");
H.MetricsViewer.breakoutLegend()
.should("contain.text", "Doohickey")
@@ -1702,7 +1738,9 @@ describe("scenarios > metrics > explorer", () => {
.should("have.length", 1)
.should("contain.text", "Doohickey")
.should("contain.text", "Gadget")
- .should("contain.text", "Category");
+ .should("contain.text", "Category is:")
+ .should("not.contain.text", "Product")
+ .should("not.contain.text", "→");
H.expectUnstructuredSnowplowEvent({
event: "metrics_viewer_filter_added",
@@ -1825,7 +1863,7 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.getAllFilterPills().should("have.length", 0);
});
- it("should allow me to apply filters to each metric individually", () => {
+ it("should allow me to apply filters to each metric individually (UXW-4849)", () => {
addMetric("Count of products");
selectDimensionBreakout("Category");
H.MetricsViewer.changeVizType("line");
@@ -1836,7 +1874,14 @@ describe("scenarios > metrics > explorer", () => {
H.MetricsViewer.getFilterButton().click();
H.popover().within(() => {
- cy.button(/count of orders/i).should("be.visible");
+ cy.button(/count of orders/i)
+ .should("be.visible")
+ .click();
+ cy.findByText("Category").should("be.visible");
+ cy.findByText("Orders").should("not.exist");
+ cy.findByText("Product").should("not.exist");
+ cy.findByText("User").should("not.exist");
+ cy.button(/count of orders/i).click();
cy.button(/count of products/i).click();
cy.findByText("Category").click();
});
@@ -2364,8 +2409,416 @@ describe("scenarios > metrics > explorer > BigInt filters", () => {
});
});
+describe("scenarios > metrics > explorer > shared dimensions", () => {
+ const SHARED_DIMENSIONS_SNAPSHOT = "shared-dimensions-snapshot";
+
+ const PEOPLE_SCALAR_METRIC: StructuredQuestionDetailsWithName = {
+ name: "Count of people",
+ type: "metric",
+ description: "A metric",
+ query: {
+ "source-table": PEOPLE_ID,
+ aggregation: [["count"]],
+ },
+ display: "scalar",
+ };
+
+ const createSeededMetric = (details: StructuredQuestionDetailsWithName) =>
+ H.createQuestion(details).then(({ body }) => {
+ expect(body.id).to.be.a("number");
+ if (typeof body.id === "number") {
+ return seedMetricDimensions(body.id);
+ }
+ });
+
+ const assertSerializedDimensionBreakout = (
+ check: (
+ dimensionBreakout: NonNullable<CompactMetricsViewerUrlState["t"]>[0],
+ ) => void,
+ ) => {
+ cy.location("hash").should((hash) => {
+ const [dimensionBreakout] = decodeMetricsViewerUrlHash(hash).t ?? [];
+ expect(dimensionBreakout, "a serialized dimension breakout").to.exist;
+ if (dimensionBreakout) {
+ check(dimensionBreakout);
+ }
+ });
+ };
+
+ const metricIds: Record<string, number> = {};
+
+ const createFixtureMetric = (
+ name: string,
+ details: StructuredQuestionDetailsWithName,
+ curate?: (metricId: number) => void,
+ ) =>
+ createSeededMetric({ ...details, name }).then((metricId) => {
+ metricIds[name] = metricId;
+ curate?.(metricId);
+ });
+
+ // The formula is built through the URL state instead of the search picker:
+ // fixture metrics share the app db with the sample content, so the picker's
+ // top suggestions are not guaranteed to include them.
+ let viewerVisitCount = 0;
+
+ const visitViewerWithMetrics = (names: string[]) => {
+ const state = JSON.stringify({
+ f: names.map((name) => ({ t: "metric", i: metricIds[name] })),
+ });
+ const hash = btoa(state)
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+ // A unique query string forces a full document load; visiting only with a
+ // changed hash would hand the new state to the previous test's stale app.
+ viewerVisitCount += 1;
+ cy.visit(`/explore?visit=${viewerVisitCount}#${hash}`);
+ H.MetricsViewer.searchBarPills().should("have.length", names.length);
+ H.MetricsViewer.getAllMetricVisualizations().should(
+ "have.length.at.least",
+ 1,
+ );
+ };
+
+ before(() => {
+ H.restore();
+ cy.signInAsAdmin();
+
+ createFixtureMetric(
+ "Orders with product category",
+ ORDERS_SCALAR_METRIC,
+ (metricId) =>
+ addConnectionDimension(
+ metricId,
+ "Product",
+ "Category",
+ "Product Category",
+ ),
+ );
+ createFixtureMetric("Plain products", PRODUCTS_SCALAR_METRIC);
+ createFixtureMetric(
+ "People with renamed source",
+ PEOPLE_SCALAR_METRIC,
+ (metricId) => renameCuratedDimension(metricId, "Source", "Category"),
+ );
+ createFixtureMetric("Accounts by country", ACCOUNTS_SCALAR_METRIC);
+ createFixtureMetric("People by state", PEOPLE_SCALAR_METRIC);
+ createFixtureMetric(
+ "Orders with user state",
+ ORDERS_SCALAR_METRIC,
+ (metricId) => addConnectionDimension(metricId, "User", "State"),
+ );
+ createFixtureMetric(
+ "Orders with user source",
+ ORDERS_SCALAR_METRIC,
+ (metricId) =>
+ addConnectionDimension(metricId, "User", "Source", "Category"),
+ );
+ createFixtureMetric("Plain orders", ORDERS_SCALAR_METRIC);
+ createFixtureMetric(
+ "Orders with default category",
+ ORDERS_SCALAR_METRIC,
+ (metricId) => {
+ addConnectionDimension(
+ metricId,
+ "Product",
+ "Category",
+ "Product Category",
+ );
+ setDefaultCuratedDimension(metricId, "Product Category");
+ },
+ );
+
+ H.snapshot(SHARED_DIMENSIONS_SNAPSHOT);
+ });
+
+ beforeEach(() => {
+ H.restore(SHARED_DIMENSIONS_SNAPSHOT);
+ cy.signInAsAdmin();
+ interceptDatasetQuery();
+ });
+
+ describe("Shared dimension matching", () => {
+ it("shows every dimension shared by repeated metric slots", () => {
+ visitViewerWithMetrics(["Plain products", "Plain products"]);
+
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByText("Dimensions").should("be.visible");
+ cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.findByRole("button", { name: "Category" }).should("be.visible");
+ cy.findByRole("button", { name: "Title" }).should("be.visible");
+ cy.findByRole("button", { name: "Vendor" }).should("be.visible");
+ cy.findByRole("button", { name: "Price" }).should("be.visible");
+ cy.findByRole("button", { name: "Rating" }).should("be.visible");
+ cy.findByRole("button", { name: "Created At" }).should("not.exist");
+ });
+
+ selectDimensionBreakout("Vendor");
+ H.MetricsViewer.getMetricControls()
+ .findByRole("button", { name: "Change column" })
+ .should("contain.text", "Vendor");
+ });
+
+ it("shares dimensions with the same source column under the first metric's dimension name", () => {
+ visitViewerWithMetrics([
+ "Orders with product category",
+ "Plain products",
+ ]);
+
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByText("Shared dimensions").should("be.visible");
+ cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.log(
+ "Orders' added connection dimension and Products' own Category read the same column, so they merge into one option",
+ );
+ cy.findByRole("button", { name: "Category" }).should("not.exist");
+ cy.findByRole("button", { name: "Product Category" }).click();
+ });
+ cy.wait(["@dataset", "@dataset"]);
+
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(dimensionBreakout.t).to.equal("category");
+ expect(dimensionBreakout.D).to.have.length(2);
+ expect(
+ dimensionBreakout.D?.every((entry) => entry.d != null),
+ "every metric mapped",
+ ).to.be.true;
+ });
+ });
+
+ it("does not share same-named dimensions from different source columns", () => {
+ visitViewerWithMetrics(["People with renamed source", "Plain products"]);
+
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.log(
+ "People's renamed Source and Products' Category share a name but not a source column",
+ );
+ cy.findByRole("button", { name: "Category" }).should("not.exist");
+ });
+ });
+
+ it("does not mix country and state geo dimensions", () => {
+ visitViewerWithMetrics(["Accounts by country", "People by state"]);
+
+ H.MetricsViewer.openDimensionPickerSidebar().within(() => {
+ cy.findByRole("button", { name: "Time" }).should("be.visible");
+ cy.findByRole("button", { name: "Country" }).should("not.exist");
+ cy.findByRole("button", { name: "State" }).should("not.exist");
+ });
+ });
+
+ it("offers a State option when every metric has a state dimension", () => {
+ visitViewerWithMetrics(["People by state", "Orders with user state"]);
+
+ selectDimensionBreakout("State");
+
+ H.MetricsViewer.assertAllVizTypes("Map", 2);
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(dimensionBreakout.t).to.equal("geo");
+ expect(dimensionBreakout.D).to.have.length(2);
+ });
+ });
+
+ it("re-maps other metrics by dimension name when switching breakout type from All fields", () => {
+ visitViewerWithMetrics(["Orders with user source", "Plain products"]);
+
+ getCuratedDimensionId(
+ metricIds["Orders with user source"],
+ "Category",
+ ).as("ordersCategoryId");
+ getCuratedDimensionId(metricIds["Plain products"], "Category").as(
+ "productsCategoryId",
+ );
+ getCuratedDimensionId(metricIds["Plain products"], "Vendor").as(
+ "productsVendorId",
+ );
+
+ cy.log("switch from the default Time breakout to a category dimension");
+ H.MetricsViewer.openDimensionPickerSidebar();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "See all" })
+ .click();
+ getExpandedMetricAccordion("Orders with user source")
+ .findByRole("button", { name: "Category" })
+ .should("be.visible")
+ .click();
+ cy.wait(["@dataset", "@dataset"]);
+
+ cy.log(
+ "Products maps to its own Category by name, even though Title comes first in its curated list",
+ );
+ cy.then(function () {
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(dimensionBreakout.t).to.equal("category");
+ expect(
+ dimensionBreakout.D?.find((entry) => entry.i === 0)?.d,
+ ).to.equal(this.ordersCategoryId);
+ expect(
+ dimensionBreakout.D?.find((entry) => entry.i === 1)?.d,
+ ).to.equal(this.productsCategoryId);
+ });
+ });
+
+ cy.log("a same-type pick under one metric changes only that metric");
+ getExpandedMetricAccordion("Plain products")
+ .findByRole("button", { name: "Vendor" })
+ .should("be.visible")
+ .click();
+ cy.wait("@dataset");
+
+ cy.then(function () {
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(
+ dimensionBreakout.D?.find((entry) => entry.i === 0)?.d,
+ ).to.equal(this.ordersCategoryId);
+ expect(
+ dimensionBreakout.D?.find((entry) => entry.i === 1)?.d,
+ ).to.equal(this.productsVendorId);
+ });
+ });
+ H.MetricsViewer.getMetricControls()
+ .findByRole("button", { name: "Change column" })
+ .should("contain.text", "Category");
+ });
+
+ it("disables metrics without a dimension of the picked type", () => {
+ visitViewerWithMetrics(["Plain orders", "Plain products"]);
+
+ H.MetricsViewer.openDimensionPickerSidebar();
+ H.MetricsViewer.dimensionPickerSidebar()
+ .findByRole("button", { name: "See all" })
+ .click();
+ getExpandedMetricAccordion("Plain products")
+ .findByRole("button", { name: "Category" })
+ .should("be.visible")
+ .click();
+ cy.wait("@dataset");
+
+ cy.log("Orders has no category dimensions, so it is excluded");
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(dimensionBreakout.t).to.equal("category");
+ expect(dimensionBreakout.D?.find((entry) => entry.i === 0)?.d).to.be
+ .undefined;
+ expect(dimensionBreakout.D?.find((entry) => entry.i === 1)?.d).to.not.be
+ .undefined;
+ });
+ verifyMetricCount(2);
+ H.echartsContainer().should("be.visible");
+ });
+ });
+
+ describe("Initial dimension breakout", () => {
+ it("selects the curated default dimension when landing from the metric's Explore button", () => {
+ getCuratedDimensionId(
+ metricIds["Orders with default category"],
+ "Product Category",
+ ).as("defaultDimensionId");
+
+ H.visitMetric(metricIds["Orders with default category"]);
+ H.MetricPage.exploreLink().click();
+ H.MetricsViewer.searchBarPills().should("have.length", 1);
+ cy.wait("@dataset");
+
+ cy.log("the curated default wins over the usual time-first breakout");
+ H.echartsContainer().findByText("Doohickey").should("be.visible");
+ cy.then(function () {
+ assertSerializedDimensionBreakout((dimensionBreakout) => {
+ expect(dimensionBreakout.t).to.equal("category");
+ expect(
+ dimensionBreakout.D?.find((entry) => entry.i === 0)?.d,
+ ).to.equal(this.defaultDimensionId);
+ });
+ });
+ });
+ });
+});
+
+const createdMetricIds: Record<string, number> = {};
+
function createMetrics(metrics: StructuredQuestionDetailsWithName[]) {
- metrics.forEach((metric) => H.createQuestion(metric));
+ metrics.forEach((metric) =>
+ H.createQuestion(metric).then(({ body }) => {
+ createdMetricIds[metric.name] = body.id;
+ }),
+ );
+}
+
+// Reading a metric seeds its curated dimension list with the self-table
+// columns.
+function seedMetricDimensions(metricId: number) {
+ return cy.request("GET", `/api/metric/${metricId}`).then(() => metricId);
+}
+
+function addConnectionDimension(
+ metricId: number,
+ groupName: string,
+ dimensionName: string,
+ displayName = dimensionName,
+) {
+ return cy
+ .request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension?with-addable=true`,
+ )
+ .then(({ body }) => {
+ const group = body.addable.find(
+ (addableGroup) => addableGroup.group.display_name === groupName,
+ );
+ const dimension = group?.dimensions.find(
+ (addableDimension) => addableDimension.display_name === dimensionName,
+ );
+ expect(dimension, `addable dimension ${groupName} → ${dimensionName}`).to
+ .exist;
+ cy.request("POST", `/api/metric/${metricId}/dimension/add`, {
+ dimensions: [{ ...dimension, display_name: displayName }],
+ });
+ });
+}
+
+function renameCuratedDimension(
+ metricId: number,
+ dimensionName: string,
+ displayName: string,
+) {
+ return cy
+ .request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension`,
+ )
+ .then(({ body }) => {
+ const dimension = body.added.find(
+ (addedDimension) => addedDimension.display_name === dimensionName,
+ );
+ expect(dimension, `curated dimension ${dimensionName}`).to.exist;
+ cy.request("POST", `/api/metric/${metricId}/dimension/${dimension?.id}`, {
+ display_name: displayName,
+ });
+ });
+}
+
+function getCuratedDimensionId(metricId: number, dimensionName: string) {
+ return cy
+ .request<ListMetricDimensionsResponse>(
+ "GET",
+ `/api/metric/${metricId}/dimension`,
+ )
+ .then(
+ ({ body }) =>
+ body.added.find(
+ (addedDimension) => addedDimension.display_name === dimensionName,
+ )?.id,
+ );
+}
+
+function setDefaultCuratedDimension(metricId: number, dimensionName: string) {
+ return getCuratedDimensionId(metricId, dimensionName).then((dimensionId) => {
+ expect(dimensionId, `curated dimension ${dimensionName}`).to.exist;
+ cy.request("POST", `/api/metric/${metricId}/dimension/set-default`, {
+ dimension_id: dimensionId,
+ });
+ });
}
function createTestMeasure(
diff --git a/e2e/test/scenarios/metrics/metrics-question.cy.spec.js b/e2e/test/scenarios/metrics/metrics-question.cy.spec.js
index a24c8257fa0..05ca0415fd4 100644
--- a/e2e/test/scenarios/metrics/metrics-question.cy.spec.js
+++ b/e2e/test/scenarios/metrics/metrics-question.cy.spec.js
@@ -174,13 +174,14 @@ describe("scenarios > metrics > question", () => {
});
it("should be able to view a table-based metric without data access", () => {
+ cy.intercept("POST", "/api/metric/dataset").as("metricDataset");
H.createQuestion(ORDERS_SCALAR_METRIC).then(({ body: card }) => {
cy.signInAsSandboxedUser();
H.visitMetric(card.id);
});
- cy.findByTestId("scalar-container")
- .findByText("18,760")
- .should("be.visible");
+ cy.wait("@metricDataset").its("response.statusCode").should("equal", 202);
+ cy.findByTestId("metric-value-preview").should("be.visible");
+ H.echartsContainer().should("be.visible");
H.MetricPage.aboutPage().within(() => {
cy.button(/Filter/).should("not.exist");
cy.button(/Summarize/).should("not.exist");
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
index cc1a0045274..e988c1a4a4c 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
@@ -48,6 +48,11 @@
(upstream-deps:native-query query)
(upstream-deps:mbql-query query)))
+(mu/defn- upstream-deps:dimension-mappings :- ::deps.schema/upstream-deps
+ "Table dependencies of `dimension-mappings`, gathered from their `:table-id`s."
+ [dimension-mappings]
+ {:table (into #{} (keep :table-id) dimension-mappings)})
+
(mu/defn- upstream-deps:python-transform :- ::deps.schema/upstream-deps
[{{tables :source-tables} :source :as _py-transform}
:- [:map [:source-tables {:optional true} [:sequential ::transforms-base.u/source-table-entry]]]]
@@ -72,13 +77,15 @@
;;; ------------------------------------------------ defmethods ------------------------------------------------
(defmethod calculate-deps* :card
- [_ {query :dataset_query :as card}]
+ [_ {query :dataset_query, dimension-mappings :dimension_mappings :as card}]
{:pre [(some? query)]}
- (let [query-deps (upstream-deps:query query)
+ (let [base-deps (merge-with into
+ (upstream-deps:query query)
+ (upstream-deps:dimension-mappings dimension-mappings))
param-card-ids (keep #(-> % :values_source_config :card_id) (:parameters card))]
(reduce (fn [deps card-id]
(update deps :card (fnil conj #{}) card-id))
- query-deps
+ base-deps
param-card-ids)))
(defmethod calculate-deps* :transform
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
index ad60e65e452..ba65e704aea 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
@@ -32,6 +32,7 @@
(derive ::card-deps :metabase/event)
(derive :event/card-create ::card-deps)
(derive :event/card-update ::card-deps)
+(derive :event/metric-dimensions-update ::card-deps)
(methodical/defmethod events/publish-event! ::card-deps
[_ {:keys [object]}]
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj
index 4968e0b55a9..60a1d03cc54 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj
@@ -1,6 +1,6 @@
(ns metabase-enterprise.sandbox.api.metric
"Enterprise sandbox filtering for metric dimensions.
- Overrides `metabase.metrics.permissions/sandbox-restricted-fields` to restrict
+ Overrides `metabase.permissions.metric/sandbox-restricted-fields` to restrict
dimensions from sandboxed tables to only fields in the sandbox source card."
(:require
[metabase.permissions.core :as perms]
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
index d696d4316b4..763a02ff87a 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
@@ -66,6 +66,27 @@
:table #{checkins-id venues-id users-id}}
(calculation/calculate-deps :card card))))))
+(deftest ^:parallel upstream-deps-metric-dimension-mappings-test
+ (testing "a metric v2's dimension mappings contribute their columns' tables as dependencies, even
+ when the base query doesn't reference them"
+ (let [mp (mt/metadata-provider)
+ venues-id (mt/id :venues)
+ categories-id (mt/id :categories)
+ base-query (-> (lib/query mp (lib.metadata/table mp venues-id))
+ (lib/aggregate (lib/count)))]
+ (mt/with-temp [:model/Card metric {:type :metric
+ :dataset_query base-query
+ :dimension_mappings [{:type :table
+ :dimension-id "550e8400-e29b-41d4-a716-446655440000"
+ :table-id categories-id
+ :target [:field {} (mt/id :categories :name)]}]}]
+ (is (= {:card #{}
+ :measure #{}
+ :segment #{}
+ :table #{venues-id categories-id}}
+ (calculation/calculate-deps :card metric))
+ "the mapped column's table (categories) is a dependency alongside the query's own table (venues)")))))
+
(deftest ^:parallel upstream-deps-card-implicit-join-filter-test
(let [mp (mt/metadata-provider)
checkins-id (mt/id :checkins)
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
index 44c53e71219..7ae19f95bdb 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
@@ -254,6 +254,28 @@
(events/publish-event! :event/card-update {:object card :previous-object card :user-id api/*current-user-id*})
(assert-stale :card card-id)))))))
+(deftest metric-dimensions-update-marks-stale-and-includes-mapped-table-test
+ (testing ":event/metric-dimensions-update marks the metric card stale and recomputes deps, including mapped-dimension tables"
+ (run-with-dependencies-setup!
+ (fn [mp]
+ (let [base (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count)))]
+ (mt/with-temp [:model/Card {card-id :id} {:type :metric
+ :dataset_query base
+ :dimension_mappings [{:type :table
+ :dimension-id "550e8400-e29b-41d4-a716-446655440000"
+ :table-id (mt/id :categories)
+ :target [:field {} (mt/id :categories :name)]}]}]
+ (events/publish-event! :event/metric-dimensions-update {:object {:id card-id}})
+ (assert-stale :card card-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (t2/exists? :model/Dependency :from_entity_type :card :from_entity_id card-id
+ :to_entity_type :table :to_entity_id (mt/id :categories))
+ "the mapped dimension's table becomes a dependency")
+ (is (t2/exists? :model/Dependency :from_entity_type :card :from_entity_id card-id
+ :to_entity_type :table :to_entity_id (mt/id :venues))
+ "the query's own table remains a dependency")))))))
+
(deftest snippet-marks-stale-on-create-update-test
(testing "Snippet create/update events mark the entity stale in dependency_status"
(run-with-dependencies-setup!
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
index 4ee57c0fef7..c975bc2adb3 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
@@ -127,6 +127,4 @@
(let [dims (metric-dimensions :rasta (:id metric))
groups (dimension-group-names dims)]
(testing "dimensions from the sandboxed Venues table should be blocked"
- (is (not (contains? groups "Venues"))))
- (testing "dimensions from non-sandboxed FK-joined tables are still visible"
- (is (contains? groups "Category"))))))))))
+ (is (not (contains? groups "Venues")))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj
new file mode 100644
index 00000000000..3a37b18a1b2
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj
@@ -0,0 +1,180 @@
+(ns metabase-enterprise.serialization.v2.metric-dimensions-test
+ (:require
+ [clojure.test :refer :all]
+ [medley.core :as m]
+ [metabase-enterprise.serialization.test-util :as ts]
+ [metabase-enterprise.serialization.v2.extract :as serdes.extract]
+ [metabase-enterprise.serialization.v2.ingest :as serdes.ingest]
+ [metabase-enterprise.serialization.v2.load :as serdes.load]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.metrics.core :as metrics]
+ [metabase.models.serialization :as serdes]
+ [metabase.search.core :as search]
+ [metabase.test :as mt]
+ [metabase.warehouses.models.database :as models.database]
+ [toucan2.core :as t2]))
+
+(use-fixtures :each (fn [thunk]
+ (mt/with-dynamic-fn-redefs [search/reindex! (constantly nil)
+ models.database/assert-not-h2! (constantly nil)]
+ (binding [models.database/*include-h2-in-extract?* true]
+ (thunk)))))
+
+(def ^:private dim-a-id "11111111-1111-4111-8111-111111111111")
+(def ^:private dim-b-id "22222222-2222-4222-8222-222222222222")
+
+(defn- no-labels [path]
+ (mapv #(dissoc % :label) path))
+
+(defn- ingestion-in-memory [extractions]
+ (let [mapped (into {} (map (juxt (comp no-labels serdes/path) identity)) extractions)]
+ (reify
+ serdes.ingest/Ingestable
+ (ingest-list [_]
+ (keys mapped))
+ (ingest-one [_ path]
+ (get mapped (no-labels path)))
+ (ingest-errors [_]
+ []))))
+
+(defn- by-model [entities model-name]
+ (filter #(-> % :serdes/meta last :model (= model-name)) entities))
+
+(defn- metric-query [db-id table-id field-id]
+ (let [metadata-provider (lib-be/application-database-metadata-provider db-id)
+ table (lib.metadata/table metadata-provider table-id)
+ query (lib/query metadata-provider table)
+ field (lib.metadata/field metadata-provider field-id)]
+ (lib/aggregate query (lib/sum field))))
+
+(defn- metric-dimensions [category-field-id title-field-id]
+ [{:id dim-a-id
+ :name "CATEGORY"
+ :display-name "Category"
+ :effective-type :type/Text
+ :status :status/active
+ :default true
+ :sources [{:type :field, :field-id category-field-id}]}
+ {:id dim-b-id
+ :name "TITLE"
+ :display-name "Title"
+ :effective-type :type/Text
+ :status :status/active
+ :sources [{:type :field, :field-id title-field-id}]}])
+
+(defn- metric-dimension-mappings
+ [sales-table-id products-table-id category-field-id title-field-id product-fk-id]
+ [{:type :table
+ :table-id sales-table-id
+ :dimension-id dim-a-id
+ :target [:field {:lib/uuid "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"} category-field-id]}
+ {:type :table
+ :table-id products-table-id
+ :dimension-id dim-b-id
+ :target [:field {:lib/uuid "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
+ :source-field product-fk-id}
+ title-field-id]}])
+
+(defn- create-source-metric! []
+ (let [collection (ts/create! :model/Collection :name "Metrics")
+ database (ts/create! :model/Database :name "metric-db")
+ sales (ts/create! :model/Table :name "sales" :db_id (:id database))
+ products (ts/create! :model/Table :name "products" :db_id (:id database))
+ amount (ts/create! :model/Field :name "amount" :table_id (:id sales))
+ category (ts/create! :model/Field :name "category" :table_id (:id sales))
+ product-fk (ts/create! :model/Field :name "product_id" :table_id (:id sales))
+ title (ts/create! :model/Field :name "title" :table_id (:id products))
+ user (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]")
+ card (ts/create! :model/Card
+ :name "Total Amount"
+ :type :metric
+ :database_id (:id database)
+ :table_id (:id sales)
+ :collection_id (:id collection)
+ :creator_id (:id user)
+ :dataset_query (metric-query (:id database) (:id sales) (:id amount))
+ :dimensions (metric-dimensions (:id category) (:id title))
+ :dimension_mappings (metric-dimension-mappings
+ (:id sales) (:id products)
+ (:id category) (:id title) (:id product-fk)))]
+ {:sales sales, :category category, :title title, :card card}))
+
+(defn- assert-portable-extraction! [serialized]
+ (let [card (m/find-first #(= "Total Amount" (:name %)) (by-model serialized "Card"))]
+ (is (=? [{:id dim-a-id :sources [{:field-id ["metric-db" nil "sales" "category"]}]}
+ {:id dim-b-id :sources [{:field-id ["metric-db" nil "products" "title"]}]}]
+ (:dimensions card)))
+ (is (=? [{:dimension-id dim-a-id
+ :table-id ["metric-db" nil "sales"]
+ :target [:field {} ["metric-db" nil "sales" "category"]]}
+ {:dimension-id dim-b-id
+ :table-id ["metric-db" nil "products"]
+ :target [:field {:source-field ["metric-db" nil "sales" "product_id"]}
+ ["metric-db" nil "products" "title"]]}]
+ (:dimension_mappings card)))
+ (is (contains? (metrics/dimension-mappings-deps (:dimension_mappings card))
+ [{:model "Database" :id "metric-db"}]))
+ (is (contains? (serdes/deserialization-dependencies card)
+ [{:model "Database" :id "metric-db"}]))))
+
+(defn- prepare-destination! []
+ (let [other-db (ts/create! :model/Database :name "other-db")
+ other-table (ts/create! :model/Table :name "junk" :db_id (:id other-db))]
+ (doseq [i (range 6)]
+ (ts/create! :model/Field :name (str "junk-field-" i) :table_id (:id other-table)))
+ (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]")))
+
+(defn- assert-remapped-import! [source]
+ (let [sales (t2/select-one :model/Table :name "sales")
+ products (t2/select-one :model/Table :name "products")
+ category (t2/select-one :model/Field :table_id (:id sales) :name "category")
+ product-fk (t2/select-one :model/Field :table_id (:id sales) :name "product_id")
+ title (t2/select-one :model/Field :table_id (:id products) :name "title")
+ card (t2/select-one :model/Card :name "Total Amount")]
+ (is (not= (-> source :sales :id) (:id sales)))
+ (is (not= (-> source :category :id) (:id category)))
+ (is (not= (-> source :title :id) (:id title)))
+ (is (=? [{:id dim-a-id :sources [{:field-id (:id category)}]}
+ {:id dim-b-id :sources [{:field-id (:id title)}]}]
+ (:dimensions card)))
+ (is (=? [{:dimension-id dim-a-id
+ :table-id (:id sales)
+ :target [:field {} (:id category)]}
+ {:dimension-id dim-b-id
+ :table-id (:id products)
+ :target [:field {:source-field (:id product-fk)} (:id title)]}]
+ (:dimension_mappings card)))
+ (is (= [dim-a-id] (into [] (comp (filter :default) (map :id)) (:dimensions card))))))
+
+(deftest metric-v2-dimensions-test
+ (testing "curated metric dimensions and mappings are portable"
+ (ts/with-dbs [source-db dest-db]
+ (let [source (ts/with-db source-db (create-source-metric!))
+ serialized (ts/with-db source-db (into [] (serdes.extract/extract {})))]
+ (assert-portable-extraction! serialized)
+ (ts/with-db dest-db
+ (prepare-destination!)
+ (serdes.load/load-metabase! (ingestion-in-memory serialized))
+ (assert-remapped-import! source))))))
+
+(deftest metric-v2-dimensions-deletion-propagates-test
+ (testing "deleting a curated dimension on the source deletes it on the destination after import"
+ (ts/with-dbs [source-db dest-db]
+ (let [source (ts/with-db source-db (create-source-metric!))
+ extract-source #(ts/with-db source-db (into [] (serdes.extract/extract {})))]
+ (ts/with-db dest-db
+ (prepare-destination!)
+ (serdes.load/load-metabase! (ingestion-in-memory (extract-source))))
+ (ts/with-db source-db
+ (t2/update! :model/Card (-> source :card :id)
+ {:dimensions (filterv #(= dim-a-id (:id %))
+ (-> source :card :dimensions))
+ :dimension_mappings (filterv #(= dim-a-id (:dimension-id %))
+ (-> source :card :dimension_mappings))}))
+ (ts/with-db dest-db
+ (serdes.load/load-metabase! (ingestion-in-memory (extract-source)))
+ (let [card (t2/select-one :model/Card :name "Total Amount")]
+ (is (= [dim-a-id] (mapv :id (:dimensions card))))
+ (is (= [dim-a-id] (mapv :dimension-id (:dimension_mappings card))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/DataStudioMetricDimensionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/DataStudioMetricDimensionsPage.tsx
new file mode 100644
index 00000000000..f40978d5681
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/DataStudioMetricDimensionsPage.tsx
@@ -0,0 +1,15 @@
+import { MetricDimensionsPage } from "metabase/metrics/pages/MetricDimensionsPage";
+
+import { DataStudioMetricBreadcrumbs } from "../../components/DataStudioMetricBreadcrumbs";
+import { dataStudioMetricUrls } from "../../urls";
+
+export function DataStudioMetricDimensionsPage() {
+ return (
+ <MetricDimensionsPage
+ urls={dataStudioMetricUrls}
+ showAppSwitcher
+ showDataStudioLink={false}
+ renderBreadcrumbs={(card) => <DataStudioMetricBreadcrumbs card={card} />}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/index.ts
new file mode 100644
index 00000000000..5cbde0288d3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricDimensionsPage/index.ts
@@ -0,0 +1 @@
+export { DataStudioMetricDimensionsPage } from "./DataStudioMetricDimensionsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx
index ee315071755..3f1f2a45e6c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx
@@ -3,6 +3,7 @@ import { Route } from "metabase/router";
import { DataStudioMetricAboutPage } from "./pages/DataStudioMetricAboutPage";
import { DataStudioMetricDependenciesPage } from "./pages/DataStudioMetricDependenciesPage";
+import { DataStudioMetricDimensionsPage } from "./pages/DataStudioMetricDimensionsPage";
import { DataStudioMetricHistoryPage } from "./pages/DataStudioMetricHistoryPage";
import { DataStudioMetricOverviewPage } from "./pages/DataStudioMetricOverviewPage";
import { DataStudioMetricQueryPage } from "./pages/DataStudioMetricQueryPage";
@@ -17,6 +18,10 @@ export function getDataStudioMetricRoutes() {
path=":cardId/overview"
element={<DataStudioMetricOverviewPage />}
/>
+ <Route
+ path=":cardId/dimensions"
+ element={<DataStudioMetricDimensionsPage />}
+ />
<Route path=":cardId/query" element={<DataStudioMetricQueryPage />} />
{PLUGIN_DEPENDENCIES.isEnabled && (
<Route
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts
index 051b9af7585..fdaf484acb6 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts
@@ -5,6 +5,7 @@ export const dataStudioMetricUrls: MetricUrls = {
about: Urls.dataStudioMetric,
overview: Urls.dataStudioMetricOverview,
query: Urls.dataStudioMetricQuery,
+ dimensions: Urls.dataStudioMetricDimensions,
dependencies: Urls.dataStudioMetricDependencies,
history: Urls.dataStudioMetricHistory,
database: (databaseId) => Urls.dataStudioData({ databaseId }),
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Breakout/BreakoutPicker/BreakoutPicker.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Breakout/BreakoutPicker/BreakoutPicker.tsx
index ca92a8805cd..eb668c7a720 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Breakout/BreakoutPicker/BreakoutPicker.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/Breakout/BreakoutPicker/BreakoutPicker.tsx
@@ -53,7 +53,6 @@ export const BreakoutPickerInner = ({
breakoutItem?.updateBreakout(column)
}
onClose={() => onClose?.()}
- isMetric={false}
/>
</Stack>
);
diff --git a/frontend/src/metabase-lib/metric/core.ts b/frontend/src/metabase-lib/metric/core.ts
index 77c17bda66b..b210fbbd1c4 100644
--- a/frontend/src/metabase-lib/metric/core.ts
+++ b/frontend/src/metabase-lib/metric/core.ts
@@ -2,7 +2,7 @@
import dayjs, { type Dayjs } from "dayjs";
import * as LibMetric from "cljs/metabase.lib_metric.js";
-import type { Metadata } from "metabase-lib";
+import type { ColumnMetadata, Metadata } from "metabase-lib";
import type {
ConcreteTableId,
JsMetricDefinition,
@@ -441,6 +441,12 @@ export function projectionableDimensions(
return LibMetric.projectionableDimensions(definition) as DimensionMetadata[];
}
+export function pickDefaultDimension(
+ dimensions: readonly ColumnMetadata[],
+): ColumnMetadata | null {
+ return LibMetric.pickDefaultDimension(dimensions) as ColumnMetadata | null;
+}
+
export function dimensionReference(
dimension: DimensionMetadata,
): ProjectionClause {
@@ -471,6 +477,14 @@ export function project(
return LibMetric.project(definition, dimensionRef) as MetricDefinition;
}
+/** Projects a dimension using its default temporal bucket or binning strategy. */
+export function projectDimension(
+ definition: MetricDefinition,
+ dimension: DimensionMetadata,
+): MetricDefinition {
+ return LibMetric.projectDimension(definition, dimension) as MetricDefinition;
+}
+
export function projectionDimension(
definition: MetricDefinition,
dimension: ProjectionClause | DimensionMetadata,
diff --git a/frontend/src/metabase-types/api/measure.ts b/frontend/src/metabase-types/api/measure.ts
index 8420eee8519..c55c57f1f03 100644
--- a/frontend/src/metabase-types/api/measure.ts
+++ b/frontend/src/metabase-types/api/measure.ts
@@ -1,38 +1,10 @@
import type { FieldValue } from "./field";
+import type { DimensionId, DimensionMapping, MetricDimension } from "./metric";
import type { DatasetQuery, OpaqueDatasetQuery } from "./query";
import type { Table, TableId } from "./table";
import type { UserInfo } from "./user";
export type MeasureId = number;
-export type DimensionId = string;
-
-export type MetricDimensionGroup = {
- id: string;
- type: "main" | "connection";
- display_name: string;
-};
-
-export type MetricDimensionSource = {
- type: string;
- "field-id": number;
-};
-
-export type MetricDimension = {
- id: DimensionId;
- display_name: string;
- effective_type: string;
- semantic_type: string | null;
- group?: MetricDimensionGroup;
- sources?: MetricDimensionSource[];
-};
-
-export type DimensionMappingTarget = ["field", Record<string, unknown>, number];
-
-export type DimensionMapping = {
- dimension_id: DimensionId;
- table_id: number;
- target: DimensionMappingTarget;
-};
export interface Measure {
id: MeasureId;
diff --git a/frontend/src/metabase-types/api/metric.ts b/frontend/src/metabase-types/api/metric.ts
index 97f8548b1d8..30e7f2c417b 100644
--- a/frontend/src/metabase-types/api/metric.ts
+++ b/frontend/src/metabase-types/api/metric.ts
@@ -1,16 +1,51 @@
import type { Collection, CollectionId } from "./collection";
import type { DatasetColumn, RowValue } from "./dataset";
import type { FieldValue } from "./field";
-import type { DimensionId, DimensionMapping, MetricDimension } from "./measure";
-
-export type {
- DimensionMapping,
- MetricDimension,
- MetricDimensionGroup,
- MetricDimensionSource,
-} from "./measure";
export type MetricId = number;
+export type DimensionId = string;
+
+export type MetricDimensionGroup = {
+ id: string;
+ type: "main" | "connection";
+ display_name: string;
+};
+
+export type MetricDimensionSource = {
+ type: string;
+ "field-id": number;
+};
+
+export type MetricDimensionStatus = "status/active" | "status/orphaned";
+
+export type MetricDimension = {
+ id: DimensionId;
+ name?: string;
+ display_name: string;
+ description?: string | null;
+ effective_type: string;
+ semantic_type: string | null;
+ default?: boolean;
+ status?: MetricDimensionStatus;
+ group?: MetricDimensionGroup;
+ sources?: MetricDimensionSource[];
+};
+
+export type DimensionMappingTarget = [
+ "field",
+ Record<string, unknown>,
+ number | string,
+];
+
+export type AddableMetricDimension = MetricDimension & {
+ mapping_target: DimensionMappingTarget;
+};
+
+export type DimensionMapping = {
+ dimension_id: DimensionId;
+ table_id: number;
+ target: DimensionMappingTarget;
+};
export type Metric = {
id: MetricId;
@@ -112,3 +147,48 @@ export type GetRemappedMetricDimensionValueRequest = {
dimensionId: DimensionId;
value: string;
};
+
+export type ListMetricDimensionsRequest = {
+ metricId: MetricId;
+ query?: string;
+ "with-addable"?: boolean;
+ "include-orphaned"?: boolean;
+};
+
+export type AddableDimensionGroup = {
+ group: MetricDimensionGroup;
+ dimensions: AddableMetricDimension[];
+};
+
+export type ListMetricDimensionsResponse = {
+ added: MetricDimension[];
+ addable: AddableDimensionGroup[];
+};
+
+export type AddMetricDimensionsRequest = {
+ metricId: MetricId;
+ dimensions: AddableMetricDimension[];
+};
+
+export type RemoveMetricDimensionsRequest = {
+ metricId: MetricId;
+ dimension_ids: DimensionId[];
+};
+
+export type SetDefaultMetricDimensionRequest = {
+ metricId: MetricId;
+ dimension_id: DimensionId;
+};
+
+export type ReorderMetricDimensionsRequest = {
+ metricId: MetricId;
+ dimension_ids: DimensionId[];
+};
+
+export type UpdateMetricDimensionRequest = {
+ metricId: MetricId;
+ dimensionId: DimensionId;
+ display_name?: string;
+ description?: string | null;
+ source?: MetricDimensionSource;
+};
diff --git a/frontend/src/metabase-types/api/mocks/metric.ts b/frontend/src/metabase-types/api/mocks/metric.ts
index 5eb2dbe98d9..353cac48b07 100644
--- a/frontend/src/metabase-types/api/mocks/metric.ts
+++ b/frontend/src/metabase-types/api/mocks/metric.ts
@@ -1,6 +1,9 @@
import type {
+ AddableDimensionGroup,
+ AddableMetricDimension,
Metric,
MetricDimension,
+ MetricDimensionGroup,
NormalizedMetric,
} from "metabase-types/api";
@@ -9,8 +12,35 @@ export const createMockMetricDimension = (
): MetricDimension => ({
id: "1",
display_name: "Dimension",
+ description: null,
effective_type: "type/Text",
semantic_type: null,
+ default: false,
+ ...opts,
+});
+
+export const createMockAddableMetricDimension = (
+ opts?: Partial<AddableMetricDimension>,
+): AddableMetricDimension => ({
+ ...createMockMetricDimension(),
+ mapping_target: ["field", {}, 1],
+ ...opts,
+});
+
+export const createMockMetricDimensionGroup = (
+ opts?: Partial<MetricDimensionGroup>,
+): MetricDimensionGroup => ({
+ id: "main",
+ type: "main",
+ display_name: "Main table",
+ ...opts,
+});
+
+export const createMockAddableDimensionGroup = (
+ opts?: Partial<AddableDimensionGroup>,
+): AddableDimensionGroup => ({
+ group: createMockMetricDimensionGroup(),
+ dimensions: [createMockAddableMetricDimension()],
...opts,
});
diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.ts
index 5e124ca4f29..2636f1e8cf5 100644
--- a/frontend/src/metabase/api/card.ts
+++ b/frontend/src/metabase/api/card.ts
@@ -99,10 +99,13 @@ export const cardApi = Api.injectEndpoints({
onQueryStarted: hydrateMetadataStore(QueryMetadataSchema),
}),
getCardQuery: builder.query<Dataset, CardQueryRequest & RtkCacheKeyed>({
- query: ({ cardId, ...body }) => ({
+ query: ({ cardId, dashboardId, ...body }) => ({
method: "POST",
url: `/api/card/${cardId}/query`,
- body,
+ body: {
+ ...body,
+ dashboard_id: dashboardId,
+ },
}),
providesTags: (_data, _error, { cardId }) =>
provideCardQueryTags(cardId),
@@ -111,10 +114,13 @@ export const cardApi = Api.injectEndpoints({
Dataset,
CardQueryRequest & RtkCacheKeyed
>({
- query: ({ cardId, ...body }) => ({
+ query: ({ cardId, dashboardId, ...body }) => ({
method: "POST",
url: `/api/card/pivot/${cardId}/query`,
- body,
+ body: {
+ ...body,
+ dashboard_id: dashboardId,
+ },
}),
providesTags: (_data, _error, { cardId }) =>
provideCardQueryTags(cardId),
diff --git a/frontend/src/metabase/api/metric.ts b/frontend/src/metabase/api/metric.ts
index b3bc1225a73..298888af95a 100644
--- a/frontend/src/metabase/api/metric.ts
+++ b/frontend/src/metabase/api/metric.ts
@@ -1,26 +1,50 @@
import { MetricSchema } from "metabase/schema";
import type {
+ AddMetricDimensionsRequest,
Dataset,
FieldValue,
GetMetricDimensionValuesRequest,
GetMetricDimensionValuesResponse,
GetRemappedMetricDimensionValueRequest,
+ ListMetricDimensionsRequest,
+ ListMetricDimensionsResponse,
Metric,
MetricBreakoutValuesRequest,
MetricBreakoutValuesResponse,
MetricDatasetRequest,
+ MetricDimension,
MetricId,
+ RemoveMetricDimensionsRequest,
+ ReorderMetricDimensionsRequest,
SearchMetricDimensionValuesRequest,
+ SetDefaultMetricDimensionRequest,
+ UpdateMetricDimensionRequest,
} from "metabase-types/api";
import { Api } from "./api";
import {
+ idTag,
+ invalidateTags,
+ provideMetricDimensionListTags,
provideMetricDimensionValuesTags,
provideMetricListTags,
provideMetricTags,
} from "./tags/utils";
+import { getMetricDatasetCacheKey } from "./utils/get-metric-dataset-cache-key";
import { hydrateMetadataStore } from "./utils/hydrate-metadata-store";
+/**
+ * Curation edits change the dimensions embedded in the metric card itself,
+ * so consumers of `getMetric` and projected metric datasets must refetch too.
+ */
+function metricDimensionInvalidationTags(metricId: MetricId) {
+ return [
+ "metric-dimension" as const,
+ idTag("metric-dimension", metricId),
+ idTag("card", metricId),
+ ];
+}
+
export const metricApi = Api.injectEndpoints({
endpoints: (builder) => ({
listMetrics: builder.query<Metric[], void>({
@@ -74,6 +98,105 @@ export const metricApi = Api.injectEndpoints({
providesTags: (_, error, { metricId }) =>
provideMetricDimensionValuesTags(metricId),
}),
+ listMetricDimensions: builder.query<
+ ListMetricDimensionsResponse,
+ ListMetricDimensionsRequest
+ >({
+ query: ({ metricId, ...params }) => ({
+ method: "GET",
+ url: `/api/metric/${metricId}/dimension`,
+ params,
+ }),
+ providesTags: (_, error, { metricId }) =>
+ provideMetricDimensionListTags(metricId),
+ }),
+ addMetricDimensions: builder.mutation<
+ MetricDimension[],
+ AddMetricDimensionsRequest
+ >({
+ query: ({ metricId, ...body }) => ({
+ method: "POST",
+ url: `/api/metric/${metricId}/dimension/add`,
+ body,
+ }),
+ invalidatesTags: (_, error, { metricId }) =>
+ invalidateTags(error, metricDimensionInvalidationTags(metricId)),
+ }),
+ removeMetricDimensions: builder.mutation<
+ MetricDimension[],
+ RemoveMetricDimensionsRequest
+ >({
+ query: ({ metricId, ...body }) => ({
+ method: "POST",
+ url: `/api/metric/${metricId}/dimension/remove`,
+ body,
+ }),
+ invalidatesTags: (_, error, { metricId }) =>
+ invalidateTags(error, metricDimensionInvalidationTags(metricId)),
+ }),
+ reorderMetricDimensions: builder.mutation<
+ MetricDimension[],
+ ReorderMetricDimensionsRequest
+ >({
+ query: ({ metricId, ...body }) => ({
+ method: "POST",
+ url: `/api/metric/${metricId}/dimension/reorder`,
+ body,
+ }),
+ onQueryStarted: async (
+ { metricId, dimension_ids },
+ { dispatch, queryFulfilled },
+ ) => {
+ // Reflect the drop immediately; the invalidation refetch confirms it.
+ const patch = dispatch(
+ metricApi.util.updateQueryData(
+ "listMetricDimensions",
+ { metricId, query: undefined, "include-orphaned": true },
+ (draft) => {
+ const position = new Map(
+ dimension_ids.map((id, index) => [id, index]),
+ );
+ draft.added.sort(
+ (a, b) =>
+ (position.get(a.id) ?? Infinity) -
+ (position.get(b.id) ?? Infinity),
+ );
+ },
+ ),
+ );
+ try {
+ await queryFulfilled;
+ } catch {
+ patch.undo();
+ }
+ },
+ invalidatesTags: (_, error, { metricId }) =>
+ invalidateTags(error, metricDimensionInvalidationTags(metricId)),
+ }),
+ setDefaultMetricDimension: builder.mutation<
+ MetricDimension[],
+ SetDefaultMetricDimensionRequest
+ >({
+ query: ({ metricId, ...body }) => ({
+ method: "POST",
+ url: `/api/metric/${metricId}/dimension/set-default`,
+ body,
+ }),
+ invalidatesTags: (_, error, { metricId }) =>
+ invalidateTags(error, metricDimensionInvalidationTags(metricId)),
+ }),
+ updateMetricDimension: builder.mutation<
+ MetricDimension,
+ UpdateMetricDimensionRequest
+ >({
+ query: ({ metricId, dimensionId, ...body }) => ({
+ method: "POST",
+ url: `/api/metric/${metricId}/dimension/${encodeURIComponent(dimensionId)}`,
+ body,
+ }),
+ invalidatesTags: (_, error, { metricId }) =>
+ invalidateTags(error, metricDimensionInvalidationTags(metricId)),
+ }),
getMetricBreakoutValues: builder.query<
MetricBreakoutValuesResponse,
MetricBreakoutValuesRequest
@@ -91,6 +214,9 @@ export const metricApi = Api.injectEndpoints({
url: "/api/metric/dataset",
body,
}),
+ serializeQueryArgs: ({ endpointName, queryArgs }) =>
+ `${endpointName}(${getMetricDatasetCacheKey(queryArgs)})`,
+ providesTags: ["metric-dimension"],
keepUnusedDataFor: 30 * 60,
}),
}),
@@ -103,6 +229,12 @@ export const {
useGetMetricDimensionValuesQuery,
useSearchMetricDimensionValuesQuery,
useGetRemappedMetricDimensionValueQuery,
+ useListMetricDimensionsQuery,
+ useAddMetricDimensionsMutation,
+ useRemoveMetricDimensionsMutation,
+ useReorderMetricDimensionsMutation,
+ useSetDefaultMetricDimensionMutation,
+ useUpdateMetricDimensionMutation,
useGetMetricBreakoutValuesQuery,
useGetMetricDatasetQuery,
} = metricApi;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index bc9d26c401b..f4956dd6d49 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -33,6 +33,7 @@ export const TAG_TYPES = [
"llm-models",
"logger-preset",
"measure",
+ "metric-dimension",
"mfa-status",
"model-index",
"notification",
diff --git a/frontend/src/metabase/api/tags/utils.ts b/frontend/src/metabase/api/tags/utils.ts
index 7ac1fb59d00..597889ac4a3 100644
--- a/frontend/src/metabase/api/tags/utils.ts
+++ b/frontend/src/metabase/api/tags/utils.ts
@@ -641,6 +641,12 @@ export function provideMetricDimensionValuesTags(
return [idTag("card", metricId)];
}
+export function provideMetricDimensionListTags(
+ metricId: MetricId,
+): TagDescription<TagType>[] {
+ return [listTag("metric-dimension"), idTag("metric-dimension", metricId)];
+}
+
export function provideSnippetListTags(
snippets: NativeQuerySnippet[],
): TagDescription<TagType>[] {
diff --git a/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.ts b/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.ts
new file mode 100644
index 00000000000..d48e4ac77b5
--- /dev/null
+++ b/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.ts
@@ -0,0 +1,30 @@
+import type { MetricDatasetRequest } from "metabase-types/api";
+
+/**
+ * Lib generates new internal UUIDs whenever a metric definition is rebuilt.
+ * Replace them with positional values so RTK Query does not refetch an otherwise
+ * unchanged metric dataset after unrelated metadata updates. Reusing a positional
+ * value preserves relationships between source and projection references.
+ */
+export function getMetricDatasetCacheKey(
+ request: MetricDatasetRequest,
+): string {
+ const canonicalUuids = new Map<string, string>();
+
+ return (
+ JSON.stringify(request, (key: string, value: unknown) => {
+ if (key !== "lib/uuid" || typeof value !== "string") {
+ return value;
+ }
+
+ const canonicalUuid = canonicalUuids.get(value);
+ if (canonicalUuid) {
+ return canonicalUuid;
+ }
+
+ const nextUuid = `uuid-${canonicalUuids.size}`;
+ canonicalUuids.set(value, nextUuid);
+ return nextUuid;
+ }) ?? ""
+ );
+}
diff --git a/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.unit.spec.ts b/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.unit.spec.ts
new file mode 100644
index 00000000000..9a6ba2956df
--- /dev/null
+++ b/frontend/src/metabase/api/utils/get-metric-dataset-cache-key.unit.spec.ts
@@ -0,0 +1,43 @@
+import type { MetricDatasetRequest } from "metabase-types/api";
+
+import { getMetricDatasetCacheKey } from "./get-metric-dataset-cache-key";
+
+function createRequest(
+ sourceUuid: string,
+ projectionUuid: string,
+ projectionSourceUuid = sourceUuid,
+): MetricDatasetRequest {
+ return {
+ definition: {
+ expression: ["metric", { "lib/uuid": sourceUuid }, 42],
+ projections: [
+ {
+ type: "metric",
+ id: 42,
+ "lib/uuid": projectionSourceUuid,
+ projection: [
+ [
+ "dimension",
+ { "lib/uuid": projectionUuid, "temporal-unit": "month" },
+ "created-at",
+ ],
+ ],
+ },
+ ],
+ },
+ };
+}
+
+describe("getMetricDatasetCacheKey", () => {
+ it("uses the same cache key for equivalent definitions with regenerated UUIDs", () => {
+ expect(getMetricDatasetCacheKey(createRequest("a", "b"))).toBe(
+ getMetricDatasetCacheKey(createRequest("c", "d")),
+ );
+ });
+
+ it("preserves UUID relationships that identify source instances", () => {
+ expect(
+ getMetricDatasetCacheKey(createRequest("a", "b", "other-source")),
+ ).not.toBe(getMetricDatasetCacheKey(createRequest("a", "b")));
+ });
+});
diff --git a/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx b/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx
index e08e99cb35c..060c9aea4fd 100644
--- a/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx
+++ b/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import { useGetCardQuery } from "metabase/api";
import { QuestionResultLoader } from "metabase/common/components/QuestionResultLoader";
+import { getMetricSeriesWithDefaultDisplay } from "metabase/common/utils/card";
import { useSelector } from "metabase/redux";
import { getMetadata } from "metabase/selectors/metadata";
import { getResponseErrorMessage } from "metabase/utils/errors";
@@ -10,7 +11,8 @@ import {
getPermissionErrorMessage,
} from "metabase/visualizations/lib/errors";
import Question from "metabase-lib/v1/Question";
-import type { IconName, RawSeries } from "metabase-types/api";
+import type Metadata from "metabase-lib/v1/metadata/Metadata";
+import type { Dataset, IconName, RawSeries } from "metabase-types/api";
export interface PinnedQuestionLoaderProps {
id: number;
@@ -63,7 +65,7 @@ const PinnedQuestionLoader = ({
children({
question,
loading: loading || results == null,
- rawSeries: getRawSeries(rawSeries),
+ rawSeries: getRawSeries(rawSeries, result, metadata),
error: getError(error, result),
errorIcon: getErrorIcon(error, result),
})
@@ -72,8 +74,20 @@ const PinnedQuestionLoader = ({
);
};
-const getRawSeries = (rawSeries: RawSeries | null | undefined) => {
- return rawSeries?.map((series) => ({
+const getRawSeries = (
+ rawSeries: RawSeries | null | undefined,
+ result: Dataset | null,
+ metadata: Metadata,
+) => {
+ const seriesWithQuery = rawSeries?.map((series) => ({
+ ...series,
+ json_query: result?.json_query,
+ }));
+ const seriesWithDisplay = seriesWithQuery
+ ? getMetricSeriesWithDefaultDisplay(seriesWithQuery, metadata)
+ : undefined;
+
+ return seriesWithDisplay?.map((series) => ({
...series,
card: {
...series.card,
diff --git a/frontend/src/metabase/collections/components/PinnedQuestionCard/test/PinnedQuestionCard.unit.spec.tsx b/frontend/src/metabase/collections/components/PinnedQuestionCard/test/PinnedQuestionCard.unit.spec.tsx
index 6353b116b13..4c5b9068459 100644
--- a/frontend/src/metabase/collections/components/PinnedQuestionCard/test/PinnedQuestionCard.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/PinnedQuestionCard/test/PinnedQuestionCard.unit.spec.tsx
@@ -2,7 +2,13 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { screen } from "__support__/ui";
+import * as Lib from "metabase-lib";
+import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
import type { CollectionItemModel } from "metabase-types/api";
+import {
+ ORDERS_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
import { setup } from "./setup";
@@ -16,6 +22,39 @@ describe("PinnedQuestionCard", () => {
1,
);
});
+
+ it("uses the default display for a pinned metric preview", async () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ {
+ type: "column",
+ name: "TOTAL",
+ sourceName: "ORDERS",
+ bins: 10,
+ },
+ ],
+ },
+ ],
+ });
+
+ setup(
+ { model: "metric", collection_preview: true },
+ {
+ card: { type: "metric", display: "line" },
+ dataset: { json_query: Lib.toJsQuery(query) },
+ databases: [createSampleDatabase()],
+ },
+ );
+
+ expect(await screen.findByTestId("visualization-root")).toHaveAttribute(
+ "data-viz-ui-name",
+ "Bar",
+ );
+ });
});
describe("description", () => {
diff --git a/frontend/src/metabase/collections/components/PinnedQuestionCard/test/setup.tsx b/frontend/src/metabase/collections/components/PinnedQuestionCard/test/setup.tsx
index 0aaffacf6ac..f2d88af8632 100644
--- a/frontend/src/metabase/collections/components/PinnedQuestionCard/test/setup.tsx
+++ b/frontend/src/metabase/collections/components/PinnedQuestionCard/test/setup.tsx
@@ -9,7 +9,12 @@ import { renderWithProviders } from "__support__/ui";
import { ROOT_COLLECTION } from "metabase/common/collections/constants";
import { createMockState } from "metabase/redux/store/mocks";
import { registerVisualizations } from "metabase/visualizations/register";
-import type { CollectionItem } from "metabase-types/api";
+import type {
+ Card,
+ CollectionItem,
+ Database,
+ Dataset,
+} from "metabase-types/api";
import {
createMockCard,
createMockCollection,
@@ -28,19 +33,32 @@ const defaultCardDetails: Partial<CollectionItem> = {
collection_preview: true,
};
+interface SetupOptions {
+ enterprise?: boolean;
+ card?: Partial<Card>;
+ dataset?: Partial<Dataset>;
+ databases?: Database[];
+}
+
export function setup(
cardDetails = defaultCardDetails,
- { enterprise } = { enterprise: false },
+ {
+ enterprise = false,
+ card: cardOverrides,
+ dataset: datasetOverrides,
+ databases = [],
+ }: SetupOptions = {},
) {
const card = createMockCard({
id: 1,
+ ...cardOverrides,
});
const collectionItem = createMockCollectionItem({
id: card.id,
...cardDetails,
});
setupCardEndpoints(card);
- setupCardQueryEndpoints(card, createMockDataset());
+ setupCardQueryEndpoints(card, createMockDataset(datasetOverrides));
const settings = mockSettings(
createMockSettings({
@@ -64,6 +82,7 @@ export function setup(
{
storeInitialState: createMockState({
entities: createMockEntitiesState({
+ databases,
questions: [card],
}),
settings,
diff --git a/frontend/src/metabase/common/metrics/types.ts b/frontend/src/metabase/common/metrics/types.ts
index 2c3b076bbb5..7019be31e3a 100644
--- a/frontend/src/metabase/common/metrics/types.ts
+++ b/frontend/src/metabase/common/metrics/types.ts
@@ -12,6 +12,7 @@ export interface MetricUrls {
about: (cardId: CardId) => string;
overview: (cardId: CardId) => string;
query: (cardId: CardId) => string;
+ dimensions: (cardId: CardId) => string;
dependencies: (cardId: CardId) => string;
history: (cardId: CardId) => string;
database?: (databaseId: DatabaseId) => string;
diff --git a/frontend/src/metabase/common/metrics/utils/dimension-types.ts b/frontend/src/metabase/common/metrics/utils/dimension-types.ts
index a5971d71159..98c2c712499 100644
--- a/frontend/src/metabase/common/metrics/utils/dimension-types.ts
+++ b/frontend/src/metabase/common/metrics/utils/dimension-types.ts
@@ -1,8 +1,25 @@
import type { DimensionMetadata } from "metabase-lib/metric";
import * as LibMetric from "metabase-lib/metric";
+import type { CardDisplayType } from "metabase-types/api";
export type DimensionType = "time" | "geo" | "category" | "boolean" | "numeric";
+export type DefaultDimensionDisplayType = Extract<
+ CardDisplayType,
+ "line" | "map" | "bar"
+>;
+
+export const DEFAULT_DISPLAY_TYPE_BY_DIMENSION: Record<
+ DimensionType,
+ DefaultDimensionDisplayType
+> = {
+ time: "line",
+ geo: "map",
+ category: "bar",
+ boolean: "bar",
+ numeric: "bar",
+};
+
export type GeoSubtype = "country" | "state";
export function isGeoDimension(dimension: DimensionMetadata): boolean {
diff --git a/frontend/src/metabase/common/metrics/utils/dimensions.ts b/frontend/src/metabase/common/metrics/utils/dimensions.ts
index 8cdbd1bbcf4..ac3735dc699 100644
--- a/frontend/src/metabase/common/metrics/utils/dimensions.ts
+++ b/frontend/src/metabase/common/metrics/utils/dimensions.ts
@@ -1,9 +1,20 @@
+import { getColumnIcon } from "metabase/common/utils/columns";
+import * as Lib from "metabase-lib";
import * as LibMetric from "metabase-lib/metric";
-import type { IconName } from "metabase-types/api";
+import type { IconName, MetricDimension } from "metabase-types/api";
export function getDimensionIcon(
- dimension: LibMetric.DimensionMetadata,
+ dimension: LibMetric.DimensionMetadata | MetricDimension,
): IconName {
+ if ("display_name" in dimension) {
+ return getColumnIcon(
+ Lib.legacyColumnTypeInfo({
+ effective_type: dimension.effective_type,
+ semantic_type: dimension.semantic_type,
+ }),
+ );
+ }
+
// semantic type checks first
if (LibMetric.isPrimaryKey(dimension)) {
return "label";
diff --git a/frontend/src/metabase/common/metrics/utils/dimensions.unit.spec.ts b/frontend/src/metabase/common/metrics/utils/dimensions.unit.spec.ts
new file mode 100644
index 00000000000..f5919988b72
--- /dev/null
+++ b/frontend/src/metabase/common/metrics/utils/dimensions.unit.spec.ts
@@ -0,0 +1,24 @@
+import { createMockMetricDimension } from "metabase-types/api/mocks";
+
+import { getDimensionIcon } from "./dimensions";
+
+describe("getDimensionIcon", () => {
+ it("supports API metric dimensions", () => {
+ expect(
+ getDimensionIcon(
+ createMockMetricDimension({
+ effective_type: "type/Text",
+ semantic_type: "type/Country",
+ }),
+ ),
+ ).toBe("location");
+ expect(
+ getDimensionIcon(
+ createMockMetricDimension({
+ effective_type: "type/Integer",
+ semantic_type: null,
+ }),
+ ),
+ ).toBe("int");
+ });
+});
diff --git a/frontend/src/metabase/common/utils/card.ts b/frontend/src/metabase/common/utils/card.ts
index 17c70d23971..a35f12a7499 100644
--- a/frontend/src/metabase/common/utils/card.ts
+++ b/frontend/src/metabase/common/utils/card.ts
@@ -11,6 +11,7 @@ import {
import { stableStringify } from "metabase/utils/objects";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
+import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import { deriveFieldOperatorFromParameter } from "metabase-lib/v1/parameters/utils/operators";
import { normalizeParameterValue } from "metabase-lib/v1/parameters/utils/parameter-values";
@@ -24,6 +25,7 @@ import type {
LegacyDatasetQuery,
Parameter,
ParameterValuesMap,
+ Series,
UnsavedCard,
VirtualDashCardParameterMapping,
} from "metabase-types/api";
@@ -96,6 +98,37 @@ export function isEqualCard(card1?: Card | null, card2?: Card | null) {
}
}
+export function getMetricSeriesWithDefaultDisplay(
+ series: Series,
+ metadata: Metadata,
+): Series {
+ if (series.length !== 1) {
+ return series;
+ }
+
+ const [metricSeries] = series;
+ if (metricSeries.card.type !== "metric" || !metricSeries.json_query) {
+ return series;
+ }
+
+ const query = Lib.fromJsQueryAndMetadata(metadata, metricSeries.json_query);
+ const { display, settings = {} } = Lib.defaultDisplay(query);
+
+ return [
+ {
+ ...metricSeries,
+ card: {
+ ...metricSeries.card,
+ display,
+ visualization_settings: {
+ ...metricSeries.card.visualization_settings,
+ ...settings,
+ },
+ },
+ },
+ ];
+}
+
// TODO Atte Keinänen 5/31/17 Deprecated, we should move tests to Questions.spec.js
export function serializeCardForUrl(
card: Card | UnsavedCard,
diff --git a/frontend/src/metabase/common/utils/card.unit.spec.ts b/frontend/src/metabase/common/utils/card.unit.spec.ts
index 144b17fb61a..f624656ad18 100644
--- a/frontend/src/metabase/common/utils/card.unit.spec.ts
+++ b/frontend/src/metabase/common/utils/card.unit.spec.ts
@@ -1,5 +1,16 @@
-import { deserializeCardFromQuery } from "metabase/common/utils/card";
+import {
+ deserializeCardFromQuery,
+ getMetricSeriesWithDefaultDisplay,
+} from "metabase/common/utils/card";
import { utf8_to_b64url } from "metabase/utils/encoding";
+import * as Lib from "metabase-lib";
+import { SAMPLE_METADATA, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
+import {
+ createMockCard,
+ createMockDataset,
+ createMockSingleSeries,
+} from "metabase-types/api/mocks";
+import { ORDERS_ID } from "metabase-types/api/mocks/presets";
describe("deserializeCardFromQuery", () => {
const MBQL_QUERY = {
@@ -20,3 +31,72 @@ describe("deserializeCardFromQuery", () => {
);
});
});
+
+describe("getMetricSeriesWithDefaultDisplay", () => {
+ function createMetricSeries(query: Lib.Query) {
+ return createMockSingleSeries(
+ createMockCard({ type: "metric", display: "line" }),
+ createMockDataset({ json_query: Lib.toJsQuery(query) }),
+ );
+ }
+
+ it("uses a bar chart for a metric with a binned numeric breakout", () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ {
+ type: "column",
+ name: "TOTAL",
+ sourceName: "ORDERS",
+ bins: 10,
+ },
+ ],
+ },
+ ],
+ });
+
+ const result = getMetricSeriesWithDefaultDisplay(
+ [createMetricSeries(query)],
+ SAMPLE_METADATA,
+ );
+
+ expect(result[0].card.display).toBe("bar");
+ });
+
+ it("uses a line chart for a metric with a temporal breakout", () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [
+ { type: "column", name: "CREATED_AT", sourceName: "ORDERS" },
+ ],
+ },
+ ],
+ });
+
+ const result = getMetricSeriesWithDefaultDisplay(
+ [createMetricSeries(query)],
+ SAMPLE_METADATA,
+ );
+
+ expect(result[0].card.display).toBe("line");
+ });
+
+ it("preserves the display of regular questions", () => {
+ const series = [
+ createMockSingleSeries(
+ createMockCard({ type: "question", display: "line" }),
+ createMockDataset(),
+ ),
+ ];
+
+ expect(getMetricSeriesWithDefaultDisplay(series, SAMPLE_METADATA)).toBe(
+ series,
+ );
+ });
+});
diff --git a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
index f8f4a4bd9ef..b4530c77ca1 100644
--- a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
@@ -257,7 +257,7 @@ describe("dashboard/actions/cards", () => {
});
});
- it("should run a new card query", async () => {
+ it("should run a new card query with dashboard context (UXW-4769)", async () => {
await runReplaceCardAction({
dashcardId: TABLE_DASHCARD.id,
nextCardId: ORDERS_LINE_CHART_CARD.id,
@@ -269,6 +269,16 @@ describe("dashboard/actions/cards", () => {
`path:/api/card/${ORDERS_LINE_CHART_CARD.id}/query`,
);
expect(queryCalls).toHaveLength(1);
+
+ const requestBody = queryCalls[0].options.body;
+ expect(typeof requestBody).toBe("string");
+
+ if (typeof requestBody !== "string") {
+ return;
+ }
+
+ const parsedBody: unknown = JSON.parse(requestBody);
+ expect(parsedBody).toMatchObject({ dashboard_id: DASHBOARD.id });
});
it("should not auto-wire parameters", async () => {
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index f59af67338d..4b4fb8c2f97 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -393,6 +393,7 @@ export const fetchCardDataAction = createAsyncThunk<
result = (await fetchDataOrError(
runQuery(cardApi.endpoints.getCardQuery, card, metadata, {
cardId: card.id,
+ dashboardId: dashcard.dashboard_id,
ignore_cache: ignoreCache,
}),
)) as Dataset | { error: unknown };
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.tsx
index 77301627ab6..7cfc2ba2a8e 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.tsx
@@ -1,6 +1,9 @@
+import { useMemo } from "react";
import { t } from "ttag";
import { isActionDashCard } from "metabase/actions/utils";
+import { skipToken } from "metabase/api";
+import { useListMetricDimensionsQuery } from "metabase/api/metric";
import {
getDashcardParameterMappingOptions,
getEditingParameter,
@@ -25,10 +28,12 @@ import { isParameterVariableTarget } from "metabase-lib/v1/parameters/utils/targ
import type {
Card,
DashboardCard,
+ MetricDimension,
Parameter,
ParameterTarget,
VirtualCard,
} from "metabase-types/api";
+import { isStructuredDimensionTarget } from "metabase-types/guards";
import { DashCardCardParameterMapperContent } from "./DashCardCardParameterMapperContent";
import S from "./DashCardParameterMapper.module.css";
@@ -79,14 +84,27 @@ export function DashCardCardParameterMapper({
editingParameterInlineDashcard,
compact,
}: DashcardCardParameterMapperProps) {
+ const metricId = card.type === "metric" ? card.id : undefined;
+ const isMetric = metricId != null;
+ const { data: metricDimensionsData } = useListMetricDimensionsQuery(
+ isMetric ? { metricId } : skipToken,
+ );
+ const visibleMappingOptions = useMemo(() => {
+ return isMetric
+ ? getMetricMappingOptions(
+ mappingOptions,
+ metricDimensionsData?.added ?? [],
+ )
+ : mappingOptions;
+ }, [isMetric, mappingOptions, metricDimensionsData?.added]);
const isQuestion = isQuestionDashCard(dashcard);
const hasSeries = isQuestion && dashcard.series && dashcard.series.length > 0;
const isAction = isActionDashCard(dashcard);
- const isDisabled = mappingOptions.length === 0 || isAction;
+ const isDisabled = visibleMappingOptions.length === 0 || isAction;
const isNative = isQuestion && isNativeDashCard(dashcard);
const selectedMappingOption = getMappingOptionByTarget(
- mappingOptions,
+ visibleMappingOptions,
target,
question,
editingParameter ?? undefined,
@@ -130,7 +148,7 @@ export function DashCardCardParameterMapper({
dashcard={dashcard}
question={question}
editingParameter={editingParameter}
- mappingOptions={mappingOptions}
+ mappingOptions={visibleMappingOptions}
isQuestion={isQuestion}
editingParameterInlineDashcard={editingParameterInlineDashcard}
card={card}
@@ -182,6 +200,43 @@ export function DashCardCardParameterMapper({
);
}
+function getMetricMappingOptions(
+ mappingOptions: ParameterMappingOption[],
+ dimensions: MetricDimension[],
+): ParameterMappingOption[] {
+ const optionByFieldId = new Map<number, ParameterMappingOption>();
+ for (const option of mappingOptions) {
+ if (!isStructuredDimensionTarget(option.target)) {
+ continue;
+ }
+ const fieldReference = option.target[1];
+ if (
+ fieldReference[0] === "field" &&
+ typeof fieldReference[1] === "number" &&
+ !optionByFieldId.has(fieldReference[1])
+ ) {
+ optionByFieldId.set(fieldReference[1], option);
+ }
+ }
+
+ return dimensions.flatMap((dimension) => {
+ for (const source of dimension.sources ?? []) {
+ const mappingOption = optionByFieldId.get(source["field-id"]);
+ if (mappingOption) {
+ return [
+ {
+ name: dimension.display_name,
+ icon: mappingOption.icon,
+ isForeign: false,
+ target: mappingOption.target,
+ },
+ ];
+ }
+ }
+ return [];
+ });
+}
+
export const DashCardCardParameterMapperConnected = connect(mapStateToProps)(
DashCardCardParameterMapper,
);
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.unit.spec.tsx
index 1f2a0552180..73cfec44692 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardParameterMapper/DashCardCardParameterMapper.unit.spec.tsx
@@ -1,5 +1,6 @@
import userEvent from "@testing-library/user-event";
+import { setupMetricDimensionsEndpoints } from "__support__/server-mocks";
import { createMockEntitiesState } from "__support__/store";
import {
getIcon,
@@ -18,6 +19,7 @@ import {
createMockDashboardCard,
createMockIFrameDashboardCard,
createMockLinkDashboardCard,
+ createMockMetricDimension,
createMockNativeDatasetQuery,
createMockNativeQuery,
createMockParameter,
@@ -251,6 +253,59 @@ describe("DashCardCardParameterMapper", () => {
expect(screen.getByText("Section.Name")).toBeInTheDocument();
});
+ it("shows only curated metric dimensions", async () => {
+ const card = createMockCard({ type: "metric" });
+ setupMetricDimensionsEndpoints(card.id, {
+ added: [
+ createMockMetricDimension({
+ id: "category",
+ display_name: "Product category",
+ sources: [{ type: "field", "field-id": 2 }],
+ }),
+ createMockMetricDimension({
+ id: "title",
+ display_name: "Product title",
+ sources: [{ type: "field", "field-id": 1 }],
+ }),
+ ],
+ addable: [],
+ });
+
+ setup({
+ card,
+ mappingOptions: [
+ {
+ target: ["dimension", ["field", 1, null]],
+ icon: "string",
+ isForeign: true,
+ sectionName: "Product",
+ name: "Title",
+ },
+ {
+ target: ["dimension", ["field", 2, null]],
+ icon: "string",
+ isForeign: true,
+ sectionName: "Product",
+ name: "Category",
+ },
+ {
+ target: ["dimension", ["field", 3, null]],
+ icon: "string",
+ isForeign: true,
+ sectionName: "User",
+ name: "Email",
+ },
+ ],
+ });
+
+ await userEvent.click(await screen.findByText("Select…"));
+
+ const options = screen.getAllByRole("option");
+ expect(options).toHaveLength(2);
+ expect(options[0]).toHaveTextContent("Product category");
+ expect(options[1]).toHaveTextContent("Product title");
+ });
+
describe("Auto-connected hint", () => {
it("should render 'Auto-connected' message on auto-wire", () => {
const card = createMockCard();
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
index 3fb05a3b8b1..c3bf9cc7aff 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from "react";
import { t } from "ttag";
import _ from "underscore";
+import { getMetricSeriesWithDefaultDisplay } from "metabase/common/utils/card";
import CS from "metabase/css/core/index.css";
import { setParameterValuesFromQueryParams } from "metabase/dashboard/actions/parameters";
import { useDashboardContext } from "metabase/dashboard/context";
@@ -217,15 +218,14 @@ export function DashCardVisualization({
}, [dashcard, rawSeries]);
const untranslatedSeries = useMemo(() => {
- if (
- !dashcard ||
- !rawSeries ||
- rawSeries.length === 0 ||
- !isVisualizerDashboardCard(dashcard)
- ) {
+ if (!dashcard || !rawSeries || rawSeries.length === 0) {
return rawSeries;
}
+ if (!isVisualizerDashboardCard(dashcard)) {
+ return getMetricSeriesWithDefaultDisplay(rawSeries, metadata);
+ }
+
const visualizerEntity = dashcard.visualization_settings.visualization;
const { display, columnValuesMapping, settings } = visualizerEntity;
@@ -312,7 +312,7 @@ export function DashCardVisualization({
}
return series;
- }, [rawSeries, dashcard, datasets]);
+ }, [rawSeries, dashcard, datasets, metadata]);
const series =
PLUGIN_CONTENT_TRANSLATION.useTranslateSeries(untranslatedSeries);
diff --git a/frontend/src/metabase/metrics-viewer/components/BreakoutDimensionPicker/BreakoutDimensionPicker.tsx b/frontend/src/metabase/metrics-viewer/components/BreakoutDimensionPicker/BreakoutDimensionPicker.tsx
index 09879e30214..34d7e11609d 100644
--- a/frontend/src/metabase/metrics-viewer/components/BreakoutDimensionPicker/BreakoutDimensionPicker.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/BreakoutDimensionPicker/BreakoutDimensionPicker.tsx
@@ -5,17 +5,13 @@ import {
AccordionList,
type Section,
} from "metabase/common/components/AccordionList";
-import {
- type DimensionOption,
- groupIntoSections,
-} from "metabase/common/components/DimensionPill";
+import type { DimensionOption } from "metabase/common/components/DimensionPill";
import { HoverParent } from "metabase/common/components/MetadataInfo/QueryColumnInfoIcon";
+import { getDimensionsByType } from "metabase/metrics-viewer/utils";
import { Flex, Icon } from "metabase/ui";
import type { MetricDefinition, ProjectionClause } from "metabase-lib/metric";
import * as LibMetric from "metabase-lib/metric";
-import { getDimensionsByType } from "../../utils/dimension-breakouts";
-
import S from "./BreakoutDimensionPicker.module.css";
import { DimensionBinningPicker } from "./DimensionBinningPicker";
import { DimensionTemporalUnitPicker } from "./DimensionTemporalUnitPicker";
@@ -47,7 +43,7 @@ export function BreakoutDimensionPicker({
selected: currentBreakoutDimensionName === dim.name,
}));
- return groupIntoSections(items);
+ return [{ items }];
}, [dimensions, currentBreakoutDimensionName]);
const handleSelect = useCallback(
@@ -136,6 +132,7 @@ export function BreakoutDimensionPicker({
renderItemWrapper={renderItemWrapper}
itemIsSelected={itemIsSelected}
alwaysExpanded
+ hideSingleSectionTitle
maxHeight={Infinity}
width="16rem"
/>
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.tsx
index 080c1a4e386..c434f0dbceb 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.tsx
@@ -35,10 +35,10 @@ import {
filterSections,
getDimensionBreakoutId,
getSelectedCategoryKey,
+ hasMatchingDimensions,
hasMultipleMetricSources,
hasSameDimensions,
isCategorySelected,
- isMatchingActiveDimensionBreakout,
} from "./utils";
type SidebarMode = "default" | "all";
@@ -50,6 +50,7 @@ type DimensionPickerSidebarProps = {
export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
const { activeDimensionBreakout } = props;
const {
+ formulaEntities,
metricSlots,
sourceColors,
sourceDataById,
@@ -75,10 +76,12 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
categories,
activeDimensionBreakout,
);
+ const isStandaloneMetric =
+ formulaEntities.length === 1 && formulaEntities[0]?.type === "metric";
const isSearching = searchText.trim() !== "";
- const showAllFields = mode === "all" || isSearching;
+ const showAllFields = !isStandaloneMetric && (mode === "all" || isSearching);
const hasAllFields = sections.length > 0;
- const showSeeAll = !showAllFields && hasAllFields;
+ const showSeeAll = !isStandaloneMetric && !showAllFields && hasAllFields;
let defaultEmptyStateText = t`No dimensions found`;
let defaultSectionHeader = t`Dimensions`;
@@ -121,7 +124,23 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
const handleAllFieldsSelect = useCallback(
(item: DimensionPickerItem) => {
- if (isMatchingActiveDimensionBreakout(item, activeDimensionBreakout)) {
+ // Clicking an already-selected dimension deselects it: the item's slots
+ // lose their dimension, excluding those metric instances from the
+ // breakout. All fields items are scoped per metric accordion, so only
+ // that metric is affected.
+ if (hasMatchingDimensions(item, activeDimensionBreakout)) {
+ const clearedSlots = Object.entries(
+ item.dimensionBreakoutInfo.dimensionMapping,
+ )
+ .filter(([, dimensionId]) => dimensionId != null)
+ .map(([slotIndex]) => [Number(slotIndex), null] as const);
+ updateActiveDimensionBreakout((prev) => ({
+ ...prev,
+ dimensionMapping: {
+ ...prev.dimensionMapping,
+ ...Object.fromEntries(clearedSlots),
+ },
+ }));
return;
}
@@ -131,14 +150,8 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
metricSlots,
activeDimensionBreakout,
});
- const dimensionBreakoutId = getDimensionBreakoutId(item);
- const dimensionBreakoutConfig = getDimensionBreakoutConfig(
- item.dimensionBreakoutInfo.type,
- );
- if (
- activeDimensionBreakout.type === item.dimensionBreakoutInfo.type &&
- dimensionBreakoutConfig.matchMode === "aggregate"
- ) {
+
+ if (activeDimensionBreakout.type === item.dimensionBreakoutInfo.type) {
updateActiveDimensionBreakout((prev) => ({
...prev,
dimensionMapping,
@@ -148,11 +161,17 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
return;
}
- onSelectDimensionBreakout({
- ...item.dimensionBreakoutInfo,
- ...(dimensionBreakoutId ? { id: dimensionBreakoutId } : {}),
- dimensionMapping,
- });
+ const dimensionBreakoutId = getDimensionBreakoutId(item);
+ onSelectDimensionBreakout(
+ {
+ ...item.dimensionBreakoutInfo,
+ ...(dimensionBreakoutId ? { id: dimensionBreakoutId } : {}),
+ dimensionMapping,
+ },
+ // Update in place when the breakout already exists (e.g. re-enabling a
+ // deselected metric), instead of silently keeping the stale mapping.
+ { updateExisting: true },
+ );
trackMetricsViewerDimensionSelected();
},
[
@@ -164,6 +183,17 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
],
);
+ const handleStandaloneMetricSelect = useCallback(
+ (item: DimensionPickerItem) => {
+ if (hasSameDimensions(item, activeDimensionBreakout)) {
+ return;
+ }
+
+ handleAllFieldsSelect(item);
+ },
+ [activeDimensionBreakout, handleAllFieldsSelect],
+ );
+
const handleCategorySelect = useCallback(
(category: DimensionPickerSidebarCategory) => {
if (expandedCategoryKey !== category.key) {
@@ -303,12 +333,12 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
<ScrollArea pb="lg" offsetScrollbars="present">
{showAllFields && (
<AllFieldsList
+ key={isSearching ? "searching" : "browsing"}
activeDimensionBreakout={activeDimensionBreakout}
sections={filteredSections}
metricSourceDataById={sourceDataById}
sourceColors={sourceColors}
metricSlots={metricSlots}
- expandAllMetricGroups={isSearching}
onSelect={handleAllFieldsSelect}
/>
)}
@@ -324,7 +354,16 @@ export function DimensionPickerSidebar(props: DimensionPickerSidebarProps) {
</Button>
)}
</Flex>
- {showFieldsByCategory ? (
+ {isStandaloneMetric ? (
+ <AllFieldsList
+ activeDimensionBreakout={activeDimensionBreakout}
+ sections={filteredSections}
+ metricSourceDataById={sourceDataById}
+ sourceColors={sourceColors}
+ metricSlots={metricSlots}
+ onSelect={handleStandaloneMetricSelect}
+ />
+ ) : showFieldsByCategory ? (
<Stack gap="xs">
{categories.map((category) => {
const isSelected =
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.unit.spec.tsx
index a23b5094b43..50b0daeea16 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.unit.spec.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/DimensionPickerSidebar.unit.spec.tsx
@@ -6,8 +6,10 @@ import { createMockMetricsViewerResult } from "metabase/metrics-viewer/test-util
import type {
MetricSourceId,
MetricsViewerDimensionBreakoutState,
+ MetricsViewerFormulaEntity,
} from "metabase/metrics-viewer/types";
import type {
+ AvailableDimension,
AvailableDimensionsResult,
SourceDisplayInfo,
} from "metabase/metrics-viewer/utils";
@@ -83,24 +85,33 @@ const sourceDataById: Record<MetricSourceId, SourceDisplayInfo> = {
[SOURCE_ID]: { type: "metric", name: "Revenue" },
};
+const standaloneMetricEntity: MetricsViewerFormulaEntity = {
+ id: SOURCE_ID,
+ type: "metric",
+ definition: null,
+};
+
function setup({
dimensionBreakout = activeDimensionBreakout,
dimensions = availableDimensions,
slots = [{ slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID }],
sourceOrder = [SOURCE_ID],
sources = sourceDataById,
+ formulaEntities = [],
}: {
dimensionBreakout?: MetricsViewerDimensionBreakoutState;
dimensions?: AvailableDimensionsResult;
slots?: MetricSlot[];
sourceOrder?: MetricSourceId[];
sources?: Record<MetricSourceId, SourceDisplayInfo>;
+ formulaEntities?: MetricsViewerFormulaEntity[];
} = {}) {
const onSelectDimensionBreakout = jest.fn();
const onUpdateActiveDimensionBreakout = jest.fn();
const metricsViewerResult = createMockMetricsViewerResult({
activeDimensionBreakout: dimensionBreakout,
+ formulaEntities,
sidebarAvailableDimensions: dimensions,
metricSlots: slots,
sourceColors: { 0: ["#509ee3"], 1: ["#f9d45c"] },
@@ -175,9 +186,11 @@ describe("DimensionPickerSidebar", () => {
await userEvent.click(screen.getByRole("button", { name: "See all" }));
- expect(
- screen.getByRole("button", { name: "Swapped dates" }),
- ).not.toHaveAttribute("aria-pressed", "true");
+ for (const button of screen.getAllByRole("button", {
+ name: "Swapped dates",
+ })) {
+ expect(button).not.toHaveAttribute("aria-pressed", "true");
+ }
});
it("filters dimensions with search", async () => {
@@ -211,6 +224,111 @@ describe("DimensionPickerSidebar", () => {
).not.toBeInTheDocument();
});
+ it("shows all curated dimensions without See all for a standalone metric", () => {
+ setup({ formulaEntities: [standaloneMetricEntity] });
+
+ expect(screen.getByRole("heading", { name: "Break out" })).toBeVisible();
+ expect(screen.getByText("Dimensions")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Category" })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Created At" })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Order Date" })).toBeVisible();
+ expect(screen.getByRole("button", { name: "No breakout" })).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "See all" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("filters standalone metric dimensions without entering All fields", async () => {
+ setup({ formulaEntities: [standaloneMetricEntity] });
+
+ await userEvent.type(screen.getByLabelText("Search fields"), "created");
+
+ expect(screen.getByRole("heading", { name: "Break out" })).toBeVisible();
+ expect(screen.queryByText("All fields")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Created At" })).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Category" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("replaces the selected standalone metric dimension", async () => {
+ const userAddressBreakout: MetricsViewerDimensionBreakoutState = {
+ id: "dim-user-address",
+ type: "category",
+ label: "User - Address",
+ display: "bar",
+ dimensionMapping: { 0: "dim-user-address" },
+ projectionConfig: {},
+ };
+ const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
+ setup({
+ dimensionBreakout: userAddressBreakout,
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "User - Address",
+ dimensionMapping: { 0: "dim-user-address" },
+ },
+ },
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-product-category" },
+ },
+ },
+ ],
+ },
+ },
+ formulaEntities: [standaloneMetricEntity],
+ });
+
+ expect(
+ screen.getByRole("button", { name: "User - Address" }),
+ ).toHaveAttribute("aria-pressed", "true");
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Product - Category" }),
+ );
+
+ expect(onUpdateActiveDimensionBreakout).toHaveBeenCalledTimes(1);
+ const updater = onUpdateActiveDimensionBreakout.mock.calls[0][0];
+ expect(updater(userAddressBreakout)).toMatchObject({
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-product-category" },
+ });
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
+ });
+
+ it("Shows See all for a single-metric expression", () => {
+ setup({
+ formulaEntities: [
+ {
+ id: "expression:1",
+ type: "expression",
+ name: "Revenue * 100",
+ tokens: [
+ { type: "metric", sourceId: SOURCE_ID, occurrenceCount: 1 },
+ { type: "operator", op: "*" },
+ { type: "constant", value: 100 },
+ ],
+ },
+ ],
+ });
+
+ expect(screen.getByRole("button", { name: "See all" })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Category" })).toBeVisible();
+ expect(
+ screen.queryByRole("button", { name: "Created At" }),
+ ).not.toBeInTheDocument();
+ });
+
it("selects no breakout and tracks it", async () => {
const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
setup();
@@ -237,6 +355,232 @@ describe("DimensionPickerSidebar", () => {
);
});
+ it("shows no shared option for category fields from different source columns", () => {
+ setup({
+ dimensionBreakout: scalarDimensionBreakout,
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "label",
+ isPreferred: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Plan Type",
+ dimensionMapping: { 0: "dim-plan-type" },
+ },
+ },
+ ],
+ [SECOND_SOURCE_ID]: [
+ {
+ icon: "label",
+ isPreferred: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 1: "dim-status" },
+ },
+ },
+ ],
+ },
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
+ });
+
+ expect(
+ screen.queryByRole("button", { name: "Category" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Plan Type" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Status" }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("No shared dimensions found")).toBeInTheDocument();
+ });
+
+ it("offers a shared option for category fields with the same source column", async () => {
+ const { onSelectDimensionBreakout } = setup({
+ dimensionBreakout: scalarDimensionBreakout,
+ dimensions: {
+ shared: [
+ {
+ icon: "label",
+ isPreferred: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Product Category",
+ dimensionMapping: {
+ 0: "dim-revenue-category",
+ 1: "dim-orders-category",
+ },
+ },
+ },
+ ],
+ bySource: {},
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
+ });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Product Category" }),
+ );
+
+ expect(onSelectDimensionBreakout).toHaveBeenCalledWith({
+ type: "category",
+ label: "Product Category",
+ dimensionMapping: {
+ 0: "dim-revenue-category",
+ 1: "dim-orders-category",
+ },
+ });
+ });
+
+ it("deselects a metric's dimension by clicking it again in See all", async () => {
+ const activeTimeBreakout: MetricsViewerDimensionBreakoutState = {
+ id: "dim-birth-date",
+ type: "time",
+ label: "Birth Date",
+ display: "line",
+ dimensionMapping: {
+ 0: "dim-birth-date",
+ 1: "second-dim-created-at",
+ },
+ projectionConfig: {},
+ };
+ const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
+ setup({
+ dimensionBreakout: activeTimeBreakout,
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Birth Date",
+ dimensionMapping: { 0: "dim-birth-date" },
+ },
+ },
+ ],
+ [SECOND_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "second-dim-created-at" },
+ },
+ },
+ ],
+ },
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "See all" }));
+
+ const selectedDimension = screen.getByRole("button", {
+ name: "Birth Date",
+ });
+ expect(selectedDimension).toHaveAttribute("aria-pressed", "true");
+
+ await userEvent.click(selectedDimension);
+
+ expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
+ const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
+ expect(updaterFn(activeTimeBreakout)).toMatchObject({
+ dimensionMapping: { 0: null, 1: "second-dim-created-at" },
+ });
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("reselects a deselected dimension from See all", async () => {
+ const activeCategoryBreakout: MetricsViewerDimensionBreakoutState = {
+ id: "dim-user-status",
+ type: "category",
+ label: "Status",
+ display: "bar",
+ dimensionMapping: { 0: null, 1: "dim-product-status" },
+ projectionConfig: {},
+ };
+ const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
+ setup({
+ dimensionBreakout: activeCategoryBreakout,
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 0: "dim-user-status" },
+ },
+ },
+ ],
+ [SECOND_SOURCE_ID]: [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 1: "dim-product-status" },
+ },
+ },
+ ],
+ },
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "See all" }));
+ await userEvent.click(screen.getAllByRole("button", { name: "Status" })[0]);
+
+ expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
+ const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
+ expect(updaterFn(activeCategoryBreakout)).toMatchObject({
+ dimensionMapping: { 0: "dim-user-status", 1: "dim-product-status" },
+ });
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
+ });
+
it("hides categories that are not available for multiple metric sources", () => {
setup({
dimensions: {
@@ -325,117 +669,49 @@ describe("DimensionPickerSidebar", () => {
});
it("updates the active time dimensionBreakout with the clicked time field from all fields", async () => {
- const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
- setup({ dimensionBreakout: timeDimensionBreakout });
-
- await userEvent.click(screen.getByRole("button", { name: "See all" }));
- await userEvent.click(screen.getByRole("button", { name: "Order Date" }));
-
- expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
- expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
- const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
- expect(updaterFn(timeDimensionBreakout)).toMatchObject({
- label: "Order Date",
- dimensionMapping: { 0: "dim-order-date" },
- });
- });
-
- it("preserves other metric mappings when selecting an aggregate field from See all", async () => {
- const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
- setup({
- dimensionBreakout: {
- id: "dim-created-at",
- type: "time",
- label: "Created At",
- display: "line",
- dimensionMapping: {
- 0: "dim-created-at",
- 1: "second-dim-created-at",
- },
- projectionConfig: {},
- },
- dimensions: {
- shared: [
- {
- icon: "calendar",
- dimensionBreakoutInfo: {
- type: "time",
- label: "Created At",
- dimensionMapping: {
- 0: "dim-created-at",
- 1: "second-dim-created-at",
- },
- },
- },
- ],
- bySource: {
- [SOURCE_ID]: [
- {
- icon: "calendar",
- dimensionBreakoutInfo: {
- type: "time",
- label: "Birth Date",
- dimensionMapping: { 0: "dim-birth-date" },
- },
- },
- ],
- [SECOND_SOURCE_ID]: [],
- },
- },
- slots: [
- { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
- { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
- ],
- sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
- sources: {
- [SOURCE_ID]: { type: "metric", name: "Revenue" },
- [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
- },
- });
+ const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
+ setup({ dimensionBreakout: timeDimensionBreakout });
await userEvent.click(screen.getByRole("button", { name: "See all" }));
- await userEvent.click(screen.getByRole("button", { name: "Birth Date" }));
+ await userEvent.click(screen.getByRole("button", { name: "Order Date" }));
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
- expect(
- updaterFn({
- id: "dim-created-at",
- type: "time",
- label: "Created At",
- display: "line",
- dimensionMapping: {
- 0: "dim-created-at",
- 1: "second-dim-created-at",
- },
- projectionConfig: {},
- }),
- ).toMatchObject({
- label: "Birth Date",
- dimensionMapping: {
- 0: "dim-birth-date",
- 1: "second-dim-created-at",
- },
+ expect(updaterFn(timeDimensionBreakout)).toMatchObject({
+ label: "Order Date",
+ dimensionMapping: { 0: "dim-order-date" },
});
- expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
});
- it("activates the clicked field when its slot is already mapped", async () => {
+ it("preserves other metric mappings when selecting an aggregate field from See all", async () => {
const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
setup({
dimensionBreakout: {
- id: "second-dim-created-at",
+ id: "dim-created-at",
type: "time",
label: "Created At",
display: "line",
dimensionMapping: {
- 0: "dim-birth-date",
+ 0: "dim-created-at",
1: "second-dim-created-at",
},
projectionConfig: {},
},
dimensions: {
- shared: [],
+ shared: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: {
+ 0: "dim-created-at",
+ 1: "second-dim-created-at",
+ },
+ },
+ },
+ ],
bySource: {
[SOURCE_ID]: [
{
@@ -447,16 +723,7 @@ describe("DimensionPickerSidebar", () => {
},
},
],
- [SECOND_SOURCE_ID]: [
- {
- icon: "calendar",
- dimensionBreakoutInfo: {
- type: "time",
- label: "Created At",
- dimensionMapping: { 1: "second-dim-created-at" },
- },
- },
- ],
+ [SECOND_SOURCE_ID]: [],
},
},
slots: [
@@ -477,12 +744,12 @@ describe("DimensionPickerSidebar", () => {
const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
expect(
updaterFn({
- id: "second-dim-created-at",
+ id: "dim-created-at",
type: "time",
label: "Created At",
display: "line",
dimensionMapping: {
- 0: "dim-birth-date",
+ 0: "dim-created-at",
1: "second-dim-created-at",
},
projectionConfig: {},
@@ -497,20 +764,21 @@ describe("DimensionPickerSidebar", () => {
expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
});
- it("selects only the clicked non-comparable field from See all", async () => {
+ it("changes only the clicked metric's dimension for a same-type field from See all", async () => {
+ const activeCategoryBreakout: MetricsViewerDimensionBreakoutState = {
+ id: "dim-status",
+ type: "category",
+ label: "Status",
+ display: "bar",
+ dimensionMapping: {
+ 0: "dim-user-category",
+ 1: "dim-product-status",
+ },
+ projectionConfig: {},
+ };
const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
setup({
- dimensionBreakout: {
- id: "dim-status",
- type: "category",
- label: "Status",
- display: "bar",
- dimensionMapping: {
- 0: "dim-user-category",
- 1: "dim-product-status",
- },
- projectionConfig: {},
- },
+ dimensionBreakout: activeCategoryBreakout,
dimensions: {
shared: [],
bySource: {
@@ -556,31 +824,32 @@ describe("DimensionPickerSidebar", () => {
await userEvent.click(screen.getByRole("button", { name: "See all" }));
await userEvent.click(screen.getAllByRole("button", { name: "Status" })[0]);
- expect(onSelectDimensionBreakout).toHaveBeenCalledWith({
- id: "dim-user-status",
- type: "category",
+ expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
+ const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
+ expect(updaterFn(activeCategoryBreakout)).toMatchObject({
label: "Status",
- dimensionMapping: { 0: "dim-user-status", 1: null },
+ dimensionMapping: { 0: "dim-user-status", 1: "dim-product-status" },
});
- expect(onUpdateActiveDimensionBreakout).not.toHaveBeenCalled();
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
});
it.each([
["Address", "dim-revenue-user-address"],
["Name", "dim-revenue-user-name"],
])(
- "does not keep Accounts Email selected when selecting Revenue User %s",
+ "keeps Accounts Email for the other slot when selecting Revenue User %s",
async (fieldName, fieldId) => {
+ const activeCategoryBreakout: MetricsViewerDimensionBreakoutState = {
+ id: "dim-accounts-email",
+ type: "category",
+ label: "Email",
+ display: "bar",
+ dimensionMapping: { 1: "dim-accounts-email" },
+ projectionConfig: {},
+ };
const { onSelectDimensionBreakout, onUpdateActiveDimensionBreakout } =
setup({
- dimensionBreakout: {
- id: "dim-accounts-email",
- type: "category",
- label: "Email",
- display: "bar",
- dimensionMapping: { 1: "dim-accounts-email" },
- projectionConfig: {},
- },
+ dimensionBreakout: activeCategoryBreakout,
dimensions: {
shared: [],
bySource: {
@@ -626,13 +895,169 @@ describe("DimensionPickerSidebar", () => {
await userEvent.click(screen.getByRole("button", { name: "See all" }));
await userEvent.click(screen.getByRole("button", { name: fieldName }));
- expect(onSelectDimensionBreakout).toHaveBeenCalledWith({
- id: fieldId,
- type: "category",
+ expect(onUpdateActiveDimensionBreakout).toHaveBeenCalled();
+ const updaterFn = onUpdateActiveDimensionBreakout.mock.calls[0][0];
+ expect(updaterFn(activeCategoryBreakout)).toMatchObject({
label: fieldName,
- dimensionMapping: { 0: fieldId, 1: null },
+ dimensionMapping: { 0: fieldId, 1: "dim-accounts-email" },
+ });
+ expect(onSelectDimensionBreakout).not.toHaveBeenCalled();
+ },
+ );
+
+ const TYPE_SWITCH_CASES: Array<
+ [string, AvailableDimension[], string | null]
+ > = [
+ [
+ "matches the other metric by name",
+ [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Priority",
+ dimensionMapping: { 1: "dim-priority" },
+ },
+ },
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 1: "dim-second-status" },
+ },
+ },
+ ],
+ "dim-second-status",
+ ],
+ [
+ "falls back to the other metric's same-type default dimension",
+ [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Priority",
+ dimensionMapping: { 1: "dim-priority" },
+ },
+ },
+ {
+ icon: "label",
+ isDefault: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Level",
+ dimensionMapping: { 1: "dim-level" },
+ },
+ },
+ ],
+ "dim-level",
+ ],
+ [
+ "falls back to the other metric's first same-type dimension in curated order",
+ [
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Priority",
+ dimensionMapping: { 1: "dim-priority" },
+ },
+ },
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Level",
+ dimensionMapping: { 1: "dim-level" },
+ },
+ },
+ ],
+ "dim-priority",
+ ],
+ [
+ "disables the other metric without a same-type dimension",
+ [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "dim-second-created-at" },
+ },
+ },
+ ],
+ null,
+ ],
+ ];
+
+ it.each(TYPE_SWITCH_CASES)(
+ "switching breakout type from See all %s",
+ async (_case, secondMetricDimensions, expectedSecondSlotDimension) => {
+ const { onSelectDimensionBreakout } = setup({
+ dimensionBreakout: {
+ id: "dim-created-at",
+ type: "time",
+ label: "Created At",
+ display: "line",
+ dimensionMapping: {
+ 0: "dim-created-at",
+ 1: "dim-second-created-at",
+ },
+ projectionConfig: {},
+ },
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-created-at" },
+ },
+ },
+ {
+ icon: "label",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 0: "dim-revenue-status" },
+ },
+ },
+ ],
+ [SECOND_SOURCE_ID]: secondMetricDimensions,
+ },
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
});
- expect(onUpdateActiveDimensionBreakout).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByRole("button", { name: "See all" }));
+ await userEvent.click(
+ screen.getAllByRole("button", { name: "Status" })[0],
+ );
+
+ expect(onSelectDimensionBreakout).toHaveBeenCalledWith(
+ {
+ id: "dim-revenue-status",
+ type: "category",
+ label: "Status",
+ dimensionMapping: {
+ 0: "dim-revenue-status",
+ 1: expectedSecondSlotDimension,
+ },
+ },
+ { updateExisting: true },
+ );
},
);
@@ -695,8 +1120,6 @@ describe("DimensionPickerSidebar", () => {
"true",
);
- await userEvent.click(screen.getByRole("button", { name: "Total Orders" }));
-
const createdAtButtons = screen.getAllByRole("button", {
name: "Created At",
});
@@ -704,7 +1127,7 @@ describe("DimensionPickerSidebar", () => {
expect(createdAtButtons[1]).toHaveAttribute("data-selected", "true");
});
- it("groups all fields by metric when multiple metrics are selected", async () => {
+ it("lists all curated fields under each metric accordion", async () => {
setup({
dimensions: {
shared: [
@@ -769,10 +1192,16 @@ describe("DimensionPickerSidebar", () => {
);
expect(
screen.getByRole("button", { name: "Total Orders" }),
- ).toHaveAttribute("aria-expanded", "false");
- expect(screen.getByText("Customers")).toBeInTheDocument();
- expect(screen.getByText("Subscriptions")).toBeInTheDocument();
- expect(screen.queryByText("Shared · Customers")).not.toBeInTheDocument();
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(
+ screen.getAllByRole("button", { name: "Customer Name" }),
+ ).toHaveLength(2);
+ expect(
+ screen.getByRole("button", { name: "Placed At" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Order Status" }),
+ ).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Total Orders" }));
@@ -782,11 +1211,13 @@ describe("DimensionPickerSidebar", () => {
);
expect(
screen.getByRole("button", { name: "Total Orders" }),
- ).toHaveAttribute("aria-expanded", "true");
- expect(screen.getByText("Orders")).toBeInTheDocument();
+ ).toHaveAttribute("aria-expanded", "false");
expect(
- screen.getByRole("button", { name: "Order Status" }),
- ).toBeInTheDocument();
+ screen.queryByRole("button", { name: "Order Status" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getAllByRole("button", { name: "Customer Name" }),
+ ).toHaveLength(1);
await userEvent.click(screen.getByRole("button", { name: "ARR" }));
@@ -796,14 +1227,63 @@ describe("DimensionPickerSidebar", () => {
);
expect(
screen.getByRole("button", { name: "Total Orders" }),
- ).toHaveAttribute("aria-expanded", "true");
- expect(screen.queryByText("Subscriptions")).not.toBeInTheDocument();
+ ).toHaveAttribute("aria-expanded", "false");
expect(
- screen.getByRole("button", { name: "Order Status" }),
- ).toBeInTheDocument();
+ screen.queryByRole("button", { name: "Placed At" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Order Status" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not repeat the metric name inside its expanded section without shared dimensions", async () => {
+ setup({
+ dimensions: {
+ shared: [],
+ bySource: {
+ [SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-created-at" },
+ },
+ },
+ ],
+ [SECOND_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "second-dim-created-at" },
+ },
+ },
+ ],
+ },
+ },
+ slots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: SECOND_SOURCE_ID },
+ ],
+ sourceOrder: [SOURCE_ID, SECOND_SOURCE_ID],
+ sources: {
+ [SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [SECOND_SOURCE_ID]: { type: "metric", name: "Total Orders" },
+ },
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "See all" }));
+
+ expect(screen.getByRole("button", { name: "Revenue" })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
+ expect(screen.getAllByText("Revenue")).toHaveLength(1);
});
- it("expands all metric accordions while searching all fields", async () => {
+ it("expands all metric accordions in See all and while searching all fields (UXW-4850)", async () => {
setup({
dimensions: {
shared: [],
@@ -847,6 +1327,12 @@ describe("DimensionPickerSidebar", () => {
"aria-expanded",
"true",
);
+ expect(
+ screen.getByRole("button", { name: "Total Orders" }),
+ ).toHaveAttribute("aria-expanded", "true");
+
+ await userEvent.click(screen.getByRole("button", { name: "Total Orders" }));
+
expect(
screen.getByRole("button", { name: "Total Orders" }),
).toHaveAttribute("aria-expanded", "false");
@@ -906,12 +1392,12 @@ describe("DimensionPickerSidebar", () => {
});
expect(revenueAccordions).toHaveLength(2);
expect(revenueAccordions[0]).toHaveAttribute("aria-expanded", "true");
- expect(revenueAccordions[1]).toHaveAttribute("aria-expanded", "false");
+ expect(revenueAccordions[1]).toHaveAttribute("aria-expanded", "true");
await userEvent.click(revenueAccordions[1]);
expect(revenueAccordions[0]).toHaveAttribute("aria-expanded", "true");
- expect(revenueAccordions[1]).toHaveAttribute("aria-expanded", "true");
+ expect(revenueAccordions[1]).toHaveAttribute("aria-expanded", "false");
});
it("uses circle indicators for expression metric dropdown rows", async () => {
@@ -1030,7 +1516,7 @@ describe("DimensionPickerSidebar", () => {
}
});
- it("merges shared and metric sections with the same table name", async () => {
+ it("shows shared and metric dimensions without table sections", async () => {
setup({
dimensions: {
shared: [
@@ -1079,10 +1565,10 @@ describe("DimensionPickerSidebar", () => {
await userEvent.click(screen.getByRole("button", { name: "See all" }));
- expect(screen.getAllByText("Product")).toHaveLength(1);
- expect(
- screen.getByRole("button", { name: "Created At" }),
- ).toBeInTheDocument();
+ expect(screen.queryByText("Product")).not.toBeInTheDocument();
+ expect(screen.getAllByRole("button", { name: "Created At" })).toHaveLength(
+ 2,
+ );
expect(screen.getByRole("button", { name: "Title" })).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/AllFieldsList.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/AllFieldsList.tsx
index 3fa7752254d..e346ef94b1a 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/AllFieldsList.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/AllFieldsList.tsx
@@ -23,7 +23,6 @@ type AllFieldsListProps = {
metricSourceDataById: Record<MetricSourceId, SourceDisplayInfo>;
sourceColors: SourceColorMap;
metricSlots: MetricSlot[];
- expandAllMetricGroups: boolean;
onSelect: (item: DimensionPickerItem) => void;
};
@@ -33,7 +32,6 @@ export function AllFieldsList({
metricSourceDataById,
sourceColors,
metricSlots,
- expandAllMetricGroups,
onSelect,
}: AllFieldsListProps) {
if (sections.length === 0) {
@@ -50,9 +48,7 @@ export function AllFieldsList({
});
if (metricSlots.length > 1 && metricGroups.length > 1) {
- const defaultExpandedGroupKeys = expandAllMetricGroups
- ? metricGroups.map((group) => group.key)
- : metricGroups.slice(0, 1).map((group) => group.key);
+ const defaultExpandedGroupKeys = metricGroups.map((group) => group.key);
return (
<MetricAccordionList
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/buildAllFieldsMetricGroups.ts b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/buildAllFieldsMetricGroups.ts
index 1fa17ed1d9a..08d47022069 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/buildAllFieldsMetricGroups.ts
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/components/AllFieldsList/buildAllFieldsMetricGroups.ts
@@ -11,57 +11,6 @@ import type { MetricSlot } from "metabase/metrics-viewer/utils/metric-slots";
import type { AllFieldsMetricGroup } from "./types";
-function getSectionKey(section: DimensionPickerSection) {
- return section.name;
-}
-
-function getDimensionItemKey(item: DimensionPickerSection["items"][number]) {
- const entries = Object.entries(item.dimensionBreakoutInfo.dimensionMapping)
- .sort(([a], [b]) => Number(a) - Number(b))
- .map(([k, v]) => `${k}=${v}`)
- .join("|");
- return `${item.dimensionBreakoutInfo.type}:${entries}`;
-}
-
-function mergeSectionsByName(sections: DimensionPickerSection[]) {
- const mergedSections: DimensionPickerSection[] = [];
- const sectionIndexesByKey = new Map<string, number>();
-
- for (const section of sections) {
- const sectionKey = getSectionKey(section);
-
- if (sectionKey == null) {
- mergedSections.push({ ...section, items: [...section.items] });
- continue;
- }
-
- const sectionIndex = sectionIndexesByKey.get(sectionKey);
-
- if (sectionIndex == null) {
- sectionIndexesByKey.set(sectionKey, mergedSections.length);
- mergedSections.push({ ...section, items: [...section.items] });
- continue;
- }
-
- const mergedSection = mergedSections[sectionIndex];
- const existingItemKeys = new Set(
- mergedSection.items.map(getDimensionItemKey),
- );
- const newItems = section.items.filter(
- (item) => !existingItemKeys.has(getDimensionItemKey(item)),
- );
-
- if (newItems.length > 0) {
- mergedSections[sectionIndex] = {
- ...mergedSection,
- items: [...mergedSection.items, ...newItems],
- };
- }
- }
-
- return mergedSections;
-}
-
function getSourceSlotIndices(
metricSlots: MetricSlot[],
sourceId: MetricSourceId,
@@ -104,14 +53,13 @@ function scopeSectionsToSource(
sections: DimensionPickerSection[],
slotIndices: Set<number>,
) {
- return sections
- .map((section) => ({
- ...section,
- items: section.items
- .map((item) => scopeItemToSlotIndices(item, slotIndices))
- .filter((item): item is DimensionPickerItem => item != null),
- }))
- .filter((section) => section.items.length > 0);
+ const items = sections.flatMap((section) =>
+ section.items
+ .map((item) => scopeItemToSlotIndices(item, slotIndices))
+ .filter((item): item is DimensionPickerItem => item != null),
+ );
+
+ return items.length > 0 ? [{ items }] : [];
}
export function buildAllFieldsMetricGroups({
@@ -152,7 +100,7 @@ export function buildAllFieldsMetricGroups({
...(slot.occurrenceCount != null
? { occurrenceCount: slot.occurrenceCount }
: {}),
- sections: mergeSectionsByName(scopedSections),
+ sections: scopedSections,
};
})
.filter((group) => group.sections.length > 0);
@@ -183,7 +131,7 @@ export function buildAllFieldsMetricGroups({
isExpressionToken: sourceSlots.every(
(slot) => slot.tokenPosition != null,
),
- sections: mergeSectionsByName(scopedSections),
+ sections: scopedSections,
};
})
.filter((group) => group.sections.length > 0);
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.ts b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.ts
index 50889a499fd..8a57027ab8e 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.ts
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.ts
@@ -1,3 +1,4 @@
+import { useMemo } from "react";
import { t } from "ttag";
import { useMetricsViewerContext } from "metabase/metrics-viewer/context";
@@ -16,9 +17,20 @@ import { useDimensionPickerSidebarSections } from "./useDimensionPickerSidebarSe
export function useDimensionPickerSidebarCategories(): DimensionPickerSidebarCategory[] {
const { metricSlots } = useMetricsViewerContext();
const sections = useDimensionPickerSidebarSections();
+
+ return useMemo(
+ () => getDimensionPickerSidebarCategories(sections, metricSlots),
+ [metricSlots, sections],
+ );
+}
+
+function getDimensionPickerSidebarCategories(
+ sections: ReturnType<typeof useDimensionPickerSidebarSections>,
+ metricSlots: MetricSlot[],
+) {
const items = sections
.flatMap((section) => section.items)
- .filter(shouldShowInDefaultSidebar);
+ .filter((item) => shouldShowInDefaultSidebar(item, metricSlots));
const categories: DimensionPickerSidebarCategory[] = [];
const groupedItems = new Map<string, DimensionPickerItem[]>();
@@ -76,7 +88,6 @@ function buildSidebarCategory(
};
}
-/** Type-keyed aggregate categories reselect their fixed breakout across related fields. */
function isTypeKeyedAggregateCategory(
key: string,
config: DimensionBreakoutTypeDefinition,
@@ -84,10 +95,17 @@ function isTypeKeyedAggregateCategory(
DimensionBreakoutTypeDefinition,
{ matchMode: "aggregate" }
> {
- return config.matchMode === "aggregate" && key.startsWith("type:");
+ return config.matchMode === "aggregate" && key === `type:${config.type}`;
}
-function shouldShowInDefaultSidebar(item: DimensionPickerItem) {
+function shouldShowInDefaultSidebar(
+ item: DimensionPickerItem,
+ metricSlots: MetricSlot[],
+) {
+ if (metricSlots.length > 1 && hasMappingForEverySlot(item, metricSlots)) {
+ return true;
+ }
+
if (item.dimensionBreakoutInfo.type === "numeric") {
return false;
}
@@ -108,19 +126,16 @@ const SIDEBAR_CATEGORY_ORDER: MetricsViewerDimensionBreakoutType[] = [
"scalar",
];
+// Rank by breakout type only; the sort is stable, so categories of the same
+// type keep the metric's curated dimension order.
function sortSidebarCategories(
first: DimensionPickerSidebarCategory,
second: DimensionPickerSidebarCategory,
) {
- const typeDiff =
+ return (
SIDEBAR_CATEGORY_ORDER.indexOf(first.dimensionBreakoutInfo.type) -
- SIDEBAR_CATEGORY_ORDER.indexOf(second.dimensionBreakoutInfo.type);
-
- if (typeDiff !== 0) {
- return typeDiff;
- }
-
- return first.name.localeCompare(second.name);
+ SIDEBAR_CATEGORY_ORDER.indexOf(second.dimensionBreakoutInfo.type)
+ );
}
function getSidebarCategoryName(item: DimensionPickerItem) {
@@ -134,24 +149,26 @@ function getSidebarCategoryName(item: DimensionPickerItem) {
return t`Country`;
}
+ if (type === "geo" && item.geoSubtype === "state") {
+ return t`State`;
+ }
+
return item.name;
}
function hasMappingForEverySlot(
- category: DimensionPickerSidebarCategory,
+ item: DimensionPickerItem,
metricSlots: MetricSlot[],
) {
return metricSlots.every(
- (slot) => category.dimensionBreakoutInfo.dimensionMapping[slot.slotIndex],
+ (slot) => item.dimensionBreakoutInfo.dimensionMapping[slot.slotIndex],
);
}
function mergeDimensionMappings(items: DimensionPickerItem[]) {
const mapping: Record<number, string> = {};
- const preferredItems = [...items].sort(sortPreferredItemsFirst);
-
- for (const item of preferredItems) {
+ for (const item of flattenNameGroupsByCoverage(items)) {
for (const [slotIndex, dimensionId] of Object.entries(
item.dimensionBreakoutInfo.dimensionMapping,
)) {
@@ -164,11 +181,37 @@ function mergeDimensionMappings(items: DimensionPickerItem[]) {
return mapping;
}
-function sortPreferredItemsFirst(
- first: DimensionPickerItem,
- second: DimensionPickerItem,
-) {
- return (
- Number(second.isPreferred === true) - Number(first.isPreferred === true)
- );
+interface DimensionNameGroup {
+ items: DimensionPickerItem[];
+ slotIndices: Set<number>;
+ hasPreferred: boolean;
+}
+
+function flattenNameGroupsByCoverage(items: DimensionPickerItem[]) {
+ const groups = new Map<string, DimensionNameGroup>();
+
+ for (const item of items) {
+ let group = groups.get(item.name);
+ if (!group) {
+ group = { items: [], slotIndices: new Set(), hasPreferred: false };
+ groups.set(item.name, group);
+ }
+ group.items.push(item);
+ group.hasPreferred ||= item.isPreferred === true;
+ for (const [slotIndex, dimensionId] of Object.entries(
+ item.dimensionBreakoutInfo.dimensionMapping,
+ )) {
+ if (dimensionId != null) {
+ group.slotIndices.add(Number(slotIndex));
+ }
+ }
+ }
+
+ return [...groups.values()]
+ .sort(
+ (first, second) =>
+ second.slotIndices.size - first.slotIndices.size ||
+ Number(second.hasPreferred) - Number(first.hasPreferred),
+ )
+ .flatMap((group) => group.items);
}
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.unit.spec.tsx
index aca6cdde892..ede97f9e5d1 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.unit.spec.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarCategories.unit.spec.tsx
@@ -319,7 +319,6 @@ describe("useDimensionPickerSidebarCategories", () => {
expect.objectContaining({ name: "User Country" }),
],
dimensionBreakoutInfo: expect.objectContaining({
- id: "geo",
type: "geo",
label: "Country",
dimensionMapping: {
@@ -331,7 +330,7 @@ describe("useDimensionPickerSidebarCategories", () => {
]);
});
- it("does not show same-named category fields from different tables as shared", () => {
+ it("does not share same-named category fields from different source columns", () => {
const { result } = setup({
availableDimensions: {
shared: [],
@@ -376,7 +375,7 @@ describe("useDimensionPickerSidebarCategories", () => {
expect(result.current).toEqual([]);
});
- it("shows exact same table and column category fields across all metrics", () => {
+ it("does not share different-named category fields across metrics", () => {
const { result } = setup({
availableDimensions: {
shared: [],
@@ -384,24 +383,22 @@ describe("useDimensionPickerSidebarCategories", () => {
[REVENUE_SOURCE_ID]: [
{
icon: "label",
- group: { id: "users", type: "main", displayName: "Users" },
isPreferred: true,
dimensionBreakoutInfo: {
type: "category",
- label: "Name",
- dimensionMapping: { 0: "dim-user-name" },
+ label: "Plan Type",
+ dimensionMapping: { 0: "dim-plan-type" },
},
},
],
[ORDERS_SOURCE_ID]: [
{
icon: "label",
- group: { id: "users", type: "main", displayName: "Users" },
isPreferred: true,
dimensionBreakoutInfo: {
type: "category",
- label: "Name",
- dimensionMapping: { 1: "dim-user-name" },
+ label: "Status",
+ dimensionMapping: { 1: "dim-status" },
},
},
],
@@ -418,6 +415,154 @@ describe("useDimensionPickerSidebarCategories", () => {
],
});
+ expect(result.current).toEqual([]);
+ });
+
+ it("prefers a time field name that covers more slots when merging the Time option", () => {
+ const { result } = setup({
+ availableDimensions: {
+ shared: [],
+ bySource: {
+ [REVENUE_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Updated At",
+ dimensionMapping: { 0: "dim-revenue-updated-at" },
+ },
+ },
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-revenue-created-at" },
+ },
+ },
+ ],
+ [ORDERS_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "dim-orders-created-at" },
+ },
+ },
+ ],
+ },
+ },
+ sourceOrder: [REVENUE_SOURCE_ID, ORDERS_SOURCE_ID],
+ sourceDataById: {
+ [REVENUE_SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [ORDERS_SOURCE_ID]: { type: "metric", name: "Orders" },
+ },
+ metricSlots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: REVENUE_SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: ORDERS_SOURCE_ID },
+ ],
+ });
+
+ // "Created At" covers both slots, so it wins over the curated-first
+ // "Updated At".
+ expect(result.current).toEqual([
+ expect.objectContaining({
+ name: "Time",
+ dimensionBreakoutInfo: expect.objectContaining({
+ dimensionMapping: {
+ 0: "dim-revenue-created-at",
+ 1: "dim-orders-created-at",
+ },
+ }),
+ }),
+ ]);
+ });
+
+ it("groups state fields across tables when every metric slot has one", () => {
+ const { result } = setup({
+ availableDimensions: {
+ shared: [],
+ bySource: {
+ [REVENUE_SOURCE_ID]: [
+ {
+ icon: "location",
+ geoSubtype: "state",
+ dimensionBreakoutInfo: {
+ type: "geo",
+ label: "Billing State",
+ dimensionMapping: { 0: "dim-billing-state" },
+ },
+ },
+ ],
+ [ORDERS_SOURCE_ID]: [
+ {
+ icon: "location",
+ geoSubtype: "state",
+ dimensionBreakoutInfo: {
+ type: "geo",
+ label: "User State",
+ dimensionMapping: { 1: "dim-user-state" },
+ },
+ },
+ ],
+ },
+ },
+ sourceOrder: [REVENUE_SOURCE_ID, ORDERS_SOURCE_ID],
+ sourceDataById: {
+ [REVENUE_SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [ORDERS_SOURCE_ID]: { type: "metric", name: "Orders" },
+ },
+ metricSlots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: REVENUE_SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: ORDERS_SOURCE_ID },
+ ],
+ });
+
+ expect(result.current).toEqual([
+ expect.objectContaining({
+ name: "State",
+ dimensionBreakoutInfo: expect.objectContaining({
+ type: "geo",
+ label: "State",
+ dimensionMapping: {
+ 0: "dim-billing-state",
+ 1: "dim-user-state",
+ },
+ }),
+ }),
+ ]);
+ });
+
+ it("shares category fields with the same source column across metrics", () => {
+ const { result } = setup({
+ availableDimensions: {
+ // Same-source-column dimensions arrive merged into one shared entry.
+ shared: [
+ {
+ icon: "label",
+ group: { id: "users", type: "main", displayName: "Users" },
+ isPreferred: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Name",
+ dimensionMapping: { 0: "dim-user-name", 1: "dim-user-name" },
+ },
+ },
+ ],
+ bySource: {},
+ },
+ sourceOrder: [REVENUE_SOURCE_ID, ORDERS_SOURCE_ID],
+ sourceDataById: {
+ [REVENUE_SOURCE_ID]: { type: "metric", name: "Revenue" },
+ [ORDERS_SOURCE_ID]: { type: "metric", name: "Orders" },
+ },
+ metricSlots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: REVENUE_SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: ORDERS_SOURCE_ID },
+ ],
+ });
+
expect(result.current).toEqual([
expect.objectContaining({
name: "Name",
@@ -430,6 +575,111 @@ describe("useDimensionPickerSidebarCategories", () => {
]);
});
+ it("shows every dimension shared by repeated metric slots", () => {
+ const { result } = setup({
+ availableDimensions: {
+ shared: [],
+ bySource: {
+ [REVENUE_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: {
+ 0: "dim-created-at",
+ 1: "dim-created-at",
+ },
+ },
+ },
+ {
+ icon: "calendar",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Updated At",
+ dimensionMapping: {
+ 0: "dim-updated-at",
+ 1: "dim-updated-at",
+ },
+ },
+ },
+ {
+ icon: "label",
+ isPreferred: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Category",
+ dimensionMapping: {
+ 0: "dim-category",
+ 1: "dim-category",
+ },
+ },
+ },
+ {
+ icon: "label",
+ isPreferred: false,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Title",
+ dimensionMapping: { 0: "dim-title", 1: "dim-title" },
+ },
+ },
+ {
+ icon: "io",
+ dimensionBreakoutInfo: {
+ type: "boolean",
+ label: "Is Active",
+ dimensionMapping: {
+ 0: "dim-is-active",
+ 1: "dim-is-active",
+ },
+ },
+ },
+ {
+ icon: "int",
+ dimensionBreakoutInfo: {
+ type: "numeric",
+ label: "Amount",
+ dimensionMapping: { 0: "dim-amount", 1: "dim-amount" },
+ },
+ },
+ ],
+ },
+ },
+ sourceOrder: [REVENUE_SOURCE_ID],
+ sourceDataById: {
+ [REVENUE_SOURCE_ID]: { type: "metric", name: "Revenue" },
+ },
+ metricSlots: [
+ { slotIndex: 0, entityIndex: 0, sourceId: REVENUE_SOURCE_ID },
+ { slotIndex: 1, entityIndex: 1, sourceId: REVENUE_SOURCE_ID },
+ ],
+ });
+
+ expect(result.current.map((category) => category.name)).toEqual([
+ "Time",
+ "Category",
+ "Title",
+ "Is Active",
+ "Amount",
+ ]);
+ expect(result.current.find((category) => category.name === "Time")).toEqual(
+ expect.objectContaining({
+ targetItems: [
+ expect.objectContaining({ name: "Created At" }),
+ expect.objectContaining({ name: "Updated At" }),
+ ],
+ }),
+ );
+ expect(
+ result.current.every(
+ (category) =>
+ category.dimensionBreakoutInfo.dimensionMapping[0] != null &&
+ category.dimensionBreakoutInfo.dimensionMapping[1] != null,
+ ),
+ ).toBe(true);
+ });
+
it("hides categories that do not match every metric slot", () => {
const { result } = setup({
availableDimensions: {
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.ts b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.ts
index e2b9f8c6622..24190bd04a6 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.ts
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.ts
@@ -1,9 +1,12 @@
+import { useMemo } from "react";
import { t } from "ttag";
import { useMetricsViewerContext } from "metabase/metrics-viewer/context";
import type {
AvailableDimension,
+ AvailableDimensionsResult,
MetricSourceId,
+ SourceDisplayInfo,
} from "metabase/metrics-viewer/types";
import type { DimensionPickerSection } from "metabase/metrics-viewer/utils";
@@ -14,119 +17,58 @@ export function useDimensionPickerSidebarSections(): DimensionPickerSection[] {
sourceDataById,
} = useMetricsViewerContext();
+ return useMemo(
+ () =>
+ getDimensionPickerSidebarSections(
+ availableDimensions,
+ sourceOrder,
+ sourceDataById,
+ ),
+ [availableDimensions, sourceDataById, sourceOrder],
+ );
+}
+
+function getDimensionPickerSidebarSections(
+ availableDimensions: AvailableDimensionsResult,
+ sourceOrder: MetricSourceId[],
+ sourceDataById: Record<MetricSourceId, SourceDisplayInfo>,
+) {
const sections: DimensionPickerSection[] = [];
- const splitByGroup = (
+ const pushSection = (
dimensions: AvailableDimension[],
- sectionName?: string,
- options: {
- isShared?: boolean;
- sourceId?: MetricSourceId;
- preferGroupName?: boolean;
- } = {},
+ name?: string,
+ options: { isShared?: boolean; sourceId?: MetricSourceId } = {},
) => {
- const { preferGroupName, isShared, sourceId } = options;
- const groups = new Map<string | undefined, AvailableDimension[]>();
- for (const dimension of dimensions) {
- const groupId = dimension.group?.id;
- const existing = groups.get(groupId);
- if (existing) {
- existing.push(dimension);
- } else {
- groups.set(groupId, [dimension]);
- }
- }
-
- if (groups.size <= 1) {
- const groupName = dimensions[0]?.group?.displayName;
- sections.push({
- name: getDimensionPickerSectionName(
- sectionName,
- groupName,
- preferGroupName,
- ),
- isShared,
- sourceId,
- items: dimensions.map((dimension) => ({
- ...dimension,
- name: dimension.dimensionBreakoutInfo.label,
- })),
- });
+ if (dimensions.length === 0) {
return;
}
-
- const sortedGroups = [...groups.values()].sort(sortDimensionGroups);
-
- for (const groupDimensions of sortedGroups) {
- const groupName = groupDimensions[0].group?.displayName;
- sections.push({
- name: getDimensionPickerSectionName(
- sectionName,
- groupName,
- preferGroupName,
- ),
- isShared,
- sourceId,
- items: groupDimensions.map((dimension) => ({
- ...dimension,
- name: dimension.dimensionBreakoutInfo.label,
- })),
- });
- }
+ sections.push({
+ name,
+ ...options,
+ items: dimensions.map((dimension) => ({
+ ...dimension,
+ name: dimension.dimensionBreakoutInfo.label,
+ })),
+ });
};
const hasMultipleSources = sourceOrder.length > 1;
- if (hasMultipleSources && availableDimensions.shared.length > 0) {
- splitByGroup(availableDimensions.shared, t`Shared`, {
- isShared: true,
- preferGroupName: true,
- });
+ if (hasMultipleSources) {
+ pushSection(availableDimensions.shared, t`Shared`, { isShared: true });
}
for (const sourceId of sourceOrder) {
- const sourceDimensions = availableDimensions.bySource[sourceId];
- if (!sourceDimensions || sourceDimensions.length === 0) {
- continue;
- }
+ const sourceDimensions = availableDimensions.bySource[sourceId] ?? [];
if (hasMultipleSources) {
const sourceName = sourceDataById[sourceId]?.name ?? sourceId;
- splitByGroup(sourceDimensions, sourceName, {
- sourceId,
- preferGroupName: true,
- });
+ pushSection(sourceDimensions, sourceName, { sourceId });
} else {
- splitByGroup(sourceDimensions);
+ pushSection(sourceDimensions);
}
}
return sections;
}
-
-function getDimensionPickerSectionName(
- sectionName: string | undefined,
- groupName: string | undefined,
- preferGroupName = false,
-) {
- if (preferGroupName && groupName) {
- return groupName;
- }
-
- if (sectionName && groupName) {
- return `${sectionName} · ${groupName}`;
- }
-
- return sectionName ?? groupName;
-}
-
-function sortDimensionGroups(
- first: AvailableDimension[],
- second: AvailableDimension[],
-) {
- return getDimensionGroupPriority(first) - getDimensionGroupPriority(second);
-}
-
-function getDimensionGroupPriority(dimensions: AvailableDimension[]) {
- return dimensions[0]?.group?.type === "main" ? 0 : 1;
-}
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.unit.spec.tsx
index 1613acefcdf..6d06079a23d 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.unit.spec.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/hooks/useDimensionPickerSidebarSections.unit.spec.tsx
@@ -41,7 +41,62 @@ function setup({
}
describe("useDimensionPickerSidebarSections", () => {
- it("uses table names without a Shared prefix for grouped shared dimensions", () => {
+ it("returns a single flat section for one metric, keeping the curated order", () => {
+ const { result } = setup({
+ availableDimensions: {
+ shared: [],
+ bySource: {
+ [REVENUE_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ group: { id: "orders", type: "main", displayName: "Orders" },
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-created-at" },
+ },
+ },
+ {
+ icon: "label",
+ group: {
+ id: "products",
+ type: "connection",
+ displayName: "Products",
+ },
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-category" },
+ },
+ },
+ {
+ icon: "int",
+ group: { id: "orders", type: "main", displayName: "Orders" },
+ dimensionBreakoutInfo: {
+ type: "numeric",
+ label: "Subtotal",
+ dimensionMapping: { 0: "dim-subtotal" },
+ },
+ },
+ ],
+ },
+ },
+ sourceOrder: [REVENUE_SOURCE_ID],
+ sourceDataById: {
+ [REVENUE_SOURCE_ID]: { type: "metric", name: "Revenue" },
+ },
+ });
+
+ expect(result.current).toHaveLength(1);
+ expect(result.current[0].name).toBeUndefined();
+ expect(result.current[0].items.map((item) => item.name)).toEqual([
+ "Created At",
+ "Product - Category",
+ "Subtotal",
+ ]);
+ });
+
+ it("returns one Shared section without splitting shared dimensions by table", () => {
const { result } = setup({
availableDimensions: {
shared: [
@@ -80,35 +135,55 @@ describe("useDimensionPickerSidebarSections", () => {
});
expect(result.current).toEqual([
- expect.objectContaining({ name: "Customers", isShared: true }),
- expect.objectContaining({ name: "Orders", isShared: true }),
+ expect.objectContaining({ name: "Shared", isShared: true }),
+ ]);
+ expect(result.current[0].items.map((item) => item.name)).toEqual([
+ "Customer Name",
+ "Created At",
]);
});
- it("orders main dimension groups before related groups", () => {
+ it("returns one section per metric named after the metric", () => {
const { result } = setup({
availableDimensions: {
- shared: [
- {
- icon: "label",
- group: { id: "users", type: "connection", displayName: "Users" },
- dimensionBreakoutInfo: {
- type: "category",
- label: "User Name",
- dimensionMapping: { 0: "dim-user-name", 1: "dim-user-name" },
+ shared: [],
+ bySource: {
+ [REVENUE_SOURCE_ID]: [
+ {
+ icon: "calendar",
+ group: { id: "orders", type: "main", displayName: "Orders" },
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-created-at" },
+ },
},
- },
- {
- icon: "calendar",
- group: { id: "orders", type: "main", displayName: "Orders" },
- dimensionBreakoutInfo: {
- type: "time",
- label: "Created At",
- dimensionMapping: { 0: "dim-created-at", 1: "dim-created-at" },
+ {
+ icon: "label",
+ group: {
+ id: "products",
+ type: "connection",
+ displayName: "Products",
+ },
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-category" },
+ },
},
- },
- ],
- bySource: {},
+ ],
+ [ORDERS_SOURCE_ID]: [
+ {
+ icon: "label",
+ group: { id: "plans", type: "connection", displayName: "Plans" },
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Plan Name",
+ dimensionMapping: { 1: "dim-plan-name" },
+ },
+ },
+ ],
+ },
},
sourceOrder: [REVENUE_SOURCE_ID, ORDERS_SOURCE_ID],
sourceDataById: {
@@ -117,9 +192,13 @@ describe("useDimensionPickerSidebarSections", () => {
},
});
- expect(result.current.map((section) => section.name)).toEqual([
- "Orders",
- "Users",
+ expect(result.current).toEqual([
+ expect.objectContaining({ name: "Revenue", sourceId: REVENUE_SOURCE_ID }),
+ expect.objectContaining({ name: "Orders", sourceId: ORDERS_SOURCE_ID }),
+ ]);
+ expect(result.current[0].items.map((item) => item.name)).toEqual([
+ "Created At",
+ "Product - Category",
]);
});
});
diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/utils.ts b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/utils.ts
index e3dba2f64ca..4fbc79ef718 100644
--- a/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/utils.ts
+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPickerSidebar/utils.ts
@@ -100,10 +100,10 @@ export function isCategorySelected(
category: DimensionPickerSidebarCategory,
activeDimensionBreakout: MetricsViewerDimensionBreakoutState,
) {
- if (
- category.dimensionBreakoutInfo.type === "time" &&
- activeDimensionBreakout.type === "time"
- ) {
+ // A type-keyed category stands for every dimension of its type, so any
+ // active breakout of that type selects it. Geo keys carry a subtype and
+ // fall through to exact dimension matching.
+ if (category.key === `type:${activeDimensionBreakout.type}`) {
return true;
}
@@ -124,17 +124,3 @@ export function getDimensionBreakoutId(item: DimensionPickerItem) {
(dimensionId) => dimensionId != null,
);
}
-
-export function isMatchingActiveDimensionBreakout(
- item: DimensionPickerItem,
- activeDimensionBreakout: MetricsViewerDimensionBreakoutState,
-) {
- const dimensionBreakoutId = getDimensionBreakoutId(item);
-
- return (
- hasMatchingDimensions(item, activeDimensionBreakout) &&
- item.dimensionBreakoutInfo.label === activeDimensionBreakout.label &&
- (dimensionBreakoutId == null ||
- dimensionBreakoutId === activeDimensionBreakout.id)
- );
-}
diff --git a/frontend/src/metabase/metrics-viewer/components/FilterPopover/types.ts b/frontend/src/metabase/metrics-viewer/components/FilterPopover/types.ts
index 2d0031c48ab..ec9d1e746be 100644
--- a/frontend/src/metabase/metrics-viewer/components/FilterPopover/types.ts
+++ b/frontend/src/metabase/metrics-viewer/components/FilterPopover/types.ts
@@ -17,10 +17,7 @@ export type SegmentListItem = {
export type FilterItem = DimensionListItem | SegmentListItem;
-export type MetricGroupFilterSection = BaseSection<FilterItem> & {
- /** True only for the metric's "main" (source-table) group. */
- isSourceTable?: boolean;
-};
+export type MetricGroupFilterSection = BaseSection<FilterItem>;
export type MetricGroup = {
id: number;
diff --git a/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.ts b/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.ts
index 9daf929268c..5406f8d278c 100644
--- a/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.ts
+++ b/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.ts
@@ -52,12 +52,6 @@ export function filterDisplayGroupsBySearch<
.filter((group) => group.sections.length > 0);
}
-type DimensionBucket = {
- groupName: string;
- groupType: "main" | "connection" | undefined;
- items: DimensionListItem[];
-};
-
export function getMetricGroups(
definitionSources: DefinitionSource[],
metricColors: SourceColorMap,
@@ -65,32 +59,22 @@ export function getMetricGroups(
return definitionSources.map((definitionSource, definitionIndex) => {
const definition = definitionSource.definition;
const segmentItems = buildSegmentItems(definition, definitionIndex);
- const dimensions = LibMetric.filterableDimensions(definition);
-
- const byGroupId = new Map<string, DimensionBucket>();
-
- for (const dimension of dimensions) {
- const info = LibMetric.displayInfo(definition, dimension);
- const groupId = info.group?.id ?? "";
- const groupName = info.group?.displayName ?? "";
- const groupType = info.group?.type;
- const item: DimensionListItem = {
- name: info.displayName,
- definition,
- definitionIndex,
- dimension,
- };
-
- const entry = byGroupId.get(groupId);
- if (entry) {
- entry.items.push(item);
- } else {
- byGroupId.set(groupId, { groupName, groupType, items: [item] });
- }
- }
+ const dimensionItems = LibMetric.filterableDimensions(definition).map(
+ (dimension): DimensionListItem => {
+ const info = LibMetric.displayInfo(definition, dimension);
+ return {
+ name: info.displayName,
+ definition,
+ definitionIndex,
+ dimension,
+ };
+ },
+ );
const hasSegments = segmentItems.length > 0;
- const sections = buildSections(byGroupId, segmentItems);
+ const items = [...segmentItems, ...dimensionItems];
+ const sections: MetricGroupFilterSection[] =
+ items.length > 0 ? [{ items }] : [];
return {
id: definitionSource.index,
@@ -104,62 +88,6 @@ export function getMetricGroups(
});
}
-function buildSections(
- byGroupId: Map<string, DimensionBucket>,
- segmentItems: SegmentListItem[],
-): MetricGroupFilterSection[] {
- // No dimensions at all — if there are segments, still surface them
- // inside a single source-table section so they don't disappear.
- if (byGroupId.size === 0) {
- if (segmentItems.length > 0) {
- return [{ isSourceTable: true, items: segmentItems }];
- }
- return [];
- }
-
- // Single-group fallback: merge every dimension + every segment
- // into one unnamed section and treat it as the source table.
- if (byGroupId.size === 1) {
- const [{ items }] = [...byGroupId.values()];
- return [
- {
- isSourceTable: true,
- items: [...segmentItems, ...items],
- },
- ];
- }
-
- // Multiple groups: segments live on the metric's source table, so
- // attach them to the source-table section. Joined-table segments are
- // out of scope for this milestone and are not surfaced by
- // `available-segments` on the backend.
- const sections: MetricGroupFilterSection[] = [];
- let mainAttached = false;
- for (const [, { groupName, groupType, items }] of byGroupId) {
- const isSourceTable = groupType === "main";
- sections.push({
- name: groupName,
- isSourceTable,
- items:
- isSourceTable && segmentItems.length > 0
- ? [...segmentItems, ...items]
- : items,
- });
- if (isSourceTable) {
- mainAttached = true;
- }
- }
-
- // Defensive: if no section was flagged as the source table but we
- // still have segments, surface them in a synthesized source-table
- // section so they don't disappear.
- if (!mainAttached && segmentItems.length > 0) {
- sections.unshift({ isSourceTable: true, items: segmentItems });
- }
-
- return sections;
-}
-
function buildSegmentItems(
definition: MetricDefinition,
definitionIndex: number,
diff --git a/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.unit.spec.ts b/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.unit.spec.ts
index b79e6b7f1ba..2e1710ae89b 100644
--- a/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.unit.spec.ts
+++ b/frontend/src/metabase/metrics-viewer/components/FilterPopover/utils.unit.spec.ts
@@ -61,25 +61,14 @@ function makeDefinitionSource(
};
}
-function getSourceTableDimensionInfo(
+function getDimensionInfo(
displayName: string,
- id = "main",
+ group: DimensionDisplayInfo["group"],
): DimensionDisplayInfo {
// Unjustified type cast. FIXME
return {
displayName,
- group: { id, displayName: "Orders", type: "main" },
- } as DimensionDisplayInfo;
-}
-
-function getJoinedTabledDimensionInfo(
- displayName: string,
- id = "conn",
-): DimensionDisplayInfo {
- // Unjustified type cast. FIXME
- return {
- displayName,
- group: { id, displayName: "Products", type: "connection" },
+ group,
} as DimensionDisplayInfo;
}
@@ -193,7 +182,7 @@ describe("filterDisplayGroupsBySearch", () => {
});
describe("getMetricGroups", () => {
- it("places segments above dimensions in the single source-table section", () => {
+ it("places segments above dimensions in a single unnamed section", () => {
const source = makeDefinitionSource(0);
// Unjustified type cast. FIXME
const dim = {
@@ -209,7 +198,11 @@ describe("getMetricGroups", () => {
mockLibMetric.displayInfo.mockImplementation(
(_def: unknown, target: unknown) => {
if (target === dim) {
- return getSourceTableDimensionInfo("Created At");
+ return getDimensionInfo("Created At", {
+ id: "main",
+ displayName: "Orders",
+ type: "main",
+ });
}
if (target === seg) {
return getSegmentInfo("Active customers");
@@ -222,7 +215,7 @@ describe("getMetricGroups", () => {
expect(group.hasSegments).toBe(true);
expect(group.sections).toHaveLength(1);
- expect(group.sections[0].isSourceTable).toBe(true);
+ expect(group.sections[0]).not.toHaveProperty("name");
expect(group.sections[0].items).toEqual([
expect.objectContaining({ name: "Active customers", segment: seg }),
expect.objectContaining({ name: "Created At", definitionIndex: 0 }),
@@ -239,7 +232,7 @@ describe("getMetricGroups", () => {
expect(group.sections).toEqual([]);
});
- it("synthesizes a source-table section when there are segments but no filterable dimensions", () => {
+ it("shows segments when there are no filterable dimensions", () => {
const source = makeDefinitionSource(0);
// Unjustified type cast. FIXME
const seg = { __seg: "big" } as unknown as LibMetric.SegmentMetadata;
@@ -251,13 +244,13 @@ describe("getMetricGroups", () => {
const [group] = getMetricGroups([source], {});
expect(group.hasSegments).toBe(true);
expect(group.sections).toHaveLength(1);
- expect(group.sections[0].isSourceTable).toBe(true);
+ expect(group.sections[0]).not.toHaveProperty("name");
expect(group.sections[0].items).toEqual([
expect.objectContaining({ name: "Big orders", segment: seg }),
]);
});
- it("only attaches segments to the main section when joined groups exist", () => {
+ it("flattens dimensions across table groups in filterable order", () => {
const source = makeDefinitionSource(0);
// Unjustified type cast. FIXME
const mainDimMeta = {
@@ -280,10 +273,18 @@ describe("getMetricGroups", () => {
mockLibMetric.displayInfo.mockImplementation(
(_def: unknown, target: unknown) => {
if (target === mainDimMeta) {
- return getSourceTableDimensionInfo("Created At");
+ return getDimensionInfo("Created At", {
+ id: "main",
+ displayName: "Orders",
+ type: "main",
+ });
}
if (target === connDimMeta) {
- return getJoinedTabledDimensionInfo("Category");
+ return getDimensionInfo("Category", {
+ id: "conn",
+ displayName: "Products",
+ type: "connection",
+ });
}
if (target === seg) {
return getSegmentInfo("Active customers");
@@ -293,70 +294,13 @@ describe("getMetricGroups", () => {
);
const [group] = getMetricGroups([source], {});
- expect(group.sections).toHaveLength(2);
-
- const mainSection = group.sections.find((s) => s.isSourceTable);
- const connSection = group.sections.find((s) => !s.isSourceTable);
-
- expect(mainSection?.items).toEqual([
+ expect(group.sections).toHaveLength(1);
+ expect(group.sections[0]).not.toHaveProperty("name");
+ expect(group.sections[0].items).toEqual([
expect.objectContaining({ name: "Active customers", segment: seg }),
expect.objectContaining({ name: "Created At" }),
- ]);
- expect(connSection?.items).toEqual([
expect.objectContaining({ name: "Category" }),
]);
- // Segments MUST NOT leak into the joined-table section.
- expect(
- connSection?.items?.some(
- // Unjustified type cast. FIXME
- (item) => (item as { segment?: unknown }).segment != null,
- ),
- ).toBe(false);
- });
-
- it("falls back to a synthesized source-table section if no group reports as main", () => {
- const source = makeDefinitionSource(0);
- // Unjustified type cast. FIXME
- const connDimMeta = {
- __dim: "productCategory",
- } as unknown as LibMetric.DimensionMetadata;
- // Unjustified type cast. FIXME
- const otherDimMeta = {
- __dim: "other",
- } as unknown as LibMetric.DimensionMetadata;
- // Unjustified type cast. FIXME
- const seg = { __seg: "x" } as unknown as LibMetric.SegmentMetadata;
-
- mockLibMetric.filterableDimensions.mockReturnValue([
- connDimMeta,
- otherDimMeta,
- ]);
- mockLibMetric.availableSegments.mockReturnValue([seg]);
- mockLibMetric.displayInfo.mockImplementation(
- (_def: unknown, target: unknown) => {
- if (target === connDimMeta) {
- return getJoinedTabledDimensionInfo("Category", "conn1");
- }
- if (target === otherDimMeta) {
- return getJoinedTabledDimensionInfo("Other", "conn2");
- }
- if (target === seg) {
- return getSegmentInfo("Seg A");
- }
- throw new Error("unexpected displayInfo target");
- },
- );
-
- const [group] = getMetricGroups([source], {});
- // Two connection sections + one synthesized source-table section at top.
- expect(group.sections).toHaveLength(3);
- expect(group.sections[0].isSourceTable).toBe(true);
- expect(group.sections[0].items).toEqual([
- expect.objectContaining({ name: "Seg A", segment: seg }),
- ]);
- expect(group.sections.slice(1).every((s) => s.isSourceTable !== true)).toBe(
- true,
- );
});
it("scopes segments per definition source index", () => {
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricControls/CenterControls/components/ControlsContent/ControlsContent.tsx b/frontend/src/metabase/metrics-viewer/components/MetricControls/CenterControls/components/ControlsContent/ControlsContent.tsx
index c1f0876da97..8f72079d6a4 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricControls/CenterControls/components/ControlsContent/ControlsContent.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricControls/CenterControls/components/ControlsContent/ControlsContent.tsx
@@ -5,6 +5,7 @@ import { useMetricsViewerContext } from "metabase/metrics-viewer/context";
import type { MetricsViewerDimensionBreakoutProjectionConfig } from "metabase/metrics-viewer/types";
import {
type DimensionFilterValue,
+ getDimensionBreakoutLabel,
getDimensionIcon,
getProjectionInfo,
} from "metabase/metrics-viewer/utils";
@@ -44,6 +45,8 @@ export function ControlsContent(props: ControlsContentProps) {
const {
activeDimensionBreakout: dimensionBreakout,
availableDimensions,
+ definitions,
+ metricSlots,
sourceOrder,
openSidebar,
updateActiveDimensionBreakout,
@@ -102,9 +105,9 @@ export function ControlsContent(props: ControlsContentProps) {
);
const columnPickerLabel =
- dimensionBreakout?.type === "time"
- ? t`Time`
- : (dimensionBreakout?.label ?? t`Select column`);
+ (dimensionBreakout
+ ? getDimensionBreakoutLabel(dimensionBreakout, definitions, metricSlots)
+ : null) ?? t`Select column`;
const dimensionFilter = dimensionBreakout?.projectionConfig.dimensionFilter;
return (
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx
index 6f30d789aa4..66dbf8a85c0 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx
@@ -12,6 +12,11 @@ import {
createMetricMetadata,
setupDefinition,
} from "metabase/metrics-viewer/utils/__tests__/test-helpers";
+import {
+ createMockMetricDimension,
+ createMockMetricDimensionGroup,
+ createMockNormalizedMetric,
+} from "metabase-types/api/mocks/metric";
import { MetricPill } from "./MetricPill";
@@ -90,6 +95,43 @@ describe("MetricPill action menu", () => {
expect(screen.getByText("Go to metric home page")).toBeInTheDocument();
});
+ it("shows curated dimension names without table headings", async () => {
+ const productsGroup = createMockMetricDimensionGroup({
+ id: "products",
+ type: "connection",
+ display_name: "Products",
+ });
+ const metric = createMockNormalizedMetric({
+ id: 2,
+ name: "Product revenue",
+ dimensions: [
+ createMockMetricDimension({
+ id: "product-category",
+ display_name: "Product type",
+ group: productsGroup,
+ }),
+ createMockMetricDimension({
+ id: "product-title",
+ display_name: "Product name",
+ group: productsGroup,
+ }),
+ ],
+ });
+ const metadata = createMetricMetadata([metric]);
+ const definition = setupDefinition(metadata, metric.id);
+
+ setup({
+ metric: { id: metric.id, name: metric.name, sourceType: "metric" },
+ definitionEntry: { id: "metric:2", definition },
+ });
+ await openPillMenu();
+ await userEvent.click(screen.getByText("Add a series breakout"));
+
+ expect(screen.getByText("Product type")).toBeInTheDocument();
+ expect(screen.getByText("Product name")).toBeInTheDocument();
+ expect(screen.queryByText("Products")).not.toBeInTheDocument();
+ });
+
it("should open the MetricSearchDropdown when Replace is clicked", async () => {
setup({
metric: { id: 1, name: "Revenue", sourceType: "metric" },
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.ts b/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.ts
index 2a9f2278613..d4e01f456b1 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.ts
@@ -10,26 +10,27 @@ export type FilterDisplayParts = {
value: string | null;
};
+function getDimensionName(
+ definition: LibMetric.MetricDefinition,
+ dimension: LibMetric.DimensionMetadata,
+) {
+ return LibMetric.displayInfo(definition, dimension).displayName;
+}
+
export function getFilterDisplayParts(
definition: LibMetric.MetricDefinition,
filter: LibMetric.FilterClause,
): FilterDisplayParts {
const stringParts = LibMetric.stringFilterParts(definition, filter);
if (stringParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- stringParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, stringParts.dimension);
const op = Lib.describeFilterOperator(stringParts.operator).toLowerCase();
return { label: `${dimName} ${op}:`, value: stringParts.values.join(", ") };
}
const booleanParts = LibMetric.booleanFilterParts(definition, filter);
if (booleanParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- booleanParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, booleanParts.dimension);
if (booleanParts.operator === "=") {
return {
label: `${dimName}:`,
@@ -44,10 +45,7 @@ export function getFilterDisplayParts(
const timeParts = LibMetric.timeFilterParts(definition, filter);
if (timeParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- timeParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, timeParts.dimension);
const op = Lib.describeFilterOperator(timeParts.operator).toLowerCase();
const formattedValues = timeParts.values
.map((d) => d.toLocaleTimeString())
@@ -59,10 +57,7 @@ export function getFilterDisplayParts(
if (dateValue) {
const dateParts = LibMetric.filterParts(definition, filter);
if (dateParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- dateParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, dateParts.dimension);
return {
label: `${dimName}:`,
value: getDateFilterDisplayName(dateValue),
@@ -72,20 +67,14 @@ export function getFilterDisplayParts(
const numberParts = LibMetric.numberFilterParts(definition, filter);
if (numberParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- numberParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, numberParts.dimension);
const op = Lib.describeFilterOperator(numberParts.operator).toLowerCase();
return { label: `${dimName} ${op}:`, value: numberParts.values.join(", ") };
}
const coordParts = LibMetric.coordinateFilterParts(definition, filter);
if (coordParts) {
- const dimName = LibMetric.displayInfo(
- definition,
- coordParts.dimension,
- ).longDisplayName;
+ const dimName = getDimensionName(definition, coordParts.dimension);
const op = Lib.describeFilterOperator(coordParts.operator).toLowerCase();
return { label: `${dimName} ${op}:`, value: coordParts.values.join(", ") };
}
@@ -93,7 +82,7 @@ export function getFilterDisplayParts(
const parts = LibMetric.filterParts(definition, filter);
if (parts) {
return {
- label: LibMetric.displayInfo(definition, parts.dimension).longDisplayName,
+ label: getDimensionName(definition, parts.dimension),
value: null,
};
}
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.unit.spec.ts b/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.unit.spec.ts
new file mode 100644
index 00000000000..6947f028bf4
--- /dev/null
+++ b/frontend/src/metabase/metrics-viewer/components/MetricsFilterPills/utils.unit.spec.ts
@@ -0,0 +1,44 @@
+import * as LibMetric from "metabase-lib/metric";
+
+import {
+ REVENUE_METRIC,
+ createMetricMetadata,
+ setupDefinition,
+} from "../../utils/__tests__/test-helpers";
+
+import { getFilterDisplayParts } from "./utils";
+
+const metadata = createMetricMetadata([REVENUE_METRIC]);
+
+describe("getFilterDisplayParts", () => {
+ it("uses the short dimension name for filter pills (UXW-4849)", () => {
+ const definition = setupDefinition(metadata, REVENUE_METRIC.id);
+ const dimension = LibMetric.filterableDimensions(definition).find(
+ (dimension) =>
+ LibMetric.displayInfo(definition, dimension).displayName === "Category",
+ );
+
+ expect(dimension).toBeDefined();
+ if (!dimension) {
+ return;
+ }
+
+ const filter = LibMetric.stringFilterClause({
+ operator: "=",
+ dimension,
+ values: ["Doohickey", "Gadget"],
+ options: {},
+ });
+ const displayInfo = LibMetric.displayInfo(definition, dimension);
+ jest.spyOn(LibMetric, "displayInfo").mockReturnValue({
+ ...displayInfo,
+ displayName: "Category",
+ longDisplayName: "Product → Category",
+ });
+
+ expect(getFilterDisplayParts(definition, filter)).toEqual({
+ label: "Category is:",
+ value: "Doohickey, Gadget",
+ });
+ });
+});
diff --git a/frontend/src/metabase/metrics-viewer/types/viewer-state.ts b/frontend/src/metabase/metrics-viewer/types/viewer-state.ts
index 1cb817e95a1..80ecff74230 100644
--- a/frontend/src/metabase/metrics-viewer/types/viewer-state.ts
+++ b/frontend/src/metabase/metrics-viewer/types/viewer-state.ts
@@ -135,6 +135,7 @@ export interface AvailableDimension {
group?: DimensionGroup;
canListValues?: boolean;
isPreferred?: boolean;
+ isDefault?: boolean;
geoSubtype?: GeoSubtype | null;
dimensionBreakoutInfo: DimensionBreakoutInfo;
}
diff --git a/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.ts b/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.ts
index 10c41c830ec..1977f617fb7 100644
--- a/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.ts
@@ -2,7 +2,10 @@ import { t } from "ttag";
import type { DimensionDescriptor } from "metabase/common/metrics/utils/dimension-descriptors";
import { getDimensionDescriptors } from "metabase/common/metrics/utils/dimension-descriptors";
-import { GEO_SUBTYPE_PRIORITY } from "metabase/common/metrics/utils/dimension-types";
+import {
+ GEO_SUBTYPE_PRIORITY,
+ getGeoSubtype,
+} from "metabase/common/metrics/utils/dimension-types";
import { getObjectEntries, objectFromEntries } from "metabase/utils/objects";
import { isNotNull } from "metabase/utils/types";
import type { DimensionMetadata, MetricDefinition } from "metabase-lib/metric";
@@ -666,11 +669,80 @@ export function computeDefaultDimensionBreakouts(
dimensionBreakouts.sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
- return dimensionBreakouts.map(
- ({ index, ...dimensionBreakout }) => dimensionBreakout,
+ return promoteDefaultDimensionBreakout(
+ dimensionBreakouts.map(
+ ({ index, ...dimensionBreakout }) => dimensionBreakout,
+ ),
+ dimensionsBySlotIndex,
+ slotOrder,
);
}
+function findDefaultDimension(
+ dimensionsBySlotIndex: Map<number, Map<string, DimensionDescriptor>>,
+ slotOrder: number[],
+): DimensionDescriptor | null {
+ for (const slotIndex of slotOrder) {
+ for (const [, info] of dimensionsBySlotIndex.get(slotIndex) ?? []) {
+ if (info.isDefault) {
+ return info;
+ }
+ }
+ }
+ return null;
+}
+
+function promoteDefaultDimensionBreakout(
+ dimensionBreakouts: MetricsViewerDimensionBreakoutState[],
+ dimensionsBySlotIndex: Map<number, Map<string, DimensionDescriptor>>,
+ slotOrder: number[],
+): MetricsViewerDimensionBreakoutState[] {
+ const defaultDimension = findDefaultDimension(
+ dimensionsBySlotIndex,
+ slotOrder,
+ );
+ if (!defaultDimension) {
+ return dimensionBreakouts;
+ }
+
+ const config = getDimensionBreakoutConfig(defaultDimension.dimensionType);
+ const defaultBreakoutId =
+ config.matchMode === "aggregate" ? config.fixedId : defaultDimension.id;
+
+ const existing = dimensionBreakouts.find(
+ (dimensionBreakout) => dimensionBreakout.id === defaultBreakoutId,
+ );
+ if (existing) {
+ return [
+ existing,
+ ...dimensionBreakouts.filter(
+ (dimensionBreakout) => dimensionBreakout !== existing,
+ ),
+ ];
+ }
+ if (config.matchMode === "aggregate") {
+ return dimensionBreakouts;
+ }
+
+ const mapping: Record<number, string> = {};
+ for (const slotIndex of slotOrder) {
+ if (dimensionsBySlotIndex.get(slotIndex)?.has(defaultDimension.id)) {
+ mapping[slotIndex] = defaultDimension.id;
+ }
+ }
+ return [
+ {
+ id: defaultDimension.id,
+ type: defaultDimension.dimensionType,
+ label: defaultDimension.displayName,
+ display: config.defaultDisplayType,
+ dimensionMapping: mapping,
+ projectionConfig: {},
+ },
+ ...dimensionBreakouts,
+ ];
+}
+
// ── Manual dimensionBreakout creation ──
export function createDimensionBreakoutFromInfo(
@@ -721,6 +793,69 @@ export function getScalarDimensionBreakoutLabel() {
return t`Totals`;
}
+export function getDimensionBreakoutTypeLabel(
+ type: MetricsViewerDimensionBreakoutType,
+): string | null {
+ switch (type) {
+ case "time":
+ return t`Time`;
+ case "category":
+ return t`Category`;
+ case "boolean":
+ return t`Boolean`;
+ case "numeric":
+ return t`Number`;
+
+ // Geo has per-subtype naming and scalar has its own label
+ default:
+ return null;
+ }
+}
+
+export function getDimensionBreakoutLabel(
+ dimensionBreakout: MetricsViewerDimensionBreakoutState,
+ definitions: Record<MetricSourceId, MetricsViewerDefinitionEntry>,
+ metricSlots: MetricSlot[],
+): string | null {
+ if (dimensionBreakout.type === "time") {
+ return getDimensionBreakoutTypeLabel("time");
+ }
+
+ const dimensions = metricSlots.flatMap((slot) => {
+ const dimensionId = dimensionBreakout.dimensionMapping[slot.slotIndex];
+ const definition = definitions[slot.sourceId]?.definition;
+ if (!dimensionId || !definition) {
+ return [];
+ }
+
+ const dimension = getDimensionDescriptors(definition).get(dimensionId);
+ return dimension ? [dimension] : [];
+ });
+
+ if (
+ dimensionBreakout.type === "geo" &&
+ dimensions.some(
+ (dimension) => getGeoSubtype(dimension.dimensionMetadata) === "state",
+ )
+ ) {
+ return t`State`;
+ }
+
+ if (dimensions.length === 0) {
+ return dimensionBreakout.label;
+ }
+
+ const [firstDimension] = dimensions;
+ const haveSameDisplayName = dimensions.every(
+ (dimension) => dimension.displayName === firstDimension.displayName,
+ );
+
+ return haveSameDisplayName && !!firstDimension.displayName
+ ? firstDimension.displayName
+ : (getDimensionBreakoutTypeLabel(dimensionBreakout.type) ??
+ dimensionBreakout.label);
+}
+
// ── DimensionBreakout dimension matching ──
function findSubtypeFromExistingDimensionBreakout(
@@ -831,10 +966,11 @@ function resolveSubtypeFallback(
}
/**
- * Resolve a stored breakout to a dimension in `dimensions` by exact identity:
- * first by dimension id, then by matching an already-mapped slot's reference
- * and requiring a shared underlying source (same physical column/table) via
- * `LibMetric.isSameSource`.
+ * Resolve a stored breakout to a dimension in `dimensions`: first by dimension
+ * id, then from an already-mapped slot's reference via the shared-source →
+ * curated-name → compatible-type ladder. The fallbacks let metrics pair
+ * dimensions of the same type even without a shared physical column (e.g.
+ * across databases).
*/
function findExactColumnMatch(
dimensions: Map<string, DimensionDescriptor>,
@@ -854,29 +990,9 @@ function findExactColumnMatch(
slotIndexToSourceId,
);
if (reference) {
- return findStrictExactColumnMatch(dimensions, reference)?.id ?? null;
- }
-
- return null;
-}
-
-function findStrictExactColumnMatch(
- dimensions: Map<string, DimensionDescriptor>,
- reference: DimensionDescriptor,
-): DimensionDescriptor | null {
- for (const [, info] of dimensions) {
- if (info.dimensionType !== reference.dimensionType) {
- continue;
- }
-
- if (
- LibMetric.isSameSource(
- info.dimensionMetadata,
- reference.dimensionMetadata,
- )
- ) {
- return info;
- }
+ return (
+ findSourceMatch(dimensions, dimensionBreakout.type, reference)?.id ?? null
+ );
}
return null;
diff --git a/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.unit.spec.ts b/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.unit.spec.ts
index 8aed648917f..5f6a874aa8d 100644
--- a/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.unit.spec.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/dimension-breakouts.unit.spec.ts
@@ -1,4 +1,10 @@
-import type { MetricSourceId } from "../types/viewer-state";
+import { createMockMetricDimensionGroup } from "metabase-types/api/mocks/metric";
+
+import type {
+ MetricSourceId,
+ MetricsViewerDefinitionEntry,
+ MetricsViewerDimensionBreakoutState,
+} from "../types/viewer-state";
import {
createMetricMetadata,
@@ -10,9 +16,203 @@ import {
computeDefaultDimensionBreakouts,
createDimensionBreakoutFromInfo,
findMatchingDimensionForBreakout,
+ getDimensionBreakoutLabel,
+ getDimensionBreakoutTypeLabel,
resolveCommonDimensionBreakoutLabel,
} from "./dimension-breakouts";
+describe("getDimensionBreakoutTypeLabel", () => {
+ it.each([
+ ["time", "Time"],
+ ["category", "Category"],
+ ["boolean", "Boolean"],
+ ["numeric", "Number"],
+ ] as const)("labels %s breakouts by dimension type", (type, label) => {
+ expect(getDimensionBreakoutTypeLabel(type)).toBe(label);
+ });
+
+ it.each(["geo", "scalar"] as const)(
+ "returns null for %s breakouts, which keep their own labels",
+ (type) => {
+ expect(getDimensionBreakoutTypeLabel(type)).toBeNull();
+ },
+ );
+});
+
+describe("getDimensionBreakoutLabel", () => {
+ const firstMetric = createMockNormalizedMetric({
+ id: 201,
+ dimensions: [
+ createMockMetricDimension({
+ id: "first-vendor",
+ name: "VENDOR",
+ display_name: "Preferred vendor",
+ semantic_type: "type/Category",
+ group: createMockMetricDimensionGroup({ display_name: "Orders" }),
+ }),
+ createMockMetricDimension({
+ id: "first-total",
+ name: "AMOUNT",
+ display_name: "Total",
+ effective_type: "type/Float",
+ semantic_type: "type/Currency",
+ }),
+ createMockMetricDimension({
+ id: "first-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ }),
+ createMockMetricDimension({
+ id: "first-state",
+ display_name: "Shipping region",
+ semantic_type: "type/State",
+ }),
+ ],
+ });
+ const secondMetric = createMockNormalizedMetric({
+ id: 202,
+ dimensions: [
+ createMockMetricDimension({
+ id: "second-vendor",
+ name: "VENDOR",
+ display_name: "Vendor",
+ semantic_type: "type/Category",
+ group: createMockMetricDimensionGroup({ display_name: "Products" }),
+ }),
+ createMockMetricDimension({
+ id: "second-total",
+ name: "PAID_AMOUNT",
+ display_name: "Total",
+ effective_type: "type/Float",
+ semantic_type: "type/Currency",
+ }),
+ createMockMetricDimension({
+ id: "second-subtotal",
+ display_name: "Subtotal",
+ effective_type: "type/Float",
+ semantic_type: "type/Currency",
+ }),
+ ],
+ });
+ const firstSourceId: MetricSourceId = `metric:${firstMetric.id}`;
+ const secondSourceId: MetricSourceId = `metric:${secondMetric.id}`;
+ const metadata = createMetricMetadata([firstMetric, secondMetric]);
+ const definitions: Record<MetricSourceId, MetricsViewerDefinitionEntry> = {
+ [firstSourceId]: {
+ id: firstSourceId,
+ definition: setupDefinition(metadata, firstMetric.id),
+ },
+ [secondSourceId]: {
+ id: secondSourceId,
+ definition: setupDefinition(metadata, secondMetric.id),
+ },
+ };
+ const metricSlots = [
+ { slotIndex: 0, entityIndex: 0, sourceId: firstSourceId },
+ { slotIndex: 1, entityIndex: 1, sourceId: secondSourceId },
+ ];
+
+ function createBreakout(
+ type: MetricsViewerDimensionBreakoutState["type"],
+ dimensionMapping: Record<number, string | null>,
+ label: string,
+ ): MetricsViewerDimensionBreakoutState {
+ return {
+ id: label,
+ type,
+ label,
+ display: "bar",
+ dimensionMapping,
+ projectionConfig: {},
+ };
+ }
+
+ it("uses the breakout type when mapped dimensions have different curated display names", () => {
+ const breakout = createBreakout(
+ "category",
+ { 0: "first-vendor", 1: "second-vendor" },
+ "Category",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Category",
+ );
+ });
+
+ it("uses the curated display name when mapped columns have different names", () => {
+ const breakout = createBreakout(
+ "numeric",
+ { 0: "first-total", 1: "second-total" },
+ "Number",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Total",
+ );
+ });
+
+ it("uses the breakout type when mapped column names differ", () => {
+ const breakout = createBreakout(
+ "numeric",
+ { 0: "first-total", 1: "second-subtotal" },
+ "Total",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Number",
+ );
+ });
+
+ it("uses the curated display name when only one slot is mapped", () => {
+ const breakout = createBreakout(
+ "numeric",
+ { 0: "first-total", 1: null },
+ "Number",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Total",
+ );
+ });
+
+ it("always labels time breakouts by type", () => {
+ const breakout = createBreakout(
+ "time",
+ { 0: "first-created-at" },
+ "Created At",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Time",
+ );
+ });
+
+ it("always labels state breakouts by subtype", () => {
+ const breakout = createBreakout(
+ "geo",
+ { 0: "first-state" },
+ "Shipping region",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "State",
+ );
+ });
+
+ it("falls back to the stored label when no mapped dimension resolves", () => {
+ const breakout = createBreakout(
+ "category",
+ { 0: "missing-dimension" },
+ "Stored label",
+ );
+
+ expect(getDimensionBreakoutLabel(breakout, definitions, metricSlots)).toBe(
+ "Stored label",
+ );
+ });
+});
+
describe("resolveCommonDimensionBreakoutLabel", () => {
it("returns null for empty array", () => {
expect(resolveCommonDimensionBreakoutLabel([])).toBeNull();
@@ -131,6 +331,144 @@ describe("computeDefaultDimensionBreakouts", () => {
dimensionBreakouts.map((dimensionBreakout) => dimensionBreakout.label),
).toEqual(["Category", "Totals"]);
});
+
+ describe("curated default dimension", () => {
+ const setupMetric = (
+ metric: ReturnType<typeof createMockNormalizedMetric>,
+ ) => {
+ const metricSourceId: MetricSourceId = `metric:${metric.id}`;
+ const metricDefinition = setupDefinition(
+ createMetricMetadata([metric]),
+ metric.id,
+ );
+ return computeDefaultDimensionBreakouts(
+ { [metricSourceId]: metricDefinition },
+ [{ slotIndex: 0, entityIndex: 0, sourceId: metricSourceId }],
+ );
+ };
+
+ it("puts the curated default dimension's breakout first", () => {
+ const dimensionBreakouts = setupMetric(
+ createMockNormalizedMetric({
+ id: 102,
+ name: "Category Default",
+ dimensions: [
+ createMockMetricDimension({
+ id: "dim-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ }),
+ createMockMetricDimension({
+ id: "dim-default-category",
+ display_name: "Category",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ default: true,
+ }),
+ ],
+ }),
+ );
+
+ expect(
+ dimensionBreakouts.map((dimensionBreakout) => dimensionBreakout.label),
+ ).toEqual(["Category", "Created At", "Totals"]);
+ expect(dimensionBreakouts[0]).toMatchObject({
+ id: "dim-default-category",
+ type: "category",
+ dimensionMapping: { 0: "dim-default-category" },
+ });
+ });
+
+ it("creates and promotes a breakout for a non-preferred curated default", () => {
+ const dimensionBreakouts = setupMetric(
+ createMockNormalizedMetric({
+ id: 103,
+ name: "Non-preferred Default",
+ dimensions: [
+ createMockMetricDimension({
+ id: "dim-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ }),
+ createMockMetricDimension({
+ id: "dim-default-status",
+ display_name: "Status",
+ effective_type: "type/Text",
+ semantic_type: null,
+ default: true,
+ }),
+ ],
+ }),
+ );
+
+ expect(
+ dimensionBreakouts.map((dimensionBreakout) => dimensionBreakout.label),
+ ).toEqual(["Status", "Created At", "Totals"]);
+ expect(dimensionBreakouts[0].dimensionMapping).toEqual({
+ 0: "dim-default-status",
+ });
+ });
+
+ it("creates and promotes a breakout for a curated default of a type that never auto-creates", () => {
+ const dimensionBreakouts = setupMetric(
+ createMockNormalizedMetric({
+ id: 104,
+ name: "Numeric Default",
+ dimensions: [
+ createMockMetricDimension({
+ id: "dim-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ }),
+ createMockMetricDimension({
+ id: "dim-default-amount",
+ display_name: "Amount",
+ effective_type: "type/Float",
+ semantic_type: "type/Currency",
+ default: true,
+ }),
+ ],
+ }),
+ );
+
+ expect(
+ dimensionBreakouts.map((dimensionBreakout) => dimensionBreakout.label),
+ ).toEqual(["Amount", "Created At", "Totals"]);
+ expect(dimensionBreakouts[0].type).toBe("numeric");
+ });
+
+ it("keeps the time breakout first and unduplicated when the curated default is a time dimension", () => {
+ const dimensionBreakouts = setupMetric(
+ createMockNormalizedMetric({
+ id: 105,
+ name: "Time Default",
+ dimensions: [
+ createMockMetricDimension({
+ id: "dim-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ default: true,
+ }),
+ createMockMetricDimension({
+ id: "dim-default-category",
+ display_name: "Category",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ }),
+ ],
+ }),
+ );
+
+ expect(
+ dimensionBreakouts.map((dimensionBreakout) => dimensionBreakout.label),
+ ).toEqual(["Created At", "Category", "Totals"]);
+ expect(dimensionBreakouts[0].id).toBe("time");
+ });
+ });
});
describe("findMatchingDimensionForBreakout", () => {
@@ -205,7 +543,7 @@ describe("findMatchingDimensionForBreakout", () => {
MATCHING_SHARED_SOURCE_METRIC.id,
);
- it("does not match exact-column dimensions without the same table group", () => {
+ it("matches exact-column dimensions by curated name across sources", () => {
expect(
findMatchingDimensionForBreakout(
secondDefinition,
@@ -218,7 +556,38 @@ describe("findMatchingDimensionForBreakout", () => {
{ [firstSourceId]: firstDefinition },
new Map([[0, firstSourceId]]),
),
- ).toBeNull();
+ ).toBe("dim-second-last-name");
+ });
+
+ it("falls back to a same-type dimension when neither source nor name match", () => {
+ const TIER_METRIC = createMockNormalizedMetric({
+ id: 205,
+ name: "Tier Metric",
+ dimensions: [
+ createMockMetricDimension({
+ id: "dim-tier",
+ display_name: "Tier",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ }),
+ ],
+ });
+ const tierMetadata = createMetricMetadata([FIRST_METRIC, TIER_METRIC]);
+ const tierDefinition = setupDefinition(tierMetadata, TIER_METRIC.id);
+
+ expect(
+ findMatchingDimensionForBreakout(
+ tierDefinition,
+ {
+ id: "dim-first-last-name",
+ type: "category",
+ label: "Last Name",
+ dimensionBySlotIndex: { 0: "dim-first-last-name" },
+ },
+ { [firstSourceId]: setupDefinition(tierMetadata, FIRST_METRIC.id) },
+ new Map([[0, firstSourceId]]),
+ ),
+ ).toBe("dim-tier");
});
it("matches the exact dimension id when available", () => {
diff --git a/frontend/src/metabase/metrics-viewer/utils/dimension-picker.ts b/frontend/src/metabase/metrics-viewer/utils/dimension-picker.ts
index 222878b1a4c..449d48b4697 100644
--- a/frontend/src/metabase/metrics-viewer/utils/dimension-picker.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/dimension-picker.ts
@@ -58,6 +58,7 @@ interface DimensionEntry {
group?: DimensionGroup;
canListValues: boolean;
isPreferred?: boolean;
+ isDefault?: boolean;
geoSubtype?: GeoSubtype | null;
sourceId: MetricSourceId;
}
@@ -91,6 +92,7 @@ function collectAllDimensionEntries(
group: info.group,
canListValues: info.canListValues,
isPreferred: info.isPreferred,
+ ...(info.isDefault ? { isDefault: true } : {}),
...(geoSubtype ? { geoSubtype } : {}),
sourceId,
});
@@ -157,6 +159,7 @@ export function getAvailableDimensionsForPicker(
group: first.group,
canListValues: first.canListValues,
isPreferred: first.isPreferred,
+ ...(first.isDefault ? { isDefault: true } : {}),
...(first.geoSubtype ? { geoSubtype: first.geoSubtype } : {}),
dimensionBreakoutInfo: {
type: first.dimensionBreakoutType,
@@ -179,6 +182,7 @@ export function getAvailableDimensionsForPicker(
group: entry.group,
canListValues: entry.canListValues,
isPreferred: entry.isPreferred,
+ ...(entry.isDefault ? { isDefault: true } : {}),
...(entry.geoSubtype ? { geoSubtype: entry.geoSubtype } : {}),
dimensionBreakoutInfo: {
type: entry.dimensionBreakoutType,
@@ -195,19 +199,8 @@ export function getAvailableDimensionsForPicker(
}
}
- result.shared.sort((first, second) =>
- first.dimensionBreakoutInfo.label.localeCompare(
- second.dimensionBreakoutInfo.label,
- ),
- );
- for (const sourceId of sourceOrder) {
- result.bySource[sourceId]?.sort((first, second) =>
- first.dimensionBreakoutInfo.label.localeCompare(
- second.dimensionBreakoutInfo.label,
- ),
- );
- }
-
+ // No sorting: entries keep the metric's curated dimension order (shared
+ // entries follow the first source's curation).
return result;
}
@@ -260,29 +253,15 @@ export function getComparableDimensionKey(item: DimensionPickerItem) {
return "type:time";
}
- if (type === "geo" && item.geoSubtype === "country") {
- return "type:geo:country";
+ if (type === "geo" && item.geoSubtype != null) {
+ return `type:geo:${item.geoSubtype}`;
}
- return [type, item.group?.id ?? "", item.name].join(":");
-}
-
-function getDimensionPickerItemByDimensionId(
- sections: DimensionPickerSection[],
-) {
- const itemsByDimensionId = new Map<string, DimensionPickerItem>();
-
- for (const item of sections.flatMap((section) => section.items)) {
- for (const dimensionId of Object.values(
- item.dimensionBreakoutInfo.dimensionMapping,
- )) {
- if (dimensionId != null && !itemsByDimensionId.has(dimensionId)) {
- itemsByDimensionId.set(dimensionId, item);
- }
- }
- }
-
- return itemsByDimensionId;
+ const mappingKey = Object.entries(item.dimensionBreakoutInfo.dimensionMapping)
+ .filter(([, dimensionId]) => dimensionId != null)
+ .map(([slotIndex, dimensionId]) => `${slotIndex}=${dimensionId}`)
+ .join("|");
+ return ["item", type, mappingKey].join(":");
}
export function getComparableDimensionMapping({
@@ -296,71 +275,57 @@ export function getComparableDimensionMapping({
metricSlots: MetricSlot[];
activeDimensionBreakout: MetricsViewerDimensionBreakoutState;
}): Record<number, string | null> {
- const comparableKey = getComparableDimensionKey(item);
- const slotIndices = new Set(metricSlots.map((slot) => slot.slotIndex));
- const mapping: Record<number, string | null> = Object.fromEntries(
- metricSlots.map((slot) => [slot.slotIndex, null]),
- );
- const clickedSlotIndices = new Set(
- Object.entries(item.dimensionBreakoutInfo.dimensionMapping)
- .filter(([, dimensionId]) => dimensionId != null)
- .map(([slotIndex]) => Number(slotIndex)),
- );
- const itemsByDimensionId = getDimensionPickerItemByDimensionId(sections);
- const comparableSectionItems = sections
- .flatMap((section) => section.items)
- .filter(
- (sectionItem) =>
- sectionItem !== item &&
- getComparableDimensionKey(sectionItem) === comparableKey,
- );
+ const type = item.dimensionBreakoutInfo.type;
+ const itemMapping = item.dimensionBreakoutInfo.dimensionMapping;
+ const isRefiningActiveType = activeDimensionBreakout.type === type;
+ const sectionItems = sections.flatMap((section) => section.items);
+ const mapping: Record<number, string | null> = {};
+
+ for (const slot of metricSlots) {
+ const slotIndex = slot.slotIndex;
- const comparableItems = [
- item,
- ...comparableSectionItems.filter(
- (sectionItem) => sectionItem.name === item.name,
- ),
- ...comparableSectionItems.filter(
- (sectionItem) => sectionItem.name !== item.name,
- ),
- ];
-
- for (const [slotIndex, dimensionId] of Object.entries(
- activeDimensionBreakout.dimensionMapping,
- )) {
- const numericSlotIndex = Number(slotIndex);
- if (
- !slotIndices.has(numericSlotIndex) ||
- clickedSlotIndices.has(numericSlotIndex)
- ) {
+ if (itemMapping[slotIndex] != null) {
+ mapping[slotIndex] = itemMapping[slotIndex];
continue;
}
- const currentItem = dimensionId
- ? itemsByDimensionId.get(dimensionId)
- : undefined;
- if (
- currentItem &&
- getComparableDimensionKey(currentItem) === comparableKey
- ) {
- mapping[numericSlotIndex] = dimensionId;
+ const activeDimensionId =
+ activeDimensionBreakout.dimensionMapping[slotIndex];
+ if (isRefiningActiveType && activeDimensionId !== undefined) {
+ mapping[slotIndex] = activeDimensionId;
+ continue;
}
- }
- for (const comparableItem of comparableItems) {
- for (const [slotIndex, dimensionId] of Object.entries(
- comparableItem.dimensionBreakoutInfo.dimensionMapping,
- )) {
- const numericSlotIndex = Number(slotIndex);
- if (slotIndices.has(numericSlotIndex)) {
- mapping[numericSlotIndex] ??= dimensionId;
- }
- }
+ mapping[slotIndex] = findSlotDimensionOfType(
+ sectionItems,
+ slotIndex,
+ type,
+ item.name,
+ );
}
return mapping;
}
+function findSlotDimensionOfType(
+ sectionItems: DimensionPickerItem[],
+ slotIndex: number,
+ type: MetricsViewerDimensionBreakoutType,
+ name: string,
+) {
+ const candidates = sectionItems.filter(
+ (candidate) =>
+ candidate.dimensionBreakoutInfo.type === type &&
+ candidate.dimensionBreakoutInfo.dimensionMapping[slotIndex] != null,
+ );
+ const match =
+ candidates.find((candidate) => candidate.name === name) ??
+ candidates.find((candidate) => candidate.isDefault) ??
+ candidates[0];
+
+ return match?.dimensionBreakoutInfo.dimensionMapping[slotIndex] ?? null;
+}
+
export function buildDimensionPickerSidebarCategorySelectRows({
category,
activeDimensionBreakout,
diff --git a/frontend/src/metabase/metrics-viewer/utils/dimension-picker.unit.spec.ts b/frontend/src/metabase/metrics-viewer/utils/dimension-picker.unit.spec.ts
index f1d044300e4..3db66414785 100644
--- a/frontend/src/metabase/metrics-viewer/utils/dimension-picker.unit.spec.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/dimension-picker.unit.spec.ts
@@ -45,16 +45,17 @@ const ordersDefinition = setupDefinition(allMetadata, ORDERS_METRIC.id);
const REVENUE_SOURCE_ID: MetricSourceId = `metric:${REVENUE_METRIC.id}`;
const ORDERS_SOURCE_ID: MetricSourceId = `metric:${ORDERS_METRIC.id}`;
+// Listed in the metric's curated dimension order, which the picker preserves.
const REVENUE_DIMENSIONS: AvailableDimension[] = [
{
- icon: "int",
+ icon: "calendar",
group: undefined,
canListValues: false,
isPreferred: undefined,
dimensionBreakoutInfo: {
- type: "numeric",
- label: "Amount",
- dimensionMapping: { 0: "dim-amount" },
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 0: "dim-created-at" },
},
},
{
@@ -69,14 +70,14 @@ const REVENUE_DIMENSIONS: AvailableDimension[] = [
},
},
{
- icon: "calendar",
+ icon: "int",
group: undefined,
canListValues: false,
isPreferred: undefined,
dimensionBreakoutInfo: {
- type: "time",
- label: "Created At",
- dimensionMapping: { 0: "dim-created-at" },
+ type: "numeric",
+ label: "Amount",
+ dimensionMapping: { 0: "dim-amount" },
},
},
{
@@ -140,6 +141,20 @@ describe("getAvailableDimensionsForPicker", () => {
});
});
+ it("preserves the curated dimension order instead of sorting alphabetically", () => {
+ const result = getAvailableDimensionsForPicker(
+ { [REVENUE_SOURCE_ID]: revenueDefinition },
+ [REVENUE_SOURCE_ID],
+ [{ slotIndex: 0, entityIndex: 0, sourceId: REVENUE_SOURCE_ID }],
+ new Set(),
+ );
+
+ const labels = (result.bySource[REVENUE_SOURCE_ID] ?? []).map(
+ (dimension) => dimension.dimensionBreakoutInfo.label,
+ );
+ expect(labels).toEqual(["Created At", "Category", "Amount", "Is Active"]);
+ });
+
it("returns dimensions for a second metric source", () => {
const result = getAvailableDimensionsForPicker(
{ [ORDERS_SOURCE_ID]: ordersDefinition },
@@ -584,6 +599,102 @@ describe("getComparableDimensionMapping", () => {
projectionConfig: {},
} satisfies MetricsViewerDimensionBreakoutState;
+ it("maps same-named category fields across metrics", () => {
+ const selectedItem = {
+ icon: "label",
+ name: "Product - Category",
+ group: { id: "group-a", type: "connection", displayName: "Product" },
+ dimensionBreakoutInfo: {
+ type: "category" as const,
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-sqlite-category" },
+ },
+ } as const;
+
+ expect(
+ getComparableDimensionMapping({
+ item: selectedItem,
+ sections: [
+ { items: [selectedItem], sourceId: REVENUE_SOURCE_ID },
+ {
+ items: [
+ {
+ icon: "label",
+ name: "Product - Category",
+ group: {
+ id: "group-b",
+ type: "connection",
+ displayName: "Product",
+ },
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Product - Category",
+ dimensionMapping: { 1: "dim-pg-category" },
+ },
+ },
+ ],
+ sourceId: ORDERS_SOURCE_ID,
+ },
+ ],
+ metricSlots,
+ activeDimensionBreakout,
+ }),
+ ).toEqual({
+ 0: "dim-sqlite-category",
+ 1: "dim-pg-category",
+ });
+ });
+
+ it("falls back to a same-type dimension for slots without a name match", () => {
+ const selectedItem = {
+ icon: "label",
+ name: "Product - Category",
+ group: { id: "group-a", type: "connection", displayName: "Product" },
+ dimensionBreakoutInfo: {
+ type: "category" as const,
+ label: "Product - Category",
+ dimensionMapping: { 0: "dim-sqlite-category" },
+ },
+ } as const;
+
+ expect(
+ getComparableDimensionMapping({
+ item: selectedItem,
+ sections: [
+ { items: [selectedItem], sourceId: REVENUE_SOURCE_ID },
+ {
+ items: [
+ {
+ icon: "calendar",
+ name: "Created At",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "dim-created-at" },
+ },
+ },
+ {
+ icon: "label",
+ name: "Plan Type",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Plan Type",
+ dimensionMapping: { 1: "dim-plan-type" },
+ },
+ },
+ ],
+ sourceId: ORDERS_SOURCE_ID,
+ },
+ ],
+ metricSlots,
+ activeDimensionBreakout,
+ }),
+ ).toEqual({
+ 0: "dim-sqlite-category",
+ 1: "dim-plan-type",
+ });
+ });
+
it("maps time fields across metric slots", () => {
const selectedItem = {
icon: "calendar",
@@ -897,7 +1008,7 @@ describe("getComparableDimensionMapping", () => {
});
});
- it("does not map same-named category fields from different tables", () => {
+ it("maps same-named category fields from different tables", () => {
const selectedItem = {
icon: "label",
name: "Name",
@@ -937,14 +1048,14 @@ describe("getComparableDimensionMapping", () => {
metricSlots,
activeDimensionBreakout,
}),
- ).toEqual({ 0: "dim-user-name", 1: null });
+ ).toEqual({ 0: "dim-user-name", 1: "dim-product-name" });
});
it.each([
["Address", "dim-revenue-user-address"],
["Name", "dim-revenue-user-name"],
])(
- "does not preserve an incompatible active field when selecting %s",
+ "falls back to the other slot's same-type field when selecting %s",
(fieldName, fieldId) => {
const selectedItem = {
icon: "label",
@@ -991,11 +1102,11 @@ describe("getComparableDimensionMapping", () => {
dimensionMapping: { 1: "dim-accounts-email" },
},
}),
- ).toEqual({ 0: fieldId, 1: null });
+ ).toEqual({ 0: fieldId, 1: "dim-accounts-email" });
},
);
- it("does not map same-typed numeric fields from different tables", () => {
+ it("maps same-typed numeric fields from different tables", () => {
const selectedItem = {
icon: "int",
name: "Total",
@@ -1035,7 +1146,7 @@ describe("getComparableDimensionMapping", () => {
metricSlots,
activeDimensionBreakout,
}),
- ).toEqual({ 0: "dim-orders-total", 1: null });
+ ).toEqual({ 0: "dim-orders-total", 1: "dim-products-price" });
});
it("maps exact same table and column category fields across metric slots", () => {
@@ -1076,4 +1187,130 @@ describe("getComparableDimensionMapping", () => {
}),
).toEqual({ 0: "dim-user-name", 1: "dim-user-name" });
});
+
+ it("prefers the other slot's same-type default dimension over curated order", () => {
+ const selectedItem = {
+ icon: "label",
+ name: "Status",
+ dimensionBreakoutInfo: {
+ type: "category" as const,
+ label: "Status",
+ dimensionMapping: { 0: "dim-revenue-status" },
+ },
+ } as const;
+
+ expect(
+ getComparableDimensionMapping({
+ item: selectedItem,
+ sections: [
+ { items: [selectedItem], sourceId: REVENUE_SOURCE_ID },
+ {
+ items: [
+ {
+ icon: "label",
+ name: "Priority",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Priority",
+ dimensionMapping: { 1: "dim-priority" },
+ },
+ },
+ {
+ icon: "label",
+ name: "Level",
+ isDefault: true,
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Level",
+ dimensionMapping: { 1: "dim-level" },
+ },
+ },
+ ],
+ sourceId: ORDERS_SOURCE_ID,
+ },
+ ],
+ metricSlots,
+ activeDimensionBreakout,
+ }),
+ ).toEqual({ 0: "dim-revenue-status", 1: "dim-level" });
+ });
+
+ it("disables slots without a dimension of the picked type", () => {
+ const selectedItem = {
+ icon: "label",
+ name: "Status",
+ dimensionBreakoutInfo: {
+ type: "category" as const,
+ label: "Status",
+ dimensionMapping: { 0: "dim-revenue-status" },
+ },
+ } as const;
+
+ expect(
+ getComparableDimensionMapping({
+ item: selectedItem,
+ sections: [
+ { items: [selectedItem], sourceId: REVENUE_SOURCE_ID },
+ {
+ items: [
+ {
+ icon: "calendar",
+ name: "Created At",
+ dimensionBreakoutInfo: {
+ type: "time",
+ label: "Created At",
+ dimensionMapping: { 1: "dim-orders-created-at" },
+ },
+ },
+ ],
+ sourceId: ORDERS_SOURCE_ID,
+ },
+ ],
+ metricSlots,
+ activeDimensionBreakout,
+ }),
+ ).toEqual({ 0: "dim-revenue-status", 1: null });
+ });
+
+ it("keeps a deselected slot disabled when refining the same type", () => {
+ const selectedItem = {
+ icon: "label",
+ name: "Status",
+ dimensionBreakoutInfo: {
+ type: "category" as const,
+ label: "Status",
+ dimensionMapping: { 0: "dim-revenue-status" },
+ },
+ } as const;
+
+ expect(
+ getComparableDimensionMapping({
+ item: selectedItem,
+ sections: [
+ { items: [selectedItem], sourceId: REVENUE_SOURCE_ID },
+ {
+ items: [
+ {
+ icon: "label",
+ name: "Status",
+ dimensionBreakoutInfo: {
+ type: "category",
+ label: "Status",
+ dimensionMapping: { 1: "dim-orders-status" },
+ },
+ },
+ ],
+ sourceId: ORDERS_SOURCE_ID,
+ },
+ ],
+ metricSlots,
+ activeDimensionBreakout: {
+ ...activeDimensionBreakout,
+ type: "category",
+ display: "bar",
+ dimensionMapping: { 0: "dim-revenue-other", 1: null },
+ },
+ }),
+ ).toEqual({ 0: "dim-revenue-status", 1: null });
+ });
});
diff --git a/frontend/src/metabase/metrics-viewer/utils/legend.ts b/frontend/src/metabase/metrics-viewer/utils/legend.ts
index a4cd139292d..43fcb85b027 100644
--- a/frontend/src/metabase/metrics-viewer/utils/legend.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/legend.ts
@@ -91,10 +91,6 @@ export function buildLegendGroups(
effectiveEntry.definition,
breakoutProjection,
);
- const dimensionInfo = rawDimension
- ? LibMetric.displayInfo(effectiveEntry.definition, rawDimension)
- : null;
-
const items: LegendItem[] = Array.from(colors.entries()).map(
([breakoutValue, color]) => ({
label: breakoutValue,
@@ -102,8 +98,10 @@ export function buildLegendGroups(
}),
);
- const header =
- dimensionInfo?.longDisplayName ?? dimensionInfo?.displayName;
+ const header = rawDimension
+ ? LibMetric.displayInfo(effectiveEntry.definition, rawDimension)
+ .displayName
+ : undefined;
if (!header) {
return;
}
diff --git a/frontend/src/metabase/metrics-viewer/utils/legend.unit.spec.ts b/frontend/src/metabase/metrics-viewer/utils/legend.unit.spec.ts
index e9ea1fd7c1b..348f1121467 100644
--- a/frontend/src/metabase/metrics-viewer/utils/legend.unit.spec.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/legend.unit.spec.ts
@@ -3,6 +3,7 @@ import Metadata from "metabase-lib/v1/metadata/Metadata";
import {
createMockMetric,
createMockMetricDimension,
+ createMockMetricDimensionGroup,
} from "metabase-types/api/mocks/metric";
import type {
@@ -26,9 +27,14 @@ const REVENUE_METRIC = createMockMetric({
}),
createMockMetricDimension({
id: "dim-2",
- display_name: "Category",
+ display_name: "Product type",
effective_type: "type/Text",
semantic_type: "type/Category",
+ group: createMockMetricDimensionGroup({
+ id: "products",
+ type: "connection",
+ display_name: "Products",
+ }),
}),
],
});
@@ -158,7 +164,7 @@ describe("buildLegendGroups", () => {
).toEqual([
{
key: 0,
- header: "Category",
+ header: "Product type",
subtitle: "Revenue",
items: [
{ label: "Gadgets", color: "#509EE3" },
diff --git a/frontend/src/metabase/metrics-viewer/utils/series.ts b/frontend/src/metabase/metrics-viewer/utils/series.ts
index c7331802de6..85ce34b17e9 100644
--- a/frontend/src/metabase/metrics-viewer/utils/series.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/series.ts
@@ -1,6 +1,7 @@
import { t } from "ttag";
import type { DimensionOption } from "metabase/common/components/DimensionPill";
+import { getDimensionDescriptors } from "metabase/common/metrics/utils/dimension-descriptors";
import type {
DimensionPillBarItem,
ExpressionDimensionItem,
@@ -682,15 +683,17 @@ function buildStandaloneDimensionItem(
return null;
}
- const dimensionInfo = LibMetric.displayInfo(
- modifiedDefinition,
- projectionDimension,
+ const dimension = getDimensionDescriptors(defEntry.definition).get(
+ dimensionId,
);
return {
type: "metric",
slotIndex: slot.slotIndex,
- label: dimensionInfo.longDisplayName,
+ label:
+ dimension?.displayName ??
+ LibMetric.displayInfo(modifiedDefinition, projectionDimension)
+ .displayName,
icon: getDimensionIcon(projectionDimension),
colors: entryColors,
availableOptions: computeAvailableOptions(
@@ -760,10 +763,11 @@ function buildExpressionMetricSources(
LibMetric.projectionDimension(modifiedDefinition, projections[0]) ??
undefined;
if (currentDimension) {
- currentDimensionLabel = LibMetric.displayInfo(
- modifiedDefinition,
- currentDimension,
- ).longDisplayName;
+ currentDimensionLabel =
+ getDimensionDescriptors(defEntry.definition).get(dimensionId)
+ ?.displayName ??
+ LibMetric.displayInfo(modifiedDefinition, currentDimension)
+ .displayName;
currentDimensionIcon = getDimensionIcon(currentDimension);
}
}
diff --git a/frontend/src/metabase/metrics-viewer/utils/series.unit.spec.ts b/frontend/src/metabase/metrics-viewer/utils/series.unit.spec.ts
index 2a9262f583f..a355df5967f 100644
--- a/frontend/src/metabase/metrics-viewer/utils/series.unit.spec.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/series.unit.spec.ts
@@ -3,6 +3,11 @@ import type {
RowValues,
} from "metabase-types/api";
import { createMockColumn } from "metabase-types/api/mocks";
+import {
+ createMockMetricDimension,
+ createMockMetricDimensionGroup,
+ createMockNormalizedMetric,
+} from "metabase-types/api/mocks/metric";
import { createMockSingleSeries } from "metabase-types/api/mocks/series";
import type { ExpressionDimensionItem } from "../components/DimensionPillBar";
@@ -570,6 +575,27 @@ describe("buildDimensionItemsFromDefinitions", () => {
definition: geoDefinition,
},
};
+ const curatedMetric = createMockNormalizedMetric({
+ id: 3,
+ name: "Order revenue",
+ dimensions: [
+ createMockMetricDimension({
+ id: "order-date",
+ display_name: "Order date",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ sources: [{ type: "field", "field-id": 1 }],
+ group: createMockMetricDimensionGroup({
+ id: "orders",
+ type: "connection",
+ display_name: "Orders",
+ }),
+ }),
+ ],
+ });
+ const curatedMetadata = createMetricMetadata([curatedMetric]);
+ const curatedDefinition = setupDefinition(curatedMetadata, curatedMetric.id);
+ const curatedSourceId: MetricSourceId = "metric:3";
const emptyProjectionConfig = {};
describe("standalone metric entities", () => {
@@ -602,6 +628,37 @@ describe("buildDimensionItemsFromDefinitions", () => {
expect(items[0].label).toBe("Created At");
expect(items[0].icon).toBeDefined();
});
+
+ it("uses the curated dimension name without its table prefix", () => {
+ const projectedDefinition = setupDefinitionWithBreakout(
+ curatedMetadata,
+ curatedMetric.id,
+ 0,
+ );
+
+ const items = buildDimensionItemsFromDefinitions(
+ {
+ [curatedSourceId]: {
+ id: curatedSourceId,
+ definition: curatedDefinition,
+ },
+ },
+ { 0: "order-date" },
+ new Map([[0, projectedDefinition]]),
+ { 0: ["#509EE3"] },
+ [{ slotIndex: 0, entityIndex: 0, sourceId: curatedSourceId }],
+ [
+ {
+ id: curatedSourceId,
+ type: "metric",
+ definition: curatedDefinition,
+ },
+ ],
+ emptyProjectionConfig,
+ );
+
+ expect(items[0].label).toBe("Order date");
+ });
});
describe("expression entities", () => {
@@ -659,6 +716,45 @@ describe("buildDimensionItemsFromDefinitions", () => {
expect(expressionItem.metricSources).toHaveLength(2);
});
+ it("uses curated dimension names for expression sources", () => {
+ const expression: MetricsViewerFormulaEntity = {
+ id: "expression:product-revenue",
+ type: "expression",
+ name: "Product revenue expression",
+ tokens: [
+ {
+ type: "metric",
+ sourceId: curatedSourceId,
+ occurrenceCount: 1,
+ },
+ ],
+ };
+
+ const items = buildDimensionItemsFromDefinitions(
+ {
+ [curatedSourceId]: {
+ id: curatedSourceId,
+ definition: curatedDefinition,
+ },
+ },
+ { 0: "order-date" },
+ new Map(),
+ { 0: ["#509EE3"] },
+ [
+ {
+ slotIndex: 0,
+ entityIndex: 0,
+ sourceId: curatedSourceId,
+ tokenPosition: 0,
+ },
+ ],
+ [expression],
+ emptyProjectionConfig,
+ );
+
+ expect(items[0].label).toBe("Order date");
+ });
+
it("shows 'multiple dimensions' label when the dimensions are different", () => {
const dimensionMapping = { 0: "dim-category", 1: "dim-created-at" };
diff --git a/frontend/src/metabase/metrics/common/hooks/use-metric-dimension-query.ts b/frontend/src/metabase/metrics/common/hooks/use-metric-dimension-query.ts
index 0d7458a57ff..5819a4a82a9 100644
--- a/frontend/src/metabase/metrics/common/hooks/use-metric-dimension-query.ts
+++ b/frontend/src/metabase/metrics/common/hooks/use-metric-dimension-query.ts
@@ -5,19 +5,21 @@ import { getDimensionDescriptors } from "metabase/common/metrics/utils/dimension
import type { MetricDefinition } from "metabase-lib/metric";
import * as LibMetric from "metabase-lib/metric";
-import { projectDimension } from "../utils/project-dimension";
-
export function useMetricDimensionQuery(
- definition: MetricDefinition,
- dimensionId: string,
+ definition: MetricDefinition | null,
+ dimensionId: string | null,
) {
const request = useMemo(() => {
+ if (!definition || !dimensionId) {
+ return null;
+ }
+
const descriptor = getDimensionDescriptors(definition).get(dimensionId);
if (!descriptor) {
return null;
}
- const projected = projectDimension(
+ const projected = LibMetric.projectDimension(
definition,
descriptor.dimensionMetadata,
);
diff --git a/frontend/src/metabase/metrics/common/use-load-card-with-metadata/use-load-card-with-metadata.ts b/frontend/src/metabase/metrics/common/use-load-card-with-metadata/use-load-card-with-metadata.ts
index d13d7e5ed65..8714a1c9cae 100644
--- a/frontend/src/metabase/metrics/common/use-load-card-with-metadata/use-load-card-with-metadata.ts
+++ b/frontend/src/metabase/metrics/common/use-load-card-with-metadata/use-load-card-with-metadata.ts
@@ -11,11 +11,15 @@ export function useLoadCardWithMetadata(cardId: CardId | undefined) {
isLoading: isLoadingCard,
error: cardError,
} = useGetCardQuery(cardId != null ? { id: cardId } : skipToken);
- const { isLoading: isLoadingMetadata, error: metadataError } =
- useGetCardQueryMetadataQuery(cardId ?? skipToken);
+ const {
+ data: metadata,
+ isLoading: isLoadingMetadata,
+ error: metadataError,
+ } = useGetCardQueryMetadataQuery(cardId ?? skipToken);
return {
card,
+ metadata,
isLoading: isLoadingCard || isLoadingMetadata,
error: cardError ?? metadataError,
};
diff --git a/frontend/src/metabase/metrics/common/utils/project-dimension.ts b/frontend/src/metabase/metrics/common/utils/project-dimension.ts
deleted file mode 100644
index 71b2f53c58c..00000000000
--- a/frontend/src/metabase/metrics/common/utils/project-dimension.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { DimensionMetadata, MetricDefinition } from "metabase-lib/metric";
-import * as LibMetric from "metabase-lib/metric";
-
-export function projectDimension(
- definition: MetricDefinition,
- dimension: DimensionMetadata,
-): MetricDefinition {
- const dimensionRef = LibMetric.dimensionReference(dimension);
- const projected = LibMetric.project(definition, dimensionRef);
-
- const projections = LibMetric.projections(projected);
- if (projections.length === 0) {
- return projected;
- }
-
- const projection = projections[projections.length - 1];
- const projectedDimension = LibMetric.projectionDimension(
- projected,
- projection,
- );
- if (!projectedDimension) {
- return projected;
- }
-
- if (LibMetric.isTemporalBucketable(projected, projectedDimension)) {
- return LibMetric.replaceClause(
- projected,
- projection,
- LibMetric.withDefaultTemporalBucket(projected, projection),
- );
- }
-
- if (LibMetric.isBinnable(projected, projectedDimension)) {
- return LibMetric.replaceClause(
- projected,
- projection,
- LibMetric.withDefaultBinning(projected, projection),
- );
- }
-
- return projected;
-}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.module.css b/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.module.css
index e18e23d6b39..84f2868bfbd 100644
--- a/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.module.css
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.module.css
@@ -23,6 +23,10 @@
}
}
+.autoLoadTrigger {
+ height: 1px;
+}
+
.skeletonCard {
aspect-ratio: 8 / 5;
overflow: hidden;
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.tsx b/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.tsx
index 3cb690aae63..13352d6e0f6 100644
--- a/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.tsx
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/MetricDimensionGrid.tsx
@@ -1,8 +1,12 @@
-import { useCallback, useMemo } from "react";
+import { useIntersection } from "@mantine/hooks";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { t } from "ttag";
import _ from "underscore";
-import type { DimensionType } from "metabase/common/metrics/utils/dimension-types";
+import {
+ DEFAULT_DISPLAY_TYPE_BY_DIMENSION,
+ type DefaultDimensionDisplayType,
+} from "metabase/common/metrics/utils/dimension-types";
import { trackMetricPageShowMoreClicked } from "metabase/metrics/analytics";
import { useMetricDimensionQuery } from "metabase/metrics/common/hooks";
import { useDispatch } from "metabase/redux";
@@ -24,33 +28,69 @@ import type {
Card,
CardDisplayType,
Dataset,
+ MetricDimension,
SingleSeries,
} from "metabase-types/api";
import type { MetricId } from "metabase-types/api/metric";
import S from "./MetricDimensionGrid.module.css";
import { useMetricDimensionCards } from "./use-metric-dimension-cards";
-import type { DefaultDimension } from "./utils";
+import type { OverviewDimension } from "./utils";
type MetricDimensionGridProps = {
metricId: MetricId;
+ dimensions: MetricDimension[];
};
const DEFAULT_SKELETON_COUNT = 3;
-const DISPLAY_TYPE_BY_DIMENSION = {
- time: "line",
- geo: "map",
- category: "bar",
- boolean: "bar",
- numeric: "bar",
-} as const satisfies Record<DimensionType, CardDisplayType>;
-
-type DimensionDisplayType = (typeof DISPLAY_TYPE_BY_DIMENSION)[DimensionType];
-
-export function MetricDimensionGrid({ metricId }: MetricDimensionGridProps) {
- const { cards, definition, isLoading, hasMore, showMore } =
- useMetricDimensionCards(metricId);
+export function MetricDimensionGrid({
+ metricId,
+ dimensions,
+}: MetricDimensionGridProps) {
+ const {
+ cards,
+ definition,
+ isLoading,
+ autoLoad,
+ canAutoLoad,
+ hasMore,
+ showMore,
+ } = useMetricDimensionCards(metricId, dimensions);
+ const { ref: autoLoadRef, entry } = useIntersection({ threshold: 0.1 });
+ const [hasScrollIntent, setHasScrollIntent] = useState(false);
+
+ useEffect(() => {
+ setHasScrollIntent(false);
+ }, [metricId]);
+
+ useEffect(() => {
+ if (!canAutoLoad) {
+ return;
+ }
+
+ const handleScrollIntent = () => setHasScrollIntent(true);
+ const handleWheel = (event: WheelEvent) => {
+ if (event.deltaY > 0) {
+ handleScrollIntent();
+ }
+ };
+
+ window.addEventListener("scroll", handleScrollIntent, true);
+ window.addEventListener("touchmove", handleScrollIntent);
+ window.addEventListener("wheel", handleWheel);
+ return () => {
+ window.removeEventListener("scroll", handleScrollIntent, true);
+ window.removeEventListener("touchmove", handleScrollIntent);
+ window.removeEventListener("wheel", handleWheel);
+ };
+ }, [canAutoLoad, metricId]);
+
+ useEffect(() => {
+ if (hasScrollIntent && entry?.isIntersecting && canAutoLoad) {
+ autoLoad();
+ }
+ }, [entry?.isIntersecting, autoLoad, canAutoLoad, hasScrollIntent]);
if (isLoading || !definition) {
return <DimensionGridSkeleton count={DEFAULT_SKELETON_COUNT} />;
@@ -69,11 +109,18 @@ export function MetricDimensionGrid({ metricId }: MetricDimensionGridProps) {
metricId={metricId}
definition={definition}
dimension={card}
- displayType={DISPLAY_TYPE_BY_DIMENSION[card.dimensionType]}
+ displayType={DEFAULT_DISPLAY_TYPE_BY_DIMENSION[card.dimensionType]}
/>
))}
</SimpleGrid>
- {hasMore && (
+ {canAutoLoad && (
+ <div
+ ref={autoLoadRef}
+ className={S.autoLoadTrigger}
+ data-testid="metric-dimension-auto-load-trigger"
+ />
+ )}
+ {hasMore && !canAutoLoad && (
<Button
fullWidth
leftSection={<Icon name="chevrondown" />}
@@ -92,8 +139,8 @@ export function MetricDimensionGrid({ metricId }: MetricDimensionGridProps) {
interface MetricDimensionCardProps {
metricId: MetricId;
definition: MetricDefinition;
- dimension: DefaultDimension;
- displayType: DimensionDisplayType;
+ dimension: OverviewDimension;
+ displayType: DefaultDimensionDisplayType;
}
function MetricDimensionCard({
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.ts b/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.ts
index d8565fe66ab..d043c6822b3 100644
--- a/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.ts
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.ts
@@ -1,43 +1,68 @@
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { useMetricDefinition } from "metabase/metrics/common/hooks";
-import type { MetricId } from "metabase-types/api/metric";
+import type { MetricDimension, MetricId } from "metabase-types/api/metric";
-import { getDefaultDimensions } from "./utils";
+import { type OverviewDimension, getOverviewDimensions } from "./utils";
+const INITIAL_VISIBLE_COUNT = 4;
+const AUTO_LOAD_VISIBLE_COUNT = 10;
const SHOW_MORE_BATCH_SIZE = 4;
-export function useMetricDimensionCards(metricId: MetricId) {
+export function useMetricDimensionCards(
+ metricId: MetricId,
+ dimensions: MetricDimension[],
+) {
const { definition, isLoading } = useMetricDefinition(metricId);
const allDimensions = useMemo(
- () => (definition ? getDefaultDimensions(definition) : []),
- [definition],
+ () => (definition ? getOverviewDimensions(definition, dimensions) : []),
+ [definition, dimensions],
);
+ const visibility = useVisibleDimensions(allDimensions, metricId);
- const [visibleCount, setVisibleCount] = useState<number | null>(null);
+ return {
+ ...visibility,
+ definition,
+ isLoading,
+ };
+}
+
+export function useVisibleDimensions(
+ dimensions: OverviewDimension[],
+ metricId: MetricId,
+) {
+ const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE_COUNT);
- if (definition && visibleCount === null && allDimensions.length > 0) {
- setVisibleCount(Math.min(allDimensions.length, SHOW_MORE_BATCH_SIZE));
- }
+ useEffect(() => {
+ setVisibleCount(INITIAL_VISIBLE_COUNT);
+ }, [metricId]);
const visibleCards = useMemo(
- () => allDimensions.slice(0, visibleCount ?? 0),
- [allDimensions, visibleCount],
+ () => dimensions.slice(0, visibleCount),
+ [dimensions, visibleCount],
);
- const hasMore = visibleCards.length < allDimensions.length;
+ const hasMore = visibleCards.length < dimensions.length;
+ const canAutoLoad =
+ visibleCards.length < Math.min(dimensions.length, AUTO_LOAD_VISIBLE_COUNT);
+
+ const autoLoad = useCallback(() => {
+ setVisibleCount((previous) =>
+ Math.max(previous, Math.min(AUTO_LOAD_VISIBLE_COUNT, dimensions.length)),
+ );
+ }, [dimensions.length]);
const showMore = useCallback(() => {
setVisibleCount((previous) =>
- Math.min((previous ?? 0) + SHOW_MORE_BATCH_SIZE, allDimensions.length),
+ Math.min(previous + SHOW_MORE_BATCH_SIZE, dimensions.length),
);
- }, [allDimensions.length]);
+ }, [dimensions.length]);
return {
cards: visibleCards,
- definition,
- isLoading,
+ autoLoad,
+ canAutoLoad,
hasMore,
showMore,
};
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.unit.spec.tsx
new file mode 100644
index 00000000000..85bdea1df67
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/use-metric-dimension-cards.unit.spec.tsx
@@ -0,0 +1,77 @@
+import { act, renderHook } from "@testing-library/react";
+
+import type { MetricId } from "metabase-types/api/metric";
+
+import { useVisibleDimensions } from "./use-metric-dimension-cards";
+import type { OverviewDimension } from "./utils";
+
+const DIMENSIONS = Array.from({ length: 15 }, (_, index) => ({
+ dimensionId: `dimension-${index + 1}`,
+ dimensionType: "category" as const,
+ label: `Dimension ${index + 1}`,
+}));
+
+function getVisibleIds(cards: OverviewDimension[]) {
+ return cards.map((card) => card.dimensionId);
+}
+
+describe("useVisibleDimensions", () => {
+ it("shows 4 dimensions, auto-loads through 10, then shows 4 per click", () => {
+ const { result } = renderHook(() => useVisibleDimensions(DIMENSIONS, 1));
+
+ expect(getVisibleIds(result.current.cards)).toEqual(
+ DIMENSIONS.slice(0, 4).map((dimension) => dimension.dimensionId),
+ );
+ expect(result.current.canAutoLoad).toBe(true);
+
+ act(() => result.current.autoLoad());
+
+ expect(getVisibleIds(result.current.cards)).toEqual(
+ DIMENSIONS.slice(0, 10).map((dimension) => dimension.dimensionId),
+ );
+ expect(result.current.canAutoLoad).toBe(false);
+ expect(result.current.hasMore).toBe(true);
+
+ act(() => result.current.showMore());
+
+ expect(getVisibleIds(result.current.cards)).toEqual(
+ DIMENSIONS.slice(0, 14).map((dimension) => dimension.dimensionId),
+ );
+
+ act(() => result.current.showMore());
+
+ expect(getVisibleIds(result.current.cards)).toEqual(
+ DIMENSIONS.map((dimension) => dimension.dimensionId),
+ );
+ expect(result.current.hasMore).toBe(false);
+ });
+
+ it("auto-loads all remaining dimensions when there are fewer than 10", () => {
+ const dimensions = DIMENSIONS.slice(0, 7);
+ const { result } = renderHook(() => useVisibleDimensions(dimensions, 1));
+
+ act(() => result.current.autoLoad());
+
+ expect(getVisibleIds(result.current.cards)).toEqual(
+ dimensions.map((dimension) => dimension.dimensionId),
+ );
+ expect(result.current.canAutoLoad).toBe(false);
+ expect(result.current.hasMore).toBe(false);
+ });
+
+ it("resets to 4 dimensions when navigating to another metric", () => {
+ const { result, rerender } = renderHook(
+ ({ metricId }: { metricId: MetricId }) =>
+ useVisibleDimensions(DIMENSIONS, metricId),
+ { initialProps: { metricId: 1 } },
+ );
+
+ act(() => result.current.autoLoad());
+ act(() => result.current.showMore());
+ expect(result.current.cards).toHaveLength(14);
+
+ rerender({ metricId: 2 });
+
+ expect(result.current.cards).toHaveLength(4);
+ });
+});
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.ts b/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.ts
index e7a95064c73..3187dc71695 100644
--- a/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.ts
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.ts
@@ -1,115 +1,32 @@
-import type { DimensionDescriptor } from "metabase/common/metrics/utils/dimension-descriptors";
import { getDimensionDescriptors } from "metabase/common/metrics/utils/dimension-descriptors";
-import type {
- DimensionType,
- GeoSubtype,
-} from "metabase/common/metrics/utils/dimension-types";
-import {
- GEO_SUBTYPE_PRIORITY,
- getGeoSubtype,
-} from "metabase/common/metrics/utils/dimension-types";
+import type { DimensionType } from "metabase/common/metrics/utils/dimension-types";
import type { MetricDefinition } from "metabase-lib/metric";
+import type { MetricDimension } from "metabase-types/api";
-export interface DefaultDimension {
+export interface OverviewDimension {
dimensionId: string;
dimensionType: DimensionType;
label: string;
}
-export function getDefaultDimensions(
+export function getOverviewDimensions(
definition: MetricDefinition,
-): DefaultDimension[] {
+ dimensions: MetricDimension[],
+): OverviewDimension[] {
const descriptors = getDimensionDescriptors(definition);
- if (descriptors.size === 0) {
- return [];
- }
- return [
- ...pickAggregate(descriptors, "time"),
- ...pickAggregate(descriptors, "geo"),
- ...pickAllOfType(descriptors, "category", { requireListValues: true }),
- ...pickAllOfType(descriptors, "boolean"),
- ];
-}
-
-function toDefaultDimension(descriptor: DimensionDescriptor): DefaultDimension {
- return {
- dimensionId: descriptor.id,
- dimensionType: descriptor.dimensionType,
- label: descriptor.displayName,
- };
-}
-
-function pickAggregate(
- descriptors: Map<string, DimensionDescriptor>,
- dimensionType: DimensionType,
-): DefaultDimension[] {
- const best =
- dimensionType === "geo"
- ? findBestGeoDimension(descriptors)
- : findBestDimension(descriptors, dimensionType);
-
- return best ? [toDefaultDimension(best)] : [];
-}
-
-function pickAllOfType(
- descriptors: Map<string, DimensionDescriptor>,
- dimensionType: DimensionType,
- options?: { requireListValues?: boolean },
-): DefaultDimension[] {
- return [...descriptors.values()]
- .filter(
- (dimension) =>
- dimension.dimensionType === dimensionType &&
- (!options?.requireListValues || dimension.canListValues) &&
- dimension.isPreferred !== false, // undefined is okay - means there is no preferred predicate
- )
- .sort((first, second) => {
- if (first.canListValues !== second.canListValues) {
- return first.canListValues ? -1 : 1;
- }
- return first.displayName.localeCompare(second.displayName);
- })
- .map(toDefaultDimension);
-}
-
-function findBestDimension(
- descriptors: Map<string, DimensionDescriptor>,
- dimensionType: DimensionType,
-): DimensionDescriptor | null {
- const matching = [...descriptors.values()].filter(
- (dimension) => dimension.dimensionType === dimensionType,
- );
-
- return (
- matching.find((dimension) => dimension.isDefault) ?? matching[0] ?? null
- );
-}
-
-function findBestGeoDimension(
- descriptors: Map<string, DimensionDescriptor>,
-): DimensionDescriptor | null {
- const geoDimensions = [...descriptors.values()].filter(
- (dimension) => dimension.dimensionType === "geo",
- );
-
- const subtypeMap = new Map(
- geoDimensions
- .map(
- (dimension) =>
- [getGeoSubtype(dimension.dimensionMetadata), dimension] as const,
- )
- .filter(
- (entry): entry is readonly [GeoSubtype, DimensionDescriptor] =>
- entry[0] != null,
- ),
- );
-
- const prioritized = GEO_SUBTYPE_PRIORITY.find((subtype) =>
- subtypeMap.has(subtype),
- );
-
- return prioritized
- ? (subtypeMap.get(prioritized) ?? null)
- : (geoDimensions[0] ?? null);
+ return dimensions.flatMap((dimension) => {
+ const descriptor = descriptors.get(dimension.id);
+ if (dimension.status === "status/orphaned" || !descriptor) {
+ return [];
+ }
+
+ return [
+ {
+ dimensionId: descriptor.id,
+ dimensionType: descriptor.dimensionType,
+ label: descriptor.displayName,
+ },
+ ];
+ });
}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.unit.spec.ts b/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.unit.spec.ts
index 989d9d47cde..18e563531ca 100644
--- a/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.unit.spec.ts
+++ b/frontend/src/metabase/metrics/components/MetricDimensionGrid/utils.unit.spec.ts
@@ -7,7 +7,7 @@ import {
createMockNormalizedMetric,
} from "metabase-types/api/mocks/metric";
-import { getDefaultDimensions } from "./utils";
+import { getOverviewDimensions } from "./utils";
type MetricDimensionOptions = NonNullable<
Parameters<typeof createMockMetricDimension>[0]
@@ -21,17 +21,16 @@ function createDimension(options: MetricDimensionOptionsWithFieldValues) {
return createMockMetricDimension(options);
}
-describe("getDefaultDimensions", () => {
- const CATEGORY_SELECTION_METRIC = createMockNormalizedMetric({
+describe("getOverviewDimensions", () => {
+ const CURATED_DIMENSIONS_METRIC = createMockNormalizedMetric({
id: 101,
- name: "Category Selection",
+ name: "Curated Dimensions",
dimensions: [
createDimension({
- id: "dim-category",
- display_name: "Category",
- effective_type: "type/Text",
- semantic_type: "type/Category",
- has_field_values: "list",
+ id: "dim-quantity",
+ display_name: "Quantity",
+ effective_type: "type/Integer",
+ semantic_type: "type/Quantity",
}),
createDimension({
id: "dim-status",
@@ -40,19 +39,43 @@ describe("getDefaultDimensions", () => {
semantic_type: null,
has_field_values: "list",
}),
+ createDimension({
+ id: "dim-created-at",
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ }),
+ createDimension({
+ id: "dim-orphaned",
+ display_name: "Orphaned",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ status: "status/orphaned",
+ }),
],
});
- const metadata = createMetricMetadata([CATEGORY_SELECTION_METRIC]);
- const definition = setupDefinition(metadata, CATEGORY_SELECTION_METRIC.id);
+ const metadata = createMetricMetadata([CURATED_DIMENSIONS_METRIC]);
+ const definition = setupDefinition(metadata, CURATED_DIMENSIONS_METRIC.id);
- it("only returns preferred category dimensions for overview cards", () => {
- expect(getDefaultDimensions(definition)).toEqual([
+ it("returns chartable active dimensions in curated order", () => {
+ expect(
+ getOverviewDimensions(definition, CURATED_DIMENSIONS_METRIC.dimensions),
+ ).toEqual([
+ {
+ dimensionId: "dim-quantity",
+ dimensionType: "numeric",
+ label: "Quantity",
+ },
{
- dimensionId: "dim-category",
+ dimensionId: "dim-status",
dimensionType: "category",
- label: "Category",
- // Status should not be included because it's not preferred
+ label: "Status",
+ },
+ {
+ dimensionId: "dim-created-at",
+ dimensionType: "time",
+ label: "Created At",
},
]);
});
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/AddDimensionsPanel.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/AddDimensionsPanel.tsx
new file mode 100644
index 00000000000..951bf00a4b6
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/AddDimensionsPanel.tsx
@@ -0,0 +1,164 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import {
+ useAddMetricDimensionsMutation,
+ useListMetricDimensionsQuery,
+} from "metabase/api/metric";
+import { EmptyState } from "metabase/common/components/EmptyState";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
+import { getDimensionIcon } from "metabase/common/metrics/utils/dimensions";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import {
+ Accordion,
+ Box,
+ Button,
+ Group,
+ Icon,
+ ScrollArea,
+ Stack,
+ Text,
+ TextInput,
+ Title,
+ UnstyledButton,
+} from "metabase/ui";
+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";
+import type {
+ AddableMetricDimension,
+ MetricDimensionGroup,
+ MetricId,
+} from "metabase-types/api";
+
+import S from "./MetricDimensions.module.css";
+import { getNewDimensionTitle } from "./utils";
+
+interface AddDimensionsPanelProps {
+ metricId: MetricId;
+ onDone: () => void;
+}
+
+export function AddDimensionsPanel({
+ metricId,
+ onDone,
+}: AddDimensionsPanelProps) {
+ const [search, setSearch] = useState("");
+ const debouncedSearch = useDebouncedValue(search, SEARCH_DEBOUNCE_DURATION);
+ const dispatch = useDispatch();
+ const { data, isLoading, error } = useListMetricDimensionsQuery({
+ metricId,
+ "with-addable": true,
+ query: debouncedSearch || undefined,
+ "include-orphaned": true,
+ });
+ const [addDimensions] = useAddMetricDimensionsMutation();
+
+ const groups = data?.addable ?? [];
+ const groupIds = groups.map(({ group }) => group.id);
+ const isSearchActive = search.length > 0 || Boolean(debouncedSearch);
+ const isEmpty = groups.length === 0;
+
+ const handleAdd = async (
+ group: MetricDimensionGroup,
+ dimension: AddableMetricDimension,
+ ) => {
+ try {
+ await addDimensions({
+ metricId,
+ dimensions: [
+ {
+ ...dimension,
+ display_name: getNewDimensionTitle(group, dimension),
+ },
+ ],
+ }).unwrap();
+ } catch {
+ dispatch(addUndo({ message: t`Couldn't add ${dimension.display_name}` }));
+ }
+ };
+
+ return (
+ <Stack gap="md" className={S.column} data-testid="add-dimensions-panel">
+ <Group justify="space-between" align="flex-start" wrap="nowrap">
+ <Box>
+ <Title order={4}>{t`Add available dimensions`}</Title>
+ <Text
+ c="text-secondary"
+ size="sm"
+ mt="xs"
+ >{t`You can pick one or many.`}</Text>
+ </Box>
+ <Button variant="filled" onClick={onDone} size="sm">{t`Done`}</Button>
+ </Group>
+
+ {(!isEmpty || isSearchActive) && (
+ <TextInput
+ classNames={{ input: S.searchInput }}
+ placeholder={t`Search…`}
+ value={search}
+ leftSection={<Icon name="search" />}
+ onChange={(event) => setSearch(event.currentTarget.value)}
+ />
+ )}
+
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ {isEmpty ? (
+ <EmptyState
+ className={S.emptyState}
+ message={
+ isSearchActive
+ ? t`No dimensions match your search.`
+ : t`All available dimensions have been added`
+ }
+ />
+ ) : (
+ <ScrollArea className={S.scrollArea} offsetScrollbars="present">
+ <Accordion
+ key={groupIds.join(",")}
+ className={S.accordion}
+ classNames={{
+ item: S.item,
+ control: S.control,
+ label: S.label,
+ chevron: S.chevron,
+ content: S.content,
+ }}
+ multiple
+ defaultValue={groupIds}
+ >
+ {groups.map(({ group, dimensions }) => (
+ <Accordion.Item key={group.id} value={group.id}>
+ <Accordion.Control
+ icon={<Icon name="table" c="text-secondary" />}
+ >
+ {group.display_name}
+ </Accordion.Control>
+ <Accordion.Panel>
+ <Stack gap="sm">
+ {dimensions.map((dimension) => (
+ <UnstyledButton
+ key={dimension.id}
+ className={S.addableRow}
+ onClick={() => handleAdd(group, dimension)}
+ >
+ <Group gap="sm" wrap="nowrap">
+ <Icon
+ name={getDimensionIcon(dimension)}
+ c="text-secondary"
+ />
+ <Text>{dimension.display_name}</Text>
+ </Group>
+ </UnstyledButton>
+ ))}
+ </Stack>
+ </Accordion.Panel>
+ </Accordion.Item>
+ ))}
+ </Accordion>
+ </ScrollArea>
+ )}
+ </LoadingAndErrorWrapper>
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/DimensionList.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionList.tsx
new file mode 100644
index 00000000000..cd1b5fb9de5
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionList.tsx
@@ -0,0 +1,146 @@
+import { PointerSensor, useSensor } from "@dnd-kit/core";
+import { t } from "ttag";
+
+import { EmptyState } from "metabase/common/components/EmptyState";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import {
+ type DragEndEvent,
+ SortableList,
+} from "metabase/common/components/Sortable";
+import {
+ ActionIcon,
+ Button,
+ Group,
+ Icon,
+ ScrollArea,
+ Stack,
+ TextInput,
+ Title,
+} from "metabase/ui";
+import type { DimensionId, MetricDimension } from "metabase-types/api";
+
+import { DimensionRow } from "./DimensionRow";
+import S from "./MetricDimensions.module.css";
+
+interface DimensionListProps {
+ dimensions: MetricDimension[];
+ isLoading: boolean;
+ error: unknown;
+ search: string;
+ isSearchActive: boolean;
+ checkedIds: Set<DimensionId>;
+ activeId: DimensionId | null;
+ isAddDisabled: boolean;
+ onSearchChange: (value: string) => void;
+ onToggle: (id: DimensionId, checked: boolean) => void;
+ onAdd: () => void;
+ onRemove: () => void;
+ onEdit: (id: DimensionId) => void;
+ onReorder: (ids: DimensionId[]) => void;
+}
+
+export function DimensionList({
+ dimensions,
+ isLoading,
+ error,
+ search,
+ isSearchActive,
+ checkedIds,
+ activeId,
+ isAddDisabled,
+ onSearchChange,
+ onToggle,
+ onAdd,
+ onRemove,
+ onEdit,
+ onReorder,
+}: DimensionListProps) {
+ const hasChecked = checkedIds.size > 0;
+ const isEmpty = dimensions.length === 0;
+ // Reordering a search-filtered subset is ambiguous, so dragging is
+ // only available on the full list.
+ const canReorder = !isSearchActive && dimensions.length > 1;
+
+ const pointerSensor = useSensor(PointerSensor, {
+ activationConstraint: { distance: 10 },
+ });
+
+ const handleSortEnd = ({ itemIds }: DragEndEvent) => {
+ onReorder(itemIds.map(String));
+ };
+
+ return (
+ <Stack
+ className={S.column}
+ data-testid="metric-dimension-list"
+ gap="md"
+ pt="lg"
+ >
+ <Group justify="space-between" wrap="nowrap" align="center">
+ <Title order={4}>{t`Dimensions of this metric`}</Title>
+ <Group gap="md" wrap="nowrap" align="center">
+ {hasChecked && (
+ <ActionIcon
+ className={S.deleteIconButton}
+ aria-label={t`Remove`}
+ onClick={onRemove}
+ variant="viewHeader"
+ >
+ <Icon name="trash" />
+ </ActionIcon>
+ )}
+ <Button
+ disabled={isAddDisabled}
+ onClick={onAdd}
+ size="sm"
+ >{t`Available dimensions`}</Button>
+ </Group>
+ </Group>
+
+ {(!isEmpty || isSearchActive) && (
+ <TextInput
+ classNames={{ input: S.searchInput }}
+ leftSection={<Icon name="search" />}
+ onChange={(event) => onSearchChange(event.currentTarget.value)}
+ placeholder={t`Search…`}
+ value={search}
+ />
+ )}
+
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ {isEmpty ? (
+ <EmptyState
+ className={S.emptyState}
+ message={
+ isSearchActive
+ ? t`No dimensions match your search.`
+ : t`No dimensions have been added.`
+ }
+ />
+ ) : (
+ <ScrollArea className={S.scrollArea} offsetScrollbars="present">
+ <Stack gap="sm">
+ <SortableList
+ items={dimensions}
+ getId={(dimension) => dimension.id}
+ sensors={[pointerSensor]}
+ onSortEnd={handleSortEnd}
+ renderItem={({ item: dimension }) => (
+ <DimensionRow
+ key={dimension.id}
+ dimension={dimension}
+ checked={checkedIds.has(dimension.id)}
+ active={dimension.id === activeId}
+ canReorder={canReorder}
+ onToggle={(checked) => onToggle(dimension.id, checked)}
+ onEdit={() => onEdit(dimension.id)}
+ />
+ )}
+ />
+ </Stack>
+ </ScrollArea>
+ )}
+ </LoadingAndErrorWrapper>
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/DimensionRow.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionRow.tsx
new file mode 100644
index 00000000000..38cb06e29bc
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionRow.tsx
@@ -0,0 +1,89 @@
+import cx from "classnames";
+import { t } from "ttag";
+
+import { Sortable } from "metabase/common/components/Sortable";
+import { getDimensionIcon } from "metabase/common/metrics/utils/dimensions";
+import {
+ Badge,
+ Box,
+ Checkbox,
+ Group,
+ Icon,
+ Text,
+ UnstyledButton,
+} from "metabase/ui";
+import type { MetricDimension } from "metabase-types/api";
+
+import S from "./MetricDimensions.module.css";
+import { isOrphaned } from "./utils";
+
+interface DimensionRowProps {
+ dimension: MetricDimension;
+ checked: boolean;
+ active: boolean;
+ canReorder: boolean;
+ onToggle: (checked: boolean) => void;
+ onEdit: () => void;
+}
+
+export function DimensionRow({
+ dimension,
+ checked,
+ active,
+ canReorder,
+ onToggle,
+ onEdit,
+}: DimensionRowProps) {
+ return (
+ <Sortable
+ id={dimension.id}
+ disabled={!canReorder}
+ draggingStyle={{ opacity: 0.5 }}
+ role="listitem"
+ >
+ {({ dragHandleRef, dragHandleListeners }) => (
+ <Group
+ gap="sm"
+ wrap="nowrap"
+ className={cx(S.row, { [S.rowActive]: active })}
+ data-testid={`dimension-row-${dimension.display_name}`}
+ >
+ {canReorder && (
+ <Box
+ component="span"
+ ref={dragHandleRef}
+ className={S.grabber}
+ data-testid="dimension-drag-handle"
+ {...dragHandleListeners}
+ >
+ <Icon name="grabber" c="text-secondary" />
+ </Box>
+ )}
+ <Checkbox
+ aria-label={dimension.display_name}
+ checked={checked}
+ size="xs"
+ onChange={(event) => onToggle(event.currentTarget.checked)}
+ />
+ <UnstyledButton className={S.rowButton} onClick={onEdit}>
+ <Group gap="sm" wrap="nowrap">
+ <Icon name={getDimensionIcon(dimension)} c="text-secondary" />
+ <Text flex={1} truncate="end">
+ {dimension.display_name}
+ </Text>
+ {dimension.default && <Badge variant="light">{t`Default`}</Badge>}
+ {isOrphaned(dimension) && (
+ <Icon
+ name="warning"
+ c="warning"
+ tooltip={t`This column is no longer available in the metric's data`}
+ />
+ )}
+ <Icon name="chevronright" c="text-secondary" size={12} />
+ </Group>
+ </UnstyledButton>
+ </Group>
+ )}
+ </Sortable>
+ );
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/DimensionSettingsPanel.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionSettingsPanel.tsx
new file mode 100644
index 00000000000..0a87a959b72
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/DimensionSettingsPanel.tsx
@@ -0,0 +1,176 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import {
+ useSetDefaultMetricDimensionMutation,
+ useUpdateMetricDimensionMutation,
+} from "metabase/api/metric";
+import { getDimensionIcon } from "metabase/common/metrics/utils/dimensions";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ Button,
+ Group,
+ Icon,
+ Input,
+ Stack,
+ Text,
+ TextInput,
+ Textarea,
+ Title,
+} from "metabase/ui";
+import type {
+ CardQueryMetadata,
+ MetricDimension,
+ MetricId,
+ UpdateMetricDimensionRequest,
+} from "metabase-types/api";
+
+import S from "./MetricDimensions.module.css";
+import {
+ getDimensionTypeLabel,
+ getSourceColumnLabel,
+ isOrphaned,
+} from "./utils";
+
+type DimensionChanges = Omit<
+ UpdateMetricDimensionRequest,
+ "metricId" | "dimensionId"
+>;
+
+interface DimensionSettingsPanelProps {
+ metricId: MetricId;
+ dimension: MetricDimension;
+ isFetching: boolean;
+ queryMetadata: CardQueryMetadata;
+}
+
+export function DimensionSettingsPanel({
+ metricId,
+ dimension,
+ isFetching,
+ queryMetadata,
+}: DimensionSettingsPanelProps) {
+ const [updateDimension] = useUpdateMetricDimensionMutation();
+ const [setDefaultDimension, { isLoading: isSettingDefault }] =
+ useSetDefaultMetricDimensionMutation();
+
+ const [displayName, setDisplayName] = useState(dimension.display_name);
+ const [description, setDescription] = useState(dimension.description ?? "");
+
+ const { sendErrorToast } = useMetadataToasts();
+
+ const sourceColumnLabel = getSourceColumnLabel(dimension, queryMetadata);
+ const showSetAsDefaultButton = !isOrphaned(dimension) && !dimension.default;
+
+ const persist = async (changes: DimensionChanges) => {
+ try {
+ await updateDimension({
+ metricId,
+ dimensionId: dimension.id,
+ ...changes,
+ }).unwrap();
+ return true;
+ } catch {
+ sendErrorToast(t`Couldn't update ${dimension.display_name}`);
+ return false;
+ }
+ };
+
+ const handleNameBlur = async () => {
+ const nextDisplayName = displayName.trim();
+ if (!nextDisplayName) {
+ setDisplayName(dimension.display_name);
+ return;
+ }
+
+ setDisplayName(nextDisplayName);
+ if (nextDisplayName !== dimension.display_name) {
+ const isPersisted = await persist({ display_name: nextDisplayName });
+ if (!isPersisted) {
+ setDisplayName(dimension.display_name);
+ }
+ }
+ };
+
+ const handleDescriptionBlur = () => {
+ if (description !== (dimension.description ?? "")) {
+ persist({ description });
+ }
+ };
+
+ const handleSetDefault = async () => {
+ try {
+ await setDefaultDimension({
+ metricId,
+ dimension_id: dimension.id,
+ }).unwrap();
+ } catch {
+ sendErrorToast(t`Couldn't make ${dimension.display_name} the default`);
+ }
+ };
+
+ return (
+ <Stack
+ className={S.column}
+ data-testid="dimension-settings-panel"
+ gap="lg"
+ pt="lg"
+ >
+ <Group
+ align="center"
+ flex="0 0 2.25rem"
+ justify="space-between"
+ wrap="nowrap"
+ >
+ <Title order={4}>{t`Settings for ${dimension.display_name}`}</Title>
+ {showSetAsDefaultButton && (
+ <Button
+ loading={isSettingDefault || isFetching}
+ onClick={handleSetDefault}
+ size="sm"
+ variant="default"
+ >
+ {t`Set as default`}
+ </Button>
+ )}
+ </Group>
+
+ <TextInput
+ label={t`Display name`}
+ value={displayName}
+ onChange={(event) => setDisplayName(event.currentTarget.value)}
+ onBlur={handleNameBlur}
+ />
+
+ <Textarea
+ label={t`Description`}
+ placeholder={t`Add a description`}
+ value={description}
+ autosize
+ minRows={3}
+ onChange={(event) => setDescription(event.currentTarget.value)}
+ onBlur={handleDescriptionBlur}
+ />
+
+ <Input.Wrapper label={t`Dimension type`} data-testid="dimension-type">
+ <Group gap="sm">
+ <Icon name={getDimensionIcon(dimension)} c="text-secondary" />
+ <Text>{getDimensionTypeLabel(dimension)}</Text>
+ </Group>
+ </Input.Wrapper>
+
+ {sourceColumnLabel && (
+ <Input.Wrapper label={t`Source column`} data-testid="dimension-source">
+ <Text>{sourceColumnLabel}</Text>
+ </Input.Wrapper>
+ )}
+
+ {dimension.default && (
+ <Group gap="xs">
+ <Icon name="star_filled" c="brand" />
+ <Text fw="bold">{t`Default dimension`}</Text>
+ </Group>
+ )}
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.module.css b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.module.css
new file mode 100644
index 00000000000..2885abb0dda
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.module.css
@@ -0,0 +1,129 @@
+.root {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.columns {
+ display: flex;
+ flex: 1;
+ width: 100%;
+ min-height: 0;
+}
+
+.column {
+ display: flex;
+ flex: 1 1 50%;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+ padding: var(--mantine-spacing-xl);
+
+ .searchInput {
+ border-radius: var(--mantine-radius-md);
+ }
+}
+
+.scrollArea {
+ flex: 1;
+ min-height: 0;
+}
+
+.emptyState {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ justify-content: center;
+}
+
+.row {
+ min-height: 2.5rem;
+ border: 1px solid var(--mb-color-border);
+ border-radius: var(--mantine-radius-md);
+ padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
+}
+
+.row:hover {
+ background-color: var(--mb-color-background-hover);
+}
+
+.rowActive,
+.rowActive:hover {
+ border-color: var(--mb-color-brand);
+}
+
+.rowButton {
+ flex: 1;
+ min-width: 0;
+}
+
+.grabber {
+ display: flex;
+ align-items: center;
+ cursor: grab;
+ touch-action: none;
+}
+
+.addableRow {
+ min-height: 2.5rem;
+ border: 1px solid var(--mb-color-border);
+ border-radius: var(--mantine-radius-md);
+ padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);
+}
+
+.addableRow:hover {
+ background-color: var(--mb-color-background-hover);
+}
+
+.accordion .item,
+.accordion .item[data-active] {
+ border: none;
+ border-radius: var(--mantine-radius-md);
+}
+
+.accordion .item + .item {
+ margin-top: var(--mantine-spacing-sm);
+}
+
+.accordion .control {
+ padding: var(--mantine-spacing-sm);
+ border-radius: var(--mantine-radius-md);
+ background-color: var(--mb-color-background-secondary);
+}
+
+.accordion .control:hover {
+ background-color: var(--mb-color-background-hover);
+}
+
+.accordion .label {
+ padding: 0;
+ color: var(--mb-color-text-primary);
+ font-weight: 700;
+ font-size: var(--mantine-font-size-md);
+ line-height: normal;
+}
+
+.accordion .chevron {
+ width: auto;
+ height: auto;
+ margin-left: var(--mantine-spacing-sm);
+ border: none;
+ border-radius: 0;
+ color: var(--mb-color-text-secondary);
+}
+
+.accordion .content {
+ padding: var(--mantine-spacing-sm) 0 0 var(--mantine-spacing-lg);
+ border-top: none;
+}
+
+.column .deleteIconButton {
+ border: 1px solid var(--mb-color-border);
+ height: 2.25rem;
+ width: 2.25rem;
+
+ &:hover {
+ border: 1px solid var(--mb-color-border-strong);
+ }
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.tsx
new file mode 100644
index 00000000000..935cf9a7124
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.tsx
@@ -0,0 +1,150 @@
+import { useState } from "react";
+import { match } from "ts-pattern";
+import { t } from "ttag";
+
+import {
+ useListMetricDimensionsQuery,
+ useRemoveMetricDimensionsMutation,
+ useReorderMetricDimensionsMutation,
+} from "metabase/api/metric";
+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { Box, Divider, Flex, Paper } from "metabase/ui";
+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";
+import type {
+ CardQueryMetadata,
+ DimensionId,
+ MetricId,
+} from "metabase-types/api";
+
+import { AddDimensionsPanel } from "./AddDimensionsPanel";
+import { DimensionList } from "./DimensionList";
+import { DimensionSettingsPanel } from "./DimensionSettingsPanel";
+import S from "./MetricDimensions.module.css";
+
+type DetailMode =
+ | { type: "idle" }
+ | { type: "add" }
+ | { type: "edit"; dimensionId: DimensionId };
+
+interface MetricDimensionsProps {
+ metricId: MetricId;
+ queryMetadata: CardQueryMetadata;
+}
+
+export function MetricDimensions({
+ metricId,
+ queryMetadata,
+}: MetricDimensionsProps) {
+ const dispatch = useDispatch();
+ const [search, setSearch] = useState("");
+ const [checkedIds, setCheckedIds] = useState<Set<DimensionId>>(new Set());
+ const [mode, setMode] = useState<DetailMode>({ type: "idle" });
+
+ const debouncedSearch = useDebouncedValue(search, SEARCH_DEBOUNCE_DURATION);
+ const { data, isLoading, error, isFetching } = useListMetricDimensionsQuery({
+ metricId,
+ query: debouncedSearch || undefined,
+ "include-orphaned": true,
+ });
+ const [removeDimensions] = useRemoveMetricDimensionsMutation();
+ const [reorderDimensions] = useReorderMetricDimensionsMutation();
+
+ const dimensions = data?.added ?? [];
+
+ const handleToggle = (id: DimensionId, checked: boolean) => {
+ setCheckedIds((prev) => {
+ const next = new Set(prev);
+ if (checked) {
+ next.add(id);
+ } else {
+ next.delete(id);
+ }
+ return next;
+ });
+ };
+
+ const handleRemove = async () => {
+ const ids = Array.from(checkedIds);
+ try {
+ await removeDimensions({ metricId, dimension_ids: ids }).unwrap();
+ setCheckedIds(new Set());
+ setMode((current) =>
+ current.type === "edit" && ids.includes(current.dimensionId)
+ ? { type: "idle" }
+ : current,
+ );
+ } catch {
+ dispatch(
+ addUndo({ message: t`Couldn't remove the selected dimensions` }),
+ );
+ }
+ };
+
+ const handleReorder = async (ids: DimensionId[]) => {
+ try {
+ await reorderDimensions({ metricId, dimension_ids: ids }).unwrap();
+ } catch {
+ dispatch(addUndo({ message: t`Couldn't reorder the dimensions` }));
+ }
+ };
+
+ const activeId = mode.type === "edit" ? mode.dimensionId : null;
+
+ return (
+ <Paper
+ withBorder
+ shadow="none"
+ className={S.root}
+ data-testid="metric-dimensions"
+ >
+ <Flex className={S.columns}>
+ <DimensionList
+ dimensions={dimensions}
+ isLoading={isLoading}
+ error={error}
+ search={search}
+ isSearchActive={search.length > 0 || Boolean(debouncedSearch)}
+ checkedIds={checkedIds}
+ activeId={activeId}
+ isAddDisabled={mode.type === "add" || checkedIds.size > 0}
+ onSearchChange={setSearch}
+ onToggle={handleToggle}
+ onAdd={() => setMode({ type: "add" })}
+ onRemove={handleRemove}
+ onEdit={(dimensionId) => setMode({ type: "edit", dimensionId })}
+ onReorder={handleReorder}
+ />
+
+ <Divider orientation="vertical" />
+
+ {match(mode)
+ .with({ type: "idle" }, () => <Box className={S.column} />)
+ .with({ type: "add" }, () => (
+ <AddDimensionsPanel
+ metricId={metricId}
+ onDone={() => setMode({ type: "idle" })}
+ />
+ ))
+ .with({ type: "edit" }, ({ dimensionId }) => {
+ const dimension = dimensions.find(
+ (item) => item.id === dimensionId,
+ );
+ return dimension ? (
+ <DimensionSettingsPanel
+ dimension={dimension}
+ isFetching={isFetching}
+ key={dimension.id}
+ metricId={metricId}
+ queryMetadata={queryMetadata}
+ />
+ ) : (
+ <Box className={S.column} />
+ );
+ })
+ .exhaustive()}
+ </Flex>
+ </Paper>
+ );
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.unit.spec.tsx
new file mode 100644
index 00000000000..423b045db4b
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/MetricDimensions.unit.spec.tsx
@@ -0,0 +1,630 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupMetricDimensionsEndpoints } from "__support__/server-mocks";
+import {
+ renderWithProviders,
+ screen,
+ waitFor,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { metricApi } from "metabase/api/metric";
+import type { ListMetricDimensionsResponse } from "metabase-types/api";
+import {
+ createMockCardQueryMetadata,
+ createMockField,
+ createMockTable,
+} from "metabase-types/api/mocks";
+import {
+ createMockAddableDimensionGroup,
+ createMockAddableMetricDimension,
+ createMockMetricDimension,
+ createMockMetricDimensionGroup,
+} from "metabase-types/api/mocks/metric";
+
+import { MetricDimensions } from "./MetricDimensions";
+
+const METRIC_ID = 1;
+
+const CREATED_AT_ID = "11111111-1111-4111-8111-111111111111";
+const COUNTRY_ID = "22222222-2222-4222-8222-222222222222";
+const SUSPEND_AT_ID = "33333333-3333-4333-8333-333333333333";
+
+const MAIN_GROUP = createMockMetricDimensionGroup({
+ id: "main",
+ type: "main",
+ display_name: "The main table",
+});
+
+const CREATED_AT = createMockMetricDimension({
+ id: CREATED_AT_ID,
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ status: "status/active",
+ default: true,
+ group: MAIN_GROUP,
+ sources: [{ type: "field", "field-id": 101 }],
+});
+
+const COUNTRY = createMockMetricDimension({
+ id: COUNTRY_ID,
+ display_name: "Country",
+ effective_type: "type/Text",
+ semantic_type: "type/Country",
+ status: "status/active",
+ sources: [{ type: "field", "field-id": 102 }],
+});
+
+const SUSPEND_AT = createMockMetricDimension({
+ id: SUSPEND_AT_ID,
+ display_name: "Suspend At",
+ effective_type: "type/DateTime",
+ semantic_type: null,
+ status: "status/orphaned",
+ sources: [{ type: "field", "field-id": 103 }],
+});
+
+const BILLED_AT = createMockAddableMetricDimension({
+ id: "44444444-4444-4444-8444-444444444444",
+ display_name: "Billed At",
+ effective_type: "type/DateTime",
+ semantic_type: null,
+ sources: [{ type: "field", "field-id": 201 }],
+ mapping_target: ["field", { "source-field": 105 }, 201],
+});
+
+const PLAN_NAME = createMockAddableMetricDimension({
+ id: "55555555-5555-4555-8555-555555555555",
+ display_name: "Plan Name",
+ effective_type: "type/Text",
+ semantic_type: null,
+ sources: [{ type: "field", "field-id": 202 }],
+ mapping_target: ["field", { "source-field": 105 }, 202],
+});
+
+const ADDABLE_GROUP = createMockAddableDimensionGroup({
+ group: createMockMetricDimensionGroup({
+ id: "fk",
+ type: "connection",
+ display_name: "Some FK-linked table",
+ }),
+ dimensions: [BILLED_AT, PLAN_NAME],
+});
+
+const SELF_ADDABLE_COLUMN = createMockAddableMetricDimension({
+ id: "66666666-6666-4666-8666-666666666666",
+ display_name: "Plan Updated At",
+ effective_type: "type/DateTime",
+ semantic_type: null,
+ sources: [{ type: "field", "field-id": 104 }],
+ mapping_target: ["field", {}, 104],
+});
+
+const SELF_ADDABLE_GROUP = createMockAddableDimensionGroup({
+ group: createMockMetricDimensionGroup({
+ id: "main",
+ type: "main",
+ display_name: "The main table",
+ }),
+ dimensions: [SELF_ADDABLE_COLUMN],
+});
+
+const QUERY_METADATA = createMockCardQueryMetadata({
+ tables: [
+ createMockTable({
+ fields: [
+ createMockField({ id: 101, display_name: "Created At" }),
+ createMockField({ id: 102, display_name: "City" }),
+ ],
+ }),
+ ],
+});
+
+function setup(response?: Partial<ListMetricDimensionsResponse>) {
+ const fullResponse: ListMetricDimensionsResponse = {
+ added: [CREATED_AT, COUNTRY, SUSPEND_AT],
+ addable: [SELF_ADDABLE_GROUP, ADDABLE_GROUP],
+ ...response,
+ };
+ setupMetricDimensionsEndpoints(METRIC_ID, fullResponse);
+ const { store } = renderWithProviders(
+ <MetricDimensions metricId={METRIC_ID} queryMetadata={QUERY_METADATA} />,
+ );
+ return { store };
+}
+
+function getListPanel() {
+ return within(screen.getByTestId("metric-dimension-list"));
+}
+
+function getDimensionRow(name: string) {
+ return within(screen.getByTestId(`dimension-row-${name}`));
+}
+
+async function openSettings(name: RegExp) {
+ await userEvent.click(getListPanel().getByRole("button", { name }));
+ return screen.findByTestId("dimension-settings-panel");
+}
+
+async function getPostBody(path: string) {
+ const calls = fetchMock.callHistory.calls(path, { method: "POST" });
+ expect(calls).toHaveLength(1);
+ const body = calls[0].options?.body;
+ if (typeof body !== "string") {
+ throw new Error("expected a string request body");
+ }
+ return JSON.parse(body);
+}
+
+describe("MetricDimensions", () => {
+ it("renders the list of added dimensions", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ expect(getListPanel().getByText("Created At")).toBeInTheDocument();
+ expect(getListPanel().getByText("Country")).toBeInTheDocument();
+ expect(screen.getByText("Dimensions of this metric")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Available dimensions" }),
+ ).toHaveAttribute("data-variant", "default");
+ });
+
+ it("shows an empty state and hides search when no dimensions have been added", async () => {
+ setup({ added: [] });
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ getListPanel().getByText("No dimensions have been added."),
+ ).toBeInTheDocument();
+ expect(
+ getListPanel().queryByPlaceholderText("Search…"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a search empty state and keeps search visible", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const search = getListPanel().getByPlaceholderText("Search…");
+ await userEvent.type(search, "Missing");
+
+ expect(
+ await getListPanel().findByText("No dimensions match your search."),
+ ).toBeInTheDocument();
+ expect(search).toBeInTheDocument();
+ });
+
+ it("shows no detail panel until the user acts", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ screen.queryByTestId("add-dimensions-panel"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("dimension-settings-panel"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("marks the default dimension with a badge", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ getDimensionRow("Created At").getByText("Default"),
+ ).toBeInTheDocument();
+ expect(
+ getDimensionRow("Country").queryByText("Default"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("marks orphaned dimensions with a warning", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ getDimensionRow("Suspend At").getByLabelText("warning icon"),
+ ).toBeInTheDocument();
+ expect(
+ getDimensionRow("Created At").queryByLabelText("warning icon"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("removes selected dimensions", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ getListPanel().getByRole("checkbox", { name: "Created At" }),
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Remove" }));
+
+ await waitFor(async () => {
+ expect(
+ await getPostBody(`path:/api/metric/${METRIC_ID}/dimension/remove`),
+ ).toEqual({ dimension_ids: [CREATED_AT_ID] });
+ });
+ });
+
+ it("shows the empty state after removing the final dimension", async () => {
+ setup({ added: [COUNTRY] });
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ getListPanel().getByRole("checkbox", { name: "Country" }),
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Remove" }));
+
+ expect(
+ await getListPanel().findByText("No dimensions have been added."),
+ ).toBeInTheDocument();
+ expect(
+ getListPanel().queryByPlaceholderText("Search…"),
+ ).not.toBeInTheDocument();
+ expect(
+ await getPostBody(`path:/api/metric/${METRIC_ID}/dimension/remove`),
+ ).toEqual({ dimension_ids: [COUNTRY_ID] });
+ });
+
+ it("adds a joined-table dimension with a table-prefixed title", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Available dimensions" }),
+ );
+
+ const addPanel = within(await screen.findByTestId("add-dimensions-panel"));
+ expect(addPanel.getByText("Add available dimensions")).toBeInTheDocument();
+ expect(
+ await addPanel.findByText("Some FK-linked table"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ await addPanel.findByRole("button", { name: /Billed At/ }),
+ );
+
+ await waitFor(async () => {
+ expect(
+ await getPostBody(`path:/api/metric/${METRIC_ID}/dimension/add`),
+ ).toEqual({
+ dimensions: [
+ { ...BILLED_AT, display_name: "Some FK-linked table - Billed At" },
+ ],
+ });
+ });
+ });
+
+ it("keeps the plain title for a self-table dimension", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Available dimensions" }),
+ );
+
+ const addPanel = within(await screen.findByTestId("add-dimensions-panel"));
+ await userEvent.click(
+ await addPanel.findByRole("button", { name: /Plan Updated At/ }),
+ );
+
+ await waitFor(async () => {
+ expect(
+ await getPostBody(`path:/api/metric/${METRIC_ID}/dimension/add`),
+ ).toEqual({ dimensions: [SELF_ADDABLE_COLUMN] });
+ });
+ });
+
+ it("shows an empty state and hides search when all dimensions have been added", async () => {
+ setup({ addable: [] });
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Available dimensions" }),
+ );
+
+ const addPanel = within(await screen.findByTestId("add-dimensions-panel"));
+ await waitForLoaderToBeRemoved();
+ expect(
+ addPanel.getByText("All available dimensions have been added"),
+ ).toBeInTheDocument();
+ expect(addPanel.queryByPlaceholderText("Search…")).not.toBeInTheDocument();
+ });
+
+ it("shows an available-dimension search empty state and keeps search visible", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Available dimensions" }),
+ );
+ const addPanel = within(await screen.findByTestId("add-dimensions-panel"));
+ await waitForLoaderToBeRemoved();
+ const search = addPanel.getByPlaceholderText("Search…");
+ await userEvent.type(search, "Missing");
+
+ expect(
+ await addPanel.findByText("No dimensions match your search."),
+ ).toBeInTheDocument();
+ expect(search).toBeInTheDocument();
+ });
+
+ it("edits a dimension's display name", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ expect(settings.getByText("Settings for Created At")).toBeInTheDocument();
+
+ const nameInput = settings.getByLabelText("Display name");
+ await userEvent.clear(nameInput);
+ await userEvent.type(nameInput, " Creation date ");
+ await userEvent.tab();
+
+ await waitFor(async () => {
+ const body = await getPostBody(
+ `path:/api/metric/${METRIC_ID}/dimension/${CREATED_AT_ID}`,
+ );
+ expect(body.display_name).toBe("Creation date");
+ });
+ expect(nameInput).toHaveValue("Creation date");
+ });
+
+ it("restores a blank display name without making a request", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ const nameInput = settings.getByLabelText("Display name");
+ await userEvent.clear(nameInput);
+ await userEvent.type(nameInput, " ");
+ await userEvent.tab();
+
+ expect(nameInput).toHaveValue("Created At");
+ expect(
+ fetchMock.callHistory.calls(
+ `path:/api/metric/${METRIC_ID}/dimension/${CREATED_AT_ID}`,
+ { method: "POST" },
+ ),
+ ).toHaveLength(0);
+ });
+
+ it("restores the persisted display name when an update fails", async () => {
+ setup();
+ fetchMock.modifyRoute(
+ `metric-${METRIC_ID}-dimension-${CREATED_AT_ID}-update`,
+ { response: { status: 500 } },
+ );
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ const nameInput = settings.getByLabelText("Display name");
+ await userEvent.clear(nameInput);
+ await userEvent.type(nameInput, "Creation date");
+ await userEvent.tab();
+
+ await waitFor(() => {
+ expect(nameInput).toHaveValue("Created At");
+ });
+ });
+
+ it("sets a dimension as the default", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Country/));
+ await userEvent.click(
+ settings.getByRole("button", { name: "Set as default" }),
+ );
+
+ await waitFor(async () => {
+ expect(
+ await getPostBody(
+ `path:/api/metric/${METRIC_ID}/dimension/set-default`,
+ ),
+ ).toEqual({ dimension_id: COUNTRY_ID });
+ });
+ });
+
+ it("does not offer set-default for the current default dimension", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ expect(settings.getByText("Default dimension")).toBeInTheDocument();
+ expect(
+ settings.queryByRole("button", { name: "Set as default" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not offer set-default for orphaned dimensions", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Suspend At/));
+ expect(
+ settings.queryByRole("button", { name: "Set as default" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a loading state while setting a default dimension", async () => {
+ let resolveSetDefault: (dimensions: (typeof COUNTRY)[]) => void = () => {};
+ setup();
+ fetchMock.modifyRoute(`metric-${METRIC_ID}-dimensions-set-default`, {
+ response: () =>
+ new Promise((resolve) => {
+ resolveSetDefault = resolve;
+ }),
+ });
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Country/));
+ const button = settings.getByRole("button", { name: "Set as default" });
+ await userEvent.click(button);
+
+ await waitFor(() => {
+ expect(button).toHaveAttribute("data-loading", "true");
+ });
+ expect(button).toBeDisabled();
+
+ resolveSetDefault([COUNTRY]);
+ await waitFor(() => {
+ expect(button).not.toHaveAttribute("data-loading", "true");
+ });
+ });
+
+ it("shows a loading state while dimensions are being fetched", async () => {
+ let resolveDimensions: (
+ response: ListMetricDimensionsResponse,
+ ) => void = () => {};
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Country/));
+ const button = settings.getByRole("button", { name: "Set as default" });
+ fetchMock.modifyRoute(`metric-${METRIC_ID}-dimensions-list`, {
+ response: () =>
+ new Promise((resolve) => {
+ resolveDimensions = resolve;
+ }),
+ });
+
+ await userEvent.type(
+ getListPanel().getByPlaceholderText("Search…"),
+ "Country",
+ );
+
+ await waitFor(() => {
+ expect(button).toHaveAttribute("data-loading", "true");
+ });
+ expect(button).toBeDisabled();
+
+ resolveDimensions({ added: [COUNTRY], addable: [] });
+ await waitFor(() => {
+ expect(button).not.toHaveAttribute("data-loading", "true");
+ });
+ });
+
+ it("displays the dimension type", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ const typeField = within(settings.getByTestId("dimension-type"));
+ expect(typeField.getByText("Dimension type")).toBeInTheDocument();
+ expect(typeField.getByText("Date")).toBeInTheDocument();
+ });
+
+ it("displays the source column read-only as table.column", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/Created At/));
+ const sourceField = within(settings.getByTestId("dimension-source"));
+
+ expect(sourceField.getByText("Source column")).toBeInTheDocument();
+ expect(
+ sourceField.getByText("The main table.Created At"),
+ ).toBeInTheDocument();
+ expect(
+ settings.queryByRole("textbox", { name: "Source column" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not use the dimension display name for the source column", async () => {
+ setup({
+ added: [
+ createMockMetricDimension({
+ ...COUNTRY,
+ display_name: "User - City",
+ group: createMockMetricDimensionGroup({
+ type: "connection",
+ display_name: "User",
+ }),
+ sources: [{ type: "field", "field-id": 102 }],
+ }),
+ ],
+ });
+ await waitForLoaderToBeRemoved();
+
+ const settings = within(await openSettings(/User - City/));
+ const sourceField = within(settings.getByTestId("dimension-source"));
+
+ expect(sourceField.getByText("User.City")).toBeInTheDocument();
+ expect(sourceField.queryByText("User.User - City")).not.toBeInTheDocument();
+ });
+
+ it("shows a drag handle on every row", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ expect(
+ getDimensionRow("Created At").getByLabelText("grabber icon"),
+ ).toBeInTheDocument();
+ expect(
+ getDimensionRow("Country").getByLabelText("grabber icon"),
+ ).toBeInTheDocument();
+ });
+
+ it("hides drag handles while searching", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.type(
+ getListPanel().getByPlaceholderText("Search…"),
+ "Country",
+ );
+
+ await waitFor(() => {
+ expect(getListPanel().queryByText("Created At")).not.toBeInTheDocument();
+ });
+ expect(
+ getDimensionRow("Country").queryByLabelText("grabber icon"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("reordering posts the new order and reorders the list optimistically", async () => {
+ const { store } = setup();
+ await waitForLoaderToBeRemoved();
+
+ const newOrder = [COUNTRY_ID, SUSPEND_AT_ID, CREATED_AT_ID];
+ store.dispatch(
+ metricApi.endpoints.reorderMetricDimensions.initiate({
+ metricId: METRIC_ID,
+ dimension_ids: newOrder,
+ }),
+ );
+
+ await waitFor(() => {
+ const names = getListPanel()
+ .getAllByTestId(/^dimension-row-/)
+ .map((row) => row.getAttribute("data-testid"));
+ expect(names).toEqual([
+ "dimension-row-Country",
+ "dimension-row-Suspend At",
+ "dimension-row-Created At",
+ ]);
+ });
+
+ expect(
+ await getPostBody(`path:/api/metric/${METRIC_ID}/dimension/reorder`),
+ ).toEqual({ dimension_ids: newOrder });
+ });
+
+ it("searches the added dimensions", async () => {
+ setup();
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.type(
+ getListPanel().getByPlaceholderText("Search…"),
+ "Country",
+ );
+
+ await waitFor(() => {
+ expect(getListPanel().queryByText("Created At")).not.toBeInTheDocument();
+ });
+ expect(getListPanel().getByText("Country")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/index.ts b/frontend/src/metabase/metrics/components/MetricDimensions/index.ts
new file mode 100644
index 00000000000..987f78316b3
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/index.ts
@@ -0,0 +1 @@
+export { MetricDimensions } from "./MetricDimensions";
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/utils.ts b/frontend/src/metabase/metrics/components/MetricDimensions/utils.ts
new file mode 100644
index 00000000000..2f7f30ef392
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/utils.ts
@@ -0,0 +1,93 @@
+import { t } from "ttag";
+
+import { COORDINATE, LOCATION } from "metabase-lib/v1/types/constants";
+import {
+ isBoolean,
+ isCategory,
+ isDate,
+ isFieldType,
+ isNumeric,
+ isString,
+ isStringLike,
+} from "metabase-lib/v1/types/utils/isa";
+import type {
+ CardQueryMetadata,
+ MetricDimension,
+ MetricDimensionGroup,
+} from "metabase-types/api";
+
+export type DimensionTypeKey =
+ | "date"
+ | "geolocation"
+ | "category"
+ | "number"
+ | "other";
+
+export function getDimensionTypeKey(
+ dimension: MetricDimension,
+): DimensionTypeKey {
+ if (isDate(dimension)) {
+ return "date";
+ }
+ if (isFieldType(LOCATION, dimension) || isFieldType(COORDINATE, dimension)) {
+ return "geolocation";
+ }
+ if (
+ isCategory(dimension) ||
+ isString(dimension) ||
+ isStringLike(dimension) ||
+ isBoolean(dimension)
+ ) {
+ return "category";
+ }
+ if (isNumeric(dimension)) {
+ return "number";
+ }
+ return "other";
+}
+
+export function getDimensionTypeLabel(dimension: MetricDimension): string {
+ switch (getDimensionTypeKey(dimension)) {
+ case "date":
+ return t`Date`;
+ case "geolocation":
+ return t`Location`;
+ case "category":
+ return t`Category`;
+ case "number":
+ return t`Number`;
+ case "other":
+ return t`Other`;
+ }
+}
+
+export function isOrphaned(dimension: MetricDimension): boolean {
+ return dimension.status === "status/orphaned";
+}
+
+export function getNewDimensionTitle(
+ group: MetricDimensionGroup,
+ dimension: MetricDimension,
+): string {
+ return group.type === "connection"
+ ? `${group.display_name} - ${dimension.display_name}`
+ : dimension.display_name;
+}
+
+export function getSourceColumnLabel(
+ dimension: MetricDimension,
+ queryMetadata: CardQueryMetadata,
+): string | null {
+ const sourceFieldId = dimension.sources?.[0]?.["field-id"];
+ const sourceField =
+ queryMetadata.fields.find((field) => field.id === sourceFieldId) ??
+ queryMetadata.tables
+ .flatMap((table) => table.fields ?? [])
+ .find((field) => field.id === sourceFieldId);
+ const sourceColumn = sourceField?.display_name;
+ if (!sourceColumn) {
+ return null;
+ }
+ const table = dimension.group?.display_name;
+ return table ? `${table}.${sourceColumn}` : sourceColumn;
+}
diff --git a/frontend/src/metabase/metrics/components/MetricDimensions/utils.unit.spec.ts b/frontend/src/metabase/metrics/components/MetricDimensions/utils.unit.spec.ts
new file mode 100644
index 00000000000..1edfec2d0cd
--- /dev/null
+++ b/frontend/src/metabase/metrics/components/MetricDimensions/utils.unit.spec.ts
@@ -0,0 +1,110 @@
+import {
+ createMockMetricDimension,
+ createMockMetricDimensionGroup,
+} from "metabase-types/api/mocks/metric";
+
+import { getDimensionTypeKey, getNewDimensionTitle } from "./utils";
+
+describe("getDimensionTypeKey", () => {
+ it("classifies temporal columns as date", () => {
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({ effective_type: "type/DateTime" }),
+ ),
+ ).toBe("date");
+ });
+
+ it("classifies location and coordinate columns as geolocation", () => {
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Text",
+ semantic_type: "type/Country",
+ }),
+ ),
+ ).toBe("geolocation");
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Float",
+ semantic_type: "type/Latitude",
+ }),
+ ),
+ ).toBe("geolocation");
+ });
+
+ it("classifies category, string, and boolean columns as category", () => {
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ }),
+ ),
+ ).toBe("category");
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Text",
+ semantic_type: null,
+ }),
+ ),
+ ).toBe("category");
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Boolean",
+ semantic_type: null,
+ }),
+ ),
+ ).toBe("category");
+ });
+
+ it("classifies numeric columns as number", () => {
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Integer",
+ semantic_type: null,
+ }),
+ ),
+ ).toBe("number");
+ });
+
+ it("falls back to other for unclassified columns", () => {
+ expect(
+ getDimensionTypeKey(
+ createMockMetricDimension({
+ effective_type: "type/Structured",
+ semantic_type: null,
+ }),
+ ),
+ ).toBe("other");
+ });
+});
+
+describe("getNewDimensionTitle", () => {
+ it("prefixes joined-table columns with the source table name", () => {
+ expect(
+ getNewDimensionTitle(
+ createMockMetricDimensionGroup({
+ type: "connection",
+ display_name: "Product",
+ }),
+ createMockMetricDimension({ display_name: "Category" }),
+ ),
+ ).toBe("Product - Category");
+ });
+
+ it("keeps the plain name for the metric's own table", () => {
+ expect(
+ getNewDimensionTitle(
+ createMockMetricDimensionGroup({
+ type: "main",
+ display_name: "Orders",
+ }),
+ createMockMetricDimension({ display_name: "Created At" }),
+ ),
+ ).toBe("Created At");
+ });
+});
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
index 09db7b1c34b..90d4f442b35 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx
@@ -65,6 +65,11 @@ function getTabs(
label: t`Definition`,
to: urls.query(card.id),
});
+
+ tabs.push({
+ label: t`Dimensions`,
+ to: urls.dimensions(card.id),
+ });
}
if (PLUGIN_DEPENDENCIES.isEnabled && canSeeDependencies) {
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
index af32851879f..fccdafc0361 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
@@ -25,6 +25,7 @@ const urls: MetricUrls = {
about: (id) => `/metric/${id}/about`,
overview: (id) => `/metric/${id}/overview`,
query: (id) => `/metric/${id}/query`,
+ dimensions: (id) => `/metric/${id}/dimensions`,
dependencies: (id) => `/metric/${id}/dependencies`,
history: (id) => `/metric/${id}/history`,
};
@@ -99,6 +100,7 @@ describe("MetricTabs", () => {
"About",
"Overview",
"Definition",
+ "Dimensions",
"History",
]);
});
@@ -111,19 +113,25 @@ describe("MetricTabs", () => {
"About",
"Overview",
"Definition",
+ "Dimensions",
"History",
]);
});
});
- it("should hide the overview tab when metric has no dimensions", async () => {
+ it("hides the overview tab when the metric has no dimensions", async () => {
setup({ hasDimensions: false });
await waitFor(() => {
- expect(getTabLabels()).toEqual(["About", "Definition", "History"]);
+ expect(getTabLabels()).toEqual([
+ "About",
+ "Definition",
+ "Dimensions",
+ "History",
+ ]);
});
});
- it("should hide the overview and definition tabs when the query is not editable", async () => {
+ it("should hide the overview, definition, and dimensions tabs when the query is not editable", async () => {
setup({
hasDataPermissions: false,
hasDimensions: true,
@@ -134,6 +142,13 @@ describe("MetricTabs", () => {
});
});
+ it("shows the dimensions tab for editable metrics", async () => {
+ setup();
+ await waitFor(() => {
+ expect(getTabLabels()).toContain("Dimensions");
+ });
+ });
+
describe("Dependencies tab (role-gated)", () => {
it("shows for admins", async () => {
setup({ role: "admin" });
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
index 98e295dcf18..0ea9aedb32e 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx
@@ -37,6 +37,7 @@ const mockUrls = {
about: (id: number) => `/metric/${id}`,
overview: (id: number) => `/metric/${id}/overview`,
query: (id: number) => `/metric/${id}/query`,
+ dimensions: (id: number) => `/metric/${id}/dimensions`,
dependencies: (id: number) => `/metric/${id}/dependencies`,
history: (id: number) => `/metric/${id}/history`,
};
diff --git a/frontend/src/metabase/metrics/components/MetricPageCard/MetricPageCard.tsx b/frontend/src/metabase/metrics/components/MetricPageCard/MetricPageCard.tsx
index bb3faf02cfd..16f3ca1b5ef 100644
--- a/frontend/src/metabase/metrics/components/MetricPageCard/MetricPageCard.tsx
+++ b/frontend/src/metabase/metrics/components/MetricPageCard/MetricPageCard.tsx
@@ -7,11 +7,11 @@ import { useLoadCardWithMetadata } from "metabase/metrics/common/use-load-card-w
import { Center } from "metabase/ui";
import * as Urls from "metabase/urls";
import { is403Error } from "metabase/utils/errors";
-import type { Card } from "metabase-types/api";
+import type { Card, CardQueryMetadata } from "metabase-types/api";
interface MetricPageCardProps {
cardId: string | undefined;
- children: (card: Card) => ReactNode;
+ children: (card: Card, metadata: CardQueryMetadata) => ReactNode;
}
/**
@@ -26,7 +26,7 @@ export function MetricPageCard({
children,
}: MetricPageCardProps) {
const cardId = Urls.extractEntityId(rawCardId);
- const { card, isLoading, error } = useLoadCardWithMetadata(cardId);
+ const { card, metadata, isLoading, error } = useLoadCardWithMetadata(cardId);
const { error: datasetError, isLoading: isLoadingDataset } =
useGetCardQueryQuery(cardId != null ? { cardId } : skipToken);
@@ -35,7 +35,7 @@ export function MetricPageCard({
}
const loading = isLoading || isLoadingDataset;
- if (loading || error != null || card == null) {
+ if (loading || error != null || card == null || metadata == null) {
return (
<Center h="100%">
<LoadingAndErrorWrapper loading={loading} error={error} />
@@ -43,5 +43,5 @@ export function MetricPageCard({
);
}
- return <>{children(card)}</>;
+ return <>{children(card, metadata)}</>;
}
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/AboutVisualization.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/AboutVisualization.tsx
index f085a988e9a..dcac525a0f1 100644
--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/AboutVisualization.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/AboutVisualization.tsx
@@ -1,25 +1,29 @@
import { useMemo } from "react";
import { MetricCardVisualization } from "metabase/common/data-studio/components/OverviewVisualization";
-import { useCardQueryData } from "metabase/common/data-studio/hooks/use-card-query-data";
import { Box, Stack } from "metabase/ui";
import {
TrendInfo,
useTrendData,
} from "metabase/visualizations/components/TrendInfo";
-import type { Card } from "metabase-types/api";
+import type { Card, Dataset } from "metabase-types/api";
import S from "./MetricAbout.module.css";
interface AboutVisualizationProps {
card: Card;
+ data: Dataset | undefined;
+ isLoading: boolean;
}
const DATE_COLUMN_INDEX = 0;
const METRIC_COLUMN_INDEX = 1;
-export function AboutVisualization({ card }: AboutVisualizationProps) {
- const { data, isLoading } = useCardQueryData(card);
+export function AboutVisualization({
+ card,
+ data,
+ isLoading,
+}: AboutVisualizationProps) {
const trendData = useTrendData(data, DATE_COLUMN_INDEX, METRIC_COLUMN_INDEX);
const lineCard = useMemo(
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx
index 6949c6ec247..80e548f9cc0 100644
--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DescriptionSection/DescriptionSection.unit.spec.tsx
@@ -31,6 +31,7 @@ const URLS: MetricUrls = {
about: (id) => `/metric/${id}/about`,
overview: (id) => `/metric/${id}/overview`,
query: (id) => `/metric/${id}/query`,
+ dimensions: (id) => `/metric/${id}/dimensions`,
dependencies: (id) => `/metric/${id}/dependencies`,
history: (id) => `/metric/${id}/history`,
database: (id) => `/browse/databases/${id}`,
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.module.css b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.module.css
new file mode 100644
index 00000000000..c1c3520f1e0
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.module.css
@@ -0,0 +1,18 @@
+.trigger {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ font-size: var(--mantine-font-size-md);
+ font-weight: 700;
+ line-height: var(--mantine-line-height-md);
+ text-align: center;
+}
+
+.label {
+ overflow-wrap: anywhere;
+}
+
+.dropdown {
+ min-width: 15rem;
+ max-width: calc(100vw - var(--mantine-spacing-xl));
+}
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.tsx
new file mode 100644
index 00000000000..8ac5012cd05
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/DimensionSelect.tsx
@@ -0,0 +1,80 @@
+import { t } from "ttag";
+
+import {
+ Combobox,
+ DefaultSelectItem,
+ Icon,
+ UnstyledButton,
+ useCombobox,
+} from "metabase/ui";
+import type { IconName } from "metabase-types/api";
+
+import S from "./DimensionSelect.module.css";
+
+interface DimensionOption {
+ icon: IconName;
+ label: string;
+ value: string;
+}
+
+interface DimensionSelectProps {
+ label: string;
+ options: readonly DimensionOption[];
+ value: string;
+ onChange: (value: string) => void;
+}
+
+export function DimensionSelect({
+ label,
+ options,
+ value,
+ onChange,
+}: DimensionSelectProps) {
+ const combobox = useCombobox();
+
+ const handleOptionSubmit = (newValue: string) => {
+ onChange(newValue);
+ combobox.closeDropdown();
+ };
+
+ return (
+ <Combobox
+ store={combobox}
+ position="top"
+ width="max-content"
+ withinPortal
+ middlewares={{ flip: true, shift: true, size: true }}
+ onOptionSubmit={handleOptionSubmit}
+ >
+ <Combobox.Target>
+ <UnstyledButton
+ aria-label={t`Select dimension: ${label}`}
+ className={S.trigger}
+ onClick={() => combobox.toggleDropdown()}
+ >
+ <span className={S.label}>{label}</span>
+ <Icon flex="0 0 0.75rem" ml="sm" name="chevrondown" size={12} />
+ </UnstyledButton>
+ </Combobox.Target>
+ <Combobox.Dropdown className={S.dropdown}>
+ <Combobox.Options>
+ {options.map((option) => (
+ <Combobox.Option
+ key={option.value}
+ value={option.value}
+ selected={option.value === value}
+ p={0}
+ >
+ <DefaultSelectItem
+ value={option.value}
+ label={option.label}
+ icon={option.icon}
+ selected={option.value === value}
+ />
+ </Combobox.Option>
+ ))}
+ </Combobox.Options>
+ </Combobox.Dropdown>
+ </Combobox>
+ );
+}
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/index.ts b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/index.ts
new file mode 100644
index 00000000000..e1dc35d9dd2
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/DimensionSelect/index.ts
@@ -0,0 +1 @@
+export * from "./DimensionSelect";
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.module.css b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.module.css
index 4863642b0d9..b84e2954c10 100644
--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.module.css
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.module.css
@@ -6,6 +6,10 @@
display: flex;
flex-direction: column;
position: relative;
+ overflow: hidden;
+ background-color: var(--mb-color-background_page-primary);
+ border: 1px solid var(--mb-color-border-neutral);
+ border-radius: var(--default-border-radius);
}
.exploreButtonOverlay {
@@ -15,14 +19,22 @@
z-index: 1;
}
+.dimensionSelectContainer {
+ align-items: center;
+ display: flex;
+ flex: 0 0 1.5rem;
+ justify-content: center;
+ margin-bottom: var(--mantine-spacing-md);
+ max-width: 100%;
+}
+
.descriptionSection {
overflow: auto;
}
.visualizationPanel {
- background-color: var(--mb-color-background_page-primary);
- border: 1px solid var(--mb-color-border-neutral);
- border-radius: var(--default-border-radius);
+ flex: 1;
+ min-height: 0;
overflow: hidden;
/* keeps the embedded visualization non-interactive (no tooltips/hover) */
pointer-events: none;
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.tsx
index 46f88f3b44b..a91742866d9 100644
--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.tsx
@@ -1,15 +1,17 @@
+import { useState } from "react";
+
import { MetricCardVisualization } from "metabase/common/data-studio/components/OverviewVisualization";
-import { useCardQueryData } from "metabase/common/data-studio/hooks/use-card-query-data";
import type { MetricUrls } from "metabase/common/metrics/types";
import { isNumericMetric } from "metabase/metrics/utils/validation";
import { Box, Flex, Stack } from "metabase/ui";
-import { isDate, isNumeric } from "metabase-lib/v1/types/utils/isa";
import type { Card } from "metabase-types/api";
import { AboutVisualization } from "./AboutVisualization";
import { DescriptionSection } from "./DescriptionSection";
+import { DimensionSelect } from "./DimensionSelect";
import { ExploreMetricButton } from "./ExploreMetricButton";
import S from "./MetricAbout.module.css";
+import { useMetricAboutQuery } from "./use-metric-about-query";
interface MetricAboutProps {
card: Card;
@@ -17,12 +19,18 @@ interface MetricAboutProps {
}
export function MetricAbout({ card, urls }: MetricAboutProps) {
- const { data, isLoading } = useCardQueryData(card);
-
- // Time series → show value + change over time. Keyed off result columns, not the
- // Lib metric definition, so metrics defined on models (name-based breakout refs) work too.
- const cols = card.result_metadata;
- const isTimeSeries = isDate(cols?.[0]) && isNumeric(cols?.[1]);
+ const [selectedDimensionId, setSelectedDimensionId] = useState<string | null>(
+ null,
+ );
+ const {
+ activeDimensionId,
+ activeDimensionSelectLabel,
+ data,
+ dimensionOptions,
+ isLoading,
+ isTimeSeries,
+ visualizationCard,
+ } = useMetricAboutQuery(card, selectedDimensionId);
return (
<Flex className={S.root} flex={1} gap="md">
@@ -33,15 +41,29 @@ export function MetricAbout({ card, urls }: MetricAboutProps) {
</Box>
)}
{isTimeSeries ? (
- <AboutVisualization card={card} />
+ <AboutVisualization
+ card={visualizationCard}
+ data={data}
+ isLoading={isLoading}
+ />
) : (
<MetricCardVisualization
- card={card}
+ card={visualizationCard}
data={data}
isLoading={isLoading}
className={S.visualizationPanel}
/>
)}
+ {activeDimensionId && activeDimensionSelectLabel && (
+ <Box className={S.dimensionSelectContainer}>
+ <DimensionSelect
+ label={activeDimensionSelectLabel}
+ options={dimensionOptions}
+ value={activeDimensionId}
+ onChange={setSelectedDimensionId}
+ />
+ </Box>
+ )}
</Box>
<Stack flex="0 0 360px" className={S.descriptionSection} mah={700}>
<DescriptionSection card={card} urls={urls} />
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.unit.spec.tsx b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.unit.spec.tsx
index 9399ac15c7b..7e9f0d26dbd 100644
--- a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/MetricAbout.unit.spec.tsx
@@ -1,15 +1,18 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
import {
setupCardEndpoints,
- setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
setupDatabaseEndpoints,
+ setupMetricDatasetEndpoint,
setupMetricEndpoint,
} from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import { registerVisualizations } from "metabase/visualizations/register";
-import type { Card, Dataset, Field } from "metabase-types/api";
+import type { Card, Dataset, Field, Metric } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
@@ -18,10 +21,14 @@ import {
createMockDatasetData,
createMockField,
createMockMetric,
+ createMockMetricDimension,
createMockNumericColumn,
} from "metabase-types/api/mocks";
import {
+ ORDERS,
ORDERS_ID,
+ PRODUCTS,
+ PRODUCTS_ID,
SAMPLE_DB_ID,
createSampleDatabase,
} from "metabase-types/api/mocks/presets";
@@ -36,6 +43,7 @@ const mockUrls = {
about: (id: number) => `/metric/${id}`,
overview: (id: number) => `/metric/${id}/overview`,
query: (id: number) => `/metric/${id}/query`,
+ dimensions: (id: number) => `/metric/${id}/dimensions`,
dependencies: (id: number) => `/metric/${id}/dependencies`,
caching: (id: number) => `/metric/${id}/caching`,
history: (id: number) => `/metric/${id}/history`,
@@ -62,19 +70,72 @@ function makeMetricCard(resultMetadata: Field[]): Card {
const SCALAR_DATASET = createMockDataset({
data: createMockDatasetData({
cols: [createMockNumericColumn({ name: "count" })],
- rows: [],
+ rows: [[150]],
+ }),
+});
+
+const TIME_SERIES = createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "created_at",
+ base_type: "type/DateTime",
+ unit: "month",
+ }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ ["2023-12-01T00:00:00Z", 100],
+ ["2024-01-01T00:00:00Z", 150],
+ ],
}),
});
-function setup(card: Card, dataset: Dataset = SCALAR_DATASET) {
+const BINNED_NUMERIC_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "quantity",
+ display_name: "Quantity: 8 bins",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ binning_info: {
+ binning_strategy: "num-bins",
+ min_value: 0,
+ max_value: 100,
+ num_bins: 8,
+ bin_width: 12.5,
+ },
+ }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ [0, 10],
+ [12.5, 20],
+ ],
+ }),
+});
+
+interface SetupOptions {
+ metric?: Metric;
+ metricDataset?: Dataset;
+}
+
+function setup(
+ card: Card,
+ dataset: Dataset = SCALAR_DATASET,
+ { metric, metricDataset }: SetupOptions = {},
+) {
setupDatabaseEndpoints(SAMPLE_DB);
setupCardEndpoints(card);
setupCardQueryMetadataEndpoint(
card,
createMockCardQueryMetadata({ databases: [SAMPLE_DB] }),
);
- setupCardQueryEndpoints(card, dataset);
- setupMetricEndpoint(createMockMetric({ id: card.id, name: card.name }));
+ setupMetricEndpoint(
+ metric ?? createMockMetric({ id: card.id, name: card.name }),
+ );
+ setupMetricDatasetEndpoint(metricDataset ?? dataset);
renderWithProviders(
<Route path="/" element={<MetricAbout card={card} urls={mockUrls} />} />,
@@ -86,6 +147,14 @@ function setup(card: Card, dataset: Dataset = SCALAR_DATASET) {
);
}
+async function getMetricDatasetRequest(): Promise<unknown> {
+ await waitFor(() => {
+ expect(fetchMock.callHistory.calls("metric-dataset")).toHaveLength(1);
+ });
+
+ return fetchMock.callHistory.lastCall("metric-dataset")?.request?.json();
+}
+
describe("MetricAbout", () => {
it("renders the Explore button on the chart card for numeric metrics", async () => {
setup(
@@ -113,88 +182,326 @@ describe("MetricAbout", () => {
expect(screen.queryByTestId("explore-link")).not.toBeInTheDocument();
});
- // The value preview (latest value + period-over-period change) only renders
- // for a time series, so its presence/absence tells us which branch was chosen.
- describe("value + change-over-time preview", () => {
- const TIME_SERIES = createMockDataset({
- data: createMockDatasetData({
- cols: [
- createMockColumn({
- name: "created_at",
- base_type: "type/DateTime",
- unit: "month",
+ describe("curated default dimension", () => {
+ it("queries the curated default instead of the saved card query", async () => {
+ const defaultDimensionId = "product-category";
+ const metric = createMockMetric({
+ id: 42,
+ dimensions: [
+ createMockMetricDimension({
+ id: defaultDimensionId,
+ display_name: "Product Category",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ default: true,
+ status: "status/active",
}),
- createMockNumericColumn({ name: "count" }),
],
- rows: [
- ["2023-12-01T00:00:00Z", 100],
- ["2024-01-01T00:00:00Z", 150],
+ dimension_mappings: [
+ {
+ dimension_id: defaultDimensionId,
+ table_id: PRODUCTS_ID,
+ target: [
+ "field",
+ { "source-field": ORDERS.PRODUCT_ID },
+ PRODUCTS.CATEGORY,
+ ],
+ },
],
- }),
- });
+ });
+ const categoryDataset = createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "category",
+ base_type: "type/Text",
+ semantic_type: "type/Category",
+ }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ ["Doohickey", 40],
+ ["Gadget", 60],
+ ],
+ }),
+ });
- it("shows the latest value when results are a (date, value) time series", async () => {
setup(
makeMetricCard([
createMockField({ name: "created_at", base_type: "type/DateTime" }),
createMockField({ name: "count", base_type: "type/Integer" }),
]),
TIME_SERIES,
+ { metric, metricDataset: categoryDataset },
);
+ expect(await getMetricDatasetRequest()).toEqual({
+ definition: expect.objectContaining({
+ projections: [
+ expect.objectContaining({
+ projection: [
+ ["dimension", expect.any(Object), defaultDimensionId],
+ ],
+ }),
+ ],
+ }),
+ });
+ expect(
+ fetchMock.callHistory.calls("path:/api/card/42/query"),
+ ).toHaveLength(0);
+ expect(
+ screen.queryByTestId("metric-value-preview"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("uses the curated time dimension for the value preview", async () => {
+ const defaultDimensionId = "created-at";
+ const metric = createMockMetric({
+ id: 42,
+ dimensions: [
+ createMockMetricDimension({
+ id: defaultDimensionId,
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ default: true,
+ status: "status/active",
+ }),
+ ],
+ dimension_mappings: [
+ {
+ dimension_id: defaultDimensionId,
+ table_id: ORDERS_ID,
+ target: ["field", {}, ORDERS.CREATED_AT],
+ },
+ ],
+ });
+
+ setup(makeMetricCard([createMockField({ name: "count" })]), undefined, {
+ metric,
+ metricDataset: TIME_SERIES,
+ });
+
expect(
await screen.findByTestId("metric-value-preview"),
).toHaveTextContent("150");
+ expect(await getMetricDatasetRequest()).toEqual({
+ definition: expect.objectContaining({
+ projections: [
+ expect.objectContaining({
+ projection: [
+ ["dimension", expect.any(Object), defaultDimensionId],
+ ],
+ }),
+ ],
+ }),
+ });
+ expect(
+ fetchMock.callHistory.calls("path:/api/card/42/query"),
+ ).toHaveLength(0);
});
- it("does not show the value preview for a scalar metric with no date column", async () => {
- setup(
- makeMetricCard([
- createMockField({ name: "count", base_type: "type/Integer" }),
- ]),
+ it("changes the chart when a curated dimension is selected (UXW-4772)", async () => {
+ const defaultDimensionId = "created-at";
+ const categoryDimensionId = "product-category";
+ const metric = createMockMetric({
+ id: 42,
+ dimensions: [
+ createMockMetricDimension({
+ id: defaultDimensionId,
+ display_name: "Created At",
+ effective_type: "type/DateTime",
+ semantic_type: "type/CreationTimestamp",
+ default: true,
+ status: "status/active",
+ }),
+ createMockMetricDimension({
+ id: categoryDimensionId,
+ display_name: "Product Category",
+ effective_type: "type/Text",
+ semantic_type: "type/Category",
+ status: "status/active",
+ }),
+ ],
+ dimension_mappings: [
+ {
+ dimension_id: defaultDimensionId,
+ table_id: ORDERS_ID,
+ target: ["field", {}, ORDERS.CREATED_AT],
+ },
+ {
+ dimension_id: categoryDimensionId,
+ table_id: PRODUCTS_ID,
+ target: [
+ "field",
+ { "source-field": ORDERS.PRODUCT_ID },
+ PRODUCTS.CATEGORY,
+ ],
+ },
+ ],
+ });
+
+ setup(makeMetricCard([createMockField({ name: "count" })]), undefined, {
+ metric,
+ metricDataset: TIME_SERIES,
+ });
+
+ const dimensionSelect = await screen.findByRole("button", {
+ name: "Select dimension: Created At",
+ });
+ expect(dimensionSelect).toHaveTextContent("Created At");
+
+ await userEvent.click(dimensionSelect);
+ const categoryOption = await screen.findByRole("option", {
+ name: /Product Category/,
+ });
+ expect(categoryOption).toContainElement(
+ within(categoryOption).getByLabelText("string icon"),
);
+ await userEvent.click(categoryOption);
- expect(await screen.findByText("Source")).toBeInTheDocument();
expect(
- screen.queryByTestId("metric-value-preview"),
- ).not.toBeInTheDocument();
+ await screen.findByRole("button", {
+ name: "Select dimension: Product Category",
+ }),
+ ).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.calls("metric-dataset")).toHaveLength(2);
+ });
+ expect(
+ await fetchMock.callHistory.lastCall("metric-dataset")?.request?.json(),
+ ).toEqual({
+ definition: expect.objectContaining({
+ projections: [
+ expect.objectContaining({
+ projection: [
+ ["dimension", expect.any(Object), categoryDimensionId],
+ ],
+ }),
+ ],
+ }),
+ });
+ });
+
+ it("shows the bin count for the selected numeric dimension", async () => {
+ const dimensionId = "quantity";
+ const metric = createMockMetric({
+ id: 42,
+ dimensions: [
+ createMockMetricDimension({
+ id: dimensionId,
+ display_name: "Quantity",
+ effective_type: "type/Integer",
+ semantic_type: "type/Quantity",
+ default: true,
+ status: "status/active",
+ }),
+ ],
+ dimension_mappings: [
+ {
+ dimension_id: dimensionId,
+ table_id: ORDERS_ID,
+ target: ["field", {}, ORDERS.QUANTITY],
+ },
+ ],
+ });
+
+ setup(makeMetricCard([createMockField({ name: "count" })]), undefined, {
+ metric,
+ metricDataset: BINNED_NUMERIC_DATASET,
+ });
+
+ const dimensionSelect = await screen.findByRole("button", {
+ name: "Select dimension: Quantity: 8 bins",
+ });
+ expect(dimensionSelect).toHaveTextContent("Quantity: 8 bins");
+
+ await userEvent.click(dimensionSelect);
+ const quantityOption = await screen.findByRole("option", {
+ name: /Quantity/,
+ });
+ expect(quantityOption).toHaveTextContent("Quantity");
+ expect(quantityOption).not.toHaveTextContent("8 bins");
});
+ });
- it("does not show the value preview when broken out by a non-temporal dimension", async () => {
+ describe("scalar fallback", () => {
+ it("shows a scalar when the curated default cannot be charted", async () => {
setup(
makeMetricCard([
- createMockField({
- name: "category",
- base_type: "type/Text",
- semantic_type: "type/Category",
- }),
+ createMockField({ name: "created_at", base_type: "type/DateTime" }),
createMockField({ name: "count", base_type: "type/Integer" }),
]),
+ TIME_SERIES,
+ {
+ metric: createMockMetric({
+ id: 42,
+ dimensions: [
+ createMockMetricDimension({
+ id: "user-id",
+ effective_type: "type/Integer",
+ semantic_type: "type/FK",
+ default: true,
+ status: "status/active",
+ }),
+ ],
+ dimension_mappings: [
+ {
+ dimension_id: "user-id",
+ table_id: ORDERS_ID,
+ target: ["field", {}, ORDERS.USER_ID],
+ },
+ ],
+ }),
+ metricDataset: SCALAR_DATASET,
+ },
);
- expect(await screen.findByText("Source")).toBeInTheDocument();
+ expect(await screen.findByTestId("scalar-value")).toHaveTextContent(
+ "150",
+ );
expect(
- screen.queryByTestId("metric-value-preview"),
- ).not.toBeInTheDocument();
+ fetchMock.callHistory.calls("path:/api/card/42/query"),
+ ).toHaveLength(0);
+ expect(await getMetricDatasetRequest()).toEqual(
+ expect.objectContaining({
+ definition: expect.not.objectContaining({
+ projections: expect.anything(),
+ }),
+ }),
+ );
});
- it("does not show the value preview for a multi-breakout series where the value is not the second column", async () => {
+ it("shows a scalar when there are no curated dimensions", async () => {
setup(
makeMetricCard([
createMockField({ name: "created_at", base_type: "type/DateTime" }),
- createMockField({
- name: "category",
- base_type: "type/Text",
- semantic_type: "type/Category",
- }),
createMockField({ name: "count", base_type: "type/Integer" }),
]),
+ TIME_SERIES,
+ {
+ metric: createMockMetric({ id: 42, dimensions: [] }),
+ metricDataset: SCALAR_DATASET,
+ },
);
- expect(await screen.findByText("Source")).toBeInTheDocument();
+ expect(await screen.findByTestId("scalar-value")).toHaveTextContent(
+ "150",
+ );
expect(
- screen.queryByTestId("metric-value-preview"),
+ screen.queryByRole("button", { name: /Select dimension:/ }),
).not.toBeInTheDocument();
+ expect(await getMetricDatasetRequest()).toEqual(
+ expect.objectContaining({
+ definition: expect.not.objectContaining({
+ projections: expect.anything(),
+ }),
+ }),
+ );
+ expect(
+ fetchMock.callHistory.calls("path:/api/card/42/query"),
+ ).toHaveLength(0);
});
});
});
diff --git a/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/use-metric-about-query.ts b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/use-metric-about-query.ts
new file mode 100644
index 00000000000..f3d77343376
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricAboutPage/MetricAbout/use-metric-about-query.ts
@@ -0,0 +1,125 @@
+import { useMemo } from "react";
+
+import {
+ skipToken,
+ useGetMetricDatasetQuery,
+ useGetMetricQuery,
+} from "metabase/api";
+import { getDimensionDescriptors } from "metabase/common/metrics/utils/dimension-descriptors";
+import { DEFAULT_DISPLAY_TYPE_BY_DIMENSION } from "metabase/common/metrics/utils/dimension-types";
+import { getDimensionIcon } from "metabase/common/metrics/utils/dimensions";
+import {
+ useMetricDefinition,
+ useMetricDimensionQuery,
+} from "metabase/metrics/common/hooks";
+import * as LibMetric from "metabase-lib/metric";
+import { isDate, isNumeric } from "metabase-lib/v1/types/utils/isa";
+import type { Card } from "metabase-types/api";
+
+export function useMetricAboutQuery(
+ card: Card,
+ selectedDimensionId: string | null,
+) {
+ const { data: metric, isLoading: isLoadingMetric } = useGetMetricQuery(
+ card.id,
+ );
+ const { definition, isLoading: isLoadingDefinition } = useMetricDefinition(
+ card.id,
+ );
+
+ const defaultDimensionId =
+ metric?.dimensions.find(
+ (dimension) =>
+ dimension.default && dimension.status !== "status/orphaned",
+ )?.id ?? null;
+
+ const dimensionDescriptors = useMemo(
+ () => (definition ? getDimensionDescriptors(definition) : null),
+ [definition],
+ );
+ const dimensionOptions =
+ metric?.dimensions.flatMap((dimension) => {
+ const descriptor = dimensionDescriptors?.get(dimension.id);
+ if (dimension.status === "status/orphaned" || !descriptor) {
+ return [];
+ }
+
+ return [
+ {
+ value: dimension.id,
+ label: descriptor.displayName,
+ icon: getDimensionIcon(descriptor.dimensionMetadata),
+ },
+ ];
+ }) ?? [];
+ const activeDimensionId = selectedDimensionId ?? defaultDimensionId;
+
+ const activeDimensionType =
+ activeDimensionId && dimensionDescriptors
+ ? (dimensionDescriptors.get(activeDimensionId)?.dimensionType ?? null)
+ : null;
+
+ const useDimension = activeDimensionType != null;
+ const useScalar = metric != null && !useDimension;
+ const isWaitingForDefinition = metric != null && !definition;
+ const { data: dimensionData, isLoading: isLoadingDimension } =
+ useMetricDimensionQuery(
+ definition,
+ useDimension ? activeDimensionId : null,
+ );
+ const scalarRequest = useMemo(() => {
+ if (!useScalar || !definition) {
+ return null;
+ }
+
+ return { definition: LibMetric.toJsMetricDefinition(definition) };
+ }, [definition, useScalar]);
+ const { data: scalarData, isLoading: isLoadingScalar } =
+ useGetMetricDatasetQuery(scalarRequest ?? skipToken);
+ const data = useDimension ? dimensionData : scalarData;
+ const activeDimensionLabel = dimensionOptions.find(
+ (option) => option.value === activeDimensionId,
+ )?.label;
+ const activeDimensionSelectLabel =
+ activeDimensionType === "numeric"
+ ? (data?.data.cols[0]?.display_name ?? activeDimensionLabel)
+ : activeDimensionLabel;
+ const isLoading =
+ isLoadingMetric ||
+ isWaitingForDefinition ||
+ (useDimension && isLoadingDimension) ||
+ (useScalar && (isLoadingDefinition || isLoadingScalar));
+
+ const visualizationCard = useMemo(() => {
+ if (!activeDimensionType) {
+ return {
+ ...card,
+ display: "scalar" as const,
+ visualization_settings: {},
+ };
+ }
+
+ return {
+ ...card,
+ display: DEFAULT_DISPLAY_TYPE_BY_DIMENSION[activeDimensionType],
+ visualization_settings: {
+ "graph.x_axis.labels_enabled": false,
+ },
+ };
+ }, [card, activeDimensionType]);
+
+ // Time series → show value + change over time. Keyed off result columns, not the
+ // Lib metric definition, so metrics defined on models (name-based breakout refs) work too.
+ const cols = data?.data.cols;
+ const isTimeSeries = isDate(cols?.[0]) && isNumeric(cols?.[1]);
+
+ return {
+ activeDimensionId,
+ activeDimensionSelectLabel,
+ data,
+ dimensionOptions,
+ isLoading,
+ isTimeSeries,
+ visualizationCard,
+ };
+}
diff --git a/frontend/src/metabase/metrics/pages/MetricDependenciesPage/MetricDependenciesPage.tsx b/frontend/src/metabase/metrics/pages/MetricDependenciesPage/MetricDependenciesPage.tsx
index 3145688ec78..3370adfa883 100644
--- a/frontend/src/metabase/metrics/pages/MetricDependenciesPage/MetricDependenciesPage.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricDependenciesPage/MetricDependenciesPage.tsx
@@ -36,7 +36,7 @@ export function MetricDependenciesPage({
defaultEntry: { id: card.id, type: "card" },
}}
>
- <Card withBorder p={0} flex={1}>
+ <Card withBorder shadow="none" p={0} flex={1}>
<Outlet />
</Card>
</PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>
diff --git a/frontend/src/metabase/metrics/pages/MetricDimensionsPage/MetricDimensionsPage.tsx b/frontend/src/metabase/metrics/pages/MetricDimensionsPage/MetricDimensionsPage.tsx
new file mode 100644
index 00000000000..a0baf1431a2
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricDimensionsPage/MetricDimensionsPage.tsx
@@ -0,0 +1,37 @@
+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";
+import type {
+ MetricPageParams,
+ MetricPageProps,
+} from "metabase/common/metrics/types";
+import { useParams } from "metabase/router";
+
+import { MetricDimensions } from "../../components/MetricDimensions";
+import { MetricPageCard } from "../../components/MetricPageCard";
+import { MetricPageShell } from "../../components/MetricPageShell";
+import { metricUrls as defaultUrls } from "../../urls";
+
+export function MetricDimensionsPage({
+ urls = defaultUrls,
+ renderBreadcrumbs,
+ showAppSwitcher,
+ showDataStudioLink = true,
+}: MetricPageProps) {
+ const { cardId } = useParams<MetricPageParams>();
+
+ return (
+ <MetricPageCard cardId={cardId}>
+ {(card, metadata) => (
+ <PageContainer data-testid="metric-dimensions-page" gap="xl">
+ <MetricPageShell
+ card={card}
+ urls={urls}
+ renderBreadcrumbs={renderBreadcrumbs}
+ showAppSwitcher={showAppSwitcher}
+ showDataStudioLink={showDataStudioLink}
+ />
+ <MetricDimensions metricId={card.id} queryMetadata={metadata} />
+ </PageContainer>
+ )}
+ </MetricPageCard>
+ );
+}
diff --git a/frontend/src/metabase/metrics/pages/MetricDimensionsPage/index.ts b/frontend/src/metabase/metrics/pages/MetricDimensionsPage/index.ts
new file mode 100644
index 00000000000..e8bf42837cb
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/MetricDimensionsPage/index.ts
@@ -0,0 +1 @@
+export { MetricDimensionsPage } from "./MetricDimensionsPage";
diff --git a/frontend/src/metabase/metrics/pages/MetricHistoryPage/MetricHistoryPage.tsx b/frontend/src/metabase/metrics/pages/MetricHistoryPage/MetricHistoryPage.tsx
index b69efcd68e0..ab8cb115e84 100644
--- a/frontend/src/metabase/metrics/pages/MetricHistoryPage/MetricHistoryPage.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricHistoryPage/MetricHistoryPage.tsx
@@ -32,7 +32,7 @@ export function MetricHistoryPage({
showAppSwitcher={showAppSwitcher}
showDataStudioLink={showDataStudioLink}
/>
- <Card withBorder p="md" flex={1} className={S.card}>
+ <Card withBorder shadow="none" p="md" flex={1} className={S.card}>
<Box maw={800} pt="md" px="md">
<MetricActivityTimeline card={card} />
</Box>
diff --git a/frontend/src/metabase/metrics/pages/MetricOverviewPage/MetricOverviewPage.tsx b/frontend/src/metabase/metrics/pages/MetricOverviewPage/MetricOverviewPage.tsx
index 5cd11cdf88a..6dca5056e6e 100644
--- a/frontend/src/metabase/metrics/pages/MetricOverviewPage/MetricOverviewPage.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricOverviewPage/MetricOverviewPage.tsx
@@ -57,8 +57,8 @@ function MetricOverviewPageBody({
const { data: metric, isLoading: isMetricLoading } = useGetMetricQuery(
card.id,
);
- const hasDimensions =
- metric?.dimensions != null && metric.dimensions.length > 0;
+ const dimensions = metric?.dimensions ?? [];
+ const hasDimensions = dimensions.length > 0;
useEffect(() => {
if (!isMetricLoading && !hasDimensions) {
@@ -87,7 +87,7 @@ function MetricOverviewPageBody({
showAppSwitcher={showAppSwitcher}
showDataStudioLink={showDataStudioLink}
/>
- <MetricDimensionGrid metricId={card.id} />
+ <MetricDimensionGrid metricId={card.id} dimensions={dimensions} />
</PageContainer>
);
}
diff --git a/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx b/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
index c38a7e7f6c4..46fd6d8db4a 100644
--- a/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
+++ b/frontend/src/metabase/metrics/pages/MetricQueryPage/MetricQueryPage.tsx
@@ -148,7 +148,7 @@ function MetricQueryPageBody({
/>
}
/>
- <Card withBorder flex={1} p={0}>
+ <Card withBorder shadow="none" flex={1} p={0}>
<MetricQueryEditor
query={question.query()}
uiState={uiState}
diff --git a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
index ca6db630242..daaacce287a 100644
--- a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
+++ b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
@@ -27,7 +27,7 @@ import { metricUrls as defaultUrls } from "../../urls";
import { getValidationResult } from "../../utils/validation";
import { CreateMetricModal } from "./CreateMetricModal";
-import { getInitialQuery, getQuery } from "./utils";
+import { ensureDefaultDimension, getInitialQuery, getQuery } from "./utils";
interface NewMetricPageProps {
urls?: MetricUrls;
@@ -86,7 +86,10 @@ export function NewMetricPage({
};
const handleChangeQuery = (query: Lib.Query) => {
- setDatasetQuery(Lib.toJsQuery(query));
+ const nextQuery = getValidationResult(query).isValid
+ ? ensureDefaultDimension(query)
+ : query;
+ setDatasetQuery(Lib.toJsQuery(nextQuery));
};
const handleCancel = () => {
@@ -131,7 +134,7 @@ export function NewMetricPage({
)
}
/>
- <Card withBorder p={0} flex={1}>
+ <Card withBorder shadow="none" p={0} flex={1}>
<MetricQueryEditor
query={query}
uiState={uiState}
diff --git a/frontend/src/metabase/metrics/pages/NewMetricPage/utils.ts b/frontend/src/metabase/metrics/pages/NewMetricPage/utils.ts
index 3ddb2db5489..d64cae22443 100644
--- a/frontend/src/metabase/metrics/pages/NewMetricPage/utils.ts
+++ b/frontend/src/metabase/metrics/pages/NewMetricPage/utils.ts
@@ -1,3 +1,5 @@
+import * as Lib from "metabase-lib";
+import * as LibMetric from "metabase-lib/metric";
import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type { DatasetQuery } from "metabase-types/api";
@@ -12,3 +14,14 @@ export function getInitialQuery(metadata: Metadata) {
metadata,
}).query();
}
+
+export function ensureDefaultDimension(query: Lib.Query): Lib.Query {
+ if (Lib.breakouts(query, -1).length > 0) {
+ return query;
+ }
+
+ const dimension = LibMetric.pickDefaultDimension(
+ Lib.breakoutableColumns(query, -1),
+ );
+ return dimension ? Lib.breakout(query, -1, dimension) : query;
+}
diff --git a/frontend/src/metabase/metrics/pages/NewMetricPage/utils.unit.spec.ts b/frontend/src/metabase/metrics/pages/NewMetricPage/utils.unit.spec.ts
new file mode 100644
index 00000000000..91188c29c0f
--- /dev/null
+++ b/frontend/src/metabase/metrics/pages/NewMetricPage/utils.unit.spec.ts
@@ -0,0 +1,44 @@
+import * as Lib from "metabase-lib";
+import { DEFAULT_TEST_QUERY, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
+
+import { ensureDefaultDimension } from "./utils";
+
+describe("ensureDefaultDimension", () => {
+ it("adds the preferred time breakout to a new metric query (UXW-4788)", () => {
+ const query = Lib.aggregateByCount(
+ Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),
+ 0,
+ );
+
+ const nextQuery = ensureDefaultDimension(query);
+ const [breakout] = Lib.breakouts(nextQuery, 0);
+ const column = Lib.breakoutColumn(nextQuery, 0, breakout);
+
+ expect(column).not.toBeNull();
+ if (!column) {
+ return;
+ }
+ expect(Lib.displayInfo(nextQuery, 0, column).displayName).toBe(
+ "Created At",
+ );
+ expect(Lib.defaultDisplay(nextQuery).display).toBe("line");
+ });
+
+ it("preserves an explicitly selected breakout", () => {
+ const query = Lib.aggregateByCount(
+ Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),
+ 0,
+ );
+ const total = Lib.breakoutableColumns(query, 0).find(
+ (column) => Lib.displayInfo(query, 0, column).displayName === "Total",
+ );
+
+ expect(total).toBeDefined();
+ if (!total) {
+ return;
+ }
+ const queryWithBreakout = Lib.breakout(query, 0, total);
+
+ expect(ensureDefaultDimension(queryWithBreakout)).toBe(queryWithBreakout);
+ });
+});
diff --git a/frontend/src/metabase/metrics/routes.tsx b/frontend/src/metabase/metrics/routes.tsx
index 0ee2a30c954..784049ed164 100644
--- a/frontend/src/metabase/metrics/routes.tsx
+++ b/frontend/src/metabase/metrics/routes.tsx
@@ -3,6 +3,7 @@ import { Route } from "metabase/router";
import { MetricAboutPage } from "./pages/MetricAboutPage";
import { MetricDependenciesPage } from "./pages/MetricDependenciesPage";
+import { MetricDimensionsPage } from "./pages/MetricDimensionsPage";
import { MetricHistoryPage } from "./pages/MetricHistoryPage";
import { MetricOverviewPage } from "./pages/MetricOverviewPage";
import { MetricQueryPage } from "./pages/MetricQueryPage";
@@ -15,6 +16,7 @@ export function getMetricRoutes() {
<Route path=":cardId" element={<MetricAboutPage />} />
<Route path=":cardId/overview" element={<MetricOverviewPage />} />
<Route path=":cardId/query" element={<MetricQueryPage />} />
+ <Route path=":cardId/dimensions" element={<MetricDimensionsPage />} />
{PLUGIN_DEPENDENCIES.isEnabled && (
<Route path=":cardId/dependencies" element={<MetricDependenciesPage />}>
<Route index element={<PLUGIN_DEPENDENCIES.DependencyGraphPage />} />
diff --git a/frontend/src/metabase/metrics/urls.ts b/frontend/src/metabase/metrics/urls.ts
index 3d80b366472..ed9b6400cc3 100644
--- a/frontend/src/metabase/metrics/urls.ts
+++ b/frontend/src/metabase/metrics/urls.ts
@@ -6,6 +6,7 @@ export const metricUrls: MetricUrls = {
about: Urls.metricAbout,
overview: Urls.metricOverview,
query: Urls.metricQuery,
+ dimensions: Urls.metricDimensions,
dependencies: Urls.metricDependencies,
history: Urls.metricHistory,
database: (id) => Urls.browseDatabase({ id }),
diff --git a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.tsx b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.tsx
index e4245c86106..7a07c809493 100644
--- a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.tsx
+++ b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.tsx
@@ -29,9 +29,7 @@ export function BreakoutStep({
);
const metricColumns = useMemo(() => {
- return isMetric
- ? Lib.breakoutableColumns(query, stageIndex).filter(Lib.isDateOrDateTime)
- : [];
+ return isMetric ? Lib.breakoutableColumns(query, stageIndex) : [];
}, [query, stageIndex, isMetric]);
const hasAddButton = !readOnly && (!isMetric || breakouts.length === 0);
@@ -80,7 +78,7 @@ export function BreakoutStep({
items={breakouts}
initialAddText={
isAddButtonDisabled
- ? t`No datetime columns available`
+ ? t`No columns available`
: t`Pick a column to group by`
}
readOnly={readOnly}
@@ -96,7 +94,6 @@ export function BreakoutStep({
stageIndex={stageIndex}
breakout={breakout}
breakoutIndex={index}
- isMetric={isMetric}
onAddBreakout={handleAddBreakout}
onUpdateBreakoutColumn={handleUpdateBreakoutColumn}
onClose={onClose}
@@ -116,7 +113,6 @@ interface BreakoutPopoverProps {
stageIndex: number;
breakout: Lib.BreakoutClause | undefined;
breakoutIndex: number | undefined;
- isMetric: boolean;
onAddBreakout: (column: Lib.ColumnMetadata) => void;
onUpdateBreakoutColumn: (
breakout: Lib.BreakoutClause,
@@ -131,7 +127,6 @@ export const BreakoutPopover = ({
stageIndex,
breakout,
breakoutIndex,
- isMetric,
onAddBreakout,
onUpdateBreakoutColumn,
onClose,
@@ -141,9 +136,7 @@ export const BreakoutPopover = ({
const filteredColumns = columns.reduce(
(columns: Lib.ColumnMetadata[], column) => {
const columnInfo = Lib.displayInfo(query, stageIndex, column);
- if (isMetric && !Lib.isDateOrDateTime(column)) {
- return columns;
- } else if (breakout && checkColumnSelected(columnInfo, breakoutIndex)) {
+ if (breakout && checkColumnSelected(columnInfo, breakoutIndex)) {
const column = Lib.breakoutColumn(query, stageIndex, breakout);
if (column != null) {
columns.push(column);
@@ -156,7 +149,7 @@ export const BreakoutPopover = ({
[],
);
return Lib.groupColumns(filteredColumns);
- }, [query, stageIndex, breakout, breakoutIndex, isMetric]);
+ }, [query, stageIndex, breakout, breakoutIndex]);
return (
<QueryColumnPicker
diff --git a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx
index 4e50f026a1f..b2107f6d279 100644
--- a/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/BreakoutStep/BreakoutStep.unit.spec.tsx
@@ -13,9 +13,13 @@ import * as Lib from "metabase-lib";
import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
import Question from "metabase-lib/v1/Question";
import type { TemporalUnit } from "metabase-types/api";
-import { createMockCard } from "metabase-types/api/mocks";
+import {
+ createMockCard,
+ createMockStructuredDatasetQuery,
+} from "metabase-types/api/mocks";
import {
ORDERS_ID,
+ SAMPLE_DB_ID,
createOrdersIdField,
createOrdersTable,
createSampleDatabase,
@@ -532,7 +536,7 @@ describe("BreakoutStep", () => {
});
describe("metrics", () => {
- it("should allow to select date and datetime columns only", async () => {
+ it("should allow selecting breakoutable columns", async () => {
const question = DEFAULT_QUESTION.setType("metric");
const step = createMockNotebookStep({ question });
const { getNextBreakouts } = setup({ step });
@@ -540,12 +544,12 @@ describe("BreakoutStep", () => {
await userEvent.click(screen.getByText("Pick a column to group by"));
expect(await screen.findByText("Orders")).toBeInTheDocument();
expect(await screen.findByText("Created At")).toBeInTheDocument();
- expect(screen.queryByText("Tax")).not.toBeInTheDocument();
+ expect(await screen.findByText("Tax")).toBeInTheDocument();
await userEvent.click(screen.getByText("User"));
expect(await screen.findByText("Created At")).toBeInTheDocument();
expect(await screen.findByText("Birth Date")).toBeInTheDocument();
- expect(screen.queryByText("Email")).not.toBeInTheDocument();
+ expect(await screen.findByText("Email")).toBeInTheDocument();
await userEvent.click(await screen.findByText("Created At"));
expect(getNextBreakouts()).toMatchObject([
@@ -562,11 +566,11 @@ describe("BreakoutStep", () => {
screen.queryByText("Pick a column to group by"),
).not.toBeInTheDocument();
expect(
- screen.queryByText("No datetime columns available"),
+ screen.queryByText("No columns available"),
).not.toBeInTheDocument();
});
- it("should not allow to select when there are no date or datetime columns", () => {
+ it("should allow selecting a numeric column when there are no temporal columns", async () => {
const metadata = createMockMetadata({
databases: [
createSampleDatabase({
@@ -575,21 +579,25 @@ describe("BreakoutStep", () => {
],
});
const question = new Question(
- createMockCard({ type: "metric" }),
+ createMockCard({
+ type: "metric",
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DB_ID,
+ query: { "source-table": ORDERS_ID },
+ }),
+ }),
metadata,
);
const step = createMockNotebookStep({
question,
query: question.query(),
});
- setup({ step });
+ const { getNextBreakouts } = setup({ step });
- expect(
- screen.getByText("No datetime columns available"),
- ).toBeInTheDocument();
- expect(
- screen.queryByText("Pick a column to group by"),
- ).not.toBeInTheDocument();
+ await userEvent.click(screen.getByText("Pick a column to group by"));
+ await userEvent.click(await screen.findByText("ID"));
+
+ expect(getNextBreakouts()).toMatchObject([{ displayName: "ID" }]);
});
it("should not allow to add more than 1 breakout", async () => {
diff --git a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
index 376b65c7dee..d527cda1a7a 100644
--- a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
@@ -218,8 +218,8 @@ describe("Notebook", () => {
const step = screen.getByTestId("step-summarize-0-0");
expect(within(step).getByText("Formula")).toBeInTheDocument();
expect(
- within(step).getAllByText("Default time dimension").length,
- ).toBeGreaterThanOrEqual(1);
+ within(step).queryByText("Default time dimension"),
+ ).not.toBeInTheDocument();
expect(within(step).queryByText("Summarize")).not.toBeInTheDocument();
expect(within(step).queryByText("by")).not.toBeInTheDocument();
expect(
diff --git a/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStep.tsx b/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStep.tsx
index 87883f869e4..a40e93edb2c 100644
--- a/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStep.tsx
+++ b/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStep.tsx
@@ -17,7 +17,7 @@ export function SummarizeStep({
const isMetric = step.question.type() === "metric";
const hasBreakouts = Lib.breakouts(step.query, step.stageIndex).length > 0;
- const showBreakouts = !readOnly || hasBreakouts;
+ const showBreakouts = !isMetric && (!readOnly || hasBreakouts);
return (
<Flex
@@ -25,7 +25,7 @@ export function SummarizeStep({
direction={{ base: "column", md: "row" }}
gap={{ base: "sm", md: isMetric ? "md" : "sm" }}
>
- <Box w={{ base: "100%", md: "50%" }} flex="1 1 auto">
+ <Box w={{ base: "100%", md: isMetric ? "100%" : "50%" }} flex="1 1 auto">
<AggregateStep
step={step}
color={color}
@@ -34,13 +34,7 @@ export function SummarizeStep({
{...props}
/>
</Box>
- {isMetric ? (
- <Box display={{ md: "none" }} c={color} fw="bold">
- {t`Default time dimension`}
- </Box>
- ) : (
- showBreakouts && <Box c={color} fw="bold">{t`by`}</Box>
- )}
+ {showBreakouts && <Box c={color} fw="bold">{t`by`}</Box>}
{showBreakouts && (
<Box w={{ base: "100%", md: "50%" }}>
<BreakoutStep
diff --git a/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStepHeader/SummarizeStepHeader.tsx b/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStepHeader/SummarizeStepHeader.tsx
index e450640e8da..6483841e0a6 100644
--- a/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStepHeader/SummarizeStepHeader.tsx
+++ b/frontend/src/metabase/querying/notebook/components/SummarizeStep/SummarizeStepHeader/SummarizeStepHeader.tsx
@@ -1,6 +1,6 @@
import { t } from "ttag";
-import { Box, Flex } from "metabase/ui";
+import { Box } from "metabase/ui";
import type { NotebookStepHeaderProps } from "../../../types";
import { NotebookStepHeader } from "../../NotebookStep/NotebookStepHeader";
@@ -26,11 +26,8 @@ export function SummarizeStepHeader({
}
return (
- <Flex c={color} fw="bold" mb="sm" gap="md">
- <Box w="50%">{t`Formula`}</Box>
- <Box display={{ base: "none", md: "block" }} w="50%">
- {t`Default time dimension`}
- </Box>
- </Flex>
+ <Box c={color} fw="bold" mb="sm">
+ {t`Formula`}
+ </Box>
);
}
diff --git a/frontend/src/metabase/urls/data-studio.ts b/frontend/src/metabase/urls/data-studio.ts
index 5adbcfe6358..dfdedead635 100644
--- a/frontend/src/metabase/urls/data-studio.ts
+++ b/frontend/src/metabase/urls/data-studio.ts
@@ -264,6 +264,10 @@ export function dataStudioMetricQuery(cardId: CardId) {
return `${dataStudioMetric(cardId)}/query`;
}
+export function dataStudioMetricDimensions(cardId: CardId) {
+ return `${dataStudioMetric(cardId)}/dimensions`;
+}
+
export function dataStudioMetricDependencies(cardId: CardId) {
return `${dataStudioMetric(cardId)}/dependencies`;
}
diff --git a/frontend/src/metabase/urls/metrics.ts b/frontend/src/metabase/urls/metrics.ts
index 22dd4d0632b..a93cd736b44 100644
--- a/frontend/src/metabase/urls/metrics.ts
+++ b/frontend/src/metabase/urls/metrics.ts
@@ -71,6 +71,10 @@ export function metricQuery(cardId: CardId): string {
return `/metric/${cardId}/query`;
}
+export function metricDimensions(cardId: CardId): string {
+ return `/metric/${cardId}/dimensions`;
+}
+
export function metricDependencies(cardId: CardId): string {
return `/metric/${cardId}/dependencies`;
}
diff --git a/frontend/test/__support__/server-mocks/metric.ts b/frontend/test/__support__/server-mocks/metric.ts
index 23e395b1bae..fb420a5123c 100644
--- a/frontend/test/__support__/server-mocks/metric.ts
+++ b/frontend/test/__support__/server-mocks/metric.ts
@@ -1,6 +1,11 @@
import fetchMock from "fetch-mock";
-import type { Metric } from "metabase-types/api";
+import type {
+ Dataset,
+ ListMetricDimensionsResponse,
+ Metric,
+ MetricId,
+} from "metabase-types/api";
export function setupMetricEndpoint(metric: Metric) {
fetchMock.get(`path:/api/metric/${metric.id}`, metric);
@@ -10,3 +15,94 @@ export function setupMetricsEndpoints(metrics: Metric[]) {
fetchMock.get("path:/api/metric", metrics);
metrics.forEach((metric) => setupMetricEndpoint(metric));
}
+
+export function setupMetricDatasetEndpoint(dataset: Dataset) {
+ fetchMock.post("path:/api/metric/dataset", dataset, {
+ name: "metric-dataset",
+ });
+}
+
+export function setupMetricDimensionsEndpoints(
+ metricId: MetricId,
+ response: ListMetricDimensionsResponse,
+) {
+ // Mutations update this so subsequent GETs reflect persisted dimensions.
+ let added = [...response.added];
+
+ fetchMock.get(
+ `path:/api/metric/${metricId}/dimension`,
+ (call) => {
+ const searchParams = new URL(call.url).searchParams;
+ const query = searchParams.get("query")?.toLowerCase();
+ const includeOrphaned = searchParams.get("include-orphaned") === "true";
+ const visibleAdded = includeOrphaned
+ ? added
+ : added.filter(({ status }) => status !== "status/orphaned");
+ const filteredAdded = query
+ ? visibleAdded.filter((dimension) =>
+ dimension.display_name.toLowerCase().includes(query),
+ )
+ : visibleAdded;
+ const addable =
+ searchParams.get("with-addable") === "true"
+ ? response.addable
+ .map(({ group, dimensions }) => ({
+ group,
+ dimensions: query
+ ? dimensions.filter((dimension) =>
+ dimension.display_name.toLowerCase().includes(query),
+ )
+ : dimensions,
+ }))
+ .filter(({ dimensions }) => dimensions.length > 0)
+ : [];
+ return { added: filteredAdded, addable };
+ },
+ { name: `metric-${metricId}-dimensions-list` },
+ );
+ fetchMock.post(`path:/api/metric/${metricId}/dimension/add`, response.added, {
+ name: `metric-${metricId}-dimensions-add`,
+ });
+ fetchMock.post(
+ `path:/api/metric/${metricId}/dimension/remove`,
+ async (call) => {
+ const body: { dimension_ids?: string[] } = JSON.parse(
+ (await call.request?.text()) ?? "{}",
+ );
+ const removedIds = new Set(body.dimension_ids ?? []);
+ added = added.filter((dimension) => !removedIds.has(dimension.id));
+ return added;
+ },
+ { name: `metric-${metricId}-dimensions-remove` },
+ );
+ fetchMock.post(
+ `path:/api/metric/${metricId}/dimension/reorder`,
+ async (call) => {
+ const body = JSON.parse((await call.request?.text()) ?? "{}");
+ const position = new Map<string, number>(
+ (body.dimension_ids ?? []).map((id: string, index: number) => [
+ id,
+ index,
+ ]),
+ );
+ added = [...added].sort(
+ (a, b) =>
+ (position.get(a.id) ?? Infinity) - (position.get(b.id) ?? Infinity),
+ );
+ return added;
+ },
+ { name: `metric-${metricId}-dimensions-reorder` },
+ );
+ fetchMock.post(
+ `path:/api/metric/${metricId}/dimension/set-default`,
+ response.added,
+ { name: `metric-${metricId}-dimensions-set-default` },
+ );
+ response.added.forEach((dimension) => {
+ fetchMock.post(
+ `path:/api/metric/${metricId}/dimension/${encodeURIComponent(dimension.id)}`,
+ dimension,
+ { name: `metric-${metricId}-dimension-${dimension.id}-update` },
+ );
+ });
+}
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 5f1726f9fbb..dbaa503f064 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -1,5 +1,11 @@
import { Global } from "@emotion/react";
-import type { Middleware, Reducer, Store } from "@reduxjs/toolkit";
+import type {
+ AnyAction,
+ Middleware,
+ Reducer,
+ Store,
+ ThunkDispatch,
+} from "@reduxjs/toolkit";
import type { MatcherFunction } from "@testing-library/dom";
import type { ByRoleMatcher, RenderHookOptions } from "@testing-library/react";
import {
@@ -229,7 +235,9 @@ export function getTestStoreAndWrapper({
initialState,
// Unjustified type cast. FIXME
storeMiddleware as Middleware[],
- ) as unknown as Store<State>;
+ ) as unknown as Store<State> & {
+ dispatch: ThunkDispatch<State, void, AnyAction>;
+ };
const wrapper = (props: any) => {
return (
diff --git a/src/metabase/lib/query.cljc b/src/metabase/lib/query.cljc
index 75590878365..e6e92ec028f 100644
--- a/src/metabase/lib/query.cljc
+++ b/src/metabase/lib/query.cljc
@@ -20,8 +20,6 @@
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.schema.template-tag :as lib.schema.template-tag]
- [metabase.lib.temporal-bucket :as lib.temporal-bucket]
- [metabase.lib.types.isa :as lib.types.isa]
[metabase.lib.util :as lib.util]
[metabase.util :as u]
[metabase.util.i18n :as i18n]
@@ -80,13 +78,7 @@
breakouts (:breakout stage)]
(and (= (stage-count query) 1)
(= (count aggregations) 1)
- (or (empty? breakouts)
- (and (= (count breakouts) 1)
- (-> (lib.metadata.calculation/metadata query (first breakouts))
- ;; extraction units change `:effective-type` to `:type/Integer`, so remove temporal bucketing
- ;; before doing type checks
- (lib.temporal-bucket/with-temporal-bucket nil)
- lib.types.isa/date-or-datetime?)))))))
+ (<= (count breakouts) 1)))))
(mu/defn can-run :- :boolean
"Returns whether the query is runnable. Manually validate schema for cljs."
diff --git a/src/metabase/lib/schema/middleware_options.cljc b/src/metabase/lib/schema/middleware_options.cljc
index f236e92c4a1..aa6cc2b16c6 100644
--- a/src/metabase/lib/schema/middleware_options.cljc
+++ b/src/metabase/lib/schema/middleware_options.cljc
@@ -14,6 +14,13 @@
`metabase.query-processor.middleware.results-metadata`; default `false`. (Note: we may change the name of this
column in the near future, to `result_metadata`, to fix inconsistencies in how we name things.)"}
:boolean]
+ [:skip-result-metadata-persistence?
+ {:optional true
+ :description
+ "Should we skip persisting `result_metadata` to a saved Card while still returning it in query results? Used by
+ `metabase.query-processor.middleware.results-metadata`; default `false`. Has no effect when
+ `skip-results-metadata?` is true."}
+ :boolean]
[:format-rows?
{:optional true
:description
diff --git a/src/metabase/lib_metric/core.cljc b/src/metabase/lib_metric/core.cljc
index 2b6a02f8222..b7d401bcc46 100644
--- a/src/metabase/lib_metric/core.cljc
+++ b/src/metabase/lib_metric/core.cljc
@@ -56,17 +56,28 @@
unprojected-sources
->query-plan]
[lib-metric.dimension
+ add-dimensions
+ addable-pairs
dimension
+ dimension-target->field-id
dimensionable-query
dimensions-changed?
dimensions-for-measure
dimensions-for-metric
dimensions-for-table
extract-persisted-dimensions
+ field-ref->key
get-persisted-dimension-mappings
get-persisted-dimensions
+ main-group?
mappings-changed?
+ pick-default-dimension
reconcile-dimensions-and-mappings
+ reconcile-existing-dimensions
+ remove-dimensions
+ reorder-dimensions
+ set-default-dimension
+ update-dimension
resolve-dimension-to-field-id]
[lib-metric.dimension.jvm
compute-dimension-pairs]
@@ -78,6 +89,8 @@
[lib-metric.projection
add-projection-positions
default-breakout-dimensions
+ dimension-breakout
+ project-dimension
projectable-dimensions])
:cljs
(do
@@ -95,16 +108,21 @@
(def source-measure-id "See [[lib-metric.definition/source-measure-id]]." lib-metric.definition/source-measure-id)
(def source-metric-id "See [[lib-metric.definition/source-metric-id]]." lib-metric.definition/source-metric-id)
(def dimension "See [[lib-metric.dimension/dimension]]." lib-metric.dimension/dimension)
+ (def dimension-target->field-id "See [[lib-metric.dimension/dimension-target->field-id]]." lib-metric.dimension/dimension-target->field-id)
(def dimensionable-query "See [[lib-metric.dimension/dimensionable-query]]." lib-metric.dimension/dimensionable-query)
(def dimensions-for-measure "See [[lib-metric.dimension/dimensions-for-measure]]." lib-metric.dimension/dimensions-for-measure)
(def dimensions-for-metric "See [[lib-metric.dimension/dimensions-for-metric]]." lib-metric.dimension/dimensions-for-metric)
(def dimensions-for-table "See [[lib-metric.dimension/dimensions-for-table]]." lib-metric.dimension/dimensions-for-table)
(def get-persisted-dimensions "See [[lib-metric.dimension/get-persisted-dimensions]]." lib-metric.dimension/get-persisted-dimensions)
(def get-persisted-dimension-mappings "See [[lib-metric.dimension/get-persisted-dimension-mappings]]." lib-metric.dimension/get-persisted-dimension-mappings)
+ (def pick-default-dimension "See [[lib-metric.dimension/pick-default-dimension]]." lib-metric.dimension/pick-default-dimension)
(def resolve-dimension-to-field-id "See [[lib-metric.dimension/resolve-dimension-to-field-id]]." lib-metric.dimension/resolve-dimension-to-field-id)
+ (def field-ref->key "See [[lib-metric.dimension/field-ref->key]]." lib-metric.dimension/field-ref->key)
(def database-provider-for-table "See [[lib-metric.metadata.provider/database-provider-for-table]]." lib-metric.metadata.provider/database-provider-for-table)
(def metric-context-metadata-provider "See [[lib-metric.metadata.provider/metric-context-metadata-provider]]." lib-metric.metadata.provider/metric-context-metadata-provider)
(def metadata-provider "See [[lib-metric.metadata.js/metadata-provider]]." lib-metric.metadata.js/metadata-provider)
(def add-projection-positions "See [[lib-metric.projection/add-projection-positions]]." lib-metric.projection/add-projection-positions)
(def default-breakout-dimensions "See [[lib-metric.projection/default-breakout-dimensions]]." lib-metric.projection/default-breakout-dimensions)
+ (def dimension-breakout "See [[lib-metric.projection/dimension-breakout]]." lib-metric.projection/dimension-breakout)
+ (def project-dimension "See [[lib-metric.projection/project-dimension]]." lib-metric.projection/project-dimension)
(def projectable-dimensions "See [[lib-metric.projection/projectable-dimensions]]." lib-metric.projection/projectable-dimensions)))
diff --git a/src/metabase/lib_metric/dimension.cljc b/src/metabase/lib_metric/dimension.cljc
index 82cc939c85e..f7a61a7c655 100644
--- a/src/metabase/lib_metric/dimension.cljc
+++ b/src/metabase/lib_metric/dimension.cljc
@@ -5,17 +5,27 @@
(:require
[medley.core :as m]
[metabase.lib-metric.schema :as lib-metric.schema]
+ [metabase.lib-metric.types.isa :as types.isa]
[metabase.lib.core :as lib]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.util :as u]
[metabase.util.i18n :as i18n]
[metabase.util.malli :as mu]
[metabase.util.performance :as perf]))
;;; ------------------------------------------------- Target Comparison -------------------------------------------------
-(defn- normalize-target
- "Normalize a target ref for comparison by removing transient options."
+(defn field-ref->key
+ "Canonical, collision-safe map key for an MBQL field (or expression) ref.
+
+ A column's Field ID is **not** unique within a query: a table can have multiple FKs to the same
+ foreign table, so the same field id is reachable via different `:source-field` paths. Keying maps
+ by field id alone therefore collides — always key by this instead.
+
+ It drops only per-instance/derived opts (`:lib/uuid`, `:effective-type`, `:base-type`) and KEEPS
+ everything identity-relevant: the id, the `:source-field`/`:join-alias` that identifies the FK or
+ join, and any `:binning`/`:temporal-unit`."
[[clause-type opts id-or-name]]
[clause-type
(dissoc opts :lib/uuid :effective-type :base-type)
@@ -24,7 +34,7 @@
(defn targets-equal?
"Compare two target refs for equality, ignoring transient options like :lib/uuid."
[target-a target-b]
- (= (normalize-target target-a) (normalize-target target-b)))
+ (= (field-ref->key target-a) (field-ref->key target-b)))
(defn- random-uuid-str []
(str (random-uuid)))
@@ -93,10 +103,10 @@
(defn- find-orphaned-dimensions
"Find persisted dimensions whose targets no longer exist in computed pairs."
[computed-pairs persisted-dims persisted-mappings]
- (let [computed-targets (set (map (comp normalize-target :target :mapping) computed-pairs))
+ (let [computed-targets (set (map (comp field-ref->key :target :mapping) computed-pairs))
persisted-dims-by-id (m/index-by :id persisted-dims)]
(->> persisted-mappings
- (remove #(contains? computed-targets (normalize-target (:target %))))
+ (remove #(contains? computed-targets (field-ref->key (:target %))))
(keep (fn [orphan-mapping]
(when-let [dim (get persisted-dims-by-id (:dimension-id orphan-mapping))]
(-> dim
@@ -122,27 +132,171 @@
{:dimensions (into active-dims orphaned-dims)
:dimension-mappings active-mappings}))
+(mu/defn reconcile-existing-dimensions :- [:map
+ [:dimensions [:sequential ::lib-metric.schema/persisted-dimension]]
+ [:dimension-mappings [:sequential ::lib-metric.schema/dimension-mapping]]]
+ "Refresh the status of an already-curated dimension set against the currently computed columns,
+ WITHOUT adding new dimensions or overwriting user edits.
+
+ Any persisted dimensions and mappings are authoritative: each persisted dimension is kept as-is, except its
+ `:status` is set to `:status/orphaned` (with a message) when its mapped target no longer appears among the computed
+ columns, and back to `:status/active` if it reappears. Newly added columns are ignored, and mappings are returned
+ unchanged. Contrast with [[reconcile-dimensions-and-mappings]], which seeds a dimension set from
+ the computed columns."
+ [computed-pairs :- [:sequential ::lib-metric.schema/computed-pair]
+ persisted-dims :- [:sequential ::lib-metric.schema/persisted-dimension]
+ persisted-mappings :- [:maybe [:sequential ::lib-metric.schema/dimension-mapping]]]
+ (let [computed-targets (into #{} (map (comp field-ref->key :target :mapping))
+ computed-pairs)
+ target-by-dim-id (into {} (map (juxt :dimension-id :target))
+ (or persisted-mappings []))
+ active? #(some->> (:id %)
+ (get target-by-dim-id)
+ field-ref->key
+ (contains? computed-targets))]
+ {:dimensions (perf/mapv (fn [dim]
+ (if (active? dim)
+ (-> dim
+ (assoc :status :status/active)
+ (dissoc :status-message))
+ (-> dim
+ (assoc :status :status/orphaned)
+ (assoc :status-message (orphaned-status-message dim)))))
+ persisted-dims)
+ :dimension-mappings (vec persisted-mappings)}))
+
(mu/defn extract-persisted-dimensions :- [:sequential ::lib-metric.schema/persisted-dimension]
"Extract dimensions that should be persisted to the database.
A dimension should be persisted if it has a status (either active or orphaned)."
[dimensions :- [:sequential ::lib-metric.schema/persisted-dimension]]
(filterv :status dimensions))
+;;; ---------------------------------------------- Dimension CRUD (pure) ----------------------------------------------
+;;; Pure transforms over the persisted dimension/mapping vectors. They never recompute from columns;
+;;; computed pairs are passed in where needed.
+
+(defn main-group?
+ "True when a computed dimension pair belongs to the entity's own (\"main\") table, as opposed to a
+ joined/FK-reachable table."
+ [pair]
+ (= "main" (perf/get-in pair [:dimension :group :type])))
+
+(defn pick-default-dimension
+ "Pick the preferred default from an ordered collection of dimensions."
+ [dimensions]
+ (let [dimensions (vec dimensions)]
+ (or (u/seek types.isa/date-or-datetime? dimensions)
+ (u/seek #(or (types.isa/country? %) (types.isa/state? %)) dimensions)
+ (u/seek #(or (= :list (:has-field-values %))
+ (types.isa/category? %))
+ dimensions)
+ (first dimensions))))
+
+(defn addable-pairs
+ "Computed dimension pairs whose target is not already mapped by one of `persisted-mappings` — i.e. the columns
+ available to add to the curated set."
+ [computed-pairs persisted-mappings]
+ (let [mapped-target? (into #{} (map (comp field-ref->key :target)) persisted-mappings)]
+ (into []
+ (remove #(-> % :mapping :target field-ref->key mapped-target?))
+ computed-pairs)))
+
+(defn add-dimensions
+ "Append `pairs` (each `{:dimension ... :mapping ...}`, with `:id`/`:dimension-id` already assigned)
+ to the persisted set, marking each added dimension `:status/active`. Pairs whose dimension `:id`
+ is already present are skipped, so adding is idempotent. Returns
+ `{:dimensions ... :dimension-mappings ...}`."
+ [persisted-dims persisted-mappings pairs]
+ (let [existing-ids (into #{} (map :id) persisted-dims)
+ new-pairs (remove #(contains? existing-ids (-> % :dimension :id)) pairs)]
+ {:dimensions (into (vec persisted-dims)
+ (comp (map :dimension)
+ (map #(assoc % :status :status/active)))
+ new-pairs)
+ :dimension-mappings (into (vec persisted-mappings) (map :mapping) new-pairs)}))
+
+(defn remove-dimensions
+ "Drop the dimensions (and their mappings) whose id is in `ids` from the persisted set.
+ Returns `{:dimensions ... :dimension-mappings ...}`."
+ [persisted-dims persisted-mappings ids]
+ (let [ids (set ids)]
+ {:dimensions (into [] (remove (comp ids :id)) persisted-dims)
+ :dimension-mappings (into [] (remove (comp ids :dimension-id)) persisted-mappings)}))
+
+(defn- update-dimension*
+ "Applies the `updates` to the dimension. See [[update-dimension]] for the details."
+ [dim {:keys [display-name source-pair] :as updates}]
+ (cond-> dim
+ (some? display-name) (assoc :display-name display-name)
+ (contains? updates :description) (assoc :description (:description updates))
+ source-pair (merge (perf/select-keys (:dimension source-pair)
+ [:name :sources :effective-type
+ :semantic-type :has-field-values :group]))))
+
+(defn- update-dimension-mapping
+ "Applies any repointing to a dimension's mapping."
+ [mapping {{:keys [table-id target]} :mapping :as _source-pair}]
+ (-> mapping
+ (assoc :target target)
+ (u/assoc-dissoc :table-id table-id)))
+
+(defn update-dimension
+ "Update a single persisted dimension by `id`. `updates` may contain:
+ - `:display-name` — set the display name
+ - `:description` — set the description (key present, even when nil, clears it)
+ - `:source-pair` — a computed `{:dimension ... :mapping ...}` for a new source column; copies the
+ column-derived fields onto the dimension and repoints its mapping target.
+ Returns `{:dimensions ... :dimension-mappings ...}`."
+ [persisted-dims persisted-mappings id {:keys [source-pair] :as updates}]
+ (let [dims-by-id (-> (m/index-by :id persisted-dims)
+ (update id update-dimension* updates))
+ mappings-by-dim-id (cond-> (m/index-by :dimension-id persisted-mappings)
+ source-pair (update id update-dimension-mapping source-pair))]
+ {:dimensions (perf/mapv (comp dims-by-id :id)
+ persisted-dims)
+ :dimension-mappings (perf/mapv (comp mappings-by-dim-id :dimension-id)
+ persisted-mappings)}))
+
+(defn set-default-dimension
+ "Mark the dimension with `id` as the sole default, clearing `:default` from every other dimension.
+ Assumes `id` exists in `persisted-dims`. Returns the updated dimensions vector."
+ [persisted-dims id]
+ (perf/mapv (fn [dim]
+ (if (= id (:id dim))
+ (assoc dim :default true)
+ (dissoc dim :default)))
+ persisted-dims))
+
+(defn reorder-dimensions
+ "Sort `persisted-dims` into the order given by `ids`. Dimensions not listed in `ids` keep their
+ relative order after the listed ones. Returns the reordered dimensions vector."
+ [persisted-dims ids]
+ (let [position (into {} (map-indexed (fn [i id] [id i])) ids)
+ missing (count ids)]
+ ;; sort-by is stable, so unlisted dimensions (all sharing the `missing` index) keep their order.
+ (vec (sort-by #(get position (:id %) missing) persisted-dims))))
+
+(def ^:private persisted-dimension-keys
+ [:id :name :display-name :semantic-type :effective-type :has-field-values :status :status-message :sources :group :default])
+
+(defn- dimensions-set [dims]
+ (into #{} (map #(perf/select-keys % persisted-dimension-keys)) dims))
+
(mu/defn dimensions-changed? :- :boolean
"Check if the persisted dimensions have changed between old and new sets."
[old-persisted :- [:maybe [:sequential ::lib-metric.schema/persisted-dimension]]
new-persisted :- [:sequential ::lib-metric.schema/persisted-dimension]]
- (let [persist-keys [:id :name :display-name :semantic-type :effective-type :has-field-values :status :status-message :sources :group]
- normalize (fn [dims] (set (map #(perf/select-keys % persist-keys) dims)))]
- (not= (normalize old-persisted) (normalize new-persisted))))
+ (not= (dimensions-set old-persisted) (dimensions-set new-persisted)))
+
+(defn- mappings-set [mappings]
+ (into #{} (map #(update % :target field-ref->key))
+ mappings))
(mu/defn mappings-changed? :- :boolean
"Check if the dimension mappings have changed between old and new sets."
[old-mappings :- [:maybe [:sequential ::lib-metric.schema/dimension-mapping]]
new-mappings :- [:sequential ::lib-metric.schema/dimension-mapping]]
- (let [normalize (fn [mappings]
- (set (map #(update % :target normalize-target) mappings)))]
- (not= (normalize old-mappings) (normalize new-mappings))))
+ (not= (mappings-set old-mappings) (mappings-set new-mappings)))
;;; ------------------------------------------------- Entity Accessors -------------------------------------------------
;;; These multimethods provide pure read access to dimensionable entities.
diff --git a/src/metabase/lib_metric/js.cljs b/src/metabase/lib_metric/js.cljs
index ca717290eae..ef2ede899e3 100644
--- a/src/metabase/lib_metric/js.cljs
+++ b/src/metabase/lib_metric/js.cljs
@@ -633,6 +633,11 @@
(to-array (lib-metric.projection/projectable-dimensions-for-source
definition (->source-instance source-instance)))))
+(defn ^:export pickDefaultDimension
+ "Pick the preferred default from an ordered array of dimensions."
+ [dimensions]
+ (lib-metric.dimension/pick-default-dimension (array-seq dimensions)))
+
(defn ^:export defaultBreakoutDimensions
"Get dimensions corresponding to the source metric's default breakout columns."
[definition]
@@ -656,6 +661,12 @@
([definition dimension-ref source-instance]
(lib-metric.projection/project-for-source definition dimension-ref (->source-instance source-instance))))
+(defn ^:export projectDimension
+ "Project a dimension using its default temporal bucket or binning strategy."
+ [definition dimension]
+ (assert-single-source! definition)
+ (lib-metric.projection/project-dimension definition dimension))
+
(defn ^:export projectionDimension
"Get the dimension metadata for a projection clause.
Returns the dimension or null if not found."
diff --git a/src/metabase/lib_metric/projection.cljc b/src/metabase/lib_metric/projection.cljc
index 26c876c6a2d..4df016057e1 100644
--- a/src/metabase/lib_metric/projection.cljc
+++ b/src/metabase/lib_metric/projection.cljc
@@ -180,11 +180,12 @@
units)))
(defn- mark-unit [options option-key unit]
- (perf/mapv (fn [option]
- (cond-> option
- (:default option) (dissoc :default)
- (= (:unit option) unit) (assoc option-key true)))
- options))
+ (cond->> options
+ (perf/some #(= (:unit %) unit) options)
+ (perf/mapv (fn [option]
+ (cond-> option
+ (contains? option option-key) (dissoc option-key)
+ (= (:unit option) unit) (assoc option-key true))))))
(defn- available-temporal-buckets-for-type
"Given a column type and nillable default-unit and selected-unit, return the appropriate bucket options."
@@ -212,7 +213,7 @@
(:temporal-unit (second proj))))
flat-projs)]
(if (isa? effective-type :type/Temporal)
- (available-temporal-buckets-for-type effective-type :month selected-unit)
+ (available-temporal-buckets-for-type effective-type nil selected-unit)
[])))
(mu/defn temporal-bucket :- [:maybe ::lib.schema.temporal-bucketing/option]
@@ -330,20 +331,51 @@
(assoc opts :binning binning-val)
(dissoc opts :binning))))))
-;;; -------------------------------------------------- Default Breakout Dimensions --------------------------------------------------
+(defn- dimension-reference-with-default-options
+ [definition dimension]
+ (let [dimension-ref (lib-metric.dimension/reference dimension)]
+ (if-let [bucket (perf/some #(when (:default %) %)
+ (available-temporal-buckets definition dimension))]
+ (with-temporal-bucket dimension-ref bucket)
+ (if-let [binning-option (perf/some #(when (:default %) %)
+ (available-binning-strategies definition dimension))]
+ (with-binning dimension-ref binning-option)
+ dimension-ref))))
+
+(mu/defn project-dimension :- ::lib-metric.schema/metric-definition
+ "Project a dimension using its default temporal bucket or binning strategy."
+ [definition :- ::lib-metric.schema/metric-definition
+ dimension :- ::lib-metric.schema/metadata-dimension]
+ (project definition (dimension-reference-with-default-options definition dimension)))
-(defn- dimension-has-field-id?
- "Check if a dimension has a source matching any of the given field IDs."
- [field-ids dimension]
- (perf/some (fn [source]
- (when-let [fid (:field-id source)]
- (field-ids fid)))
- (:sources dimension)))
+(defn dimension-breakout
+ "Return the dimension's mapped field reference with its default projection options, or nil when it has no mapping."
+ [definition dimension]
+ (when-let [target (perf/get-in dimension [:dimension-mapping :target])]
+ (let [dimension-ref (dimension-reference-with-default-options definition dimension)
+ options (perf/select-keys (second dimension-ref) [:temporal-unit :binning])]
+ (lib/update-options (lib/ensure-uuid target) #(merge % options)))))
-(mu/defn default-breakout-dimensions :- [:sequential ::lib-metric.schema/metadata-dimension]
- "Get dimensions corresponding to the source metric's default breakout columns.
- Returns DimensionMetadata objects matching the breakout field-ids in the dataset_query."
- [definition :- ::lib-metric.schema/metric-definition]
+;;; -------------------------------------------------- Default Breakout Dimensions --------------------------------------------------
+
+(defn- column-key
+ "Collision-safe key for the underlying column of a field ref, ignoring any bucketing. Unlike a bare
+ field id, this keeps the `:source-field`/`:join-alias` so columns reached via different FKs to the
+ same table don't collide. See [[lib-metric.dimension/field-ref->key]]."
+ [field-ref]
+ (-> field-ref
+ (update 1 dissoc :temporal-unit :binning)
+ lib-metric.dimension/field-ref->key))
+
+(defn- dimension-column-key
+ "Column key for a metadata dimension, derived from its mapping target (which carries the
+ `:source-field`). Returns nil when the dimension has no mapping."
+ [dimension]
+ (some-> dimension :dimension-mapping :target column-key))
+
+(defn- source-query-breakout-dimensions
+ "Dimensions matching the breakout columns of the source metric's own dataset_query."
+ [definition]
(let [{:keys [expression metadata-provider]} definition
leaf-type (lib-metric.definition/expression-leaf-type expression)
leaf-id (lib-metric.definition/expression-leaf-id expression)]
@@ -356,12 +388,23 @@
raw-query (lib-metric.dimension/dimensionable-query metadata)]
(if-not raw-query
[]
- (let [mbql5-query (lib/query metadata-provider raw-query)
- breakout-clauses (lib/breakouts mbql5-query)
- breakout-field-ids (into #{}
- (keep lib-metric.dimension/dimension-target->field-id)
- breakout-clauses)]
- (if (perf/empty? breakout-field-ids)
+ (let [mbql5-query (lib/query metadata-provider raw-query)
+ breakout-clauses (lib/breakouts mbql5-query)
+ ;; Key by the full column ref (incl. :source-field), not the bare field id, since a
+ ;; field id can be reached via multiple FKs to the same foreign table.
+ breakout-keys (into #{} (keep column-key) breakout-clauses)]
+ (if (perf/empty? breakout-keys)
[]
- (filterv #(dimension-has-field-id? breakout-field-ids %)
+ (filterv #(when-let [k (dimension-column-key %)]
+ (contains? breakout-keys k))
(projectable-dimensions definition)))))))))
+
+(mu/defn default-breakout-dimensions :- [:sequential ::lib-metric.schema/metadata-dimension]
+ "Get the dimensions to treat as the entity's defaults for breakouts: the curated default
+ dimension when one is set, otherwise dimensions matching the breakout columns in the source
+ metric's own dataset_query."
+ [definition :- ::lib-metric.schema/metric-definition]
+ (let [curated-defaults (filterv :default (projectable-dimensions definition))]
+ (if (seq curated-defaults)
+ curated-defaults
+ (source-query-breakout-dimensions definition))))
diff --git a/src/metabase/lib_metric/schema.cljc b/src/metabase/lib_metric/schema.cljc
index 49af2b81716..7e37f4a6d78 100644
--- a/src/metabase/lib_metric/schema.cljc
+++ b/src/metabase/lib_metric/schema.cljc
@@ -326,7 +326,9 @@
[:status {:optional true} [:maybe ::dimension-status]]
[:status-message {:optional true} [:maybe :string]]
[:sources {:optional true} [:maybe [:sequential ::dimension-source]]]
- [:group {:optional true} [:maybe ::dimension-group]]])
+ [:group {:optional true} [:maybe ::dimension-group]]
+ ;; At most one dimension per entity may be the default.
+ [:default {:optional true} [:maybe :boolean]]])
(mr/def ::persisted-dimensions
"Schema for a sequence of persisted dimensions."
@@ -374,6 +376,7 @@
[:status-message {:optional true} [:maybe :string]]
[:sources {:optional true} [:maybe [:sequential ::dimension-source]]]
[:group {:optional true} [:maybe ::dimension-group]]
+ [:default {:optional true} [:maybe :boolean]]
;; Source tracking
[:source-type ::dimension-source-type]
[:source-id pos-int?]
diff --git a/src/metabase/measures/api.clj b/src/metabase/measures/api.clj
index 1e67362bf4d..ab77edea3f8 100644
--- a/src/metabase/measures/api.clj
+++ b/src/metabase/measures/api.clj
@@ -83,17 +83,21 @@
(events/publish-event! :event/measure-create {:object measure :user-id api/*current-user-id*})
(t2/hydrate measure :creator))))
-(mu/defn- hydrated-measure [id :- ms/PositiveInt]
+(mu/defn- hydrated-measure [id :- ms/PositiveInt
+ include-orphaned? :- :boolean]
(api/read-check (t2/select-one :model/Measure :id id))
(metrics/sync-dimensions! :metadata/measure id)
- (-> (t2/hydrate (t2/select-one :model/Measure :id id) :creator)
- metrics/filter-dimensions-for-user))
+ (cond-> (-> (t2/hydrate (t2/select-one :model/Measure :id id) :creator)
+ metrics/filter-dimensions-for-user)
+ (not include-orphaned?) metrics/without-orphaned-dimensions))
(api.macros/defendpoint :get "/:id" :- ::measure
"Fetch `Measure` with ID."
[{:keys [id]} :- [:map
- [:id ms/PositiveInt]]]
- (let [measure (hydrated-measure id)]
+ [:id ms/PositiveInt]]
+ {:keys [include-orphaned]} :- [:map
+ [:include-orphaned {:optional true} [:maybe ms/BooleanValue]]]]
+ (let [measure (hydrated-measure id (boolean include-orphaned))]
(assoc measure :result_column_name (metrics/aggregation-column-name (:database (:definition measure)) (:definition measure)))))
(api.macros/defendpoint :get "/" :- [:sequential ::measure]
@@ -127,7 +131,7 @@
(api/create-check :model/Measure {:table_id new-table-id}))))
(when changes
(t2/update! :model/Measure id changes))
- (u/prog1 (hydrated-measure id)
+ (u/prog1 (hydrated-measure id false)
(events/publish-event! :event/measure-update
{:object <> :user-id api/*current-user-id* :revision-message revision_message}))))
@@ -166,7 +170,7 @@
[{:keys [id dimension-key]} :- [:map
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]]
- (let [measure (hydrated-measure id)]
+ (let [measure (hydrated-measure id false)]
(metrics/dimension-values
(:dimensions measure)
(:dimension_mappings measure)
@@ -181,7 +185,7 @@
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]
{:keys [query]} :- [:map [:query ms/NonBlankString]]]
- (let [measure (hydrated-measure id)]
+ (let [measure (hydrated-measure id false)]
(metrics/dimension-search-values
(:dimensions measure)
(:dimension_mappings measure)
@@ -197,7 +201,7 @@
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]
{:keys [value]} :- [:map [:value :string]]]
- (let [measure (hydrated-measure id)]
+ (let [measure (hydrated-measure id false)]
(metrics/dimension-remapped-value
(:dimensions measure)
(:dimension_mappings measure)
diff --git a/src/metabase/metrics/api.clj b/src/metabase/metrics/api.clj
index bb4f78ea318..ade8498084f 100644
--- a/src/metabase/metrics/api.clj
+++ b/src/metabase/metrics/api.clj
@@ -4,15 +4,18 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.collections.models.collection :as collection]
+ [metabase.events.core :as events]
[metabase.lib-metric.core :as lib-metric]
[metabase.lib-metric.schema :as lib-metric.schema]
[metabase.metrics.core :as metrics]
[metabase.metrics.permissions :as metrics.perms]
[metabase.query-processor.core :as qp]
+ [metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.pipeline :as qp.pipeline]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.request.core :as request]
[metabase.server.core :as server]
+ [metabase.util :as u]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
@@ -85,18 +88,22 @@
:offset offset
:data metrics}))
-(mu/defn- hydrated-metric [id :- ms/PositiveInt]
+(mu/defn- hydrated-metric [id :- ms/PositiveInt
+ include-orphaned? :- :boolean]
(api/read-check (t2/select-one :model/Card :id id :type "metric"))
(metrics/sync-dimensions! :metadata/metric id)
- (-> (t2/select-one :model/Card :id id :type "metric")
- metrics.perms/filter-dimensions-for-user))
+ (cond-> (-> (t2/select-one :model/Card :id id :type "metric")
+ metrics.perms/filter-dimensions-for-user)
+ (not include-orphaned?) metrics/without-orphaned-dimensions))
(api.macros/defendpoint :get "/:id" :- ::MetricWithDimensions
"Fetch a `Metric` with ID.
Returns the metric with hydrated dimensions and dimension mappings."
- [{:keys [id]} :- [:map [:id ms/PositiveInt]]]
- (let [metric (hydrated-metric id)]
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ {:keys [include-orphaned]} :- [:map
+ [:include-orphaned {:optional true} [:maybe ms/BooleanValue]]]]
+ (let [metric (hydrated-metric id (boolean include-orphaned))]
(assoc metric :result_column_name (metrics/aggregation-column-name (:database_id metric) (:dataset_query metric)))))
;;; +----------------------------------------------------------------------------------------------------------------+
@@ -162,12 +169,20 @@
[:row_count ms/IntGreaterThanOrEqualToZero]])
(defn- check-expression-permissions
- "Collect all metric/measure leaves from the expression and verify query permissions for each."
+ "Verify permissions for each expression leaf and return metric card IDs keyed by UUID."
[expression]
- (doseq [[source-type source-id] (collect-expression-leaves expression)]
- (case source-type
- :metric (api/query-check (t2/select-one :model/Card :id source-id :type "metric"))
- :measure (api/query-check (t2/select-one :model/Measure :id source-id)))))
+ (into {}
+ (keep (fn [leaf]
+ (let [source-type (lib-metric/expression-leaf-type leaf)
+ source-id (lib-metric/expression-leaf-id leaf)]
+ (case source-type
+ :metric (do
+ (api/read-check (t2/select-one :model/Card :id source-id :type "metric"))
+ [(lib-metric/expression-leaf-uuid leaf) source-id])
+ :measure (do
+ (api/query-check (t2/select-one :model/Measure :id source-id))
+ nil))))
+ (lib-metric/expression-leaves expression))))
(defn- from-api-definition
"Create a MetricDefinition from API definition parameters.
@@ -175,12 +190,9 @@
The definition map is passed through directly as the internal MetricDefinition,
since the API format and internal format now match.
- Permission checks are performed on all referenced entities in the expression."
+ Referenced entities must be permission-checked before calling this function."
[provider definition]
(let [{:keys [expression filters projections]} definition]
- ;; Permission check all expression leaves
- (check-expression-permissions expression)
- ;; Build MetricDefinition — format matches directly
{:lib/type :metric/definition
:expression expression
:filters (or filters [])
@@ -196,14 +208,23 @@
(update query :info merge {:executed-by api/*current-user-id*
:context :metric}))
+(defn- process-leaf-query
+ ([query metric-card-id]
+ (binding [qp.perms/*card-id* metric-card-id]
+ (qp/process-query (qp/userland-query (with-metric-exec-info query)))))
+ ([query metric-card-id rff]
+ (binding [qp.perms/*card-id* metric-card-id]
+ (qp/process-query (qp/userland-query (with-metric-exec-info query)) rff))))
+
(defn- execute-leaf-queries
"Execute all leaf queries in parallel, collecting results eagerly.
Must be called OUTSIDE streaming context to avoid JSON writer conflicts.
- Returns {uuid -> qp-result}."
- [leaves]
+ Returns {uuid -> qp-result}."
+ [leaves metric-card-ids]
(let [uuid->future (into {}
(map (fn [[uuid leaf-plan]]
- [uuid (future (qp/process-query (qp/userland-query (with-metric-exec-info (:leaf/mbql leaf-plan)))))]))
+ [uuid (future (process-leaf-query (:leaf/mbql leaf-plan)
+ (get metric-card-ids uuid)))]))
leaves)]
(into {}
(map (fn [[uuid f]] [uuid @f]))
@@ -231,13 +252,14 @@
[_route-params
_query-params
{:keys [definition]} :- ::DatasetRequest]
- (let [definition (from-api-definition (lib-metric/metadata-provider) definition)
- plan (lib-metric/->query-plan definition {:limit 10000})]
+ (let [metric-card-ids (check-expression-permissions (:expression definition))
+ definition (from-api-definition (lib-metric/metadata-provider) definition)
+ plan (lib-metric/->query-plan definition {:limit 10000})]
(if (= :leaf (:plan/type plan))
(qp.streaming/streaming-response [rff :api]
- (qp/process-query (qp/userland-query (with-metric-exec-info (:plan/mbql plan))) rff))
+ (process-leaf-query (:plan/mbql plan) (some-> metric-card-ids vals first) rff))
;; Arithmetic: execute leaf queries BEFORE streaming to avoid JSON writer conflicts
- (let [uuid->result (execute-leaf-queries (:plan/leaves plan))]
+ (let [uuid->result (execute-leaf-queries (:plan/leaves plan) metric-card-ids)]
(qp.streaming/streaming-response [rff :api]
(stream-arithmetic-results plan uuid->result rff))))))
@@ -257,9 +279,10 @@
[_route-params
_query-params
{:keys [definition]} :- ::DatasetRequest]
- (let [definition (from-api-definition (lib-metric/metadata-provider) definition)
- plan (lib-metric/->query-plan definition {:limit 100 :values-only true})
- result (qp/process-query (qp/userland-query (with-metric-exec-info (:plan/mbql plan))))
+ (let [metric-card-ids (check-expression-permissions (:expression definition))
+ definition (from-api-definition (lib-metric/metadata-provider) definition)
+ plan (lib-metric/->query-plan definition {:limit 100 :values-only true})
+ result (process-leaf-query (:plan/mbql plan) (some-> metric-card-ids vals first))
col (first (get-in result [:data :cols]))
values (mapv first (get-in result [:data :rows]))]
{:values values
@@ -276,7 +299,7 @@
[{:keys [id dimension-key]} :- [:map
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]]
- (let [metric (hydrated-metric id)]
+ (let [metric (hydrated-metric id false)]
(metrics/dimension-values
(:dimensions metric)
(:dimension_mappings metric)
@@ -291,7 +314,7 @@
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]
{:keys [query]} :- [:map [:query ms/NonBlankString]]]
- (let [metric (hydrated-metric id)]
+ (let [metric (hydrated-metric id false)]
(metrics/dimension-search-values
(:dimensions metric)
(:dimension_mappings metric)
@@ -307,9 +330,115 @@
[:id ms/PositiveInt]
[:dimension-key ms/UUIDString]]
{:keys [value]} :- [:map [:value :string]]]
- (let [metric (hydrated-metric id)]
+ (let [metric (hydrated-metric id false)]
(metrics/dimension-remapped-value
(:dimensions metric)
(:dimension_mappings metric)
dimension-key
value)))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Dimension CRUD Endpoints |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defn- read-check-metric! [id]
+ (api/read-check (t2/select-one :model/Card :id id :type "metric")))
+
+(defn- write-check-metric! [id]
+ (api/write-check (t2/select-one :model/Card :id id :type "metric")))
+
+;; The module-local parent keeps the topic publishable in OSS, where no consumer namespace derives
+;; it. (A direct :metabase/event derive would throw once an EE consumer makes it an ancestor.)
+(derive ::dimensions-event :metabase/event)
+(derive :event/metric-dimensions-update ::dimensions-event)
+
+(defn- notify-dimensions-changed!
+ "Signal that a metric's dimension mappings changed so its dependency graph is recomputed."
+ [id]
+ (events/publish-event! :event/metric-dimensions-update {:object {:id id}}))
+
+(api.macros/defendpoint :get "/:id/dimension"
+ :- [:map
+ [:added [:sequential :map]]
+ [:addable [:sequential :map]]]
+ "List a metric's curated dimensions, and (when `with-addable=true`) the columns still available to
+ add, grouped by source table. Both can be filtered with a `query` name substring."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ {:keys [query with-addable include-orphaned]} :- [:map
+ [:query {:optional true} [:maybe :string]]
+ [:with-addable {:optional true} [:maybe ms/BooleanValue]]
+ [:include-orphaned {:optional true} [:maybe ms/BooleanValue]]]]
+ (read-check-metric! id)
+ (metrics/sync-dimensions! :metadata/metric id)
+ (metrics/list-dimensions :metadata/metric id {:query query
+ :with-addable? (boolean with-addable)
+ :include-orphaned? (boolean include-orphaned)}))
+
+(api.macros/defendpoint :post "/:id/dimension/add"
+ :- [:sequential :map]
+ "Add dimensions to a metric. Each entry carries its UUID and mapping target; the column-derived fields and mapping
+ are recomputed server-side.
+
+ Returns the updated list of dimensions."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ _query-params
+ {:keys [dimensions]} :- [:map
+ [:dimensions [:sequential [:map
+ [:id ms/NonBlankString]
+ [:display_name {:optional true} ms/NonBlankString]
+ [:description {:optional true} [:maybe :string]]
+ [:mapping_target ::lib-metric.schema/dimension-mapping.target]]]]]]
+ (write-check-metric! id)
+ (u/prog1 (metrics/add-dimensions! :metadata/metric id dimensions)
+ (notify-dimensions-changed! id)))
+
+(api.macros/defendpoint :post "/:id/dimension/remove"
+ :- [:sequential :map]
+ "Remove dimensions (by UUID) from a metric. Returns the updated list of added dimensions."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ _query-params
+ {:keys [dimension_ids]} :- [:map [:dimension_ids [:sequential ms/NonBlankString]]]]
+ (write-check-metric! id)
+ (u/prog1 (metrics/remove-dimensions! :metadata/metric id dimension_ids)
+ (notify-dimensions-changed! id)))
+
+(api.macros/defendpoint :post "/:id/dimension/set-default"
+ :- [:sequential :map]
+ "Mark exactly one dimension as the metric's default, clearing any previous default. Returns the
+ updated list of added dimensions. (It is legal for a metric to have no default; this always leaves
+ exactly one.)"
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ _query-params
+ {:keys [dimension_id]} :- [:map [:dimension_id ms/NonBlankString]]]
+ (write-check-metric! id)
+ (metrics/set-default-dimension! :metadata/metric id dimension_id))
+
+(api.macros/defendpoint :post "/:id/dimension/reorder"
+ :- [:sequential :map]
+ "Persist a new ordering for a metric's dimensions. `dimension_ids` is the desired order; dimensions
+ not listed keep their relative order after the listed ones. Returns the updated list of added
+ dimensions."
+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]
+ _query-params
+ {:keys [dimension_ids]} :- [:map [:dimension_ids [:sequential ms/NonBlankString]]]]
+ (write-check-metric! id)
+ (metrics/reorder-dimensions! :metadata/metric id dimension_ids))
+
+(api.macros/defendpoint :post "/:id/dimension/:dimension-key"
+ :- :map
+ "Update a metric dimension's `display_name`, `description`, and/or source column.
+
+ `source` is a `{type, field-id}`; the new column must have the same effective type."
+ [{:keys [id dimension-key]} :- [:map
+ [:id ms/PositiveInt]
+ [:dimension-key ms/UUIDString]]
+ _query-params
+ body :- [:map
+ [:display_name {:optional true} ms/NonBlankString]
+ [:description {:optional true} [:maybe :string]]
+ [:source {:optional true} [:maybe [:map [:field-id ms/PositiveInt]]]]]]
+ (write-check-metric! id)
+ (u/prog1 (metrics/update-dimension! :metadata/metric id dimension-key body)
+ ;; Only a source-column change alters the mapping (and thus the deps graph).
+ (when (:source body)
+ (notify-dimensions-changed! id))))
diff --git a/src/metabase/metrics/core.clj b/src/metabase/metrics/core.clj
index 1b0241a744f..49f5cd261cb 100644
--- a/src/metabase/metrics/core.clj
+++ b/src/metabase/metrics/core.clj
@@ -2,6 +2,7 @@
"Core namespace for metrics functionality including dimension hydration.
Contains persistence multimethod and orchestration logic."
(:require
+ [clojure.string :as str]
[metabase.lib-be.core :as lib-be]
[metabase.lib-metric.core :as lib-metric]
[metabase.lib.core :as lib]
@@ -9,6 +10,8 @@
[metabase.metrics.dimension :as metrics.dimension]
[metabase.metrics.permissions :as metrics.perms]
[metabase.metrics.transforms :as metrics.transforms]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.namespaces :as shared.ns]))
;;; ------------------------------------------------- Re-exports --------------------------------
@@ -26,7 +29,12 @@
normalize-target-ref
normalize-dimension-mapping
transform-dimensions
- transform-dimension-mappings])
+ transform-dimension-mappings
+ export-dimensions
+ import-dimensions
+ export-dimension-mappings
+ import-dimension-mappings
+ dimension-mappings-deps])
;;; ------------------------------------------------- Query Utilities -------------------------------------------------
@@ -51,36 +59,321 @@
{:arglists '([entity dimensions dimension-mappings])}
(fn [entity _dimensions _dimension-mappings] (:lib/type entity)))
+(defmulti dimensions-initialized?
+ "Whether an entity's dimensions have been initialized in durable storage."
+ {:arglists '([entity])}
+ :lib/type)
+
+(defmethod dimensions-initialized? :default
+ [entity]
+ (some? (lib-metric/get-persisted-dimensions entity)))
+
;;; ------------------------------------------------- Hydration -------------------------------------------------
+(defn- save-dimensions-if-changed!
+ "Persist `new-dims`/`new-mappings` only when they differ from the currently stored set."
+ [entity old-dims old-mappings new-dims new-mappings]
+ (when (or (lib-metric/dimensions-changed? old-dims new-dims)
+ (lib-metric/mappings-changed? old-mappings new-mappings))
+ (save-dimensions! entity new-dims new-mappings)))
+
+(defn- sync-measure-dimensions!
+ "Measures are fully synced on every load: recompute from the visible columns and reconcile with the
+ persisted set — preserving the UUIDs (and user edits) of dimensions that already existed, adding
+ new columns, and marking removed columns `:status/orphaned`. Measures have no curation API."
+ [entity computed-pairs persisted-dims persisted-mappings]
+ (let [{:keys [dimensions dimension-mappings]}
+ (lib-metric/reconcile-dimensions-and-mappings computed-pairs persisted-dims persisted-mappings)]
+ (save-dimensions-if-changed! entity
+ (lib-metric/extract-persisted-dimensions (or persisted-dims []))
+ persisted-mappings
+ (lib-metric/extract-persisted-dimensions dimensions)
+ dimension-mappings)))
+
+(defn- table-prefixed-dimension
+ [dimension]
+ (if (= "connection" (get-in dimension [:group :type]))
+ (assoc dimension :display-name (str (get-in dimension [:group :display-name])
+ " - "
+ (or (:display-name dimension) (:name dimension))))
+ dimension))
+
+(defn compute-full-dimension-set
+ "Compute the FULL dimension set for a metric's `query` — its own-table columns PLUS every
+ implicitly-joined (FK-reachable) column — in the persisted `{:dimensions ... :dimension-mappings ...}`
+ shape (or `nil` when `query` is blank).
+
+ Unlike the seeded default (own-table and explicitly-joined columns only), this includes every
+ FK-reachable column."
+ [query]
+ (when (seq query)
+ (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)
+ {:keys [dimensions dimension-mappings]}
+ (lib-metric/reconcile-dimensions-and-mappings computed-pairs nil nil)
+ dimensions (mapv table-prefixed-dimension dimensions)]
+ {:dimensions (lib-metric/extract-persisted-dimensions dimensions)
+ :dimension-mappings dimension-mappings})))
+
+(defn- seed-metric-dimensions!
+ "First initialization of a v2 metric: seed dimensions from the entity's own columns and explicit
+ query joins, leaving implicitly-joinable FK columns out."
+ [entity computed-pairs]
+ (let [seed-pairs (filterv #(or (lib-metric/main-group? %)
+ (= :source/joins (get-in % [:dimension :lib/source])))
+ computed-pairs)
+ {:keys [dimensions dimension-mappings]}
+ (lib-metric/reconcile-dimensions-and-mappings seed-pairs nil nil)
+ dimensions (lib-metric/extract-persisted-dimensions dimensions)
+ default-dimension (lib-metric/pick-default-dimension dimensions)
+ dimensions (cond-> dimensions
+ default-dimension (lib-metric/set-default-dimension (:id default-dimension)))]
+ (save-dimensions! entity
+ dimensions
+ dimension-mappings)))
+
+(defn- refresh-metric-dimensions!
+ "A v2 metric that already has curated dimensions: the stored dimensions/mappings are authoritative
+ (never re-added, overwritten, or auto-extended); only `:status` is refreshed (a dimension whose
+ column disappeared becomes `:status/orphaned`, and back to `:status/active` if it returns)."
+ [entity computed-pairs persisted-dims persisted-mappings]
+ (let [{:keys [dimensions dimension-mappings]}
+ (lib-metric/reconcile-existing-dimensions computed-pairs persisted-dims persisted-mappings)]
+ (save-dimensions-if-changed! entity persisted-dims persisted-mappings dimensions dimension-mappings)))
+
(defn sync-dimensions!
- "Compute dimensions from visible-columns, reconcile with persisted data,
- and persist to the database if changed.
+ "Sync an entity's dimensions to the database. Behaviour differs by entity type:
+
+ - `:metadata/measure` — fully synced on every load; see [[sync-measure-dimensions!]].
+ - `:metadata/metric` (v2 Cards) — curated; seeded once via [[seed-metric-dimensions!]], then kept
+ authoritative via [[refresh-metric-dimensions!]].
Arguments:
- - `metadata-type` - the metadata type, either `:metadata/metric` or `:metadata/measure`
+ - `metadata-type` - `:metadata/metric` or `:metadata/measure`
- `id` - the entity ID
- This function only handles the side-effect of syncing dimensions to the database.
- Callers should fetch the entity separately after calling this function."
+ Side-effecting only; does not return the updated entity."
[metadata-type id]
(when-let [entity (first (lib.metadata.protocols/metadatas
(lib-metric/metadata-provider)
{:lib/type metadata-type :id #{id}}))]
(when-let [query (lib-metric/dimensionable-query entity)]
- (let [mp (lib-metric/metadata-provider)
- computed-pairs (lib-metric/compute-dimension-pairs mp query)
+ (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)
persisted-dims (lib-metric/get-persisted-dimensions entity)
- persisted-mappings (lib-metric/get-persisted-dimension-mappings entity)
-
- {:keys [dimensions dimension-mappings]}
- (lib-metric/reconcile-dimensions-and-mappings
- computed-pairs persisted-dims persisted-mappings)
-
- old-persisted (lib-metric/extract-persisted-dimensions
- (or persisted-dims []))
- new-persisted (lib-metric/extract-persisted-dimensions
- dimensions)]
- (when (or (lib-metric/dimensions-changed? old-persisted new-persisted)
- (lib-metric/mappings-changed? persisted-mappings dimension-mappings))
- (save-dimensions! entity new-persisted dimension-mappings))))))
+ persisted-mappings (lib-metric/get-persisted-dimension-mappings entity)]
+ (case metadata-type
+ :metadata/measure
+ (sync-measure-dimensions! entity computed-pairs persisted-dims persisted-mappings)
+
+ :metadata/metric
+ (if (dimensions-initialized? entity)
+ (refresh-metric-dimensions! entity computed-pairs persisted-dims persisted-mappings)
+ (if (nil? persisted-dims)
+ (seed-metric-dimensions! entity computed-pairs)
+ (save-dimensions! entity
+ (lib-metric/extract-persisted-dimensions persisted-dims)
+ persisted-mappings))))))))
+
+(defn without-orphaned-dimensions
+ "Remove orphaned dimensions and their mappings from an API response without changing persistence."
+ [entity]
+ (if (nil? (:dimensions entity))
+ entity
+ (let [dimensions (filterv #(not= :status/orphaned (:status %)) (:dimensions entity))
+ dimension-ids (into #{} (map :id) dimensions)]
+ (assoc entity
+ :dimensions dimensions
+ :dimension_mappings
+ (filterv #(contains? dimension-ids (:dimension-id %))
+ (:dimension_mappings entity))))))
+
+;;; ------------------------------------------------- Dimension CRUD -------------------------------------------------
+;;; Each function loads the dimensionable entity (measure / metric) by its metadata-type + id, mutates
+;;; the curated dimension set, persists via `save-dimensions!`, and returns API-shaped dimensions.
+;;; None of these functions performs authorization checks.
+
+(defn- dimension-entity
+ "Fetch the dimensionable entity metadata (`:metadata/metric` or `:metadata/measure`) by id."
+ [metadata-type id]
+ (or (first (lib.metadata.protocols/metadatas
+ (lib-metric/metadata-provider)
+ {:lib/type metadata-type :id #{id}}))
+ (throw (ex-info (tru "Not found.") {:status-code 404}))))
+
+(defn- entity-computed-pairs
+ "All computed dimension pairs (main + connection groups) for an entity's query, or `[]`."
+ [entity]
+ (if-let [query (lib-metric/dimensionable-query entity)]
+ (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)
+ []))
+
+(defn- pair->field-id
+ "Field id targeted by a computed pair's mapping, if any."
+ [pair]
+ (let [target (-> pair :mapping :target)]
+ (when (and (vector? target) (= :field (first target)) (>= (count target) 3))
+ (let [id (nth target 2)]
+ (when (pos-int? id) id)))))
+
+(defn- search-matches?
+ "True when `query` is blank or appears (case-insensitively) in the dimension's display/name."
+ [query dim]
+ (or (str/blank? query)
+ (let [q (u/lower-case-en query)]
+ (boolean (some #(and % (str/includes? (u/lower-case-en %) q))
+ [(:display-name dim) (:name dim)])))))
+
+(defn- added-dimensions
+ "Perm-filter persisted dims/mappings for the current user and return them as API dimensions."
+ [dims mappings]
+ (->> (metrics.perms/filter-dimensions-for-user {:dimensions (vec dims) :dimension_mappings (vec mappings)})
+ :dimensions
+ (mapv metrics.dimension/->api-dimension)))
+
+(defn- addable-groups
+ "Group addable computed pairs by their column group, assigning each a fresh random UUID, and
+ return the API `[{:group ... :dimensions [...]}]` shape."
+ [pairs]
+ (->> pairs
+ (map (fn [{:keys [dimension] :as pair}]
+ (assoc pair :dimension (assoc dimension :id (str (random-uuid))))))
+ (group-by (comp :group :dimension))
+ (mapv (fn [[group dimension-pairs]]
+ {:group (metrics.dimension/->api-group group)
+ :dimensions (mapv metrics.dimension/->api-addable-dimension dimension-pairs)}))))
+
+(defn list-dimensions
+ "List a metric/measure's curated (`:added`) dimensions and, when `with-addable?`, the columns still
+ available to add (`:addable`, grouped by source table). Both are filtered by `query` (a name
+ substring) and by the current user's permissions. Orphaned dimensions are omitted unless
+ `include-orphaned?` is true."
+ [metadata-type id {:keys [query with-addable? include-orphaned?]}]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ visible (cond-> {:dimensions persisted-dims
+ :dimension_mappings persisted-mappings}
+ (not include-orphaned?) without-orphaned-dimensions)
+ added (added-dimensions
+ (filterv #(search-matches? query %) (:dimensions visible))
+ (:dimension_mappings visible))]
+ {:added added
+ :addable (if with-addable?
+ (->> (lib-metric/addable-pairs (entity-computed-pairs entity) persisted-mappings)
+ (filter #(search-matches? query (:dimension %)))
+ addable-groups)
+ [])}))
+
+(defn add-dimensions!
+ "Add the given dimensions to a metric/measure. The column-derived fields and mapping are recomputed
+ server-side from the submitted mapping target; only the UUID, display name, and description come
+ from the request. Returns the updated `:added` list."
+ [metadata-type id api-dims]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ pair-by-target (into {}
+ (map (fn [pair]
+ [(lib-metric/field-ref->key (-> pair :mapping :target)) pair]))
+ (lib-metric/addable-pairs
+ (entity-computed-pairs entity)
+ persisted-mappings))
+ pairs (keep (fn [d]
+ (when-let [pair (get pair-by-target
+ (lib-metric/field-ref->key
+ (metrics.transforms/normalize-target-ref
+ (:mapping_target d))))]
+ {:dimension (cond-> (assoc (:dimension pair) :id (:id d))
+ (:display_name d) (assoc :display-name (:display_name d))
+ (contains? d :description) (assoc :description (:description d)))
+ :mapping (assoc (:mapping pair) :dimension-id (:id d))}))
+ api-dims)
+ {:keys [dimensions dimension-mappings]}
+ (lib-metric/add-dimensions persisted-dims persisted-mappings pairs)
+ added? (> (count dimensions) (count persisted-dims))
+ default-dimension (when (and added? (not-any? :default dimensions))
+ (lib-metric/pick-default-dimension
+ (remove #(= :status/orphaned (:status %)) dimensions)))
+ dimensions (cond-> dimensions
+ default-dimension
+ (lib-metric/set-default-dimension (:id default-dimension)))]
+ (save-dimensions! entity dimensions dimension-mappings)
+ (added-dimensions dimensions dimension-mappings)))
+
+(defn remove-dimensions!
+ "Remove dimensions (by UUID) from a metric/measure. Returns the updated `:added` list."
+ [metadata-type id dimension-ids]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ removed-ids (set dimension-ids)
+ removed-default? (some #(and (:default %) (removed-ids (:id %))) persisted-dims)
+ {:keys [dimensions dimension-mappings]}
+ (lib-metric/remove-dimensions persisted-dims persisted-mappings dimension-ids)
+ next-default (when removed-default?
+ (lib-metric/pick-default-dimension
+ (remove #(= :status/orphaned (:status %)) dimensions)))
+ dimensions (cond-> dimensions
+ next-default (lib-metric/set-default-dimension (:id next-default)))]
+ (save-dimensions! entity dimensions dimension-mappings)
+ (added-dimensions dimensions dimension-mappings)))
+
+(defn reorder-dimensions!
+ "Persist a new ordering for a metric/measure's dimensions. `dimension-ids` is the desired order;
+ dimensions not listed keep their relative order after the listed ones. Mappings are untouched.
+ Returns the updated `:added` list."
+ [metadata-type id dimension-ids]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ dimensions (lib-metric/reorder-dimensions persisted-dims dimension-ids)]
+ (save-dimensions! entity dimensions persisted-mappings)
+ (added-dimensions dimensions persisted-mappings)))
+
+(defn update-dimension!
+ "Update a single dimension's `display_name`, `description`, and/or source column (`source` is a
+ `{:type :field-id}`). Changing the source column is only allowed to a column of the same effective
+ type. Returns the updated API dimension."
+ [metadata-type id dimension-id {:keys [display_name source] :as body}]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ current (or (u/seek #(= dimension-id (:id %)) persisted-dims)
+ (throw (ex-info (tru "Dimension not found.") {:status-code 404})))
+ source-pair (when source
+ (let [pair (u/seek #(= (:field-id source) (pair->field-id %))
+ (entity-computed-pairs entity))]
+ (when-not pair
+ (throw (ex-info (tru "Source column is not available for this metric.")
+ {:status-code 400})))
+ (when (and (:effective-type current)
+ (not= (:effective-type current)
+ (-> pair :dimension :effective-type)))
+ (throw (ex-info (tru "Cannot change a dimension''s source column to one of a different type.")
+ {:status-code 400})))
+ pair))
+ updates (cond-> {}
+ (some? display_name) (assoc :display-name display_name)
+ (contains? body :description) (assoc :description (:description body))
+ source-pair (assoc :source-pair source-pair))
+ {:keys [dimensions dimension-mappings]}
+ (lib-metric/update-dimension persisted-dims persisted-mappings dimension-id updates)]
+ (save-dimensions! entity dimensions dimension-mappings)
+ (some-> (u/seek #(= dimension-id (:id %)) dimensions)
+ metrics.dimension/->api-dimension)))
+
+(defn set-default-dimension!
+ "Mark `dimension-id` as the entity's sole default dimension, clearing any previous default.
+ Throws a 404 when the dimension does not exist and a 400 when it is orphaned.
+ Returns the updated `:added` list."
+ [metadata-type id dimension-id]
+ (let [entity (dimension-entity metadata-type id)
+ persisted-dims (or (lib-metric/get-persisted-dimensions entity) [])
+ persisted-mappings (or (lib-metric/get-persisted-dimension-mappings entity) [])
+ current (or (u/seek #(= dimension-id (:id %)) persisted-dims)
+ (throw (ex-info (tru "Dimension not found.") {:status-code 404})))
+ _ (when (= :status/orphaned (:status current))
+ (throw (ex-info (tru "Cannot set an orphaned dimension as the default.")
+ {:status-code 400})))
+ dimensions (lib-metric/set-default-dimension persisted-dims dimension-id)]
+ (save-dimensions! entity dimensions persisted-mappings)
+ (added-dimensions dimensions persisted-mappings)))
diff --git a/src/metabase/metrics/dimension.clj b/src/metabase/metrics/dimension.clj
index 179d6b9826d..12a05322f3f 100644
--- a/src/metabase/metrics/dimension.clj
+++ b/src/metabase/metrics/dimension.clj
@@ -3,10 +3,48 @@
(:require
[metabase.lib-metric.core :as lib-metric]
[metabase.parameters.core :as parameters]
+ [metabase.util :as u]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
+;;; ------------------------------------------------- API Shape -------------------------------------------------
+;;; Convert internal (kebab-case) dimensions to the snake_case API shape.
+
+(defn ->api-group
+ "Convert an internal dimension group `{:id :type :display-name}` to the API shape."
+ [group]
+ (when group
+ {:id (:id group)
+ :type (:type group)
+ :display_name (:display-name group)}))
+
+(defn- ->api-source
+ [source]
+ {:type (:type source)
+ :field-id (:field-id source)})
+
+(defn ->api-dimension
+ "Convert an internal (kebab) persisted or computed dimension to the API shape consumed by the
+ dimension editor: snake_case top-level keys, fully-qualified type strings, and a `:sources` list
+ whose entries keep the kebab `field-id` key."
+ [dim]
+ (cond-> {:id (:id dim)
+ :display_name (or (:display-name dim) (:name dim))
+ :description (:description dim)
+ :effective_type (some-> (:effective-type dim) u/qualified-name)
+ :semantic_type (some-> (:semantic-type dim) u/qualified-name)
+ :default (boolean (:default dim))}
+ (:status dim) (assoc :status (:status dim))
+ (:group dim) (assoc :group (->api-group (:group dim)))
+ (:sources dim) (assoc :sources (mapv ->api-source (:sources dim)))))
+
+(defn ->api-addable-dimension
+ "Convert a computed dimension/mapping pair to the API shape."
+ [{:keys [dimension mapping]}]
+ (assoc (->api-dimension dimension)
+ :mapping_target (lib-metric/field-ref->key (:target mapping))))
+
(mu/defn dimension-values :- ms/FieldValuesResult
"Fetch values for a dimension given its UUID.
Uses the same logic as the field values API."
diff --git a/src/metabase/metrics/permissions.clj b/src/metabase/metrics/permissions.clj
index 2b8bba9cddb..136b1ddebd0 100644
--- a/src/metabase/metrics/permissions.clj
+++ b/src/metabase/metrics/permissions.clj
@@ -1,126 +1,9 @@
(ns metabase.metrics.permissions
- "Filters dimensions and dimension-mappings by user permissions at the API boundary.
- Dimensions are persisted system-wide by `sync-dimensions!`, but returned to individual
- users filtered by:
- 1. Field visibility_type (hidden/sensitive excluded)
- 2. Table-level view-data permissions
- 3. Column-level sandbox restrictions (EE, via defenterprise)"
+ "Metric permission helpers."
(:require
- [metabase.api.common :as api]
- [metabase.permissions.core :as perms]
- [metabase.premium-features.core :refer [defenterprise]]
- [toucan2.core :as t2]))
-
-(set! *warn-on-reflection* true)
-
-;;; ------------------------------------------------- Batch Lookups -------------------------------------------------
-
-(defn- batch-field-info
- "Batch-fetch field visibility_type and table_id for a set of field IDs.
- Returns {field-id -> {:visibility_type keyword, :table_id int}}."
- [field-ids]
- (when (seq field-ids)
- (into {}
- (map (fn [f] [(:id f) (select-keys f [:visibility_type :table_id])]))
- (t2/select [:model/Field :id :visibility_type :table_id]
- :id [:in field-ids]))))
-
-(defn- batch-table-db-ids
- "Batch-fetch db_id for a set of table IDs.
- Returns {table-id -> db-id}."
- [table-ids]
- (when (seq table-ids)
- (into {}
- (map (fn [t] [(:id t) (:db_id t)]))
- (t2/select [:model/Table :id :db_id]
- :id [:in table-ids]))))
-
-;;; ------------------------------------------------- Permission Predicates -------------------------------------------------
-
-(defn- hidden-field?
- "Returns true if the field's visibility_type should be excluded from metric dimensions."
- [visibility-type]
- (contains? #{:hidden :sensitive :retired} visibility-type))
-
-(defn- user-can-access-table?
- "Returns true if the current user has :unrestricted :perms/view-data for the given table."
- [user-id database-id table-id]
- (perms/user-has-permission-for-table? user-id :perms/view-data :unrestricted database-id table-id))
-
-;;; ------------------------------------------------- Sandbox Extension -------------------------------------------------
-
-(defenterprise sandbox-restricted-fields
- "For sandboxed tables, returns {table-id -> #{allowed-field-ids}}.
- Tables not in the returned map have no column restriction. nil means no sandboxes apply.
- OSS stub returns nil (fail open — :model/Sandbox not available in OSS).
- EE override uses :feature :none to fail closed when MetaStore is down."
- metabase-enterprise.sandbox.api.metric
- [_table-ids]
- nil)
-
-;;; ------------------------------------------------- Core Filter -------------------------------------------------
-
-(defn- target->field-id
- "Extract the integer field ID from a dimension mapping target ref.
- Returns nil if the target is not a field ref or uses a name instead of ID."
- [target]
- (when (and (vector? target)
- (= :field (first target))
- (>= (count target) 3))
- (let [id-or-name (nth target 2)]
- (when (pos-int? id-or-name)
- id-or-name))))
-
-(defn- build-dim->field-id
- "Build a map of {dimension-id -> field-id} from dimensions and their mappings."
- [dimensions dimension-mappings]
- (let [mappings-by-dim-id (into {} (map (juxt :dimension-id identity)) dimension-mappings)]
- (into {}
- (keep (fn [dim]
- (let [field-id (or (some-> dim :sources first :field-id)
- (some-> (get mappings-by-dim-id (:id dim))
- :target
- target->field-id))]
- (when field-id
- [(:id dim) field-id]))))
- dimensions)))
+ [metabase.permissions.metric :as permissions.metric]))
(defn filter-dimensions-for-user
- "Filter dimensions and dimension_mappings on a metric, removing those the
- current user shouldn't see due to:
- 1. Field visibility_type (:hidden or :sensitive)
- 2. Table-level view-data permissions
- 3. Sandbox column restrictions (EE)
-
- Superusers bypass all checks. Dimensions without resolvable field IDs are
- kept (conservative fallback)."
- [{:keys [dimensions dimension_mappings] :as metric}]
- (if (or api/*is-superuser?*
- (empty? dimensions))
- metric
- (let [dim->field-id (build-dim->field-id dimensions dimension_mappings)
- all-field-ids (set (vals dim->field-id))
- field-info (batch-field-info all-field-ids)
- table-ids (into #{} (keep :table_id) (vals field-info))
- table->db (batch-table-db-ids table-ids)
- sandbox-map (sandbox-restricted-fields table-ids)
- allowed? (fn [dim]
- (let [fid (get dim->field-id (:id dim))]
- (if-not fid
- true ;; can't resolve field -> keep (conservative)
- (let [{:keys [visibility_type table_id]} (get field-info fid)
- db-id (get table->db table_id)]
- (and
- ;; not hidden/sensitive
- (not (hidden-field? visibility_type))
- ;; user has table access
- (or (nil? db-id)
- (user-can-access-table? api/*current-user-id* db-id table_id))
- ;; sandbox allows this field
- (or (nil? sandbox-map)
- (nil? (get sandbox-map table_id))
- (contains? (get sandbox-map table_id) fid)))))))
- kept-ids (into #{} (comp (filter allowed?) (map :id)) dimensions)]
- (assoc metric
- :dimensions (filterv #(contains? kept-ids (:id %)) dimensions)
- :dimension_mappings (filterv #(contains? kept-ids (:dimension-id %)) dimension_mappings)))))
+ "Remove metric dimensions and mappings unavailable to the current user."
+ [metric]
+ (permissions.metric/filter-dimensions-for-user metric))
diff --git a/src/metabase/metrics/transforms.clj b/src/metabase/metrics/transforms.clj
index 93282c8787f..379185bfd25 100644
--- a/src/metabase/metrics/transforms.clj
+++ b/src/metabase/metrics/transforms.clj
@@ -1,8 +1,8 @@
(ns metabase.metrics.transforms
- "Shared JSON transform functions for dimension and dimension-mapping columns
- used by both Card and Measure models."
+ "Toucan JSON transforms for dimension and dimension-mapping columns."
(:require
- [metabase.models.interface :as mi]))
+ [metabase.models.interface :as mi]
+ [metabase.models.serialization :as serdes]))
(defn normalize-dimension
"Normalize a dimension after JSON parsing, converting string values to keywords."
@@ -44,3 +44,77 @@
(some->> mappings
mi/json-out-with-keywordization
(mapv normalize-dimension-mapping)))})
+
+;;; ------------------------------------------------- Serialization -------------------------------------------------
+;;; Dimensions and dimension-mappings embed instance-specific Field and Table IDs that must be turned into portable
+;;; references on export and resolved back to local IDs on import. Only curated (metric v2) entities serialize these;
+;;; others re-derive them from their query on the far side.
+
+(defn- export-dimension
+ "Convert the Field IDs embedded in a persisted dimension's `:sources` to portable references."
+ [dimension]
+ (cond-> dimension
+ (seq (:sources dimension))
+ (update :sources (fn [sources]
+ (mapv (fn [source]
+ (cond-> source
+ (pos-int? (:field-id source))
+ (update :field-id serdes/*export-field-fk*)))
+ sources)))))
+
+(defn- import-dimension
+ "Inverse of [[export-dimension]]."
+ [dimension]
+ (cond-> dimension
+ (seq (:sources dimension))
+ (update :sources (fn [sources]
+ (mapv (fn [source]
+ (cond-> source
+ (vector? (:field-id source))
+ (update :field-id serdes/*import-field-fk*)))
+ sources)))))
+
+(defn export-dimensions
+ "Serialize a curated entity's `:dimensions`: convert the Field IDs embedded in each dimension's `:sources` to
+ portable references. `nil` in, `nil` out (so the column is elided for non-curated entities); an empty vector is
+ preserved, so a fully cleared dimension set round-trips as cleared rather than being re-seeded on import."
+ [dimensions]
+ (when (some? dimensions)
+ (mapv export-dimension dimensions)))
+
+(defn import-dimensions
+ "Inverse of [[export-dimensions]]."
+ [dimensions]
+ (when (some? dimensions)
+ (mapv import-dimension dimensions)))
+
+(defn export-dimension-mappings
+ "Serialize a curated entity's `:dimension_mappings`: convert `:table-id` and the Field IDs inside each mapping's
+ `:target` field ref to portable references. `nil`/empty handled as in [[export-dimensions]]."
+ [mappings]
+ (when (some? mappings)
+ (mapv (fn [mapping]
+ (cond-> mapping
+ (pos-int? (:table-id mapping)) (update :table-id serdes/*export-table-fk*)
+ (:target mapping) (update :target serdes/export-mbql)))
+ mappings)))
+
+(defn import-dimension-mappings
+ "Inverse of [[export-dimension-mappings]]."
+ [mappings]
+ (when (some? mappings)
+ (mapv (fn [mapping]
+ (cond-> mapping
+ (vector? (:table-id mapping)) (update :table-id serdes/*import-table-fk*)
+ (:target mapping) (update :target serdes/import-mbql)))
+ mappings)))
+
+(defn dimension-mappings-deps
+ "Serdes dependencies contributed by an entity's `:dimension_mappings` — the Fields/Tables referenced by each
+ mapping's `:target`."
+ ([mappings]
+ (dimension-mappings-deps false mappings))
+ ([allow-int-ids? mappings]
+ (into #{} (comp (map :target)
+ (mapcat #(serdes/mbql-deps allow-int-ids? %)))
+ mappings)))
diff --git a/src/metabase/permissions/metric.clj b/src/metabase/permissions/metric.clj
new file mode 100644
index 00000000000..9e896430e4e
--- /dev/null
+++ b/src/metabase/permissions/metric.clj
@@ -0,0 +1,164 @@
+(ns metabase.permissions.metric
+ "Filters dimensions and dimension-mappings by user permissions at the API boundary.
+ Dimensions are persisted system-wide by `sync-dimensions!`, but returned to individual
+ users filtered by:
+ 1. Field visibility_type (hidden/sensitive excluded)
+ 2. Table-level view-data permissions
+ 3. Column-level sandbox restrictions (EE, via defenterprise)"
+ (:require
+ [metabase.api.common :as api]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.permissions.core :as perms]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; ------------------------------------------------- Batch Lookups -------------------------------------------------
+
+(defn- batch-field-info
+ "Batch-fetch field visibility_type and table_id for a set of field IDs.
+ Returns {field-id -> {:visibility_type keyword, :table_id int}}."
+ [field-ids]
+ (when (seq field-ids)
+ (into {}
+ (map (fn [f] [(:id f) (select-keys f [:visibility_type :table_id])]))
+ (t2/select [:model/Field :id :visibility_type :table_id]
+ :id [:in field-ids]))))
+
+(defn- batch-table-db-ids
+ "Batch-fetch db_id for a set of table IDs.
+ Returns {table-id -> db-id}."
+ [table-ids]
+ (when (seq table-ids)
+ (into {}
+ (map (fn [t] [(:id t) (:db_id t)]))
+ (t2/select [:model/Table :id :db_id]
+ :id [:in table-ids]))))
+
+;;; ------------------------------------------------- Permission Predicates -------------------------------------------------
+
+(defn- hidden-field?
+ "Returns true if the field's visibility_type should be excluded from metric dimensions."
+ [visibility-type]
+ (contains? #{:hidden :sensitive :retired} visibility-type))
+
+(defn- user-can-access-table?
+ "Returns true if the current user has :unrestricted :perms/view-data for the given table."
+ [user-id database-id table-id]
+ (perms/user-has-permission-for-table? user-id :perms/view-data :unrestricted database-id table-id))
+
+;;; ------------------------------------------------- Sandbox Extension -------------------------------------------------
+
+(defenterprise sandbox-restricted-fields
+ "For sandboxed tables, returns {table-id -> #{allowed-field-ids}}.
+ Tables not in the returned map have no column restriction. nil means no sandboxes apply.
+ OSS stub returns nil (fail open — :model/Sandbox not available in OSS).
+ EE override uses :feature :none to fail closed when MetaStore is down."
+ metabase-enterprise.sandbox.api.metric
+ [_table-ids]
+ nil)
+
+;;; ------------------------------------------------- Core Filter -------------------------------------------------
+
+(defn- target->field-id
+ "Extract the integer field ID from a dimension mapping target ref.
+ Returns nil if the target is not a field ref or uses a name instead of ID."
+ [target]
+ (when (and (vector? target)
+ (= 3 (count target)))
+ (let [[tag options id-or-name] target]
+ (when (and (= tag :field)
+ (map? options)
+ (pos-int? id-or-name))
+ id-or-name))))
+
+(defn- metadata-field-info [metadata-provider field-ids]
+ (into {}
+ (keep (fn [field-id]
+ (when-let [field (lib.metadata/field metadata-provider field-id)]
+ [field-id field])))
+ field-ids))
+
+(defn can-use-dimension-mapping?
+ "Whether the current user can use a dimension mapping as a query breakout."
+ [metadata-provider database-id {:keys [target]}]
+ (let [[_ options] target
+ target-field-id (target->field-id target)
+ source-field-id (:source-field options)
+ source-field-valid? (or (not (contains? options :source-field))
+ (pos-int? source-field-id))
+ field-ids (cond-> #{}
+ target-field-id (conj target-field-id)
+ (pos-int? source-field-id) (conj source-field-id))]
+ (and (pos-int? database-id)
+ (pos-int? target-field-id)
+ source-field-valid?
+ (let [field-info (metadata-field-info metadata-provider field-ids)
+ table-ids (into #{} (keep :table-id) (vals field-info))
+ sandbox-map (when (and (not api/*is-superuser?*) (seq table-ids))
+ (sandbox-restricted-fields table-ids))]
+ (and (= field-ids (set (keys field-info)))
+ (every? (fn [[field-id {:keys [visibility-type table-id]}]]
+ (and (pos-int? table-id)
+ (or api/*is-superuser?*
+ (and (not (hidden-field? visibility-type))
+ (user-can-access-table? api/*current-user-id* database-id table-id)
+ (or (nil? sandbox-map)
+ (nil? (get sandbox-map table-id))
+ (contains? (get sandbox-map table-id) field-id))))))
+ field-info))))))
+
+(defn- build-dim->field-id
+ "Build a map of {dimension-id -> field-id} from dimensions and their mappings."
+ [dimensions dimension-mappings]
+ (let [mappings-by-dim-id (into {} (map (juxt :dimension-id identity)) dimension-mappings)]
+ (into {}
+ (keep (fn [dim]
+ (let [field-id (or (some-> dim :sources first :field-id)
+ (some-> (get mappings-by-dim-id (:id dim))
+ :target
+ target->field-id))]
+ (when field-id
+ [(:id dim) field-id]))))
+ dimensions)))
+
+(defn filter-dimensions-for-user
+ "Filter dimensions and dimension_mappings on a metric, removing those the
+ current user shouldn't see due to:
+ 1. Field visibility_type (:hidden or :sensitive)
+ 2. Table-level view-data permissions
+ 3. Sandbox column restrictions (EE)
+
+ Superusers bypass all checks. Dimensions without resolvable field IDs are
+ kept (conservative fallback)."
+ [{:keys [dimensions dimension_mappings] :as metric}]
+ (if (or api/*is-superuser?*
+ (empty? dimensions))
+ metric
+ (let [dim->field-id (build-dim->field-id dimensions dimension_mappings)
+ all-field-ids (set (vals dim->field-id))
+ field-info (batch-field-info all-field-ids)
+ table-ids (into #{} (keep :table_id) (vals field-info))
+ table->db (batch-table-db-ids table-ids)
+ sandbox-map (sandbox-restricted-fields table-ids)
+ allowed? (fn [dim]
+ (let [fid (get dim->field-id (:id dim))]
+ (if-not fid
+ true ;; can't resolve field -> keep (conservative)
+ (let [{:keys [visibility_type table_id]} (get field-info fid)
+ db-id (get table->db table_id)]
+ (and
+ ;; not hidden/sensitive
+ (not (hidden-field? visibility_type))
+ ;; user has table access
+ (or (nil? db-id)
+ (user-can-access-table? api/*current-user-id* db-id table_id))
+ ;; sandbox allows this field
+ (or (nil? sandbox-map)
+ (nil? (get sandbox-map table_id))
+ (contains? (get sandbox-map table_id) fid)))))))
+ kept-ids (into #{} (comp (filter allowed?) (map :id)) dimensions)]
+ (assoc metric
+ :dimensions (filterv #(contains? kept-ids (:id %)) dimensions)
+ :dimension_mappings (filterv #(contains? kept-ids (:dimension-id %)) dimension_mappings)))))
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index fdb638812e9..31ea460a604 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -82,7 +82,7 @@
The core `after-select` logic compares each row's `card_schema` and runs the upgrade functions for all versions up to
and including [[current-schema-version]]."
- 23)
+ 24)
(defmulti ^:private upgrade-card-schema-to
"Upgrades a card on read, so that it fits the given schema version number.
@@ -110,6 +110,12 @@
{:dimensions dimensions
:dimension_mappings dimension-mappings})))
+(defmethod metrics/dimensions-initialized? :metadata/metric
+ [metric]
+ (some? (:dimensions (t2/query-one {:select [:dimensions]
+ :from [:report_card]
+ :where [:= :id (:id metric)]}))))
+
(t2/deftransforms :model/Card
{:dataset_query lib-be/transform-query
:display mi/transform-keyword
@@ -724,6 +730,23 @@
;; just a no-op.
card)
+;; Schema upgrade: 23 to 24 ==========================================================================================
+;; Curated metric dimensions. New metrics seed their own-table columns only, with joined/FK
+;; columns available to add on demand. But metrics created before curated dimensions shipped implicitly
+;; exposed EVERY breakoutable column (own-table + implicitly-joined), and existing dashboard filters may
+;; be mapped to those joined columns. Modernize such a metric on read by backfilling the full
+;; implicitly-joined dimension set, so every existing mapping still corresponds to a live dimension.
+;; Only un-curated metrics (`:dimensions` still nil) are touched; once a metric is curated (any write),
+;; its `card_schema` is bumped to current and this upgrade no longer runs, so removals stay sticky.
+(defmethod upgrade-card-schema-to 24
+ [card _schema-version]
+ (if (and (= :metric (keyword (:type card)))
+ (nil? (:dimensions card))
+ (seq (:dataset_query card)))
+ (let [{:keys [dimensions dimension-mappings]} (metrics/compute-full-dimension-set (:dataset_query card))]
+ (assoc card :dimensions dimensions :dimension_mappings dimension-mappings))
+ card))
+
(mu/defn- upgrade-card-schema-to-latest :- ::queries.schema/card
[card :- :map]
(-> (if (and (:id card)
@@ -1406,8 +1429,6 @@
:dataset_query_metrics_v2_migration_backup
;; this column is not used anymore
:cache_ttl
- ;; dimensions are computed from the query and reconciled on read, not serialized
- :dimensions :dimension_mappings
;; temporary column to power rollback from v57 to v56; we can remove it in v58
:legacy_query
;; always derivable from dataset_query by populate-query-fields; nil when not derivable
@@ -1440,7 +1461,10 @@
:parameters {:export serdes/export-parameters :import serdes/import-parameters}
:parameter_mappings {:export serdes/export-parameter-mappings :import serdes/import-parameter-mappings}
:visualization_settings {:export serdes/export-visualization-settings :import serdes/import-visualization-settings}
- :result_metadata {:export-with-context export-result-metadata :import import-result-metadata}}
+ :result_metadata {:export-with-context export-result-metadata :import import-result-metadata}
+ ;; curated metric v2 dimensions & their column mappings; nil for non-metric cards, which elides the keys
+ :dimensions {:export metrics/export-dimensions :import metrics/import-dimensions}
+ :dimension_mappings {:export metrics/export-dimension-mappings :import metrics/import-dimension-mappings}}
:defaults {:archived false
:archived_directly false
:collection_preview true
@@ -1454,12 +1478,13 @@
"The serdes dependencies of a Card as `:serdes/meta` paths. `allow-int-ids?` selects raw-appdb vs serialized ref semantics for
the mbql walkers. Shared by [[serdes/deserialization-dependencies]] (allow-int-ids? false) and
[[serdes/serialization-dependencies]] (allow-int-ids? true)."
- [allow-int-ids? {:keys [collection_id database_id dataset_query parameters parameter_mappings
+ [allow-int-ids? {:keys [collection_id database_id dataset_query dimension_mappings parameters parameter_mappings
result_metadata source_card_id visualization_settings
dashboard_id document_id]}]
(set
(concat
(mapcat #(serdes/mbql-deps allow-int-ids? %) parameter_mappings)
+ (metrics/dimension-mappings-deps allow-int-ids? dimension_mappings)
(serdes/parameters-deps allow-int-ids? parameters)
(when database_id [[{:model "Database" :id database_id}]])
(when source_card_id #{[{:model "Card" :id source_card_id}]})
diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.clj
index c8c0c543cef..1428327a39f 100644
--- a/src/metabase/queries_rest/api/card.clj
+++ b/src/metabase/queries_rest/api/card.clj
@@ -24,6 +24,7 @@
[metabase.query-permissions.core :as query-perms]
[metabase.query-processor.api :as api.dataset]
[metabase.query-processor.card :as qp.card]
+ [metabase.query-processor.dashboard :as qp.dashboard]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.pivot :as qp.pivot]
[metabase.query-processor.schema :as qp.schema]
@@ -897,18 +898,21 @@
[:ignore_cache {:default false} :boolean]
[:collection_preview {:optional true} [:maybe :boolean]]
[:dashboard_id {:optional true} [:maybe ms/PositiveInt]]]]
- ;; TODO -- we should probably warn if you pass `dashboard_id`, and tell you to use the new
- ;;
- ;; POST /api/dashboard/:dashboard-id/queries/:card-id/query
- ;;
- ;; endpoint instead. Or error in that situation? We're not even validating that you have access to this Dashboard.
- (let [resolved-card-id (eid-translation/->id-or-404 :card card-id)]
+ (let [resolved-card-id (eid-translation/->id-or-404 :card card-id)
+ card (api/check-404 (t2/select-one :model/Card resolved-card-id))]
+ (when dashboard_id
+ (api/read-check :model/Dashboard dashboard_id))
(qp.card/process-query-for-card
- (api/check-404 (t2/select-one :model/Card resolved-card-id)) :api
+ card :api
:parameters parameters
:ignore-cache ignore_cache
:dashboard-id dashboard_id
- :context (if collection_preview :collection :question)
+ :card-transform (when (or dashboard_id collection_preview)
+ qp.dashboard/card-with-default-metric-dimension)
+ :context (cond
+ collection_preview :collection
+ dashboard_id :dashboard
+ :else :question)
:middleware {:process-viz-settings? false})))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
@@ -1018,13 +1022,20 @@
[{:keys [card-id]} :- [:map
[:card-id ms/PositiveInt]]
_query-params
- {:keys [parameters ignore_cache]
+ {:keys [parameters ignore_cache dashboard_id]
:or {ignore_cache false}} :- [:map
- [:ignore_cache {:optional true} [:maybe :boolean]]]]
- (qp.card/process-query-for-card (api/check-404 (t2/select-one :model/Card card-id)) :api
- :parameters parameters
- :qp qp.pivot/run-pivot-query
- :ignore-cache ignore_cache))
+ [:ignore_cache {:optional true} [:maybe :boolean]]
+ [:dashboard_id {:optional true} [:maybe ms/PositiveInt]]]]
+ (let [card (api/check-404 (t2/select-one :model/Card card-id))]
+ (when dashboard_id
+ (api/read-check :model/Dashboard dashboard_id))
+ (qp.card/process-query-for-card card :api
+ :parameters parameters
+ :qp qp.pivot/run-pivot-query
+ :ignore-cache ignore_cache
+ :dashboard-id dashboard_id
+ :card-transform (when dashboard_id qp.dashboard/card-with-default-metric-dimension)
+ :context (if dashboard_id :dashboard :question))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/query_processor/card.clj b/src/metabase/query_processor/card.clj
index addb5e7d91f..de8944d1b57 100644
--- a/src/metabase/query_processor/card.clj
+++ b/src/metabase/query_processor/card.clj
@@ -316,10 +316,13 @@
`context` is a keyword describing the situation in which this query is being ran, e.g. `:question` (from a Saved
Question) or `:dashboard` (from a Saved Question in a Dashboard). See [[metabase.legacy-mbql.schema/Context]] for
- all valid options."
+ all valid options.
+
+ `card-transform` is applied after the Card read check and must preserve the Card's identity. Result metadata from a
+ transformed query is returned but not persisted to the Card."
[card :- ::queries.schema/card
export-format
- & {:keys [parameters constraints context dashboard-id dashcard middleware qp make-run ignore-cache]
+ & {:keys [parameters constraints context dashboard-id dashcard middleware qp make-run ignore-cache card-transform]
:or {constraints (qp.constraints/default-query-constraints)
context :question
;; param `make-run` can be used to control how the query is ran, e.g. if you need to customize the `context`
@@ -327,6 +330,11 @@
make-run process-query-for-card-default-run-fn}}]
{:pre [(map? card) (pos-int? (:id card)) (u/maybe? sequential? parameters)]}
(let [card (api/read-check card)
+ stored-query (:dataset_query card)
+ card ((or card-transform identity) card)
+ middleware (cond-> middleware
+ (not= stored-query (:dataset_query card))
+ (assoc :skip-result-metadata-persistence? true))
card-id (:id card)
dashcard-id (:id dashcard)
parameters (some-> parameters parameters.schema/normalize-parameters-without-adding-default-types)
diff --git a/src/metabase/query_processor/dashboard.clj b/src/metabase/query_processor/dashboard.clj
index 2f8343dda39..05a1e2c1f57 100644
--- a/src/metabase/query_processor/dashboard.clj
+++ b/src/metabase/query_processor/dashboard.clj
@@ -8,9 +8,11 @@
[metabase.dashboards.models.dashboard :as dashboard]
[metabase.dashboards.schema :as dashboards.schema]
[metabase.events.core :as events]
+ [metabase.lib-metric.core :as lib-metric]
[metabase.lib.core :as lib]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.permissions.core :as perms]
+ [metabase.permissions.metric :as permissions.metric]
[metabase.query-processor.card :as qp.card]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.middleware.constraints :as qp.constraints]
@@ -37,6 +39,57 @@
:card_id card-id
:dashboardcard_id dashcard-id))))))
+(defn- current-dimension-mapping?
+ [provider query mapping]
+ (let [target-key (lib-metric/field-ref->key (:target mapping))]
+ (boolean
+ (some #(= target-key (lib-metric/field-ref->key (-> % :mapping :target)))
+ (lib-metric/compute-dimension-pairs provider query)))))
+
+(defn- default-metric-dimension
+ [provider query card]
+ (let [metric-metadata {:lib/type :metadata/metric
+ :id (:id card)
+ :dataset-query (:dataset_query card)
+ :dimensions (:dimensions card)
+ :dimension-mappings (:dimension_mappings card)}
+ dimensions (lib-metric/get-persisted-dimensions metric-metadata)
+ mappings (lib-metric/get-persisted-dimension-mappings metric-metadata)]
+ (when-let [dimension (u/seek #(and (:default %)
+ (not= :status/orphaned (:status %)))
+ dimensions)]
+ (when-let [mapping (u/seek #(= (:id dimension) (:dimension-id %)) mappings)]
+ (when (current-dimension-mapping? provider query mapping)
+ (when-let [database-provider (lib-metric/database-provider-for-table provider (:table-id mapping))]
+ (when (permissions.metric/can-use-dimension-mapping? database-provider (:database_id card) mapping)
+ (let [field-id (lib-metric/dimension-target->field-id (:target mapping))]
+ (cond-> (assoc dimension
+ :lib/type :metadata/dimension
+ :source-type :metric
+ :source-id (:id card)
+ :dimension-mapping mapping)
+ (and (not (seq (:sources dimension))) field-id)
+ (assoc :sources [{:type :field, :field-id field-id}]))))))))))
+
+(defn card-with-default-metric-dimension
+ "Replace a metric card's final-stage breakouts with its active default dimension when the current user can access it."
+ [card]
+ (if-not (= :metric (:type card))
+ card
+ (let [provider (lib-metric/metadata-provider)
+ query (lib/query provider (:dataset_query card))]
+ (if-not (and (= 1 (count (:stages query)))
+ (lib/mbql-stage? query -1))
+ card
+ (if-let [dimension (default-metric-dimension provider query card)]
+ (let [definition (lib-metric/from-metric-metadata provider card)
+ breakout (lib-metric/dimension-breakout definition dimension)]
+ (cond-> card
+ breakout (assoc :dataset_query (-> query
+ lib/remove-all-breakouts
+ (lib/breakout breakout)))))
+ card)))))
+
(defn- resolve-param-for-card
[card-id dashcard-id param-id->param {param-id :id, :as request-param}]
(when-not param-id
@@ -197,4 +250,5 @@
dashboard-id card-id dashcard-id)
;; we've already validated our parameters, so we don't need the [[qp.card]] namespace to do it again
(binding [qp.card/*allow-arbitrary-mbql-parameters* true]
- (m/mapply qp.card/process-query-for-card card export-format options))))))
+ (m/mapply qp.card/process-query-for-card card export-format
+ (assoc options :card-transform card-with-default-metric-dimension)))))))
diff --git a/src/metabase/query_processor/middleware/results_metadata.clj b/src/metabase/query_processor/middleware/results_metadata.clj
index 3c42d224a8f..1f1068d720d 100644
--- a/src/metabase/query_processor/middleware/results_metadata.clj
+++ b/src/metabase/query_processor/middleware/results_metadata.clj
@@ -144,11 +144,15 @@
(mu/defn record-and-return-metadata! :- ::qp.schema/rff
"Post-processing middleware that records metadata about the columns returned when running the query. Returns an rff."
- [{{:keys [skip-results-metadata?]} :middleware, :as query} :- ::qp.schema/any-query
- rff :- ::qp.schema/rff]
+ [{{:keys [skip-results-metadata? skip-result-metadata-persistence?]} :middleware, :as query}
+ :- ::qp.schema/any-query
+ rff :- ::qp.schema/rff]
(if skip-results-metadata?
rff
- (let [record! (partial record-metadata! query)]
+ (let [query (cond-> query
+ skip-result-metadata-persistence?
+ (assoc :qp/skip-result-metadata-persistence true))
+ record! (partial record-metadata! query)]
(fn record-and-return-metadata!-rff* [metadata]
(insights-xform metadata record! (rff metadata))))))
diff --git a/test/metabase/lib/query_test.cljc b/test/metabase/lib/query_test.cljc
index 59a9438e914..448423f4664 100644
--- a/test/metabase/lib/query_test.cljc
+++ b/test/metabase/lib/query_test.cljc
@@ -222,9 +222,12 @@
(lib/aggregate (lib/count))
(lib/breakout (meta/field-metadata :people :created-at))
(lib/breakout (meta/field-metadata :people :birth-date)))
- false :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ true :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
(lib/aggregate (lib/count))
(lib/breakout (meta/field-metadata :people :name)))
+ true :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (lib/aggregate (lib/count))
+ (lib/breakout (meta/field-metadata :people :id)))
false :metric (-> (lib.tu/venues-query)
(lib/aggregate (lib/count))
(lib/append-stage)
@@ -257,9 +260,12 @@
(lib/aggregate (lib/count))
(lib/breakout (meta/field-metadata :people :created-at))
(lib/breakout (meta/field-metadata :people :birth-date)))
- false :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ true :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
(lib/aggregate (lib/count))
(lib/breakout (meta/field-metadata :people :id)))
+ true :metric (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (lib/aggregate (lib/count))
+ (lib/breakout (meta/field-metadata :people :name)))
false :metric (-> (lib.tu/venues-query)
(lib/aggregate (lib/count))
(lib/append-stage)
diff --git a/test/metabase/lib_metric/dimension_test.cljc b/test/metabase/lib_metric/dimension_test.cljc
index efb3e676829..7ccfd78fc67 100644
--- a/test/metabase/lib_metric/dimension_test.cljc
+++ b/test/metabase/lib_metric/dimension_test.cljc
@@ -24,6 +24,23 @@
{:dimension {:id nil :name name}
:mapping {:type :table :table-id table-id :target target}}))
+(deftest ^:parallel pick-default-dimension-test
+ (let [fallback {:id "fallback" :effective-type :type/Integer}
+ category {:id "category" :semantic-type :type/Category}
+ low-cardinality {:id "low-cardinality" :effective-type :type/Text :has-field-values :list}
+ state {:id "state" :effective-type :type/Text :semantic-type :type/State}
+ time {:id "time" :effective-type :type/DateTime}]
+ (testing "prefers time, then geo, then category or low-cardinality, then the first dimension (UXW-4788)"
+ (is (= time (lib-metric.dimension/pick-default-dimension
+ [fallback category low-cardinality state time])))
+ (is (= state (lib-metric.dimension/pick-default-dimension
+ [fallback category low-cardinality state])))
+ (is (= category (lib-metric.dimension/pick-default-dimension
+ [fallback category low-cardinality])))
+ (is (= low-cardinality (lib-metric.dimension/pick-default-dimension
+ [fallback low-cardinality])))
+ (is (= fallback (lib-metric.dimension/pick-default-dimension [fallback]))))))
+
;;; -------------------------------------------------- Target Comparison --------------------------------------------------
(deftest ^:parallel targets-equal?-same-field-id-test
@@ -56,6 +73,35 @@
(is (lib-metric.dimension/targets-equal? target-a target-b)
"effective-type and base-type are ignored")))
+;;; -------------------------------------------------- field-ref->key --------------------------------------------------
+
+(deftest ^:parallel field-ref->key-ignores-transient-opts-test
+ (testing ":lib/uuid and type hints are not part of the key"
+ (is (= (lib-metric.dimension/field-ref->key
+ [:field {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" :effective-type :type/Integer} 100])
+ (lib-metric.dimension/field-ref->key
+ [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" :base-type :type/BigInteger} 100])))))
+
+(deftest ^:parallel field-ref->key-distinguishes-source-field-test
+ (testing "the SAME field id reached via different FKs (:source-field) yields DISTINCT keys"
+ ;; This is the bug this function exists to prevent: field ids are not unique within a query when
+ ;; a table has multiple FKs to the same foreign table.
+ (is (not= (lib-metric.dimension/field-ref->key [:field {:source-field 1} 100])
+ (lib-metric.dimension/field-ref->key [:field {:source-field 2} 100]))))
+ (testing "the same field id + same :source-field yields the same key (regardless of :lib/uuid)"
+ (is (= (lib-metric.dimension/field-ref->key
+ [:field {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" :source-field 1} 100])
+ (lib-metric.dimension/field-ref->key
+ [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" :source-field 1} 100])))))
+
+(deftest ^:parallel field-ref->key-includes-bucketing-test
+ (testing "binning is part of the key"
+ (is (not= (lib-metric.dimension/field-ref->key [:field {:binning {:strategy :default}} 100])
+ (lib-metric.dimension/field-ref->key [:field {} 100]))))
+ (testing "temporal-unit is part of the key"
+ (is (not= (lib-metric.dimension/field-ref->key [:field {:temporal-unit :month} 100])
+ (lib-metric.dimension/field-ref->key [:field {:temporal-unit :day} 100])))))
+
;;; -------------------------------------------------- Reconciliation --------------------------------------------------
(deftest ^:parallel reconcile-new-dimensions-get-random-uuids-test
diff --git a/test/metabase/lib_metric/projection_test.cljc b/test/metabase/lib_metric/projection_test.cljc
index 0e1615974b6..b0bf0fec0ff 100644
--- a/test/metabase/lib_metric/projection_test.cljc
+++ b/test/metabase/lib_metric/projection_test.cljc
@@ -206,6 +206,42 @@
(is (= uuid-1 (nth (first dim-refs) 2)))
(is (= uuid-1 (nth (second dim-refs) 2))))))
+(deftest ^:parallel project-dimension-applies-default-options-test
+ (testing "Temporal dimensions use the default temporal bucket"
+ (let [result (lib-metric.projection/project-dimension definition-with-provider dimension-1)
+ projection (get-in result [:projections 0 :projection 0])]
+ (is (= :month (:temporal-unit (second projection))))))
+ (testing "Time dimensions use an hourly default temporal bucket"
+ (let [dimension (assoc dimension-1 :effective-type :type/Time)
+ result (lib-metric.projection/project-dimension definition-with-provider dimension)
+ projection (get-in result [:projections 0 :projection 0])]
+ (is (= :hour (:temporal-unit (second projection))))))
+ (testing "Field-backed numeric dimensions use the default binning strategy"
+ (let [dimension (assoc dimension-3 :sources [{:type :field :field-id 3}])
+ result (lib-metric.projection/project-dimension definition-with-provider dimension)
+ projection (get-in result [:projections 0 :projection 0])]
+ (is (= {:strategy :default} (:binning (second projection))))))
+ (testing "Categorical dimensions are projected without bucketing"
+ (let [result (lib-metric.projection/project-dimension definition-with-provider dimension-2)
+ projection (get-in result [:projections 0 :projection 0])]
+ (is (= #{} (set (keys (dissoc (second projection) :lib/uuid))))))))
+
+(deftest ^:parallel dimension-breakout-test
+ (testing "The mapped field and its join information are preserved"
+ (let [dimension (assoc dimension-1
+ :dimension-mapping {:type :table
+ :dimension-id uuid-1
+ :target [:field {:lib/uuid "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ :source-field 10}
+ 20]})
+ breakout (lib-metric.projection/dimension-breakout definition-with-provider dimension)]
+ (is (= :field (first breakout)))
+ (is (= 20 (nth breakout 2)))
+ (is (= 10 (:source-field (second breakout))))
+ (is (= :month (:temporal-unit (second breakout))))))
+ (testing "A dimension without a mapping has no breakout"
+ (is (nil? (lib-metric.projection/dimension-breakout definition-with-provider dimension-1)))))
+
;;; -------------------------------------------------- projection-dimension --------------------------------------------------
(deftest ^:parallel projection-dimension-requires-valid-provider-test
diff --git a/test/metabase/metrics/api_dimension_test.clj b/test/metabase/metrics/api_dimension_test.clj
index b393aa46a2e..1d51bf66388 100644
--- a/test/metabase/metrics/api_dimension_test.clj
+++ b/test/metabase/metrics/api_dimension_test.clj
@@ -1,6 +1,8 @@
(ns metabase.metrics.api-dimension-test
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.metrics.core :as metrics]
@@ -18,6 +20,12 @@
(-> (lib/query mp table-metadata)
(lib/aggregate (lib/count)))))
+(defn- orders-metric-query []
+ (let [mp (mt/metadata-provider)
+ table-metadata (lib.metadata/table mp (mt/id :orders))]
+ (-> (lib/query mp table-metadata)
+ (lib/aggregate (lib/count)))))
+
(defn- get-dimension-id [metric dimension-name]
(let [dim (first (filter #(= (:name %) dimension-name) (:dimensions metric)))]
(:id dim)))
@@ -205,3 +213,438 @@
(mt/user-http-request :rasta :get 403
(str "metric/" (:id metric) "/dimension/" fake-dimension-id "/remapping")
:value "1")))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Dimension CRUD Endpoints |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defmacro ^:private with-seeded-metric [[binding] & body]
+ `(mt/with-temp [:model/Card metric# {:name "CRUD Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric#))
+ (let [~binding metric#]
+ ~@body)))
+
+(deftest list-dimensions-test
+ (testing "GET /api/metric/:id/dimension lists the curated (self-table) dimensions"
+ (with-seeded-metric [metric]
+ (let [resp (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))]
+ (is (seq (:added resp)) "should list seeded self-table dimensions")
+ (is (= [] (:addable resp)) "addable is empty unless requested")
+ (is (contains? (set (map :display_name (:added resp))) "Price"))))))
+
+(deftest list-dimensions-with-addable-test
+ (testing "GET /api/metric/:id/dimension?with-addable=true returns joinable columns to add"
+ (with-seeded-metric [metric]
+ (let [resp (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension") :with-addable true)]
+ (is (seq (:addable resp)) "FK-joinable (categories) columns should be addable")
+ (is (every? #(and (contains? % :group) (seq (:dimensions %))) (:addable resp))
+ "each addable entry is a {group, dimensions} group")))))
+
+(deftest list-dimensions-search-test
+ (testing "GET /api/metric/:id/dimension?query=… filters added dimensions by name"
+ (with-seeded-metric [metric]
+ (let [names (->> (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension") :query "Price")
+ :added (map :display_name) set)]
+ (is (contains? names "Price"))
+ (is (not (contains? names "Latitude")))))))
+
+(deftest list-dimensions-excludes-orphaned-dimensions-test
+ (testing "GET /api/metric/:id/dimension synchronizes and optionally includes orphaned dimensions"
+ (with-seeded-metric [metric]
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))
+ orphan-id (:id (first dimensions))
+ mappings (mapv #(if (= orphan-id (:dimension-id %))
+ (assoc-in % [:target 2] (mt/id :users :name))
+ %)
+ dimension_mappings)]
+ (t2/update! :model/Card (:id metric) {:dimension_mappings mappings})
+ (let [response (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension"))]
+ (is (not (some #(= orphan-id (:id %)) (:added response)))))
+ (let [response (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension")
+ :include-orphaned true)
+ orphan (some #(when (= orphan-id (:id %)) %) (:added response))]
+ (is (= "status/orphaned" (:status orphan))))))))
+
+(deftest remove-dimensions-test
+ (testing "POST /api/metric/:id/dimension/remove removes dimensions by id and persists"
+ (with-seeded-metric [metric]
+ (let [price-id (get-dimension-id (t2/select-one :model/Card :id (:id metric)) "PRICE")
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/remove")
+ {:dimension_ids [price-id]})]
+ (is (not (contains? (set (map :id resp)) price-id))
+ "removed dimension is gone from the response")
+ (is (not (contains? (set (map :id (:dimensions (t2/select-one :model/Card :id (:id metric))))) price-id))
+ "removal is persisted")))))
+
+(deftest remove-default-dimension-test
+ (testing "removing the default dimension assigns the preferred remaining active dimension"
+ (with-seeded-metric [metric]
+ (let [dimensions (:dimensions (t2/select-one :model/Card :id (:id metric)))
+ current-default (m/find-first :default dimensions)
+ remaining-ids (into #{}
+ (comp (remove #(= (:id current-default) (:id %)))
+ (remove #(= :status/orphaned (:status %)))
+ (map :id))
+ dimensions)]
+ (is (some? current-default))
+ (is (seq remaining-ids))
+ (when current-default
+ (let [resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/remove")
+ {:dimension_ids [(:id current-default)]})
+ defaults (filter :default resp)]
+ (is (= 1 (count defaults)))
+ (is (contains? remaining-ids (:id (first defaults))))))))))
+
+(deftest remove-all-dimensions-test
+ (testing "removing all dimensions leaves the metric without a default"
+ (with-seeded-metric [metric]
+ (let [dimension-ids (mapv :id (:dimensions (t2/select-one :model/Card :id (:id metric))))
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/remove")
+ {:dimension_ids dimension-ids})]
+ (is (empty? resp))
+ (is (empty? (:dimensions (t2/select-one :model/Card :id (:id metric)))))))))
+
+(deftest add-dimensions-test
+ (testing "POST /api/metric/:id/dimension/add adds a full dimension object and preserves the default"
+ (with-seeded-metric [metric]
+ (let [default-id (-> (m/find-first :default
+ (:dimensions (t2/select-one :model/Card :id (:id metric))))
+ :id)
+ addable (-> (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension") :with-addable true)
+ :addable first :dimensions first)]
+ (is (some? addable) "there should be an addable joinable dimension")
+ (let [resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/add")
+ {:dimensions [addable]})
+ field-ids (->> resp (mapcat :sources) (map :field-id) set)]
+ (is (contains? (set (map :id resp)) (:id addable))
+ "added dimension keeps the posted UUID")
+ (is (contains? field-ids (-> addable :sources first :field-id))
+ "added dimension targets the chosen column")
+ (is (contains? (set (map :id (:dimensions (t2/select-one :model/Card :id (:id metric))))) (:id addable))
+ "the addition is persisted")
+ (is (= [default-id] (mapv :id (filter :default resp)))
+ "the existing default is preserved"))))))
+
+(deftest add-dimension-validation-test
+ (testing "POST /api/metric/:id/dimension/add validates names and descriptions"
+ (with-seeded-metric [metric]
+ (let [path (str "metric/" (:id metric) "/dimension/add")
+ addable (-> (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension") :with-addable true)
+ :addable first :dimensions first)]
+ (doseq [display-name [nil "" " "]]
+ (mt/user-http-request :crowberto :post 400 path
+ {:dimensions [(assoc addable :display_name display-name)]}))
+ (mt/user-http-request :crowberto :post 400 path
+ {:dimensions [(assoc addable :description 42)]})))))
+
+(deftest add-dimension-through-one-of-multiple-foreign-key-paths-test
+ (testing "adding a dimension reached through duplicate foreign key paths preserves the selected path"
+ (let [product-id-field-id (mt/id :orders :product_id)
+ user-id-field-id (mt/id :orders :user_id)
+ product-title-id (mt/id :products :title)]
+ (mt/with-temp-vals-in-db :model/Field user-id-field-id
+ {:fk_target_field_id (mt/id :products :id)}
+ (mt/with-temp [:model/Card metric {:name "Duplicate FK Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query (orders-metric-query)}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [response (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension")
+ :with-addable true)
+ title-dimensions (->> (:addable response)
+ (mapcat :dimensions)
+ (filter #(= product-title-id (-> % :sources first :field-id))))
+ source-field #(get (second (:mapping_target %)) :source-field)
+ by-source-field (m/index-by source-field
+ title-dimensions)
+ selected (get by-source-field product-id-field-id)]
+ (is (= #{product-id-field-id user-id-field-id}
+ (set (keys by-source-field))))
+ (is (some? selected))
+ (when selected
+ (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/add")
+ {:dimensions [selected]})
+ (let [stored-mapping (->> (t2/select-one-fn :dimension_mappings
+ :model/Card :id (:id metric))
+ (m/find-first #(= (:id selected) (:dimension-id %))))
+ remaining (->> (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension")
+ :with-addable true)
+ :addable
+ (mapcat :dimensions)
+ (filter #(= product-title-id (-> % :sources first :field-id))))]
+ (is (= product-id-field-id (get-in stored-mapping [:target 1 :source-field])))
+ (is (= [user-id-field-id]
+ (mapv source-field remaining)))))))))))
+
+(deftest add-first-dimension-assigns-default-test
+ (testing "adding a dimension to an empty curated list makes it the default"
+ (with-seeded-metric [metric]
+ (let [dimension-ids (mapv :id (:dimensions (t2/select-one :model/Card :id (:id metric))))]
+ (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/remove")
+ {:dimension_ids dimension-ids})
+ (let [addable (-> (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension") :with-addable true)
+ :addable first :dimensions first)
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/add")
+ {:dimensions [addable]})]
+ (is (= [(:id addable)] (mapv :id (filter :default resp))))
+ (is (= [(:id addable)]
+ (->> (t2/select-one :model/Card :id (:id metric))
+ :dimensions
+ (filter :default)
+ (mapv :id)))))))))
+
+(deftest update-dimension-display-name-test
+ (testing "POST /api/metric/:id/dimension/:id updates display_name"
+ (with-seeded-metric [metric]
+ (let [price-id (get-dimension-id (t2/select-one :model/Card :id (:id metric)) "PRICE")
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/" price-id)
+ {:display_name "Cost"})]
+ (is (= "Cost" (:display_name resp)))
+ (is (= "Cost" (->> (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))
+ :added (m/find-first #(= price-id (:id %))) :display_name))
+ "the rename is persisted")))))
+
+(deftest update-dimension-validation-test
+ (testing "POST /api/metric/:id/dimension/:id validates names and descriptions"
+ (with-seeded-metric [metric]
+ (let [price-id (get-dimension-id (t2/select-one :model/Card :id (:id metric)) "PRICE")
+ path (str "metric/" (:id metric) "/dimension/" price-id)]
+ (doseq [display-name [nil "" " "]]
+ (mt/user-http-request :crowberto :post 400 path {:display_name display-name}))
+ (mt/user-http-request :crowberto :post 400 path {:description 42})
+ (is (= "A price"
+ (:description (mt/user-http-request :crowberto :post 200 path {:description "A price"}))))
+ (is (nil? (:description (mt/user-http-request :crowberto :post 200 path {:description nil}))))))))
+
+(deftest update-dimension-source-type-mismatch-test
+ (testing "POST /api/metric/:id/dimension/:id rejects a source column of a different type"
+ (with-seeded-metric [metric]
+ (let [name-id (get-dimension-id (t2/select-one :model/Card :id (:id metric)) "NAME")
+ resp (mt/user-http-request :crowberto :post 400
+ (str "metric/" (:id metric) "/dimension/" name-id)
+ {:source {:type "field" :field-id (mt/id :venues :price)}})]
+ (is (re-find #"different type" resp))))))
+
+(deftest dimension-crud-permission-test
+ (testing "dimension CRUD endpoints require write permission"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card metric {:name "Protected Metric"
+ :type :metric
+ :collection_id (:id collection)
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403
+ (str "metric/" (:id metric) "/dimension/remove")
+ {:dimension_ids [fake-dimension-id]})))))))
+
+(deftest default-dimension-picked-on-seed-test
+ (testing "a freshly seeded metric has one default dimension"
+ (with-seeded-metric [metric]
+ (let [added (:added (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension")))]
+ (is (seq added))
+ (is (= 1 (count (filter :default added))))))))
+
+(deftest set-default-dimension-test
+ (testing "POST /api/metric/:id/dimension/set-default keeps exactly one dimension as the default"
+ (with-seeded-metric [metric]
+ (let [added (:added (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension")))
+ a (:id (first added))
+ b (:id (second added))
+ defaults (fn [resp] (into #{} (comp (filter :default) (map :id)) resp))]
+ (t2/update! :model/Card (:id metric)
+ {:dimensions (mapv #(assoc % :default true)
+ (t2/select-one-fn :dimensions :model/Card :id (:id metric)))})
+ (is (= #{a} (defaults (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/set-default")
+ {:dimension_id a})))
+ "setting A repairs multiple persisted defaults")
+ (is (= #{b} (defaults (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/set-default")
+ {:dimension_id b})))
+ "setting B clears A — still exactly one default")
+ (is (= #{b} (defaults (:added (mt/user-http-request :crowberto :get 200
+ (str "metric/" (:id metric) "/dimension")))))
+ "the default is persisted")))))
+
+(deftest set-default-dimension-not-found-test
+ (testing "set-default returns 404 for an unknown dimension"
+ (with-seeded-metric [metric]
+ (is (mt/user-http-request :crowberto :post 404
+ (str "metric/" (:id metric) "/dimension/set-default")
+ {:dimension_id fake-dimension-id})))))
+
+(deftest reorder-dimensions-test
+ (testing "POST /api/metric/:id/dimension/reorder persists the given order"
+ (with-seeded-metric [metric]
+ (let [ids (->> (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))
+ :added (mapv :id))
+ new-order (vec (reverse ids))
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/reorder")
+ {:dimension_ids new-order})]
+ (is (= new-order (mapv :id resp))
+ "response reflects the new order")
+ (is (= new-order
+ (->> (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))
+ :added (mapv :id)))
+ "the order is persisted")))))
+
+(deftest reorder-dimensions-partial-list-test
+ (testing "dimensions missing from the posted order keep their relative order after the listed ones"
+ (with-seeded-metric [metric]
+ (let [ids (->> (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))
+ :added (mapv :id))
+ [listed unlisted] [(vec (reverse (take 2 ids))) (vec (drop 2 ids))]
+ resp (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/reorder")
+ {:dimension_ids listed})]
+ (is (= (into listed unlisted) (mapv :id resp)))))))
+
+(deftest reorder-dimensions-permission-test
+ (testing "POST /api/metric/:id/dimension/reorder requires write permission"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card metric {:name "Protected Metric"
+ :type :metric
+ :collection_id (:id collection)
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403
+ (str "metric/" (:id metric) "/dimension/reorder")
+ {:dimension_ids [fake-dimension-id]})))))))
+
+(deftest update-dimension-preserves-other-mappings-test
+ (testing "updating one dimension leaves every dimension mapping intact"
+ (with-seeded-metric [metric]
+ (let [before (:dimension_mappings (t2/select-one :model/Card :id (:id metric)))
+ price-id (get-dimension-id (t2/select-one :model/Card :id (:id metric)) "PRICE")]
+ (mt/user-http-request :crowberto :post 200
+ (str "metric/" (:id metric) "/dimension/" price-id)
+ {:display_name "Cost"})
+ (let [after (:dimension_mappings (t2/select-one :model/Card :id (:id metric)))]
+ (is (= (count before) (count after)) "no mappings dropped")
+ (is (every? some? after) "no nil mappings")
+ (is (= (set (map :dimension-id before)) (set (map :dimension-id after)))
+ "every dimension is still mapped"))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Curated dimensions: pre-curation metric modernization on read |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defn- pre-curation-metric!
+ "Insert a metric on ORDERS and stamp it with the previous release's `card_schema` and no persisted
+ `:dimensions`, simulating a metric created before curated dimensions shipped. `f` receives the
+ metric id."
+ [f]
+ (let [mp (mt/metadata-provider)
+ orders-q (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))]
+ (mt/with-temp [:model/Card metric {:name "Orders Count"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query orders-q}]
+ ;; Force the previous release's card_schema (23) and leave :dimensions never synced (nil),
+ ;; bypassing before-update so nothing bumps it back to the current version.
+ (t2/query-one {:update :report_card
+ :set {:card_schema 23}
+ :where [:= :id (:id metric)]})
+ (f (:id metric)))))
+
+(deftest pre-curation-metric-modernized-to-full-dimension-set-on-read-test
+ (testing (str "UXW-4808: a metric with the previous release's `card_schema` and no persisted "
+ "`:dimensions` is modernized on read — the `:model/Card` schema upgrade backfills the "
+ "FULL implicitly-joined dimension set (own-table + FK-joined columns) it implicitly "
+ "exposed pre-curation, so existing dashboard-filter mappings on joined columns still "
+ "correspond to a live dimension.")
+ (pre-curation-metric!
+ (fn [metric-id]
+ (let [cat-field (mt/id :products :category) ; reachable from ORDERS only via the implicit FK join
+ dims (:dimensions (mt/user-http-request :crowberto :get 200 (str "metric/" metric-id)))
+ groups (into #{} (comp (map :group)
+ (map :type))
+ dims)
+ fields (into #{} (comp (mapcat :sources)
+ (map :field-id))
+ dims)
+ field-names (into {}
+ (map (juxt #(-> % :sources first :field-id) :display-name))
+ dims)]
+ (testing "the modernized set spans the own-table AND joined columns"
+ (is (contains? groups "main") "own-table (main) dimensions are present")
+ (is (contains? groups "connection") "FK-joined (connection) dimensions are present"))
+ (testing "a joined column that an existing dashboard filter targets exists as a dimension"
+ (is (contains? fields cat-field)
+ "implicitly-joined PRODUCTS.CATEGORY is a live dimension after modernization"))
+ (testing "connected dimensions use table-prefixed display names (UXW-4896)"
+ (doseq [{:keys [display-name group]} dims
+ :when (= "connection" (:type group))]
+ (is (str/starts-with? display-name (str (:display-name group) " - "))))
+ (is (= "ID" (field-names (mt/id :orders :id))))
+ (is (= "Product - ID" (field-names (mt/id :products :id))))
+ (is (= "User - ID" (field-names (mt/id :people :id))))))))))
+
+(deftest pre-curation-metric-dashboard-filter-on-joined-column-works-test
+ (testing (str "UXW-4808: a dashboard filter bound to an implicitly-joined column of a pre-curation metric "
+ "(previous-release `card_schema`, no persisted `:dimensions`) resolves and filters the "
+ "query. The metric is modernized on read while the dashcard query runs, and the "
+ "parameter mapping (a field ref via :source-field) executes correctly.")
+ (pre-curation-metric!
+ (fn [metric-id]
+ (let [cat-field (mt/id :products :category)
+ fk-field (mt/id :orders :product_id)
+ target [:dimension [:field cat-field {:source-field fk-field}]]]
+ (mt/with-temp [:model/Dashboard dash {:name "Dash"
+ :parameters [{:id "cat" :name "Category"
+ :slug "category" :type "string/="}]}
+ :model/DashboardCard dc {:dashboard_id (:id dash)
+ :card_id metric-id
+ :parameter_mappings
+ [{:parameter_id "cat"
+ :card_id metric-id
+ :target target}]}]
+ (let [run (fn [params]
+ (mt/user-http-request
+ :crowberto :post 202
+ (format "dashboard/%d/dashcard/%d/card/%d/query"
+ (:id dash) (:id dc) metric-id)
+ {:parameters params}))
+ total (-> (run []) :data :rows ffirst)
+ filtered (-> (run [{:id "cat"
+ :target target
+ :value ["Gadget"]}])
+ :data :rows ffirst)]
+ (testing "the join-column filter applies to the pre-curation metric's dashcard query"
+ (is (pos-int? total)
+ "unfiltered metric returns a positive count")
+ (is (pos-int? filtered)
+ "the filtered query executes and returns a count")
+ (is (< filtered total)
+ "filtering by a single joined product category returns fewer rows than unfiltered")))))))))
diff --git a/test/metabase/metrics/api_test.clj b/test/metabase/metrics/api_test.clj
index f45623566af..b7d07578c70 100644
--- a/test/metabase/metrics/api_test.clj
+++ b/test/metabase/metrics/api_test.clj
@@ -4,6 +4,8 @@
[clojure.test :refer :all]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[toucan2.core :as t2]))
@@ -190,6 +192,38 @@
(is (seq (:dimensions updated-card)))
(is (seq (:dimension_mappings updated-card))))))))
+(deftest fetch-metric-excludes-orphaned-dimensions-test
+ (testing "GET /api/metric/:id excludes orphaned dimensions unless explicitly requested"
+ (mt/with-temp [:model/Card metric {:name "Metric with orphaned dimension"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}]
+ (mt/user-http-request :rasta :get 200 (str "metric/" (:id metric)))
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))
+ orphan-id (:id (first dimensions))
+ orphan-mapping (some #(when (= orphan-id (:dimension-id %)) %) dimension_mappings)
+ mappings (mapv #(if (= orphan-id (:dimension-id %))
+ (assoc-in % [:target 2] (mt/id :users :name))
+ %)
+ dimension_mappings)]
+ (is (some? orphan-mapping))
+ (t2/update! :model/Card (:id metric) {:dimension_mappings mappings})
+ (let [response (mt/user-http-request :rasta :get 200 (str "metric/" (:id metric)))
+ response-ids (into #{} (map :id) (:dimensions response))
+ response-mapping-ids (into #{} (map :dimension-id) (:dimension_mappings response))]
+ (is (not (contains? response-ids orphan-id)))
+ (is (not (contains? response-mapping-ids orphan-id))))
+ (let [response (mt/user-http-request :rasta :get 200
+ (str "metric/" (:id metric))
+ :include-orphaned true)
+ orphan (some #(when (= orphan-id (:id %)) %) (:dimensions response))]
+ (is (= "status/orphaned" (:status orphan)))
+ (is (some #(= orphan-id (:dimension-id %)) (:dimension_mappings response))))
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))]
+ (is (= :status/orphaned (:status (some #(when (= orphan-id (:id %)) %) dimensions))))
+ (is (some #(= orphan-id (:dimension-id %)) dimension_mappings)))))))
+
(deftest fetch-metric-dimensions-have-has-field-values-test
(testing "GET /api/metric/:id returns dimensions with has-field-values populated"
(mt/with-temp [:model/Card metric {:name "Metric with HFV"
@@ -280,6 +314,19 @@
(mt/user-http-request :rasta :post 403 "metric/dataset"
{:definition {:expression [:metric {:lib/uuid "a"} (:id metric)]}})))))))
+(deftest dataset-endpoint-metric-without-query-building-permissions-test
+ (testing "POST /api/metric/dataset runs a readable metric without query-building permissions"
+ (mt/with-temp [:model/Card metric {:name "Test Metric"
+ :type :metric
+ :dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)
+ (is (= [[100]]
+ (-> (mt/user-http-request :rasta :post 202 "metric/dataset"
+ {:definition {:expression [:metric {:lib/uuid "a"} (:id metric)]}})
+ (get-in [:data :rows]))))))))
+
(deftest dataset-endpoint-rejects-non-metric-card-test
(testing "POST /api/metric/dataset returns 404 for non-metric cards"
(mt/with-temp [:model/Card card {:name "Regular Question"
diff --git a/test/metabase/metrics/core_test.clj b/test/metabase/metrics/core_test.clj
index 65be9eb2ffe..bc650238be4 100644
--- a/test/metabase/metrics/core_test.clj
+++ b/test/metabase/metrics/core_test.clj
@@ -2,6 +2,7 @@
"Tests for metrics.core dimension sync functionality."
(:require
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.metrics.core :as metrics]
@@ -29,6 +30,15 @@
(-> (lib/query mp table-metadata)
(lib/aggregate aggregation-clause))))
+(deftest without-orphaned-dimensions-test
+ (let [entity {:dimensions [{:id "active" :status :status/active}
+ {:id "orphaned" :status :status/orphaned}]
+ :dimension_mappings [{:dimension-id "active"}
+ {:dimension-id "orphaned"}]}]
+ (is (= {:dimensions [{:id "active" :status :status/active}]
+ :dimension_mappings [{:dimension-id "active"}]}
+ (metrics/without-orphaned-dimensions entity)))))
+
;;; ------------------------------------------------ Metric Dimension Sync Tests ------------------------------------------------
(deftest metric-sync-dimensions-basic-test
@@ -69,6 +79,41 @@
(is (some? (:dimension_mappings reloaded))
"Dimension mappings should be persisted to database")))))
+(deftest metric-sync-dimensions-persists-schema-upgraded-dimensions-test
+ (testing "sync-dimensions! persists dimensions generated by the legacy metric schema upgrade (UXW-4808)"
+ (mt/with-temp [:model/Card metric {:name "Legacy Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (t2/query-one {:update :report_card
+ :set {:card_schema 23, :dimensions nil, :dimension_mappings nil}
+ :where [:= :id (:id metric)]})
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [stored (t2/query-one {:select [:dimensions :dimension_mappings]
+ :from [:report_card]
+ :where [:= :id (:id metric)]})
+ first-ids (mapv :id (:dimensions (t2/select-one :model/Card :id (:id metric))))
+ next-ids (mapv :id (:dimensions (t2/select-one :model/Card :id (:id metric))))]
+ (is (some? (:dimensions stored)))
+ (is (some? (:dimension_mappings stored)))
+ (is (= first-ids next-ids))))))
+
+(deftest metric-sync-dimensions-picks-default-test
+ (testing "new metrics persist the preferred seeded dimension as default (UXW-4788)"
+ (let [mp (mt/metadata-provider)
+ orders-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))]
+ (mt/with-temp [:model/Card metric {:name "Test Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query orders-query}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [defaults (filter :default
+ (:dimensions (t2/select-one :model/Card :id (:id metric))))]
+ (is (= ["CREATED_AT"] (mapv :name defaults))))))))
+
(deftest metric-sync-dimensions-preserves-user-modifications-test
(testing "sync-dimensions! preserves user modifications like display-name for metrics"
(mt/with-temp [:model/Card metric {:name "Test Metric"
@@ -110,6 +155,75 @@
(is (nil? (:dimension_mappings reloaded))
"Dimension mappings should remain nil when query is empty")))))
+(deftest metric-sync-dimensions-does-not-re-add-removed-test
+ (testing "sync-dimensions! does not re-add a user-removed dimension on subsequent syncs"
+ (mt/with-temp [:model/Card metric {:name "Test Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))
+ removed-id (:id (first dimensions))
+ kept (rest dimensions)
+ kept-ids (into #{} (map :id) kept)
+ kept-mappings (filter (comp kept-ids :dimension-id)
+ dimension_mappings)]
+ (is (>= (count dimensions) 2)
+ "Venues should yield multiple dimensions to curate")
+ ;; Simulate the user removing the first dimension (and its mapping).
+ (t2/update! :model/Card (:id metric)
+ {:dimensions kept
+ :dimension_mappings kept-mappings})
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [reloaded-ids (into #{} (map :id)
+ (t2/select-one-fn :dimensions :model/Card :id (:id metric)))]
+ (is (not (contains? reloaded-ids removed-id))
+ "Removed dimension must not reappear")
+ (is (= kept-ids reloaded-ids)
+ "Only the curated dimensions remain"))))))
+
+(deftest metric-sync-dimensions-does-not-reseed-when-emptied-test
+ (testing "sync-dimensions! does not regenerate dimensions after the user removes them all"
+ (mt/with-temp [:model/Card metric {:name "Test Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ ;; User removes every dimension; the empty `:dimensions` is authoritative, not "uninitialized".
+ (t2/update! :model/Card (:id metric) {:dimensions []
+ :dimension_mappings []})
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (is (zero? (count (t2/select-one-fn :dimensions :model/Card :id (:id metric))))
+ "Emptied dimensions must not be re-seeded"))))
+
+(deftest metric-sync-dimensions-orphans-deleted-column-test
+ (testing "sync-dimensions! marks a dimension whose underlying column no longer exists as orphaned"
+ (mt/with-temp [:model/Card metric {:name "Test Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :venues)
+ :dataset_query (metric-query)}]
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))
+ dim (first dimensions)
+ mapping (m/find-first #(= (:id dim) (:dimension-id %))
+ dimension_mappings)
+ ;; Repoint this dimension at a column the venues query can't see (users.name is not
+ ;; reachable from venues), simulating a deleted column — keeping the rest of the
+ ;; field ref (incl. :lib/uuid) intact.
+ orphan-mapping (assoc-in mapping [:target 2] (mt/id :users :name))]
+ (t2/update! :model/Card (:id metric)
+ {:dimensions [dim]
+ :dimension_mappings [orphan-mapping]})
+ (metrics/sync-dimensions! :metadata/metric (:id metric))
+ (let [reloaded (first (t2/select-one-fn :dimensions :model/Card :id (:id metric)))]
+ (is (= :status/orphaned (:status reloaded))
+ "A dimension with a missing column should be orphaned")
+ (is (some? (:status-message reloaded))
+ "Orphaned dimension should carry a status message"))))))
+
;;; ------------------------------------------------ Measure Dimension Sync Tests ------------------------------------------------
(deftest measure-sync-dimensions-basic-test
@@ -171,5 +285,31 @@
(is (= "My Custom Name" (:display-name matching-dim))
"User's custom display-name should be preserved"))))))
+(deftest measure-sync-dimensions-fully-resyncs-test
+ (testing "measures fully re-sync on every load: columns missing from storage are re-added, and the
+ UUIDs of dimensions that still existed are preserved (measures have no curation)"
+ (mt/with-temp [:model/Measure measure {:name "Test Measure"
+ :table_id (mt/id :venues)
+ :creator_id (mt/user->id :rasta)
+ :definition (measure-definition (lib/count))}]
+ (metrics/sync-dimensions! :metadata/measure (:id measure))
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Measure :id (:id measure))
+ kept (rest dimensions)
+ kept-ids (into #{} (map :id) kept)
+ kept-mappings (filter (comp kept-ids :dimension-id)
+ dimension_mappings)]
+ (is (>= (count dimensions) 2)
+ "Venues should yield multiple dimensions")
+ ;; Drop one dimension from storage; a full re-sync should bring it back.
+ (t2/update! :model/Measure (:id measure)
+ {:dimensions kept
+ :dimension_mappings kept-mappings})
+ (metrics/sync-dimensions! :metadata/measure (:id measure))
+ (let [reloaded-ids (into #{} (map :id) (t2/select-one-fn :dimensions :model/Measure :id (:id measure)))]
+ (is (= (count dimensions) (count reloaded-ids))
+ "the column dropped from storage is re-added by the full sync")
+ (is (every? reloaded-ids kept-ids)
+ "UUIDs of dimensions that still existed are preserved"))))))
+
;; Note: There's no test for "no-op without definition" for measures
;; because measures have a NOT NULL constraint on the definition column - they must always have a definition.
diff --git a/test/metabase/metrics/permissions_test.clj b/test/metabase/metrics/permissions_test.clj
index 8825fb33a24..47125dfa33c 100644
--- a/test/metabase/metrics/permissions_test.clj
+++ b/test/metabase/metrics/permissions_test.clj
@@ -2,7 +2,10 @@
{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.metrics.permissions-test]}}}}}}
(:require
[clojure.test :refer :all]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.metrics.core :as metrics]
[metabase.metrics.permissions :as metrics.perms]
+ [metabase.permissions.metric :as permissions.metric]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.test :as mt]
@@ -28,6 +31,13 @@
[dims]
(into #{} (map #(get-in % [:group :display-name])) dims))
+(defn- persist-full-dimension-set!
+ [metric]
+ (let [{:keys [dimensions dimension-mappings]}
+ (metrics/compute-full-dimension-set (:dataset_query metric))]
+ (t2/update! :model/Card (:id metric)
+ {:dimensions dimensions, :dimension_mappings dimension-mappings})))
+
;;; ------------------------------------------------- Field Visibility Tests -------------------------------------------------
(deftest hidden-fields-are-filtered-out-test
@@ -82,6 +92,7 @@
(mt/with-temp [:model/Card metric {:name "Orders Count"
:type :metric
:dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]
+ (persist-full-dimension-set! metric)
;; Establish dimensions as superuser first (sync happens on first read)
(let [all-dims (metric-dimensions :crowberto (:id metric))
all-groups (dimension-group-names all-dims)]
@@ -109,6 +120,7 @@
(mt/with-temp [:model/Card metric {:name "Orders Count"
:type :metric
:dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]
+ (persist-full-dimension-set! metric)
(mt/with-no-data-perms-for-all-users!
;; Even with all perms revoked for all-users group, crowberto (superuser) sees everything
(let [dims (metric-dimensions :crowberto (:id metric))
@@ -141,6 +153,7 @@
(mt/with-temp [:model/Card metric {:name "Orders Count"
:type :metric
:dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]
+ (persist-full-dimension-set! metric)
;; Establish dimensions as superuser
(let [all-response (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))
;; Find a dimension from the Product group (FK-joined from Products table)
@@ -183,3 +196,43 @@
(testing "both mappings are preserved"
(is (= #{"resolvable" "unresolvable"}
(into #{} (map :dimension-id) (:dimension_mappings result))))))))
+
+(deftest dimension-mapping-source-field-permissions-test
+ (testing "A dimension mapping requires access to its FK source field"
+ (let [mapping {:target [:field {:source-field (mt/id :orders :user_id)}
+ (mt/id :people :state)]}]
+ (mt/with-test-user :rasta
+ (is (true? (permissions.metric/can-use-dimension-mapping? (mt/metadata-provider) (mt/id) mapping))))
+ (mt/with-temp-vals-in-db :model/Field (mt/id :orders :user_id) {:visibility_type :sensitive}
+ (mt/with-test-user :rasta
+ (is (false? (permissions.metric/can-use-dimension-mapping? (mt/metadata-provider) (mt/id) mapping)))))
+ (mt/with-temp-vals-in-db :model/Field (mt/id :people :state) {:visibility_type :hidden}
+ (mt/with-test-user :rasta
+ (is (false? (permissions.metric/can-use-dimension-mapping? (mt/metadata-provider) (mt/id) mapping))))))))
+
+(deftest invalid-dimension-mapping-targets-test
+ (testing "Unresolved and malformed field targets fail closed"
+ (let [field-id (mt/id :orders :user_id)]
+ (doseq [target [[:field {} "USER_ID"]
+ [:field {:source-field field-id} "USER_ID"]
+ [:field {} Integer/MAX_VALUE]
+ [:field {} field-id :extra]
+ [:field {}]
+ [:field [] field-id]]]
+ (is (false? (permissions.metric/can-use-dimension-mapping?
+ (mt/metadata-provider)
+ (mt/id)
+ {:target target})))))))
+
+(deftest dimension-mapping-permission-uses-metadata-provider-cache-test
+ (testing "Permission checks reuse cached field metadata"
+ (let [provider (mt/metadata-provider)
+ source-field-id (mt/id :orders :user_id)
+ target-field-id (mt/id :people :state)
+ mapping {:target [:field {:source-field source-field-id} target-field-id]}]
+ (lib.metadata/field provider source-field-id)
+ (lib.metadata/field provider target-field-id)
+ (mt/with-test-user :crowberto
+ (t2/with-call-count [call-count]
+ (is (true? (permissions.metric/can-use-dimension-mapping? provider (mt/id) mapping)))
+ (is (zero? (call-count))))))))
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index c2e6a0996f7..8d7bf982f70 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -201,6 +201,50 @@
:target [:variable [:template-tag :category]]
:value 2}]})))))))
+(deftest dashboard-and-collection-context-metric-query-uses-default-dimension-test
+ (testing "POST card query endpoints use the metric's default dimension in dashboard and collection contexts (UXW-4769, UXW-4771)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ product-id (lib.metadata/field mp (mt/id :orders :product_id))
+ dimension-id (str (random-uuid))]
+ (mt/with-temp [:model/Card {metric-id :id}
+ {:name "Orders metric"
+ :type :metric
+ :display :line
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query (-> (lib/query mp orders)
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))
+ :dimensions [{:id dimension-id
+ :display-name "Product ID"
+ :effective-type :type/Integer
+ :semantic-type :type/FK
+ :status :status/active
+ :sources [{:type :field, :field-id (mt/id :orders :product_id)}]
+ :default true}]
+ :dimension_mappings [{:type :table
+ :table-id (mt/id :orders)
+ :dimension-id dimension-id
+ :target (lib/ref product-id)}]}
+ :model/Dashboard {dashboard-id :id} {}]
+ (let [path (format "card/%d/query" metric-id)
+ canonical (mt/user-http-request :crowberto :post 202 path)
+ stored-metadata (t2/select-one-fn :result_metadata :model/Card :id metric-id)]
+ (is (= "CREATED_AT" (-> canonical mt/cols first :name)))
+ (doseq [query-path [path (format "card/pivot/%d/query" metric-id)]]
+ (let [result (mt/user-http-request :crowberto :post 202 query-path {:dashboard_id dashboard-id})]
+ (is (= "PRODUCT_ID" (-> result mt/cols first :name)))
+ (is (= stored-metadata
+ (t2/select-one-fn :result_metadata :model/Card :id metric-id)))))
+ (let [result (mt/user-http-request :crowberto :post 202 path {:collection_preview true})]
+ (is (= "PRODUCT_ID" (-> result mt/cols first :name)))
+ (is (= stored-metadata
+ (t2/select-one-fn :result_metadata :model/Card :id metric-id))))
+ (mt/user-http-request :crowberto :post 404 path {:dashboard_id Integer/MAX_VALUE})))))))
+
(deftest execute-card-with-default-parameters-test
(testing "GET /api/card/:id/query with parameters with default values"
(mt/with-temp
diff --git a/test/metabase/query_processor/dashboard_test.clj b/test/metabase/query_processor/dashboard_test.clj
index df5b0510d2c..ada566e7369 100644
--- a/test/metabase/query_processor/dashboard_test.clj
+++ b/test/metabase/query_processor/dashboard_test.clj
@@ -7,9 +7,11 @@
[clojure.test :refer :all]
[metabase.dashboards-rest.api-test :as api.dashboard-test]
[metabase.driver.common :as driver.common]
+ [metabase.lib-metric.core :as lib-metric]
[metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.metrics.core :as metrics]
[metabase.query-processor.card-test :as qp.card-test]
[metabase.query-processor.dashboard :as qp.dashboard]
[metabase.query-processor.test :as qp]
@@ -36,6 +38,33 @@
card-id
params))
+(defn- count-of-orders-by-created-at-query []
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))]
+ (-> (lib/query mp orders)
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))))
+
+(defn- set-default-metric-dimension! [metric-id display-name]
+ (metrics/sync-dimensions! :metadata/metric metric-id)
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ dimension (some #(when (= display-name (:display-name %)) %) (:dimensions metric))
+ dimensions (mapv #(if (= (:id dimension) (:id %))
+ (assoc % :default true)
+ (dissoc % :default))
+ (:dimensions metric))]
+ (is (some? dimension) (str "Missing metric dimension " display-name))
+ (when dimension
+ (t2/update! :model/Card metric-id {:dimensions dimensions}))))
+
+(defn- default-metric-dimension [metric]
+ (let [provider (lib-metric/metadata-provider)]
+ (#'qp.dashboard/default-metric-dimension
+ provider
+ (lib/query provider (:dataset_query metric))
+ metric)))
+
(deftest ^:parallel resolve-parameters-validation-test
(api.dashboard-test/with-chain-filter-fixtures [{{dashboard-id :id} :dashboard
{card-id :id} :card
@@ -126,6 +155,110 @@
#"Not found"
(run-query-for-dashcard dashboard-id card-id-2 dashcard-id-3))))))
+(deftest dashboard-metric-uses-default-curated-dimension-test
+ (testing "A dashboard metric uses its active curated default dimension (UXW-4769)"
+ (mt/dataset test-data
+ (mt/with-temp [:model/Card {metric-id :id} {:name "Orders metric"
+ :type :metric
+ :display :line
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query (count-of-orders-by-created-at-query)
+ :visualization_settings {:graph.dimensions ["CREATED_AT"]}}
+ :model/Dashboard {dashboard-id :id} {:parameters []}
+ :model/DashboardCard {dashcard-id :id} {:card_id metric-id
+ :dashboard_id dashboard-id
+ :visualization_settings {:card.title "Dashboard metric"}}]
+ (testing "without a curated default, the saved breakout is unchanged"
+ (let [result (run-query-for-dashcard dashboard-id metric-id dashcard-id)]
+ (is (= "CREATED_AT" (-> result mt/cols first :name)))))
+ (let [stored-metadata (t2/select-one-fn :result_metadata :model/Card :id metric-id)]
+ (set-default-metric-dimension! metric-id "Product ID")
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ dimensions (mapv #(cond-> %
+ (:default %) (dissoc :sources))
+ (:dimensions metric))]
+ (t2/update! :model/Card metric-id {:dimensions dimensions}))
+ (testing "missing dimension sources are derived from the mapping"
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ dimension (mt/as-admin (default-metric-dimension metric))]
+ (is (= [{:type :field, :field-id (mt/id :orders :product_id)}]
+ (:sources dimension)))))
+ (let [result (run-query-for-dashcard dashboard-id metric-id dashcard-id)]
+ (is (= "PRODUCT_ID" (-> result mt/cols first :name)))
+ (is (= 200 (count (mt/rows result)))))
+ (testing "the rewritten query does not replace the metric's saved result metadata"
+ (is (= stored-metadata
+ (t2/select-one-fn :result_metadata :model/Card :id metric-id))))
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ dimensions (mapv #(cond-> %
+ (:default %)
+ (assoc :sources [{:type :field, :field-id (mt/id :orders :tax)}]))
+ (:dimensions metric))]
+ (t2/update! :model/Card metric-id {:dimensions dimensions}))
+ (testing "a curated default hidden from the current user is ignored"
+ (mt/with-temp-vals-in-db :model/Field (mt/id :orders :product_id) {:visibility_type :sensitive}
+ (mt/with-test-user :rasta
+ (let [metric (t2/select-one :model/Card :id metric-id)]
+ (is (nil? (default-metric-dimension metric)))))))
+ (testing "a curated default that is no longer projectable is ignored"
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ default-id (some (fn [dimension]
+ (when (:default dimension)
+ (:id dimension)))
+ (:dimensions metric))
+ mappings (mapv #(cond-> %
+ (= (:dimension-id %) default-id)
+ (assoc-in [:target 1 :source-field] (mt/id :orders :tax)))
+ (:dimension_mappings metric))]
+ (mt/with-temp-vals-in-db :model/Card metric-id {:dimension_mappings mappings}
+ (let [metric (t2/select-one :model/Card :id metric-id)]
+ (is (nil? (mt/as-admin (default-metric-dimension metric))))))))
+ (testing "a curated default with a missing mapped field is ignored"
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ default-id (some (fn [dimension]
+ (when (:default dimension)
+ (:id dimension)))
+ (:dimensions metric))
+ mappings (mapv #(cond-> %
+ (= (:dimension-id %) default-id)
+ (assoc :target [:field {} Integer/MAX_VALUE]))
+ (:dimension_mappings metric))]
+ (mt/with-temp-vals-in-db :model/Card metric-id {:dimension_mappings mappings}
+ (let [metric (t2/select-one :model/Card :id metric-id)]
+ (is (nil? (mt/as-admin (default-metric-dimension metric))))))))
+ (let [metric (t2/select-one :model/Card :id metric-id)
+ dimensions (mapv #(cond-> %
+ (:default %) (assoc :status :status/orphaned))
+ (:dimensions metric))]
+ (t2/update! :model/Card metric-id {:dimensions dimensions}))
+ (testing "an orphaned curated default falls back to the saved breakout"
+ (let [result (run-query-for-dashcard dashboard-id metric-id dashcard-id)]
+ (is (= "CREATED_AT" (-> result mt/cols first :name))))))))))
+
+(deftest native-dashboard-metric-keeps-saved-query-test
+ (testing "A native dashboard metric keeps its saved query because it cannot be reprojected (UXW-4769)"
+ (let [dimension-id (str (random-uuid))]
+ (mt/with-temp [:model/Card {metric-id :id}
+ {:name "Native metric"
+ :type :metric
+ :database_id (mt/id)
+ :dataset_query (mt/native-query {:query "SELECT COUNT(*) AS count FROM ORDERS"})
+ :dimensions [{:id dimension-id
+ :display-name "Count"
+ :effective-type :type/Integer
+ :status :status/active
+ :default true}]
+ :dimension_mappings [{:type :table
+ :dimension-id dimension-id
+ :target [:field {:base-type :type/Integer
+ :lib/uuid (str (random-uuid))}
+ "count"]}]}]
+ (let [original (t2/select-one :model/Card :id metric-id)
+ card (mt/as-admin
+ (qp.dashboard/card-with-default-metric-dimension original))]
+ (is (= (:dataset_query original) (:dataset_query card))))))))
+
(deftest default-value-precedence-test-field-filters
(testing "If both Dashboard and Card have default values for a Field filter parameter, Card defaults should take precedence\n"
(mt/dataset test-data
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_average_order.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_average_order.yaml
index c2258586b41..a0e92bc8093 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_average_order.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_average_order.yaml
@@ -34,7 +34,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdMnthlyAvgOr0003
label: monthly_average_order
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_cumulative_orders.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_cumulative_orders.yaml
index cbb9fd1eff9..c000d624a11 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_cumulative_orders.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_cumulative_orders.yaml
@@ -79,7 +79,7 @@ result_metadata:
lib/source-column-alias: count
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdMnthlyCumul0004
label: monthly_cumulative_orders
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_orders.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_orders.yaml
index 6691193d4f9..c5400aba22f 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_orders.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_orders.yaml
@@ -79,7 +79,7 @@ result_metadata:
lib/source-column-alias: count
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdMnthlyOrdrs0001
label: monthly_orders
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_revenue.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_revenue.yaml
index 74416ea210b..2893a5bd650 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_revenue.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/monthly_revenue.yaml
@@ -84,7 +84,7 @@ result_metadata:
lib/source-column-alias: sum
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdMnthlyRevnu0002
label: monthly_revenue
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/native_orders_query.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/native_orders_query.yaml
index 45747ed2012..9ee04c0acc7 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/native_orders_query.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/native_orders_query.yaml
@@ -22,7 +22,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdNatveOrders0005
label: native_orders_query
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/total_revenue.yaml b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/total_revenue.yaml
index d3e51ad641d..90012fe4514 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/total_revenue.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/series_and_parameter_mappings/total_revenue.yaml
@@ -41,7 +41,7 @@ result_metadata:
lib/source-column-alias: sum
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdTtlRevScalr0006
label: total_revenue
diff --git a/test_resources/serialization_baseline/collections/main/dashboards/tabbed_dashboard/products_table.yaml b/test_resources/serialization_baseline/collections/main/dashboards/tabbed_dashboard/products_table.yaml
index 287fc37f81c..f4bf33d3b07 100644
--- a/test_resources/serialization_baseline/collections/main/dashboards/tabbed_dashboard/products_table.yaml
+++ b/test_resources/serialization_baseline/collections/main/dashboards/tabbed_dashboard/products_table.yaml
@@ -248,7 +248,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dShCrdProdsTables0007
label: products_table
diff --git a/test_resources/serialization_baseline/collections/main/documents/product_analysis_report/category_breakdown.yaml b/test_resources/serialization_baseline/collections/main/documents/product_analysis_report/category_breakdown.yaml
index ffe04ae7f02..649837905a7 100644
--- a/test_resources/serialization_baseline/collections/main/documents/product_analysis_report/category_breakdown.yaml
+++ b/test_resources/serialization_baseline/collections/main/documents/product_analysis_report/category_breakdown.yaml
@@ -28,7 +28,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: cRdCaTbReAkDoWn0ExMp1
label: category_breakdown
diff --git a/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/product_overview.yaml b/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/product_overview.yaml
index 802032edc5b..424e092fc40 100644
--- a/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/product_overview.yaml
+++ b/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/product_overview.yaml
@@ -125,7 +125,7 @@ result_metadata:
lib/source-column-alias: avg
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: f1C68pznmrpN1F5xFDj6d
label: product_overview
diff --git a/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/top_products_by_revenue.yaml b/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/top_products_by_revenue.yaml
index 947e533de9f..a5d6773730c 100644
--- a/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/top_products_by_revenue.yaml
+++ b/test_resources/serialization_baseline/collections/main/minimal/marketing_analytics/top_products_by_revenue.yaml
@@ -31,7 +31,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: FTxpeL9vY5pyb6Lc6lCDK
label: top_products_by_revenue
diff --git a/test_resources/serialization_baseline/collections/main/queries/arithmetic_expressions.yaml b/test_resources/serialization_baseline/collections/main/queries/arithmetic_expressions.yaml
index 7f4ad1e4323..87c0979579e 100644
--- a/test_resources/serialization_baseline/collections/main/queries/arithmetic_expressions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/arithmetic_expressions.yaml
@@ -207,7 +207,7 @@ result_metadata:
lib/source-column-alias: avg
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: 1O_2jSo2fD6m3Qr6My7aa
label: arithmetic_expressions
diff --git a/test_resources/serialization_baseline/collections/main/queries/basic_aggregations.yaml b/test_resources/serialization_baseline/collections/main/queries/basic_aggregations.yaml
index 6fc76a42986..01a65e78ba3 100644
--- a/test_resources/serialization_baseline/collections/main/queries/basic_aggregations.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/basic_aggregations.yaml
@@ -241,7 +241,7 @@ result_metadata:
lib/source-column-alias: total_revenue
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: h5F2EjHsRd73Dqqh8sAtd
label: basic_aggregations
diff --git a/test_resources/serialization_baseline/collections/main/queries/comparison_filters.yaml b/test_resources/serialization_baseline/collections/main/queries/comparison_filters.yaml
index 835eb7a0d92..8732088c5a4 100644
--- a/test_resources/serialization_baseline/collections/main/queries/comparison_filters.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/comparison_filters.yaml
@@ -230,7 +230,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: 8kTL-8IzNdWMtXfaMPZaE
label: comparison_filters
diff --git a/test_resources/serialization_baseline/collections/main/queries/conditional_aggregations.yaml b/test_resources/serialization_baseline/collections/main/queries/conditional_aggregations.yaml
index 3f60fa7d9a3..b053fdc8b6a 100644
--- a/test_resources/serialization_baseline/collections/main/queries/conditional_aggregations.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/conditional_aggregations.yaml
@@ -172,7 +172,7 @@ result_metadata:
lib/source-column-alias: share
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: irROiaJoSsiXPKGxwWvWY
label: conditional_aggregations
diff --git a/test_resources/serialization_baseline/collections/main/queries/conditional_and_type_conversion.yaml b/test_resources/serialization_baseline/collections/main/queries/conditional_and_type_conversion.yaml
index 6a9f7e5f474..6b3fae1bdb5 100644
--- a/test_resources/serialization_baseline/collections/main/queries/conditional_and_type_conversion.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/conditional_and_type_conversion.yaml
@@ -469,7 +469,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: 1hsUzNOepulZo3Jamzd1R
label: conditional_and_type_conversion
diff --git a/test_resources/serialization_baseline/collections/main/queries/cumulative_and_statistical_aggregations.yaml b/test_resources/serialization_baseline/collections/main/queries/cumulative_and_statistical_aggregations.yaml
index 15e451e6e09..e487b7502d7 100644
--- a/test_resources/serialization_baseline/collections/main/queries/cumulative_and_statistical_aggregations.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/cumulative_and_statistical_aggregations.yaml
@@ -207,7 +207,7 @@ result_metadata:
lib/source-column-alias: percentile
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: x61UtCMCuBNjw0TEFQeWG
label: cumulative_and_statistical_aggregations
diff --git a/test_resources/serialization_baseline/collections/main/queries/fields_and_expressions.yaml b/test_resources/serialization_baseline/collections/main/queries/fields_and_expressions.yaml
index 9de3527f8cf..6b0dc009df0 100644
--- a/test_resources/serialization_baseline/collections/main/queries/fields_and_expressions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/fields_and_expressions.yaml
@@ -165,7 +165,7 @@ result_metadata:
lib/source-column-alias: Profit
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: fLdExPr3sS10nS0ExAmPl
label: fields_and_expressions
diff --git a/test_resources/serialization_baseline/collections/main/queries/geographic_filter__inside_.yaml b/test_resources/serialization_baseline/collections/main/queries/geographic_filter__inside_.yaml
index f6b966809e7..6fd65c441e9 100644
--- a/test_resources/serialization_baseline/collections/main/queries/geographic_filter__inside_.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/geographic_filter__inside_.yaml
@@ -431,7 +431,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: bK64P6yr9_Nx-A8S3PqOZ
label: geographic_filter__inside_
diff --git a/test_resources/serialization_baseline/collections/main/queries/joins___strategies_and_compound_conditions.yaml b/test_resources/serialization_baseline/collections/main/queries/joins___strategies_and_compound_conditions.yaml
index 057ac6f83e0..ea8a8c672cf 100644
--- a/test_resources/serialization_baseline/collections/main/queries/joins___strategies_and_compound_conditions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/joins___strategies_and_compound_conditions.yaml
@@ -665,7 +665,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: wpW9JO5MsHQd0-7WrR7gN
label: joins___strategies_and_compound_conditions
diff --git a/test_resources/serialization_baseline/collections/main/queries/math_functions.yaml b/test_resources/serialization_baseline/collections/main/queries/math_functions.yaml
index 1158dcbaf52..f7f0babd413 100644
--- a/test_resources/serialization_baseline/collections/main/queries/math_functions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/math_functions.yaml
@@ -471,7 +471,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: jPrM-oh3r1BR42xSs4Ipj
label: math_functions
diff --git a/test_resources/serialization_baseline/collections/main/queries/metric__measure__and_segment_references.yaml b/test_resources/serialization_baseline/collections/main/queries/metric__measure__and_segment_references.yaml
index cbcf548fced..80f54986c5b 100644
--- a/test_resources/serialization_baseline/collections/main/queries/metric__measure__and_segment_references.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/metric__measure__and_segment_references.yaml
@@ -57,7 +57,7 @@ result_metadata:
lib/source-column-alias: count
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: kBjQ5VXJ5z3vYSW72J6qa
label: metric__measure__and_segment_references
diff --git a/test_resources/serialization_baseline/collections/main/queries/native_query___card_and_snippet_references.yaml b/test_resources/serialization_baseline/collections/main/queries/native_query___card_and_snippet_references.yaml
index ee1bd0a010f..c693f2bbbf3 100644
--- a/test_resources/serialization_baseline/collections/main/queries/native_query___card_and_snippet_references.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/native_query___card_and_snippet_references.yaml
@@ -32,7 +32,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: HiBFSt0BNx5s5MxVDLLKB
label: native_query___card_and_snippet_references
diff --git a/test_resources/serialization_baseline/collections/main/queries/native_query___field_filter_and_temporal_unit.yaml b/test_resources/serialization_baseline/collections/main/queries/native_query___field_filter_and_temporal_unit.yaml
index e00f718e7b4..102162045a6 100644
--- a/test_resources/serialization_baseline/collections/main/queries/native_query___field_filter_and_temporal_unit.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/native_query___field_filter_and_temporal_unit.yaml
@@ -59,7 +59,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: sk02d7sPWAk2TYH2Y7JhZ
label: native_query___field_filter_and_temporal_unit
diff --git a/test_resources/serialization_baseline/collections/main/queries/native_query___variables.yaml b/test_resources/serialization_baseline/collections/main/queries/native_query___variables.yaml
index 347536f04a5..0c0a2d130f2 100644
--- a/test_resources/serialization_baseline/collections/main/queries/native_query___variables.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/native_query___variables.yaml
@@ -46,7 +46,7 @@ dataset_query:
lib/type: mbql/query
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: 2u10n8GV6u0LFYrq8yV5p
label: native_query___variables
diff --git a/test_resources/serialization_baseline/collections/main/queries/nested_query.yaml b/test_resources/serialization_baseline/collections/main/queries/nested_query.yaml
index 3c76c930088..dc681d6b494 100644
--- a/test_resources/serialization_baseline/collections/main/queries/nested_query.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/nested_query.yaml
@@ -124,7 +124,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: 1t9TE-8T-AlaM19nx3yQV
label: nested_query
diff --git a/test_resources/serialization_baseline/collections/main/queries/null__empty__and_string_filters.yaml b/test_resources/serialization_baseline/collections/main/queries/null__empty__and_string_filters.yaml
index dde2f471ef1..f3d5dcd9ffe 100644
--- a/test_resources/serialization_baseline/collections/main/queries/null__empty__and_string_filters.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/null__empty__and_string_filters.yaml
@@ -419,7 +419,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: ZvHEBpdFQ-VSvem16KCkL
label: null__empty__and_string_filters
diff --git a/test_resources/serialization_baseline/collections/main/queries/source_card_reference.yaml b/test_resources/serialization_baseline/collections/main/queries/source_card_reference.yaml
index ac65f6df54a..be62247e4eb 100644
--- a/test_resources/serialization_baseline/collections/main/queries/source_card_reference.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/source_card_reference.yaml
@@ -205,7 +205,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: gt4OaWYAuDWRHn5Irnd4h
label: source_card_reference
diff --git a/test_resources/serialization_baseline/collections/main/queries/string_functions.yaml b/test_resources/serialization_baseline/collections/main/queries/string_functions.yaml
index 82f73928d8b..3b2ba3d0d18 100644
--- a/test_resources/serialization_baseline/collections/main/queries/string_functions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/string_functions.yaml
@@ -550,7 +550,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: HeLFZSVb4Jm25p4tWfVP9
label: string_functions
diff --git a/test_resources/serialization_baseline/collections/main/queries/temporal_and_logical_filters.yaml b/test_resources/serialization_baseline/collections/main/queries/temporal_and_logical_filters.yaml
index f3968b05093..27875035200 100644
--- a/test_resources/serialization_baseline/collections/main/queries/temporal_and_logical_filters.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/temporal_and_logical_filters.yaml
@@ -302,7 +302,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: BMx-SlSPsSfGSKaEgOzn0
label: temporal_and_logical_filters
diff --git a/test_resources/serialization_baseline/collections/main/queries/temporal_expressions.yaml b/test_resources/serialization_baseline/collections/main/queries/temporal_expressions.yaml
index 49b3b43b40a..e13e4a1ca5e 100644
--- a/test_resources/serialization_baseline/collections/main/queries/temporal_expressions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/temporal_expressions.yaml
@@ -462,7 +462,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: DBBrqcMAmOO0sbM_CzM_Z
label: temporal_expressions
diff --git a/test_resources/serialization_baseline/collections/main/queries/temporal_extraction.yaml b/test_resources/serialization_baseline/collections/main/queries/temporal_extraction.yaml
index 7747f077f74..ea48c4e31fc 100644
--- a/test_resources/serialization_baseline/collections/main/queries/temporal_extraction.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/temporal_extraction.yaml
@@ -705,7 +705,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: bDK7jyPszEHzHh4aG4_SV
label: temporal_extraction
diff --git a/test_resources/serialization_baseline/collections/main/queries/total_revenue.yaml b/test_resources/serialization_baseline/collections/main/queries/total_revenue.yaml
index 1b90b6de180..681c78339a9 100644
--- a/test_resources/serialization_baseline/collections/main/queries/total_revenue.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/total_revenue.yaml
@@ -41,7 +41,7 @@ result_metadata:
lib/source-column-alias: sum
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: IW8kbqZVaMxdGtCM2F4U6
label: total_revenue
diff --git a/test_resources/serialization_baseline/collections/main/queries/url_functions.yaml b/test_resources/serialization_baseline/collections/main/queries/url_functions.yaml
index 3ea41a6987d..1657e1705e9 100644
--- a/test_resources/serialization_baseline/collections/main/queries/url_functions.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/url_functions.yaml
@@ -538,7 +538,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: uwAeNRHymXTD1G_7lWV1d
label: url_functions
diff --git a/test_resources/serialization_baseline/collections/main/queries/window_function___offset.yaml b/test_resources/serialization_baseline/collections/main/queries/window_function___offset.yaml
index 9494ebcc343..d1bcc055d8e 100644
--- a/test_resources/serialization_baseline/collections/main/queries/window_function___offset.yaml
+++ b/test_resources/serialization_baseline/collections/main/queries/window_function___offset.yaml
@@ -108,7 +108,7 @@ result_metadata:
lib/source-column-alias: offset
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: ErQY8K5Tep4xBc3VY_-1e
label: window_function___offset
diff --git a/test_resources/serialization_baseline/collections/main/source_model.yaml b/test_resources/serialization_baseline/collections/main/source_model.yaml
index 950c55c7cda..72da689d68c 100644
--- a/test_resources/serialization_baseline/collections/main/source_model.yaml
+++ b/test_resources/serialization_baseline/collections/main/source_model.yaml
@@ -322,7 +322,7 @@ result_metadata:
qp/implicit-field?: true
visualization_settings:
column_settings: null
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: sRcMoDeL00ExAmPlEx001
label: source_model
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/customer_locations__map_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/customer_locations__map_.yaml
index c8d3952d26c..a57f2b33294 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/customer_locations__map_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/customer_locations__map_.yaml
@@ -451,7 +451,7 @@ visualization_settings:
map.pin_type: markers
map.type: pin
map.zoom: 4
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: CI61cHgBAKPBEDTxhK8X3
label: customer_locations__map_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/monthly_revenue_changes__waterfall_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/monthly_revenue_changes__waterfall_.yaml
index b6c6b1353f7..b229292a2ee 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/monthly_revenue_changes__waterfall_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/monthly_revenue_changes__waterfall_.yaml
@@ -88,7 +88,7 @@ visualization_settings:
waterfall.increase_color: '#88BF4D'
waterfall.show_total: true
waterfall.total_color: '#509EE3'
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: kJWYpTzyc9ow-75HjyIhf
label: monthly_revenue_changes__waterfall_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__pie_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__pie_.yaml
index 6dc797851f5..99af0a706e6 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__pie_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__pie_.yaml
@@ -88,7 +88,7 @@ visualization_settings:
pie.show_total: true
pie.slice_threshold: 2.5
version: 2
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: dYD1j3pQtJdctg8duByUL
label: orders_by_category__pie_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__stacked_bar_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__stacked_bar_.yaml
index 30c2dc663ad..420abbbcb9f 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__stacked_bar_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_by_category__stacked_bar_.yaml
@@ -118,7 +118,7 @@ visualization_settings:
graph.x_axis.title_text: Quarter
graph.y_axis.title_text: Order Count
stackable.stack_type: stacked
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: ciG63nSLHKRTImt5iWEte
label: orders_by_category__stacked_bar_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_pivot_table.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_pivot_table.yaml
index 4f173ae54fe..438e12a4e6e 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/orders_pivot_table.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/orders_pivot_table.yaml
@@ -144,7 +144,7 @@ visualization_settings:
- sum
pivot_table.show_column_totals: true
pivot_table.show_row_totals: true
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: BjwHr6elEuKQuL26BEgno
label: orders_pivot_table
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/products_table__formatted_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/products_table__formatted_.yaml
index f4a89d43ece..c7ce11839e1 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/products_table__formatted_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/products_table__formatted_.yaml
@@ -336,7 +336,7 @@ visualization_settings:
name: CREATED_AT
- enabled: false
name: EAN
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: Wo5d6IV8lb63wex29uh6H
label: products_table__formatted_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_gauge.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_gauge.yaml
index 90e9e8cc530..32890f2b82c 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_gauge.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_gauge.yaml
@@ -54,7 +54,7 @@ visualization_settings:
label: High
max: 300000
min: 150000
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: GWrIQqjbzxysSCm8PLU5j
label: revenue_gauge
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_over_time__line_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_over_time__line_.yaml
index 44086bee966..38d5d4edea6 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_over_time__line_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/revenue_over_time__line_.yaml
@@ -107,7 +107,7 @@ visualization_settings:
line.size: M
line.style: solid
show_series_values: true
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: UEWVldEEZ-3sYUjjN54qz
label: revenue_over_time__line_
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/sales_funnel.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/sales_funnel.yaml
index efc24777337..340b3d514da 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/sales_funnel.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/sales_funnel.yaml
@@ -79,7 +79,7 @@ visualization_settings:
funnel.dimension: CATEGORY
funnel.metric: count
funnel.type: funnel
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: mkKa6jf-QsuCRnaPOIsYh
label: sales_funnel
diff --git a/test_resources/serialization_baseline/collections/main/visualization_settings/total_revenue__smart_scalar_.yaml b/test_resources/serialization_baseline/collections/main/visualization_settings/total_revenue__smart_scalar_.yaml
index 12dc82b1852..08186d0f4d1 100644
--- a/test_resources/serialization_baseline/collections/main/visualization_settings/total_revenue__smart_scalar_.yaml
+++ b/test_resources/serialization_baseline/collections/main/visualization_settings/total_revenue__smart_scalar_.yaml
@@ -99,7 +99,7 @@ visualization_settings:
label: Monthly Target
type: staticNumber
value: 50000
-card_schema: 23
+card_schema: 24
serdes/meta:
- id: bSj47tilPIkwDIewvMf8z
label: total_revenue__smart_scalar_