Merge branch '13327-include-container-uuid' refs #13327
[arvados.git] / services / workbench2 / src / store / shared-with-me-panel / shared-with-me-middleware-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import {
6     DataExplorerMiddlewareService,
7     listResultsToDataExplorerItemsMeta,
8     dataExplorerToListParams,
9     getDataExplorerColumnFilters,
10 } from "../data-explorer/data-explorer-middleware-service";
11 import { ServiceRepository } from "services/services";
12 import { MiddlewareAPI, Dispatch } from "redux";
13 import { RootState } from 'store/store';
14 import { getDataExplorer, DataExplorer } from 'store/data-explorer/data-explorer-reducer';
15 import { updateFavorites } from 'store/favorites/favorites-actions';
16 import { updateResources } from 'store/resources/resources-actions';
17 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
18 import { sharedWithMePanelActions } from './shared-with-me-panel-actions';
19 import { ListResults } from 'services/common-service/common-service';
20 import { ContentsArguments, GroupContentsResource, GroupContentsResourcePrefix } from 'services/groups-service/groups-service';
21 import { SortDirection } from 'components/data-table/data-column';
22 import { OrderBuilder, OrderDirection } from 'services/api/order-builder';
23 import { ProjectResource } from 'models/project';
24 import { getSortColumn } from "store/data-explorer/data-explorer-reducer";
25 import { updatePublicFavorites } from 'store/public-favorites/public-favorites-actions';
26 import { FilterBuilder, joinFilters } from 'services/api/filter-builder';
27 import { progressIndicatorActions } from 'store/progress-indicator/progress-indicator-actions';
28 import { AuthState } from 'store/auth/auth-reducer';
29 import { SharedWithMePanelColumnNames } from 'views/shared-with-me-panel/shared-with-me-panel';
30 import { buildProcessStatusFilters, serializeResourceTypeFilters } from 'store/resource-type-filters/resource-type-filters';
31 import { DataColumns } from 'components/data-table/data-table';
32 import { couldNotFetchItemsAvailable } from 'store/data-explorer/data-explorer-action';
33
34 export class SharedWithMeMiddlewareService extends DataExplorerMiddlewareService {
35     constructor(private services: ServiceRepository, id: string) {
36         super(id);
37     }
38
39     async requestItems(api: MiddlewareAPI<Dispatch, RootState>, criteriaChanged?: boolean, background?: boolean) {
40         const state = api.getState();
41         const dataExplorer = getDataExplorer(state.dataExplorer, this.getId());
42         try {
43             if (!background) { api.dispatch(progressIndicatorActions.START_WORKING(this.getId())); }
44             const response = await this.services.groupsService
45                 .contents('', getParams(dataExplorer, state.auth));
46             api.dispatch<any>(updateFavorites(response.items.map(item => item.uuid)));
47             api.dispatch<any>(updatePublicFavorites(response.items.map(item => item.uuid)));
48             api.dispatch(updateResources(response.items));
49             if (response.included) { api.dispatch(updateResources(response.included)); }
50             api.dispatch(setItems(response));
51         } catch (e) {
52             api.dispatch(couldNotFetchSharedItems());
53         } finally {
54             api.dispatch(progressIndicatorActions.PERSIST_STOP_WORKING(this.getId()));
55         }
56     }
57
58     async requestCount(api: MiddlewareAPI<Dispatch, RootState>, criteriaChanged?: boolean) {
59         const state = api.getState();
60         const dataExplorer = getDataExplorer(state.dataExplorer, this.getId());
61
62         if (criteriaChanged) {
63             // Get itemsAvailable
64             return this.services.groupsService.contents('', getCountParams(dataExplorer, state.auth))
65                 .then((results: ListResults<GroupContentsResource>) => {
66                     if (results.itemsAvailable !== undefined) {
67                         api.dispatch<any>(sharedWithMePanelActions.SET_ITEMS_AVAILABLE(results.itemsAvailable));
68                     } else {
69                         couldNotFetchItemsAvailable();
70                     }
71                 })
72         }
73     }
74 }
75
76 export const getParams = (dataExplorer: DataExplorer, authState: AuthState): ContentsArguments => ({
77     ...dataExplorerToListParams(dataExplorer),
78     order: getOrder(dataExplorer),
79     filters: getFilters(dataExplorer, authState),
80     excludeHomeProject: true,
81     count: "none",
82     include: ["owner_uuid", "container_uuid"]
83 });
84
85 const getCountParams = (dataExplorer: DataExplorer, authState: AuthState): ContentsArguments => ({
86     limit: 0,
87     count: 'exact',
88     filters: getFilters(dataExplorer, authState),
89     excludeHomeProject: true,
90 });
91
92 const getOrder = (dataExplorer: DataExplorer) => {
93     const sortColumn = getSortColumn<ProjectResource>(dataExplorer);
94     const order = new OrderBuilder<ProjectResource>();
95     if (sortColumn && sortColumn.sort) {
96         const sortDirection = sortColumn.sort.direction === SortDirection.ASC
97             ? OrderDirection.ASC
98             : OrderDirection.DESC;
99
100         // Use createdAt as a secondary sort column so we break ties consistently.
101         return order
102             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.COLLECTION)
103             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROCESS)
104             .addOrder(sortDirection, sortColumn.sort.field, GroupContentsResourcePrefix.PROJECT)
105             .addOrder(OrderDirection.DESC, "createdAt", GroupContentsResourcePrefix.PROCESS)
106             .getOrder();
107     } else {
108         return order.getOrder();
109     }
110 };
111
112 const getFilters = (dataExplorer: DataExplorer, authState: AuthState) => {
113     const columns = dataExplorer.columns as DataColumns<string, ProjectResource>;
114     const typeFilters = serializeResourceTypeFilters(getDataExplorerColumnFilters(columns, SharedWithMePanelColumnNames.TYPE));
115     const statusColumnFilters = getDataExplorerColumnFilters(columns, "Status");
116     const activeStatusFilter = Object.keys(statusColumnFilters).find(filterName => statusColumnFilters[filterName].selected);
117
118     // TODO: Extract group contents name filter
119     const nameFilters = new FilterBuilder()
120         .addILike("name", dataExplorer.searchValue, GroupContentsResourcePrefix.COLLECTION)
121         .addILike("name", dataExplorer.searchValue, GroupContentsResourcePrefix.PROCESS)
122         .addILike("name", dataExplorer.searchValue, GroupContentsResourcePrefix.PROJECT)
123         .getFilters();
124
125     // Filter by container status
126     const statusFilters = buildProcessStatusFilters(new FilterBuilder(), activeStatusFilter || "", GroupContentsResourcePrefix.PROCESS).getFilters();
127
128     // Filter public favorites
129     const favoritesFilter = new FilterBuilder().addDistinct('uuid', `${authState.config.uuidPrefix}-j7d0g-publicfavorites`).getFilters()
130
131     return joinFilters(statusFilters, typeFilters, nameFilters, favoritesFilter);
132 };
133
134
135 export const setItems = (listResults: ListResults<GroupContentsResource>) =>
136     sharedWithMePanelActions.SET_ITEMS({
137         ...listResultsToDataExplorerItemsMeta(listResults),
138         items: listResults.items.map(resource => resource.uuid),
139     });
140
141 const couldNotFetchSharedItems = () =>
142     snackbarActions.OPEN_SNACKBAR({
143         message: 'Could not fetch shared items.',
144         kind: SnackbarKind.ERROR
145     });