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
feat(sdk, embedjs): support saving and editing questions created with metabot (#68950)
Sébastien5558eeabedd3
diff --git a/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsxindex 007c091eabc..0079611800c 100644--- a/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/metabot-question.cy.spec.tsx@@ -1,6 +1,9 @@const { H } = cy;-import { MetabotQuestion } from "@metabase/embedding-sdk-react";+import {+ InteractiveQuestion,+ MetabotQuestion,+} from "@metabase/embedding-sdk-react";import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";@@ -41,6 +44,7 @@ describe("scenarios > embedding-sdk > metabot-question", () => {body: response,});+ cy.log("Create a question");H.createQuestion({name: "1",query: {@@ -54,6 +58,14 @@ describe("scenarios > embedding-sdk > metabot-question", () => {cy.wrap(question.entity_id).as("questionEntityId");});+ cy.log("Create a collection");+ cy.request("POST", "/api/collection", {+ name: "first_collection",+ description: "First collection",+ }).then(({ body }) => {+ cy.wrap(body.id).as("collectionId");+ });+cy.signOut();mockAuthProviderAndJwtSignIn();};@@ -70,6 +82,43 @@ describe("scenarios > embedding-sdk > metabot-question", () => {});});+ it("should allow saving a question", () => {+ cy.intercept("POST", "/api/card").as("postCard");++ setup(metabotResponseWithNavigateTo);++ cy.get("@collectionId").then((collectionId) => {+ mountSdkContent(+ <MetabotQuestion isSaveEnabled targetCollection={collectionId} />,+ );++ getSdkRoot().within(() => {+ cy.findByTestId("metabot-chat-input").type("Show orders {enter}");++ cy.findByTestId("visualization-root").should("exist");++ cy.findByText("Save").should("be.visible").click();++ H.modal().within(() => {+ cy.findByText("Save new question").should("be.visible");+ cy.findByRole("button", { name: "Save" }).click();+ });+ });++ cy.wait("@postCard").then((interception) => {+ const response = interception.response?.body;+ const questionId = response.id;++ mountSdkContent(<InteractiveQuestion questionId={questionId} />);+ getSdkRoot().within(() => {+ cy.findByText(+ "Orders, Max of Quantity, Grouped by Product ID, 2 rows",+ ).should("be.visible");+ });+ });+ });+ });+it("should show the ad-hoc question when clicking its link", () => {setup(metabotResponse);diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.tsindex e1a0ea56271..1e8fc9ad4da 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-elements-api.cy.spec.ts@@ -437,6 +437,88 @@ describe("scenarios > embedding > sdk iframe embedding > custom elements api", (.findAllByText("AI isn't perfect. Double-check results.").should("be.visible");});++ describe("saving a metabot question", () => {+ const query = {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ };+ const adHocQuestionPath = `/question#${btoa(+ JSON.stringify({+ dataset_query: { database: 1, type: "query", query },+ display: "table",+ displayIsLocked: true,+ visualization_settings: {},+ }),+ )}`;++ const metabotResponse = `0:"Here is the [question link](${adHocQuestionPath})"`;+ const metabotResponseWithNavigateTo = `${metabotResponse}+ 2:{"type":"navigate_to","version":1,"value":"${adHocQuestionPath}"}`;++ it("should allow to save a new question", () => {+ H.mockMetabotResponse({+ statusCode: 200,+ body: metabotResponseWithNavigateTo,+ });++ cy.intercept("POST", "http://localhost:4000/api/card").as("postCard");++ cy.log("Create a collection");+ cy.request("POST", "/api/collection", {+ name: "first_collection",+ description: "First collection",+ parent_id: undefined,+ }).then(({ body }) => {+ cy.log("Visit an embed metabase-metabot");+ H.visitCustomHtmlPage(`+ ${H.getNewEmbedScriptTag()}+ ${H.getNewEmbedConfigurationScript()}+ <metabase-metabot is-save-enabled="true" target-collection="${body.id}" />+ `);++ H.getSimpleEmbedIframeContent().within(() => {+ cy.log("Ask a Metabot to create a question");+ // the question doesn't matter, we're stubbing the response+ cy.findByPlaceholderText("Ask AI a question...").type(+ "Show me something{enter}",+ );++ cy.findByText("question link").click();++ cy.findByText("Max of Quantity by Product ID").should("be.visible");++ cy.log("Save the question");+ cy.findByRole("button", { name: "Save" })+ .should("be.visible")+ .click();++ H.modal().within(() => {+ cy.findByText("Save new question").should("be.visible");+ cy.findByRole("button", { name: "Save" }).click();+ });+ });++ cy.wait("@postCard").then((interception) => {+ const response = interception.response?.body;+ const questionId = response.id;++ cy.log("Open the question");+ H.visitQuestion(questionId)?.then(() => {+ // Name of the collection should be visible at the top of the page+ // findAllBy because there are two "first_collection", one in the sidebar and one at the top+ cy.findAllByText("first_collection").first().should("be.visible");+ // Name of the new question should be visible too+ cy.findByText(+ "Orders, Max of Quantity, Grouped by Product ID, 2 rows",+ ).should("be.visible");+ });+ });+ });+ });+ });});describe("common checks", () => {diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.schema.ts b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.schema.tsindex 48213b1bcaa..edbe522cc6a 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.schema.ts+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.schema.ts@@ -12,6 +12,8 @@ const propsSchema: Yup.SchemaOf<MetabotQuestionProps> = Yup.object({layout: Yup.mixed<"auto" | "sidebar" | "stacked">().oneOf(["auto", "sidebar", "stacked"]).optional(),+ isSaveEnabled: Yup.mixed().optional(),+ targetCollection: Yup.mixed().optional(),});export const metabotQuestionSchema: FunctionSchema = { input: [propsSchema] };diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsxindex 48144b6faa3..a834627f01f 100644--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx@@ -36,6 +36,8 @@ const MetabotQuestionInner = ({className,style,layout = "auto",+ isSaveEnabled = false,+ targetCollection,}: MetabotQuestionProps) => {const { isLocaleLoading } = useLocale();const { navigateToPath } = useMetabotReactions();@@ -68,7 +70,8 @@ const MetabotQuestionInner = ({<SdkAdHocQuestionquestionPath={navigateToPath}title={false}- isSaveEnabled={false}+ isSaveEnabled={isSaveEnabled}+ targetCollection={targetCollection}><SdkQuestionDefaultViewheight="100%"diff --git a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/types.ts b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/types.tsindex 0cd8ff1b97f..b841c9bfe91 100644--- a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/types.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/types.ts@@ -1,5 +1,6 @@import type { CSSProperties } from "react";+import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";/**@@ -28,4 +29,14 @@ export interface MetabotQuestionProps extends CommonStylingProps {* A number or string specifying a CSS size value that specifies the width of the component*/width?: CSSProperties["width"];++ /**+ * Whether to show the save button.+ */+ isSaveEnabled?: boolean;++ /**+ * The collection to save the question to. This will hide the collection picker from the save modal.+ */+ targetCollection?: SdkCollectionId;}diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex a6663275202..484c713e33b 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -275,6 +275,8 @@ const SdkIframeEmbedView = ({<MetabotQuestionkey={rerenderKey}layout={settings.layout}+ isSaveEnabled={settings.isSaveEnabled}+ targetCollection={settings.targetCollection}height="100%"/>),diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.tsindex 624bf56a5b8..eff9085461e 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts@@ -66,7 +66,11 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"withNewQuestion","withNewDashboard",] satisfies (keyof BrowserEmbedOptions)[],- metabot: ["layout"] satisfies (keyof MetabotEmbedOptions)[],+ metabot: [+ "layout",+ "isSaveEnabled",+ "targetCollection",+ ] satisfies (keyof MetabotEmbedOptions)[],} as const;export const ALLOWED_GUEST_EMBED_SETTING_KEYS_MAP = {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.tsindex c7a2e95b510..aad5eff23b9 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts@@ -533,6 +533,8 @@ const MetabaseManageContentElement = createCustomElement("metabase-browser", [const MetabaseMetabotElement = createCustomElement("metabase-metabot", ["layout",+ "is-save-enabled",+ "target-collection",]);// Expose the old API that's still used in the tests, we'll probably remove this api unless customers prefer itdiff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.tsindex be64ea22a75..ea9146e08d2 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts@@ -163,6 +163,16 @@ export interface MetabotEmbedOptions {/** Layout mode for the metabot interface */layout?: "auto" | "sidebar" | "stacked";+ /**+ * The collection to save a question to+ */+ targetCollection?: CollectionId;++ /**+ * Whether the save button is enabled+ */+ isSaveEnabled?: boolean;+// incompatible optionstemplate?: never;questionId?: never;