Update redux form types, make getFilters keywords aware
[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 { unionize, ofType, UnionOf } from "~/common/unionize";
6 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
7 import { Dispatch } from 'redux';
8 import { change, arrayPush } 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 { ResourceKind } from '~/models/resource';
14 import { GroupClass } from '~/models/group';
15 import { SearchView } from '~/store/search-bar/search-bar-reducer';
16 import { navigateToSearchResults, navigateTo } from '~/store/navigation/navigation-action';
17 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
18 import { initialize } from 'redux-form';
19 import { SearchBarAdvanceFormData, PropertyValues, ClusterObjectType } from '~/models/search-bar';
20 import { debounce } from 'debounce';
21 import * as _ from "lodash";
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) => {
83         let value = '';
84         if (data.type) {
85             value += ` type:${data.type}`;
86         }
87         if (data.cluster) {
88             value += ` cluster:${data.cluster}`;
89         }
90         if (data.projectUuid) {
91             value += ` project:${data.projectUuid}`;
92         }
93         if (data.inTrash) {
94             value += ` is:trashed`;
95         }
96         if (data.dateFrom) {
97             value += ` from:${data.dateFrom}`;
98         }
99         if (data.dateTo) {
100             value += ` from:${data.dateTo}`;
101         }
102         value = value.substr(1) + data.searchQuery;
103         dispatch(searchBarActions.SET_SEARCH_VALUE(value));
104     };
105
106 const saveQuery = (data: SearchBarAdvanceFormData) =>
107     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
108         const savedQueries = services.searchService.getSavedQueries();
109         if (data.saveQuery && data.searchQuery) {
110             const filteredQuery = savedQueries.find(query => query.searchQuery === data.searchQuery);
111             if (filteredQuery) {
112                 services.searchService.editSavedQueries(data);
113                 dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
114                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
115             } else {
116                 services.searchService.saveQuery(data);
117                 dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
118                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
119             }
120         }
121     };
122
123 export const deleteSavedQuery = (id: number) =>
124     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
125         services.searchService.deleteSavedQuery(id);
126         const savedSearchQueries = services.searchService.getSavedQueries();
127         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
128         return savedSearchQueries || [];
129     };
130
131 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
132     (dispatch: Dispatch<any>) => {
133         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
134         dispatch(searchBarActions.SET_SEARCH_VALUE(data.searchQuery));
135         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
136     };
137
138 export const openSearchView = () =>
139     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
140         const savedSearchQueries = services.searchService.getSavedQueries();
141         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
142         dispatch(loadRecentQueries());
143         dispatch(searchBarActions.OPEN_SEARCH_VIEW());
144         dispatch(searchBarActions.SELECT_FIRST_ITEM());
145     };
146
147 export const closeSearchView = () =>
148     (dispatch: Dispatch<any>) => {
149         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
150         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
151     };
152
153 export const closeAdvanceView = () =>
154     (dispatch: Dispatch<any>) => {
155         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
156         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
157     };
158
159 export const navigateToItem = (uuid: string) =>
160     (dispatch: Dispatch<any>) => {
161         dispatch(searchBarActions.SET_SELECTED_ITEM(''));
162         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
163         dispatch(navigateTo(uuid));
164     };
165
166 export const changeData = (searchValue: string) =>
167     (dispatch: Dispatch, getState: () => RootState) => {
168         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
169         const currentView = getState().searchBar.currentView;
170         const searchValuePresent = searchValue.length > 0;
171
172         if (currentView === SearchView.ADVANCED) {
173
174         } else if (searchValuePresent) {
175             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
176             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
177             debounceStartSearch(dispatch);
178         } else {
179             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
180             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
181             dispatch(searchBarActions.SELECT_FIRST_ITEM());
182         }
183     };
184
185 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
186     (dispatch: Dispatch, getState: () => RootState) => {
187         event.preventDefault();
188         const searchValue = getState().searchBar.searchValue;
189         dispatch<any>(saveRecentQuery(searchValue));
190         dispatch<any>(loadRecentQueries());
191         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
192         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
193         dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
194         dispatch(navigateToSearchResults);
195     };
196
197 const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
198
199 const startSearch = () =>
200     (dispatch: Dispatch, getState: () => RootState) => {
201         const searchValue = getState().searchBar.searchValue;
202         dispatch<any>(searchData(searchValue));
203     };
204
205 const searchGroups = (searchValue: string, limit: number) =>
206     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
207         const currentView = getState().searchBar.currentView;
208
209         if (searchValue || currentView === SearchView.ADVANCED) {
210             const filters = getFilters('name', searchValue);
211             const { items } = await services.groupsService.contents('', {
212                 filters,
213                 limit,
214                 recursive: true
215             });
216             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
217         }
218     };
219
220 export const parseQuery: (searchValue: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string) => {
221     const keywords = [
222         'type:',
223         'cluster:',
224         'project:',
225         'is:',
226         'from:',
227         'to:'
228     ];
229
230     const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
231     let keywordsCnt = 0;
232
233     const properties = {};
234
235     keywords.forEach(k => {
236         const p = searchValue.indexOf(k);
237         const l = searchValue.length;
238         if (p >= 0) {
239             keywordsCnt += 1;
240
241             let v = '';
242             let i = p + k.length;
243             while (i < l && searchValue[i] === ' ') {
244                 ++i;
245             }
246             const vp = i;
247             while (i < l && searchValue[i] !== ' ') {
248                 v += searchValue[i];
249                 ++i;
250             }
251
252             if (hasKeywords(v)) {
253                 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
254             } else {
255                 if (v !== '') {
256                     properties[k.substr(0, k.length - 1)] = v;
257                 }
258                 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
259             }
260         }
261     });
262
263     const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
264
265     return { hasKeywords: keywordsCnt > 0, values, properties };
266 };
267
268 export const getFilters = (filterName: string, searchValue: string): string => {
269     const filter = new FilterBuilder();
270
271     const pq = parseQuery(searchValue);
272
273     if (!pq.hasKeywords) {
274         filter
275             .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
276             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
277             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
278     } else {
279
280         if (pq.properties.type) {
281             pq.values.forEach(v => {
282                 let prefix = '';
283                 switch (ResourceKind[pq.properties.type]) {
284                     case ResourceKind.PROJECT:
285                         prefix = GroupContentsResourcePrefix.PROJECT;
286                         break;
287                     case ResourceKind.COLLECTION:
288                         prefix = GroupContentsResourcePrefix.COLLECTION;
289                         break;
290                     case ResourceKind.PROCESS:
291                         prefix = GroupContentsResourcePrefix.PROCESS;
292                         break;
293                 }
294                 if (prefix !== '') {
295                     filter.addILike(filterName, v, prefix);
296                 }
297             });
298         } else {
299             pq.values.forEach(v => {
300                 filter
301                     .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
302                     .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
303                     .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
304             });
305         }
306
307         if (pq.properties.is && pq.properties.is === 'trashed') {
308         }
309
310         if (pq.properties.project) {
311             filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
312         }
313
314         if (pq.properties.from) {
315             filter.addGte('modified_at', buildDateFilter(pq.properties.from));
316         }
317
318         if (pq.properties.to) {
319             filter.addLte('modified_at', buildDateFilter(pq.properties.to));
320         }
321         // filter
322         //     .addIsA("uuid", buildUuidFilter(resourceKind))
323         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
324         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
325         //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
326         //     .addLte('modified_at', buildDateFilter(dateTo))
327         //     .addGte('modified_at', buildDateFilter(dateFrom))
328         //     .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
329     }
330
331     return filter
332         .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
333         .getFilters();
334 };
335
336 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
337     return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
338 };
339
340 const buildDateFilter = (date?: string): string => {
341     return date ? date : '';
342 };
343
344 export const initAdvanceFormProjectsTree = () =>
345     (dispatch: Dispatch) => {
346         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
347     };
348
349 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
350     (dispatch: Dispatch) => {
351         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
352     };
353
354 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
355     (dispatch: Dispatch) => {
356         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
357     };
358
359 export const moveUp = () =>
360     (dispatch: Dispatch) => {
361         dispatch(searchBarActions.MOVE_UP());
362     };
363
364 export const moveDown = () =>
365     (dispatch: Dispatch) => {
366         dispatch(searchBarActions.MOVE_DOWN());
367     };