15840: Project panel uses collection attributes for file count and size
[arvados-workbench2.git] / src / store / tree-picker / tree-picker-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { unionize, ofType, UnionOf } from "~/common/unionize";
6 import { TreeNode, initTreeNode, getNodeDescendants, TreeNodeStatus, getNode, TreePickerId, Tree } from '~/models/tree';
7 import { createCollectionFilesTree } from "~/models/collection-file";
8 import { Dispatch } from 'redux';
9 import { RootState } from '~/store/store';
10 import { ServiceRepository } from '~/services/services';
11 import { FilterBuilder } from '~/services/api/filter-builder';
12 import { pipe, values } from 'lodash/fp';
13 import { ResourceKind } from '~/models/resource';
14 import { GroupContentsResource } from '~/services/groups-service/groups-service';
15 import { getTreePicker, TreePicker } from './tree-picker';
16 import { ProjectsTreePickerItem } from '~/views-components/projects-tree-picker/generic-projects-tree-picker';
17 import { OrderBuilder } from '~/services/api/order-builder';
18 import { ProjectResource } from '~/models/project';
19 import { mapTree } from '../../models/tree';
20 import { LinkResource, LinkClass } from "~/models/link";
21 import { mapTreeValues } from "~/models/tree";
22 import { sortFilesTree } from "~/services/collection-service/collection-service-files-response";
23
24 export const treePickerActions = unionize({
25     LOAD_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string }>(),
26     LOAD_TREE_PICKER_NODE_SUCCESS: ofType<{ id: string, nodes: Array<TreeNode<any>>, pickerId: string }>(),
27     APPEND_TREE_PICKER_NODE_SUBTREE: ofType<{ id: string, subtree: Tree<any>, pickerId: string }>(),
28     TOGGLE_TREE_PICKER_NODE_COLLAPSE: ofType<{ id: string, pickerId: string }>(),
29     ACTIVATE_TREE_PICKER_NODE: ofType<{ id: string, pickerId: string, relatedTreePickers?: string[] }>(),
30     DEACTIVATE_TREE_PICKER_NODE: ofType<{ pickerId: string }>(),
31     TOGGLE_TREE_PICKER_NODE_SELECTION: ofType<{ id: string, pickerId: string }>(),
32     SELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
33     DESELECT_TREE_PICKER_NODE: ofType<{ id: string | string[], pickerId: string }>(),
34     EXPAND_TREE_PICKER_NODES: ofType<{ ids: string[], pickerId: string }>(),
35     RESET_TREE_PICKER: ofType<{ pickerId: string }>()
36 });
37
38 export type TreePickerAction = UnionOf<typeof treePickerActions>;
39
40 export const getProjectsTreePickerIds = (pickerId: string) => ({
41     home: `${pickerId}_home`,
42     shared: `${pickerId}_shared`,
43     favorites: `${pickerId}_favorites`,
44     publicFavorites: `${pickerId}_publicFavorites`
45 });
46
47 export const getAllNodes = <Value>(pickerId: string, filter = (node: TreeNode<Value>) => true) => (state: TreePicker) =>
48     pipe(
49         () => values(getProjectsTreePickerIds(pickerId)),
50
51         ids => ids
52             .map(id => getTreePicker<Value>(id)(state)),
53
54         trees => trees
55             .map(getNodeDescendants(''))
56             .reduce((allNodes, nodes) => allNodes.concat(nodes), []),
57
58         allNodes => allNodes
59             .reduce((map, node) =>
60                 filter(node)
61                     ? map.set(node.id, node)
62                     : map, new Map<string, TreeNode<Value>>())
63             .values(),
64
65         uniqueNodes => Array.from(uniqueNodes),
66     )();
67 export const getSelectedNodes = <Value>(pickerId: string) => (state: TreePicker) =>
68     getAllNodes<Value>(pickerId, node => node.selected)(state);
69
70 export const initProjectsTreePicker = (pickerId: string) =>
71     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
72         const { home, shared, favorites, publicFavorites } = getProjectsTreePickerIds(pickerId);
73         dispatch<any>(initUserProject(home));
74         dispatch<any>(initSharedProject(shared));
75         dispatch<any>(initFavoritesProject(favorites));
76         dispatch<any>(initPublicFavoritesProject(publicFavorites));
77     };
78
79 interface ReceiveTreePickerDataParams<T> {
80     data: T[];
81     extractNodeData: (value: T) => { id: string, value: T, status?: TreeNodeStatus };
82     id: string;
83     pickerId: string;
84 }
85
86 export const receiveTreePickerData = <T>(params: ReceiveTreePickerDataParams<T>) =>
87     (dispatch: Dispatch) => {
88         const { data, extractNodeData, id, pickerId, } = params;
89         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
90             id,
91             nodes: data.map(item => initTreeNode(extractNodeData(item))),
92             pickerId,
93         }));
94         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
95     };
96
97 interface LoadProjectParams {
98     id: string;
99     pickerId: string;
100     includeCollections?: boolean;
101     includeFiles?: boolean;
102     loadShared?: boolean;
103 }
104 export const loadProject = (params: LoadProjectParams) =>
105     async (dispatch: Dispatch, _: () => RootState, services: ServiceRepository) => {
106         const { id, pickerId, includeCollections = false, includeFiles = false, loadShared = false } = params;
107
108         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
109
110         const filters = pipe(
111             (fb: FilterBuilder) => includeCollections
112                 ? fb.addIsA('uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
113                 : fb.addIsA('uuid', [ResourceKind.PROJECT]),
114             fb => fb.getFilters(),
115         )(new FilterBuilder());
116
117         const { items } = await services.groupsService.contents(loadShared ? '' : id, { filters, excludeHomeProject: loadShared || undefined });
118
119         dispatch<any>(receiveTreePickerData<GroupContentsResource>({
120             id,
121             pickerId,
122             data: items,
123             extractNodeData: item => ({
124                 id: item.uuid,
125                 value: item,
126                 status: item.kind === ResourceKind.PROJECT
127                     ? TreeNodeStatus.INITIAL
128                     : includeFiles
129                         ? TreeNodeStatus.INITIAL
130                         : TreeNodeStatus.LOADED
131             }),
132         }));
133     };
134
135 export const loadCollection = (id: string, pickerId: string) =>
136     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
137         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
138
139         const picker = getTreePicker<ProjectsTreePickerItem>(pickerId)(getState().treePicker);
140         if (picker) {
141
142             const node = getNode(id)(picker);
143             if (node && 'kind' in node.value && node.value.kind === ResourceKind.COLLECTION) {
144
145                 const files = await services.collectionService.files(node.value.portableDataHash);
146                 const tree = createCollectionFilesTree(files);
147                 const sorted = sortFilesTree(tree);
148                 const filesTree = mapTreeValues(services.collectionService.extendFileURL)(sorted);
149
150                 dispatch(
151                     treePickerActions.APPEND_TREE_PICKER_NODE_SUBTREE({
152                         id,
153                         pickerId,
154                         subtree: mapTree(node => ({ ...node, status: TreeNodeStatus.LOADED }))(filesTree)
155                     }));
156
157                 dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
158             }
159         }
160     };
161
162
163 export const initUserProject = (pickerId: string) =>
164     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
165         const uuid = services.authService.getUuid();
166         if (uuid) {
167             dispatch(receiveTreePickerData({
168                 id: '',
169                 pickerId,
170                 data: [{ uuid, name: 'Projects' }],
171                 extractNodeData: value => ({
172                     id: value.uuid,
173                     status: TreeNodeStatus.INITIAL,
174                     value,
175                 }),
176             }));
177         }
178     };
179 export const loadUserProject = (pickerId: string, includeCollections = false, includeFiles = false) =>
180     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
181         const uuid = services.authService.getUuid();
182         if (uuid) {
183             dispatch(loadProject({ id: uuid, pickerId, includeCollections, includeFiles }));
184         }
185     };
186
187 export const SHARED_PROJECT_ID = 'Shared with me';
188 export const initSharedProject = (pickerId: string) =>
189     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
190         dispatch(receiveTreePickerData({
191             id: '',
192             pickerId,
193             data: [{ uuid: SHARED_PROJECT_ID, name: SHARED_PROJECT_ID }],
194             extractNodeData: value => ({
195                 id: value.uuid,
196                 status: TreeNodeStatus.INITIAL,
197                 value,
198             }),
199         }));
200     };
201
202 export const FAVORITES_PROJECT_ID = 'Favorites';
203 export const initFavoritesProject = (pickerId: string) =>
204     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
205         dispatch(receiveTreePickerData({
206             id: '',
207             pickerId,
208             data: [{ uuid: FAVORITES_PROJECT_ID, name: FAVORITES_PROJECT_ID }],
209             extractNodeData: value => ({
210                 id: value.uuid,
211                 status: TreeNodeStatus.INITIAL,
212                 value,
213             }),
214         }));
215     };
216
217 export const PUBLIC_FAVORITES_PROJECT_ID = 'Public Favorites';
218 export const initPublicFavoritesProject = (pickerId: string) =>
219     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
220         dispatch(receiveTreePickerData({
221             id: '',
222             pickerId,
223             data: [{ uuid: PUBLIC_FAVORITES_PROJECT_ID, name: PUBLIC_FAVORITES_PROJECT_ID }],
224             extractNodeData: value => ({
225                 id: value.uuid,
226                 status: TreeNodeStatus.INITIAL,
227                 value,
228             }),
229         }));
230     };
231
232 interface LoadFavoritesProjectParams {
233     pickerId: string;
234     includeCollections?: boolean;
235     includeFiles?: boolean;
236 }
237
238 export const loadFavoritesProject = (params: LoadFavoritesProjectParams) =>
239     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
240         const { pickerId, includeCollections = false, includeFiles = false } = params;
241         const uuid = services.authService.getUuid();
242         if (uuid) {
243
244             const filters = pipe(
245                 (fb: FilterBuilder) => includeCollections
246                     ? fb.addIsA('headUuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
247                     : fb.addIsA('headUuid', [ResourceKind.PROJECT]),
248                 fb => fb.getFilters(),
249             )(new FilterBuilder());
250
251             const { items } = await services.favoriteService.list(uuid, { filters });
252
253             dispatch<any>(receiveTreePickerData<GroupContentsResource>({
254                 id: 'Favorites',
255                 pickerId,
256                 data: items,
257                 extractNodeData: item => ({
258                     id: item.uuid,
259                     value: item,
260                     status: item.kind === ResourceKind.PROJECT
261                         ? TreeNodeStatus.INITIAL
262                         : includeFiles
263                             ? TreeNodeStatus.INITIAL
264                             : TreeNodeStatus.LOADED
265                 }),
266             }));
267         }
268     };
269
270 export const loadPublicFavoritesProject = (params: LoadFavoritesProjectParams) =>
271     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
272         const { pickerId, includeCollections = false, includeFiles = false } = params;
273         const uuidPrefix = getState().config.uuidPrefix;
274         const uuid = `${uuidPrefix}-j7d0g-fffffffffffffff`;
275         if (uuid) {
276
277             const filters = pipe(
278                 (fb: FilterBuilder) => includeCollections
279                     ? fb.addIsA('headUuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
280                     : fb.addIsA('headUuid', [ResourceKind.PROJECT]),
281                 fb => fb
282                     .addEqual('linkClass', LinkClass.STAR)
283                     .addEqual('ownerUuid', uuid)
284                     .addLike('name', '')
285                     .getFilters(),
286             )(new FilterBuilder());
287
288             const { items } = await services.linkService.list({ filters });
289
290             dispatch<any>(receiveTreePickerData<LinkResource>({
291                 id: 'Public Favorites',
292                 pickerId,
293                 data: items,
294                 extractNodeData: item => ({
295                     id: item.headUuid,
296                     value: item,
297                     status: item.headKind === ResourceKind.PROJECT
298                         ? TreeNodeStatus.INITIAL
299                         : includeFiles
300                             ? TreeNodeStatus.INITIAL
301                             : TreeNodeStatus.LOADED
302                 }),
303             }));
304         }
305     };
306
307 export const receiveTreePickerProjectsData = (id: string, projects: ProjectResource[], pickerId: string) =>
308     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
309         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
310             id,
311             nodes: projects.map(project => initTreeNode({ id: project.uuid, value: project })),
312             pickerId,
313         }));
314
315         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
316     };
317
318 export const loadProjectTreePickerProjects = (id: string) =>
319     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
320         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PROJECTS }));
321
322         const ownerUuid = id.length === 0 ? services.authService.getUuid() || '' : id;
323         const { items } = await services.projectService.list(buildParams(ownerUuid));
324
325         dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PROJECTS));
326     };
327
328 export const loadFavoriteTreePickerProjects = (id: string) =>
329     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
330         const parentId = services.authService.getUuid() || '';
331
332         if (id === '') {
333             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.FAVORITES }));
334             const { items } = await services.favoriteService.list(parentId);
335             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.FAVORITES));
336         } else {
337             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.FAVORITES }));
338             const { items } = await services.projectService.list(buildParams(id));
339             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.FAVORITES));
340         }
341
342     };
343
344 export const loadPublicFavoriteTreePickerProjects = (id: string) =>
345     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
346         const parentId = services.authService.getUuid() || '';
347
348         if (id === '') {
349             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.PUBLIC_FAVORITES }));
350             const { items } = await services.favoriteService.list(parentId);
351             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.PUBLIC_FAVORITES));
352         } else {
353             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PUBLIC_FAVORITES }));
354             const { items } = await services.projectService.list(buildParams(id));
355             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PUBLIC_FAVORITES));
356         }
357
358     };
359
360 const buildParams = (ownerUuid: string) => {
361     return {
362         filters: new FilterBuilder()
363             .addEqual('ownerUuid', ownerUuid)
364             .getFilters(),
365         order: new OrderBuilder<ProjectResource>()
366             .addAsc('name')
367             .getOrder()
368     };
369 };