Skip to content

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

flatten collection list for tenant users (#67072)

Nicolò Pretto76bf2624ebe2
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
index 9af6ebc079d..2dfeff49af9 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.tsx
@@ -4,7 +4,6 @@ import { t } from "ttag";
import {
useCreateCollectionMutation,
useListCollectionsQuery,
- useListCollectionsTreeQuery,
} from "metabase/api";
import { CreateCollectionForm } from "metabase/collections/components/CreateCollectionForm";
import type { CreateCollectionProperties } from "metabase/collections/components/CreateCollectionForm/CreateCollectionForm";
@@ -19,23 +18,29 @@ import {
SidebarSection,
} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
-import { getUser, getUserIsAdmin } from "metabase/selectors/user";
+import { getIsTenantUser, getUserIsAdmin } from "metabase/selectors/user";
import { ActionIcon, Flex, Icon, Modal, Tooltip } from "metabase/ui";
import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";
import { CollectionSyncStatusBadge } from "metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge";
+import type { Collection } from "metabase-types/api";
+
+export const MainNavSharedCollections = ({
+ canCreateSharedCollection,
+ sharedTenantCollections,
+}: {
+ canCreateSharedCollection: boolean;
+ sharedTenantCollections: Collection[] | undefined;
+}) => {
+ const isTenantUser = useSelector(getIsTenantUser);
+ if (isTenantUser) {
+ throw new Error(
+ "MainNavSharedCollections should not be rendered for tenant users",
+ );
+ }
-export const MainNavSharedCollections = () => {
const [modalOpen, setModalOpen] = useState(false);
const isTenantsEnabled = useSetting("use-tenants");
const isAdmin = useSelector(getUserIsAdmin);
- const currentUser = useSelector(getUser);
-
- const { data: tenantCollections } = useListCollectionsTreeQuery(
- { namespace: "shared-tenant-collection" },
- {
- skip: !isTenantsEnabled,
- },
- );
// Fetch flat list of tenant collections to check if any are remote-synced
const { data: tenantCollectionsList = [] } = useListCollectionsQuery(
@@ -56,9 +61,9 @@ export const MainNavSharedCollections = () => {
const [createCollection] = useCreateCollectionMutation();
- const tenantCollectionTree = useMemo(
- () => buildCollectionTree(tenantCollections),
- [tenantCollections],
+ const sharedTenantCollectionTree = useMemo(
+ () => buildCollectionTree(sharedTenantCollections),
+ [sharedTenantCollections],
);
const changedCollections = useMemo(
@@ -97,30 +102,24 @@ export const MainNavSharedCollections = () => {
return null;
}
- const userTenantCollectionId = currentUser?.tenant_collection_id;
- const hasVisibleTenantCollections = tenantCollectionTree.length > 0;
+ const hasVisibleSharedTenantCollections =
+ sharedTenantCollectionTree.length > 0;
+
const shouldShowSharedCollectionsSection =
- isAdmin || hasVisibleTenantCollections;
+ hasVisibleSharedTenantCollections || canCreateSharedCollection;
return (
<>
- {userTenantCollectionId && (
- <SidebarSection>
- <SidebarHeading>{t`My tenant collection`}</SidebarHeading>
- <PaddedSidebarLink
- icon="folder"
- url={`/collection/${userTenantCollectionId}`}
- >
- {t`My Tenant Collection`}
- </PaddedSidebarLink>
- </SidebarSection>
- )}
-
{shouldShowSharedCollectionsSection && (
<SidebarSection>
- <Flex align="center" justify="space-between">
+ <Flex
+ align="center"
+ justify="space-between"
+ // add spacing in place of the add button if it is hidden
+ mb={canCreateSharedCollection ? 0 : "sm"}
+ >
<SidebarHeading>{t`External collections`}</SidebarHeading>
- {isAdmin && (
+ {canCreateSharedCollection && (
<Tooltip label={t`Create a shared collection`}>
<ActionIcon
color="text-medium"
@@ -132,7 +131,7 @@ export const MainNavSharedCollections = () => {
)}
</Flex>
<Tree
- data={tenantCollectionTree}
+ data={sharedTenantCollectionTree}
TreeNode={SidebarCollectionLink}
role="tree"
aria-label="tenant-collection-tree"
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
index 8f34facad42..6b47329160d 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/components/MainNavSharedCollections/MainNavSharedCollections.unit.spec.tsx
@@ -21,22 +21,39 @@ const setup = ({
isAdmin = false,
tenantCollections = MOCK_TENANT_COLLECTIONS,
currentUser = createMockUser({ is_superuser: isAdmin }),
+ canWriteToSharedCollectionRoot = false,
}: {
isAdmin?: boolean;
tenantCollections?: Collection[];
currentUser?: ReturnType<typeof createMockUser>;
+ canWriteToSharedCollectionRoot?: boolean;
} = {}) => {
const settings = mockSettings({ "use-tenants": true });
- setupCollectionsEndpoints({ collections: tenantCollections });
- renderWithProviders(<MainNavSharedCollections />, {
- storeInitialState: createMockState({ settings, currentUser }),
+ setupCollectionsEndpoints({
+ collections: tenantCollections,
+ rootCollection: createMockCollection({
+ id: "root",
+ name: "Root shared collection",
+ namespace: "shared-tenant-collection",
+ can_write: canWriteToSharedCollectionRoot,
+ }),
});
+
+ renderWithProviders(
+ <MainNavSharedCollections
+ canCreateSharedCollection={canWriteToSharedCollectionRoot}
+ sharedTenantCollections={tenantCollections}
+ />,
+ {
+ storeInitialState: createMockState({ settings, currentUser }),
+ },
+ );
};
describe("MainNavSharedCollections > create shared tenant collection button", () => {
- it("shows the create button for admin users", async () => {
- setup({ isAdmin: true });
+ it("shows the create button if the user can write to root collection", async () => {
+ setup({ canWriteToSharedCollectionRoot: true });
await screen.findByText("External collections");
expect(screen.getByRole("button", { name: /add/i })).toBeInTheDocument();
@@ -54,7 +71,7 @@ describe("MainNavSharedCollections > create shared tenant collection button", ()
describe("MainNavSharedCollections > new shared collection modal", () => {
it("hides the authority level picker when creating a shared tenant collection", async () => {
- setup({ isAdmin: true });
+ setup({ isAdmin: true, canWriteToSharedCollectionRoot: true });
await screen.findByText("External collections");
const addButton = screen.getByRole("button", { name: /add/i });
@@ -72,8 +89,8 @@ describe("MainNavSharedCollections > new shared collection modal", () => {
});
describe("MainNavSharedCollections > section visibility", () => {
- it("shows the section for admins when there are no collections", async () => {
- setup({ isAdmin: true, tenantCollections: [] });
+ it("shows the section if they can write to root collection", async () => {
+ setup({ canWriteToSharedCollectionRoot: true, tenantCollections: [] });
expect(await screen.findByText("External collections")).toBeInTheDocument();
});
@@ -85,7 +102,11 @@ describe("MainNavSharedCollections > section visibility", () => {
});
it("hides the section for non-admins when there are no collections", () => {
- setup({ isAdmin: false, tenantCollections: [] });
+ setup({
+ isAdmin: false,
+ tenantCollections: [],
+ canWriteToSharedCollectionRoot: false,
+ });
expect(screen.queryByText("External collections")).not.toBeInTheDocument();
});
@@ -100,10 +121,32 @@ describe("MainNavSharedCollections > section visibility", () => {
// Tree endpoint returns an empty array as it is filtered by permissions
fetchMock.get("path:/api/collection/tree", () => []);
- renderWithProviders(<MainNavSharedCollections />, {
- storeInitialState: createMockState({ settings, currentUser }),
+ // Root collection endpoint - user cannot write
+ fetchMock.get("path:/api/collection/root", (call) => {
+ const url = new URL(call.url);
+
+ if (url.searchParams.get("namespace") === "shared-tenant-collection") {
+ return createMockCollection({
+ id: "root",
+ name: "Root shared collection",
+ namespace: "shared-tenant-collection",
+ can_write: false,
+ });
+ }
+
+ return 404;
});
+ renderWithProviders(
+ <MainNavSharedCollections
+ canCreateSharedCollection={false}
+ sharedTenantCollections={[]}
+ />,
+ {
+ storeInitialState: createMockState({ settings, currentUser }),
+ },
+ );
+
expect(screen.queryByText("External collections")).not.toBeInTheDocument();
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
index 514c2530058..cb44e813017 100644
--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx
@@ -8,6 +8,16 @@ import { NewUserModal } from "metabase/admin/people/containers/NewUserModal";
import { UserActivationModal } from "metabase/admin/people/containers/UserActivationModal";
import { UserPasswordResetModal } from "metabase/admin/people/containers/UserPasswordResetModal";
import { UserSuccessModal } from "metabase/admin/people/containers/UserSuccessModal";
+import {
+ useGetCollectionQuery,
+ useListCollectionsTreeQuery,
+} from "metabase/api";
+import { useSetting } from "metabase/common/hooks/use-setting";
+import {
+ type CollectionTreeItem,
+ buildCollectionTree,
+ getCollectionIcon,
+} from "metabase/entities/collections";
import { ModalRoute } from "metabase/hoc/ModalRoute";
import { getGroupNameLocalized } from "metabase/lib/groups";
import { useSelector } from "metabase/lib/redux";
@@ -17,6 +27,7 @@ import {
PLUGIN_TENANTS,
} from "metabase/plugins";
import type { TenantCollectionPathItem } from "metabase/plugins/oss/tenants";
+import { getIsTenantUser } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Text } from "metabase/ui";
import { hasPremiumFeature } from "metabase-enterprise/settings";
@@ -263,5 +274,72 @@ export function initializePlugin() {
path: ["root"],
can_write: false,
};
+
+ PLUGIN_TENANTS.getFlattenedCollectionsForNavbar = ({
+ currentUser,
+ sharedTenantCollections,
+ regularCollections = [],
+ }) => {
+ if (currentUser?.tenant_collection_id) {
+ const sharedTenantCollectionTree = buildCollectionTree(
+ sharedTenantCollections,
+ );
+ const userTenantCollectionId = currentUser?.tenant_collection_id;
+
+ const ourDataCollection: CollectionTreeItem = {
+ id: userTenantCollectionId,
+ name: t`Our data`,
+ description: null,
+ can_write: true,
+ can_restore: false,
+ can_delete: false,
+ archived: false,
+ namespace: null,
+ location: "/",
+ icon: getCollectionIcon({ id: userTenantCollectionId }),
+ children: [],
+ };
+
+ return [
+ ...sharedTenantCollectionTree,
+ ourDataCollection,
+ ...regularCollections,
+ ];
+ }
+
+ // fallback, but should never happen
+ return regularCollections;
+ };
+ PLUGIN_TENANTS.useTenantMainNavbarData = () => {
+ const isTenantUser = useSelector(getIsTenantUser);
+ const useTenants = useSetting("use-tenants");
+
+ const { data: sharedTenantCollections } = useListCollectionsTreeQuery(
+ { namespace: "shared-tenant-collection" },
+ { skip: !useTenants },
+ );
+
+ // Fetch shared collection root for non-tenant users to check write permissions
+ const { data: sharedCollectionRoot } = useGetCollectionQuery(
+ { id: "root", namespace: "shared-tenant-collection" },
+ { skip: !useTenants || isTenantUser },
+ );
+
+ // Non-admins can create shared collections if they have curate permissions on the root shared collection
+ const canCreateSharedCollection =
+ sharedCollectionRoot?.can_write ?? false;
+ const hasVisibleSharedCollections =
+ (sharedTenantCollections?.length ?? 0) > 0;
+ const showExternalCollectionsSection =
+ useTenants &&
+ !isTenantUser &&
+ (hasVisibleSharedCollections || canCreateSharedCollection);
+
+ return {
+ canCreateSharedCollection,
+ showExternalCollectionsSection,
+ sharedTenantCollections,
+ };
+ };
}
}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
index f7ba2495cfc..4ec5ef9f0e2 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
@@ -24,6 +24,7 @@ import {
import { Databases } from "metabase/entities/databases";
import { connect, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
+import { PLUGIN_TENANTS } from "metabase/plugins";
import {
getUser,
getUserCanWriteToCollections,
@@ -111,6 +112,12 @@ function MainNavbarContainer({
"include-library": true,
});
+ const {
+ canCreateSharedCollection,
+ showExternalCollectionsSection,
+ sharedTenantCollections,
+ } = PLUGIN_TENANTS.useTenantMainNavbarData();
+
const collectionTree = useMemo<CollectionTreeItem[]>(() => {
const preparedCollections = [];
const userPersonalCollections = currentUserPersonalCollections(
@@ -205,6 +212,9 @@ function MainNavbarContainer({
handleCreateNewCollection={onCreateNewCollection}
handleCloseNavbar={closeNavbar}
handleLogout={logout}
+ sharedTenantCollections={sharedTenantCollections}
+ canCreateSharedCollection={canCreateSharedCollection}
+ showExternalCollectionsSection={showExternalCollectionsSection}
/>
{modal && <Modal onClose={closeModal}>{renderModalContent()}</Modal>}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
index bff091d1f51..557290ceb3b 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
@@ -28,9 +28,13 @@ import {
PLUGIN_REMOTE_SYNC,
PLUGIN_TENANTS,
} from "metabase/plugins";
-import { getUserCanWriteToCollections } from "metabase/selectors/user";
+import {
+ getIsTenantUser,
+ getUser,
+ getUserCanWriteToCollections,
+} from "metabase/selectors/user";
import { ActionIcon, Icon, Tooltip } from "metabase/ui";
-import type { Bookmark } from "metabase-types/api";
+import type { Bookmark, Collection } from "metabase-types/api";
import {
PaddedSidebarLink,
@@ -58,6 +62,9 @@ type Props = {
hasDataAccess: boolean;
collections: CollectionTreeItem[];
selectedItems: SelectedItem[];
+ sharedTenantCollections?: Collection[];
+ canCreateSharedCollection: boolean;
+ showExternalCollectionsSection: boolean;
handleCloseNavbar: () => void;
handleLogout: () => void;
handleCreateNewCollection: () => void;
@@ -80,6 +87,9 @@ export function MainNavbarView({
reorderBookmarks,
handleCreateNewCollection,
handleCloseNavbar,
+ sharedTenantCollections,
+ canCreateSharedCollection,
+ showExternalCollectionsSection,
}: Props) {
const [expandBookmarks = true, setExpandBookmarks] = useUserSetting(
"expand-bookmarks-in-nav",
@@ -90,6 +100,9 @@ export function MainNavbarView({
const isAtHomepageDashboard = useIsAtHomepageDashboard();
const canWriteToCollections = useSelector(getUserCanWriteToCollections);
+ const currentUser = useSelector(getUser);
+ const useTenants = useSetting("use-tenants");
+ const isTenantUser = useSelector(getIsTenantUser);
const [
addDataModalOpened,
@@ -139,9 +152,22 @@ export function MainNavbarView({
return {
...collectionsByCategory,
- regularCollections,
+ regularCollections:
+ useTenants && isTenantUser
+ ? PLUGIN_TENANTS.getFlattenedCollectionsForNavbar({
+ currentUser,
+ sharedTenantCollections,
+ regularCollections,
+ })
+ : regularCollections,
};
- }, [collections]);
+ }, [
+ collections,
+ isTenantUser,
+ useTenants,
+ sharedTenantCollections,
+ currentUser,
+ ]);
const isNewInstance = useSelector(getIsNewInstance);
const canAccessOnboarding = useSelector(getCanAccessOnboardingPage);
@@ -151,8 +177,7 @@ export function MainNavbarView({
const areThereOtherUsers = (activeUsersCount ?? 0) > 1;
const showOtherUsersCollections = isAdmin && areThereOtherUsers;
- const useTenants = useSetting("use-tenants");
- const collectionsHeading = useTenants
+ const collectionsHeading = showExternalCollectionsSection
? t`Internal Collections`
: t`Collections`;
@@ -211,7 +236,13 @@ export function MainNavbarView({
</SidebarSection>
)}
- <PLUGIN_TENANTS.MainNavSharedCollections />
+ {/* Tenant users don't see the section about "External collections" */}
+ {showExternalCollectionsSection && (
+ <PLUGIN_TENANTS.MainNavSharedCollections
+ canCreateSharedCollection={canCreateSharedCollection}
+ sharedTenantCollections={sharedTenantCollections}
+ />
+ )}
{PLUGIN_DATA_STUDIO.isEnabled && (
<PLUGIN_DATA_STUDIO.NavbarLibrarySection
@@ -230,7 +261,7 @@ export function MainNavbarView({
iconSize={8}
onToggle={setExpandCollections}
rightAction={
- canWriteToCollections ? (
+ canWriteToCollections && !isTenantUser ? (
<Tooltip label={t`Create a new collection`}>
<ActionIcon
aria-label={t`Create a new collection`}
diff --git a/frontend/src/metabase/plugins/oss/tenants.ts b/frontend/src/metabase/plugins/oss/tenants.ts
index 98142a540fa..6d3d1a6cec1 100644
--- a/frontend/src/metabase/plugins/oss/tenants.ts
+++ b/frontend/src/metabase/plugins/oss/tenants.ts
@@ -1,6 +1,7 @@
import type React from "react";
import type { CollectionItemListProps } from "metabase/common/components/Pickers/CollectionPicker/types";
+import type { CollectionTreeItem } from "metabase/entities/collections/utils";
import type {
Collection,
CollectionId,
@@ -36,7 +37,10 @@ const getDefaultPluginTenants = () => ({
ReactivateExternalUserButton: ({ user: _user }: { user: User }) =>
null as React.ReactElement | null,
TenantGroupHintIcon: PluginPlaceholder,
- MainNavSharedCollections: PluginPlaceholder,
+ MainNavSharedCollections: PluginPlaceholder as React.ComponentType<{
+ canCreateSharedCollection: boolean;
+ sharedTenantCollections: Collection[] | undefined;
+ }>,
TenantCollectionItemList: (_props: CollectionItemListProps) =>
null as React.ReactElement | null,
TenantSpecificCollectionsItemList: (_props: CollectionItemListProps) =>
@@ -62,11 +66,22 @@ const getDefaultPluginTenants = () => ({
path: CollectionId[];
can_write: boolean;
} | null,
+ getFlattenedCollectionsForNavbar: () => [],
+ useTenantMainNavbarData: () => ({
+ canCreateSharedCollection: false,
+ showExternalCollectionsSection: false,
+ sharedTenantCollections: [],
+ }),
});
export const PLUGIN_TENANTS: {
isEnabled: boolean;
userStrategyRoute: React.ReactElement | null;
+ useTenantMainNavbarData: () => {
+ canCreateSharedCollection: boolean;
+ showExternalCollectionsSection: boolean;
+ sharedTenantCollections: Collection[] | undefined;
+ };
tenantsRoutes: React.ReactElement | null;
EditUserStrategySettingsButton: React.ComponentType;
FormTenantWidget: (props: any) => React.ReactElement | null;
@@ -80,7 +95,10 @@ export const PLUGIN_TENANTS: {
user: User;
}) => React.ReactElement | null;
TenantGroupHintIcon: React.ComponentType;
- MainNavSharedCollections: React.ComponentType;
+ MainNavSharedCollections: React.ComponentType<{
+ canCreateSharedCollection: boolean;
+ sharedTenantCollections: Collection[] | undefined;
+ }>;
TenantCollectionItemList: (
props: CollectionItemListProps,
) => React.ReactElement | null;
@@ -107,6 +125,11 @@ export const PLUGIN_TENANTS: {
path: CollectionId[];
can_write: boolean;
} | null;
+ getFlattenedCollectionsForNavbar: (args: {
+ currentUser: User | null;
+ sharedTenantCollections: Collection[] | undefined;
+ regularCollections: CollectionTreeItem[];
+ }) => CollectionTreeItem[];
} = getDefaultPluginTenants();
/**
diff --git a/frontend/src/metabase/selectors/user.ts b/frontend/src/metabase/selectors/user.ts
index 39d025f06ab..ea854311640 100644
--- a/frontend/src/metabase/selectors/user.ts
+++ b/frontend/src/metabase/selectors/user.ts
@@ -59,3 +59,8 @@ export const getUserCanWriteToCollections = createSelector(
[getUser],
(user) => user?.can_write_any_collection,
);
+
+export const getIsTenantUser = createSelector(
+ [getUser],
+ (user) => user?.tenant_id != null,
+);