CommonViewFunction.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. define([ "require", "utils/Utils", "modules/Modal", "utils/Messages", "utils/Enums", "moment", "utils/Globals", "moment-timezone" ], function(require, Utils, Modal, Messages, Enums, moment, Globals) {
  2. "use strict";
  3. var CommonViewFunction = {};
  4. return CommonViewFunction.deleteTag = function(options) {
  5. require([ "models/VTag" ], function(VTag) {
  6. if (options && options.guid && options.tagName) {
  7. var tagModel = new VTag(), noticeRef = null, notifyObj = {
  8. modal: !0,
  9. okCloses: !1,
  10. okShowLoader: !0,
  11. text: options.msg,
  12. title: options.titleMessage,
  13. okText: options.okText,
  14. ok: function(notice) {
  15. noticeRef = notice, options.showLoader && options.showLoader(), tagModel.deleteAssociation(options.guid, options.tagName, options.associatedGuid, {
  16. defaultErrorMessage: options.tagName + Messages.deleteErrorMessage,
  17. success: function(data) {
  18. noticeRef && noticeRef.remove(), Utils.notifySuccess({
  19. content: "分类 " + options.tagName + Messages.getAbbreviationMsg(!1, "removeSuccessMessage")
  20. }), options.callback && options.callback(), options.collection && options.collection.fetch({
  21. reset: !0
  22. });
  23. },
  24. cust_error: function(model, response) {
  25. noticeRef && noticeRef.hideButtonLoader(), options.hideLoader && options.hideLoader();
  26. }
  27. });
  28. },
  29. cancel: function(argument) {
  30. options.hideLoader && options.hideLoader();
  31. }
  32. };
  33. Utils.notifyConfirm(notifyObj);
  34. }
  35. });
  36. }, CommonViewFunction.propertyTable = function(options) {
  37. var scope = options.scope, sortBy = options.sortBy, valueObject = options.valueObject, extractJSON = options.extractJSON, getArrayOfStringElement = options.getArrayOfStringElement, getArrayOfStringFormat = options.getArrayOfStringFormat, isTable = !!_.isUndefined(options.isTable) || options.isTable, attributeDefs = options.attributeDefs, formatIntVal = options.formatIntVal, showListCount = options.showListCount || !0, highlightString = options.highlightString, formatStringVal = options.formatStringVal, numberFormat = options.numberFormat || _.numberFormatWithComma, table = "", getHighlightedString = function(resultStr) {
  38. if (!highlightString || !highlightString.length) return resultStr;
  39. try {
  40. return resultStr.replace(new RegExp(highlightString, "gi"), function(foundStr) {
  41. return "<span class='searched-term-highlight'>" + foundStr + "</span>";
  42. });
  43. } catch (error) {
  44. return resultStr;
  45. }
  46. }, getEmptyString = function(key) {
  47. return options.getEmptyString ? options.getEmptyString(key) : "N/A";
  48. }, getValue = function(val, key) {
  49. if (options && options.getValue && (val = options.getValue(val, key)), _.isUndefined(val) || _.isNull(val)) return getEmptyString(key);
  50. if (!_.isNumber(val) && _.isNaN(parseInt(val)) || !formatIntVal) {
  51. var newVal = val;
  52. return formatStringVal && (newVal = parseInt(val), newVal = _.isNaN(newVal) ? val : numberFormat(newVal)),
  53. getHighlightedString(_.escape(newVal));
  54. }
  55. return numberFormat(val);
  56. }, fetchInputOutputValue = function(id, defEntity) {
  57. scope.entityModel.getEntityHeader(id, {
  58. success: function(serverData) {
  59. var value = "", deleteButton = "", data = serverData;
  60. value = Utils.getName(data);
  61. var id = "";
  62. data.guid && (Enums.entityStateReadOnly[data.status || data.entityStatus] && (deleteButton += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>'),
  63. id = data.guid), value.length > 0 ? scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + getValue(value) + "</a>") : scope.$('td div[data-id="' + id + '"]').html('<a href="#!/detailPage/' + id + '">' + _.escape(id) + "</a>"),
  64. deleteButton.length && (scope.$('td div[data-id="' + id + '"]').addClass("block readOnlyLink"),
  65. scope.$('td div[data-id="' + id + '"]').append(deleteButton));
  66. },
  67. cust_error: function(error, xhr) {
  68. 403 == xhr.status ? 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>') : defEntity && defEntity.options && "true" === defEntity.options.isSoftReference ? scope.$('td div[data-id="' + id + '"]').html("<div> " + id + "</div>") : 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>");
  69. },
  70. complete: function() {}
  71. });
  72. }, extractObject = function(opt) {
  73. var valueOfArray = [], keyValue = opt.keyValue, key = opt.key, defEntity = opt.defEntity;
  74. !_.isArray(keyValue) && _.isObject(keyValue) && (keyValue = [ keyValue ]);
  75. for (var subLink = "", i = 0; i < keyValue.length; i++) {
  76. var inputOutputField = keyValue[i], id = inputOutputField.guid || (_.isObject(inputOutputField.id) ? inputOutputField.id.id : inputOutputField.id), tempLink = "", status = inputOutputField.status || inputOutputField.entityStatus || (_.isObject(inputOutputField.id) ? inputOutputField.id.state : inputOutputField.state), readOnly = Enums.entityStateReadOnly[status];
  77. if (!inputOutputField.attributes && inputOutputField.values && (inputOutputField.attributes = inputOutputField.values),
  78. _.isString(inputOutputField) || _.isBoolean(inputOutputField) || _.isNumber(inputOutputField)) {
  79. var tempVarfor$check = inputOutputField.toString();
  80. if (tempVarfor$check.indexOf("$") == -1) {
  81. var tmpVal = getValue(inputOutputField, key);
  82. getArrayOfStringElement ? valueOfArray.push(getArrayOfStringElement(tmpVal, key)) : valueOfArray.push('<span class="json-string">' + tmpVal + "</span>");
  83. }
  84. } else if (_.isObject(inputOutputField) && !id) {
  85. var attributesList = inputOutputField;
  86. if (scope.typeHeaders && inputOutputField.typeName) {
  87. var typeNameCategory = scope.typeHeaders.fullCollection.findWhere({
  88. name: inputOutputField.typeName
  89. });
  90. attributesList.attributes && typeNameCategory && "STRUCT" === typeNameCategory.get("category") && (attributesList = attributesList.attributes);
  91. }
  92. if (extractJSON && extractJSON.extractKey) {
  93. var newAttributesList = {};
  94. _.each(attributesList, function(objValue, objKey) {
  95. var value = _.isObject(objValue) ? objValue : _.escape(objValue), tempVarfor$check = objKey.toString();
  96. tempVarfor$check.indexOf("$") == -1 && (_.isObject(extractJSON.extractKey) ? _.each(extractJSON.extractKey, function(extractKey) {
  97. objKey === extractKey && (newAttributesList[_.escape(objKey)] = value);
  98. }) : _.isString(extractJSON.extractKey) && extractJSON.extractKey === objKey && (newAttributesList[_.escape(objKey)] = value));
  99. }), valueOfArray.push(Utils.JSONPrettyPrint(newAttributesList, getValue));
  100. } else valueOfArray.push(Utils.JSONPrettyPrint(attributesList, getValue));
  101. }
  102. if (id && inputOutputField) {
  103. var name = Utils.getName(inputOutputField);
  104. if ("-" !== name && name !== id || inputOutputField.attributes) tempLink += "AtlasGlossaryTerm" == inputOutputField.typeName ? '<a href="#!/glossary/' + id + "?guid=" + id + '&gType=term&viewType=term&fromView=entity">' + name + "</a>" : '<a href="#!/detailPage/' + id + '">' + name + "</a>"; else {
  105. var fetch = !0, fetchId = _.isObject(id) ? id.id : id;
  106. fetchInputOutputValue(fetchId, defEntity), tempLink += '<div data-id="' + fetchId + '"><div class="value-loader"></div></div>';
  107. }
  108. }
  109. readOnly ? fetch ? (fetch = !1, subLink += tempLink) : (tempLink += '<button title="Deleted" class="btn btn-action btn-md deleteBtn"><i class="fa fa-trash"></i></button>',
  110. subLink += '<div class="block readOnlyLink">' + tempLink + "</div>") : tempLink.search("href") != -1 ? subLink += "<div>" + tempLink + "</div>" : tempLink.length && (subLink += tempLink);
  111. }
  112. return valueOfArray.length && (subLink = getArrayOfStringFormat ? getArrayOfStringFormat(valueOfArray, key) : valueOfArray.join(", ")),
  113. "" === subLink ? getEmptyString(key) : subLink;
  114. }, valueObjectKeysList = _.keys(valueObject);
  115. return (_.isUndefined(sortBy) || 1 == sortBy) && (valueObjectKeysList = _.sortBy(valueObjectKeysList)),
  116. valueObjectKeysList.map(function(key) {
  117. if ("profileData" != key) {
  118. var keyValue = valueObject[key], listCount = showListCount && _.isArray(keyValue) && keyValue.length > 0 ? " (" + numberFormat(keyValue.length) + ")" : "", defEntity = _.find(attributeDefs, {
  119. name: key
  120. });
  121. if (defEntity && defEntity.typeName) {
  122. var defEntityType = defEntity.typeName.toLocaleLowerCase();
  123. "date" === defEntityType ? keyValue = keyValue > 0 ? Utils.formatDate({
  124. date: keyValue
  125. }) : null : _.isObject(keyValue) && (keyValue = extractObject({
  126. keyValue: keyValue,
  127. key: key,
  128. defEntity: defEntity
  129. }));
  130. } else _.isObject(keyValue) && (keyValue = extractObject({
  131. keyValue: keyValue,
  132. key: key
  133. }));
  134. var val = "";
  135. if (val = _.isObject(valueObject[key]) ? keyValue : "guid" === key || "__guid" === key ? options.guidHyperLink === !1 ? getValue(keyValue, key) : '<a title="' + key + '" href="#!/detailPage/' + _.escape(keyValue) + '">' + getValue(keyValue, key) + "</a>" : getValue(keyValue, key),
  136. isTable) {
  137. var value = val, appendClass = "N/A" == value ? "hide-row" : "", htmlTag = '<div class="scroll-y">' + value + "</div>";
  138. if (_.isObject(valueObject[key]) && !_.isEmpty(valueObject[key])) {
  139. var matchedLinkString = val.match(/href|value-loader\w*/g), matchedJson = val.match(/json-value|json-string\w*/g), isMatchJSONStringIsSingle = (val.match(/json-key\w*/g),
  140. matchedLinkString && matchedLinkString.length <= 5, matchedJson && 1 == matchedJson.length), expandCollapseButton = "";
  141. if (matchedJson || matchedLinkString) {
  142. var className = "code-block fixed-height";
  143. isMatchJSONStringIsSingle || (className += " shrink", expandCollapseButton = '<button class="expand-collapse-button"><i class="fa"></i></button>'),
  144. htmlTag = '<pre class="' + className + '">' + expandCollapseButton + "<code>" + val + "</code></pre>";
  145. }
  146. }
  147. table += '<tr class="' + appendClass + '"><td>' + (_.escape(key) + listCount) + "</td><td>" + htmlTag + "</td></tr>";
  148. } else table += "<span>" + val + "</span>";
  149. }
  150. }), table && table.length > 0 ? table : '<tr class="empty"><td colspan="22"><span>No Record found!</span></td></tr>';
  151. }, CommonViewFunction.tagForTable = function(obj) {
  152. var traits = obj.classifications, tagHtml = "", addTag = "", popTag = "", count = 0, entityName = Utils.getName(obj);
  153. return traits && traits.map(function(tag) {
  154. var className = "btn btn-action btn-sm btn-blue btn-icon", deleteIcon = "";
  155. 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>' : obj.guid !== tag.entityGuid && "DELETED" === tag.entityStatus ? 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>' : className += " propagte-classification";
  156. var tagString = '<a class="' + className + '" data-id="tagClick"><span title="' + tag.typeName + '">' + tag.typeName + "</span>" + deleteIcon + "</a>";
  157. count >= 1 ? popTag += tagString : tagHtml += tagString, ++count;
  158. }), Enums.entityStateReadOnly[obj.status || obj.entityStatus] || (addTag += obj.guid ? '<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>' : '<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>'),
  159. count > 1 && (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>"),
  160. '<div class="tagList btn-inline btn-fixed-width">' + tagHtml + addTag + "</div>";
  161. }, CommonViewFunction.termForTable = function(obj) {
  162. var terms = obj.meanings, termHtml = "", addTerm = "", popTerm = "", count = 0, entityName = Utils.getName(obj);
  163. return terms && terms.map(function(term) {
  164. var displayText = _.escape(term.displayText), className = "btn btn-action btn-sm btn-blue btn-icon", deleteIcon = '<i class="fa fa-times" data-id="delete" data-assetname="' + entityName + '" data-name="' + displayText + '" data-type="term" data-guid="' + obj.guid + '" data-termGuid="' + term.termGuid + '" ></i>', termString = '<a class="' + className + '" data-id="termClick"><span title="' + displayText + '">' + displayText + "</span>" + deleteIcon + "</a>";
  165. count >= 1 ? popTerm += termString : termHtml += termString, ++count;
  166. }), Enums.entityStateReadOnly[obj.status || obj.entityStatus] || (addTerm += obj.guid ? '<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>' : '<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>'),
  167. 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>"),
  168. '<div class="tagList btn-inline btn-fixed-width">' + termHtml + addTerm + "</div>";
  169. }, CommonViewFunction.generateQueryOfFilter = function(value) {
  170. function objToString(filterObj) {
  171. var generatedQuery = _.map(filterObj.rules, function(obj, key) {
  172. var obj = $.extend(!0, {}, obj);
  173. return _.has(obj, "condition") ? '&nbsp<span class="operator">' + obj.condition + "</span>&nbsp(" + objToString(obj) + ")" : ("date" === obj.type && (Enums.queryBuilderDateRangeUIValueToAPI[obj.value] ? obj.value = Enums.queryBuilderDateRangeUIValueToAPI[obj.value] : obj.value = obj.value + " (" + moment.tz(moment.tz.guess()).zoneAbbr() + ")"),
  174. '<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>");
  175. });
  176. return generatedQuery;
  177. }
  178. value = Utils.getUrlState.getQueryParams();
  179. var entityFilters = CommonViewFunction.attributeFilter.extractUrl({
  180. value: value.entityFilters,
  181. formatDate: !0
  182. }), tagFilters = CommonViewFunction.attributeFilter.extractUrl({
  183. value: value.tagFilters,
  184. formatDate: !0
  185. }), queryArray = [];
  186. if (value.type) {
  187. var typeKeyValue = '<span class="key">类型:</span>&nbsp<span class="value">' + _.escape(value.type) + "</span>";
  188. if (entityFilters) {
  189. var conditionForEntity = 1 == entityFilters.rules.length ? "" : "与";
  190. typeKeyValue += '&nbsp<span class="operator">' + conditionForEntity + '</span>&nbsp(<span class="operator">' + entityFilters.condition + "</span>&nbsp(" + objToString(entityFilters) + "))";
  191. }
  192. queryArray.push(typeKeyValue);
  193. }
  194. if (value.tag) {
  195. var tagKeyValue = '<span class="key">分类:</span>&nbsp<span class="value">' + _.escape(value.tag) + "</span>";
  196. if (tagFilters) {
  197. var conditionFortag = 1 == tagFilters.rules.length ? "" : "与";
  198. tagKeyValue += '&nbsp<span class="operator">' + conditionFortag + '</span>&nbsp(<span class="operator">' + tagFilters.condition + "</span>&nbsp(" + objToString(tagFilters) + "))";
  199. }
  200. queryArray.push(tagKeyValue);
  201. }
  202. if (value.term) {
  203. var tagKeyValue = '<span class="key">术语:</span>&nbsp<span class="value">' + _.escape(value.term) + "</span>";
  204. queryArray.push(tagKeyValue);
  205. }
  206. return value.query && queryArray.push('<span class="key">查询语句:</span>&nbsp<span class="value">' + _.trim(_.escape(value.query)) + "</span>&nbsp"),
  207. 1 == queryArray.length ? queryArray.join() : "<span>(</span>&nbsp" + queryArray.join("<span>&nbsp)</span>&nbsp<span>AND</span>&nbsp<span>(</span>&nbsp") + "&nbsp<span>)</span>";
  208. }, CommonViewFunction.generateObjectForSaveSearchApi = function(options) {
  209. var obj = {
  210. name: options.name,
  211. guid: options.guid
  212. }, value = options.value;
  213. if (value) return _.each(Enums.extractFromUrlForSearch, function(svalue, skey) {
  214. _.isObject(svalue) ? _.each(svalue, function(v, k) {
  215. var val = value[k];
  216. _.isUndefinedNull(val) || ("attributes" == k ? val = val.split(",") : _.contains([ "tagFilters", "entityFilters" ], k) ? val = CommonViewFunction.attributeFilter.generateAPIObj(val) : _.contains([ "includeDE", "excludeST", "excludeSC" ], k) && (val = !val)),
  217. _.contains([ "includeDE", "excludeST", "excludeSC" ], k) && (val = !!_.isUndefinedNull(val) || val),
  218. obj[skey] || (obj[skey] = {}), obj[skey][v] = val;
  219. }) : obj[skey] = value[skey];
  220. }), obj;
  221. }, CommonViewFunction.generateUrlFromSaveSearchObject = function(options) {
  222. var value = options.value, classificationDefCollection = options.classificationDefCollection, entityDefCollection = options.entityDefCollection, obj = {};
  223. if (value) return _.each(Enums.extractFromUrlForSearch, function(svalue, skey) {
  224. _.isObject(svalue) ? _.each(svalue, function(v, k) {
  225. var val = value[skey][v];
  226. if (!_.isUndefinedNull(val)) if ("attributes" == k) val = val.join(","); else if ("tagFilters" == k) {
  227. if (classificationDefCollection) {
  228. var classificationDef = classificationDefCollection.fullCollection.findWhere({
  229. name: value[skey].classification
  230. }), attributeDefs = [];
  231. classificationDef && (attributeDefs = Utils.getNestedSuperTypeObj({
  232. collection: classificationDefCollection,
  233. attrMerge: !0,
  234. data: classificationDef.toJSON()
  235. })), Globals[value[skey].typeName] && (attributeDefs = Globals[value[skey].typeName].attributeDefs),
  236. Globals._ALL_CLASSIFICATION_TYPES && Globals._ALL_CLASSIFICATION_TYPES.attributeDefs && (attributeDefs = attributeDefs.concat(Globals._ALL_CLASSIFICATION_TYPES.attributeDefs));
  237. }
  238. val = CommonViewFunction.attributeFilter.generateUrl({
  239. value: val,
  240. attributeDefs: attributeDefs
  241. });
  242. } else if ("entityFilters" == k) {
  243. if (entityDefCollection) {
  244. var entityDef = entityDefCollection.fullCollection.findWhere({
  245. name: value[skey].typeName
  246. }), attributeDefs = [];
  247. entityDef && (attributeDefs = Utils.getNestedSuperTypeObj({
  248. collection: entityDefCollection,
  249. attrMerge: !0,
  250. data: entityDef.toJSON()
  251. })), Globals[value[skey].typeName] && (attributeDefs = Globals[value[skey].typeName].attributeDefs),
  252. Globals._ALL_ENTITY_TYPES && Globals._ALL_ENTITY_TYPES.attributeDefs && (attributeDefs = attributeDefs.concat(Globals._ALL_ENTITY_TYPES.attributeDefs));
  253. }
  254. val = CommonViewFunction.attributeFilter.generateUrl({
  255. value: val,
  256. attributeDefs: attributeDefs
  257. });
  258. } else _.contains([ "includeDE", "excludeST", "excludeSC" ], k) && (val = !val);
  259. obj[k] = val;
  260. }) : obj[skey] = value[skey];
  261. }), obj;
  262. }, CommonViewFunction.attributeFilter = {
  263. generateUrl: function(options) {
  264. function conditionalURl(options, spliter) {
  265. return options ? _.map(options.rules || options.criterion, function(obj, key) {
  266. if (_.has(obj, "condition")) return obj.condition + "(" + conditionalURl(obj, spliter + 1) + ")";
  267. if (attributeDefs) {
  268. var attributeDef = _.findWhere(attributeDefs, {
  269. name: obj.attributeName
  270. });
  271. attributeDef && (obj.attributeValue = obj.attributeValue, obj.attributeType = attributeDef.typeName);
  272. }
  273. var type = obj.type || obj.attributeType, value = _.isString(obj.value) && _.contains([ "is_null", "not_null" ], obj.operator) && "date" === type || _.isObject(obj.value) ? "" : _.trim(obj.value || obj.attributeValue), url = [ obj.id || obj.attributeName, mapApiOperatorToUI(obj.operator), value ];
  274. return "TIME_RANGE" === obj.operator ? value.indexOf("-") > -1 ? url[2] = value.split("-").map(function(udKey) {
  275. return Date.parse(udKey.trim()).toString();
  276. }).join(",") : url[2] = Enums.queryBuilderDateRangeUIValueToAPI[_.trim(value)] || value : value.length && "date" === type && formatedDateToLong && (url[2] = Date.parse(value)),
  277. type && url.push(type), url.join("::");
  278. }).join("|" + spliter + "|") : null;
  279. }
  280. function mapApiOperatorToUI(oper) {
  281. return Enums.queryBuilderApiOperatorToUI[oper] || oper;
  282. }
  283. var attrQuery = [], attrObj = options.value, formatedDateToLong = options.formatedDateToLong, attributeDefs = options.attributeDefs, spliter = 1;
  284. return attrQuery = conditionalURl(attrObj, spliter), attrQuery.length ? attrObj.condition + "(" + attrQuery + ")" : null;
  285. },
  286. extractUrl: function(options) {
  287. var attrObj = {}, urlObj = options.value, formatDate = options.formatDate, spliter = 1, apiObj = options.apiObj, mapUiOperatorToAPI = function(oper) {
  288. return Enums.queryBuilderUIOperatorToAPI[oper] || oper;
  289. }, createObject = function(urlObj) {
  290. var finalObj = {};
  291. return finalObj.condition = /^AND\(/.test(urlObj) ? "AND" : "OR", urlObj = "AND" === finalObj.condition ? urlObj.substr(4).slice(0, -1) : urlObj.substr(3).slice(0, -1),
  292. finalObj[apiObj ? "criterion" : "rules"] = _.map(urlObj.split("|" + spliter + "|"), function(obj, key) {
  293. var isStringNested = obj.split("|" + (spliter + 1) + "|").length > 1, isCondition = /^AND\(/.test(obj) || /^OR\(/.test(obj);
  294. if (isStringNested && isCondition) return ++spliter, createObject(obj);
  295. if (isCondition) return createObject(obj);
  296. var temp = obj.split("::") || obj.split("|" + spliter + "|"), rule = {};
  297. return apiObj ? (rule = {
  298. attributeName: temp[0],
  299. operator: mapUiOperatorToAPI(temp[1]),
  300. attributeValue: _.trim(temp[2])
  301. }, rule.attributeValue = "date" === rule.type && formatDate && rule.attributeValue.length ? Utils.formatDate({
  302. date: parseInt(rule.attributeValue),
  303. zone: !1
  304. }) : rule.attributeValue) : (rule = {
  305. id: temp[0],
  306. operator: temp[1],
  307. value: _.trim(temp[2])
  308. }, temp[3] && (rule.type = temp[3]), "TIME_RANGE" === rule.operator ? temp[2].indexOf(",") > -1 ? rule.value = temp[2].split(",").map(function(udKey) {
  309. return Utils.formatDate({
  310. date: parseInt(udKey.trim()),
  311. zone: !1
  312. });
  313. }).join(" - ") : rule.value = Enums.queryBuilderDateRangeAPIValueToUI[_.trim(rule.value)] || rule.value : "date" === rule.type && formatDate && rule.value.length && (rule.value = Utils.formatDate({
  314. date: parseInt(rule.value),
  315. zone: !1
  316. }))), rule;
  317. }), finalObj;
  318. };
  319. return urlObj && urlObj.length ? attrObj = createObject(urlObj) : null;
  320. },
  321. generateAPIObj: function(url) {
  322. return url && url.length ? this.extractUrl({
  323. value: url,
  324. apiObj: !0
  325. }) : null;
  326. }
  327. }, CommonViewFunction.createEditGlossaryCategoryTerm = function(options) {
  328. if (options) var model = options.model, isTermView = options.isTermView, isGlossaryView = options.isGlossaryView, collection = options.collection;
  329. require([ "views/glossary/CreateEditCategoryTermLayoutView", "views/glossary/CreateEditGlossaryLayoutView", "modules/Modal" ], function(CreateEditCategoryTermLayoutView, CreateEditGlossaryLayoutView, Modal) {
  330. var view = null, title = null;
  331. isGlossaryView ? (view = new CreateEditGlossaryLayoutView({
  332. glossaryCollection: collection,
  333. model: model
  334. }), title = "Glossary") : (view = new CreateEditCategoryTermLayoutView({
  335. glossaryCollection: collection,
  336. modelJSON: model
  337. }), title = isTermView ? "Term" : "Category");
  338. var modal = new Modal({
  339. title: (model ? "Update " : "Create ") + title,
  340. content: view,
  341. cancelText: "Cancel",
  342. okCloses: !1,
  343. okText: model ? "Update" : "Create",
  344. allowCancel: !0
  345. }).open();
  346. modal.$el.find("input[data-id=shortDescription]").on("input keydown", function(e) {
  347. $(this).val($(this).val().replace(/\s+/g, " "));
  348. }), modal.$el.find("button.ok").attr("disabled", "true"), modal.on("ok", function() {
  349. modal.$el.find("button.ok").showButtonLoader(), CommonViewFunction.createEditGlossaryCategoryTermSubmit(_.extend({
  350. ref: view,
  351. modal: modal
  352. }, options));
  353. }), modal.on("closeModal", function() {
  354. modal.trigger("cancel"), options.onModalClose && options.onModalClose();
  355. });
  356. });
  357. }, CommonViewFunction.createEditGlossaryCategoryTermSubmit = function(options) {
  358. 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) {
  359. return obj[item.name] = item.value.trim(), obj;
  360. }, {}), newModel = new options.collection.model(), messageType = "Glossary ";
  361. isTermView ? messageType = "Term " : isCategoryView && (messageType = "Category ");
  362. var ajaxOptions = {
  363. silent: !0,
  364. success: function(rModel, response) {
  365. var msgType = model ? "editSuccessMessage" : "addSuccessMessage";
  366. Utils.notifySuccess({
  367. content: messageType + ref.ui.name.val() + Messages.getAbbreviationMsg(!1, msgType)
  368. }), options.callback && options.callback(rModel), modal.trigger("closeModal");
  369. },
  370. cust_error: function() {
  371. modal.$el.find("button.ok").hideButtonLoader();
  372. }
  373. };
  374. if (model) isGlossaryView ? model.clone().set(data, {
  375. silent: !0
  376. }).save(null, ajaxOptions) : newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
  377. guid: model.guid,
  378. data: JSON.stringify(_.extend({}, model, data))
  379. })); else if (isGlossaryView) new collection.model().set(data).save(null, ajaxOptions); else {
  380. if (node) {
  381. data.anchor = {
  382. glossaryGuid: node.glossaryId || node.guid,
  383. displayText: node.glossaryName || node.text
  384. }, "GlossaryCategory" == node.type && (data.parentCategory = {
  385. categoryGuid: node.guid
  386. });
  387. }
  388. newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
  389. data: JSON.stringify(data)
  390. }));
  391. }
  392. }, CommonViewFunction.removeCategoryTermAssociation = function(options) {
  393. if (options) {
  394. var selectedGuid = options.selectedGuid, termGuid = options.termGuid, isCategoryView = options.isCategoryView, isTermView = options.isTermView, isEntityView = options.isEntityView, model = (options.collection,
  395. options.model), newModel = new options.collection.model(), noticeRef = null, ajaxOptions = {
  396. success: function(rModel, response) {
  397. noticeRef && noticeRef.remove(), Utils.notifySuccess({
  398. content: (isCategoryView || isEntityView ? "Term" : "Category") + " association is removed successfully"
  399. }), options.callback && options.callback();
  400. },
  401. cust_error: function() {
  402. noticeRef && noticeRef.hideButtonLoader(), options.hideLoader && options.hideLoader();
  403. }
  404. }, notifyObj = {
  405. modal: !0,
  406. okCloses: !1,
  407. okShowLoader: !0,
  408. text: options.msg,
  409. title: options.titleMessage,
  410. okText: options.buttonText,
  411. ok: function(notice) {
  412. if (noticeRef = notice, options.showLoader && options.showLoader(), isEntityView && model) {
  413. var data = [ model ];
  414. newModel.removeTermFromEntity(termGuid, _.extend(ajaxOptions, {
  415. data: JSON.stringify(data)
  416. }));
  417. } else {
  418. var data = _.extend({}, model);
  419. isTermView ? data.categories = _.reject(data.categories, function(term) {
  420. return term.categoryGuid == selectedGuid;
  421. }) : data.terms = _.reject(data.terms, function(term) {
  422. return term.termGuid == selectedGuid;
  423. }), newModel[isTermView ? "createEditTerm" : "createEditCategory"](_.extend(ajaxOptions, {
  424. guid: model.guid,
  425. data: JSON.stringify(_.extend({}, model, data))
  426. }));
  427. }
  428. },
  429. cancel: function() {}
  430. };
  431. Utils.notifyConfirm(notifyObj);
  432. }
  433. }, CommonViewFunction.addRestCsrfCustomHeader = function(xhr, settings) {
  434. if (null != settings.url) {
  435. var method = settings.type, csrfToken = CommonViewFunction.restCsrfValue;
  436. null == CommonViewFunction.restCsrfCustomHeader || CommonViewFunction.restCsrfMethodsToIgnore[method] || xhr.setRequestHeader(CommonViewFunction.restCsrfCustomHeader, csrfToken);
  437. }
  438. }, CommonViewFunction.restCsrfCustomHeader = null, CommonViewFunction.restCsrfMethodsToIgnore = null,
  439. CommonViewFunction.userDataFetch = function(options) {
  440. function getTrimmedStringArrayValue(string) {
  441. var str = string, array = [];
  442. if (str) for (var splitStr = str.split(","), i = 0; i < splitStr.length; i++) array.push(splitStr[i].trim());
  443. return array;
  444. }
  445. var csrfEnabled = !1, header = null, methods = [];
  446. options.url && $.ajax({
  447. url: options.url,
  448. success: function(response) {
  449. if (response) {
  450. if (response["atlas.rest-csrf.enabled"]) {
  451. var str = "" + response["atlas.rest-csrf.enabled"];
  452. csrfEnabled = "true" == str.toLowerCase();
  453. }
  454. if (response["atlas.rest-csrf.custom-header"] && (header = response["atlas.rest-csrf.custom-header"].trim()),
  455. response["atlas.rest-csrf.methods-to-ignore"] && (methods = getTrimmedStringArrayValue(response["atlas.rest-csrf.methods-to-ignore"])),
  456. csrfEnabled) {
  457. CommonViewFunction.restCsrfCustomHeader = header, CommonViewFunction.restCsrfMethodsToIgnore = {},
  458. CommonViewFunction.restCsrfValue = response._csrfToken || '""', methods.map(function(method) {
  459. CommonViewFunction.restCsrfMethodsToIgnore[method] = !0;
  460. });
  461. var statusCodeErrorFn = function(error) {
  462. Utils.defaultErrorHandler(null, error);
  463. };
  464. Backbone.$.ajaxSetup({
  465. statusCode: {
  466. 401: statusCodeErrorFn,
  467. 419: statusCodeErrorFn,
  468. 403: statusCodeErrorFn
  469. },
  470. beforeSend: CommonViewFunction.addRestCsrfCustomHeader
  471. });
  472. }
  473. }
  474. },
  475. complete: function(response) {
  476. options.callback && options.callback(response.responseJSON);
  477. }
  478. });
  479. }, CommonViewFunction.CheckDuplicateAndEmptyInput = function(elements, datalist) {
  480. for (var keyMap = new Map(), validation = !0, hasDup = [], i = 0; i < elements.length; i++) {
  481. var input = elements[i], pEl = input.nextElementSibling, classes = "form-control", val = input.value.trim();
  482. if (pEl.innerText = "", "" === val) validation = !1, pEl.innerText = "Required!"; else if (val.includes(":")) {
  483. validation = !1;
  484. var errorText = $(".errorMsg[data-id='charSupportMsg']").text();
  485. errorText && 0 === errorText.length && (pEl.innerText = "These special character '(:)' are not supported.");
  486. } else if ("INPUT" === input.tagName) {
  487. var duplicates = datalist.filter(function(c) {
  488. return c.key === val;
  489. });
  490. keyMap.has(val) || duplicates.length > 1 ? (classes = "form-control errorClass",
  491. // hasDup.push("duplicate"), pEl.innerText = "Duplicate key") : keyMap.set(val, val);
  492. hasDup.push("duplicate"), pEl.innerText = "重复的关键值") : keyMap.set(val, val);
  493. }
  494. validation === !1 && (classes = "form-control errorClass"), input.setAttribute("class", classes);
  495. }
  496. return {
  497. validation: validation,
  498. hasDuplicate: 0 !== hasDup.length
  499. };
  500. }, CommonViewFunction.getRandomIdAndAnchor = function() {
  501. var randomId = "collapse_" + parseInt(100 * Math.random()) + "_" + new Date().getUTCMilliseconds();
  502. return {
  503. id: randomId,
  504. anchor: "#" + randomId
  505. };
  506. }, CommonViewFunction.udKeysStringParser = function(udKeys) {
  507. var o = {};
  508. return _.each(udKeys.split(","), function(udKey) {
  509. var ud = udKey.split(":");
  510. o[ud[0]] = ud[1];
  511. }), o;
  512. }, CommonViewFunction.udKeysObjectToStringParser = function(udKeys) {
  513. var list = _.map(udKeys, function(udKey) {
  514. var t = udKey.key + ":" + udKey.value;
  515. return t;
  516. });
  517. return list.join(",");
  518. }, CommonViewFunction.fetchRootEntityAttributes = function(options) {
  519. $.ajax({
  520. url: options.url,
  521. methods: "GET",
  522. dataType: "json",
  523. cache: !0,
  524. success: function(response) {
  525. response && _.each(options.entity, function(rootEntity) {
  526. Globals[rootEntity] = $.extend(!0, {}, response, {
  527. name: rootEntity,
  528. guid: rootEntity
  529. });
  530. });
  531. },
  532. complete: function(response) {
  533. options.callback && options.callback(response);
  534. }
  535. });
  536. }, CommonViewFunction.fetchRootClassificationAttributes = function(options) {
  537. $.ajax({
  538. url: options.url,
  539. methods: "GET",
  540. dataType: "json",
  541. cache: !0,
  542. success: function(response) {
  543. response && _.each(options.classification, function(rootClassification) {
  544. Globals[rootClassification] = $.extend(!0, {}, response, {
  545. name: rootClassification,
  546. guid: rootClassification
  547. });
  548. });
  549. },
  550. complete: function(response) {
  551. options.callback && options.callback(response);
  552. }
  553. });
  554. }, CommonViewFunction;
  555. });