Skip to content

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

Remove Action entity (#73978)

Romeo Van Snick46b1ff0919dc
diff --git a/e2e/support/helpers/e2e-action-helpers.js b/e2e/support/helpers/e2e-action-helpers.js
index b98b31a7b15..3123d36b92e 100644
--- a/e2e/support/helpers/e2e-action-helpers.js
+++ b/e2e/support/helpers/e2e-action-helpers.js
@@ -20,7 +20,7 @@ export function fillActionQuery(query) {
}
/**
*
- * @param {import("metabase/entities/actions/actions").CreateQueryActionParams} actionDetails
+ * @param {import("metabase/actions/types").CreateQueryActionParams} actionDetails
*/
export function createAction(actionDetails) {
return cy.request("POST", "/api/action", actionDetails);
diff --git a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
index 93f4c640c8b..ab2e8a5fbbf 100644
--- a/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
+++ b/e2e/test/scenarios/actions/actions-on-dashboards.cy.spec.js
@@ -536,6 +536,11 @@ const MODEL_NAME = "Test Action Model";
cy.findByText("Update").click();
});
+ cy.wait("@updateAction");
+ // The action editor closes after the update; wait until it is gone
+ // before navigating to the dashboard.
+ cy.findByTestId("action-creator").should("not.exist");
+
H.visitDashboard("@dashboardId");
cy.findByRole("button", { name: "Update Score" }).click();
@@ -986,6 +991,9 @@ const MODEL_NAME = "Test Action Model";
cy.button("Update").click();
});
+ cy.wait("@updateAction");
+ cy.findByTestId("action-editor-modal").should("not.exist");
+
getActionParametersInputModal().within(() => {
cy.findByTestId("modal-header").findByText("New action name");
@@ -1030,6 +1038,9 @@ const MODEL_NAME = "Test Action Model";
cy.button("Update").click();
});
+ cy.wait("@updateAction");
+ cy.findByTestId("action-editor-modal").should("not.exist");
+
getActionParametersInputModal().within(() => {
cy.findByLabelText("Timestamp").type("2020-01-01");
cy.findByLabelText("ID").type("1");
@@ -1260,6 +1271,10 @@ describe(
cy.wait("@updateAction");
+ // The action editor closes after the update; wait until only the
+ // parameter mapping dialog remains.
+ cy.findByTestId("action-creator").should("not.exist");
+
cy.findByRole("dialog").within(() => {
cy.findByText("New Score: required");
cy.findByRole("button", { name: "Done" }).should("be.disabled");
@@ -1322,6 +1337,8 @@ function createDashboardWithActionButton({
cy.wait("@updateAction");
});
+
+ cy.findByTestId("action-creator").should("not.exist");
}
if (idFilter) {
diff --git a/e2e/test/scenarios/actions/model-actions.cy.spec.js b/e2e/test/scenarios/actions/model-actions.cy.spec.js
index b0e8e3b7fe4..39505f7e2b5 100644
--- a/e2e/test/scenarios/actions/model-actions.cy.spec.js
+++ b/e2e/test/scenarios/actions/model-actions.cy.spec.js
@@ -124,6 +124,11 @@ describe(
.should("be.checked");
cy.findByRole("button", { name: "Update" }).click();
+ cy.wait("@updateAction");
+ // The action editor closes after the update; wait until it is gone
+ // before asserting on the action list behind it.
+ cy.findByTestId("action-creator").should("not.exist");
+
cy.findByLabelText("Action list")
.findByText(
"DELETE FROM orders WHERE id = {{ id }} AND status = 'pending'",
@@ -480,6 +485,11 @@ describe(
cy.findByRole("button", { name: "Update" }).click();
+ cy.wait("@updateAction");
+ // The action editor closes after the update; wait until it is gone
+ // before clicking through to the run modal behind it.
+ cy.findByTestId("action-creator").should("not.exist");
+
runActionFor(SAMPLE_QUERY_ACTION.name);
H.modal().within(() => {
@@ -508,6 +518,9 @@ describe(
});
cy.findByRole("button", { name: "Update" }).click();
+ cy.wait("@updateAction");
+ cy.findByTestId("action-creator").should("not.exist");
+
runActionFor(SAMPLE_QUERY_ACTION.name);
H.modal().within(() => {
@@ -534,6 +547,9 @@ describe(
cy.findByRole("button", { name: "Update" }).click();
});
+ cy.wait("@updateAction");
+ cy.findByTestId("action-creator").should("not.exist");
+
runActionFor(SAMPLE_QUERY_ACTION.name);
H.modal().within(() => {
@@ -573,6 +589,9 @@ describe(
cy.findByRole("button", { name: "Update" }).click();
+ cy.wait("@updateAction");
+ cy.findByTestId("action-creator").should("not.exist");
+
runActionFor("Create");
H.modal().within(() => {
@@ -634,6 +653,9 @@ describe(
cy.findByRole("button", { name: "Update" }).click();
+ cy.wait("@updateAction");
+ cy.findByTestId("action-creator").should("not.exist");
+
cy.signOut();
cy.get("@queryActionPublicUrl").then((url) => {
@@ -680,6 +702,7 @@ describe(
cy.findByRole("button", { name: "Update" }).click();
cy.wait("@updateAction");
+ cy.findByTestId("action-creator").should("not.exist");
cy.signOut();
diff --git a/frontend/src/metabase-types/api/schema.ts b/frontend/src/metabase-types/api/schema.ts
index 947f259e689..1e0e9c26d5a 100644
--- a/frontend/src/metabase-types/api/schema.ts
+++ b/frontend/src/metabase-types/api/schema.ts
@@ -1,4 +1,3 @@
-import type { WritebackAction } from "./actions";
import type { Card, CardId } from "./card";
import type { Collection, CollectionId, CollectionItemId } from "./collection";
import type { Dashboard } from "./dashboard";
@@ -20,7 +19,6 @@ import type {
} from "./table";
import type { Timeline, TimelineEventId } from "./timeline";
-export type NormalizedWritebackAction = WritebackAction;
export type NormalizedDashboard = Dashboard;
export type NormalizedDocument = Document;
export type NormalizedCard = Card;
diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionContextProvider.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionContextProvider.tsx
index 78e7ff2f43b..12a523e8858 100644
--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionContextProvider.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionContextProvider.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import _ from "underscore";
-import type { CreateQueryActionParams } from "metabase/entities/actions";
+import type { CreateQueryActionParams } from "metabase/actions/types";
import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import { getTemplateTagParametersFromCard } from "metabase-lib/v1/parameters/utils/template-tags";
diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
index ed245038dee..f675bfd66f8 100644
--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
@@ -3,16 +3,17 @@ import type { Route } from "react-router";
import { t } from "ttag";
import _ from "underscore";
-import { skipToken, useGetActionQuery } from "metabase/api";
+import {
+ skipToken,
+ useCreateActionMutation,
+ useGetActionQuery,
+ useUpdateActionMutation,
+} from "metabase/api";
import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";
import { Modal } from "metabase/common/components/Modal";
import { useBeforeUnload } from "metabase/common/hooks/use-before-unload";
import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
-import type {
- CreateActionParams,
- UpdateActionParams,
-} from "metabase/entities/actions";
-import { Actions } from "metabase/entities/actions";
+import { useToast } from "metabase/common/hooks/use-toast";
import { Databases } from "metabase/entities/databases";
import { Questions } from "metabase/entities/questions";
import { connect } from "metabase/redux";
@@ -55,32 +56,18 @@ interface StateProps {
metadata: Metadata;
}
-interface DispatchProps {
- onCreateAction: (params: CreateActionParams) => void;
- onUpdateAction: (params: UpdateActionParams) => void;
-}
-
export type ActionCreatorProps = OwnProps;
-type Props = OwnProps & ModelLoaderProps & StateProps & DispatchProps;
+type Props = OwnProps & ModelLoaderProps & StateProps;
const mapStateToProps = (state: State) => ({
metadata: getMetadata(state),
});
-const mapDispatchToProps = {
- onCreateAction: Actions.actions.create,
- onUpdateAction: Actions.actions.update,
-};
-
-function ActionCreator({
- model,
- onCreateAction,
- onUpdateAction,
- onSubmit,
- onClose,
- route,
-}: Props) {
+function ActionCreator({ model, onSubmit, onClose, route }: Props) {
+ const [createAction] = useCreateActionMutation();
+ const [updateAction] = useUpdateActionMutation();
+ const [sendToast] = useToast();
const {
action,
formSettings,
@@ -112,38 +99,46 @@ function ActionCreator({
return; // only query action creation is supported now
}
- const reduxAction = await onCreateAction({
- ...action,
- ...values,
- visualization_settings: formSettings,
- } as WritebackQueryAction);
- const createdAction = Actions.HACK_getObjectFromAction(reduxAction);
+ try {
+ const createdAction = await createAction({
+ ...action,
+ ...values,
+ visualization_settings: formSettings,
+ } as WritebackQueryAction).unwrap();
- // Sync the editor state with data from save modal form
- handleActionChange(values);
+ // Sync the editor state with data from save modal form
+ handleActionChange(values);
- setShowSaveModal(false);
- onSubmit?.(createdAction);
+ setShowSaveModal(false);
+ onSubmit?.(createdAction);
- scheduleCallback(() => {
- onClose?.();
- });
+ scheduleCallback(() => {
+ onClose?.();
+ });
+ } catch (_error) {
+ sendToast({ icon: "warning", message: t`Failed to create action` });
+ }
};
const handleUpdate = async () => {
- if (isSavedAction(action)) {
- const reduxAction = await onUpdateAction({
+ if (!isSavedAction(action)) {
+ return;
+ }
+
+ try {
+ const updatedAction = await updateAction({
...action,
model_id: model?.id(),
visualization_settings: formSettings,
- });
+ }).unwrap();
- const updatedAction = Actions.HACK_getObjectFromAction(reduxAction);
onSubmit?.(updatedAction);
scheduleCallback(() => {
onClose?.();
});
+ } catch (_error) {
+ sendToast({ icon: "warning", message: t`Failed to update action` });
}
};
@@ -155,7 +150,7 @@ function ActionCreator({
if (isNew) {
showSaveModal();
} else {
- handleUpdate();
+ void handleUpdate();
}
};
@@ -231,5 +226,5 @@ export default _.compose(
entityAlias: "model",
}),
Databases.loadList(),
- connect(mapStateToProps, mapDispatchToProps),
+ connect(mapStateToProps),
)(ActionCreatorWithContext);
diff --git a/frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx b/frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx
index b1f1e4156ed..afc957d853c 100644
--- a/frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreator/CreateActionForm/CreateActionForm.tsx
@@ -2,13 +2,13 @@ import { useMemo } from "react";
import { t } from "ttag";
import * as Yup from "yup";
+import type { CreateQueryActionParams } from "metabase/actions/types";
import { Button } from "metabase/common/components/Button";
import { FormErrorMessage } from "metabase/common/components/FormErrorMessage";
import { FormFooter } from "metabase/common/components/FormFooter";
import { FormInput } from "metabase/common/components/FormInput";
import { FormSubmitButton } from "metabase/common/components/FormSubmitButton";
import { FormTextArea } from "metabase/common/components/FormTextArea";
-import type { CreateQueryActionParams } from "metabase/entities/actions";
import { Form, FormProvider } from "metabase/forms";
import { FormModelPicker } from "metabase/models/containers/FormModelPicker";
import * as Errors from "metabase/utils/errors";
diff --git a/frontend/src/metabase/actions/containers/ActionPicker/ActionPicker.tsx b/frontend/src/metabase/actions/containers/ActionPicker/ActionPicker.tsx
index 61cdcbe56f5..1ecde6196a0 100644
--- a/frontend/src/metabase/actions/containers/ActionPicker/ActionPicker.tsx
+++ b/frontend/src/metabase/actions/containers/ActionPicker/ActionPicker.tsx
@@ -3,12 +3,11 @@ import { useMemo, useState } from "react";
import { t } from "ttag";
import ActionCreator from "metabase/actions/containers/ActionCreator";
-import { useSearchQuery } from "metabase/api";
+import { useListActionsQuery, useSearchQuery } from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { Modal } from "metabase/common/components/Modal";
import { useToggle } from "metabase/common/hooks/use-toggle";
import CS from "metabase/css/core/index.css";
-import { Actions } from "metabase/entities/actions";
import type { Card, WritebackAction } from "metabase-types/api";
import {
@@ -156,13 +155,18 @@ function ModelActionPicker({
}
function ActionPickerWithModels(
- props: Omit<Parameters<typeof ActionPicker>[0], "models">,
+ props: Omit<Parameters<typeof ActionPicker>[0], "models" | "actions">,
) {
const {
data: searchResponse,
- isLoading,
- error,
+ isLoading: isLoadingSearch,
+ error: searchError,
} = useSearchQuery({ models: ["dataset"] });
+ const {
+ data: actions = [],
+ isLoading: isLoadingActions,
+ error: actionsError,
+ } = useListActionsQuery({});
const models = (searchResponse?.data ?? []).flatMap((result) =>
typeof result.id === "number"
? [
@@ -174,13 +178,13 @@ function ActionPickerWithModels(
]
: [],
);
+ const isLoading = isLoadingSearch || isLoadingActions;
+ const error = searchError || actionsError;
return (
<LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
- <ActionPicker {...props} models={models} />
+ <ActionPicker {...props} models={models} actions={actions} />
</LoadingAndErrorWrapper>
);
}
-export const ConnectedActionPicker = Actions.loadList({
- loadingAndErrorWrapper: false,
-})(ActionPickerWithModels);
+export const ConnectedActionPicker = ActionPickerWithModels;
diff --git a/frontend/src/metabase/actions/types.ts b/frontend/src/metabase/actions/types.ts
index 8d379dc41a4..1285ebc3d4a 100644
--- a/frontend/src/metabase/actions/types.ts
+++ b/frontend/src/metabase/actions/types.ts
@@ -3,8 +3,43 @@ import type {
ActionFormOption,
FieldSettings as BaseFieldSettings,
InputComponentType,
+ WritebackAction,
+ WritebackImplicitQueryAction,
+ WritebackQueryAction,
} from "metabase-types/api";
+type BaseCreateActionParams = Pick<
+ WritebackAction,
+ "name" | "description" | "model_id" | "parameters" | "visualization_settings"
+>;
+
+type BaseUpdateActionParams = {
+ id: WritebackAction["id"];
+};
+
+export type CreateQueryActionParams = BaseCreateActionParams &
+ Pick<WritebackQueryAction, "type" | "dataset_query">;
+
+export type UpdateQueryActionParams = Partial<CreateQueryActionParams> &
+ BaseUpdateActionParams;
+
+export type CreateImplicitActionParams = BaseCreateActionParams &
+ Pick<WritebackImplicitQueryAction, "type" | "kind">;
+
+export type UpdateImplicitActionParams = Omit<
+ Partial<CreateImplicitActionParams>,
+ "type"
+> &
+ BaseUpdateActionParams;
+
+export type CreateActionParams =
+ | CreateQueryActionParams
+ | CreateImplicitActionParams;
+
+export type UpdateActionParams =
+ | UpdateQueryActionParams
+ | UpdateImplicitActionParams;
+
export type FieldSettings = BaseFieldSettings & {
field?: Field;
};
diff --git a/frontend/src/metabase/api/action.ts b/frontend/src/metabase/api/action.ts
index 91d0c4c0529..916e178b741 100644
--- a/frontend/src/metabase/api/action.ts
+++ b/frontend/src/metabase/api/action.ts
@@ -1,6 +1,5 @@
import _ from "underscore";
-import { ActionSchema } from "metabase/schema";
import type {
CreateActionRequest,
GetActionRequest,
@@ -19,7 +18,6 @@ import {
provideActionListTags,
provideActionTags,
} from "./tags";
-import { hydrateLegacyEntities } from "./utils/hydrate-legacy-entities";
export const actionApi = Api.injectEndpoints({
endpoints: (builder) => ({
@@ -30,7 +28,6 @@ export const actionApi = Api.injectEndpoints({
params,
}),
providesTags: (collections = []) => provideActionListTags(collections),
- onQueryStarted: hydrateLegacyEntities([ActionSchema]),
}),
getAction: builder.query<WritebackAction, GetActionRequest>({
query: ({ id }) => ({
@@ -38,7 +35,6 @@ export const actionApi = Api.injectEndpoints({
url: `/api/action/${id}`,
}),
providesTags: (action) => (action ? provideActionTags(action) : []),
- onQueryStarted: hydrateLegacyEntities(ActionSchema),
}),
createAction: builder.mutation<WritebackAction, CreateActionRequest>({
query: (body) => ({
@@ -53,7 +49,33 @@ export const actionApi = Api.injectEndpoints({
query: (body) => ({
method: "PUT",
url: `/api/action/${body.id}`,
- body: _.omit(body, "type"), // Changing action type is not supported
+ // The action editor passes the full WritebackAction it fetched
+ // (including server-managed fields like `creator`, `created_at`,
+ // `database_enabled_actions`, ...). The backend routes anything
+ // outside the Action columns to the type-specific update table
+ // (query_action / implicit_action / http_action), where those
+ // columns don't exist and the request 500s. Whitelist only the
+ // fields that the API endpoint actually accepts.
+ body: _.pick(body, [
+ "id",
+ "archived",
+ "body",
+ "database_id",
+ "dataset_query",
+ "description",
+ "error_handle",
+ "headers",
+ "kind",
+ "model_id",
+ "name",
+ "parameter_mappings",
+ "parameters",
+ "public_uuid",
+ "response_handle",
+ "template",
+ "url",
+ "visualization_settings",
+ ]),
}),
invalidatesTags: (action, error) =>
action
@@ -116,7 +138,9 @@ export const {
useGetActionQuery,
useListActionsQuery,
useListPublicActionsQuery,
+ useCreateActionMutation,
useUpdateActionMutation,
+ useDeleteActionMutation,
useCreateActionPublicLinkMutation,
useDeleteActionPublicLinkMutation,
endpoints: {
diff --git a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts
index 298353b5629..881ce02da66 100644
--- a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts
@@ -254,7 +254,6 @@ describe("setParameterMapping", () => {
},
}),
entities: {
- actions: {},
collections: {},
dashboards: {},
databases: {},
@@ -371,7 +370,6 @@ describe("setParameterMapping", () => {
},
}),
entities: {
- actions: {},
collections: {},
dashboards: {},
databases: {},
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index 6a069790e50..ec7b593b414 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -1,11 +1,11 @@
import { type UnknownAction, createReducer } from "@reduxjs/toolkit";
import { assoc, chain, merge, updateIn } from "icepick";
-import { Actions } from "metabase/entities/actions";
+import { actionApi } from "metabase/api";
import { Questions } from "metabase/entities/questions";
import { combineReducers } from "metabase/redux";
import { SET_PARAMETER_VALUES, initialize } from "metabase/redux/dashboard";
-import type { Card, WritebackAction } from "metabase-types/api";
+import type { Card } from "metabase-types/api";
import {
REMOVE_CARD_FROM_DASH,
@@ -194,18 +194,9 @@ const dashcards = createReducer(
});
},
)
- .addCase<
- string,
- {
- type: string;
- payload: { object: WritebackAction | null | undefined };
- }
- >(
- Actions.actionTypes.UPDATE,
- (state, { payload: { object: action } }) => {
- if (!action) {
- return;
- }
+ .addMatcher(
+ actionApi.endpoints.updateAction.matchFulfilled,
+ (state, { payload: action }) => {
Object.values(state).forEach((dashcard) => {
if (!("action" in dashcard) || dashcard.action?.id !== action.id) {
return;
diff --git a/frontend/src/metabase/entities/actions/actions.ts b/frontend/src/metabase/entities/actions/actions.ts
deleted file mode 100644
index 61b033b0e91..00000000000
--- a/frontend/src/metabase/entities/actions/actions.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { t } from "ttag";
-
-import {
- actionApi,
- useGetActionQuery,
- useListActionsQuery,
-} from "metabase/api";
-import type { Dispatch } from "metabase/redux/store";
-import { ActionSchema } from "metabase/schema";
-import type {
- CreateActionRequest,
- GetActionRequest,
- ListActionsRequest,
- UpdateActionRequest,
- WritebackAction,
- WritebackActionId,
- WritebackImplicitQueryAction,
- WritebackQueryAction,
-} from "metabase-types/api";
-
-import { createEntity, entityCompatibleQuery } from "../utils";
-
-type BaseCreateActionParams = Pick<
- WritebackAction,
- "name" | "description" | "model_id" | "parameters" | "visualization_settings"
->;
-
-type BaseUpdateActionParams = {
- id: WritebackAction["id"];
-};
-
-export type CreateQueryActionParams = BaseCreateActionParams &
- Pick<WritebackQueryAction, "type" | "dataset_query">;
-
-export type UpdateQueryActionParams = Partial<CreateQueryActionParams> &
- BaseUpdateActionParams;
-
-export type CreateImplicitActionParams = BaseCreateActionParams &
- Pick<WritebackImplicitQueryAction, "type" | "kind">;
-
-export type UpdateImplicitActionParams = Omit<
- Partial<CreateImplicitActionParams>,
- "type"
-> &
- BaseUpdateActionParams;
-
-export type CreateActionParams =
- | CreateQueryActionParams
- | CreateImplicitActionParams;
-
-export type UpdateActionParams =
- | UpdateQueryActionParams
- | UpdateImplicitActionParams;
-
-const defaultImplicitActionCreateOptions = {
- insert: true,
- update: true,
- delete: true,
-};
-
-const enableImplicitActionsForModel =
- (modelId: number, options = defaultImplicitActionCreateOptions) =>
- async (dispatch: Dispatch) => {
- // We're ordering actions that's most recently created first.
- // So if we want to show Create, Update, Delete, then we need
- // to create them in the reverse order.
- if (options.delete) {
- await Actions.api.create(
- {
- name: t`Delete`,
- type: "implicit",
- kind: "row/delete",
- model_id: modelId,
- },
- dispatch,
- );
- }
-
- if (options.update) {
- await Actions.api.create(
- {
- name: t`Update`,
- type: "implicit",
- kind: "row/update",
- model_id: modelId,
- },
- dispatch,
- );
- }
-
- if (options.insert) {
- await Actions.api.create(
- {
- name: t`Create`,
- type: "implicit",
- kind: "row/create",
- model_id: modelId,
- },
- dispatch,
- );
- }
-
- dispatch(Actions.actions.invalidateLists());
- };
-
-/**
- * @deprecated use "metabase/api" instead
- */
-export const Actions = createEntity({
- name: "actions",
- nameOne: "action",
- schema: ActionSchema,
- path: "/api/action",
- rtk: () => ({
- getUseGetQuery: () => ({
- useGetQuery: useGetActionQuery,
- }),
- useListQuery: useListActionsQuery,
- }),
- api: {
- list: (entityQuery: ListActionsRequest, dispatch: Dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- actionApi.endpoints.listActions,
- ),
- get: (
- entityQuery: GetActionRequest,
- _options: unknown,
- dispatch: Dispatch,
- ) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- actionApi.endpoints.getAction,
- ),
- create: (entityQuery: CreateActionRequest, dispatch: Dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- actionApi.endpoints.createAction,
- ),
- update: (entityQuery: UpdateActionRequest, dispatch: Dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- actionApi.endpoints.updateAction,
- ),
- delete: (id: WritebackActionId, dispatch: Dispatch) =>
- entityCompatibleQuery(id, dispatch, actionApi.endpoints.deleteAction),
- },
- actions: {
- enableImplicitActionsForModel,
- },
- writableProperties: [
- "name",
- "description",
- "type",
- "model_id",
- "database_id",
- "dataset_query",
- "parameters",
- "public_uuid",
- "visualization_settings",
- "archived",
- ],
-});
diff --git a/frontend/src/metabase/entities/actions/index.ts b/frontend/src/metabase/entities/actions/index.ts
deleted file mode 100644
index 8ff5a89aff8..00000000000
--- a/frontend/src/metabase/entities/actions/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./actions";
diff --git a/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts b/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts
index d756f08abd7..8e704fa6db1 100644
--- a/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts
+++ b/frontend/src/metabase/entities/containers/rtk-query/types/entities.ts
@@ -35,7 +35,6 @@ export type ReloadIntervalSelector<Entity> = (
* There should be an entry here for every "createEntity" function call.
*/
export type EntityType =
- | "actions"
| "alerts"
| "bookmarks"
| "collections"
diff --git a/frontend/src/metabase/entities/index.ts b/frontend/src/metabase/entities/index.ts
index a28e1fe66a3..d54c8bf795f 100644
--- a/frontend/src/metabase/entities/index.ts
+++ b/frontend/src/metabase/entities/index.ts
@@ -68,7 +68,6 @@
* )(BookContainer);
*/
-export { Actions as actions } from "./actions/actions";
export { Collections as collections } from "./collections";
export { SnippetCollections as snippetCollections } from "./snippet-collections";
export { Dashboards as dashboards } from "./dashboards";
diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx
index 0ce9c75ea2c..e590efe0a81 100644
--- a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx
+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionDetails.tsx
@@ -2,14 +2,12 @@ import { useCallback, useMemo } from "react";
import { t } from "ttag";
import _ from "underscore";
+import { useDeleteActionMutation, useListActionsQuery } from "metabase/api";
import { Button } from "metabase/common/components/Button";
import { Link } from "metabase/common/components/Link";
import { useSetArchive } from "metabase/common/hooks";
import { useConfirmation } from "metabase/common/hooks/use-confirmation";
-import { Actions } from "metabase/entities/actions";
import { Databases } from "metabase/entities/databases";
-import { connect } from "metabase/redux";
-import type { Dispatch, State } from "metabase/redux/store";
import * as Urls from "metabase/urls";
import { parseTimestamp } from "metabase/utils/time-dayjs";
import type Question from "metabase-lib/v1/Question";
@@ -36,45 +34,28 @@ import {
Root,
} from "./ModelActionDetails.styled";
import ModelActionListItem from "./ModelActionListItem";
+import { useEnableImplicitActionsForModel } from "./useEnableImplicitActionsForModel";
interface OwnProps {
model: Question;
}
-interface DispatchProps {
- onEnableImplicitActions: () => void;
- onDeleteAction: (action: WritebackAction) => void;
-}
-
-interface ActionsLoaderProps {
- actions: WritebackAction[];
-}
-
interface DatabaseLoaderProps {
databases: Database[];
}
-type Props = OwnProps &
- DispatchProps &
- ActionsLoaderProps &
- DatabaseLoaderProps;
-
-function mapDispatchToProps(dispatch: Dispatch, { model }: OwnProps) {
- return {
- onEnableImplicitActions: () =>
- dispatch(Actions.actions.enableImplicitActionsForModel(model.id())),
- onDeleteAction: (action: WritebackAction) =>
- dispatch(Actions.actions.delete(action.id)),
- };
-}
-
-function ModelActionDetails({
- model,
- actions,
- databases,
- onEnableImplicitActions,
- onDeleteAction,
-}: Props) {
+type Props = OwnProps & DatabaseLoaderProps;
+
+function ModelActionDetails({ model, databases }: Props) {
+ const { data: actions = [] } = useListActionsQuery({
+ "model-id": model.id(),
+ });
+ const [deleteAction] = useDeleteActionMutation();
+ const onEnableImplicitActions = useEnableImplicitActionsForModel(model.id());
+ const onDeleteAction = useCallback(
+ (action: WritebackAction) => deleteAction(action.id),
+ [deleteAction],
+ );
const archive = useSetArchive();
const onArchiveAction = useCallback(
(action: WritebackAction) =>
@@ -223,12 +204,4 @@ function mostRecentFirst(action: WritebackAction) {
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- Actions.loadList({
- query: (state: State, { model }: OwnProps) => ({
- "model-id": model.id(),
- }),
- }),
- Databases.loadList(),
- connect(null, mapDispatchToProps),
-)(ModelActionDetails);
+export default _.compose(Databases.loadList())(ModelActionDetails);
diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/useEnableImplicitActionsForModel.ts b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/useEnableImplicitActionsForModel.ts
new file mode 100644
index 00000000000..9a4cf5bd8de
--- /dev/null
+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/useEnableImplicitActionsForModel.ts
@@ -0,0 +1,41 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { useCreateActionMutation } from "metabase/api";
+import { useToast } from "metabase/common/hooks/use-toast";
+import type { CardId } from "metabase-types/api";
+
+export function useEnableImplicitActionsForModel(modelId: CardId) {
+ const [createAction] = useCreateActionMutation();
+ const [sendToast] = useToast();
+ return useCallback(async () => {
+ try {
+ // We're ordering actions that's most recently created first.
+ // So if we want to show Create, Update, Delete, then we need
+ // to create them in the reverse order.
+ await createAction({
+ name: t`Delete`,
+ type: "implicit",
+ kind: "row/delete",
+ model_id: modelId,
+ }).unwrap();
+ await createAction({
+ name: t`Update`,
+ type: "implicit",
+ kind: "row/update",
+ model_id: modelId,
+ }).unwrap();
+ await createAction({
+ name: t`Create`,
+ type: "implicit",
+ kind: "row/create",
+ model_id: modelId,
+ }).unwrap();
+ } catch (_error) {
+ sendToast({
+ icon: "warning",
+ message: t`Failed to create basic actions`,
+ });
+ }
+ }, [createAction, modelId, sendToast]);
+}
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
index a75e6d2a172..cfd0ef361d2 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
@@ -4,8 +4,8 @@ import { replace } from "react-router-redux";
import { useMount } from "react-use";
import _ from "underscore";
+import { useListActionsQuery } from "metabase/api";
import { NotFound } from "metabase/common/components/ErrorPages";
-import { Actions } from "metabase/entities/actions";
import { Databases } from "metabase/entities/databases";
import { Questions } from "metabase/entities/questions";
import { Tables } from "metabase/entities/tables";
@@ -18,7 +18,7 @@ import * as Urls from "metabase/urls";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type Table from "metabase-lib/v1/metadata/Table";
-import type { Card, WritebackAction } from "metabase-types/api";
+import type { Card } from "metabase-types/api";
type OwnProps = {
params: {
@@ -28,7 +28,6 @@ type OwnProps = {
};
type EntityLoadersProps = {
- actions: WritebackAction[];
model: Question;
};
@@ -48,12 +47,14 @@ const mapDispatchToProps = {
function ModelActions({
model,
- actions,
children,
loadMetadataForCard,
fetchTableForeignKeys,
onChangeLocation,
}: Props) {
+ const { data: actions = [] } = useListActionsQuery({
+ "model-id": model.id(),
+ });
const [hasFetchedTableMetadata, setHasFetchedTableMetadata] = useState(false);
usePageTitle(model?.displayName() || "");
@@ -119,11 +120,6 @@ function getModelId(state: State, props: OwnProps) {
export default _.compose(
Questions.load({ id: getModelId, entityAlias: "model" }),
Databases.loadList(),
- Actions.loadList({
- query: (state: State, props: OwnProps) => ({
- "model-id": getModelId(state, props),
- }),
- }),
connect<null, DispatchProps, OwnProps & EntityLoadersProps, State>(
null,
mapDispatchToProps,
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
index e506d25fa47..e0176c322fe 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
@@ -583,13 +583,17 @@ describe("ModelActions", () => {
await userEvent.click(screen.getByLabelText("Actions menu"));
await userEvent.click(await screen.findByText("Create basic actions"));
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/action", { method: "POST" }),
+ ).toHaveLength(3);
+ });
const createActionCalls = fetchMock.callHistory.calls(
"path:/api/action",
{
method: "POST",
},
);
- expect(createActionCalls).toHaveLength(3);
expect(await createActionCalls[0].request?.json()).toEqual({
name: "Delete",
@@ -619,13 +623,18 @@ describe("ModelActions", () => {
screen.getByRole("button", { name: /Create basic action/i }),
);
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/action", { method: "POST" }),
+ ).toHaveLength(3);
+ });
+
const createActionCalls = fetchMock.callHistory.calls(
"path:/api/action",
{
method: "POST",
},
);
- expect(createActionCalls).toHaveLength(3);
expect(await createActionCalls[0].request?.json()).toEqual({
name: "Delete",
diff --git a/frontend/src/metabase/redux/store/entities.ts b/frontend/src/metabase/redux/store/entities.ts
index 51c4c9796e5..da26c2a85bf 100644
--- a/frontend/src/metabase/redux/store/entities.ts
+++ b/frontend/src/metabase/redux/store/entities.ts
@@ -10,11 +10,9 @@ import type {
NormalizedSchema,
NormalizedSegment,
NormalizedTable,
- NormalizedWritebackAction,
} from "metabase-types/api";
export interface EntitiesState {
- actions: Record<string, NormalizedWritebackAction>;
collections: Record<string, NormalizedCollection>;
dashboards: Record<string, NormalizedDashboard>;
databases: Record<string, NormalizedDatabase>;
diff --git a/frontend/src/metabase/redux/store/mocks/entities.ts b/frontend/src/metabase/redux/store/mocks/entities.ts
index d71396de82b..2460db29dde 100644
--- a/frontend/src/metabase/redux/store/mocks/entities.ts
+++ b/frontend/src/metabase/redux/store/mocks/entities.ts
@@ -3,7 +3,6 @@ import type { EntitiesState } from "metabase/redux/store";
// This is a helper for cases when entities state doesn't matter
// Most likely, createMockEntitiesState from __support__/store would be a better choice
export const createMockNormalizedEntitiesState = (): EntitiesState => ({
- actions: {},
collections: {},
dashboards: {},
databases: {},
diff --git a/frontend/src/metabase/schema.js b/frontend/src/metabase/schema.js
index e97ef88a77d..d29d3df8ad0 100644
--- a/frontend/src/metabase/schema.js
+++ b/frontend/src/metabase/schema.js
@@ -7,7 +7,6 @@ import { getUniqueFieldId } from "metabase-lib/v1/metadata/utils/fields";
import { SAVED_QUESTIONS_VIRTUAL_DB_ID } from "metabase-lib/v1/metadata/utils/saved-questions";
import { generateSchemaId } from "metabase-lib/v1/metadata/utils/schema";
-export const ActionSchema = new schema.Entity("actions");
export const QuestionSchema = new schema.Entity("questions");
export const CacheConfigSchema = new schema.Entity("cacheConfigs");
export const BookmarkSchema = new schema.Entity("bookmarks");
@@ -116,7 +115,6 @@ MeasureSchema.define({
CacheConfigSchema.define({});
export const ENTITIES_SCHEMA_MAP = {
- actions: ActionSchema,
questions: QuestionSchema,
cacheConfigs: CacheConfigSchema,
bookmarks: BookmarkSchema,
diff --git a/frontend/test/__support__/store.ts b/frontend/test/__support__/store.ts
index 1b9ee1472cd..7f58de759df 100644
--- a/frontend/test/__support__/store.ts
+++ b/frontend/test/__support__/store.ts
@@ -4,7 +4,6 @@ import { normalize } from "normalizr";
import type { EntitiesState } from "metabase/redux/store";
import { createMockNormalizedEntitiesState } from "metabase/redux/store/mocks";
import {
- ActionSchema,
CollectionSchema,
DashboardSchema,
DatabaseSchema,
@@ -30,11 +29,9 @@ import type {
Segment,
Table,
User,
- WritebackAction,
} from "metabase-types/api";
export interface EntitiesStateOpts {
- actions?: WritebackAction[];
collections?: Collection[];
dashboards?: Dashboard[];
databases?: (Database | SavedQuestionDatabase)[];
@@ -49,7 +46,6 @@ export interface EntitiesStateOpts {
}
const EntitiesSchema: Record<keyof EntitiesState, NormalizrSchema<any>> = {
- actions: [ActionSchema],
collections: [CollectionSchema],
dashboards: [DashboardSchema],
databases: [DatabaseSchema],