21621: Add unit test for json copy to clipboard
[arvados.git] / services / workbench2 / src / store / workbench / workbench-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 { RootState } from "store/store";
7 import { getUserUuid } from "common/getuser";
8 import { loadDetailsPanel } from "store/details-panel/details-panel-action";
9 import { snackbarActions, SnackbarKind } from "store/snackbar/snackbar-actions";
10 import { favoritePanelActions, loadFavoritePanel } from "store/favorite-panel/favorite-panel-action";
11 import { getProjectPanelCurrentUuid, setIsProjectPanelTrashed } from "store/project-panel/project-panel-action";
12 import { projectPanelDataActions, projectPanelRunActions } from "store/project-panel/project-panel-action-bind";
13 import {
14     activateSidePanelTreeItem,
15     initSidePanelTree,
16     loadSidePanelTreeProjects,
17     SidePanelTreeCategory,
18     SIDE_PANEL_TREE,
19 } from "store/side-panel-tree/side-panel-tree-actions";
20 import { updateResources } from "store/resources/resources-actions";
21 import { projectPanelDataColumns } from "views/project-panel/project-panel-data";
22 import { projectPanelRunColumns } from "views/project-panel/project-panel-run";
23 import { favoritePanelColumns } from "views/favorite-panel/favorite-panel";
24 import { matchRootRoute } from "routes/routes";
25 import {
26     setGroupDetailsBreadcrumbs,
27     setGroupsBreadcrumbs,
28     setProcessBreadcrumbs,
29     setSharedWithMeBreadcrumbs,
30     setSidePanelBreadcrumbs,
31     setTrashBreadcrumbs,
32     setUsersBreadcrumbs,
33     setMyAccountBreadcrumbs,
34     setUserProfileBreadcrumbs,
35     setInstanceTypesBreadcrumbs,
36     setVirtualMachinesBreadcrumbs,
37     setVirtualMachinesAdminBreadcrumbs,
38     setRepositoriesBreadcrumbs,
39 } from "store/breadcrumbs/breadcrumbs-actions";
40 import { navigateTo, navigateToRootProject } from "store/navigation/navigation-action";
41 import { MoveToFormDialogData } from "store/move-to-dialog/move-to-dialog";
42 import { ServiceRepository } from "services/services";
43 import { getResource } from "store/resources/resources";
44 import * as projectCreateActions from "store/projects/project-create-actions";
45 import * as projectMoveActions from "store/projects/project-move-actions";
46 import * as projectUpdateActions from "store/projects/project-update-actions";
47 import * as collectionCreateActions from "store/collections/collection-create-actions";
48 import * as collectionCopyActions from "store/collections/collection-copy-actions";
49 import * as collectionMoveActions from "store/collections/collection-move-actions";
50 import * as processesActions from "store/processes/processes-actions";
51 import * as processMoveActions from "store/processes/process-move-actions";
52 import * as processUpdateActions from "store/processes/process-update-actions";
53 import * as processCopyActions from "store/processes/process-copy-actions";
54 import { trashPanelColumns } from "views/trash-panel/trash-panel";
55 import { loadTrashPanel, trashPanelActions } from "store/trash-panel/trash-panel-action";
56 import { loadProcessPanel } from "store/process-panel/process-panel-actions";
57 import { loadSharedWithMePanel, sharedWithMePanelActions } from "store/shared-with-me-panel/shared-with-me-panel-actions";
58 import { sharedWithMePanelColumns } from "views/shared-with-me-panel/shared-with-me-panel";
59 import { CopyFormDialogData } from "store/copy-dialog/copy-dialog";
60 import { workflowPanelActions } from "store/workflow-panel/workflow-panel-actions";
61 import { loadSshKeysPanel } from "store/auth/auth-action-ssh";
62 import { loadLinkAccountPanel, linkAccountPanelActions } from "store/link-account-panel/link-account-panel-actions";
63 import { loadSiteManagerPanel } from "store/auth/auth-action-session";
64 import { workflowPanelColumns } from "views/workflow-panel/workflow-panel-view";
65 import { progressIndicatorActions } from "store/progress-indicator/progress-indicator-actions";
66 import { getProgressIndicator } from "store/progress-indicator/progress-indicator-reducer";
67 import { extractUuidKind, Resource, ResourceKind } from "models/resource";
68 import { FilterBuilder } from "services/api/filter-builder";
69 import { GroupContentsResource } from "services/groups-service/groups-service";
70 import { MatchCases, ofType, unionize, UnionOf } from "common/unionize";
71 import { loadRunProcessPanel } from "store/run-process-panel/run-process-panel-actions";
72 import { collectionPanelActions, loadCollectionPanel } from "store/collection-panel/collection-panel-action";
73 import { CollectionResource } from "models/collection";
74 import { WorkflowResource } from "models/workflow";
75 import { loadSearchResultsPanel, searchResultsPanelActions } from "store/search-results-panel/search-results-panel-actions";
76 import { searchResultsPanelColumns } from "views/search-results-panel/search-results-panel-view";
77 import { loadVirtualMachinesPanel } from "store/virtual-machines/virtual-machines-actions";
78 import { loadRepositoriesPanel } from "store/repositories/repositories-actions";
79 import { loadKeepServicesPanel } from "store/keep-services/keep-services-actions";
80 import { loadUsersPanel, userBindedActions } from "store/users/users-actions";
81 import * as userProfilePanelActions from "store/user-profile/user-profile-actions";
82 import { linkPanelActions, loadLinkPanel } from "store/link-panel/link-panel-actions";
83 import { linkPanelColumns } from "views/link-panel/link-panel-root";
84 import { userPanelColumns } from "views/user-panel/user-panel";
85 import { loadApiClientAuthorizationsPanel, apiClientAuthorizationsActions } from "store/api-client-authorizations/api-client-authorizations-actions";
86 import { apiClientAuthorizationPanelColumns } from "views/api-client-authorization-panel/api-client-authorization-panel-root";
87 import * as groupPanelActions from "store/groups-panel/groups-panel-actions";
88 import { groupsPanelColumns } from "views/groups-panel/groups-panel";
89 import * as groupDetailsPanelActions from "store/group-details-panel/group-details-panel-actions";
90 import { groupDetailsMembersPanelColumns, groupDetailsPermissionsPanelColumns } from "views/group-details-panel/group-details-panel";
91 import { DataTableFetchMode } from "components/data-table/data-table";
92 import { loadPublicFavoritePanel, publicFavoritePanelActions } from "store/public-favorites-panel/public-favorites-action";
93 import { publicFavoritePanelColumns } from "views/public-favorites-panel/public-favorites-panel";
94 import {
95     loadCollectionsContentAddressPanel,
96     collectionsContentAddressActions,
97 } from "store/collections-content-address-panel/collections-content-address-panel-actions";
98 import { collectionContentAddressPanelColumns } from "views/collection-content-address-panel/collection-content-address-panel";
99 import { subprocessPanelActions } from "store/subprocess-panel/subprocess-panel-actions";
100 import { subprocessPanelColumns } from "views/subprocess-panel/subprocess-panel-root";
101 import { loadAllProcessesPanel, allProcessesPanelActions } from "../all-processes-panel/all-processes-panel-action";
102 import { allProcessesPanelColumns } from "views/all-processes-panel/all-processes-panel";
103 import { userProfileGroupsColumns } from "views/user-profile-panel/user-profile-panel-root";
104 import { selectedToArray, selectedToKindSet } from "components/multiselect-toolbar/MultiselectToolbar";
105 import { deselectOne } from "store/multiselect/multiselect-actions";
106 import { treePickerActions } from "store/tree-picker/tree-picker-actions";
107 import { workflowProcessesPanelColumns } from "views/workflow-panel/workflow-processes-panel-root";
108 import { workflowProcessesPanelActions } from "store/workflow-panel/workflow-panel-actions";
109
110 export const WORKBENCH_LOADING_SCREEN = "workbenchLoadingScreen";
111
112 export const isWorkbenchLoading = (state: RootState) => {
113     const progress = getProgressIndicator(WORKBENCH_LOADING_SCREEN)(state.progressIndicator);
114     return progress ? progress.working : false;
115 };
116
117 export const handleFirstTimeLoad = (action: any) => async (dispatch: Dispatch<any>, getState: () => RootState) => {
118     try {
119         await dispatch(action);
120     } catch (e) {
121         snackbarActions.OPEN_SNACKBAR({
122             message: "Error " + e,
123             hideDuration: 8000,
124             kind: SnackbarKind.WARNING,
125         })
126     } finally {
127         if (isWorkbenchLoading(getState())) {
128             dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
129         }
130     }
131 };
132
133 export const loadWorkbench = () => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
134     dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
135     const { auth, router } = getState();
136     const { user } = auth;
137     if (user) {
138         dispatch(projectPanelDataActions.SET_COLUMNS({ columns: projectPanelDataColumns }));
139         dispatch(projectPanelRunActions.SET_COLUMNS({ columns: projectPanelRunColumns }));
140         dispatch(favoritePanelActions.SET_COLUMNS({ columns: favoritePanelColumns }));
141         dispatch(
142             allProcessesPanelActions.SET_COLUMNS({
143                 columns: allProcessesPanelColumns,
144             })
145         );
146         dispatch(
147             publicFavoritePanelActions.SET_COLUMNS({
148                 columns: publicFavoritePanelColumns,
149             })
150         );
151         dispatch(trashPanelActions.SET_COLUMNS({ columns: trashPanelColumns }));
152         dispatch(sharedWithMePanelActions.SET_COLUMNS({ columns: sharedWithMePanelColumns }));
153         dispatch(workflowPanelActions.SET_COLUMNS({ columns: workflowPanelColumns }));
154         dispatch(
155             searchResultsPanelActions.SET_FETCH_MODE({
156                 fetchMode: DataTableFetchMode.INFINITE,
157             })
158         );
159         dispatch(
160             searchResultsPanelActions.SET_COLUMNS({
161                 columns: searchResultsPanelColumns,
162             })
163         );
164         dispatch(userBindedActions.SET_COLUMNS({ columns: userPanelColumns }));
165         dispatch(
166             groupPanelActions.GroupsPanelActions.SET_COLUMNS({
167                 columns: groupsPanelColumns,
168             })
169         );
170         dispatch(
171             groupDetailsPanelActions.GroupMembersPanelActions.SET_COLUMNS({
172                 columns: groupDetailsMembersPanelColumns,
173             })
174         );
175         dispatch(
176             groupDetailsPanelActions.GroupPermissionsPanelActions.SET_COLUMNS({
177                 columns: groupDetailsPermissionsPanelColumns,
178             })
179         );
180         dispatch(
181             userProfilePanelActions.UserProfileGroupsActions.SET_COLUMNS({
182                 columns: userProfileGroupsColumns,
183             })
184         );
185         dispatch(linkPanelActions.SET_COLUMNS({ columns: linkPanelColumns }));
186         dispatch(
187             apiClientAuthorizationsActions.SET_COLUMNS({
188                 columns: apiClientAuthorizationPanelColumns,
189             })
190         );
191         dispatch(
192             collectionsContentAddressActions.SET_COLUMNS({
193                 columns: collectionContentAddressPanelColumns,
194             })
195         );
196         dispatch(subprocessPanelActions.SET_COLUMNS({ columns: subprocessPanelColumns }));
197         dispatch(workflowProcessesPanelActions.SET_COLUMNS({ columns: workflowProcessesPanelColumns }));
198
199         if (services.linkAccountService.getAccountToLink()) {
200             dispatch(linkAccountPanelActions.HAS_SESSION_DATA());
201         }
202
203         dispatch<any>(initSidePanelTree());
204         if (router.location) {
205             const match = matchRootRoute(router.location.pathname);
206             if (match) {
207                 dispatch<any>(navigateToRootProject);
208             }
209         }
210     } else {
211         dispatch(userIsNotAuthenticated);
212     }
213 };
214
215 export const loadFavorites = () =>
216     handleFirstTimeLoad((dispatch: Dispatch) => {
217         dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.FAVORITES));
218         dispatch<any>(loadFavoritePanel());
219         dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.FAVORITES));
220     });
221
222 export const loadCollectionContentAddress = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
223     await dispatch(loadCollectionsContentAddressPanel());
224 });
225
226 export const loadTrash = () =>
227     handleFirstTimeLoad((dispatch: Dispatch) => {
228         dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
229         dispatch<any>(loadTrashPanel());
230         dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.TRASH));
231     });
232
233 export const loadAllProcesses = () =>
234     handleFirstTimeLoad((dispatch: Dispatch) => {
235         dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.ALL_PROCESSES));
236         dispatch<any>(loadAllProcessesPanel());
237         dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.ALL_PROCESSES));
238     });
239
240 export const loadProject = (uuid: string) =>
241     handleFirstTimeLoad(async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
242         const userUuid = getUserUuid(getState());
243         dispatch(setIsProjectPanelTrashed(false));
244         if (!userUuid) {
245             return;
246         }
247         try {
248             dispatch(progressIndicatorActions.START_WORKING(uuid));
249             if (extractUuidKind(uuid) === ResourceKind.USER && userUuid !== uuid) {
250                 // Load another users home projects
251                 dispatch(finishLoadingProject(uuid));
252                 dispatch<any>(setSidePanelBreadcrumbs(uuid));
253             } else if (userUuid !== uuid) {
254                 await dispatch(finishLoadingProject(uuid));
255                 const match = await loadGroupContentsResource({
256                     uuid,
257                     userUuid,
258                     services,
259                 });
260                 match({
261                     OWNED: async () => {
262                         await dispatch(activateSidePanelTreeItem(uuid));
263                         dispatch<any>(setSidePanelBreadcrumbs(uuid));
264                     },
265                     SHARED: async () => {
266                         await dispatch(activateSidePanelTreeItem(uuid));
267                         dispatch<any>(setSharedWithMeBreadcrumbs(uuid));
268                     },
269                     TRASHED: async () => {
270                         await dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
271                         dispatch<any>(setTrashBreadcrumbs(uuid));
272                         dispatch(setIsProjectPanelTrashed(true));
273                     },
274                 });
275             } else {
276                 await dispatch(finishLoadingProject(userUuid));
277                 await dispatch(activateSidePanelTreeItem(userUuid));
278                 dispatch<any>(setSidePanelBreadcrumbs(userUuid));
279             }
280         } finally {
281             dispatch(progressIndicatorActions.STOP_WORKING(uuid));
282         }
283     });
284
285 export const createProject = (data: projectCreateActions.ProjectCreateFormDialogData) => async (dispatch: Dispatch) => {
286     const newProject = await dispatch<any>(projectCreateActions.createProject(data));
287     if (newProject) {
288         dispatch(
289             snackbarActions.OPEN_SNACKBAR({
290                 message: "Project has been successfully created.",
291                 hideDuration: 2000,
292                 kind: SnackbarKind.SUCCESS,
293             })
294         );
295         await dispatch<any>(loadSidePanelTreeProjects(newProject.ownerUuid));
296         dispatch<any>(navigateTo(newProject.uuid));
297     }
298 };
299
300 export const moveProject =
301     (data: MoveToFormDialogData, isSecondaryMove = false) =>
302         async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
303             const checkedList = getState().multiselect.checkedList;
304             const uuidsToMove: string[] = data.fromContextMenu ? [data.uuid] : selectedToArray(checkedList);
305
306             //if no items in checkedlist default to normal context menu behavior
307             if (!isSecondaryMove && !uuidsToMove.length) uuidsToMove.push(data.uuid);
308
309             const sourceUuid = getResource(data.uuid)(getState().resources)?.ownerUuid;
310             const destinationUuid = data.ownerUuid;
311
312             const projectsToMove: MoveableResource[] = uuidsToMove
313                 .map(uuid => getResource(uuid)(getState().resources) as MoveableResource)
314                 .filter(resource => resource.kind === ResourceKind.PROJECT);
315
316             for (const project of projectsToMove) {
317                 await moveSingleProject(project);
318             }
319
320             //omly propagate if this call is the original
321             if (!isSecondaryMove) {
322                 const kindsToMove: Set<string> = selectedToKindSet(checkedList);
323                 kindsToMove.delete(ResourceKind.PROJECT);
324
325                 kindsToMove.forEach(kind => {
326                     secondaryMove[kind](data, true)(dispatch, getState, services);
327                 });
328             }
329
330             async function moveSingleProject(project: MoveableResource) {
331                 try {
332                     const oldProject: MoveToFormDialogData = { name: project.name, uuid: project.uuid, ownerUuid: data.ownerUuid };
333                     const oldOwnerUuid = oldProject ? oldProject.ownerUuid : "";
334                     const movedProject = await dispatch<any>(projectMoveActions.moveProject(oldProject));
335                     if (movedProject) {
336                         dispatch(
337                             snackbarActions.OPEN_SNACKBAR({
338                                 message: "Project has been moved",
339                                 hideDuration: 2000,
340                                 kind: SnackbarKind.SUCCESS,
341                             })
342                         );
343                         await dispatch<any>(reloadProjectMatchingUuid([oldOwnerUuid, movedProject.ownerUuid, movedProject.uuid]));
344                     }
345                 } catch (e) {
346                     dispatch(
347                         snackbarActions.OPEN_SNACKBAR({
348                             message: !!(project as any).frozenByUuid ? 'Could not move frozen project.' : e.message,
349                             hideDuration: 2000,
350                             kind: SnackbarKind.ERROR,
351                         })
352                     );
353                 }
354             }
355             if (sourceUuid) await dispatch<any>(loadSidePanelTreeProjects(sourceUuid));
356             await dispatch<any>(loadSidePanelTreeProjects(destinationUuid));
357         };
358
359 export const updateProject = (data: projectUpdateActions.ProjectUpdateFormDialogData) => async (dispatch: Dispatch) => {
360     const updatedProject = await dispatch<any>(projectUpdateActions.updateProject(data));
361     if (updatedProject) {
362         dispatch(
363             snackbarActions.OPEN_SNACKBAR({
364                 message: "Project has been successfully updated.",
365                 hideDuration: 2000,
366                 kind: SnackbarKind.SUCCESS,
367             })
368         );
369         await dispatch<any>(loadSidePanelTreeProjects(updatedProject.ownerUuid));
370         dispatch<any>(reloadProjectMatchingUuid([updatedProject.ownerUuid, updatedProject.uuid]));
371     }
372 };
373
374 export const updateGroup = (data: projectUpdateActions.ProjectUpdateFormDialogData) => async (dispatch: Dispatch) => {
375     const updatedGroup = await dispatch<any>(groupPanelActions.updateGroup(data));
376     if (updatedGroup) {
377         dispatch(
378             snackbarActions.OPEN_SNACKBAR({
379                 message: "Group has been successfully updated.",
380                 hideDuration: 2000,
381                 kind: SnackbarKind.SUCCESS,
382             })
383         );
384         await dispatch<any>(loadSidePanelTreeProjects(updatedGroup.ownerUuid));
385         dispatch<any>(reloadProjectMatchingUuid([updatedGroup.ownerUuid, updatedGroup.uuid]));
386     }
387 };
388
389 export const loadCollection = (uuid: string) =>
390     handleFirstTimeLoad(async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
391         const userUuid = getUserUuid(getState());
392         try {
393             dispatch(progressIndicatorActions.START_WORKING(uuid));
394             if (userUuid) {
395                 const match = await loadGroupContentsResource({
396                     uuid,
397                     userUuid,
398                     services,
399                 });
400                 let collection: CollectionResource | undefined;
401                 let breadcrumbfunc:
402                     | ((uuid: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => Promise<void>)
403                     | undefined;
404                 let sidepanel: string | undefined;
405                 match({
406                     OWNED: thecollection => {
407                         collection = thecollection as CollectionResource;
408                         sidepanel = collection.ownerUuid;
409                         breadcrumbfunc = setSidePanelBreadcrumbs;
410                     },
411                     SHARED: thecollection => {
412                         collection = thecollection as CollectionResource;
413                         sidepanel = collection.ownerUuid;
414                         breadcrumbfunc = setSharedWithMeBreadcrumbs;
415                     },
416                     TRASHED: thecollection => {
417                         collection = thecollection as CollectionResource;
418                         sidepanel = SidePanelTreeCategory.TRASH;
419                         breadcrumbfunc = () => setTrashBreadcrumbs("");
420                     },
421                 });
422                 if (collection && breadcrumbfunc && sidepanel) {
423                     dispatch(updateResources([collection]));
424                     await dispatch<any>(finishLoadingProject(collection.ownerUuid));
425                     dispatch(collectionPanelActions.SET_COLLECTION(collection));
426                     await dispatch(activateSidePanelTreeItem(sidepanel));
427                     dispatch(breadcrumbfunc(collection.ownerUuid));
428                     dispatch(loadCollectionPanel(collection.uuid));
429                 }
430             }
431         } finally {
432             dispatch(progressIndicatorActions.STOP_WORKING(uuid));
433         }
434     });
435
436 export const createCollection = (data: collectionCreateActions.CollectionCreateFormDialogData) => async (dispatch: Dispatch) => {
437     const collection = await dispatch<any>(collectionCreateActions.createCollection(data));
438     if (collection) {
439         dispatch(
440             snackbarActions.OPEN_SNACKBAR({
441                 message: "Collection has been successfully created.",
442                 hideDuration: 2000,
443                 kind: SnackbarKind.SUCCESS,
444             })
445         );
446         dispatch<any>(updateResources([collection]));
447         dispatch<any>(navigateTo(collection.uuid));
448     }
449 };
450
451 export const copyCollection = (data: CopyFormDialogData) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
452     const checkedList = getState().multiselect.checkedList;
453     const uuidsToCopy: string[] = data.fromContextMenu ? [data.uuid] : selectedToArray(checkedList);
454
455     //if no items in checkedlist && no items passed in, default to normal context menu behavior
456     if (!uuidsToCopy.length) uuidsToCopy.push(data.uuid);
457
458     const collectionsToCopy: CollectionCopyResource[] = uuidsToCopy
459         .map(uuid => getResource(uuid)(getState().resources) as CollectionCopyResource)
460         .filter(resource => resource.kind === ResourceKind.COLLECTION);
461
462     for (const collection of collectionsToCopy) {
463         await copySingleCollection({ ...collection, ownerUuid: data.ownerUuid } as CollectionCopyResource);
464     }
465
466     async function copySingleCollection(copyToProject: CollectionCopyResource) {
467         const newName = data.fromContextMenu || collectionsToCopy.length === 1 ? data.name : `Copy of: ${copyToProject.name}`;
468         try {
469             const collection = await dispatch<any>(
470                 collectionCopyActions.copyCollection({
471                     ...copyToProject,
472                     name: newName,
473                     fromContextMenu: collectionsToCopy.length === 1 ? true : data.fromContextMenu,
474                 })
475             );
476             if (copyToProject && collection) {
477                 await dispatch<any>(reloadProjectMatchingUuid([copyToProject.uuid]));
478                 dispatch(
479                     snackbarActions.OPEN_SNACKBAR({
480                         message: "Collection has been copied.",
481                         hideDuration: 3000,
482                         kind: SnackbarKind.SUCCESS,
483                         link: collection.ownerUuid,
484                     })
485                 );
486                 dispatch<any>(deselectOne(copyToProject.uuid));
487             }
488         } catch (e) {
489             dispatch(
490                 snackbarActions.OPEN_SNACKBAR({
491                     message: e.message,
492                     hideDuration: 2000,
493                     kind: SnackbarKind.ERROR,
494                 })
495             );
496         }
497     }
498     dispatch(projectPanelDataActions.REQUEST_ITEMS());
499 };
500
501 export const moveCollection =
502     (data: MoveToFormDialogData, isSecondaryMove = false) =>
503         async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
504             const checkedList = getState().multiselect.checkedList;
505             const uuidsToMove: string[] = data.fromContextMenu ? [data.uuid] : selectedToArray(checkedList);
506
507             //if no items in checkedlist && no items passed in, default to normal context menu behavior
508             if (!isSecondaryMove && !uuidsToMove.length) uuidsToMove.push(data.uuid);
509
510             const collectionsToMove: MoveableResource[] = uuidsToMove
511                 .map(uuid => getResource(uuid)(getState().resources) as MoveableResource)
512                 .filter(resource => resource.kind === ResourceKind.COLLECTION);
513
514             for (const collection of collectionsToMove) {
515                 await moveSingleCollection(collection);
516             }
517
518             //omly propagate if this call is the original
519             if (!isSecondaryMove) {
520                 const kindsToMove: Set<string> = selectedToKindSet(checkedList);
521                 kindsToMove.delete(ResourceKind.COLLECTION);
522
523                 kindsToMove.forEach(kind => {
524                     secondaryMove[kind](data, true)(dispatch, getState, services);
525                 });
526             }
527
528             async function moveSingleCollection(collection: MoveableResource) {
529                 try {
530                     const oldCollection: MoveToFormDialogData = { name: collection.name, uuid: collection.uuid, ownerUuid: data.ownerUuid };
531                     const movedCollection = await dispatch<any>(collectionMoveActions.moveCollection(oldCollection));
532                     dispatch<any>(updateResources([movedCollection]));
533                     dispatch<any>(reloadProjectMatchingUuid([movedCollection.ownerUuid]));
534                     dispatch(
535                         snackbarActions.OPEN_SNACKBAR({
536                             message: "Collection has been moved.",
537                             hideDuration: 2000,
538                             kind: SnackbarKind.SUCCESS,
539                         })
540                     );
541                 } catch (e) {
542                     dispatch(
543                         snackbarActions.OPEN_SNACKBAR({
544                             message: e.message,
545                             hideDuration: 2000,
546                             kind: SnackbarKind.ERROR,
547                         })
548                     );
549                 }
550             }
551         };
552
553 export const loadProcess = (uuid: string) =>
554     handleFirstTimeLoad(async (dispatch: Dispatch, getState: () => RootState) => {
555         try {
556             dispatch(progressIndicatorActions.START_WORKING(uuid));
557             dispatch<any>(loadProcessPanel(uuid));
558             const process = await dispatch<any>(processesActions.loadProcess(uuid));
559             if (process) {
560                 await dispatch<any>(finishLoadingProject(process.containerRequest.ownerUuid));
561                 await dispatch<any>(activateSidePanelTreeItem(process.containerRequest.ownerUuid));
562                 dispatch<any>(setProcessBreadcrumbs(uuid));
563                 dispatch<any>(loadDetailsPanel(uuid));
564             }
565         } finally {
566             dispatch(progressIndicatorActions.STOP_WORKING(uuid));
567         }
568     });
569
570 export const loadRegisteredWorkflow = (uuid: string) =>
571     handleFirstTimeLoad(async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
572         const userUuid = getUserUuid(getState());
573         if (userUuid) {
574             const match = await loadGroupContentsResource({
575                 uuid,
576                 userUuid,
577                 services,
578             });
579             let workflow: WorkflowResource | undefined;
580             let breadcrumbfunc:
581                 | ((uuid: string) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => Promise<void>)
582                 | undefined;
583             match({
584                 OWNED: async theworkflow => {
585                     workflow = theworkflow as WorkflowResource;
586                     breadcrumbfunc = setSidePanelBreadcrumbs;
587                 },
588                 SHARED: async theworkflow => {
589                     workflow = theworkflow as WorkflowResource;
590                     breadcrumbfunc = setSharedWithMeBreadcrumbs;
591                 },
592                 TRASHED: () => { },
593             });
594             if (workflow && breadcrumbfunc) {
595                 dispatch(updateResources([workflow]));
596                 await dispatch<any>(finishLoadingProject(workflow.ownerUuid));
597                 await dispatch<any>(activateSidePanelTreeItem(workflow.ownerUuid));
598                 dispatch<any>(breadcrumbfunc(workflow.ownerUuid));
599                 dispatch(workflowProcessesPanelActions.REQUEST_ITEMS());
600             }
601         }
602     });
603
604 export const updateProcess = (data: processUpdateActions.ProcessUpdateFormDialogData) => async (dispatch: Dispatch) => {
605     try {
606         const process = await dispatch<any>(processUpdateActions.updateProcess(data));
607         if (process) {
608             dispatch(
609                 snackbarActions.OPEN_SNACKBAR({
610                     message: "Process has been successfully updated.",
611                     hideDuration: 2000,
612                     kind: SnackbarKind.SUCCESS,
613                 })
614             );
615             dispatch<any>(updateResources([process]));
616             dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
617         }
618     } catch (e) {
619         dispatch(
620             snackbarActions.OPEN_SNACKBAR({
621                 message: e.message,
622                 hideDuration: 2000,
623                 kind: SnackbarKind.ERROR,
624             })
625         );
626     }
627 };
628
629 export const moveProcess =
630     (data: MoveToFormDialogData, isSecondaryMove = false) =>
631         async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
632             const checkedList = getState().multiselect.checkedList;
633             const uuidsToMove: string[] = data.fromContextMenu ? [data.uuid] : selectedToArray(checkedList);
634
635             //if no items in checkedlist && no items passed in, default to normal context menu behavior
636             if (!isSecondaryMove && !uuidsToMove.length) uuidsToMove.push(data.uuid);
637
638             const processesToMove: MoveableResource[] = uuidsToMove
639                 .map(uuid => getResource(uuid)(getState().resources) as MoveableResource)
640                 .filter(resource => resource.kind === ResourceKind.PROCESS);
641
642             for (const process of processesToMove) {
643                 await moveSingleProcess(process);
644             }
645
646             //omly propagate if this call is the original
647             if (!isSecondaryMove) {
648                 const kindsToMove: Set<string> = selectedToKindSet(checkedList);
649                 kindsToMove.delete(ResourceKind.PROCESS);
650
651                 kindsToMove.forEach(kind => {
652                     secondaryMove[kind](data, true)(dispatch, getState, services);
653                 });
654             }
655
656             async function moveSingleProcess(process: MoveableResource) {
657                 try {
658                     const oldProcess: MoveToFormDialogData = { name: process.name, uuid: process.uuid, ownerUuid: data.ownerUuid };
659                     const movedProcess = await dispatch<any>(processMoveActions.moveProcess(oldProcess));
660                     dispatch<any>(updateResources([movedProcess]));
661                     dispatch<any>(reloadProjectMatchingUuid([movedProcess.ownerUuid]));
662                     dispatch(
663                         snackbarActions.OPEN_SNACKBAR({
664                             message: "Process has been moved.",
665                             hideDuration: 2000,
666                             kind: SnackbarKind.SUCCESS,
667                         })
668                     );
669                 } catch (e) {
670                     dispatch(
671                         snackbarActions.OPEN_SNACKBAR({
672                             message: e.message,
673                             hideDuration: 2000,
674                             kind: SnackbarKind.ERROR,
675                         })
676                     );
677                 }
678             }
679         };
680
681 export const copyProcess = (data: CopyFormDialogData) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
682     try {
683         const process = await dispatch<any>(processCopyActions.copyProcess(data));
684         dispatch<any>(updateResources([process]));
685         dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
686         dispatch(
687             snackbarActions.OPEN_SNACKBAR({
688                 message: "Process has been copied.",
689                 hideDuration: 2000,
690                 kind: SnackbarKind.SUCCESS,
691             })
692         );
693         dispatch<any>(navigateTo(process.uuid));
694     } catch (e) {
695         dispatch(
696             snackbarActions.OPEN_SNACKBAR({
697                 message: e.message,
698                 hideDuration: 2000,
699                 kind: SnackbarKind.ERROR,
700             })
701         );
702     }
703 };
704
705 export const resourceIsNotLoaded = (uuid: string) =>
706     snackbarActions.OPEN_SNACKBAR({
707         message: `Resource identified by ${uuid} is not loaded.`,
708         kind: SnackbarKind.ERROR,
709     });
710
711 export const userIsNotAuthenticated = snackbarActions.OPEN_SNACKBAR({
712     message: "User is not authenticated",
713     kind: SnackbarKind.ERROR,
714 });
715
716 export const couldNotLoadUser = snackbarActions.OPEN_SNACKBAR({
717     message: "Could not load user",
718     kind: SnackbarKind.ERROR,
719 });
720
721 export const reloadProjectMatchingUuid =
722     (matchingUuids: string[]) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
723         const currentProjectPanelUuid = getProjectPanelCurrentUuid(getState());
724         if (currentProjectPanelUuid && matchingUuids.some(uuid => uuid === currentProjectPanelUuid)) {
725             dispatch<any>(loadProject(currentProjectPanelUuid));
726         }
727     };
728
729 export const loadSharedWithMe = handleFirstTimeLoad(async (dispatch: Dispatch) => {
730     dispatch<any>(loadSharedWithMePanel());
731     await dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
732     await dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.SHARED_WITH_ME));
733 });
734
735 export const loadRunProcess = handleFirstTimeLoad(async (dispatch: Dispatch) => {
736     await dispatch<any>(loadRunProcessPanel());
737 });
738
739 export const loadPublicFavorites = () =>
740     handleFirstTimeLoad((dispatch: Dispatch) => {
741         dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.PUBLIC_FAVORITES));
742         dispatch<any>(loadPublicFavoritePanel());
743         dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.PUBLIC_FAVORITES));
744     });
745
746 export const loadSearchResults = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
747     await dispatch(loadSearchResultsPanel());
748 });
749
750 export const loadLinks = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
751     await dispatch(loadLinkPanel());
752 });
753
754 export const loadVirtualMachines = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
755     await dispatch(loadVirtualMachinesPanel());
756     dispatch(setVirtualMachinesBreadcrumbs());
757     dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.SHELL_ACCESS));
758 });
759
760 export const loadVirtualMachinesAdmin = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
761     await dispatch(loadVirtualMachinesPanel());
762     dispatch(setVirtualMachinesAdminBreadcrumbs());
763     dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SIDE_PANEL_TREE }))
764 });
765
766 export const loadRepositories = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
767     await dispatch(loadRepositoriesPanel());
768     dispatch(setRepositoriesBreadcrumbs());
769 });
770
771 export const loadSshKeys = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
772     await dispatch(loadSshKeysPanel());
773 });
774
775 export const loadInstanceTypes = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
776     dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.INSTANCE_TYPES));
777     dispatch(setInstanceTypesBreadcrumbs());
778 });
779
780 export const loadSiteManager = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
781     await dispatch(loadSiteManagerPanel());
782 });
783
784 export const loadUserProfile = (userUuid?: string) =>
785     handleFirstTimeLoad((dispatch: Dispatch<any>) => {
786         if (userUuid) {
787             dispatch(setUserProfileBreadcrumbs(userUuid));
788             dispatch(userProfilePanelActions.loadUserProfilePanel(userUuid));
789         } else {
790             dispatch(setMyAccountBreadcrumbs());
791             dispatch(userProfilePanelActions.loadUserProfilePanel());
792         }
793     });
794
795 export const loadLinkAccount = handleFirstTimeLoad((dispatch: Dispatch<any>) => {
796     dispatch(loadLinkAccountPanel());
797 });
798
799 export const loadKeepServices = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
800     await dispatch(loadKeepServicesPanel());
801 });
802
803 export const loadUsers = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
804     await dispatch(loadUsersPanel());
805     dispatch(setUsersBreadcrumbs());
806 });
807
808 export const loadApiClientAuthorizations = handleFirstTimeLoad(async (dispatch: Dispatch<any>) => {
809     await dispatch(loadApiClientAuthorizationsPanel());
810 });
811
812 export const loadGroupsPanel = handleFirstTimeLoad((dispatch: Dispatch<any>) => {
813     dispatch(setGroupsBreadcrumbs());
814     dispatch(groupPanelActions.loadGroupsPanel());
815 });
816
817 export const loadGroupDetailsPanel = (groupUuid: string) =>
818     handleFirstTimeLoad((dispatch: Dispatch<any>) => {
819         dispatch(setGroupDetailsBreadcrumbs(groupUuid));
820         dispatch(groupDetailsPanelActions.loadGroupDetailsPanel(groupUuid));
821     });
822
823 const finishLoadingProject = (project: GroupContentsResource | string) => async (dispatch: Dispatch<any>) => {
824     const uuid = typeof project === "string" ? project : project.uuid;
825     dispatch(loadDetailsPanel(uuid));
826     if (typeof project !== "string") {
827         dispatch(updateResources([project]));
828     }
829 };
830
831 const loadGroupContentsResource = async (params: { uuid: string; userUuid: string; services: ServiceRepository }) => {
832     const filters = new FilterBuilder().addEqual("uuid", params.uuid).getFilters();
833     const { items } = await params.services.groupsService.contents(params.userUuid, {
834         filters,
835         recursive: true,
836         includeTrash: true,
837     });
838     const resource = items.shift();
839     let handler: GroupContentsHandler;
840     if (resource) {
841         handler =
842             (resource.kind === ResourceKind.COLLECTION || resource.kind === ResourceKind.PROJECT) && resource.isTrashed
843                 ? groupContentsHandlers.TRASHED(resource)
844                 : groupContentsHandlers.OWNED(resource);
845     } else {
846         const kind = extractUuidKind(params.uuid);
847         let resource: GroupContentsResource;
848         if (kind === ResourceKind.COLLECTION) {
849             resource = await params.services.collectionService.get(params.uuid);
850         } else if (kind === ResourceKind.PROJECT) {
851             resource = await params.services.projectService.get(params.uuid);
852         } else if (kind === ResourceKind.WORKFLOW) {
853             resource = await params.services.workflowService.get(params.uuid);
854         } else if (kind === ResourceKind.CONTAINER_REQUEST) {
855             resource = await params.services.containerRequestService.get(params.uuid);
856         } else {
857             throw new Error("loadGroupContentsResource unsupported kind " + kind);
858         }
859         handler = groupContentsHandlers.SHARED(resource);
860     }
861     return (cases: MatchCases<typeof groupContentsHandlersRecord, GroupContentsHandler, void>) => groupContentsHandlers.match(handler, cases);
862 };
863
864 const groupContentsHandlersRecord = {
865     TRASHED: ofType<GroupContentsResource>(),
866     SHARED: ofType<GroupContentsResource>(),
867     OWNED: ofType<GroupContentsResource>(),
868 };
869
870 const groupContentsHandlers = unionize(groupContentsHandlersRecord);
871
872 type GroupContentsHandler = UnionOf<typeof groupContentsHandlers>;
873
874 type CollectionCopyResource = Resource & { name: string; fromContextMenu: boolean };
875
876 type MoveableResource = Resource & { name: string };
877
878 type MoveFunc = (
879     data: MoveToFormDialogData,
880     isSecondaryMove?: boolean
881 ) => (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => Promise<void>;
882
883 const secondaryMove: Record<string, MoveFunc> = {
884     [ResourceKind.PROJECT]: moveProject,
885     [ResourceKind.PROCESS]: moveProcess,
886     [ResourceKind.COLLECTION]: moveCollection,
887 };