CommonViewFunction.js 42.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * 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.
 */

19
define(['require', 'utils/Utils', 'modules/Modal', 'utils/Messages', 'utils/Enums', 'moment'], function(require, Utils, Modal, Messages, Enums, moment) {
20 21 22 23 24
    'use strict';

    var CommonViewFunction = {};
    CommonViewFunction.deleteTag = function(options) {
        require(['models/VTag'], function(VTag) {
25
            if (options && options.guid && options.tagName) {
26 27 28 29 30 31 32 33 34 35
                var tagModel = new VTag(),
                    notifyObj = {
                        modal: true,
                        text: options.msg,
                        title: options.titleMessage,
                        okText: options.okText,
                        ok: function(argument) {
                            if (options.showLoader) {
                                options.showLoader();
                            }
36
                            tagModel.deleteAssociation(options.guid, options.tagName, options.associatedGuid, {
37 38 39 40 41 42 43 44 45 46 47
                                skipDefaultError: true,
                                success: function(data) {
                                    Utils.notifySuccess({
                                        content: "Classification " + options.tagName + Messages.removeSuccessMessage
                                    });
                                    if (options.callback) {
                                        options.callback();
                                    }
                                    if (options.collection) {
                                        options.collection.fetch({ reset: true });
                                    }
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
                                },
                                cust_error: function(model, response) {
                                    var message = options.tagName + Messages.deleteErrorMessage;
                                    if (response && response.responseJSON) {
                                        message = response.responseJSON.errorMessage;
                                    }
                                    if (options.hideLoader) {
                                        options.hideLoader();
                                    }
                                    Utils.notifyError({
                                        content: message
                                    });
                                }
                            });
                        },
                        cancel: function(argument) {
                            if (options.hideLoader) {
                                options.hideLoader();
                            }
68
                        }
69 70
                    };
                Utils.notifyConfirm(notifyObj);
71
            }
72 73
        });
    };
74 75
    CommonViewFunction.propertyTable = function(options) {
        var scope = options.scope,
76
            sortBy = options.sortBy,
77 78
            valueObject = options.valueObject,
            extractJSON = options.extractJSON,
79
            isTable = _.isUndefined(options.isTable) ? true : options.isTable,
80
            attributeDefs = options.attributeDefs,
81 82 83
            formatIntVal = options.formatIntVal,
            showListCount = options.showListCount || true,
            numberFormat = options.numberFormat || _.numberFormatWithComa;
84

85
        var table = "",
86
            getValue = function(val) {
87 88
                if (val) {
                    if ((_.isNumber(val) || !_.isNaN(parseInt(val))) && formatIntVal) {
89
                        return numberFormat(val);
90 91
                    } else {
                        return val;
92 93
                    }
                } else {
94
                    return "N/A";
95 96
                }
            },
97
            fetchInputOutputValue = function(id, defEntity) {
98
                var that = this;
99
                scope.entityModel.getEntityHeader(id, {
100
                    success: function(serverData) {
101
                        var value = "",
102
                            deleteButton = "",
103
                            data = serverData;
104
                        value = Utils.getName(data);
105
                        var id = "";
106
                        if (data.guid) {
107
                            if (Enums.entityStateReadOnly[data.status]) {
108
                                deleteButton += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
109
                            }
110
                            id = data.guid;
111
                        }
112
                        if (value.length > 0) {
113
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + getValue(value) + '</a>');
114
                        } else {
115
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + _.escape(id) + '</a>');
116
                        }
117 118 119 120
                        if (deleteButton.length) {
                            scope.$('td div[data-id="' + id + '"]').addClass('block readOnlyLink');
                            scope.$('td div[data-id="' + id + '"]').append(deleteButton);
                        }
121
                    },
122 123 124
                    cust_error: function(error, xhr) {
                        if (xhr.status == 403) {
                            scope.$('td div[data-id="' + id + '"]').html('<div><span class="text-danger"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Not Authorized</span></div>');
125 126
                        } else if (defEntity && defEntity.options && defEntity.options.isSoftReference === "true") {
                            scope.$('td div[data-id="' + id + '"]').html('<div> ' + id + '</div>');
127 128 129
                        } else {
                            scope.$('td div[data-id="' + id + '"]').html('<div><span class="text-danger"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> ' + Messages.defaultErrorMessage + '</span></div>');
                        }
130
                    },
131
                    complete: function() {}
132
                });
133
            },
134 135 136
            extractObject = function(opt) {
                var valueOfArray = [],
                    keyValue = opt.keyValue,
137 138
                    key = opt.key,
                    defEntity = opt.defEntity;
139 140 141 142 143 144 145 146 147 148 149 150
                if (!_.isArray(keyValue) && _.isObject(keyValue)) {
                    keyValue = [keyValue];
                }
                var subLink = "";
                for (var i = 0; i < keyValue.length; i++) {
                    var inputOutputField = keyValue[i],
                        id = inputOutputField.guid || (_.isObject(inputOutputField.id) ? inputOutputField.id.id : inputOutputField.id),
                        tempLink = "",
                        status = inputOutputField.status || (_.isObject(inputOutputField.id) ? inputOutputField.id.state : inputOutputField.state),
                        readOnly = Enums.entityStateReadOnly[status];
                    if (!inputOutputField.attributes && inputOutputField.values) {
                        inputOutputField['attributes'] = inputOutputField.values;
151
                    }
152 153 154
                    if (_.isString(inputOutputField) || _.isBoolean(inputOutputField) || _.isNumber(inputOutputField)) {
                        var tempVarfor$check = inputOutputField.toString();
                        if (tempVarfor$check.indexOf("$") == -1) {
155
                            valueOfArray.push('<span class="json-string">' + getValue(_.escape(inputOutputField)) + '</span>');
156
                        }
157 158 159 160 161 162
                    } else if (_.isObject(inputOutputField) && !id) {
                        var attributesList = inputOutputField;
                        if (scope.typeHeaders && inputOutputField.typeName) {
                            var typeNameCategory = scope.typeHeaders.fullCollection.findWhere({ name: inputOutputField.typeName });
                            if (attributesList.attributes && typeNameCategory && typeNameCategory.get('category') === 'STRUCT') {
                                attributesList = attributesList.attributes;
163
                            }
164
                        }
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

                        if (extractJSON && extractJSON.extractKey) {
                            var newAttributesList = {};
                            _.each(attributesList, function(objValue, objKey) {
                                var value = _.isObject(objValue) ? objValue : _.escape(objValue),
                                    tempVarfor$check = objKey.toString();
                                if (tempVarfor$check.indexOf("$") == -1) {
                                    if (_.isObject(extractJSON.extractKey)) {
                                        _.each(extractJSON.extractKey, function(extractKey) {
                                            if (objKey === extractKey) {
                                                newAttributesList[_.escape(objKey)] = value;
                                            }
                                        });
                                    } else if (_.isString(extractJSON.extractKey) && extractJSON.extractKey === objKey) {
                                        newAttributesList[_.escape(objKey)] = value;
180 181
                                    }
                                }
182 183 184 185 186
                            });
                            valueOfArray.push(Utils.JSONPrettyPrint(newAttributesList));
                        } else {
                            valueOfArray.push(Utils.JSONPrettyPrint(attributesList));
                        }
187 188 189
                    }
                    if (id && inputOutputField) {
                        var name = Utils.getName(inputOutputField);
190
                        if ((name === "-" || name === id) && !inputOutputField.attributes) {
191 192
                            var fetch = true;
                            var fetchId = (_.isObject(id) ? id.id : id);
193
                            fetchInputOutputValue(fetchId, defEntity);
194
                            tempLink += '<div data-id="' + fetchId + '"><div class="value-loader"></div></div>';
195
                        } else {
196
                            tempLink += '<a href="#!/detailPage/' + id + '">' + name + '</a>'
197
                        }
198
                    }
199 200
                    if (readOnly) {
                        if (!fetch) {
201
                            tempLink += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
202 203 204 205 206
                            subLink += '<div class="block readOnlyLink">' + tempLink + '</div>';
                        } else {
                            fetch = false;
                            subLink += tempLink;
                        }
207

208 209 210 211 212 213 214 215 216 217 218 219 220
                    } else {
                        if (tempLink.search('href') != -1) {
                            subLink += '<div>' + tempLink + '</div>'
                        } else if (tempLink.length) {
                            subLink += tempLink
                        }
                    }
                }
                if (valueOfArray.length) {
                    subLink = valueOfArray.join(', ');
                }
                return subLink;
            }
221 222 223 224 225 226
        var valueObjectKeysList = _.keys(valueObject);
        if (_.isUndefined(sortBy) || sortBy == true) {
            valueObjectKeysList = _.sortBy(valueObjectKeysList);
        }
        valueObjectKeysList.map(function(key) {

227
            key = _.escape(key);
228 229 230
            if (key == "profileData") {
                return;
            }
231 232
            var keyValue = valueObject[key],
                listCount = showListCount && _.isArray(keyValue) && keyValue.length > 0 ? ' (' + numberFormat(keyValue.length) + ')' : "";
233
            var defEntity = _.find(attributeDefs, { name: key });
234 235
            if (defEntity && defEntity.typeName) {
                var defEntityType = defEntity.typeName.toLocaleLowerCase();
236
                if (defEntityType === 'date') {
237 238
                    keyValue = new Date(keyValue);
                } else if (_.isObject(keyValue)) {
239
                    keyValue = extractObject({ "keyValue": keyValue, "key": key, 'defEntity': defEntity });
240 241 242
                }
            } else {
                if (_.isObject(keyValue)) {
243
                    keyValue = extractObject({ "keyValue": keyValue, "key": key });
244 245
                }
            }
246 247 248 249 250
            var val = "";
            if (_.isObject(valueObject[key])) {
                val = keyValue
            } else if (Utils.isUrl(keyValue)) {
                val = '<a target="_blank" class="blue-link" href="' + keyValue + '">' + keyValue + '</a>';
251 252
            } else if (key === 'guid' || key === "__guid") {
                val = '<a title="' + key + '" href="#!/detailPage/' + keyValue + '">' + keyValue + '</a>';
253 254 255
            } else {
                val = _.escape(keyValue);
            }
256
            if (isTable) {
257
                var htmlTag = '<div class="scroll-y">' + getValue(val) + '</div>';
258
                if (_.isObject(valueObject[key]) && !_.isEmpty(valueObject[key])) {
259 260
                    var matchedLinkString = val.match(/href|value-loader\w*/g),
                        matchedJson = val.match(/json-value|json-string\w*/g),
261
                        isMatchLinkStringIsSingle = matchedLinkString && matchedLinkString.length <= 5,
262 263 264
                        isMatchJSONStringIsSingle = matchedJson && matchedJson.length == 1,
                        expandCollapseButton = "";
                    if ((matchedJson && !isMatchJSONStringIsSingle) || (matchedLinkString && !isMatchLinkStringIsSingle)) {
265 266
                        expandCollapseButton = '<button class="expand-collapse-button"><i class="fa"></i></button>';
                        htmlTag = '<pre class="shrink code-block ' + (isMatchJSONStringIsSingle ? 'fixed-height' : '') + '">' + expandCollapseButton + '<code>' + val + '</code></pre>';
267 268
                    }
                }
269
                table += '<tr><td>' + (_.escape(key) + listCount) + '</td><td>' + htmlTag + '</td></tr>';
270
            } else {
271
                table += '<div>' + val + '</div>';
272 273
            }

274 275 276
        });
        return table;
    }
277
    CommonViewFunction.tagForTable = function(obj) {
278
        var traits = obj.classifications,
279
            tagHtml = "",
280
            addTag = "",
281
            popTag = "",
282
            count = 0,
283
            entityName = Utils.getName(obj);
284 285
        if (traits) {
            traits.map(function(tag) {
286
                var className = "btn btn-action btn-sm btn-blue btn-icon",
287 288 289
                    deleteIcon = "";
                if (obj.guid === tag.entityGuid) {
                    deleteIcon = '<i class="fa fa-times" data-id="delete"  data-assetname="' + entityName + '"data-name="' + tag.typeName + '" data-type="tag" data-guid="' + obj.guid + '" ></i>';
290 291
                } else if (obj.guid !== tag.entityGuid && tag.entityStatus === "DELETED") {
                    deleteIcon = '<i class="fa fa-times" data-id="delete"  data-assetname="' + entityName + '"data-name="' + tag.typeName + '" data-type="tag" data-entityguid="' + tag.entityGuid + '" data-guid="' + obj.guid + '" ></i>';
292 293 294 295
                } else {
                    className += " propagte-classification";
                }
                var tagString = '<a class="' + className + '" data-id="tagClick"><span title="' + tag.typeName + '">' + tag.typeName + '</span>' + deleteIcon + '</a>';
296 297 298
                if (count >= 1) {
                    popTag += tagString;
                } else {
299
                    tagHtml += tagString;
300
                }
301
                ++count;
302 303 304 305
            });
        }
        if (!Enums.entityStateReadOnly[obj.status]) {
            if (obj.guid) {
306
                addTag += '<a href="javascript:void(0)" data-id="addTag" class="btn btn-action btn-sm assignTag" data-guid="' + obj.guid + '" ><i class="fa fa-plus"></i></a>';
307
            } else {
308
                addTag += '<a href="javascript:void(0)" data-id="addTag" class="btn btn-action btn-sm assignTag"><i style="right:0" class="fa fa-plus"></i></a>';
309 310 311
            }
        }
        if (count > 1) {
312
            addTag += '<div data-id="showMoreLess" class="btn btn-action btn-sm assignTag"><i class="fa fa-ellipsis-h" aria-hidden="true"></i><div class="popup-tag-term">' + popTag + '</div></div>'
313
        }
314 315 316 317 318 319 320 321 322 323 324 325
        return '<div class="tagList btn-inline btn-fixed-width">' + tagHtml + addTag + '</div>';
    }
    CommonViewFunction.termForTable = function(obj) {
        var terms = obj.meanings,
            termHtml = "",
            addTerm = "",
            popTerm = "",
            count = 0,
            entityName = Utils.getName(obj);
        if (terms) {
            terms.map(function(term) {
                var className = "btn btn-action btn-sm btn-blue btn-icon",
326 327
                    deleteIcon = '<i class="fa fa-times" data-id="delete"  data-assetname="' + entityName + '"data-name="' + term.displayText + '" data-type="term" data-guid="' + obj.guid + '" data-termGuid="' + term.termGuid + '" ></i>',
                    termString = '<a class="' + className + '" data-id="termClick"><span title="' + term.displayText + '">' + term.displayText + '</span>' + deleteIcon + '</a>';
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
                if (count >= 1) {
                    popTerm += termString;
                } else {
                    termHtml += termString;
                }
                ++count;
            });
        }
        if (!Enums.entityStateReadOnly[obj.status]) {
            if (obj.guid) {
                addTerm += '<a href="javascript:void(0)" data-id="addTerm" class="btn btn-action btn-sm assignTag" data-guid="' + obj.guid + '" ><i class="fa fa-plus"></i></a>';
            } else {
                addTerm += '<a href="javascript:void(0)" data-id="addTerm" class="btn btn-action btn-sm assignTag"><i style="right:0" class="fa fa-plus"></i></a>';
            }
        }
        if (count > 1) {
            addTerm += '<div data-id="showMoreLess" class="btn btn-action btn-sm assignTerm"><i class="fa fa-ellipsis-h" aria-hidden="true"></i><div class="popup-tag-term">' + popTerm + '</div></div>'
        }
        return '<div class="tagList btn-inline btn-fixed-width">' + termHtml + addTerm + '</div>';
347 348
    }
    CommonViewFunction.generateQueryOfFilter = function(value) {
349 350
        var entityFilters = CommonViewFunction.attributeFilter.extractUrl({ "value": value.entityFilters, "formatDate": true }),
            tagFilters = CommonViewFunction.attributeFilter.extractUrl({ "value": value.tagFilters, "formatDate": true }),
351 352 353 354 355 356 357 358 359 360 361 362
            queryArray = [];

        function objToString(filterObj) {
            var generatedQuery = _.map(filterObj.rules, function(obj, key) {
                if (_.has(obj, 'condition')) {
                    return '&nbsp<span class="operator">' + obj.condition + '</span>&nbsp' + '(' + objToString(obj) + ')';
                } else {
                    return '<span class="key">' + _.escape(obj.id) + '</span>&nbsp<span class="operator">' + _.escape(obj.operator) + '</span>&nbsp<span class="value">' + _.escape(obj.value) + "</span>";
                }
            });
            return generatedQuery;
        }
363 364 365
        if (value.type) {
            var typeKeyValue = '<span class="key">Type:</span>&nbsp<span class="value">' + _.escape(value.type) + '</span>';
            if (entityFilters) {
366 367
                var conditionForEntity = entityFilters.rules.length == 1 ? '' : 'AND';
                typeKeyValue += '&nbsp<span class="operator">' + conditionForEntity + '</span>&nbsp(<span class="operator">' + entityFilters.condition + '</span>&nbsp(' + objToString(entityFilters) + '))';
368 369 370 371
            }
            queryArray.push(typeKeyValue)
        }
        if (value.tag) {
372
            var tagKeyValue = '<span class="key">Classification:</span>&nbsp<span class="value">' + _.escape(value.tag) + '</span>';
373
            if (tagFilters) {
374 375
                var conditionFortag = tagFilters.rules.length == 1 ? '' : 'AND';
                tagKeyValue += '&nbsp<span class="operator">' + conditionFortag + '</span>&nbsp(<span class="operator">' + tagFilters.condition + '</span>&nbsp(' + objToString(tagFilters) + '))';
376 377 378
            }
            queryArray.push(tagKeyValue);
        }
379 380 381 382
        if (value.term) {
            var tagKeyValue = '<span class="key">Term:</span>&nbsp<span class="value">' + _.escape(value.term) + '</span>';
            queryArray.push(tagKeyValue);
        }
383
        if (value.query) {
384
            queryArray.push('<span class="key">Query:</span>&nbsp<span class="value">' + _.trim(_.escape(value.query)) + '</span>&nbsp');
385 386 387 388 389 390
        }
        if (queryArray.length == 1) {
            return queryArray.join();
        } else {
            return "<span>(</span>&nbsp" + queryArray.join('<span>&nbsp)</span>&nbsp<span>AND</span>&nbsp<span>(</span>&nbsp') + "&nbsp<span>)</span>";

391 392
        }
    }
393 394 395
    CommonViewFunction.generateObjectForSaveSearchApi = function(options) {
        var obj = {
            name: options.name,
396
            guid: options.guid
397 398 399
        };
        var value = options.value;
        if (value) {
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
            _.each(Enums.extractFromUrlForSearch, function(svalue, skey) {
                if (_.isObject(svalue)) {
                    _.each(svalue, function(v, k) {
                        var val = value[k];
                        if (!_.isUndefinedNull(val)) {
                            if (k == "attributes") {
                                val = val.split(',');
                            } else if (_.contains(["tagFilters", "entityFilters"], k)) {
                                val = CommonViewFunction.attributeFilter.generateAPIObj(val);
                            } else if (_.contains(["includeDE", "excludeST", "excludeSC"], k)) {
                                val = val ? false : true;
                            }
                        }
                        if (_.contains(["includeDE", "excludeST", "excludeSC"], k)) {
                            val = _.isUndefinedNull(val) ? true : val;
                        }
                        if (!obj[skey]) {
                            obj[skey] = {};
                        }
                        obj[skey][v] = val;
                    });
                } else {
                    obj[skey] = value[skey];
423
                }
424 425 426 427 428 429 430 431 432 433
            });
            return obj;
        }
    }
    CommonViewFunction.generateUrlFromSaveSearchObject = function(options) {
        var value = options.value,
            classificationDefCollection = options.classificationDefCollection,
            entityDefCollection = options.entityDefCollection,
            obj = {};
        if (value) {
434
            _.each(Enums.extractFromUrlForSearch, function(svalue, skey) {
435
                if (_.isObject(svalue)) {
436 437 438 439 440 441 442 443 444 445 446 447 448
                    _.each(svalue, function(v, k) {
                        var val = value[skey][v];
                        if (!_.isUndefinedNull(val)) {
                            if (k == "attributes") {
                                val = val.join(',');
                            } else if (k == "tagFilters") {
                                if (classificationDefCollection) {
                                    var classificationDef = classificationDefCollection.fullCollection.findWhere({ 'name': value[skey].classification })
                                    attributeDefs = Utils.getNestedSuperTypeObj({
                                        collection: classificationDefCollection,
                                        attrMerge: true,
                                        data: classificationDef.toJSON()
                                    });
449
                                }
450
                                val = CommonViewFunction.attributeFilter.generateUrl({ "value": val, "attributeDefs": attributeDefs });
451 452 453 454 455 456 457 458
                            } else if (k == "entityFilters") {
                                if (entityDefCollection) {
                                    var entityDef = entityDefCollection.fullCollection.findWhere({ 'name': value[skey].typeName }),
                                        attributeDefs = Utils.getNestedSuperTypeObj({
                                            collection: entityDefCollection,
                                            attrMerge: true,
                                            data: entityDef.toJSON()
                                        });
459
                                }
460
                                val = CommonViewFunction.attributeFilter.generateUrl({ "value": val, "attributeDefs": attributeDefs });
461 462 463
                            } else if (_.contains(["includeDE", "excludeST", "excludeSC"], k)) {
                                val = val ? false : true;
                            }
464
                        }
465 466
                        obj[k] = val;
                    });
467
                } else {
468
                    obj[skey] = value[skey];
469 470 471 472 473
                }
            });
            return obj;
        }
    }
474
    CommonViewFunction.attributeFilter = {
475 476 477
        generateUrl: function(options) {
            var attrQuery = [],
                attrObj = options.value,
478
                formatedDateToLong = options.formatedDateToLong,
479 480
                attributeDefs = options.attributeDefs,
                /* set attributeType for criterion while creating object*/
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
                spliter = 1;
            attrQuery = conditionalURl(attrObj, spliter);

            function conditionalURl(options, spliter) {
                if (options) {
                    return _.map(options.rules || options.criterion, function(obj, key) {
                        if (_.has(obj, 'condition')) {
                            return obj.condition + '(' + conditionalURl(obj, (spliter + 1)) + ')';
                        }
                        if (attributeDefs) {
                            var attributeDef = _.findWhere(attributeDefs, { 'name': obj.attributeName });
                            if (attributeDef) {
                                obj.attributeValue = obj.attributeValue;
                                obj['attributeType'] = attributeDef.typeName;
                            }
                        }
                        var type = (obj.type || obj.attributeType),
                            //obj.value will come as an object when selected type is Date and operator is isNull or not_null;
499
                            value = ((_.isString(obj.value) && _.contains(["is_null", "not_null"], obj.operator) && type === 'date') || _.isObject(obj.value) ? "" : _.trim(obj.value || obj.attributeValue)),
500 501 502 503 504 505
                            url = [(obj.id || obj.attributeName), mapApiOperatorToUI(obj.operator), (type === 'date' && formatedDateToLong && value.length ? Date.parse(value) : value)];
                        if (type) {
                            url.push(type);
                        }
                        return url.join("::");
                    }).join('|' + spliter + '|')
506 507 508
                } else {
                    return null;
                }
509 510 511
            }
            if (attrQuery.length) {
                return attrObj.condition + '(' + attrQuery + ')';
512 513 514
            } else {
                return null;
            }
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534

            function mapApiOperatorToUI(oper) {
                if (oper == "eq") {
                    return "=";
                } else if (oper == "neq") {
                    return "!=";
                } else if (oper == "lt") {
                    return "<";
                } else if (oper == "lte") {
                    return "<=";
                } else if (oper == "gt") {
                    return ">";
                } else if (oper == "gte") {
                    return ">=";
                } else if (oper == "startsWith") {
                    return "begins_with";
                } else if (oper == "endsWith") {
                    return "ends_with";
                } else if (oper == "contains") {
                    return "contains";
535 536 537 538
                } else if (oper == "notNull") {
                    return "not_null";
                } else if (oper == "isNull") {
                    return "is_null";
539 540 541
                }
                return oper;
            }
542
        },
543
        extractUrl: function(options) {
544
            var attrObj = {},
545
                urlObj = options.value,
546 547 548
                formatDate = options.formatDate,
                spliter = 1,
                apiObj = options.apiObj; //if apiObj then create object for API call else for QueryBuilder.
549
            if (urlObj && urlObj.length) {
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                attrObj = createObject(urlObj);

                function createObject(urlObj) {
                    var finalObj = {};
                    finalObj['condition'] = /^AND\(/.test(urlObj) ? "AND" : "OR";
                    urlObj = finalObj.condition === "AND" ? urlObj.substr(4).slice(0, -1) : urlObj.substr(3).slice(0, -1);
                    finalObj[apiObj ? "criterion" : "rules"] = _.map(urlObj.split('|' + spliter + '|'), function(obj, key) {
                        var isStringNested = obj.split('|' + (spliter + 1) + '|').length > 1,
                            isCondition = /^AND\(/.test(obj) || /^OR\(/.test(obj);
                        if (isStringNested && isCondition) {
                            ++spliter;
                            return createObject(obj);
                        } else if (isCondition) {
                            return createObject(obj);
                        } else {
                            var temp = obj.split("::") || obj.split('|' + spliter + '|'),
                                rule = {};
                            if (apiObj) {
                                rule = { attributeName: temp[0], operator: mapUiOperatorToAPI(temp[1]), attributeValue: _.trim(temp[2]) }
                                rule.attributeValue = rule.type === 'date' && formatDate && rule.attributeValue.length ? moment(parseInt(rule.attributeValue)).format('MM/DD/YYYY h:mm A') : rule.attributeValue;
                            } else {
                                rule = { id: temp[0], operator: temp[1], value: _.trim(temp[2]) }
                                if (temp[3]) {
                                    rule['type'] = temp[3];
                                }
                                rule.value = rule.type === 'date' && formatDate && rule.value.length ? moment(parseInt(rule.value)).format('MM/DD/YYYY h:mm A') : rule.value;
                            }
                            return rule;
                        }
                    });
                    return finalObj;
581 582 583 584
                }
            } else {
                return null;
            }
585
            return attrObj;
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

            function mapUiOperatorToAPI(oper) {
                if (oper == "=") {
                    return "eq";
                } else if (oper == "!=") {
                    return "neq";
                } else if (oper == "<") {
                    return "lt";
                } else if (oper == "<=") {
                    return "lte";
                } else if (oper == ">") {
                    return "gt";
                } else if (oper == ">=") {
                    return "gte";
                } else if (oper == "begins_with") {
                    return "startsWith";
                } else if (oper == "ends_with") {
                    return "endsWith";
                } else if (oper == "contains") {
                    return "contains";
606 607 608 609
                } else if (oper == "not_null") {
                    return "notNull";
                } else if (oper == "is_null") {
                    return "isNull";
610 611 612
                }
                return oper;
            }
613 614 615 616 617 618 619
        },
        generateAPIObj: function(url) {
            if (url && url.length) {
                return this.extractUrl({ "value": url, "apiObj": true });
            } else {
                return null;
            }
620 621
        }
    }
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    CommonViewFunction.createEditGlossaryCategoryTerm = function(options) {
        if (options) {
            var model = options.model,
                isTermView = options.isTermView,
                isGlossaryView = options.isGlossaryView,
                collection = options.collection
        }
        require([
            'views/glossary/CreateEditCategoryTermLayoutView',
            'views/glossary/CreateEditGlossaryLayoutView',
            'modules/Modal'
        ], function(CreateEditCategoryTermLayoutView, CreateEditGlossaryLayoutView, Modal) {
            var view = null,
                title = null;
            if (isGlossaryView) {
                view = new CreateEditGlossaryLayoutView({ "glossaryCollection": collection, "model": model });
                title = "Glossary";
            } else {
                view = new CreateEditCategoryTermLayoutView({ "glossaryCollection": collection, "modelJSON": model });
                title = (isTermView ? 'Term' : 'Category');
            }

            var modal = new Modal({
                "title": ((model ? "Update " : "Create ") + title),
                "content": view,
                "cancelText": "Cancel",
                "okCloses": false,
                "okText": model ? "Update" : "Create",
                "allowCancel": true
            }).open();
652 653 654 655 656 657
            modal.$el.find('button.ok').attr("disabled", "true");
            if (model) {
                view.$('input,textarea').on('keyup', function(e) {
                    modal.$el.find('button.ok').attr("disabled", false);
                });
            } else {
658
                view.ui.name.on('keyup', function(e) {
659 660 661
                    modal.$el.find('button.ok').attr("disabled", false);
                });
            }
662
            view.ui.name.on('keyup', function(e) {
663 664 665 666
                if ((e.keyCode == 8 || e.keyCode == 32 || e.keyCode == 46) && e.currentTarget.value.trim() == "") {
                    modal.$el.find('button.ok').attr("disabled", true);
                }
            });
667
            modal.on('ok', function() {
668
                modal.$el.find('button.ok').attr("disabled", true);
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
                CommonViewFunction.createEditGlossaryCategoryTermSubmit(_.extend({ "ref": view, "modal": modal }, options));
            });
            modal.on('closeModal', function() {
                modal.trigger('cancel');
                if (options.onModalClose) {
                    options.onModalClose()
                }
            });
        });
    }
    CommonViewFunction.createEditGlossaryCategoryTermSubmit = function(options) {
        if (options) {
            var ref = options.ref,
                modal = options.modal,
                model = options.model,
                node = options.node,
                isTermView = options.isTermView,
                isCategoryView = options.isCategoryView,
                collection = options.collection,
                isGlossaryView = options.isGlossaryView,
                data = ref.ui[(isGlossaryView ? "glossaryForm" : "categoryTermForm")].serializeArray().reduce(function(obj, item) {
                    obj[item.name] = item.value;
                    return obj;
                }, {}),
                newModel = new options.collection.model(),
                messageType = "Glossary ";
        }
        if (isTermView) {
            messageType = "Term ";
        } else if (isCategoryView) {
            messageType = "Category ";
        }
        var ajaxOptions = {
702
            silent: true,
703 704
            success: function(rModel, response) {
                Utils.notifySuccess({
705
                    content: messageType + ref.ui.name.val() + Messages[model ? "editSuccessMessage" : "addSuccessMessage"]
706 707
                });
                if (options.callback) {
708
                    options.callback(rModel);
709 710
                }
                modal.trigger('closeModal');
711 712
            },
            cust_error: function() {
713
                modal.$el.find('button.ok').attr("disabled", false);
714 715 716 717
            }
        }
        if (model) {
            if (isGlossaryView) {
718
                model.clone().set(data, { silent: true }).save(null, ajaxOptions)
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
            } else {
                newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
                    guid: model.guid,
                    data: JSON.stringify(_.extend({}, model, data)),
                }));
            }

        } else {
            if (isGlossaryView) {
                new collection.model().set(data).save(null, ajaxOptions);
            } else {
                if (node) {
                    var key = "anchor",
                        guidKey = "glossaryGuid";
                    data["anchor"] = {
                        "glossaryGuid": node.glossaryId || node.guid,
                        "displayText": node.glossaryName || node.text
                    }
                    if (node.type == "GlossaryCategory") {
                        data["parentCategory"] = {
                            "categoryGuid": node.guid
                        }
                    }
                }
                newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
                    data: JSON.stringify(data),
                }));
            }
        }

    }
    CommonViewFunction.removeCategoryTermAssociation = function(options) {
        if (options) {
752
            var selectedGuid = options.selectedGuid,
753 754 755 756 757 758 759 760 761 762
                termGuid = options.termGuid,
                isCategoryView = options.isCategoryView,
                isTermView = options.isTermView,
                isEntityView = options.isEntityView,
                collection = options.collection,
                model = options.model,
                newModel = new options.collection.model(),
                ajaxOptions = {
                    success: function(rModel, response) {
                        Utils.notifySuccess({
763
                            content: ((isCategoryView || isEntityView ? "Term" : "Category") + " association is removed successfully")
764 765 766 767 768 769 770 771 772 773 774
                        });
                        if (options.callback) {
                            options.callback();
                        }
                    },
                    cust_error: function() {
                        if (options.hideLoader) {
                            options.hideLoader();
                        }
                    }
                },
775 776 777
                notifyObj = {
                    modal: true,
                    text: options.msg,
778 779
                    title: options.titleMessage,
                    okText: options.buttonText,
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
                    ok: function(argument) {
                        if (options.showLoader) {
                            options.showLoader();
                        }
                        if (isEntityView && model) {
                            var data = [model];
                            newModel.removeTermFromEntity(termGuid, _.extend(ajaxOptions, {
                                data: JSON.stringify(data)
                            }))
                        } else {
                            var data = _.extend({}, model);
                            if (isTermView) {
                                data.categories = _.reject(data.categories, function(term) { return term.categoryGuid == selectedGuid });
                            } else {
                                data.terms = _.reject(data.terms, function(term) { return term.termGuid == selectedGuid });
                            }
796

797 798 799 800 801 802 803 804 805
                            newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
                                guid: model.guid,
                                data: JSON.stringify(_.extend({}, model, data)),
                            }));
                        }
                    },
                    cancel: function(argument) {}
                };
            Utils.notifyConfirm(notifyObj);
806 807
        }
    }
808 809 810 811 812 813 814 815 816 817 818 819
    CommonViewFunction.addRestCsrfCustomHeader = function(xhr, settings) {
        if (settings.url == null) {
            return;
        }
        var method = settings.type;
        if (CommonViewFunction.restCsrfCustomHeader != null && !CommonViewFunction.restCsrfMethodsToIgnore[method]) {
            // The value of the header is unimportant.  Only its presence matters.
            xhr.setRequestHeader(CommonViewFunction.restCsrfCustomHeader, '""');
        }
    }
    CommonViewFunction.restCsrfCustomHeader = null;
    CommonViewFunction.restCsrfMethodsToIgnore = null;
820
    CommonViewFunction.userDataFetch = function(options) {
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
        var csrfEnabled = false,
            header = null,
            methods = [];

        function getTrimmedStringArrayValue(string) {
            var str = string,
                array = [];
            if (str) {
                var splitStr = str.split(',');
                for (var i = 0; i < splitStr.length; i++) {
                    array.push(splitStr[i].trim());
                }
            }
            return array;
        }
836 837 838 839
        if (options.url) {
            $.ajax({
                url: options.url,
                success: function(response) {
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
                    if (response) {
                        if (response['atlas.rest-csrf.enabled']) {
                            var str = "" + response['atlas.rest-csrf.enabled'];
                            csrfEnabled = (str.toLowerCase() == 'true');
                        }
                        if (response['atlas.rest-csrf.custom-header']) {
                            header = response['atlas.rest-csrf.custom-header'].trim();
                        }
                        if (response['atlas.rest-csrf.methods-to-ignore']) {
                            methods = getTrimmedStringArrayValue(response['atlas.rest-csrf.methods-to-ignore']);
                        }
                        if (csrfEnabled) {
                            CommonViewFunction.restCsrfCustomHeader = header;
                            CommonViewFunction.restCsrfMethodsToIgnore = {};
                            methods.map(function(method) { CommonViewFunction.restCsrfMethodsToIgnore[method] = true; });
                            Backbone.$.ajaxSetup({
                                beforeSend: CommonViewFunction.addRestCsrfCustomHeader
                            });
                        }
                    }
                },
                complete: function(response) {
862
                    if (options.callback) {
863
                        options.callback(response.responseJSON);
864 865 866 867 868
                    }
                }
            });
        }
    }
869
    return CommonViewFunction;
870
});