SearchResultLayoutView.js 55 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
            },

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

198
                    if (this.arr.length > 0) {
199
                        this.$('.multiSelectTag').show();
200
                    } else {
201
                        this.$('.multiSelectTag').hide();
202
                    }
203
                });
204
                this.listenTo(this.searchCollection, "error", function(model, response) {
205 206
                    this.hideLoader({ type: 'error' });
                    var responseJSON = response && response.responseJSON ? response.responseJSON : null,
207
                        errorText = (responseJSON && (responseJSON.errorMessage || responseJSON.message || responseJSON.error)) || 'Invalid Expression';
208
                    if (errorText) {
209
                        Utils.notifyError({
210
                            content: errorText
211
                        });
212
                        this.$('.searchTable > .well').html('<center>' + errorText + '</center>')
213
                    }
214
                }, this);
215 216 217
                this.listenTo(this.searchCollection, "state-changed", function(state) {
                    if (Utils.getUrlState.isSearchTab()) {
                        this.updateColumnList(state);
218 219
                        var excludeDefaultColumn = [];
                        if (this.value && this.value.type) {
220
                            excludeDefaultColumn = _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag", "term");
221 222 223 224 225
                            if (this.searchTableColumns[this.value.type] === null) {
                                this.ui.columnEmptyInfo.show();
                            } else {
                                this.ui.columnEmptyInfo.hide();
                            }
226
                        }
227
                        this.columnOrder = this.getColumnOrder(this.REntityTableLayoutView.$el.find('.colSort th.renderable'));
228
                        this.triggerUrl();
229
                        var attributes = this.searchCollection.filterObj.attributes;
230
                        if ((excludeDefaultColumn && attributes) && (excludeDefaultColumn.length > attributes.length || _.difference(excludeDefaultColumn, attributes).length)) {
231 232
                            this.fetchCollection(this.value);
                        }
233 234
                    }
                }, this);
235 236 237
                this.listenTo(this.searchVent, "search:refresh", function(model, response) {
                    this.fetchCollection();
                }, this);
238 239
            },
            onRender: function() {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                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: {
255
                            buttonTemplate: _.template("<button class='btn btn-action btn-sm pull-right'>Columns&nbsp<i class='fa fa-caret-down'></i></button>")
256 257 258 259 260
                        },
                        el: this.ui.colManager
                    },
                    gridOpts: {
                        emptyText: 'No Record found!',
261
                        className: 'table table-hover backgrid table-quickMenu colSort'
262 263 264 265
                    },
                    filterOpts: {},
                    paginatorOpts: {}
                };
266 267 268 269 270
                if (!this.initialView) {
                    var value = {},
                        that = this;
                    if (this.value) {
                        value = this.value;
271 272 273
                        if (value && value.includeDE) {
                            this.ui.checkDeletedEntity.prop('checked', true);
                        }
274 275 276 277 278 279 280
                        if (value && value.excludeSC) {
                            this.ui.checkSubClassification.prop('checked', true);
                        }
                        if (value && value.excludeST) {
                            this.ui.checkSubType.prop('checked', true);
                        }

281 282
                    } else {
                        value = {
283
                            'query': null,
284
                            'searchType': 'basic'
285 286
                        };
                    }
287
                    this.updateColumnList();
288 289 290 291 292
                    if (this.value && this.searchTableColumns && this.searchTableColumns[this.value.type] === null) {
                        this.ui.columnEmptyInfo.show();
                    } else {
                        this.ui.columnEmptyInfo.hide();
                    }
293
                    this.fetchCollection(value, _.extend({ 'fromUrl': true }, (this.value && this.value.pageOffset ? { 'next': true } : null)));
294 295 296 297 298 299 300 301 302
                    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 });
                    }
303 304 305
                } else {
                    if (Globals.entityTypeConfList) {
                        this.$(".entityLink").show();
306
                    }
307 308 309 310 311
                    if (this.isTypeTagNotExists) {
                        Utils.notifyError({
                            content: Messages.search.notExists
                        });
                    }
312 313
                }
            },
314 315 316 317 318 319
            getColumnOrderWithPosition: function() {
                var that = this;
                return _.map(that.columnOrder, function(value, key) {
                    return key + "::" + value;
                }).join(",");
            },
320 321 322
            triggerUrl: function(options) {
                Utils.setUrl(_.extend({
                    url: Utils.getUrlState.getQueryUrl().queyParams[0],
323
                    urlParams: this.columnOrder ? _.extend(this.value, { 'uiParameters': this.getColumnOrderWithPosition() }) : this.value,
324 325 326 327
                    mergeBrowserUrl: false,
                    trigger: false,
                    updateTabState: true
                }, options));
328
            },
329 330
            updateColumnList: function(updatedList) {
                if (updatedList) {
331
                    var listOfColumns = [];
332 333 334 335 336 337
                    _.map(updatedList, function(obj) {
                        var key = obj.name;
                        if (obj.renderable) {
                            listOfColumns.push(obj.name);
                        }
                    });
338
                    listOfColumns = _.sortBy(listOfColumns);
339
                    this.value.attributes = listOfColumns.length ? listOfColumns.join(",") : null;
340
                    if (this.value && this.value.type && this.searchTableColumns) {
341 342 343 344
                        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(",");
345 346
                }
            },
347
            fetchCollection: function(value, options) {
348
                var that = this,
349 350 351 352 353 354
                    isPostMethod = (this.value && this.value.searchType === "basic"),
                    isSearchTab = Utils.getUrlState.isSearchTab(),
                    tagFilters = null,
                    entityFilters = null;
                if (isSearchTab) {
                    tagFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.tagFilters);
355
                    entityFilters = CommonViewFunction.attributeFilter.generateAPIObj(this.value.entityFilters);
356 357 358
                }

                if (isPostMethod && isSearchTab) {
359
                    var excludeDefaultColumn = this.value.type && this.searchTableColumns ? _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag") : null,
360 361 362 363 364 365 366
                        filterObj = {
                            'entityFilters': entityFilters,
                            'tagFilters': tagFilters,
                            'attributes': excludeDefaultColumn ? excludeDefaultColumn : null
                        };
                }

367
                this.showLoader();
368
                if (Globals.searchApiCallRef && Globals.searchApiCallRef.readyState === 1) {
369 370
                    Globals.searchApiCallRef.abort();
                }
371
                var apiObj = {
372
                    skipDefaultError: true,
373
                    sort: false,
374
                    success: function(dataOrCollection, response) {
375 376 377
                        if (that.isDestroyed) {
                            return;
                        }
378
                        Globals.searchApiCallRef = undefined;
379 380 381
                        var isFirstPage = that.offset === 0,
                            dataLength = 0,
                            goToPage = that.ui.gotoPage.val();
382 383 384
                        if (!(that.ui.pageRecordText instanceof jQuery)) {
                            return;
                        }
385 386 387 388 389 390 391
                        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)) {
392
                            /* User clicks on next button and server returns
393 394
                            empty response then disabled the next button without rendering table*/

395
                            that.hideLoader();
396 397 398
                            var pageNumber = that.activePage + 1;
                            if (goToPage) {
                                pageNumber = goToPage;
399
                                that.offset = (that.activePage - 1) * that.limit;
400 401 402 403 404 405 406 407 408 409 410 411
                            } 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'
                            });
412 413
                            return;
                        }
414
                        if (isPostMethod) {
415 416
                            that.searchCollection.referredEntities = dataOrCollection.referredEntities;
                            Utils.findAndMergeRefEntity(dataOrCollection.entities, dataOrCollection.referredEntities);
417
                            that.searchCollection.reset(dataOrCollection.entities, { silent: true });
418
                        }
419

420

421
                        /*Next button check.
422
                        It's outside of Previous button else condition
423 424
                        because when user comes from 2 page to 1 page than we need to check next button.*/
                        if (dataLength < that.limit) {
425 426 427 428
                            that.ui.nextData.attr('disabled', true);
                        } else {
                            that.ui.nextData.attr('disabled', false);
                        }
429 430 431 432 433 434 435 436 437 438

                        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);
439 440
                            that.pageFrom = 1;
                            that.pageTo = that.limit;
441 442 443 444 445
                        } else {
                            that.ui.previousData.attr('disabled', false);
                        }

                        if (options && options.next) {
446 447 448
                            //on next click, adding "1" for showing the another records.
                            that.pageTo = that.offset + that.limit;
                            that.pageFrom = that.offset + 1;
449
                        } else if (!isFirstPage && options && options.previous) {
450 451 452
                            that.pageTo = that.pageTo - that.limit;
                            that.pageFrom = (that.pageTo - that.limit) + 1;
                        }
453
                        that.ui.pageRecordText.html("Showing  <u>" + that.searchCollection.models.length + " records</u> From " + that.pageFrom + " - " + that.pageTo);
454 455 456
                        that.activePage = Math.round(that.pageTo / that.limit);
                        that.ui.activePage.attr('title', "Page " + that.activePage);
                        that.ui.activePage.text(that.activePage);
457
                        that.renderTableLayoutView();
458

459
                        if (Utils.getUrlState.isSearchTab() && value && !value.profileDBView) {
460
                            var searchString = 'Results for: <span class="filterQuery">' + CommonViewFunction.generateQueryOfFilter(that.value) + "</span>";
461 462 463 464
                            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);
465
                        }
466
                    },
467 468
                    silent: true,
                    reset: true
469
                }
470 471 472 473
                if (this.value) {
                    var checkBoxValue = {
                        'excludeDeletedEntities': (this.value.includeDE ? false : true),
                        'includeSubClassifications': (this.value.excludeSC ? false : true),
474
                        'includeSubTypes': (this.value.excludeST ? false : true),
475
                        'includeClassificationAttributes': true // server will return classication details with guid
476 477
                    }
                }
478 479 480 481
                if (value) {
                    if (value.searchType) {
                        this.searchCollection.url = UrlLinks.searchApiUrl(value.searchType);
                    }
482
                    _.extend(this.searchCollection.queryParams, { 'limit': this.limit, 'offset': this.offset, 'query': _.trim(value.query), 'typeName': value.type || null, 'classification': value.tag || null, 'termName': value.term || null });
483
                    if (value.profileDBView && value.typeName && value.guid) {
484 485
                        var profileParam = {};
                        profileParam['guid'] = value.guid;
486
                        profileParam['relation'] = value.typeName === 'hive_db' ? '__hive_table.db' : '__hbase_table.namespace';
487 488
                        profileParam['sortBy'] = 'name';
                        profileParam['sortOrder'] = 'ASCENDING';
489
                        _.extend(this.searchCollection.queryParams, profileParam);
490
                    }
491
                    if (isPostMethod) {
492
                        this.searchCollection.filterObj = _.extend({}, filterObj);
493
                        apiObj['data'] = _.extend(checkBoxValue, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification', 'termName'))
494 495 496
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
497
                        this.searchCollection.filterObj = null;
498
                        if (this.value.profileDBView) {
499
                            _.extend(this.searchCollection.queryParams, checkBoxValue);
500
                        }
501 502 503 504
                        Globals.searchApiCallRef = this.searchCollection.fetch(apiObj);
                    }
                } else {
                    if (isPostMethod) {
505
                        apiObj['data'] = _.extend(checkBoxValue, filterObj, _.pick(this.searchCollection.queryParams, 'query', 'excludeDeletedEntities', 'limit', 'offset', 'typeName', 'classification', 'termName'));
506 507 508
                        Globals.searchApiCallRef = this.searchCollection.getBasicRearchResult(apiObj);
                    } else {
                        apiObj.data = null;
509
                        if (this.value.profileDBView) {
510
                            _.extend(this.searchCollection.queryParams, checkBoxValue);
511
                        }
512 513 514 515 516 517 518 519 520 521 522
                        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
                    }));
523
                });
524
            },
525
            renderTableLayoutView: function(col) {
526
                var that = this;
527
                require(['utils/TableLayout'], function(TableLayout) {
528
                    // displayOrder added for column manager
529 530 531 532 533
                    if (that.value.uiParameters) {
                        var savedColumnOrder = _.object(that.value.uiParameters.split(',').map(function(a) {
                            return a.split('::');
                        })); // get Column position from string to object
                    }
534
                    var columnCollection = Backgrid.Columns.extend({
535
                        sortKey: "displayOrder",
536 537 538 539 540
                        comparator: function(item) {
                            return item.get(this.sortKey) || 999;
                        },
                        setPositions: function() {
                            _.each(this.models, function(model, index) {
541
                                model.set("displayOrder", (savedColumnOrder == null ? index : parseInt(savedColumnOrder[model.get('label')])) + 1, { silent: true });
542 543 544 545
                            });
                            return this;
                        }
                    });
546
                    var columns = new columnCollection((that.searchCollection.dynamicTable ? that.getDaynamicColumns(that.searchCollection.toJSON()) : that.getFixedDslColumn()));
547
                    columns.setPositions().sort();
548
                    var table = new TableLayout(_.extend({}, that.commonTableOptions, {
549
                        columns: columns
550
                    }));
551 552 553
                    if (!that.REntityTableLayoutView) {
                        return;
                    }
554
                    that.REntityTableLayoutView.show(table);
555 556
                    if (that.value.searchType !== "dsl") {
                        that.ui.containerCheckBox.show();
557
                    } else {
558
                        that.ui.containerCheckBox.hide();
559
                    }
560
                    that.$(".ellipsis .inputAssignTag").hide();
561
                    table.trigger("grid:refresh"); /*Event fire when table rendered*/
562 563 564 565 566 567 568
                    if (that.isDisable !== true) {
                        tableDragger(document.querySelector(".colSort")).on('drop', function(from, to, el) {
                            that.columnOrder = that.getColumnOrder(el.querySelectorAll('th.renderable'));
                            table.trigger("grid:refresh:update");
                            that.triggerUrl();
                        });
                    }
569
                    that.checkTableFetch();
570 571
                });
            },
572 573 574 575 576 577 578
            getColumnOrder: function(arr) {
                var obj = {};
                for (var i = 0; i < arr.length; ++i) {
                    obj[(arr[i].innerText == "" ? 'Select' : arr[i].innerText)] = i;
                }
                return obj;
            },
579
            checkTableFetch: function() {
580
                if (this.asyncFetchCounter <= 0) {
581
                    this.hideLoader();
582 583
                    Utils.generatePopover({
                        el: this.$('[data-id="showMoreLess"]'),
584
                        contentClass: 'popover-tag-term',
585
                        viewFixedPopover: true,
586
                        popoverOptions: {
587
                            container: null,
588
                            content: function() {
589
                                return $(this).find('.popup-tag-term').children().clone();
590 591 592
                            }
                        }
                    });
593 594
                }
            },
595 596
            getFixedDslColumn: function() {
                var that = this,
597
                    nameCheck = 0,
598
                    columnToShow = null,
599
                    col = {};
600
                if (this.value && this.value.searchType === "basic" && this.searchTableColumns && (this.searchTableColumns[this.value.type] !== undefined)) {
601 602
                    columnToShow = this.searchTableColumns[this.value.type] == null ? [] : this.searchTableColumns[this.value.type];
                }
603

604 605
                col['Check'] = {
                    name: "selected",
606
                    label: "Select",
607
                    cell: "select-row",
608 609
                    resizeable: false,
                    orderable: false,
610
                    renderable: (columnToShow ? _.contains(columnToShow, 'selected') : true),
611 612
                    headerCell: "select-all"
                };
613

614

615
                col['name'] = {
616
                    label: this.value && this.value.profileDBView ? "Table Name" : "Name",
617 618 619
                    cell: "html",
                    editable: false,
                    sortable: false,
620 621 622
                    resizeable: true,
                    orderable: true,
                    renderable: true,
623 624 625
                    className: "searchTableName",
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
626 627 628
                            var obj = model.toJSON(),
                                nameHtml = "",
                                name = Utils.getName(obj);
629
                            if (obj.guid) {
630 631 632 633 634
                                if (obj.guid == "-1") {
                                    nameHtml = '<span title="' + name + '">' + name + '</span>';
                                } else {
                                    nameHtml = '<a title="' + name + '" href="#!/detailPage/' + obj.guid + (that.fromView ? "?from=" + that.fromView : "") + '">' + name + '</a>';
                                }
635
                            } else {
636
                                nameHtml = '<span title="' + name + '">' + name + '</span>';
637 638
                            }
                            if (obj.status && Enums.entityStateReadOnly[obj.status]) {
639
                                nameHtml += '<button type="button" title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
640
                                return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>';
641
                            }
642
                            return nameHtml;
643 644 645
                        }
                    })
                };
646

647 648
                col['owner'] = {
                    label: "Owner",
649 650
                    cell: "String",
                    editable: false,
651
                    sortable: false,
652 653 654
                    resizeable: true,
                    orderable: true,
                    renderable: true,
655 656
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
657
                            var obj = model.toJSON();
658 659
                            if (obj && obj.attributes && obj.attributes.owner) {
                                return obj.attributes.owner;
660 661 662
                            }
                        }
                    })
663
                };
664 665


666 667 668 669 670 671 672 673 674 675 676 677 678 679
                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 '-'
                                }
680
                            }
681 682 683 684
                        })
                    }
                }
                if (this.value && !this.value.profileDBView) {
685

686 687 688 689 690 691 692 693 694 695 696 697 698 699
                    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;
                                }
700
                            }
701 702
                        })
                    };
703 704


705 706 707 708 709 710 711 712 713 714 715 716 717 718
                    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>';
                                }
719
                            }
720 721
                        })
                    };
722
                    this.getTagCol({ 'col': col, 'columnToShow': columnToShow });
723
                    if ((!_.contains(["glossary"], this.fromView))) {
724 725
                        this.getTermCol({ 'col': col, 'columnToShow': columnToShow });
                    }
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
                    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
757 758
                                                };
                                                tempObj.valueObject[key] = modelObj.attributes[key];
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
                                                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) {
776 777 778 779 780 781 782 783 784 785 786 787 788 789
                        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) {
790
                                            nameHtml = '<a title="' + name + '" href="#!/detailPage/' + modelObj.guid + (that.fromView ? "?from=" + that.fromView : "") + '">' + name + '</a>';
791 792 793 794 795 796
                                        } 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>';
797
                                        }
798 799 800 801 802 803 804 805 806 807
                                        return nameHtml;
                                    } else if (modelObj && !_.isUndefined(modelObj[key])) {
                                        var tempObj = {
                                            'scope': that,
                                            // 'attributeDefs':
                                            'valueObject': {},
                                            'isTable': false
                                        };
                                        tempObj.valueObject[key] = modelObj[key];
                                        return CommonViewFunction.propertyTable(tempObj);
808
                                    }
809 810 811
                                }
                            })
                        };
812 813 814 815
                    });
                }
                return this.searchCollection.constructor.getTableCols(col, this.searchCollection);
            },
816
            getTagCol: function(options) {
817 818 819 820
                var that = this,
                    columnToShow = options.columnToShow,
                    col = options.col;
                if (col) {
821
                    col['tag'] = {
822
                        label: "Classifications",
823 824 825
                        cell: "Html",
                        editable: false,
                        sortable: false,
826
                        resizeable: true,
827
                        orderable: true,
828 829
                        renderable: (columnToShow ? _.contains(columnToShow, 'tag') : true),
                        className: 'searchTag',
830 831
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
832
                                var obj = model.toJSON();
833 834 835
                                if (obj.guid == "-1") {
                                    return
                                }
836
                                if (obj.status && Enums.entityStateReadOnly[obj.status]) {
837
                                    return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj); + '</div>';
838
                                } else {
839
                                    return CommonViewFunction.tagForTable(obj);
840
                                }
841

842 843 844
                            }
                        })
                    };
845
                }
846
            },
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
            getTermCol: function(options) {
                var that = this,
                    columnToShow = options.columnToShow,
                    col = options.col;
                if (col) {
                    col['term'] = {
                        label: "Term",
                        cell: "Html",
                        editable: false,
                        sortable: false,
                        resizeable: true,
                        orderable: true,
                        renderable: (columnToShow ? _.contains(columnToShow, 'term') : true),
                        className: 'searchTag',
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
                                var obj = model.toJSON();
864 865 866
                                if (obj.guid == "-1") {
                                    return
                                }
867
                                if (obj.typeName && !(_.startsWith(obj.typeName, "AtlasGlossary"))) {
868 869 870 871 872
                                    if (obj.status && Enums.entityStateReadOnly[obj.status]) {
                                        return '<div class="readOnly">' + CommonViewFunction.termForTable(obj); + '</div>';
                                    } else {
                                        return CommonViewFunction.termForTable(obj);
                                    }
873 874 875 876 877 878
                                }
                            }
                        })
                    };
                }
            },
879
            addTagModalView: function(guid, multiple) {
880
                var that = this;
881
                require(['views/tag/AddTagModalView'], function(AddTagModalView) {
882
                    var view = new AddTagModalView({
883 884
                        guid: guid,
                        multiple: multiple,
885 886
                        callback: function() {
                            that.fetchCollection();
887 888
                            that.arr = [];
                        },
889
                        tagList: that.getTagList(guid, multiple),
890
                        showLoader: that.showLoader.bind(that),
891
                        hideLoader: that.hideLoader.bind(that),
892
                        collection: that.classificationDefCollection,
893
                        enumDefCollection: that.enumDefCollection
894 895 896
                    });
                });
            },
897 898 899
            getTagList: function(guid, multiple) {
                var that = this;
                if (!multiple || multiple.length === 0) {
900 901
                    var model = this.searchCollection.find(function(item) {
                        var obj = item.toJSON();
902 903 904 905
                        if (obj.guid === guid) {
                            return true;
                        }
                    });
906
                    if (model) {
907
                        var obj = model.toJSON();
908 909 910
                    } else {
                        return [];
                    }
911 912 913 914 915
                    return _.compact(_.map(obj.classifications, function(val) {
                        if (val.entityGuid == guid) {
                            return val.typeName
                        }
                    }));
916 917 918 919
                } else {
                    return [];
                }
            },
920
            showLoader: function() {
921 922
                this.$('.fontLoader:not(.for-ignore)').addClass('show');
                this.$('.tableOverlay').addClass('show');
923
            },
924
            hideLoader: function(options) {
925
                this.$('.fontLoader:not(.for-ignore)').removeClass('show');
926
                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
927
                this.$('.tableOverlay').removeClass('show');
928
            },
929 930
            checkedValue: function(e) {
                var guid = "",
931
                    that = this,
932 933 934
                    isTagMultiSelect = $(e.currentTarget).hasClass('multiSelectTag');
                if (isTagMultiSelect && this.arr && this.arr.length) {
                    that.addTagModalView(guid, this.arr);
935
                } else {
936 937
                    guid = that.$(e.currentTarget).data("guid");
                    that.addTagModalView(guid);
938 939
                }
            },
940 941 942 943 944 945 946 947 948 949 950 951 952
            onClickAddTermBtn: function(e) {
                var that = this,
                    entityGuid = $(e.currentTarget).data("guid");
                require(['views/glossary/AssignTermLayoutView'], function(AssignTermLayoutView) {
                    var view = new AssignTermLayoutView({
                        guid: entityGuid,
                        callback: function() {
                            that.fetchCollection();
                        },
                        glossaryCollection: that.glossaryCollection,
                    });
                });
            },
953
            onClickTagCross: function(e) {
954 955
                var that = this,
                    tagName = $(e.target).data("name"),
956
                    guid = $(e.target).data("guid"),
957 958 959 960 961 962 963 964 965 966 967 968 969 970
                    assetName = $(e.target).data("assetname");
                CommonViewFunction.deleteTag({
                    tagName: tagName,
                    guid: guid,
                    msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>",
                    titleMessage: Messages.removeTag,
                    okText: "Remove",
                    showLoader: that.showLoader.bind(that),
                    hideLoader: that.hideLoader.bind(that),
                    callback: function() {
                        that.fetchCollection();
                    }
                });

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
            onClickTermCross: function(e) {
                var $el = $(e.target),
                    termGuid = $el.data('termguid'),
                    guid = $el.data('guid'),
                    termName = $(e.currentTarget).text(),
                    assetname = $el.data('assetname'),
                    meanings = this.searchCollection.find({ "guid": guid }).get("meanings"),
                    that = this,
                    termObj = _.find(meanings, { termGuid: termGuid });
                CommonViewFunction.removeCategoryTermAssociation({
                    termGuid: termGuid,
                    model: {
                        guid: guid,
                        relationshipGuid: termObj.relationGuid
                    },
                    collection: that.glossaryCollection,
                    msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(termName) + "</b> assignment from" + " " + "<b>" + assetname + "?</b></div>",
                    titleMessage: Messages.glossary.removeTermfromEntity,
                    isEntityView: true,
                    buttonText: "Remove",
                    callback: function() {
                        that.fetchCollection();
                    }
                });
            },
997
            onClicknextData: function() {
998 999 1000
                this.offset = this.offset + this.limit;
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
1001
                });
1002 1003 1004 1005 1006 1007
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
1008 1009 1010
                this.fetchCollection(null, {
                    next: true
                });
1011 1012
            },
            onClickpreviousData: function() {
1013 1014 1015 1016 1017 1018
                this.offset = this.offset - this.limit;
                if (this.offset <= -1) {
                    this.offset = 0;
                }
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
1019
                });
1020 1021 1022 1023 1024 1025
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
                this.ui.gotoPage.val('');
                this.ui.gotoPage.parent().removeClass('has-error');
1026 1027 1028
                this.fetchCollection(null, {
                    previous: true
                });
1029
            },
1030 1031 1032 1033 1034 1035 1036
            onClickCreateEntity: function(e) {
                var that = this;
                $(e.currentTarget).blur();
                require([
                    'views/entity/CreateEntityLayoutView'
                ], function(CreateEntityLayoutView) {
                    var view = new CreateEntityLayoutView({
1037
                        entityDefCollection: that.entityDefCollection,
1038
                        typeHeaders: that.typeHeaders,
1039 1040 1041 1042 1043
                        callback: function() {
                            that.fetchCollection();
                        }
                    });
                });
1044
            },
1045 1046 1047
            onCheckExcludeIncludeResult: function(e) {
                var flag = false,
                    val = $(e.currentTarget).attr('data-value');
1048
                if (e.target.checked) {
1049
                    flag = true;
1050
                }
1051
                if (this.value) {
1052
                    this.value[val] = flag;
1053
                    this.triggerUrl();
1054
                }
1055
                _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
1056
                this.fetchCollection();
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
            },
            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 });
                    }
                }
1102
            }
1103
        });
1104
    return SearchResultLayoutView;
1105
});