refs #master Merge branch 'origin/master' into 14280-query-language
[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 interface ParsedSearchQuery {
289     hasKeywords: boolean;
290     values: string[];
291     properties: {
292         [key: string]: string
293     };
294 }
295
296 export const parseSearchQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string): ParsedSearchQuery => {
297     const keywords = [
298         'type:',
299         'cluster:',
300         'project:',
301         'is:',
302         'from:',
303         'to:',
304         'has:'
305     ];
306
307     const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
308     let keywordsCnt = 0;
309
310     const properties = {};
311
312     keywords.forEach(k => {
313         let p = searchValue.indexOf(k);
314         const key = k.substr(0, k.length - 1);
315
316         while (p >= 0) {
317             const l = searchValue.length;
318             keywordsCnt += 1;
319
320             let v = '';
321             let i = p + k.length;
322             while (i < l && searchValue[i] === ' ') {
323                 ++i;
324             }
325             const vp = i;
326             while (i < l && searchValue[i] !== ' ') {
327                 v += searchValue[i];
328                 ++i;
329             }
330
331             if (hasKeywords(v)) {
332                 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
333             } else {
334                 if (v !== '') {
335                     if (!properties[key]) {
336                         properties[key] = [];
337                     }
338                     properties[key].push(v);
339                 }
340                 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
341             }
342             p = searchValue.indexOf(k);
343         }
344     });
345
346     const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
347
348     return { hasKeywords: keywordsCnt > 0, values, properties };
349 };
350
351 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
352     const r = parseSearchQuery(query);
353
354     const getFirstProp = (name: string) => r.properties[name] && r.properties[name][0];
355     const getPropValue = (name: string, value: string) => r.properties[name] && r.properties[name].find((v: string) => v === value);
356     const getProperties = () => {
357         if (r.properties.has) {
358             return r.properties.has.map((value: string) => {
359                 const v = value.split(':');
360                 return {
361                     key: v[0],
362                     value: v[1]
363                 };
364             });
365         }
366         return [];
367     };
368
369     return {
370         searchValue: r.values.join(' '),
371         type: getResourceKind(getFirstProp('type')),
372         cluster: getClusterObjectType(getFirstProp('cluster')),
373         projectUuid: getFirstProp('project'),
374         inTrash: getPropValue('is', 'trashed') !== undefined,
375         dateFrom: getFirstProp('from'),
376         dateTo: getFirstProp('to'),
377         properties: getProperties(),
378         saveQuery: false,
379         queryName: ''
380     };
381 };
382
383 export const getFilters = (filterName: string, searchValue: string): string => {
384     const filter = new FilterBuilder();
385
386     const pq = parseSearchQuery(searchValue);
387
388     if (!pq.hasKeywords) {
389         filter
390             .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
391             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
392             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
393     } else {
394
395         if (pq.properties.type) {
396             pq.values.forEach(v => {
397                 let prefix = '';
398                 switch (ResourceKind[pq.properties.type]) {
399                     case ResourceKind.PROJECT:
400                         prefix = GroupContentsResourcePrefix.PROJECT;
401                         break;
402                     case ResourceKind.COLLECTION:
403                         prefix = GroupContentsResourcePrefix.COLLECTION;
404                         break;
405                     case ResourceKind.PROCESS:
406                         prefix = GroupContentsResourcePrefix.PROCESS;
407                         break;
408                 }
409                 if (prefix !== '') {
410                     filter.addILike(filterName, v, prefix);
411                 }
412             });
413         } else {
414             pq.values.forEach(v => {
415                 filter
416                     .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
417                     .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
418                     .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
419             });
420         }
421
422         if (pq.properties.is && pq.properties.is === 'trashed') {
423         }
424
425         if (pq.properties.project) {
426             filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
427         }
428
429         if (pq.properties.from) {
430             filter.addGte('modified_at', buildDateFilter(pq.properties.from));
431         }
432
433         if (pq.properties.to) {
434             filter.addLte('modified_at', buildDateFilter(pq.properties.to));
435         }
436         // filter
437         //     .addIsA("uuid", buildUuidFilter(resourceKind))
438         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
439         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
440         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
441         //     .addLte('modified_at', buildDateFilter(dateTo))
442         //     .addGte('modified_at', buildDateFilter(dateFrom))
443         //     .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
444     }
445
446     return filter
447         .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
448         .getFilters();
449 };
450
451 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
452     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
453 };
454
455 const buildDateFilter = (date?: string): string => {
456     return date ? date : '';
457 };
458
459 export const initAdvanceFormProjectsTree = () =>
460     (dispatch: Dispatch) => {
461         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
462     };
463
464 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
465     (dispatch: Dispatch) => {
466         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
467     };
468
469 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
470     (dispatch: Dispatch) => {
471         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
472     };
473
474 export const moveUp = () =>
475     (dispatch: Dispatch) => {
476         dispatch(searchBarActions.MOVE_UP());
477     };
478
479 export const moveDown = () =>
480     (dispatch: Dispatch) => {
481         dispatch(searchBarActions.MOVE_DOWN());
482     };