SearchResultLayoutView.js 56.3 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
    'utils/Messages',
    'utils/Enums',
32 33 34
    'utils/UrlLinks',
    'platform'
], function(require, Backbone, tableDragger, SearchResultLayoutViewTmpl, Modal, VEntity, Utils, Globals, VSearchList, VCommon, CommonViewFunction, Messages, Enums, UrlLinks, platform) {
35 36
    'use strict';

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

42
            template: SearchResultLayoutViewTmpl,
43 44 45 46 47

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

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

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

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

                if (isPostMethod && isSearchTab) {
369
                    var excludeDefaultColumn = this.value.type && this.searchTableColumns ? _.without(this.searchTableColumns[this.value.type], "selected", "name", "description", "typeName", "owner", "tag") : null,
370 371 372 373 374 375 376
                        filterObj = {
                            'entityFilters': entityFilters,
                            'tagFilters': tagFilters,
                            'attributes': excludeDefaultColumn ? excludeDefaultColumn : null
                        };
                }

377
                this.showLoader();
378
                if (Globals.searchApiCallRef && Globals.searchApiCallRef.readyState === 1) {
379 380
                    Globals.searchApiCallRef.abort();
                }
381
                var apiObj = {
382
                    skipDefaultError: true,
383
                    sort: false,
384
                    success: function(dataOrCollection, response) {
385 386 387
                        if (that.isDestroyed) {
                            return;
                        }
388 389 390
                        that.ui.gotoPage.val('');
                        that.ui.gotoPage.parent().removeClass('has-error');
                        that.ui.gotoPagebtn.prop("disabled", true);
391
                        Globals.searchApiCallRef = undefined;
392 393 394
                        var isFirstPage = that.offset === 0,
                            dataLength = 0,
                            goToPage = that.ui.gotoPage.val();
395 396 397
                        if (!(that.ui.pageRecordText instanceof jQuery)) {
                            return;
                        }
398 399 400 401 402 403 404
                        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)) {
405
                            /* User clicks on next button and server returns
406 407
                            empty response then disabled the next button without rendering table*/

408
                            that.hideLoader();
409 410 411
                            var pageNumber = that.activePage + 1;
                            if (goToPage) {
                                pageNumber = goToPage;
412
                                that.offset = (that.activePage - 1) * that.limit;
413 414 415 416 417 418 419 420 421 422 423 424
                            } 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'
                            });
425 426
                            return;
                        }
427
                        if (isPostMethod) {
428
                            that.searchCollection.referredEntities = dataOrCollection.referredEntities;
429 430 431 432
                            Utils.findAndMergeRefEntity({
                                attributeObject: dataOrCollection.entities,
                                referredEntities: dataOrCollection.referredEntities
                            });
433
                            that.searchCollection.fullCollection.reset(dataOrCollection.entities, { silent: false });
434
                        }
435

436

437
                        /*Next button check.
438
                        It's outside of Previous button else condition
439 440
                        because when user comes from 2 page to 1 page than we need to check next button.*/
                        if (dataLength < that.limit) {
441 442 443 444
                            that.ui.nextData.attr('disabled', true);
                        } else {
                            that.ui.nextData.attr('disabled', false);
                        }
445 446 447 448 449 450 451 452 453 454

                        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);
455 456
                            that.pageFrom = 1;
                            that.pageTo = that.limit;
457 458 459 460 461
                        } else {
                            that.ui.previousData.attr('disabled', false);
                        }

                        if (options && options.next) {
462 463 464
                            //on next click, adding "1" for showing the another records.
                            that.pageTo = that.offset + that.limit;
                            that.pageFrom = that.offset + 1;
465
                        } else if (!isFirstPage && options && options.previous) {
466 467 468
                            that.pageTo = that.pageTo - that.limit;
                            that.pageFrom = (that.pageTo - that.limit) + 1;
                        }
469
                        that.ui.pageRecordText.html("Showing  <u>" + that.searchCollection.models.length + " records</u> From " + that.pageFrom + " - " + that.pageTo);
470 471 472
                        that.activePage = Math.round(that.pageTo / that.limit);
                        that.ui.activePage.attr('title', "Page " + that.activePage);
                        that.ui.activePage.text(that.activePage);
473
                        that.renderTableLayoutView();
474

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

                    that.tableRender({ "order": savedColumnOrder, "table": TableLayout });
598
                    that.checkTableFetch();
599 600
                });
            },
601 602 603
            getColumnOrder: function(arr) {
                var obj = {};
                for (var i = 0; i < arr.length; ++i) {
604 605
                    var innerText = arr[i].innerText.trim();
                    obj[(innerText == "" ? 'Select' : innerText)] = i;
606 607 608
                }
                return obj;
            },
609
            checkTableFetch: function() {
610
                if (this.asyncFetchCounter <= 0) {
611
                    this.hideLoader();
612 613
                    Utils.generatePopover({
                        el: this.$('[data-id="showMoreLess"]'),
614
                        contentClass: 'popover-tag-term',
615
                        viewFixedPopover: true,
616
                        popoverOptions: {
617
                            container: null,
618
                            content: function() {
619
                                return $(this).find('.popup-tag-term').children().clone();
620 621 622
                            }
                        }
                    });
623 624
                }
            },
625 626
            getFixedDslColumn: function() {
                var that = this,
627
                    nameCheck = 0,
628
                    columnToShow = null,
629
                    col = {};
630
                if (this.value && this.value.searchType === "basic" && this.searchTableColumns && (this.searchTableColumns[this.value.type] !== undefined)) {
631 632
                    columnToShow = this.searchTableColumns[this.value.type] == null ? [] : this.searchTableColumns[this.value.type];
                }
633

634 635
                col['Check'] = {
                    name: "selected",
636
                    label: "Select",
637
                    cell: "select-row",
638 639
                    resizeable: false,
                    orderable: false,
640
                    renderable: (columnToShow ? _.contains(columnToShow, 'selected') : true),
641 642
                    headerCell: "select-all"
                };
643

644

645
                col['name'] = {
646
                    label: this.value && this.value.profileDBView ? "Table Name" : "Name",
647 648
                    cell: "html",
                    editable: false,
649
                    resizeable: true,
650
                    orderable: false,
651
                    renderable: true,
652 653 654
                    className: "searchTableName",
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
655 656 657
                            var obj = model.toJSON(),
                                nameHtml = "",
                                name = Utils.getName(obj);
658
                            if (obj.guid) {
659 660 661 662 663
                                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>';
                                }
664
                            } else {
665
                                nameHtml = '<span title="' + name + '">' + name + '</span>';
666 667
                            }
                            if (obj.status && Enums.entityStateReadOnly[obj.status]) {
668
                                nameHtml += '<button type="button" title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
669
                                return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>';
670
                            }
671
                            return nameHtml;
672 673 674
                        }
                    })
                };
675

676 677
                col['owner'] = {
                    label: "Owner",
678 679
                    cell: "String",
                    editable: false,
680 681 682
                    resizeable: true,
                    orderable: true,
                    renderable: true,
683 684
                    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                        fromRaw: function(rawValue, model) {
685
                            var obj = model.toJSON();
686 687
                            if (obj && obj.attributes && obj.attributes.owner) {
                                return obj.attributes.owner;
688 689 690
                            }
                        }
                    })
691
                };
692 693


694 695 696 697 698 699 700 701 702 703 704 705 706
                if (this.value && this.value.profileDBView) {
                    col['createTime'] = {
                        label: "Date Created",
                        cell: "Html",
                        editable: 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 '-'
                                }
707
                            }
708 709 710 711
                        })
                    }
                }
                if (this.value && !this.value.profileDBView) {
712

713 714 715 716 717 718 719 720 721 722 723 724 725
                    col['description'] = {
                        label: "Description",
                        cell: "String",
                        editable: 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;
                                }
726
                            }
727 728
                        })
                    };
729 730


731 732 733 734 735 736 737 738 739 740 741 742 743
                    col['typeName'] = {
                        label: "Type",
                        cell: "Html",
                        editable: 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>';
                                }
744
                            }
745 746
                        })
                    };
747
                    this.getTagCol({ 'col': col, 'columnToShow': columnToShow });
748
                    if ((!_.contains(["glossary"], this.fromView))) {
749 750
                        this.getTermCol({ 'col': col, 'columnToShow': columnToShow });
                    }
751

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
                    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,
                                    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
781 782
                                                };
                                                tempObj.valueObject[key] = modelObj.attributes[key];
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
                                                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) {
800 801 802 803 804 805 806 807 808 809 810 811 812
                        col[key] = {
                            label: key.capitalize(),
                            cell: "Html",
                            editable: 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) {
813
                                            nameHtml = '<a title="' + name + '" href="#!/detailPage/' + modelObj.guid + (that.fromView ? "?from=" + that.fromView : "") + '">' + name + '</a>';
814 815 816 817 818 819
                                        } 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>';
820
                                        }
821 822 823 824 825 826 827 828 829 830
                                        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);
831
                                    }
832 833 834
                                }
                            })
                        };
835 836 837 838
                    });
                }
                return this.searchCollection.constructor.getTableCols(col, this.searchCollection);
            },
839
            getTagCol: function(options) {
840 841 842 843
                var that = this,
                    columnToShow = options.columnToShow,
                    col = options.col;
                if (col) {
844
                    col['tag'] = {
845
                        label: "Classifications",
846 847 848
                        cell: "Html",
                        editable: false,
                        sortable: false,
849
                        resizeable: true,
850
                        orderable: true,
851 852
                        renderable: (columnToShow ? _.contains(columnToShow, 'tag') : true),
                        className: 'searchTag',
853 854
                        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                            fromRaw: function(rawValue, model) {
855
                                var obj = model.toJSON();
856 857 858
                                if (obj.guid == "-1") {
                                    return
                                }
859
                                if (obj.status && Enums.entityStateReadOnly[obj.status]) {
860
                                    return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj); + '</div>';
861
                                } else {
862
                                    return CommonViewFunction.tagForTable(obj);
863
                                }
864

865 866 867
                            }
                        })
                    };
868
                }
869
            },
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
            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();
887 888 889
                                if (obj.guid == "-1") {
                                    return
                                }
890
                                if (obj.typeName && !(_.startsWith(obj.typeName, "AtlasGlossary"))) {
891 892 893 894 895
                                    if (obj.status && Enums.entityStateReadOnly[obj.status]) {
                                        return '<div class="readOnly">' + CommonViewFunction.termForTable(obj); + '</div>';
                                    } else {
                                        return CommonViewFunction.termForTable(obj);
                                    }
896 897 898 899 900 901
                                }
                            }
                        })
                    };
                }
            },
902
            addTagModalView: function(guid, multiple) {
903
                var that = this;
904
                require(['views/tag/AddTagModalView'], function(AddTagModalView) {
905
                    var view = new AddTagModalView({
906 907
                        guid: guid,
                        multiple: multiple,
908 909
                        callback: function() {
                            that.fetchCollection();
910 911
                            that.arr = [];
                        },
912
                        tagList: that.getTagList(guid, multiple),
913
                        showLoader: that.showLoader.bind(that),
914
                        hideLoader: that.hideLoader.bind(that),
915
                        collection: that.classificationDefCollection,
916
                        enumDefCollection: that.enumDefCollection
917 918 919
                    });
                });
            },
920 921 922
            getTagList: function(guid, multiple) {
                var that = this;
                if (!multiple || multiple.length === 0) {
923 924
                    var model = this.searchCollection.find(function(item) {
                        var obj = item.toJSON();
925 926 927 928
                        if (obj.guid === guid) {
                            return true;
                        }
                    });
929
                    if (model) {
930
                        var obj = model.toJSON();
931 932 933
                    } else {
                        return [];
                    }
934 935 936 937 938
                    return _.compact(_.map(obj.classifications, function(val) {
                        if (val.entityGuid == guid) {
                            return val.typeName
                        }
                    }));
939 940 941 942
                } else {
                    return [];
                }
            },
943
            showLoader: function() {
944 945
                this.$('.fontLoader:not(.for-ignore)').addClass('show');
                this.$('.tableOverlay').addClass('show');
946
            },
947
            hideLoader: function(options) {
948
                this.$('.fontLoader:not(.for-ignore)').removeClass('show');
949
                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
950
                this.$('.tableOverlay').removeClass('show');
951
            },
952 953
            checkedValue: function(e) {
                var guid = "",
954
                    that = this,
955 956 957
                    isTagMultiSelect = $(e.currentTarget).hasClass('multiSelectTag');
                if (isTagMultiSelect && this.arr && this.arr.length) {
                    that.addTagModalView(guid, this.arr);
958
                } else {
959 960
                    guid = that.$(e.currentTarget).data("guid");
                    that.addTagModalView(guid);
961 962
                }
            },
963 964
            onClickAddTermBtn: function(e) {
                var that = this,
965 966
                    entityGuid = $(e.currentTarget).data("guid"),
                    associatedTerms = this.searchCollection.find({ guid: entityGuid }).get('meanings');
967 968 969
                require(['views/glossary/AssignTermLayoutView'], function(AssignTermLayoutView) {
                    var view = new AssignTermLayoutView({
                        guid: entityGuid,
970
                        associatedTerms: associatedTerms,
971 972 973 974 975 976 977
                        callback: function() {
                            that.fetchCollection();
                        },
                        glossaryCollection: that.glossaryCollection,
                    });
                });
            },
978
            onClickTagCross: function(e) {
979 980
                var that = this,
                    tagName = $(e.target).data("name"),
981
                    guid = $(e.target).data("guid"),
982
                    entityGuid = $(e.target).data("entityguid"),
983 984 985 986
                    assetName = $(e.target).data("assetname");
                CommonViewFunction.deleteTag({
                    tagName: tagName,
                    guid: guid,
987
                    associatedGuid: guid != entityGuid ? entityGuid : null,
988 989 990 991 992 993 994 995 996 997
                    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();
                    }
                });

998
            },
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            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();
                    }
                });
            },
1024
            onClicknextData: function() {
1025 1026 1027
                this.offset = this.offset + this.limit;
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
1028
                });
1029 1030 1031 1032
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
1033 1034 1035
                this.fetchCollection(null, {
                    next: true
                });
1036 1037
            },
            onClickpreviousData: function() {
1038 1039 1040 1041 1042 1043
                this.offset = this.offset - this.limit;
                if (this.offset <= -1) {
                    this.offset = 0;
                }
                _.extend(this.searchCollection.queryParams, {
                    offset: this.offset
1044
                });
1045 1046 1047 1048
                if (this.value) {
                    this.value.pageOffset = this.offset;
                    this.triggerUrl();
                }
1049 1050 1051
                this.fetchCollection(null, {
                    previous: true
                });
1052
            },
1053 1054 1055 1056 1057 1058 1059
            onClickCreateEntity: function(e) {
                var that = this;
                $(e.currentTarget).blur();
                require([
                    'views/entity/CreateEntityLayoutView'
                ], function(CreateEntityLayoutView) {
                    var view = new CreateEntityLayoutView({
1060
                        entityDefCollection: that.entityDefCollection,
1061
                        typeHeaders: that.typeHeaders,
1062 1063 1064 1065 1066
                        callback: function() {
                            that.fetchCollection();
                        }
                    });
                });
1067
            },
1068 1069 1070
            onCheckExcludeIncludeResult: function(e) {
                var flag = false,
                    val = $(e.currentTarget).attr('data-value');
1071
                if (e.target.checked) {
1072
                    flag = true;
1073
                }
1074
                if (this.value) {
1075
                    this.value[val] = flag;
1076
                    this.triggerUrl();
1077
                }
1078
                _.extend(this.searchCollection.queryParams, { limit: this.limit, offset: this.offset });
1079
                this.fetchCollection();
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
            },
            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();
                    }
                    _.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 });
                    }
                }
1123
            }
1124
        });
1125
    return SearchResultLayoutView;
1126
});