22141: Refactoring to reduce circular import dependencies
[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 } 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         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: projectUuid, pickerId: SIDE_PANEL_TREE }));
119         const params = {
120             filters: new FilterBuilder()
121                 .addEqual('owner_uuid', projectUuid)
122                 .getFilters(),
123             order: new OrderBuilder<ProjectResource>()
124                 .addDesc('createdAt')
125                 .getOrder(),
126             limit: SIDEPANEL_TREE_NODE_LIMIT,
127         };
128
129         const { items } = await services.projectService.list(params);
130
131         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
132             id: projectUuid,
133             pickerId: SIDE_PANEL_TREE,
134             nodes: items.map(item => initTreeNode({ id: item.uuid, value: item })),
135         }));
136         dispatch(resourcesActions.SET_RESOURCES(items));
137     };
138
139 export const loadFavoritesTree = () => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
140     dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: SidePanelTreeCategory.FAVORITES, pickerId: SIDE_PANEL_TREE }));
141
142     const params = {
143         filters: new FilterBuilder()
144             .addEqual('link_class', LinkClass.STAR)
145             .addEqual('tail_uuid', getUserUuid(getState()))
146             .addEqual('tail_kind', ResourceKind.USER)
147             .getFilters(),
148         order: new OrderBuilder<ProjectResource>().addDesc('createdAt').getOrder(),
149         limit: SIDEPANEL_TREE_NODE_LIMIT,
150     };
151
152     const { items } = await services.linkService.list(params);
153
154     dispatch(
155         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
156             id: SidePanelTreeCategory.FAVORITES,
157             pickerId: SIDE_PANEL_TREE,
158             nodes: items.map(item => initTreeNode({ id: item.headUuid, value: item.name })),
159         })
160     );
161
162     return items;
163 };
164
165 const setFaves = async(links: LinkResource[], dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
166
167     const uuids = links.map(it => it.headUuid);
168     const groupItems: Promise<any> = services.groupsService.list({
169         filters: new FilterBuilder()
170             .addIn("uuid", uuids)
171             .getFilters()
172     });
173     const collectionItems: Promise<any> = services.collectionService.list({
174         filters: new FilterBuilder()
175             .addIn("uuid", uuids)
176             .getFilters()
177     });
178     const processItems: Promise<any> = services.containerRequestService.list({
179         filters: new FilterBuilder()
180             .addIn("uuid", uuids)
181             .getFilters()
182     });
183
184     const resolvedItems = await Promise.all([groupItems, collectionItems, processItems]);
185
186     const responseItems = resolvedItems.reduce((acc, response) => acc.concat(response.items), []);
187
188     //setting resources here so they won't be re-fetched in validation step
189     dispatch(resourcesActions.SET_RESOURCES(responseItems));
190 };
191
192 const verifyAndUpdateLinkNames = async (category: SidePanelTreeCategory, links: LinkResource[], dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
193     const verfifiedLinks = await verifyAndUpdateLinks(links, dispatch, getState, services);
194
195     dispatch(
196         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
197             id: category,
198             pickerId: SIDE_PANEL_TREE,
199             nodes: verfifiedLinks.map(item => initTreeNode({ id: item.headUuid, value: item })),
200         })
201     );
202 };
203
204 export const loadPublicFavoritesTree = () => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
205     dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: SidePanelTreeCategory.PUBLIC_FAVORITES, pickerId: SIDE_PANEL_TREE }));
206
207     const uuidPrefix = getState().auth.config.uuidPrefix;
208     const publicProjectUuid = `${uuidPrefix}-j7d0g-publicfavorites`;
209     const typeFilters = [ResourceKind.COLLECTION, ResourceKind.CONTAINER_REQUEST, ResourceKind.GROUP, ResourceKind.WORKFLOW];
210
211     const params = {
212         filters: new FilterBuilder()
213             .addEqual('link_class', LinkClass.STAR)
214             .addEqual('owner_uuid', publicProjectUuid)
215             .addIsA('head_uuid', typeFilters)
216             .getFilters(),
217         order: new OrderBuilder<ProjectResource>().addDesc('createdAt').getOrder(),
218         limit: SIDEPANEL_TREE_NODE_LIMIT,
219     };
220
221     const { items } = await services.linkService.list(params);
222
223     const uuids = items.map(it => it.headUuid);
224     const groupItems: Promise<any> = services.groupsService.list({
225         filters: new FilterBuilder()
226             .addIn("uuid", uuids)
227             .addIsA("uuid", typeFilters)
228             .getFilters()
229     });
230     const collectionItems: Promise<any> = services.collectionService.list({
231         filters: new FilterBuilder()
232             .addIn("uuid", uuids)
233             .addIsA("uuid", typeFilters)
234             .getFilters()
235     });
236     const processItems: Promise<any> = services.containerRequestService.list({
237         filters: new FilterBuilder()
238             .addIn("uuid", uuids)
239             .addIsA("uuid", typeFilters)
240             .getFilters()
241     });
242
243     const resolvedItems = await Promise.all([groupItems, collectionItems, processItems]);
244
245     const responseItems = resolvedItems.reduce((acc, response) => acc.concat(response.items), []);
246
247     const filteredItems = items.filter(item => responseItems.some(responseItem => responseItem.uuid === item.headUuid));
248
249     dispatch(
250         treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
251             id: SidePanelTreeCategory.PUBLIC_FAVORITES,
252             pickerId: SIDE_PANEL_TREE,
253             nodes: filteredItems.map(item => initTreeNode({ id: item.headUuid, value: item })),
254         })
255     );
256
257     //setting resources here so they won't be re-fetched in validation step
258     dispatch(resourcesActions.SET_RESOURCES(responseItems));
259
260     return filteredItems;
261 };
262
263 export const activateSidePanelTreeItem = (id: string) =>
264     async (dispatch: Dispatch, getState: () => RootState) => {
265         const node = getSidePanelTreeNode(id)(getState().treePicker);
266         if (node && !node.active) {
267         dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id, pickerId: SIDE_PANEL_TREE }));
268     }
269     if (!isSidePanelTreeCategory(id)) {
270             await dispatch<any>(activateSidePanelTreeProject(id));
271         }
272     };
273
274 export const activateSidePanelTreeProject = (id: string) =>
275     async (dispatch: Dispatch, getState: () => RootState) => {
276         const { treePicker } = getState();
277         const node = getSidePanelTreeNode(id)(treePicker);
278         if (node && node.status !== TreeNodeStatus.LOADED) {
279             await dispatch<any>(loadSidePanelTreeProjects(id));
280         } else if (node === undefined) {
281             await dispatch<any>(activateSidePanelTreeBranch(id));
282         }
283         dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
284             ids: getSidePanelTreeNodeAncestorsIds(id)(treePicker),
285             pickerId: SIDE_PANEL_TREE
286         }));
287         dispatch<any>(expandSidePanelTreeItem(id));
288     };
289
290 export const activateSidePanelTreeBranch = (id: string) =>
291     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
292         const userUuid = getUserUuid(getState());
293         if (!userUuid) { return; }
294         const ancestors = await services.ancestorsService.ancestors(id, userUuid);
295         for (const ancestor of ancestors) {
296             await dispatch<any>(loadSidePanelTreeProjects(ancestor.uuid));
297         }
298         dispatch(treePickerActions.EXPAND_TREE_PICKER_NODES({
299             ids: ancestors.map(ancestor => ancestor.uuid),
300             pickerId: SIDE_PANEL_TREE
301         }));
302         dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ id, pickerId: SIDE_PANEL_TREE }));
303     };
304
305 export const toggleSidePanelTreeItemCollapse = (id: string) =>
306     async (dispatch: Dispatch, getState: () => RootState) => {
307         const node = getSidePanelTreeNode(id)(getState().treePicker);
308         if (node && node.status === TreeNodeStatus.INITIAL) {
309             await dispatch<any>(loadSidePanelTreeProjects(node.id));
310         }
311             dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId: SIDE_PANEL_TREE }));
312     };
313
314 export const expandSidePanelTreeItem = (id: string) =>
315     async (dispatch: Dispatch, getState: () => RootState) => {
316         const node = getSidePanelTreeNode(id)(getState().treePicker);
317         if (node && !node.expanded) {
318             dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId: SIDE_PANEL_TREE }));
319         }
320     };
321
322 export const getSidePanelTreeNode = (id: string) => (treePicker: TreePicker) => {
323     const sidePanelTree = getTreePicker(SIDE_PANEL_TREE)(treePicker);
324     return sidePanelTree
325         ? getNode(id)(sidePanelTree)
326         : undefined;
327 };
328
329 export const getSidePanelTreeNodeAncestorsIds = (id: string) => (treePicker: TreePicker) => {
330     const sidePanelTree = getTreePicker(SIDE_PANEL_TREE)(treePicker);
331     return sidePanelTree
332         ? getNodeAncestorsIds(id)(sidePanelTree)
333         : [];
334 };
335
336 export const getSidePanelIcon = (category: string) => {
337     switch (category) {
338         case SidePanelTreeCategory.FAVORITES:
339             return FavoriteIcon;
340         case SidePanelTreeCategory.PROJECTS:
341             return ProjectsIcon;
342         case SidePanelTreeCategory.SHARED_WITH_ME:
343             return ShareMeIcon;
344         case SidePanelTreeCategory.TRASH:
345             return TrashIcon;
346         case SidePanelTreeCategory.PUBLIC_FAVORITES:
347             return PublicFavoriteIcon;
348         case SidePanelTreeCategory.ALL_PROCESSES:
349             return ProcessIcon;
350         case SidePanelTreeCategory.INSTANCE_TYPES:
351             return ResourceIcon;
352         case SidePanelTreeCategory.GROUPS:
353             return GroupsIcon;
354         case SidePanelTreeCategory.SHELL_ACCESS:
355             return TerminalIcon
356         default:
357             return ProjectIcon;
358     }
359 };