Fix various search issues
[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 } from '~/store/tree-picker/tree-picker-actions';
11 import { ServiceRepository } from '~/services/services';
12 import { FilterBuilder } from "~/services/api/filter-builder";
13 import { getResourceKind, ResourceKind } from '~/models/resource';
14 import { GroupClass } from '~/models/group';
15 import { SearchView } from '~/store/search-bar/search-bar-reducer';
16 import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
17 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
18 import { getClusterObjectType, PropertyValues, SearchBarAdvanceFormData } from '~/models/search-bar';
19 import { debounce } from 'debounce';
20 import * as _ from "lodash";
21 import { getModifiedKeysValues } from "~/common/objects";
22
23 export const searchBarActions = unionize({
24     SET_CURRENT_VIEW: ofType<string>(),
25     OPEN_SEARCH_VIEW: ofType<{}>(),
26     CLOSE_SEARCH_VIEW: ofType<{}>(),
27     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
28     SET_SEARCH_VALUE: ofType<string>(),
29     SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
30     SET_RECENT_QUERIES: ofType<string[]>(),
31     UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
32     SET_SELECTED_ITEM: ofType<string>(),
33     MOVE_UP: ofType<{}>(),
34     MOVE_DOWN: ofType<{}>(),
35     SELECT_FIRST_ITEM: ofType<{}>()
36 });
37
38 export type SearchBarActions = UnionOf<typeof searchBarActions>;
39
40 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
41
42 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
43
44 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
45
46 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
47
48 export const saveRecentQuery = (query: string) =>
49     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
50         services.searchService.saveRecentQuery(query);
51
52
53 export const loadRecentQueries = () =>
54     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
55         const recentQueries = services.searchService.getRecentQueries();
56         dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
57         return recentQueries;
58     };
59
60 export const searchData = (searchValue: string) =>
61     async (dispatch: Dispatch, getState: () => RootState) => {
62         const currentView = getState().searchBar.currentView;
63         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
64         if (searchValue.length > 0) {
65             dispatch<any>(searchGroups(searchValue, 5));
66             if (currentView === SearchView.BASIC) {
67                 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
68                 dispatch(navigateToSearchResults);
69             }
70         }
71     };
72
73 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
74     async (dispatch: Dispatch) => {
75         dispatch<any>(saveQuery(data));
76         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
77         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
78         dispatch(navigateToSearchResults);
79     };
80
81 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
82     (dispatch: Dispatch, getState: () => RootState) => {
83         const searchValue = getState().searchBar.searchValue;
84         const value = getQueryFromAdvancedData({
85             ...data,
86             searchValue
87         }, prevData);
88         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
89     };
90
91 export const setAdvancedDataFromSearchValue = (search: string) =>
92     (dispatch: Dispatch) => {
93         const data = getAdvancedDataFromQuery(search);
94         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
95     };
96
97 const saveQuery = (data: SearchBarAdvanceFormData) =>
98     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
99         const savedQueries = services.searchService.getSavedQueries();
100         if (data.saveQuery && data.queryName) {
101             const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
102             data.searchValue = getState().searchBar.searchValue;
103             if (filteredQuery) {
104                 services.searchService.editSavedQueries(data);
105                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
106                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
107             } else {
108                 services.searchService.saveQuery(data);
109                 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
110                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
111             }
112         }
113     };
114
115 export const deleteSavedQuery = (id: number) =>
116     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
117         services.searchService.deleteSavedQuery(id);
118         const savedSearchQueries = services.searchService.getSavedQueries();
119         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
120         return savedSearchQueries || [];
121     };
122
123 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
124     (dispatch: Dispatch<any>) => {
125         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
126         dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
127         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
128     };
129
130 export const openSearchView = () =>
131     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
132         const savedSearchQueries = services.searchService.getSavedQueries();
133         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
134         dispatch(loadRecentQueries());
135         dispatch(searchBarActions.OPEN_SEARCH_VIEW());
136         dispatch(searchBarActions.SELECT_FIRST_ITEM());
137     };
138
139 export const closeSearchView = () =>
140     (dispatch: Dispatch<any>) => {
141         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
142         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
143     };
144
145 export const closeAdvanceView = () =>
146     (dispatch: Dispatch<any>) => {
147         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
148         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
149     };
150
151 export const navigateToItem = (uuid: string) =>
152     (dispatch: Dispatch<any>) => {
153         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
154         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
155         dispatch(navigateTo(uuid));
156     };
157
158 export const changeData = (searchValue: string) =>
159     (dispatch: Dispatch, getState: () => RootState) => {
160         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
161         const currentView = getState().searchBar.currentView;
162         const searchValuePresent = searchValue.length > 0;
163
164         if (currentView === SearchView.ADVANCED) {
165             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
166         } else if (searchValuePresent) {
167             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
168             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
169             debounceStartSearch(dispatch);
170         } else {
171             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
172             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
173             dispatch(searchBarActions.SELECT_FIRST_ITEM());
174         }
175     };
176
177 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
178     (dispatch: Dispatch, getState: () => RootState) => {
179         event.preventDefault();
180         const searchValue = getState().searchBar.searchValue;
181         dispatch<any>(saveRecentQuery(searchValue));
182         dispatch<any>(loadRecentQueries());
183         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
184         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
185         dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
186         dispatch(navigateToSearchResults);
187     };
188
189 const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
190
191 const startSearch = () =>
192     (dispatch: Dispatch, getState: () => RootState) => {
193         const searchValue = getState().searchBar.searchValue;
194         dispatch<any>(searchData(searchValue));
195     };
196
197 const searchGroups = (searchValue: string, limit: number) =>
198     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
199         const currentView = getState().searchBar.currentView;
200
201         if (searchValue || currentView === SearchView.ADVANCED) {
202             const filters = getFilters('name', searchValue);
203             const { items } = await services.groupsService.contents('', {
204                 filters,
205                 limit,
206                 recursive: true
207             });
208             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
209         }
210     };
211
212 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
213     let value = data.searchValue;
214
215     const rem = (field: string, fieldValue: any, value: string) => {
216     };
217
218     const addRem = (field: string, key: string) => {
219         const v = data[key];
220
221         if (data.hasOwnProperty(key)) {
222             const pattern = v === false
223                 ? `${field.replace(':', '\\:\\s*')}\\s*`
224                 : `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*\\s*`;
225             value = value.replace(new RegExp(pattern), '');
226         }
227
228         if (v) {
229             const nv = v === true
230                 ? `${field}`
231                 : `${field}:${v}`;
232
233             if (mode === 'rebuild') {
234                 value = value + ' ' + nv;
235             } else {
236                 value = nv + ' ' + value;
237             }
238         }
239     };
240
241     keyMap.forEach(km => addRem(km[0], km[1]));
242
243     return value;
244 };
245
246 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
247     let value = '';
248
249     const flatData = (data: SearchBarAdvanceFormData) => {
250         const fo = {
251             searchValue: data.searchValue,
252             type: data.type,
253             cluster: data.cluster,
254             projectUuid: data.projectUuid,
255             inTrash: data.inTrash,
256             dateFrom: data.dateFrom,
257             dateTo: data.dateTo,
258         };
259         (data.properties || []).forEach(p => fo[`prop-${p.key}`] = p.value);
260         return fo;
261     };
262
263     const keyMap = [
264         ['type', 'type'],
265         ['cluster', 'cluster'],
266         ['project', 'projectUuid'],
267         ['is:trashed', 'inTrash'],
268         ['from', 'dateFrom'],
269         ['to', 'dateTo']
270     ];
271     _.union(data.properties, prevData ? prevData.properties : [])
272         .forEach(p => keyMap.push([`has:${p.key}`, `prop-${p.key}`]));
273
274     if (prevData) {
275         const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
276         value = buildQueryFromKeyMap({
277             searchValue: data.searchValue,
278             ...obj
279         } as SearchBarAdvanceFormData, keyMap, "reuse");
280     } else {
281         value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
282     }
283
284     value = value.trim();
285     return value;
286 };
287
288 export const parseQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string) => {
289     const keywords = [
290         'type:',
291         'cluster:',
292         'project:',
293         'is:',
294         'from:',
295         'to:',
296         'has:'
297     ];
298
299     const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
300     let keywordsCnt = 0;
301
302     const properties = {};
303
304     keywords.forEach(k => {
305         let p = searchValue.indexOf(k);
306         const key = k.substr(0, k.length - 1);
307
308         while (p >= 0) {
309             const l = searchValue.length;
310             keywordsCnt += 1;
311
312             let v = '';
313             let i = p + k.length;
314             while (i < l && searchValue[i] === ' ') {
315                 ++i;
316             }
317             const vp = i;
318             while (i < l && searchValue[i] !== ' ') {
319                 v += searchValue[i];
320                 ++i;
321             }
322
323             if (hasKeywords(v)) {
324                 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
325             } else {
326                 if (v !== '') {
327                     if (!properties[key]) {
328                         properties[key] = [];
329                     }
330                     properties[key].push(v);
331                 }
332                 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
333             }
334             p = searchValue.indexOf(k);
335         }
336     });
337
338     const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
339
340     return { hasKeywords: keywordsCnt > 0, values, properties };
341 };
342
343 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
344     const r = parseQuery(query);
345
346     const getFirstProp = (name: string) => r.properties[name] && r.properties[name][0];
347     const getPropValue = (name: string, value: string) => r.properties[name] && r.properties[name].find((v: string) => v === value);
348     const getProperties = () => {
349         if (r.properties.has) {
350             return r.properties.has.map((value: string) => {
351                 const v = value.split(':');
352                 return {
353                     key: v[0],
354                     value: v[1]
355                 };
356             });
357         }
358         return [];
359     };
360
361     return {
362         searchValue: r.values.join(' '),
363         type: getResourceKind(getFirstProp('type')),
364         cluster: getClusterObjectType(getFirstProp('cluster')),
365         projectUuid: getFirstProp('project'),
366         inTrash: getPropValue('is', 'trashed') !== undefined,
367         dateFrom: getFirstProp('from'),
368         dateTo: getFirstProp('to'),
369         properties: getProperties(),
370         saveQuery: false,
371         queryName: ''
372     };
373 };
374
375 export const getFilters = (filterName: string, searchValue: string): string => {
376     const filter = new FilterBuilder();
377
378     const pq = parseQuery(searchValue);
379
380     if (!pq.hasKeywords) {
381         filter
382             .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
383             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
384             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
385     } else {
386
387         if (pq.properties.type) {
388             pq.values.forEach(v => {
389                 let prefix = '';
390                 switch (ResourceKind[pq.properties.type]) {
391                     case ResourceKind.PROJECT:
392                         prefix = GroupContentsResourcePrefix.PROJECT;
393                         break;
394                     case ResourceKind.COLLECTION:
395                         prefix = GroupContentsResourcePrefix.COLLECTION;
396                         break;
397                     case ResourceKind.PROCESS:
398                         prefix = GroupContentsResourcePrefix.PROCESS;
399                         break;
400                 }
401                 if (prefix !== '') {
402                     filter.addILike(filterName, v, prefix);
403                 }
404             });
405         } else {
406             pq.values.forEach(v => {
407                 filter
408                     .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
409                     .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
410                     .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
411             });
412         }
413
414         if (pq.properties.is && pq.properties.is === 'trashed') {
415         }
416
417         if (pq.properties.project) {
418             filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
419         }
420
421         if (pq.properties.from) {
422             filter.addGte('modified_at', buildDateFilter(pq.properties.from));
423         }
424
425         if (pq.properties.to) {
426             filter.addLte('modified_at', buildDateFilter(pq.properties.to));
427         }
428         // filter
429         //     .addIsA("uuid", buildUuidFilter(resourceKind))
430         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
431         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
432         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
433         //     .addLte('modified_at', buildDateFilter(dateTo))
434         //     .addGte('modified_at', buildDateFilter(dateFrom))
435         //     .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
436     }
437
438     return filter
439         .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
440         .getFilters();
441 };
442
443 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
444     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
445 };
446
447 const buildDateFilter = (date?: string): string => {
448     return date ? date : '';
449 };
450
451 export const initAdvanceFormProjectsTree = () =>
452     (dispatch: Dispatch) => {
453         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
454     };
455
456 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
457     (dispatch: Dispatch) => {
458         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
459     };
460
461 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
462     (dispatch: Dispatch) => {
463         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
464     };
465
466 export const moveUp = () =>
467     (dispatch: Dispatch) => {
468         dispatch(searchBarActions.MOVE_UP());
469     };
470
471 export const moveDown = () =>
472     (dispatch: Dispatch) => {
473         dispatch(searchBarActions.MOVE_DOWN());
474     };