CommonViewFunction.js 39 KB

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