SearchLayoutView.js 28.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(['require',
    'backbone',
    'hbs!tmpl/search/SearchLayoutView_tmpl',
    'utils/Utils',
23 24
    'utils/UrlLinks',
    'utils/Globals',
25
    'collection/VSearchList',
26
    'utils/CommonViewFunction'
27
], function(require, Backbone, SearchLayoutViewTmpl, Utils, UrlLinks, Globals, VSearchList, CommonViewFunction) {
28 29 30 31 32 33 34 35 36 37
    'use strict';

    var SearchLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends SearchLayoutView */
        {
            _viewName: 'SearchLayoutView',

            template: SearchLayoutViewTmpl,

            /** Layout sub regions */
38 39 40 41
            regions: {
                RSaveSearchBasic: "[data-id='r_saveSearchBasic']",
                RSaveSearchAdvance: "[data-id='r_saveSearchAdvance']"
            },
42 43 44 45

            /** ui selector cache */
            ui: {
                searchInput: '[data-id="searchInput"]',
46 47
                searchType: 'input[name="queryType"]',
                searchBtn: '[data-id="searchBtn"]',
48
                clearSearch: '[data-id="clearSearch"]',
49
                typeLov: '[data-id="typeLOV"]',
50 51
                tagLov: '[data-id="tagLOV"]',
                refreshBtn: '[data-id="refreshBtn"]',
52 53 54
                advancedInfoBtn: '[data-id="advancedInfo"]',
                typeAttrFilter: '[data-id="typeAttrFilter"]',
                tagAttrFilter: '[data-id="tagAttrFilter"]'
55 56
            },

57 58 59 60 61 62
            /** ui events hash */
            events: function() {
                var events = {},
                    that = this;
                events["keyup " + this.ui.searchInput] = function(e) {
                    var code = e.which;
63
                    this.value.query = e.currentTarget.value;
64
                    if (code == 13) {
65
                        that.findSearchResult();
66
                    }
67
                    this.checkForButtonVisiblity();
68
                };
69 70 71
                events["change " + this.ui.searchType] = 'dslFulltextToggle';
                events["click " + this.ui.searchBtn] = 'findSearchResult';
                events["click " + this.ui.clearSearch] = 'clearSearchData';
72 73
                events["change " + this.ui.typeLov] = 'checkForButtonVisiblity';
                events["change " + this.ui.tagLov] = 'checkForButtonVisiblity';
74
                events["click " + this.ui.refreshBtn] = 'onRefreshButton';
75
                events["click " + this.ui.advancedInfoBtn] = 'advancedInfo';
76 77 78 79 80 81
                events["click " + this.ui.typeAttrFilter] = function() {
                    this.openAttrFilter('type');
                };
                events["click " + this.ui.tagAttrFilter] = function() {
                    this.openAttrFilter('tag');
                };
82 83 84 85 86 87 88
                return events;
            },
            /**
             * intialize a new SearchLayoutView Layout
             * @constructs
             */
            initialize: function(options) {
89
                _.extend(this, _.pick(options, 'value', 'typeHeaders', 'searchVent', 'entityDefCollection', 'enumDefCollection', 'classificationDefCollection', 'searchTableColumns', 'searchTableFilters'));
90
                this.type = "basic";
91 92 93
                var param = Utils.getUrlState.getQueryParams();
                this.query = {
                    dsl: {
94
                        query: null,
95 96 97
                        type: null,
                        pageOffset: null,
                        pageLimit: null
98
                    },
99
                    basic: {
100 101
                        query: null,
                        type: null,
102
                        tag: null,
103
                        attributes: null,
104
                        tagFilters: null,
105 106
                        pageOffset: null,
                        pageLimit: null,
107
                        entityFilters: null,
108
                        includeDE: null
109 110
                    }
                };
111 112 113
                if (!this.value) {
                    this.value = {};
                }
114
                this.dsl = false;
115
                if (param && param.searchType) {
116 117
                    this.type = param.searchType;
                    this.updateQueryObject(param);
118
                }
119
                this.bindEvents();
120
            },
121 122
            renderSaveSearch: function() {
                var that = this;
123
                require(['views/search/save/SaveSearchView'], function(SaveSearchView) {
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
                    var saveSearchBaiscCollection = new VSearchList(),
                        saveSearchAdvanceCollection = new VSearchList(),
                        saveSearchCollection = new VSearchList();
                    saveSearchCollection.url = UrlLinks.saveSearchApiUrl();
                    var obj = {
                        value: that.value,
                        searchVent: that.searchVent,
                        typeHeaders: that.typeHeaders,
                        fetchCollection: fetchSaveSearchCollection,
                        classificationDefCollection: that.classificationDefCollection,
                        entityDefCollection: that.entityDefCollection,
                        getValue: function() {
                            var queryObj = that.query[that.type],
                                entityObj = that.searchTableFilters['entityFilters'],
                                tagObj = that.searchTableFilters['tagFilters'],
                                urlObj = Utils.getUrlState.getQueryParams();
                            if (urlObj) {
141
                                // includeDE value in because we need to send "true","false" to the server.
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
                                if (urlObj.includeDE == "true") {
                                    urlObj.includeDE = true;
                                } else {
                                    urlObj.includeDE = false;
                                }
                            }
                            return _.extend({}, queryObj, urlObj, {
                                'entityFilters': entityObj ? entityObj[queryObj.type] : null,
                                'tagFilters': tagObj ? tagObj[queryObj.tag] : null,
                                'type': queryObj.type,
                                'query': queryObj.query,
                                'tag': queryObj.tag
                            })
                        },
                        applyValue: function(model, searchType) {
                            that.manualRender(_.extend(searchType, CommonViewFunction.generateUrlFromSaveSearchObject({
                                value: model.get('searchParameters'),
                                classificationDefCollection: that.classificationDefCollection,
                                entityDefCollection: that.entityDefCollection
                            })));
                        }
                    }
                    that.RSaveSearchBasic.show(new SaveSearchView(_.extend(obj, {
                        isBasic: true,
                        collection: saveSearchBaiscCollection
                    })));
                    that.RSaveSearchAdvance.show(new SaveSearchView(_.extend(obj, {
                        isBasic: false,
                        collection: saveSearchAdvanceCollection
                    })));

                    function fetchSaveSearchCollection() {
                        saveSearchCollection.fetch({
                            success: function(collection, data) {
                                saveSearchAdvanceCollection.reset(_.where(data, { "searchType": "ADVANCED" }));
                                saveSearchBaiscCollection.reset(_.where(data, { "searchType": "BASIC" }));
                            },
                            silent: true
                        });
                    }
                    fetchSaveSearchCollection();
                });
            },
185
            bindEvents: function(param) {
186
                this.listenTo(this.typeHeaders, "reset", function(value) {
187
                    this.renderTypeTagList();
188 189
                    this.setValues();
                    this.ui.typeLov.select2({
190
                        placeholder: "Select",
191 192
                        allowClear: true
                    });
193 194 195 196 197
                    this.ui.tagLov.select2({
                        placeholder: "Select",
                        allowClear: true
                    });
                    this.checkForButtonVisiblity();
198 199
                }, this);
            },
200 201 202 203 204 205 206 207 208 209
            makeFilterButtonActive: function(filtertypeParam) {
                var filtertype = ['entityFilters', 'tagFilters'],
                    that = this;
                if (filtertypeParam) {
                    if (_.isArray(filtertypeParam)) {
                        filtertype = filtertypeParam;
                    } else if (_.isString(filtertypeParam)) {
                        filtertype = [filtertypeParam];
                    }
                }
210
                var typeCheck = function(filterObj, type) {
211 212 213
                    if (that.value.type) {
                        if (filterObj && filterObj.length) {
                            that.ui.typeAttrFilter.addClass('active');
214
                        } else {
215
                            that.ui.typeAttrFilter.removeClass('active');
216
                        }
217 218 219 220
                        that.ui.typeAttrFilter.prop('disabled', false);
                    } else {
                        that.ui.typeAttrFilter.removeClass('active');
                        that.ui.typeAttrFilter.prop('disabled', true);
221
                    }
222
                }
223
                var tagCheck = function(filterObj, type) {
224 225 226 227
                    if (that.value.tag) {
                        that.ui.tagAttrFilter.prop('disabled', false);
                        if (filterObj && filterObj.length) {
                            that.ui.tagAttrFilter.addClass('active');
228
                        } else {
229
                            that.ui.tagAttrFilter.removeClass('active');
230
                        }
231 232 233
                    } else {
                        that.ui.tagAttrFilter.removeClass('active');
                        that.ui.tagAttrFilter.prop('disabled', true);
234 235
                    }
                }
236
                _.each(filtertype, function(type) {
237
                    var filterObj = that.searchTableFilters[type];
238
                    if (type == "entityFilters") {
239
                        typeCheck(filterObj[that.value.type], type);
240 241
                    }
                    if (type == "tagFilters") {
242
                        tagCheck(filterObj[that.value.tag], type);
243 244
                    }
                });
245
            },
246
            checkForButtonVisiblity: function(e, options) {
247 248 249 250 251 252 253 254 255
                if (this.type == "basic" && e && e.currentTarget) {
                    var $el = $(e.currentTarget),
                        isTagEl = $el.data('id') == "tagLOV" ? true : false;
                    if (e.type == "change" && $el.select2('data')) {
                        var value = $el.val(),
                            key = (isTagEl ? 'tag' : 'type'),
                            filterType = (isTagEl ? 'tagFilters' : 'entityFilters'),
                            value = value.length ? value : null;
                        if (this.value) {
256 257
                            //On Change handle
                            if (this.value[key] !== value || (!value && !this.value[key])) {
258 259 260
                                var temp = {};
                                temp[key] = value;
                                _.extend(this.value, temp);
261
                                // on change of type/tag change the offset.
262 263 264
                                if (_.isUndefined(options)) {
                                    this.value.pageOffset = 0;
                                }
265
                                _.extend(this.query[this.type], temp);
266 267 268 269 270 271
                            } else {
                                // Initial loading handle.
                                var filterObj = this.searchTableFilters[filterType];
                                if (filterObj && this.value[key]) {
                                    this.searchTableFilters[filterType][this.value[key]] = this.value[filterType] ? this.value[filterType] : null;
                                }
272 273 274 275 276 277 278 279 280 281 282 283 284
                                if (this.value.type) {
                                    if (this.value.attributes) {
                                        var attributes = _.sortBy(this.value.attributes.split(',')),
                                            tableColumn = this.searchTableColumns[this.value.type];
                                        if (_.isEmpty(this.searchTableColumns) || !tableColumn) {
                                            this.searchTableColumns[this.value.type] = attributes
                                        } else if (tableColumn.join(",") !== attributes.join(",")) {
                                            this.searchTableColumns[this.value.type] = attributes;
                                        }
                                    } else if (this.searchTableColumns[this.value.type]) {
                                        this.searchTableColumns[this.value.type] = undefined;
                                    }
                                }
285
                            }
286
                            this.makeFilterButtonActive(filterType);
287 288 289 290 291 292
                        } else {
                            this.ui.tagAttrFilter.prop('disabled', true);
                            this.ui.typeAttrFilter.prop('disabled', true);
                        }
                    }
                }
293 294
                var that = this,
                    value = this.ui.searchInput.val() || this.ui.typeLov.val();
295
                if (!this.dsl && !value) {
296 297 298 299 300 301 302 303 304 305 306
                    value = this.ui.tagLov.val();
                }
                if (value && value.length) {
                    this.ui.searchBtn.removeAttr("disabled");
                    setTimeout(function() {
                        that.ui.searchInput.focus();
                    }, 0);
                } else {
                    this.ui.searchBtn.attr("disabled", "true");
                }
            },
307 308
            onRender: function() {
                // array of tags which is coming from url
309
                this.renderTypeTagList();
310 311
                this.setValues();
                this.ui.typeLov.select2({
312 313 314 315 316
                    placeholder: "Select",
                    allowClear: true
                });
                this.ui.tagLov.select2({
                    placeholder: "Select",
317 318
                    allowClear: true
                });
319
                this.renderSaveSearch();
320
            },
321 322 323 324
            updateQueryObject: function(param) {
                if (param && param.searchType) {
                    this.type = param.searchType;
                }
325 326 327
                _.extend(this.query[this.type],
                    (this.type == "dsl" ? {
                        query: null,
328 329 330
                        type: null,
                        pageOffset: null,
                        pageLimit: null
331
                    } : {
332 333
                        query: null,
                        type: null,
334
                        tag: null,
335
                        attributes: null,
336
                        tagFilters: null,
337 338
                        pageOffset: null,
                        pageLimit: null,
339
                        entityFilters: null,
340
                        includeDE: null
341
                    }), param);
342
            },
343
            fetchCollection: function(value) {
344
                this.typeHeaders.fetch({ reset: true });
345
            },
346 347
            onRefreshButton: function() {
                this.fetchCollection();
348 349 350
                //to check url query param contain type or not 
                var checkURLValue = Utils.getUrlState.getQueryParams(this.url);
                if (this.searchVent && (_.has(checkURLValue, "tag") || _.has(checkURLValue, "type") || _.has(checkURLValue, "query"))) {
351 352
                    this.searchVent.trigger('search:refresh');
                }
353
            },
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            advancedInfo: function(e) {
                require([
                    'views/search/AdvancedSearchInfoView',
                    'modules/Modal'
                ], function(AdvancedSearchInfoView, Modal) {
                    var view = new AdvancedSearchInfoView();
                    var modal = new Modal({
                        title: 'Advanced Search Queries',
                        content: view,
                        okCloses: true,
                        showFooter: true,
                        allowCancel: false
                    }).open();
                    view.on('closeModal', function() {
                        modal.trigger('cancel');
                    });
                });
            },
372 373 374 375 376 377 378 379 380 381 382
            openAttrFilter: function(filterType) {
                var that = this;
                require(['views/search/SearchQueryView'], function(SearchQueryView) {
                    that.attrModal = new SearchQueryView({
                        value: that.value,
                        tag: (filterType === "tag" ? true : false),
                        type: (filterType === "type" ? true : false),
                        searchVent: that.searchVent,
                        typeHeaders: that.typeHeaders,
                        entityDefCollection: that.entityDefCollection,
                        enumDefCollection: that.enumDefCollection,
383 384
                        classificationDefCollection: that.classificationDefCollection,
                        searchTableFilters: that.searchTableFilters
385
                    });
386 387
                    that.attrModal.on('ok', function(scope, e) {
                        that.okAttrFilterButton(e);
388 389 390
                    });
                });
            },
391
            okAttrFilterButton: function(e) {
392 393
                var isTag = this.attrModal.tag ? true : false,
                    filtertype = isTag ? 'tagFilters' : 'entityFilters',
394 395 396 397
                    queryBuilderRef = this.attrModal.RQueryBuilder.currentView.ui.builder;
                if (queryBuilderRef.data('queryBuilder')) {
                    var rule = queryBuilderRef.queryBuilder('getRules');
                }
398
                if (rule) {
399
                    var ruleUrl = CommonViewFunction.attributeFilter.generateUrl({ "value": rule.rules, "formatedDateToLong": true });
400
                    this.searchTableFilters[filtertype][(isTag ? this.value.tag : this.value.type)] = ruleUrl;
401
                    this.makeFilterButtonActive(filtertype);
402
                    if (!isTag && this.value && this.value.type && this.searchTableColumns) {
403 404 405 406 407
                        if (!this.searchTableColumns[this.value.type]) {
                            this.searchTableColumns[this.value.type] = ["selected", "name", "owner", "description", "tag", "typeName"]
                        }
                        this.searchTableColumns[this.value.type] = _.sortBy(_.union(this.searchTableColumns[this.value.type], _.pluck(rule.rules, 'id')));
                    }
408
                    this.attrModal.modal.close();
409 410
                    if ($(e.currentTarget).hasClass('search')) {
                        this.findSearchResult();
411 412 413
                    }
                }
            },
414
            manualRender: function(paramObj) {
415
                this.updateQueryObject(paramObj);
416
                this.setValues(paramObj);
417
            },
418
            renderTypeTagList: function() {
419 420
                var that = this;
                this.ui.typeLov.empty();
421 422
                var typeStr = '<option></option>',
                    tagStr = typeStr;
423 424
                this.typeHeaders.fullCollection.comparator = function(model) {
                    return Utils.getName(model.toJSON(), 'name').toLowerCase();
425
                }
426
                this.typeHeaders.fullCollection.sort().each(function(model) {
427
                    var name = Utils.getName(model.toJSON(), 'name');
428
                    if (model.get('category') == 'ENTITY') {
429
                        typeStr += '<option>' + (name) + '</option>';
430 431
                    }
                    if (model.get('category') == 'CLASSIFICATION') {
432
                        tagStr += '<option>' + (name) + '</option>';
433
                    }
434
                });
435 436
                that.ui.typeLov.html(typeStr);
                that.ui.tagLov.html(tagStr);
437
            },
438
            setValues: function(paramObj) {
439 440
                var arr = [],
                    that = this;
441 442 443 444
                if (paramObj) {
                    this.value = paramObj;
                }
                if (this.value) {
445
                    this.ui.searchInput.val(this.value.query || "");
446
                    if (this.value.dslChecked == "true") {
447 448 449
                        if (!this.ui.searchType.prop("checked")) {
                            this.ui.searchType.prop("checked", true).trigger("change");
                        }
450
                    } else {
451 452 453
                        if (this.ui.searchType.prop("checked")) {
                            this.ui.searchType.prop("checked", false).trigger("change");
                        }
454
                    }
455
                    this.ui.typeLov.val(this.value.type);
456
                    if (this.ui.typeLov.data('select2')) {
457 458
                        if (this.ui.typeLov.val() !== this.value.type) {
                            this.value.type = null;
459
                            this.ui.typeLov.val("").trigger("change", { 'manual': true });
460
                        } else {
461
                            this.ui.typeLov.trigger("change", { 'manual': true });
462
                        }
463
                    }
464

465
                    if (!this.dsl) {
466
                        this.ui.tagLov.val(this.value.tag);
467
                        if (this.ui.tagLov.data('select2')) {
468 469 470
                            // To handle delete scenario.
                            if (this.ui.tagLov.val() !== this.value.tag) {
                                this.value.tag = null;
471
                                this.ui.tagLov.val("").trigger("change", { 'manual': true });
472
                            } else {
473
                                this.ui.tagLov.trigger("change", { 'manual': true });
474
                            }
475 476
                        }
                    }
477 478 479
                    setTimeout(function() {
                        that.ui.searchInput.focus();
                    }, 0);
480 481 482
                }
            },
            findSearchResult: function() {
483 484 485
                this.triggerSearch(this.ui.searchInput.val());
            },
            triggerSearch: function(value) {
486 487
                var params = {
                    searchType: this.type,
488 489 490
                    dslChecked: this.ui.searchType.is(':checked'),
                    tagFilters: null,
                    entityFilters: null
491
                }
492
                params['type'] = this.ui.typeLov.select2('val') || null;
493
                if (!this.dsl) {
494
                    params['tag'] = this.ui.tagLov.select2('val') || null;
495 496 497 498 499 500 501 502
                    var entityFilterObj = this.searchTableFilters['entityFilters'],
                        tagFilterObj = this.searchTableFilters['tagFilters'];
                    if (this.value.tag) {
                        params['tagFilters'] = tagFilterObj[this.value.tag]
                    }
                    if (this.value.type) {
                        params['entityFilters'] = entityFilterObj[this.value.type]
                    }
503
                    var columnList = this.value && this.value.type && this.searchTableColumns ? this.searchTableColumns[this.value.type] : null;
504
                    if (columnList) {
505
                        params['attributes'] = columnList.join(',');
506
                    }
507 508 509
                    if (_.isUndefinedNull(this.value.includeDE)) {
                        params['includeDE'] = false;
                    } else {
510 511 512
                        params['includeDE'] = this.value.includeDE;
                    }
                }
513
                if (!_.isUndefinedNull(this.value.pageLimit)) {
514
                    params['pageLimit'] = this.value.pageLimit;
515
                }
516 517
                if (!_.isUndefinedNull(this.value.pageOffset)) {
                    if (!_.isUndefinedNull(this.query[this.type]) && this.query[this.type].query != value) {
518
                        params['pageOffset'] = 0;
519
                    } else {
520
                        params['pageOffset'] = this.value.pageOffset;
521 522
                    }
                }
523 524
                params['query'] = value || null;
                _.extend(this.query[this.type], params);
525 526
                Utils.setUrl({
                    url: '#!/search/searchResult',
527
                    urlParams: _.extend({}, this.query[this.type]),
528
                    mergeBrowserUrl: false,
529 530
                    trigger: true,
                    updateTabState: true
531 532 533
                });
            },
            dslFulltextToggle: function(e) {
534
                var paramObj = Utils.getUrlState.getQueryParams();
535 536 537
                if (paramObj && this.type == paramObj.searchType) {
                    this.updateQueryObject(paramObj);
                }
538 539
                if (e.currentTarget.checked) {
                    this.type = "dsl";
540
                    this.dsl = true;
541
                    this.$('.tagBox').hide();
542
                    this.$('.temFilterBtn').hide();
543 544
                    this.$('.temFilter').addClass('col-sm-12');
                    this.$('.temFilter').removeClass('col-sm-10');
545 546
                    this.$('.basicSaveSearch').hide();
                    this.$('.advanceSaveSearch').show();
547 548
                    this.$('.searchText').text('Search By Query');
                    this.ui.searchInput.attr("placeholder", 'Search By Query eg. where name="sales_fact"');
549
                } else {
550 551
                    this.$('.temFilter').addClass('col-sm-10');
                    this.$('.temFilter').removeClass('col-sm-12');
552
                    this.$('.temFilterBtn').show();
553
                    this.$('.tagBox').show();
554 555
                    this.$('.basicSaveSearch').show();
                    this.$('.advanceSaveSearch').hide();
556
                    this.dsl = false;
557
                    this.type = "basic";
558 559
                    this.$('.searchText').text('Search By Text');
                    this.ui.searchInput.attr("placeholder", "Search By Text");
560
                }
561 562 563 564 565
                if (Utils.getUrlState.isSearchTab()) {
                    Utils.setUrl({
                        url: '#!/search/searchResult',
                        urlParams: _.extend(this.query[this.type], {
                            searchType: this.type,
566
                            dslChecked: this.ui.searchType.is(':checked')
567 568
                        }),
                        mergeBrowserUrl: false,
569 570
                        trigger: true,
                        updateTabState: true
571
                    });
572
                }
573 574
            },
            clearSearchData: function() {
575
                this.updateQueryObject();
576
                this.ui.typeLov.val("").trigger("change");
577
                this.ui.tagLov.val("").trigger("change");
578
                this.ui.searchInput.val("");
579 580 581 582 583 584
                var type = "basicSaveSearch";
                if (this.type == "dsl") {
                    type = "advanceSaveSearch";
                }
                this.$('.' + type + ' .saveSearchList').find('li.active').removeClass('active');
                this.$('.' + type + ' [data-id="saveBtn"]').attr('disabled', true);
585
                if (!this.dsl) {
586 587 588
                    this.searchTableFilters.tagFilters = {};
                    this.searchTableFilters.entityFilters = {};
                }
589
                this.checkForButtonVisiblity();
590
                Utils.setUrl({
591 592 593 594 595
                    url: '#!/search/searchResult',
                    urlParams: {
                        searchType: this.type,
                        dslChecked: this.ui.searchType.is(':checked')
                    },
596 597 598
                    mergeBrowserUrl: false,
                    trigger: true
                });
599
            }
600 601
        });
    return SearchLayoutView;
602
});