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