Merge branch '14772-gloabal-search-is-unable-to-find-projects-or-collections-only...
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
index a2eed93a2149c3a33feffc18b2c2fc7faa55b654..01a0311ec34eb27cc155223548f465e686d3c2c0 100644 (file)
@@ -7,18 +7,21 @@ import { GroupContentsResource, GroupContentsResourcePrefix } from '~/services/g
 import { Dispatch } from 'redux';
 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 { getResourceKind, ResourceKind } from '~/models/resource';
-import { GroupClass } from '~/models/group';
+import { ResourceKind, isResourceUuid, extractUuidKind } from '~/models/resource';
 import { SearchView } from '~/store/search-bar/search-bar-reducer';
 import { navigateTo, navigateToSearchResults } from '~/store/navigation/navigation-action';
 import { snackbarActions, SnackbarKind } from '~/store/snackbar/snackbar-actions';
-import { getClusterObjectType, PropertyValues, SearchBarAdvanceFormData } from '~/models/search-bar';
+import { PropertyValue, SearchBarAdvanceFormData } from '~/models/search-bar';
 import { debounce } from 'debounce';
 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";
 
 export const searchBarActions = unionize({
     SET_CURRENT_VIEW: ofType<string>(),
@@ -60,6 +63,7 @@ export const loadRecentQueries = () =>
 export const searchData = (searchValue: string) =>
     async (dispatch: Dispatch, getState: () => RootState) => {
         const currentView = getState().searchBar.currentView;
+        dispatch(searchResultsPanelActions.CLEAR());
         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
         if (searchValue.length > 0) {
             dispatch<any>(searchGroups(searchValue, 5));
@@ -73,6 +77,7 @@ export const searchData = (searchValue: string) =>
 export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
     async (dispatch: Dispatch) => {
         dispatch<any>(saveQuery(data));
+        dispatch(searchResultsPanelActions.CLEAR());
         dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.BASIC));
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
         dispatch(navigateToSearchResults);
@@ -89,9 +94,13 @@ export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, p
     };
 
 export const setAdvancedDataFromSearchValue = (search: string) =>
-    (dispatch: Dispatch) => {
+    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) =>
@@ -145,6 +154,7 @@ export const closeSearchView = () =>
 export const closeAdvanceView = () =>
     (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));
     };
 
@@ -183,6 +193,7 @@ export const submitData = (event: React.FormEvent<HTMLFormElement>) =>
         dispatch(searchBarActions.CLOSE_SEARCH_VIEW());
         dispatch(searchBarActions.SET_SEARCH_VALUE(searchValue));
         dispatch(searchBarActions.SET_SEARCH_RESULTS([]));
+        dispatch(searchResultsPanelActions.CLEAR());
         dispatch(navigateToSearchResults);
     };
 
@@ -199,12 +210,19 @@ const searchGroups = (searchValue: string, limit: number) =>
         const currentView = getState().searchBar.currentView;
 
         if (searchValue || currentView === SearchView.ADVANCED) {
-            const filters = getFilters('name', searchValue);
-            const { items } = await services.groupsService.contents('', {
-                filters,
-                limit,
-                recursive: true
-            });
+            const sq = parseSearchQuery(searchValue);
+            const clusterId = getSearchQueryFirstProp(sq, 'cluster');
+            const sessions = getSearchSessions(clusterId, getState().auth.sessions);
+            const lists: ListResults<GroupContentsResource>[] = await Promise.all(sessions.map(session => {
+                const filters = getFilters('name', searchValue, sq);
+                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));
         }
     };
@@ -212,9 +230,6 @@ const searchGroups = (searchValue: string, limit: number) =>
 const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | 'reuse') => {
     let value = data.searchValue;
 
-    const rem = (field: string, fieldValue: any, value: string) => {
-    };
-
     const addRem = (field: string, key: string) => {
         const v = data[key];
 
@@ -285,15 +300,15 @@ export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevDat
     return value;
 };
 
-export interface ParsedSearchQuery {
+export class ParseSearchQuery {
     hasKeywords: boolean;
     values: string[];
     properties: {
-        [key: string]: string
+        [key: string]: string[]
     };
 }
 
-export const parseSearchQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string): ParsedSearchQuery => {
+export const parseSearchQuery: (query: string) => ParseSearchQuery = (searchValue: string) => {
     const keywords = [
         'type:',
         'cluster:',
@@ -304,42 +319,44 @@ export const parseSearchQuery: (query: string) => { hasKeywords: boolean; values
         'has:'
     ];
 
-    const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + search.indexOf(keyword) >= 0 ? 1 : 0, 0);
+    const hasKeywords = (search: string) => keywords.reduce((acc, keyword) => acc + (search.includes(keyword) ? 1 : 0), 0);
     let keywordsCnt = 0;
 
     const properties = {};
 
     keywords.forEach(k => {
-        let p = searchValue.indexOf(k);
-        const key = k.substr(0, k.length - 1);
-
-        while (p >= 0) {
-            const l = searchValue.length;
-            keywordsCnt += 1;
-
-            let v = '';
-            let i = p + k.length;
-            while (i < l && searchValue[i] === ' ') {
-                ++i;
-            }
-            const vp = i;
-            while (i < l && searchValue[i] !== ' ') {
-                v += searchValue[i];
-                ++i;
-            }
+        if (k) {
+            let p = searchValue.indexOf(k);
+            const key = k.substr(0, k.length - 1);
+
+            while (p >= 0) {
+                const l = searchValue.length;
+                keywordsCnt += 1;
+
+                let v = '';
+                let i = p + k.length;
+                while (i < l && searchValue[i] === ' ') {
+                    ++i;
+                }
+                const vp = i;
+                while (i < l && searchValue[i] !== ' ') {
+                    v += searchValue[i];
+                    ++i;
+                }
 
-            if (hasKeywords(v)) {
-                searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
-            } else {
-                if (v !== '') {
-                    if (!properties[key]) {
-                        properties[key] = [];
+                if (hasKeywords(v)) {
+                    searchValue = searchValue.substr(0, p) + searchValue.substr(vp);
+                } else {
+                    if (v !== '') {
+                        if (!properties[key]) {
+                            properties[key] = [];
+                        }
+                        properties[key].push(v);
                     }
-                    properties[key].push(v);
+                    searchValue = searchValue.substr(0, p) + searchValue.substr(i);
                 }
-                searchValue = searchValue.substr(0, p) + searchValue.substr(i);
+                p = searchValue.indexOf(k);
             }
-            p = searchValue.indexOf(k);
         }
     });
 
@@ -348,103 +365,144 @@ export const parseSearchQuery: (query: string) => { hasKeywords: boolean; values
     return { hasKeywords: keywordsCnt > 0, values, properties };
 };
 
+export const getSearchQueryFirstProp = (sq: ParseSearchQuery, name: string) => sq.properties[name] && sq.properties[name][0];
+export const getSearchQueryPropValue = (sq: ParseSearchQuery, name: string, value: string) => sq.properties[name] && sq.properties[name].find((v: string) => v === value);
+export const getSearchQueryProperties = (sq: ParseSearchQuery): PropertyValue[] => {
+    if (sq.properties.has) {
+        return sq.properties.has.map((value: string) => {
+            const v = value.split(':');
+            return {
+                key: v[0],
+                value: v[1]
+            };
+        });
+    }
+    return [];
+};
+
 export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormData => {
-    const r = parseSearchQuery(query);
-
-    const getFirstProp = (name: string) => r.properties[name] && r.properties[name][0];
-    const getPropValue = (name: string, value: string) => r.properties[name] && r.properties[name].find((v: string) => v === value);
-    const getProperties = () => {
-        if (r.properties.has) {
-            return r.properties.has.map((value: string) => {
-                const v = value.split(':');
-                return {
-                    key: v[0],
-                    value: v[1]
-                };
-            });
-        }
-        return [];
-    };
+    const sq = parseSearchQuery(query);
 
     return {
-        searchValue: r.values.join(' '),
-        type: getResourceKind(getFirstProp('type')),
-        cluster: getClusterObjectType(getFirstProp('cluster')),
-        projectUuid: getFirstProp('project'),
-        inTrash: getPropValue('is', 'trashed') !== undefined,
-        dateFrom: getFirstProp('from'),
-        dateTo: getFirstProp('to'),
-        properties: getProperties(),
+        searchValue: sq.values.join(' '),
+        type: getSearchQueryFirstProp(sq, 'type') as ResourceKind,
+        cluster: getSearchQueryFirstProp(sq, 'cluster'),
+        projectUuid: getSearchQueryFirstProp(sq, 'project'),
+        inTrash: getSearchQueryPropValue(sq, 'is', 'trashed') !== undefined,
+        dateFrom: getSearchQueryFirstProp(sq, 'from'),
+        dateTo: getSearchQueryFirstProp(sq, 'to'),
+        properties: getSearchQueryProperties(sq),
         saveQuery: false,
         queryName: ''
     };
 };
 
-export const getFilters = (filterName: string, searchValue: string): string => {
+export const getSearchSessions = (clusterId: string | undefined, sessions: Session[]): Session[] => {
+    return sessions.filter(s => s.loggedIn && (!clusterId || s.clusterId === clusterId));
+};
+
+export const getFilters = (filterName: string, searchValue: string, sq: ParseSearchQuery): string => {
     const filter = new FilterBuilder();
+    const isSearchQueryUuid = isResourceUuid(sq.values[0]);
+    const resourceKind = getSearchQueryFirstProp(sq, 'type') as ResourceKind; 
+
+    let prefix = '';
+    switch (resourceKind) {
+        case ResourceKind.COLLECTION:
+            prefix = GroupContentsResourcePrefix.COLLECTION;
+            break;
+        case ResourceKind.PROCESS:
+            prefix = GroupContentsResourcePrefix.PROCESS;
+            break;
+        default:
+            prefix = GroupContentsResourcePrefix.PROJECT;
+            break;
+    }
 
-    const pq = parseSearchQuery(searchValue);
+    const isTrashed = getSearchQueryPropValue(sq, 'is', 'trashed');
 
-    if (!pq.hasKeywords) {
+    if (!sq.hasKeywords && !isSearchQueryUuid) {
         filter
             .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
+            .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
-            .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
-    } else {
+            .addEqual('is_trashed', false, GroupContentsResourcePrefix.COLLECTION)
+            .addEqual('is_trashed', false, GroupContentsResourcePrefix.PROJECT);
 
-        if (pq.properties.type) {
-            pq.values.forEach(v => {
-                let prefix = '';
-                switch (ResourceKind[pq.properties.type]) {
-                    case ResourceKind.PROJECT:
-                        prefix = GroupContentsResourcePrefix.PROJECT;
-                        break;
-                    case ResourceKind.COLLECTION:
-                        prefix = GroupContentsResourcePrefix.COLLECTION;
-                        break;
-                    case ResourceKind.PROCESS:
-                        prefix = GroupContentsResourcePrefix.PROCESS;
-                        break;
-                }
-                if (prefix !== '') {
-                    filter.addILike(filterName, v, prefix);
-                }
-            });
+        if (isTrashed) {
+            filter.addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS);
+        }
+    } else if (!sq.hasKeywords && isSearchQueryUuid) {
+        filter
+            .addILike('uuid', searchValue, GroupContentsResourcePrefix.COLLECTION)
+            .addILike('uuid', searchValue, GroupContentsResourcePrefix.PROJECT)
+            .addILike('uuid', searchValue, GroupContentsResourcePrefix.PROCESS)
+            .addEqual('is_trashed', false, GroupContentsResourcePrefix.COLLECTION)
+            .addEqual('is_trashed', false, GroupContentsResourcePrefix.PROJECT);
+    }
+    else {
+        if (prefix) {
+            sq.values.forEach(v =>
+                filter.addILike(filterName, v, prefix)
+            );
         } else {
-            pq.values.forEach(v => {
+            sq.values.forEach(v => {
                 filter
                     .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
+                    .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT)
                     .addILike(filterName, v, GroupContentsResourcePrefix.PROCESS)
-                    .addILike(filterName, v, GroupContentsResourcePrefix.PROJECT);
+                    .addEqual('is_trashed', false, GroupContentsResourcePrefix.COLLECTION)
+                    .addEqual('is_trashed', false, GroupContentsResourcePrefix.PROJECT);
+
+                if (isTrashed) {
+                    filter.addILike(filterName, v, GroupContentsResourcePrefix.PROCESS);
+                }
             });
         }
+        if (prefix && !isTrashed) {
+            sq.values.forEach(v =>
+                filter.addILike(filterName, v, prefix)
+                    .addEqual('is_trashed', false, GroupContentsResourcePrefix.COLLECTION)
+                    .addEqual('is_trashed', false, GroupContentsResourcePrefix.PROJECT)
+            );
+        }
 
-        if (pq.properties.is && pq.properties.is === 'trashed') {
+        if (isTrashed) {
+            sq.values.forEach(v => {
+                filter.addEqual('is_trashed', true, GroupContentsResourcePrefix.COLLECTION)
+                    .addEqual('is_trashed', true, GroupContentsResourcePrefix.PROJECT)
+                    .addILike(filterName, v, GroupContentsResourcePrefix.COLLECTION)
+                    .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS);
+            });
         }
 
-        if (pq.properties.project) {
-            filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
+        const projectUuid = getSearchQueryFirstProp(sq, 'project');
+        if (projectUuid) {
+            filter.addEqual('uuid', projectUuid, prefix);
         }
 
-        if (pq.properties.from) {
-            filter.addGte('modified_at', buildDateFilter(pq.properties.from));
+        const dateFrom = getSearchQueryFirstProp(sq, 'from');
+        if (dateFrom) {
+            filter.addGte('modified_at', buildDateFilter(dateFrom));
         }
 
-        if (pq.properties.to) {
-            filter.addLte('modified_at', buildDateFilter(pq.properties.to));
+        const dateTo = getSearchQueryFirstProp(sq, 'to');
+        if (dateTo) {
+            filter.addLte('modified_at', buildDateFilter(dateTo));
         }
-        // filter
-        //     .addIsA("uuid", buildUuidFilter(resourceKind))
-        //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
-        //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
-        //     .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT)
-        //     .addLte('modified_at', buildDateFilter(dateTo))
-        //     .addGte('modified_at', buildDateFilter(dateFrom))
-        //     .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
+
+        const props = getSearchQueryProperties(sq);
+        props.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
-        .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
+        .addIsA("uuid", buildUuidFilter(resourceKind))
         .getFilters();
 };
 
@@ -461,12 +519,12 @@ export const initAdvanceFormProjectsTree = () =>
         dispatch<any>(initUserProject(SEARCH_BAR_ADVANCE_FORM_PICKER_ID));
     };
 
-export const changeAdvanceFormProperty = (property: string, value: PropertyValues[] | string = '') =>
+export const changeAdvanceFormProperty = (property: string, value: PropertyValue[] | string = '') =>
     (dispatch: Dispatch) => {
         dispatch(change(SEARCH_BAR_ADVANCE_FORM_NAME, property, value));
     };
 
-export const updateAdvanceFormProperties = (propertyValues: PropertyValues) =>
+export const updateAdvanceFormProperties = (propertyValues: PropertyValue) =>
     (dispatch: Dispatch) => {
         dispatch(arrayPush(SEARCH_BAR_ADVANCE_FORM_NAME, 'properties', propertyValues));
     };