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