Refactor loading resource that can be owned, shared or trashed
[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";
7 import { loadDetailsPanel } from '~/store/details-panel/details-panel-action';
8 import { snackbarActions } from '../snackbar/snackbar-actions';
9 import { loadFavoritePanel } from '../favorite-panel/favorite-panel-action';
10 import { openProjectPanel, projectPanelActions } from '~/store/project-panel/project-panel-action';
11 import { activateSidePanelTreeItem, initSidePanelTree, SidePanelTreeCategory, loadSidePanelTreeProjects } from '../side-panel-tree/side-panel-tree-actions';
12 import { loadResource, updateResources } from '../resources/resources-actions';
13 import { favoritePanelActions } from '~/store/favorite-panel/favorite-panel-action';
14 import { projectPanelColumns } from '~/views/project-panel/project-panel';
15 import { favoritePanelColumns } from '~/views/favorite-panel/favorite-panel';
16 import { matchRootRoute } from '~/routes/routes';
17 import { setSidePanelBreadcrumbs, setProcessBreadcrumbs, setSharedWithMeBreadcrumbs, setTrashBreadcrumbs } from '../breadcrumbs/breadcrumbs-actions';
18 import { navigateToProject } from '../navigation/navigation-action';
19 import { MoveToFormDialogData } from '~/store/move-to-dialog/move-to-dialog';
20 import { ServiceRepository } from '~/services/services';
21 import { getResource } from '../resources/resources';
22 import { getProjectPanelCurrentUuid } from '../project-panel/project-panel-action';
23 import * as projectCreateActions from '~/store/projects/project-create-actions';
24 import * as projectMoveActions from '~/store/projects/project-move-actions';
25 import * as projectUpdateActions from '~/store/projects/project-update-actions';
26 import * as collectionCreateActions from '~/store/collections/collection-create-actions';
27 import * as collectionCopyActions from '~/store/collections/collection-copy-actions';
28 import * as collectionUpdateActions from '~/store/collections/collection-update-actions';
29 import * as collectionMoveActions from '~/store/collections/collection-move-actions';
30 import * as processesActions from '../processes/processes-actions';
31 import * as processMoveActions from '~/store/processes/process-move-actions';
32 import * as processUpdateActions from '~/store/processes/process-update-actions';
33 import * as processCopyActions from '~/store/processes/process-copy-actions';
34 import { trashPanelColumns } from "~/views/trash-panel/trash-panel";
35 import { loadTrashPanel, trashPanelActions } from "~/store/trash-panel/trash-panel-action";
36 import { initProcessLogsPanel } from '../process-logs-panel/process-logs-panel-actions';
37 import { loadProcessPanel } from '~/store/process-panel/process-panel-actions';
38 import { sharedWithMePanelActions } from '~/store/shared-with-me-panel/shared-with-me-panel-actions';
39 import { loadSharedWithMePanel } from '../shared-with-me-panel/shared-with-me-panel-actions';
40 import { CopyFormDialogData } from '~/store/copy-dialog/copy-dialog';
41 import { progressIndicatorActions } from '~/store/progress-indicator/progress-indicator-actions';
42 import { getProgressIndicator } from '../progress-indicator/progress-indicator-reducer';
43 import { ResourceKind, extractUuidKind } from '~/models/resource';
44 import { FilterBuilder } from '~/services/api/filter-builder';
45 import { GroupContentsResource } from '~/services/groups-service/groups-service';
46 import { unionize, ofType, UnionOf, MatchCases } from '~/common/unionize';
47
48 export const WORKBENCH_LOADING_SCREEN = 'workbenchLoadingScreen';
49
50 export const isWorkbenchLoading = (state: RootState) => {
51     const progress = getProgressIndicator(WORKBENCH_LOADING_SCREEN)(state.progressIndicator);
52     return progress ? progress.working : false;
53 };
54
55 const handleFirstTimeLoad = (action: any) =>
56     async (dispatch: Dispatch<any>, getState: () => RootState) => {
57         try {
58             await dispatch(action);
59         } finally {
60             if (isWorkbenchLoading(getState())) {
61                 dispatch(progressIndicatorActions.STOP_WORKING(WORKBENCH_LOADING_SCREEN));
62             }
63         }
64     };
65
66
67 export const loadWorkbench = () =>
68     async (dispatch: Dispatch, getState: () => RootState) => {
69         dispatch(progressIndicatorActions.START_WORKING(WORKBENCH_LOADING_SCREEN));
70         const { auth, router } = getState();
71         const { user } = auth;
72         if (user) {
73             const userResource = await dispatch<any>(loadResource(user.uuid));
74             if (userResource) {
75                 dispatch(projectPanelActions.SET_COLUMNS({ columns: projectPanelColumns }));
76                 dispatch(favoritePanelActions.SET_COLUMNS({ columns: favoritePanelColumns }));
77                 dispatch(trashPanelActions.SET_COLUMNS({ columns: trashPanelColumns }));
78                 dispatch(sharedWithMePanelActions.SET_COLUMNS({ columns: projectPanelColumns }));
79                 dispatch<any>(initSidePanelTree());
80                 if (router.location) {
81                     const match = matchRootRoute(router.location.pathname);
82                     if (match) {
83                         dispatch(navigateToProject(userResource.uuid));
84                     }
85                 }
86             } else {
87                 dispatch(userIsNotAuthenticated);
88             }
89         } else {
90             dispatch(userIsNotAuthenticated);
91         }
92     };
93
94 export const loadFavorites = () =>
95     handleFirstTimeLoad(
96         (dispatch: Dispatch) => {
97             dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.FAVORITES));
98             dispatch<any>(loadFavoritePanel());
99             dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.FAVORITES));
100         });
101
102 export const loadTrash = () =>
103     handleFirstTimeLoad(
104         (dispatch: Dispatch) => {
105             dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
106             dispatch<any>(loadTrashPanel());
107             dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.TRASH));
108         });
109
110 export const loadProject = (uuid: string) =>
111     handleFirstTimeLoad(
112         async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
113             const userUuid = services.authService.getUuid();
114             if (userUuid) {
115                 if (userUuid !== uuid) {
116                     const match = await loadGroupContentsResource({ uuid, userUuid, services });
117                     match({
118                         OWNED: async project => {
119                             await dispatch(activateSidePanelTreeItem(uuid));
120                             dispatch<any>(setSidePanelBreadcrumbs(uuid));
121                             dispatch(finishLoadingProject(project));
122                         },
123                         SHARED: project => {
124                             dispatch<any>(setSharedWithMeBreadcrumbs(uuid));
125                             dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
126                             dispatch(finishLoadingProject(project));
127                         },
128                         TRASHED: project => {
129                             dispatch<any>(setTrashBreadcrumbs(uuid));
130                             dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
131                             dispatch(finishLoadingProject(project));
132                         }
133                     });
134                 } else {
135                     await dispatch(activateSidePanelTreeItem(userUuid));
136                     dispatch<any>(setSidePanelBreadcrumbs(userUuid));
137                     dispatch(finishLoadingProject(userUuid));
138                 }
139             }
140         });
141
142 export const createProject = (data: projectCreateActions.ProjectCreateFormDialogData) =>
143     async (dispatch: Dispatch) => {
144         const newProject = await dispatch<any>(projectCreateActions.createProject(data));
145         if (newProject) {
146             dispatch(snackbarActions.OPEN_SNACKBAR({
147                 message: "Project has been successfully created.",
148                 hideDuration: 2000
149             }));
150             await dispatch<any>(loadSidePanelTreeProjects(newProject.ownerUuid));
151             dispatch<any>(reloadProjectMatchingUuid([newProject.ownerUuid]));
152         }
153     };
154
155 export const moveProject = (data: MoveToFormDialogData) =>
156     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
157         try {
158             const oldProject = getResource(data.uuid)(getState().resources);
159             const oldOwnerUuid = oldProject ? oldProject.ownerUuid : '';
160             const movedProject = await dispatch<any>(projectMoveActions.moveProject(data));
161             if (movedProject) {
162                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Project has been moved', hideDuration: 2000 }));
163                 if (oldProject) {
164                     await dispatch<any>(loadSidePanelTreeProjects(oldProject.ownerUuid));
165                 }
166                 dispatch<any>(reloadProjectMatchingUuid([oldOwnerUuid, movedProject.ownerUuid, movedProject.uuid]));
167             }
168         } catch (e) {
169             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
170         }
171     };
172
173 export const updateProject = (data: projectUpdateActions.ProjectUpdateFormDialogData) =>
174     async (dispatch: Dispatch) => {
175         const updatedProject = await dispatch<any>(projectUpdateActions.updateProject(data));
176         if (updatedProject) {
177             dispatch(snackbarActions.OPEN_SNACKBAR({
178                 message: "Project has been successfully updated.",
179                 hideDuration: 2000
180             }));
181             await dispatch<any>(loadSidePanelTreeProjects(updatedProject.ownerUuid));
182             dispatch<any>(reloadProjectMatchingUuid([updatedProject.ownerUuid, updatedProject.uuid]));
183         }
184     };
185
186 export const loadCollection = (uuid: string) =>
187     handleFirstTimeLoad(
188         async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
189             const userUuid = services.authService.getUuid();
190             if (userUuid) {
191                 const match = await loadGroupContentsResource({ uuid, userUuid, services });
192                 match({
193                     OWNED: async collection => {
194                         dispatch(updateResources([collection]));
195                         await dispatch(activateSidePanelTreeItem(collection.ownerUuid));
196                         dispatch(setSidePanelBreadcrumbs(collection.ownerUuid));
197                     },
198                     SHARED: collection => {
199                         dispatch(updateResources([collection]));
200                         dispatch<any>(setSharedWithMeBreadcrumbs(collection.ownerUuid));
201                         dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
202                     },
203                     TRASHED: collection => {
204                         dispatch(updateResources([collection]));
205                         dispatch(setTrashBreadcrumbs(''));
206                         dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.TRASH));
207                     },
208
209                 });
210             }
211         });
212
213 export const createCollection = (data: collectionCreateActions.CollectionCreateFormDialogData) =>
214     async (dispatch: Dispatch) => {
215         const collection = await dispatch<any>(collectionCreateActions.createCollection(data));
216         if (collection) {
217             dispatch(snackbarActions.OPEN_SNACKBAR({
218                 message: "Collection has been successfully created.",
219                 hideDuration: 2000
220             }));
221             dispatch<any>(updateResources([collection]));
222             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
223         }
224     };
225
226 export const updateCollection = (data: collectionUpdateActions.CollectionUpdateFormDialogData) =>
227     async (dispatch: Dispatch) => {
228         const collection = await dispatch<any>(collectionUpdateActions.updateCollection(data));
229         if (collection) {
230             dispatch(snackbarActions.OPEN_SNACKBAR({
231                 message: "Collection has been successfully updated.",
232                 hideDuration: 2000
233             }));
234             dispatch<any>(updateResources([collection]));
235             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
236         }
237     };
238
239 export const copyCollection = (data: CopyFormDialogData) =>
240     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
241         try {
242             const collection = await dispatch<any>(collectionCopyActions.copyCollection(data));
243             dispatch<any>(updateResources([collection]));
244             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
245             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Collection has been copied.', hideDuration: 2000 }));
246         } catch (e) {
247             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
248         }
249     };
250
251 export const moveCollection = (data: MoveToFormDialogData) =>
252     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
253         try {
254             const collection = await dispatch<any>(collectionMoveActions.moveCollection(data));
255             dispatch<any>(updateResources([collection]));
256             dispatch<any>(reloadProjectMatchingUuid([collection.ownerUuid]));
257             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Collection has been moved.', hideDuration: 2000 }));
258         } catch (e) {
259             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
260         }
261     };
262
263 export const loadProcess = (uuid: string) =>
264     handleFirstTimeLoad(
265         async (dispatch: Dispatch, getState: () => RootState) => {
266             dispatch<any>(loadProcessPanel(uuid));
267             const process = await dispatch<any>(processesActions.loadProcess(uuid));
268             await dispatch<any>(activateSidePanelTreeItem(process.containerRequest.ownerUuid));
269             dispatch<any>(setProcessBreadcrumbs(uuid));
270             dispatch(loadDetailsPanel(uuid));
271         });
272
273 export const updateProcess = (data: processUpdateActions.ProcessUpdateFormDialogData) =>
274     async (dispatch: Dispatch) => {
275         try {
276             const process = await dispatch<any>(processUpdateActions.updateProcess(data));
277             if (process) {
278                 dispatch(snackbarActions.OPEN_SNACKBAR({
279                     message: "Process has been successfully updated.",
280                     hideDuration: 2000
281                 }));
282                 dispatch<any>(updateResources([process]));
283                 dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
284             }
285         } catch (e) {
286             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
287         }
288     };
289
290 export const moveProcess = (data: MoveToFormDialogData) =>
291     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
292         try {
293             const process = await dispatch<any>(processMoveActions.moveProcess(data));
294             dispatch<any>(updateResources([process]));
295             dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
296             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Process has been moved.', hideDuration: 2000 }));
297         } catch (e) {
298             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
299         }
300     };
301
302 export const copyProcess = (data: CopyFormDialogData) =>
303     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
304         try {
305             const process = await dispatch<any>(processCopyActions.copyProcess(data));
306             dispatch<any>(updateResources([process]));
307             dispatch<any>(reloadProjectMatchingUuid([process.ownerUuid]));
308             dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Process has been copied.', hideDuration: 2000 }));
309         } catch (e) {
310             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000 }));
311         }
312     };
313
314 export const loadProcessLog = (uuid: string) =>
315     handleFirstTimeLoad(
316         async (dispatch: Dispatch) => {
317             const process = await dispatch<any>(processesActions.loadProcess(uuid));
318             dispatch<any>(setProcessBreadcrumbs(uuid));
319             dispatch<any>(initProcessLogsPanel(uuid));
320             await dispatch<any>(activateSidePanelTreeItem(process.containerRequest.ownerUuid));
321         });
322
323 export const resourceIsNotLoaded = (uuid: string) =>
324     snackbarActions.OPEN_SNACKBAR({
325         message: `Resource identified by ${uuid} is not loaded.`
326     });
327
328 export const userIsNotAuthenticated = snackbarActions.OPEN_SNACKBAR({
329     message: 'User is not authenticated'
330 });
331
332 export const couldNotLoadUser = snackbarActions.OPEN_SNACKBAR({
333     message: 'Could not load user'
334 });
335
336 export const reloadProjectMatchingUuid = (matchingUuids: string[]) =>
337     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
338         const currentProjectPanelUuid = getProjectPanelCurrentUuid(getState());
339         if (currentProjectPanelUuid && matchingUuids.some(uuid => uuid === currentProjectPanelUuid)) {
340             dispatch<any>(loadProject(currentProjectPanelUuid));
341         }
342     };
343
344 export const loadSharedWithMe = handleFirstTimeLoad(async (dispatch: Dispatch) => {
345     dispatch<any>(loadSharedWithMePanel());
346     await dispatch<any>(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
347     await dispatch<any>(setSidePanelBreadcrumbs(SidePanelTreeCategory.SHARED_WITH_ME));
348 });
349
350 const finishLoadingProject = (project: GroupContentsResource | string) =>
351     async (dispatch: Dispatch<any>) => {
352         const uuid = typeof project === 'string' ? project : project.uuid;
353         dispatch(openProjectPanel(uuid));
354         dispatch(loadDetailsPanel(uuid));
355         if (typeof project !== 'string') {
356             dispatch(updateResources([project]));
357         }
358     };
359
360 const loadGroupContentsResource = async (params: {
361     uuid: string,
362     userUuid: string,
363     services: ServiceRepository
364 }) => {
365     const filters = new FilterBuilder()
366         .addEqual('uuid', params.uuid)
367         .getFilters();
368     const { items } = await params.services.groupsService.contents(params.userUuid, {
369         filters,
370         recursive: true,
371         includeTrash: true,
372     });
373     const resource = items.shift();
374     let handler: GroupContentsHandler;
375     if (resource) {
376         handler = (resource.kind === ResourceKind.COLLECTION || resource.kind === ResourceKind.PROJECT) && resource.isTrashed
377             ? groupContentsHandlers.TRASHED(resource)
378             : groupContentsHandlers.OWNED(resource);
379     } else {
380         const kind = extractUuidKind(params.uuid);
381         let resource: GroupContentsResource;
382         if (kind === ResourceKind.COLLECTION) {
383             resource = await params.services.collectionService.get(params.uuid);
384         } else if (kind === ResourceKind.PROJECT) {
385             resource = await params.services.projectService.get(params.uuid);
386         } else {
387             resource = await params.services.containerRequestService.get(params.uuid);
388         }
389         handler = groupContentsHandlers.SHARED(resource);
390     }
391     return (cases: MatchCases<typeof groupContentsHandlersRecord, GroupContentsHandler, void>) =>
392         groupContentsHandlers.match(handler, cases);
393
394 };
395
396 const groupContentsHandlersRecord = {
397     TRASHED: ofType<GroupContentsResource>(),
398     SHARED: ofType<GroupContentsResource>(),
399     OWNED: ofType<GroupContentsResource>(),
400 };
401
402 const groupContentsHandlers = unionize(groupContentsHandlersRecord);
403
404 type GroupContentsHandler = UnionOf<typeof groupContentsHandlers>;