update collections create and update (forms and dialogs)
[arvados.git] / src / store / collections / collection-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 } from "redux-form";
7 import { RootState } from '~/store/store';
8 import { uploadCollectionFiles } from '~/store/collections/uploader/collection-uploader-actions';
9 import { projectPanelActions } from "~/store/project-panel/project-panel-action";
10 import { snackbarActions } from "~/store/snackbar/snackbar-actions";
11 import { dialogActions } from "~/store/dialog/dialog-actions";
12 import { CollectionResource } from '~/models/collection';
13 import { ServiceRepository } from '~/services/services';
14 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/common/api/common-resource-service";
15
16 export interface CollectionCreateFormDialogData {
17     name: string;
18     description: string;
19     files: File[];
20 }
21
22 export const COLLECTION_CREATE_FORM_NAME = "collectionCreateFormName";
23
24 export const openCollectionCreateDialog = () =>
25     (dispatch: Dispatch) => {
26         dispatch(dialogActions.OPEN_DIALOG({ id: COLLECTION_CREATE_FORM_NAME, data: {} }));
27     };
28
29 export const addCollection = (data: CollectionCreateFormDialogData) =>
30     async (dispatch: Dispatch) => {
31         await dispatch<any>(createCollection(data));
32         dispatch(snackbarActions.OPEN_SNACKBAR({
33             message: "Collection has been successfully created.",
34             hideDuration: 2000
35         }));
36     };
37
38 export const createCollection = (collection: Partial<CollectionResource>) =>
39     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
40         dispatch(startSubmit(COLLECTION_CREATE_FORM_NAME));
41         try {
42             const newCollection = await services.collectionService.create(collection);
43             await dispatch<any>(uploadCollectionFiles(newCollection.uuid));
44             dispatch(projectPanelActions.REQUEST_ITEMS());
45             dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_CREATE_FORM_NAME }));
46             dispatch(reset(COLLECTION_CREATE_FORM_NAME));
47         } catch (e) {
48             const error = getCommonResourceServiceError(e);
49             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
50                 dispatch(stopSubmit(COLLECTION_CREATE_FORM_NAME, { name: 'Collection with the same name already exists.' }));
51             }
52         }
53     };