1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
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<{}>()
38 export type SearchBarActions = UnionOf<typeof searchBarActions>;
40 export const SEARCH_BAR_ADVANCE_FORM_NAME = 'searchBarAdvanceFormName';
42 export const SEARCH_BAR_ADVANCE_FORM_PICKER_ID = 'searchBarAdvanceFormPickerId';
44 export const DEFAULT_SEARCH_DEBOUNCE = 1000;
46 export const goToView = (currentView: string) => searchBarActions.SET_CURRENT_VIEW(currentView);
48 export const saveRecentQuery = (query: string) =>
49 (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) =>
50 services.searchService.saveRecentQuery(query);
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));
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);
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);
81 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
82 (dispatch: Dispatch, getState: () => RootState) => {
83 const value = getQueryFromAdvancedData({
84 searchValue: getState().searchBar.searchValue,
87 dispatch(searchBarActions.SET_SEARCH_VALUE(value));
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;
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 }));
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 }));
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 || [];
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));
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());
132 export const closeSearchView = () =>
133 (dispatch: Dispatch<any>) => {
134 dispatch(searchBarActions.SET_SELECTED_ITEM(''));
135 dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
138 export const closeAdvanceView = () =>
139 (dispatch: Dispatch<any>) => {
140 dispatch(searchBarActions.SET_SEARCH_VALUE(''));
141 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
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));
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;
157 if (currentView === SearchView.ADVANCED) {
159 } else if (searchValuePresent) {
160 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
161 dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
162 debounceStartSearch(dispatch);
164 dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
165 dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
166 dispatch(searchBarActions.SELECT_FIRST_ITEM());
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);
182 const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
184 const startSearch = () =>
185 (dispatch: Dispatch, getState: () => RootState) => {
186 const searchValue = getState().searchBar.searchValue;
187 dispatch<any>(searchData(searchValue));
190 const searchGroups = (searchValue: string, limit: number) =>
191 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
192 const currentView = getState().searchBar.currentView;
194 if (searchValue || currentView === SearchView.ADVANCED) {
195 const filters = getFilters('name', searchValue);
196 const { items } = await services.groupsService.contents('', {
201 dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
205 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
206 let value = data.searchValue;
208 const addRem = (field: string, key: string) => {
211 const nv = v === true
215 if (mode === 'rebuild') {
216 value = value + ' ' + nv;
218 value = nv + ' ' + value;
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), '');
228 keyMap.forEach(km => addRem(km[0], km[1]));
233 export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
236 const flatData = (data: SearchBarAdvanceFormData) => {
238 searchValue: data.searchValue,
240 cluster: data.cluster,
241 projectUuid: data.projectUuid,
242 inTrash: data.inTrash,
243 dateFrom: data.dateFrom,
246 (data.properties || []).forEach(p => fo[`prop-${p.key}`] = p.value);
252 ['cluster', 'cluster'],
253 ['project', 'projectUuid'],
254 ['is:trashed', 'inTrash'],
255 ['from', 'dateFrom'],
258 _.union(data.properties, prevData ? prevData.properties : [])
259 .forEach(p => keyMap.push([`has:${p.key}`, `prop-${p.key}`]));
262 const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
264 value = buildQueryFromKeyMap({
265 searchValue: data.searchValue,
267 } as SearchBarAdvanceFormData, keyMap, "reuse");
269 value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
272 value = value.trim();
276 export const parseQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string) => {
287 const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
290 const properties = {};
292 keywords.forEach(k => {
293 let p = searchValue.indexOf(k);
294 const key = k.substr(0, k.length - 1);
297 const l = searchValue.length;
301 let i = p + k.length;
302 while (i < l && searchValue[i] === ' ') {
306 while (i < l && searchValue[i] !== ' ') {
311 if (hasKeywords(v)) {
312 searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
315 if (!properties[key]) {
316 properties[key] = [];
318 properties[key].push(v);
320 searchValue = searchValue.substr(0, p) + searchValue.substr(i);
322 p = searchValue.indexOf(k);
326 const values = _.uniq(searchValue.split(' ').filter(v => v.length > 0));
328 return { hasKeywords: keywordsCnt > 0, values, properties };
331 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
332 const r = parseQuery(query);
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(':');
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(),
363 export const getFilters = (filterName: string, searchValue: string): string => {
364 const filter = new FilterBuilder();
366 const pq = parseQuery(searchValue);
368 if (!pq.hasKeywords) {
370 .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
371 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
372 .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
375 if (pq.properties.type) {
376 pq.values.forEach(v => {
378 switch (ResourceKind[pq.properties.type]) {
379 case ResourceKind.PROJECT:
380 prefix = GroupContentsResourcePrefix.PROJECT;
382 case ResourceKind.COLLECTION:
383 prefix = GroupContentsResourcePrefix.COLLECTION;
385 case ResourceKind.PROCESS:
386 prefix = GroupContentsResourcePrefix.PROCESS;
390 filter.addILike(filterName, v, prefix);
394 pq.values.forEach(v => {
396 .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
397 .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
398 .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
402 if (pq.properties.is && pq.properties.is === 'trashed') {
405 if (pq.properties.project) {
406 filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
409 if (pq.properties.from) {
410 filter.addGte('modified_at', buildDateFilter(pq.properties.from));
413 if (pq.properties.to) {
414 filter.addLte('modified_at', buildDateFilter(pq.properties.to));
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)
427 .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
431 const buildUuidFilter = (type?: ResourceKind): ResourceKind[] => {
432 return type ? [type] : [ResourceKind.PROJECT, ResourceKind.COLLECTION, ResourceKind.PROCESS];
435 const buildDateFilter = (date?: string): string => {
436 return date ? date : '';
439 export const initAdvanceFormProjectsTree = () =>
440 (dispatch: Dispatch) => {
441 dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
444 export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
445 (dispatch: Dispatch) => {
446 dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
449 export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
450 (dispatch: Dispatch) => {
451 dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
454 export const moveUp = () =>
455 (dispatch: Dispatch) => {
456 dispatch(searchBarActions.MOVE_UP());
459 export const moveDown = () =>
460 (dispatch: Dispatch) => {
461 dispatch(searchBarActions.MOVE_DOWN());