Utils.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. define(['require',
  19. 'utils/Enums',
  20. 'utils/LangSupport',
  21. 'moment',
  22. 'utils/Globals',
  23. 'bootbox'
  24. ],function(require,XAEnums,localization,moment,Globals,bootbox) {
  25. 'use strict';
  26. var prevNetworkErrorTime = 0;
  27. var Utils = {};
  28. require(['noty'],function(){
  29. $.extend($.noty.defaults,{
  30. timeout : 5000,
  31. layout : "topRight",
  32. theme : "relax",
  33. closeWith: ['click','button'],
  34. animation : {
  35. open : 'animated flipInX',
  36. close : 'animated flipOutX',
  37. easing: 'swing',
  38. speed : 500
  39. }
  40. });
  41. });
  42. // ///////////////////////////////////////////////////////
  43. // Enum utility methods
  44. // //////////////////////////////////////////////////////
  45. /**
  46. * Get enum for the enumId
  47. *
  48. * @param {integer}
  49. * enumId - The enumId
  50. */
  51. Utils.getEnum = function(enumId) {
  52. if (!enumId || enumId.length < 1) {
  53. return "";
  54. }
  55. // check if the enums are loaded
  56. if (!XAEnums[enumId]) {
  57. return "";
  58. }
  59. return XAEnums[enumId];
  60. };
  61. /**
  62. * Get enum by Enum and value
  63. *
  64. * @param {Object}
  65. * myEnum - The enum
  66. * @param {integer}
  67. * value - The value
  68. */
  69. Utils.enumElementByValue = function(myEnum, value) {
  70. var element = _.detect(myEnum, function(element) {
  71. return element.value == value;
  72. });
  73. return element;
  74. };
  75. /**
  76. * Get enum by Enum and name, value
  77. *
  78. * @param {Object}
  79. * myEnum - The enum
  80. * @param {string}
  81. * propertyName - The name of key
  82. * @param {integer}
  83. * propertyValue - The value
  84. */
  85. Utils.enumElementByPropertyNameValue = function(myEnum, propertyName,
  86. propertyValue) {
  87. for ( var element in myEnum) {
  88. if (myEnum[element][propertyName] == propertyValue) {
  89. return myEnum[element];
  90. }
  91. }
  92. return null;
  93. };
  94. /**
  95. * Get enum value for given enum label
  96. *
  97. * @param {Object}
  98. * myEnum - The enum
  99. * @param {string}
  100. * label - The label to search for in the Enum
  101. */
  102. Utils.enumLabelToValue = function(myEnum, label) {
  103. var element = _.detect(myEnum, function(element) {
  104. return element.label == label;
  105. });
  106. return (typeof element === "undefined") ? "--" : element.value;
  107. };
  108. /**
  109. * Get enum label for given enum value
  110. *
  111. * @param {Object}
  112. * myEnum - The enum
  113. * @param {integer}
  114. * value - The value
  115. */
  116. Utils.enumValueToLabel = function(myEnum, value) {
  117. var element = _.detect(myEnum, function(element) {
  118. return element.value == value;
  119. });
  120. return (typeof element === "undefined") ? "--" : element.label;
  121. };
  122. /**
  123. * Get enum label tt string for given Enum value
  124. *
  125. * @param {Object}
  126. * myEnum - The enum
  127. * @param {integer}
  128. * value - The value
  129. */
  130. Utils.enumValueToLabeltt = function(myEnum, value) {
  131. var element = _.detect(myEnum, function(element) {
  132. return element.value == value;
  133. });
  134. return (typeof element === "undefined") ? "--" : element.tt;
  135. };
  136. /**
  137. * Get NVpairs for given Enum to be used in Select
  138. *
  139. * @param {Object}
  140. * myEnum - The enum
  141. */
  142. Utils.enumToSelectPairs = function(myEnum) {
  143. return _.map(myEnum, function(o) {
  144. return {
  145. val : o.value,
  146. label : o.label
  147. };
  148. });
  149. };
  150. /**
  151. * Get NVpairs for given Enum
  152. *
  153. * @param {Object}
  154. * myEnum - The enum
  155. */
  156. Utils.enumNVPairs = function(myEnum) {
  157. var nvPairs = {
  158. ' ' : '--Select--'
  159. };
  160. for ( var name in myEnum) {
  161. nvPairs[myEnum[name].value] = myEnum[name].label;
  162. }
  163. return nvPairs;
  164. };
  165. /**
  166. * Get array NV pairs for given Array
  167. *
  168. * @param {Array}
  169. * myArray - The eArraynum
  170. */
  171. Utils.arrayNVPairs = function(myArray) {
  172. var nvPairs = {
  173. ' ' : '--Select--'
  174. };
  175. _.each(myArray, function(val) {
  176. nvPairs[val] = val;
  177. });
  178. return nvPairs;
  179. };
  180. Utils.notifyInfo = function(options) {
  181. noty({
  182. type:"information",
  183. text : "<i class='fa fa-exclamation-circle'></i> "+(options.content || "Info message.")
  184. });
  185. };
  186. Utils.notifyWarn = function(options) {
  187. noty({
  188. type:"warning",
  189. text : "<i class='fa fa-times-circle'></i> "+(options.content || "Info message.")
  190. });
  191. };
  192. Utils.notifyError = function(options) {
  193. noty({
  194. type:"error",
  195. text : "<i class='fa fa-times-circle'></i> "+(options.content || "Error occurred.")
  196. });
  197. };
  198. Utils.notifySuccess = function(options) {
  199. noty({
  200. type:"success",
  201. text : "<i class='fa fa-check-circle-o'></i> "+(options.content || "Error occurred.")
  202. });
  203. };
  204. /**
  205. * Convert new line to <br />
  206. *
  207. * @param {string}
  208. * str - the string to convert
  209. */
  210. Utils.nl2br = function(str) {
  211. if (!str)
  212. return '';
  213. return str.replace(/\n/g, '<br/>').replace(/[\r\t]/g, " ");
  214. };
  215. /**
  216. * Convert <br />
  217. * to new line
  218. *
  219. * @param {string}
  220. * str - the string to convert
  221. */
  222. Utils.br2nl = function(str) {
  223. if (!str)
  224. return '';
  225. return str.replace(/\<br(\s*\/|)\>/gi, '\n');
  226. };
  227. /**
  228. * Escape html chars
  229. *
  230. * @param {string}
  231. * str - the html string to escape
  232. */
  233. Utils.escapeHtmlChar = function(str) {
  234. if (!str)
  235. return '';
  236. str = str.replace(/&/g, "&amp;");
  237. str = str.replace(/>/g, "&gt;");
  238. str = str.replace(/</g, "&lt;");
  239. str = str.replace(/\"/g, "&quot;");
  240. str = str.replace(/'/g, "&#039;");
  241. return str;
  242. };
  243. /**
  244. * nl2br and Escape html chars
  245. *
  246. * @param {string}
  247. * str - the html string
  248. */
  249. Utils.nl2brAndEscapeHtmlChar = function(str) {
  250. if (!str)
  251. return '';
  252. var escapedStr = escapeHtmlChar(str);
  253. var finalStr = nl2br(str);
  254. return finalStr;
  255. };
  256. /**
  257. * prevent navigation with msg and call callback
  258. *
  259. * @param {String}
  260. * msg - The msg to show
  261. * @param {function}
  262. * callback - The callback to call
  263. */
  264. Utils.preventNavigation = function(msg, $form) {
  265. window._preventNavigation = true;
  266. window._preventNavigationMsg = msg;
  267. $("body a, i[class^='icon-']").on("click.blockNavigation", function(e) {
  268. Utils.preventNavigationHandler.call(this, e, msg, $form);
  269. });
  270. };
  271. /**
  272. * remove the block of preventNavigation
  273. */
  274. Utils.allowNavigation = function() {
  275. window._preventNavigation = false;
  276. window._preventNavigationMsg = undefined;
  277. $("body a, i[class^='icon-']").off('click.blockNavigation');
  278. };
  279. Utils.preventNavigationHandler = function(e, msg, $form) {
  280. var formChanged = false;
  281. var target = this;
  282. if (!_.isUndefined($form))
  283. formChanged = $form.find('.dirtyField').length > 0 ? true : false;
  284. if (!$(e.currentTarget).hasClass("_allowNav") && formChanged) {
  285. e.preventDefault();
  286. e.stopImmediatePropagation();
  287. bootbox.dialog(msg, [ {
  288. "label" : localization.tt('btn.stayOnPage'),
  289. "class" : "btn-success btn-small",
  290. "callback" : function() {
  291. }
  292. }, {
  293. "label" : localization.tt('btn.leavePage'),
  294. "class" : "btn-danger btn-small",
  295. "callback" : function() {
  296. Utils.allowNavigation();
  297. target.click();
  298. }
  299. } ]);
  300. return false;
  301. }
  302. };
  303. /**
  304. * Bootbox wrapper for alert
  305. *
  306. * @param {Object}
  307. * params - The params
  308. */
  309. Utils.alertPopup = function(params) {
  310. if (params.callback == undefined) {
  311. bootbox.alert(params.msg);
  312. } else {
  313. bootbox.alert(params.msg, params.callback);
  314. }
  315. };
  316. /**
  317. * Bootbox wrapper for confirm
  318. *
  319. * @param {Object}
  320. * params - The params
  321. */
  322. Utils.confirmPopup = function(params) {
  323. bootbox.confirm(params.msg, function(result) {
  324. if (result) {
  325. params.callback();
  326. }
  327. });
  328. };
  329. Utils.filterResultByIds = function(results, selectedVals) {
  330. return _.filter(results, function(obj) {
  331. if ($.inArray(obj.id, selectedVals) < 0)
  332. return obj;
  333. });
  334. };
  335. Utils.filterResultByText = function(results, selectedVals) {
  336. return _.filter(results, function(obj) {
  337. if ($.inArray(obj.text, selectedVals) < 0)
  338. return obj;
  339. });
  340. };
  341. Utils.scrollToField = function(field) {
  342. $("html, body").animate({
  343. scrollTop : field.position().top - 80
  344. }, 1100, function() {
  345. field.focus();
  346. });
  347. };
  348. Utils.blockUI = function(options) {
  349. var Opt = {
  350. autoUnblock : false,
  351. clickUnblock : false,
  352. bgPath : 'images/',
  353. content : '<img src="images/blockLoading.gif" > Please wait..',
  354. css : {}
  355. };
  356. options = _.isUndefined(options) ? Opt : options;
  357. $.msg(options);
  358. };
  359. var errorShown = false;
  360. Utils.defaultErrorHandler = function(model, error) {
  361. if (error.status == 500) {
  362. try {
  363. if (!errorShown) {
  364. errorShown = true;
  365. Utils.notifyError({
  366. content: "Some issue on server, Please try again later."
  367. });
  368. setTimeout(function() {
  369. errorShown = false;
  370. }, 3000);
  371. }
  372. } catch (e) {}
  373. }
  374. else if (error.status == 400) {
  375. try {
  376. if (!errorShown) {
  377. errorShown = true;
  378. Utils.notifyError({
  379. content: JSON.parse(error.responseText).msgDesc
  380. });
  381. setTimeout(function() {
  382. errorShown = false;
  383. }, 3000);
  384. }
  385. } catch (e) {}
  386. } else if (error.status == 401) {
  387. window.location = 'login.jsp' + window.location.search;
  388. // App.rContent.show(new vError({
  389. // status : error.status
  390. // }));
  391. } else if (error.status == 419) {
  392. window.location = 'login.jsp' + window.location.search;
  393. } else if (error.status == "0") {
  394. var diffTime = (new Date().getTime() - prevNetworkErrorTime);
  395. if (diffTime > 3000) {
  396. prevNetworkErrorTime = new Date().getTime();
  397. Utils.notifyError({
  398. content: "Network Connection Failure : " +
  399. "It seems you are not connected to the internet. Please check your internet connection and try again"
  400. })
  401. }
  402. }
  403. // require(['views/common/ErrorView','App'],function(vError,App){
  404. // });
  405. };
  406. Utils.select2Focus = function(event) {
  407. if (/^select2-focus/.test(event.type)) {
  408. $(this).select2('open');
  409. }
  410. };
  411. Utils.checkDirtyField = function(arg1, arg2, $elem) {
  412. if (_.isEqual(arg1, arg2)) {
  413. $elem.removeClass('dirtyField');
  414. } else {
  415. $elem.addClass('dirtyField');
  416. }
  417. };
  418. Utils.checkDirtyFieldForToggle = function($el) {
  419. if ($el.hasClass('dirtyField')) {
  420. $el.removeClass('dirtyField');
  421. } else {
  422. $el.addClass('dirtyField');
  423. }
  424. };
  425. Utils.checkDirtyFieldForSelect2 = function($el, dirtyFieldValue, that) {
  426. if ($el.hasClass('dirtyField')
  427. && _.isEqual($el.val(), dirtyFieldValue.toString())) {
  428. $el.removeClass('dirtyField');
  429. } else if (!$el.hasClass('dirtyField')) {
  430. $el.addClass('dirtyField');
  431. dirtyFieldValue = !_.isUndefined(that.value.values) ? that.value.values
  432. : '';
  433. }
  434. return dirtyFieldValue;
  435. };
  436. Utils.enumToSelectLabelValuePairs = function(myEnum) {
  437. return _.map(myEnum, function(o) {
  438. return {
  439. label : o.label,
  440. value : o.value + ''
  441. // category :'DHSS',
  442. };
  443. });
  444. };
  445. Utils.hackForVSLabelValuePairs = function(myEnum) {
  446. return _.map(myEnum, function(o) {
  447. return {
  448. label : o.label,
  449. value : o.label + ''
  450. // category :'DHSS',
  451. };
  452. });
  453. };
  454. Utils.addVisualSearch = function(searchOpt, serverAttrName, collection,
  455. pluginAttr) {
  456. var visualSearch;
  457. var search = function(searchCollection, serverAttrName, searchOpt,
  458. collection) {
  459. var params = {};
  460. searchCollection.each(function(m) {
  461. var serverParamName = _.findWhere(serverAttrName, {
  462. text : m.attributes.category
  463. });
  464. var extraParam = {};
  465. if (_.has(serverParamName, 'multiple')
  466. && serverParamName.multiple) {
  467. extraParam[serverParamName.label] = Utils
  468. .enumLabelToValue(serverParamName.optionsArr, m
  469. .get('value'));
  470. ;
  471. $.extend(params, extraParam);
  472. } else {
  473. if (!_.isUndefined(serverParamName)) {
  474. extraParam[serverParamName.label] = m.get('value');
  475. $.extend(params, extraParam);
  476. }
  477. }
  478. });
  479. collection.queryParams = $.extend(collection.queryParams, params);
  480. collection.state.currentPage = collection.state.firstPage;
  481. collection.fetch({
  482. reset : true,
  483. cache : false
  484. // data : params,
  485. });
  486. };
  487. // var searchOpt = ['Event Time','User','Resource Name','Resource
  488. // ID','Resource Type','Repository Name','Repository
  489. // Type','Result','Client IP','Client Type','Access Type','Access
  490. // Enforcer','Audit Type','Session ID'];
  491. var callbackCommon = {
  492. search : function(query, searchCollection) {
  493. collection.VSQuery = query;
  494. search(searchCollection, serverAttrName, searchOpt, collection);
  495. },
  496. clearSearch : function(callback) {
  497. _.each(serverAttrName, function(attr) {
  498. delete collection.queryParams[attr.label];
  499. });
  500. callback();
  501. },
  502. facetMatches : function(callback) {
  503. // console.log(visualSearch);
  504. var searchOptTemp = $.extend(true, [], searchOpt);
  505. visualSearch.searchQuery.each(function(m) {
  506. if ($.inArray(m.get('category'), searchOptTemp) >= 0) {
  507. searchOptTemp.splice($.inArray(m.get('category'),
  508. searchOptTemp), 1);
  509. }
  510. });
  511. // visualSearch.options.readOnly = searchOptTemp.length <= 0 ?
  512. // true : false;
  513. callback(searchOptTemp, {
  514. preserveOrder : false
  515. });
  516. },
  517. removedFacet : function(removedFacet, searchCollection, indexObj) {
  518. // console.log(removedFacet);
  519. var removedFacetSeverName = _.findWhere(serverAttrName, {
  520. text : removedFacet.get('category')
  521. });
  522. if (!_.isUndefined(removedFacetSeverName)) {
  523. delete collection.queryParams[removedFacetSeverName.label];
  524. collection.state.currentPage = collection.state.firstPage;
  525. collection.fetch({
  526. reset : true,
  527. cache : false
  528. });
  529. }
  530. // TODO Added for Demo to remove datapicker popups
  531. if (!_.isUndefined(visualSearch.searchBox.$el))
  532. visualSearch.searchBox.$el.parents('body').find(
  533. '.datepicker').remove();
  534. }
  535. // we can also add focus, blur events callback here..
  536. };
  537. pluginAttr.callbacks = $.extend(callbackCommon, pluginAttr.callbacks);
  538. // Initializing VisualSearch Plugin....
  539. visualSearch = VS.init($.extend(pluginAttr, {
  540. remainder : false
  541. }));
  542. if (visualSearch.searchQuery.length > 0) // For On Load Visual Search
  543. search(visualSearch.searchQuery, serverAttrName, searchOpt,
  544. collection);
  545. return visualSearch;
  546. };
  547. Utils.displayDatepicker = function($el, facet, $date, callback) {
  548. var input = $el
  549. .find('.search_facet.is_editing input.search_facet_input');
  550. $el.parents('body').find('.datepicker').hide();
  551. input.datepicker({
  552. autoclose : true,
  553. dateFormat : 'yy-mm-dd'
  554. }).on('changeDate', function(ev) {
  555. callback(ev.date);
  556. input.datepicker("hide");
  557. var e = jQuery.Event("keydown");
  558. e.which = 13; // Enter
  559. $(this).trigger(e);
  560. });
  561. if (!_.isUndefined($date)) {
  562. if (facet == 'Start Date') {
  563. input.datepicker('setEndDate', $date);
  564. } else {
  565. input.datepicker('setStartDate', $date);
  566. }
  567. }
  568. input.datepicker('show');
  569. input.on('blur', function(e) {
  570. input.datepicker("hide");
  571. // $('.datepicker').remove();
  572. });
  573. // input.attr("readonly", "readonly");
  574. input.on('keydown', function(e) {
  575. if (e.which == 9 && e.shiftKey) {
  576. input.datepicker('setValue', new Date());
  577. input.trigger('change');
  578. input.datepicker("hide");
  579. }
  580. if (e.which == 13) {
  581. var e1 = jQuery.Event("keypress");
  582. e1.which = 13; // Enter
  583. $(this).trigger(e1);
  584. }
  585. });
  586. return input;
  587. };
  588. Utils.capitaliseFirstLetter = function(string) {
  589. return string.charAt(0).toUpperCase() + string.slice(1);
  590. };
  591. Utils.lowerCaseFirstLetter = function(string) {
  592. return string.charAt(0).toLowerCase() + string.slice(1);
  593. };
  594. Utils.toUpperCase = function(string) {
  595. return (""+string).toUpperCase();
  596. };
  597. Utils.bindDraggableEvent = function($el){
  598. //
  599. // Function maked all .box selector is draggable, to disable for concrete element add class .no-drop
  600. //
  601. $el
  602. .draggable({
  603. revert: true,
  604. zIndex: 2000,
  605. cursor: "crosshair",
  606. handle: '.box-name',
  607. opacity: 0.8
  608. })
  609. .droppable({
  610. tolerance: 'pointer',
  611. drop: function( event, ui ) {
  612. var draggable = ui.draggable;
  613. var droppable = $(this);
  614. var dragPos = draggable.position();
  615. var dropPos = droppable.position();
  616. draggable.swap(droppable);
  617. setTimeout(function() {
  618. var dropmap = droppable.find('[id^=map-]');
  619. var dragmap = draggable.find('[id^=map-]');
  620. if (dragmap.length > 0 || dropmap.length > 0){
  621. dragmap.resize();
  622. dropmap.resize();
  623. }
  624. else {
  625. draggable.resize();
  626. droppable.resize();
  627. }
  628. }, 50);
  629. setTimeout(function() {
  630. draggable.find('[id^=map-]').resize();
  631. droppable.find('[id^=map-]').resize();
  632. }, 250);
  633. }
  634. });
  635. };
  636. Utils.scrollToSearchString = function(results, type, counter, adjPx,$el){
  637. if(results.length > 0){
  638. if(type === 'next'){
  639. if(counter > 0 && results.length == counter){
  640. counter = 0;
  641. }
  642. } else if (type === 'prev') {
  643. if(counter < 0){
  644. counter = results.length - 1;
  645. } else if(counter === results.length){
  646. counter = counter - 2;
  647. }
  648. }
  649. results.removeClass("active");
  650. $(results[counter]).addClass("active");
  651. if(_.isUndefined($el)){
  652. $('html,body').animate({
  653. scrollTop: $(results[counter]).offset().top - adjPx
  654. }, 100);
  655. }else{
  656. $el.animate({
  657. scrollTop: $(results[counter]).offset().top - adjPx
  658. }, 100);
  659. }
  660. counter = (type === 'prev') ? counter - 1 : counter + 1;
  661. }
  662. return counter;
  663. };
  664. //date should be javascript date
  665. Utils.convertDateToUTC = function (date) {
  666. return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
  667. }
  668. Utils.randomNumber = function(){
  669. var date = new Date();
  670. var id = new Number();
  671. return ((Math.random()*date.getTime())/2).toFixed(0)
  672. }
  673. /**
  674. * GET data from form
  675. * @param {object} title -serializeArray
  676. */
  677. Utils.getFormData = function(serializeArray) {
  678. var formJson = {};
  679. _.each(serializeArray, function(fValues) {
  680. formJson[fValues.name] = fValues.value;
  681. });
  682. return formJson;
  683. };
  684. Utils.getQueryParams = function(qs) {
  685. qs = qs.split('+').join(' ');
  686. var params = {},
  687. tokens,
  688. re = /[?&]?([^=]+)=([^&]*)/g;
  689. while (tokens = re.exec(qs)) {
  690. params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
  691. }
  692. return params;
  693. };
  694. /**
  695. * [converDate description]
  696. * @param {[type]} option [pass String or momnet object]
  697. * @return {[type]} [it is string]
  698. */
  699. Utils.dateUtil = new function() {
  700. var that = this;
  701. this.getTimeZone = function(string, format) {
  702. return moment(string).format((format || Globals.dateFormat));
  703. };
  704. this.getJSON = function(string) {
  705. return moment(string).toJSON();
  706. };
  707. this.getMomentUTC = function(string) {
  708. return moment.utc(string)
  709. };
  710. this.getMomentObject = function(string) {
  711. return moment(string)
  712. }
  713. this.getLocalTimeZoneDateObject = function(date,offset) {
  714. return new Date(date.setMinutes(-(date.getTimezoneOffset() + (offset))))
  715. }
  716. this.getTimeZoneDateObject = function(string) {
  717. return new Date(string)
  718. }
  719. /**
  720. * [getTimeZoneMomentDateObject it will return ]
  721. * @param {[type]} option [require moment tz object]
  722. * @return {[type]} [description]
  723. */
  724. this.getTimeZoneFromMomentObject = function(momentO) {
  725. if(momentO.isValid()){
  726. var date = momentO.format('MM/DD/YYYY,HH:mm:ss.SSS').split(',');
  727. var dateObjectWithMilisecond ="";
  728. if(date[0] && date[1]){
  729. var milliseconds = date[1].split('.');
  730. if(milliseconds[0] && milliseconds[1] ){
  731. dateObjectWithMilisecond = new Date( date[0] +" " +milliseconds[0]);
  732. dateObjectWithMilisecond.setMilliseconds(milliseconds[1]);
  733. }else{
  734. dateObjectWithMilisecond = new Date(date[0]);
  735. }
  736. return dateObjectWithMilisecond;
  737. }
  738. }else{
  739. this.getLocalTimeZoneDateObject( ((momentO.toDate())?(momentO.toDate()):(new Date(momentO))));
  740. }
  741. }
  742. this.getTimeDiff = function(option) {
  743. // If You have time more then 24 hours so moment returns 0 for HH:MM:SS so using this 3 line we get perfect time gap
  744. var self = this;
  745. var ms = moment(option[1], "DD/MM/YYYY HH:mm:ss").diff(moment(option[0], "DD/MM/YYYY HH:mm:ss"));
  746. var d = moment.duration(ms);
  747. var s = Math.floor(d.asHours()) + that.getMomentUTC(ms).format(":mm:ss");
  748. this.splitedValue = s.split(':');
  749. this.getHourDiff = function() {
  750. return parseInt(self.splitedValue[0]);
  751. };
  752. this.getMinuteDiff = function() {
  753. return parseInt(self.splitedValue[1]);
  754. };
  755. this.getSecondDiff = function() {
  756. return parseInt(self.splitedValue[2]);
  757. };
  758. }
  759. this.setTimeZone =function(zone){
  760. moment.tz.setDefault(zone)
  761. }
  762. this.getRelativeDateString =function(){}
  763. this.getLast1HourRange = function(){
  764. return [moment().hour(moment().hours() - 1).minute(moment().minutes() - 1).seconds(moment().seconds() - 1), moment().hour(moment().hours()).minute(moment().minutes()).seconds(moment().seconds())];
  765. }
  766. this.getTodayRange = function() {
  767. return [moment().hour('0').minute('0').seconds('01').milliseconds("000"), moment().hour('23').minute('59').seconds('59').milliseconds("999")];
  768. }
  769. this.getYesterdayRange = function() {
  770. return [moment().subtract(1, 'days').hour('0').minute('0').seconds('01').milliseconds("000"), moment().subtract(1, 'days').hour('23').minute('59').seconds('59').milliseconds("999")];
  771. }
  772. this.getLast7DaysRange = function() {
  773. return [moment().subtract(6, 'days').hour('0').minute('0').seconds('01').milliseconds("000"), moment().hour('23').minute('59').seconds('59').milliseconds("999")];
  774. }
  775. this.getLast30DaysRange = function() {
  776. return [moment().subtract(29, 'days').hour('0').minute('0').seconds('01').milliseconds("000"), moment().hour('23').minute('59').seconds('59').milliseconds("999")];
  777. }
  778. this.getThisMonthRange = function() {
  779. return [moment().startOf('month').hour('0').minute('0').seconds('01').milliseconds("000"), moment().endOf('month').hour('23').minute('59').seconds('59').milliseconds("999")];
  780. }
  781. this.getLastMonthRange = function() {
  782. return [moment().subtract(1, 'month').startOf('month').hour('0').minute('0').seconds('01').milliseconds("000"), moment().subtract(1, 'month').endOf('month').hour('23').minute('59').seconds('59').milliseconds("999")];
  783. }
  784. this.getOneDayTimeDiff = function(checkTime) {
  785. var hourDiff = checkTime.getHourDiff();
  786. var seconDiff = checkTime.getSecondDiff();
  787. var minuteDiff = checkTime.getMinuteDiff();
  788. if (hourDiff <= 2) {
  789. if (hourDiff == 0) {
  790. if (minuteDiff == 0) {
  791. if (seconDiff == 0) {
  792. return "+100MILLISECOND";
  793. } else {
  794. if (seconDiff > 30) {
  795. return "+2SECOND";
  796. } else if (seconDiff < 30 && seconDiff > 1) {
  797. return "+500MILLISECOND";
  798. } else {
  799. return "+100MILLISECOND";
  800. }
  801. }
  802. } else {
  803. if (minuteDiff > 30) {
  804. return "+2MINUTE";
  805. } else if (minuteDiff < 30 || minuteDiff > 1) {
  806. return "+1MINUTE";
  807. }
  808. }
  809. } else {
  810. if (hourDiff == 1) {
  811. return "+2MINUTE";
  812. } else if (hourDiff == 2) {
  813. return "+5MINUTE";
  814. }
  815. }
  816. } else if (hourDiff <= 6) {
  817. return "+5MINUTE";
  818. } else if (hourDiff <= 10) {
  819. return "+10MINUTE";
  820. } else {
  821. return "+1HOUR";
  822. }
  823. }
  824. this.getMonthDiff = function(startDate, endDate, dayGap, checkTime) {
  825. var dayDiff = (moment(endDate).diff(startDate, 'days'));
  826. if (dayDiff <= dayGap) {
  827. if (dayDiff == 0) {
  828. return this.getOneDayTimeDiff(checkTime)
  829. } else {
  830. return "+" + (moment(endDate).diff(startDate, 'days')) + "HOUR"
  831. }
  832. } else {
  833. return "+1DAY"
  834. }
  835. }
  836. this.calculateUnit =function(picker){
  837. var dayGap = 10,
  838. startDate = new Date(picker.startDate.format('MM/DD/YYYY')),
  839. endDate = new Date(picker.endDate.format('MM/DD/YYYY')),
  840. now = new Date(moment().format('MM/DD/YYYY'));
  841. var checkTime = new that.getTimeDiff([picker.startDate.format('MM/DD/YYYY HH:mm:ss'), picker.endDate.format('MM/DD/YYYY HH:mm:ss')]);
  842. if ((moment(startDate).isSame(endDate)) && (moment(startDate).isSame(now))) {
  843. //console.log("today")
  844. return that.getOneDayTimeDiff(checkTime);
  845. } else if ((moment(startDate).isSame(endDate)) && (moment(startDate).isBefore(now))) {
  846. //console.log("yesterday")
  847. return that.getOneDayTimeDiff(checkTime);
  848. } else if ((moment(startDate).isBefore(now)) || (moment(now).diff(startDate, 'days'))) {
  849. if ((moment(now).diff(startDate, 'days')) === 6) {
  850. //console.log("last 7 days");
  851. return "+8HOUR";
  852. } else if ((moment(now).diff(startDate, 'days') === 29) || (moment(now).diff(startDate, 'days') === 28) || (moment(now).diff(startDate, 'days') === 30)) {
  853. //console.log("Last 30 days");
  854. return that.getMonthDiff(startDate, endDate, dayGap, checkTime);
  855. } else if ((moment(now).diff(startDate, 'month') === 1) && (moment(now).diff(startDate, 'days') > 30) && (moment(startDate).isSame(endDate, 'month'))) {
  856. //console.log("Last Month");
  857. return that.getMonthDiff(startDate, endDate, dayGap, checkTime);
  858. } else if ((moment(startDate).isSame(endDate, 'month')) && ((moment(now).diff(startDate, 'days') === 29) || (moment(now).diff(startDate, 'days') === 30) || (moment(now).diff(startDate, 'days') === 28))) {
  859. //console.log("this Month");
  860. return that.getMonthDiff(startDate, endDate, dayGap, checkTime);
  861. } else if ((moment(endDate).diff(startDate, 'days') >= 28) && (moment(endDate).diff(startDate, 'days') <= 30)) {
  862. //console.log("Last 30 days");
  863. return that.getMonthDiff(startDate, endDate, dayGap, checkTime);
  864. } else if ((moment(endDate).diff(startDate, 'month') > 3)) {
  865. return "+1MONTH";
  866. } else if ((moment(endDate).diff(startDate, 'month') < 3)) {
  867. if ((moment(endDate).diff(startDate, 'month')) === 0) {
  868. return that.getMonthDiff(startDate, endDate, dayGap, checkTime);
  869. } else {
  870. return "+1MONTH"
  871. }
  872. } else {
  873. return "+1MONTH";
  874. }
  875. } else {
  876. if ((moment(endDate).diff(startDate, 'days') < 10)) {
  877. return "+2HOUR";
  878. } else if ((moment(endDate).diff(startDate, 'days') >15)) {
  879. return "+8HOUR";
  880. } else if ((moment(endDate).diff(startDate, 'days') <= 30)) {
  881. return "+1DAY";
  882. } else {
  883. return "+1MONTH";
  884. }
  885. }
  886. }
  887. this.getRelativeDateFromString = function(string){
  888. var obj = _.findWhere(Utils.relativeDates, { text : string})
  889. if(obj)
  890. return obj.fn && obj.fn();
  891. }
  892. };
  893. Utils.relativeDates = {
  894. last1Hour : {text : "Last 1 Hour",fn:Utils.dateUtil.getLast1HourRange},
  895. today : {text : "Today",fn:Utils.dateUtil.getTodayRange},
  896. yesterday : {text : "Yesterday",fn:Utils.dateUtil.getYesterdayRange},
  897. last7Days : {text : "Last 7 Days",fn:Utils.dateUtil.getLast7DaysRange},
  898. last30Days: {text : "Last 30 Days",fn:Utils.dateUtil.getLast30DaysRange},
  899. thisMonth : {text : "This Month",fn:Utils.dateUtil.getThisMonthRange},
  900. lastMonth : {text : "Last Month",fn:Utils.dateUtil.getLastMonthRange}
  901. };
  902. /*
  903. * Converting Include Exclude string
  904. */
  905. Utils.encodeIncludeExcludeStr = function(arrOrStr,doEncode,token){
  906. var token = token || Globals.splitToken;
  907. if(doEncode && _.isArray(arrOrStr)){
  908. return arrOrStr.join(token);
  909. }else if(_.isString(arrOrStr)){
  910. return arrOrStr.split(token);
  911. }
  912. };
  913. Utils.localStorage = {
  914. checkLocalStorage:function(key,value){
  915. if (typeof(Storage) !== "undefined") {
  916. return this.getLocalStorage(key,value);
  917. } else {
  918. console.log('Sorry! No Web Storage support');
  919. Utils.cookie.checkCookie(key,value);
  920. }
  921. },
  922. setLocalStorage:function(key,value){
  923. localStorage.setItem(key,value);
  924. return {found:false,'value':value};
  925. },
  926. getLocalStorage:function(key,value){
  927. var keyValue = localStorage.getItem(key)
  928. if(!keyValue || keyValue == "undefined"){
  929. return this.setLocalStorage(key,value);
  930. }else{
  931. return {found:true,'value':keyValue};
  932. }
  933. }
  934. }
  935. Utils.cookie ={
  936. setCookie:function(cname,cvalue) {
  937. //var d = new Date();
  938. //d.setTime(d.getTime() + (exdays*24*60*60*1000));
  939. //var expires = "expires=" + d.toGMTString();
  940. document.cookie = cname+"="+cvalue+"; "
  941. return {found:false,'value':cvalue};
  942. },
  943. getCookie:function(findString) {
  944. var search = findString + "=";
  945. var ca = document.cookie.split(';');
  946. for(var i=0; i<ca.length; i++) {
  947. var c = ca[i];
  948. while (c.charAt(0)==' ') c = c.substring(1);
  949. if (c.indexOf(name) == 0) {
  950. return c.substring(name.length, c.length);
  951. }
  952. }
  953. return "";
  954. },
  955. checkCookie:function(key,value) {
  956. var findString = getCookie(key);
  957. if (findString != "" || keyValue != "undefined") {
  958. return {found:true,'value':((findString == "undefined")?(undefined):(findString))};
  959. } else {
  960. return setCookie(key,value);
  961. }
  962. }
  963. }
  964. Utils.getRandomColor = function getRandomColor(str) {
  965. if(!str)
  966. return "#000";
  967. var hashCode = function(str) {
  968. var hash = 0;
  969. for (var i = 0; i < str.length; i++) {
  970. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  971. }
  972. return hash;
  973. };
  974. var intToRGB = function(i){
  975. var c = (i & 0x00FFFFFF)
  976. .toString(16)
  977. .toUpperCase();
  978. return "00000".substring(0, 6 - c.length) + c;
  979. };
  980. return "#" +intToRGB(hashCode(str));
  981. };
  982. /**
  983. * [genrateSelect2 description]
  984. * @param {[array of object]} listOfselect2 []
  985. * listOfselect2 = [
  986. {
  987. id: "select2 id",
  988. placeholder: "placeholder",
  989. collection: "collection",
  990. dataText: 'display text', //in binding for appling name
  991. collectionHasCode: 'collection dosnt have id then pass what you want to show', // if collection dont have id ,
  992. modelAttr: 'collection attribute name',
  993. mandatory: false,
  994. nonCrud: getAuditSchemaFieldsName // pass function Name with params (suucess,error,etc)
  995. fetch: true,
  996. data:[] // it will not fetch from collection
  997. },
  998. {...}
  999. ]
  1000. collectionFetchLov // listenTo in your view
  1001. * @param {[type]} that [scope of function or view]
  1002. * @return {[type]} [description]
  1003. */
  1004. Utils.genrateSelect2 =function(listOfselect2,that){
  1005. for (var i = 0; i < listOfselect2.length; i++) {
  1006. if (listOfselect2[i]['data'] || listOfselect2[i]['attachSelect']) {
  1007. if(listOfselect2[i]['attachSelect']){
  1008. that.ui[listOfselect2[i]['id']].select2({
  1009. placeholder: listOfselect2[i]['placeholder'],
  1010. width: '100%'
  1011. });
  1012. continue;
  1013. }
  1014. if(that.ui[listOfselect2[i]['id']]){
  1015. that.ui[listOfselect2[i]['id']].select2({
  1016. placeholder: listOfselect2[i]['placeholder'],
  1017. width: '100%',
  1018. data: listOfselect2[i]['data']
  1019. });
  1020. }
  1021. continue;
  1022. } else {
  1023. if(that.ui[listOfselect2[i]['id']]){
  1024. that.ui[listOfselect2[i]['id']].select2({
  1025. placeholder: listOfselect2[i]['placeholder'],
  1026. width: '100%',
  1027. data: []
  1028. });
  1029. that.ui[listOfselect2[i]['id']].select2("disable");
  1030. }else{
  1031. continue;
  1032. }
  1033. }
  1034. if (listOfselect2[i]['fetch']) {
  1035. if (listOfselect2[i].collection && typeof that.listOfselect2[i].collection === "object") {
  1036. that.listOfselect2[i]['collectionFetchLov'] = that.listOfselect2[i].collection
  1037. } else if (listOfselect2[i].collection && typeof that.listOfselect2[i].collection === "string") {
  1038. that.listOfselect2[i]['collectionFetchLov'] = that[listOfselect2[i]['collection']]
  1039. }
  1040. }
  1041. }
  1042. _.each(that.listOfselect2, function(obj, i) {
  1043. if(obj['collectionFetchLov']){
  1044. that.listenTo(obj['collectionFetchLov'], "reset", function(collection, response, options) {
  1045. if (obj['collectionHasCode']) {
  1046. for (var i = 0; i < collection.models.length; i++) {
  1047. $.extend(collection.models[i].attributes, {
  1048. id: collection.models[i].get(obj['collectionHasCode'])
  1049. })
  1050. }
  1051. }
  1052. var allowClearFlag = false;
  1053. if(!obj['mandatory'])allowClearFlag = true
  1054. var data = _.pluck(collection.models, 'attributes');
  1055. that.ui[obj['id']].select2({
  1056. placeholder: obj['placeholder'],
  1057. width: '100%',
  1058. data: {
  1059. results: data,
  1060. text: obj['dataText']
  1061. },
  1062. allowClear: allowClearFlag,
  1063. formatSelection: function(item) {
  1064. return item[obj['dataText']];
  1065. },
  1066. formatResult: function(item) {
  1067. return item[obj['dataText']];
  1068. }
  1069. });
  1070. if(!obj['disabled']){
  1071. that.ui[obj['id']].select2("enable");
  1072. }
  1073. if (that.model && !that.model.isNew()) {
  1074. that.ui[obj['id']].select2('val', that.model.get(obj['modelAttr'])).trigger('change');
  1075. }
  1076. }, that);
  1077. if(obj['nonCrud']){
  1078. obj['nonCrud'](that.ui[obj['id']]);
  1079. }else{
  1080. obj['collectionFetchLov'].fetch({reset:true});
  1081. }
  1082. }
  1083. });
  1084. },
  1085. /* This Method for handling graph unit.
  1086. which seperate number from the string and again append to
  1087. the string by formatting it
  1088. */
  1089. Utils.graphUnitParse = function(unitVal){
  1090. if(! unitVal){
  1091. return "";
  1092. }
  1093. var pattern = /(\d)\s+(?=\d)/g;
  1094. var number = unitVal.match(/\d+/g).map(Number);
  1095. var numString = number.toString().replace(pattern , '$1');
  1096. var str = unitVal.replace(/\d+/g, '').replace(/\+/g,'');
  1097. return numString +" " + Utils.getCamelCase(str) + "(s) gap";
  1098. },
  1099. Utils.getCamelCase = function(str){
  1100. if(!str){
  1101. return "";
  1102. }
  1103. var str = str.toLowerCase();
  1104. return str.replace(/(?:^|\s)\w/g, function(match) {
  1105. return match.toUpperCase()
  1106. });
  1107. };
  1108. return Utils;
  1109. });