Merge branch 'master' into 14103-improve-dialogs
[arvados-workbench2.git] / src / store / collections / collection-copy-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 { dialogActions } from "~/store/dialog/dialog-actions";
7 import { initialize, startSubmit, stopSubmit } from 'redux-form';
8 import { resetPickerProjectTree } from '~/store/project-tree-picker/project-tree-picker-actions';
9 import { RootState } from '~/store/store';
10 import { ServiceRepository } from '~/services/services';
11 import { getCommonResourceServiceError, CommonResourceServiceError } from '~/common/api/common-resource-service';
12 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
13 import { projectPanelActions } from '~/store/project-panel/project-panel-action';
14
15 export const COLLECTION_COPY_FORM_NAME = 'collectionCopyFormName';
16
17 export interface CollectionCopyFormDialogData {
18     name: string;
19     ownerUuid: string;
20     uuid: string;
21 }
22
23 export const openCollectionCopyDialog = (resource: { name: string, uuid: string }) =>
24     (dispatch: Dispatch) => {
25         dispatch<any>(resetPickerProjectTree());
26         const initialData: CollectionCopyFormDialogData = { name: `Copy of: ${resource.name}`, ownerUuid: '', uuid: resource.uuid };
27         dispatch<any>(initialize(COLLECTION_COPY_FORM_NAME, initialData));
28         dispatch(dialogActions.OPEN_DIALOG({ id: COLLECTION_COPY_FORM_NAME, data: {} }));
29     };
30
31 export const copyCollection = (resource: CollectionCopyFormDialogData) =>
32     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
33         dispatch(startSubmit(COLLECTION_COPY_FORM_NAME));
34         try {
35             const collection = await services.collectionService.get(resource.uuid);
36             const uuidKey = 'uuid';
37             delete collection[uuidKey];
38             await services.collectionService.create({ ...collection, ownerUuid: resource.ownerUuid, name: resource.name });
39             dispatch(projectPanelActions.REQUEST_ITEMS());
40             dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_COPY_FORM_NAME }));
41             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Collection has been copied', hideDuration: 2000 }));
42         } catch (e) {
43             const error = getCommonResourceServiceError(e);
44             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
45                 dispatch(stopSubmit(COLLECTION_COPY_FORM_NAME, { ownerUuid: 'A collection with the same name already exists in the target project.' }));
46             } else {
47                 dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_COPY_FORM_NAME }));
48                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not copy the collection', hideDuration: 2000 }));
49             }
50         }
51     };