Refactor code
[arvados-workbench2.git] / src / store / move-collection-dialog / move-collection-dialog.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 { startSubmit, stopSubmit, initialize } from 'redux-form';
8 import { ServiceRepository } from '~/services/services';
9 import { RootState } from '~/store/store';
10 import { getCommonResourceServiceError, CommonResourceServiceError } from "~/common/api/common-resource-service";
11 import { snackbarActions } from '~/store/snackbar/snackbar-actions';
12 import { projectPanelActions } from '~/store/project-panel/project-panel-action';
13 import { MoveToFormDialogData } from '../move-to-dialog/move-to-dialog';
14
15 export const MOVE_COLLECTION_DIALOG = 'moveCollectionDialog';
16
17 export const openMoveCollectionDialog = (resource: { name: string, uuid: string }) =>
18     (dispatch: Dispatch) => {
19         dispatch(initialize(MOVE_COLLECTION_DIALOG, resource));
20         dispatch(dialogActions.OPEN_DIALOG({ id: MOVE_COLLECTION_DIALOG, data: {} }));
21     };
22
23 export const moveCollection = (resource: MoveToFormDialogData) =>
24     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
25         dispatch(startSubmit(MOVE_COLLECTION_DIALOG));
26         try {
27             const collection = await services.collectionService.get(resource.uuid);
28             await services.collectionService.update(resource.uuid, { ...collection, ownerUuid: resource.ownerUuid });
29             dispatch(projectPanelActions.REQUEST_ITEMS());
30             dispatch(dialogActions.CLOSE_DIALOG({ id: MOVE_COLLECTION_DIALOG }));
31             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Collection has been moved', hideDuration: 2000 }));
32         } catch (e) {
33             const error = getCommonResourceServiceError(e);
34             if (error === CommonResourceServiceError.UNIQUE_VIOLATION) {
35                 dispatch(stopSubmit(MOVE_COLLECTION_DIALOG, { ownerUuid: 'A collection with the same name already exists in the target project.' }));
36             } else {
37                 dispatch(dialogActions.CLOSE_DIALOG({ id: MOVE_COLLECTION_DIALOG }));
38                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Could not move the collection.', hideDuration: 2000 }));
39             }
40         }
41     };