Merge branch '14103-improve-dialogs'
[arvados-workbench2.git] / src / store / projects / project-update-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from "redux";
6 import { initialize, startSubmit, stopSubmit } from 'redux-form';
7 import { RootState } from "~/store/store";
8 import { updateDetails } from "~/store/details-panel/details-panel-action";
9 import { dialogActions } from "~/store/dialog/dialog-actions";
10 import { snackbarActions } from "~/store/snackbar/snackbar-actions";
11 import { ContextMenuResource } from '~/store/context-menu/context-menu-reducer';
12 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/common/api/common-resource-service";
13 import { ServiceRepository } from "~/services/services";
14 import { ProjectResource } from '~/models/project';
15 import { getProjectList } from '~/store/project/project-action';
16 import { projectPanelActions } from '~/store/project-panel/project-panel-action';
17
18 export interface ProjectUpdateFormDialogData {
19     uuid: string;
20     name: string;
21     description: string;
22 }
23
24 export const PROJECT_UPDATE_FORM_NAME = 'projectUpdateFormName';
25
26 export const openProjectUpdateDialog = (resource: ContextMenuResource) =>
27     (dispatch: Dispatch) => {
28         dispatch(initialize(PROJECT_UPDATE_FORM_NAME, resource));
29         dispatch(dialogActions.OPEN_DIALOG({ id: PROJECT_UPDATE_FORM_NAME, data: {} }));
30     };
31
32 export const editProject = (data: ProjectUpdateFormDialogData) =>
33     async (dispatch: Dispatch) => {
34         await dispatch<any>(updateProject(data));
35         dispatch(snackbarActions.OPEN_SNACKBAR({
36             message: "Project has been successfully updated.",
37             hideDuration: 2000
38         }));
39     };
40
41 export const updateProject = (project: Partial<ProjectResource>) =>
42     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
43         const uuid = project.uuid || '';
44         dispatch(startSubmit(PROJECT_UPDATE_FORM_NAME));
45         try {
46             const updatedProject = await services.projectService.update(uuid, project);
47             dispatch(projectPanelActions.REQUEST_ITEMS());
48             dispatch<any>(getProjectList(updatedProject.ownerUuid));
49             dispatch<any>(updateDetails(updatedProject));
50             dispatch(dialogActions.CLOSE_DIALOG({ id: PROJECT_UPDATE_FORM_NAME }));
51         } catch (e) {
52             const error = getCommonResourceServiceError(e);
53             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
54                 dispatch(stopSubmit(PROJECT_UPDATE_FORM_NAME, { name: 'Project with the same name already exists.' }));
55             }
56         }
57     };