Fix showing undefined in chips if there's no value
[arvados-workbench2.git] / src / store / search-bar / search-bar-actions.ts
index 2ad9b2838a578b909491cf09f4580c3926980f06..9d1c6ace21021e3f7c587970a8d75900db0d14f3 100644 (file)
@@ -7,18 +7,19 @@ 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 { ResourceKind } from '~/models/resource';
 import { GroupClass } from '~/models/group';
 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 { ClusterObjectType, 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";
 
 export const searchBarActions = unionize({
     SET_CURRENT_VIEW: ofType<string>(),
@@ -80,13 +81,24 @@ export const searchAdvanceData = (data: SearchBarAdvanceFormData) =>
 
 export const setSearchValueFromAdvancedData = (data: SearchBarAdvanceFormData, prevData?: SearchBarAdvanceFormData) =>
     (dispatch: Dispatch, getState: () => RootState) => {
+        const searchValue = getState().searchBar.searchValue;
         const value = getQueryFromAdvancedData({
-            searchValue: getState().searchBar.searchValue,
-            ...data
+            ...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 savedQueries = services.searchService.getSavedQueries();
@@ -138,6 +150,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));
     };
 
@@ -155,7 +168,7 @@ export const changeData = (searchValue: string) =>
         const searchValuePresent = searchValue.length > 0;
 
         if (currentView === SearchView.ADVANCED) {
-
+            dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
         } else if (searchValuePresent) {
             dispatch(searchBarActions.SET_CURRENT_VIEW(SearchView.AUTOCOMPLETE));
             dispatch(searchBarActions.SET_SELECTED_ITEM(searchValue));
@@ -207,6 +220,14 @@ const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | '
 
     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}`
@@ -217,11 +238,6 @@ const buildQueryFromKeyMap = (data: any, keyMap: string[][], mode: 'rebuild' | '
             } else {
                 value = nv + ' ' + value;
             }
-        } else if (data.hasOwnProperty(key) && (v === undefined || v === false)) {
-            const pattern = v === false
-                ? `${field.replace(':', '\\:\\s*')}\\s*`
-                : `${field.replace(':', '\\:\\s*')}\\:\\s*[\\w|\\#|\\-|\\/]*`;
-            value = value.replace(new RegExp(pattern), '');
         }
     };
 
@@ -260,7 +276,6 @@ export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevDat
 
     if (prevData) {
         const obj = getModifiedKeysValues(flatData(data), flatData(prevData));
-        console.log(obj);
         value = buildQueryFromKeyMap({
             searchValue: data.searchValue,
             ...obj
@@ -273,7 +288,15 @@ export const getQueryFromAdvancedData = (data: SearchBarAdvanceFormData, prevDat
     return value;
 };
 
-export const parseQuery: (query: string) => { hasKeywords: boolean; values: string[]; properties: any } = (searchValue: string) => {
+export interface ParseSearchQuery {
+    hasKeywords: boolean;
+    values: string[];
+    properties: {
+        [key: string]: string[]
+    };
+}
+
+export const parseSearchQuery: (query: string) => ParseSearchQuery = (searchValue: string) => {
     const keywords = [
         'type:',
         'cluster:',
@@ -328,33 +351,33 @@ export const parseQuery: (query: string) => { hasKeywords: boolean; values: stri
     return { hasKeywords: keywordsCnt > 0, values, properties };
 };
 
+const getFirstProp = (sq: ParseSearchQuery, name: string) => sq.properties[name] && sq.properties[name][0];
+const getPropValue = (sq: ParseSearchQuery, name: string, value: string) => sq.properties[name] && sq.properties[name].find((v: string) => v === value);
+const getProperties = (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 = parseQuery(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: getFirstProp(sq, 'type') as ResourceKind,
+        cluster: getFirstProp(sq, 'cluster') as ClusterObjectType,
+        projectUuid: getFirstProp(sq, 'project'),
+        inTrash: getPropValue(sq, 'is', 'trashed') !== undefined,
+        dateFrom: getFirstProp(sq, 'from'),
+        dateTo: getFirstProp(sq, 'to'),
+        properties: getProperties(sq),
         saveQuery: false,
         queryName: ''
     };
@@ -362,36 +385,35 @@ export const getAdvancedDataFromQuery = (query: string): SearchBarAdvanceFormDat
 
 export const getFilters = (filterName: string, searchValue: string): string => {
     const filter = new FilterBuilder();
+    const sq = parseSearchQuery(searchValue);
+
+    const resourceKind = getFirstProp(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 = parseQuery(searchValue);
-
-    if (!pq.hasKeywords) {
+    if (!sq.hasKeywords) {
         filter
             .addILike(filterName, searchValue, GroupContentsResourcePrefix.COLLECTION)
             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROCESS)
             .addILike(filterName, searchValue, GroupContentsResourcePrefix.PROJECT);
     } else {
-
-        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 (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.PROCESS)
@@ -399,32 +421,35 @@ export const getFilters = (filterName: string, searchValue: string): string => {
             });
         }
 
-        if (pq.properties.is && pq.properties.is === 'trashed') {
+        if (getPropValue(sq, 'is', 'trashed')) {
+            filter.addEqual("is_trashed", true);
         }
 
-        if (pq.properties.project) {
-            filter.addEqual('owner_uuid', pq.properties.project, GroupContentsResourcePrefix.PROJECT);
+        const projectUuid = getFirstProp(sq, 'project');
+        if (projectUuid) {
+            filter.addEqual('uuid', projectUuid, prefix);
         }
 
-        if (pq.properties.from) {
-            filter.addGte('modified_at', buildDateFilter(pq.properties.from));
+        const dateFrom = getFirstProp(sq, 'from');
+        if (dateFrom) {
+            filter.addGte('modified_at', buildDateFilter(dateFrom));
         }
 
-        if (pq.properties.to) {
-            filter.addLte('modified_at', buildDateFilter(pq.properties.to));
+        const dateTo = getFirstProp(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 = getProperties(sq);
+        props.forEach(p => {
+            // filter.addILike(`properties.${p.key}`, p.value);
+            filter.addExists(p.key);
+        });
     }
 
     return filter
         .addEqual('groupClass', GroupClass.PROJECT, GroupContentsResourcePrefix.PROJECT)
+        .addIsA("uuid", buildUuidFilter(resourceKind))
         .getFilters();
 };
 
@@ -441,12 +466,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));
     };