Skip to content

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

Fix tenant collections showing up as unknown in the dashboard question picker (#80824)

Phoomparin Manob0525d2dc48e
diff --git a/e2e/test/scenarios/dashboard/dashboard-tenant-specific-question-picker.cy.spec.ts b/e2e/test/scenarios/dashboard/dashboard-tenant-specific-question-picker.cy.spec.ts
new file mode 100644
index 00000000000..e143beee72c
--- /dev/null
+++ b/e2e/test/scenarios/dashboard/dashboard-tenant-specific-question-picker.cy.spec.ts
@@ -0,0 +1,99 @@
+const { H } = cy;
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { Collection, Dashboard, Tenant } from "metabase-types/api";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+describe("scenarios > dashboard > admins using tenant-specific question picker", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ H.updateSetting("use-tenants", true);
+
+ cy.request("POST", "/api/ee/tenant", {
+ name: "Acme",
+ slug: "acme",
+ })
+ .its("body")
+ .as("tenant");
+
+ cy.get<Tenant>("@tenant")
+ .then(({ tenant_collection_id }) =>
+ H.createCollection({
+ name: "Tenant questions",
+ parent_id: tenant_collection_id,
+ }),
+ )
+ .its("body")
+ .as("tenantCollection");
+
+ cy.get<Collection>("@tenantCollection").then((tenantCollection) =>
+ H.createQuestion({
+ name: "Tenant orders",
+ collection_id: tenantCollection.id,
+ query: { "source-table": ORDERS_ID },
+ }),
+ );
+ });
+
+ it("allows adding questions from the dashboard's tenant-specific collection (EMB-2312)", () => {
+ cy.get<Tenant>("@tenant")
+ .then(({ tenant_collection_id }) =>
+ H.createDashboard({
+ name: "Tenant dashboard",
+ collection_id: tenant_collection_id,
+ }),
+ )
+ .its("body")
+ .as("dashboard");
+
+ cy.get<Dashboard>("@dashboard").then(({ id }) => {
+ H.visitDashboard(id);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .should("contain", "Acme")
+ .and("not.contain", "Unknown");
+
+ H.sidebar().findByText("Tenant questions").click();
+ H.sidebar().findByText("Tenant orders").click();
+
+ H.getDashboardCards()
+ .should("have.length", 1)
+ .and("contain", "Tenant orders");
+ });
+ });
+
+ // Verify that Tenant collections and Our analytics are separate top-level entries.
+ it("allows browsing into a tenant-specific collection from Our Analytics (EMB-2312)", () => {
+ H.createDashboard({ name: "Our analytics dashboard" })
+ .its("body")
+ .as("dashboard");
+
+ cy.get<Dashboard>("@dashboard").then(({ id }) => {
+ H.visitDashboard(id);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .should("contain", "Collections")
+ .and("contain", "Our analytics");
+
+ H.sidebar().findByTestId("breadcrumbs").findByText("Collections").click();
+
+ H.sidebar().findByText("Tenant collections").click();
+ H.sidebar().findByText("Acme").click();
+ H.sidebar().findByText("Tenant questions").click();
+ H.sidebar().findByText("Tenant orders").click();
+
+ H.getDashboardCards()
+ .should("have.length", 1)
+ .and("contain", "Tenant orders");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/dashboard/dashboard-tenant-user-question-picker.cy.spec.ts b/e2e/test/scenarios/dashboard/dashboard-tenant-user-question-picker.cy.spec.ts
new file mode 100644
index 00000000000..ca48af76fa2
--- /dev/null
+++ b/e2e/test/scenarios/dashboard/dashboard-tenant-user-question-picker.cy.spec.ts
@@ -0,0 +1,159 @@
+const { H } = cy;
+
+import { JWT_SHARED_SECRET } from "e2e/support/helpers/e2e-jwt-helpers";
+import type { Collection, Dashboard, Tenant, User } from "metabase-types/api";
+
+const TENANT_USER = {
+ first_name: "acme",
+ last_name: "user",
+ email: "[email protected]",
+ "@tenant": "acme",
+};
+
+const loginAsTenantUser = (returnTo: string) => {
+ cy.task<string>("signJwt", {
+ payload: TENANT_USER,
+ secret: JWT_SHARED_SECRET,
+ }).then((key) =>
+ cy.visit(`/auth/sso?return_to=${encodeURIComponent(returnTo)}&jwt=${key}`),
+ );
+};
+
+describe("scenarios > dashboard > tenant users using question picker", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+
+ cy.request("PUT", "/api/setting", {
+ "jwt-attribute-email": "email",
+ "jwt-attribute-firstname": "first_name",
+ "jwt-attribute-lastname": "last_name",
+ "jwt-enabled": true,
+ "jwt-identity-provider-uri": "localhost:4000",
+ "jwt-shared-secret": JWT_SHARED_SECRET,
+ "jwt-user-provisioning-enabled?": true,
+ "use-tenants": true,
+ });
+
+ cy.request("POST", "/api/ee/tenant", {
+ name: "Acme",
+ slug: "acme",
+ })
+ .its("body")
+ .as("tenant");
+
+ H.createSharedTenantCollection("Finance")
+ .its("body")
+ .as("financeCollection");
+
+ H.createSharedTenantCollection("Marketing")
+ .its("body")
+ .as("marketingCollection");
+
+ cy.get<Tenant>("@tenant")
+ .then(({ tenant_collection_id }) =>
+ H.createCollection({
+ name: "Tenant questions",
+ parent_id: tenant_collection_id,
+ }),
+ )
+ .its("body")
+ .as("tenantCollection");
+ });
+
+ // Tenant users do not know what is a 'Tenant-specific collection' or 'Shared collection'.
+ // Only show a flattened structure for them, with "Our data" being their tenant collection.
+ it("shows flattened tenant collections without grouping by namespaces (EMB-2312)", () => {
+ cy.get<Collection>("@tenantCollection")
+ .then(({ id }) =>
+ H.createDashboard({
+ name: "Tenant dashboard",
+ collection_id: id,
+ }),
+ )
+ .its("body")
+ .as("dashboard");
+
+ cy.get<Dashboard>("@dashboard").then(({ id }) => {
+ loginAsTenantUser(`/dashboard/${id}`);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .should("contain", "Collections")
+ .and("contain", "Our data");
+
+ H.sidebar().findByTestId("breadcrumbs").findByText("Collections").click();
+
+ H.sidebar().findByText("Our data").should("be.visible");
+ H.sidebar().findByText("Finance").should("be.visible");
+ H.sidebar().findByText("Marketing").should("be.visible");
+ H.sidebar().findByText("Our analytics").should("not.exist");
+ H.sidebar().findByText("Shared collections").should("not.exist");
+ H.sidebar().findByText("Tenant collections").should("not.exist");
+ });
+ });
+
+ // The API omits 'Our analytics' when tenant users cannot read it, but it still
+ // returns their personal collection. Show that collection directly under the
+ // synthetic collections level instead of adding another 'collections' folder.
+ it("shows the personal collection under top-level collections (EMB-2312)", () => {
+ loginAsTenantUser("/");
+
+ cy.request<User>("GET", "/api/user/current").its("body").as("tenantUser");
+
+ cy.get<User>("@tenantUser")
+ .then(({ personal_collection_id }) => {
+ if (personal_collection_id == null) {
+ throw new Error("Tenant user has no personal collection");
+ }
+
+ return H.createDashboard({
+ name: "Personal dashboard",
+ collection_id: personal_collection_id,
+ });
+ })
+ .its("body")
+ .as("personalDashboard");
+
+ cy.get<Dashboard>("@personalDashboard").then(({ id }) => {
+ cy.intercept({
+ method: "GET",
+ pathname: "/api/collection/tree",
+ query: {
+ namespace: "shared-tenant-collection",
+ "exclude-archived": "true",
+ },
+ }).as("sharedTenantCollections");
+
+ H.visitDashboard(id);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+
+ cy.wait("@sharedTenantCollections");
+
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .should("contain", "Collections")
+ .and("contain", "My personal collection");
+
+ H.sidebar().findByTestId("breadcrumbs").findByText("Collections").click();
+
+ H.sidebar()
+ .findByRole("menuitem", { name: "My personal collection" })
+ .should("be.visible");
+
+ // There should not be a second nested "Collections" folder.
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .findAllByText("Collections")
+ .should("have.length", 1);
+
+ H.sidebar()
+ .findByRole("menuitem", { name: "Collections" })
+ .should("not.exist");
+ });
+ });
+});
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.ts
index 9a1470ca7e7..d9f182dc74f 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,7 @@
const { H } = cy;
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
+import type { Dashboard } from "metabase-types/api";
const { ORDERS_ID } = SAMPLE_DATABASE;
@@ -429,6 +430,43 @@ describe("scenarios > organization > entity picker > shared-tenant-collection na
});
});
+ it("should allow admins to add questions from shared tenant sub-collections", () => {
+ setupTenantCollections().as("tenantCollections");
+
+ cy.get<{ subCollectionId: number }>("@tenantCollections").then(
+ ({ subCollectionId }) =>
+ H.createQuestion({
+ name: "Tenant Sub-Collection Orders Question",
+ collection_id: subCollectionId,
+ query: { "source-table": ORDERS_ID },
+ }),
+ );
+
+ H.createDashboard({ name: "Test Dashboard" }).its("body").as("dashboard");
+
+ cy.get<Dashboard>("@dashboard").then(({ id }) => {
+ H.visitDashboard(id);
+ H.editDashboard();
+ H.openQuestionsSidebar();
+
+ H.sidebar()
+ .findByTestId("breadcrumbs")
+ .should("contain", "Collections")
+ .and("contain", "Our analytics")
+ .findByText("Collections")
+ .click();
+
+ H.sidebar().findByText(TENANT_ROOT_NAME).should("be.visible").click();
+ H.sidebar().findByText("Test Tenant Collection").click();
+ H.sidebar().findByText("Tenant Sub-Collection").click();
+ H.sidebar().findByText("Tenant Sub-Collection Orders Question").click();
+
+ H.getDashboardCards()
+ .should("have.length", 1)
+ .and("contain", "Tenant Sub-Collection Orders Question");
+ });
+ });
+
it("should show 'Collections' in breadcrumb when navigating into Our Analytics sub-collections", () => {
setupTenantCollections().then(() => {
H.createCollection({ name: "Our Analytics Sub" }).then(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 2f5c237cc3e..e05f842f331 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -125,10 +125,12 @@ export function initializePlugin() {
if (hasPremiumFeature("tenants")) {
PLUGIN_TENANTS.isEnabled = true;
- PLUGIN_TENANTS.useListActiveTenants = () => {
- const { data, isLoading, error } = useListTenantsQuery({
- status: "active",
- });
+ PLUGIN_TENANTS.useListActiveTenants = ({ skip } = {}) => {
+ const { data, isLoading, error } = useListTenantsQuery(
+ { status: "active" },
+ { skip },
+ );
+
return { data: data?.data, isLoading, error };
};
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
index 86f63eb80dd..a181a3c8338 100644
--- a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
@@ -28,11 +28,12 @@ import type { CollectionId } from "metabase-types/api";
import { QuestionList } from "./QuestionList";
import S from "./QuestionPicker.module.css";
import { addDashboardQuestion } from "./actions";
+import { useCollectionsWithTenants } from "./hooks/use-collections-with-tenants";
import {
COLLECTIONS_TOP_LEVEL_ID,
SHARED_TENANT_COLLECTIONS_ROOT_ID,
- useCollectionsWithTenants,
-} from "./hooks/use-collections-with-tenants";
+ TENANT_SPECIFIC_COLLECTIONS_ROOT_ID,
+} from "./utils/tenant-collection-tree";
interface QuestionPickerProps {
onSelect: BaseSelectListItemProps["onSelect"];
@@ -59,11 +60,22 @@ export function QuestionPicker({ onSelect }: QuestionPickerProps) {
SEARCH_DEBOUNCE_DURATION,
);
- const collectionsById = useCollectionsWithTenants(baseCollectionsById);
+ // getExpandedCollectionsById always creates a root collection,
+ // but we only want to show it if the user has access to it.
+ const canReadRootCollection = allCollectionsList.some(
+ ({ id }) => id === ROOT_COLLECTION.id,
+ );
+
+ const collectionsById = useCollectionsWithTenants(
+ baseCollectionsById,
+ canReadRootCollection,
+ );
const isAtTopLevel = currentCollectionId === COLLECTIONS_TOP_LEVEL_ID;
const isAtSharedTenantRoot =
currentCollectionId === SHARED_TENANT_COLLECTIONS_ROOT_ID;
+ const isAtTenantSpecificRoot =
+ currentCollectionId === TENANT_SPECIFIC_COLLECTIONS_ROOT_ID;
const collection = collectionsById[currentCollectionId];
const crumbs = getCollectionBreadCrumbs(
collection,
@@ -165,10 +177,11 @@ export function QuestionPicker({ onSelect }: QuestionPickerProps) {
</>
)}
- {/* 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) && (
+ {/* Hide the question list at top-level "Collections" and tenant roots.
+ These have fake IDs that don't map to real collections, so querying
+ questions against them would fail. */}
+ {((!isAtSharedTenantRoot && !isAtTenantSpecificRoot && !isAtTopLevel) ||
+ debouncedSearchText) && (
<QuestionList
hasCollections={collections.length > 0}
searchText={debouncedSearchText}
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.ts
index 6c0bf86c318..8965f5fd021 100644
--- 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.ts
@@ -2,36 +2,44 @@ import { useMemo } from "react";
import { t } from "ttag";
import { skipToken, useListCollectionsTreeQuery } from "metabase/api";
-import { ROOT_COLLECTION } from "metabase/common/collections/constants";
import getExpandedCollectionsById from "metabase/common/collections/getExpandedCollectionsById";
-import { getUserPersonalCollectionId } from "metabase/current-user";
+import {
+ getIsTenantUser,
+ getUserPersonalCollectionId,
+} from "metabase/current-user";
import { PLUGIN_TENANTS } from "metabase/plugins";
import { useSelector } from "metabase/redux";
import type { ExpandedCollection } from "metabase/redux/store";
import { useSetting } from "metabase/settings";
import type { CollectionId } from "metabase-types/api";
-export const SHARED_TENANT_COLLECTIONS_ROOT_ID: CollectionId =
- "shared-tenant-collections-root";
-
-export const COLLECTIONS_TOP_LEVEL_ID: CollectionId = "collections-top-level";
+import { flattenCollectionTree } from "../utils/tenant-collection-tree";
+import {
+ mergeTenantCollections,
+ mergeTenantUserCollections,
+} from "../utils/tenant-collections";
/**
- * When tenants are enabled, fetches shared tenant collections and merges them
- * into the collectionsById map so they appear as a top-level browsable entry.
+ * When tenants are enabled, fetches tenant collections and adds their
+ * namespaces as top-level browsable entries.
*
* The tree structure becomes:
* Collections (top level)
* ├── Our analytics (root collection)
- * └── Shared collections (synthetic root for shared collections)
+ * ├── Shared collections (synthetic collection)
* ├── Shared collection A
* └── Shared collection B
+ * └── Tenant collections (synthetic collection)
+ * ├── Tenant collection A
+ * └── Tenant collection B
*/
export function useCollectionsWithTenants(
collectionsById: Record<CollectionId, ExpandedCollection>,
+ canReadRootCollection: boolean,
): Record<CollectionId, ExpandedCollection> {
const useTenants = useSetting("use-tenants");
const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);
+ const isTenantUser = useSelector(getIsTenantUser);
const isTenantsActive = useTenants && PLUGIN_TENANTS.isEnabled;
const { data: sharedTenantCollections } = useListCollectionsTreeQuery(
@@ -43,154 +51,82 @@ export function useCollectionsWithTenants(
: skipToken,
);
+ const { data: tenantSpecificCollections } = useListCollectionsTreeQuery(
+ isTenantsActive
+ ? {
+ namespace: PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE,
+ "exclude-archived": true,
+ }
+ : skipToken,
+ );
+
+ const { data: tenants } = PLUGIN_TENANTS.useListActiveTenants({
+ skip: !isTenantsActive || isTenantUser,
+ });
+
+ const tenantCollectionNamesById = useMemo(
+ () =>
+ new Map(
+ tenants?.flatMap(({ tenant_collection_id, name }) =>
+ tenant_collection_id == null ? [] : [[tenant_collection_id, name]],
+ ),
+ ),
+ [tenants],
+ );
+
return useMemo(() => {
- if (!isTenantsActive || !sharedTenantCollections?.length) {
+ if (!isTenantsActive) {
return collectionsById;
}
- // Unjustified type cast. FIXME
- const sharedCollectionsById = getExpandedCollectionsById(
- sharedTenantCollections,
- userPersonalCollectionId,
- );
+ const sharedCollectionsById = sharedTenantCollections?.length
+ ? getExpandedCollectionsById(
+ flattenCollectionTree(sharedTenantCollections),
+ userPersonalCollectionId,
+ )
+ : {};
+
+ const tenantSpecificCollectionsById = tenantSpecificCollections?.length
+ ? getExpandedCollectionsById(
+ flattenCollectionTree(tenantSpecificCollections),
+ userPersonalCollectionId,
+ )
+ : {};
+
+ if (
+ Object.keys(sharedCollectionsById).length === 0 &&
+ Object.keys(tenantSpecificCollectionsById).length === 0
+ ) {
+ return collectionsById;
+ }
const displayName =
PLUGIN_TENANTS.getNamespaceDisplayName(
PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,
- ) ?? "";
-
- return mergeSharedCollections(
- collectionsById,
- sharedCollectionsById,
- displayName,
- );
+ ) ?? t`Shared collections`;
+
+ return isTenantUser
+ ? mergeTenantUserCollections({
+ baseCollectionsById: collectionsById,
+ sharedCollectionsById,
+ tenantSpecificCollectionsById,
+ canReadRootCollection,
+ })
+ : mergeTenantCollections({
+ baseCollectionsById: collectionsById,
+ sharedCollectionsById,
+ tenantSpecificCollectionsById,
+ sharedCollectionsName: displayName,
+ tenantCollectionNamesById,
+ });
}, [
isTenantsActive,
sharedTenantCollections,
+ tenantSpecificCollections,
+ tenantCollectionNamesById,
collectionsById,
+ canReadRootCollection,
+ isTenantUser,
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, ExpandedCollection>,
- sharedCollectionsById: Record<CollectionId, ExpandedCollection>,
- displayName: string,
-): Record<CollectionId, ExpandedCollection> {
- const sharedRoot = sharedCollectionsById[ROOT_COLLECTION.id];
- const rootCollection = baseCollectionsById[ROOT_COLLECTION.id];
-
- // Create the top-level "Collections" node that parents both namespaces
- const syntheticTopLevel: ExpandedCollection = {
- 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: ExpandedCollection = {
- 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,
- })),
- };
-
- // Fix circular parent reference now that sharedSyntheticRoot exists
- sharedSyntheticRoot.children = sharedSyntheticRoot.children.map((child) => ({
- ...child,
- parent: sharedSyntheticRoot,
- }));
-
- // 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,
- };
-
- // Merge shared collections with rewritten paths
- for (const [id, collection] of Object.entries(sharedCollectionsById)) {
- if (id === String(ROOT_COLLECTION.id)) {
- continue;
- }
-
- mergedCollectionsById[id] = {
- ...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,
- };
- }
-
- // 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;
-
- if (!collectionNode.path) {
- continue;
- }
-
- mergedCollectionsById[id] = {
- ...collectionNode,
- // Rewrite path: Collections > Our Analytics > ...
- path: [COLLECTIONS_TOP_LEVEL_ID, ...collectionNode.path],
- };
- }
-
- 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.ts
index 26654bab8c9..0763a39beca 100644
--- 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.ts
@@ -1,11 +1,11 @@
import { setupEnterprisePlugins } from "__support__/enterprise";
import { setupCollectionTreeEndpoint } from "__support__/server-mocks/collection";
+import { setupTenantEntpoints } from "__support__/server-mocks/tenant";
import { mockSettings } from "__support__/settings";
import { renderHookWithProviders, waitFor } from "__support__/ui";
-import { ROOT_COLLECTION } from "metabase/common/collections/constants";
-import type { ExpandedCollection } from "metabase/redux/store";
+import getExpandedCollectionsById from "metabase/common/collections/getExpandedCollectionsById";
import { createMockState } from "metabase/redux/store/mocks";
-import type { Collection, CollectionId } from "metabase-types/api";
+import type { Collection, Tenant } from "metabase-types/api";
import {
createMockCollection,
createMockTokenFeatures,
@@ -14,38 +14,27 @@ import {
import {
COLLECTIONS_TOP_LEVEL_ID,
SHARED_TENANT_COLLECTIONS_ROOT_ID,
- mergeSharedCollections,
- useCollectionsWithTenants,
-} from "./use-collections-with-tenants";
+} from "../utils/tenant-collection-tree";
-const createMockExpandedCollection = (
- overrides: Partial<Collection> & { path?: CollectionId[] | null },
-): ExpandedCollection => ({
- ...createMockCollection(overrides),
- path: overrides.path ?? [],
- parent: null,
- children: [],
- is_personal: false,
-});
+import { useCollectionsWithTenants } from "./use-collections-with-tenants";
+
+type SetupHookOptions = {
+ useTenants?: boolean;
+ sharedCollections?: Collection[];
+ tenants?: Tenant[];
+};
function setupHook({
useTenants = false,
- // Unjustified type cast. FIXME
- sharedCollections = [] as Collection[],
-} = {}) {
+ sharedCollections = [],
+ tenants = [],
+}: SetupHookOptions = {}) {
setupCollectionTreeEndpoint(sharedCollections);
-
- const baseRoot = createMockExpandedCollection({
- ...ROOT_COLLECTION,
- path: [],
- });
-
- const collectionsById: Record<CollectionId, ExpandedCollection> = {
- [ROOT_COLLECTION.id]: baseRoot,
- };
+ setupTenantEntpoints(tenants);
return renderHookWithProviders(
- () => useCollectionsWithTenants(collectionsById),
+ () =>
+ useCollectionsWithTenants(getExpandedCollectionsById([], null), false),
{
storeInitialState: createMockState({
settings: mockSettings({
@@ -66,34 +55,28 @@ describe("useCollectionsWithTenants", () => {
setupEnterprisePlugins();
});
- it("should return collectionsById unchanged when tenants are disabled", () => {
- const { result } = setupHook({ useTenants: false });
+ it("returns collectionsById unchanged when tenants are disabled", () => {
+ const { result } = setupHook();
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: [] });
+ it("returns collectionsById unchanged when tenant collections are empty", async () => {
+ const { result } = setupHook({ useTenants: true });
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({
- // Unjustified type cast. FIXME
- id: 100 as CollectionId,
+ it("merges shared collections when tenants are enabled", async () => {
+ const sharedCollection = createMockCollection({
+ id: 100,
name: "Tenant A",
location: "/",
namespace: "shared-tenant-collection",
@@ -101,7 +84,7 @@ describe("useCollectionsWithTenants", () => {
const { result } = setupHook({
useTenants: true,
- sharedCollections: [tenantCollection],
+ sharedCollections: [sharedCollection],
});
await waitFor(() => {
@@ -113,153 +96,3 @@ describe("useCollectionsWithTenants", () => {
);
});
});
-
-function setup() {
- const baseRoot = createMockExpandedCollection({
- ...ROOT_COLLECTION,
- path: [],
- });
-
- const ourAnalyticsSubCollection = createMockExpandedCollection({
- id: 200,
- name: "Our Analytics Sub",
- location: "/",
- path: ["root"],
- });
-
- const ourAnalyticsNestedCollection = createMockExpandedCollection({
- id: 201,
- name: "Nested Sub",
- location: "/200/",
- path: ["root", 200],
- });
-
- baseRoot.children = [ourAnalyticsSubCollection];
- ourAnalyticsSubCollection.parent = baseRoot;
- ourAnalyticsSubCollection.children = [ourAnalyticsNestedCollection];
- ourAnalyticsNestedCollection.parent = ourAnalyticsSubCollection;
-
- const baseCollectionsById: Record<CollectionId, ExpandedCollection> = {
- [ROOT_COLLECTION.id]: baseRoot,
- // Unjustified type cast. FIXME
- [200 as CollectionId]: ourAnalyticsSubCollection,
- // Unjustified type cast. FIXME
- [201 as CollectionId]: ourAnalyticsNestedCollection,
- };
-
- const sharedRoot = createMockExpandedCollection({
- ...ROOT_COLLECTION,
- path: [],
- });
-
- const tenantA = createMockExpandedCollection({
- id: 100,
- name: "Tenant A",
- location: "/",
- path: ["root"],
- });
-
- const subCollection = createMockExpandedCollection({
- id: 300,
- name: "Subcollection",
- location: "/100/",
- path: ["root", 100],
- });
-
- sharedRoot.children = [tenantA];
- tenantA.parent = sharedRoot;
- tenantA.children = [subCollection];
- subCollection.parent = tenantA;
-
- const collectionsById = mergeSharedCollections(
- baseCollectionsById,
- {
- [ROOT_COLLECTION.id]: sharedRoot,
- // Unjustified type cast. FIXME
- [100 as CollectionId]: tenantA,
- // Unjustified type cast. FIXME
- [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();
- // Unjustified type cast. FIXME
- const expanded = collectionsById as Record<
- CollectionId,
- ExpandedCollection
- >;
-
- 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();
- // Unjustified type cast. FIXME
- const expanded = collectionsById as Record<
- CollectionId,
- ExpandedCollection
- >;
-
- 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,
- ]);
- });
-});
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.ts
new file mode 100644
index 00000000000..11329006a71
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.ts
@@ -0,0 +1,134 @@
+import { t } from "ttag";
+
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import type { ExpandedCollection } from "metabase/redux/store";
+import type { Collection, CollectionId } from "metabase-types/api";
+
+export const SHARED_TENANT_COLLECTIONS_ROOT_ID: CollectionId =
+ "shared-tenant-collections-root";
+
+export const TENANT_SPECIFIC_COLLECTIONS_ROOT_ID: CollectionId =
+ "tenant-specific-collections-root";
+
+export const COLLECTIONS_TOP_LEVEL_ID: CollectionId = "collections-top-level";
+
+export const flattenCollectionTree = (
+ collections: Collection[],
+): Collection[] =>
+ collections.flatMap((collection) => [
+ collection,
+ ...flattenCollectionTree(collection.children ?? []),
+ ]);
+
+export const createSyntheticTopLevel = (): ExpandedCollection => ({
+ 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: [],
+});
+
+export function mergeCollectionNamespaceChildren({
+ collectionsById,
+ namespaceCollectionsById,
+ parent,
+ pathPrefix,
+ getCollectionName,
+}: {
+ collectionsById: Record<CollectionId, ExpandedCollection>;
+ namespaceCollectionsById: Record<CollectionId, ExpandedCollection>;
+ parent: ExpandedCollection;
+ pathPrefix: CollectionId[];
+ getCollectionName?: (collection: ExpandedCollection) => string;
+}): ExpandedCollection[] {
+ const namespaceRoot = namespaceCollectionsById[ROOT_COLLECTION.id];
+ if (!namespaceRoot?.children.length) {
+ return [];
+ }
+
+ const directCollectionIds = new Set(
+ namespaceRoot.children.map((collection) => collection.id),
+ );
+
+ const directCollections = namespaceRoot.children.map((collection) => {
+ const mergedCollection = {
+ ...collection,
+ name: getCollectionName?.(collection) ?? collection.name,
+ path: pathPrefix,
+ parent,
+ };
+
+ collectionsById[collection.id] = mergedCollection;
+
+ return mergedCollection;
+ });
+
+ for (const collection of Object.values(namespaceCollectionsById)) {
+ if (
+ collection.id === ROOT_COLLECTION.id ||
+ directCollectionIds.has(collection.id)
+ ) {
+ continue;
+ }
+
+ const path = collection.path
+ ? [
+ ...pathPrefix,
+ ...collection.path.filter((pathId) => pathId !== ROOT_COLLECTION.id),
+ ]
+ : null;
+
+ const parent = collection.parent
+ ? (collectionsById[collection.parent.id] ?? collection.parent)
+ : null;
+
+ collectionsById[collection.id] = { ...collection, path, parent };
+ }
+
+ return directCollections;
+}
+
+export function mergeBaseCollectionsAtTopLevel({
+ baseCollectionsById,
+ mergedCollectionsById,
+ syntheticTopLevel,
+ shouldIncludeRoot = true,
+}: {
+ baseCollectionsById: Record<CollectionId, ExpandedCollection>;
+ mergedCollectionsById: Record<CollectionId, ExpandedCollection>;
+ syntheticTopLevel: ExpandedCollection;
+ shouldIncludeRoot?: boolean;
+}): ExpandedCollection | null {
+ if (!shouldIncludeRoot) {
+ return null;
+ }
+
+ const rootCollection = baseCollectionsById[ROOT_COLLECTION.id];
+
+ const mergedRoot = {
+ ...rootCollection,
+ path: [COLLECTIONS_TOP_LEVEL_ID],
+ parent: syntheticTopLevel,
+ };
+
+ mergedCollectionsById[ROOT_COLLECTION.id] = mergedRoot;
+
+ for (const collection of Object.values(baseCollectionsById)) {
+ if (collection.id === ROOT_COLLECTION.id || !collection.path) {
+ continue;
+ }
+
+ mergedCollectionsById[collection.id] = {
+ ...collection,
+ path: [COLLECTIONS_TOP_LEVEL_ID, ...collection.path],
+ };
+ }
+
+ return mergedRoot;
+}
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.unit.spec.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.unit.spec.ts
new file mode 100644
index 00000000000..3909a295c6c
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collection-tree.unit.spec.ts
@@ -0,0 +1,132 @@
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import getExpandedCollectionsById from "metabase/common/collections/getExpandedCollectionsById";
+import type { ExpandedCollection } from "metabase/redux/store";
+import type { Collection, CollectionId } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+
+import {
+ COLLECTIONS_TOP_LEVEL_ID,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ createSyntheticTopLevel,
+ flattenCollectionTree,
+ mergeBaseCollectionsAtTopLevel,
+ mergeCollectionNamespaceChildren,
+} from "./tenant-collection-tree";
+
+const expandCollections = (collections: Collection[] = []) =>
+ getExpandedCollectionsById(collections, null);
+
+describe("mergeBaseCollectionsAtTopLevel", () => {
+ it("adds Collections to base collection paths", () => {
+ const subCollection = createMockCollection({
+ id: 200,
+ name: "Our Analytics Sub",
+ location: "/",
+ });
+
+ const nestedCollection = createMockCollection({
+ id: 201,
+ name: "Nested Sub",
+ location: "/200/",
+ });
+
+ const syntheticTopLevel = createSyntheticTopLevel();
+ const mergedCollectionsById: Record<CollectionId, ExpandedCollection> = {};
+
+ const mergedRoot = mergeBaseCollectionsAtTopLevel({
+ baseCollectionsById: expandCollections([subCollection, nestedCollection]),
+ mergedCollectionsById,
+ syntheticTopLevel,
+ });
+
+ expect(mergedRoot?.parent).toBe(syntheticTopLevel);
+ expect(mergedRoot?.path).toEqual([COLLECTIONS_TOP_LEVEL_ID]);
+
+ expect(mergedCollectionsById[subCollection.id].path).toEqual([
+ COLLECTIONS_TOP_LEVEL_ID,
+ ROOT_COLLECTION.id,
+ ]);
+
+ expect(mergedCollectionsById[nestedCollection.id].path).toEqual([
+ COLLECTIONS_TOP_LEVEL_ID,
+ ROOT_COLLECTION.id,
+ String(subCollection.id),
+ ]);
+ });
+});
+
+describe("mergeCollectionNamespaceChildren", () => {
+ it("reparents namespace collections and rewrites their paths", () => {
+ const tenantCollection = createMockCollection({
+ id: 100,
+ name: "Tenant A",
+ location: "/",
+ });
+
+ const subCollection = createMockCollection({
+ id: 300,
+ name: "Subcollection",
+ location: "/100/",
+ });
+
+ const syntheticTopLevel = createSyntheticTopLevel();
+
+ const syntheticCollection: ExpandedCollection = {
+ ...syntheticTopLevel,
+ id: SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ name: "Shared collections",
+ parent: syntheticTopLevel,
+ path: [COLLECTIONS_TOP_LEVEL_ID],
+ };
+
+ const collectionsById: Record<CollectionId, ExpandedCollection> = {};
+
+ mergeCollectionNamespaceChildren({
+ collectionsById,
+ namespaceCollectionsById: expandCollections([
+ tenantCollection,
+ subCollection,
+ ]),
+ parent: syntheticCollection,
+ pathPrefix: [COLLECTIONS_TOP_LEVEL_ID, syntheticCollection.id],
+ });
+
+ const mergedTenantCollection = collectionsById[tenantCollection.id];
+ const mergedSubCollection = collectionsById[subCollection.id];
+
+ expect(mergedTenantCollection.parent).toBe(syntheticCollection);
+
+ expect(mergedTenantCollection.path).toEqual([
+ COLLECTIONS_TOP_LEVEL_ID,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ ]);
+
+ expect(mergedSubCollection.parent).toBe(mergedTenantCollection);
+
+ expect(mergedSubCollection.path).toEqual([
+ COLLECTIONS_TOP_LEVEL_ID,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ String(tenantCollection.id),
+ ]);
+ });
+});
+
+describe("flattenCollectionTree", () => {
+ it("flattens nested collections", () => {
+ const tenantCollection = createMockCollection({
+ id: 100,
+ name: "Acme",
+ children: [
+ createMockCollection({
+ id: 101,
+ name: "Tenant questions",
+ children: [],
+ }),
+ ],
+ });
+
+ expect(
+ flattenCollectionTree([tenantCollection]).map(({ id }) => id),
+ ).toEqual([100, 101]);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.ts
new file mode 100644
index 00000000000..7c105f667da
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.ts
@@ -0,0 +1,232 @@
+import { t } from "ttag";
+
+import { PLUGIN_TENANTS } from "metabase/plugins";
+import type { ExpandedCollection } from "metabase/redux/store";
+import type { Collection, CollectionId } from "metabase-types/api";
+
+import {
+ COLLECTIONS_TOP_LEVEL_ID,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ TENANT_SPECIFIC_COLLECTIONS_ROOT_ID,
+ createSyntheticTopLevel,
+ mergeBaseCollectionsAtTopLevel,
+ mergeCollectionNamespaceChildren,
+} from "./tenant-collection-tree";
+
+/**
+ * Collection trees used to construct the question picker for tenant-aware users.
+ */
+interface TenantCollectionTrees {
+ baseCollectionsById: Record<CollectionId, ExpandedCollection>;
+ sharedCollectionsById: Record<CollectionId, ExpandedCollection>;
+ tenantSpecificCollectionsById: Record<CollectionId, ExpandedCollection>;
+}
+
+/**
+ * Input to populate the question picker's synthetic collections
+ * for non-tenant users, including admins.
+ */
+interface MergeTenantCollectionsArgs extends TenantCollectionTrees {
+ sharedCollectionsName: string;
+ tenantCollectionNamesById?: ReadonlyMap<CollectionId, string>;
+}
+
+/**
+ * Input to populate the question picker for a tenant user.
+ */
+interface MergeTenantUserCollectionsArgs extends TenantCollectionTrees {
+ canReadRootCollection: boolean;
+}
+
+/**
+ * Describes one synthetic collection below `Collections`.
+ */
+interface SyntheticCollectionConfig {
+ id: CollectionId;
+ name: string;
+ namespace: Collection["namespace"];
+ collectionNamesById?: ReadonlyMap<CollectionId, string>;
+}
+
+/**
+ * Adds one synthetic collection under the synthetic `Collections` root.
+ *
+ * Collections/
+ * Shared collections/ # adds this collection
+ * Finance/
+ *
+ * Updates the collection path and parent links for this new hierarchy.
+ * Returns `null` when the namespace has no collections.
+ */
+function addSyntheticCollectionToRoot({
+ topLevel,
+ syntheticCollection: { id, name, namespace, collectionNamesById },
+ collectionsById,
+ namespaceCollectionsById,
+}: {
+ topLevel: ExpandedCollection;
+ syntheticCollection: SyntheticCollectionConfig;
+ collectionsById: Record<CollectionId, ExpandedCollection>;
+ namespaceCollectionsById: Record<CollectionId, ExpandedCollection>;
+}): ExpandedCollection | null {
+ const syntheticCollection: ExpandedCollection = {
+ id,
+ name,
+ description: null,
+ can_write: false,
+ can_restore: false,
+ can_delete: false,
+ namespace,
+ location: null,
+ path: [COLLECTIONS_TOP_LEVEL_ID],
+ parent: topLevel,
+ children: [],
+ };
+
+ const children = mergeCollectionNamespaceChildren({
+ collectionsById,
+ namespaceCollectionsById,
+ parent: syntheticCollection,
+ pathPrefix: [COLLECTIONS_TOP_LEVEL_ID, syntheticCollection.id],
+ getCollectionName: (collection) =>
+ collectionNamesById?.get(collection.id) ?? collection.name,
+ });
+
+ if (children.length === 0) {
+ return null;
+ }
+
+ syntheticCollection.children = children;
+
+ return syntheticCollection;
+}
+
+/**
+ * Builds the question picker tree for admins and other non-tenant users.
+ *
+ * It adds synthetic shared collections and tenant-specific collections to the tree.
+ */
+export function mergeTenantCollections({
+ baseCollectionsById,
+ sharedCollectionsById,
+ tenantSpecificCollectionsById,
+ sharedCollectionsName,
+ tenantCollectionNamesById,
+}: MergeTenantCollectionsArgs): Record<CollectionId, ExpandedCollection> {
+ const syntheticTopLevel = createSyntheticTopLevel();
+ const mergedCollectionsById = { ...baseCollectionsById };
+
+ const mergedRoot = mergeBaseCollectionsAtTopLevel({
+ baseCollectionsById,
+ mergedCollectionsById,
+ syntheticTopLevel,
+ });
+
+ const sharedSyntheticCollection = addSyntheticCollectionToRoot({
+ collectionsById: mergedCollectionsById,
+ namespaceCollectionsById: sharedCollectionsById,
+ topLevel: syntheticTopLevel,
+ syntheticCollection: {
+ id: SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ name: sharedCollectionsName,
+ namespace: PLUGIN_TENANTS.SHARED_TENANT_NAMESPACE,
+ },
+ });
+
+ const tenantSpecificSyntheticCollection = addSyntheticCollectionToRoot({
+ collectionsById: mergedCollectionsById,
+ namespaceCollectionsById: tenantSpecificCollectionsById,
+ topLevel: syntheticTopLevel,
+ syntheticCollection: {
+ id: TENANT_SPECIFIC_COLLECTIONS_ROOT_ID,
+ name: t`Tenant collections`,
+ namespace: PLUGIN_TENANTS.TENANT_SPECIFIC_NAMESPACE,
+ collectionNamesById: tenantCollectionNamesById,
+ },
+ });
+
+ syntheticTopLevel.children = [
+ mergedRoot,
+ sharedSyntheticCollection,
+ tenantSpecificSyntheticCollection,
+ ].filter(
+ (collection): collection is ExpandedCollection => collection != null,
+ );
+
+ for (const syntheticCollection of [
+ sharedSyntheticCollection,
+ tenantSpecificSyntheticCollection,
+ ]) {
+ if (syntheticCollection) {
+ mergedCollectionsById[syntheticCollection.id] = syntheticCollection;
+ }
+ }
+
+ mergedCollectionsById[COLLECTIONS_TOP_LEVEL_ID] = syntheticTopLevel;
+
+ return mergedCollectionsById;
+}
+
+/**
+ * Builds the question picker tree for tenant users,
+ * who uses full-app embedding or uses the internal app:
+ *
+ * Collections/
+ * Our data/ # tenant collection
+ * Finance/ # shared collection
+ *
+ * This assumes that the tenant user has access to dashboard creation.
+ * An admin or internal user will never see this tree.
+ */
+export function mergeTenantUserCollections({
+ baseCollectionsById,
+ sharedCollectionsById,
+ tenantSpecificCollectionsById,
+ canReadRootCollection,
+}: MergeTenantUserCollectionsArgs): Record<CollectionId, ExpandedCollection> {
+ const syntheticTopLevel = createSyntheticTopLevel();
+ const mergedCollectionsById = { ...baseCollectionsById };
+
+ const tenantCollections = mergeCollectionNamespaceChildren({
+ collectionsById: mergedCollectionsById,
+ namespaceCollectionsById: tenantSpecificCollectionsById,
+ parent: syntheticTopLevel,
+ pathPrefix: [COLLECTIONS_TOP_LEVEL_ID],
+ getCollectionName: () => t`Our data`,
+ });
+
+ const sharedCollections = mergeCollectionNamespaceChildren({
+ collectionsById: mergedCollectionsById,
+ namespaceCollectionsById: sharedCollectionsById,
+ parent: syntheticTopLevel,
+ pathPrefix: [COLLECTIONS_TOP_LEVEL_ID],
+ });
+
+ const baseCollections = canReadRootCollection
+ ? []
+ : mergeCollectionNamespaceChildren({
+ collectionsById: mergedCollectionsById,
+ namespaceCollectionsById: baseCollectionsById,
+ parent: syntheticTopLevel,
+ pathPrefix: [COLLECTIONS_TOP_LEVEL_ID],
+ });
+
+ const mergedRoot = mergeBaseCollectionsAtTopLevel({
+ baseCollectionsById,
+ mergedCollectionsById,
+ syntheticTopLevel,
+ // The root can contain questions even when it has no child collections.
+ shouldIncludeRoot: canReadRootCollection,
+ });
+
+ syntheticTopLevel.children = [
+ ...tenantCollections,
+ ...sharedCollections,
+ ...baseCollections,
+ ...(mergedRoot ? [mergedRoot] : []),
+ ];
+
+ mergedCollectionsById[COLLECTIONS_TOP_LEVEL_ID] = syntheticTopLevel;
+
+ return mergedCollectionsById;
+}
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.unit.spec.ts b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.unit.spec.ts
new file mode 100644
index 00000000000..b47ba59cd86
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/utils/tenant-collections.unit.spec.ts
@@ -0,0 +1,131 @@
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import getExpandedCollectionsById from "metabase/common/collections/getExpandedCollectionsById";
+import type { Collection, CollectionId } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+
+import {
+ COLLECTIONS_TOP_LEVEL_ID,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ TENANT_SPECIFIC_COLLECTIONS_ROOT_ID,
+} from "./tenant-collection-tree";
+import {
+ mergeTenantCollections,
+ mergeTenantUserCollections,
+} from "./tenant-collections";
+
+const expandCollections = (
+ collections: Collection[] = [],
+ personalCollectionId: CollectionId | null = null,
+) => getExpandedCollectionsById(collections, personalCollectionId);
+
+describe("mergeTenantCollections", () => {
+ it("adds synthetic tenant collections below the root namespace", () => {
+ const tenantCollection = createMockCollection({
+ id: 100,
+ name: "Tenant collection: Acme",
+ location: "/",
+ namespace: "tenant-specific",
+ });
+
+ const sharedCollection = createMockCollection({
+ id: 101,
+ name: "Finance",
+ location: "/",
+ namespace: "shared-tenant-collection",
+ });
+
+ const collectionsById = mergeTenantCollections({
+ baseCollectionsById: expandCollections(),
+ sharedCollectionsById: expandCollections([sharedCollection]),
+ tenantSpecificCollectionsById: expandCollections([tenantCollection]),
+ sharedCollectionsName: "Shared collections",
+ tenantCollectionNamesById: new Map([[tenantCollection.id, "Acme"]]),
+ });
+
+ expect(
+ collectionsById[COLLECTIONS_TOP_LEVEL_ID].children.map(({ id }) => id),
+ ).toEqual([
+ ROOT_COLLECTION.id,
+ SHARED_TENANT_COLLECTIONS_ROOT_ID,
+ TENANT_SPECIFIC_COLLECTIONS_ROOT_ID,
+ ]);
+
+ expect(collectionsById[SHARED_TENANT_COLLECTIONS_ROOT_ID].name).toBe(
+ "Shared collections",
+ );
+
+ expect(collectionsById[TENANT_SPECIFIC_COLLECTIONS_ROOT_ID].name).toBe(
+ "Tenant collections",
+ );
+
+ expect(collectionsById[tenantCollection.id].name).toBe("Acme");
+ });
+});
+
+describe("mergeTenantUserCollections", () => {
+ it("flattens personal collections when Our analytics is not readable", () => {
+ const tenantCollection = createMockCollection({
+ id: 100,
+ name: "Tenant collection: Acme",
+ location: "/",
+ namespace: "tenant-specific",
+ });
+
+ const sharedCollections = ["Finance", "Marketing"].map((name, index) =>
+ createMockCollection({
+ id: 101 + index,
+ name,
+ location: "/",
+ namespace: "shared-tenant-collection",
+ }),
+ );
+
+ const personalCollection = createMockCollection({
+ id: 103,
+ name: "Poom's personal collection",
+ location: "/",
+ personal_owner_id: 1,
+ });
+
+ const collectionsById = mergeTenantUserCollections({
+ baseCollectionsById: expandCollections(
+ [personalCollection],
+ personalCollection.id,
+ ),
+ sharedCollectionsById: expandCollections(sharedCollections),
+ tenantSpecificCollectionsById: expandCollections([tenantCollection]),
+ canReadRootCollection: false,
+ });
+
+ expect(
+ collectionsById[COLLECTIONS_TOP_LEVEL_ID].children.map(
+ ({ name }) => name,
+ ),
+ ).toEqual(["Our data", "Finance", "Marketing", "My personal collection"]);
+
+ expect(collectionsById).not.toHaveProperty(
+ String(SHARED_TENANT_COLLECTIONS_ROOT_ID),
+ );
+
+ expect(collectionsById).not.toHaveProperty(
+ String(TENANT_SPECIFIC_COLLECTIONS_ROOT_ID),
+ );
+ });
+
+ it("keeps readable Our analytics when it has no subcollections", () => {
+ const ourAnalytics = createMockCollection({ ...ROOT_COLLECTION });
+
+ const collectionsById = mergeTenantUserCollections({
+ baseCollectionsById: expandCollections([ourAnalytics]),
+ sharedCollectionsById: expandCollections(),
+ tenantSpecificCollectionsById: expandCollections(),
+ canReadRootCollection: true,
+ });
+
+ expect(
+ collectionsById[COLLECTIONS_TOP_LEVEL_ID].children.map(
+ ({ name }) => name,
+ ),
+ ).toEqual(["Our analytics"]);
+ });
+});
diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.ts
index 75d5a61f358..db0e0e742f9 100644
--- a/frontend/src/metabase/plugins/oss/tenants.ts
+++ b/frontend/src/metabase/plugins/oss/tenants.ts
@@ -45,9 +45,15 @@ export type UseListActiveTenantsResult = {
error: unknown;
};
+type UseListActiveTenantsOptions = {
+ skip?: boolean;
+};
+
const getDefaultPluginTenants = () => ({
isEnabled: false,
- useListActiveTenants: (): UseListActiveTenantsResult => ({
+ useListActiveTenants: (
+ _options?: UseListActiveTenantsOptions,
+ ): UseListActiveTenantsResult => ({
data: undefined,
isLoading: false,
error: undefined,
@@ -135,7 +141,9 @@ const getDefaultPluginTenants = () => ({
export const PLUGIN_TENANTS: {
isEnabled: boolean;
- useListActiveTenants: () => UseListActiveTenantsResult;
+ useListActiveTenants: (
+ options?: UseListActiveTenantsOptions,
+ ) => UseListActiveTenantsResult;
userStrategyRoute: React.ReactElement | null;
useTenantMainNavbarData: () => {
canAccessTenantSpecificCollections: boolean;