Merge branch '18692-frozen-projects-workbench-support' into main
[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         dispatch<any>(receiveTreePickerData<GroupContentsResource>({
123             id,
124             pickerId,
125             data: items.filter((item) => {
126                     if (!includeFilterGroups && (item as GroupResource).groupClass && (item as GroupResource).groupClass === GroupClass.FILTER) {
127                         return false;
128                     }
129
130                     if (options && options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as ProjectResource).frozenByUuid) {
131                         return false;
132                     }
133
134                     return true;
135                 }),
136             extractNodeData: item => ({
137                 id: item.uuid,
138                 value: item,
139                 status: item.kind === ResourceKind.PROJECT
140                     ? TreeNodeStatus.INITIAL
141                     : includeFiles
142                         ? TreeNodeStatus.INITIAL
143                         : TreeNodeStatus.LOADED
144             }),
145         }));
146     };
147
148 export const loadCollection = (id: string, pickerId: string) =>
149     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
150         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId }));
151
152         const picker = getTreePicker<ProjectsTreePickerItem>(pickerId)(getState().treePicker);
153         if (picker) {
154
155             const node = getNode(id)(picker);
156             if (node && 'kind' in node.value && node.value.kind === ResourceKind.COLLECTION) {
157                 const files = await services.collectionService.files(node.value.portableDataHash);
158                 const tree = createCollectionFilesTree(files);
159                 const sorted = sortFilesTree(tree);
160                 const filesTree = mapTreeValues(services.collectionService.extendFileURL)(sorted);
161
162                 dispatch(
163                     treePickerActions.APPEND_TREE_PICKER_NODE_SUBTREE({
164                         id,
165                         pickerId,
166                         subtree: mapTree(node => ({ ...node, status: TreeNodeStatus.LOADED }))(filesTree)
167                     }));
168
169                 dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
170             }
171         }
172     };
173
174
175 export const initUserProject = (pickerId: string) =>
176     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
177         const uuid = getUserUuid(getState());
178         if (uuid) {
179             dispatch(receiveTreePickerData({
180                 id: '',
181                 pickerId,
182                 data: [{ uuid, name: 'Projects' }],
183                 extractNodeData: value => ({
184                     id: value.uuid,
185                     status: TreeNodeStatus.INITIAL,
186                     value,
187                 }),
188             }));
189         }
190     };
191 export const loadUserProject = (pickerId: string, includeCollections = false, includeFiles = false, options?: { showOnlyOwned: boolean, showOnlyWritable: boolean } ) =>
192     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
193         const uuid = getUserUuid(getState());
194         if (uuid) {
195             dispatch(loadProject({ id: uuid, pickerId, includeCollections, includeFiles, options }));
196         }
197     };
198
199 export const SHARED_PROJECT_ID = 'Shared with me';
200 export const initSharedProject = (pickerId: string) =>
201     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
202         dispatch(receiveTreePickerData({
203             id: '',
204             pickerId,
205             data: [{ uuid: SHARED_PROJECT_ID, name: SHARED_PROJECT_ID }],
206             extractNodeData: value => ({
207                 id: value.uuid,
208                 status: TreeNodeStatus.INITIAL,
209                 value,
210             }),
211         }));
212     };
213
214 export const FAVORITES_PROJECT_ID = 'Favorites';
215 export const initFavoritesProject = (pickerId: string) =>
216     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
217         dispatch(receiveTreePickerData({
218             id: '',
219             pickerId,
220             data: [{ uuid: FAVORITES_PROJECT_ID, name: FAVORITES_PROJECT_ID }],
221             extractNodeData: value => ({
222                 id: value.uuid,
223                 status: TreeNodeStatus.INITIAL,
224                 value,
225             }),
226         }));
227     };
228
229 export const PUBLIC_FAVORITES_PROJECT_ID = 'Public Favorites';
230 export const initPublicFavoritesProject = (pickerId: string) =>
231     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
232         dispatch(receiveTreePickerData({
233             id: '',
234             pickerId,
235             data: [{ uuid: PUBLIC_FAVORITES_PROJECT_ID, name: PUBLIC_FAVORITES_PROJECT_ID }],
236             extractNodeData: value => ({
237                 id: value.uuid,
238                 status: TreeNodeStatus.INITIAL,
239                 value,
240             }),
241         }));
242     };
243
244 interface LoadFavoritesProjectParams {
245     pickerId: string;
246     includeCollections?: boolean;
247     includeFiles?: boolean;
248     options?: { showOnlyOwned: boolean, showOnlyWritable: boolean };
249 }
250
251 export const loadFavoritesProject = (params: LoadFavoritesProjectParams,
252     options: { showOnlyOwned: boolean, showOnlyWritable: boolean } = { showOnlyOwned: true, showOnlyWritable: false }) =>
253     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
254         const { pickerId, includeCollections = false, includeFiles = false } = params;
255         const uuid = getUserUuid(getState());
256         if (uuid) {
257             const filters = pipe(
258                 (fb: FilterBuilder) => includeCollections
259                     ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
260                     : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
261                 fb => fb.getFilters(),
262             )(new FilterBuilder());
263
264             const { items } = await services.favoriteService.list(uuid, { filters }, options.showOnlyOwned);
265
266             dispatch<any>(receiveTreePickerData<GroupContentsResource>({
267                 id: 'Favorites',
268                 pickerId,
269                 data: items.filter((item) => {
270                     if (options.showOnlyWritable && (item as GroupResource).writableBy && (item as GroupResource).writableBy.indexOf(uuid) === -1) {
271                         return false;
272                     }
273
274                     if (options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as ProjectResource).frozenByUuid) {
275                         return false;
276                     }
277
278                     return true;
279                 }),
280                 extractNodeData: item => ({
281                     id: item.uuid,
282                     value: item,
283                     status: item.kind === ResourceKind.PROJECT
284                         ? TreeNodeStatus.INITIAL
285                         : includeFiles
286                             ? TreeNodeStatus.INITIAL
287                             : TreeNodeStatus.LOADED
288                 }),
289             }));
290         }
291     };
292
293 export const loadPublicFavoritesProject = (params: LoadFavoritesProjectParams) =>
294     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
295         const { pickerId, includeCollections = false, includeFiles = false } = params;
296         const uuidPrefix = getState().auth.config.uuidPrefix;
297         const publicProjectUuid = `${uuidPrefix}-j7d0g-publicfavorites`;
298
299         const filters = pipe(
300             (fb: FilterBuilder) => includeCollections
301                 ? fb.addIsA('head_uuid', [ResourceKind.PROJECT, ResourceKind.COLLECTION])
302                 : fb.addIsA('head_uuid', [ResourceKind.PROJECT]),
303             fb => fb
304                 .addEqual('link_class', LinkClass.STAR)
305                 .addEqual('owner_uuid', publicProjectUuid)
306                 .getFilters(),
307         )(new FilterBuilder());
308
309         const { items } = await services.linkService.list({ filters });
310
311         dispatch<any>(receiveTreePickerData<LinkResource>({
312             id: 'Public Favorites',
313             pickerId,
314             data: items.filter(item => {
315                 if (params.options && params.options.showOnlyWritable && item.hasOwnProperty('frozenByUuid') && (item as any).frozenByUuid) {
316                     return false;
317                 }
318
319                 return true;
320             }),
321             extractNodeData: item => ({
322                 id: item.headUuid,
323                 value: item,
324                 status: item.headKind === ResourceKind.PROJECT
325                     ? TreeNodeStatus.INITIAL
326                     : includeFiles
327                         ? TreeNodeStatus.INITIAL
328                         : TreeNodeStatus.LOADED
329             }),
330         }));
331     };
332
333 export const receiveTreePickerProjectsData = (id: string, projects: ProjectResource[], pickerId: string) =>
334     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
335         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE_SUCCESS({
336             id,
337             nodes: projects.map(project => initTreeNode({ id: project.uuid, value: project })),
338             pickerId,
339         }));
340
341         dispatch(treePickerActions.TOGGLE_TREE_PICKER_NODE_COLLAPSE({ id, pickerId }));
342     };
343
344 export const loadProjectTreePickerProjects = (id: string) =>
345     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
346         dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PROJECTS }));
347
348
349         const ownerUuid = id.length === 0 ? getUserUuid(getState()) || '' : id;
350         const { items } = await services.projectService.list(buildParams(ownerUuid));
351
352         dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PROJECTS));
353     };
354
355 export const loadFavoriteTreePickerProjects = (id: string) =>
356     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
357         const parentId = getUserUuid(getState()) || '';
358
359         if (id === '') {
360             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.FAVORITES }));
361             const { items } = await services.favoriteService.list(parentId);
362             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.FAVORITES));
363         } else {
364             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.FAVORITES }));
365             const { items } = await services.projectService.list(buildParams(id));
366             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.FAVORITES));
367         }
368
369     };
370
371 export const loadPublicFavoriteTreePickerProjects = (id: string) =>
372     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
373         const parentId = getUserUuid(getState()) || '';
374
375         if (id === '') {
376             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id: parentId, pickerId: TreePickerId.PUBLIC_FAVORITES }));
377             const { items } = await services.favoriteService.list(parentId);
378             dispatch<any>(receiveTreePickerProjectsData(parentId, items as ProjectResource[], TreePickerId.PUBLIC_FAVORITES));
379         } else {
380             dispatch(treePickerActions.LOAD_TREE_PICKER_NODE({ id, pickerId: TreePickerId.PUBLIC_FAVORITES }));
381             const { items } = await services.projectService.list(buildParams(id));
382             dispatch<any>(receiveTreePickerProjectsData(id, items, TreePickerId.PUBLIC_FAVORITES));
383         }
384
385     };
386
387 const buildParams = (ownerUuid: string) => {
388     return {
389         filters: new FilterBuilder()
390             .addEqual('owner_uuid', ownerUuid)
391             .getFilters(),
392         order: new OrderBuilder<ProjectResource>()
393             .addAsc('name')
394             .getOrder()
395     };
396 };