15027: Fixes unused declarations errors.
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
index d6203d2f46d0c269f6cf56bb06b5e0c01c8a562b..e1551c23f89211876054cd1140457f1f3c7ef1fc 100644 (file)
@@ -2,22 +2,27 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import { unionize, ofType, UnionOf } from "~/common/unionize";
+import { ofType, unionize, UnionOf } from "~/common/unionize";
 import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/groups-service/groups-service';
 import { Dispatch } from 'redux';
-import { change, arrayPush } from 'redux-form';
+import { arrayPush, change, initialize } from 'redux-form';
 import { RootState } from '~/store/store';
-import { initUserProject } from '~/store/tree-picker/tree-picker-actions';
+import { initUserProject, treePickerActions } from '~/store/tree-picker/tree-picker-actions';
 import { ServiceRepository } from '~/services/services';
 import { FilterBuilder } from "~/services/api/filter-builder";
-import { ResourceKind } from '~/models/resource';
-import { GroupClass } from '~/models/group';
+import { ResourceKind, RESOURCE_UUID_REGEX, COLLECTION_PDH_REGEX } from '~/models/resource';
 import { SearchView } from '~/store/search-bar/search-bar-reducer';
-import { navigateToSearchResults, navigateTo } from '~/store/navigation/navigation-action';
+import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
-import { initialize } from 'redux-form';
-import { SearchBarAdvanceFormData, PropertyValues } from '~/models/search-bar';
-import { debounce } from 'debounce';
+import { PropertyValue, SearchBarAdvanceFormData } from '~/models/search-bar';
+import * as _ from "lodash";
+import { getModifiedKeysValues } from "~/common/objects";
+import { activateSearchBarProject } from "~/store/search-bar/search-bar-tree-actions";
+import { Session } from "~/models/session";
+import { searchResultsPanelActions } from "~/store/search-results-panel/search-results-panel-actions";
+import { ListResults } from "~/services/common-service/common-service";
+import * as parser from './search-query/arv-parser';
+import { Keywords } from './search-query/arv-parser';
 
 export const searchBarActions = unionize({
     SET_CURRENT_VIEW: ofType<string>(),
@@ -26,7 +31,12 @@ export const searchBarActions = unionize({
     SET_SEARCH_RESULTS: ofType<GroupContentsResource[]>(),
     SET_SEARCH_VALUE: ofType<string>(),
     SET_SAVED_QUERIES: ofType<SearchBarAdvanceFormData[]>(),
-    UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>()
+    SET_RECENT_QUERIES: ofType<string[]>(),
+    UPDATE_SAVED_QUERY: ofType<SearchBarAdvanceFormData[]>(),
+    SET_SELECTED_ITEM: ofType<string>(),
+    MOVE_UP: ofType<{}>(),
+    MOVE_DOWN: ofType<{}>(),
+    SELECT_FIRST_ITEM: ofType<{}>()
 });
 
 export type SearchBarActions = UnionOf<typeof searchBarActions>;
@@ -46,47 +56,68 @@ export const saveRecentQuery = (query: string) =>
 
 export const loadRecentQueries = () =>
     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
-        const recentSearchQueries = services.searchService.getRecentQueries();
-        return recentSearchQueries || [];
+        const recentQueries = services.searchService.getRecentQueries();
+        dispatch(searchBarActions.SET_RECENT_QUERIES(recentQueries));
+        return recentQueries;
     };
 
 export const searchData = (searchValue: string) =>
-    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+    async (dispatch: Dispatch, getState: () => RootState) => {
         const currentView = getState().searchBar.currentView;
+        dispatch(searchResultsPanelActions.CLEAR());
         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
-        dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
-        dispatch<any>(searchGroups(searchValue, 5, {}));
-        if (currentView === SearchView.BASIC) {
-            dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
-            dispatch(navigateToSearchResults);
+        if (searchValue.length > 0) {
+            dispatch<any>(searchGroups(searchValue, 5));
+            if (currentView === SearchView.BASIC) {
+                dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
+                dispatch(navigateToSearchResults);
+            }
         }
-
     };
 
 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
-    async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
-        const searchValue = getState().searchBar.searchValue;
+    async (dispatch: Dispatch) => {
         dispatch<any>(saveQuery(data));
-        dispatch<any>(searchGroups(searchValue, 100, data));
+        dispatch(searchResultsPanelActions.CLEAR());
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
         dispatch(navigateToSearchResults);
     };
 
-// Todo: create ids for particular searchQuery
+export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
+    (dispatch: Dispatch, getState: () => RootState) => {
+        const searchValue = getState().searchBar.searchValue;
+        const value = getQueryFromAdvancedData({
+            ...data,
+            searchValue
+        }, prevData);
+        dispatch(searchBarActions.SET_SEARCH_VALUE(value));
+    };
+
+export const setAdvancedDataFromSearchValue = (search: string) =>
+    async (dispatch: Dispatch) => {
+        const data = getAdvancedDataFromQuery(search);
+        dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
+        if (data.projectUuid) {
+            await dispatch<any>(activateSearchBarProject(data.projectUuid));
+            dispatch(treePickerActions.ACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID, id: data.projectUuid }));
+        }
+    };
+
 const saveQuery = (data: SearchBarAdvanceFormData) =>
     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
-        const savedSearchQueries = services.searchService.getSavedQueries();
-        const filteredQuery = savedSearchQueries.find(query => query.searchQuery === data.searchQuery);
-        if (data.saveQuery && data.searchQuery) {
+        const savedQueries = services.searchService.getSavedQueries();
+        if (data.saveQuery && data.queryName) {
+            const filteredQuery = savedQueries.find(query => query.queryName === data.queryName);
+            data.searchValue = getState().searchBar.searchValue;
             if (filteredQuery) {
                 services.searchService.editSavedQueries(data);
-                dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedSearchQueries));
-                dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been sucessfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
+                dispatch(searchBarActions.UPDATE_SAVED_QUERY(savedQueries));
+                dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully updated', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
             } else {
                 services.searchService.saveQuery(data);
-                dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
-                dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been sucessfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
+                dispatch(searchBarActions.SET_SAVED_QUERIES(savedQueries));
+                dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Query has been successfully saved', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
             }
         }
     };
@@ -100,109 +131,224 @@ export const deleteSavedQuery = (id: number) =>
     };
 
 export const editSavedQuery = (data: SearchBarAdvanceFormData) =>
-    (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.ADVANCED));
-        dispatch(searchBarActions.SET_SEARCH_VALUE(data.searchQuery));
+        dispatch(searchBarActions.SET_SEARCH_VALUE(getQueryFromAdvancedData(data)));
         dispatch<any>(initialize(SEARCH_BAR_ADVANCE_FORM_NAME, data));
     };
 
 export const openSearchView = () =>
     (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
-        dispatch(searchBarActions.OPEN_SEARCH_VIEW());
         const savedSearchQueries = services.searchService.getSavedQueries();
         dispatch(searchBarActions.SET_SAVED_QUERIES(savedSearchQueries));
+        dispatch(loadRecentQueries());
+        dispatch(searchBarActions.OPEN_SEARCH_VIEW());
+        dispatch(searchBarActions.SELECT_FIRST_ITEM());
     };
 
 export const closeSearchView = () =>
-    (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
-        const isOpen = getState().searchBar.open;
-        if (isOpen) {
-            dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
-            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
-        }
+    (dispatch: Dispatch<any>) => {
+        dispatch(searchBarActions.SET_SELECTED_ITEM(''));
+        dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
     };
 
 export const closeAdvanceView = () =>
-    (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch<any>) => {
         dispatch(searchBarActions.SET_SEARCH_VALUE(''));
+        dispatch(treePickerActions.DEACTIVATE_TREE_PICKER_NODE({ pickerId: SEARCH_BAR_ADVANCE_FORM_PICKER_ID }));
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
     };
 
 export const navigateToItem = (uuid: string) =>
-    (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch<any>) => {
+        dispatch(searchBarActions.SET_SELECTED_ITEM(''));
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
         dispatch(navigateTo(uuid));
     };
 
 export const changeData = (searchValue: string) =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch, getState: () => RootState) => {
         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
         const currentView = getState().searchBar.currentView;
         const searchValuePresent = searchValue.length > 0;
 
         if (currentView === SearchView.ADVANCED) {
-
+            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
         } else if (searchValuePresent) {
-            dispatch<any>(goToView(SearchView.AUTOCOMPLETE));
-            debounceStartSearch(dispatch);
+            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
+            dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
         } else {
-            dispatch<any>(goToView(SearchView.BASIC));
-            dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
+            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
             dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
+            dispatch(searchBarActions.SELECT_FIRST_ITEM());
         }
     };
 
 export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch, getState: () => RootState) => {
         event.preventDefault();
         const searchValue = getState().searchBar.searchValue;
         dispatch<any>(saveRecentQuery(searchValue));
-        dispatch<any>(searchDataOnEnter(searchValue));
         dispatch<any>(loadRecentQueries());
-    };
-
-const searchDataOnEnter = (searchValue: string) =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
-        dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
-        dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
-        dispatch<any>(searchGroups(searchValue, 100, {}));
-        dispatch(navigateToSearchResults);
+        if (RESOURCE_UUID_REGEX.exec(searchValue) || COLLECTION_PDH_REGEX.exec(searchValue)) {
+            dispatch<any>(navigateTo(searchValue));
+        } else {
+            dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
+            dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
+            dispatch(searchResultsPanelActions.CLEAR());
+            dispatch(navigateToSearchResults);
+        }
     };
 
-const debounceStartSearch = debounce((dispatch: Dispatch) => dispatch<any>(startSearch()), DEFAULT_SEARCH_DEBOUNCE);
-
-const startSearch = () =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
-        const searchValue = getState().searchBar.searchValue;
-        dispatch<any>(searchData(searchValue));
-    };
 
-const searchGroups = (searchValue: string, limit: number, {...props}) =>
+const searchGroups = (searchValue: string, limit: number) =>
     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
         const currentView = getState().searchBar.currentView;
 
         if (searchValue || currentView === SearchView.ADVANCED) {
-            const filters = getFilters('name', searchValue, props);
-            const { items } = await services.groupsService.contents('', {
-                filters,
-                limit,
-                recursive: true
-            });
+            const { cluster: clusterId } = getAdvancedDataFromQuery(searchValue);
+            const sessions = getSearchSessions(clusterId, getState().auth.sessions);
+            const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
+                const filters = queryToFilters(searchValue);
+                return services.groupsService.contents('', {
+                    filters,
+                    limit,
+                    recursive: true
+                }, session);
+            }));
+
+            const items = lists.reduce((items, list) => items.concat(list.items), [] as GroupContentsResource[]);
             dispatch(searchBarActions.SET_SEARCH_RESULTS(items));
         }
     };
 
-export const getFilters = (filterName: string, searchValue: string, {...props}): string => {
-    const { resourceKind, dateTo, dateFrom } = props;
-    return new FilterBuilder()
+const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
+    let value = data.searchValue;
+
+    const addRem = (field: string, key: string) => {
+        const v = data[key];
+
+        if (data.hasOwnProperty(key)) {
+            const pattern = v === false
+                ? `${field.replace(':', '\\:\\s*')}\\s*`
+                : `${field.replace(':', '\\:\\s*')}\\:\\s*"[\\w|\\#|\\-|\\/]*"\\s*`;
+            value = value.replace(new RegExp(pattern), '');
+        }
+
+        if (v) {
+            const nv = v === true
+                ? `${field}`
+                : `${field}:${v}`;
+
+            if (mode === 'rebuild') {
+                value = value + ' ' + nv;
+            } else {
+                value = nv + ' ' + value;
+            }
+        }
+    };
+
+    keyMap.forEach(km => addRem(km[0], km[1]));
+
+    return value;
+};
+
+export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) => {
+    let value = '';
+
+    const flatData = (data: SearchBarAdvanceFormData) => {
+        const fo = {
+            searchValue: data.searchValue,
+            type: data.type,
+            cluster: data.cluster,
+            projectUuid: data.projectUuid,
+            inTrash: data.inTrash,
+            dateFrom: data.dateFrom,
+            dateTo: data.dateTo,
+        };
+        (data.properties || []).forEach(p => fo[`prop-"${p.key}"`] = `"${p.value}"`);
+        return fo;
+    };
+
+    const keyMap = [
+        ['type', 'type'],
+        ['cluster', 'cluster'],
+        ['project', 'projectUuid'],
+        [`is:${parser.States.TRASHED}`, 'inTrash'],
+        ['from', 'dateFrom'],
+        ['to', 'dateTo']
+    ];
+    _.union(data.properties, prevData ? prevData.properties : [])
+        .forEach(p => keyMap.push([`has:"${p.key}"`, `prop-"${p.key}"`]));
+
+    if (prevData) {
+        const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
+        value = buildQueryFromKeyMap({
+            searchValue: data.searchValue,
+            ...obj
+        } as SearchBarAdvanceFormData, keyMap, "reuse");
+    } else {
+        value = buildQueryFromKeyMap(flatData(data), keyMap, "rebuild");
+    }
+
+    value = value.trim();
+    return value;
+};
+
+export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
+    const { tokens, searchString } = parser.parseSearchQuery(query);
+    const getValue = parser.getValue(tokens);
+    return {
+        searchValue: searchString,
+        type: getValue(Keywords.TYPE) as ResourceKind,
+        cluster: getValue(Keywords.CLUSTER),
+        projectUuid: getValue(Keywords.PROJECT),
+        inTrash: parser.isTrashed(tokens),
+        dateFrom: getValue(Keywords.FROM) || '',
+        dateTo: getValue(Keywords.TO) || '',
+        properties: parser.getProperties(tokens),
+        saveQuery: false,
+        queryName: ''
+    };
+};
+
+export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
+    return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
+};
+
+export const queryToFilters = (query: string) => {
+    const data = getAdvancedDataFromQuery(query);
+    const filter = new FilterBuilder();
+    const resourceKind = data.type;
+
+    if (data.searchValue) {
+        filter.addFullTextSearch(data.searchValue);
+    }
+
+    if (data.projectUuid) {
+        filter.addEqual('ownerUuid', data.projectUuid);
+    }
+
+    if (data.dateFrom) {
+        filter.addGte('modified_at', buildDateFilter(data.dateFrom));
+    }
+
+    if (data.dateTo) {
+        filter.addLte('modified_at', buildDateFilter(data.dateTo));
+    }
+
+    data.properties.forEach(p => {
+        if (p.value) {
+            filter
+                .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.PROJECT)
+                .addILike(`properties.${p.key}`, p.value, GroupContentsResourcePrefix.COLLECTION);
+        }
+        filter.addExists(p.key);
+    });
+
+    return filter
         .addIsA("uuid", buildUuidFilter(resourceKind))
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
-        .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
-        .addLte('created_at', buildDateFilter(dateTo))
-        .addGte('created_at', buildDateFilter(dateFrom))
-        .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
         .getFilters();
 };
 
@@ -215,16 +361,26 @@ const buildDateFilter = (date?: string): string => {
 };
 
 export const initAdvanceFormProjectsTree = () =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+    (dispatch: Dispatch) => {
         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
     };
 
-export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
+    (dispatch: Dispatch) => {
         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
     };
 
-export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
-    (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
+export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
+    (dispatch: Dispatch) => {
         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
-    };
\ No newline at end of file
+    };
+
+export const moveUp = () =>
+    (dispatch: Dispatch) => {
+        dispatch(searchBarActions.MOVE_UP());
+    };
+
+export const moveDown = () =>
+    (dispatch: Dispatch) => {
+        dispatch(searchBarActions.MOVE_DOWN());
+    };