15027: Fixes unused declarations errors.
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { ofType, unionize, UnionOf } from "~/common/unionize";
6 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
7 import { Dispatch } from 'redux';
8 import { arrayPush, change, initialize } from 'redux-form';
9 import { RootState } from '~/store/store';
10 import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions';
11 import { ServiceRepository } from '~/services/services';
12 import { FilterBuilder } from "~/services/api/filter-builder";
13 import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource';
14 import { SearchView } from '~/store/search-bar/search-bar-reducer';
15 import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
16 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
17 import { PropertyValue, SearchBarAdvanceFormData } from '~/models/search-bar';
18 import * as _ from "lodash";
19 import { getModifiedKeysValues } from "~/common/objects";
20 import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
21 import { Session } from "~/models/session";
22 import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions";
23 import { ListResults } from "~/services/common-service/common-service";
24 import * as parser from './search-query/arv-parser';
25 import { Keywords } from './search-query/arv-parser';
26
27 export const searchBarActions = unionize({
28     SET_CURRENT_VIEW: ofType<string>(),
29     OPEN_SEARCH_VIEW: ofType<{}>(),
30     CLOSE_SEARCH_VIEW: ofType<{}>(),
31     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
32     SET_SEARCH_VALUE: ofType<string>(),
33     SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
34     SET_RECENT_QUERIES: ofType<string[]>(),
35     UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
36     SET_SELECTED_ITEM: ofType<string>(),
37     MOVE_UP: ofType<{}>(),
38     MOVE_DOWN: ofType<{}>(),
39     SELECT_FIRST_ITEM: ofType<{}>()
40 });
41
42 export type SearchBarActions = UnionOf<typeof searchBarActions>;
43
44 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
45
46 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
47
48 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
49
50 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
51
52 export const saveRecentQuery = (query: string) =>
53     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
54         services.searchService.saveRecentQuery(query);
55
56
57 export const loadRecentQueries = () =>
58     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
59         const recentQueries = services.searchService.getRecentQueries();
60         dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
61         return recentQueries;
62     };
63
64 export const searchData = (searchValue: string) =>
65     async (dispatch: Dispatch, getState: () => RootState) => {
66         const currentView = getState().searchBar.currentView;
67         dispatch(searchResultsPanelActions.CLEAR());
68         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
69         if (searchValue.length > 0) {
70             dispatch<any>(searchGroups(searchValue, 5));
71             if (currentView === SearchView.BASIC) {
72                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
73                 dispatch(navigateToSearchResults);
74             }
75         }
76     };
77
78 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
79     async (dispatch: Dispatch) => {
80         dispatch<any>(saveQuery(data));
81         dispatch(searchResultsPanelActions.CLEAR());
82         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
83         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
84         dispatch(navigateToSearchResults);
85     };
86
87 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
88     (dispatch: Dispatch, getState: () => RootState) => {
89         const searchValue = getState().searchBar.searchValue;
90         const value = getQueryFromAdvancedData({
91             ...data,
92             searchValue
93         }, prevData);
94         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
95     };
96
97 export const setAdvancedDataFromSearchValue = (search: string) =>
98     async (dispatch: Dispatch) => {
99         const data = getAdvancedDataFromQuery(search);
100         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
101         if (data.projectUuid) {
102             await dispatch<any>(activateSearchBarProject(data.projectUuid));
103             dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
104         }
105     };
106
107 const saveQuery = (data: SearchBarAdvanceFormData) =>
108     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
109         const savedQueries = services.searchService.getSavedQueries();
110         if (data.saveQuery && data.queryName) {
111             const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
112             data.searchValue = getState().searchBar.searchValue;
113             if (filteredQuery) {
114                 services.searchService.editSavedQueries(data);
115                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
116                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
117             } else {
118                 services.searchService.saveQuery(data);
119                 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
120                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
121             }
122         }
123     };
124
125 export const deleteSavedQuery = (id: number) =>
126     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
127         services.searchService.deleteSavedQuery(id);
128         const savedSearchQueries = services.searchService.getSavedQueries();
129         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
130         return savedSearchQueries || [];
131     };
132
133 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
134     (dispatch: Dispatch<any>) => {
135         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
136         dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
137         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
138     };
139
140 export const openSearchView = () =>
141     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
142         const savedSearchQueries = services.searchService.getSavedQueries();
143         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
144         dispatch(loadRecentQueries());
145         dispatch(searchBarActions.OPEN_SEARCH_VIEW());
146         dispatch(searchBarActions.SELECT_FIRST_ITEM());
147     };
148
149 export const closeSearchView = () =>
150     (dispatch: Dispatch<any>) => {
151         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
152         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
153     };
154
155 export const closeAdvanceView = () =>
156     (dispatch: Dispatch<any>) => {
157         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
158         dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
159         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
160     };
161
162 export const navigateToItem = (uuid: string) =>
163     (dispatch: Dispatch<any>) => {
164         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
165         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
166         dispatch(navigateTo(uuid));
167     };
168
169 export const changeData = (searchValue: string) =>
170     (dispatch: Dispatch, getState: () => RootState) => {
171         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
172         const currentView = getState().searchBar.currentView;
173         const searchValuePresent = searchValue.length > 0;
174
175         if (currentView === SearchView.ADVANCED) {
176             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
177         } else if (searchValuePresent) {
178             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
179             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
180         } else {
181             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
182             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
183             dispatch(searchBarActions.SELECT_FIRST_ITEM());
184         }
185     };
186
187 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
188     (dispatch: Dispatch, getState: () => RootState) => {
189         event.preventDefault();
190         const searchValue = getState().searchBar.searchValue;
191         dispatch<any>(saveRecentQuery(searchValue));
192         dispatch<any>(loadRecentQueries());
193         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
194         if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
195             dispatch<any>(navigateTo(searchValue));
196         } else {
197             dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
198             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
199             dispatch(searchResultsPanelActions.CLEAR());
200             dispatch(navigateToSearchResults);
201         }
202     };
203
204
205 const searchGroups = (searchValue: string, limit: number) =>
206     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
207         const currentView = getState().searchBar.currentView;
208
209         if (searchValue || currentView === SearchView.ADVANCED) {
210             const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
211             const sessions = getSearchSessions(clusterId, getState().auth.sessions);
212             const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
213                 const filters = queryToFilters(searchValue);
214                 return services.groupsService.contents('', {
215                     filters,
216                     limit,
217                     recursive: true
218                 }, session);
219             }));
220
221             const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
222             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
223         }
224     };
225
226 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
227     let value = data.searchValue;
228
229     const addRem = (field: string, key: string) => {
230         const v = data[key];
231
232         if (data.hasOwnProperty(key)) {
233             const pattern = v === false
234                 ? `${field.replace(':', '\\:\\s*')}\\s*`
235                 : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
236             value = value.replace(new RegExp(pattern), '');
237         }
238
239         if (v) {
240             const nv = v === true
241                 ? `${field}`
242                 : `${field}:${v}`;
243
244             if (mode === 'rebuild') {
245                 value = value + ' ' + nv;
246             } else {
247                 value = nv + ' ' + value;
248             }
249         }
250     };
251
252     keyMap.forEach(km => addRem(km[0], km[1]));
253
254     return value;
255 };
256
257 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
258     let value = '';
259
260     const flatData = (data: SearchBarAdvanceFormData) => {
261         const fo = {
262             searchValue: data.searchValue,
263             type: data.type,
264             cluster: data.cluster,
265             projectUuid: data.projectUuid,
266             inTrash: data.inTrash,
267             dateFrom: data.dateFrom,
268             dateTo: data.dateTo,
269         };
270         (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
271         return fo;
272     };
273
274     const keyMap = [
275         ['type', 'type'],
276         ['cluster', 'cluster'],
277         ['project', 'projectUuid'],
278         [`is:${parser.States.TRASHED}`, 'inTrash'],
279         ['from', 'dateFrom'],
280         ['to', 'dateTo']
281     ];
282     _.union(data.properties, prevData ? prevData.properties : [])
283         .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
284
285     if (prevData) {
286         const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
287         value = buildQueryFromKeyMap({
288             searchValue: data.searchValue,
289             ...obj
290         } as SearchBarAdvanceFormData, keyMap, "reuse");
291     } else {
292         value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
293     }
294
295     value = value.trim();
296     return value;
297 };
298
299 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
300     const { tokens, searchString } = parser.parseSearchQuery(query);
301     const getValue = parser.getValue(tokens);
302     return {
303         searchValue: searchString,
304         type: getValue(Keywords.TYPE) as ResourceKind,
305         cluster: getValue(Keywords.CLUSTER),
306         projectUuid: getValue(Keywords.PROJECT),
307         inTrash: parser.isTrashed(tokens),
308         dateFrom: getValue(Keywords.FROM) || '',
309         dateTo: getValue(Keywords.TO) || '',
310         properties: parser.getProperties(tokens),
311         saveQuery: false,
312         queryName: ''
313     };
314 };
315
316 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
317     return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
318 };
319
320 export const queryToFilters = (query: string) => {
321     const data = getAdvancedDataFromQuery(query);
322     const filter = new FilterBuilder();
323     const resourceKind = data.type;
324
325     if (data.searchValue) {
326         filter.addFullTextSearch(data.searchValue);
327     }
328
329     if (data.projectUuid) {
330         filter.addEqual('ownerUuid', data.projectUuid);
331     }
332
333     if (data.dateFrom) {
334         filter.addGte('modified_at', buildDateFilter(data.dateFrom));
335     }
336
337     if (data.dateTo) {
338         filter.addLte('modified_at', buildDateFilter(data.dateTo));
339     }
340
341     data.properties.forEach(p => {
342         if (p.value) {
343             filter
344                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
345                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
346         }
347         filter.addExists(p.key);
348     });
349
350     return filter
351         .addIsA("uuid", buildUuidFilter(resourceKind))
352         .getFilters();
353 };
354
355 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
356     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
357 };
358
359 const buildDateFilter = (date?: string): string => {
360     return date ? date : '';
361 };
362
363 export const initAdvanceFormProjectsTree = () =>
364     (dispatch: Dispatch) => {
365         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
366     };
367
368 export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
369     (dispatch: Dispatch) => {
370         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
371     };
372
373 export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
374     (dispatch: Dispatch) => {
375         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
376     };
377
378 export const moveUp = () =>
379     (dispatch: Dispatch) => {
380         dispatch(searchBarActions.MOVE_UP());
381     };
382
383 export const moveDown = () =>
384     (dispatch: Dispatch) => {
385         dispatch(searchBarActions.MOVE_DOWN());
386     };