/
var
/
www
/
html
/
sugar14
/
cache
/
include
/
javascript
/
Upload File
HOME
(function(app){var bwcRedirectRoutes=['config','create','pipeline','editAllRecurrences','layout','list','record','record_layout','record_layout_action','vcardImport'];app.events.on('router:init',function(){var routes=[{name:"index",route:""},{name:"logout",route:"logout/?clear=:clear"},{name:"logout",route:"logout"},{name:'finishImpersonation',route:'finishImpersonation',callback:function(){app.controller.loadView({module:'Logout',layout:'finish-impersonation',skipFetch:true,create:true,});}},{name:"forgotpassword",route:"forgotpassword",callback:function(){app.controller.loadView({module:"Forgotpassword",layout:"forgotpassword",create:true});}},{name:'changePassword',route:'changePassword',callback:function(){if(!app.controller.context.get('layout')){app.controller.loadView({module:'Users',layout:'record',modelId:app.user.get('id'),});} app.drawer.open({layout:'change-password',context:{fromRouter:true,skipFetch:true}});}},{name:'externalAuthError',route:'externalAuthError',callback:function(){app.controller.loadView({module:'Login',layout:'login',create:true});app.alert.show('needs_login_error',{level:'error',messages:app.lang.getAppString('LBL_LOGIN_INACTIVE_USER'),title:app.lang.get('LBL_INVALID_CREDS_TITLE')});app.router.redirect('/');}},{name:'stsAuthError',route:'stsAuthError',callback:function(){app.controller.loadView({module:'Logout',layout:'logout',create:true});app.alert.show('needs_login_error',{level:'error',messages:app.lang.getAppString('LBL_UNAUTHORIZED'),title:app.lang.get('LBL_UNAUTHORIZED_TITLE')});}},{name:'maintenance',route:'maintenance',callback:function(){app.controller.loadView({module:'Logout',layout:'logout',create:true});app.alert.show('needs_login_error',{level:'error',messages:app.lang.getAppString('EXCEPTION_MAINTENANCE'),title:app.lang.get('LBL_ERROR')});}},{name:'licenseSeats',route:'licenseSeats',callback:function(){app.controller.loadView({module:'Logout',layout:'logout',create:true});app.alert.show('needs_login_error',{level:'error',messages:app.lang.getAppString('ERROR_LICENSE_SEATS_MAXED'),title:app.lang.get('LBL_ERROR')});}},{name:'about',route:'about',callback:function(){app.controller.loadView({layout:'about',module:'Home',skipFetch:true});}},{name:"forecasts",route:"Forecasts",callback:function(){let acls=app.user.getAcls().Forecasts;let hasAccess=(!_.has(acls,'access')||acls.access=='yes');let opportunitiesAcl=app.user.getAcls().Opportunities;let hasOppAccess=(!_.has(opportunitiesAcl,'access')||opportunitiesAcl.access==='yes');let forecastBy=app.metadata.getModule('Forecasts','config');let forecastByAcl=app.user.getAcls()[forecastBy?forecastBy.forecast_by:{}];let hasForecastByAccess=(!_.has(forecastByAcl,'access')||forecastByAcl.access==='yes');let title='';let msg='';if(hasAccess){if(hasOppAccess&&hasForecastByAccess){if(!app.utils.checkForecastConfig()){title='LBL_FORECASTS_MISSING_STAGE_TITLE';msg='LBL_FORECASTS_MISSING_SALES_STAGE_VALUES';}}else{title='LBL_FORECASTS_ACLS_NO_ACCESS_TITLE';msg='LBL_FORECASTS_RECORDS_ACLS_NO_ACCESS_MSG';}}else{title='LBL_FORECASTS_ACLS_NO_ACCESS_TITLE';msg='LBL_FORECASTS_ACLS_NO_ACCESS_MSG';} if(title==''&&msg==''){app.controller.loadView({module:'Forecasts',layout:'records'});}else{app.alert.show('no_access_to_forecasts',{level:'error',title:app.lang.get(title,'Forecasts')+':',messages:[app.lang.get(msg,'Forecasts')]});}}},{name:'profile',route:'profile',callback:function(){const route=app.router.buildRoute('Users',app.user.get('id'));app.router.navigate(route,{trigger:true,replace:true});}},{name:"bwc",route:"bwc/*url",callback:function(url,params){url=url||'';var bwcUrl=_.isEmpty(params)?url:url+'?'+params;app.logger.debug("BWC: "+bwcUrl);var frame=$('#bwc-frame');if(frame.length===1&&app.utils.rmIframeMark('index.php'+frame.get(0).contentWindow.location.search)===bwcUrl){app.drawer.reset();return;} if(bwcUrl==='index.php'){app.router.navigate('#Home',{trigger:true});return;} var options={layout:'bwc',url:bwcUrl};var module=/module=([^&]*)/.exec(bwcUrl);if(!_.isNull(module)&&!_.isEmpty(module[1])){options.module=module[1];if(module[1]==='Import'){module=/import_module=([^&]*)/.exec(bwcUrl);if(!_.isNull(module)&&!_.isEmpty(module[1])){options.module=module[1];}}} app.controller.loadView(options);}},{name:'search',route:'search(/)(:term)',callback:function(term,urlParams){var searchTerm=term?term:'';var params={modules:[],tags:[]};if(urlParams){var paramsArray=urlParams.split('&');_.each(paramsArray,function(paramPair){var keyValueArray=paramPair.split('=');if(keyValueArray.length>1){params[keyValueArray[0]]=keyValueArray[1].split(',');}});} var appContext=app.controller.context;var termHasChanged=appContext.get('searchTerm')!==searchTerm;var modulesHaveChanged=!_.isEqual(appContext.get('module_list'),params.modules);params.tags=_.map(params.tags,function(tag){return decodeURIComponent(tag);});var tagsHaveChanged=!_.isEqual(appContext.get('tagParams'),params.tags);if(termHasChanged){appContext.set('searchTerm',searchTerm);} if(modulesHaveChanged){appContext.set('module_list',params.modules);} if(tagsHaveChanged){appContext.set('tagParams',params.tags);} if(tagsHaveChanged){appContext.trigger('tagsearch:fire:new')}else if(termHasChanged||modulesHaveChanged){appContext.trigger('search:fire:new');} var header=app.additionalComponents['header-nav'];var quicksearch=header&&header.getComponent('quicksearch');if(quicksearch){quicksearch.trigger('route:search');} if(appContext&&appContext.get('search')){return;} app.controller.loadView({layout:'search',searchTerm:searchTerm,module_list:params.modules,tagParams:params.tags,mixed:true});}},{name:'list',route:':module',callback:function(module){if(!app.router._moduleExists(module)){return;} const enabledModulesKey='enabled_modules';let pipelineConfig=app.metadata.getModule('VisualPipeline','config')||{};let enableModules=pipelineConfig[enabledModulesKey]||[];let isAvailablePipeline=_.includes(enableModules,module);let layout='records';if(app.user.lastState.get(module+':pipeline')){if(isAvailablePipeline){layout='pipeline-records';}else{app.user.lastState.set(module+':pipeline',0);app.user.lastState.set(`${module}:list-filterpanel:toggle-view`,'list');}} app.controller.loadView({module:module,layout:layout});}},{name:'create',route:':module/create',callback:function(module){if(!app.router._moduleExists(module)){return;} var prevLayout=app.controller.context.get('layout');if(prevLayout&&prevLayout!=='login'){app.drawer.open({layout:'create',context:{module:module,create:true,fromRouter:true}},function(context,model){if(model&&model.module===app.controller.context.get('module')){app.controller.context.reloadData();}});return;} app.router.record(module,'create');}},{name:"vcardImport",route:":module/vcard-import",callback:function(module){if(!app.router._moduleExists(module)){return;} app.controller.loadView({module:module,layout:"records"});app.drawer.open({layout:'vcard-import'},_.bind(function(){var route=app.router.buildRoute(module);app.router.navigate(route,{replace:true});},this));}},{name:'editAllRecurrences',route:':module/:id/edit/all_recurrences',callback:function(module,id){if(!app.router._moduleExists(module)){return;} app.controller.loadView({module:module,layout:'record',action:'edit',modelId:id,all_recurrences:true});}},{name:"layout",route:":module/layout/:view"},{name:'config',route:':module/config',callback:function(module){if(!app.router._moduleExists(module)){return;} var prevLayout=app.controller.context.get('layout');if(prevLayout&&prevLayout!=='login'){app.drawer.open({layout:'config-drawer',context:{module:module,fromRouter:true}});return;} app.controller.loadView({layout:'config-drawer',module:module});}},{name:'pipelineView',route:':module/pipeline',callback:function(module){if(!app.router._moduleExists(module)){return;} app.router.redirect('#'+module);}},{name:'record',route:':module/:id(/:action)'},{name:'recordLayoutAction',route:':module/:id/layout/:layout(/:action)',callback:function(module,id,layout,action){if(!app.router._moduleExists(module)){return;} app.router.record(module,id,action,layout);}}];app.router.addRoutes(routes);});app.events.on('app:init',function(){app.api.setRefreshTokenSuccessCallback(function(callback){callback();app.events.trigger("api:refreshtoken:success");});});app.routing.before('route',function(options){var hasAccess=app.router.hasAccessToModule(options)!==false,isBwcRedirect=app.router.bwcRedirect(options)!==false;return hasAccess&&isBwcRedirect;});var titles={'records':'TPL_BROWSER_SUGAR7_RECORDS_TITLE','record':'TPL_BROWSER_SUGAR7_RECORD_TITLE','about':'TPL_BROWSER_SUGAR7_ABOUT_TITLE','activities':'TPL_BROWSER_SUGAR7_RECORD_TITLE','pipeline-records':'TPL_BROWSER_SUGAR7_RECORDS_TITLE'};var getTitle=function(model){var context=app.controller.context,module=context.get('module'),template=Handlebars.compile(app.lang.get(titles[context.get('layout')],module)||''),moduleName=app.lang.getModuleName(module,{plural:true}),title;var titleInfo=_.extend({module:moduleName,appId:app.config.systemName||app.config.appId},model?model.attributes:{});if(titleInfo.name){if(module==='Dashboards'&&titleInfo.dashboard_module){titleInfo.name=app.lang.get(titleInfo.name,titleInfo.dashboard_module);}else{titleInfo.name=app.lang.get(titleInfo.name,module);}} title=template(titleInfo);return $('<span/>').html(title).text();};var setTitle=function(model){var title=getTitle(model);document.title=title||document.title;};var prevModel;app.events.on("app:view:change",function(){var context=app.controller.context,module=context.get("module"),metadata=app.metadata.getModule(module),title;if(prevModel){prevModel.off("change",setTitle);} if(_.isEmpty(metadata)||metadata.isBwcEnabled){title=$('#bwc-frame').get(0)?$('#bwc-frame').get(0).contentWindow.document.title:getTitle();}else{var currModel=context.get('model');if(!_.isEmpty(currModel)){title=getTitle(currModel);currModel.on("change",setTitle,this);prevModel=currModel;}else{title=getTitle();}} document.title=title||document.title;},this);var refreshExternalLogin=function(){var config=app.metadata.getConfig();app.api.setExternalLogin(config&&config['externalLogin']);if(config&&(_.isNull(config['externalLoginSameWindow'])||config['externalLoginSameWindow']===false)){app.api.setExternalLoginUICallback(window.open);}};app.events.on("app:sync:complete",refreshExternalLogin,this);app.events.on("app:init",refreshExternalLogin,this);app.Router=app.Router.extend({bwcRedirect:function(options){if(options.route&&!_.contains(bwcRedirectRoutes,options.route)){return true;} if(_.isArray(options.args)&&options.args[0]){var module=options.args[0];var id=options.args[1];var action=id?'DetailView':'index';var meta=app.metadata.getModule(module);if(meta&&meta.isBwcEnabled){var sidecarAction=options.args[2]||options.route,bwcAction=app.bwc.getAction(sidecarAction);if(bwcAction!==sidecarAction){action=bwcAction;} var redirect='bwc/index.php?module='+module+'&action='+action;if(id){redirect+='&record='+id;} _.defer(function(){app.router.navigate(redirect,{trigger:true,replace:true});});return false;}} return true;},hasAccessToModule:function(options){options=options||{};var checkAccessRoutes={'record':'view','create':'create','vcardImport':'create'},route=options.route||'',args=options.args||[],module=args[0],accessCheck=checkAccessRoutes[route];if(accessCheck&&!app.acl.hasAccess(accessCheck,module)){_.defer(function(){app.controller.loadView({layout:'access-denied'});});return false;} var showWizard=false;if(app.user&&app.user.has('show_wizard')){showWizard=app.user.get('show_wizard');if(showWizard){var system_config=app.metadata.getConfig();if(system_config.system_status&&system_config.system_status.level&&system_config.system_status.level==='admin_only'){showWizard=false;} if(app.cache&&app.cache.has('ImpersonationFor')){showWizard=false;}}} if(showWizard){var callbacks={complete:function(){var module=app.utils.getWindowLocationParameterByName('module',window.location.search),action=app.utils.getWindowLocationParameterByName('action',window.location.search);if(_.isString(module)&&_.isString(action)&&module.toLowerCase()==='users'&&action.toLowerCase()==='authenticate'){window.location=window.location.pathname;}else{window.location.reload();}}};app.controller.loadView({layout:'first-login-wizard',module:'Users',modelId:app.user.get('id'),callbacks:callbacks,wizardName:app.user.get('type')});app.additionalComponents['header-nav'].hide();return false;} if(route&&route!=='logout'&&app.user&&app.user.get('is_password_expired')){app.controller.loadView({layout:'password-expired',module:'Users',callbacks:{complete:function(){window.location.reload();}},modelId:app.user.get('id')});app.additionalComponents['header-nav'].hide();return false;}}});app.augment("progress",_.extend({init:function(){NProgress.configure({template:'<div class="loading gate">'+' <div class="progress progress-danger">'+' <div role="bar" class="bar"></div>'+' </div>'+'</div>'});NProgress.start();NProgress.set(0.25);},hide:function(){$("#nprogress").hide();}},NProgress),false);app.events.on("app:logout:success",function(data){if(app.config&&app.config.externalLogin&&data&&data.url){if(typeof data.url=='string'){document.location.href=data.url;}else if(typeof data.url=='object'){var formHTML='<form id="externalLogoutForm" method="POST" target="logoutframe" action="'+ data.url.url+'">';_.each(data.url.params,function(value,key,list){formHTML+='<input type="hidden" name="'+_.escape(key)+'" value="'+_.escape(value)+'" />';});formHTML+='</form>'+'<script type="text/javascript">document.getElementById("externalLogoutForm").submit();</script>';$('#sugarcrm').append(formHTML);}}});app.events.on('app:logout',function(){var filters=app.data.getCollectionClasses().Filters;if(filters){filters.prototype.resetFiltersCacheAndRequests();}});app.user.on('change:show_wizard',function(user,show_wizard){if(show_wizard){app.shortcuts.disable();}else{app.shortcuts.enable();}});})(SUGAR.App); /* End of File include/javascript/sugar7.js */ (function(app){var animationSpeed=500;var scrollOffset=25;var scrollViewReduction=75;app.augment('tutorial',{instance:null,hasTutorial:function(layout,module){module=module||app.controller.context.get('module');layout=layout||app.controller.context.get('layout');var meta=app.metadata.getModule(module);var defaultMeta=app.metadata.getView('','tutorial');if(defaultMeta){this.data=defaultMeta;} if(meta&&meta.views&&meta.views.tutorial&&meta.views.tutorial.meta&&meta.views.tutorial.meta[layout]){return true;}else if(this.data&&this.data[layout]){return true;}else{return false;}},show:function(name,params){if(app.tutorial.data){this.doTutorial(name,params);}else if(app.metadata.getView('','tutorial')){app.tutorial.data=app.metadata.getView('','tutorial');this.doTutorial(name,params);}},doTutorial:function(name,params){var tutorialData=app.tutorial.data[name];var prefKey=name;if(params&¶ms.module){var meta=app.metadata.getModule(params.module);if(meta.views&&meta.views.tutorial&&meta.views.tutorial.meta&&meta.views.tutorial.meta[name]){tutorialData=meta.views.tutorial.meta[name];prefKey=name+params.module;}} var prefs=this.getPrefs();if(tutorialData&&(!prefs.skipVersion[prefKey]||prefs.skipVersion[prefKey]<tutorialData.version)&&(!prefs.viewedVersion[prefKey]||prefs.viewedVersion[prefKey]<tutorialData.version)){params=_.extend(tutorialData,{type:'Tutorial'});app.tutorial.instance=app.view.createView(params);app.tutorial.instance.show();prefs.viewedVersion[prefKey]=tutorialData.version;app.cache.set('tutorialPrefs',prefs);}},getPrefs:function(){var prefs=app.cache.get('tutorialPrefs')||{};prefs.viewedVersion=prefs.viewedVersion||{};prefs.skipVersion=prefs.skipVersion||{};return prefs;},resetPrefs:function(prefs){prefs=prefs||{};prefs.viewedVersion={};prefs.skipVersion={};app.cache.set('tutorialPrefs',prefs);},skipTutorial:function(){var prefs=this.getPrefs();_.each(app.tutorial.data,function(data,name){prefs.skipVersion[name]=app.tutorial.data[name].version;});app.user.setPreference('tutorialPrefs',prefs);}});app.view.TutorialView=app.view.View.extend({events:{'click .btn.disabled':function(e){return false;},'click .back-btn:not(.disabled)':'back','click .next-btn:not(.disabled)':'next','click .done-btn':'hide','swipeLeft':'onSwipeLeft'},_duringAnimate:false,initialize:function(options){options=_.extend({},options||{});this.index=0;this.setIntro(options.intro);this.setContent(options.content);this.setScroll(options.scroll);app.events.on('app:login app:logout',this.hide,this);},setContent:function(content){this.content=content;},setIntro:function(intro){this.intro=intro;},setScroll:function(scroll){this.scroll=scroll;},reset:function(){this.index=0;},onSwipeLeft:function(e){app.tutorial.skipTutorial();this.hide(e);},show:function(options){options=_.extend({},options||{});if(options.content){this.setContent(options.content);} if(options.intro){this.setIntro(options.intro);} if(options.scroll){this.setScroll(options.scroll);} if(options.reset){this.reset();} this.render();if(this.intro&&!this.introShown){this.index=-1;this.introShown=true;this.showMessageOnly(this.intro);}else{this.highlightItem(this.index);}},hide:function(event){if(event){event.preventDefault();} this.dispose();},back:function(event){if(event){event.preventDefault();} if(this._duringAnimate){return;} this.highlightItem(this.index-1);},next:function(event){if(event){event.preventDefault();} if(this._duringAnimate){return;} this.highlightItem(this.index+1);},highlightItem:function(index){var self=this;if(index<0){return;} if(index>=this.content.length){this.hide();return;} var content=this.content[index];if(!content.name){this.showMessageOnly(content.text);}else{var item=$(content.name);var direction=this.index>index?-1:1;if((item.length===0||item.css('display')==='none')||item.parents('.hide').length>0){return this.highlightItem(index+direction);} var highlightCallback=function(){if(!this.highlight){this.highlight=$('<div/>');this.highlight.attr('id','highlight');this.highlightText=$('<div/>');this.highlightText.attr('id','highlight-text');this.highlight.html(this.highlightText);$('#tutorial-content').html(this.highlight);} this.highlightText.hide();this.hideGlow();this._duringAnimate=true;this.highlight.animate({'top':item.offset().top+(content.vertAdj||0),'left':item.offset().left+(content.horizAdj||0),'width':content.full?item.offset().width:'','height':content.full?item.offset().height:''},animationSpeed,'linear',function(){self._duringAnimate=false;if(content.glow===undefined||content.glow!==false){self.showGlow();} self.showHighlightText(content.text);});};highlightCallback=_.bind(highlightCallback,this);this.scrollToEl(item,highlightCallback);} if(index<=0){this.$el.find('.back-btn').addClass('disabled');}else{this.$el.find('.back-btn').removeClass('disabled');} if(index>=(this.content.length-1)){this.$el.find('.next-btn').addClass('disabled');}else{this.$el.find('.next-btn').removeClass('disabled');} this.index=index;},showGlow:function(){this.$el.find('#mask').css('background-image','-webkit-radial-gradient('+(this.highlight.offset().left+(this.highlight.width()/ 2))+'px '+ (this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2))+'px , '+ this.highlight.width()+'px '+this.highlight.height()+'px, transparent, black '+Math.max(this.highlight.width(),this.highlight.height())+'px)');this.$el.find('#mask').css('background','radial-gradient(circle closest-side at '+(this.highlight.offset().left+(this.highlight.width()/ 2))+'px '+ (this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2))+'px , '+' transparent 0%, black '+Math.max(this.highlight.width(),this.highlight.height())+'px)');this.$el.find('#mask').css('background-color','transparent');},hideGlow:function(){this.$el.find('#mask').css('background-color','');this.$el.find('#mask').css('background-image','');},showHighlightText:function(message){var top;var highlightBorderOffset;this.highlightText.html(app.lang.get(message,app.controller.context.get('module')));this.highlightText.show();if(this.highlight.offset().left-this.getTotalWidth(this.highlightText)>0&&this.findIntersectors([this.highlight.offset().left-this.getTotalWidth(this.highlightText),this.highlight.offset().left],[this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2),this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2)+this.getTotalHeight(this.highlightText)],'.btn-group').length===0){highlightBorderOffset=parseInt(this.highlight.css('border-left-width'));this.highlightText.css('left',0-(this.getTotalWidth(this.highlightText)+highlightBorderOffset));top=(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2);this.highlightText.css('top',top>=0?top:0);this.highlightText.css('text-align','right');}else if(this.highlight.offset().left+this.getTotalWidth(this.highlight)+this.getTotalWidth(this.highlightText)<$(window).width()&&this.findIntersectors([this.highlight.offset().left+this.getTotalWidth(this.highlight),this.highlight.offset().left+this.getTotalWidth(this.highlight)+this.getTotalWidth(this.highlightText)],[this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2),this.highlight.offset().top+(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2)+this.getTotalHeight(this.highlightText)],'.btn-group').length===0){highlightBorderOffset=parseInt(this.highlight.css('border-right-width'));this.highlightText.css('left',this.getTotalWidth(this.highlight)+highlightBorderOffset);top=(this.getTotalHeight(this.highlight)/ 2)-(this.getTotalHeight(this.highlightText)/ 2);this.highlightText.css('top',top>=0?top:0);this.highlightText.css('text-align','left');}else{var newLeftVal=(this.getTotalWidth(this.highlight)/ 2)-(this.getTotalWidth(this.highlightText)/ 2);var leftEdge=this.highlight.offset().left+newLeftVal;newLeftVal=leftEdge<0?0-this.highlight.offset().left:newLeftVal;var rightEdge=this.highlight.offset().left+newLeftVal+this.getTotalWidth(this.highlightText);newLeftVal=rightEdge>$(window).width()?newLeftVal-(rightEdge-$(window).width()):newLeftVal;var newTopVal;if(this.highlight.offset().top+this.getTotalHeight(this.highlight)+this.getTotalHeight(this.highlightText)<$(window).height()&&this.findIntersectors([this.highlight.offset().left+newLeftVal,this.highlight.offset().left+newLeftVal+this.getTotalWidth(this.highlightText)],[this.highlight.offset().top+this.getTotalHeight(this.highlight),this.highlight.offset().top+this.getTotalHeight(this.highlight)+this.getTotalHeight(this.highlightText)],'.btn-group').length===0){newTopVal=this.getTotalHeight(this.highlight);}else{newTopVal=-5-this.getTotalHeight(this.highlightText);} this.highlightText.css('left',newLeftVal);this.highlightText.css('top',newTopVal);this.highlightText.css('text-align','center');}},findIntersectors:function(tX,tY,intersectorsSelector){var intersectors=[];var self=this;this.$el.find(intersectorsSelector).each(function(){var $this=$(this);var thisPos=$this.offset();var iX=[thisPos.left,thisPos.left+self.getTotalWidth($this)];var iY=[thisPos.top,thisPos.top+self.getTotalHeight($this)];if(tX[0]<iX[1]&&tX[1]>iX[0]&&tY[0]<iY[1]&&tY[1]>iY[0]){intersectors.push($this);}});return intersectors;},showMessageOnly:function(message){$('#tutorial-content').html("<div class='text-container'><div class='text'>"+ app.lang.get(message,app.controller.context.get('module'))+'</div></div>');this.highlight=null;this.hideGlow();},getTotalWidth:function(el){var totalWidth=el.width();totalWidth+=parseInt(el.css('padding-left'),10)+parseInt(el.css('padding-right'),10);totalWidth+=parseInt(el.css('margin-left'),10)+parseInt(el.css('margin-right'),10);return totalWidth;},getTotalHeight:function(el){var totalHeight=el.height();totalHeight+=parseInt(el.css('padding-top'),10)+parseInt(el.css('padding-bottom'),10);totalHeight+=parseInt(el.css('margin-top'),10)+parseInt(el.css('margin-bottom'),10);return totalHeight;},scrollToEl:function($targetEl,callback){var viewportHeight=$(window).height();var elTop=$targetEl.offset().top;var elHeight=$targetEl.height();var headerHeight=($('.navbar').height()+3)||0;var footerHeight=$('footer').height()||0;var buffer=125;var direction;if($.contains('.navbar',$targetEl)){headerHeight=0;} if($.contains('footer',$targetEl)){footerHeight=0;} if(elTop+elHeight>window.pageYOffset+viewportHeight-footerHeight){direction='down';buffer*=-1;}else if(elTop+elHeight<window.pageYOffset+elHeight+headerHeight){direction='up';}else{direction='none';if(callback&&_.isFunction(callback)){callback();}} if(direction!=='none'){$('#content, .main-pane, .side-pane').animate({scrollTop:elTop+buffer},{duration:'fast',complete:function(){if(callback&&_.isFunction(callback)){callback();}}});}},render:function(){var tutorial=app.template.get('tutorial');$('body').append(tutorial());app.$contentEl.attr('aria-hidden',true);this.$el=$('#tutorial');this.delegateEvents();this.$el.show();return this;},remove:function(){app.$contentEl.removeAttr('aria-hidden');if(app.tutorial.instance===this){app.tutorial.instance=null;} if(this.highlight){this.highlight.stop(true,true);} delete this.highlight;delete this.highlightText;Backbone.View.prototype.remove.call(this);}});})(SUGAR.App); /* End of File include/javascript/sugar7/tutorial.js */ (function(app){var Bwc={login:function(redirectUrl,callback){var url=app.api.buildURL('oauth2','bwc/login');return app.api.call('create',url,{},{success:function(data){if(data&&data.name){app.cache.set('SessionName',data.name);} if(callback){callback();} if(redirectUrl){if(redirectUrl.indexOf('&bwcRedirect=1')>-1){app.error.handleInvalidClientError();}else{app.router.navigate('#bwc/'+redirectUrl+'&bwcRedirect=1',{trigger:true});}}}});},logout:function(callback){let url=app.api.buildURL('oauth2','bwc/logout');return app.api.call('create',url,{},{success:function(data){if(callback){callback(data);}}});},getAction:function(action){var bwcActions={'create':'EditView','edit':'EditView','detail':'DetailView'};return bwcActions[action]||action;},buildRoute:function(module,id,action,params){var href='bwc/index.php?',params=_.extend({},{module:module},params);if(!action&&!id||action==='DetailView'&&!id){params.action='index';}else{if(action){params.action=action;}else{params.action='DetailView';} if(id){params.record=id;}} return href+$.param(params);},_createRelatedRecordUrlParams:function(parentModel,link){var params={parent_type:parentModel.module,parent_name:parentModel.get('name')||parentModel.get('full_name')||app.utils.formatNameLocale(parentModel.attributes),parent_id:parentModel.get("id"),return_module:parentModel.module,return_id:parentModel.get("id"),return_name:parentModel.get('name')||parentModel.get('full_name')||app.utils.formatNameLocale(parentModel.attributes)};var linkField=_.find(parentModel.fields,function(field){return(field.type=='link'&&field.name==link)});if(linkField){params['return_relationship']=linkField.relationship;} params=this._handleRelatedRecordSpecialCases(params,parentModel,link);var fields=app.data.getRelateFields(parentModel.module,link);_.each(fields,function(field){params[field.name]=parentModel.get(field.rname)||app.utils.formatNameLocale(parentModel.attributes);params[field.id_name]=parentModel.get("id");if(field.populate_list){_.each(field.populate_list,function(target,source){source=_.isNumber(source)?target:source;if(!_.isUndefined(parentModel.get(source))){params[target]=parentModel.get(source);}},this);}});return params;},_handleRelatedRecordSpecialCases:function(params,parentModel,link){var syncedAttributes=parentModel.getSynced();if(parentModel.module=='Contacts'&&parentModel.has('account_id')&&(link=='meetings'||link=='calls')){params=_.extend(params,{parent_type:'Accounts',parent_id:syncedAttributes.account_id||parentModel.get('account_id'),account_id:syncedAttributes.account_id||parentModel.get('account_id'),account_name:syncedAttributes.account_name||parentModel.get('account_name'),parent_name:syncedAttributes.account_name||parentModel.get('account_name'),contact_id:syncedAttributes.id||parentModel.get('id'),contact_name:syncedAttributes.full_name||parentModel.get('full_name')});} if(link=='quotes'||link=='contracts'){if(parentModel.has('account_id')){params=_.extend(params,{account_id:syncedAttributes.account_id||parentModel.get('account_id'),account_name:syncedAttributes.account_name||parentModel.get('account_name')});} if(parentModel.module==='Contacts'){params=_.extend(params,{contact_id:parentModel.get('id')});}else if(parentModel.has('contact_id')){params=_.extend(params,{contact_id:syncedAttributes.contact_id||parentModel.get('contact_id')});}} return params;},createRelatedRecord:function(module,parentModel,link,id){var params=this._createRelatedRecordUrlParams(parentModel,link);var route=app.bwc.buildRoute(module,id||null,"EditView",params);app.router.navigate("#"+route,{trigger:true});},shareRecord:function(module,id,name){var containerView=app.view.createView({});var shareField=app.view.createField({def:{type:'shareaction'},module:module,model:app.data.createBean(module,{id:id,name:name}),view:containerView});if(shareField.useSugarEmailClient()){shareField.shareWithSugarEmailClient();}else{this._launchExternalEmail(shareField.getShareMailtoUrl());} containerView.dispose();},_launchExternalEmail:function(mailto){var tempMailTo=$('<a href="'+mailto+'"></a>').appendTo('body');tempMailTo.get(0).click();tempMailTo.remove();},revertAttributes:function(){var view=app.controller.layout.getComponent('bwc');if(!view){return;} view.revertBwcModel();}};app.augment('bwc',_.extend(Bwc,Backbone.Events),false);})(SUGAR.App); /* End of File include/javascript/sugar7/bwc.js */ (function(app){app.events.on("app:init",function(){var tooltipTemplate=Handlebars.compile('<div class="tooltip">'+'<div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>');var $tooltipTemplate=$(tooltipTemplate());function setParentAttributes(model,parent){var fields=app.metadata.getModule(model.module,'fields');var modules;var name;modules=_.chain(app.lang.getAppListStrings(fields.parent_type.options)).keys().filter(function(module){return app.acl.hasAccess('list',module);}).value();if(!_.contains(modules,parent.module)){return;} function setAttributes(parent){model.set('parent',_.extend({type:parent.module},parent.toJSON()));model.set('parent_type',parent.module);model.set('parent_id',parent.get('id'));model.set('parent_name',parent.get('name'));} if(_.isEmpty(parent.get('id'))){return;} if(_.isEmpty(parent.get('name'))&&!app.utils.isNameErased(parent)){name=app.utils.getRecordName(parent);if(!_.isEmpty(name)){parent.set('name',name);setAttributes(parent);}else{parent.fetch({showAlerts:false,success:setAttributes,fields:['name']});}}else{setAttributes(parent);}} function prepopulateEmailWithCase(email,aCase){var config;var keyMacro='%1';var caseMacro;var subject;var contacts;if(aCase.module!=='Cases'){return;} config=app.metadata.getConfig();caseMacro=config.inboundEmailCaseSubjectMacro;subject=caseMacro+' '+aCase.get('name');subject=subject.replace(keyMacro,aCase.get('case_number'));email.set('name',subject);if(email.get('to_collection').length===0){contacts=aCase.getRelatedCollection('contacts');contacts.fetch({relate:true,success:function(data){var records=data.map(function(record){var parentName=app.utils.getRecordName(record);return app.data.createBean('EmailParticipants',{_link:'to',parent:_.extend({type:record.module},app.utils.deepCopy(record.attributes)),parent_type:record.module,parent_id:record.get('id'),parent_name:parentName});});email.get('to_collection').add(records);},fields:['id','name','email']});}} function prepopulateEmailForCreate(email,data){var fields=app.metadata.getModule('Emails','fields');var fieldNames=_.keys(fields);var fieldMap={attachments:'attachments_collection',from:'from_collection',to:'to_collection',cc:'cc_collection',bcc:'bcc_collection'};var nonFieldData={};_.each(data,function(value,fieldName){var fieldDefs;fieldName=fieldMap[fieldName]||fieldName;fieldDefs=fields[fieldName]||{};if(fieldName==='related'){if(data.skip_prepopulate_with_case!==true){prepopulateEmailWithCase(email,value);} setParentAttributes(email,value);}else if(fieldDefs.type==='collection'){if(value instanceof app.BeanCollection){value=value.models;} email.get(fieldName).add(value);}else if(_.contains(fieldNames,fieldName)){email.set(fieldName,value);}else{nonFieldData[fieldName]=value;}});if(data.outboundEmails){app.utils.removeOutboundEmails(email.attributes.to_collection,email.attributes.cc_collection,email.attributes.bcc_collection,data.outboundEmails);} return nonFieldData;} app.utils=_.extend(app.utils,{convertCompToDashletView:function(comp){var dashletConfigs=comp.view.dashletConfig;dashletConfigs=_.isArray(dashletConfigs)?dashletConfigs:[dashletConfigs];return _.map(dashletConfigs,function(dashletConfig){var metadata={component:'external-app-dashlet',config:{customConfig:true,src:comp.view.src,dashletConfig:comp.view.dashletConfig,},customDashletMeta:comp,description:comp.view.description,label:comp.view.name,dashletType:dashletConfig.type,type:'external-app-dashlet'};return{description:comp.view.description,metadata:metadata,title:comp.view.name,type:'external-app-dashlet'};});},removeOutboundEmails:function(to,cc,bcc,outboundEmails){const toEmails=_.isObject(to)?to.models.map(to=>to.attributes.email_address):[];const ccEmails=_.isObject(cc)?cc.models.map(cc=>cc.attributes.email_address):[];const bccEmails=_.isObject(bcc)?bcc.models.map(bcc=>bcc.attributes.email_address):[];outboundEmails.forEach((emailAddress)=>{if(toEmails.indexOf(emailAddress)!==-1){to.models.splice(toEmails.indexOf(emailAddress),1);} if(ccEmails.indexOf(emailAddress)!==-1){cc.models.splice(ccEmails.indexOf(emailAddress),1);} if(bccEmails.indexOf(emailAddress)!==-1){bcc.models.splice(bccEmails.indexOf(emailAddress),1);}});},getMfeDashletViews:function(context){var isMultiLine=context&&context.parent&&context.parent.get('layout')==='multi-line';var parentModule=isMultiLine?context.parent.get('module'):app.controller.context.get('module');var parentView=isMultiLine?'record':app.controller.context.get('layout');var dashletView=parentView==='records'?'list-dashlet':'record-dashlet';var dashletMeta=app.metadata.getLayout(parentModule,dashletView);if(!dashletMeta){return[];} return _(dashletMeta.components).chain().map(function(comp){try{return app.utils.convertCompToDashletView(comp);}catch(err){return[];}}).flatten().value();},hideForecastCommitStageField:function(panels){var config=app.metadata.getModule('Forecasts','config'),isSetup=(config&&config.is_setup);if(!isSetup){_.each(panels,function(panel){_.every(panel.fields,function(field,index){if(field.name=='commit_stage'){panel.fields[index]={'name':'spacer','label':field.label,'span':6,'readonly':true};return false;} return true;},this);},this);}},createHistoryLog:function(oldestModel,newestModel,isRepWorksheet){var labels=[];if(_.isEmpty(oldestModel)){oldestModel=new Backbone.Model({best_case:0,likely_case:0,worst_case:0,date_entered:''});labels.push('LBL_COMMITTED_HISTORY_SETUP_FORECAST');}else{labels.push('LBL_COMMITTED_HISTORY_UPDATED_FORECAST');} var fields=['worst','likely','best'],final=[],num_shown=0,config=app.metadata.getModule('Forecasts','config'),aclModule=(isRepWorksheet)?config.forecast_by:newestModel.module;_.each(fields,function(field){var fieldName=field+'_case';if(config['show_worksheet_'+field]&&app.acl.hasAccess('view',aclModule,null,fieldName)){var diff=this.getDifference(oldestModel,newestModel,fieldName);num_shown++;if(diff!=0){var direction=this.getDirection(diff);final.push(this.gatherLangArgsByParams(direction,this.getArrowDirectionSpan(direction),diff,newestModel,fieldName));labels.push('LBL_COMMITTED_HISTORY_'+field.toUpperCase()+'_CHANGED');}else{final.push([]);labels.push('LBL_COMMITTED_HISTORY_'+field.toUpperCase()+'_SAME');}}},this);var lang_string_key='LBL_COMMITTED_HISTORY_'+num_shown+'_SHOWN',hb=Handlebars.compile('{{{str key module args}}}');final=this.parseArgsAndLabels(final,labels);var text=hb({'key':lang_string_key,'module':'Forecasts','args':final});return{'text':new Handlebars.SafeString(text),'text2':app.date(newestModel.get('date_modified')).formatUser(false,app.user)};},gatherLangArgsByParams:function(dir,arrow,diff,model,attrStr){return{'direction':new Handlebars.SafeString(app.lang.get(dir,'Forecasts')+arrow),'from':app.currency.formatAmountLocale(Math.abs(diff)),'to':app.currency.formatAmountLocale(model.get(attrStr))};},getArrowDirectionSpan:function(directionClass){return directionClass=='LBL_UP'?' <i class="sicon sicon-arrow-up font-green"></i>':directionClass=='LBL_DOWN'?' <i class="sicon sicon-arrow-down font-red"></i>':'';},getForecastType:function(isManager,showOpps){return(!showOpps&&isManager)?'Rollup':'Direct';},parseArgsAndLabels:function(argsArray,labels){var retArgs={},argsKeys=['first','second','third'],hb=Handlebars.compile('{{{str key module args}}}');if((argsArray.length+1)!=labels.length){var msg='ForecastsUtils.parseArgsAndLabels() :: '+'argsArray and labels params are not the same length';app.logger.error(msg);return null;} retArgs.intro=hb({'key':_.first(labels),'module':'Forecasts','args':[]});labels=_.last(labels,labels.length-1);_.each(labels,function(label,index){retArgs[argsKeys[index]]=hb({'key':label,'module':'Forecasts','args':argsArray[index]});});return retArgs;},getDifference:function(oldModel,newModel,attr){return(app.math.isDifferentWithPrecision(newModel.get(attr),oldModel.get(attr)))?app.math.getDifference(newModel.get(attr),oldModel.get(attr)):0;},getDirection:function(difference){return difference>0?'LBL_UP':(difference<0?'LBL_DOWN':'');},getSubpanelList:function(module){var list={},subpanels=app.metadata.getModule(module),comps;if(subpanels&&subpanels.layouts){subpanels=subpanels.layouts.subpanels;if(subpanels&&subpanels.meta){if(subpanels.meta.dynamic){comps=this.getDynamicSubpanelList(module);if(comps&&comps.meta){comps=comps.meta.components||[];}}else{comps=subpanels.meta.components||[];}}} if(comps){_.each(comps,function(comp){if(comp.context&&comp.context.link){list[comp.label]=comp.context.link;}else{app.logger.warning("Subpanel's subpanels.meta.components " +"has component with no context or context.link");}});} return list;},getDynamicSubpanelList:function(module){var dSubpanels=this.getDynamicSubpanelMetadata(module);return{meta:dSubpanels};},getDynamicSubpanelMetadata:function(module){var rels=app.metadata.get().relationships,fields=app.metadata.getModule(module).fields,modules=app.metadata.getModules(),comps=[],self=this;_.each(fields,function(fDefs,fName){var relModule,relDefName,spLabel;if(fDefs.type&&fDefs.type==='link'&&fDefs.relationship){relDefName=fDefs.relationship;if(self.hasDynamicSubpanelDef(rels,relDefName,module)){relModule=rels[relDefName].lhs_module;if(modules[relModule]){var layoutName='subpanel';if(modules[relModule].additionalProperties&&modules[relModule].additionalProperties.dynamic_subpanel_name){layoutName=modules[relModule].additionalProperties.dynamic_subpanel_name;} comps.push({context:{link:fDefs.name},label:self.getDynamicSubpanelLabel(module,relModule),layout:layoutName});}}}});return{components:comps};},getDynamicSubpanelLabel:function(module,relModule){var lIndex='LBL_'+relModule.toUpperCase()+'_SUBPANEL_TITLE';var stackDef=[{key:'LBL_DEFAULT_SUBPANEL_TITLE',mod:relModule},{key:lIndex,mod:module},{key:lIndex,mod:relModule},{key:'LBL_MODULE_NAME',mod:relModule}];var label;for(var i in stackDef){if(label=app.lang.getModString(stackDef[i].key,stackDef[i].mod)){return label;}} return relModule;},hasDynamicSubpanelDef:function(rels,relDefName,module){return rels[relDefName]&&rels[relDefName].dynamic_subpanel&&rels[relDefName].lhs_module&&rels[relDefName].rhs_module&&rels[relDefName].rhs_module===module;},isRequiredLink:function(module,link){var relatedFields=app.data.getRelateFields(module,link),requiredField=_.some(relatedFields,function(field){return field.required===true;},this);return requiredField;},_tableColumnsConfigKeyMapManager:{'likely_case':'show_worksheet_likely','likely_case_adjusted':'show_worksheet_likely','best_case':'show_worksheet_best','best_case_adjusted':'show_worksheet_best','worst_case':'show_worksheet_worst','worst_case_adjusted':'show_worksheet_worst'},_tableColumnsConfigKeyMapRep:{'likely_case':'show_worksheet_likely','best_case':'show_worksheet_best','worst_case':'show_worksheet_worst'},getColumnVisFromKeyMap:function(key,viewName){var moduleMap={'forecastsWorksheet':'rep','forecastsWorksheetTotals':'rep','forecastsWorksheetManager':'mgr','forecastsWorksheetManagerTotals':'mgr'},whichKeyMap,keyMap,returnValue;whichKeyMap=moduleMap[viewName];keyMap=(whichKeyMap==='rep')?this._tableColumnsConfigKeyMapRep:this._tableColumnsConfigKeyMapManager;returnValue=app.metadata.getModule('Forecasts','config')[keyMap[key]];if(!_.isUndefined(returnValue)){returnValue=returnValue==1}else{returnValue=true;} return returnValue;},getSelectedUsersReportees:function(selectedUser,context){if(selectedUser.is_manager){if(_.isUndefined(selectedUser.reportees)){selectedUser.reportees=[];} var url=app.api.buildURL('Users','filter'),post_args={"filter":[{'reports_to_id':selectedUser.id,'status':'Active'}],'fields':'full_name','max_num':1000},options={};options.success=_.bind(function(resp,status,xhr){_.each(resp.records,function(user){selectedUser.reportees.push({id:user.id,name:user.full_name});});this.set({selectedUser:selectedUser,forecastType:app.utils.getForecastType(selectedUser.is_manager,selectedUser.showOpps)});},context);app.api.call("create",url,post_args,options);}else{context.set({selectedUser:selectedUser,forecastType:app.utils.getForecastType(selectedUser.is_manager,selectedUser.showOpps)});}},checkForecastConfig:function(){var forecastConfigOK=true,cfg=app.metadata.getModule('Forecasts','config')||{},salesWonVals=cfg.sales_stage_won,salesLostVals=cfg.sales_stage_lost,salesWonLostVals=cfg.sales_stage_won.concat(cfg.sales_stage_lost),domVals=app.lang.getAppListStrings('sales_stage_dom');if(salesWonVals.length==0||salesLostVals.length==0||_.isEmpty(domVals)){forecastConfigOK=false;}else{forecastConfigOK=_.every(salesWonLostVals,function(val){return(val!=''&&_.has(domVals,val));},this);} return forecastConfigOK;},isTouchDevice:function(){return Modernizr.touch;},customBuildRoute:function(moduleOrContext,id,action,inBwc){var module,moduleMeta;if(_.isEmpty(moduleOrContext)){return'';} if(_.isString(moduleOrContext)){module=moduleOrContext;}else{module=moduleOrContext.get('module');} if(_.isEmpty(module)||!app.bwc){return'';} moduleMeta=app.metadata.getModule(module)||{};if(inBwc===false||(_.isUndefined(inBwc)&&!moduleMeta.isBwcEnabled)){return'';} return app.bwc.buildRoute(module,id,app.bwc.getAction(action));},addIframeMark:function(url){var parts=url.split('?');if(parts[1]&&parts[1].indexOf('bwcFrame=1')!=-1)return url;return parts[0]+'?'+(parts[1]?parts[1]+'&bwcFrame=1':'bwcFrame=1');},rmIframeMark:function(url){var parts=url.split('?');if(!parts[1]){return url;} return parts[0]+'?'+_.reduce(parts[1].split('&'),function(acc,item){if(item=='bwcFrame=1'){return acc;}else{return acc?acc+'&'+item:item;}},'');},getSubpanelCollection:function(ctx,module){var retCollection=undefined,mdl=_.find(ctx.children,function(child){return(child.get('module')==module);});if(mdl&&_.has(mdl.attributes,'collection')){retCollection=mdl.get('collection');} return retCollection;},getRecordName:function(model){var metadata=app.metadata.getModule(model.module)||{};var format;var name;if(!_.isEmpty(metadata.nameFormat)){format=app.user.getPreference('default_locale_name_format')||'s f l';name=app.utils.formatNameModel(model.module,model.attributes,format);}else if(model.module==='Documents'&&model.has('document_name')){name=model.get('document_name');} return name||model.get('full_name')||model.get('name')||'';},getEmailAddress:function(model,options){var addresses;options||(options={});addresses=model.get('email');return _.chain(addresses).findWhere(options).pick('email_address').values().first().value()||'';},getPrimaryEmailAddress:function(model){return app.utils.getEmailAddress(model,{primary_address:true,invalid_email:false})||app.utils.getEmailAddress(model,{invalid_email:false});},resolve409Conflict:function(error,model,callback){app.drawer.open({layout:'resolve-conflicts',context:{dataInDb:error.payload.record,modelToSave:model}},callback);},getForecastNotSetUpMessage:function(isAdmin){var langKey=(isAdmin)?'LBL_DASHLET_FORECAST_NOT_SETUP_ADMIN':'LBL_DASHLET_FORECAST_NOT_SETUP',msg=app.lang.get(langKey,'Forecasts');if(isAdmin){var linkText=app.lang.get('LBL_DASHLET_FORECAST_CONFIG_LINK_TEXT','Forecasts');msg+=' <a href="#Forecasts/config">'+linkText+'</a>';} return msg;},getFieldLabels:function(moduleName,fields){var moduleMeta=app.metadata.getModule(moduleName);var labels=[];_.each(_.flatten(fields),function(fieldName){var fieldMeta=moduleMeta.fields[fieldName];if(fieldMeta){labels.push(app.lang.get(fieldMeta.vname,moduleName));}});return labels;},getReadableFileSize:function(size){var i=-1;var units=['K','M','G','T'];if(_.isEmptyValue(size)||size<1){size=0;}else if(size<1000){size=1000;} do{size=Math.round(size / 1000);i++;}while(size>=1000&&i<(units.length-1));return size+units[i];},getWindowLocationParameterByName:function(name,queryString){name=name.replace(/[\[]/,'\\[').replace(/[\]]/,'\\]');var regex=new RegExp('[\\?&]'+name+'=([^&#]*)','g'),matchResults=queryString.match(regex);if(matchResults&&matchResults.length>0){var results=regex.exec(matchResults[matchResults.length-1]);} return(results===undefined||results===null)?'':decodeURIComponent(results[1].replace(/\+/g,' '));},isTruthy:function(value){if(_.isString(value)){value=value.toLowerCase();} return value===true||value==='true'||value===1||value==='1'||value==='on'||value==='yes';},getFullnameFieldComponents:function(model,format){var components=[];var nameDef=model.fields.name;if(!nameDef){return components;} if(nameDef.type==='fullname'){format=format||app.user.getPreference('default_locale_name_format');var metadata=app.metadata.getModule(model.module)||{fields:{}};var formatMap=metadata.nameFormat||{};if(_.isEmpty(formatMap)){return['name'];} _.each(format.split(''),function(letter){if(formatMap[letter]){components.push(formatMap[letter]);}});return components;}else if(nameDef.fields){return nameDef.fields;} return['name'];},isNameErased:function(model){var erasedFields=model.get('_erased_fields');if(_.isEmpty(erasedFields)){return false;} var nameComponents=this.getFullnameFieldComponents(model);var anyNameFieldErased=_.some(nameComponents,function(field){return _.contains(erasedFields,field);});return anyNameFieldErased&&_.every(nameComponents.concat('name'),function(field){return!model.get(field);});},openEmailCreateDrawer:function(layout,data,onClose){var context={create:true,module:'Emails'};data=data||{};if(data.model&&data.model instanceof app.Bean&&data.model.module===context.module){context.model=data.model;}else{context.model=app.data.createBean(context.module);} data=_.omit(data,'model');data=prepopulateEmailForCreate(context.model,data);context=_.extend(data,context);app.drawer.open({layout:layout,context:context},onClose);},getLinksBetweenModules:function(primaryModule,relatedModule){var fields=app.metadata.getModule(primaryModule).fields;return _.chain(fields).filter(function(field){return field.type&&field.type==='link';}).filter(function(link){return app.data.getRelatedModule(primaryModule,link.name)===relatedModule;},this).value();},getSiteUrl:function(){var origin;if(app.config.siteUrl){return app.config.siteUrl;} if(window.location.origin){origin=window.location.origin;}else{origin=window.location.protocol+'//'+ window.location.hostname+ (window.location.port?':'+window.location.port:'');} return origin+window.location.pathname;},getProbabilityBySalesStage:function(salesStage){var cfg=app.metadata.getModule('Forecasts','config');var salesProb=0;if(!cfg.is_setup){return salesProb;} salesProb=app.lang.getAppListStrings('sales_probability_dom');return salesProb[salesStage];},getCommitStageBySalesStage:function(salesStage){var cfg=app.metadata.getModule('Forecasts','config');var stage='';if(!cfg.is_setup){return stage;} var probability=app.utils.getProbabilityBySalesStage(salesStage);var ranges=cfg[cfg.forecast_ranges+'_ranges'];_.find(ranges,function(range,index){if(probability>=range.min&&probability<=range.max){stage=index;return true;} return false;});return stage;},isPasswordRuleSet:function(passwordRule){if(_.isString(passwordRule)){return(!isNaN(passwordRule)&&parseInt(passwordRule,10)>0)?true:false;} return passwordRule;},validatePassword:function(password){var passwordSetting=app.config.passwordsetting||{};var invalidPassword={isValid:false,error:'',};if(password&&passwordSetting){if(app.utils.isPasswordRuleSet(passwordSetting.maxpwdlength)&&password.length>passwordSetting.maxpwdlength){invalidPassword.error+='<li>'+app.utils.formatString(app.lang.get('LBL_PASSWORD_MAX_LENGTH'),[passwordSetting.maxpwdlength])+'</li>';} if(app.utils.isPasswordRuleSet(passwordSetting.minpwdlength)&&password.length<passwordSetting.minpwdlength){invalidPassword.error+='<li>'+app.utils.formatString(app.lang.get('LBL_PASSWORD_MIN_LENGTH'),[passwordSetting.minpwdlength])+'</li>';} if(app.utils.isPasswordRuleSet(passwordSetting.onenumber)&&!(/\d+/).test(password)){invalidPassword.error+='<li>'+app.lang.get('LBL_PASSWORD_ONE_NUMBER')+'</li>';} if(app.utils.isPasswordRuleSet(passwordSetting.onelower)&&!(/[a-z]/).test(password)){invalidPassword.error+='<li>'+app.lang.get('LBL_PASSWORD_ONE_LOWERCASE')+'</li>';} if(app.utils.isPasswordRuleSet(passwordSetting.oneupper)&&!(/[A-Z]/).test(password)){invalidPassword.error+='<li>'+app.lang.get('LBL_PASSWORD_ONE_UPPERCASE')+'</li>';} if(app.utils.isPasswordRuleSet(passwordSetting.onespecial)&&!(/[~!@#$%^&*()_+\-={}|]/).test(password)){invalidPassword.error+='<li>'+app.lang.get('LBL_PASSWORD_ONE_SPECIAL_CHAR')+'</li>';} if(_.isString(passwordSetting.customregex)&&passwordSetting.customregex.length>0){var regex=new RegExp(passwordSetting.customregex);if(regex.test(password)){invalidPassword.error+='<li>'+app.utils.formatString(app.lang.get('LBL_PASSWORD_REGEX_REQUIREMENT'),[passwordSetting.customregex])+'</li>';}} if(invalidPassword.error){invalidPassword.error='<ul>'+invalidPassword.error+'</ul>';return invalidPassword;}} return{isValid:true,error:''};},createUserSrn:function(userId){let srnParts=app.config.tenant.split(':').slice(0,5);srnParts.splice(3,1,'');srnParts.push('user',userId);return srnParts.join(':');},getUnderscoreToCamelCaseString:function(str){return str.replace(/_(\D)/g,function(a,b){return b.toUpperCase();});},kebabToCamelCase:function(str){str=str.split('-').map(_.bind(function(a,i){return i===0?a:this.capitalize(a);},this)).join('');return str;},maps:{arrayToObject:function(array){if(!_.isArray(array)||_.isEmpty(array)){return{};} return array.reduce(function reduceArray(obj,item){const fieldName=Object.keys(item).pop();obj[fieldName]=item[fieldName];return obj;});},isMapsModuleEnabled:function(module){if(!_.has(app.config,'maps')){return false;} if(!_.has(app.config.maps,'enabled_modules')){return false;} const allowedModules=app.config.maps.enabled_modules;return _.contains(allowedModules,module);}},reports:{getDataSeries:function(dataSeries){if(!_.isString(dataSeries)){return false;} const dataSeriesParts=dataSeries.split(':');if(!dataSeriesParts||dataSeriesParts.length<=1){return false;} const groupFunction=dataSeriesParts.pop();let fieldName;let tableKey;if(groupFunction==='count'){fieldName='id';}else{fieldName=dataSeriesParts.pop();} tableKey=dataSeriesParts.join(':');return{fieldName,tableKey,groupFunction,};},hasAccessToAllReport:function(model,typeOfAction='view'){if(!_.isObject(model)){return true;} let hasAccess=true;const content=model.get?model.get('content'):model.content;const reportDef=app.utils.tryParseJSONObject(content);if(!reportDef){return hasAccess;} if(!app.acl.hasAccess(typeOfAction,reportDef.module)){hasAccess=false;return hasAccess;} const displayColumnsKey='display_columns';const summaryColumnsKey='summary_columns';const tableListKey='full_table_list';const tableKey='table_key';const tables=reportDef[tableListKey];const displayColumns=reportDef[displayColumnsKey]||[];const summaryColumns=reportDef[summaryColumnsKey]||[];if(!tables){return hasAccess;} const fields=displayColumns.concat(summaryColumns);_.each(fields,function checkACL(fieldData){const tableName=fieldData[tableKey];const fieldName=fieldData.name;const module=tables[tableName].module;const bean=app.data.createBean(module);const accessToField=app.acl.hasAccessToModel(typeOfAction,bean,fieldName);const accessToModule=app.acl.hasAccess(typeOfAction,module);if(!accessToField||!accessToModule){hasAccess=false;}},this);return hasAccess;},},setUsersEditableFields:function(fields,tplName){let idmException=['email1','email','email_addresses','email_addresses_primary',];let readonlyFields=['is_admin'];let vardefFields=app.metadata.getModule('Users','fields');_.each(fields,function(field){if(app.config.idmModeEnabled&&'record'===tplName&&_.contains(idmException,field.name)){return;} if(!app.config.idmModeEnabled){let adminDeveloperReadonlyFields=['is_admin'];let regularUserReadonlyFields=['user_name','status','is_admin','license_type','employee_status','title','department','reports_to_link','reportees',];let adminTypeUser='admin';let acls=app.user.getAcls().Users;let isAdmin=!_.has(acls,adminTypeUser);let isDev=!_.has(acls,'developer');let userType=app.user.get('type');if(isAdmin&&isDev&&userType!==adminTypeUser&&_.contains(adminDeveloperReadonlyFields,field.name)){field.readonly=true;return;} if(!isAdmin&&userType!==adminTypeUser&&_.contains(regularUserReadonlyFields,field.name)){field.readonly=true;return;} return;} if(_.contains(readonlyFields,field.name)||field.idm_mode_disabled){field.readonly=true;return;} _.each(vardefFields,function(vardef,index){if(index===field.name&&vardef.idm_mode_disabled){field.readonly=true;return;}},this);},this);},isFieldAlwaysReadOnly:function(fieldDef,viewDef){if(_.isUndefined(viewDef)||_.isUndefined(viewDef.readonly)){return app.utils.isTruthy(fieldDef.readonly)&&_.isUndefined(fieldDef.readonly_formula);}else{return app.utils.isTruthy(viewDef.readonly);}},updatePendoMetadata:function(addCustomFieldToVisitor,addCustomFieldToAccount){var pendoObject=app.analytics.connectors.Pendo.getPendoMetadata();var updatedVisitorObject=addCustomFieldToVisitor?_.extend(pendoObject.visitor,addCustomFieldToVisitor):pendoObject.visitor;var updatedAccountObject=addCustomFieldToAccount?_.extend(pendoObject.account,addCustomFieldToAccount):pendoObject.account;pendo.updateOptions({visitor:updatedVisitorObject,account:updatedAccountObject});},openFocusDrawer:function(focusDrawer,module,modelId,$el){if(focusDrawer&&module&&modelId){var context={layout:'row-model-data',context:{layout:'focus',module:module,modelId:modelId}};if(focusDrawer.isOpen()&&_.isEqual(context,focusDrawer.currentContextDef)){return;} focusDrawer.open(context,null,focusDrawer.isOpen(),$el);}},deleteFileFromField:function(field,data,shouldRender){callbacks={success:function(){field.model.set(data.field,'');field.model.save({},{showAlerts:{'process':true,'success':{messages:app.lang.get('LBL_FILE_DELETED')}},fields:[data.field]});if(self.disposed){return;} if(shouldRender){field.render();}},error:function(data){app.error.handleHttpError(data,{});}};app.api.file('delete',data,null,callbacks,{htmlJsonFormat:false});},isRliFieldValidForCascade:function(model,fieldName,attrs){const getValue=fieldName=>{if(attrs&&attrs[fieldName]){return attrs[fieldName];} return model.get(fieldName);};if(fieldName==='service_start_date'){return app.utils.isTruthy(getValue('service'));} if(['service_duration_value','service_duration_unit'].includes(fieldName)){return app.utils.isTruthy(getValue('service'))&&_.isEmpty(getValue('add_on_to_id'))&&!app.utils.isTruthy(getValue('lock_duration'));} if(fieldName==='commit_stage'){if(!app.acl.hasAccess('access','Forecasts')){return false;} let forecastConfig=app.metadata.getModule('Forecasts','config');let closedSalesStages=[...forecastConfig.sales_stage_won,...forecastConfig.sales_stage_lost];return!closedSalesStages.includes(getValue('sales_stage'));} return true;},DocumentMerge:{openHelpDocumentation:function(module){const serverInfo=app.metadata.getServerInfo();const version=encodeURIComponent(serverInfo.version);const edition=encodeURIComponent(serverInfo.flavor);const lang=encodeURIComponent(app.lang.getLanguage());const products=app.user.getProductCodes().join(',');const key=encodeURIComponent(App.metadata.getConfig().uniqueKey);const devStatus=encodeURIComponent(this.getVersionStatus(version));const url=`http://www.sugarcrm.com/crm/product_doc.php?edition=${edition}& version=${version}&lang=${lang}&module=${module}&products=${products} &status=${devStatus}&key=${key}&help_action=`;window.open(url);},getVersionStatus:function(version){const matches=version.match('/^[\d\.]+?([a-zA-Z]+?)[\d]*?$/si');if(_.isArray(matches)&&!_.isEmpty(matches)){return(matches[1]).toUpperCase();}else{return'GA';}},TagBuilderFactory:function(type,name,attributes){this.type=type;this.name=name;this.attributes=attributes;this.getTagBuilder=function getTagBuilder(type){this.type=type||this.type;let tagBuilder=null;switch(this.type){case'base':tagBuilder=new BaseTagBuilder();break;case'collection':tagBuilder=new CollectionTagBuilder();break;case'directive':tagBuilder=new DirectiveTagBuilder();break;case'conditional':tagBuilder=new ConditionalTagBuilder();break;} return tagBuilder;};function TagFactory(){this.getTag=function getTag(type){let tag=null;switch(type){case'base':tag=new Tag();break;case'directive':tag=new DirectiveTag();break;case'conditional':tag=new ConditionalTag();break;case'collection':tag=new CollectionTag();break;} return tag;};};function Tag(){this.type=null;this.name=null;this.attributes=[];this.tagValue='';this.setName=function setName(baseName,relateName){this.name=baseName;if(relateName){this.name+='.'+relateName;} return this;};this.setAttributes=function setAttributes(attributes){this.attributes=attributes;return this;};this.setAttribute=function setAttribute(attribute){_.extend(this.attributes,attribute);return this;};this.setTagValue=function(tagValue){this.tagValue=tagValue;return this;};this.getTagValue=function(){return this.tagValue;};this.getName=function(){return this.name;};this.getAttributes=function(){return this.attributes;};this.removeAttribute=function(attrName){delete this.attributes[attrName];};this.compile=function compile(){let attributes=this.getAttributes();let name=this.getName();let eachAttributes='';for(let attributeIndex in attributes){let attributeValue=attributes[attributeIndex];eachAttributes+=' '+attributeIndex+'=\''+attributeValue+'\'';} this.setTagValue('{'+name+eachAttributes+'}');return this;};};function CollectionTag(){Tag.call(this);this.compile=function compile(){let attributes=this.getAttributes();let name=this.getName();let eachAttributes='';let fieldTags=this.getFields()||'';for(let attributeIndex in attributes){let attributeValue=attributes[attributeIndex];eachAttributes+=' '+attributeIndex+'=\''+attributeValue+'\'';} let startingCollectionTag=`{#${name} ${eachAttributes}}`;let endingCollectionTag=`{/${name}}`;this.setCollectionTags(startingCollectionTag,endingCollectionTag);this.setTagValue(startingCollectionTag+fieldTags+endingCollectionTag);return this;};this.setCollectionTableFields=function(fieldName,fieldLabel){let field={name:`{${fieldName}}`,label:fieldLabel,};this.collectionTags.fields=this.collectionTags.fields||[];this.collectionTags.fields.push(field);return this;};this.setCollectionTags=function(startingCollectionTag,endingCollectionTag){this.fieldTags={};this.collectionTags={startingCollectionTag:startingCollectionTag,endingCollectionTag:endingCollectionTag,};return this;};this.getCollectionTags=function(){return this.collectionTags;};this.setFields=function setFields(fields){this.fieldTags='';for(let field of fields){this.fieldTags=this.fieldTags+'{'+field+'}';} return this;};this.getFields=function getFields(){return this.fieldTags;};};function DirectiveTag(){Tag.call(this);this.compile=function compile(){let attributes=this.getAttributes();let name=this.getName();let eachAttributes='';for(let attributeIndex in attributes){let attributeValue=attributes[attributeIndex];eachAttributes+=' '+attributeIndex+'=\''+attributeValue+'\'';} this.setTagValue('{!'+name+eachAttributes+'}');return this;};};function ConditionalTag(){Tag.call(this);this.compile=function compile(){let attributes=this.getAttributes();let tag='';for(let key in attributes){if(key==='if'||key==='else'){let data=attributes[key];tag+='{'+key+' '+data.condition+'}'+data.result;} if(key==='elseifs'){for(let elseif of attributes[key]){tag+='{elseif '+elseif.condition+'}'+elseif.result;}}} this.setTagValue(tag+'{endif}');return this;};};function BaseTagBuilder(name,attributes){this.name=name;this.attributes=attributes||{};this.tag=null;this.type=this.type||'base';this.newTag=function newTag(){let tagFactory=new TagFactory();this.tag=tagFactory.getTag(this.type);return this;};this.setName=function setName(name){this.tag.setName(name);return this;};this.setAttribute=function setAttribute(attribute){this.tag.setAttribute(attribute);return this;};this.setAttributes=function setAttributes(attributes){this.tag.setAttributes(attributes);return this;};this.get=function get(){return this.tag;};};function CollectionTagBuilder(name,attributes){BaseTagBuilder.call(this,name,attributes);this.type='collection';this.collectionTags={startingCollectionTag:'',endingCollectionTag:'',fields:[]};this.setName=function(name){this.tag.setName('#'+name);return this;};};function DirectiveTagBuilder(name,attributes){this.type='directive';this.setName=function(name){this.tag.setName('!'+name);return this;};BaseTagBuilder.call(this,name,attributes);};function ConditionalTagBuilder(name,attributes){BaseTagBuilder.call(this,name,attributes);this.type='conditional';};},},isDarkMode:function(parent=false){let bodyHasDarkModeClass=null;if(app.utils.isTruthy(parent)){bodyHasDarkModeClass=window.parent.document.body.classList.contains('sugar-dark-theme');}else{bodyHasDarkModeClass=document.body.classList.contains('sugar-dark-theme');} return bodyHasDarkModeClass||localStorage.getItem('last_appearance_preference')==='dark';},isWhiteColor:function(color){color=color.substring(1);var rgb=parseInt(color,16);var r=(rgb>>16)&0xff;var g=(rgb>>8)&0xff;var b=(rgb>>0)&0xff;var luma=0.2126*r+0.7152*g+0.0722*b;if(luma<100){return false;} return true;},tryParseJSONObject:function(jsonString){try{const response=JSON.parse(jsonString);if(response&&_.isObject(response)){return response;}} catch(e){} return false;},});});})(SUGAR.App); /* End of File include/javascript/sugar7/utils.js */ (function(app){app.events.on('app:init',function(){app.utils=_.extend(app.utils,{'FilterOptions':Backbone.Model.extend({initialize:function(options){this._filterPopulateNames=[];this._filterRelate=null;},setFilterRelate:function(value){if(!_.isObject(value)||_.isEmpty(value)){return this;} this._filterRelate=value;this.set('stickiness',false);return this;},setFilterPopulate:function(value){if(!_.isObject(value)||_.isEmpty(value)){return this;} this.set('filter_populate',value);this.set('stickiness',false);return this;},setInitialFilter:function(id){this.set('initial_filter',id);return this;},setInitialFilterLabel:function(name){this.set('initial_filter_label',name);return this;},setLangModules:function(modules){if(!_.isArray(modules)){return;} this.set('initial_filter_lang_modules',modules);},relateInitialFilterLabel:function(){this.set('initial_filter_label',this._filterPopulateNames.join(', '));return this;},config:function(options){options=options||{};this.setInitialFilter(options.initial_filter);this.setInitialFilterLabel(options.initial_filter_label);this.setFilterPopulate(options.filter_populate);this.setFilterRelate(options.filter_relate);return this;},populateRelate:function(relateModel){if(_.isEmpty(this._filterRelate)){return this;} var filterPopulate=this.get('filter_populate')||{};_.each(this._filterRelate,function(toField,fromField){filterPopulate[toField]=relateModel.get(fromField);var relateNameField=_.find(relateModel.fields,function(field){return field.id_name===fromField;});if(relateNameField){this._filterPopulateNames.push(relateModel.get(relateNameField.name));}},this);this.set('filter_populate',filterPopulate);if(!this.get('initial_filter_label')){this.relateInitialFilterLabel();} return this;},format:function(){if(!this.get('initial_filter')||!this.get('filter_populate')){return;} return this.toJSON();},keyValueFilterDef:function(key,value,fieldList){var isPredefinedFilter=(fieldList[key]&&fieldList[key].predefined_filter===true);if(key==='$or'){var keys=_.reduce(value,function(memo,obj){return memo.concat(_.keys(obj));},[]);key=_.find(_.keys(fieldList),function(key){if(_.has(fieldList[key],'dbFields')){return _.isEqual(fieldList[key].dbFields.sort(),keys.sort());}},this);value=_.values(value[0])[0];}else if(key==='$and'){var values=_.reduce(value,function(memo,obj){return _.extend(memo,obj);},{});var def=_.find(fieldList,function(fieldDef){return _.has(values,fieldDef.id_name||fieldDef.name);},this);var operator='$equals';key=def?def.name:key;if(def&&!_.isString(values[def.name])&&def.type==='currency'){operator=_.keys(values[def.name])[0];values[key]=values[key][operator];} value={};value[operator]=values;} if(!fieldList[key]){var relate=_.find(fieldList,function(field){return field.id_name===key;});if(!relate){return;} key=relate.name;if(_.isString(value)||_.isNumber(value)){value={$in:[value]};}else if(_.keys(value)[0]==='$not_equals'){var val=_.values([value])[0];value={$not_in:val};}}else if(!fieldList[key]&&!isPredefinedFilter){return;} if(_.isString(value)||_.isNumber(value)){value={$equals:value};} return[key,value];}})});});})(SUGAR.App); /* End of File include/javascript/sugar7/utils-filters.js */ (function(app){app.events.on('app:init',function(){app.utils=_.extend(app.utils,{'GlobalSearch':{formatRecords:function(collection,linkableHighlights){collection.each(function(model){if(model.formatted){return;} var highlights=model.get('_highlights');if(!highlights){model.formatted=true;return;} var moduleMeta=app.metadata.getModule(model.get('_module'));var nameFormatValues=_.values(moduleMeta.nameFormat);if(nameFormatValues.length){var personAttrs=_.pick(model.attributes,nameFormatValues);_.each(personAttrs,function(val,key){personAttrs[key]=Handlebars.Utils.escapeExpression(val);});if(!highlights.full_name){var fullname=app.utils.formatNameModel(model.get('_module'),_.extend({},personAttrs,highlights));if(fullname.length){highlights.name=[fullname];} highlights=_.omit(highlights,_.keys(personAttrs));}} var formattedHighlights=_.map(highlights,function(val,key){if(key==='email'){if(val.primary){val=new Handlebars.SafeString(_.first(val.primary));var label='LBL_PRIMARY_EMAIL';}else{return false;}}else if(key==='commentlog'){if(val.commentlog_entry){val=new Handlebars.SafeString(_.first(val.commentlog_entry));}else{return false;}}else{val=new Handlebars.SafeString(_.first(val));} return{name:key,value:val,label:label||moduleMeta.fields[key].vname,link:linkableHighlights,highlighted:true};});formattedHighlights=_.reject(formattedHighlights,function(highlight){return highlight===false;});var highlightedSecondaryEmail=highlights.email?highlights.email.secondary:null;if(highlightedSecondaryEmail){formattedHighlights.push({name:'secondaryEmail',type:'email',value:new Handlebars.SafeString(highlightedSecondaryEmail.join(', ')),label:moduleMeta.fields.email.vname,link:linkableHighlights,highlighted:true});} model.set('_highlights',formattedHighlights);model.formatted=true;});},getFieldsMeta:function(module,options){options=options||{};var fieldsMeta={};var meta=_.extend({},this.meta,app.metadata.getView(module,'search-list'));_.each(meta.panels,function(panel){if(panel.name==='primary'){fieldsMeta.primaryFields=this._setFieldsCategory(panel.fields,'primary',options);}else if(panel.name==='secondary'){fieldsMeta.secondaryFields=this._setFieldsCategory(panel.fields,'secondary',options);}},this);fieldsMeta.rowactions=meta.rowactions;return fieldsMeta;},_setFieldsCategory:function(fields,category,options){var fieldList={};_.each(fields,function(field){if(!fieldList[field.name]){fieldList[field.name]=_.extend({},fieldList[field.name],field);} fieldList[field.name][category]=true;fieldList[field.name].ellipsis=false;if(category==='primary'&&options.linkablePrimary===false){fieldList[field.name].link=false;} if(category==='secondary'){fieldList[field.name].link=false;if(field.type==='email'){fieldList[field.name].emailLink=false;}}});return fieldList;},highlightFields:function(model,viewDefs,add){var highlighted=model.get('_highlights');var varDefs=model.fields;viewDefs=_.clone(viewDefs)||{};_.each(highlighted,function(field){var hasViewDefs=viewDefs[field.name];var addOrPatchExisting=(hasViewDefs||add);if(!addOrPatchExisting){return;} if(!_.isUndefined(model.primaryFields)&&model.primaryFields[field.name]){return;} viewDefs[field.name]=_.extend({},varDefs[field.name],viewDefs[field.name],field);});return viewDefs;},buildSearchRoute:function(term,options){options=options||{};term=term?encodeURIComponent(term):'';var paramString='?';var firstParamDefined=false;var modules=options.modules;if(modules&&modules.length>0){paramString=paramString+'modules='+modules.join(',');firstParamDefined=true;} var tags=options.tags;if(tags&&tags.length>0){if(firstParamDefined){paramString=paramString+'&'} var encodedTags=_.map(tags,function(tag){return encodeURIComponent(tag);});paramString=paramString+'tags='+encodedTags.join(',');} return app.router.buildRoute('search',term+paramString);}}});});})(SUGAR.App); /* End of File include/javascript/sugar7/utils-search.js */ (function(app){app.events.on('app:init',function(){app.utils=_.extend(app.utils,{charts:{isNumeric:function(value){let v=parseFloat(value);return!isNaN(v)&&typeof v==='number'&&isFinite(v);},round:function(x,n){let tenN=Math.pow(10,n);return Math.round(x*tenN)/ tenN;},countSigFigsAfter:function(value){let re=/^[^\d]*([\d.,\s]+)[^\d]*$/;let digits=value.toString().match(re)[1].replace(/[,\s]/,'.');let sigfigs=0;if(Math.floor(digits)!==parseFloat(digits)){sigfigs=parseFloat(digits).toString().split('.').pop().length||0;} return sigfigs;},countSigFigsBefore:function(value){return Math.floor(value).toString().replace(/0+$/g,'').length;},siDecimal:function(n){return Math.pow(10,Math.floor(Math.log(n)*Math.LOG10E));},siValue:function(si){if(app.utils.charts.isNumeric(si)){return app.utils.charts.siDecimal(si);} let units={y:1e-24,yocto:1e-24,z:1e-21,zepto:1e-21,a:1e-18,atto:1e-18,f:1e-15,femto:1e-15,p:1e-12,pico:1e-12,n:1e-9,nano:1e-9,µ:1e-6,micro:1e-6,m:1e-3,milli:1e-3,k:1e3,kilo:1e3,M:1e6,mega:1e6,G:1e9,giga:1e9,T:1e12,tera:1e12,P:1e15,peta:1e15,E:1e18,exa:1e18,Z:1e21,zetta:1e21,Y:1e24,yotta:1e24};return units[si]||0;},numberFormat:function(number,precision,currency,locale){let d=parseFloat(number);let c=typeof currency==='boolean'?currency:false;d=parseFloat(number);c=typeof currency==='boolean'?currency:false;if(!app.utils.charts.isNumeric(d)||(d===0&&!c)){return number.toString();} let m=app.utils.charts.countSigFigsAfter(d);let p=app.utils.charts.isNumeric(precision)?Math.floor(precision):typeof locale!=='undefined'?locale.precision:c?2:null;p=!app.utils.charts.isNumeric(p)?m:m&&c?p:Math.min(p,m);let f=typeof locale==='undefined'?d3sugar.format:d3sugar.formatLocale(locale).format;let s=c?'$,':',';s+=m?('.'+p+'f'):'';return f(s)(d);},numberFormatFixed:function(d,p,c,l){if(!app.utils.charts.isNumeric(d)){return d.toString();} c=typeof c==='boolean'?c:false;p=app.utils.charts.isNumeric(p)?p:c?2:0;let f=typeof l==='undefined'?d3sugar.format:d3sugar.formatLocale(l).format;let s=c?'$,':',';s+='.'+p+'f';return f(s)(d);},numberFormatSI:function(d,p,c,l){if(!app.utils.charts.isNumeric(d)){return d;} c=typeof c==='boolean'?c:false;p=app.utils.charts.isNumeric(p)?p:0;let f=typeof l==='undefined'?d3sugar.format:d3sugar.formatLocale(l).format;let m=app.utils.charts.countSigFigsAfter(d);let s=c?'$,':',';if(c&&m&&d<1000){d=app.utils.charts.round(d,p);m=app.utils.charts.countSigFigsAfter(d);p=Math.min(m,p);if(p===1){p=2;} s+='.'+p+'f';} else if(Math.abs(d)<1){s+=(+d.toFixed(p)===0?'.1s':'.'+Math.min(p,m)+'f');} else if(Math.abs(d)<1000){d=app.utils.charts.round(d,p);}else if(Math.abs(d)>=1e9){d /=1e9;f=typeof l==='undefined'?d3sugar.format:d3sugar.formatLocale(l).format;return f('s')(d)+'B';}else{f=typeof l==='undefined'?d3sugar.formatPrefix:d3sugar.formatLocale(l).formatPrefix;if(p!==0){var d1=f('.'+p+'s',d)(d);var d2=d1.split('.').pop().replace(/[^\d]+$/,'').match(/0+$/g);if(Array.isArray(d2)){p-=d2.pop().length;}} s+='.'+p+'s';return f(s,d)(d);} return f(s)(d);},numberFormatSIFixed:function(d,p,c,l,si){if(!app.utils.charts.isNumeric(d)){return d.toString();} c=typeof c==='boolean'?c:false;p=app.utils.charts.isNumeric(p)?p:c?2:0;let f=typeof l==='undefined'?d3sugar.formatPrefix:d3sugar.formatLocale(l).formatPrefix;si=app.utils.charts.siValue(si);let s=c?'$,':',';s+='.'+p+'s';return f(s,si)(d);},numberFormatPercent:function(number,total,locale){let t=parseFloat(total);let n=app.utils.charts.isNumeric(t)&&t>0?(number*100 / t):100;let p=locale&&typeof locale.precision!=='undefined'?locale.precision:1;let d=app.utils.charts.numberFormat(n,p,false,locale);return d+'%';},buildLocality:function(l,d){let locale=l||{};let deep=!!d;let unfer=function(a){return a.join('|').split('|').map(function(b){return!(b)?'':isNaN(b)?b:+b;});};let definition={'decimal':'.','thousands':',','grouping':[3],'currency':['$',''],'precision':2,'periods':['AM','PM'],'days':['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],'shortDays':['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],'months':['January','February','March','April','May','June','July','August','September','October','November','December'],'shortMonths':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],'date':'%b %-d, %Y','time':'%-I:%M:%S %p','dateTime':'%B %-d, %Y at %X GMT%Z','full':'%A, %c','long':'%c','medium':'%x, %X','short':'%-m/%-d/%y, %-I:%M %p','yMMMEd':'%a, %x','yMEd':'%a, %-m/%-d/%Y','yMMMMd':'%B %-d, %Y','yMMMd':'%x','yMd':'%-m/%-d/%Y','yMMMM':'%B %Y','yMMM':'%b %Y','MMMd':'%b %-d','MMMM':'%B','MMM':'%b','y':'%Y'};Object.getOwnPropertyNames(locale).forEach(function(key){let def=locale[key];definition[key]=!deep||!Array.isArray(def)?def:unfer(def);});return definition;},},});});})(SUGAR.App); /* End of File include/javascript/sugar7/utils-charts.js */ (function(app){var _useRequiredLabels={"bool":true,"radioenum":'edit'};app.events.on("app:init",function(){var _fieldProto=_.clone(app.view.Field.prototype);_.extend(app.view.Field.prototype,{hideHelp:false,exclamationMarkTemplate:Handlebars.compile(`<span class="error-tooltip add-on" data-container="body" rel="tooltip" title="{{arrayJoin this ", "}}"> <i class="sicon sicon-warning-circle"></i> </span>`),handleValidationError:function(errors){this.clearErrorDecoration();_.defer(function(field){field._errors=errors;if(_.include(['edit','disabled'],field.action)||field.view.inlineEditMode){if(field.parent){field.parent.setMode('edit');}else{field.setMode('edit');}} if(!field._shouldRenderRequiredPlaceholder()){field.decorateRequired();} if(field.view&&field.view.trigger){field.view.trigger('field:error',field,true);}},this);this.$el.off("keydown.record");$(document).off("mousedown.record"+this.name);},removeValidationErrors:function(){this._errors={};},_removeViewClass:function(action){this.$el.removeClass(action);},_addViewClass:function(action){this.$el.addClass(action);},showNoData:function(){var viewDefs=this.viewDefs||{};return app.utils.isFieldAlwaysReadOnly(this.def,viewDefs)&&app.acl.hasAccessToModel('readonly',this.model,this.name)&&this.name&&!this.model.has(this.name);},_isErasedField:function(){if(!this.model){return false;} return!this.model.get(this.name)&&_.contains(this.model.get('_erased_fields'),this.name);},_hasLicenseAccess:function(){if(!this.model){return true;} return app.acl.hasAccessToModel('license',this.model,this.name);},_checkAccessToAction:function(action){if(_.contains(this.fallbackActions,action)&&_.isUndefined(this.viewFallbackMap[action])){return true;} if(_.result(this,'showNoData')===true){return action==='nodata';} if(action==='erased'){return app.acl.hasAccessToModel('detail',this.model,this.name);} return app.acl.hasAccessToModel(action,this.model,this.name);},viewFallbackMap:{'preview':'detail','list':'detail','edit':'detail','detail':'noaccess','erased':'noaccess','noaccess':'nodata'},fallbackActions:['nolicense','noaccess','nodata','erased'],_getFallbackTemplate:function(viewName){if(_.contains(this.fallbackActions,viewName)){return viewName;} return(this.isDisabled()&&viewName==='disabled')?'edit':(this.view.fallbackFieldTemplate||'detail');},_setErasedFieldAction:function(){if(this._isErasedField()&&this.action!=='edit'){this.action='erased';this.options.viewName='erased';}},_markFieldLackingAccess:function(){if(!this._hasLicenseAccess()){this.action='nolicense';this.options.viewName='nolicense';}},_render:function(){this.clearErrorDecoration();this._processHelp();this._setErasedFieldAction();this._markFieldLackingAccess();_fieldProto._render.call(this);if(this._previousAction){this._addViewClass(this._previousAction);} this._addViewClass(this.action);if(!_.isEmpty(this._errors)){if(_.include(['edit','disabled'],this.action)){this.decorateError(this._errors);}} if(this.def.required){this.clearRequiredLabel();if((this.action==='edit'||-1!==_.indexOf(['edit','list-edit','disabled'],this.tplName))&&this._shouldRenderRequiredPlaceholder()){this.decorateRequired();}} if(this.def.help){this.clearHelper();if(this.action==='edit'||-1!==_.indexOf(['edit','list-edit'],this.tplName)){this.decorateHelper();}}},isFieldEmpty:function(){if(!this.model){return true;} var value=this.model.get(this.name);return _.isNull(value)||_.isUndefined(value)||((_.isString(value)||_.isArray(value))&&_.isEmpty(value));},_processHelp:function(){if(this.meta&&!_.isUndefined(this.meta['hide_help'])){this.hideHelp=!!this.meta['hide_help'];return;} if(this.view.action==='list'&&this.action==='edit'){this.hideHelp=true;}},clearHelper:function(){this.$el.closest('.record-cell').attr({'rel':''});},decorateHelper:function(){var title=app.lang.get(this.def.help,this.module);this.$el.closest('.record-cell').attr({'rel':'tooltip','data-title':title,'data-bs-placement':'bottom'});},_shouldRenderRequiredPlaceholder:function(){return!this.def.no_required_placeholder;},decorateRequired:function(){var useLabels=_useRequiredLabels[this.type];useLabels=_.isString(useLabels)?(useLabels===this.tplName):useLabels;if(useLabels){this.setRequiredLabel();}else{this.setRequiredPlaceholder();}},setRequiredPlaceholder:function(el){var label=app.lang.get('LBL_REQUIRED_FIELD',this.module),placeholder;el=el||this.$(this.fieldTag).first();placeholder=el.attr('placeholder');placeholder=(placeholder)?'('+label+') '+placeholder:label;el.attr('placeholder',placeholder.trim()).addClass('required');},setRequiredLabel:function(element){var ele=element||this.$el;var $label=ele.closest('.record-cell').find(".record-label");$label.append(' <span data-required="required">('+app.lang.get("LBL_REQUIRED_FIELD",this.module)+')</span>');},clearRequiredLabel:function(element){var ele=element||this.$el;var $label=ele.closest('.record-cell').find('span[data-required]');$label.remove();},setViewName:function(view){var viewDefs=this.viewDefs||{};if(app.utils.isFieldAlwaysReadOnly(this.def,viewDefs)){var readOnlyViews=['detail','list'];view=_.contains(readOnlyViews,view)?view:'detail';} this.options.viewName=view;},setMode:function(name){var oldAction=this._previousAction||this.action;this._removeViewClass(oldAction);_fieldProto.setMode.call(this,name);},setDisabled:function(disable,options){if(!this._checkAccessToAction('disabled')){return;} disable=_.isUndefined(disable)?true:disable;if(disable===false&&this.isDisabled()){this._removeViewClass(this.action);} _fieldProto.setDisabled.call(this,disable,options);var ele=$('.'+this.baseFieldName+'_should_cascade');if(ele.length===1&&!(_.isUndefined(this.def.readOnlyProp)||_.isUndefined(this.readOnlyProp))){ele.prop('disabled',(this.def.readOnlyProp||this.readOnlyProp));}},decorateError:function(errors){var ftag=this.fieldTag||'',$ftag=this.$(ftag),errorMessages=[],$tooltip;this.$el.closest('.record-cell').addClass('error');this.$el.addClass('error');if(_.isString(errors)){errorMessages.push(errors);}else{_.each(errors,function(errorContext,errorName){errorMessages.push(app.error.getErrorString(errorName,errorContext));});} var isWrapped=$ftag.parent().hasClass('input-append');if(!isWrapped){$ftag.wrap('<div class="input-append '+ftag+'">');} $ftag.parent().addClass('error');$tooltip=$(this.exclamationMarkTemplate(errorMessages));$ftag.after($tooltip);},_dispose:function(){_fieldProto._dispose.call(this);},clearErrorDecoration:function(){var ftag=this.fieldTag||'';var $ftag=this.$(ftag);var $parent=$ftag.parent().first();this.$('.add-on.error-tooltip').remove();var isWrappedError=$parent.hasClass('input-append')&&$parent.hasClass('error');var isWrapperException=false;_.each(['date','currency','timeselect'],function(item){isWrapperException=isWrapperException||$parent.hasClass(item);});if(isWrapperException){$parent.removeClass('error');}else if(isWrappedError){$ftag.unwrap('.input-append.error');} this.$el.removeClass(ftag);this.$el.removeClass("error");this.$el.closest('.record-cell').removeClass("error");if(this.view&&this.view.trigger){this.view.trigger('field:error',this,false);}},delegateEvents:function(events){events=events||_.result(this,'events')||(this.def?this.def.events:null);if(!events){return;} events['click a[href="javascript:void(0)"]']='_handleBadLinkHref';events['click a[href="javascript:void(0);"]']='_handleBadLinkHref';_fieldProto.delegateEvents.call(this,events);},bindDomChange:function(){this.$(this.fieldTag).on('focus',_.bind(_.debounce(this.handleFocus,40),this));_fieldProto.bindDomChange.call(this);},handleFocus:function(){if(this.disposed){return;} var $flexList=this.$el.closest('.flex-list-view-content');if(!_.isUndefined($flexList)){var previousScrollLeftValue=$flexList.data('previousScrollLeftValue');if(!_.isUndefined(previousScrollLeftValue)&&$flexList.scrollLeft()!==previousScrollLeftValue){$flexList.scrollLeft(previousScrollLeftValue);$flexList.removeData('previousScrollLeftValue');}} var left=this.$el.position().left;var right=this.$el.outerWidth()+left;var top=this.$el.offset().top;var bottom=this.$el.outerHeight()+top;var fieldPadding=parseInt(this.$el.parent().css('padding-left'),10);this.view.trigger('field:focus:location',{left:left,right:right,top:top,bottom:bottom,fieldPadding:fieldPadding});},_handleBadLinkHref:function(evt){evt.preventDefault();}});});})(SUGAR.App); /* End of File include/javascript/sugar7/field.js */ (function(app){var _oldMetadataSet=app.metadata.set;app.metadata.set=function(data){_.each(data.modules,function(module){if(!_.isUndefined(module.fields)){var field=module.fields.team_name;if(field){delete field.len;field.type="teamset";} if(module.fields.acl_team_names){module.fields.acl_team_names.type='teamset';} _.each(module.fields,function(field){if(field.name&&(field.type==="relate")&&(field.name.length>2&&(field.name.length- field.name.lastIndexOf("_id"))===3)){field.type="id";delete field.source;}});}},this);_oldMetadataSet.apply(this,arguments);};app.data.sync=_.wrap(app.data.sync,function(_super,method,model,options){if(app.config.platform==='base'){options=options||{};options.params=_.extend(options.params||{},{erased_fields:true});} return _super.call(app.data,method,model,options);});})(SUGAR.App); /* End of File include/javascript/sugar7/hacks.js */ (function(app){app.events.on('app:sync',function(){app.alert.show('app:sync',{level:'process',title:app.lang.get('LBL_LOADING')});});app.events.on('app:sync:complete app:sync:error',function(){app.alert.dismiss('app:sync');});var _contextProto=_.clone(app.Context.prototype);app.Context.prototype.loadData=function(options){if(!this.parent){options=options||{};options.showAlerts=true;} _contextProto.loadData.call(this,options);};var processAlert={_count:0,dismiss:function(){this._count--;if(this._count<1){this._count=0;app.alert.dismiss('data:sync:process');}},show:function(options){this._count++;app.alert.show('data:sync:process',options);},reset:function(){this._count=0;app.alert.dismiss('data:sync:process');}};app.events.on('data:sync:start',function(method,model,options){options=options||{};if(!options.showAlerts){return;} if(options.showAlerts.process===false){return;} var alertOpts={level:'process'};if(method==='read'){alertOpts.title=app.lang.get('LBL_LOADING');} else if(method==='delete'){alertOpts.title=options.relate?app.lang.get('LBL_UNLINKING'):app.lang.get('LBL_DELETING');} else{alertOpts.title=app.lang.get('LBL_SAVING');} if(_.isObject(options.showAlerts.process)){_.extend(alertOpts,options.showAlerts.process);} processAlert.show(alertOpts);});var syncCompleteHandler=function(type,messages,method,model,options){options=options||{};var alertOpts={level:type,messages:messages};alertOpts.autoClose=(alertOpts.level==='error')?false:true;if(!options.showAlerts)return;if(method==='read')return;if(options.showAlerts[type]===false)return;if(_.isObject(options.showAlerts[type])){_.extend(alertOpts,options.showAlerts[type]);} app.alert.show('data:sync:'+type,alertOpts);};app.events.on('data:sync:success',function(method,model,options){var messages;if(method==='delete'){messages=options.relate?'LBL_UNLINKED':'LBL_DELETED';} else{messages='LBL_SAVED';} syncCompleteHandler('success',messages,method,model,options);});app.events.on('data:sync:error',function(method,model,options,error){var suppressErrorMessageFor=[409,412];if(!error||(!error.handled&&_.indexOf(suppressErrorMessageFor,error.status)===-1)){syncCompleteHandler('error','ERR_GENERIC_SERVER_ERROR',method,model,options);}});app.events.on('data:sync:complete',function(method,model,options){if(options.showAlerts&&options.showAlerts.process!==false){processAlert.dismiss();}});app.events.on('processalert:reset',function(){processAlert.reset();});})(SUGAR.App); /* End of File include/javascript/sugar7/alert.js */ (function(app){app.events.on('app:init',function(){app.lang=_.extend(app.lang,{getModuleIconLabel:function(module){var name=app.lang.getAppListStrings('moduleIconList')[module]||app.lang.getModuleName(module);var space=name.indexOf(' ');var hasSpace=space!==-1;var result;if(hasSpace){result=name.substring(0,1)+name.substring(space+1,space+2);}else{result=name.substring(0,2);} return result;}});});app.events.on('app:sync:complete',function(){var language=app.user.getPreference('language') if(language){language=language.replace('_','-') app.date.locale(language.toLowerCase());if($.fn.select2.locales){var twoLetterCode=language.substring(0,2).toLowerCase();if(twoLetterCode in $.fn.select2.locales){$.extend($.fn.select2.defaults,$.fn.select2.locales[twoLetterCode]);} if(language in $.fn.select2.locales){$.extend($.fn.select2.defaults,$.fn.select2.locales[language]);}}}});app.events.on('lang:direction:change',function(){var direction=app.lang.direction,isRTL=direction==='rtl';$('html').toggleClass('rtl',isRTL);});})(SUGAR.App); /* End of File include/javascript/sugar7/language.js */ (function(app){app.augment("help",{_moduleLabelMap:undefined,get:function(module,view,context){var objModule=_.extend({'module_name':app.lang.getModuleName(module),'plural_module_name':app.lang.getModuleName(module,{plural:true})},context||{},this._getModuleLabelMap());var viewName=this._cleanupViewName(view).toUpperCase();return{'body':this._get('LBL_HELP_'+viewName,module,objModule),'more_help':this._get('LBL_HELP_MORE_INFO',module,objModule)};},_get:function(label,module,context){var text=app.lang.get(label,module,context);if(_.isEqual(label,text)){return undefined;} return text;},_cleanupViewName:function(viewName){switch(viewName.toLowerCase()){case'list':return'records';case'detail':return'record';default:return viewName;}},_getModuleLabelMap:function(){if(!_.isUndefined(this._moduleLabelMap)){return this._moduleLabelMap;} this._moduleLabelMap={};_.each(app.metadata.getModuleNames({filter:'enabled'}),function(module){var key=module.toLowerCase();this._moduleLabelMap[key+'_singular_module']=app.lang.getModuleName(module);this._moduleLabelMap[key+'_module']=app.lang.getModuleName(module,{plural:true});},this);return this._moduleLabelMap;},clearModuleLabelMap:function(){this._moduleLabelMap=undefined;},getMoreInfoHelpURL:function(layoutName,module){layoutName=layoutName||'list';module=module||app.controller.context.get('module');var serverInfo=app.metadata.getServerInfo(),lang=app.lang.getLanguage(),url;if(layoutName=='records'){layoutName='list';} url='https://www.sugarcrm.com/crm/product_doc.php?edition='+serverInfo.flavor+'&version='+serverInfo.version+'&lang='+lang+'&module='+module+'&route='+layoutName;let products=app.user.getProductCodes();url+=products?'&products='+encodeURIComponent(products.join(',')):'';if(layoutName=='bwc'){var action=window.location.hash.match(/#bwc.*action=(\w*)/i);if(action&&!_.isUndefined(action[1])){url+='&action='+action[1];}} return url;},getDocumentationUrl:function(moduleName){var serverInfo=app.metadata.getServerInfo();var language=app.lang.getLanguage();var module=moduleName||app.controller.context.get('module');let products=app.user.getProductCodes();products=products?products.join(','):'';var params={edition:serverInfo.flavor,version:serverInfo.version,lang:language,};if(!_.isEmpty(products)){params.products=products;} params.module=module;return'https://www.sugarcrm.com/crm/product_doc.php?'+$.param(params);},});app.events.on("app:sync:complete",function(){app.help.clearModuleLabelMap();});})(SUGAR.App); /* End of File include/javascript/sugar7/help.js */ (function(app){app.events.on("app:init",function(){Handlebars.registerHelper('moduleIconLabel',function(module){return app.lang.getModuleIconLabel(module);});Handlebars.registerHelper('moduleIconToolTip',function(module){return app.lang.getModuleName(module);});Handlebars.registerHelper('getDDLabel',function(value,key){return app.lang.getAppListStrings(key)[value]||value;});Handlebars.registerHelper('subViewTemplate',function(key,data,options){var frame,template;template=app.template.getView(key,options.hash.module);frame=_.extend(Handlebars.createFrame(options.data||{}),options.hash);return template?template(data,{data:frame}):'';});Handlebars.registerHelper('subFieldTemplate',function(fieldName,view,data,options){var frame,template;template=app.template.getField(fieldName,view,options.hash.module);frame=_.extend(Handlebars.createFrame(options.data||{}),options.hash);return template?template(data,{data:frame}):'';});Handlebars.registerHelper('subLayoutTemplate',function(key,data,options){var frame,template;template=app.template.getLayout(key,options.hash.module);frame=_.extend(Handlebars.createFrame(options.data||{}),options.hash);return template?template(data,{data:frame}):'';});Handlebars.registerHelper('buildUrl',function(options){return new Handlebars.SafeString(app.utils.buildUrl(options.hash.url));});Handlebars.registerHelper('loading',function(str,options){str=app.lang.get(str);var cssClass=['loading'];if(_.isString(options.hash.cssClass)){cssClass=_.unique(cssClass.concat(Handlebars.Utils.escapeExpression(options.hash.cssClass).split(' ')));} return new Handlebars.SafeString('<div class="'+cssClass.join(' ')+'">' +Handlebars.Utils.escapeExpression(str) +'<i class="l1">.</i><i class="l2">.</i><i class="l3">.</i>' +'</div>');});Handlebars.registerHelper('decoratedField',function(type,view,options){var def={type:type,field:this};var field=app.view.createField({type:type,def:def,viewDefs:def,view:view,model:options.hash.model,viewName:options.hash.template,});if(options.hash.parent&&_.isArray(options.hash.parent.fields)){options.hash.parent.fields.push(field);} return field.getPlaceholder();});Handlebars.registerHelper('timeAgo',function(str,options){return moment?moment.utc(str).fromNow():str;});Handlebars.registerHelper('or',function(){for(let i=0;i<arguments.length-1;i++){if(!!arguments[i]){return true;}} return false;});Handlebars.registerHelper('times',function(n,block){let accum='';for(let i=0;i<n;i++){accum+=block.fn(i);} return accum;});Handlebars.registerHelper('buildIcon',function(iconClass){return iconClass.includes('sicon')?`sicon ${iconClass}`:`fa ${iconClass}`;});Handlebars.registerHelper('moduleLabel',function(module,size,options){let contents='';let attributes=_.clone(options.hash)||{};attributes.class=attributes.class?`${attributes.class} label label-module`:'label label-module';size=_.contains(['sm','lg'],size)?size:'sm';attributes.class+=` label-module-size-${size}`;let moduleMeta=app.metadata.getModule(module)||{};let color=_.has(attributes,'color')?attributes.color:moduleMeta.color||'ocean';attributes.class+=` label-module-color-${color}`;if(moduleMeta.display_type==='abbreviation'){contents=app.lang.getModuleIconLabel(module);}else{let icon=moduleMeta.icon||'sicon-default-module-lg';attributes.class+=` sicon ${icon}`;} attributes=_.reduce(attributes,function(string,value,key){return`${string} ${key}="${value}"`;},'');return new Handlebars.SafeString(`<span ${attributes.trim()}>${contents.trim()}</span>`);});Handlebars.registerHelper('tooltipTemplate',function(title,placement){let html=`<span class="absolute h-full w-full top-0 left-0" rel="tooltip" `;if(placement&&_.isString(placement)){html+=`data-bs-placement="${placement}" `;} html+=`data-original-title="${title}"></span>`;return new Handlebars.SafeString(html);});Handlebars.registerHelper('moduleLabelContainer',function(module,size){let moduleMeta=app.metadata.getModule(module)||{};let color=moduleMeta.color||'ocean';size=_.contains(['sm','lg'],size)?size:'sm';return`label label-module label-module-size-${size} label-module-color-${color}`;});Handlebars.registerHelper('reportField',function(view,options){const parentModel=options.hash.model;const index=options.hash.index;const html=options.hash.html;const model=parentModel.get(index);let self=this;try{self=app.utils.deepCopy(this);}catch(e){} if(_.isEmpty(model.get('id'))&&self.link){self.type='text';self.link=false;} if(self.type==='currency'){self.showTransactionalAmount=false;self.skip_preferred_conversion=true;} const field=SUGAR.App.view.createField({def:self,viewDefs:self,view:view,model:model,viewName:options.hash.template});if(options.hash.parent&&_.isArray(options.hash.parent.fields)){options.hash.parent.fields.push(field);} if(field.type==='htmleditable_tinymce'){field.render();return new Handlebars.SafeString(field.$el.html());} if(html){if(field.type==='enum'){if(_.has(self,'options')){field.items=app.lang.getAppListStrings(self.options);}else if(_.has(self,'function')&&!_.isUndefined(view.data.functionOptions)&&!_.isUndefined(view.data.functionOptions[self.function])){field.items=view.data.functionOptions[self.function];}} field.render();if(field.type==='image'&&field.value){field.resizeWidget();} return field.$el.html();} return field.getPlaceholder();});Handlebars.registerHelper('includes',function(haystack,needle,options){if(haystack&&(_.has(haystack,needle)||(_.isString(haystack)&&_.isString(needle)&&haystack.toLowerCase().includes(needle.toLowerCase()))||(_.isArray(haystack)&&_.isString(needle)&&haystack.includes(needle)))){return options.fn(this);}else{return options.inverse(this);}});Handlebars.registerHelper('sanitize',function(options){return new Handlebars.SafeString(DOMPurify.sanitize(options.fn(this),{ADD_ATTR:['target']}));});});})(SUGAR.App); /* End of File include/javascript/sugar7/hbs-helpers.js */ (function(app){app.events.on('app:init',function(){_.mixin({moveIndex:function(array,fromIndex,toIndex){array.splice(toIndex,0,_.first(array.splice(fromIndex,1)));return array;}});});})(SUGAR.App); /* End of File include/javascript/sugar7/underscore-mixins.js */ (function(app){var trackFilterDropdown=function(){if(!app.view.views.BaseFilterFilterDropdownView.prototype){return;} var _filterDropdownProto=_.clone(app.view.views.BaseFilterFilterDropdownView.prototype);_.extend(app.view.views.BaseFilterFilterDropdownView.prototype,{handleChange:function(id){_filterDropdownProto.handleChange.apply(this,[id]);this.trackGA(id);},trackGA:function(id){app.analytics.trackEvent('click',id+'Filter-selected',id);}});};var trackFilterFieldAndOperator=function(){var currentFieldName;if(!app.view.views.BaseFilterRowsView.prototype){return;} var _filterFieldOperatorProto=_.clone(app.view.views.BaseFilterRowsView.prototype);_.extend(app.view.views.BaseFilterRowsView.prototype,{handleOperatorSelected:function(e){_filterFieldOperatorProto.handleOperatorSelected.apply(this,[e]);var $el=this.$(e.currentTarget),operator=$el.val();app.analytics.trackEvent(e.type,currentFieldName+"With"+operator,e);},handleFieldSelected:function(e){_filterFieldOperatorProto.handleFieldSelected.apply(this,[e]);var $el=this.$(e.currentTarget),fieldName=$el.val();currentFieldName=fieldName;}});};app.events.on('app:sync:complete',function(){trackFilterDropdown();trackFilterFieldAndOperator();});})(SUGAR.App); /* End of File include/javascript/sugar7/filter-analytics.js */ (function(app){app.events.on('app:init',function(){var getSystemActions=function(){var actions=[{callback:'openConfig',action:'config',name:app.lang.get('LBL_SWEETSPOT_CONFIG'),icon:'sicon-settings'}];return actions;};var hasAccessToAction=function(module,action){if(module&&action.acl_action){if(!app.acl.hasAccess(action.acl_action,module)){return false;} return action;} if(action.acl_action==='admin'&&!app.acl.hasAccessToAny('developer')){return false;} return action;};var getModuleLinks=function(){var actions=[];var moduleList=app.metadata.getModuleNames({filter:'display_tab',access:true});if(app.user.get('type')==='admin'&&app.metadata.getModule('Administration')){moduleList.push('Administration');moduleList=_.uniq(moduleList);} _.each(moduleList,function(module){var moduleMeta=app.metadata.getModule(module);var menuMeta=moduleMeta&&moduleMeta.menu;var headerMeta=menuMeta&&menuMeta.header&&menuMeta.header.meta||[];var sweetspotMeta=menuMeta&&menuMeta.sweetspot&&menuMeta.sweetspot.meta||[];_.each(headerMeta.concat(sweetspotMeta),function(action){if(hasAccessToAction(action.acl_module||module,action)===false){return;} var name;var jsFunc='push';var weight;var bwcModuleRoute='#'+app.bwc.buildRoute(module);var sidecarModuleRoute='#'+module;var isIndexRoute=action.route===sidecarModuleRoute||action.route===bwcModuleRoute;var isCreateRoute=(action.route==='#'+module+'/create');if(isIndexRoute){jsFunc='unshift';name=app.lang.getModuleName(module,{plural:true});weight=10;}else if(isCreateRoute){weight=20;name=app.lang.get(action.label,module)}else{weight=30;name=app.lang.get(action.label,module)} var actionObj={module:module,label:app.lang.getModuleIconLabel(module),name:name,route:action.route,icon:action.icon,weight:weight,};if(action.idm_mode_link&&app.metadata.getConfig().idmModeEnabled){actionObj.route=action.idm_mode_link+'&user_hint='+encodeURIComponent(app.utils.createUserSrn(app.user.id));actionObj.openwindow=true;} if(action.openwindow){actionObj.openwindow=action.openwindow;} actions[jsFunc](actionObj);});});var profileActions=app.metadata.getView(null,'profileactions');_.each(profileActions,function(action){if(hasAccessToAction(action.acl_module,action)===false){return;} var profileActionObj={name:app.lang.get(action.label),route:action.route,icon:action.icon,weight:10};if(action.openwindow){profileActionObj.openwindow=action.openwindow;} actions.push(profileActionObj);});return actions;};app.metadata.getSweetspotActions=function(){var collection={};var actions=getModuleLinks().concat(getSystemActions());_.each(actions,function(action){if(!action.label){action.label=app.lang.getModuleIconLabel(action.name);} collection[action.route||action.callback]=action;});return collection;};});})(SUGAR.App); /* End of File include/javascript/sugar7/sweetspot.js */ (function(app){app.augment('tooltip',{_$currentTip:null,init:function(){if(Modernizr.touch){this._disable();return;} this._enable();},_onShow:function(event){if(event&&event.namespace!=='bs.tooltip'){return;} var target=event.target;var $target=$(target).first();let isChildEllipsed=false;if(target.children.length>0&&target.querySelectorAll(':scope > .text-overflow')){let ellipsedChild=target.querySelectorAll(':scope > .text-overflow').item(0);if(ellipsedChild){isChildEllipsed=ellipsedChild.offsetWidth<ellipsedChild.scrollWidth;}} var showTooltip=($target.attr('rel')==='tooltip'||target.offsetWidth<target.scrollWidth||isChildEllipsed);if(!showTooltip){event.preventDefault();}},_saveTip:function(event){if(event.namespace!=='bs.tooltip'){return;} var $target=$(event.target);this._$currentTip=$.fn.tooltip.Constructor.getInstance($target);$target.on('remove',this.clear);},_disable:function(){var $html=$('html');if(typeof $html.tooltip!=='function'){return;} $html.tooltip('dispose');$html.off('.tooltip');if(!this._tooltip){this._tooltip=$.fn.tooltip;} $.fn.tooltip=function(){return this;};},_enable:function(){$.fn.tooltip=this._tooltip||$.fn.tooltip;var $html=$('html');if(typeof $html.tooltip!=='function'){return;} $html.tooltip({selector:'.ellipsis_inline, [rel=tooltip]',container:'body',trigger:'hover',title:(el)=>{const $el=$(el);let title=$el.attr('data-original-title')||$el.attr('data-bs-original-title')||$el.attr('title');if(title&&$el.attr('data-tooltip-plaintext')==='true'){title=$('<div/>').text(title).html();} return title;},html:true,});_.bindAll(this,'_saveTip','clear');$html.on('show.bs.tooltip',this._onShow);$html.on('shown.bs.tooltip',this._saveTip);$html.on('click.tooltip',this.clear);},clear:function(){if(this._$currentTip&&this._$currentTip._element){this._$currentTip.dispose();} const tooltipEl=$('body > .tooltip');tooltipEl.tooltip('hide');tooltipEl.remove();}});})(SUGAR.App); /* End of File include/javascript/sugar7/tooltip.js */ (function(app){app.events.on("app:login:success",function(){app.cache.set("show_project_import_warning",true);app.cache.set("show_project_export_warning",true);app.cache.set("show_br_import_warning",true);app.cache.set("show_br_export_warning",true);app.cache.set("show_emailtpl_import_warning",true);app.cache.set("show_emailtpl_export_warning",true);});})(SUGAR.App); /* End of File include/javascript/sugar7/import-export-warnings.js */ (function(app){var bindShortcutKeys=function(keys,func,component){var wrapper=_.wrap(func,function(callback){var args=Array.prototype.slice.call(arguments,1);if(!component.disposed){callback.apply(component,args);} return false;});Mousetrap.bind(keys,wrapper);};var unbindShortcutKeys=function(keys){Mousetrap.unbind(keys);};var getShortcutKey=function(id,keys){var shortcuts=app.user.getPreference('shortcuts');return(shortcuts&&shortcuts[id])?shortcuts[id]:keys;};var findCallOnFocus=function(shortcuts,key){var callOnFocus=false,shortcutKey=_.find(shortcuts,function(shortcut,id){return _.contains(getShortcutKey(id,shortcut.keys),key)});if(shortcutKey){callOnFocus=!!shortcutKey.callOnFocus;} return callOnFocus;};var originalStopCallback=Mousetrap.stopCallback;Mousetrap.stopCallback=function(e,element,combo){var isInInputField=function(){return element.tagName==='INPUT'||element.tagName==='SELECT'||element.tagName==='TEXTAREA'||element.isContentEditable;};if(!app.shortcuts.isEnabled()){return true;} if(isInInputField()&&app.shortcuts.shouldCallOnFocus(combo)){$(element).trigger('change');return false;}else{return originalStopCallback(e,element);}};app.events.on('app:login:success',function(){app.shortcuts.enable();});app.events.on('app:logout:success',function(){app.shortcuts.disable();});app.events.once('app:init',function(){app.before('app:view:change',function(){app.shortcuts.clearSession();return true;});});app.augment('shortcuts',{_currentSession:null,_savedSessions:[],_globalShortcuts:{},_enable:false,createSession:function(shortcutIds,layout){var self=this;this.clearSession();this._currentSession=new ShortcutSession(shortcutIds,layout);this._currentSession.activate();layout._dispose=_.wrap(layout._dispose,function(func){var args=Array.prototype.slice.call(arguments,1);func.apply(layout,args);self.deleteSavedSession(layout);});},clearSession:function(){if(this._currentSession){this._currentSession.deactivate();this._currentSession=null;}},register:function(shortcut,keys,func,component,callOnFocus){var session;if(_.isString(shortcut)){app.logger.warn('app.shortcuts.register(id, keys, func, component, callOnFocus) is deprecated and will be removed in 7.9. '+'Please use the app.shortcuts.register(shortcut) method signature.');shortcut={id:shortcut,keys:keys,handler:func,component:component,callOnFocus:callOnFocus};} if(!_.isArray(shortcut.keys)){shortcut.keys=[shortcut.keys];} if(this._isGlobalShortcutKey(shortcut.keys)){return;} session=this._getShortcutSessionForComponent(shortcut.component);if(session){session.register(shortcut);}},registerGlobal:function(shortcut){if(!_.isArray(shortcut.keys)){shortcut.keys=[shortcut.keys];} if(this._isGlobalShortcutKey(shortcut.keys)){return;} this._globalShortcuts[shortcut.id]={keys:shortcut.keys,func:shortcut.handler,component:shortcut.component,description:shortcut.description};if(shortcut.callOnFocus){this._globalShortcuts[shortcut.id].callOnFocus=shortcut.callOnFocus;} bindShortcutKeys(shortcut.keys,shortcut.handler,shortcut.component);},unregister:function(id,component){var session=this._getShortcutSessionForComponent(component);if(session){session.unregister(id);}},saveSession:function(){this._savedSessions.push(this._currentSession);this.clearSession();},restoreSession:function(){if(this._savedSessions.length===0){return;} this.clearSession();this._currentSession=this._savedSessions.pop();if(!this._currentSession){return;} if(this._currentSession.layout.disposed){this.restoreSession();}else{this._currentSession.activate();}},enable:function(){this._enable=true;},disable:function(){this._enable=false;},isEnabled:function(){return this._enable;},getCurrentSession:function(){return this._currentSession;},getLastSavedSession:function(){return _.last(this._savedSessions);},deleteSavedSession:function(layout){var savedSessionToDelete,savedSession;for(var index=0;index<this._savedSessions.length;index++){savedSession=this._savedSessions[index];if(savedSession&&savedSession.layout===layout){savedSessionToDelete=index;break;}} if(!_.isUndefined(savedSessionToDelete)){this._savedSessions.splice(savedSessionToDelete,1);}},saveCustomShortcutKey:function(shortcuts,callback){var self=this,preferences;if(_.isEmpty(shortcuts)){callback();return;} preferences=app.user.get('preferences');if(_.isEmpty(preferences.shortcuts)){preferences.shortcuts={};} _.each(shortcuts,function(shortcut){if(this._isGlobalShortcutId(shortcut.id)){app.logger.error(shortcut.id+' is a global shortcut and cannot be customized.');}else{preferences.shortcuts[shortcut.id]=shortcut.keys;}},this);this.getCurrentSession().deactivate();app.user.updatePreferences(preferences,function(error){self.getCurrentSession().activate();callback(error);});},removeCustomShortcutKeys:function(shortcuts,callback){var self=this,hasChanged=false,preferences=app.user.get('preferences');if(_.isEmpty(preferences.shortcuts)){callback();return;} _.each(shortcuts,function(id){if(preferences.shortcuts[id]){hasChanged=true;delete preferences.shortcuts[id];}});if(hasChanged){this.getCurrentSession().deactivate();app.user.updatePreferences(preferences,function(error){self.getCurrentSession().activate();callback(error);});}},getRegisteredGlobalShortcuts:function(){return _.map(this._globalShortcuts,function(shortcut,id){return{id:id,keys:shortcut.keys,description:shortcut.description};});},shouldCallOnFocus:function(key){var shouldCall=false;if(this._currentSession){shouldCall=this._currentSession.shouldCallOnFocus(key)} if(!shouldCall){shouldCall=findCallOnFocus(this._globalShortcuts,key);} return shouldCall;},_getShortcutSessionForComponent:function(component){var session,parentLayout=app.utils.getParentLayout(component);if(this._currentSession&&this._currentSession.layout===component){session=this._currentSession;}else{session=_.find(this._savedSessions,function(shortcuts){return(shortcuts&&shortcuts.layout===component);});} if(_.isUndefined(session)&&parentLayout){session=this._getShortcutSessionForComponent(parentLayout);} return session;},_isGlobalShortcutKey:function(keys){return!_.every(keys,function(key){return _.every(this._globalShortcuts,function(shortcut){return _.indexOf(shortcut.keys,key)===-1;});},this);},_isGlobalShortcutId:function(id){return!!this._globalShortcuts[id];}},false);var ShortcutSession=function(shortcutIds,layout){this.layout=layout;this._active=false;this._shortcuts={};_.each(shortcutIds,function(id){this._allowShortcut(id);},this);};_.extend(ShortcutSession.prototype,{activate:function(){this.deactivate();this._active=true;_.each(this._shortcuts,function(shortcut,id){var shortcutKey;if(!_.isEmpty(shortcut)){shortcutKey=getShortcutKey(id,shortcut.keys);bindShortcutKeys(shortcutKey,shortcut.func,shortcut.component);}},this);},deactivate:function(){if(this.isActive()){_.each(this._shortcuts,function(shortcuts,id){this._unbindShortcutKeys(id);},this);this._active=false;}},isActive:function(){return this._active;},register:function(shortcut){if(!this._isShortcutAllowed(shortcut.id)||this._isInDashboard(shortcut.component)){return;} if(!_.isArray(shortcut.keys)){shortcut.keys=[shortcut.keys];} this.unregister(shortcut.id);this._bindShortcutKeys(shortcut);},unregister:function(id){if(!this._isShortcutAllowed(id)){return;} if(this.isActive()){this._unbindShortcutKeys(id);} this._shortcuts[id]={};},getRegisteredShortcuts:function(){var registeredShortcuts=[];_.each(this._shortcuts,function(shortcut,id){if(!_.isEmpty(shortcut)){registeredShortcuts.push({id:id,keys:getShortcutKey(id,shortcut.keys),description:shortcut.description});}});return registeredShortcuts;},shouldCallOnFocus:function(key){var shouldCall=false;if(this.isActive()){shouldCall=findCallOnFocus(this._shortcuts,key);} return shouldCall;},_bindShortcutKeys:function(shortcut){var shortcutKey;if(!this._isShortcutAllowed(shortcut.id)){return;} this._shortcuts[shortcut.id].keys=shortcut.keys;this._shortcuts[shortcut.id].func=shortcut.handler;this._shortcuts[shortcut.id].component=shortcut.component;this._shortcuts[shortcut.id].description=shortcut.description;if(shortcut.callOnFocus){this._shortcuts[shortcut.id].callOnFocus=shortcut.callOnFocus;} if(this.isActive()){shortcutKey=getShortcutKey(shortcut.id,shortcut.keys);bindShortcutKeys(shortcutKey,shortcut.handler,shortcut.component);}},_unbindShortcutKeys:function(id){var keysToUnbind;if(this._isShortcutAllowed(id)){keysToUnbind=getShortcutKey(id,this._shortcuts[id].keys);if(keysToUnbind){unbindShortcutKeys(keysToUnbind);}}},_allowShortcut:function(id){this._shortcuts[id]={};},_isShortcutAllowed:function(id){return!_.isUndefined(this._shortcuts[id]);},_isInDashboard:function(component){var layout=component.layout||(!_.isUndefined(component.view)&&component.view.layout);return(layout.type==='dashlet')||(layout.type==='dashboard');}});})(SUGAR.App); /* End of File include/javascript/sugar7/shortcuts.js */ (function(app){app.augment('accessibility',{init:function(app){if(app.accessibility.helpers&&!_.isEmpty(app.accessibility.helpers)){app.view.Component.prototype.initialize=_.wrap(app.view.Component.prototype.initialize,function(func,options){func.call(this,options);this.on('render',function(){app.accessibility.run(this);},this);});}},run:function(component,helper){var helpers=this.whichHelpers(helper);_.each(helpers,function(klass,name){if(_.isFunction(klass.run)){app.logger.debug('Applying accessibility helper `'+name+'`');klass.run(component);}else{app.logger.debug('Unable to apply accessibility helper `'+name+'`');}});},whichHelpers:function(helper){var helpers;if(_.isUndefined(helper)){return app.accessibility.helpers;} if(!_.isArray(helper)){helper=[helper];} helpers=_.reduce(helper,function(memo,name){if(!!app.accessibility.helpers[name]){memo[name]=app.accessibility.helpers[name];} return memo;},{});return helpers;},getElementTag:function($el){var attributes,tagName;tagName=($el.prop('tagName')||'').toLowerCase();attributes=[tagName];if($el[0]&&$el[0].attributes){_.each($el[0].attributes,function(attr){attributes.push('['+attr.name+'="'+attr.value+'"]');});}else if($el.selector){return $el.selector;} return attributes.join('');},handleKeyClick:function(evt,$el){var code=evt.which;if((code===13)||(code===32)){evt.preventDefault();evt.stopPropagation();if(evt.originalEvent&&evt.originalEvent.repeat){return;} $el.click();}}},false);})(SUGAR.App); /* End of File include/javascript/sugar7/accessibility/accessibility.js */ (function(app){app.accessibility=app.accessibility||{};app.accessibility.helpers=app.accessibility.helpers||{};app.accessibility.helpers.click={run:function(component){var self=this,$el,events;if(component instanceof app.view.Component){$el=component.$el;}else if(_.isArray(component)){component.each(function(){self.run(this);});return;}else if(component.length>1){component.each(function(){self.run($(this));});return;}else{$el=component;} events=$._data($el[0]||$el,'events');if(!events||!events.click){app.logger.debug('Found no events on '+app.accessibility.getElementTag($el));return;} _.each(events.click,function(clickEvent){if(clickEvent.selector){$el.find(clickEvent.selector).each(function(){self._makeElementCompliant($(this));});}else{self._makeElementCompliant($el);}});},_isElementCompliant:function($el){var tag=$el.prop('tagName');if(!tag){app.logger.debug('The element does not have a tag name');return true;} switch(tag.toLowerCase()){case'button':case'input':case'select':case'textarea':return true;case'a':return!!($el.attr('href'))||$el.attr('role')==='button';case'area':return!!($el.attr('href'));default:return $el[0].hasAttribute('tabindex');}},_makeElementCompliant:function($el){var role,tagName,tagPretty;role=$el.attr('role');tagName=$el.prop('tagName').toLowerCase();tagPretty=app.accessibility.getElementTag($el);if(this._isElementCompliant($el)){app.logger.debug('Found '+tagPretty+' to be compliant');if(tagName==='a'&&role==='button'&&!$el[0].hasAttribute('tabindex')){$el.attr('tabindex',0);}}else{app.logger.debug('Made '+tagPretty+' compliant');$el.attr('tabindex',-1);}}};})(SUGAR.App); /* End of File include/javascript/sugar7/accessibility/click.js */ (function(app){app.accessibility=app.accessibility||{};app.accessibility.helpers=app.accessibility.helpers||{};app.accessibility.helpers.label={run:function(component){var self=this;if(!(component instanceof app.view.Field)){return;} if(component.label&&component.fieldTag){component.$el.find(component.fieldTag).each(function(){self._makeElementCompliant($(this),component.label);});}},_isElementCompliant:function($el){var ariaLabel,tag;ariaLabel=$el.attr('aria-label');tag=$el.prop('tagName').toLowerCase();return(!_.contains(['input','button','select','textarea'],tag)||!_.isUndefined(ariaLabel));},_makeElementCompliant:function($el,label){if(!this._isElementCompliant($el)){$el.attr('aria-label',label);}}};})(SUGAR.App); /* End of File include/javascript/sugar7/accessibility/label.js */ (function(app){var clipboard;app.events.once('app:init',function(){app.before('app:view:change',function(){app.alert.dismiss('clipboard');return true;});});function triggerEvent(target,event,params){$(target).trigger('clipboard.'+event,params);} app.augment('clipboard',{init:function(){if(clipboard){return;} clipboard=new ClipboardJS('[data-clipboard=enabled]');clipboard.on('success',function(evt){app.alert.show('clipboard',{level:'success',messages:app.lang.get('LBL_TEXT_COPIED_TO_CLIPBOARD_SUCCESS'),autoClose:true});evt.clearSelection();triggerEvent(evt.trigger,'success',evt);});clipboard.on('error',function(evt){app.alert.show('clipboard',{level:'error',messages:app.lang.get('LBL_TEXT_COPIED_TO_CLIPBOARD_ERROR'),});evt.clearSelection();triggerEvent(evt.trigger,'error',evt);});},dispose:function(){if(clipboard){clipboard.destroy();clipboard=undefined;}}},false);})(SUGAR.App); /* End of File include/javascript/sugar7/clipboard.js */ (function initExpressions(app){app.events.on('app:init',function appInit(){SUGAR.expressions.validateExpressionSidecar=function(expression,fieldsArray,moduleName,matchType){try{var varTypeMap={};fieldsArray=fieldsArray?fieldsArray:[];expression=expression?expression:'';_.each(fieldsArray,function getVarTypeMap(fieldData){varTypeMap[fieldData[0]]=fieldData[1];});var tokens=new SUGAR.expressions.ExpressionParser().tokenize(expression);SUGAR.expressions.setReturnTypesSidecar(tokens,varTypeMap);SUGAR.expressions.validateReturnTypesSidecar(tokens);var def=SUGAR.expressions.validateRelateFunctionsSidecar(tokens,moduleName);var returnType=tokens.returnType;if(tokens.name==='related'&&def.type){switch(def.type){case'date':case'datetime':case'datetimecombo':returnType='date';break;case'bool':returnType='boolean';break;default:matchType='';}} if(matchType&&matchType!==returnType){app.alert.show('alert_return_type_missmatch',{level:'error',title:app.lang.get('LBL_INVALID_FORMULA'),messages:app.lang.get('LBL_RETURN_TYPE_MISSMATCH')+' '+matchType,autoClose:true,autoCloseDelay:5000});return false;} return true;}catch(e){app.alert.show('alert_expression_error',{level:'error',title:app.lang.get('LBL_INVALID_FORMULA'),messages:e.message?e.message:e,autoClose:true,autoCloseDelay:5000});return false;}};SUGAR.expressions.setReturnTypesSidecar=function(t,vMap){var see=SUGAR.expressions.Expression;if(t.type==='variable'){if(_.isUndefined(vMap[t.name])){throw'Unknown field: '+t.name;}else if(vMap[t.name]==='relate'){t.returnType=SUGAR.expressions.Expression.GENERIC_TYPE;}else{t.returnType=vMap[t.name];}} if(t.type==='function'){for(var i in t.args){SUGAR.expressions.setReturnTypesSidecar(t.args[i],vMap);} var fMap=SUGAR.FunctionMap;if(_.isUndefined(fMap[t.name])){throw t.name+': No such function defined';} for(var j in see.TYPE_MAP){if(fMap[t.name].prototype instanceof see.TYPE_MAP[j]){t.returnType=j;break;}} if(t.name==='ifElse'){var args=t.args;var returnTypeIndex=2;if(args[1].returnType===args[returnTypeIndex].returnType){t.returnType=args[1].returnType;}} if(!t.returnType){throw t.name+': No known return type!';}}};SUGAR.expressions.validateReturnTypesSidecar=function(t){if(t.type==='function'){for(var i in t.args){SUGAR.expressions.validateReturnTypesSidecar(t.args[i]);} var fMap=SUGAR.FunctionMap;var see=SUGAR.expressions.Expression;if(_.isUndefined(fMap[t.name])){throw t.name+': No such function defined';} var types=fMap[t.name].prototype.getParameterTypes();var count=fMap[t.name].prototype.getParamCount();if(count===see.INFINITY&&t.args.length===0){throw t.name+': Requires at least one parameter';} if(count!==see.INFINITY&&t.args instanceof Array&&t.args.length!==count){throw t.name+': Requires exactly '+count+' parameter(s)';} if(typeof types==='string'){for(var j=0;j<t.args.length;j++){if(!t.args[j].returnType){throw t.name+': No known return type!';} if(!fMap[t.name].prototype.isProperType(new see.TYPE_MAP[t.args[j].returnType](),types)){throw t.name+': All parameters must be of type \''+types+'\'';}}}else{for(var k=0;k<types.length;k++){if(!fMap[t.name].prototype.isProperType(new see.TYPE_MAP[t.args[k].returnType](),types[k])){throw t.name+': The parameter at index '+k+' must be of type '+types[k];}}}}};SUGAR.expressions.validateRelateFunctionsSidecar=function(t,moduleName){if(t.type==='function'){for(var i in t.args){SUGAR.expressions.validateRelateFunctionsSidecar(t.args[i],moduleName);} let relFuncs=['related','rollupAve','rollupMax','rollupMin','rollupSum'];let userFuncs=['currentUserField'];let url;if(relFuncs.includes(t.name)){url='index.php?'+SUGAR.expressions.paramsToUrl({module:'ExpressionEngine',action:'validateRelatedField',tmodule:moduleName,package:'',link:t.args[0].name,related:t.args[1].value});}else if(userFuncs.includes(t.name)){url='index.php?'+SUGAR.expressions.paramsToUrl({module:'ExpressionEngine',action:'validateUserField',package:'',related:t.args[0].value});}else{return true;} var resp=SUGAR.expressions.httpFetchSyncSidecar(url);var def=JSON.parse(resp.responseText);if(typeof def==='string'){throw t.name+': '+def;} let genericTypeFunctions=['related','currentUserField'];let numberTypes=['decimal','int','float','currency'];if(!genericTypeFunctions.includes(t.name)&&def.type&&!numberTypes.includes(def.type)){throw(t.name+': related field '+t.args[1].value+' must be a number');} return def;}};SUGAR.expressions.httpFetchSyncSidecar=function(url,postData,headers){headers=headers||{};var globalXmlhttp=new XMLHttpRequest();var method='GET';if(typeof postData!=='undefined'){method='POST';} try{globalXmlhttp.open(method,url,false);}catch(e){var message='message:'+e.message+':url:'+url;app.alert.show('alert_expression_error',{level:'error',title:app.lang.get('LBL_INVALID_FORMULA'),messages:message,autoClose:true,autoCloseDelay:5000});} if(method==='POST'&&typeof headers['Content-Type']==='undefined'){headers['Content-Type']='application/x-www-form-urlencoded';} for(var header in headers){globalXmlhttp.setRequestHeader(header,headers[header]);} globalXmlhttp.send(postData);var args={responseText:globalXmlhttp.responseText,responseXML:globalXmlhttp.responseXML,request_id:0};return args;};SUGAR.expressions.paramsToUrl=function(params){var parts=[];for(var i in params){if(_.has(params,i)){parts.push(encodeURIComponent(i)+'='+encodeURIComponent(params[i]));}} return parts.join('&');};SUGAR.expressions.arrayIndexOf=function(arr,val,start){if(typeof arr.indexOf==='function'){return arr.indexOf(val,start);} for(var i=start||0,j=arr.length;i<j;i++){if(arr[i]===val){return i;}} return-1;};});})(SUGAR.App); /* End of File include/javascript/sugar7/expressions.js */ (function utils(app){app.Calendar=app.Calendar||{};let utils={};utils.buildUserKeyForStorage=function buildKeyForStorage(componentName){return'Calendar:'+app.user.id+':'+componentName+':storage';};utils.buildUserKeyForShowFilteredRecords=function buildKeyForStorage(componentName){return'Calendar:'+app.user.id+':'+componentName+':applyFilter';};utils.getConfigurationsByKey=function getConfigurationsByKey(key,calendarCategory){let calendarsSaved=app.user.lastState.get(key);let calendarConfigurations={myCalendars:[],otherCalendars:[]};if(typeof calendarsSaved==='object'){if(!_.isEmpty(calendarCategory)){return calendarsSaved[calendarCategory];} if(calendarsSaved.myCalendars.length>0){calendarConfigurations.myCalendars=calendarsSaved.myCalendars;} if(calendarsSaved.otherCalendars.length>0){calendarConfigurations.otherCalendars=calendarsSaved.otherCalendars;}} if(!_.isEmpty(calendarCategory)){return calendarConfigurations[calendarCategory];} return calendarConfigurations;};utils.whiteColor=function whiteColor(c){c=c.substring(1);const rgb=parseInt(c,16);const r=(rgb>>16)&0xff;const g=(rgb>>8)&0xff;const b=(rgb>>0)&0xff;const luma=0.2126*r+0.7152*g+0.0722*b;if(luma<100){return false;} return true;};function hashFnv32a(str,asString,seed){let i;let l;let hval=seed===undefined?0x811c9dc5:seed;for(i=0,l=str.length;i<l;i++){hval^=str.charCodeAt(i);hval+=(hval<<1)+ (hval<<4)+ (hval<<7)+ (hval<<8)+ (hval<<24);} if(asString){return('0000000'+(hval>>>0).toString(16)).substr(-8);} return hval>>>0;} utils.pastelColor=function(str){let hash=hashFnv32a(str);const rHash=Math.abs(hash%200);hash=Math.round(hash / 1000);const gHash=Math.abs(hash%147);hash=Math.round(hash / 1000);const bHash=Math.abs(hash%147);const r=(rHash+50).toString(16);const g=(gHash+70).toString(16);const b=(bHash+70).toString(16);return'#'+r+g+b;};const dateMapping={'Y-m-d':{full:'yyyy-MM-dd',dayAndMonth:'MM-dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'yyyy, MMMM dd',},'m-d-Y':{full:'MM-dd-YYYY',dayAndMonth:'MM-dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'MMMM dd, yyyy',},'d-m-Y':{full:'dd-MM-YYYY',dayAndMonth:'dd-MM',dayAndVerboseMonth:'dd MMMM',fullVerboseMonth:'dd MMMM, yyyy',},'Y/m/d':{full:'yyyy/MM/dd',dayAndMonth:'MM/dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'yyyy, MMMM dd',},'m/d/Y':{full:'MM/dd/yyyy',dayAndMonth:'MM/dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'MMMM dd, yyyy',},'d/m/Y':{full:'dd/MM/yyyy',dayAndMonth:'dd/MM',dayAndVerboseMonth:'dd MMMM',fullVerboseMonth:'dd MMMM, yyyy',},'Y.m.d':{full:'yyyy.MM.dd',dayAndMonth:'MM.dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'yyyy, MMMM dd',},'d.m.Y':{full:'dd.MM.yyyy',dayAndMonth:'dd.MM',dayAndVerboseMonth:'dd MMMM',fullVerboseMonth:'dd MMMM, yyyy',},'m.d.Y':{full:'MM.dd.yyyy',dayAndMonth:'MM.dd',dayAndVerboseMonth:'MMMM dd',fullVerboseMonth:'MMMM dd, yyyy',},};const timeMapping={'H:i':'H:mm','h:ia':'h:mmtt','h:iA':'h:mmtt','h:i a':'h:mm tt','h:i A':'h:mm tt','H.i':'H.mm','h.ia':'h.mmtt','h.iA':'h.mmtt','h.i a':'h.mm tt','h.i A':'h.mm tt'};utils.getKendoDateMapping=function(datePref,interestingParts){return dateMapping[datePref][interestingParts]||dateMapping[datePref].full;};utils.getKendoTimeMapping=function(timePref){return timeMapping[timePref];};app.Calendar.utils=utils;})(SUGAR.App); /* End of File include/javascript/calendar/utils.js */ (function(app){app.events.on('app:init',function(){var plugin={onAttach:function(){this.loadCss();},loadCss:function(cssFiles){var $previouslyAdded;_.each(cssFiles||this.css,function(file){var $link;if(!this.isCssLoaded(file)){if(file.indexOf('.css')===-1){file=file+'.css';} $link=$('<link>',{href:'themes/basehint/'+file,type:'text/css',rel:'stylesheet'});if($previouslyAdded){$previouslyAdded.after($link);}else{$link.prependTo(document.head);} $previouslyAdded=$link;}},this);},isCssLoaded:function(href){return!!_.find(document.styleSheets,function(style){return style.href&&(style.href.indexOf(href)!==-1);});}};app.plugins.register('Stage2CssLoader',['layout','view','field'],plugin);});})(SUGAR.App); /* End of File include/javascript/sugar7/plugins/Stage2CssLoader.js */ (function(app){app.events.on('app:init',function(){app.plugins.register('PushNotifications',['layout','view'],{pushNotificationKey:'',pushNotificationFileName:'',onAttach:function(component){if(this.areDependenciesSet()){this.initialize();}else{app.alert.show('pushnotif_missing_dependencies',{level:'error',messages:app.lang.get('LBL_HINT_PUSH_ERROR',null,component)});}},areDependenciesSet:function(){return typeof this.pushNotificationFilePath==='string'&&this.pushNotificationFilePath.length>0&&typeof this.saveSubscription==='function';},initialize:function(){this.pushMessageSupport=this.hasPushMessagesSupport();if(this.pushMessageSupport){this.setPushNotificationFileName();this.setPushNotificationKey();}},setPushNotificationFileName:function(){this.pushNotificationFileName=_.last(this.pushNotificationFilePath.split('/')).replace('.js','');},setPushNotificationKey:function(){var self=this;app.api.call('GET',app.api.buildURL('stage2/params'),null,{success:function(data){self.pushNotificationKey=data.pushNotificationKey;},error:function(err){app.logger.error('Failed to get Hint params: '+JSON.stringify(err));}});},setupPushNotifications:function(denyPermissionCallback){if(this.pushMessageSupport&&this.pushNotificationKey){if(this.hasNotificationPermission()){this.checkWorkerRegistration();}else{this.warnAboutPermissionRequest();}}},warnAboutPermissionRequest:function(){app.alert.show('pushrequest_confirmation',{level:'confirmation',messages:app.lang.get('LBL_HINT_PUSH_MESSAGES_PERMISSION',this.module),onConfirm:_.bind(this.handlePermissionConfirm,this),onCancel:$.noop});},handlePermissionConfirm:function(){var permission=this.requestPushNotificationPermission();permission.then(_.bind(this.checkWorkerRegistration,this));},requestPushNotificationPermission:function(){var self=this;return new Promise(function(resolve,reject){const permissionResult=Notification.requestPermission(function(result){resolve(result);});if(permissionResult){permissionResult.then(resolve,reject);}}).then(function(permissionResult){if(permissionResult!=='granted'){if(self.handleDeniedPermission){self.handleDeniedPermission();} throw new Error('Permission was not granted.');}});},hasRegisteredWorker:function(registrations){var self=this;return _.some(registrations,function(registration){return registration.active.scriptURL.indexOf(self.pushNotificationFileName)>-1;});},checkWorkerRegistration:function(){var self=this;navigator.serviceWorker.getRegistrations().then(function(registrations){if(!self.hasRegisteredWorker(registrations)){self.registerServiceWorker();}});},registerServiceWorker:function(){navigator.serviceWorker.register(this.pushNotificationFilePath).then(_.bind(this.handleRegisteredWorkerStates,this)).catch(this.handleFailedWorkerRegistration);},handleRegisteredWorkerStates:function(registration){var worker=registration.installing||registration.waiting||registration.active;if(worker){if(worker.state==='activated'){this.subscribeUserToPushNotifications(registration);}else{var self=this;worker.addEventListener('statechange',function(event){if(event.target.state==='activated'){self.subscribeUserToPushNotifications(registration);}});}}},subscribeUserToPushNotifications:function(registration){registration.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:this.urlBase64ToUint8Array(this.pushNotificationKey)}).then(_.bind(this.saveSubscription||$.noop,this)).catch(this.handleFailedWorkerRegistration);},handleFailedWorkerRegistration:function(error){var message=error.message?error.message:JSON.stringify(error);app.logger.error('An error occured while registering a service worker: '.concat(message));},urlBase64ToUint8Array:function(base64String){const padding='='.repeat((4-base64String.length%4)%4);const base64=(base64String+padding).replace(/\-/g,'+').replace(/_/g,'/');const rawData=window.atob(base64);const outputArray=new Uint8Array(rawData.length);for(let i=0;i<rawData.length;++i){outputArray[i]=rawData.charCodeAt(i);} return outputArray;},hasPushMessagesSupport:function(){return('serviceWorker'in navigator)&&('PushManager'in window);},hasNotificationPermission:function(){return Notification.permission==='granted';}});});})(SUGAR.App); /* End of File include/javascript/sugar7/plugins/PushNotifications.js */ (function(app){function isGivenLayout(layoutName){if(app.sideDrawer&&app.sideDrawer.isOpen()){return app.sideDrawer._components[0].name===layoutName;} return app.controller.layout&&app.controller.layout.name===layoutName;} function getView(component,hierarchyPath){while(component&&hierarchyPath.length){component=component.getComponent(hierarchyPath.shift());} return component;} function getPreview(){var previewCmpPath=['sidebar','preview-pane','preview'];return getView(app.drawer,['create'].concat(previewCmpPath))||getView(app.sideDrawer,['record'].concat(previewCmpPath))||getView(app.controller.layout,previewCmpPath);} function _getPreviewPane(){var previewCmpPath=['sidebar','preview-pane'];return getView(app.drawer,['create'].concat(previewCmpPath))||getView(app.sideDrawer,['record'].concat(previewCmpPath))||getView(app.controller.layout,previewCmpPath);} function _getSpecificLayoutPosition(path,layout){const component=path?path._components:[];for(var i=0;i<component.length;i++){if(component[i].label===layout||component[i].name===layout){return i;}} return-1;} function _getNonHintPreview(){var previewPane=_getPreviewPane();var componentIndex=_getSpecificLayoutPosition(previewPane,'preview');if(componentIndex>=0){return previewPane._components[componentIndex];}} function _getHintPreview(){var previewPane=_getPreviewPane();var componentIndex=_getSpecificLayoutPosition(previewPane,'Hint-Tab');if(componentIndex>=0){return previewPane._components[componentIndex];}} function addViewToPanelMeta(preview,cmp,type){var component={context:{forceNew:true}};component[type||'view']=cmp;preview._componentsMeta.push(component);} function isEnrichedModel(model){var enrichedModules=['Leads','Contacts','Accounts'];return _.contains(enrichedModules,model.module);} function isTriggeredOnSubpanel(model){var hasModelFromSubpanel=false;var recordModel=app.sideDrawer&&app.sideDrawer.isOpen()?app.sideDrawer._components[0].model:app.controller.layout.model;var moduleLink=model.link&&model.link.name;if(moduleLink&&isGivenLayout('record')&&recordModel){var relatedCollection=recordModel.getRelatedCollection(moduleLink);var relatedModel=relatedCollection&&relatedCollection.get(model.cid);hasModelFromSubpanel=!!relatedModel;} return hasModelFromSubpanel;} function isTriggeredOnListview(preview){return isGivenLayout('records')&&!isInMergeView(preview);} function isInMergeView(preview){return preview.options.type==='merge-duplicates-preview';} function isCreateLayout(){return!!(getView(app.drawer,['create'])||isGivenLayout('create'));} function isEnrichedRecordView(model){var isEnrichedRecord=isGivenLayout('record')&&isEnrichedModel(model);var dashBoardHeaderPath=['sidebar','dashboard-pane','dashboard','dashboard-headerpane'];var recordLayout=app.sideDrawer&&app.sideDrawer.isOpen()?app.sideDrawer._components[0]:app.controller.layout;var dashBoardHeader=getView(recordLayout,dashBoardHeaderPath);if(isEnrichedRecord&&dashBoardHeader){var dashboardTitle=_.findWhere(dashBoardHeader.fields,{type:'hint-dashboardtitle'});isEnrichedRecord=dashboardTitle&&dashboardTitle.getHintState(dashboardTitle.hintStateKey);} return isEnrichedRecord;} function isHintPreview(preview,model){var doesHintApply=false;var shouldHintBeDisplayed=app.hint.isSugarProSpecialCase()||app.hint.isHintUser();if(isEnrichedModel(model)){doesHintApply=isCreateLayout()||isGivenLayout('search')||isTriggeredOnListview(preview)||isTriggeredOnSubpanel(model)||isEnrichedRecordView(model);} return doesHintApply&&shouldHintBeDisplayed;} function shouldShowRelatedContacts(model){return model.module==='Accounts'&&isGivenLayout('records');} function addHintPreviewComponents(preview,model,collection){preview._componentsMeta=[];addViewToPanelMeta(preview,'hint-preview-header');preview._componentsMeta.push({view:'stage2-preview',});if(app.hint.isHintUser()){if(!isCreateLayout()){if(shouldShowRelatedContacts(model)){addViewToPanelMeta(preview,{type:'hint-panel-header',icon:'user',title:'LBL_HINT_CONTACTS_TITLE'});addViewToPanelMeta(preview,'stage2-related-contacts');} addViewToPanelMeta(preview,'hint-news-panel','layout');addViewToPanelMeta(preview,{type:'hint-panel-header',icon:'history',title:'LBL_HINT_HISTORY_TITLE'});addViewToPanelMeta(preview,'stage2-history');}}} function doesSugerHaveTabbedDashlets(){return app.hint.versionCompare()>=0;} function _tabViewValidationCheck(model){var validModules=['Accounts','Contacts','Leads'];return _.contains(validModules,model.module)&&doesSugerHaveTabbedDashlets();} function addDefaultPreviewComponents(modelName,preview){preview._componentsMeta=app.metadata.getLayout(modelName,'preview').components;} function _editStyles(){var $navTabs;var $tabbableClass;var tabbable=App.sideDrawer&&App.sideDrawer.isOpen()?App.sideDrawer._components[0]._components[0]:App.controller.layout._components[0];var self=tabbable._components[2];var hintTabsHidden=tabbable.$(tabbable.$('.tabbable.hide-tabs.preview-active'));var hintLabelTitle=tabbable.$(tabbable.$('.nav-item'));var hintLabelNonHidden=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs.preview-pane-tabs'));var hintLabelHidden=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs.hide.preview-pane-tabs'));var hintPreviewPosition=_getSpecificLayoutPosition(_getPreviewPane(),'Hint-Tab')+1;self.$(hintLabelTitle[hintPreviewPosition]).addClass('hint-nav-tab');if(hintLabelHidden.length){hintLabelHidden.removeClass('hide');hintLabelTitle[hintPreviewPosition].children[0].innerText=app.lang.get('LBL_HINT_PANEL');}else if(hintLabelNonHidden.length){hintLabelTitle[hintPreviewPosition].children[0].innerText=app.lang.get('LBL_HINT_PANEL');} if(hintTabsHidden.length){hintTabsHidden.removeClass('hide-tabs');} self.$('li[data-bs-toggle="tab"]').on('shown.bs.tab',function(e){var tabName=$(e.target.parentElement).data('tab-name');$navTabs=$(e.target).parents('.nav-tabs');$tabbableClass=$(e.target).parents('.tabbable');$navTabs.addClass('preview-pane-tabs',tabName==='preview');$tabbableClass.addClass('preview-active',tabName==='preview');});} function _editStylesHintUndo(){var tabbable=App.sideDrawer&&App.sideDrawer.isOpen()?App.sideDrawer._components[0]._components[0]:App.controller.layout._components[0];var hintTabs=tabbable.$(tabbable.$('.tabbable.preview-active'));var hintLabel=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs.preview-pane-tabs'));if(hintLabel.length){hintLabel.addClass('hide');} if(hintTabs.length){hintTabs.addClass('hide-tabs');} if(tabbable._components){var self=tabbable._components[2];var previewPosition=_getSpecificLayoutPosition(_getPreviewPane(),'preview');var hintPreviewPosition=_getSpecificLayoutPosition(_getPreviewPane(),'Hint-Tab');if(previewPosition>=0&&self){var nonHintSubmodulePreview=self.$(self.$('li')[previewPosition]).hasClass('active');var nonHintSubmodulePreview2=self.$(self.$('.tab-pane')[previewPosition]).hasClass('active');if(!nonHintSubmodulePreview&&!nonHintSubmodulePreview2){self.$(self.$('li')[previewPosition]).addClass('active');self.$(self.$('.tab-pane')[previewPosition]).addClass('active');}} if(hintPreviewPosition>=0){var hintPreviewChosen=self.$(self.$('li')[hintPreviewPosition]).hasClass('active');var hintPreviewChosen2=self.$(self.$('.tab-pane')[hintPreviewPosition]).hasClass('active');if(hintPreviewChosen&&hintPreviewChosen2){self.$(self.$('li')[hintPreviewPosition]).removeClass('active');self.$(self.$('.tab-pane')[hintPreviewPosition]).removeClass('active');}}}} function _editStylesPreviewUndo(){var tabbable=App.sideDrawer&&App.sideDrawer.isOpen()?App.sideDrawer._components[0]._components[0]:App.controller.layout._components[0];var hintTabs=tabbable.$(tabbable.$('.tabbable.preview-active'));var hintLabel=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs.preview-pane-tabs'));if(hintLabel.length){hintLabel.addClass('hide');} if(hintTabs.length){hintTabs.addClass('hide-tabs');} var self=tabbable._components[2];var previewPosition=_getSpecificLayoutPosition(_getPreviewPane(),'preview');var hintPreviewPosition=_getSpecificLayoutPosition(_getPreviewPane(),'Hint-Tab');if(hintPreviewPosition>=0){var nonHintSubmodulePreview=self.$(self.$('li')[hintPreviewPosition]).hasClass('active');var nonHintSubmodulePreview2=self.$(self.$('.tab-pane')[hintPreviewPosition]).hasClass('active');if(!nonHintSubmodulePreview&&!nonHintSubmodulePreview2){self.$(self.$('li')[hintPreviewPosition]).addClass('active');self.$(self.$('.tab-pane')[hintPreviewPosition]).addClass('active');}} if(previewPosition>=0){var hintPreviewChosen=self.$(self.$('li')[previewPosition]).hasClass('active');var hintPreviewChosen2=self.$(self.$('.tab-pane')[previewPosition]).hasClass('active');if(hintPreviewChosen&&hintPreviewChosen2){self.$(self.$('li')[previewPosition]).removeClass('active');self.$(self.$('.tab-pane')[previewPosition]).removeClass('active');}}} function _removeExtraStyles(){var tabbable=App.sideDrawer&&App.sideDrawer.isOpen()?App.sideDrawer._components[0]._components[0]:App.controller.layout._components[0];var hintLabel=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs')[3]);var addHideClassOnce=tabbable.$(tabbable.$('.nav.nav-tabs.related-tabs.hide')[3]).hasClass('hide');if(hintLabel.length&&!(addHideClassOnce)){hintLabel.addClass('hide');}} function togglePreview(model,collection){var preview;var modelName=model.module;if(app.hint.isHintUser()){var isRecordViewlayoutType=SUGAR.App.sideDrawer&&SUGAR.App.sideDrawer.isOpen()?SUGAR.App.sideDrawer._components[0].type==='record':SUGAR.App.controller.layout.type==='record';var hintViewInTab=app.hint.shouldUseOldHintPreview(modelName);if(_tabViewValidationCheck(model)&&!isRecordViewlayoutType){_editStyles();preview=_getHintPreview();}else if(_tabViewValidationCheck(model)&&hintViewInTab){_editStyles();preview=_getHintPreview();}else if(_tabViewValidationCheck(model)&&!hintViewInTab){_editStylesPreviewUndo();preview=_getHintPreview();}else if(doesSugerHaveTabbedDashlets()){_editStylesHintUndo();preview=_getNonHintPreview();}else{_removeExtraStyles();preview=getPreview();}}else if(app.hint.isSugarProSpecialCase()){_editStyles();preview=_getHintPreview();}else{_editStylesHintUndo();preview=_getNonHintPreview();} if(!preview||!preview._isActive()){return;} var hasComponents=!_.isEmpty(preview._components);var isSameModel=model==preview.context.get('model');var modelChanged=preview.context.get('module')!==modelName;if(!isSameModel&&(!hasComponents||modelChanged)){if(isHintPreview(preview,model)){addHintPreviewComponents(preview,model,collection);}else{addDefaultPreviewComponents(modelName,preview);}}} app.events.on('preview:render',togglePreview);})(SUGAR.App); /* End of File include/javascript/hint/hint-preview.js */ SUGAR.App.events.on('router:init',function(){SUGAR.App.router.route('hint/data-enrichment','hint-data-enrichment',function(){SUGAR.App.drawer.open({layout:'hint-data-enrichment-drawer',context:{model:SUGAR.App.data.createBean('Accounts'),title:SUGAR.App.lang.get('LBL_HINT_CONFIG_TITLE')}});});SUGAR.App.router.route('hint/config','hint-config',function(){SUGAR.App.drawer.open({layout:'hint-config-drawer',context:{model:SUGAR.App.data.createBean(),title:SUGAR.App.lang.get('LBL_HINT_CONFIG_TITLE','Administration')}});});SUGAR.App.router.route('hint/insights/resync','hint-insights-resync',function(){SUGAR.App.alert.show('resync_warning',{level:'confirmation',title:SUGAR.App.lang.get('LBL_HINT_RESYNC_NOTIFICATION_TITLE','Administration'),messages:SUGAR.App.lang.get('LBL_HINT_RESYNC_NOTIFICATION_DESCRIPTION','Administration'),onConfirm:function(){console.log('Do something for resync confirm');SUGAR.App.api.call('create',SUGAR.App.api.buildURL('hint/insights/resync'),{},{success:function(){console.log('Success resyncing Hint');SUGAR.App.router.navigate('',{trigger:false});},error:function(err){console.log('Error resyncing Hint',err);SUGAR.App.router.navigate('',{trigger:false});}});},onCancel:function(){SUGAR.App.router.navigate('',{trigger:false});}});});}); /* End of File include/javascript/hint/hint-routes.js */ (function(app){var hint=(function(){var getPanelDefinitionFieldsByName;setDefaultValuesForFields=function(field,module){switch(field.name){case'hint_account_website':return'www.example.net';case'account_name':return'Example Corp';case'full_name':return'Jon Doe';case'title':return'President';default:return field.label;}};getPanelDefinitionFieldsByName=function(module,panelName){var fields=[];var viewName=module.toLowerCase()==='accounts'?'stage2-account-preview':'stage2-preview';var refPanels=app.metadata.get(module).views[viewName].meta.panels;var panels=JSON.parse(JSON.stringify(refPanels));_.each(panels,function(panel){if(panel.name!==panelName){return;} _.each(panel.fields,function(field){field.label=app.lang.get(field.label,module);field.value=setDefaultValuesForFields(field,module);if(field.label){fields.push(field);}});});return fields;};return{getAllFieldsForView:function(module){var fields={};var allFields=this.getModuleFieldsAvailableForSelection(module);_.each(allFields,function(field){field.value=setDefaultValuesForFields(field,module);fields[field.name]=field;});return fields;},getModuleFieldsAvailableForSelection:function(module){var fields=[];var refPanels=App.metadata.getModule(module).views.record.meta.panels;var panels=JSON.parse(JSON.stringify(refPanels));_.each(panels,function(panel){_.each(panel.fields,function(field){if(typeof(field.readonly)!=='undefined'&&field.readonly){return;} if(!field.label||field.label===''){console.log('Missing field for label: '+field.name);return;} field.label=app.lang.get(field.label,module);fields.push(field);});});if(module=='Accounts'){var allDefaultFields=this.getAccountDefaultBasicPanelFields().concat(this.getAccountDefaultExpandedPanelFields());}else{var allDefaultFields=this.getPeopleDefaultBasicPanelFields(module).concat(this.getPeopleDefaultExpandedPanelFields(module));} var allFieldsWithDups=_.union(fields,allDefaultFields);fields=_.uniq(allFieldsWithDups,false,function(item){return item.name;});fields=_.sortBy(fields,function(f){return f.label;});return fields;},getPanelFieldsFromConfiguration:function(module,panelType,defaultPanel,otherPanel){var metdata=app.modules.metadata.getModule(module);if(metdata&&metdata.config&&typeof(metdata.config.hintConfig)!=='undefined'&&typeof(metdata.config.hintConfig[panelType])!=='undefined'){var panelFields=[];var fieldDefinitions=this.getAllFieldsForView(module);var savedFields=metdata.config.hintConfig[panelType];for(var $x=0;$x<savedFields.length;$x++){var fieldName=savedFields[$x];var existsInBasicPanel=_.find(defaultPanel,function(field){return field.name==fieldName;});if(existsInBasicPanel){panelFields.push(existsInBasicPanel);continue;} var existsInOtherPanel=_.find(otherPanel,function(field){return field.name==fieldName;});if(existsInOtherPanel){panelFields.push(existsInOtherPanel);continue;} if(fieldDefinitions[fieldName]){panelFields.push(fieldDefinitions[fieldName]);}} if(module=='Accounts'){var allDefaultFields=this.getAccountDefaultBasicPanelFields().concat(this.getAccountDefaultExpandedPanelFields());var allDefaultFieldsByKey={};_.each(allDefaultFields,function(field){allDefaultFieldsByKey[field.name]=field;});var attributesToCopy=['person_name','person_label'];_.each(panelFields,function(field){var fieldDefaultPanelDefinition=allDefaultFieldsByKey[field.name];if(fieldDefaultPanelDefinition){for(var x=0;x<attributesToCopy.length;x++){var key=attributesToCopy[x];if(typeof(fieldDefaultPanelDefinition[key])!=='undefined'){field[key]=fieldDefaultPanelDefinition[key];}}}});} if(panelType==='expanded'){var excludedFields=['name','website'];panelFields=_.reduce(excludedFields,function(fields,fieldName){return _.without(fields,_.findWhere(fields,{name:fieldName}));},panelFields);} return panelFields;}else{return defaultPanel;}},getFieldDefinitionFromDefaultPanel:function(module,fieldName){var refAccountMetadata=app.metadata.getView(null,'stage2-account-preview').panels;var refPeopleMetadata=app.metadata.getView(null,'stage2-preview').panels;var accountMetadata=JSON.parse(JSON.stringify(refAccountMetadata));var peopleMetadata=JSON.parse(JSON.stringify(refPeopleMetadata));var metadataToParse=module=='Accounts'?accountMetadata:peopleMetadata;var result=false;_.every(metadataToParse,function(panel){result=_.find(panel.fields,function(field){return field.name&&field.name==fieldName;});return!result;});return result;},getPanelMetadata:function(module){var originalModule=SUGAR.App.sideDrawer&&SUGAR.App.sideDrawer.isOpen()?SUGAR.App.sideDrawer._components[0].module:SUGAR.App.controller.layout.model.module;var isPersonOrientedModule=!_.includes(['Accounts','Administration'],originalModule);var panelToMapping={'company_info':this.getAccountBasicPanelFields(),'company_extended':this.getAccountExpandedPanelFields(),'contacts_basic':this.getPeopleBasicPanelFields(module),'contacts_extended':this.getPeopleExpandedPanelFields(module)};var refAccountMetadata=app.metadata.getView(null,'stage2-account-preview').panels;var refPeopleMetadata=app.metadata.getView(null,'stage2-preview').panels;var accountMetadata=JSON.parse(JSON.stringify(refAccountMetadata));var peopleMetadata=JSON.parse(JSON.stringify(refPeopleMetadata));var metdataToParse=module=='Accounts'?accountMetadata:peopleMetadata;for(var x=0;x<metdataToParse.length;x++){var tmpPanel=metdataToParse[x];if(panelToMapping[tmpPanel.name]){tmpPanel.fields=panelToMapping[tmpPanel.name];if(module=='Contacts'||module=='Leads'){var phoneWorkFieldIndex=_.findIndex(tmpPanel.fields,function(f){return f.name=='phone_work';});var educationIndex=_.findIndex(tmpPanel.fields,function(f){return f.name=='hint_education';});var secondEducationIndex=_.findIndex(tmpPanel.fields,function(f){return f.name=='hint_education_2';});if(educationIndex>=0&&secondEducationIndex<0){tmpPanel.fields.splice(++educationIndex,0,this.getFieldDefinitionFromDefaultPanel(module,'hint_education_2'));} if(tmpPanel.name=='company_extended'||tmpPanel.name=='company_info'){_.each(tmpPanel.fields,function(field){if(typeof(field.person_name)!=='undefined'){field.name=field.person_name;} if(field.name==='annual_revenue'&&isPersonOrientedModule){field.name='hint_account_annual_revenue';} if(typeof(field.person_label)!=='undefined'){field.label=field.person_label;}});}} _.each(tmpPanel.fields,function(field){if(field.name==='sic_code'&&originalModule==='Accounts'){field.name='hint_account_sic_code_label';}});}} return metdataToParse;},getPeopleDefaultBasicPanelFields:function(module){var fields=getPanelDefinitionFieldsByName(module,'contacts_basic');return this.filterPersonPanelFields(fields);},getPeopleDefaultExpandedPanelFields:function(module){var fields=getPanelDefinitionFieldsByName(module,'contacts_extended');return this.filterPersonPanelFields(fields);},getAccountDefaultBasicPanelFields:function(){return getPanelDefinitionFieldsByName('accounts','company_info');},getAccountDefaultExpandedPanelFields:function(){return getPanelDefinitionFieldsByName('accounts','company_extended');},getAccountBasicPanelFields:function(){var module='Accounts';var panelType='basic';var defaultPanel=this.getAccountDefaultBasicPanelFields();var otherPanel=this.getAccountDefaultExpandedPanelFields();return this.getPanelFieldsFromConfiguration(module,panelType,defaultPanel,otherPanel);},getAccountExpandedPanelFields:function(){var module='Accounts';var panelType='expanded';var defaultPanel=this.getAccountDefaultExpandedPanelFields();var otherPanel=this.getAccountDefaultBasicPanelFields();return this.getPanelFieldsFromConfiguration(module,panelType,defaultPanel,otherPanel);},getPeopleExpandedPanelFields:function(module){var panelType='expanded';var defaultPanel=this.getPeopleDefaultExpandedPanelFields(module);var otherPanel=this.getPeopleDefaultBasicPanelFields(module);var fields=this.getPanelFieldsFromConfiguration(module,panelType,defaultPanel,otherPanel);return this.filterPersonPanelFields(fields);},getPeopleBasicPanelFields:function(module){var panelType='basic';var defaultPanel=this.getPeopleDefaultBasicPanelFields(module);var otherPanel=this.getPeopleDefaultExpandedPanelFields(module);var fields=this.getPanelFieldsFromConfiguration(module,panelType,defaultPanel,otherPanel);return this.filterPersonPanelFields(fields);},filterPersonPanelFields:function(fields){fields=_.without(fields,_.findWhere(fields,{name:'hint_phone_1'}));fields=_.without(fields,_.findWhere(fields,{name:'hint_phone_2'}));return _.without(fields,_.findWhere(fields,{name:'hint_education_2'}));},getVisibleFieldsFromAllPannelsForDefaultSelection:function(module){var basicFields=[];var extendedFields=[];switch(module.toLowerCase()){case'accounts':basicFields=app.hint.getAccountBasicPanelFields();extendedFields=app.hint.getAccountExpandedPanelFields();break;default:basicFields=app.hint.getPeopleBasicPanelFields(module);extendedFields=app.hint.getPeopleExpandedPanelFields(module);} return basicFields.concat(extendedFields);},getBasicViewDefaultFields:function(module){var panelMapping={'Accounts':{view:'stage2-account-preview',panelFields:['company_extended','company_info','company_header']},'Contacts':{view:'stage2-preview',panelFields:['panel_header','contacts_basic','contacts_extended']},'Leads':{view:'stage2-preview',panelFields:['panel_header','contacts_basic','contacts_extended']},};var fields=[];var panelName=panelMapping[module].view;var refPanels=app.metadata.get(module).views[panelName].meta.panels;var panels=JSON.parse(JSON.stringify(refPanels));if(panelName&&panels){_.each(panels,function(panel){if(_.contains(panelMapping[module].panelFields,panel.name)){fields=fields.concat(panel.fields);}});} return fields;},getPanelsForHintEnrichFields:function(module){var panelMapping={'Accounts':{view:'stage2-account-preview',panelFields:['company_extended','company_info','company_header']},'Contacts':{view:'stage2-preview',panelFields:['panel_header','contacts_basic','contacts_extended']},'Leads':{view:'stage2-preview',panelFields:['panel_header','contacts_basic','contacts_extended']},};var fields=[];var results=[];var allfields=this.getModuleFieldsAvailableForSelection(module);var panelName=panelMapping[module].view;var refPanels=app.metadata.get(module).views[panelName].meta.panels;var panels=JSON.parse(JSON.stringify(refPanels));_.each(panels,function(panel){if(panel.fields){fields=fields.concat(panel.fields);}});for(let i=0;i<allfields.length;i++){if(allfields[i].name==='picture'){results.push(allfields[i]);} for(var j=0;j<fields.length;j++){if(allfields[i].name===fields[j].name){results.push(allfields[i]);}}} return results;},versionCompare:function(validSugarVersion,shouldDisplayLicenseErrMessage,sugarVersion){validSugarVersion=validSugarVersion||'9.1.0';sugarVersion=sugarVersion||app.metadata.getServerInfo().version;var isCreateDrawerOpen=app.drawer;if(!shouldDisplayLicenseErrMessage&&isCreateDrawerOpen&&!_.isEmpty(isCreateDrawerOpen._events.render[0].ctx._components)){return-1;} if(validSugarVersion===sugarVersion){return 0;} if(sugarVersion){var versionLimit=validSugarVersion.split('.');var currentSugarVerion=sugarVersion.split('.');var len=Math.min(versionLimit.length,currentSugarVerion.length);for(var i=0;i<len;i++){if(parseInt(versionLimit[i])>parseInt(currentSugarVerion[i])){return-1;} if(parseInt(versionLimit[i])<parseInt(currentSugarVerion[i])){return 1;}} if(versionLimit.length>currentSugarVerion.length){return-1;} if(versionLimit.length<currentSugarVerion.length){return 1;} return 1;} return-1;},shouldUseOldHintPreview:function(modelName){var layout=SUGAR.App.sideDrawer&&SUGAR.App.sideDrawer.isOpen()?SUGAR.App.sideDrawer._components[0]:SUGAR.App.controller.layout;if(layout&&modelName){var isRecordViewlayoutType=layout.type==='record';var mainLayoutModuleName=layout.model.module;var modelName=modelName;if(!isRecordViewlayoutType){return true;} return isRecordViewlayoutType&&(modelName!==mainLayoutModuleName);}},isSugarProSpecialCase:function(){var sugarFlavor=SUGAR.App.metadata.getServerInfo().flavor;return this.versionCompare('10.3.0',true)>=0&&sugarFlavor==='PRO';},deepFreeze:function(objToFreeze){var self=this;Object.keys(objToFreeze).forEach(function(prop){if(typeof objToFreeze[prop]==='object'&&!Object.isFrozen(objToFreeze[prop])){self.deepFreeze(objToFreeze[prop]);}});return Object.freeze(objToFreeze);},isHintUser:function(){return app.user.hasLicense('HINT');},isListView:function(){var layout=app.controller.layout;var isCreateDrawerActive=app.drawer.isActive();if((layout.type==='search')&&isCreateDrawerActive&&(this.versionCompare()<0)){return true;} return false;},isDarkMode:function(){if(app.utils.isDarkMode()){return app.utils.isDarkMode();} return false;},isEnrichedModel:function(module){var enrichedModules=['Leads','Contacts','Accounts'];return _.contains(enrichedModules,module);},};})();app.hint=hint;})(SUGAR.App); /* End of File include/javascript/hint/hint.js */ (function(app){app.events.on('app:init',function(){Handlebars.registerHelper('toUpperCase',function(str){if(!str){return str;} return str.toUpperCase();});Handlebars.registerHelper('hint_gt',function(a,b){var next=arguments[arguments.length-1];return(a>b)?next.fn(this):next.inverse(this);});Handlebars.registerHelper('hint_safeUrl',function(url){if(url){if(!url.match(/^([a-zA-Z]+):/)){url='http://'+url;} var whiteList=app.config.allowedLinkSchemes;var filteredWhitelist=whiteList.filter(function(scheme){return url.toLowerCase().indexOf(scheme+'://')===0;});if(!filteredWhitelist.length){url='#';}} return encodeURI(url);});Handlebars.registerHelper('flexibleDashboards',function(){return app.hint.versionCompare('10.2.0')>-1;});});function getActiveLayout(module,view,layout,components){_.each(components,function(cmp){if(cmp.module===module&&cmp.type===view){layout=cmp;}});if(!layout){_.each(components,function(cmp){var shouldSearchDeeper=!layout&&cmp._components&&cmp._components.length>0;if(shouldSearchDeeper){layout=getActiveLayout(module,view,layout,cmp._components);}});} return layout;} function setAccountNameChangeListener(module,view){if(module==='Contacts'&&view==='create'&&!_inDrawer(module)){var createView;var createLayout=app.drawer.getComponent('create');if(!createLayout){var mainComponents=app.controller.layout._components;createLayout=getActiveLayout(module,view,null,mainComponents);createView=createLayout.layout;}else{createView=createLayout.getComponent('sidebar').getComponent('main-pane');} createLayout.model.on('change:account_name',function(){var hintModel=_.first(createView.collection.models);app.events.trigger('preview:close');app.events.trigger('preview:render',hintModel);app.events.trigger('hint:user-input',true);});}} function _inDrawer(expectedModule){var comps=app.additionalComponents;if(comps&&comps.drawer&&comps.drawer._components&&comps.drawer._components.length>0){const drawerComp=comps.drawer._components[0];return drawerComp.module!=expectedModule;} return false;} app.events.on('app:view:change',function(view){var _module=app.controller.context.get('module');setAccountNameChangeListener(_module,view);});})(SUGAR.App); /* End of File include/javascript/hint/stage2-handlebar-helpers.js */ (function(app){app.events.on('router:init',function(){var routes=[{name:'notification-preferences',route:'notification-preferences',callback:function(){app.controller.loadView({module:'Home',layout:'stage2-news-preferences-drawer'});}}];app.router.addRoutes(routes);});})(SUGAR.App); /* End of File include/javascript/notification-preferences.js */ (function(app){app.events.on('app:init',function(){app.plugins.register('ReportsPanel','view',{_panelEventMapping:{'rows-columns':'report:data:table:loaded','summation':'report:data:table:loaded','summation-details':'report:data:table:loaded','matrix':'report:data:table:loaded','report-chart':'report:data:chart:loaded','report-filters':'report:data:filters:loaded',},onAttach:function(){if(_.isFunction(this._beforeInit)){this._beforeInit();} this.listenTo(this,'init',function(){if(_.isFunction(this._initProperties)){this._initProperties();} const dataLoadedEvent=this._panelEventMapping[this.name];const refreshEventName='report:refresh';this.listenTo(this.context,dataLoadedEvent,this._showLoadingScreen,this);this.listenTo(this.context,refreshEventName,this._loadReportPanelData,this);if(_.isFunction(this._registerEvents)){this._registerEvents();} this._loadReportPanelData();},this);this.listenTo(this,'render',function(){if(this.context.get('previewMode')){if(_.isFunction(this._setupPreviewReportPanel)&&!this._previewModeLoaded){this._previewModeLoaded=true;this._setupPreviewReportPanel();} this._showLoadingScreen(false);}},this);},_loadReportPanelData:function(){if(this.context.get('previewMode')){return;} if(_.isFunction(this._loadReportData)){this._loadReportData();}},_getCustomFiltersMeta:function(customOptions,stateKey){let filters={};if(!customOptions){return filters;} if(_.has(customOptions,'filtersDef')&&customOptions.filtersDef){filters=this._applyDashboardFilters(customOptions.filtersDef);} if(!stateKey){return filters;} const lastState=app.user.lastState.get(stateKey);if(_.has(lastState,'filtersDef')){filters=this._applyDashboardFilters(lastState.filtersDef);} return filters;},_applyDashboardFilters:function(filters){const customFilters=app.utils.deepCopy(filters);const dashletFilters=customFilters.Filter_1;const customContainer=this.closestComponentByType(this.layout,'dashlet-grid-wrapper');let dashboardFilterGroups=customContainer.model.get('metadata').filters;const dashletId=customContainer.el.getAttribute('data-gs-id');const dashboardId=customContainer.model.get('id');const userDashboardFiltersSetup=this._getUserDashboardLastState(dashboardId);if(!_.isEmpty(userDashboardFiltersSetup)){dashboardFilterGroups=userDashboardFiltersSetup.filters;} _.each(dashboardFilterGroups,(dashboardFilterGroup)=>{_.each(dashboardFilterGroup.fields,_.bind(this._applyFiltersFields,this,dashletId,dashletFilters,dashboardFilterGroup));});return customFilters;},_applyFiltersFields:function(dashletId,dashletFilters,dashboardFilterGroup,dashboardFilterField){_.each(dashletFilters,(dashletFilter,dashletFilterKey)=>{if(dashletFilterKey==='operator'){return;} if(!_.isEmpty(dashletFilter.operator)){this._applyFiltersFields(dashletId,dashletFilter,dashboardFilterGroup,dashboardFilterField);}else if(dashboardFilterField.dashletId===dashletId&&dashboardFilterField.fieldName===dashletFilter.name&&dashboardFilterField.tableKey===dashletFilter.table_key){const inputValues=4;for(let inputValueIdx=0;inputValueIdx<inputValues;inputValueIdx++){dashletFilter[`input_name${inputValueIdx}`]='';} _.each(dashboardFilterGroup.filterDef,(propertyValue,propertyKey)=>{dashletFilter[propertyKey]=propertyValue;});}});},closestComponentByType:function(container,type){if(!container){return;} if(container.type===type){return container;} return this.closestComponentByType(container.layout,type);},_getUserDashboardLastState:function(dashboardId){const userDashboardStateKey=this._getUserDashboardLastStateKey(dashboardId);const dashboardFiltersStored=app.user.lastState.get(userDashboardStateKey);return dashboardFiltersStored;},_getUserDashboardLastStateKey:function(dashboardId){const dashboardKey=`Dashboards:${dashboardId}`;const dashboardComponentKey='dashboard-filters';const lastStateKey=app.user.lastState.buildKey(dashboardComponentKey,app.user.id,dashboardKey);return lastStateKey;},_getCustomReportMeta:function(customReportDef,lastStateKey){let customMeta={};if(customReportDef){if(_.has(customReportDef,'summaryColumns')&&!_.isEmpty(customReportDef.summaryColumns)){customMeta.summaryColumns=customReportDef.summaryColumns;} if(_.has(customReportDef,'displayColumns')&&!_.isEmpty(customReportDef.displayColumns)){customMeta.displayColumns=customReportDef.displayColumns;} if(_.has(customReportDef,'fullTableList')&&!_.isEmpty(customReportDef.fullTableList)){customMeta.fullTableList=customReportDef.fullTableList;} if(_.has(customReportDef,'groupDefs')&&!_.isEmpty(customReportDef.groupDefs)){customMeta.groupDefs=customReportDef.groupDefs;}} customMeta.filtersDef=this._getCustomFiltersMeta(customReportDef,lastStateKey);return customMeta;},_adjustLoadingWidgetSize:function(loadingElementType){if(this.disposed){return;} const loadingWidget=this.$el.parentsUntil('.grid-stack-item').find(`[data-widget=report-loading][data-type=${loadingElementType}]`);const loadingWidgetParent=loadingWidget.parent();const loadingWidetParentWidth=loadingWidgetParent.width();const loadingWidetParenHeight=loadingWidgetParent.height();if(loadingWidetParentWidth&&loadingWidetParentWidth>0&&loadingWidetParenHeight>0){loadingWidget.width(loadingWidetParentWidth);loadingWidget.height(loadingWidetParenHeight);}},_showLoadingScreen:function(show,type=false){if(this.disposed){return;} let loadingEl;if(type){loadingEl=this.$el.parentsUntil('.grid-stack-item').find(`[data-widget=report-loading][data-type=${type}]`);}else{loadingEl=this.$el.parentsUntil('.grid-stack-item').find('[data-widget=report-loading]');} if(show&&_.isBoolean(show)){loadingEl.show();if(_.isFunction(this._showAdditionalComponents)){this._showAdditionalComponents();}}else{loadingEl.hide();if(_.isFunction(this._hideAdditionalComponents)){this._hideAdditionalComponents();} this.context.trigger('refresh-results-complete');} if(!show){this.context.trigger('dashlet-finished-loading');}},});});})(SUGAR.App); /* End of File include/javascript/sugar7/plugins/ReportsPanel.js */ (function(app){app.events.on('app:init',function(){app.plugins.register('ReportExport','view',{exportToPdf:function(options){if(!options){options={};} let queryParams={};const reportData=this.context.get('data');const hasChart=this.context.get('reportHasChart');if(reportData&&_.has(reportData,'orderBy')){queryParams.orderBy=reportData.orderBy;} if(hasChart){queryParams.shouldHaveChartCanvas=true;} let reportId=this.context.get('model').get('id');if(!reportId&&this.layout&&_.has(this.layout,'model')){reportId=this.layout.model.get('report_id');} let url=app.api.buildURL('Reports',reportId+'/'+'base64',null,queryParams);app.alert.show('export-to-pdf',{level:'process',title:app.lang.get('LBL_EXPORT_PDF','Reports'),});this.$('[data-content=report-export-modal]').hide();const completeCallback=options.completeCallback||this.exportCompleteCallback;const errorCallback=options.exportErrorCallback||this.exportErrorCallback;app.api.call('read',url,{},{complete:_.bind(completeCallback,this,'pdf'),error:_.bind(errorCallback,this,'pdf'),});},exportToCsv:function(options){if(!options){options={};} let queryParams={};const reportData=this.context.get('data');if(reportData&&_.has(reportData,'orderBy')){queryParams.orderBy=reportData.orderBy;} let reportId=this.context.get('model').get('id');if(!reportId&&this.layout&&_.has(this.layout,'model')){reportId=this.layout.model.get('report_id');} let url=app.api.buildURL('Reports',reportId+'/'+'csv',null,queryParams);app.alert.show('export-to-csv',{level:'process',title:app.lang.get('LBL_EXPORT_CSV','Reports'),});this.$('[data-content=report-export-modal]').hide();const completeCallback=options.completeCallback||this.exportCompleteCallback;const errorCallback=options.exportErrorCallback||this.exportErrorCallback;app.api.call('read',url,{},{complete:_.bind(completeCallback,this,'csv'),error:_.bind(errorCallback,this,'csv'),});},downloadFileLocally:function(filename,content,contentType){const dataURIToBlob=function(dataURI){let binStr=contentType==='csv'?dataURI:atob(dataURI);let len=binStr.length;let arr=new Uint8Array(len);for(let i=0;i<len;i++){arr[i]=binStr.charCodeAt(i);} let blob=new Blob([arr],{type:'application/octet-stream',});if(contentType==='csv'){const bom=new Uint8Array([0xEF,0xBB,0xBF]);blob=new Blob([bom,binStr],{type:'text/plain;charset=utf-8',});} return blob;};const blob=dataURIToBlob(content);const url=URL.createObjectURL(blob);let element=document.createElement('a');element.setAttribute('href',url);element.setAttribute('download',filename);element.style.display='none';document.body.appendChild(element);element.click();document.body.removeChild(element);},formatDateToString:function(){const currentDate=moment();return currentDate.format('YYYY_MM_DD_HH_mm');},exportErrorCallback:function(type,error){if(error&&(error.errorThrown==='timeout'||error.textStatus==='timeout')){app.alert.show(`export-to-${type}-failed`,{level:'error',messages:app.lang.get('LBL_EXPORT_FAILED','Reports'),});if(_.isFunction(this.closeModal)){this.closeModal();} app.alert.dismiss(`export-to-${type}-failed`);}},exportCompleteCallback:function(type,data){if(this.disposed){return;} const reportModelName=this._buildReportName();const currentTime=this.formatDateToString();const userName=app.user.get('user_name');const reportName=reportModelName.replace(/ /g,'_');const name=`${reportName}_${userName}_${currentTime}.${type}`;this.downloadFileLocally(name,data.xhr.responseText,type);if(_.isFunction(this.closeModal)){this.closeModal();} const typeUpper=type.toUpperCase();app.alert.dismiss(`export-to-${type}`);app.alert.show(`export-to-${type}-success`,{level:'success',messages:app.lang.get(`LBL_EXPORT_${typeUpper}_SUCCESS`,'Reports'),autoClose:true});},_buildReportName:function(){let reportModelName=this.context.get('model').get('name');if(!reportModelName&&this.layout){reportModelName=this.layout.model.get('report_name');} if(!reportModelName){reportModelName='Report';} return reportModelName;},});});})(SUGAR.App); /* End of File include/javascript/sugar7/plugins/ReportExport.js */ (function DocuSignConsole(app){const utils={initiateSend:function(payload,step){if(_.isUndefined(payload.processInProgress)&&app.DocuSign._activeSendingProcess===true){return;} app.DocuSign._activeSendingProcess=true;payload.processInProgress=true;const showRecipients=this.shouldShowRecipients();if(_.isUndefined(step)){if(showRecipients){let contextModule=this._getEnvelopeSourceModule();let ctxModelId=this._getEnvelopeSourceModelId();let recipientsListContext={module:'DocuSignEnvelopes',contextModule:contextModule,ctxModelId:ctxModelId,isMultiSelect:true,};if(payload.template){recipientsListContext.templateDetails=payload.template;} app.drawer.open({layout:'recipients-list',type:'recipients-list',context:recipientsListContext},_.bind(function(selected){if(selected.closeEvent){app.DocuSign._activeSendingProcess=false;return;} payload.recipients=[];_.each(selected,function(recipient){payload.recipients.push(recipient);});const nextStep='envelopeSetup';this.initiateSend(payload,nextStep);},this));return;}else{const nextStep='envelopeSetup';this.initiateSend(payload,nextStep);return;}} if(step==='envelopeSetup'){app.drawer.open({layout:'envelope-setup',type:'envelope-setup',context:{module:'DocuSignEnvelopes',payload:payload,}},_.bind(function(envelopeDetails){if(envelopeDetails.closeEvent){if(_.isUndefined(envelopeDetails.dsProcessWillContinue)){app.DocuSign._activeSendingProcess=false;} return;} const step='openEnvelope';payload.envelopeName=envelopeDetails.envelopeName;this.initiateSend(payload,step);},this));return;} if(step==='openEnvelope'||step==='openDraft'){app.DocuSign._activeSendingProcess=false;const tab=window.open(app.DocuSign._loadPageUrl);this.openEnvelope(payload,tab);return;} if(step==='selectTemplate'){app.drawer.open({layout:'templates-list',type:'templates-list',context:{module:'DocuSignEnvelopes',}},_.bind(function(selected){if(selected.closeEvent){app.DocuSign._activeSendingProcess=false;return;} payload.templateSelected=selected;const step='getTemplate';this.initiateSend(payload,step);},this));return;} if(step==='getTemplate'){app.api.call('create',app.api.buildURL('DocuSign/getTemplateDetails'),{template:payload.templateSelected},{success:_.bind(function(template){payload.template=template;this.initiateSend(payload);},this),});return;}},initiateCompositeSend:function(payload,step){if(_.isUndefined(payload.processInProgress)&&app.DocuSign._activeSendingProcess===true){return;} app.DocuSign._activeSendingProcess=true;payload.processInProgress=true;const showRecipients=this.shouldShowRecipients();if(_.isUndefined(step)&&showRecipients){let contextModule=this._getEnvelopeSourceModule();let ctxModelId=this._getEnvelopeSourceModelId();let recipientsListContext={module:'Users',contextModule:contextModule,ctxModelId:ctxModelId,};if(payload.template){recipientsListContext.templateDetails=payload.template;} app.drawer.open({layout:'recipients-list-composite',type:'recipients-list-composite',context:recipientsListContext,isMultiSelect:true},_.bind(function(selected){if(_.isUndefined(selected)||selected.closeEvent){if(_.isUndefined(selected.dsProcessWillContinue)){app.DocuSign._activeSendingProcess=false;} return;} payload.recipients=[];_.each(selected,function(recipient){payload.recipients.push(recipient);});const nextStep='envelopeSetup';payload.composite=true;this.initiateSend(payload,nextStep);},this));return;} if((_.isUndefined(step)&&!showRecipients)||step==='envelopeSetup'){const nextStep='envelopeSetup';this.initiateSend(payload,nextStep);return;} if(step==='selectTemplate'){app.drawer.open({layout:'templates-list-composite',type:'templates-list-composite',context:{module:'DocuSignEnvelopes',}},_.bind(function(selected){if(_.isUndefined(selected)||selected.closeEvent){app.DocuSign._activeSendingProcess=false;return;} payload.templateSelected=selected;payload.composite=true;const step='getTemplate';this.initiateCompositeSend(payload,step);},this));return;} if(step==='getTemplate'){app.api.call('create',app.api.buildURL('DocuSign/getTemplateDetails'),{template:payload.templateSelected},{success:_.bind(function(template){payload.template=template;this.initiateCompositeSend(payload);},this),});return;} const nextStep='openEnvelope';this.initiateCompositeSend(payload,nextStep);},openEnvelope:function(payload,tab){app.alert.show('load-tab-for-sending',{level:'process',title:app.lang.get('LBL_LOADING')});app.api.call('create',app.api.buildURL('DocuSign/send'),payload,{success:_.bind(this.succesGettingEnvelope,this,tab),error:function(error){app.alert.show('error-loading-tab',{level:'error',messages:error.message});},complete:function(){app.alert.dismiss('load-tab-for-sending');}});},isRecipientSelectionEnabled:function(){let recipientSelectionIsEnabled=false;if(!_.isUndefined(app.config.docusign)&&_.isString(app.config.docusign.recipientSelection)){recipientSelectionIsEnabled=app.config.docusign.recipientSelection==='show';} return recipientSelectionIsEnabled;},shouldShowRecipients:function(){const ctxModel=app.controller.context;const recordViewContext=ctxModel.get('layout')==='record';const homeModule=ctxModel.get('module')==='Home';const recipientSelectionIsEnabled=this.isRecipientSelectionEnabled();const showRecipients=recipientSelectionIsEnabled&&recordViewContext&&!homeModule;return showRecipients;},succesGettingEnvelope:function(tab,res){if((res.status&&res.status==='error')||res.envelopeStatus==='deleted'){var minifiedErrorMessage=res.message.toLowerCase();if(minifiedErrorMessage.includes('envelope status in docusign is now')){if(res.envelopeStatus==='deleted'){this.confirmDelete(res);}else{this.confirmUpdate(res);}}else if(minifiedErrorMessage!=='cancel'&&!_.isEmpty(res.message)){app.alert.show('ds_error',{level:'error',messages:res.message,autoClose:false});} tab.close();return;} tab.location.href=res.url;this.listenForTabClosing();},confirmDelete:function(data){app.alert.show('draft-does-not-exist',{level:'confirmation',messages:app.lang.get('LBL_DRAFT_DELETED_CONFIRMATION','DocuSignEnvelopes'),autoClose:false,onConfirm:function(){let removeCallbacks=this.getConfirmationCallbacks({successMessage:app.lang.get('LBL_DRAFT_DELETE_SUCCESS','DocuSignEnvelopes'),errorMessage:app.lang.get('LBL_DRAFT_DELETE_ERROR','DocuSignEnvelopes')});app.api.call('create',app.api.buildURL('DocuSign/removeEnvelope'),{envelopeId:data.envelopeId},removeCallbacks);app.alert.show('envelope-loading',{level:'process',title:app.lang.get('LBL_LOADING')});},});},confirmUpdate:function(data){app.alert.show('draft-does-not-exist',{level:'confirmation',messages:app.lang.get('LBL_DRAFT_CHANGED_CONFIRM','DocuSignEnvelopes',{status:data.status}),autoClose:false,onConfirm:function(){let updateCallbacks=this.getConfirmationCallbacks({successMessage:app.lang.get('LBL_DRAFT_CHANGED_SUCCESS','DocuSignEnvelopes'),errorMessage:app.lang.get('LBL_DRAFT_CHANGED_ERROR','DocuSignEnvelopes')});app.api.call('create',app.api.buildURL('DocuSign/updateEnvelope'),{envelopeId:data.envelopeId},updateCallbacks);app.alert.show('envelope-loading',{level:'process',title:app.lang.get('LBL_LOADING')});},});},getConfirmationCallbacks:function(options){return{success:function(res){if(res){app.alert.show('succes-change-envelope',{level:'success',messages:options.successMessage,autoClose:true});app.events.trigger('docusign:reload');}else{app.alert.show('error-change-envelope',{level:'error',messages:options.errorMessage,autoClose:true,autoCloseDelay:'10000'});}},error:function(error){app.alert.show('error-change-envelope',{level:'error',messages:error.message});},complete:function(){app.alert.dismiss('envelope-loading');}};},listenForTabClosing:function(){$(window).on('storage.docusignAction',function(e){if(e.originalEvent.key!=='docusignAction'){return;} const action=e.originalEvent.newValue;if(!action){return;} $(window).off('storage.docusignAction');app.events.trigger('docusign:send:finished');if(app.controller.context.get('module')==='pmse_Inbox'&&app.controller.layout.name==='show-case'){return;} app.events.trigger('docusign:reload');});},_getEnvelopeSourceModule:function(){var module=app.controller.context.get('module');if(module==='pmse_Inbox'&&app.controller.layout.name==='show-case'){try{var sourceModel=app.controller.layout._components[0].getComponent('sidebar').getComponent('main-pane').model;return sourceModel.get('_module');}catch(showCaseError){app.log.error(`_getEnvelopeSourceModule. show-case layout error: ${showCaseError}`);}} return module;},_getEnvelopeSourceModelId:function(){var module=app.controller.context.get('module');var modelId=app.controller.context.get('modelId');if(module==='pmse_Inbox'&&app.controller.layout.name==='show-case'){try{var sourceModel=app.controller.layout._components[0].getComponent('sidebar').getComponent('main-pane').model;return sourceModel.get('id');}catch(showCaseError){app.log.error(`_getEnvelopeSourceModelId. show-case layout error: ${showCaseError}`);}} return modelId;},_showRolesNotSetAlert:function(){const msg=app.lang.get('LBL_RECIPIENT_ROLE_MISSING_ERROR','DocuSignEnvelopes');app.alert.show('recipient-role-not-set',{level:'error',messages:msg,autoClose:true});},};app.DocuSign=app.DocuSign||{};app.DocuSign.utils=utils;app.events.on('app:init',function(){app.DocuSign._loadPageUrl=app.api.buildURL('DocuSign','loadPage');app.events.on('docusign:send:initiate',app.DocuSign.utils.initiateSend,app.DocuSign.utils);app.events.on('docusign:compositeSend:initiate',app.DocuSign.utils.initiateCompositeSend,app.DocuSign.utils);app.events.on('app:view:change',function(layoutType,contextOptions){const docusignSendingLayouts=['recipients-list','recipients-list-composite','templates-list','templates-list-composite','envelope-setup'];if(!_.contains(docusignSendingLayouts,layoutType)&&_.isUndefined(contextOptions.drawer)){app.DocuSign._activeSendingProcess=false;return;}});});})(SUGAR.App); /* End of File include/javascript/docusign/docusign-console.js */ (function(app){app.events.on('app:init',function(){app.plugins.register('ReportIntelligenceDashlet','view',{_setIntelligence:function(){const intelligenceEl=this.$('[data-fieldname="intelligent"]');const checkboxElement=this.$('[data-fieldname="intelligent"] input');const field=this.getField('linkedFields');if(!field){return;} const fieldEl=this.$('[data-name="linkedFields"]');if(checkboxElement.is(':checked')==1){fieldEl.show();}else{fieldEl.hide();} if(this._isNotRecordLayout()&&this._isNotFocusDrawerLayout()){intelligenceEl.parent().hide();fieldEl.parent().hide();}},_setLinkedFields:function(reportModule){if(!this.meta.config){return;} reportModule=reportModule?reportModule:this.settings.get('module');const linkedField=this.getField('linkedFields');if(!linkedField){return;} let relationships=this._getRelationships(reportModule);linkedField.items=relationships;if(_.isEmpty(linkedField.items)){this._toggleIntelligence(false);this.settings.set('linkedFields','');return;} let linkName=this.settings.get('linkedFields');const link=linkedField.items[linkName];if(_.isUndefined(link)){this.settings.set('linkedFields','');} linkedField._render();if(!linkName&&this.settings.get('intelligent')){linkName=_.chain(relationships).keys().first().value();this.settings.set('linkedFields',linkName);linkedField.$('.select2-container').select2('data',{id:linkName,text:relationships[linkName],});}},_toggleInput:function(enable,fieldName,title){if(!this.meta.config){return;} const checkboxElement=this.$(`[data-fieldname="${fieldName}"] input`);$(checkboxElement).prop('disabled',!enable);if(!enable){this.settings.set(fieldName,false);} this._toggleInputTooltip(!enable,fieldName,title);},_toggleIntelligence:function(enable){if(!this.meta.config){return;} const checkboxElement=this.$('[data-fieldname="intelligent"] input');$(checkboxElement).prop('disabled',!enable);if(!enable){const fieldEl=this.$('[data-name="linkedFields"]');$(checkboxElement).prop('checked',false);fieldEl.hide();this.settings.set({linkedFields:'',intelligent:false,});} this._toggleIntelligenceTooltip(!enable);},_wrapInputEl:function(fieldName){const containerFieldName=`${fieldName}Container`;let checkboxEl=this.$(`[data-fieldname="${fieldName}"] input`);let checkboxContainer=`<div class="saved-report-tooltip" data-fieldname="${containerFieldName}"`+` data-container="body">`;if(this.$(`[data-fieldname="${containerFieldName}"]`).length>0){return;} checkboxEl.parent().prepend(checkboxContainer);let checkboxContainerEl=this.$(`[data-fieldname="${containerFieldName}"]`);checkboxContainerEl.append(checkboxEl.detach());},_toggleIntelligenceTooltip:function(enable){const sideCtx=app.sideDrawer.currentContextDef;const appContext=app.controller.context;const module=sideCtx?sideCtx.context.module:appContext.get('module');const message=app.lang.get('LBL_REPORTS_DASHLET_NO_LINKS_SELECTED',null,{module:module,});this._toggleInputTooltip(enable,'intelligent',message);},_toggleInputTooltip:function(enable,fieldName,title){let checkboxContainerEl=$(`[data-fieldname="${fieldName}Container"]`);checkboxContainerEl.attr('rel','tooltip');checkboxContainerEl.tooltip({title,});checkboxContainerEl.tooltip(enable?'enable':'disable');},_getRelationships:function(reportModule){const sideCtx=app.sideDrawer.currentContextDef;const appContext=app.controller.context;const currentModule=sideCtx?sideCtx.context.module:appContext.get('module');const fieldDefs=app.metadata.getModule(currentModule).fields;const subpanels=app.metadata.getLayout(currentModule,'subpanels');const relates=_.filter(fieldDefs,function(field){if(!_.isUndefined(field.type)&&(field.type==='link')){return app.data.getRelatedModule(currentModule,field.name)===reportModule;} return false;},this);let result={};_.each(relates,function(field){result[field.name]=app.lang.get(field.vname||field.name,[currentModule,reportModule]);const linkType='link_type';const linkTypeCustom='link-type';if(field[linkType]==='one'||field[linkTypeCustom]==='one'){let oneField=false;if(field.id_name){oneField=_.first(_.filter(fieldDefs,function(targetField){return targetField.type==='relate'&&targetField.id_name===field.id_name;},this));}else{oneField=_.first(_.filter(fieldDefs,function(targetField){return targetField.type==='relate'&&targetField.link===field.name;},this));} if(oneField&&oneField.vname){result[field.name]=app.lang.get(oneField.vname,currentModule);}} if(!subpanels||!subpanels.components){return;} const subpanel=_.first(_.filter(subpanels.components,function getSubpanel(component){return component.context&&component.context.link===field.name;},this));if(subpanel&&subpanel.label){result[field.name]=app.lang.get(subpanel.label,currentModule);}},this);return result;},_isNotRecordLayout:function(){return app.controller.context.get('dataView')!=='record';},_isNotFocusDrawerLayout:function(){const sideDrawerContext=app.sideDrawer.currentContextDef;return!sideDrawerContext||(sideDrawerContext&&sideDrawerContext.context.layout!=='focus');},_toggleChartFields:function(){if(this.meta.config){let xOptionsFieldset=this.getField('x_label_options');let yOptionsFieldset=this.getField('y_label_options');let showValuesField=this.getField('showValues');let showLegendField=this.getField('showLegend');let showDimensionOptions=false;let showBarOptions=false;let showLegend=true;let xOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_XAXIS_LABEL');let yOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_YAXIS_LABEL');switch(this.settings.get('chartType')){case'pieF':case'donutF':case'funnelF':showDimensionOptions=false;showBarOptions=false;break;case'treemapF':showLegend=false;showDimensionOptions=false;showBarOptions=false;break;case'lineF':showDimensionOptions=true;showBarOptions=false;break;case'hBarF':case'hGBarF':case'vBarF':case'vGBarF':showDimensionOptions=true;showBarOptions=true;break;default:showDimensionOptions=false;showBarOptions=false;} if(showDimensionOptions){switch(this.settings.get('chartType')){case'hBarF':case'hGBarF':xOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_YAXIS_LABEL');yOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_XAXIS_LABEL');break;default:xOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_XAXIS_LABEL');yOptionsLabel=app.lang.get('LBL_CHART_CONFIG_SHOW_YAXIS_LABEL');}} if(xOptionsFieldset){xOptionRecordCell=xOptionsFieldset.$el.closest('.record-cell');if(showDimensionOptions){xOptionRecordCell.show();}else{xOptionRecordCell.hide();} xOptionRecordCell.find('.record-label').text(xOptionsLabel);} if(yOptionsFieldset){yOptionRecordCell=yOptionsFieldset.$el.closest('.record-cell');if(showDimensionOptions){yOptionRecordCell.show();}else{yOptionRecordCell.hide();} yOptionRecordCell.find('.record-label').text(yOptionsLabel);} if(showValuesField){showValuesField.$el.closest('.record-cell').toggleClass('hidden',!showBarOptions);} if(showLegendField){showLegendField.$el.toggleClass('hidden',!showLegend);} this.settings.set('isBarChart',!!showBarOptions);}},});});})(SUGAR.App); /* End of File include/javascript/sugar7/plugins/ReportIntelligenceDashlet.js */