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(sdk): Accept an entity id as a target collection id for CreateQuestionModal (#64601)
Timofey Kachalov7e19ce967fa4
diff --git a/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsxindex 21f0f9c800e..1c209679300 100644--- a/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/create-question.cy.spec.tsx@@ -2,6 +2,8 @@ import { InteractiveQuestion } from "@metabase/embedding-sdk-react";import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import {+ ADMIN_PERSONAL_COLLECTION_ID,+ FIRST_COLLECTION_ENTITY_ID,FIRST_COLLECTION_ID,ORDERS_DASHBOARD_ID,} from "e2e/support/cypress_sample_instance_data";@@ -235,4 +237,55 @@ describe("scenarios > embedding-sdk > interactive-question > creating a questioncy.findAllByRole("link").should("have.length", MODEL_COUNT + TABLE_COUNT);});});++ [+ {+ targetCollectionId: "personal",+ respondedCollectionId: ADMIN_PERSONAL_COLLECTION_ID,+ },+ {+ targetCollectionId: FIRST_COLLECTION_ENTITY_ID,+ respondedCollectionId: FIRST_COLLECTION_ID,+ },+ ].forEach(({ targetCollectionId, respondedCollectionId }) => {+ it(`can create a question in a collection passing the \`${targetCollectionId}\` as a target collection id (metabase#64584)`, () => {+ cy.signOut();+ mockAuthProviderAndJwtSignIn();+ cy.intercept("POST", "/api/card").as("createCard");++ mountSdkContent(+ <Flex p="xl">+ <InteractiveQuestion+ questionId="new"+ targetCollection={targetCollectionId}+ />+ </Flex>,+ );++ assertSdkNotebookEditorUsable();++ getSdkRoot().within(() => {+ // Should be able to save to a new question right away+ cy.findByRole("button", { name: "Save" }).click();+ });++ modal().within(() => {+ cy.findByPlaceholderText("What is the name of your question?")+ .clear()+ .type("My Orders");+ });++ modal().button("Save").click();++ cy.wait("@createCard").then(({ response }) => {+ expect(response?.statusCode).to.equal(200);+ expect(response?.body.name).to.equal("My Orders");+ expect(response?.body?.dashboard_id).to.equal(null);+ expect(response?.body?.collection_id).to.equal(respondedCollectionId);+ });++ // The question title's header should be updated.+ getSdkRoot().contains("My Orders");+ });+ });});diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.tsindex 7505288fadc..79fc5c4633a 100644--- a/frontend/src/metabase/collections/utils.ts+++ b/frontend/src/metabase/collections/utils.ts@@ -1,11 +1,12 @@import { t } from "ttag";import { PLUGIN_COLLECTIONS } from "metabase/plugins";-import type {- Collection,- CollectionEssentials,- CollectionId,- CollectionItem,+import {+ type Collection,+ type CollectionEssentials,+ type CollectionId,+ type CollectionItem,+ isBaseEntityID,} from "metabase-types/api";export function nonPersonalOrArchivedCollection(@@ -238,6 +239,16 @@ export function canonicalCollectionId(}}+export function canonicalCollectionIdOrEntityId(+ collectionId: string | number | null | undefined,+): number | string | null {+ if (isBaseEntityID(collectionId)) {+ return collectionId;+ }++ return canonicalCollectionId(collectionId);+}+export function isValidCollectionId(collectionId: unknown,): collectionId is CollectionId {diff --git a/frontend/src/metabase/collections/utils.unit.spec.ts b/frontend/src/metabase/collections/utils.unit.spec.tsindex 4c6422f8b8d..4119524b2b5 100644--- a/frontend/src/metabase/collections/utils.unit.spec.ts+++ b/frontend/src/metabase/collections/utils.unit.spec.ts@@ -1,5 +1,6 @@import {canonicalCollectionId,+ canonicalCollectionIdOrEntityId,getCollectionPathAsString,isExamplesCollection,isItemCollection,@@ -101,6 +102,10 @@ describe("Collections > utils", () => {expect(canonicalCollectionId("root")).toBe(null);});+ it("returns NaN if the collection id is entity id", () => {+ expect(canonicalCollectionId("HPAvJNTD9XTRkwJZUX9Fz")).toBe(NaN);+ });+it("returns null if the collection id is null or undefined", () => {expect(canonicalCollectionId(null)).toBe(null);/* @ts-expect-error checking if a race condition not returning expected data behaves as expected */@@ -108,6 +113,34 @@ describe("Collections > utils", () => {});});+ describe("canonicalCollectionIdOrEntityId", () => {+ it("returns the id of the collection if it is not a root collection", () => {+ expect(canonicalCollectionIdOrEntityId(1337)).toBe(1337);+ expect(canonicalCollectionIdOrEntityId(1)).toBe(1);+ });++ it("handles string id inputs", () => {+ expect(canonicalCollectionIdOrEntityId("1337")).toBe(1337);+ expect(canonicalCollectionIdOrEntityId("1")).toBe(1);+ });++ it('returns null if the collection id is "root"', () => {+ expect(canonicalCollectionIdOrEntityId("root")).toBe(null);+ });++ it("returns the id of the collection if the collection id is entity id", () => {+ expect(canonicalCollectionIdOrEntityId("HPAvJNTD9XTRkwJZUX9Fz")).toBe(+ "HPAvJNTD9XTRkwJZUX9Fz",+ );+ });++ it("returns null if the collection id is null or undefined", () => {+ expect(canonicalCollectionIdOrEntityId(null)).toBe(null);+ /* @ts-expect-error checking if a race condition not returning expected data behaves as expected */+ expect(canonicalCollectionIdOrEntityId()).toBe(null);+ });+ });+describe("isRootCollection", () => {it("returns true if the collection is the root collection", () => {/* @ts-expect-error the null id should have been coerced to 'root' but lets make sure this still doesn't blow up */diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts b/frontend/src/metabase/common/components/SaveQuestionForm/util.tsindex 2d5722736da..2369166c152 100644--- a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts+++ b/frontend/src/metabase/common/components/SaveQuestionForm/util.ts@@ -1,7 +1,10 @@import { P, match } from "ts-pattern";import { t } from "ttag";-import { canonicalCollectionId } from "metabase/collections/utils";+import {+ canonicalCollectionId,+ canonicalCollectionIdOrEntityId,+} from "metabase/collections/utils";import { isNullOrUndefined } from "metabase/lib/types";import type Question from "metabase-lib/v1/Question";import type { CardType } from "metabase-types/api";@@ -37,7 +40,7 @@ export const createQuestion = async (options: CreateQuestionOptions) => {// `targetCollection` is used to override the target collection of the question,// this is mainly used for the embedding SDK.- const collectionId = canonicalCollectionId(+ const collectionId = canonicalCollectionIdOrEntityId(isNullOrUndefined(targetCollection)? details.collection_id: targetCollection,diff --git a/src/metabase/queries/api/card.clj b/src/metabase/queries/api/card.cljindex c5eef3409db..9e7f0067dca 100644--- a/src/metabase/queries/api/card.clj+++ b/src/metabase/queries/api/card.clj@@ -503,7 +503,7 @@[:description {:optional true} [:maybe ms/NonBlankString]][:display ms/NonBlankString][:visualization_settings ms/Map]- [:collection_id {:optional true} [:maybe ms/PositiveInt]]+ [:collection_id {:optional true} [:maybe [:or ms/PositiveInt ms/NanoIdString]]][:collection_position {:optional true} [:maybe ms/PositiveInt]][:result_metadata {:optional true} [:maybe analyze/ResultsMetadata]][:cache_ttl {:optional true} [:maybe ms/PositiveInt]]@@ -514,8 +514,11 @@"Create a new `Card`. Card `type` can be `question`, `metric`, or `model`."[_route-params_query-params- {card-type :type, :as card} :- CardCreateSchema]- (let [card (update card :dataset_query lib-be/normalize-query)+ {card-type :type, collection-id :collection_id, :as card} :- CardCreateSchema]+ (let [card (-> card+ (update :dataset_query lib-be/normalize-query)+ (cond-> (some? collection-id)+ (update :collection_id #(eid-translation/->id-or-404 :collection %))))query (:dataset_query card)](check-if-card-can-be-saved query card-type);; check that we have permissions to run the query that we're trying to savediff --git a/test/metabase/queries/api/card_test.clj b/test/metabase/queries/api/card_test.cljindex 6a4797d9da7..7fb8e8d46e8 100644--- a/test/metabase/queries/api/card_test.clj+++ b/test/metabase/queries/api/card_test.clj@@ -1162,6 +1162,75 @@:collection_position 1}(t2/select-one :model/Card :name card-name)))))))))+(deftest create-card-with-entity-id-as-collection-id-test+ (testing "POST /api/card with entity ID as collection_id"+ (testing "Should be able to create a Card using collection entity ID"+ (mt/with-non-admin-groups-no-root-collection-perms+ (let [card-name (mt/random-name)]+ (mt/with-temp [:model/Collection collection {}]+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)+ (mt/with-model-cleanup [:model/Card]+ (let [collection-entity-id (:entity_id collection)+ created-card (mt/user-http-request :rasta :post 200 "card"+ (assoc (card-with-name-and-query card-name)+ :collection_id collection-entity-id))]+ (testing "Card should be created successfully"+ (is (=? {:collection_id (u/the-id collection)+ :name card-name}+ created-card)))+ (testing "Card should be saved with numeric collection_id in database"+ (is (=? {:collection_id (u/the-id collection)}+ (t2/select-one :model/Card :name card-name))))))))))))++(deftest create-card-with-entity-id-and-nil-collection-id-test+ (testing "POST /api/card with nil collection_id should work (root collection)"+ (mt/with-non-admin-groups-no-root-collection-perms+ (let [card-name (mt/random-name)]+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection/root-collection)+ (mt/with-model-cleanup [:model/Card]+ (let [created-card (mt/user-http-request :rasta :post 200 "card"+ (assoc (card-with-name-and-query card-name)+ :collection_id nil))]+ (testing "Card should be created successfully in root collection"+ (is (=? {:collection_id nil+ :name card-name}+ created-card)))+ (testing "Card should be saved with nil collection_id in database"+ (is (=? {:collection_id nil}+ (t2/select-one :model/Card :name card-name))))))))))++(deftest create-card-with-entity-id-and-position-test+ (testing "POST /api/card with entity ID as collection_id and collection_position"+ (mt/with-non-admin-groups-no-root-collection-perms+ (let [card-name (mt/random-name)]+ (mt/with-temp [:model/Collection collection {}]+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)+ (mt/with-model-cleanup [:model/Card]+ (let [collection-entity-id (:entity_id collection)+ created-card (mt/user-http-request :rasta :post 200 "card"+ (assoc (card-with-name-and-query card-name)+ :collection_id collection-entity-id+ :collection_position 1))]+ (testing "Card should be created with correct collection and position"+ (is (=? {:collection_id (u/the-id collection)+ :collection_position 1+ :name card-name}+ created-card)))+ (testing "Card should be saved correctly in database"+ (is (=? {:collection_id (u/the-id collection)+ :collection_position 1}+ (t2/select-one :model/Card :name card-name)))))))))))++(deftest create-card-with-invalid-entity-id-test+ (testing "POST /api/card with invalid entity ID should return 400"+ (mt/with-model-cleanup [:model/Card]+ (let [invalid-entity-id "invalid_entity_id_12345"+ response (mt/user-http-request :crowberto :post 400 "card"+ (assoc (card-with-name-and-query)+ :collection_id invalid-entity-id))]+ (testing "Should get 400 for malformed entity ID"+ (is (contains? (:errors response) :collection_id)))))))+(deftest need-permission-for-collection(testing "You need to have Collection permissions to create a Card in a Collection"(mt/with-non-admin-groups-no-root-collection-perms