Skip to content

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

feat(embedding-hub): add "copy dashboard to shared tenant collection" step (#70726)

Nicolò Pretto446de63944fd
diff --git a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
index 235e22496fb..8c95a57b956 100644
--- a/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/embedding-hub/embedding-hub.cy.spec.ts
@@ -362,6 +362,27 @@ describe("scenarios - embedding hub", () => {
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
+ cy.log("create an x-ray dashboard via the embedding setup guide");
+ cy.visit("/admin/embedding/setup-guide");
+
+ cy.findByTestId("admin-layout-content")
+ .findByText("Create a dashboard")
+ .click();
+
+ cy.log("select Orders table from the modal");
+ H.modal().within(() => {
+ H.pickEntity({
+ path: ["Databases", "Sample Database", "Orders"],
+ });
+ });
+
+ cy.log("wait for x-ray dashboard to generate and save it");
+ H.main()
+ .findByText("A look at", { exact: false, timeout: 30_000 })
+ .should("be.visible");
+ cy.button("Save this").click();
+ H.undoToast().should("contain", "Your dashboard was saved");
+
cy.visit("/admin/embedding/setup-guide/permissions");
cy.log("tenants should not be enabled");
@@ -399,6 +420,44 @@ describe("scenarios - embedding hub", () => {
expect(response.body[0].name).to.equal("Shared collection");
});
+ cy.log(
+ "dashboard picker should appear with the x-ray dashboard pre-selected",
+ );
+ H.main()
+ .findByText("This will allow tenant users to see it.")
+ .should("be.visible");
+
+ cy.log("x-ray dashboard should be pre-selected, move it");
+ H.main()
+ .findByRole("button", {
+ name: "Move to shared collection",
+ timeout: 10_000,
+ })
+ .should("be.enabled")
+ .click();
+
+ cy.log(
+ "x-rayed dashboard should have been moved to the shared collection",
+ );
+ cy.request(
+ "GET",
+ "/api/collection/tree?namespace=shared-tenant-collection",
+ ).then((response) => {
+ const sharedCollectionId = response.body[0].id;
+ cy.request(
+ "GET",
+ `/api/collection/${sharedCollectionId}/items?models=dashboard`,
+ ).then((itemsResponse) => {
+ const dashboards = itemsResponse.body.data;
+ expect(dashboards.length).to.be.greaterThan(0);
+ expect(
+ dashboards.some((d: { name: string }) =>
+ d.name.includes("A look at"),
+ ),
+ ).to.be.true;
+ });
+ });
+
cy.log("enable-tenants step should be marked as completed");
H.main()
.findByRole("listitem", {
@@ -408,6 +467,14 @@ describe("scenarios - embedding hub", () => {
timeout: 10_000,
})
.should("have.attr", "data-completed", "true");
+
+ cy.log("move-dashboard step should be marked as completed");
+ H.main()
+ .findByRole("listitem", {
+ name: "Create a dashboard in the shared collection",
+ timeout: 10_000,
+ })
+ .should("have.attr", "data-completed", "true");
});
it("enable-tenants step should not be marked as completed when tenants are enabled but no shared collection exists", () => {
@@ -480,6 +547,11 @@ describe("scenarios - embedding hub", () => {
.should("be.enabled")
.click();
+ cy.log("complete the move-dashboard step");
+ H.main()
+ .findByRole("button", { name: "Create a sample dashboard" })
+ .click();
+
cy.log("select database routing strategy");
H.main()
.findByRole("radio", { name: /Database routing/ })
@@ -731,6 +803,11 @@ describe("scenarios - embedding hub", () => {
.icon("check")
.should("exist");
+ cy.log("complete the move-dashboard step");
+ H.main()
+ .findByRole("button", { name: "Create a sample dashboard" })
+ .click();
+
cy.log("use row and column level security");
H.main()
.findByRole("radio", { name: /Row and column level security/ })
@@ -789,6 +866,11 @@ describe("scenarios - embedding hub", () => {
.icon("check")
.should("exist");
+ cy.log("complete the move-dashboard step");
+ H.main()
+ .findByRole("button", { name: "Create a sample dashboard" })
+ .click();
+
cy.log("use row and column level security");
H.main()
.findByRole("radio", { name: /Row and column level security/ })
@@ -885,6 +967,11 @@ describe("scenarios - embedding hub", () => {
.icon("check")
.should("exist");
+ cy.log("complete the move-dashboard step");
+ H.main()
+ .findByRole("button", { name: "Create a sample dashboard" })
+ .click();
+
H.main()
.findByRole("radio", { name: /Row and column level security/ })
.scrollIntoView()
@@ -1016,11 +1103,16 @@ describe("scenarios - embedding hub", () => {
cy.log("enable tenants to create the all-external-users");
H.updateSetting("use-tenants", true);
- cy.log("create shared collection");
+ cy.log("create shared collection with a dashboard");
cy.request("POST", "/api/collection", {
name: "Shared collection",
parent_id: null,
namespace: "shared-tenant-collection",
+ }).then(({ body: collection }) => {
+ H.createDashboard({
+ name: "Test Dashboard",
+ collection_id: collection.id,
+ });
});
cy.log("create an existing sandbox for Orders table via API");
@@ -1042,11 +1134,7 @@ describe("scenarios - embedding hub", () => {
cy.visit("/admin/embedding/setup-guide/permissions");
- cy.log("wait for create tenants step to be active and unlocked");
- H.main()
- .findByRole("listitem", { name: "Create tenants" })
- .should("have.attr", "data-active", "true");
-
+ cy.log("open the data segregation strategy step");
H.main()
.findByText("Which data segregation strategy does your database use?")
.scrollIntoView()
@@ -1145,6 +1233,11 @@ describe("scenarios - embedding hub", () => {
.icon("check")
.should("exist");
+ cy.log("complete the move-dashboard step");
+ H.main()
+ .findByRole("button", { name: "Create a sample dashboard" })
+ .click();
+
cy.log("select RLS strategy");
H.main()
.findByRole("radio", { name: /Row and column level security/ })
@@ -1260,6 +1353,11 @@ describe("scenarios - embedding hub", () => {
cy.request("POST", "/api/collection", {
name: "Shared collection",
namespace: "shared-tenant-collection",
+ }).then(({ body: collection }) => {
+ H.createDashboard({
+ name: "Test Dashboard",
+ collection_id: collection.id,
+ });
});
});
@@ -1475,6 +1573,11 @@ describe("scenarios - embedding hub", () => {
cy.request("POST", "/api/collection", {
name: "Shared collection",
namespace: "shared-tenant-collection",
+ }).then(({ body: collection }) => {
+ H.createDashboard({
+ name: "Test Dashboard",
+ collection_id: collection.id,
+ });
});
});
diff --git a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
index 90d7121e6db..67f837e115c 100644
--- a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj
@@ -61,6 +61,14 @@
[:= :namespace "shared-tenant-collection"]
[:= :archived false]]}))
+(defn- shared-collection-has-dashboards? []
+ (when-let [shared-coll-id (t2/select-one-pk :model/Collection {:where [:and
+ [:= :namespace "shared-tenant-collection"]
+ [:= :archived false]]})]
+ (t2/exists? :model/Dashboard {:where [:and
+ [:= :collection_id shared-coll-id]
+ [:= :archived false]]})))
+
(defn- has-configured-data-segregation-strategy? []
;; Check if any of the 3 data segregation strategies are enabled:
;; 1. Row and Column Level Security (Sandboxing)
@@ -102,6 +110,7 @@
;; for the "configure data permissions and enable tenants" sub-checklist page
"enable-tenants" enable-tenants?
+ "move-dashboard-to-shared" (boolean (shared-collection-has-dashboards?))
"create-tenants" create-tenants?
"setup-data-segregation-strategy" setup-data-segregation-strategy?
@@ -125,6 +134,7 @@
["sso-configured" :boolean]
["data-permissions-and-enable-tenants" :boolean]
["enable-tenants" :boolean]
+ ["move-dashboard-to-shared" :boolean]
["create-tenants" :boolean]
["setup-data-segregation-strategy" :boolean]
["sso-auth-manual-tested" :boolean]]]
diff --git a/frontend/src/metabase/api/embedding-hub.ts b/frontend/src/metabase/api/embedding-hub.ts
index c7294beb921..a54d1024ce1 100644
--- a/frontend/src/metabase/api/embedding-hub.ts
+++ b/frontend/src/metabase/api/embedding-hub.ts
@@ -11,6 +11,7 @@ type CheckListApiStep =
| "embed-production"
| "sso-configured"
| "enable-tenants"
+ | "move-dashboard-to-shared"
| "create-tenants"
| "setup-data-segregation-strategy"
| "data-permissions-and-enable-tenants"
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.tsx
new file mode 100644
index 00000000000..8dd5ee886bd
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.tsx
@@ -0,0 +1,149 @@
+import { useCallback, useState } from "react";
+import { t } from "ttag";
+
+import { useListCollectionsTreeQuery } from "metabase/api";
+import { getErrorMessage } from "metabase/api/utils";
+import { DashboardSelector } from "metabase/common/components/DashboardSelector";
+import { useToast } from "metabase/common/hooks";
+import { Box, Button, Divider, Group, Stack, Text } from "metabase/ui";
+import type { CollectionItem, DashboardId } from "metabase-types/api";
+
+import {
+ useCreateSampleDashboardInSharedCollection,
+ useMoveXrayDashboardToSharedCollection,
+} from "./hooks/use-xray-dashboards";
+
+interface MoveDashboardStepContentProps {
+ isMoveDashboardDone: boolean;
+ hasXrayDashboard: boolean;
+ lastDashboard: CollectionItem | null;
+ onCompleted: () => void;
+}
+
+export const MoveDashboardStepContent = ({
+ isMoveDashboardDone,
+ hasXrayDashboard,
+ lastDashboard,
+ onCompleted,
+}: MoveDashboardStepContentProps) => {
+ const [sendToast] = useToast();
+
+ const { data: sharedTenantCollections } = useListCollectionsTreeQuery({
+ namespace: "shared-tenant-collection",
+ });
+
+ const sharedCollectionId =
+ sharedTenantCollections && sharedTenantCollections.length > 0
+ ? sharedTenantCollections[0].id
+ : null;
+
+ const { moveDashboard, isMoving } = useMoveXrayDashboardToSharedCollection();
+ const { createSampleDashboard, isCreating } =
+ useCreateSampleDashboardInSharedCollection();
+
+ const [selectedDashboardId, setSelectedDashboardId] =
+ useState<DashboardId | null>(null);
+
+ // Use the manually picked dashboard, or fall back to the last x-ray dashboard
+ const effectiveDashboardId =
+ selectedDashboardId ?? (lastDashboard ? lastDashboard.id : null);
+
+ const handleMoveDashboard = useCallback(async () => {
+ if (!effectiveDashboardId || !sharedCollectionId) {
+ return;
+ }
+
+ try {
+ await moveDashboard(Number(effectiveDashboardId), sharedCollectionId);
+ onCompleted();
+ } catch (error) {
+ sendToast({
+ icon: "warning",
+ toastColor: "error",
+ message: getErrorMessage(
+ error,
+ t`Failed to move dashboard to the shared collection`,
+ ),
+ });
+ }
+ }, [
+ effectiveDashboardId,
+ sharedCollectionId,
+ moveDashboard,
+ sendToast,
+ onCompleted,
+ ]);
+
+ const handleCreateSampleDashboard = useCallback(async () => {
+ if (!sharedCollectionId) {
+ return;
+ }
+
+ try {
+ await createSampleDashboard(sharedCollectionId);
+ onCompleted();
+ } catch (error) {
+ sendToast({
+ icon: "warning",
+ toastColor: "error",
+ message: getErrorMessage(error, t`Failed to create a sample dashboard`),
+ });
+ }
+ }, [sharedCollectionId, createSampleDashboard, sendToast, onCompleted]);
+
+ if (isMoveDashboardDone) {
+ return (
+ <Stack gap="md">
+ <Text size="md" c="text-secondary" lh="lg">
+ {t`The shared collection already has dashboards.`}
+ </Text>
+ <Group justify="flex-end">
+ <Button variant="filled" onClick={onCompleted}>
+ {t`Continue`}
+ </Button>
+ </Group>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack gap="md">
+ <Text size="md" c="text-secondary" lh="lg">
+ {t`This will allow tenant users to see it.`}
+ </Text>
+
+ {hasXrayDashboard && (
+ <>
+ <Group gap="sm" align="center">
+ <Box flex="1">
+ <DashboardSelector
+ value={effectiveDashboardId ?? undefined}
+ onChange={(id) => setSelectedDashboardId(id ?? null)}
+ />
+ </Box>
+ <Button
+ variant="filled"
+ onClick={handleMoveDashboard}
+ loading={isMoving}
+ disabled={!effectiveDashboardId}
+ >
+ {t`Move to shared collection`}
+ </Button>
+ </Group>
+
+ <Divider label={t`or`} />
+ </>
+ )}
+
+ <Group justify={hasXrayDashboard ? "center" : "flex-end"}>
+ <Button
+ variant={hasXrayDashboard ? "default" : "filled"}
+ onClick={handleCreateSampleDashboard}
+ loading={isCreating}
+ >
+ {t`Create a sample dashboard`}
+ </Button>
+ </Group>
+ </Stack>
+ );
+};
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx
new file mode 100644
index 00000000000..0f736f79409
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/MoveDashboardStepContent.unit.spec.tsx
@@ -0,0 +1,159 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupCollectionTreeEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
+
+import { MoveDashboardStepContent } from "./MoveDashboardStepContent";
+
+const SHARED_COLLECTION = createMockCollection({
+ id: 42,
+ name: "Shared collection",
+});
+
+const XRAY_DASHBOARD = createMockCollectionItem({
+ id: 200,
+ name: "A look at Invoices",
+ model: "dashboard",
+});
+
+function setup({
+ isMoveDashboardDone = false,
+ hasXrayDashboard = false,
+}: {
+ isMoveDashboardDone?: boolean;
+ hasXrayDashboard?: boolean;
+} = {}) {
+ const onCompleted = jest.fn();
+ const lastDashboard = hasXrayDashboard ? XRAY_DASHBOARD : null;
+
+ // Shared tenant collections tree (still needed for sharedCollectionId)
+ setupCollectionTreeEndpoint([SHARED_COLLECTION]);
+
+ if (hasXrayDashboard) {
+ // DashboardSelector fetches the dashboard details
+ fetchMock.get("path:/api/dashboard/200", {
+ id: 200,
+ name: "A look at Invoices",
+ collection_id: 99,
+ dashcards: [],
+ });
+ }
+
+ renderWithProviders(
+ <MoveDashboardStepContent
+ isMoveDashboardDone={isMoveDashboardDone}
+ hasXrayDashboard={hasXrayDashboard}
+ lastDashboard={lastDashboard}
+ onCompleted={onCompleted}
+ />,
+ );
+
+ return { onCompleted };
+}
+
+describe("MoveDashboardStepContent", () => {
+ it('shows "Continue" when shared collection already has dashboards', async () => {
+ setup({ isMoveDashboardDone: true });
+
+ expect(await screen.findByText("Continue")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Move to shared collection"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Create a sample dashboard"),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows only "Create a sample dashboard" when no xray dashboard exists', async () => {
+ setup({ hasXrayDashboard: false });
+
+ expect(
+ await screen.findByText("Create a sample dashboard"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Move to shared collection"),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows both "Move" and "Create" when xray dashboard exists', async () => {
+ setup({ hasXrayDashboard: true });
+
+ expect(
+ await screen.findByText("Move to shared collection"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Create a sample dashboard")).toBeInTheDocument();
+ });
+
+ it("moves dashboard to shared collection when Move button is clicked", async () => {
+ fetchMock.put("path:/api/dashboard/200", 200);
+
+ const { onCompleted } = setup({ hasXrayDashboard: true });
+
+ const moveButton = await screen.findByText("Move to shared collection");
+ await userEvent.click(moveButton);
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/dashboard/200", {
+ method: "PUT",
+ }),
+ ).toHaveLength(1);
+ });
+
+ const lastCall = fetchMock.callHistory.lastCall("path:/api/dashboard/200", {
+ method: "PUT",
+ });
+ expect(await lastCall?.request?.json()).toEqual(
+ expect.objectContaining({ collection_id: 42 }),
+ );
+
+ await waitFor(() => {
+ expect(onCompleted).toHaveBeenCalled();
+ });
+ });
+
+ it("creates a sample dashboard when Create button is clicked", async () => {
+ fetchMock.post("path:/api/dashboard", {
+ id: 999,
+ name: "Sample dashboard",
+ collection_id: 42,
+ dashcards: [],
+ });
+ fetchMock.put("path:/api/dashboard/999", 200);
+
+ const { onCompleted } = setup({ hasXrayDashboard: false });
+
+ const createButton = await screen.findByText("Create a sample dashboard");
+ await userEvent.click(createButton);
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/dashboard", { method: "POST" }),
+ ).toHaveLength(1);
+ });
+
+ const postCall = fetchMock.callHistory.lastCall("path:/api/dashboard", {
+ method: "POST",
+ });
+ expect(await postCall?.request?.json()).toEqual(
+ expect.objectContaining({ name: "Sample dashboard", collection_id: 42 }),
+ );
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/dashboard/999", {
+ method: "PUT",
+ }),
+ ).toHaveLength(1);
+ });
+
+ await waitFor(() => {
+ expect(onCompleted).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/SetupPermissionsAndTenantsPage.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/SetupPermissionsAndTenantsPage.tsx
index 74c3e9f77ab..179de6f6f41 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/SetupPermissionsAndTenantsPage.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/SetupPermissionsAndTenantsPage.tsx
@@ -19,9 +19,11 @@ import {
} from "./DataSegregationStrategyPicker";
import { DatabaseRoutingStepContent } from "./DatabaseRoutingStepContent";
import { EnableTenantsStepContent } from "./EnableTenantsStepContent";
+import { MoveDashboardStepContent } from "./MoveDashboardStepContent";
import type { RlsSelectionResult } from "./RlsDataSelector";
import { RlsDataSelector } from "./RlsDataSelector";
import S from "./SetupPermissionsAndTenantsPage.module.css";
+import { useLastXrayDashboard } from "./hooks/use-xray-dashboards";
const SETUP_GUIDE_PATH = "/admin/embedding/setup-guide";
@@ -48,6 +50,11 @@ export const SetupPermissionsAndTenantsPage = () => {
columnName: null,
});
+ const isMoveDashboardDone = checklist?.["move-dashboard-to-shared"] ?? false;
+
+ const { lastDashboard, isLoading: isLoadingXray } = useLastXrayDashboard();
+ const hasXrayDashboard = !isLoadingXray && lastDashboard != null;
+
// Prefer in-session UI state; fall back to backend detection for reloads
const activeStrategy =
selectedStrategy ?? checklistResponse?.["data-isolation-strategy"] ?? null;
@@ -67,6 +74,7 @@ export const SetupPermissionsAndTenantsPage = () => {
const completedSteps = useMemo(() => {
return {
"enable-tenants": isTenantsEnabled,
+ "move-dashboard": isMoveDashboardDone,
"data-segregation": isPickDataStrategyDone,
"select-data": isDataSegregationSetupDone,
"create-tenants": isTenantsCreated,
@@ -76,6 +84,7 @@ export const SetupPermissionsAndTenantsPage = () => {
};
}, [
isTenantsEnabled,
+ isMoveDashboardDone,
isPickDataStrategyDone,
isDataSegregationSetupDone,
isTenantsCreated,
@@ -83,6 +92,9 @@ export const SetupPermissionsAndTenantsPage = () => {
const lockedSteps = useMemo(() => {
return {
+ // The shared tenant collection is created when tenants are enabled,
+ // so the move-dashboard step can't work until that's done.
+ "move-dashboard": !isTenantsEnabled,
// Unlock once we know the strategy — either from in-session confirmation
// or from the backend on reload.
"select-data": activeStrategy === null,
@@ -127,6 +139,22 @@ export const SetupPermissionsAndTenantsPage = () => {
<EnableTenantsStepContent isTenantsEnabled={isTenantsEnabled} />
</OnboardingStepper.Step>
+ <OnboardingStepper.Step
+ stepId="move-dashboard"
+ title={
+ hasXrayDashboard
+ ? t`Move a dashboard to the shared collection`
+ : t`Create a dashboard in the shared collection`
+ }
+ >
+ <MoveDashboardStepContent
+ isMoveDashboardDone={isMoveDashboardDone}
+ hasXrayDashboard={hasXrayDashboard}
+ lastDashboard={lastDashboard}
+ onCompleted={() => stepperRef.current?.goToNextStep()}
+ />
+ </OnboardingStepper.Step>
+
<OnboardingStepper.Step
stepId="data-segregation"
title={t`Which data segregation strategy does your database use?`}
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts
new file mode 100644
index 00000000000..2c09c7bf5e3
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupPermissionsAndTenantsPage/hooks/use-xray-dashboards.ts
@@ -0,0 +1,129 @@
+import { useCallback, useState } from "react";
+import { t } from "ttag";
+
+import {
+ Api,
+ skipToken,
+ useCreateDashboardMutation,
+ useListCollectionItemsQuery,
+ useUpdateDashboardMutation,
+} from "metabase/api";
+import { listTag } from "metabase/api/tags";
+import { createDashCard, createVirtualCard } from "metabase/dashboard/utils";
+import { useDispatch } from "metabase/lib/redux";
+import type {
+ CollectionId,
+ CollectionItem,
+ DashboardCard,
+} from "metabase-types/api";
+
+// This name is hardcoded in the backend (see xrays/automagic_dashboards/populate.clj).
+// There is no special collection type — the name is the canonical identifier.
+const AUTO_GENERATED_DASHBOARDS_COLLECTION_NAME =
+ "Automatically Generated Dashboards";
+
+/**
+ * Returns the most recently edited dashboard from the
+ * "Automatically Generated Dashboards" collection, useful for pre-filling
+ * the dashboard picker.
+ */
+export const useLastXrayDashboard = () => {
+ const { data: rootItems, isLoading: isLoadingRoot } =
+ useListCollectionItemsQuery({
+ id: "root",
+ models: ["collection"],
+ });
+
+ const autoGenCollection = rootItems?.data.find(
+ (item: CollectionItem) =>
+ item.name === AUTO_GENERATED_DASHBOARDS_COLLECTION_NAME,
+ );
+
+ const { data: dashboardItems, isLoading: isLoadingDashboards } =
+ useListCollectionItemsQuery(
+ autoGenCollection
+ ? {
+ id: autoGenCollection.id,
+ models: ["dashboard"],
+ sort_column: "last_edited_at",
+ sort_direction: "desc",
+ }
+ : skipToken,
+ );
+
+ const dashboards = dashboardItems?.data ?? [];
+ const lastDashboard = dashboards.length > 0 ? dashboards[0] : null;
+
+ return {
+ lastDashboard,
+ isLoading: isLoadingRoot || isLoadingDashboards,
+ };
+};
+
+export const useMoveXrayDashboardToSharedCollection = () => {
+ const dispatch = useDispatch();
+ const [updateDashboard, { isLoading: isMoving }] =
+ useUpdateDashboardMutation();
+
+ const moveDashboard = useCallback(
+ async (
+ dashboardId: number,
+ targetCollectionId: CollectionId,
+ ): Promise<void> => {
+ await updateDashboard({
+ id: dashboardId,
+ collection_id: targetCollectionId,
+ }).unwrap();
+
+ dispatch(Api.util.invalidateTags([listTag("embedding-hub-checklist")]));
+ },
+ [updateDashboard, dispatch],
+ );
+
+ return { moveDashboard, isMoving };
+};
+
+export const useCreateSampleDashboardInSharedCollection = () => {
+ const dispatch = useDispatch();
+ const [createDashboard] = useCreateDashboardMutation();
+ const [updateDashboard] = useUpdateDashboardMutation();
+ const [isCreating, setIsCreating] = useState(false);
+
+ const createSampleDashboard = useCallback(
+ async (targetCollectionId: CollectionId): Promise<void> => {
+ setIsCreating(true);
+ try {
+ const dashboard = await createDashboard({
+ name: t`Sample dashboard`,
+ collection_id: targetCollectionId,
+ }).unwrap();
+
+ const virtualCard = createVirtualCard("text");
+ const dashcard = createDashCard({
+ dashboard_id: dashboard.id,
+ card: virtualCard,
+ row: 0,
+ col: 0,
+ size_x: 18,
+ size_y: 2,
+ visualization_settings: {
+ virtual_card: virtualCard,
+ text: t`Hello, world!`,
+ },
+ });
+
+ await updateDashboard({
+ id: dashboard.id,
+ dashcards: [dashcard as DashboardCard],
+ }).unwrap();
+
+ dispatch(Api.util.invalidateTags([listTag("embedding-hub-checklist")]));
+ } finally {
+ setIsCreating(false);
+ }
+ },
+ [createDashboard, updateDashboard, dispatch],
+ );
+
+ return { createSampleDashboard, isCreating };
+};