15669: Advanced search also sets query in URI
[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(searchValue));
74             }
75         }
76     };
77
78 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
79     async (dispatch: Dispatch, getState: () => RootState) => {
80         dispatch<any>(saveQuery(data));
81         const searchValue = getState().searchBar.searchValue;
82         dispatch(searchResultsPanelActions.CLEAR());
83         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
84         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
85         dispatch(navigateToSearchResults(searchValue));
86     };
87
88 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
89     (dispatch: Dispatch, getState: () => RootState) => {
90         const searchValue = getState().searchBar.searchValue;
91         const value = getQueryFromAdvancedData({
92             ...data,
93             searchValue
94         }, prevData);
95         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
96     };
97
98 export const setAdvancedDataFromSearchValue = (search: string) =>
99     async (dispatch: Dispatch) => {
100         const data = getAdvancedDataFromQuery(search);
101         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
102         if (data.projectUuid) {
103             await dispatch<any>(activateSearchBarProject(data.projectUuid));
104             dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
105         }
106     };
107
108 const saveQuery = (data: SearchBarAdvanceFormData) =>
109     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
110         const savedQueries = services.searchService.getSavedQueries();
111         if (data.saveQuery && data.queryName) {
112             const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
113             data.searchValue = getState().searchBar.searchValue;
114             if (filteredQuery) {
115                 services.searchService.editSavedQueries(data);
116                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
117                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
118             } else {
119                 services.searchService.saveQuery(data);
120                 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
121                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
122             }
123         }
124     };
125
126 export const deleteSavedQuery = (id: number) =>
127     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
128         services.searchService.deleteSavedQuery(id);
129         const savedSearchQueries = services.searchService.getSavedQueries();
130         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
131         return savedSearchQueries || [];
132     };
133
134 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
135     (dispatch: Dispatch<any>) => {
136         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
137         dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
138         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
139     };
140
141 export const openSearchView = () =>
142     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
143         const savedSearchQueries = services.searchService.getSavedQueries();
144         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
145         dispatch(loadRecentQueries());
146         dispatch(searchBarActions.OPEN_SEARCH_VIEW());
147         dispatch(searchBarActions.SELECT_FIRST_ITEM());
148     };
149
150 export const closeSearchView = () =>
151     (dispatch: Dispatch<any>) => {
152         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
153         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
154     };
155
156 export const closeAdvanceView = () =>
157     (dispatch: Dispatch<any>) => {
158         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
159         dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
160         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
161     };
162
163 export const navigateToItem = (uuid: string) =>
164     (dispatch: Dispatch<any>) => {
165         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
166         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
167         dispatch(navigateTo(uuid));
168     };
169
170 export const changeData = (searchValue: string) =>
171     (dispatch: Dispatch, getState: () => RootState) => {
172         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
173         const currentView = getState().searchBar.currentView;
174         const searchValuePresent = searchValue.length > 0;
175
176         if (currentView === SearchView.ADVANCED) {
177             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
178         } else if (searchValuePresent) {
179             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
180             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
181         } else {
182             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
183             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
184             dispatch(searchBarActions.SELECT_FIRST_ITEM());
185         }
186     };
187
188 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
189     (dispatch: Dispatch, getState: () => RootState) => {
190         event.preventDefault();
191         const searchValue = getState().searchBar.searchValue;
192         dispatch<any>(saveRecentQuery(searchValue));
193         dispatch<any>(loadRecentQueries());
194         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
195         if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
196             dispatch<any>(navigateTo(searchValue));
197         } else {
198             dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
199             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
200             dispatch(searchResultsPanelActions.CLEAR());
201             dispatch(navigateToSearchResults(searchValue));
202         }
203     };
204
205
206 const searchGroups = (searchValue: string, limit: number) =>
207     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
208         const currentView = getState().searchBar.currentView;
209
210         if (searchValue || currentView === SearchView.ADVANCED) {
211             const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
212             const sessions = getSearchSessions(clusterId, getState().auth.sessions);
213             const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
214                 const filters = queryToFilters(searchValue);
215                 return services.groupsService.contents('', {
216                     filters,
217                     limit,
218                     recursive: true
219                 }, session);
220             }));
221
222             const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
223             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
224         }
225     };
226
227 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
228     let value = data.searchValue;
229
230     const addRem = (field: string, key: string) => {
231         const v = data[key];
232
233         if (data.hasOwnProperty(key)) {
234             const pattern = v === false
235                 ? `${field.replace(':', '\\:\\s*')}\\s*`
236                 : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
237             value = value.replace(new RegExp(pattern), '');
238         }
239
240         if (v) {
241             const nv = v === true
242                 ? `${field}`
243                 : `${field}:${v}`;
244
245             if (mode === 'rebuild') {
246                 value = value + ' ' + nv;
247             } else {
248                 value = nv + ' ' + value;
249             }
250         }
251     };
252
253     keyMap.forEach(km => addRem(km[0], km[1]));
254
255     return value;
256 };
257
258 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
259     let value = '';
260
261     const flatData = (data: SearchBarAdvanceFormData) => {
262         const fo = {
263             searchValue: data.searchValue,
264             type: data.type,
265             cluster: data.cluster,
266             projectUuid: data.projectUuid,
267             inTrash: data.inTrash,
268             dateFrom: data.dateFrom,
269             dateTo: data.dateTo,
270         };
271         (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
272         return fo;
273     };
274
275     const keyMap = [
276         ['type', 'type'],
277         ['cluster', 'cluster'],
278         ['project', 'projectUuid'],
279         [`is:${parser.States.TRASHED}`, 'inTrash'],
280         ['from', 'dateFrom'],
281         ['to', 'dateTo']
282     ];
283     _.union(data.properties, prevData ? prevData.properties : [])
284         .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
285
286     if (prevData) {
287         const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
288         value = buildQueryFromKeyMap({
289             searchValue: data.searchValue,
290             ...obj
291         } as SearchBarAdvanceFormData, keyMap, "reuse");
292     } else {
293         value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
294     }
295
296     value = value.trim();
297     return value;
298 };
299
300 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
301     const { tokens, searchString } = parser.parseSearchQuery(query);
302     const getValue = parser.getValue(tokens);
303     return {
304         searchValue: searchString,
305         type: getValue(Keywords.TYPE) as ResourceKind,
306         cluster: getValue(Keywords.CLUSTER),
307         projectUuid: getValue(Keywords.PROJECT),
308         inTrash: parser.isTrashed(tokens),
309         dateFrom: getValue(Keywords.FROM) || '',
310         dateTo: getValue(Keywords.TO) || '',
311         properties: parser.getProperties(tokens),
312         saveQuery: false,
313         queryName: ''
314     };
315 };
316
317 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
318     return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
319 };
320
321 export const queryToFilters = (query: string) => {
322     const data = getAdvancedDataFromQuery(query);
323     const filter = new FilterBuilder();
324     const resourceKind = data.type;
325
326     if (data.searchValue) {
327         filter.addFullTextSearch(data.searchValue);
328     }
329
330     if (data.projectUuid) {
331         filter.addEqual('ownerUuid', data.projectUuid);
332     }
333
334     if (data.dateFrom) {
335         filter.addGte('modified_at', buildDateFilter(data.dateFrom));
336     }
337
338     if (data.dateTo) {
339         filter.addLte('modified_at', buildDateFilter(data.dateTo));
340     }
341
342     data.properties.forEach(p => {
343         if (p.value) {
344             filter
345                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
346                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
347         }
348         filter.addExists(p.key);
349     });
350
351     return filter
352         .addIsA("uuid", buildUuidFilter(resourceKind))
353         .getFilters();
354 };
355
356 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
357     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
358 };
359
360 const buildDateFilter = (date?: string): string => {
361     return date ? date : '';
362 };
363
364 export const initAdvanceFormProjectsTree = () =>
365     (dispatch: Dispatch) => {
366         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
367     };
368
369 export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
370     (dispatch: Dispatch) => {
371         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
372     };
373
374 export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
375     (dispatch: Dispatch) => {
376         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
377     };
378
379 export const moveUp = () =>
380     (dispatch: Dispatch) => {
381         dispatch(searchBarActions.MOVE_UP());
382     };
383
384 export const moveDown = () =>
385     (dispatch: Dispatch) => {
386         dispatch(searchBarActions.MOVE_DOWN());
387     };