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