SearchResultLayoutView.js 50 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/**
 * 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',
21
    'table-dragger',
22
    'hbs!tmpl/search/SearchResultLayoutView_tmpl',
23 24 25 26
    'modules/Modal',
    'models/VEntity',
    'utils/Utils',
    'utils/Globals',
27
    'collection/VSearchList',
28
    'models/VCommon',
29
    'utils/CommonViewFunction',
30 31 32
    'utils/Messages',
    'utils/Enums',
    'utils/UrlLinks'
33
], function(require, Backbone, tableDragger, SearchResultLayoutViewTmpl, Modal, VEntity, Utils, Globals, VSearchList, VCommon, CommonViewFunction, Messages, Enums, UrlLinks) {
34 35
    'use strict';

36 37
    var SearchResultLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends SearchResultLayoutView */
38
        {
39
            _viewName: 'SearchResultLayoutView',
40

41
            template: SearchResultLayoutViewTmpl,
42 43 44 45 46

            /** Layout sub regions */
            regions: {
                RTagLayoutView: "#r_tagLayoutView",
                RSearchLayoutView: "#r_searchLayoutView",
47
                REntityTableLayoutView: "#r_searchResultTableLayoutView",
48
                RSearchQuery: '#r_searchQuery'
49 50 51 52 53 54
            },

            /** ui selector cache */
            ui: {
                tagClick: '[data-id="tagClick"]',
                addTag: '[data-id="addTag"]',
55 56
                paginationDiv: '[data-id="paginationDiv"]',
                previousData: "[data-id='previousData']",
57
                nextData: "[data-id='nextData']",
58
                pageRecordText: "[data-id='pageRecordText']",
59
                addAssignTag: "[data-id='addAssignTag']",
60
                createEntity: "[data-id='createEntity']",
61
                checkDeletedEntity: "[data-id='checkDeletedEntity']",
62 63
                checkSubClassification: "[data-id='checkSubClassification']",
                checkSubType: "[data-id='checkSubType']",
64
                colManager: "[data-id='colManager']",
65
                containerCheckBox: "[data-id='containerCheckBox']",
66 67 68 69 70
                columnEmptyInfo: "[data-id='columnEmptyInfo']",
                showPage: "[data-id='showPage']",
                gotoPage: "[data-id='gotoPage']",
                gotoPagebtn: "[data-id='gotoPagebtn']",
                activePage: "[data-id='activePage']",
71 72 73
            },
            templateHelpers: function() {
                return {
74
                    entityCreate: Globals.entityCreate,
75
                    searchType: this.searchType
76
                };
77 78 79
            },
            /** ui events hash */
            events: function() {
80 81
                var events = {},
                    that = this;
82
                events["click " + this.ui.tagClick] = function(e) {
83
                    var scope = $(e.currentTarget);
84 85 86
                    if (e.target.nodeName.toLocaleLowerCase() == "i") {
                        this.onClickTagCross(e);
                    } else {
87 88 89 90 91 92 93
                        this.triggerUrl({
                            url: '#!/tag/tagAttribute/' + scope.text(),
                            urlParams: null,
                            mergeBrowserUrl: false,
                            trigger: true,
                            updateTabState: null
                        });
94 95
                    }
                };
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
                events["keyup " + this.ui.gotoPage] = function(e) {
                    var code = e.which,
                        goToPage = parseInt(e.currentTarget.value);
                    if (e.currentTarget.value) {
                        that.ui.gotoPagebtn.attr('disabled', false);
                    } else {
                        that.ui.gotoPagebtn.attr('disabled', true);
                    }
                    if (code == 13) {
                        if (e.currentTarget.value) {
                            that.gotoPagebtn();
                        }
                    }
                };
                events["change " + this.ui.showPage] = 'changePageLimit';
                events["click " + this.ui.gotoPagebtn] = 'gotoPagebtn';
112 113
                events["click " + this.ui.addTag] = 'checkedValue';
                events["click " + this.ui.addAssignTag] = 'checkedValue';
114 115
                events["click " + this.ui.nextData] = "onClicknextData";
                events["click " + this.ui.previousData] = "onClickpreviousData";
116
                events["click " + this.ui.createEntity] = 'onClickCreateEntity';
117 118 119
                events["click " + this.ui.checkDeletedEntity] = 'onCheckExcludeIncludeResult';
                events["click " + this.ui.checkSubClassification] = 'onCheckExcludeIncludeResult';
                events["click " + this.ui.checkSubType] = 'onCheckExcludeIncludeResult';
120 121 122
                return events;
            },
            /**
123
             * intialize a new SearchResultLayoutView Layout
124 125 126
             * @constructs
             */
            initialize: function(options) {
127
                _.extend(this, _.pick(options, 'value', 'initialView', 'isTypeTagNotExists', 'classificationDefCollection', 'entityDefCollection', 'typeHeaders', 'searchVent', 'enumDefCollection', 'tagCollection', 'searchTableColumns'));
128
                this.entityModel = new VEntity();
129
                this.searchCollection = new VSearchList();
130
                this.limit = 25;
131
                this.asyncFetchCounter = 0;
132
                this.offset = 0;
133
                this.bindEvents();
134
                this.arr = [];
135
                this.searchType = 'Basic Search';
136
                this.columnOrder = null;
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
                if (this.value) {
                    if (this.value.searchType && this.value.searchType == 'dsl') {
                        this.searchType = 'Advanced Search';
                    }
                    if (this.value.pageLimit) {
                        var pageLimit = parseInt(this.value.pageLimit, 10);
                        if (_.isNaN(pageLimit) || pageLimit == 0 || pageLimit <= -1) {
                            this.value.pageLimit = this.limit;
                            this.triggerUrl();
                        } else {
                            this.limit = pageLimit;
                        }
                    }
                    if (this.value.pageOffset) {
                        var pageOffset = parseInt(this.value.pageOffset, 10);
                        if (_.isNaN(pageOffset) || pageLimit <= -1) {
                            this.value.pageOffset = this.offset;
                            this.triggerUrl();
                        } else {
                            this.offset = pageOffset;
                        }
                    }
159
                }
160 161
            },
            bindEvents: function() {
162
                var that = this;
163
                this.listenTo(this.searchCollection, 'backgrid:selected', function(model, checked) {
164
                    this.arr = [];
165 166 167 168 169 170 171
                    if (checked === true) {
                        model.set("isEnable", true);
                    } else {
                        model.set("isEnable", false);
                    }
                    this.searchCollection.find(function(item) {
                        if (item.get('isEnable')) {
172
                            var obj = item.toJSON();
173
                            that.arr.push({
174 175
                                id: obj.guid,
                                model: obj
176 177 178
                            });
                        }
                    });
179

180
                    if (this.arr.length > 0) {
181
                        this.$('.multiSelectTag').show();
182
                    } else {
183
                        this.$('.multiSelectTag').hide();
184
                    }
185
                });
186
                this.listenTo(this.searchCollection, "error", function(model, response) {
187 188 189 190
                    this.hideLoader({ type: 'error' });
                    var responseJSON = response && response.responseJSON ? response.responseJSON : null,
                    errorText = (responseJSON && (responseJSON.errorMessage || responseJSON.message || responseJSON.error ))|| 'Invalid Expression';
                    if (errorText) {
191
                        Utils.notifyError({
192
                            content: errorText
193
                        });
194
                        this.$('.searchTable > .well').html('<center>' + errorText + '</center>')
195
                    }
196
                }, this);
197 198 199
                this.listenTo(this.searchCollection, "state-changed", function(state) {
                    if (Utils.getUrlState.isSearchTab()) {
                        this.updateColumnList(state);
200 201
                        var excludeDefaultColumn = [];
                        if (this.value && this.value.type) {
202
                            excludeDefaultColumn = _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag");
203 204 205 206 207
                            if (this.searchTableColumns[this.value.type] === null) {
                                this.ui.columnEmptyInfo.show();
                            } else {
                                this.ui.columnEmptyInfo.hide();
                            }
208
                        }
209
                        this.columnOrder = this.getColumnOrder(this.REntityTableLayoutView.$el.find('.colSort th.renderable'));
210
                        this.triggerUrl();
211
                        var attributes = this.searchCollection.filterObj.attributes;
212
                        if ((excludeDefaultColumn && attributes) && (excludeDefaultColumn.length > attributes.length || _.difference(excludeDefaultColumn, attributes).length)) {
213 214
                            this.fetchCollection(this.value);
                        }
215 216
                    }
                }, this);
217 218 219
                this.listenTo(this.searchVent, "search:refresh", function(model, response) {
                    this.fetchCollection();
                }, this);
220 221
            },
            onRender: function() {
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                var that = this;
                this.commonTableOptions = {
                    collection: this.searchCollection,
                    includePagination: false,
                    includeFooterRecords: false,
                    includeColumnManager: (Utils.getUrlState.isSearchTab() && this.value && this.value.searchType === "basic" && !this.value.profileDBView ? true : false),
                    includeOrderAbleColumns: false,
                    includeSizeAbleColumns: false,
                    includeTableLoader: false,
                    columnOpts: {
                        opts: {
                            initialColumnsVisible: null,
                            saveState: false
                        },
                        visibilityControlOpts: {
237
                            buttonTemplate: _.template("<button class='btn btn-action btn-sm pull-right'>Columns&nbsp<i class='fa fa-caret-down'></i></button>")
238 239 240 241 242
                        },
                        el: this.ui.colManager
                    },
                    gridOpts: {
                        emptyText: 'No Record found!',
243
                        className: 'table table-hover backgrid table-quickMenu colSort'
244 245 246 247
                    },
                    filterOpts: {},
                    paginatorOpts: {}
                };
248 249 250 251 252
                if (!this.initialView) {
                    var value = {},
                        that = this;
                    if (this.value) {
                        value = this.value;
253 254 255
                        if (value && value.includeDE) {
                            this.ui.checkDeletedEntity.prop('checked', true);
                        }
256 257 258 259 260 261 262
                        if (value && value.excludeSC) {
                            this.ui.checkSubClassification.prop('checked', true);
                        }
                        if (value && value.excludeST) {
                            this.ui.checkSubType.prop('checked', true);
                        }

263 264
                    } else {
                        value = {
265
                            'query': null,
266
                            'searchType': 'basic'
267 268
                        };
                    }
269
                    this.updateColumnList();
270 271 272 273 274
                    if (this.value && this.searchTableColumns && this.searchTableColumns[this.value.type] === null) {
                        this.ui.columnEmptyInfo.show();
                    } else {
                        this.ui.columnEmptyInfo.hide();
                    }
275
                    this.fetchCollection(value, _.extend({ 'fromUrl': true }, (this.value && this.value.pageOffset ? { 'next': true } : null)));
276 277 278 279 280 281 282 283 284
                    this.ui.showPage.select2({
                        data: _.sortBy(_.union([25, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500], [this.limit])),
                        tags: true,
                        dropdownCssClass: "number-input",
                        multiple: false
                    });
                    if (this.value && this.value.pageLimit) {
                        this.ui.showPage.val(this.limit).trigger('change', { "skipViewChange": true });
                    }
285 286 287
                } else {
                    if (Globals.entityTypeConfList) {
                        this.$(".entityLink").show();
288
                    }
289 290 291 292 293
                    if (this.isTypeTagNotExists) {
                        Utils.notifyError({
                            content: Messages.search.notExists
                        });
                    }
294 295
                }
            },
296 297 298 299 300 301
            getColumnOrderWithPosition: function() {
                var that = this;
                return _.map(that.columnOrder, function(value, key) {
                    return key + "::" + value;
                }).join(",");
            },
302 303 304
            triggerUrl: function(options) {
                Utils.setUrl(_.extend({
                    url: Utils.getUrlState.getQueryUrl().queyParams[0],
305
                    urlParams: this.columnOrder ? _.extend(this.value, { 'uiParameters': this.getColumnOrderWithPosition() }) : this.value,
306 307 308 309
                    mergeBrowserUrl: false,
                    trigger: false,
                    updateTabState: true
                }, options));
310
            },
311 312
            updateColumnList: function(updatedList) {
                if (updatedList) {
313
                    var listOfColumns = [];
314 315 316 317 318 319
                    _.map(updatedList, function(obj) {
                        var key = obj.name;
                        if (obj.renderable) {
                            listOfColumns.push(obj.name);
                        }
                    });
320
                    listOfColumns = _.sortBy(listOfColumns);
321
                    this.value.attributes = listOfColumns.length ? listOfColumns.join(",") : null;
322
                    if (this.value && this.value.type && this.searchTableColumns) {
323 324 325 326
                        this.searchTableColumns[this.value.type] = listOfColumns.length ? listOfColumns : null;
                    }
                } else if (this.value && this.value.type && this.searchTableColumns && this.value.attributes) {
                    this.searchTableColumns[this.value.type] = this.value.attributes.split(",");
327 328
                }
            },
329
            fetchCollection: function(value, options) {
330
                var that = this,
331 332 333 334 335 336
                    isPostMethod = (this.value && this.value.searchType === "basic"),
                    isSearchTab = Utils.getUrlState.isSearchTab(),
                    tagFilters = null,
                    entityFilters = null;
                if (isSearchTab) {
                    tagFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.tagFilters);
337
                    entityFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.entityFilters);
338 339 340
                }

                if (isPostMethod && isSearchTab) {
341
                    var excludeDefaultColumn = this.value.type && this.searchTableColumns ? _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag") : null,
342 343 344 345 346 347 348
                        filterObj = {
                            'entityFilters': entityFilters,
                            'tagFilters': tagFilters,
                            'attributes': excludeDefaultColumn ? excludeDefaultColumn : null
                        };
                }

349
                this.showLoader();
350
                if (Globals.searchApiCallRef && Globals.searchApiCallRef.readyState === 1) {
351 352
                    Globals.searchApiCallRef.abort();
                }
353
                var apiObj = {
354
                    skipDefaultError: true,
355
                    sort: false,
356
                    success: function(dataOrCollection, response) {
357
                        Globals.searchApiCallRef = undefined;
358 359 360
                        var isFirstPage = that.offset === 0,
                            dataLength = 0,
                            goToPage = that.ui.gotoPage.val();
361 362 363
                        if (!(that.ui.pageRecordText instanceof jQuery)) {
                            return;
                        }
364 365 366 367 368 369 370
                        if (isPostMethod && dataOrCollection && dataOrCollection.entities) {
                            dataLength = dataOrCollection.entities.length;
                        } else {
                            dataLength = dataOrCollection.length;
                        }

                        if (!dataLength && that.offset >= that.limit && ((options && options.next) || goToPage) && (options && !options.fromUrl)) {
371
                            /* User clicks on next button and server returns
372 373
                            empty response then disabled the next button without rendering table*/

374
                            that.hideLoader();
375 376 377
                            var pageNumber = that.activePage + 1;
                            if (goToPage) {
                                pageNumber = goToPage;
378
                                that.offset = (that.activePage - 1) * that.limit;
379 380 381 382 383 384 385 386 387 388 389 390
                            } else {
                                that.ui.nextData.attr('disabled', true);
                                that.offset = that.offset - that.limit;
                            }
                            if (that.value) {
                                that.value.pageOffset = that.offset;
                                that.triggerUrl();
                            }
                            Utils.notifyInfo({
                                html: true,
                                content: Messages.search.noRecordForPage + '<b>' + Utils.getNumberSuffix({ number: pageNumber, sup: true }) + '</b> page'
                            });
391 392
                            return;
                        }
393
                        if (isPostMethod) {
394 395
                            that.searchCollection.referredEntities = dataOrCollection.referredEntities;
                            Utils.findAndMergeRefEntity(dataOrCollection.entities, dataOrCollection.referredEntities);
396
                            that.searchCollection.reset(dataOrCollection.entities, { silent: true });
397
                        }
398

399

400
                        /*Next button check.
401
                        It's outside of Previous button else condition
402 403
                        because when user comes from 2 page to 1 page than we need to check next button.*/
                        if (dataLength < that.limit) {
404 405 406 407
                            that.ui.nextData.attr('disabled', true);
                        } else {
                            that.ui.nextData.attr('disabled', false);
                        }
408 409 410 411 412 413 414 415 416 417

                        if (isFirstPage && (!dataLength || dataLength < that.limit)) {
                            that.ui.paginationDiv.hide();
                        } else {
                            that.ui.paginationDiv.show();
                        }

                        // Previous button check.
                        if (isFirstPage) {
                            that.ui.previousData.attr('disabled', true);
418 419
                            that.pageFrom = 1;
                            that.pageTo = that.limit;
420 421 422 423 424
                        } else {
                            that.ui.previousData.attr('disabled', false);
                        }

                        if (options && options.next) {
425 426 427
                            //on next click, adding "1" for showing the another records.
                            that.pageTo = that.offset + that.limit;
                            that.pageFrom = that.offset + 1;
428
                        } else if (!isFirstPage && options && options.previous) {
429 430 431
                            that.pageTo = that.pageTo - that.limit;
                            that.pageFrom = (that.pageTo - that.limit) + 1;
                        }
432
                        that.ui.pageRecordText.html("Showing  <u>" + that.searchCollection.models.length + " records</u> From " + that.pageFrom + " - " + that.pageTo);
433 434 435
                        that.activePage = Math.round(that.pageTo / that.limit);
                        that.ui.activePage.attr('title', "Page " + that.activePage);
                        that.ui.activePage.text(that.activePage);
436
                        that.renderTableLayoutView();
437

438
                        if (Utils.getUrlState.isSearchTab() && value && !value.profileDBView) {
439
                            var searchString = 'Results for: <span class="filterQuery">' + CommonViewFunction.generateQueryOfFilter(that.value) + "</span>";
440 441 442 443
                            if (Globals.entityCreate && Globals.entityTypeConfList && Utils.getUrlState.isSearchTab()) {
                                searchString += "<p>If you do not find the entity in search result below then you can" + '<a href="javascript:void(0)" data-id="createEntity"> create new entity</a></p>';
                            }
                            that.$('.searchResult').html(searchString);
444
                        }
445
                    },
446 447
                    silent: true,
                    reset: true
448
                }
449 450 451 452 453 454 455
                if (this.value) {
                    var checkBoxValue = {
                        'excludeDeletedEntities': (this.value.includeDE ? false : true),
                        'includeSubClassifications': (this.value.excludeSC ? false : true),
                        'includeSubTypes': (this.value.excludeST ? false : true)
                    }
                }
456 457 458 459
                if (value) {
                    if (value.searchType) {
                        this.searchCollection.url = UrlLinks.searchApiUrl(value.searchType);
                    }
460
                    _.extend(this.searchCollection.queryParams, { 'limit': this.limit, 'offset': this.offset, 'query': _.trim(value.query), 'typeName': value.type || null, 'classification': value.tag || null });
461 462 463 464 465 466
                    if (value.profileDBView && value.guid) {
                        var profileParam = {};
                        profileParam['guid'] = value.guid;
                        profileParam['relation'] = '__hive_table.db';
                        profileParam['sortBy'] = 'name';
                        profileParam['sortOrder'] = 'ASCENDING';
467
                        _.extend(this.searchCollection.queryParams, profileParam);
468
                    }
469
                    if (isPostMethod) {
470
                        this.searchCollection.filterObj = _.extend({}, filterObj);
471
                        apiObj['data'] = _.extend(checkBoxValue, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification'))
472 473 474
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
475
                        this.searchCollection.filterObj = null;
476
                        if (this.value.profileDBView) {
477
                            _.extend(this.searchCollection.queryParams, checkBoxValue);
478
                        }
479 480 481 482
                        Globals.searchApiCallRef = this.searchCollection.fetch(apiObj);
                    }
                } else {
                    if (isPostMethod) {
483
                        apiObj['data'] = _.extend(checkBoxValue, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification'));
484 485 486
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
487
                        if (this.value.profileDBView) {
488
                            _.extend(this.searchCollection.queryParams,checkBoxValue);
489
                        }
490 491 492 493 494 495 496 497 498 499 500
                        Globals.searchApiCallRef = this.searchCollection.fetch(apiObj);
                    }
                }
            },
            renderSearchQueryView: function() {
                var that = this;
                require(['views/search/SearchQueryView'], function(SearchQueryView) {
                    that.RSearchQuery.show(new SearchQueryView({
                        value: that.value,
                        searchVent: that.searchVent
                    }));
501
                });
502
            },
503
            renderTableLayoutView: function(col) {
504
                var that = this;
505
                require(['utils/TableLayout'], function(TableLayout) {
506
                    // displayOrder added for column manager
507 508 509 510 511
                    if (that.value.uiParameters) {
                        var savedColumnOrder = _.object(that.value.uiParameters.split(',').map(function(a) {
                            return a.split('::');
                        })); // get Column position from string to object
                    }
512
                    var columnCollection = Backgrid.Columns.extend({
513
                        sortKey: "displayOrder",
514 515 516 517 518
                        comparator: function(item) {
                            return item.get(this.sortKey) || 999;
                        },
                        setPositions: function() {
                            _.each(this.models, function(model, index) {
519
                                model.set("displayOrder", (savedColumnOrder == null ? index : parseInt(savedColumnOrder[model.get('label')])) + 1, { silent: true });
520 521 522 523
                            });
                            return this;
                        }
                    });
524
                    var columns = new columnCollection((that.searchCollection.dynamicTable ? that.getDaynamicColumns(that.searchCollection.toJSON()) : that.getFixedDslColumn()));
525
                    columns.setPositions().sort();
526
                    var table = new TableLayout(_.extend({}, that.commonTableOptions, {
527
                        columns: columns
528 529
                    }));
                    that.REntityTableLayoutView.show(table);
530 531
                    if (that.value.searchType !== "dsl") {
                        that.ui.containerCheckBox.show();
532
                    } else {
533
                        that.ui.containerCheckBox.hide();
534
                    }
535
                    that.$(".ellipsis .inputAssignTag").hide();
536
                    table.trigger("grid:refresh"); /*Event fire when table rendered*/
537
                    tableDragger(document.querySelector(".colSort")).on('drop', function(from, to, el) {
538 539 540
                        that.columnOrder = that.getColumnOrder(el.querySelectorAll('th.renderable'));
                        table.trigger("grid:refresh:update");
                        that.triggerUrl();
541
                    });
542
                    that.checkTableFetch();
543 544
                });
            },
545 546 547 548 549 550 551
            getColumnOrder: function(arr) {
                var obj = {};
                for (var i = 0; i < arr.length; ++i) {
                    obj[(arr[i].innerText == "" ? 'Select' : arr[i].innerText)] = i;
                }
                return obj;
            },
552
            checkTableFetch: function() {
553
                if (this.asyncFetchCounter <= 0) {
554
                    this.hideLoader();
555 556 557
                    Utils.generatePopover({
                        el: this.$('[data-id="showMoreLess"]'),
                        contentClass: 'popover-tag',
558
                        viewFixedPopover: true,
559
                        popoverOptions: {
560
                            container: null,
561 562 563 564 565
                            content: function() {
                                return $(this).find('.popup-tag').children().clone();
                            }
                        }
                    });
566 567
                }
            },
568 569
            getFixedDslColumn: function() {
                var that = this,
570
                    nameCheck = 0,
571
                    columnToShow = null,
572
                    col = {};
573
                if (this.value && this.value.searchType === "basic" && this.searchTableColumns && (this.searchTableColumns[this.value.type] !== undefined)) {
574 575
                    columnToShow = this.searchTableColumns[this.value.type] == null ? [] : this.searchTableColumns[this.value.type];
                }
576 577
                col['Check'] = {
                    name: "selected",
578
                    label: "Select",
579
                    cell: "select-row",
580 581
                    resizeable: false,
                    orderable: false,
582
                    renderable: (columnToShow ? _.contains(columnToShow, 'selected') : true),
583 584
                    headerCell: "select-all"
                };
585

586
                col['name'] = {
587
                    label: this.value && this.value.profileDBView ? "Table Name" : "Name",
588 589 590
                    cell: "html",
                    editable: false,
                    sortable: false,
591 592 593
                    resizeable: true,
                    orderable: true,
                    renderable: true,
594 595 596
                    className: "searchTableName",
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
597 598 599
                            var obj = model.toJSON(),
                                nameHtml = "",
                                name = Utils.getName(obj);
600 601 602
                            if (obj.guid) {
                                nameHtml = '<a title="' + name + '" href="#!/detailPage/' + obj.guid + '">' + name + '</a>';
                            } else {
603
                                nameHtml = '<span title="' + name + '">' + name + '</span>';
604 605
                            }
                            if (obj.status && Enums.entityStateReadOnly[obj.status]) {
606
                                nameHtml += '<button type="button" title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
607
                                return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>';
608
                            }
609
                            return nameHtml;
610 611 612
                        }
                    })
                };
613 614
                col['owner'] = {
                    label: "Owner",
615 616
                    cell: "String",
                    editable: false,
617
                    sortable: false,
618 619 620
                    resizeable: true,
                    orderable: true,
                    renderable: true,
621 622
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
623
                            var obj = model.toJSON();
624 625
                            if (obj && obj.attributes && obj.attributes.owner) {
                                return obj.attributes.owner;
626 627 628
                            }
                        }
                    })
629
                };
630 631 632 633 634 635 636 637 638 639 640 641 642 643
                if (this.value && this.value.profileDBView) {
                    col['createTime'] = {
                        label: "Date Created",
                        cell: "Html",
                        editable: false,
                        sortable: false,
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.attributes && obj.attributes.createTime) {
                                    return new Date(obj.attributes.createTime);
                                } else {
                                    return '-'
                                }
644
                            }
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
                        })
                    }
                }
                if (this.value && !this.value.profileDBView) {
                    col['description'] = {
                        label: "Description",
                        cell: "String",
                        editable: false,
                        sortable: false,
                        resizeable: true,
                        orderable: true,
                        renderable: true,
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.attributes && obj.attributes.description) {
                                    return obj.attributes.description;
                                }
663
                            }
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
                        })
                    };
                    col['typeName'] = {
                        label: "Type",
                        cell: "Html",
                        editable: false,
                        sortable: false,
                        resizeable: true,
                        orderable: true,
                        renderable: (columnToShow ? _.contains(columnToShow, 'typeName') : true),
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
                                if (obj && obj.typeName) {
                                    return '<a title="Search ' + obj.typeName + '" href="#!/search/searchResult?query=' + obj.typeName + ' &searchType=dsl&dslChecked=true">' + obj.typeName + '</a>';
                                }
680
                            }
681 682
                        })
                    };
683
                    this.getTagCol({ 'col': col, 'columnToShow': columnToShow });
684

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
                    if (this.value && this.value.searchType === "basic") {
                        var def = this.entityDefCollection.fullCollection.find({ name: this.value.type });
                        if (def) {
                            var attrObj = Utils.getNestedSuperTypeObj({ data: def.toJSON(), collection: this.entityDefCollection, attrMerge: true });
                            _.each(attrObj, function(obj, key) {
                                var key = obj.name,
                                    isRenderable = _.contains(columnToShow, key)
                                if (key == "name" || key == "description" || key == "owner") {
                                    if (columnToShow) {
                                        col[key].renderable = isRenderable;
                                    }
                                    return;
                                }
                                col[obj.name] = {
                                    label: obj.name.capitalize(),
                                    cell: "Html",
                                    editable: false,
                                    sortable: false,
                                    resizeable: true,
                                    orderable: true,
                                    renderable: isRenderable,
                                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                        fromRaw: function(rawValue, model) {
                                            var modelObj = model.toJSON();
                                            if (modelObj && modelObj.attributes && !_.isUndefined(modelObj.attributes[key])) {
                                                var tempObj = {
                                                    'scope': that,
                                                    'attributeDefs': [obj],
                                                    'valueObject': {},
                                                    'isTable': false
715 716
                                                };
                                                tempObj.valueObject[key] = modelObj.attributes[key];
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
                                                return CommonViewFunction.propertyTable(tempObj);
                                            }
                                        }
                                    })
                                };
                            });
                        }
                    }
                }
                return this.searchCollection.constructor.getTableCols(col, this.searchCollection);
            },
            getDaynamicColumns: function(valueObj) {
                var that = this,
                    col = {};
                if (valueObj && valueObj.length) {
                    var firstObj = _.first(valueObj);
                    _.each(_.keys(firstObj), function(key) {
                        if (key !== 'guid') {
                            col[key] = {
                                label: key.capitalize(),
                                cell: "Html",
                                editable: false,
                                sortable: false,
                                resizeable: true,
                                orderable: true,
                                formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                    fromRaw: function(rawValue, model) {
                                        var modelObj = model.toJSON();
                                        if (key == "name") {
                                            var nameHtml = "",
                                                name = modelObj[key];
                                            if (modelObj.guid) {
                                                nameHtml = '<a title="' + name + '" href="#!/detailPage/' + modelObj.guid + '">' + name + '</a>';
                                            } else {
                                                nameHtml = '<span title="' + name + '">' + name + '</span>';
                                            }
                                            if (modelObj.status && Enums.entityStateReadOnly[modelObj.status]) {
                                                nameHtml += '<button type="button" title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
                                                return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>';
                                            }
                                            return nameHtml;
                                        } else if (modelObj && !_.isUndefined(modelObj[key])) {
                                            var tempObj = {
                                                'scope': that,
                                                // 'attributeDefs':
                                                'valueObject': {},
                                                'isTable': false
764 765
                                            };
                                            tempObj.valueObject[key] = modelObj[key];
766 767 768 769 770 771 772 773 774 775
                                            return CommonViewFunction.propertyTable(tempObj);
                                        }
                                    }
                                })
                            };
                        }
                    });
                }
                return this.searchCollection.constructor.getTableCols(col, this.searchCollection);
            },
776
            getTagCol: function(options) {
777 778 779 780
                var that = this,
                    columnToShow = options.columnToShow,
                    col = options.col;
                if (col) {
781 782
                    col['tag'] = {
                        label: "Tags",
783 784 785
                        cell: "Html",
                        editable: false,
                        sortable: false,
786
                        resizeable: true,
787
                        orderable: true,
788 789
                        renderable: (columnToShow ? _.contains(columnToShow, 'tag') : true),
                        className: 'searchTag',
790 791
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
792
                                var obj = model.toJSON();
793
                                if (obj.status && Enums.entityStateReadOnly[obj.status]) {
794
                                    return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj); + '</div>';
795
                                } else {
796
                                    return CommonViewFunction.tagForTable(obj);
797
                                }
798

799 800 801
                            }
                        })
                    };
802
                }
803
            },
804
            addTagModalView: function(guid, multiple) {
805
                var that = this;
806
                require(['views/tag/AddTagModalView'], function(AddTagModalView) {
807
                    var view = new AddTagModalView({
808 809
                        guid: guid,
                        multiple: multiple,
810 811
                        callback: function() {
                            that.fetchCollection();
812 813
                            that.arr = [];
                        },
814
                        tagList: that.getTagList(guid, multiple),
815
                        showLoader: that.showLoader.bind(that),
816
                        hideLoader: that.hideLoader.bind(that),
817
                        collection: that.classificationDefCollection,
818
                        enumDefCollection: that.enumDefCollection
819 820 821
                    });
                });
            },
822 823 824
            getTagList: function(guid, multiple) {
                var that = this;
                if (!multiple || multiple.length === 0) {
825 826
                    var model = this.searchCollection.find(function(item) {
                        var obj = item.toJSON();
827 828 829 830
                        if (obj.guid === guid) {
                            return true;
                        }
                    });
831
                    if (model) {
832
                        var obj = model.toJSON();
833 834 835 836 837 838 839 840
                    } else {
                        return [];
                    }
                    return obj.classificationNames;
                } else {
                    return [];
                }
            },
841
            showLoader: function() {
842 843
                this.$('.fontLoader:not(.for-ignore)').addClass('show');
                this.$('.tableOverlay').addClass('show');
844
            },
845
            hideLoader: function(options) {
846
                this.$('.fontLoader:not(.for-ignore)').removeClass('show');
847
                options && options.type === 'error' ? this.$('.ellipsis,.pagination-box').hide() : this.$('.ellipsis,.pagination-box').show(); // only show for first time and hide when type is error
848
                this.$('.tableOverlay').removeClass('show');
849
            },
850 851
            checkedValue: function(e) {
                var guid = "",
852
                    that = this,
853 854 855
                    isTagMultiSelect = $(e.currentTarget).hasClass('multiSelectTag');
                if (isTagMultiSelect && this.arr && this.arr.length) {
                    that.addTagModalView(guid, this.arr);
856
                } else {
857 858
                    guid = that.$(e.currentTarget).data("guid");
                    that.addTagModalView(guid);
859 860
                }
            },
861
            onClickTagCross: function(e) {
862 863
                var that = this,
                    tagName = $(e.target).data("name"),
864
                    guid = $(e.target).data("guid"),
865
                    assetName = $(e.target).data("assetname"),
866
                    modal = CommonViewFunction.deleteTagModel({
867
                        msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>",
868 869 870
                        titleMessage: Messages.removeTag,
                        buttonText: "Remove"
                    });
871 872
                if (modal) {
                    modal.on('ok', function() {
873 874 875 876
                        that.deleteTagData({
                            'tagName': tagName,
                            'guid': guid
                        });
877 878 879 880 881
                    });
                    modal.on('closeModal', function() {
                        modal.trigger('cancel');
                    });
                }
882
            },
883 884 885
            deleteTagData: function(options) {
                var that = this;
                CommonViewFunction.deleteTag(_.extend({}, options, {
886 887
                    showLoader: that.showLoader.bind(that),
                    hideLoader: that.hideLoader.bind(that),
888 889 890
                    callback: function() {
                        that.fetchCollection();
                    }
891
                }));
892 893
            },
            onClicknextData: function() {
894 895 896
                this.offset = this.offset + this.limit;
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
897
                });
898 899 900 901 902 903
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
904 905 906
                this.fetchCollection(null, {
                    next: true
                });
907 908
            },
            onClickpreviousData: function() {
909 910 911 912 913 914
                this.offset = this.offset - this.limit;
                if (this.offset <= -1) {
                    this.offset = 0;
                }
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
915
                });
916 917 918 919 920 921
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
922 923 924
                this.fetchCollection(null, {
                    previous: true
                });
925
            },
926 927 928 929 930 931 932
            onClickCreateEntity: function(e) {
                var that = this;
                $(e.currentTarget).blur();
                require([
                    'views/entity/CreateEntityLayoutView'
                ], function(CreateEntityLayoutView) {
                    var view = new CreateEntityLayoutView({
933
                        entityDefCollection: that.entityDefCollection,
934
                        typeHeaders: that.typeHeaders,
935 936 937 938 939
                        callback: function() {
                            that.fetchCollection();
                        }
                    });
                });
940
            },
941 942 943
            onCheckExcludeIncludeResult: function(e) {
                var flag = false,
                    val = $(e.currentTarget).attr('data-value');
944
                if (e.target.checked) {
945
                    flag = true;
946
                }
947
                if (this.value) {
948
                    this.value[val] = flag;
949
                    this.triggerUrl();
950
                }
951
                _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
952
                this.fetchCollection();
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
            },
            changePageLimit: function(e, obj) {
                if (!obj || (obj && !obj.skipViewChange)) {
                    var limit = parseInt(this.ui.showPage.val());
                    if (limit == 0) {
                        this.ui.showPage.data('select2').$container.addClass('has-error');
                        return;
                    } else {
                        this.ui.showPage.data('select2').$container.removeClass('has-error');
                    }
                    this.limit = limit;
                    this.offset = 0;
                    if (this.value) {
                        this.value.pageLimit = this.limit;
                        this.value.pageOffset = this.offset;
                        this.triggerUrl();
                    }
                    this.ui.gotoPage.val('');
                    this.ui.gotoPage.parent().removeClass('has-error');
                    _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
                    this.fetchCollection();
                }
            },
            gotoPagebtn: function(e) {
                var that = this;
                var goToPage = parseInt(this.ui.gotoPage.val());
                if (!(_.isNaN(goToPage) || goToPage <= -1)) {
                    this.offset = (goToPage - 1) * this.limit;
                    if (this.offset <= -1) {
                        this.offset = 0;
                    }
                    _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
                    if (this.offset == (this.pageFrom - 1)) {
                        Utils.notifyInfo({
                            content: Messages.search.onSamePage
                        });
                    } else {
                        if (this.value) {
                            this.value.pageOffset = this.offset;
                            this.triggerUrl();
                        }
                        // this.offset is updated in gotoPagebtn function so use next button calculation.
                        this.fetchCollection(null, { 'next': true });
                    }
                }
998
            }
999
        });
1000
    return SearchResultLayoutView;
1001
});