The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix guest embed question downloads ignoring editable filters (#73553)
Sébastien52d30bc4a564
diff --git a/e2e/test-component/scenarios/embedding-sdk/guest-embed-reproductions.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/guest-embed-reproductions.cy.spec.tsxindex 62b5feb7c70..3a390ebea66 100644--- a/e2e/test-component/scenarios/embedding-sdk/guest-embed-reproductions.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/guest-embed-reproductions.cy.spec.tsx@@ -1,5 +1,8 @@+import type { Interception } from "cypress/types/net-stubbing";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import {+ createNativeQuestion,createQuestion,downloadAndAssert,getSignedJwtForResource,@@ -7,9 +10,12 @@ import {import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";import { mountGuestEmbedQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";import { signInAsAdminAndSetupGuestEmbedding } from "e2e/support/helpers/embedding-sdk-testing";-import type { Card } from "metabase-types/api";+import type { Card, TemplateTags } from "metabase-types/api";+import { createMockParameter } from "metabase-types/api/mocks";++const { ORDERS, ORDERS_ID, PRODUCTS } = SAMPLE_DATABASE;-const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;+const { H } = cy;describe("scenarios > embedding-sdk > guest-embed reproductions", () => {const setup = ({ display }: { display?: Card["display"] } = {}) => {@@ -86,4 +92,93 @@ describe("scenarios > embedding-sdk > guest-embed reproductions", () => {});});});++ it("should include the active editable filter in native question downloads (EMB-1549)", () => {+ signInAsAdminAndSetupGuestEmbedding({ token: "pro-cloud" });++ const TEMPLATE_TAGS: TemplateTags = {+ category: {+ id: "category",+ name: "category",+ "display-name": "Category",+ type: "dimension",+ "widget-type": "string/=",+ dimension: ["field", PRODUCTS.CATEGORY, null],+ },+ };++ const PARAMETERS = [+ createMockParameter({+ id: "category",+ name: "Category",+ slug: "category",+ type: "string/=",+ target: ["dimension", ["template-tag", "category"]],+ }),+ ];++ createNativeQuestion(+ {+ name: "EMB-1549 native question with editable filter",+ native: {+ query: "SELECT * FROM PRODUCTS WHERE {{category}}",+ "template-tags": TEMPLATE_TAGS,+ },+ parameters: PARAMETERS,+ enable_embedding: true,+ embedding_params: {+ category: "enabled",+ },+ },+ { wrapId: true },+ );++ cy.signOut();++ cy.get("@questionId").then(async (questionId) => {+ const token = await getSignedJwtForResource({+ resourceId: questionId as unknown as number,+ resourceType: "question",+ });++ mountGuestEmbedQuestion(+ { token, withDownloads: true },+ { shouldAssertCardQuery: false },+ );++ getSdkRoot()+ .findAllByTestId("parameter-widget")+ .button("Category")+ .click();++ H.popover().within(() => {+ cy.findByText("Widget").click();+ cy.findByText("Add filter").click();+ });++ getSdkRoot()+ .findAllByTestId("parameter-widget")+ .button("Category")+ .should("contain.text", "Widget");++ downloadAndAssert({+ isDashboard: false,+ isEmbed: true,+ enableFormatting: true,+ assertStatusCode: 200,+ waitForDismiss: false,+ fileType: "csv",+ downloadUrl: "/api/embed/card/*/query/csv*",+ downloadMethod: "GET",+ });++ cy.get<Interception>("@fileDownload").then((interception) => {+ const url = new URL(interception.request.url);+ const parameters = JSON.parse(+ url.searchParams.get("parameters") ?? "{}",+ );+ expect(parameters).to.deep.equal({ category: ["Widget"] });+ });+ });+ });});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsxindex f4625cc79e2..f90adae89c8 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx@@ -1,5 +1,6 @@import { useMemo } from "react";+import { getGuestEmbedFilteredParameters } from "embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters";import {QuestionDownloadWidget,type UseDownloadDataParams,@@ -24,7 +25,7 @@ const DownloadWidgetInner = ({...rest}: DownloadWidgetProps &Pick<UseDownloadDataParams, "question" | "result">) => {- const { withDownloads } = useSdkQuestionContext();+ const { withDownloads, parameterValues } = useSdkQuestionContext();const { token } = useEmbeddingEntityContext();const visualizationSettings = useMemo(@@ -35,10 +36,19 @@ const DownloadWidgetInner = ({[question, result],);+ // For Guest Embeds, downloads must honor the active editable filter state+ // (EMB-1549). The `params` slug-keyed map mirrors what `runQuestionQuerySdk`+ // sends for live results.+ const params = useMemo(+ () => getGuestEmbedFilteredParameters(question, parameterValues),+ [question, parameterValues],+ );+const [, handleDownload] = useDownloadData({question,result,token,+ params,visualizationSettings,});diff --git a/frontend/src/metabase/redux/downloads.ts b/frontend/src/metabase/redux/downloads.tsindex 6fdc946c192..9790cf15277 100644--- a/frontend/src/metabase/redux/downloads.ts+++ b/frontend/src/metabase/redux/downloads.ts@@ -324,40 +324,42 @@ const getEmbedDashcardParams = (}),});+const convertSearchParamsToObject = (params: URLSearchParams) => {+ const object: Record<string, string | string[]> = {};+ for (const [key, value] of params.entries()) {+ if (object[key]) {+ object[key] = ([] as string[]).concat(+ object[key] as string | string[],+ value,+ );+ } else {+ object[key] = value;+ }+ }++ return object;+};+const getEmbedQuestionParams = (token: EntityToken,type: string,+ params: Record<string, unknown>,exportParams: ExportParams,): DownloadQueryResultsParams => {- const params = isEmbeddingSdk()- ? // For SDK/EmbedJS we must not read params from location search as in both cases- // additional params are not supported by a public endpoint- null- : new URLSearchParams(window.location.search);-- const convertSearchParamsToObject = (params: URLSearchParams) => {- const object: Record<string, string | string[]> = {};- for (const [key, value] of params.entries()) {- if (object[key]) {- object[key] = ([] as string[]).concat(- object[key] as string | string[],- value,- );- } else {- object[key] = value;- }- }-- return object;- };+ // Guest Embed / Modular embedding SDK embeds receive parameter values via postMessage+ // from the host page, so window.location.search does not reflect the active+ // editable filter state. Fall back to the params provided by the caller.+ // Static embed iframes encode filter values in the iframe URL, so read them+ // from window.location.search.+ const downloadParameters = isEmbeddingSdk()+ ? params+ : convertSearchParamsToObject(new URLSearchParams(window.location.search));return {method: "GET",url: Urls.embedCard(token, type),params: new URLSearchParams({- ...(params && {- parameters: JSON.stringify(convertSearchParamsToObject(params)),- }),+ parameters: JSON.stringify(downloadParameters),..._.mapObject(exportParams, (value) => String(value)),}),};@@ -423,7 +425,7 @@ const getAdHocQuestionParams = (},});-const getDatasetParams = ({+export const getDatasetParams = ({type,question,dashboardId,@@ -494,7 +496,7 @@ const getDatasetParams = ({);}if (resourceType === "question" && token) {- return getEmbedQuestionParams(token, type, exportParams);+ return getEmbedQuestionParams(token, type, params, exportParams);}}diff --git a/frontend/src/metabase/redux/downloads.unit.spec.ts b/frontend/src/metabase/redux/downloads.unit.spec.tsindex 1fc1c1f73ef..a6876c88366 100644--- a/frontend/src/metabase/redux/downloads.unit.spec.ts+++ b/frontend/src/metabase/redux/downloads.unit.spec.ts@@ -1,8 +1,14 @@+import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";import api from "metabase/utils/api";import Question from "metabase-lib/v1/Question";-import { createMockCard } from "metabase-types/api/mocks";+import type { EntityToken } from "metabase-types/api/entity";+import { createMockCard, createMockDataset } from "metabase-types/api/mocks";-import { getChartFileName, getDatasetDownloadUrl } from "./downloads";+import {+ getChartFileName,+ getDatasetDownloadUrl,+ getDatasetParams,+} from "./downloads";describe("getDatasetResponse", () => {describe("normal deployment", () => {@@ -55,6 +61,74 @@ describe("getDatasetResponse", () => {});});+describe("getDatasetParams - embed question (token-based)", () => {+ const TOKEN = "fake.jwt.token" as EntityToken;+ const question = new Question(createMockCard({ id: 1 }), undefined);+ const result = createMockDataset();++ const setLocationSearch = (search: string) => {+ window.history.replaceState({}, "", `/${search}`);+ };++ afterEach(() => {+ jest.restoreAllMocks();+ setLocationSearch("");+ });++ it("uses caller-provided params for guest embeds (EMB-1549)", async () => {+ await mockIsEmbeddingSdk(true);+ setLocationSearch("?stale_param=stale");++ const downloadParams = getDatasetParams({+ type: "csv",+ question,+ result,+ token: TOKEN,+ params: { country: "Brazil", quarter: "Q1" },+ });++ const url = new URLSearchParams(downloadParams.params);+ expect(JSON.parse(url.get("parameters") ?? "")).toEqual({+ country: "Brazil",+ quarter: "Q1",+ });+ });++ it("falls back to window.location.search for static embed iframes", async () => {+ await mockIsEmbeddingSdk(false);+ setLocationSearch("?country=Brazil&quarter=Q1");++ const downloadParams = getDatasetParams({+ type: "csv",+ question,+ result,+ token: TOKEN,+ params: {},+ });++ const url = new URLSearchParams(downloadParams.params);+ expect(JSON.parse(url.get("parameters") ?? "")).toEqual({+ country: "Brazil",+ quarter: "Q1",+ });+ });++ it("sends an empty parameters object for guest embeds when no filter is set", async () => {+ await mockIsEmbeddingSdk(true);++ const downloadParams = getDatasetParams({+ type: "csv",+ question,+ result,+ token: TOKEN,+ params: {},+ });++ const url = new URLSearchParams(downloadParams.params);+ expect(JSON.parse(url.get("parameters") ?? "")).toEqual({});+ });+});+describe("getChartFileName", () => {beforeEach(() => {jest.useFakeTimers();