CommonViewFunction.js 49.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', 'utils/Globals'], function(require, Utils, Modal, Messages, Enums, moment, Globals) {
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
                var tagModel = new VTag(),
27
                    noticeRef = null,
28 29
                    notifyObj = {
                        modal: true,
30 31
                        okCloses: false,
                        okShowLoader: true,
32 33 34
                        text: options.msg,
                        title: options.titleMessage,
                        okText: options.okText,
35 36
                        ok: function(notice) {
                            noticeRef = notice;
37 38 39
                            if (options.showLoader) {
                                options.showLoader();
                            }
40
                            tagModel.deleteAssociation(options.guid, options.tagName, options.associatedGuid, {
41
                                defaultErrorMessage: options.tagName + Messages.deleteErrorMessage,
42
                                success: function(data) {
43 44 45
                                    if (noticeRef) {
                                        noticeRef.remove();
                                    }
46
                                    Utils.notifySuccess({
47
                                        content: "Classification " + options.tagName + Messages.getAbbreviationMsg(false, 'removeSuccessMessage')
48 49 50 51 52 53 54
                                    });
                                    if (options.callback) {
                                        options.callback();
                                    }
                                    if (options.collection) {
                                        options.collection.fetch({ reset: true });
                                    }
55

56 57
                                },
                                cust_error: function(model, response) {
58 59 60
                                    if (noticeRef) {
                                        noticeRef.hideButtonLoader();
                                    }
61 62 63 64 65 66 67 68 69 70
                                    if (options.hideLoader) {
                                        options.hideLoader();
                                    }
                                }
                            });
                        },
                        cancel: function(argument) {
                            if (options.hideLoader) {
                                options.hideLoader();
                            }
71
                        }
72 73
                    };
                Utils.notifyConfirm(notifyObj);
74
            }
75 76
        });
    };
77 78
    CommonViewFunction.propertyTable = function(options) {
        var scope = options.scope,
79
            sortBy = options.sortBy,
80 81
            valueObject = options.valueObject,
            extractJSON = options.extractJSON,
82
            isTable = _.isUndefined(options.isTable) ? true : options.isTable,
83
            attributeDefs = options.attributeDefs,
84 85
            formatIntVal = options.formatIntVal,
            showListCount = options.showListCount || true,
86
            highlightString = options.highlightString,
87
            formatStringVal = options.formatStringVal,
88
            numberFormat = options.numberFormat || _.numberFormatWithComa;
89

90
        var table = "",
91 92 93 94 95 96 97 98 99 100 101 102 103
            getHighlightedString = function(resultStr) {
                if (highlightString && highlightString.length) {
                    try {
                        return resultStr.replace(new RegExp(highlightString, "gi"), function(foundStr) {
                            return "<span class='searched-term-highlight'>" + foundStr + "</span>"
                        });
                    } catch (error) {
                        return resultStr;
                    }
                } else {
                    return resultStr;
                }
            },
104
            getValue = function(val) {
105 106
                if (val) {
                    if ((_.isNumber(val) || !_.isNaN(parseInt(val))) && formatIntVal) {
107
                        return numberFormat(val);
108
                    } else {
109 110 111 112 113 114 115 116 117 118
                        var newVal = val;
                        if (formatStringVal) {
                            newVal = parseInt(val);
                            if (newVal === NaN) {
                                newVal = val;
                            } else {
                                newVal = numberFormat(newVal);
                            }
                        }
                        return getHighlightedString(newVal);
119 120
                    }
                } else {
121
                    return "N/A";
122 123
                }
            },
124
            fetchInputOutputValue = function(id, defEntity) {
125
                var that = this;
126
                scope.entityModel.getEntityHeader(id, {
127
                    success: function(serverData) {
128
                        var value = "",
129
                            deleteButton = "",
130
                            data = serverData;
131
                        value = Utils.getName(data);
132
                        var id = "";
133
                        if (data.guid) {
134
                            if (Enums.entityStateReadOnly[data.status || data.entityStatus]) {
135
                                deleteButton += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
136
                            }
137
                            id = data.guid;
138
                        }
139
                        if (value.length > 0) {
140
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + getValue(value) + '</a>');
141
                        } else {
142
                            scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + _.escape(id) + '</a>');
143
                        }
144 145 146 147
                        if (deleteButton.length) {
                            scope.$('td div[data-id="' + id + '"]').addClass('block readOnlyLink');
                            scope.$('td div[data-id="' + id + '"]').append(deleteButton);
                        }
148
                    },
149 150 151
                    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>');
152 153
                        } else if (defEntity && defEntity.options && defEntity.options.isSoftReference === "true") {
                            scope.$('td div[data-id="' + id + '"]').html('<div> ' + id + '</div>');
154 155 156
                        } 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>');
                        }
157
                    },
158
                    complete: function() {}
159
                });
160
            },
161 162 163
            extractObject = function(opt) {
                var valueOfArray = [],
                    keyValue = opt.keyValue,
164 165
                    key = opt.key,
                    defEntity = opt.defEntity;
166 167 168 169 170 171 172 173
                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 = "",
174
                        status = (inputOutputField.status || inputOutputField.entityStatus) || (_.isObject(inputOutputField.id) ? inputOutputField.id.state : inputOutputField.state),
175 176 177
                        readOnly = Enums.entityStateReadOnly[status];
                    if (!inputOutputField.attributes && inputOutputField.values) {
                        inputOutputField['attributes'] = inputOutputField.values;
178
                    }
179 180 181
                    if (_.isString(inputOutputField) || _.isBoolean(inputOutputField) || _.isNumber(inputOutputField)) {
                        var tempVarfor$check = inputOutputField.toString();
                        if (tempVarfor$check.indexOf("$") == -1) {
182
                            valueOfArray.push('<span class="json-string">' + getValue(_.escape(inputOutputField)) + '</span>');
183
                        }
184 185 186 187 188 189
                    } 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;
190
                            }
191
                        }
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

                        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;
207 208
                                    }
                                }
209
                            });
210
                            valueOfArray.push(Utils.JSONPrettyPrint(newAttributesList, getValue));
211
                        } else {
212
                            valueOfArray.push(Utils.JSONPrettyPrint(attributesList, getValue));
213
                        }
214 215 216
                    }
                    if (id && inputOutputField) {
                        var name = Utils.getName(inputOutputField);
217
                        if ((name === "-" || name === id) && !inputOutputField.attributes) {
218 219
                            var fetch = true;
                            var fetchId = (_.isObject(id) ? id.id : id);
220
                            fetchInputOutputValue(fetchId, defEntity);
221
                            tempLink += '<div data-id="' + fetchId + '"><div class="value-loader"></div></div>';
222
                        } else {
223
                            tempLink += '<a href="#!/detailPage/' + id + '">' + getValue(name) + '</a>'
224
                        }
225
                    }
226 227
                    if (readOnly) {
                        if (!fetch) {
228
                            tempLink += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>';
229 230 231 232 233
                            subLink += '<div class="block readOnlyLink">' + tempLink + '</div>';
                        } else {
                            fetch = false;
                            subLink += tempLink;
                        }
234

235 236 237 238 239 240 241 242 243 244 245
                    } else {
                        if (tempLink.search('href') != -1) {
                            subLink += '<div>' + tempLink + '</div>'
                        } else if (tempLink.length) {
                            subLink += tempLink
                        }
                    }
                }
                if (valueOfArray.length) {
                    subLink = valueOfArray.join(', ');
                }
246
                return subLink === "" ? "N/A" : subLink;
247
            }
248 249 250 251 252 253
        var valueObjectKeysList = _.keys(valueObject);
        if (_.isUndefined(sortBy) || sortBy == true) {
            valueObjectKeysList = _.sortBy(valueObjectKeysList);
        }
        valueObjectKeysList.map(function(key) {

254
            key = _.escape(key);
255 256 257
            if (key == "profileData") {
                return;
            }
258 259
            var keyValue = valueObject[key],
                listCount = showListCount && _.isArray(keyValue) && keyValue.length > 0 ? ' (' + numberFormat(keyValue.length) + ')' : "";
260
            var defEntity = _.find(attributeDefs, { name: key });
261 262
            if (defEntity && defEntity.typeName) {
                var defEntityType = defEntity.typeName.toLocaleLowerCase();
263
                if (defEntityType === 'date') {
264
                    keyValue = keyValue > 0 ? new Date(keyValue) : "";
265
                } else if (_.isObject(keyValue)) {
266
                    keyValue = extractObject({ "keyValue": keyValue, "key": key, 'defEntity': defEntity });
267 268 269
                }
            } else {
                if (_.isObject(keyValue)) {
270
                    keyValue = extractObject({ "keyValue": keyValue, "key": key });
271 272
                }
            }
273 274 275 276
            var val = "";
            if (_.isObject(valueObject[key])) {
                val = keyValue
            } else if (Utils.isUrl(keyValue)) {
277
                val = '<a target="_blank" class="blue-link" href="' + keyValue + '">' + getValue(keyValue) + '</a>';
278
            } else if (key === 'guid' || key === "__guid") {
279
                val = '<a title="' + key + '" href="#!/detailPage/' + keyValue + '">' + getValue(keyValue) + '</a>';
280
            } else {
281
                val = getValue(_.escape(keyValue));
282
            }
283
            if (isTable) {
284
                var value = val,
285 286
                    appendClass = (value == "N/A" ? "hide-row" : ""),
                    htmlTag = '<div class="scroll-y">' + value + '</div>';
287
                if (_.isObject(valueObject[key]) && !_.isEmpty(valueObject[key])) {
288 289
                    var matchedLinkString = val.match(/href|value-loader\w*/g),
                        matchedJson = val.match(/json-value|json-string\w*/g),
290
                        isMatchLinkStringIsSingle = matchedLinkString && matchedLinkString.length <= 5,
291 292 293
                        isMatchJSONStringIsSingle = matchedJson && matchedJson.length == 1,
                        expandCollapseButton = "";
                    if ((matchedJson && !isMatchJSONStringIsSingle) || (matchedLinkString && !isMatchLinkStringIsSingle)) {
294 295
                        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>';
296 297
                    }
                }
298
                table += '<tr class="' + appendClass + '"><td>' + (_.escape(key) + listCount) + '</td><td>' + htmlTag + '</td></tr>';
299
            } else {
300
                table += '<span>' + val + '</span>';
301 302
            }

303
        });
304
        return table && table.length > 0 ? table : '<tr class="empty"><td colspan="22"><span>No Record found!</span></td></tr>';
305
    }
306
    CommonViewFunction.tagForTable = function(obj) {
307
        var traits = obj.classifications,
308
            tagHtml = "",
309
            addTag = "",
310
            popTag = "",
311
            count = 0,
312
            entityName = Utils.getName(obj);
313 314
        if (traits) {
            traits.map(function(tag) {
315
                var className = "btn btn-action btn-sm btn-blue btn-icon",
316 317 318
                    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>';
319 320
                } 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>';
321 322 323 324
                } else {
                    className += " propagte-classification";
                }
                var tagString = '<a class="' + className + '" data-id="tagClick"><span title="' + tag.typeName + '">' + tag.typeName + '</span>' + deleteIcon + '</a>';
325 326 327
                if (count >= 1) {
                    popTag += tagString;
                } else {
328
                    tagHtml += tagString;
329
                }
330
                ++count;
331 332
            });
        }
333
        if (!Enums.entityStateReadOnly[obj.status || obj.entityStatus]) {
334
            if (obj.guid) {
335
                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>';
336
            } else {
337
                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>';
338 339 340
            }
        }
        if (count > 1) {
341
            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>'
342
        }
343 344 345 346 347 348 349 350 351 352 353 354
        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",
355
                    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>',
356
                    termString = '<a class="' + className + '" data-id="termClick"><span title="' + _.escape(term.displayText) + '">' + _.escape(term.displayText) + '</span>' + deleteIcon + '</a>';
357 358 359 360 361 362 363 364
                if (count >= 1) {
                    popTerm += termString;
                } else {
                    termHtml += termString;
                }
                ++count;
            });
        }
365
        if (!Enums.entityStateReadOnly[obj.status || obj.entityStatus]) {
366 367 368 369 370 371 372 373 374 375
            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>';
376 377
    }
    CommonViewFunction.generateQueryOfFilter = function(value) {
378
        value = Utils.getUrlState.getQueryParams();
379 380
        var entityFilters = CommonViewFunction.attributeFilter.extractUrl({ "value": value.entityFilters, "formatDate": true }),
            tagFilters = CommonViewFunction.attributeFilter.extractUrl({ "value": value.tagFilters, "formatDate": true }),
381 382 383 384 385 386 387
            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 {
388
                    return '<span class="key">' + (Enums.systemAttributes[obj.id] ? Enums.systemAttributes[obj.id] : _.escape(obj.id)) + '</span>&nbsp<span class="operator">' + _.escape(obj.operator) + '</span>&nbsp<span class="value">' + (Enums[obj.id] ? Enums[obj.id][obj.value] : _.escape(obj.value)) + "</span>";
389 390 391 392
                }
            });
            return generatedQuery;
        }
393 394 395
        if (value.type) {
            var typeKeyValue = '<span class="key">Type:</span>&nbsp<span class="value">' + _.escape(value.type) + '</span>';
            if (entityFilters) {
396 397
                var conditionForEntity = entityFilters.rules.length == 1 ? '' : 'AND';
                typeKeyValue += '&nbsp<span class="operator">' + conditionForEntity + '</span>&nbsp(<span class="operator">' + entityFilters.condition + '</span>&nbsp(' + objToString(entityFilters) + '))';
398 399 400 401
            }
            queryArray.push(typeKeyValue)
        }
        if (value.tag) {
402
            var tagKeyValue = '<span class="key">Classification:</span>&nbsp<span class="value">' + _.escape(value.tag) + '</span>';
403
            if (tagFilters) {
404 405
                var conditionFortag = tagFilters.rules.length == 1 ? '' : 'AND';
                tagKeyValue += '&nbsp<span class="operator">' + conditionFortag + '</span>&nbsp(<span class="operator">' + tagFilters.condition + '</span>&nbsp(' + objToString(tagFilters) + '))';
406 407 408
            }
            queryArray.push(tagKeyValue);
        }
409 410 411 412
        if (value.term) {
            var tagKeyValue = '<span class="key">Term:</span>&nbsp<span class="value">' + _.escape(value.term) + '</span>';
            queryArray.push(tagKeyValue);
        }
413
        if (value.query) {
414
            queryArray.push('<span class="key">Query:</span>&nbsp<span class="value">' + _.trim(_.escape(value.query)) + '</span>&nbsp');
415 416 417 418 419 420
        }
        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>";

421 422
        }
    }
423 424 425
    CommonViewFunction.generateObjectForSaveSearchApi = function(options) {
        var obj = {
            name: options.name,
426
            guid: options.guid
427 428 429
        };
        var value = options.value;
        if (value) {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
            _.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];
453
                }
454 455 456 457 458 459 460 461 462 463
            });
            return obj;
        }
    }
    CommonViewFunction.generateUrlFromSaveSearchObject = function(options) {
        var value = options.value,
            classificationDefCollection = options.classificationDefCollection,
            entityDefCollection = options.entityDefCollection,
            obj = {};
        if (value) {
464
            _.each(Enums.extractFromUrlForSearch, function(svalue, skey) {
465
                if (_.isObject(svalue)) {
466 467 468 469 470 471 472
                    _.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) {
473 474
                                    var classificationDef = classificationDefCollection.fullCollection.findWhere({ 'name': value[skey].classification }),
                                        attributeDefs = [];
475
                                    if (classificationDef) {
476
                                        attributeDefs = Utils.getNestedSuperTypeObj({
477 478 479 480 481 482 483 484
                                            collection: classificationDefCollection,
                                            attrMerge: true,
                                            data: classificationDef.toJSON()
                                        });
                                    }
                                    if (Globals[value[skey].typeName]) {
                                        attributeDefs = Globals[value[skey].typeName].attributeDefs;
                                    }
485
                                }
486
                                val = CommonViewFunction.attributeFilter.generateUrl({ "value": val, "attributeDefs": attributeDefs });
487 488
                            } else if (k == "entityFilters") {
                                if (entityDefCollection) {
489 490 491
                                    var entityDef = entityDefCollection.fullCollection.findWhere({ 'name': value[skey].typeName }),
                                        attributeDefs = [];
                                    if (entityDef) {
492
                                        attributeDefs = Utils.getNestedSuperTypeObj({
493 494 495 496 497 498 499 500
                                            collection: entityDefCollection,
                                            attrMerge: true,
                                            data: entityDef.toJSON()
                                        });
                                    }
                                    if (Globals[value[skey].typeName]) {
                                        attributeDefs = Globals[value[skey].typeName].attributeDefs;
                                    }
501
                                }
502
                                val = CommonViewFunction.attributeFilter.generateUrl({ "value": val, "attributeDefs": attributeDefs });
503 504 505
                            } else if (_.contains(["includeDE", "excludeST", "excludeSC"], k)) {
                                val = val ? false : true;
                            }
506
                        }
507 508
                        obj[k] = val;
                    });
509
                } else {
510
                    obj[skey] = value[skey];
511 512 513 514 515
                }
            });
            return obj;
        }
    }
516
    CommonViewFunction.attributeFilter = {
517 518 519
        generateUrl: function(options) {
            var attrQuery = [],
                attrObj = options.value,
520
                formatedDateToLong = options.formatedDateToLong,
521 522
                attributeDefs = options.attributeDefs,
                /* set attributeType for criterion while creating object*/
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
                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;
541
                            value = ((_.isString(obj.value) && _.contains(["is_null", "not_null"], obj.operator) && type === 'date') || _.isObject(obj.value) ? "" : _.trim(obj.value || obj.attributeValue)),
542 543 544 545 546 547
                            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 + '|')
548 549 550
                } else {
                    return null;
                }
551 552 553
            }
            if (attrQuery.length) {
                return attrObj.condition + '(' + attrQuery + ')';
554 555 556
            } else {
                return null;
            }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

            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";
577 578 579 580
                } else if (oper == "notNull") {
                    return "not_null";
                } else if (oper == "isNull") {
                    return "is_null";
581 582 583
                }
                return oper;
            }
584
        },
585
        extractUrl: function(options) {
586
            var attrObj = {},
587
                urlObj = options.value,
588 589
                formatDate = options.formatDate,
                spliter = 1,
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
                apiObj = options.apiObj,
                mapUiOperatorToAPI = function(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";
                    } else if (oper == "not_null") {
                        return "notNull";
                    } else if (oper == "is_null") {
                        return "isNull";
                    }
                    return oper;
                },
                createObject = function(urlObj) {
618 619 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
                    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;
646
                }
647 648 649
            //if apiObj then create object for API call else for QueryBuilder.
            if (urlObj && urlObj.length) {
                attrObj = createObject(urlObj);
650 651 652
            } else {
                return null;
            }
653 654 655 656 657 658 659 660
            return attrObj;
        },
        generateAPIObj: function(url) {
            if (url && url.length) {
                return this.extractUrl({ "value": url, "apiObj": true });
            } else {
                return null;
            }
661 662
        }
    }
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    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();
693 694 695 696 697 698
            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 {
699
                view.ui.name.on('keyup', function(e) {
700 701 702
                    modal.$el.find('button.ok').attr("disabled", false);
                });
            }
703
            view.ui.name.on('keyup', function(e) {
704 705 706 707
                if ((e.keyCode == 8 || e.keyCode == 32 || e.keyCode == 46) && e.currentTarget.value.trim() == "") {
                    modal.$el.find('button.ok').attr("disabled", true);
                }
            });
708
            modal.on('ok', function() {
709
                modal.$el.find('button.ok').showButtonLoader();
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
                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) {
731
                    obj[item.name] = item.value.trim();
732 733 734 735 736 737 738 739 740 741 742
                    return obj;
                }, {}),
                newModel = new options.collection.model(),
                messageType = "Glossary ";
        }
        if (isTermView) {
            messageType = "Term ";
        } else if (isCategoryView) {
            messageType = "Category ";
        }
        var ajaxOptions = {
743
            silent: true,
744
            success: function(rModel, response) {
745
                var msgType = model ? "editSuccessMessage" : "addSuccessMessage";
746
                Utils.notifySuccess({
747
                    content: messageType + ref.ui.name.val() + Messages.getAbbreviationMsg(false, msgType)
748 749
                });
                if (options.callback) {
750
                    options.callback(rModel);
751 752
                }
                modal.trigger('closeModal');
753 754
            },
            cust_error: function() {
755
                modal.$el.find('button.ok').hideButtonLoader();
756 757 758 759
            }
        }
        if (model) {
            if (isGlossaryView) {
760
                model.clone().set(data, { silent: true }).save(null, ajaxOptions)
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
            } 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) {
794
            var selectedGuid = options.selectedGuid,
795 796 797 798 799 800 801
                termGuid = options.termGuid,
                isCategoryView = options.isCategoryView,
                isTermView = options.isTermView,
                isEntityView = options.isEntityView,
                collection = options.collection,
                model = options.model,
                newModel = new options.collection.model(),
802
                noticeRef = null,
803 804
                ajaxOptions = {
                    success: function(rModel, response) {
805 806 807
                        if (noticeRef) {
                            noticeRef.remove();
                        }
808
                        Utils.notifySuccess({
809
                            content: ((isCategoryView || isEntityView ? "Term" : "Category") + " association is removed successfully")
810 811 812 813 814 815
                        });
                        if (options.callback) {
                            options.callback();
                        }
                    },
                    cust_error: function() {
816 817 818
                        if (noticeRef) {
                            noticeRef.hideButtonLoader();
                        }
819 820 821 822 823
                        if (options.hideLoader) {
                            options.hideLoader();
                        }
                    }
                },
824 825
                notifyObj = {
                    modal: true,
826 827
                    okCloses: false,
                    okShowLoader: true,
828
                    text: options.msg,
829 830
                    title: options.titleMessage,
                    okText: options.buttonText,
831 832
                    ok: function(notice) {
                        noticeRef = notice;
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                        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 });
                            }
848

849 850 851 852 853 854
                            newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
                                guid: model.guid,
                                data: JSON.stringify(_.extend({}, model, data)),
                            }));
                        }
                    },
855
                    cancel: function() {}
856 857
                };
            Utils.notifyConfirm(notifyObj);
858 859
        }
    }
860 861 862 863 864 865 866 867 868 869 870 871
    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;
872
    CommonViewFunction.userDataFetch = function(options) {
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
        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;
        }
888 889 890 891
        if (options.url) {
            $.ajax({
                url: options.url,
                success: function(response) {
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
                    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; });
907 908 909
                            var statusCodeErrorFn = function(error) {
                                Utils.defaultErrorHandler(null, error)
                            }
910
                            Backbone.$.ajaxSetup({
911 912 913 914 915
                                statusCode: {
                                    401: statusCodeErrorFn,
                                    419: statusCodeErrorFn,
                                    403: statusCodeErrorFn
                                },
916 917 918 919 920 921
                                beforeSend: CommonViewFunction.addRestCsrfCustomHeader
                            });
                        }
                    }
                },
                complete: function(response) {
922
                    if (options.callback) {
923
                        options.callback(response.responseJSON);
924 925 926 927 928
                    }
                }
            });
        }
    }
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    CommonViewFunction.CheckDuplicateAndEmptyInput = function(elements, datalist) {
        var keyMap = new Map(),
            validation = true,
            hasDup = [];
        for (var i = 0; i < elements.length; i++) {
            var input = elements[i],
                pEl = input.nextElementSibling,
                classes = 'form-control',
                val = input.value.trim();
            pEl.innerText = "";

            if (val === '') {
                classes = 'form-control errorClass';
                validation = false;
                pEl.innerText = 'Required!';
            } else {
                if (input.tagName === 'INPUT') {
                    var duplicates = datalist.filter(function(c) {
                        return c.key === val;
                    });
                    if (keyMap.has(val) || duplicates.length > 1) {
                        classes = 'form-control errorClass';
                        hasDup.push('duplicate');
                        pEl.innerText = 'Duplicate key';
                    } else {
                        keyMap.set(val, val);
                    }
                }
            }
            input.setAttribute('class', classes);
        }
        return {
            validation: validation,
            hasDuplicate: (hasDup.length === 0 ? false : true)
        };
    }
    CommonViewFunction.getRandomIdAndAnchor = function() {
        var randomId = "collapse_" + parseInt((Math.random() * 100)) + "_" + new Date().getUTCMilliseconds();
        return {
            id: randomId,
            anchor: "#" + randomId
        };
    }
    CommonViewFunction.udKeysStringParser = function(udKeys) {
        var o = {};
        _.each(udKeys.split(','), function(udKey) {
            var ud = udKey.split(':');
            o[ud[0]] = ud[1];
        })
        return o;
    }
    CommonViewFunction.udKeysObjectToStringParser = function(udKeys) {
        var list = _.map(udKeys, function(udKey) {
            var t = udKey.key + ':' + udKey.value;
            return t;
        });
        return list.join(',');
    }
987
    CommonViewFunction.fetchRootEntityAttributes = function(options) {
988 989 990 991 992 993 994 995 996 997
        $.ajax({
            url: options.url,
            methods: 'GET',
            dataType: 'json',
            cache: true,
            success: function(response) {
                if (response) {
                    _.each(options.entity, function(rootEntity) {
                        Globals[rootEntity] = $.extend(true, {}, response, { name: rootEntity, guid: rootEntity });
                    });
998
                }
999 1000 1001 1002
            },
            complete: function(response) {
                if (options.callback) {
                    options.callback(response);
1003
                }
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
            }
        });
    }
    CommonViewFunction.fetchRootClassificationAttributes = function(options) {
        $.ajax({
            url: options.url,
            methods: 'GET',
            dataType: 'json',
            cache: true,
            success: function(response) {
                if (response) {
                    _.each(options.classification, function(rootClassification) {
                        Globals[rootClassification] = $.extend(true, {}, response, { name: rootClassification, guid: rootClassification });
                    });
                }
            },
            complete: function(response) {
                if (options.callback) {
                    options.callback(response);
                }
            }
        });
    }
1027
    return CommonViewFunction;
1028
});