Merge branch '15230-fed-collection-crash' refs #15230
[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, isResourceUuid, extractUuidKind, 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 { debounce } from 'debounce';
19 import * as _ from "lodash";
20 import { getModifiedKeysValues } from "~/common/objects";
21 import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
22 import { Session } from "~/models/session";
23 import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions";
24 import { ListResults } from "~/services/common-service/common-service";
25 import * as parser from './search-query/arv-parser';
26 import { Keywords } from './search-query/arv-parser';
27
28 export const searchBarActions = unionize({
29     SET_CURRENT_VIEW: ofType<string>(),
30     OPEN_SEARCH_VIEW: ofType<{}>(),
31     CLOSE_SEARCH_VIEW: ofType<{}>(),
32     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
33     SET_SEARCH_VALUE: ofType<string>(),
34     SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
35     SET_RECENT_QUERIES: ofType<string[]>(),
36     UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
37     SET_SELECTED_ITEM: ofType<string>(),
38     MOVE_UP: ofType<{}>(),
39     MOVE_DOWN: ofType<{}>(),
40     SELECT_FIRST_ITEM: ofType<{}>()
41 });
42
43 export type SearchBarActions = UnionOf<typeof searchBarActions>;
44
45 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
46
47 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
48
49 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
50
51 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
52
53 export const saveRecentQuery = (query: string) =>
54     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
55         services.searchService.saveRecentQuery(query);
56
57
58 export const loadRecentQueries = () =>
59     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
60         const recentQueries = services.searchService.getRecentQueries();
61         dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
62         return recentQueries;
63     };
64
65 export const searchData = (searchValue: string) =>
66     async (dispatch: Dispatch, getState: () => RootState) => {
67         const currentView = getState().searchBar.currentView;
68         dispatch(searchResultsPanelActions.CLEAR());
69         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
70         if (searchValue.length > 0) {
71             dispatch<any>(searchGroups(searchValue, 5));
72             if (currentView === SearchView.BASIC) {
73                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
74                 dispatch(navigateToSearchResults);
75             }
76         }
77     };
78
79 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
80     async (dispatch: Dispatch) => {
81         dispatch<any>(saveQuery(data));
82         dispatch(searchResultsPanelActions.CLEAR());
83         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
84         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
85         dispatch(navigateToSearchResults);
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);
202         }
203     };
204
205
206 const startSearch = () =>
207     (dispatch: Dispatch, getState: () => RootState) => {
208         const searchValue = getState().searchBar.searchValue;
209         dispatch<any>(searchData(searchValue));
210     };
211
212 const searchGroups = (searchValue: string, limit: number) =>
213     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
214         const currentView = getState().searchBar.currentView;
215
216         if (searchValue || currentView === SearchView.ADVANCED) {
217             const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
218             const sessions = getSearchSessions(clusterId, getState().auth.sessions);
219             const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
220                 const filters = queryToFilters(searchValue);
221                 return services.groupsService.contents('', {
222                     filters,
223                     limit,
224                     recursive: true
225                 }, session);
226             }));
227
228             const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
229             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
230         }
231     };
232
233 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
234     let value = data.searchValue;
235
236     const addRem = (field: string, key: string) => {
237         const v = data[key];
238
239         if (data.hasOwnProperty(key)) {
240             const pattern = v === false
241                 ? `${field.replace(':', '\\:\\s*')}\\s*`
242                 : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
243             value = value.replace(new RegExp(pattern), '');
244         }
245
246         if (v) {
247             const nv = v === true
248                 ? `${field}`
249                 : `${field}:${v}`;
250
251             if (mode === 'rebuild') {
252                 value = value + ' ' + nv;
253             } else {
254                 value = nv + ' ' + value;
255             }
256         }
257     };
258
259     keyMap.forEach(km => addRem(km[0], km[1]));
260
261     return value;
262 };
263
264 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
265     let value = '';
266
267     const flatData = (data: SearchBarAdvanceFormData) => {
268         const fo = {
269             searchValue: data.searchValue,
270             type: data.type,
271             cluster: data.cluster,
272             projectUuid: data.projectUuid,
273             inTrash: data.inTrash,
274             dateFrom: data.dateFrom,
275             dateTo: data.dateTo,
276         };
277         (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
278         return fo;
279     };
280
281     const keyMap = [
282         ['type', 'type'],
283         ['cluster', 'cluster'],
284         ['project', 'projectUuid'],
285         [`is:${parser.States.TRASHED}`, 'inTrash'],
286         ['from', 'dateFrom'],
287         ['to', 'dateTo']
288     ];
289     _.union(data.properties, prevData ? prevData.properties : [])
290         .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
291
292     if (prevData) {
293         const fd = flatData(data);
294         const pfd = flatData(prevData);
295         const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
296         value = buildQueryFromKeyMap({
297             searchValue: data.searchValue,
298             ...obj
299         } as SearchBarAdvanceFormData, keyMap, "reuse");
300     } else {
301         value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
302     }
303
304     value = value.trim();
305     return value;
306 };
307
308 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
309     const { tokens, searchString } = parser.parseSearchQuery(query);
310     const getValue = parser.getValue(tokens);
311     return {
312         searchValue: searchString,
313         type: getValue(Keywords.TYPE) as ResourceKind,
314         cluster: getValue(Keywords.CLUSTER),
315         projectUuid: getValue(Keywords.PROJECT),
316         inTrash: parser.isTrashed(tokens),
317         dateFrom: getValue(Keywords.FROM) || '',
318         dateTo: getValue(Keywords.TO) || '',
319         properties: parser.getProperties(tokens),
320         saveQuery: false,
321         queryName: ''
322     };
323 };
324
325 export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
326     return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
327 };
328
329 export const queryToFilters = (query: string) => {
330     const data = getAdvancedDataFromQuery(query);
331     const filter = new FilterBuilder();
332     const resourceKind = data.type;
333
334     if (data.searchValue) {
335         filter.addFullTextSearch(data.searchValue);
336     }
337
338     if (data.projectUuid) {
339         filter.addEqual('ownerUuid', data.projectUuid);
340     }
341
342     if (data.dateFrom) {
343         filter.addGte('modified_at', buildDateFilter(data.dateFrom));
344     }
345
346     if (data.dateTo) {
347         filter.addLte('modified_at', buildDateFilter(data.dateTo));
348     }
349
350     data.properties.forEach(p => {
351         if (p.value) {
352             filter
353                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
354                 .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
355         }
356         filter.addExists(p.key);
357     });
358
359     return filter
360         .addIsA("uuid", buildUuidFilter(resourceKind))
361         .getFilters();
362 };
363
364 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
365     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
366 };
367
368 const buildDateFilter = (date?: string): string => {
369     return date ? date : '';
370 };
371
372 export const initAdvanceFormProjectsTree = () =>
373     (dispatch: Dispatch) => {
374         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
375     };
376
377 export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
378     (dispatch: Dispatch) => {
379         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
380     };
381
382 export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
383     (dispatch: Dispatch) => {
384         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
385     };
386
387 export const moveUp = () =>
388     (dispatch: Dispatch) => {
389         dispatch(searchBarActions.MOVE_UP());
390     };
391
392 export const moveDown = () =>
393     (dispatch: Dispatch) => {
394         dispatch(searchBarActions.MOVE_DOWN());
395     };