The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix deletion of tenant collections (#74536)
Romeo Van Snickb6fe71475dc1
diff --git a/e2e/test/scenarios/collections/tenant-collection-trash.cy.spec.ts b/e2e/test/scenarios/collections/tenant-collection-trash.cy.spec.tsnew file mode 100644index 00000000000..0aca8a94a22--- /dev/null+++ b/e2e/test/scenarios/collections/tenant-collection-trash.cy.spec.ts@@ -0,0 +1,63 @@+const { H } = cy;++const TENANT_NAMESPACE = "shared-tenant-collection";+const TENANT_COLLECTION_NAME = "Acme Tenant Collection";++/**+ * Create a collection in the shared-tenant-collection namespace, the kind of+ * collection an admin adds when tenants are enabled.+ */+function createTenantCollection(name: string) {+ return cy+ .request("POST", "/api/collection", {+ name,+ namespace: TENANT_NAMESPACE,+ parent_id: null,+ })+ .then(({ body }) => body);+}++function archiveBanner() {+ return cy.findByTestId("archive-banner");+}++describe("scenarios > collections > tenant collection trash", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ H.activateToken("bleeding-edge");+ H.updateSetting("use-tenants", true);+ });++ it("can permanently delete a trashed shared tenant collection (metabase#74461)", () => {+ cy.intercept("DELETE", "/api/collection/*").as("deleteCollection");++ createTenantCollection(TENANT_COLLECTION_NAME).then((collection) => {+ H.archiveCollection(collection.id);++ cy.visit(`/collection/${collection.id}`);++ cy.log("the trashed collection page shows the archived banner");+ archiveBanner().should("be.visible");++ cy.log("permanently delete it from the banner");+ archiveBanner().findByText("Delete permanently").click();+ H.modal()+ .findByText(`Delete ${TENANT_COLLECTION_NAME} permanently?`)+ .should("be.visible");+ H.modal().findByText("Delete permanently").click();++ cy.log("the delete request succeeds rather than failing with a 400");+ cy.wait("@deleteCollection").its("response.statusCode").should("eq", 200);++ cy.log("the collection is gone from the database");+ cy.request({+ method: "GET",+ url: `/api/collection/${collection.id}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 404);+ });+ });+});diff --git a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/api_test.cljindex 2113d5383bd..17fdf23e490 100644--- a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj@@ -654,6 +654,24 @@(is (= #{"Normal Collection" "Shared Tenant Collection" "Tenant Specific Collection"}trash-items)))))))))+(deftest tenant-collections-can-be-permanently-deleted-from-trash-test+ (testing "DELETE /api/collection/:id"+ (testing "archived tenant collections can be permanently deleted (#74148)"+ (mt/with-premium-features #{:tenants}+ (mt/with-temporary-setting-values [use-tenants true]+ (mt/with-temp [:model/Collection {normal-id :id} {:name "Normal Collection"}+ :model/Collection {shared-id :id} {:name "Shared Tenant Collection"+ :namespace "shared-tenant-collection"}+ :model/Collection {tenant-id :id} {:name "Tenant Specific Collection"+ :namespace "tenant-specific"}]+ ;; collections must be trashed before they can be deleted+ (doseq [id [normal-id shared-id tenant-id]]+ (mt/user-http-request :crowberto :put 200 (str "collection/" id) {:archived true}))+ (testing "every trashed collection is permanently deleted, regardless of namespace"+ (doseq [id [normal-id shared-id tenant-id]]+ (mt/user-http-request :crowberto :delete 200 (str "collection/" id))+ (is (not (t2/exists? :model/Collection :id id)))))))))))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | Tenant Deactivation Archives Collections Tests |;;; +----------------------------------------------------------------------------------------------------------------+diff --git a/frontend/src/metabase/archive/hooks/use-delete-item.ts b/frontend/src/metabase/archive/hooks/use-delete-item.tsindex d6c1662d273..94f23c7472d 100644--- a/frontend/src/metabase/archive/hooks/use-delete-item.ts+++ b/frontend/src/metabase/archive/hooks/use-delete-item.ts@@ -52,7 +52,10 @@ export function useDeleteItem() {const [deleteDocument] = useDeleteDocumentMutation();return useCallback(- async (item: DeletableItem) => {+ async (+ item: DeletableItem,+ { notify = true }: { notify?: boolean } = {},+ ) => {await match(item).with({ model: "card" },@@ -69,7 +72,9 @@ export function useDeleteItem() {).exhaustive();- sendToast({ message: t`This item has been permanently deleted.` });+ if (notify) {+ sendToast({ message: t`This item has been permanently deleted.` });+ }},[sendToast, deleteCard, deleteDashboard, deleteCollection, deleteDocument],);diff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsxindex 337f7f2ad78..1d685726063 100644--- a/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.tsx@@ -82,18 +82,30 @@ export const ArchivedBulkActions = ({};const handleBulkDeletePermanently = async () => {- const actions = selected.filter(canDelete).map((item) => deleteItem(item));- Promise.all(actions).finally(unselect);- dispatch(- addUndo({- message: ngettext(- msgid`${selected.length} item has been permanently deleted.`,- `${selected.length} items have been permanently deleted.`,- selected.length,- ),- canDismiss: true,- }),- );+ const itemsToDelete = selected.filter(canDelete);+ try {+ await Promise.all(+ itemsToDelete.map((item) => deleteItem(item, { notify: false })),+ );+ dispatch(+ addUndo({+ message: ngettext(+ msgid`${itemsToDelete.length} item has been permanently deleted.`,+ `${itemsToDelete.length} items have been permanently deleted.`,+ itemsToDelete.length,+ ),+ canDismiss: true,+ }),+ );+ } catch {+ dispatch(+ addUndo({+ message: t`There was an error permanently deleting these items.`,+ }),+ );+ } finally {+ unselect();+ }};// movediff --git a/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.unit.spec.tsxnew file mode 100644index 00000000000..6d4dfb2d4e7--- /dev/null+++ b/frontend/src/metabase/collections/components/CollectionBulkActions/ArchivedBulkActions.unit.spec.tsx@@ -0,0 +1,120 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { useState } from "react";++import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { UndoListing } from "metabase/common/components/UndoListing";+import type { Collection, CollectionItem } from "metabase-types/api";+import {+ createMockCollection,+ createMockCollectionItem,+} from "metabase-types/api/mocks";++import { ArchivedBulkActions } from "./ArchivedBulkActions";++const trashCollection = createMockCollection({ id: 1, type: "trash" });++function TestComponent({+ selected,+ collection,+}: {+ selected: CollectionItem[];+ collection: Collection;+}) {+ const [selectedItems, setSelectedItems] = useState<CollectionItem[] | null>(+ null,+ );+ const [selectedAction, setSelectedAction] = useState<string | null>(null);++ return (+ <>+ <ArchivedBulkActions+ selected={selected}+ collection={collection}+ selectedItems={selectedItems}+ selectedAction={selectedAction}+ clearSelected={jest.fn()}+ setSelectedItems={setSelectedItems}+ setSelectedAction={setSelectedAction}+ />+ <UndoListing />+ </>+ );+}++const setup = (selected: CollectionItem[]) => {+ renderWithProviders(+ <TestComponent selected={selected} collection={trashCollection} />,+ );+};++const confirmBulkDelete = async () => {+ await userEvent.click(+ screen.getByRole("button", { name: "Delete permanently" }),+ );+ const dialog = await screen.findByRole("dialog");+ await userEvent.click(+ within(dialog).getByRole("button", { name: "Delete permanently" }),+ );+};++const archivedCollectionItems = [+ createMockCollectionItem({+ id: 10,+ model: "collection",+ name: "First",+ can_delete: true,+ }),+ createMockCollectionItem({+ id: 11,+ model: "collection",+ name: "Second",+ can_delete: true,+ }),+];++describe("ArchivedBulkActions", () => {+ it("shows a single success message and closes the modal when all deletes succeed", async () => {+ fetchMock.delete("path:/api/collection/10", 204);+ fetchMock.delete("path:/api/collection/11", 204);++ setup(archivedCollectionItems);+ await confirmBulkDelete();++ expect(+ await screen.findByText("2 items have been permanently deleted."),+ ).toBeInTheDocument();+ // the per-item toast must not also fire for bulk deletes+ expect(+ screen.queryByText("This item has been permanently deleted."),+ ).not.toBeInTheDocument();++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ expect(+ fetchMock.callHistory.calls(undefined, { method: "DELETE" }),+ ).toHaveLength(2);+ });++ it("shows an error message instead of success when a delete fails", async () => {+ fetchMock.delete("path:/api/collection/10", 204);+ fetchMock.delete("path:/api/collection/11", 500);++ setup(archivedCollectionItems);+ await confirmBulkDelete();++ expect(+ await screen.findByText(+ "There was an error permanently deleting these items.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("2 items have been permanently deleted."),+ ).not.toBeInTheDocument();++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ });+});diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex 654f09d2c4f..7183835e91d 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -1622,8 +1622,8 @@new-children-location (:location collection)](api/check-400 (:archived collection)"Collection must be trashed before deletion.")- (api/check-400 (contains? #{:tenant-specific :shared-tenant-collections nil} (:namespace collection))- "Collections in non-nil namespaces cannot be deleted.")+ (api/check-400 (contains? #{:tenant-specific collection/shared-tenant-ns nil} (:namespace collection))+ "Only collections in the default or tenant namespaces can be deleted.");; Shouldn't happen, because they can't be archived either... but juuuuust in case.(api/check-400 (nil? (:personal_owner_id collection))"Personal collections cannot be deleted.")diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 1ae3d79b543..02335e27b51 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -3451,7 +3451,7 @@(is (= "Collection must be trashed before deletion."(mt/user-http-request :crowberto :delete 400 (str "/collection/" a-id)))))(mt/with-temp [:model/Collection {a-id :id} {:namespace "flippity" :archived true}]- (is (= "Collections in non-nil namespaces cannot be deleted."+ (is (= "Only collections in the default or tenant namespaces can be deleted."(mt/user-http-request :crowberto :delete 400 (str "/collection/" a-id)))))(mt/with-temp [:model/Collection {a-id :id} {:archived true}](is (= "You don't have permissions to do that."