22130: Use 'contents' to count processes
[arvados.git] / services / workbench2 / src / store / side-panel-tree / side-panel-tree-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 { treePickerActions } from "store/tree-picker/tree-picker-actions";
7 import { RootState } from 'store/store';
8 import { getUserUuid } from "common/getuser";
9 import { ServiceRepository } from 'services/services';
10 import { FilterBuilder } from 'services/api/filter-builder';
11 import { resourcesActions } from 'store/resources/resources-actions';
12 import { getTreePicker, TreePicker } from 'store/tree-picker/tree-picker';
13 import { getNodeAncestors, getNodeAncestorsIds, getNode, TreeNode, initTreeNode, TreeNodeStatus } from 'models/tree';
14 import { ProjectResource } from 'models/project';
15 import { OrderBuilder } from 'services/api/order-builder';
16 import { ResourceKind, extractUuidObjectType, ResourceObjectType } from 'models/resource';
17 import { CategoriesListReducer } from 'common/plugintypes';
18 import { pluginConfig } from 'plugins';
19 import { LinkClass, LinkResource } from 'models/link';
20 import { verifyAndUpdateLinks } from 'common/link-update-name';
21 import { ProcessIcon, ProjectIcon, FilterGroupIcon, FavoriteIcon, ProjectsIcon, ShareMeIcon, TrashIcon, PublicFavoriteIcon, GroupsIcon, TerminalIcon, ResourceIcon } from 'components/icon/icon';
22
23 export enum SidePanelTreeCategory {
24     PROJECTS = 'Home Projects',
25     FAVORITES = 'My Favorites',
26     PUBLIC_FAVORITES = 'Public Favorites',
27     SHARED_WITH_ME = 'Shared with me',
28     ALL_PROCESSES = 'All Processes',
29     INSTANCE_TYPES = 'Instance Types',
30     SHELL_ACCESS = 'Shell Access',
31     GROUPS = 'Groups',
32     TRASH = 'Trash',
33 }
34
35 export const SIDE_PANEL_TREE = 'sidePanelTree';
36 const SIDEPANEL_TREE_NODE_LIMIT = 50
37
38 export const getSidePanelTree = (treePicker: TreePicker) =>
39     getTreePicker<ProjectResource | string>(SIDE_PANEL_TREE)(treePicker);
40
41 export const getSidePanelTreeBranch = (uuid: string) => (treePicker: TreePicker): Array<TreeNode<ProjectResource | string>> => {
42     const tree = getSidePanelTree(treePicker);
43     if (tree) {
44         const ancestors = getNodeAncestors(uuid)(tree);
45         const node = getNode(uuid)(tree);
46         if (node) {
47             return [...ancestors, node];
48         }
49     }
50     return [];
51 };
52
53 let SIDE_PANEL_CATEGORIES: string[] = [
54     SidePanelTreeCategory.PROJECTS,
55     SidePanelTreeCategory.FAVORITES,
56     SidePanelTreeCategory.PUBLIC_FAVORITES,
57     SidePanelTreeCategory.SHARED_WITH_ME,
58     SidePanelTreeCategory.ALL_PROCESSES,
59     SidePanelTreeCategory.INSTANCE_TYPES,
60     SidePanelTreeCategory.SHELL_ACCESS,
61     SidePanelTreeCategory.GROUPS,
62     SidePanelTreeCategory.TRASH
63 ];
64
65 const reduceCatsFn: (a: string[],
66     b: CategoriesListReducer) => string[] = (a, b) => b(a);
67
68 SIDE_PANEL_CATEGORIES = pluginConfig.sidePanelCategories.reduce(reduceCatsFn, SIDE_PANEL_CATEGORIES);
69
70 export const isSidePanelTreeCategory = (id: string) => SIDE_PANEL_CATEGORIES.some(category => category === id);
71
72
73 export const initSidePanelTree = () =>
74     (dispatch: Dispatch, getState: () => RootState, { authService }: ServiceRepository) => {
75         const rootProjectUuid = getUserUuid(getState());
76         if (!rootProjectUuid) { return; }
77         const nodes = SIDE_PANEL_CATEGORIES.map(id => {
78             if (id === SidePanelTreeCategory.PROJECTS) {
79                 return initTreeNode({ id: rootProjectUuid, value: SidePanelTreeCategory.PROJECTS });
80             } else {
81                 return initTreeNode({ id, value: id });
82             }
83         });
84         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
85             id: '',
86             pickerId: SIDE_PANEL_TREE,
87             nodes
88         }));
89         SIDE_PANEL_CATEGORIES.forEach(category => {
90                 if (category !== SidePanelTreeCategory.PROJECTS && category !== SidePanelTreeCategory.FAVORITES && category !== SidePanelTreeCategory.PUBLIC_FAVORITES ) {
91                 dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
92                     id: category,
93                     pickerId: SIDE_PANEL_TREE,
94                     nodes: []
95                 }));
96             }
97         });
98     };
99
100 export const loadSidePanelTreeProjects = (projectUuid: string) =>
101     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
102         const treePicker = getTreePicker(SIDE_PANEL_TREE)(getState().treePicker);
103         const node = treePicker ? getNode(projectUuid)(treePicker) : undefined;
104         if (projectUuid === SidePanelTreeCategory.PUBLIC_FAVORITES) {
105             const unverifiedPubFaves = await dispatch<any>(loadPublicFavoritesTree());
106             verifyAndUpdateLinkNames(projectUuid, unverifiedPubFaves, dispatch, getState, services);
107         } else if (projectUuid === SidePanelTreeCategory.FAVORITES) {
108             const unverifiedFaves = await dispatch<any>(loadFavoritesTree());
109             await setFaves(unverifiedFaves, dispatch, getState, services);
110             verifyAndUpdateLinkNames(projectUuid, unverifiedFaves, dispatch, getState, services);
111         } else if (node || projectUuid !== '') {
112             await dispatch<any>(loadProject(projectUuid));
113         }
114     };
115
116 const loadProject = (projectUuid: string) =>
117     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
118
119         const objectType = extractUuidObjectType(projectUuid);
120         if (objectType !== ResourceObjectType.USER && objectType !== ResourceObjectType.GROUP) {
121             return;
122         }
123
124         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: projectUuid, pickerId: SIDE_PANEL_TREE }));
125         const params = {
126             filters: new FilterBuilder()
127                 .addEqual('owner_uuid', projectUuid)
128                 .getFilters(),
129             order: new OrderBuilder<ProjectResource>()
130                 .addDesc('createdAt')
131                 .getOrder(),
132             limit: SIDEPANEL_TREE_NODE_LIMIT,
133         };
134
135         const { items } = await services.projectService.list(params);
136
137         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
138             id: projectUuid,
139             pickerId: SIDE_PANEL_TREE,
140             nodes: items.map(item => initTreeNode({ id: item.uuid, value: item })),
141         }));
142         dispatch(resourcesActions.SET_RESOURCES(items));
143     };
144
145 export const loadFavoritesTree = () => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
146     dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: SidePanelTreeCategory.FAVORITES, pickerId: SIDE_PANEL_TREE }));
147
148     const params = {
149         filters: new FilterBuilder()
150             .addEqual('link_class', LinkClass.STAR)
151             .addEqual('tail_uuid', getUserUuid(getState()))
152             .addEqual('tail_kind', ResourceKind.USER)
153             .getFilters(),
154         order: new OrderBuilder<ProjectResource>().addDesc('createdAt').getOrder(),
155         limit: SIDEPANEL_TREE_NODE_LIMIT,
156     };
157
158     const { items } = await services.linkService.list(params);
159
160     dispatch(
161         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
162             id: SidePanelTreeCategory.FAVORITES,
163             pickerId: SIDE_PANEL_TREE,
164             nodes: items.map(item => initTreeNode({ id: item.headUuid, value: item.name })),
165         })
166     );
167
168     return items;
169 };
170
171 const setFaves = async(links: LinkResource[], dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
172
173     const uuids = links.map(it => it.headUuid);
174     const groupItems: Promise<any> = services.groupsService.list({
175         filters: new FilterBuilder()
176             .addIn("uuid", uuids)
177             .getFilters()
178     });
179     const collectionItems: Promise<any> = services.collectionService.list({
180         filters: new FilterBuilder()
181             .addIn("uuid", uuids)
182             .getFilters()
183     });
184     const processItems: Promise<any> = services.containerRequestService.list({
185         filters: new FilterBuilder()
186             .addIn("uuid", uuids)
187             .getFilters()
188     });
189
190     const resolvedItems = await Promise.all([groupItems, collectionItems, processItems]);
191
192     const responseItems = resolvedItems.reduce((acc, response) => acc.concat(response.items), []);
193
194     //setting resources here so they won't be re-fetched in validation step
195     dispatch(resourcesActions.SET_RESOURCES(responseItems));
196 };
197
198 const verifyAndUpdateLinkNames = async (category: SidePanelTreeCategory, links: LinkResource[], dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
199     const verfifiedLinks = await verifyAndUpdateLinks(links, dispatch, getState, services);
200
201     dispatch(
202         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
203             id: category,
204             pickerId: SIDE_PANEL_TREE,
205             nodes: verfifiedLinks.map(item => initTreeNode({ id: item.headUuid, value: item })),
206         })
207     );
208 };
209
210 export const loadPublicFavoritesTree = () => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
211     dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: SidePanelTreeCategory.PUBLIC_FAVORITES, pickerId: SIDE_PANEL_TREE }));
212
213     const uuidPrefix = getState().auth.config.uuidPrefix;
214     const publicProjectUuid = `${uuidPrefix}-j7d0g-publicfavorites`;
215     const typeFilters = [ResourceKind.COLLECTION, ResourceKind.CONTAINER_REQUEST, ResourceKind.GROUP, ResourceKind.WORKFLOW];
216
217     const params = {
218         filters: new FilterBuilder()
219             .addEqual('link_class', LinkClass.STAR)
220             .addEqual('owner_uuid', publicProjectUuid)
221             .addIsA('head_uuid', typeFilters)
222             .getFilters(),
223         order: new OrderBuilder<ProjectResource>().addDesc('createdAt').getOrder(),
224         limit: SIDEPANEL_TREE_NODE_LIMIT,
225     };
226
227     const { items } = await services.linkService.list(params);
228
229     const uuids = items.map(it => it.headUuid);
230     const groupItems: Promise<any> = services.groupsService.list({
231         filters: new FilterBuilder()
232             .addIn("uuid", uuids)
233             .addIsA("uuid", typeFilters)
234             .getFilters()
235     });
236     const collectionItems: Promise<any> = services.collectionService.list({
237         filters: new FilterBuilder()
238             .addIn("uuid", uuids)
239             .addIsA("uuid", typeFilters)
240             .getFilters()
241     });
242     const processItems: Promise<any> = services.containerRequestService.list({
243         filters: new FilterBuilder()
244             .addIn("uuid", uuids)
245             .addIsA("uuid", typeFilters)
246             .getFilters()
247     });
248
249     const resolvedItems = await Promise.all([groupItems, collectionItems, processItems]);
250
251     const responseItems = resolvedItems.reduce((acc, response) => acc.concat(response.items), []);
252
253     const filteredItems = items.filter(item => responseItems.some(responseItem => responseItem.uuid === item.headUuid));
254
255     dispatch(
256         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
257             id: SidePanelTreeCategory.PUBLIC_FAVORITES,
258             pickerId: SIDE_PANEL_TREE,
259             nodes: filteredItems.map(item => initTreeNode({ id: item.headUuid, value: item })),
260         })
261     );
262
263     //setting resources here so they won't be re-fetched in validation step
264     dispatch(resourcesActions.SET_RESOURCES(responseItems));
265
266     return filteredItems;
267 };
268
269 export const activateSidePanelTreeItem = (id: string) =>
270     async (dispatch: Dispatch, getState: () => RootState) => {
271         const node = getSidePanelTreeNode(id)(getState().treePicker);
272         if (node && !node.active) {
273         dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id, pickerId: SIDE_PANEL_TREE }));
274     }
275     if (!isSidePanelTreeCategory(id)) {
276             await dispatch<any>(activateSidePanelTreeProject(id));
277         }
278     };
279
280 export const activateSidePanelTreeProject = (id: string) =>
281     async (dispatch: Dispatch, getState: () => RootState) => {
282         const { treePicker } = getState();
283         const node = getSidePanelTreeNode(id)(treePicker);
284         if (node && node.status !== TreeNodeStatus.LOADED) {
285             await dispatch<any>(loadSidePanelTreeProjects(id));
286         } else if (node === undefined) {
287             await dispatch<any>(activateSidePanelTreeBranch(id));
288         }
289         dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
290             ids: getSidePanelTreeNodeAncestorsIds(id)(treePicker),
291             pickerId: SIDE_PANEL_TREE
292         }));
293         dispatch<any>(expandSidePanelTreeItem(id));
294     };
295
296 export const activateSidePanelTreeBranch = (id: string) =>
297     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
298         const userUuid = getUserUuid(getState());
299         if (!userUuid) { return; }
300         const ancestors = await services.ancestorsService.ancestors(id, userUuid);
301         for (const ancestor of ancestors) {
302             await dispatch<any>(loadSidePanelTreeProjects(ancestor.uuid));
303         }
304         dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
305             ids: ancestors.map(ancestor => ancestor.uuid),
306             pickerId: SIDE_PANEL_TREE
307         }));
308         dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id, pickerId: SIDE_PANEL_TREE }));
309     };
310
311 export const toggleSidePanelTreeItemCollapse = (id: string) =>
312     async (dispatch: Dispatch, getState: () => RootState) => {
313         const node = getSidePanelTreeNode(id)(getState().treePicker);
314         if (node && node.status === TreeNodeStatus.INITIAL) {
315             await dispatch<any>(loadSidePanelTreeProjects(node.id));
316         }
317             dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId: SIDE_PANEL_TREE }));
318     };
319
320 export const expandSidePanelTreeItem = (id: string) =>
321     async (dispatch: Dispatch, getState: () => RootState) => {
322         const node = getSidePanelTreeNode(id)(getState().treePicker);
323         if (node && !node.expanded) {
324             dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId: SIDE_PANEL_TREE }));
325         }
326     };
327
328 export const getSidePanelTreeNode = (id: string) => (treePicker: TreePicker) => {
329     const sidePanelTree = getTreePicker(SIDE_PANEL_TREE)(treePicker);
330     return sidePanelTree
331         ? getNode(id)(sidePanelTree)
332         : undefined;
333 };
334
335 export const getSidePanelTreeNodeAncestorsIds = (id: string) => (treePicker: TreePicker) => {
336     const sidePanelTree = getTreePicker(SIDE_PANEL_TREE)(treePicker);
337     return sidePanelTree
338         ? getNodeAncestorsIds(id)(sidePanelTree)
339         : [];
340 };
341
342 export const getSidePanelIcon = (category: string) => {
343     switch (category) {
344         case SidePanelTreeCategory.FAVORITES:
345             return FavoriteIcon;
346         case SidePanelTreeCategory.PROJECTS:
347             return ProjectsIcon;
348         case SidePanelTreeCategory.SHARED_WITH_ME:
349             return ShareMeIcon;
350         case SidePanelTreeCategory.TRASH:
351             return TrashIcon;
352         case SidePanelTreeCategory.PUBLIC_FAVORITES:
353             return PublicFavoriteIcon;
354         case SidePanelTreeCategory.ALL_PROCESSES:
355             return ProcessIcon;
356         case SidePanelTreeCategory.INSTANCE_TYPES:
357             return ResourceIcon;
358         case SidePanelTreeCategory.GROUPS:
359             return GroupsIcon;
360         case SidePanelTreeCategory.SHELL_ACCESS:
361             return TerminalIcon
362         default:
363             return ProjectIcon;
364     }
365 };