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