make a copy process
[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 '~/services/common-service/common-resource-service';
12 import { CopyFormDialogData } from '~/store/copy-dialog/copy-dialog';
13
14 export const COLLECTION_COPY_FORM_NAME = 'collectionCopyFormName';
15
16 export const openCollectionCopyDialog = (resource: { name: string, uuid: string }) =>
17     (dispatch: Dispatch) => {
18         dispatch<any>(resetPickerProjectTree());
19         const initialData: CopyFormDialogData = { name: `Copy of: ${resource.name}`, ownerUuid: '', uuid: resource.uuid };
20         dispatch<any>(initialize(COLLECTION_COPY_FORM_NAME, initialData));
21         dispatch(dialogActions.OPEN_DIALOG({ id: COLLECTION_COPY_FORM_NAME, data: {} }));
22     };
23
24 export const copyCollection = (resource: CopyFormDialogData) =>
25     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
26         dispatch(startSubmit(COLLECTION_COPY_FORM_NAME));
27         try {
28             const collection = await services.collectionService.get(resource.uuid);
29             const uuidKey = 'uuid';
30             delete collection[uuidKey];
31             await services.collectionService.create({ ...collection, ownerUuid: resource.ownerUuid, name: resource.name });
32             dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_COPY_FORM_NAME }));
33             return collection;
34         } catch (e) {
35             const error = getCommonResourceServiceError(e);
36             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
37                 dispatch(stopSubmit(COLLECTION_COPY_FORM_NAME, { ownerUuid: 'A collection with the same name already exists in the target project.' }));
38             } else {
39                 dispatch(dialogActions.CLOSE_DIALOG({ id: COLLECTION_COPY_FORM_NAME }));
40                 throw new Error('Could not copy the collection.');
41             }
42             return ;
43         }
44     };