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 admins unable to browse shared collections in question picker (#72086)
Phoomparin Manoee5d17282f54
diff --git a/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.tsindex d50d4edc27d..9a1470ca7e7 100644--- a/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts+++ b/e2e/test/scenarios/organization/entity-picker-shared-tenant-collection.cy.spec.ts@@ -1,6 +1,9 @@const { H } = cy;+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";+const { ORDERS_ID } = SAMPLE_DATABASE;+const TENANT_ROOT_NAME = "Shared collections";const TENANT_NAMESPACE = "shared-tenant-collection";@@ -349,4 +352,118 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na});});});++ describe("dashboard edit question picker sidebar", () => {+ it("should not show shared collections when tenants are disabled", () => {+ setupTenantCollections().then(() => {+ H.updateSetting("use-tenants", false);++ H.createDashboard({+ name: "Test Dashboard",+ }).then(({ body: dashboard }) => {+ H.visitDashboard(dashboard.id);+ H.editDashboard();+ H.openQuestionsSidebar();++ H.sidebar().findByText(TENANT_ROOT_NAME).should("not.exist");++ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Our analytics");++ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("not.contain", "Collections");+ });+ });+ });++ it("should allow admins to browse shared collections via breadcrumbs and add questions", () => {+ setupTenantCollections().then(({ tenantCollectionId }) => {+ H.createQuestion({+ name: "Tenant Orders Question",+ collection_id: tenantCollectionId,+ query: { "source-table": ORDERS_ID },+ });++ H.createDashboard({+ name: "Test Dashboard",+ }).then(({ body: dashboard }) => {+ H.visitDashboard(dashboard.id);+ H.editDashboard();+ H.openQuestionsSidebar();++ cy.log(+ "breadcrumb should show 'Collections' as the top level as shared collections exist",+ );+ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Collections")+ .and("contain", "Our analytics");++ cy.log("navigate to the top level to see both namespaces");+ H.sidebar()+ .findByTestId("breadcrumbs")+ .findByText("Collections")+ .click();++ H.sidebar().findByText("Our analytics").should("be.visible");+ H.sidebar().findByText(TENANT_ROOT_NAME).should("be.visible");++ H.sidebar().findByText(TENANT_ROOT_NAME).click();+ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Collections")+ .and("contain", TENANT_ROOT_NAME);++ H.sidebar().findByText("Test Tenant Collection").click();+ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Collections")+ .and("contain", TENANT_ROOT_NAME)+ .and("contain", "Test Tenant Collection");++ H.sidebar().findByText("Tenant Orders Question").click();+ H.getDashboardCards().should("have.length", 1);+ });+ });+ });++ it("should show 'Collections' in breadcrumb when navigating into Our Analytics sub-collections", () => {+ setupTenantCollections().then(() => {+ H.createCollection({ name: "Our Analytics Sub" }).then(() => {+ H.createDashboard({ name: "Test Dashboard" }).then(+ ({ body: dashboard }) => {+ H.visitDashboard(dashboard.id);+ H.editDashboard();+ H.openQuestionsSidebar();++ cy.log("navigate to top level");+ H.sidebar()+ .findByTestId("breadcrumbs")+ .findByText("Collections")+ .click();++ cy.log("navigate into Our Analytics");+ H.sidebar().findByText("Our analytics").click();++ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Collections")+ .and("contain", "Our analytics");++ cy.log("navigate into a sub-collection under our analytics");+ H.sidebar().findByText("Our Analytics Sub").click();++ H.sidebar()+ .findByTestId("breadcrumbs")+ .should("contain", "Collections")+ .and("contain", "Our analytics")+ .and("contain", "Our Analytics Sub");+ },+ );+ });+ });+ });+ });});diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsxindex 00f23b6d6b2..133008b1f58 100644--- a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx@@ -27,6 +27,11 @@ import type { Collection, CollectionId } from "metabase-types/api";import { QuestionList } from "./QuestionList";import S from "./QuestionPicker.module.css";import { addDashboardQuestion } from "./actions";+import {+ COLLECTIONS_TOP_LEVEL_ID,+ SHARED_TENANT_COLLECTIONS_ROOT_ID,+ useCollectionsWithTenants,+} from "./hooks/use-collections-with-tenants";interface QuestionPickerInnerProps {onSelect: BaseSelectListItemProps["onSelect"];@@ -35,7 +40,7 @@ interface QuestionPickerInnerProps {function QuestionPickerInner({onSelect,- collectionsById,+ collectionsById: baseCollectionsById,}: QuestionPickerInnerProps) {const dispatch = useDispatch();const dashboard = useSelector(getDashboard);@@ -49,6 +54,11 @@ function QuestionPickerInner({SEARCH_DEBOUNCE_DURATION,);+ const collectionsById = useCollectionsWithTenants(baseCollectionsById);++ const isAtTopLevel = currentCollectionId === COLLECTIONS_TOP_LEVEL_ID;+ const isAtSharedTenantRoot =+ currentCollectionId === SHARED_TENANT_COLLECTIONS_ROOT_ID;const collection = collectionsById[currentCollectionId];const crumbs = getCollectionBreadCrumbs(collection,@@ -143,13 +153,18 @@ function QuestionPickerInner({</>)}- <QuestionList- hasCollections={collections.length > 0}- searchText={debouncedSearchText}- collectionId={currentCollectionId}- onSelect={onSelect}- showOnlyPublicCollections={showOnlyPublicCollections}- />+ {/* Hide the question list at top-level "Collections"+ and "Shared collections" root. These have fake IDs that don't map to+ real collections, so querying questions against them would fail. */}+ {((!isAtSharedTenantRoot && !isAtTopLevel) || debouncedSearchText) && (+ <QuestionList+ hasCollections={collections.length > 0}+ searchText={debouncedSearchText}+ collectionId={currentCollectionId}+ onSelect={onSelect}+ showOnlyPublicCollections={showOnlyPublicCollections}+ />+ )}</div>);}diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.tsnew file mode 100644index 00000000000..cf519dc1e16--- /dev/null+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.ts@@ -0,0 +1,205 @@+import { useMemo } from "react";+import { t } from "ttag";++import { skipToken, useListCollectionsTreeQuery } from "metabase/api";+import { useSetting } from "metabase/common/hooks/use-setting";+import { ROOT_COLLECTION } from "metabase/entities/collections";+import getExpandedCollectionsById from "metabase/entities/collections/getExpandedCollectionsById";+import { PLUGIN_TENANTS } from "metabase/plugins";+import { getUserPersonalCollectionId } from "metabase/selectors/user";+import { useSelector } from "metabase/utils/redux";+import type { Collection, CollectionId } from "metabase-types/api";++// getExpandedCollectionsById produces path as CollectionId[] at runtime,+// but ExpandedCollection types it as string, so we use a corrected type.+export type ExpandedCollectionNode = Collection & {+ path: CollectionId[] | null;+ parent: Collection | null;+ children: Collection[];+ is_personal?: boolean;+};++export const SHARED_TENANT_COLLECTIONS_ROOT_ID =+ "shared-tenant-collections-root" as CollectionId;++export const COLLECTIONS_TOP_LEVEL_ID = "collections-top-level" as CollectionId;++/**+ * When tenants are enabled, fetches shared tenant collections and merges them+ * into the collectionsById map so they appear as a top-level browsable entry.+ *+ * The tree structure becomes:+ * Collections (top level)+ * ├── Our analytics (root collection)+ * └── Shared collections (synthetic root for shared collections)+ * ├── Shared collection A+ * └── Shared collection B+ */+export function useCollectionsWithTenants(+ collectionsById: Record<CollectionId, Collection>,+): Record<CollectionId, Collection> {+ const useTenants = useSetting("use-tenants");+ const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);+ const isTenantsActive = useTenants && PLUGIN_TENANTS.isEnabled;++ const { data: sharedTenantCollections } = useListCollectionsTreeQuery(+ isTenantsActive+ ? {+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ "exclude-archived": true,+ }+ : skipToken,+ );++ return useMemo(() => {+ if (!isTenantsActive || !sharedTenantCollections?.length) {+ return collectionsById;+ }++ const sharedCollectionsById = getExpandedCollectionsById(+ sharedTenantCollections,+ userPersonalCollectionId,+ ) as Record<CollectionId, ExpandedCollectionNode>;++ const displayName =+ PLUGIN_TENANTS.getNamespaceDisplayName(+ PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ ) ?? "";++ return mergeSharedCollections(+ collectionsById,+ sharedCollectionsById,+ displayName,+ );+ }, [+ isTenantsActive,+ sharedTenantCollections,+ collectionsById,+ userPersonalCollectionId,+ ]);+}++/**+ * Merge shared tenant collections into the base collections map,+ * creating a top-level "Collections" node that contains both+ * "Our analytics" and "Shared collections" as siblings.+ */+export function mergeSharedCollections(+ baseCollectionsById: Record<CollectionId, Collection>,+ sharedCollectionsById: Record<CollectionId, ExpandedCollectionNode>,+ displayName: string,+): Record<CollectionId, Collection> {+ const sharedRoot = sharedCollectionsById[ROOT_COLLECTION.id];+ const rootCollection = baseCollectionsById[+ ROOT_COLLECTION.id+ ] as ExpandedCollectionNode;++ // Create the top-level "Collections" node that parents both namespaces+ const syntheticTopLevel: ExpandedCollectionNode = {+ id: COLLECTIONS_TOP_LEVEL_ID,+ name: t`Collections`,+ description: null,+ can_write: false,+ can_restore: false,+ can_delete: false,+ namespace: null,+ location: null,+ path: [],+ parent: null,+ children: [],+ };++ // Create the shared collections synthetic root as a sibling of Our analytics+ const sharedSyntheticRoot: ExpandedCollectionNode = {+ id: SHARED_TENANT_COLLECTIONS_ROOT_ID,+ name: displayName,+ description: null,+ can_write: false,+ can_restore: false,+ can_delete: false,+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,+ location: null,+ path: [COLLECTIONS_TOP_LEVEL_ID],+ parent: syntheticTopLevel,+ children: (sharedRoot?.children ?? []).map((child) => ({+ ...child,+ parent: null,+ })) as ExpandedCollectionNode[],+ };++ // Fix circular parent reference now that sharedSyntheticRoot exists+ sharedSyntheticRoot.children = sharedSyntheticRoot.children.map((child) => ({+ ...child,+ parent: sharedSyntheticRoot,+ })) as ExpandedCollectionNode[];++ // Wire up the top-level children+ syntheticTopLevel.children = [rootCollection, sharedSyntheticRoot];++ const mergedCollectionsById = { ...baseCollectionsById };++ // Rewrite root collection to point to top-level parent+ mergedCollectionsById[ROOT_COLLECTION.id] = {+ ...rootCollection,+ path: [COLLECTIONS_TOP_LEVEL_ID],+ parent: syntheticTopLevel,+ } as ExpandedCollectionNode;++ // Merge shared collections with rewritten paths+ for (const [id, collection] of Object.entries(sharedCollectionsById)) {+ if (id === String(ROOT_COLLECTION.id)) {+ continue;+ }++ mergedCollectionsById[id as CollectionId] = {+ ...collection,++ // Rewrite path: Collections > Shared collections > ...+ path: collection.path+ ? [+ COLLECTIONS_TOP_LEVEL_ID,+ SHARED_TENANT_COLLECTIONS_ROOT_ID,+ ...collection.path.filter(+ (pathId) => pathId !== ROOT_COLLECTION.id,+ ),+ ]+ : null,++ // This loop only processes sharedCollectionsById (tenant collections),+ // never baseCollectionsById (Our Analytics collections), so there is no risk+ // of re-parenting "Our Analytics" sub-collections here.+ parent:+ collection.parent?.id === ROOT_COLLECTION.id+ ? sharedSyntheticRoot+ : collection.parent,+ } as ExpandedCollectionNode;+ }++ // Rewrite paths for all base collections (children of Our Analytics / root)+ // so that "Collections" appears at the top of the breadcrumb when navigating+ // into sub-collections under Our Analytics.+ for (const [id, collection] of Object.entries(baseCollectionsById)) {+ if (id === String(ROOT_COLLECTION.id)) {+ continue; // already rewritten above+ }++ const collectionNode = collection as ExpandedCollectionNode;++ if (!collectionNode.path) {+ continue;+ }++ mergedCollectionsById[id as CollectionId] = {+ ...collectionNode,+ // Rewrite path: Collections > Our Analytics > ...+ path: [COLLECTIONS_TOP_LEVEL_ID, ...collectionNode.path],+ } as ExpandedCollectionNode;+ }++ mergedCollectionsById[SHARED_TENANT_COLLECTIONS_ROOT_ID] =+ sharedSyntheticRoot;++ mergedCollectionsById[COLLECTIONS_TOP_LEVEL_ID] = syntheticTopLevel;++ return mergedCollectionsById;+}diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.unit.spec.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.unit.spec.tsnew file mode 100644index 00000000000..f448402cafd--- /dev/null+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/hooks/use-collections-with-tenants.unit.spec.ts@@ -0,0 +1,261 @@+import { setupEnterprisePlugins } from "__support__/enterprise";+import { setupCollectionTreeEndpoint } from "__support__/server-mocks/collection";+import { mockSettings } from "__support__/settings";+import { renderHookWithProviders, waitFor } from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/entities/collections";+import { createMockState } from "metabase/redux/store/mocks";+import type { Collection, CollectionId } from "metabase-types/api";+import {+ createMockCollection,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import {+ COLLECTIONS_TOP_LEVEL_ID,+ type ExpandedCollectionNode,+ SHARED_TENANT_COLLECTIONS_ROOT_ID,+ mergeSharedCollections,+ useCollectionsWithTenants,+} from "./use-collections-with-tenants";++const createMockExpandedCollection = (+ overrides: Partial<Collection> & { path?: CollectionId[] | null },+): Collection & {+ parent: Collection | null;+ path: CollectionId[];+ children: Collection[];+} => ({+ ...createMockCollection(overrides),+ path: overrides.path ?? [],+ parent: null,+ children: [],+ is_personal: false,+});++function setupHook({+ useTenants = false,+ sharedCollections = [] as Collection[],+} = {}) {+ setupCollectionTreeEndpoint(sharedCollections);++ const baseRoot = createMockExpandedCollection({+ ...ROOT_COLLECTION,+ path: [],+ });++ const collectionsById = {+ [ROOT_COLLECTION.id]: baseRoot,+ } as Record<CollectionId, Collection>;++ return renderHookWithProviders(+ () => useCollectionsWithTenants(collectionsById),+ {+ storeInitialState: createMockState({+ settings: mockSettings({+ "use-tenants": useTenants,+ "token-features": createMockTokenFeatures({ tenants: true }),+ }),+ }),+ },+ );+}++describe("useCollectionsWithTenants", () => {+ beforeAll(() => {+ mockSettings({+ "token-features": createMockTokenFeatures({ tenants: true }),+ });++ setupEnterprisePlugins();+ });++ it("should return collectionsById unchanged when tenants are disabled", () => {+ const { result } = setupHook({ useTenants: false });++ expect(result.current).not.toHaveProperty(String(COLLECTIONS_TOP_LEVEL_ID));++ expect(result.current).not.toHaveProperty(+ String(SHARED_TENANT_COLLECTIONS_ROOT_ID),+ );+ });++ it("should return collectionsById unchanged when tenants are enabled but no shared collections exist", async () => {+ const { result } = setupHook({ useTenants: true, sharedCollections: [] });++ await waitFor(() => {+ expect(result.current).not.toHaveProperty(+ String(COLLECTIONS_TOP_LEVEL_ID),+ );+ });++ expect(result.current).not.toHaveProperty(+ String(SHARED_TENANT_COLLECTIONS_ROOT_ID),+ );+ });++ it("should merge shared collections when tenants are enabled", async () => {+ const tenantCollection = createMockCollection({+ id: 100 as CollectionId,+ name: "Tenant A",+ location: "/",+ namespace: "shared-tenant-collection" as any,+ });++ const { result } = setupHook({+ useTenants: true,+ sharedCollections: [tenantCollection],+ });++ await waitFor(() => {+ expect(result.current).toHaveProperty(String(COLLECTIONS_TOP_LEVEL_ID));+ });++ expect(result.current).toHaveProperty(+ String(SHARED_TENANT_COLLECTIONS_ROOT_ID),+ );+ });+});++function setup() {+ const baseRoot = createMockExpandedCollection({+ ...ROOT_COLLECTION,+ path: [],+ });++ const ourAnalyticsSubCollection = createMockExpandedCollection({+ id: 200 as CollectionId,+ name: "Our Analytics Sub",+ location: "/",+ path: ["root" as CollectionId],+ });++ const ourAnalyticsNestedCollection = createMockExpandedCollection({+ id: 201 as CollectionId,+ name: "Nested Sub",+ location: "/200/",+ path: ["root" as CollectionId, 200 as CollectionId],+ });++ baseRoot.children = [ourAnalyticsSubCollection];+ ourAnalyticsSubCollection.parent = baseRoot;+ ourAnalyticsSubCollection.children = [ourAnalyticsNestedCollection];+ ourAnalyticsNestedCollection.parent = ourAnalyticsSubCollection;++ const baseCollectionsById = {+ [ROOT_COLLECTION.id]: baseRoot,+ [200 as CollectionId]: ourAnalyticsSubCollection,+ [201 as CollectionId]: ourAnalyticsNestedCollection,+ } as Record<CollectionId, Collection>;++ const sharedRoot = createMockExpandedCollection({+ ...ROOT_COLLECTION,+ path: [],+ });++ const tenantA = createMockExpandedCollection({+ id: 100 as CollectionId,+ name: "Tenant A",+ location: "/",+ path: ["root" as CollectionId],+ });++ const subCollection = createMockExpandedCollection({+ id: 300 as CollectionId,+ name: "Subcollection",+ location: "/100/",+ path: ["root" as CollectionId, 100 as CollectionId],+ });++ sharedRoot.children = [tenantA];+ tenantA.parent = sharedRoot;+ tenantA.children = [subCollection];+ subCollection.parent = tenantA;++ const collectionsById = mergeSharedCollections(+ baseCollectionsById,+ {+ [ROOT_COLLECTION.id]: sharedRoot,+ [100 as CollectionId]: tenantA,+ [300 as CollectionId]: subCollection,+ },+ "Shared collections",+ );++ return {+ collectionsById,+ ourAnalyticsSubCollection,+ ourAnalyticsNestedCollection,+ tenantA,+ subCollection,+ };+}++describe("mergeSharedCollections", () => {+ it("should create a top-level Collections node with Our analytics and Shared collections as siblings", () => {+ const { collectionsById } = setup();+ const expanded = collectionsById as Record<+ CollectionId,+ ExpandedCollectionNode+ >;++ const topLevel = expanded[COLLECTIONS_TOP_LEVEL_ID];+ expect(topLevel.name).toBe("Collections");+ expect(topLevel.parent).toBeNull();+ expect(topLevel.children).toHaveLength(2);+ expect(topLevel.children[0].id).toBe(ROOT_COLLECTION.id);+ expect(topLevel.children[1].id).toBe(SHARED_TENANT_COLLECTIONS_ROOT_ID);++ const root = expanded[ROOT_COLLECTION.id];+ expect(root.parent?.id).toBe(COLLECTIONS_TOP_LEVEL_ID);+ expect(root.path).toEqual([COLLECTIONS_TOP_LEVEL_ID]);++ const syntheticRoot = expanded[SHARED_TENANT_COLLECTIONS_ROOT_ID];+ expect(syntheticRoot.name).toBe("Shared collections");+ expect(syntheticRoot.parent?.id).toBe(COLLECTIONS_TOP_LEVEL_ID);+ expect(syntheticRoot.path).toEqual([COLLECTIONS_TOP_LEVEL_ID]);+ });++ it("should rewrite paths for Our Analytics sub-collections to include the top-level Collections node", () => {+ const {+ collectionsById,+ ourAnalyticsSubCollection,+ ourAnalyticsNestedCollection,+ } = setup();++ expect(collectionsById[ourAnalyticsSubCollection.id].path).toEqual([+ COLLECTIONS_TOP_LEVEL_ID,+ "root",+ ]);++ expect(collectionsById[ourAnalyticsNestedCollection.id].path).toEqual([+ COLLECTIONS_TOP_LEVEL_ID,+ "root",+ ourAnalyticsSubCollection.id,+ ]);+ });++ it("should re-parent children and rewrite paths through the top-level and synthetic root", () => {+ const { collectionsById, tenantA, subCollection } = setup();+ const expanded = collectionsById as Record<+ CollectionId,+ ExpandedCollectionNode+ >;++ const mergedTenantA = expanded[tenantA.id];++ expect(mergedTenantA.parent?.id).toBe(SHARED_TENANT_COLLECTIONS_ROOT_ID);+ expect(mergedTenantA.path).toEqual([+ COLLECTIONS_TOP_LEVEL_ID,+ SHARED_TENANT_COLLECTIONS_ROOT_ID,+ ]);++ const mergedSubCollection = expanded[subCollection.id];++ expect(mergedSubCollection.parent?.id).toBe(tenantA.id);+ expect(mergedSubCollection.path).toEqual([+ COLLECTIONS_TOP_LEVEL_ID,+ SHARED_TENANT_COLLECTIONS_ROOT_ID,+ tenantA.id,+ ]);+ });+});