CommonViewFunction.js 39 KB

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