Merge branch '14103-improve-dialogs'
[arvados.git] / src / store / projects / project-create-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 { reset, startSubmit, stopSubmit, initialize } from 'redux-form';
7 import { RootState } from '~/store/store';
8 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
9 import { dialogActions } from "~/store/dialog/dialog-actions";
10 import { projectPanelActions } from '~/store/project-panel/project-panel-action';
11 import { getProjectList } from '~/store/project/project-action';
12 import { getCommonResourceServiceError, CommonResourceServiceError } from '~/common/api/common-resource-service';
13 import { ProjectResource } from '~/models/project';
14 import { ServiceRepository } from '~/services/services';
15
16
17 export interface ProjectCreateFormDialogData {
18     ownerUuid: string;
19     name: string;
20     description: string;
21 }
22
23 export const PROJECT_CREATE_FORM_NAME = 'projectCreateFormName';
24
25 export const openProjectCreateDialog = (ownerUuid: string) =>
26     (dispatch: Dispatch) => {
27         dispatch(initialize(PROJECT_CREATE_FORM_NAME, { ownerUuid }));
28         dispatch(dialogActions.OPEN_DIALOG({ id: PROJECT_CREATE_FORM_NAME, data: {} }));
29     };
30
31 export const addProject = (data: ProjectCreateFormDialogData) =>
32     async (dispatch: Dispatch) => {
33         await dispatch<any>(createProject(data));
34         dispatch(snackbarActions.OPEN_SNACKBAR({
35             message: "Project has been successfully created.",
36             hideDuration: 2000
37         }));
38     };
39
40
41 const createProject = (project: Partial<ProjectResource>) =>
42     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
43         dispatch(startSubmit(PROJECT_CREATE_FORM_NAME));
44         try {
45             const newProject = await services.projectService.create(project);
46             dispatch<any>(getProjectList(newProject.ownerUuid));
47             dispatch(projectPanelActions.REQUEST_ITEMS());
48             dispatch(dialogActions.CLOSE_DIALOG({ id: PROJECT_CREATE_FORM_NAME }));
49             dispatch(reset(PROJECT_CREATE_FORM_NAME));
50         } catch (e) {
51             const error = getCommonResourceServiceError(e);
52             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
53                 dispatch(stopSubmit(PROJECT_CREATE_FORM_NAME, { name: 'Project with the same name already exists.' }));
54             }
55         }
56     };