(function(){var a,b,c,d,e,f,g,h,i=[].slice,j={}.hasOwnProperty,k=function(a,b){function c(){this.constructor=a}for(var d in b)j.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a};g=function(){},b=function(){function a(){}return a.prototype.addEventListener=a.prototype.on,a.prototype.on=function(a,b){return this._callbacks=this._callbacks||{},this._callbacks[a]||(this._callbacks[a]=[]),this._callbacks[a].push(b),this},a.prototype.emit=function(){var a,b,c,d,e,f;if(d=arguments[0],a=2<=arguments.length?i.call(arguments,1):[],this._callbacks=this._callbacks||{},c=this._callbacks[d])for(e=0,f=c.length;f>e;e++)b=c[e],b.apply(this,a);return this},a.prototype.removeListener=a.prototype.off,a.prototype.removeAllListeners=a.prototype.off,a.prototype.removeEventListener=a.prototype.off,a.prototype.off=function(a,b){var c,d,e,f,g;if(!this._callbacks||0===arguments.length)return this._callbacks={},this;if(d=this._callbacks[a],!d)return this;if(1===arguments.length)return delete this._callbacks[a],this;for(e=f=0,g=d.length;g>f;e=++f)if(c=d[e],c===b){d.splice(e,1);break}return this},a}(),a=function(a){function c(a,b){var e,f,g;if(this.element=a,this.version=c.version,this.defaultOptions.previewTemplate=this.defaultOptions.previewTemplate.replace(/\n*/g,""),this.clickableElements=[],this.listeners=[],this.files=[],"string"==typeof this.element&&(this.element=document.querySelector(this.element)),!this.element||null==this.element.nodeType)throw new Error("Invalid dropzone element.");if(this.element.dropzone)throw new Error("Dropzone already attached.");if(c.instances.push(this),this.element.dropzone=this,e=null!=(g=c.optionsForElement(this.element))?g:{},this.options=d({},this.defaultOptions,e,null!=b?b:{}),this.options.forceFallback||!c.isBrowserSupported())return this.options.fallback.call(this);if(null==this.options.url&&(this.options.url=this.element.getAttribute("action")),!this.options.url)throw new Error("No URL provided.");if(this.options.acceptedFiles&&this.options.acceptedMimeTypes)throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");this.options.acceptedMimeTypes&&(this.options.acceptedFiles=this.options.acceptedMimeTypes,delete this.options.acceptedMimeTypes),this.options.method=this.options.method.toUpperCase(),(f=this.getExistingFallback())&&f.parentNode&&f.parentNode.removeChild(f),this.options.previewsContainer!==!1&&(this.previewsContainer=this.options.previewsContainer?c.getElement(this.options.previewsContainer,"previewsContainer"):this.element),this.options.clickable&&(this.clickableElements=this.options.clickable===!0?[this.element]:c.getElements(this.options.clickable,"clickable")),this.init()}var d,e;return k(c,a),c.prototype.Emitter=b,c.prototype.events=["drop","dragstart","dragend","dragenter","dragover","dragleave","addedfile","addedfiles","removedfile","thumbnail","error","errormultiple","processing","processingmultiple","uploadprogress","totaluploadprogress","sending","sendingmultiple","success","successmultiple","canceled","canceledmultiple","complete","completemultiple","reset","maxfilesexceeded","maxfilesreached","queuecomplete"],c.prototype.defaultOptions={url:null,method:"post",withCredentials:!1,parallelUploads:2,uploadMultiple:!1,maxFilesize:256,paramName:"file",createImageThumbnails:!0,maxThumbnailFilesize:10,thumbnailWidth:120,thumbnailHeight:120,filesizeBase:1e3,maxFiles:null,params:{},clickable:!0,ignoreHiddenFiles:!0,acceptedFiles:null,acceptedMimeTypes:null,autoProcessQueue:!0,autoQueue:!0,addRemoveLinks:!1,previewsContainer:null,hiddenInputContainer:"body",capture:null,dictDefaultMessage:"Drop files here to upload",dictFallbackMessage:"Your browser does not support drag'n'drop file uploads.",dictFallbackText:"Please use the fallback form below to upload your files like in the olden days.",dictFileTooBig:"File is too big ({{filesize}}Mb). Max filesize: {{maxFilesize}}Mb.",dictInvalidFileType:"You can't upload files of this type.",dictResponseError:"Server responded with {{statusCode}} code.",dictCancelUpload:"Cancel upload",dictCancelUploadConfirmation:"Are you sure you want to cancel this upload?",dictRemoveFile:"Remove file",dictRemoveFileConfirmation:null,dictMaxFilesExceeded:"You can not upload any more files.",accept:function(a,b){return b()},init:function(){return g},forceFallback:!1,fallback:function(){var a,b,d,e,f,g;for(this.element.className=""+this.element.className+" dz-browser-not-supported",g=this.element.getElementsByTagName("div"),e=0,f=g.length;f>e;e++)a=g[e],/(^| )dz-message($| )/.test(a.className)&&(b=a,a.className="dz-message");return b||(b=c.createElement('
'),this.element.appendChild(b)),d=b.getElementsByTagName("span")[0],d&&(null!=d.textContent?d.textContent=this.options.dictFallbackMessage:null!=d.innerText&&(d.innerText=this.options.dictFallbackMessage)),this.element.appendChild(this.getFallbackForm())},resize:function(a){var b,c,d;return b={srcX:0,srcY:0,srcWidth:a.width,srcHeight:a.height},c=a.width/a.height,b.optWidth=this.options.thumbnailWidth,b.optHeight=this.options.thumbnailHeight,null==b.optWidth&&null==b.optHeight?(b.optWidth=b.srcWidth,b.optHeight=b.srcHeight):null==b.optWidth?b.optWidth=c*b.optHeight:null==b.optHeight&&(b.optHeight=1/c*b.optWidth),d=b.optWidth/b.optHeight,a.heightd?(b.srcHeight=a.height,b.srcWidth=b.srcHeight*d):(b.srcWidth=a.width,b.srcHeight=b.srcWidth/d),b.srcX=(a.width-b.srcWidth)/2,b.srcY=(a.height-b.srcHeight)/2,b},drop:function(){return this.element.classList.remove("dz-drag-hover")},dragstart:g,dragend:function(){return this.element.classList.remove("dz-drag-hover")},dragenter:function(){return this.element.classList.add("dz-drag-hover")},dragover:function(){return this.element.classList.add("dz-drag-hover")},dragleave:function(){return this.element.classList.remove("dz-drag-hover")},paste:g,reset:function(){return this.element.classList.remove("dz-started")},addedfile:function(a){var b,d,e,f,g,h,i,j,k,l,m,n,o;if(this.element===this.previewsContainer&&this.element.classList.add("dz-started"),this.previewsContainer){for(a.previewElement=c.createElement(this.options.previewTemplate.trim()),a.previewTemplate=a.previewElement,this.previewsContainer.appendChild(a.previewElement),l=a.previewElement.querySelectorAll("[data-dz-name]"),f=0,i=l.length;i>f;f++)b=l[f],b.textContent=a.name;for(m=a.previewElement.querySelectorAll("[data-dz-size]"),g=0,j=m.length;j>g;g++)b=m[g],b.innerHTML=this.filesize(a.size);for(this.options.addRemoveLinks&&(a._removeLink=c.createElement(''+this.options.dictRemoveFile+""),a.previewElement.appendChild(a._removeLink)),d=function(b){return function(d){return d.preventDefault(),d.stopPropagation(),a.status===c.UPLOADING?c.confirm(b.options.dictCancelUploadConfirmation,function(){return b.removeFile(a)}):b.options.dictRemoveFileConfirmation?c.confirm(b.options.dictRemoveFileConfirmation,function(){return b.removeFile(a)}):b.removeFile(a)}}(this),n=a.previewElement.querySelectorAll("[data-dz-remove]"),o=[],h=0,k=n.length;k>h;h++)e=n[h],o.push(e.addEventListener("click",d));return o}},removedfile:function(a){var b;return a.previewElement&&null!=(b=a.previewElement)&&b.parentNode.removeChild(a.previewElement),this._updateMaxFilesReachedClass()},thumbnail:function(a,b){var c,d,e,f;if(a.previewElement){for(a.previewElement.classList.remove("dz-file-preview"),f=a.previewElement.querySelectorAll("[data-dz-thumbnail]"),d=0,e=f.length;e>d;d++)c=f[d],c.alt=a.name,c.src=b;return setTimeout(function(){return function(){return a.previewElement.classList.add("dz-image-preview")}}(this),1)}},error:function(a,b){var c,d,e,f,g;if(a.previewElement){for(a.previewElement.classList.add("dz-error"),"String"!=typeof b&&b.error&&(b=b.error),f=a.previewElement.querySelectorAll("[data-dz-errormessage]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.textContent=b);return g}},errormultiple:g,processing:function(a){return a.previewElement&&(a.previewElement.classList.add("dz-processing"),a._removeLink)?a._removeLink.textContent=this.options.dictCancelUpload:void 0},processingmultiple:g,uploadprogress:function(a,b){var c,d,e,f,g;if(a.previewElement){for(f=a.previewElement.querySelectorAll("[data-dz-uploadprogress]"),g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push("PROGRESS"===c.nodeName?c.value=b:c.style.width=""+b+"%");return g}},totaluploadprogress:g,sending:g,sendingmultiple:g,success:function(a){return a.previewElement?a.previewElement.classList.add("dz-success"):void 0},successmultiple:g,canceled:function(a){return this.emit("error",a,"Upload canceled.")},canceledmultiple:g,complete:function(a){return a._removeLink&&(a._removeLink.textContent=this.options.dictRemoveFile),a.previewElement?a.previewElement.classList.add("dz-complete"):void 0},completemultiple:g,maxfilesexceeded:g,maxfilesreached:g,queuecomplete:g,addedfiles:g,previewTemplate:'
\n
\n
\n
\n
\n
\n
\n
\n
\n \n Check\n \n \n \n \n \n
\n
\n \n Error\n \n \n \n \n \n \n \n
\n
'},d=function(){var a,b,c,d,e,f,g;for(d=arguments[0],c=2<=arguments.length?i.call(arguments,1):[],f=0,g=c.length;g>f;f++){b=c[f];for(a in b)e=b[a],d[a]=e}return d},c.prototype.getAcceptedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted&&e.push(a);return e},c.prototype.getRejectedFiles=function(){var a,b,c,d,e;for(d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.accepted||e.push(a);return e},c.prototype.getFilesWithStatus=function(a){var b,c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.status===a&&f.push(b);return f},c.prototype.getQueuedFiles=function(){return this.getFilesWithStatus(c.QUEUED)},c.prototype.getUploadingFiles=function(){return this.getFilesWithStatus(c.UPLOADING)},c.prototype.getAddedFiles=function(){return this.getFilesWithStatus(c.ADDED)},c.prototype.getActiveFiles=function(){var a,b,d,e,f;for(e=this.files,f=[],b=0,d=e.length;d>b;b++)a=e[b],(a.status===c.UPLOADING||a.status===c.QUEUED)&&f.push(a);return f},c.prototype.init=function(){var a,b,d,e,f,g,h;for("form"===this.element.tagName&&this.element.setAttribute("enctype","multipart/form-data"),this.element.classList.contains("dropzone")&&!this.element.querySelector(".dz-message")&&this.element.appendChild(c.createElement('
'+this.options.dictDefaultMessage+"
")),this.clickableElements.length&&(d=function(a){return function(){return a.hiddenFileInput&&a.hiddenFileInput.parentNode.removeChild(a.hiddenFileInput),a.hiddenFileInput=document.createElement("input"),a.hiddenFileInput.setAttribute("type","file"),(null==a.options.maxFiles||a.options.maxFiles>1)&&a.hiddenFileInput.setAttribute("multiple","multiple"),a.hiddenFileInput.className="dz-hidden-input",null!=a.options.acceptedFiles&&a.hiddenFileInput.setAttribute("accept",a.options.acceptedFiles),null!=a.options.capture&&a.hiddenFileInput.setAttribute("capture",a.options.capture),a.hiddenFileInput.style.visibility="hidden",a.hiddenFileInput.style.position="absolute",a.hiddenFileInput.style.top="0",a.hiddenFileInput.style.left="0",a.hiddenFileInput.style.height="0",a.hiddenFileInput.style.width="0",document.querySelector(a.options.hiddenInputContainer).appendChild(a.hiddenFileInput),a.hiddenFileInput.addEventListener("change",function(){var b,c,e,f;if(c=a.hiddenFileInput.files,c.length)for(e=0,f=c.length;f>e;e++)b=c[e],a.addFile(b);return a.emit("addedfiles",c),d()})}}(this))(),this.URL=null!=(g=window.URL)?g:window.webkitURL,h=this.events,e=0,f=h.length;f>e;e++)a=h[e],this.on(a,this.options[a]);return this.on("uploadprogress",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("removedfile",function(a){return function(){return a.updateTotalUploadProgress()}}(this)),this.on("canceled",function(a){return function(b){return a.emit("complete",b)}}(this)),this.on("complete",function(a){return function(){return 0===a.getAddedFiles().length&&0===a.getUploadingFiles().length&&0===a.getQueuedFiles().length?setTimeout(function(){return a.emit("queuecomplete")},0):void 0}}(this)),b=function(a){return a.stopPropagation(),a.preventDefault?a.preventDefault():a.returnValue=!1},this.listeners=[{element:this.element,events:{dragstart:function(a){return function(b){return a.emit("dragstart",b)}}(this),dragenter:function(a){return function(c){return b(c),a.emit("dragenter",c)}}(this),dragover:function(a){return function(c){var d;try{d=c.dataTransfer.effectAllowed}catch(e){}return c.dataTransfer.dropEffect="move"===d||"linkMove"===d?"move":"copy",b(c),a.emit("dragover",c)}}(this),dragleave:function(a){return function(b){return a.emit("dragleave",b)}}(this),drop:function(a){return function(c){return b(c),a.drop(c)}}(this),dragend:function(a){return function(b){return a.emit("dragend",b)}}(this)}}],this.clickableElements.forEach(function(a){return function(b){return a.listeners.push({element:b,events:{click:function(d){return(b!==a.element||d.target===a.element||c.elementInside(d.target,a.element.querySelector(".dz-message")))&&a.hiddenFileInput.click(),!0}}})}}(this)),this.enable(),this.options.init.call(this)},c.prototype.destroy=function(){var a;return this.disable(),this.removeAllFiles(!0),(null!=(a=this.hiddenFileInput)?a.parentNode:void 0)&&(this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput),this.hiddenFileInput=null),delete this.element.dropzone,c.instances.splice(c.instances.indexOf(this),1)},c.prototype.updateTotalUploadProgress=function(){var a,b,c,d,e,f,g,h;if(d=0,c=0,a=this.getActiveFiles(),a.length){for(h=this.getActiveFiles(),f=0,g=h.length;g>f;f++)b=h[f],d+=b.upload.bytesSent,c+=b.upload.total;e=100*d/c}else e=100;return this.emit("totaluploadprogress",e,c,d)},c.prototype._getParamName=function(a){return"function"==typeof this.options.paramName?this.options.paramName(a):""+this.options.paramName+(this.options.uploadMultiple?"["+a+"]":"")},c.prototype.getFallbackForm=function(){var a,b,d,e;return(a=this.getExistingFallback())?a:(d='
',this.options.dictFallbackText&&(d+="

"+this.options.dictFallbackText+"

"),d+='
',b=c.createElement(d),"FORM"!==this.element.tagName?(e=c.createElement('
'),e.appendChild(b)):(this.element.setAttribute("enctype","multipart/form-data"),this.element.setAttribute("method",this.options.method)),null!=e?e:b)},c.prototype.getExistingFallback=function(){var a,b,c,d,e,f;for(b=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)if(b=a[c],/(^| )fallback($| )/.test(b.className))return b},f=["div","form"],d=0,e=f.length;e>d;d++)if(c=f[d],a=b(this.element.getElementsByTagName(c)))return a},c.prototype.setupEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.addEventListener(b,c,!1));return e}());return g},c.prototype.removeEventListeners=function(){var a,b,c,d,e,f,g;for(f=this.listeners,g=[],d=0,e=f.length;e>d;d++)a=f[d],g.push(function(){var d,e;d=a.events,e=[];for(b in d)c=d[b],e.push(a.element.removeEventListener(b,c,!1));return e}());return g},c.prototype.disable=function(){var a,b,c,d,e;for(this.clickableElements.forEach(function(a){return a.classList.remove("dz-clickable")}),this.removeEventListeners(),d=this.files,e=[],b=0,c=d.length;c>b;b++)a=d[b],e.push(this.cancelUpload(a));return e},c.prototype.enable=function(){return this.clickableElements.forEach(function(a){return a.classList.add("dz-clickable")}),this.setupEventListeners()},c.prototype.filesize=function(a){var b,c,d,e,f,g,h,i;if(d=0,e="b",a>0){for(g=["TB","GB","MB","KB","b"],c=h=0,i=g.length;i>h;c=++h)if(f=g[c],b=Math.pow(this.options.filesizeBase,4-c)/10,a>=b){d=a/Math.pow(this.options.filesizeBase,4-c),e=f;break}d=Math.round(10*d)/10}return""+d+" "+e},c.prototype._updateMaxFilesReachedClass=function(){return null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(this.getAcceptedFiles().length===this.options.maxFiles&&this.emit("maxfilesreached",this.files),this.element.classList.add("dz-max-files-reached")):this.element.classList.remove("dz-max-files-reached")},c.prototype.drop=function(a){var b,c;a.dataTransfer&&(this.emit("drop",a),b=a.dataTransfer.files,this.emit("addedfiles",b),b.length&&(c=a.dataTransfer.items,c&&c.length&&null!=c[0].webkitGetAsEntry?this._addFilesFromItems(c):this.handleFiles(b)))},c.prototype.paste=function(a){var b,c;if(null!=(null!=a&&null!=(c=a.clipboardData)?c.items:void 0))return this.emit("paste",a),b=a.clipboardData.items,b.length?this._addFilesFromItems(b):void 0},c.prototype.handleFiles=function(a){var b,c,d,e;for(e=[],c=0,d=a.length;d>c;c++)b=a[c],e.push(this.addFile(b));return e},c.prototype._addFilesFromItems=function(a){var b,c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],f.push(null!=c.webkitGetAsEntry&&(b=c.webkitGetAsEntry())?b.isFile?this.addFile(c.getAsFile()):b.isDirectory?this._addFilesFromDirectory(b,b.name):void 0:null!=c.getAsFile?null==c.kind||"file"===c.kind?this.addFile(c.getAsFile()):void 0:void 0);return f},c.prototype._addFilesFromDirectory=function(a,b){var c,d;return c=a.createReader(),d=function(a){return function(c){var d,e,f;for(e=0,f=c.length;f>e;e++)d=c[e],d.isFile?d.file(function(c){return a.options.ignoreHiddenFiles&&"."===c.name.substring(0,1)?void 0:(c.fullPath=""+b+"/"+c.name,a.addFile(c))}):d.isDirectory&&a._addFilesFromDirectory(d,""+b+"/"+d.name)}}(this),c.readEntries(d,function(a){return"undefined"!=typeof console&&null!==console&&"function"==typeof console.log?console.log(a):void 0})},c.prototype.accept=function(a,b){return a.size>1024*this.options.maxFilesize*1024?b(this.options.dictFileTooBig.replace("{{filesize}}",Math.round(a.size/1024/10.24)/100).replace("{{maxFilesize}}",this.options.maxFilesize)):c.isValidFile(a,this.options.acceptedFiles)?null!=this.options.maxFiles&&this.getAcceptedFiles().length>=this.options.maxFiles?(b(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}",this.options.maxFiles)),this.emit("maxfilesexceeded",a)):this.options.accept.call(this,a,b):b(this.options.dictInvalidFileType)},c.prototype.addFile=function(a){return a.upload={progress:0,total:a.size,bytesSent:0},this.files.push(a),a.status=c.ADDED,this.emit("addedfile",a),this._enqueueThumbnail(a),this.accept(a,function(b){return function(c){return c?(a.accepted=!1,b._errorProcessing([a],c)):(a.accepted=!0,b.options.autoQueue&&b.enqueueFile(a)),b._updateMaxFilesReachedClass()}}(this))},c.prototype.enqueueFiles=function(a){var b,c,d;for(c=0,d=a.length;d>c;c++)b=a[c],this.enqueueFile(b);return null},c.prototype.enqueueFile=function(a){if(a.status!==c.ADDED||a.accepted!==!0)throw new Error("This file can't be queued because it has already been processed or was rejected.");return a.status=c.QUEUED,this.options.autoProcessQueue?setTimeout(function(a){return function(){return a.processQueue()}}(this),0):void 0},c.prototype._thumbnailQueue=[],c.prototype._processingThumbnail=!1,c.prototype._enqueueThumbnail=function(a){return this.options.createImageThumbnails&&a.type.match(/image.*/)&&a.size<=1024*this.options.maxThumbnailFilesize*1024?(this._thumbnailQueue.push(a),setTimeout(function(a){return function(){return a._processThumbnailQueue()}}(this),0)):void 0},c.prototype._processThumbnailQueue=function(){return this._processingThumbnail||0===this._thumbnailQueue.length?void 0:(this._processingThumbnail=!0,this.createThumbnail(this._thumbnailQueue.shift(),function(a){return function(){return a._processingThumbnail=!1,a._processThumbnailQueue()}}(this)))},c.prototype.removeFile=function(a){return a.status===c.UPLOADING&&this.cancelUpload(a),this.files=h(this.files,a),this.emit("removedfile",a),0===this.files.length?this.emit("reset"):void 0},c.prototype.removeAllFiles=function(a){var b,d,e,f;for(null==a&&(a=!1),f=this.files.slice(),d=0,e=f.length;e>d;d++)b=f[d],(b.status!==c.UPLOADING||a)&&this.removeFile(b);return null},c.prototype.createThumbnail=function(a,b){var c;return c=new FileReader,c.onload=function(d){return function(){return"image/svg+xml"===a.type?(d.emit("thumbnail",a,c.result),void(null!=b&&b())):d.createThumbnailFromUrl(a,c.result,b)}}(this),c.readAsDataURL(a)},c.prototype.createThumbnailFromUrl=function(a,b,c,d){var e;return e=document.createElement("img"),d&&(e.crossOrigin=d),e.onload=function(b){return function(){var d,g,h,i,j,k,l,m;return a.width=e.width,a.height=e.height,h=b.options.resize.call(b,a),null==h.trgWidth&&(h.trgWidth=h.optWidth),null==h.trgHeight&&(h.trgHeight=h.optHeight),d=document.createElement("canvas"),g=d.getContext("2d"),d.width=h.trgWidth,d.height=h.trgHeight,f(g,e,null!=(j=h.srcX)?j:0,null!=(k=h.srcY)?k:0,h.srcWidth,h.srcHeight,null!=(l=h.trgX)?l:0,null!=(m=h.trgY)?m:0,h.trgWidth,h.trgHeight),i=d.toDataURL("image/png"),b.emit("thumbnail",a,i),null!=c?c():void 0}}(this),null!=c&&(e.onerror=c),e.src=b},c.prototype.processQueue=function(){var a,b,c,d;if(b=this.options.parallelUploads,c=this.getUploadingFiles().length,a=c,!(c>=b)&&(d=this.getQueuedFiles(),d.length>0)){if(this.options.uploadMultiple)return this.processFiles(d.slice(0,b-c));for(;b>a;){if(!d.length)return;this.processFile(d.shift()),a++}}},c.prototype.processFile=function(a){return this.processFiles([a])},c.prototype.processFiles=function(a){var b,d,e;for(d=0,e=a.length;e>d;d++)b=a[d],b.processing=!0,b.status=c.UPLOADING,this.emit("processing",b);return this.options.uploadMultiple&&this.emit("processingmultiple",a),this.uploadFiles(a)},c.prototype._getFilesWithXhr=function(a){var b,c;return c=function(){var c,d,e,f;for(e=this.files,f=[],c=0,d=e.length;d>c;c++)b=e[c],b.xhr===a&&f.push(b);return f}.call(this)},c.prototype.cancelUpload=function(a){var b,d,e,f,g,h,i;if(a.status===c.UPLOADING){for(d=this._getFilesWithXhr(a.xhr),e=0,g=d.length;g>e;e++)b=d[e],b.status=c.CANCELED;for(a.xhr.abort(),f=0,h=d.length;h>f;f++)b=d[f],this.emit("canceled",b);this.options.uploadMultiple&&this.emit("canceledmultiple",d)}else((i=a.status)===c.ADDED||i===c.QUEUED)&&(a.status=c.CANCELED,this.emit("canceled",a),this.options.uploadMultiple&&this.emit("canceledmultiple",[a]));return this.options.autoProcessQueue?this.processQueue():void 0},e=function(){var a,b;return b=arguments[0],a=2<=arguments.length?i.call(arguments,1):[],"function"==typeof b?b.apply(this,a):b},c.prototype.uploadFile=function(a){return this.uploadFiles([a])},c.prototype.uploadFiles=function(a){var b,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L;for(w=new XMLHttpRequest,x=0,B=a.length;B>x;x++)b=a[x],b.xhr=w;p=e(this.options.method,a),u=e(this.options.url,a),w.open(p,u,!0),w.withCredentials=!!this.options.withCredentials,s=null,g=function(c){return function(){var d,e,f;for(f=[],d=0,e=a.length;e>d;d++)b=a[d],f.push(c._errorProcessing(a,s||c.options.dictResponseError.replace("{{statusCode}}",w.status),w));return f}}(this),t=function(c){return function(d){var e,f,g,h,i,j,k,l,m;if(null!=d)for(f=100*d.loaded/d.total,g=0,j=a.length;j>g;g++)b=a[g],b.upload={progress:f,total:d.total,bytesSent:d.loaded};else{for(e=!0,f=100,h=0,k=a.length;k>h;h++)b=a[h],(100!==b.upload.progress||b.upload.bytesSent!==b.upload.total)&&(e=!1),b.upload.progress=f,b.upload.bytesSent=b.upload.total;if(e)return}for(m=[],i=0,l=a.length;l>i;i++)b=a[i],m.push(c.emit("uploadprogress",b,f,b.upload.bytesSent));return m}}(this),w.onload=function(b){return function(d){var e;if(a[0].status!==c.CANCELED&&4===w.readyState){if(s=w.responseText,w.getResponseHeader("content-type")&&~w.getResponseHeader("content-type").indexOf("application/json"))try{s=JSON.parse(s)}catch(f){d=f,s="Invalid JSON response from server."}return t(),200<=(e=w.status)&&300>e?b._finished(a,s,d):g()}}}(this),w.onerror=function(){return function(){return a[0].status!==c.CANCELED?g():void 0}}(this),r=null!=(G=w.upload)?G:w,r.onprogress=t,j={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},this.options.headers&&d(j,this.options.headers);for(h in j)i=j[h],i&&w.setRequestHeader(h,i);if(f=new FormData,this.options.params){H=this.options.params;for(o in H)v=H[o],f.append(o,v)}for(y=0,C=a.length;C>y;y++)b=a[y],this.emit("sending",b,w,f);if(this.options.uploadMultiple&&this.emit("sendingmultiple",a,w,f),"FORM"===this.element.tagName)for(I=this.element.querySelectorAll("input, textarea, select, button"),z=0,D=I.length;D>z;z++)if(l=I[z],m=l.getAttribute("name"),n=l.getAttribute("type"),"SELECT"===l.tagName&&l.hasAttribute("multiple"))for(J=l.options,A=0,E=J.length;E>A;A++)q=J[A],q.selected&&f.append(m,q.value);else(!n||"checkbox"!==(K=n.toLowerCase())&&"radio"!==K||l.checked)&&f.append(m,l.value);for(k=F=0,L=a.length-1;L>=0?L>=F:F>=L;k=L>=0?++F:--F)f.append(this._getParamName(k),a[k],a[k].name);return this.submitRequest(w,f,a)},c.prototype.submitRequest=function(a,b){return a.send(b)},c.prototype._finished=function(a,b,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=c.SUCCESS,this.emit("success",e,b,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("successmultiple",a,b,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},c.prototype._errorProcessing=function(a,b,d){var e,f,g;for(f=0,g=a.length;g>f;f++)e=a[f],e.status=c.ERROR,this.emit("error",e,b,d),this.emit("complete",e);return this.options.uploadMultiple&&(this.emit("errormultiple",a,b,d),this.emit("completemultiple",a)),this.options.autoProcessQueue?this.processQueue():void 0},c}(b),a.version="4.2.0",a.options={},a.optionsForElement=function(b){return b.getAttribute("id")?a.options[c(b.getAttribute("id"))]:void 0},a.instances=[],a.forElement=function(a){if("string"==typeof a&&(a=document.querySelector(a)),null==(null!=a?a.dropzone:void 0))throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");return a.dropzone},a.autoDiscover=0,a.discover=function(){var b,c,d,e,f,g;for(document.querySelectorAll?d=document.querySelectorAll(".dropzone"):(d=[],b=function(a){var b,c,e,f;for(f=[],c=0,e=a.length;e>c;c++)b=a[c],f.push(/(^| )dropzone($| )/.test(b.className)?d.push(b):void 0);return f},b(document.getElementsByTagName("div")),b(document.getElementsByTagName("form"))),g=[],e=0,f=d.length;f>e;e++)c=d[e],g.push(a.optionsForElement(c)!==!1?new a(c):void 0);return g},a.blacklistedBrowsers=[/opera.*Macintosh.*version\/12/i],a.isBrowserSupported=function(){var b,c,d,e,f;if(b=!0,window.File&&window.FileReader&&window.FileList&&window.Blob&&window.FormData&&document.querySelector)if("classList"in document.createElement("a"))for(f=a.blacklistedBrowsers,d=0,e=f.length;e>d;d++)c=f[d],c.test(navigator.userAgent)&&(b=!1);else b=!1;else b=!1;return b},h=function(a,b){var c,d,e,f;for(f=[],d=0,e=a.length;e>d;d++)c=a[d],c!==b&&f.push(c);return f},c=function(a){return a.replace(/[\-_](\w)/g,function(a){return a.charAt(1).toUpperCase()})},a.createElement=function(a){var b;return b=document.createElement("div"),b.innerHTML=a,b.childNodes[0]},a.elementInside=function(a,b){if(a===b)return!0;for(;a=a.parentNode;)if(a===b)return!0;return!1},a.getElement=function(a,b){var c;if("string"==typeof a?c=document.querySelector(a):null!=a.nodeType&&(c=a),null==c)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector or a plain HTML element.");return c},a.getElements=function(a,b){var c,d,e,f,g,h,i,j;if(a instanceof Array){e=[];try{for(f=0,h=a.length;h>f;f++)d=a[f],e.push(this.getElement(d,b))}catch(k){c=k,e=null}}else if("string"==typeof a)for(e=[],j=document.querySelectorAll(a),g=0,i=j.length;i>g;g++)d=j[g],e.push(d);else null!=a.nodeType&&(e=[a]);if(null==e||!e.length)throw new Error("Invalid `"+b+"` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");return e},a.confirm=function(a,b,c){return window.confirm(a)?b():null!=c?c():void 0},a.isValidFile=function(a,b){var c,d,e,f,g;if(!b)return!0;for(b=b.split(","),d=a.type,c=d.replace(/\/.*$/,""),f=0,g=b.length;g>f;f++)if(e=b[f],e=e.trim(),"."===e.charAt(0)){if(-1!==a.name.toLowerCase().indexOf(e.toLowerCase(),a.name.length-e.length))return!0}else if(/\/\*$/.test(e)){if(c===e.replace(/\/.*$/,""))return!0}else if(d===e)return!0;return!1},"undefined"!=typeof jQuery&&null!==jQuery&&(jQuery.fn.dropzone=function(b){return this.each(function(){return new a(this,b)})}),"undefined"!=typeof module&&null!==module?module.exports=a:window.Dropzone=a,a.ADDED="added",a.QUEUED="queued",a.ACCEPTED=a.QUEUED,a.UPLOADING="uploading",a.PROCESSING=a.UPLOADING,a.CANCELED="canceled",a.ERROR="error",a.SUCCESS="success",e=function(a){var b,c,d,e,f,g,h,i,j,k;for(h=a.naturalWidth,g=a.naturalHeight,c=document.createElement("canvas"),c.width=1,c.height=g,d=c.getContext("2d"),d.drawImage(a,0,0),e=d.getImageData(0,0,1,g).data,k=0,f=g,i=g;i>k;)b=e[4*(i-1)+3],0===b?f=i:k=i,i=f+k>>1;return j=i/g,0===j?1:j},f=function(a,b,c,d,f,g,h,i,j,k){var l;return l=e(b),a.drawImage(b,c,d,f,g,h,i,j,k/l)},d=function(a,b){var c,d,e,f,g,h,i,j,k;if(e=!1,k=!0,d=a.document,j=d.documentElement,c=d.addEventListener?"addEventListener":"attachEvent",i=d.addEventListener?"removeEventListener":"detachEvent",h=d.addEventListener?"":"on",f=function(c){return"readystatechange"!==c.type||"complete"===d.readyState?(("load"===c.type?a:d)[i](h+c.type,f,!1),!e&&(e=!0)?b.call(a,c.type||c):void 0):void 0},g=function(){var a;try{j.doScroll("left")}catch(b){return a=b,void setTimeout(g,50)}return f("poll")},"complete"!==d.readyState){if(d.createEventObject&&j.doScroll){try{k=!a.frameElement}catch(l){}k&&g()}return d[c](h+"DOMContentLoaded",f,!1),d[c](h+"readystatechange",f,!1),a[c](h+"load",f,!1)}},a._autoDiscoverFunction=function(){return a.autoDiscover?a.discover():void 0},d(window,a._autoDiscoverFunction)}).call(this);;function CommonSale_ApplyCouponDialog(saleTaskID,applyDiscountFunc){if(!saleTaskID||saleTaskID==emptyGuid){Dear_Notification_Error('Please save this sale.');return;} window.saleApplyDiscountFunc=applyDiscountFunc;var couponCode='';if(!$('#saleCouponDialog').length){$('body').append($("\n
\n
\n
\n
\n

Apply coupon

\n \n
\n
\n
\n \n \n
\n
\n \n
\n
\n
\n \n
\n
\n
\n
\n ")));} $('#saleCouponDialog').modal('show');setTimeout(function(){$('#newSaleCouponCode').focus();},500);} function CommonSale_RenderExpiryDate(value){if(value==null){return'';} return" (".concat(Ext.util.Format.date(value,UserDateFormat),")");} function CommonSale_RemoveCoupon(applyDiscountFunc){dearSwal({title:'Confirmation',text:'Would you like to remove a coupon?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes, remove it!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){var saleTaskID=CommonSale_GetSaleTaskID();if(!saleTaskID){Dear_Notification_Error('Cannot determine sale task ID to remove coupon.');return;} Ext.Ajax.request({url:'/api/Sale_Index_Coupon',params:{taskID:saleTaskID},jsonData:Ext.encode({taskID:saleTaskID}),method:'PUT',success:function success(response){dearHelper.blockUI.hide();CommonSale_UpdateCouponButtons();if(typeof window[applyDiscountFunc]=='function'){window[applyDiscountFunc](true);} $('#saleCouponDialog').modal('hide');CommonSale_SubmitSaleTask();}});}});} function ShowMultipleCoupons(){var saleTaskID=CommonSale_GetSaleTaskID();dearHelper.blockUI.show('Please wait...');$.get('/api/Sale_Index_Coupon',{taskID:saleTaskID},function(data){dearHelper.blockUI.hide();var couponCode='';if(!$('#saleMulripleCouponDialog').length){$('body').append($("\n
\n
\n
\n
\n

Applied coupons

\n \n
\n
\n
\n \n
\n
\n
\n
\n "));} var html='';for(var i=0;i".concat(Ext.htmlEncode(data[i].DealName),"").concat(Ext.htmlEncode(data[i].CouponCode),"");} $('#saleMulripleCouponDialogBody').html("".concat(html,"
DealCoupon code
"));$('#saleMulripleCouponDialog').modal('show');});} function CommonSale_GetSaleTaskID(){return typeof Opportunity_Index_GetOpportunityProperty=='function'?Opportunity_Index_GetOpportunityProperty('OpportunityID'):typeof SaleMult_Index_GetSaleTaskProperty=='function'?SaleMult_Index_GetSaleTaskProperty('OpportunityID'):typeof SaleService_Index_GetSaleTaskProperty=='function'?SaleService_Index_GetSaleTaskProperty('OpportunityID'):'';} function CommonSale_SubmitSaleTask(){if(typeof Sale_Index_Submit=='function'){Sale_Index_Submit();}else if(typeof SaleMult_Index_Submit=='function'){SaleMult_Index_Submit();}else if(typeof SaleService_Index_Submit=='function'){SaleService_Index_Submit();}} function CommonSale_AddCoupon(saleTaskID){var code=$('#newSaleCouponCode').val();if(!code){Dear_Notification_Error('Please enter a coupon code.');return;} dearHelper.blockUI.show('Please wait...');$.post('/api/Sale_Index_Coupon',{taskID:saleTaskID,couponCode:code},function(data){dearHelper.blockUI.hide();if(data.success){$('#saleCouponDialog').modal('hide');CommonSale_UpdateCouponButtons(code,data.couponDealName,1);if(typeof window.saleApplyDiscountFunc=='function'){window.saleApplyDiscountFunc(true);} $('#newSaleCouponCode').val('');}else{Dear_Notification_Error(data.message);}});} function CommonSale_UpdateCouponButtons(couponCode,couponDealName,appliedCouponNumber){if(appliedCouponNumber>1){$('.btnApplyCoupon').addClass('hidden');$('.btnRemoveCoupon').removeClass('hidden').html(Ext.String.format('{0}Applied{1} {2}{3} coupons{4}','','','',appliedCouponNumber,''));}else if(couponCode){$('.btnApplyCoupon').addClass('hidden');$('.btnRemoveCoupon').removeClass('hidden').html(Ext.String.format('Coupon {0} ({1}) {2}remove{3}',couponCode,couponDealName,'',''));}else{$('.btnApplyCoupon').removeClass('hidden');$('.btnRemoveCoupon').addClass('hidden');}} window.GiftCardGlobalSettings={};window.giftButtonSelector=null;function formatMoney(v){if(!v){v='';} var m=DEARMoneyFormat(Number(v));m=m.replace(/[^\d.-]/g,'');return m;} Ext.define('GiftCardGlobalSettings',{idProperty:'GiftCardProductID',extend:'Ext.data.Model',fields:[{name:'GiftCardProductID',type:'string'},{name:'IsGiftCardEnabled',type:'bool'},{name:'DefaultGiftCardExpirationPeriod',type:'string'},{name:'CanGiftCardExpire',type:'bool'},{name:'GiftCardSaleTaxID',type:'string'},{name:'GiftProductName',type:'string'},{name:'GiftProductCode',type:'string'},{name:'GiftCardRevenueAccount',type:'string'},{name:'GiftCardRevenueAccountName',type:'string'},{name:'CanGiftCardRefund',type:'bool'}]});Ext.define('vSaleGiftCards',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'TaskID',type:'string'},{name:'GiftCardCode',type:'string'},{name:'InitialBalance',type:'float'},{name:'CurrentBalance',type:'float'},{name:'Date',type:'date',dateFormat:'c'},{name:'ExpirationDate',type:'date',dateFormat:'c'},{name:'RefundID',type:'string'}]});window.GiftCardGlobalSettingsStore=Ext.create('Ext.data.JsonStore',{model:'GiftCardGlobalSettings',proxy:{type:'rest',reader:{type:'json',root:'GiftCardGlobalSettings'}},listeners:{load:function load(store,operation){window.GiftCardGlobalSettings={};if(store.totalCount>0){window.GiftCardGlobalSettings=store.getAt(0).raw;}}}});if($('#newPayGiftCardAmount').length>0){window.newPayGiftCardAmount=dearHelper.control.init('#newPayGiftCardAmount');dearHelper.control.addNumberMaskWithDecmal(window.newPayGiftCardAmount,{rightAlign:false});} window.dtLockDate=$('#newSaleGiftCardExpirationDate').dearDatepicker({autoclose:true,enableOnReadonly:false,dateFormat:'d/m/Y',altFormats:window.dearAltFormats});window.GiftCardGlobalSettings={};function CommonSale_ShowGiftCardDialog(){var saleTaskID=CommonSale_GetSaleTaskID();if(!saleTaskID||saleTaskID==emptyGuid){Dear_Notification_Error('Please save this sale.');return;} if(window.GiftCardGlobalSettings.CanGiftCardExpire===true){$('#newGiftCardExpirationSection').show();var expDate=null;switch(window.GiftCardGlobalSettings.DefaultGiftCardExpirationPeriod){case'month':expDate=moment().add(1,'M');break;case'quarter':expDate=moment().add(3,'M');break;case'threeyears':expDate=moment().add(3,'Y');break;case'fiveyears':expDate=moment().add(5,'Y');break;default:expDate=moment().add(12,'M');break;} dearHelper.control.setValue(dtLockDate,expDate.format('DD/MM/YYYY'));}else{$('#newGiftCardExpirationSection').hide();} $('#saleGiftCardDialog').modal('show');setTimeout(function(){$('#newSaleGiftCardCode').focus();},500);} function checkGiftCardIsUnique(code,callback){$.post('/api/Sale_Index_GiftCard',{giftCardCode:code},function(data){if(typeof callback==='function'){callback(data);}});} function Sale_AddGiftCardToAdditionalChargesLines(code,dt,amount){switch(giftButtonSelector){case'#divNewGiftCard_Order':if(!StatusTracker.order.readOnly){addNewGiftCard_Order(code,dt,amount);} break;case'#divNewGiftCard_Invoice':if(!StatusTracker.invoice.readOnlyLines){addNewGiftCard_Invoice(code,dt,amount);} break;}} function Common_UpdateTotals(){var formType=SaleFormType();if(formType=='salemult'){SaleMult_Invoice_UpdateTotals();}else if(formType=='saleservice'){SaleService_Invoice_UpdateTotals();}else{Sale_Invoice_UpdateTotals();}} function SaleFormType(){if(typeof Sale_Index_Submit=='function'){return'sale';}else if(typeof SaleMult_Index_Submit=='function'){return'salemult';}else if(typeof SaleService_Index_Submit=='function'){return'saleservice';} return null;} window.currentGiftCardBalance=0;window.currentGiftCardID=null;window.lastChecked=null;function CommonSale_CheckGiftCard(){lastChecked=null;var val=$('#newPayGiftCardCode').val().trim();if(!val){Dear_Notification_Error('Please enter the gift card code.');return;} $('#newPayGiftCardCode').select();window.currentGiftCardBalance=0;window.currentGiftCardID=null;dearHelper.blockUI.show('Please wait...');CheckGiftCardBalance(val,function(data){dearHelper.blockUI.hide();if(data.success!==true){Dear_Notification_Error("Gift card doesn't exist.");}else if(data.isRefunded===true){Dear_Notification_Error('This gift card has been refunded.');}else if(data.isForfeited===true){Dear_Notification_Error('This gift card has been forfeited.');}else{window.currentGiftCardBalance=formatMoney(data.balance);window.currentGiftCardID=data.giftCardID;lastChecked=$('#newPayGiftCardCode').val();var el=$('#giftCardCurrentBalance');if(el.is('input')){$('#giftCardCurrentBalance').val(currentGiftCardBalance);}else{$('#giftCardCurrentBalance').text(currentGiftCardBalance);} enableButton('#applyGiftCardPayment',true);}});} function fieldGiftCardIsChanged(){if(lastChecked==null||lastChecked!=$('#newPayGiftCardCode').val()||!currentGiftCardBalance){window.currentGiftCardBalance='';var el=$('#giftCardCurrentBalance');if(el.is('input')){$('#giftCardCurrentBalance').val(currentGiftCardBalance);}else{$('#giftCardCurrentBalance').text(currentGiftCardBalance);} enableButton('#applyGiftCardPayment',false);}else{enableButton('#applyGiftCardPayment',true);}} function CommonSale_PayByGiftCard(){var code=$('#newPayGiftCardCode').val().trim();var amount=$('#newPayGiftCardAmount').val().trim();var amountCheck=/^\d+$/;if(!amount){Dear_Notification_Error('Please enter the amount to pay with this gift card.');return;} if(!amountCheck.test(amount)){Dear_Notification_Error('Amount should consist only numbers.');return;} amount=formatMoney(amount);var balance=formatMoney(currentGiftCardBalance);if(!code){Dear_Notification_Error('Please enter the gift card code.');return;} if(Number(amount)<=0){Dear_Notification_Error('Please enter the amount to pay with this gift card.');return;} if(Number(amount)>Number(balance)){Dear_Notification_Error('Please enter the amount to pay with this gift card that is less than or equal to the current gift card balance.');return;} dearHelper.blockUI.show('Please wait...');CheckGiftCardBalance(code,function(data){dearHelper.blockUI.hide();if(data.success!==true){Dear_Notification_Error("Gift card doesn't exist or has expired.");}else{window.currentGiftCardBalance=formatMoney(data.balance);window.currentGiftCardID=data.giftCardID;var el=$('#giftCardCurrentBalance');if(el.is('input')){$('#giftCardCurrentBalance').val(currentGiftCardBalance);}else{$('#giftCardCurrentBalance').text(currentGiftCardBalance);} enableButton('#applyGiftCardPayment',true);if(Number(amount)>Number(balance)){Dear_Notification_Error('Please enter the amount to pay with this gift card that is less than or equal to the current gift card balance.');return;} if(AddGiftCardPayment(code,amount)==true){$('#payGiftCardDialog').modal('hide');$('#newPayGiftCardCode').val('');$('#newPayGiftCardAmount').val('');fieldGiftCardIsChanged();}}});} function CheckPaymentGiftCardRelated(record){var gid=record.get('SaleGiftCardID');return!!gid;} function CheckRefundGiftCardRelated(record){var gid=record.get('InvoiceCostID');var formType=SaleFormType();var store;if(formType=='salemult'){var masterTask=OpportunityUpdated.getAt(0);store=masterTask.vSaleGiftCardsStore;}else{store=vSaleGiftCardStore;} var record=store.findExact('RefundID',gid);return record>=0;} function AddGiftCardPayment(giftCardCode,amount){var formType=SaleFormType();var saleTaskID=formType=='salemult'?window.SelectedInvoiceTaskID:CommonSale_GetSaleTaskID();var invoiceTask=formType=='salemult'?SaleMult_Index_GetTaskByID(window.SelectedInvoiceTaskID):null;var store;if(formType=='salemult'){var masterTask=OpportunityUpdated.getAt(0);store=masterTask.vSaleGiftCardsStore;}else{store=vSaleGiftCardStore;} var rec=store.getById(currentGiftCardID);if(rec){Dear_Notification_Error('This gift card is in this sale. It cannot be used for payment in the same sale.');return false;} var paymentStore=!invoiceTask?vSalePaymentLinesStore:invoiceTask.vSalePaymentLinesStore;var orderIndex=paymentStore.findExact('SaleGiftCardID',currentGiftCardID);if(orderIndex>=0){Dear_Notification_Error('This gift card is already used for payment. Please, enter another gift card code.');return false;} var PaymentID=guid();var r=Ext.create('vSalePaymentLines',{PaymentID:PaymentID,Amount:amount,Type:'ACCREC',PaymentType:'R',DatePaid:new Date(),AccountCode:window.GiftCardGlobalSettings.GiftCardRevenueAccount,Reference:giftCardCode,CurrencyConversionRate:1,SaleGiftCardID:currentGiftCardID,SaleGiftCardCode:giftCardCode,ValidationText:'',ValidationState:'Good'});r.setDirty();paymentStore.add(r);Common_UpdateTotals();return true;} function MarkGiftCardAsRefunded(id,refundID){var formType=SaleFormType();var store;if(formType=='salemult'){var masterTask=OpportunityUpdated.getAt(0);store=masterTask.vSaleGiftCardsStore;}else{store=vSaleGiftCardStore;} var record=store.getById(id);if(record){if(window.GiftCardGlobalSettings.CanGiftCardRefund!==true){Dear_Notification_Error('Gift card refund is not allowed.');return false;} record.data.RefundID=refundID;record.setDirty();} return true;} function MarkGiftCardAsNotRefunded(refundID){var formType=SaleFormType();var store;if(formType=='salemult'){var masterTask=OpportunityUpdated.getAt(0);store=masterTask.vSaleGiftCardsStore;}else{store=vSaleGiftCardStore;} var idx=store.findExact('RefundID',refundID);if(idx>=0){var record=store.getAt(idx);record.data.RefundID=null;record.setDirty();}} function giftCardPress(e){if(e.keyCode===13){e.preventDefault();CommonSale_CheckGiftCard();}} function GetOnHandValue(values){if(values.Type!=='Non Inventory'){return values.OnHand;}else{return'N/A';}} function CommonSale_GetCustomerForNewSale(){try{if(sessionStorage['newSaleCustomer']!=null){var customerInfo=Ext.JSON.decode(sessionStorage['newSaleCustomer']);sessionStorage.removeItem('newSaleCustomer');return customerInfo;}}catch(e){} return null;} var CommonSale=CommonSale||{};CommonSale.Avalara=function(){var _wrapperStore;var _hasAvalaraIntegration;var _customerAddressStore=null;var vSale_AvalaraSaleTaxCodeStore;var cmbAvalaraTaxExemptionCode;var cmbAvalaraTaxExemptionCode_NewAddress;var _currentSelectedCode;var _isDisabled;var _isFirst=true;function InitialControls(wrapperStore){_wrapperStore=wrapperStore;var wrapperRecord=_wrapperStore.getAt(0);_hasAvalaraIntegration=wrapperRecord.get('HasAvalaraIntegration');if(_hasAvalaraIntegration===true){$('#SaleCommon_AvalaraTaxExemptionCode').removeClass('hiddenContent');$('#SaleCommon_NewAddress_AvalaraTaxExemptionCode').removeClass('hiddenContent');Ext.define('AvalaraSaleTaxCode',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'Name',type:'string'}]});vSale_AvalaraSaleTaxCodeStore=Ext.create('Ext.data.JsonStore',{model:'AvalaraSaleTaxCode',proxy:{type:'rest',url:'/api/Avalara_Index_vTaxCodeList/TaxExemptionReason',reader:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,null);}}}});cmbAvalaraTaxExemptionCode=Ext.create('Ext.ux.ComboBox',{store:vSale_AvalaraSaleTaxCodeStore,queryMode:'local',triggerAction:'all',selectOnTab:true,displayField:'Name',valueField:'Code',enableKeyEvents:true,renderTo:'cmbAvalaraTaxExemptionCode',emptyText:'choose...',selectOnFocus:true,inputId:'SaleTask_cmbAvalaraTaxExemptionCode',listeners:{select:function select(field,records){var wrapperRecord=wrapperStore.getAt(0);wrapperRecord.set('AvalaraTaxExemptionCode',cmbAvalaraTaxExemptionCode.getValue());wrapperRecord.setDirty();},change:function change(field,newValue){var wrapperRecord=wrapperStore.getAt(0);wrapperRecord.set('AvalaraTaxExemptionCode',newValue);wrapperRecord.setDirty();},blur:HideComboInputElement,focus:ShowInputElement}});cmbAvalaraTaxExemptionCode_NewAddress=Ext.create('Ext.ux.ComboBox',{store:vSale_AvalaraSaleTaxCodeStore,queryMode:'local',triggerAction:'all',selectOnTab:true,displayField:'Name',valueField:'Code',enableKeyEvents:true,renderTo:'cmbAvalaraTaxExemptionCode_NewAddress',emptyText:'choose...',selectOnFocus:true,inputId:'SaleTask_cmbAvalaraTaxExemptionCode_NewAddress',listeners:{blur:HideComboInputElement,focus:ShowInputElement,beforequery:function beforequery(queryEvent,eOpts){if(window.vSale_AvalaraTaxExemptionCodeStoreQuery){queryEvent.query=window.vSale_NewAddress_AvalaraTaxExemptionCodeStoreQuery;}},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.vSale_NewAddress_AvalaraTaxExemptionCodeStoreQuery=Me.getRawValue();}}}});vSale_AvalaraSaleTaxCodeStore.load({callback:function callback(){if(wrapperRecord.get('AvalaraTaxExemptionCode')){SelectValue(wrapperRecord.get('AvalaraTaxExemptionCode'));} if(window.vSale_CustomerAddressStore&&window.vSale_CustomerAddressStore.getCount()>0){_customerAddressStore=window.vSale_CustomerAddressStore;} if(window.vSaleMult_CustomerAddressStore&&window.vSaleMult_CustomerAddressStore.getCount()>0){_customerAddressStore=window.vSaleMult_CustomerAddressStore;} if(_customerAddressStore){var taxCode=_customerAddressStore.getAt(0).get('TaxExemptionReasonCode');if(taxCode){cmbAvalaraTaxExemptionCode.setValue(taxCode);}}}});}} function SelectValue(code){if(_hasAvalaraIntegration===true&&(_isDisabled!==true||_isFirst)){if(code){cmbAvalaraTaxExemptionCode.setValue(code);}else{cmbAvalaraTaxExemptionCode.setValue(null);} _isFirst=false;var wrapperRecord=_wrapperStore.getAt(0);wrapperRecord.set('AvalaraTaxExemptionCode',code);wrapperRecord.setDirty();}} function resizeSaleCmb(width){if(_hasAvalaraIntegration===true){cmbAvalaraTaxExemptionCode.setWidth(width);}} function resizeSaleAddressCmb(width){if(_hasAvalaraIntegration===true){cmbAvalaraTaxExemptionCode_NewAddress.setWidth(width);}} function SetAddressType(type){if(_hasAvalaraIntegration===true){cmbAvalaraTaxExemptionCode_NewAddress.setValue(null);if(type==='Shipping'){$('#SaleCommon_NewAddress_AvalaraTaxExemptionCode').removeClass('hiddenContent');}else{_currentSelectedCode=null;$('#SaleCommon_NewAddress_AvalaraTaxExemptionCode').addClass('hiddenContent');}}} function SetBillingAddressType(type){if(_hasAvalaraIntegration===true){cmbAvalaraTaxExemptionCode_NewAddress.setValue(null);if(type==='Billing'){$('#SaleCommon_NewAddress_AvalaraTaxExemptionCode').removeClass('hiddenContent');}else{_currentSelectedCode=null;$('#SaleCommon_NewAddress_AvalaraTaxExemptionCode').addClass('hiddenContent');}}} function getCurrentSelectedCode(){if(_hasAvalaraIntegration===true){return cmbAvalaraTaxExemptionCode_NewAddress.getValue();} return null;} function getStore(){if(_hasAvalaraIntegration===true){return vSale_AvalaraSaleTaxCodeStore;} return null;} function setDisabled(f){if(_hasAvalaraIntegration===true){_isDisabled=f;return cmbAvalaraTaxExemptionCode.setDisabled(_isDisabled);}} return{initialization:InitialControls,selectValue:SelectValue,getCurrentSelectedCode:getCurrentSelectedCode,resizeSaleCmb:resizeSaleCmb,resizeSaleAddressCmb:resizeSaleAddressCmb,setAddressType:SetAddressType,setBillingAddressType:SetBillingAddressType,getStore:getStore,setDisabled:setDisabled};}();function CommonSale_CheckVisibleTaxExemptionCode(activeTab){return;} function CommonSale_NewProduct_DefaultValuesInit(){var cmbFields=[];var entityType=window.DefaultFieldValuesConstant.EntityTypes.Product;function add(fieldName,element){if(element){cmbFields.push({FieldName:fieldName,Element:element});}} var el=window.cmbSale_NewProduct_Type?window.cmbSale_NewProduct_Type:window.cmbSaleMult_NewProduct_Type?window.cmbSaleMult_NewProduct_Type:window.cmbSaleService_NewProduct_Type;add(window.DefaultFieldValuesConstant.FieldNames.ProductType,el);el=window.cmbSale_NewProduct_Category?window.cmbSale_NewProduct_Category:window.cmbSaleMult_NewProduct_Category?window.cmbSaleMult_NewProduct_Category:window.cmbSaleService_NewProduct_Category;add(window.DefaultFieldValuesConstant.FieldNames.ProductCategory,el);el=window.cmbSale_NewProduct_CostingMethod?window.cmbSale_NewProduct_CostingMethod:window.cmbSaleMult_NewProduct_CostingMethod?window.cmbSaleMult_NewProduct_CostingMethod:window.cmbSaleService_NewProduct_CostingMethod;add(window.DefaultFieldValuesConstant.FieldNames.ProductCostingMethod,el);el=window.cmbSale_NewProduct_UnitOfMeasure?window.cmbSale_NewProduct_UnitOfMeasure:window.cmbSaleMult_NewProduct_UnitOfMeasure?window.cmbSaleMult_NewProduct_UnitOfMeasure:window.cmbSaleService_NewProduct_UnitOfMeasure;add(window.DefaultFieldValuesConstant.FieldNames.ProductUnitMeasure,el);el=window.cmbSale_NewProduct_DropShipMode?window.cmbSale_NewProduct_DropShipMode:window.cmbSaleMult_NewProduct_DropShipMode?window.cmbSaleMult_NewProduct_DropShipMode:window.cmbSaleService_NewProduct_DropShipMode;add(window.DefaultFieldValuesConstant.FieldNames.ProductDropShip,el);el=window.Sale_NewProduct_cmbProductAttributeSet?window.Sale_NewProduct_cmbProductAttributeSet:window.SaleMult_NewProduct_cmbProductAttributeSet?window.SaleMult_NewProduct_cmbProductAttributeSet:window.SaleService_NewProduct_cmbProductAttributeSet;add(window.DefaultFieldValuesConstant.FieldNames.ProductAttrSet,el);DFVHandler.init(entityType,cmbFields,window.DefaultFieldValuesConstant);} function CommonSale_NewCustomer_DefaultValuesInit(){var cmbFields=[];var entityType=window.DefaultFieldValuesConstant.EntityTypes.Customer;function add(fieldName,element){if(element){cmbFields.push({FieldName:fieldName,Element:element});}} add(window.DefaultFieldValuesConstant.FieldNames.CustomerCurrency,window.cmbSale_NewCustomer_Currency?window.cmbSale_NewCustomer_Currency:window.cmbSaleMult_NewCustomer_Currency);add(window.DefaultFieldValuesConstant.FieldNames.CustomerPaymentTerm,window.cmbSale_NewCustomer_PaymentTerm?window.cmbSale_NewCustomer_PaymentTerm:window.cmbSaleMult_NewCustomer_PaymentTerm);add(window.DefaultFieldValuesConstant.FieldNames.CustomerTaxRules,window.cmbSale_NewCustomer_TaxRule?window.cmbSale_NewCustomer_TaxRule:window.cmbSaleMult_NewCustomer_TaxRule);add(window.DefaultFieldValuesConstant.FieldNames.CustomerSalePriceTier,window.cmbSale_NewCustomer_SalePriceTier?window.cmbSale_NewCustomer_SalePriceTier:window.cmbSaleMult_NewCustomer_SalePriceTier);add(window.DefaultFieldValuesConstant.FieldNames.CustomerSalesRepresentative,window.cmbSale_NewCustomer_DefaultSalesRepresentative?window.cmbSale_NewCustomer_DefaultSalesRepresentative:window.cmbSaleMult_NewCustomer_DefaultSalesRepresentative);DFVHandler.init(entityType,cmbFields,window.DefaultFieldValuesConstant);} window.controlIndexes={customer:10,contact:20,phone:30,email:40,customerRef:50,billAddr:51,billAddr2:53,priceTier:54,terms:55,salesRep:56,account:58,convRate:59,taxRule:60,taxInclusive:61,skipQuote:62,recurringTask:63,date:64,shipToCompany:65,shipToContact:66,shipAddr:67,shipAddr2:68,shipNotes:70,reqBy:71,comments:72,recuringFreq:150};function Sale_Index_CollapseToggle(){var expander=$('.expandPanel');var parent=expander.closest('.page-block');if(parent.hasClass('collapsed')){parent.removeClass('collapsed');}else{parent.addClass('collapsed');}} function randomGridInc(){return'_a';} function tpl_simpleList(){var fieldToDisplay=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'Description';return new Ext.XTemplate("\n \n "));} function tpl_productFullWithModal(modalcall){var modulePrefix=modalcall.split('_').shift();return new Ext.XTemplate("\n
\n
Add a new item
\n
\n \n "));} function tpl_serviceListWithModal(modalcall){var addLink=modalcall?"
Add a new item
"):'';return new Ext.XTemplate("\n
\n ".concat(addLink,"\n
\n \n "));} function tpl_carrierListWithModal(modalcall){return new Ext.XTemplate("\n
\n
Add a new item
\n
\n \n "));} function tpl_carrierExternalList(){return new Ext.XTemplate("\n \n ");} function tpl_productFullWithAttr(){return new Ext.XTemplate("\n
\n
\n
Batch/serial #
\n
Location
\n
Available
\n
\n \n
\n
\n \n
\n
\n
\n {[RenderHTMLText(values.Name)]}\n \n
\n
\n SKU: {[RenderHTMLText(values.ProductCode)]}\n \n
\n
\n
\n
\n
N/A{[RenderHTMLText(values.BatchSN)]}{[CommonSale_RenderExpiryDate(values.ExpiryDate)]}
\n
{[RenderHTMLText(values.Location)]}
\n
{Available}
\n
\n
\n
\n ");} function tpl_productWithAttr(){return new Ext.XTemplate("\n
\n
\n
Product
\n
Available
\n
\n \n
\n
\n \n
\n
\n
\n {[RenderHTMLText(values.Name)]}\n \n
\n
\n SKU: {[RenderHTMLText(values.ProductCode)]}\n {RemainingQuantity}\n
\n
\n
\n
\n
\n ");} function tpl_serviceFullWithAttr(){return new Ext.XTemplate("\n
\n
\n
Batch/serial #
\n
Expiry date
\n
Location
\n
Available
\n
\n \n
\n
N/A{[RenderHTMLText(values.BatchSN)]}
\n
{ExpiryDate:date(UserDateFormat)}
\n
{[RenderHTMLText(values.Location)]}
\n
{Available}
\n
\n
\n
\n ");} function tpl_productInvoice(){return new Ext.XTemplate("\n \n ");};window.SaleStatuses={};window.SaleStatuses['ORDERING']={title:'Ordering',clColor:'draft'};window.SaleStatuses['ESTIMATED']={title:'Estimated',clColor:'draft'};window.SaleStatuses['QUOTE COMPLETED']={title:'Estimated',clColor:'draft'};window.SaleStatuses['ESTIMATING']={title:'Estimating',clColor:'draft'};window.SaleStatuses['DRAFT']={title:'Draft',clColor:'draft'};window.SaleStatuses['SO IN PROGRESS']={title:'Ordering',clColor:'draft'};window.SaleStatuses['QUOTE IN PROGRESS']={title:'Estimating',clColor:'draft'};window.SaleStatuses['AWAITING APPROVAL']={title:'Awaiting approval',clColor:'draft'};window.SaleStatuses['IN PROGRESS']={title:'In progress',clColor:'new'};window.SaleStatuses['CLOSED']={title:'Closed',clColor:'completed'};window.SaleStatuses['COMPLETED']={title:'Completed',clColor:'completed'};window.SaleStatuses['COMPLETED / CREDIT NOTE']={title:'Credited',clColor:'completed'};window.SaleStatuses['CREDITED']={title:'Credited',clColor:'completed'};window.SaleStatuses['VOIDED']={title:'Voided',clColor:'voided'};window.SaleStatuses['BACKORDERED']={title:'Backordered',clColor:'backordered'};window.SaleStatuses['PARTIALLY INVOICED / CREDITED']={title:'Partially invoiced / credited',clColor:'invoicing'};window.SaleStatuses['INVOICE IN PROGRESS']={title:'Invoicing',clColor:'invoicing'};window.SaleStatuses['QUOTE COMPLETED']={title:'Estimated',clColor:'invoicing'};window.SaleStatuses['PARTIALLY INVOICED']={title:'Partially invoiced',clColor:'invoicing'};window.SaleStatuses['INVOICED / CREDITED']={title:'Invoiced / credited',clColor:'invoicing'};window.SaleStatuses['INVOICED']={title:'Invoiced',clColor:'invoicing'};window.SaleStatuses['INVOICE COMPLETED']={title:'Invoiced',clColor:'invoicing'};window.SaleStatuses['ORDERED']={title:'Ordered',clColor:'ordered'};window.SaleStatuses['PICK IN PROGRESS']={title:'Picking',clColor:'ordered'};window.SaleStatuses['SO COMPLETED']={title:'Ordered',clColor:'ordered'};window.SaleStatuses['PACK COMPLETED']={title:'Packed',clColor:'packed'};window.SaleStatuses['PACK IN PROGRESS']={title:'Packing',clColor:'picked'};window.SaleStatuses['PICK COMPLETED']={title:'Picked',clColor:'picked'};window.SaleStatuses['SHIPMENT IN PROGRESS']={title:'Shipping',clColor:'shipping'};window.SaleStatuses['PAID']={title:'Paid',clColor:'default'};window.SaleStatuses['AUTHORISED']={title:'Authorised',clColor:'authorised'};function SaleList_Index_AdjustStatus(status){var obj=window.SaleStatuses[status];if(obj){return obj.title;} return status;} function Sale_Shared_RenderStatus(status){var obj=window.SaleStatuses[status];if(obj){return"").concat(obj.title,"");} return status;};function Sale_AdditionalCOGS_IsFieldEditable(){if(StatusTracker.additionalCOGS.readOnly){return false;} return true;} function Sale_AdditionalCOGS_CreateControls(){window.vSaleAdditionalCOGSEditing=Ext.create('Ext.grid.plugin.CellEditing',{clicksToEdit:1,listeners:{beforeedit:function beforeedit(editor,e,eOpts){if(StatusTracker.additionalCOGS.readOnly){return false;}},edit:function edit(editor,e){if(enterpressed){window.enterpressed=false;vSaleAdditionalCOGSEditing.startEditByPosition(vSaleAdditionalCOGSGrid.getSelectionModel().getCurrentPosition());} if(e.field=='Debit'||e.field=='Credit'){var c=vChartOfAccountsForAdditionalCOGSStore.getCount();var isFound=false;for(var i=0;itype to search...';}}},{header:'Start time',flex:1,dataIndex:'Date',xtype:'datecolumn',editor:{xtype:'datefield',selectOnFocus:true,format:UserDateFormat,altFormats:dearAltFormats,listeners:{blur:HideDateInputElement,focus:ShowInputElement,specialkey:function specialkey(field,e){ColumnTab(e);}}},format:UserDateFormat},{header:'End time',flex:1,dataIndex:'Amount',itemId:'colAmount_AdditionalCOGS',align:'right',renderer:function renderer(val){if(HasPriceInfoAccess){if(val!=null){return DEARMoneyFormat(val);}else{return'';}}else{return'No access';}},editor:new Ext.form.field.Number({allowBlank:false,hideTrigger:true,step:0,selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vSaleAdditionalCOGSGrid,vSaleAdditionalCOGSEditing,e);ColumnTab(e);}}})},window.extExtension.column.getDelete({id:'colDeleteAdditionalCOGS',listeners:{click:function click(grid,td,rowIndex){vSaleAdditionalCOGSStore.removeAt(rowIndex);}}})],selModel:{selType:'cellmodel'},renderTo:'divAdditionalTransactionsContainer',flex:1,plugins:[vSaleAdditionalCOGSEditing]});} function Sale_AdditionalCOGS_AddLine(){if(!StatusTracker.additionalCOGS.readOnly){if(typeof COGSAccount!=='undefined'){var r=Ext.create('vSaleAdditionalCOGS',{Debit:COGSAccount,Amount:0,LineOrder:0,Date:new Date(),ValidationText:'',ValidationState:'Good'});r.setDirty();vSaleAdditionalCOGSStore.add(r);StatusTracker.additionalCOGS.setStatus(StatusTracker.statuses.draft);vSaleAdditionalCOGSEditing.startEdit(r,vSaleAdditionalCOGSGrid.columns[1]);}else{Dear_Notification_Warning('Your Cost of Goods Sold (COGS) account is not defined in account mapping.');}}} function Sale_AdditionalCOGS_ResetLayout(){vSaleAdditionalCOGSGrid.reconfigure(null,vSaleAdditionalCOGSGrid.initialConfig.columns);Ext.each(vSaleAdditionalCOGSGrid.columns,function(column){if(column.getEditor()){column.setEditor(column.getEditor().cloneConfig());}});vSaleAdditionalCOGSGrid.getView().getHeaderCt().child('#colDeleteAdditionalCOGS').setVisible(!StatusTracker.additionalCOGS.readOnly);} function Sale_AdditionalCOGS_Complete(){if(vSaleAdditionalCOGSStore.getCount()==0){Dear_Notification_Warning('Your manual journals list is empty. You cannot authorise an empty manual journals list.');}else{StatusTracker.additionalCOGS.setStatus(StatusTracker.statuses.authorized);window.PlannedOperation='';Opportunity_Index_Submit();}} Dropzone.autoDiscover=false;function Opportunity_Attachments_CreateControls(){window.FileUploadInProgress=false;window.GridOpportunity_Attachments=Ext.create('Ext.grid.Panel',{header:false,border:false,stateful:true,stateId:"OpportunityAttachments".concat(randomGridInc()),store:AttachmentsStore,cls:'edit-grid',emptyText:'You do not have any files attached.',viewConfig:{markDirty:false},listeners:{viewready:GridTooltipsListener},columns:[{header:'Name',flex:2,dataIndex:'FileName',renderer:function renderer(val,meta,record){if(record.get('ContentType')=='Email'){return"").concat(RenderHTMLText(val),"");}else{return Common_CreateAttachmentLink(val,record,'Opportunity');}}},{header:'Date',flex:1,dataIndex:'Date',renderer:function renderer(val){return Ext.util.Format.date(val,"".concat(UserDateFormat," H:i:s"));}},{header:'Attached by',flex:2,dataIndex:'UserName',renderer:RenderHTMLText},{header:'Processed',width:80,dataIndex:'IsProcessed',xtype:'checkcolumn',stopSelection:false,renderer:function renderer(value,metaData,record){var cssPrefix=Ext.baseCSSPrefix;var cls=["".concat(cssPrefix,"grid-checkheader")];if(IsReadOnly){if(value){cls.push("".concat(cssPrefix,"grid-checkheader-disabled-checked"));}else{cls.push("".concat(cssPrefix,"grid-checkheader-disabled"));}}else if(value){cls.push("".concat(cssPrefix,"grid-checkheader-checked"));} return"
 
");},listeners:{beforecheckchange:function beforecheckchange(me,recordIndex,checked){return!IsReadOnly;},checkchange:function checkchange(me,recordIndex,checked){AttachmentsStore.save();}}},window.extExtension.column.getDelete({id:'colDeleteAttachments',listeners:{click:function click(grid,td,rowIndex){var record=AttachmentsStore.getAt(rowIndex);window.rowIndex=rowIndex;dearSwal({title:'Confirmation',text:'Are you sure you want to delete this file?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm&&rowIndex>=0){AttachmentsStore.removeAt(rowIndex);AttachmentsStore.save();} window.rowIndex=-1;});}}})],renderTo:'divAttachmentList',flex:1});var uploader=new Dropzone('#frmUpload',{paramName:'file',maxFilesize:16,uploadMultiple:false,parallelUploads:1,url:'/Opportunity/Upload',method:'post',dictDefaultMessage:'',previewTemplate:document.getElementById('preview-template').innerHTML,clickable:true,init:function init(){this.on('sending',function(){dearHelper.blockUI.show();});this.on('complete',function(data){if(data&&data.xhr&&data.xhr.status===200){Opportunity_Attachments_Load();this.removeFile(data);dearHelper.blockUI.hide();}});this.on('error',function(file,message){Dear_Notification_Error(message);this.removeFile(file);dearHelper.blockUI.hide();});}});} function Opportunity_Attachments_Load(){var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(!IsEmptyID(OpportunityID)){AttachmentsStore.removeAll();AttachmentsStore.commitChanges();AttachmentsStore.getProxy().extraParams={OpportunityID:OpportunityID};AttachmentsStore.load();}} function Opportunity_Attachments_Attach(){var value=fOpportunity_Index_UploadControl.getValue();if(value==null||value==''){Dear_Notification_Warning('Please select a document to attach.');}else{FileUploadInProgress=true;dearHelper.blockUI.show('Uploading the file...');document.getElementById('frmUpload').submit();}} function Opportunity_Attachments_ResetLayout(){GridOpportunity_Attachments.reconfigure(null,GridOpportunity_Attachments.initialConfig.columns);GridOpportunity_Attachments.getView().getHeaderCt().child('#colDeleteAttachments').setVisible(!IsReadOnly);};function Sale_Family_Show(source){window.FamilyDialogSource=source;if(typeof FamilyDialog=='undefined'){Sale_Family_Init();} cmbProductFamily.setValue(null);cmbFamilyOption1.setValue(null);cmbFamilyOption2.setValue(null);cmbFamilyOption3.setValue(null);dearHelper.control.setValue(txtProductFamilyQuantity,0);if(source==='Quote'){dearHelper.control.setValue(txtProductFamilyQuantity,getDefaultQuoteQuantity());} dearHelper.control.setValue(chkOnlyAvailable,false);Ext.get('lblFamilyOption1').setHTML('Option1');Ext.get('lblFamilyOption2').setHTML('Option2');Ext.get('lblFamilyOption3').setHTML('Option3');FamilyOptions1Store.removeAll();FamilyOptions2Store.removeAll();FamilyOptions3Store.removeAll();cmbProductFamily.setReadOnly(false);cmbFamilyOption1.setReadOnly(false);cmbFamilyOption2.setReadOnly(false);cmbFamilyOption3.setReadOnly(false);dearHelper.control.setReadOnly(chkOnlyAvailable,false);dearHelper.control.setReadOnly(txtProductFamilyQuantity,false);var Location=cmbLocation.getRawValue();if(Location==null){Location='';} if(Location==''){Ext.get('lblOnlyAvailable').setHTML('Sell only available variations');}else{var message=Ext.String.format('Sell only variations available at {0}',Location);Ext.get('lblOnlyAvailable').setHTML(message);} Sale_Family_OptionsSetVisible(false);FamilyDialog.modal('show');setTimeout(function(){cmbProductFamily.focus();},700);} function Sale_Family_OptionsSetVisible(visible){var divFamilyOptions=Ext.get('divFamilyOptions');if(visible){divFamilyOptions.removeCls('hiddenContent');}else{divFamilyOptions.addCls('hiddenContent');}} function Sale_Family_ProcessLoad(){var ProductFamilyQuantity=dearHelper.control.getValue(txtProductFamilyQuantity);var addedCount=0;var skippedCount=0;var TaxRule=cmbTax.getValue();var TaxPercent=Opportunity_Index_GetOpportunityProperty('TaxPercent');var modelArray=new Array();FamilyProductsStore.each(function(record){var isFound=false;var storeToSearch=null;var ProductID=record.get('ProductID');if(FamilyDialogSource=='Quote'){storeToSearch=vOpportunityLinesStore;}else{storeToSearch=vSaleOrderLinesStore;} var count=storeToSearch.getCount();for(var j=0;j0){if(FamilyDialogSource=='Quote'){Sale_Quote_UpdateLinesCompleteGrid();}else{Sale_Order_UpdateCompleteGrid();}} if(addedCount>0){if(FamilyDialogSource=='Quote'){vOpportunityLinesGrid.getView().focusRow(vOpportunityLinesStore.getCount()-1);}else{vSaleOrderLinesGrid.getView().focusRow(vSaleOrderLinesStore.getCount()-1);}} var message=null;if(addedCount==0&&skippedCount==0){message=Ext.String.format('{0}No{1} variations found in the family with specified search criteria.','','');}else if(addedCount>0){if(addedCount==1){message=Ext.String.format('{0}{1}{2} product was added.','',1,'');}else{message=Ext.String.format('{0}{1}{2} products were added.','',addedCount,'');}} if(message!=null){if(skippedCount>0){message+=' and ';}}else{message=Ext.String.format('{0}No{1} products were added and ','','');} if(skippedCount>0){if(skippedCount==1){message+=Ext.String.format('{0}{1}{2} product was already in the ','',1,'');}else{message+=Ext.String.format('{0}{1}{2} products were already in the ','',skippedCount,'');} message+=FamilyDialogSource;} if(addedCount==0&&skippedCount==0){Dear_Notification_Error(message);}else if(skippedCount>0){Dear_Notification_Warning(message);}else{Dear_Notification_SuccessInfo(message);} cmbProductFamily.setReadOnly(false);cmbFamilyOption1.setReadOnly(false);cmbFamilyOption2.setReadOnly(false);cmbFamilyOption3.setReadOnly(false);dearHelper.control.setReadOnly(chkOnlyAvailable,false);dearHelper.control.setReadOnly(txtProductFamilyQuantity,false);cmbProductFamily.focus();} function Sale_Family_Init(){window.cmbProductFamily=new Ext.ux.ComboBox({store:FamilyStore,queryMode:'remote',typeAhead:true,queryParam:'Name',minChars:0,width:267,triggerAction:'query',selectOnTab:true,displayField:'Name',valueField:'ID',selectOnFocus:true,forseSelection:true,enableKeyEvents:true,inputId:'cmbProductFamily',renderTo:'tdProductFamily',listConfig:{},listeners:{beforequery:function beforequery(queryEvent,eOpts){queryEvent.query=window.FamilyStoreQuery;},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.FamilyStoreQuery=Me.getRawValue();}},blur:function blur(Me){HideComboInputElement(Me,true);},select:function select(Me){cmbFamilyOption1.setValue(null);cmbFamilyOption2.setValue(null);cmbFamilyOption3.setValue(null);var FamilyID=cmbProductFamily.getValue();if(IsEmptyID(FamilyID)){FamilyOptions1Store.removeAll();FamilyOptions2Store.removeAll();FamilyOptions3Store.removeAll();Ext.get('lblFamilyOption1').setHTML('Option 1');Ext.get('lblFamilyOption2').setHTML('Option 2');Ext.get('lblFamilyOption3').setHTML('Option 3');Sale_Family_OptionsSetVisible(false);}else{var record=FamilyStore.getById(FamilyID);FamilyOptions1Store.removeAll();FamilyOptions2Store.removeAll();FamilyOptions3Store.removeAll();var name=record.get('Option1Name');if(name==null||name==''){name='Option 1';} Ext.get('lblFamilyOption1').setHTML(name);var name=record.get('Option2Name');if(name==null||name==''){name='Option 2';} Ext.get('lblFamilyOption2').setHTML(name);var name=record.get('Option3Name');if(name==null||name==''){name='Option 3';} Ext.get('lblFamilyOption3').setHTML(name);var options=record.get('Option1Values');if(options==null||options==''){options=new Array();}else{options=options.split('|');} for(var i=0;i0)){PriceTier=1;} if(Location==null){Location='';} var OnlyAvailable=dearHelper.control.getValue(chkOnlyAvailable);var ProductFamilyQuantity=dearHelper.control.getValue(txtProductFamilyQuantity);if(IsEmptyID(FamilyID)){Dear_Notification_Error('Please choose a product family.');}else if((Option1==null||Option1=='')&&(Option2==null||Option2=='')&&(Option3==null||Option3=='')){Dear_Notification_Error('Please choose the family options.');}else{Dear_Notification_Info('Adding products to your sale task');cmbProductFamily.setReadOnly(true);cmbFamilyOption1.setReadOnly(true);cmbFamilyOption2.setReadOnly(true);cmbFamilyOption3.setReadOnly(true);dearHelper.control.setReadOnly(chkOnlyAvailable,true);dearHelper.control.setReadOnly(txtProductFamilyQuantity,true);FamilyProductsStore.removeAll();FamilyProductsStore.getProxy().extraParams={FamilyID:FamilyID,PriceTier:PriceTier,Options1:Option1,Options2:Option2,Options3:Option3,OnlyAvailable:OnlyAvailable,Location:Location,Quantity:ProductFamilyQuantity,lang:currentUILang,currencyRate:txtSale_Index_CurrencyConversionRate.getValue(),customerID:Opportunity_Index_GetOpportunityProperty('CustomerID')};FamilyProductsStore.load();}} function Sale_Family_Cancel(){FamilyDialog.modal('hide');};(()=>{"use strict";;function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function");};function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);};function toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.");} return("string"===r?String:Number)(t);};function toPropertyKey(t){var i=toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+"";};function _defineProperties(e,r){for(var t=0;t');} return val;}}],renderTo:'divWorkflowHistoryLines',flex:1});return this.grid;}}]);}();window.WorkflowHistoryLog_Init=function(store,stateID){return new WorkflowHistoryLog(store,stateID);};})();function Sale_Index_LoginSuccessCallback(operation){if(operation==null){CheckAccess('Opportunity','Index',Sale_Index_AccessCallback,Sale_Index_LoginSuccessCallback);}else if(operation.action!='read'){Opportunity_Index_Submit();}} function Opportunity_Index_Print(ID){window.ClickedTemplateID=ID.replace('Print','');window.PlannedOperation='Print';Opportunity_Index_Submit();} function Opportunity_Index_Email(ID){window.ClickedTemplateID=ID.replace('Email','');window.PlannedOperation='Email';Opportunity_Index_Submit();} function Sale_Index_UpdateControlSizes(){switch(Sale_GetActiveTab()){case'tabOpportunity':vOpportunityLinesGrid.getView().refresh();vOpportunityAdditionalChargesGrid.getView().refresh();break;case'tabAttachments':GridOpportunity_Attachments.getView().refresh();break;case'tabHistory':GridSale_History.getView().refresh();GridSale_WorkflowHistory.getView().refresh();break;} setTimeout(function(){if(window.mainTabSlider){window.mainTabSlider.refresh();}},1000);} function Sale_Index_ApplyDiscountedPrices(storeToWork,data){var hasChanges=false;var remains={};var count=storeToWork.getCount();var modelName='vOpportunityLines';var idPropertyName='OpportunityLineID';for(var i=0;i=0;i--){var rec=totalStore.getAt(i);if(rec.get('Description')==orderTotalDiscount){totalStore.removeAt(i);}} count=storeToWork.getCount();var $discountDescription=$("#".concat(modelName,"DiscountDescription"));$discountDescription.hide();var descriptionArray={};for(var j=0;j100){discount=100;} var quantity=el.Quantity;if(DEARRound((price-price/100.0*DEARRound(discount,2))*quantity,2)===DEARRound((price-price/100.0*discount)*quantity,2)){discount=DEARRound(discount,2);} if(productID===emptyGuid&&quantity===1){if(Quickbooks){Ext.Ajax.request({url:'/api/SaleService_Index_GetOrderTotalDiscountProduct',method:'POST',jsonData:null});} var descriptionKey="".concat(el.DealID,"|").concat(el.DiscountID,"|").concat(el.DealName,"|").concat(el.DiscountName);var descriptionEl=descriptionArray[descriptionKey];if(!descriptionEl){descriptionArray[descriptionKey]={dealName:el.DealName,discountName:el.DiscountName,dealID:el.DealID,discountID:el.DiscountID,products:false};} var r=Ext.create(totalModel,{Description:orderTotalDiscount,Quantity:1,Amount:discountedPrice,Discount:0,Total:discountedPrice,TaxRule:cmbTax.getValue(),LineOrder:storeToWork.getCount()+1,RevenueAccount:storeRec.get('RevenueAccount'),Comment:storeRec.get('Comment'),OpportunityID:storeRec.get('OpportunityID'),ValidationText:'',ValidationState:'Good'});var tax=vTenantTaxationRuleStore.getById(cmbTax.getValue());if(tax!=null){if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){r.set('TaxPercent',tax.get('EffectivePercentInclusive'));}else{r.set('TaxPercent',tax.get('EffectivePercentExclusive'));} UpdateAdditionalTaxAndTotal(r);} r.set(totalIdPropertyName,guid());r.setDirty();totalStore.add(r);continue;} var searchStep=0;for(var i=0;i0&&searchStep<2;i++){var storeRec=storeToWork.getAt(i);var id=storeRec.get(idPropertyName);if(remains[id]&&remains[id].ProductID==productID&&remains[id].Quantity>0&&(searchStep===1||storeRec.get('Price')===discountedPrice)){if(discountedPrice!=price&&(el.DiscountID!=null||el.DiscountName!=null)){var descriptionKey="".concat(el.DealID,"|").concat(el.DiscountID,"|").concat(el.DealName,"|").concat(el.DiscountName);var descriptionEl=descriptionArray[descriptionKey];if(!descriptionEl){descriptionArray[descriptionKey]={dealName:el.DealName,discountName:el.DiscountName,dealID:el.DealID,discountID:el.DiscountID,products:{}};} descriptionArray[descriptionKey].products[productID]=storeRec.get('Name');} if(remains[id].Quantity>quantity){var r=Ext.create(modelName,{Quantity:quantity,Price:DiscountCalculationMethod=='Price'?discountedPrice:price,LineOrder:storeToWork.getCount()+1,Discount:DiscountCalculationMethod=='Price'?0:discount,Total:0,CostingMethod:storeRec.get('CostingMethod'),Tax:storeRec.get('Tax'),DropShipMode:storeRec.get('DropShipMode'),TaxRule:storeRec.get('TaxRule'),TaxPercent:storeRec.get('TaxPercent'),UnitOfMeasure:storeRec.get('UnitOfMeasure'),AverageCost:storeRec.get('AverageCost'),ProductCode:storeRec.get('ProductCode'),ProductID:storeRec.get('ProductID'),Name:storeRec.get('Name'),RevenueAccount:storeRec.get('RevenueAccount'),Comment:storeRec.get('Comment'),OpportunityID:storeRec.get('OpportunityID'),ValidationText:'',ValidationState:'Good'});if(modelName=='vSaleOrderLines'){r.set('Backordered',storeRec.get('Backordered'));r.set('DropShip',storeRec.get('DropShip'));} r.set(idPropertyName,guid());r.setDirty();storeToWork.add(r);count=storeToWork.getCount();remains[id].Quantity-=quantity;quantity=0;storeRec.set('Quantity',remains[id].Quantity);}else{if(DiscountCalculationMethod=='Price'){storeRec.set('Price',discountedPrice);storeRec.set('Discount',0);}else{storeRec.set('Price',price);storeRec.set('Discount',discount);} hasChanges=true;quantity=DEARRound(quantity-remains[id].Quantity,8);remains[id].Quantity=0;} hasChanges=true;} if(i+1===count){i=-1;searchStep++;}}} var description='';var uniqMessage={};for(var el in descriptionArray){var info=descriptionArray[el];var products='';if(info.products){for(var i in info.products){products+="".concat(products?', ':'',"").concat(info.products[i],"");}}else if(info.products===false){products='Whole order';} if(uniqMessage[info.dealID?info.dealID:info.discountID]){continue;} uniqMessage[info.dealID?info.dealID:info.discountID]=true;var href=info.dealID?"/Deal#".concat(info.dealID):info.discountID?"DiscountNew#".concat(info.discountID):"/Customer#".concat(Opportunity_Index_GetOpportunityProperty('CustomerID'));var name=info.dealID?info.dealName:info.discountName;description+="Discount ").concat(name," applied to ").concat(products,"
");} if(data.customerPercentOverDiscounts){var customerDiscountName=Ext.String.format('Customer discount - {0}%',data.customerPercentOverDiscounts);description+="").concat(customerDiscountName,"
");} if(description){setTimeout(function(){$discountDescription.html("\n
\n \n
".concat(description,"
\n
\n "));$discountDescription.removeClass('hiddenContent');$discountDescription.show();window.DiscountsDescription=description;},500);} return hasChanges;} function Sale_Index_Get_DiscountType(discountType){console.log("Sale_Index_Get_DiscountType discountType: ".concat(discountType));var discountCount=vDiscountStore.getCount();console.log("vDiscountStore Count: ".concat(discountCount));if(!discountCount){return null;} for(var i=0;i0){var wrapper=new Object();wrapper.Tier=CurrentTier;wrapper.CustomerID=Opportunity_Index_GetOpportunityProperty('CustomerID');wrapper.Products=requestArray;wrapper.OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');wrapper.OnlyDiscountedProducts=OnlyDiscountedProducts;wrapper.CurrencyRate=txtSale_Index_CurrencyConversionRate.getValue();dearHelper.blockUI.show('Applying discounts...');Ext.Ajax.request({url:'/api/Sale_Index_PriceRequest',method:'POST',jsonData:Ext.encode(wrapper),success:function success(response){var data=Ext.decode(response.responseText);var storeToWork=vOpportunityLinesStore;var HasChanges=false;if(storeToWork!=null){HasChanges=Sale_Index_ApplyDiscountedPrices(storeToWork,data);} if(HasChanges){if(storeToWork==vOpportunityLinesStore){Sale_Quote_UpdateLinesCompleteGrid();}else{Sale_Order_UpdateCompleteGrid();}} dearHelper.blockUI.hide();if(submitAfterAction===true){Opportunity_Index_Submit();} if(callback&&typeof callback==='function'){callback();}},failure:function failure(response){dearHelper.blockUI.hide();}});}}}}} function Opportunity_Index_New(){var newSaleTask=Ext.create('Opportunity',{OpportunityNumber:'Not assigned',Currency:TenantCurrency,PriceTier:1,CurrencyConversionRate:1,CreditNoteConversionRate:1,TaxPercent:0,OpportunityDate:new Date(),OpportunityStatus:StatusTracker.statuses.draft,ValidationText:'',ValidationState:'Good'});if(vTenantContactsStore.getCount()>0){newSaleTask.set('SalesRepresentative',vTenantContactsStore.getAt(0).get('Name'));} OpportunityUpdated.add(newSaleTask);Opportunity_Index_ProcessLoad();Sale_Index_CommitAllChanges();} window.inSaleProcess=false;function Opportunity_Index_Submit(){if(window.SavingProcessing==true){return;} window.SavingProcessing=true;var _isSend=false;if(typeof OpportunityUpdated!=='undefined'&&OpportunityUpdated!=null&&OpportunityUpdated.getCount()==1){StatusTracker.updateStatuses();if(ArePendingChanges()){dearHelper.blockUI.show();var dataToSave=new Object();dataToSave.ID=OpportunityWrapperStore.getAt(0).getId();dataToSave.HasErrors=false;dataToSave.DiscountsDescription=window.DiscountsDescription;dataToSave.ConvertedSaleTaskID=window.ConvertedSaleTaskID;var tempArray=new Array();var range=OpportunityOriginal.getRange();if(range.length>0){tempArray.push(OpportunityOriginal.getRange()[0].getData(true));} dataToSave.Original=tempArray;tempArray=new Array();range=OpportunityUpdated.getRange();if(range.length>0){tempArray.push(OpportunityUpdated.getRange()[0].getData(true));} dataToSave.Updated=tempArray;var isNewTask=IsEmptyID(dataToSave.ID);_isSend=true;Ext.Ajax.request({url:isNewTask?'/api/Opportunity_Index_vOpportunity':"/api/Opportunity_Index_vOpportunity/".concat(dataToSave.ID),method:isNewTask?'POST':'PUT',jsonData:Ext.encode(dataToSave),timeout:2000000,success:function success(response){window.SavingProcessing=false;OpportunityWrapperStore.loadRawData(Ext.decode(response.responseText));if(isNewTask){var savedTask=OpportunityUpdated.getAt(0);if(!IsEmptyID(savedTask.get('OpportunityID'))){window.location.hash=savedTask.get('OpportunityID');window.Tasks_taskListDropDown.updateEntityData({entityID:savedTask.get('OpportunityID')});}} window.DiscountsDescription='';var record=OpportunityWrapperStore.getAt(0);if(record&&record.get('HasErrors')===false){CommonSale_CheckVisibleTaxExemptionCode();} QuickLinks.Tooltips.clearCache();if(window.PlannedOperation.length==0){dearHelper.blockUI.hide();}},failure:function failure(response){window.SavingProcessing=false;dearHelper.blockUI.hide();Dear_Notification_Error(GetErrorMessage(response));OpportunityWrapperStore.load();}});}else{Opportunity_Index_ProcessPlannedOperation();}} window.SavingProcessing=_isSend;} function Sale_SetActiveTab(tabId){var divOpportunity=$('#divQuote');var divHistory=$('#divHistory');var divAttachments=$('#divAttachments');var tabOpportunity=$('#tabOpportunity');var tabHistory=$('#tabHistory');var tabAttachments=$('#tabAttachments');if(!divOpportunity.hasClass('hiddenContent')&&tabId!='tabOpportunity'){divOpportunity.addClass('hiddenContent');} if(!divHistory.hasClass('hiddenContent')&&tabId!='tabHistory'){divHistory.addClass('hiddenContent');} if(!divAttachments.hasClass('hiddenContent')&&tabId!='tabAttachments'){divAttachments.addClass('hiddenContent');} if(tabOpportunity.hasClass('active')&&tabId!='tabOpportunity'){tabOpportunity.removeClass('active');} if(tabHistory.hasClass('active')&&tabId!='tabHistory'){tabHistory.removeClass('active');} if(tabAttachments.hasClass('active')&&tabId!='tabAttachments'){tabAttachments.removeClass('active');} var record=OpportunityUpdated.getAt(0);var IsCancelled=StatusTracker.isCancelled;var IsSaved=!IsEmptyID(Opportunity_Index_GetOpportunityProperty('OpportunityID'));var allowVisible=!IsReadOnly&&!IsCancelled&&IsSaved;switch(tabId){case'tabHistory':if(divHistory.hasClass('hiddenContent')){divHistory.removeClass('hiddenContent');} if(!tabHistory.hasClass('active')){tabHistory.addClass('active');} var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');window.HistoryLog.load(OpportunityID);if(WorkflowHistoryStore.getCount()==0&&!IsEmptyID(OpportunityID)){WorkflowHistoryStore.getProxy().extraParams={entityID:OpportunityID};WorkflowHistoryStore.load();} GridSale_WorkflowHistory.getView().refresh();break;case'tabAttachments':if(divAttachments.hasClass('hiddenContent')){divAttachments.removeClass('hiddenContent');} if(!tabAttachments.hasClass('active')){tabAttachments.addClass('active');} if(AttachmentsStore.getCount()==0){Opportunity_Attachments_Load();} GridOpportunity_Attachments.getView().refresh();break;default:if(divOpportunity.hasClass('hiddenContent')){divOpportunity.removeClass('hiddenContent');} if(!tabOpportunity.hasClass('active')){tabOpportunity.addClass('active');} if(allowVisible){$('#tabQuotePrintAction').removeClass('hiddenContent');$('#tabQuoteEmailAction').removeClass('hiddenContent');} vOpportunityLinesGrid.getView().refresh();vOpportunityAdditionalChargesGrid.getView().refresh();break;} window.location.hash=Opportunity_Index_GetHashFromTask(record,tabId);StatusTracker.activeTab=tabId;$(document).trigger('resize');setTimeout(function(){dearHelper.control.updateAutosize();},200);} function Sale_GetActiveTab(){return StatusTracker.activeTab;} function Sale_SetFirstAvailableTab(){Sale_SetActiveTab('tabOpportunity');} function Opportunity_Index_ProcessPlannedOperation(){switch(PlannedOperation){case'':window.PlannedOperation='';break;case'convertStart':window.PlannedOperation='';Opportunity_Index_LeadConvert();break;case'convertLead':window.PlannedOperation='';Opportunity_Index_Convert();break;case'convertFinish':window.PlannedOperation='';Opportunity_Index_ConvertFinish();break;case'Undo':dearHelper.blockUI.hide();window.PlannedOperation='';break;case'Cancel':window.PlannedOperation='';dearHelper.blockUI.hide();Dear_Notification_Success('Void operation completed successfully.');break;case'Invoice:Authorise':window.PlannedOperation='';Sale_Invoice_CheckForDeposits();break;case'Print':window.PlannedOperation='';var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(!IsEmptyID(OpportunityID)){dearHelper.blockUI.show('Printing...');Ext.Ajax.request({url:'/Opportunity/Print',method:'GET',timeout:180000,params:{PrintEntityID:OpportunityID,PrintTemplateID:ClickedTemplateID},callback:function callback(options,success,response){dearHelper.blockUI.hide();if(success){Opportunity_Attachments_Load();var id=response.responseText;Ext.get('divPrint').setHTML("").concat(id,""));window.PrintInProgress=true;AttachmentsStore.removeAll();AttachmentsStore.commitChanges();AttachmentsStore.getProxy().extraParams={OpportunityID:Opportunity_Index_GetOpportunityProperty('OpportunityID')};AttachmentsStore.load();}else{Dear_Notification_Error(getClearText(response.responseText));}}});} break;case'clone':window.PlannedOperation='';var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(!IsEmptyID(OpportunityID)){$.post('/Opportunity/Clone',{sourceID:OpportunityID},function(res){if(res.Status!=='ok'){Dear_Notification_Error(res.Message);}else{window.open("/Opportunity#".concat(res.Data),'_self');setTimeout(function(){window.location.reload();},100);}}).fail(function(){Dear_Notification_Error('Server request error');});} break;case'Email':window.PlannedOperation='';var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');Dear_Notification_Info('Generating a report, please wait...');if(!IsEmptyID(OpportunityID)){dearHelper.blockUI.show();Ext.Ajax.request({url:'/Opportunity/Print',timeout:180000,method:'GET',params:{PrintEntityID:OpportunityID,PrintTemplateID:ClickedTemplateID},callback:function callback(options,success,response){dearHelper.blockUI.hide();if(success){var id=response.responseText;Email_Show('Opportunity',Opportunity_Index_GetOpportunityProperty('OpportunityID'),null,id,ClickedTemplateID);}else{Dear_Notification_Error(getClearText(response.responseText));}}});} break;} window.PlannedOperation='';} function Opportunity_Index_AdjustMainToolbarActions(){var IsCancelled=StatusTracker.isCancelled;var IsSaved=!IsEmptyID(Opportunity_Index_GetOpportunityProperty('OpportunityID'));var isDisabled=window.AddEditPermission!=='Full';$('#saveAction').removeClass('hiddenContent');if(IsCancelled||isDisabled){$('#saveAction').addClass('hiddenContent');} $('#saveAction2').removeClass('hiddenContent');if(IsCancelled||isDisabled){$('#saveAction2').addClass('hiddenContent');} $('#convert2SaleAction').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved||StatusTracker.OpportunityStatus!==StatusTracker.statuses.won){$('#convert2SaleAction').addClass('hiddenContent');} $('#voidAction').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved||VoidPermission!=='Full'){$('#voidAction').addClass('hiddenContent');} $('#cloneAction').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved){$('#cloneAction').addClass('hiddenContent');} $('#divAuthorise_Quote').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved||StatusTracker.OpportunityStatus!==StatusTracker.statuses.inProgress){$('#divAuthorise_Quote').addClass('hiddenContent');} $('#divSetInProgress').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved||StatusTracker.OpportunityStatus!==StatusTracker.statuses.draft){$('#divSetInProgress').addClass('hiddenContent');} $('#btMarkAsLost').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved){$('#btMarkAsLost').addClass('hiddenContent');} $('#undoAction').removeClass('hiddenContent');if(IsCancelled||isDisabled||!IsSaved||UndoPermission!=='Full'){$('#undoAction').addClass('hiddenContent');} var printActionVisible=!IsCancelled&&IsSaved&&!isDisabled;if(printActionVisible===true){$("[id*='PrintAction'], [id*='EmailAction']").showContent();}else{$("[id*='PrintAction'], [id*='EmailAction']").hideContent();} $('#btApprove').removeClass('hiddenContent').addClass('hiddenContent');$('#btReject').removeClass('hiddenContent').addClass('hiddenContent');$('#btReview').removeClass('hiddenContent').addClass('hiddenContent');$('#addBtn_Sale_Index_Customer').removeClass('hiddenContent');switch(StatusTracker.OpportunityStatus){case StatusTracker.statuses.waitingForApproval:if(window.ApprovePermission==='Full'&&!isDisabled){$('#btApprove').removeClass('hiddenContent');$('#btReject').removeClass('hiddenContent');} break;case StatusTracker.statuses.inReview:if(window.ApprovePermission==='Full'&&!isDisabled){$('#btReview').removeClass('hiddenContent');} break;case StatusTracker.statuses.lost:$('#btMarkAsLost').removeClass('hiddenContent').addClass('hiddenContent');break;}} function Sale_Index_GetPrice(Product){var currentPriceTier=cmbPriceTier.getValue();switch(currentPriceTier){case 1:return Product.get('PriceTear1');case 2:return Product.get('PriceTear2');case 3:return Product.get('PriceTear3');case 4:return Product.get('PriceTear4');case 5:return Product.get('PriceTear5');case 6:return Product.get('PriceTear6');case 7:return Product.get('PriceTear7');case 8:return Product.get('PriceTear8');case 9:return Product.get('PriceTear9');case 10:return Product.get('PriceTear10');default:return 0;}} function Sale_Index_ApplyReadOnlyState(){cmbCustomer.setDisabled(true);cmbContact.setDisabled(true);txtPhone.setDisabled(true);txtEmail.setDisabled(true);cmbBillingAddressLine1.setDisabled(true);txtBillingAddressLine2.setDisabled(true);txtSale_Index_CurrencyConversionRate.setDisabled(true);cmbTax.setDisabled(true);cmbPriceTier.setDisabled(true);cmbTerms.setDisabled(true);txtCustomerReference.setDisabled(true);txtShipToCompany.setDisabled(true);txtShipToContact.setDisabled(true);cmbSalesRepresentative.setDisabled(true);cmbLocation.setDisabled(true);dtDate.setDisabled(true);chkHeaderShipToOther.setDisabled(true);cmbShippingAddressLine1.setDisabled(true);txtShippingAddressLine2.setDisabled(true);dearHelper.control.setDisabled(txtOpportunityComment,true);dearHelper.control.setDisabled(txtOpportunity_Memo,true);} function Opportunity_Index_SetReadonly_Attribute(){var isReadOnly=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;Opportunity_Index_SetReadonlyForAttribute(customField1,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField2,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField3,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField4,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField5,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField6,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField7,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField8,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField9,isReadOnly);Opportunity_Index_SetReadonlyForAttribute(customField10,isReadOnly);} function Sale_Index_AccessCallback(accessLevel){window.JobID=null;Sale_Index_CreateControls();QuickLinks.Tooltips.init(QuickLinks.Pages.Sale);} function Sale_Index_LoadJob(){JobCostingStore.getProxy().extraParams={id:JobID};JobCostingStore.load();} function Sale_Index_CommitAllChanges(){OpportunityUpdated.commitChanges();if(typeof vOpportunityLinesStore!=='undefined'&&vOpportunityLinesStore!==null){vOpportunityLinesStore.commitChanges();} if(typeof vOpportunityAdditionalChargesStore!=='undefined'&&vOpportunityAdditionalChargesStore!==null){vOpportunityAdditionalChargesStore.commitChanges();}} $(document).ready(function(){window.mainTabSlider=$('.navigation-icons').lightSlider({autoWidth:true,loop:false,pager:false,slideMargin:10,onSliderLoad:function onSliderLoad(){$(window).trigger('resize');}});});function Sale_Index_CreateControls(){Grid_InitMeasure();window.Tasks_taskListDropDown=taskHelper.taskListDropDown('#divCustomerTask',{entityType:window.TaskConstant.EntityType.OpportunityTask,isChild:false});$('#secEmail').slideUp();window.PlannedOperation='';window.PrintInProgress=false;window.TemplatesLoaded=false;initStatePersistance();window.NewEntityType='';var map=new Ext.util.KeyMap(document,{key:Ext.EventObject.S,ctrl:true,fn:function fn(key,e){e.stopEvent();window.PlannedOperation='';Opportunity_Index_Submit();}});Ext.Ajax.on('beforerequest',function(conn,options,eOpts){if(options.action=='create'){switch(NewEntityType){case'Address':if(typeof options.jsonData.AddressID!=='undefined'){delete options.jsonData.AddressID;} break;case'Carrier':if(typeof options.jsonData.CarrierID!=='undefined'){delete options.jsonData.CarrierID;} break;case'Contact':if(typeof options.jsonData.ContactID!=='undefined'){delete options.jsonData.ContactID;} break;case'Lead':if(typeof options.jsonData.LeadID!=='undefined'){delete options.jsonData.LeadID;} break;case'Term':if(typeof options.jsonData.TermID!=='undefined'){delete options.jsonData.TermID;} break;case'Product':if(typeof options.jsonData.ProductID!=='undefined'){delete options.jsonData.ProductID;} break;}}});window.ArePendingChanges=function(){if(StatusTracker.isCancelled){return false;} Opportunity_Index_ApplyChangesToOpportunity();Sale_Quote_PrepareForSave();var HasErrors=OpportunityWrapperStore.getAt(0).get('HasErrors');if(HasErrors){return true;} return IsStoreDirty(OpportunityUpdated)||IsStoreDirty(vOpportunityLinesStore)||IsStoreDirty(vOpportunityAdditionalChargesStore)||IsStoreDirty(OpportunityWrapperStore);};BindPageLeave();window.HistoryLog=window.HistoryLog_Init('/api/Opportunity_Index_History');Opportunity_Index_InitModels();Opportunity_Index_CreateStores();Opportunity_Index_CreateSaleTaskControls();window.touchEventElement=null;$('#tabOpportunity, #tabAttachments, #tabHistory').registerTouchClickEvent();$('#tabOpportunity').on('touchClick',function(){Sale_SetActiveTab('tabOpportunity');});$('#tabAttachments').on('touchClick',function(){Sale_SetActiveTab('tabAttachments');});$('#tabHistory').on('touchClick',function(){Sale_SetActiveTab('tabHistory');});$('#saveAction, #saveAction2').on('click',function(){var requiredFieldsIds=['Sale_Index_BillingAddressLine1','Sale_Index_PriceTier','Sale_Index_SalesRepresentative','tdSale_Index_DefaultAccount','Sale_Index_Tax','Sale_Index_Location','Sale_Index_Date'];if(!window.__HighlightInvalidFields.validation(requiredFieldsIds)){return false;} window.PlannedOperation='';Opportunity_Index_Submit();});$('#cloneAction').click(Opportunity_Index_Clone);$('#undoAction').click(Opportunity_Index_Undo);$('#voidAction').click(Opportunity_Index_Cancel);$('#convert2SaleAction').click(Opportunity_Index_StartConvert);Sale_Quote_CreateControls();Opportunity_Attachments_CreateControls();window.GridSale_History=window.HistoryLog.getGrid();window.GridSale_WorkflowHistory=window.WorkflowHistoryLog_Init(WorkflowHistoryStore,'OpportunityWorkflowHistory090323').grid;Opportunity_Index_InitializeStatusTracker();window.onresize=Sale_Index_UpdateControlSizes;if(IsReadOnly){Sale_Index_ApplyReadOnlyState();} var isEmptyTask=true;if(window.location.hash){var hash=window.location.hash.substring(1);if(hash.indexOf('job')==0){JobID=hash.substring(3);}else{var params=Opportunity_Index_ParseParameterFromHash(hash);if(!IsEmptyID(params.masterID)){OpportunityWrapperStore.getProxy().extraParams={id:params.masterID,lang:currentUILang};window.Tasks_taskListDropDown.updateEntityData({entityID:params.masterID});window.tabname=params.tabName;isEmptyTask=false;}}} if(isEmptyTask){OpportunityWrapperStore.getProxy().extraParams={};} $("[id*='PrintAction'], [id*='EmailAction']").parent().on('shown.bs.dropdown',function(){Opportunity_Index_RefreshPrintEmailTemplatesMenu();});OpportunityWrapperStore.load({callback:function callback(){if(IsEmptyID(OpportunityWrapperStore.getProxy().extraParams.id)){var savedCustomer=CommonSale_GetCustomerForNewSale();if(savedCustomer){vOpportunity_CustomerStore.getProxy().extraParams={lang:currentUILang,CountrySpecificKey:'',Name:savedCustomer.Name};vOpportunity_CustomerStore.load({callback:function callback(){var rec=vOpportunity_CustomerStore.findRecord('CustomerID',savedCustomer.CustomerID);if(rec){cmbCustomer.setValue(rec.get('Name'));}else{cmbCustomer.setValue(savedCustomer.Name);} cmbCustomer.fireEvent('select',cmbCustomer);cmbDefaultAccount.setValue(window.DefaultAccountCode);}});}}else{Sale_SetActiveTab(window.tabname);Common_LightSlider_ShowActiveTab();}}});SkuAutogenerationFlag.load();} function Opportunity_Index_ParseParameterFromHash(hash){var result=hash.split('~');var masterID=result[0];var tabName=result[1]||'';return{masterID:masterID,tabName:tabName};} function Opportunity_Index_GetHashFromTask(record,tabName){var OpportunityID=record.get('OpportunityID');var hashString=OpportunityID;if(tabName){hashString+="~".concat(tabName);} return hashString;} function Sale_History_ResetLayout(){GridSale_History.reconfigure(null,GridSale_History.initialConfig.columns);TransactionsGrid.reconfigure(null,TransactionsGrid.initialConfig.columns);} function Sale_Index_Ready(){CheckAccess('Opportunity','Index',Sale_Index_AccessCallback,Sale_Index_LoginSuccessCallback);$('.expandPanel').click(Sale_Index_CollapseToggle);} function Opportunity_Index_Clone(){var sourceID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(IsEmptyID(sourceID)){Dear_Notification_Warning('You cannot clone an unsaved opportunity. Save it first.');}else{dearSwal({title:'Confirmation',text:'Are you sure you want to create a copy of this opportunity?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){PlannedOperation='clone';Opportunity_Index_Submit();}});}} function Opportunity_Index_Undo(){var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(IsEmptyID(OpportunityID)){Dear_Notification_Warning('You cannot undo an unsaved opportunity.');}else{dearSwal({title:'Confirmation',text:'This will change the opportunity status back to draft. Would you like to proceed anyway?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){StatusTracker.setOpportunityStatus(StatusTracker.statuses.draft);Opportunity_Index_Submit();}});}} function Opportunity_Index_Cancel(){var OpportunityID=Opportunity_Index_GetOpportunityProperty('OpportunityID');if(IsEmptyID(OpportunityID)){Dear_Notification_Warning("You cannot void an unsaved opportunity. Just close this page if you don't want to save it.");}else{dearSwal({title:'Confirmation',text:'This will drop your current changes and delete the opportunity! Would you like to proceed anyway?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){dearHelper.blockUI.show();Ext.Ajax.request({url:'/Opportunity/Void',method:'POST',params:{OpportunityID:Opportunity_Index_GetOpportunityProperty('OpportunityID')},success:function success(response){showResponseNotification(response);OpportunityWrapperStore.getProxy().extraParams={id:Opportunity_Index_GetOpportunityProperty('OpportunityID'),lang:currentUILang};OpportunityWrapperStore.load();},failure:function failure(response){dearHelper.blockUI.hide();Dear_Notification_Error(GetErrorMessage(response));showResponseNotification(response);}});}});}} function Sale_Index_Convert(){var IsSaved=!IsEmptyID(Opportunity_Index_GetOpportunityProperty('OpportunityID'));if(IsSaved&&!IsReadOnly&&UndoPermission==='Full'&&VoidPermission==='Full'){dearSwal({title:'Confirmation',text:'This sale will be converted to a sale with advanced features. Please note that the conversion is irreversible. Would you like to proceed?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){dearHelper.blockUI.show();window.PlannedOperation='Multiple';if(StatusTracker.order.status==StatusTracker.statuses.fulfilled||StatusTracker.order.status==StatusTracker.statuses.closed){StatusTracker.order.setStatus(StatusTracker.statuses.authorized);}else if(StatusTracker.order.status==StatusTracker.statuses.authorized||StatusTracker.order.status==StatusTracker.statuses.authNoAllocation||StatusTracker.order.status==StatusTracker.statuses.notAvailable||StatusTracker.order.status==StatusTracker.statuses.draft){}else{StatusTracker.order.setStatus(StatusTracker.statuses.draft);} Opportunity_Index_Submit();}});}} function Sale_Index_GetProductImageTemplate(classes){return"
");} function Sale_Index_GetPriceTier(values){return DEARPriceFormat(values["PriceTear".concat(cmbPriceTier.getValue())]);} function Sale_Index_GetShippingRate(mode,ShippingServiceID){window.GetShippingRateOperationMode=mode;window.GetShippingRateOperationServiceID=ShippingServiceID;window.PlannedOperation='GetShippingRate';Opportunity_Index_Submit();} function Sale_Index_DonwloadFile(id){document.getElementById('donwloadFileId').value=id;document.getElementById('frmDownloadFile').submit();} function Sale_Index_ApplySaleTaxManagementService(){cmbTax.setValue(window.SaleTaxManagementRuleID);Opportunity_Index_SetOpportunityProperty('TaxSchema',window.SaleTaxManagementRuleID);cmbTax.setDisabled(true);StatusTracker.quote.readOnlyTaxAccounts=true;} function Sale_Index_RefreshSaleTask(){OpportunityWrapperStore.getProxy().extraParams={id:Opportunity_Index_GetOpportunityProperty('OpportunityID'),lang:currentUILang};OpportunityWrapperStore.load();QuickLinks.Tooltips.clearCache();} function Sale_Index_OpenTutorial(){window.open('https://youtu.be/HbfkprmASAs');} function Opportunity_Index_RefreshPrintEmailTemplatesMenu(forceRefresh){this.reportTemplatesStore=Ext.create('Ext.data.JsonStore',{model:'ReportTemplate',proxy:{type:'rest',url:'/OpportunityList/GetTemplates',reader:{type:'json'}},autoLoad:true,listeners:{load:function load(res){var divPrint=$('#tabQuotePrintAction').closest('.form-control').find('.dropdown-menu');var divEmail=$('#tabQuoteEmailAction').closest('.form-control').find('.dropdown-menu');divPrint.html('');divEmail.html('');for(var _i2=0,_res$data$items2=res.data.items;_i2<_res$data$items2.length;_i2++){var i=_res$data$items2[_i2];$(divPrint).append("").concat(i['data']['Name'],""));$(divEmail).append("").concat(i['data']['Name'],""));}}}});} function getDefaultQuoteQuantity(){return!window.DefaultQuantity?0:window.DefaultQuantity;} function showMessage(message,type){switch(type){case'success':Dear_Notification_Success(message,null,3000);break;case'error':Dear_Notification_Error(message);break;case'info':Dear_Notification_Info(message);break;default:Dear_Notification_Warning(message);break;}};function Opportunity_Index_InitModels(){Ext.define('Family',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'Name',type:'string'},{name:'Option1Name',type:'string'},{name:'Option1Values',type:'string'},{name:'Option2Name',type:'string'},{name:'Option2Values',type:'string'},{name:'Option3Name',type:'string'},{name:'Option3Values',type:'string'}]});Ext.define('AccountCurrency',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'Currency',type:'string'}]});Ext.define('vTransaction',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'Debit',type:'string'},{name:'Credit',type:'string'},{name:'Amount',type:'float'},{name:'EffectiveDate',type:'date',dateFormat:'c'}]});Ext.define('vTenantInventoryCategory',{idProperty:'CategoryID',extend:'Ext.data.Model',fields:[{name:'CategoryID',type:'string'},{name:'Category',type:'string'}]});Ext.define('XeroLink',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'Type',type:'string'}]});Ext.define('RecurringFrequency',{idProperty:'Value',extend:'Ext.data.Model',fields:[{name:'Value',type:'string'},{name:'Name',type:'string'}]});Ext.define('JobCosting',{idProperty:'CustomerID',extend:'Ext.data.Model',fields:[{name:'CustomerID',type:'string'},{name:'CustomerName',type:'string'},{name:'Comments',type:'string'},{name:'Contact',type:'string'},{name:'AddressLine1',type:'string'},{name:'AddressLine2',type:'string'},{name:'CustomerCurrency',type:'string'},{name:'Phone',type:'string'},{name:'PaymentTerm',type:'string'},{name:'TaxRuleID',type:'string'},{name:'DefaultSalesRepresentative',type:'string'},{name:'Discount',type:'float'},{name:'SalePriceTier',type:'int'},{name:'CreditLimit',type:'float'},{name:'SaleAccount',type:'string'},{name:'DefaultLocation',type:'string'}]});Ext.define('vSupplier',{idProperty:'SupplierID',extend:'Ext.data.Model',fields:[{name:'SupplierID',type:'string'},{name:'Name',type:'string'}]});Ext.define('FamilyProduct',{idProperty:'ProductID',extend:'Ext.data.Model',fields:[{name:'ProductID',type:'string'},{name:'ProductCode',type:'string'},{name:'Name',type:'string'},{name:'UnitOfMeasure',type:'string'},{name:'Price',type:'float'},{name:'CostingMethod',type:'string'},{name:'RevenueAccount',type:'string'},{name:'DropShipMode',type:'string'},{name:'TaxRule',type:'string'},{name:'ImageID',type:'string'},{name:'NonInventory',type:'bool'}]});Ext.define('FamilyOption',{idProperty:'value',extend:'Ext.data.Model',fields:[{name:'value',type:'string'}]});Ext.define('ShipBox',{idProperty:'Box',extend:'Ext.data.Model',fields:[{name:'Box',type:'string'}]});Ext.define('PickLocations',{idProperty:'FakeKey',extend:'Ext.data.Model',fields:[{name:'FakeKey',type:'string'},{name:'ProductID',type:'string'},{name:'ProductCode',type:'string'},{name:'Name',type:'string'},{name:'UnitOfMeasure',type:'string'},{name:'LocationID',type:'string'},{name:'Location',type:'string'},{name:'CostingMethod',type:'string'},{name:'BatchSN',type:'string'},{name:'ExpiryDate',type:'date',dateFormat:'c'},{name:'Available',type:'float'},{name:'ImageID',type:'string'},{name:'IsFirst',type:'bool'},{name:'NonInventory',type:'bool'}]});Ext.define('AutoPick',{extend:'Ext.data.Model',fields:[{name:'ProductID',type:'string'},{name:'ProductCode',type:'string'},{name:'Name',type:'string'},{name:'UnitOfMeasure',type:'string'},{name:'Quantity',type:'float'},{name:'LocationID',type:'string'},{name:'CostingMethod',type:'string'},{name:'BatchSN',type:'string'},{name:'ExpiryDate',type:'date',dateFormat:'c'},{name:'ImageID',type:'string'}]});Ext.define('vOpportunity_CustomerContact',{idProperty:'ContactID',extend:'Ext.data.Model',fields:[{name:'CustomerID',type:'string'},{name:'ContactID',type:'string'},{name:'Name',type:'string'},{name:'IsDefault',type:'bool'},{name:'Phone',type:'string'},{name:'Email',type:'string'}]});Ext.define('vOpportunityAttachement',{idProperty:'AttachementID',extend:'Ext.data.Model',fields:[{name:'OpportunityID',type:'string'},{name:'AttachementID',type:'string'},{name:'BlobGUID',type:'string'},{name:'ContentType',type:'string'},{name:'FileName',type:'string'},{name:'Date',type:'date',dateFormat:'c'},{name:'UserName',type:'string'},{name:'IsProcessed',type:'bool'}]});Ext.define('vShippingLabelAttachment',{idProperty:'BlobGUID',extend:'Ext.data.Model',fields:[{name:'BlobGUID',type:'string'},{name:'TrackNumber',type:'string'}]});Ext.define('History',{idProperty:'EntryID',extend:'Ext.data.Model',fields:[{name:'EntryID',type:'string'},{name:'ColumnsChanged',type:'string'},{name:'DateChanged',type:'date',dateFormat:'c'},{name:'ChangedBy',type:'string'}]});Ext.define('WorkflowHistory',{idProperty:'WorkflowHistoryID',extend:'Ext.data.Model',fields:[{name:'WorkflowHistoryID',type:'string'},{name:'WorkflowID',type:'string'},{name:'EntityID',type:'string'},{name:'EntityType',type:'string'},{name:'ChildEntityID',type:'string'},{name:'ChildEntityType',type:'string'},{name:'Name',type:'string'},{name:'Description',type:'string'},{name:'State',type:'string'},{name:'DateUtc',type:'date',dateFormat:'c'},{name:'WorkflowName',type:'string'},{name:'EventName',type:'string'}]});Ext.define('vFulfillmentOrder',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'ConfigID',type:'string'},{name:'ShippingMethod',type:'string'},{name:'FFOrderId',type:'string'},{name:'ExternalOrderID',type:'string'},{name:'Status',type:'string'},{name:'Source',type:'string'},{name:'Date',type:'date',dateFormat:'c'},{name:'Memo',type:'string'}]});Ext.define('vChartOfAccounts',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'DisplayName',type:'string'},{name:'Class',type:'string'},{name:'Type',type:'string'}]});Ext.define('vTenantPaymentTerm',{idProperty:'TermID',extend:'Ext.data.Model',fields:[{name:'TermID',type:'string'},{name:'Name',type:'string'},{name:'Days',type:'int'},{name:'Method',type:'int'},{name:'DueNextMonth',type:'int'}]});Ext.define('vOpportunity_CustomerAddress',{idProperty:'AddressID',extend:'Ext.data.Model',fields:[{name:'CustomerID',type:'string'},{name:'AddressID',type:'string'},{name:'Line1',type:'string'},{name:'Line2',type:'string'},{name:'Type',type:'string'},{name:'DefaultForType',type:'bool'},{name:'Type',type:'string'},{name:'AddressLine1',type:'string'},{name:'AddressLine2',type:'string'},{name:'AddressCitySuburb',type:'string'},{name:'AddressStateProvince',type:'string'},{name:'AddressCountry',type:'string'},{name:'AddressZipPostCode',type:'string'},{name:'TaxExemptionReasonCode',type:'string'}]});Ext.define('vTenantCarrier',{idProperty:'CarrierID',extend:'Ext.data.Model',fields:[{name:'CarrierID',type:'string'},{name:'Description',type:'string'}]});Ext.define('vTenantCarrierWithShippingOptions',{idProperty:'CarrierID',extend:'Ext.data.Model',fields:[{name:'CarrierID',type:'string'},{name:'Code',type:'string'},{name:'Description',type:'string'},{name:'ExternalService',type:'string'},{name:'IsDefault',type:'bool'}]});Ext.define('vTenantContact',{idProperty:'ContactID',extend:'Ext.data.Model',fields:[{name:'ContactID',type:'string'},{name:'Name',type:'string'}]});Ext.define('Country',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'Name',type:'string'}]});Ext.define('vOpportunity_TenantAddress',{idProperty:'AddressID',extend:'Ext.data.Model',fields:[{name:'AddressID',type:'string'},{name:'Line1',type:'string'},{name:'Line2',type:'string'},{name:'Type',type:'string'},{name:'DefaultForType',type:'bool'}]});Ext.define('vTenantTaxationRule',{idProperty:'RuleID',extend:'Ext.data.Model',fields:[{name:'RuleID',type:'string'},{name:'Description',type:'string'},{name:'EffectivePercentExclusive',type:'float'},{name:'EffectivePercentInclusive',type:'float'},{name:'EffectivePercent',type:'float'},{name:'Inclusive',type:'bool'},{name:'Tax1',type:'string'}]});Ext.define('vTenantLocation',{idProperty:'LocationID',extend:'Ext.data.Model',fields:[{name:'LocationID',type:'string'},{name:'ParentID',type:'string'},{name:'Description',type:'string'},{name:'FFServiceID',type:'string'},{name:'UseForFixedAssetsOnly',type:'bool'},{name:'IsDefault',type:'bool'}]});Ext.define('vSalesPriceTier',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'int'},{name:'Name',type:'string'}]});Ext.define('OpportunityWrapper',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'HasErrors',type:'bool'},{name:'DiscountsDesciption',type:'string'},{name:'HasAvalaraIntegration',type:'bool'},{name:'AvalaraTaxExemptionCode',type:'string'},{name:'Warnings',type:'string'},{name:'ConvertedSaleTaskID',type:'string'}]});Ext.define('SkuAutogenerationFlagModel',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'Value',type:'bool'}]});Ext.define('ReportTemplate',{idProperty:'TemplateID',extend:'Ext.data.Model',fields:[{name:'TemplateID',type:'string'},{name:'Type',type:'string'},{name:'Name',type:'string'}]});Ext.define('CustomerDefaultTemplate',{idProperty:'DefaultTemplateID',extend:'Ext.data.Model',fields:[{name:'DefaultTemplateID',type:'string'},{name:'TemplateID',type:'string'},{name:'Type',type:'string'}]});Ext.define('OpportunityReferenceData',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'int'},{name:'DefaultTaxRule',type:'string'},{name:'DefaultAccountCode',type:'string'},{name:'ProductFamilyCount',type:'int'},{name:'DiscountCount',type:'int'},{name:'ChangePricesDiscountsPermission',type:'string'},{name:'HasPriceInfoAccess',type:'bool'},{name:'UndoPermission',type:'string'},{name:'VoidPermission',type:'string'},{name:'ApprovePermission',type:'string'},{name:'AddEditPermission',type:'string'},{name:'CSVImportPermission',type:'string'},{name:'TasksViewPermission',type:'string'},{name:'CurrentAttributeSetId',type:'string'},{name:'EnableOpportunityApproval',type:'bool'},{name:'TaxCalculationMethod',type:'string'},{name:'DiscountCalculationMethod',type:'string'},{name:'HeadersVisible',type:'bool'},{name:'ForceHideLookup',type:'bool'}]});Ext.define('vTermsMethod',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'int'},{name:'Name',type:'string'}]});Ext.define('vShippingRateOrLabelProvider',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'string'},{name:'IsDefault',type:'bool'},{name:'Name',type:'string'}]});Ext.define('vOpportunityCredits',{idProperty:'SaleCreditID',extend:'Ext.data.Model',fields:[{name:'SaleCreditID',type:'string'},{name:'CustomerID',type:'string'},{name:'CustomerName',type:'string'},{name:'Currency',type:'string'},{name:'Amount',type:'float'},{name:'RemainingAmount',type:'float'},{name:'Account',type:'string'},{name:'SourceLineID',type:'string'},{name:'CreditSourceTaskID',type:'string'},{name:'OrigTaskType',type:'string'},{name:'Type',type:'string'},{name:'Date',type:'date',dateFormat:'Y-m-d'}]});Ext.define('vOpportunityCreditWithDetails',{idProperty:'SaleCreditID',extend:'Ext.data.Model',fields:[{name:'SaleCreditID',type:'string'},{name:'CustomerID',type:'string'},{name:'Currency',type:'string'},{name:'Amount',type:'float'},{name:'RemainingAmount',type:'float'},{name:'Account',type:'string'},{name:'Description',type:'string'},{name:'Date',type:'date',dateFormat:'c'},{name:'AllocatedAmount',type:'float'},{name:'Selected',type:'bool'},{name:'ConvRate',type:'float'}]});Ext.define('vOpportunityAllocations',{idProperty:'AllocationID',extend:'Ext.data.Model',fields:[{name:'SaleCreditID',type:'string'},{name:'AllocationID',type:'string'},{name:'SalePaymentID',type:'string'},{name:'TaskID',type:'string'},{name:'Flag',type:'bool'}]});Ext.define('Opportunity',{idProperty:'OpportunityID',extend:'Ext.data.Model',fields:[{name:'OpportunityID',type:'string'},{name:'CustomerID',type:'string'},{name:'LeadID',type:'string'},{name:'CustomerName',type:'string'},{name:'Contact',type:'string'},{name:'Phone',type:'string'},{name:'Email',type:'string'},{name:'DefaultAccount',type:'string'},{name:'BillingAddressLine1',type:'string'},{name:'BillingAddressLine2',type:'string'},{name:'Currency',type:'string'},{name:'TaxPercent',type:'float'},{name:'TaxInclusive',type:'bool'},{name:'TaxSchema',type:'string'},{name:'Discount',type:'float'},{name:'TermDays',type:'int'},{name:'TermMethod',type:'int'},{name:'Terms',type:'string'},{name:'PriceTier',type:'int'},{name:'ShippingAddressLine1',type:'string'},{name:'ShippingAddressLine2',type:'string'},{name:'OpportunityLocationID',type:'string'},{name:'OpportunityLocation',type:'string'},{name:'OpportunityNumber',type:'string'},{name:'OpportunityDate',type:'date',dateFormat:'c'},{name:'OpportunityMemo',type:'string'},{name:'OpportunityComment',type:'string'},{name:'OpportunityStatus',type:'string'},{name:'CustomerReference',type:'string'},{name:'SalesRepresentative',type:'string'},{name:'CurrencyConversionRate',type:'float'},{name:'CustomerCurrency',type:'string'},{name:'Carrier',type:'string'},{name:'TermDueNextMonth',type:'int'},{name:'ShipAddressID',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'},{name:'ShipToOther',type:'bool'},{name:'ShipToCompany',type:'string'},{name:'ShipToContact',type:'string'},{name:'ShipToCountry',type:'string'},{name:'ShipToPostCode',type:'string'},{name:'ShipToState',type:'string'},{name:'ShipToCity',type:'string'},{name:'ShipToAddress1',type:'string'},{name:'ShipToAddress2',type:'string'},{name:'ASTaxTotal',type:'float'},{name:'ASTotalWithTax',type:'float'},{name:'ProductTaxTotal',type:'float'},{name:'ProductTotalWithTax',type:'float'},{name:'TaxTotal',type:'float'},{name:'TotalWithTax',type:'TotalWithTax'},{name:'CustomField1',type:'string'},{name:'CustomField2',type:'string'},{name:'CustomField3',type:'string'},{name:'CustomField4',type:'string'},{name:'CustomField5',type:'string'},{name:'CustomField6',type:'string'},{name:'CustomField7',type:'string'},{name:'CustomField8',type:'string'},{name:'CustomField9',type:'string'},{name:'CustomField10',type:'string'},{name:'CarrierCode',type:'string'},{name:'CarrierServiceCode',type:'string'},{name:'CarrierServiceDisplayName',type:'string'}],associations:[{type:'hasMany',associationKey:'vOpportunityAdditionalCharges',model:'vOpportunityAdditionalCharges',name:'vOpportunityAdditionalCharges',foreignKey:'OpportunityID',primaryKey:'OpportunityID'},{type:'hasMany',associationKey:'vOpportunityLines',model:'vOpportunityLines',name:'vOpportunityLines',foreignKey:'OpportunityID',primaryKey:'OpportunityID'}]});Ext.define('LookupCarrierModel',{idProperty:'FakeID',extend:'Ext.data.Model',fields:[{name:'FakeID',type:'string'},{name:'CarrierCode',type:'string'},{name:'ServiceCode',type:'string'},{name:'Highlighted',type:'bool'},{name:'DisplayName',type:'string'}]});Ext.define('vOpportunityAdditionalCharges',{idProperty:'FakeID',extend:'Ext.data.Model',fields:[{name:'FakeID',type:'int'},{name:'OpportunityID',type:'string'},{name:'ChargeID',type:'string'},{name:'Description',type:'string'},{name:'Quantity',type:'float'},{name:'Amount',type:'float'},{name:'Discount',type:'float'},{name:'TaxRule',type:'string'},{name:'Tax',type:'float'},{name:'Total',type:'float'},{name:'TaxPercent',type:'float'},{name:'LineOrder',type:'int'},{name:'RevenueAccount',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'},{name:'Comment',type:'string'}]});Ext.define('vOpportunityLines',{idProperty:'FakeID',extend:'Ext.data.Model',fields:[{name:'FakeID',type:'int'},{name:'OpportunityID',type:'string'},{name:'OpportunityLineID',type:'string'},{name:'ProductID',type:'string'},{name:'Quantity',type:'float'},{name:'Price',type:'float'},{name:'Discount',type:'float'},{name:'Tax',type:'float'},{name:'Total',type:'float'},{name:'LineOrder',type:'int'},{name:'Name',type:'string'},{name:'UnitOfMeasure',type:'string'},{name:'ProductCode',type:'string'},{name:'AverageCost',type:'float'},{name:'CostingMethod',type:'string'},{name:'RevenueAccount',type:'string'},{name:'DropShipMode',type:'string'},{name:'TaxRule',type:'string'},{name:'TaxPercent',type:'float'},{name:'Comment',type:'string'},{name:'ImageID',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'}]});Ext.define('Product',{idProperty:'ProductID',extend:'Ext.data.Model',fields:[{name:'ProductID',type:'string'},{name:'ProductCode',type:'string'},{name:'Name',type:'string'},{name:'UnitOfMeasure',type:'string'},{name:'PriceTear1',type:'float'},{name:'PriceTear2',type:'float'},{name:'PriceTear3',type:'float'},{name:'PriceTear4',type:'float'},{name:'PriceTear5',type:'float'},{name:'PriceTear6',type:'float'},{name:'PriceTear7',type:'float'},{name:'PriceTear8',type:'float'},{name:'PriceTear9',type:'float'},{name:'PriceTear10',type:'float'},{name:'Available',type:'float'},{name:'OnHand',type:'float'},{name:'AverageCost',type:'float'},{name:'CostingMethod',type:'string'},{name:'RevenueAccount',type:'string'},{name:'BatchSN',type:'string'},{name:'ExpiryDate',type:'date',dateFormat:'c'},{name:'DropShipMode',type:'string'},{name:'SaleTaxRule',type:'string'},{name:'Account',type:'string'},{name:'TaxRule',type:'string'},{name:'TaxPercent',type:'float'},{name:'ImageID',type:'string'},{name:'Type',type:'string'}]});Ext.define('vTenantUnitOfMeasure',{idProperty:'UnitOfMeasureID',extend:'Ext.data.Model',fields:[{name:'UnitOfMeasureID',type:'string'},{name:'Unit',type:'string'}]});Ext.define('vTenantAttributeSet',{idProperty:'SetID',extend:'Ext.data.Model',fields:[{name:'SetID',type:'string'},{name:'Name',type:'string'},{name:'Column1',type:'string'},{name:'Column2',type:'string'},{name:'Column3',type:'string'},{name:'Column4',type:'string'},{name:'Column5',type:'string'},{name:'Column6',type:'string'},{name:'Column7',type:'string'},{name:'Column8',type:'string'},{name:'Column9',type:'string'},{name:'Column10',type:'string'},{name:'Column1Type',type:'string'},{name:'Column2Type',type:'string'},{name:'Column3Type',type:'string'},{name:'Column4Type',type:'string'},{name:'Column5Type',type:'string'},{name:'Column6Type',type:'string'},{name:'Column7Type',type:'string'},{name:'Column8Type',type:'string'},{name:'Column9Type',type:'string'},{name:'Column10Type',type:'string'},{name:'Column1Values',type:'string'},{name:'Column2Values',type:'string'},{name:'Column3Values',type:'string'},{name:'Column4Values',type:'string'},{name:'Column5Values',type:'string'},{name:'Column6Values',type:'string'},{name:'Column7Values',type:'string'},{name:'Column8Values',type:'string'},{name:'Column9Values',type:'string'},{name:'Column10Values',type:'string'}]});Ext.define('LeadWrapper',{idProperty:'ID',extend:'Ext.data.Model',fields:[{name:'ID',type:'int'},{name:'HasErrors',type:'bool'}]});Ext.define('vLead',{idProperty:'LeadID',extend:'Ext.data.Model',fields:[{name:'LeadID',type:'string'},{name:'LeadStatus',type:'string'},{name:'Name',type:'string'},{name:'Currency',type:'string'},{name:'Amount',type:'float'},{name:'SalesRepresentative',type:'string'},{name:'CloseChance',type:'string'},{name:'CloseDate',type:'date',dateFormat:'c'},{name:'Comments',type:'string'},{name:'PriceTier',type:'float'},{name:'TermID',type:'string'},{name:'TaxSchema',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'}],associations:[{type:'hasMany',associationKey:'vLeadAddresses',model:'vLeadAddress',name:'vLeadAddresses',foreignKey:'LeadID',primaryKey:'LeadID'},{type:'hasMany',associationKey:'vLeadContacts',model:'vLeadContact',name:'vLeadContacts',foreignKey:'LeadID',primaryKey:'LeadID'},{type:'hasMany',associationKey:'vMultilingualTemplateDatas',model:'vMultilingualTemplateDatas',name:'vMultilingualTemplateDatas',foreignKey:'EntityId',primaryKey:'TemplateId'}]});Ext.define('vLeadAddress',{idProperty:'FakeID',extend:'Ext.data.Model',fields:[{name:'Edit',type:'string'},{name:'FakeID',type:'int'},{name:'LeadID',type:'string'},{name:'AddressID',type:'string'},{name:'Line1',type:'string'},{name:'Line2',type:'string'},{name:'CitySuburb',type:'string'},{name:'StateProvince',type:'string'},{name:'ZipPostCode',type:'string'},{name:'Country',type:'string'},{name:'Type',type:'string'},{name:'DefaultForType',type:'bool'},{name:'TaxExemptionReasonCode',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'}]});Ext.define('vLeadContact',{idProperty:'FakeID',extend:'Ext.data.Model',fields:[{name:'Edit',type:'string'},{name:'FakeID',type:'int'},{name:'LeadID',type:'string'},{name:'ContactID',type:'string'},{name:'Name',type:'string'},{name:'Phone',type:'string'},{name:'Fax',type:'string'},{name:'Email',type:'string'},{name:'JobTitle',type:'string'},{name:'MobilePhone',type:'string'},{name:'Website',type:'string'},{name:'IsDefault',type:'bool'},{name:'Comment',type:'string'},{name:'IncludeInEmail',type:'bool'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'}]});};function AutocompleteAddressField(inputId,selectFunction){AutocompleteAddressField.prototype.SetCountry=function(countryName){$.get("/api/address/country/code/".concat(countryName),function(data){if(data!=undefined){AutocompleteAddressField.prototype.CurrentCountryCode=data;if(AutocompleteAddressField.prototype.cmbAddress!=null){AutocompleteAddressField.prototype.cmbAddress.setValue('');}}});};AutocompleteAddressField.prototype.IsEnabled=undefined;AutocompleteAddressField.prototype.IsInitialized=false;AutocompleteAddressField.prototype.AddressInfoStore=null;AutocompleteAddressField.prototype.cmbAddress=null;AutocompleteAddressField.prototype.cmbAddress_StoreQuery=null;AutocompleteAddressField.prototype.CurrentCountryCode=null;AutocompleteAddressField.prototype.Select=function(placeId,successCallback){$.get("/api/address/details/".concat(placeId)).done(function(result){if(result!=undefined){if(successCallback!==undefined&&typeof successCallback==='function'){successCallback(convertResultDetails(result));}else{throw'successCallback not defined for AutocompleteAddressField.prototype.Select';}}});};AutocompleteAddressField.prototype.CheckEnabled=function(successCallback){$.get('/api/address/hasAccess').done(function(result){if(result!==undefined&&result===true){AutocompleteAddressField.prototype.IsEnabled=result;if(successCallback!==undefined&&typeof successCallback==='function'){successCallback(result);}else{throw'successCallback not defined for AutocompleteAddressField.prototype.CheckEnabled';}}else{AutocompleteAddressField.prototype.IsEnabled=false;}}).fail(function(){AutocompleteAddressField.prototype.IsEnabled=false;});};AutocompleteAddressField.prototype.Init=function(successCallback){if(AutocompleteAddressField.prototype.IsEnabled===true&&AutocompleteAddressField.prototype.IsInitialized===false){initControls(inputId,selectFunction);if(successCallback!==undefined&&typeof successCallback==='function'){successCallback();}}else if(AutocompleteAddressField.prototype.IsEnabled===true&&AutocompleteAddressField.prototype.IsInitialized===true){if(successCallback!==undefined&&typeof successCallback==='function'){successCallback();}}else{$.get('/api/address/hasAccess').done(function(result){if(result!==undefined){AutocompleteAddressField.prototype.IsEnabled=result;if(result===true){initControls(inputId,selectFunction);if(successCallback!==undefined&&typeof successCallback==='function'){successCallback();}else{throw'successCallback not defined for AutocompleteAddressField.prototype.IsEnabled';}}}else{AutocompleteAddressField.prototype.IsEnabled=false;}}).fail(function(){AutocompleteAddressField.prototype.IsEnabled=false;});}};AutocompleteAddressField.prototype.Clear=function(){if(AutocompleteAddressField.prototype.cmbAddress!=null){AutocompleteAddressField.prototype.cmbAddress.setValue('');}};function initControls(inputId,selectFunction){Ext.onReady(function(){Ext.define('AddressInfo',{idProperty:'place_id',extend:'Ext.data.Model',fields:[{name:'description',type:'string'},{name:'place_id',type:'string'},{name:'terms',type:'object'}]});AutocompleteAddressField.prototype.AddressInfoStore=Ext.create('Ext.data.JsonStore',{model:'AddressInfo',proxy:{type:'rest',url:'/api/address',reader:{type:'json'},extraParams:{countryCode:''},noCache:true,listeners:{exception:loadException}}});AutocompleteAddressField.prototype.cmbAddress=Ext.create('Ext.ux.ComboBox',{store:AutocompleteAddressField.prototype.AddressInfoStore,queryMode:'remote',typeAhead:true,queryParam:'Name',minChars:0,triggerAction:'all',selectOnTab:true,displayField:'description',valueField:'place_id',renderTo:inputId,selectOnFocus:true,forseSelection:true,emptyText:'Look up an address',enableKeyEvents:true,tabIndex:400,listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.description)]}
',itemSelector:'li.x-boundlist-item'},listeners:{beforequery:function beforequery(queryEvent,eOpts){queryEvent.query=AutocompleteAddressField.prototype.cmbAddress_StoreQuery;if(queryEvent.query===undefined){queryEvent.query='';} if(AutocompleteAddressField.prototype.CurrentCountryCode!=null){AutocompleteAddressField.prototype.AddressInfoStore.getProxy().extraParams={CountryCode:AutocompleteAddressField.prototype.CurrentCountryCode};}},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){AutocompleteAddressField.prototype.cmbAddress_StoreQuery=Me.getRawValue();}},select:function select(){selectFunction.apply(window,arguments);},change:function change(field,newValue){try{document.dispatchEvent(new CustomEvent('cmbAddress_changed'));}catch(_unused){}}}});AutocompleteAddressField.prototype.IsInitialized=true;$("#".concat(inputId)).parents('.hidden').removeClass('hidden');});} function loadException(proxy,response,operation){ProcessException(response,operation,null,null);} function ClearAddressComponents(){$('#Organisation_AddressLine1').val('');$('#Organisation_AddressLine2').val('');$('#Organisation_CitySuburb').val('');$('#Organisation_StateProvince').val('');$('#Organisation_ZipPostcode').val('');} function convertResultDetails(data){ClearAddressComponents();var result={route:'',locality:'',sublocality:'',postalCode:'',state:''};for(var i=0;i0){result.route+="\xA0".concat(value);}else{result.route=value;} $('#Organisation_AddressLine1').val(result.route);break;} case'locality-political':{result.locality=value;$('#Organisation_CitySuburb').val(value);break;} case'sublocality_level_1-sublocality-political':{result.sublocality=value;$('#Organisation_AddressLine2').val(value);break;} case'postal_code':{result.postalCode=value;$('#Organisation_ZipPostcode').val(value);break;} case'administrative_area_level_1-political':{result.state=value;$('#Organisation_StateProvince').val(value);break;}}} return result;}};function Opportunity_NewAddress_LoginSuccessCallback(operation){if(operation.action!='read'){Opportunity_NewAddress_Save();}} function Opportunity_NewAddress_Clear(){dearHelper.control.setValue(txtSale_NewAddress_Line1,'');dearHelper.control.setValue(txtSale_NewAddress_Line2,'');dearHelper.control.setValue(txtSale_NewAddress_CitySuburb,'');dearHelper.control.setValue(txtSale_NewAddress_StateProvince,'');dearHelper.control.setValue(txtSale_NewAddress_ZipPostCode,'');dearHelper.control.setValue(cmbSale_NewAddress_Country,TenantCountry);dearHelper.control.setValue(chkSale_NewAddress_DefaultForType,false);} function Opportunity_NewAddress_Show(){if(typeof NewAddressDialog=='undefined'){Opportunity_NewAddress_Init();}else{Opportunity_NewAddress_Clear();vCustomerAddressStore.removeAll();vCustomerAddressStore.commitChanges();} if(window.NewAddressOrigin=='Billing'){dearHelper.control.setValue(cmbSale_NewAddress_Type,'Billing');}else{dearHelper.control.setValue(cmbSale_NewAddress_Type,'Shipping');} CommonSale.Avalara.setAddressType(cmbSale_NewAddress_Type.val());NewAddressDialog.modal('show');setTimeout(function(){txtSale_NewAddress_Line1.focus();},700);if(window.autocompleteField==undefined){window.autocompleteField=new AutocompleteAddressField('cmbAddress',AutocompleteAddressField_SelectItem);window.autocompleteField.Init(function(){AutocompleteAddressField_SetCountry();cmbSale_NewAddress_Country.change(function(){var name=cmbSale_NewAddress_Country.val();window.autocompleteField.SetCountry(name);});});}else{window.autocompleteField.Clear();window.autocompleteField.SetCountry(cmbSale_NewAddress_Country.val());} setTimeout(AutocompleteAddressField_SetWidth,200);setTimeout(Avalara_TaxReasonCode_Resize,200);} function Opportunity_NewAddress_Init(){AutocompleteAddressField.prototype.cmbAddress=dearHelper.control.init('#cmbAddress',{tabIndex:400});window.txtSale_NewAddress_Line1=dearHelper.control.init('#tdSale_NewAddress_Line1',{tabIndex:401});window.txtSale_NewAddress_Line2=dearHelper.control.init('#tdSale_NewAddress_Line2',{tabIndex:402});window.txtSale_NewAddress_CitySuburb=dearHelper.control.init('#tdSale_NewAddress_CitySuburb',{tabIndex:403});window.txtSale_NewAddress_StateProvince=dearHelper.control.init('#tdSale_NewAddress_StateProvince',{tabIndex:404});window.txtSale_NewAddress_ZipPostCode=dearHelper.control.init('#tdSale_NewAddress_ZipPostCode',{tabIndex:405});window.cmbSale_NewAddress_Country=dearHelper.control.init('#tdSale_NewAddress_Country',{tabIndex:406});window.cmbSale_NewAddress_Type=dearHelper.control.init('#tdSale_NewAddress_Type',{tabIndex:407});window.chkSale_NewAddress_DefaultForType=dearHelper.control.init('#tdSale_NewAddress_DefaultForType',{tabIndex:408});cmbSale_NewAddress_Type.on('change',function(){CommonSale.Avalara.setAddressType(cmbSale_NewAddress_Type.val());});window.countryStore=Ext.create('Ext.data.JsonStore',{model:'Country',autoLoad:false,proxy:{type:'rest',url:'/api/country',reader:{type:'json'}},listeners:{load:function load(store){PopulateStore(store,cmbSale_NewAddress_Country,'Name','Name',TenantCountry,false);}}});countryStore.load();window.NewAddressDialog=$('#Sale_NewAddress_Content');Ext.define('vCustomerAddress',{idProperty:'AddressID',extend:'Ext.data.Model',fields:[{name:'CustomerID',type:'string'},{name:'AddressID',type:'string'},{name:'Line1',type:'string'},{name:'Line2',type:'string'},{name:'CitySuburb',type:'string'},{name:'StateProvince',type:'string'},{name:'ZipPostCode',type:'string'},{name:'Country',type:'string'},{name:'Type',type:'string'},{name:'DefaultForType',type:'bool'},{name:'TaxExemptionReasonCode',type:'string'}]});window.vCustomerAddressStore=Ext.create('Ext.data.JsonStore',{model:'vCustomerAddress',proxy:{type:'rest',url:'/api/Opportunity_Index_vCustomerAddress',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,Opportunity_NewAddress_LoginSuccessCallback);txtSale_NewAddress_Line1.focus();}}},listeners:{write:function write(){var saved=vCustomerAddressStore.getAt(0);var savedID=saved.getId();var Line1="".concat(saved.get('Line1')," ").concat(saved.get('Line2'));var Line2="".concat(saved.get('CitySuburb')," ").concat(saved.get('StateProvince')," ").concat(saved.get('ZipPostCode'));var newCustomerAddress=new vOpportunity_CustomerAddress({AddressID:savedID,CustomerID:saved.get('CustomerID'),Type:saved.get('Type'),DefaultForType:saved.get('DefaultForType'),Line1:Line1,Line2:Line2,AddressLine1:saved.get('Line1'),AddressLine2:saved.get('Line2'),AddressCitySuburb:saved.get('CitySuburb'),AddressStateProvince:saved.get('StateProvince'),AddressCountry:saved.get('Country'),AddressZipPostCode:saved.get('ZipPostCode'),TaxExemptionReasonCode:saved.get('TaxExemptionReasonCode')});vOpportunity_CustomerAddressStore.add(newCustomerAddress);if(NewAddressOrigin=='Billing'){cmbBillingAddressLine1.setValue(Line1);txtBillingAddressLine2.setValue(Line2);}else if(NewAddressOrigin=='Shipping'){cmbShippingAddressLine1.setValue(Line1);txtShippingAddressLine2.setValue(Line2);Opportunity_Index_SetOpportunityProperty('ShipAddressID',savedID);Opportunity_Index_SetOpportunityProperty('ShipToAddress1',newCustomerAddress.get('AddressLine1'));Opportunity_Index_SetOpportunityProperty('ShipToAddress2',newCustomerAddress.get('AddressLine2'));Opportunity_Index_SetOpportunityProperty('ShipToCity',newCustomerAddress.get('AddressCitySuburb'));Opportunity_Index_SetOpportunityProperty('ShipToState',newCustomerAddress.get('AddressStateProvince'));Opportunity_Index_SetOpportunityProperty('ShipToCountry',newCustomerAddress.get('AddressCountry'));Opportunity_Index_SetOpportunityProperty('ShipToPostCode',newCustomerAddress.get('AddressZipPostCode'));} NewAddressDialog.modal('hide');if(NewAddressOrigin==='Billing'){Dear_Notification_Info('A new billing address has been added.');}else{Dear_Notification_Info('A new shipping address has been added.');} if(NewAddressOrigin==='Billing'){cmbBillingAddressLine1.focus();}else{cmbShippingAddressLine1.focus();}}}});Opportunity_NewAddress_Clear();$(window).resize(function(){if(window.autocompleteField!=undefined){var width=AutocompleteAddressField_GetWidth();window.autocompleteField.cmbAddress.setWidth(width);} Avalara_TaxReasonCode_Resize();});} function Opportunity_NewAddress_Save(){if(!window.__HighlightInvalidFields.validation(['tdSale_NewAddress_Line1'])){return false;} var Line1=dearHelper.control.getValue(txtSale_NewAddress_Line1);var Line2=dearHelper.control.getValue(txtSale_NewAddress_Line2);var CitySuburb=dearHelper.control.getValue(txtSale_NewAddress_CitySuburb);var StateProvince=dearHelper.control.getValue(txtSale_NewAddress_StateProvince);var ZipPostCode=dearHelper.control.getValue(txtSale_NewAddress_ZipPostCode);var Country=dearHelper.control.getValue(cmbSale_NewAddress_Country);var Type=dearHelper.control.getValue(cmbSale_NewAddress_Type);var DefaultForType=dearHelper.control.getValue(chkSale_NewAddress_DefaultForType);var avalaraTaxExemptionCode=CommonSale.Avalara.getCurrentSelectedCode();var CustomerID=Opportunity_Index_GetOpportunityProperty('CustomerID');var isForLead=false;if(!CustomerID){CustomerID=Opportunity_Index_GetOpportunityProperty('LeadID');isForLead=true;} if(vCustomerAddressStore.getCount()==1){var model=vCustomerAddressStore.getAt(0);model.set('CustomerID',CustomerID);model.set('Line1',Line1);model.set('Line2',Line2);model.set('CitySuburb',CitySuburb);model.set('StateProvince',StateProvince);model.set('ZipPostCode',ZipPostCode);model.set('Country',Country);model.set('Type',Type);model.set('DefaultForType',DefaultForType);model.set('TaxExemptionReasonCode',avalaraTaxExemptionCode);}else{var model=new vCustomerAddress({CustomerID:CustomerID,Line1:Line1,Line2:Line2,CitySuburb:CitySuburb,StateProvince:StateProvince,ZipPostCode:ZipPostCode,Country:Country,Type:Type,DefaultForType:DefaultForType,TaxExemptionReasonCode:avalaraTaxExemptionCode});vCustomerAddressStore.add(model);} NewEntityType='Address';vCustomerAddressStore.getProxy().extraParams={isForLead:isForLead};vCustomerAddressStore.save();} function Opportunity_NewAddress_Cancel(){NewAddressDialog.modal('hide');} function AutocompleteAddressField_SelectItem(){var newValue=window.autocompleteField.AddressInfoStore.getById(window.autocompleteField.cmbAddress.getValue());if(newValue!==null&&newValue!==undefined){window.autocompleteField.Select(newValue.data.place_id,function(data){txtSale_NewAddress_Line1.val(data.route);txtSale_NewAddress_Line2.val(data.sublocality);txtSale_NewAddress_CitySuburb.val(data.locality);txtSale_NewAddress_ZipPostCode.val(data.postalCode);txtSale_NewAddress_StateProvince.val(data.state);});}} function AutocompleteAddressField_GetWidth(){console.log($('#tdSale_NewAddress_Line1').outerWidth());var width=$('#tdSale_NewAddress_Line1').outerWidth();return width-45;} function AutocompleteAddressField_SetWidth(){if(window.autocompleteField.IsInitialized===true){window.autocompleteField.cmbAddress.setWidth(AutocompleteAddressField_GetWidth());}else{setTimeout(AutocompleteAddressField_SetWidth,10);}} function AutocompleteAddressField_SetCountry(){var countryName=cmbSale_NewAddress_Country.val();if(countryName){window.autocompleteField.SetCountry(countryName);}else{setTimeout(AutocompleteAddressField_SetCountry,100);}} function Avalara_TaxReasonCode_Resize(){var width=$('#tdSale_NewAddress_CitySuburb').outerWidth();CommonSale.Avalara.resizeSaleAddressCmb(width);};function Sale_EditAddress_LoginSuccessCallback(operation){if(operation.action!='read'){Sale_EditAddress_Save();}} function Sale_EditAddress_Show(){if(IsReadOnly){return;} if(typeof EditAddressDialog=='undefined'){Sale_EditAddress_Init();} var ffTask=OpportunityUpdated.getAt(0);dearHelper.control.setValue(txtSale_EditAddress_Line1,ffTask.get('ShipToAddress1'));dearHelper.control.setValue(txtSale_EditAddress_Line2,ffTask.get('ShipToAddress2'));dearHelper.control.setValue(txtSale_EditAddress_CitySuburb,ffTask.get('ShipToCity'));dearHelper.control.setValue(txtSale_EditAddress_StateProvince,ffTask.get('ShipToState'));dearHelper.control.setValue(txtSale_EditAddress_ZipPostCode,ffTask.get('ShipToPostCode'));dearHelper.control.setValue(cmbSale_EditAddress_Country,ffTask.get('ShipToCountry'));cmbShipAnotherCustomer.setValue(null);cmbShipAnotherAddressLine1.setValue(null);EditAddressDialog.modal('show');setTimeout(function(){txtSale_EditAddress_Line1.focus();},500);} function Sale_EditAddress_Init(){window.txtSale_EditAddress_Line1=$('#tdSale_EditAddress_Line1');window.txtSale_EditAddress_Line2=$('#tdSale_EditAddress_Line2');window.txtSale_EditAddress_CitySuburb=$('#tdSale_EditAddress_CitySuburb');window.txtSale_EditAddress_StateProvince=$('#tdSale_EditAddress_StateProvince');window.txtSale_EditAddress_ZipPostCode=$('#tdSale_EditAddress_ZipPostCode');window.cmbSale_EditAddress_Country=$('#tdSale_EditAddress_Country');window.countryStoreForGiftAddress=Ext.create('Ext.data.JsonStore',{model:'Country',autoLoad:false,proxy:{type:'rest',url:'/api/country',reader:{type:'json'}},listeners:{load:function load(store){var ffTask=OpportunityUpdated.getAt(0);var defaultCountry=TenantCountry;if(ffTask!=null&&ffTask.get('ShipToCountry')!=null&&ffTask.get('ShipToCountry')!=''){defaultCountry=ffTask.get('ShipToCountry');} PopulateStore(store,cmbSale_EditAddress_Country,'Name','Name',defaultCountry,false);}}});countryStoreForGiftAddress.load();window.EditAddressDialog=$('#Sale_EditAddress_Content');} function Sale_EditAddress_Save(){if(IsReadOnly){return;} if(!window.__HighlightInvalidFields.validation(['tdSale_EditAddress_Country'])){return false;} var country=dearHelper.control.getValue(cmbSale_EditAddress_Country);if(!country){Dear_Notification_Error('Country should be selected.');return;} var saleTask=OpportunityUpdated.getAt(0);saleTask.set('ShipToAddress1',dearHelper.control.getValue(txtSale_EditAddress_Line1));saleTask.set('ShipToAddress2',dearHelper.control.getValue(txtSale_EditAddress_Line2));saleTask.set('ShipToCity',dearHelper.control.getValue(txtSale_EditAddress_CitySuburb));saleTask.set('ShipToState',dearHelper.control.getValue(txtSale_EditAddress_StateProvince));saleTask.set('ShipToPostCode',dearHelper.control.getValue(txtSale_EditAddress_ZipPostCode));saleTask.set('ShipToCountry',country);Sale_EditAddress_Cancel();} function Sale_EditAddress_Cancel(){Sale_Index_UpdateOtherAddress();EditAddressDialog.modal('hide');} function Sale_ShowAddressSearch(){$('#divShowAddressSearch').addClass('hiddenContent');$('#divHideAddressSearch').removeClass('hiddenContent');$('#divSale_Index_Ship_Another_Customer').removeClass('hiddenContent');var width=$('#Sale_Index_Ship_Another_Customer').width();cmbShipAnotherCustomer.setWidth(width);cmbShipAnotherAddressLine1.setWidth(width);} function Sale_HideAddressSearch(){$('#divShowAddressSearch').removeClass('hiddenContent');$('#divHideAddressSearch').addClass('hiddenContent');$('#divSale_Index_Ship_Another_Customer').addClass('hiddenContent');};function Opportunity_NewContact_LoginSuccessCallback(operation){if(operation.action!='read'){Opportunity_NewContact_Save();}} function Opportunity_NewContact_Clear(){dearHelper.control.setValue(txtSale_NewContact_Name,'');dearHelper.control.setValue(txtSale_NewContact_JobTitle,'');dearHelper.control.setValue(txtSale_NewContact_Phone,'');dearHelper.control.setValue(txtSale_NewContact_MobilePhone,'');dearHelper.control.setValue(txtSale_NewContact_Fax,'');dearHelper.control.setValue(txtSale_NewContact_Email,'');dearHelper.control.setValue(txtSale_NewContact_Website,'');dearHelper.control.setValue(txtSale_NewContact_Comment,'');dearHelper.control.setValue(chkSale_NewContact_IsDefault,false);} function Opportunity_NewContact_Show(){if(typeof NewContactDialog=='undefined'){Opportunity_NewContact_Init();}else{Opportunity_NewContact_Clear();vCustomerContactStore.removeAll();vCustomerContactStore.commitChanges();} NewContactDialog.modal('show');setTimeout(function(){txtSale_NewContact_Name.focus();},700);} function Opportunity_NewContact_Init(){window.txtSale_NewContact_Name=dearHelper.control.init('#tdSale_NewContact_Name',{tabIndex:700});window.txtSale_NewContact_JobTitle=dearHelper.control.init('#tdSale_NewContact_JobTitle',{tabIndex:701});window.txtSale_NewContact_Phone=dearHelper.control.init('#tdSale_NewContact_Phone',{tabIndex:702});window.txtSale_NewContact_MobilePhone=dearHelper.control.init('#tdSale_NewContact_MobilePhone',{tabIndex:703});window.txtSale_NewContact_Fax=dearHelper.control.init('#tdSale_NewContact_Fax',{tabIndex:704});window.txtSale_NewContact_Email=dearHelper.control.init('#tdSale_NewContact_Email',{tabIndex:705});window.txtSale_NewContact_Website=dearHelper.control.init('#tdSale_NewContact_Website',{tabIndex:706});window.txtSale_NewContact_Comment=dearHelper.control.init('#tdSale_NewContact_Comment',{tabIndex:708});window.chkSale_NewContact_IsDefault=dearHelper.control.init('#tdSale_NewContact_IsDefault',{tabIndex:707});dearHelper.control.setValue(chkSale_NewContact_IsDefault,false);window.NewContactDialog=$('#Sale_NewContact_Content');Ext.define('vCustomerContact',{idProperty:'ContactID',extend:'Ext.data.Model',fields:[{name:'CustomerID',type:'string'},{name:'ContactID',type:'string'},{name:'Name',type:'string'},{name:'JobTitle',type:'string'},{name:'Phone',type:'string'},{name:'MobilePhone',type:'string'},{name:'Fax',type:'string'},{name:'Email',type:'string'},{name:'Website',type:'string'},{name:'IsDefault',type:'bool'},{name:'Comment',type:'string'}]});window.vCustomerContactStore=Ext.create('Ext.data.JsonStore',{model:'vCustomerContact',proxy:{type:'rest',url:'/api/Opportunity_Index_vCustomerContact',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,Opportunity_NewContact_LoginSuccessCallback);txtSale_NewContact_Name.focus();}}},autoLoad:false,listeners:{write:function write(){var saved=vCustomerContactStore.getAt(0);var savedID=saved.getId();var newCustomerContact=new vOpportunity_CustomerContact({ContactID:savedID,CustomerID:saved.get('CustomerID'),Name:saved.get('Name'),IsDefault:saved.get('IsDefault'),Phone:saved.get('Phone'),Email:saved.get('Email')});vOpportunity_CustomerContactStore.add(newCustomerContact);cmbContact.setValue(saved.get('Name'));txtPhone.setValue(saved.get('Phone'));txtEmail.setValue(saved.get('Email'));Opportunity_Index_SetOpportunityProperty('ShipToContact',saved.get('Name'));NewContactDialog.modal('hide');Dear_Notification_Info('New customer contact has been added.');cmbContact.focus();}}});Opportunity_NewContact_Clear();} function Opportunity_NewContact_Save(){if(!window.__HighlightInvalidFields.validation(['tdSale_NewContact_Name'])){return false;} var Name=dearHelper.control.getValue(txtSale_NewContact_Name);var JobTitle=dearHelper.control.getValue(txtSale_NewContact_JobTitle);var Phone=dearHelper.control.getValue(txtSale_NewContact_Phone);var MobilePhone=dearHelper.control.getValue(txtSale_NewContact_MobilePhone);var Fax=dearHelper.control.getValue(txtSale_NewContact_Fax);var Email=dearHelper.control.getValue(txtSale_NewContact_Email);var Website=dearHelper.control.getValue(txtSale_NewContact_Website);var Comment=dearHelper.control.getValue(txtSale_NewContact_Comment);var IsDefault=dearHelper.control.getValue(chkSale_NewContact_IsDefault);var CustomerID=Opportunity_Index_GetOpportunityProperty('CustomerID');var isForLead=false;if(!CustomerID){CustomerID=Opportunity_Index_GetOpportunityProperty('LeadID');isForLead=true;} if(vCustomerContactStore.getCount()==1){var model=vCustomerContactStore.getAt(0);model.set('CustomerID',CustomerID);model.set('Name',Name);model.set('JobTitle',JobTitle);model.set('Phone',Phone);model.set('MobilePhone',MobilePhone);model.set('Fax',Fax);model.set('Email',Email);model.set('Website',Website);model.set('IsDefault',IsDefault);model.set('Comment',Comment);}else{var model=new vCustomerContact({CustomerID:CustomerID,Name:Name,JobTitle:JobTitle,Phone:Phone,MobilePhone:MobilePhone,Fax:Fax,Email:Email,Website:Website,IsDefault:IsDefault,Comment:Comment});vCustomerContactStore.add(model);} NewEntityType='Contact';vCustomerContactStore.getProxy().extraParams={isForLead:isForLead};vCustomerContactStore.save();} function Opportunity_NewContact_Cancel(){NewContactDialog.modal('hide');};function Sale_NewCustomer_LoginSuccessCallback(operation){Sale_NewCustomer_Save();} function Sale_NewCustomer_Show(){if(typeof NewCustomerDialog=='undefined'){Sale_NewCustomer_Init();}else{Sale_NewCustomer_ApplyDefaults();vCustomerStore.removeAll();vCustomerStore.commitChanges();} DFVHandler.getValuesAsync(window.DefaultFieldValuesConstant.EntityTypes.Customer,function(data){DFVHandler.setValues(window.DefaultFieldValuesConstant.EntityTypes.Customer,data);});NewCustomerDialog.modal('show');setTimeout(function(){txtSale_NewCustomer_Name.focus();Sale_NewCustomer_UpdateControlSize();},700);} function Sale_NewCustomer_ApplyDefaults(){dearHelper.control.setValue(txtSale_NewCustomer_Name,cmbCustomer.getValue());if(vTenantPaymentTermStore.getCount()>0){dearHelper.control.setValue(cmbSale_NewCustomer_PaymentTerm,vTenantPaymentTermStore.getAt(0).get('TermID'));}else{dearHelper.control.setValue(cmbSale_NewCustomer_PaymentTerm,null);} if(vTenantTaxationRuleStore.getCount()==1){dearHelper.control.setValue(cmbSale_NewCustomer_TaxRule,vTenantTaxationRuleStore.getAt(0).get('RuleID'));}else if(!IsEmptyID(DefaultTaxRule)){dearHelper.control.setValue(cmbSale_NewCustomer_TaxRule,DefaultTaxRule);}else{dearHelper.control.setValue(cmbSale_NewCustomer_TaxRule,null);} if(vTenantContactsStore.getCount()>0){dearHelper.control.setValue(cmbSale_NewCustomer_DefaultSalesRepresentative,vTenantContactsStore.getAt(0).get('ContactID'));}else{dearHelper.control.setValue(cmbSale_NewCustomer_DefaultSalesRepresentative,null);} cmbLead_Index_Status.setValue(null);cmbLead_Index_CloseChance.setValue(null);txtLead_Index_Amount.setValue(0);dearHelper.control.setValue(cmbSale_NewCustomer_SalePriceTier,1);dearHelper.control.setValue(txtSale_NewCustomer_Comments,null);dtCloseDate.setValue(moment().add(1,'M').toDate());cmbSale_NewCustomer_Currency.setValue(TenantCurrency);} function Sale_NewCustomer_Init(){window.txtSale_NewCustomer_Name=dearHelper.control.init('#tdOpportunity_NewCustomer_Name',{tabIndex:101});window.cmbSale_NewCustomer_PaymentTerm=dearHelper.control.init('#tdOpportunity_NewCustomer_PaymentTerm',{tabIndex:108});window.cmbSale_NewCustomer_DefaultSalesRepresentative=dearHelper.control.init('#tdOpportunity_NewCustomer_DefaultSalesRepresentative',{tabIndex:104});window.cmbSale_NewCustomer_TaxRule=dearHelper.control.init('#tdOpportunity_NewCustomer_TaxRule',{tabIndex:106});window.cmbSale_NewCustomer_SalePriceTier=dearHelper.control.init('#tdOpportunity_NewCustomer_SalePriceTier',{tabIndex:110});window.txtSale_NewCustomer_Comments=dearHelper.control.init('#tdOpportunity_NewCustomer_Comments',{tabIndex:113});Ext.define('Currency',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'Name',type:'string'}]});Lead_Common_InitStatusModels();window.currencyStore=Ext.create('Ext.data.JsonStore',{model:'Currency',proxy:{type:'rest',url:'/api/currency',reader:{type:'json'}},autoLoad:false});currencyStore.load();window.cmbSale_NewCustomer_Currency=Ext.create('Ext.ux.ComboBox',{store:currencyStore,queryMode:'remote',typeAhead:true,triggerAction:'all',minChars:0,tabIndex:102,selectOnTab:true,lazyRender:true,queryParam:'Code',displayField:'Code',inputId:'Sale_NewCustomer_Currency',valueField:'Code',renderTo:'tdOpportunity_NewCustomer_Currency',selectOnFocus:true,forceSelection:true,anchor:'100%',listConfig:{getInnerTpl:function getInnerTpl(){return'{[RenderHTMLText(values.Code)]} - {[RenderHTMLText(values.Name)]}';}},listeners:{blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement}});Sale_NewCustomer_LoadComboboxes();Ext.define('vLead',{idProperty:'LeadID',extend:'Ext.data.Model',fields:[{name:'LeadID',type:'string'},{name:'LeadStatus',type:'string'},{name:'Name',type:'string'},{name:'Currency',type:'string'},{name:'Amount',type:'float'},{name:'SalesRepresentative',type:'string'},{name:'CloseChance',type:'string'},{name:'CloseDate',type:'date',dateFormat:'c'},{name:'Comments',type:'string'},{name:'PriceTier',type:'float'},{name:'TermID',type:'string'},{name:'TaxSchema',type:'string'},{name:'ValidationText',type:'string'},{name:'ValidationState',type:'string'}]});window.vCustomerStore=Ext.create('Ext.data.JsonStore',{model:'vLead',proxy:{type:'rest',url:'/api/Opportunity_Index_vCustomer',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,Sale_NewCustomer_LoginSuccessCallback);txtSale_NewCustomer_Name.focus();}}},autoLoad:false,listeners:{write:function write(){var saved=vCustomerStore.getAt(0);var savedID=saved.getId();var newCustomer=new vOpportunity_Customer({CustomerID:savedID,isLead:true,Name:saved.get('Name'),Currency:saved.get('Currency'),PaymentTerm:saved.get('TermID'),TaxRule:saved.get('TaxSchema'),Comments:saved.get('Comments'),DefaultSalesRepresentative:saved.get('SalesRepresentative'),SalePriceTier:saved.get('PriceTier')});vOpportunity_CustomerStore.add(newCustomer);cmbCustomer.setValue('');cmbCustomer.setValue(saved.get('Name'));NewCustomerDialog.modal('hide');Dear_Notification_Success('A new lead has been created.');cmbCustomer.focus();}}});window.NewCustomerDialog=$('#Sale_NewCustomer_Content');Sale_NewCustomer_ApplyDefaults();$(window).resize(function(){Sale_NewCustomer_UpdateControlSize();});CommonSale_NewCustomer_DefaultValuesInit();} function Sale_NewCustomer_UpdateControlSize(){var width=$('#tdOpportunity_NewCustomer_Currency').width();cmbSale_NewCustomer_Currency.setWidth(width);} function Sale_NewCustomer_LoadComboboxes(){window.CloseChanceStore=new Ext.data.ArrayStore({fields:['Value','Name'],data:[['0','0%'],['10','10%'],['20','20%'],['30','30%'],['40','40%'],['50','50%'],['60','60%'],['70','70%'],['80','80%'],['90','90%'],['100','100%']]});LeadStatusStore.load();window.cmbLead_Index_CloseChance=Ext.create('Ext.ux.ComboBox',{store:CloseChanceStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,tabIndex:105,displayField:'Name',valueField:'Value',renderTo:'tdLead_Index_CloseChance',selectOnFocus:true,editable:false,forceSelection:true,emptyText:'choose...',inputId:'Lead_Index_CloseChance',listeners:{blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement}});window.cmbLead_Index_Status=Ext.create('Ext.ux.ComboBox',{store:LeadStatusStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Name',valueField:'Name',tabIndex:103,inputId:'Lead_Index_Status',renderTo:'tdLead_Index_Status',editable:false,forceSelection:true,emptyText:'choose...',listeners:{blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement}});window.txtLead_Index_Amount=Ext.create('Ext.form.field.Number',{renderTo:'tdLead_Index_Amount',tabIndex:107,minValue:0,maxValue:100000,decimalPrecision:6,inputId:'Lead_Index_Amount',hideTrigger:true,step:0,selectOnFocus:true,editable:true});window.dtCloseDate=Ext.create('Ext.form.field.Date',{renderTo:'tdLead_Index_CloseDate',emptyText:'choose...',altFormats:dearAltFormats,format:UserDateFormat,tabIndex:109,selectOnFocus:true,inputId:'Lead_Index_CloseDate',listeners:{blur:HideDateInputElement,focus:ShowInputElement}});PopulateStore(vTenantContactsStore,cmbSale_NewCustomer_DefaultSalesRepresentative,'ContactID','Name',null,false);PopulateStore(vTenantPaymentTermStore,cmbSale_NewCustomer_PaymentTerm,'TermID','Name',null,false);var newTaxRuleStore=Ext.create('Ext.data.JsonStore',{model:'vTenantTaxationRule',proxy:{type:'rest',reader:{type:'json',root:'SaleTaxRules'}}});var cnt=vTenantTaxationRuleStore.getCount();for(var i=0;iService';cmbSale_NewProduct_Type.closest('.form-control').addClass('hiddenContent');}else{TypeStore.add({Type:'Non Inventory'});options+='';TypeStore.add({Type:'Stock'});options+='';} window.cmbSale_NewProduct_Type.html(options);window.cmbSale_NewProduct_Type.selectpicker('refresh');Sale_NewProduct_AdjustControlsByType(dearHelper.control.getValue(cmbSale_NewProduct_Type));Sale_NewProduct_UpdateCustomAttributeControls();DFVHandler.getValuesAsync(window.DefaultFieldValuesConstant.EntityTypes.Product,function(data){DFVHandler.setValues(window.DefaultFieldValuesConstant.EntityTypes.Product,data);});NewProductDialog.modal('show');setTimeout(function(){txtSale_NewProduct_ProductCode.focus();Sale_NewProduct_UpdateControlSize();},700);} function Sale_NewProduct_UpdateControlSize(){var width=$('#tdSale_NewProduct_Supplier').width();cmbSale_NewProduct_Supplier.setWidth(width);width=$('[data-id="Sale_NewProduct_ProductAttributeSet"]',window.NewProductDialog).outerWidth();AttributeSet.Fields.setWidth(width);} function Sale_NewProduct_Init(){Ext.define('vTenantInventoryCategory',{idProperty:'CategoryID',extend:'Ext.data.Model',fields:[{name:'CategoryID',type:'string'},{name:'Category',type:'string'}]});Ext.define('vExpenseAccounts',{idProperty:'Code',extend:'Ext.data.Model',fields:[{name:'Code',type:'string'},{name:'DisplayName',type:'string'},{name:'Class',type:'string'},{name:'ForPayments',type:'bool'},{name:'Type',type:'string'}]});window.vTenantInventoryCategoryStore=Ext.create('Ext.data.JsonStore',{model:'vTenantInventoryCategory',proxy:{type:'rest',url:'/api/Sale_Index_Category',reader:{type:'json'}},listeners:{load:function load(store){PopulateStore(store,cmbSale_NewProduct_Category,'CategoryID','Category',null,false);}}});vTenantInventoryCategoryStore.load();window.vExpenseAccountsStore=Ext.create('Ext.data.JsonStore',{model:'vExpenseAccounts',proxy:{type:'rest',url:'/api/Sale_Index_vChartOfAccountsExpense',reader:{type:'json'}},listeners:{load:function load(store){PopulateStore(store,cmbSale_NewProduct_ExpenseAccount,'Code','DisplayName',null,false);Common_COA_TreeMode_Selectpicker_RestoreCodes(cmbSale_NewProduct_ExpenseAccount,store);}}});vExpenseAccountsStore.load();window.NewProductDialog=$('#Sale_NewProduct_Content');window.txtSale_NewProduct_ProductCode=dearHelper.control.init('#Sale_NewProduct_ProductCode',{tabIndex:700});window.txtSale_NewProduct_Name=dearHelper.control.init('#Sale_NewProduct_Name',{tabIndex:701});window.cmbSale_NewProduct_Type=$('#Sale_NewProduct_Type');window.cmbSale_NewProduct_Category=dearHelper.control.init('#Sale_NewProduct_Category',{tabIndex:702});window.cmbSale_NewProduct_PurchaseTaxRule=dearHelper.control.init('#Sale_NewProduct_PurchaseTaxRule',{tabIndex:703});window.cmbSale_NewProduct_SaleTaxRule=dearHelper.control.init('#Sale_NewProduct_SaleTaxRule',{tabIndex:704});window.SupplierStoreQuery='';window.cmbSale_NewProduct_Supplier=Ext.create('Ext.ux.ComboBox',{store:SupplierStore,queryMode:'remote',typeAhead:true,queryParam:'Name',minChars:0,triggerAction:'query',inputId:'Sale_NewProduct_Supplier',selectOnTab:true,displayField:'Name',valueField:'SupplierID',renderTo:'tdSale_NewProduct_Supplier',emptyText:'type to search...',selectOnFocus:true,forseSelection:true,enableKeyEvents:true,tabIndex:706,width:270,listConfig:{},listeners:{blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(queryEvent,eOpts){queryEvent.query=window.SupplierStoreQuery;},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.SupplierStoreQuery=Me.getRawValue();}}}});window.cmbSale_NewProduct_PurchasePrice=dearHelper.control.init('#Sale_NewProduct_PurchasePrice',{tabIndex:707});dearHelper.control.addNumberMaskWithDecmal(cmbSale_NewProduct_PurchasePrice);window.cmbSale_NewProduct_UnitOfMeasure=dearHelper.control.init('#Sale_NewProduct_UnitOfMeasure',{tabIndex:708});window.cmbSale_NewProduct_CostingMethod=dearHelper.control.init('#Sale_NewProduct_CostingMethod',{tabIndex:709});window.txtSale_NewProduct_MinimumBeforeReorder=dearHelper.control.init('#Sale_NewProduct_MinimumBeforeReorder',{tabIndex:710});window.txtSale_NewProduct_ReorderQuantity=dearHelper.control.init('#Sale_NewProduct_ReorderQuantity',{tabIndex:711});dearHelper.control.addNumberMaskWithDecmal(txtSale_NewProduct_MinimumBeforeReorder);dearHelper.control.addNumberMaskWithDecmal(txtSale_NewProduct_ReorderQuantity);window.txtSale_NewProduct_Barcode=dearHelper.control.init('#Sale_NewProduct_Barcode',{tabIndex:712});window.Sale_NewProduct_txtStockLocator=dearHelper.control.init('#Sale_NewProduct_StockLocator',{tabIndex:713});window.cmbSale_NewProduct_DropShipMode=dearHelper.control.init('#Sale_NewProduct_DropShipMode',{tabIndex:713});window.Sale_NewProduct_cmbProductAttributeSet=dearHelper.control.init('#Sale_NewProduct_ProductAttributeSet',{tabIndex:714});window.Sale_NewProduct_cmbProductAttributeSet.on('change',function(){Sale_NewProduct_UpdateCustomAttributeControls();});window.cmbSale_NewProduct_ExpenseAccount=dearHelper.control.init('#Sale_NewProduct_ExpenseAccount',{tabIndex:725});window.TypeStore=new Ext.data.ArrayStore({fields:['Type'],data:[]});window.cmbSale_NewProduct_Type.on('change',function(){var value=dearHelper.control.getValue(cmbSale_NewProduct_Type);Sale_NewProduct_AdjustControlsByType(value);});if(SkuAutogenerationFlag.Value()){$('#txtSale_NewProduct_ProductCode').attr('placeholder','auto-generated');dearHelper.control.setDisabled(txtSale_NewProduct_ProductCode,true);} if(SkuAutogenerationFlag.Value()&&IsReadOnly){dearHelper.control.setReadOnly(txtSale_NewProduct_ProductCode,true);} PopulateStore(window.PurchaseTaxRuleStore,cmbSale_NewProduct_PurchaseTaxRule,'RuleID','Description',null,true);PopulateStore(window.vTenantTaxationRuleStore,cmbSale_NewProduct_SaleTaxRule,'RuleID','Description',null,true);PopulateStore(window.vTenantUnitOfMeasureStore,cmbSale_NewProduct_UnitOfMeasure,'UnitOfMeasureID','Unit',null,false);PopulateStore(window.vTenantExpenseAccountStore,cmbSale_NewProduct_ExpenseAccount,'ExpenseAccountID','Unit',null,false);window.NewProductCostingMethodStore=CreateCostingMethodStore();PopulateStore(window.NewProductCostingMethodStore,cmbSale_NewProduct_CostingMethod,'CostingMethod','DisplayName',null,false);window.DropShipModeStore=CreateDropShipModeStore();PopulateStore(window.DropShipModeStore,cmbSale_NewProduct_DropShipMode,'DropShipMode','DisplayName',null,false);PopulateStore(window.AttributeSetStore,Sale_NewProduct_cmbProductAttributeSet,'SetID','Name',null,false);Ext.define('vProduct',{idProperty:'ProductID',extend:'Ext.data.Model',fields:[{name:'ProductID',type:'string'},{name:'SkuAutogenerationFlag',type:'bool'},{name:'ProductCode',type:'string'},{name:'Name',type:'string'},{name:'Category',type:'string'},{name:'Type',type:'string'},{name:'DefaultUnitOfMeasure',type:'string'},{name:'CostingMethod',type:'string'},{name:'MinimumBeforeReorder',type:'float'},{name:'ReorderQuantity',type:'float'},{name:'QuantityToProduce',type:'float'},{name:'ProductAttributeSet',type:'string'},{name:'Barcode',type:'string'},{name:'CustomField1',type:'string'},{name:'CustomField2',type:'string'},{name:'CustomField3',type:'string'},{name:'CustomField4',type:'string'},{name:'CustomField5',type:'string'},{name:'CustomField6',type:'string'},{name:'CustomField7',type:'string'},{name:'CustomField8',type:'string'},{name:'CustomField9',type:'string'},{name:'CustomField10',type:'string'},{name:'Status',type:'string'},{name:'StockLocator',type:'string'},{name:'DropShipMode',type:'string'},{name:'AverageCost',type:'float'},{name:'PurchaseTaxRule',type:'string'},{name:'LastSuppliedBy',type:'string'},{name:'SaleTaxRule',type:'string'},{name:'ExpenseAccount',type:'string'},{name:'BrandID',type:'string'},{name:'DiscountID',type:'string'},{name:'DefaultLocation',type:'string'},{name:'NotSellable',type:'string'}]});window.NewvProductStore=Ext.create('Ext.data.JsonStore',{model:'vProduct',proxy:{type:'rest',url:'/api/Sale_Index_Product',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,Sale_NewProduct_LoginSuccessCallback);txtSale_NewProduct_ProductCode.focus();}}},autoLoad:false,listeners:{write:function write(){var saved=NewvProductStore.getAt(0);var ID=saved.getId();var Name=saved.get('Name');var Code=saved.get('ProductCode');var flag=saved.get('SkuAutogenerationFlag');var UnitOfMeasure=saved.get('DefaultUnitOfMeasure');var CostingMethod=saved.get('CostingMethod');var position=null;var TaxRule=window.IsSaleTaxManagementServiceEnabled!==true?saved.get('SaleTaxRule'):Opportunity_Index_GetOpportunityProperty('TaxSchema');var DropShipMode=saved.get('DropShipMode');var targetRecord=null;if(NewProductOrigin=='QuoteProduct'||NewProductOrigin=='Order'){if(NewProductOrigin=='QuoteProduct'){position=vOpportunityLinesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vOpportunityLinesStore.getAt(position);} if(NewProductOrigin=='Order'){position=vSaleOrderLinesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vSaleOrderLinesStore.getAt(position);} targetRecord.set('Name',Name);targetRecord.set('ProductID',ID);targetRecord.set('ProductCode',Code);targetRecord.set('SkuAutogenerationFlag',flag);targetRecord.set('UnitOfMeasure',UnitOfMeasure);targetRecord.set('AverageCost',0);targetRecord.set('CostingMethod',CostingMethod);targetRecord.set('RevenueAccount',null);targetRecord.set('DropShipMode',DropShipMode);targetRecord.set('DropShip',DropShipMode!='N');if(!IsEmptyID(TaxRule)){var ruleRec=vTenantTaxationRuleStore.getById(TaxRule);if(ruleRec!=null){targetRecord.set('TaxRule',TaxRule);if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){targetRecord.set('TaxPercent',ruleRec.get('EffectivePercentInclusive'));}else{targetRecord.set('TaxPercent',ruleRec.get('EffectivePercentExclusive'));} UpdateTaxAndTotal(targetRecord);}}}else{if(NewProductOrigin=='QuoteService'){position=vOpportunityAdditionalChargesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vOpportunityAdditionalChargesStore.getAt(position);} if(NewProductOrigin=='OrderService'){position=vSaleOrderAdditionalChargesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vSaleOrderAdditionalChargesStore.getAt(position);} if(NewProductOrigin=='Invoice'){position=vSaleInvoiceAdditionalChargesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vSaleInvoiceAdditionalChargesStore.getAt(position);} if(NewProductOrigin=='CreditNote'){position=vSaleCreditNoteCostLinesGrid.getSelectionModel().getCurrentPosition().row;targetRecord=vSaleCreditNoteCostLinesStore.getAt(position);} targetRecord.set('Description',Name);if(!IsEmptyID(TaxRule)){var ruleRec=vTenantTaxationRuleStore.getById(TaxRule);if(ruleRec!=null){targetRecord.set('TaxRule',TaxRule);if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){targetRecord.set('TaxPercent',ruleRec.get('EffectivePercentInclusive'));}else{targetRecord.set('TaxPercent',ruleRec.get('EffectivePercentExclusive'));} UpdateAdditionalTaxAndTotal(targetRecord);}}} NewProductDialog.modal('hide');Dear_Notification_Info('A new product has been created.');switch(NewProductOrigin){case'QuoteProduct':vOpportunityLinesEditing.startEditByPosition({row:position,column:1});break;case'QuoteService':vOpportunityAdditionalChargesEditing.startEditByPosition({row:position,column:1});break;case'Order':vSaleOrderLinesEditing.startEditByPosition({row:position,column:1});break;case'OrderService':vSaleOrderAdditionalChargesEditing.startEditByPosition({row:position,column:1});break;case'Invoice':vSaleInvoiceAdditionalChargesEditing.startEditByPosition({row:position,column:1});break;case'CreditNote':vSaleCreditNoteCostLinesEditing.startEditByPosition({row:position,column:1});break;}}}});$(window).resize(function(){Sale_NewProduct_UpdateControlSize();});Sale_NewProduct_Clear();CommonSale_NewProduct_DefaultValuesInit();} function Sale_NewProduct_Save(){if(!window.__HighlightInvalidFields.validation(['Sale_NewProduct_ProductCode','Sale_NewProduct_Name','Sale_NewProduct_Category','Sale_NewProduct_UnitOfMeasure','Sale_NewProduct_CostingMethod','Sale_NewProduct_ExpenseAccount'])){return false;} var skuAutogenerationFlag=SkuAutogenerationFlag.Value();var ProductCode=dearHelper.control.getValue(txtSale_NewProduct_ProductCode);var Name=dearHelper.control.getValue(txtSale_NewProduct_Name);var Type=dearHelper.control.getValue(cmbSale_NewProduct_Type);var Category=dearHelper.control.getValue(cmbSale_NewProduct_Category);var UnitOfMeasure=dearHelper.control.getValue(cmbSale_NewProduct_UnitOfMeasure);var CostingMethod=dearHelper.control.getValue(cmbSale_NewProduct_CostingMethod);var ExpenseAccount=dearHelper.control.getValue(cmbSale_NewProduct_ExpenseAccount);var MinimumBeforeReorder=dearHelper.control.getValue(txtSale_NewProduct_MinimumBeforeReorder);var ReorderQuantity=dearHelper.control.getValue(txtSale_NewProduct_ReorderQuantity);var Barcode=dearHelper.control.getValue(txtSale_NewProduct_Barcode);var DropShipMode=dearHelper.control.getValue(cmbSale_NewProduct_DropShipMode);var LastSuppliedBy=cmbSale_NewProduct_Supplier.getValue();var PurchaseCost=dearHelper.control.getValue(cmbSale_NewProduct_PurchasePrice);var ProductAttributeSet=dearHelper.control.getValue(Sale_NewProduct_cmbProductAttributeSet);var PurchaseTaxRule=dearHelper.control.getValue(cmbSale_NewProduct_PurchaseTaxRule);var SaleTaxRule=dearHelper.control.getValue(cmbSale_NewProduct_SaleTaxRule);var StockLocator=dearHelper.control.getValue(Sale_NewProduct_txtStockLocator);if(NewvProductStore.getCount()==1){var model=NewvProductStore.getAt(0);model.set('SkuAutogenerationFlag',skuAutogenerationFlag);model.set('ProductCode',ProductCode);model.set('Name',Name);model.set('Category',Category);model.set('DefaultUnitOfMeasure',UnitOfMeasure);model.set('CostingMethod',CostingMethod);model.set('ExpenseAccount',ExpenseAccount);model.set('MinimumBeforeReorder',MinimumBeforeReorder);model.set('ReorderQuantity',ReorderQuantity);model.set('Barcode',Barcode);model.set('Type',Type);model.set('ProductAttributeSet',ProductAttributeSet);model.set('Status','A');model.set('QuantityToProduce',1);model.set('StockLocator',StockLocator);model.set('DropShipMode',DropShipMode);model.set('AverageCost',PurchaseCost);model.set('LastSuppliedBy',LastSuppliedBy);model.set('PurchaseTaxRule',PurchaseTaxRule);model.set('SaleTaxRule',SaleTaxRule);}else{var model=new vProduct({SkuAutogenerationFlag:skuAutogenerationFlag,ProductCode:ProductCode,Name:Name,Category:Category,Type:Type,DefaultUnitOfMeasure:UnitOfMeasure,CostingMethod:CostingMethod,ExpenseAccount:ExpenseAccount,MinimumBeforeReorder:MinimumBeforeReorder,ReorderQuantity:ReorderQuantity,Barcode:Barcode,ProductAttributeSet:ProductAttributeSet,Status:'A',QuantityToProduce:1,StockLocator:StockLocator,DropShipMode:DropShipMode,AverageCost:PurchaseCost,LastSuppliedBy:LastSuppliedBy,PurchaseTaxRule:PurchaseTaxRule,SaleTaxRule:SaleTaxRule,BrandID:DFVHandler.getFieldData(window.DefaultFieldValuesConstant.EntityTypes.Product,window.DefaultFieldValuesConstant.FieldNames.ProductBrand),DiscountID:DFVHandler.getFieldData(window.DefaultFieldValuesConstant.EntityTypes.Product,window.DefaultFieldValuesConstant.FieldNames.ProductDiscount),DefaultLocation:DFVHandler.getFieldData(window.DefaultFieldValuesConstant.EntityTypes.Product,window.DefaultFieldValuesConstant.FieldNames.ProductLocation),NotSellable:DFVHandler.getFieldData(window.DefaultFieldValuesConstant.EntityTypes.Product,window.DefaultFieldValuesConstant.FieldNames.ProductIsSelling)});NewvProductStore.add(model);} AttributeSet.Fields.prepareSave(NewvProductStore.getAt(0));NewEntityType='Product';NewvProductStore.save();} function Sale_NewProduct_Cancel(){NewProductDialog.modal('hide');} function Sale_NewProduct_AdjustControlsByType(newType){if(newType==='Stock'){Ext.get('trExpenseAccount').addCls('hiddenContent');Ext.get('trCostingMethod').removeCls('hiddenContent');Ext.get('trMinimumBeforeReorder').removeCls('hiddenContent');Ext.get('trReorderQuantity').removeCls('hiddenContent');Ext.get('trStockLocator').removeCls('hiddenContent');Ext.get('trSupplier').removeCls('hiddenContent');Ext.get('trPurchasePrice').removeCls('hiddenContent');Ext.get('trDropShipMode').removeCls('hiddenContent');}else if(newType==='Non Inventory'){Ext.get('trExpenseAccount').removeCls('hiddenContent');Ext.get('trCostingMethod').removeCls('hiddenContent');Ext.get('trMinimumBeforeReorder').addCls('hiddenContent');Ext.get('trReorderQuantity').addCls('hiddenContent');Ext.get('trStockLocator').addCls('hiddenContent');Ext.get('trSupplier').addCls('hiddenContent');Ext.get('trPurchasePrice').addCls('hiddenContent');Ext.get('trDropShipMode').addCls('hiddenContent');}else{Ext.get('trExpenseAccount').addCls('hiddenContent');Ext.get('trCostingMethod').addCls('hiddenContent');Ext.get('trMinimumBeforeReorder').addCls('hiddenContent');Ext.get('trReorderQuantity').addCls('hiddenContent');Ext.get('trStockLocator').addCls('hiddenContent');Ext.get('trSupplier').addCls('hiddenContent');Ext.get('trPurchasePrice').addCls('hiddenContent');Ext.get('trDropShipMode').addCls('hiddenContent');}};function Sale_NewTenantContact_LoginSuccessCallback(operation){if(operation.action!='read'){Sale_NewTenantContact_Save();}} function Sale_NewTenantContact_Clear(){dearHelper.control.setValue(txtSale_NewTenantContact_Name,'');dearHelper.control.setValue(txtSale_NewTenantContact_Phone,'');dearHelper.control.setValue(txtSale_NewTenantContact_Fax,'');dearHelper.control.setValue(txtSale_NewTenantContact_Email,'');dearHelper.control.setValue(txtSale_NewTenantContact_Website,'');dearHelper.control.setValue(txtSale_NewTenantContact_Comment,'');} function Sale_NewTenantContact_Show(){if(typeof NewTenantContactDialog=='undefined'){Sale_NewTenantContact_Init();}else{Sale_NewTenantContact_Clear();vNewTenantContactStore.removeAll();vNewTenantContactStore.commitChanges();} NewTenantContactDialog.modal('show');setTimeout(function(){txtSale_NewTenantContact_Name.focus();},700);} function Sale_NewTenantContact_Init(){window.txtSale_NewTenantContact_Name=$('#tdSale_NewTenantContact_Name');window.txtSale_NewTenantContact_Phone=$('#tdSale_NewTenantContact_Phone');window.txtSale_NewTenantContact_Fax=$('#tdSale_NewTenantContact_Fax');window.txtSale_NewTenantContact_Email=$('#tdSale_NewTenantContact_Email');window.txtSale_NewTenantContact_Website=$('#tdSale_NewTenantContact_Website');window.txtSale_NewTenantContact_Comment=$('#tdSale_NewTenantContact_Comment');window.NewTenantContactDialog=$('#Sale_NewTenantContact_Content');Ext.define('NewvTenantContact',{idProperty:'ContactID',extend:'Ext.data.Model',fields:[{name:'ContactID',type:'string'},{name:'Name',type:'string'},{name:'Phone',type:'string'},{name:'Fax',type:'string'},{name:'Email',type:'string'},{name:'Website',type:'string'},{name:'Type',type:'string'},{name:'DefaultForType',type:'bool'},{name:'Comment',type:'string'}]});window.vNewTenantContactStore=Ext.create('Ext.data.JsonStore',{model:'NewvTenantContact',proxy:{type:'rest',url:'/api/Sale_Index_vTenantContact',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,Sale_NewTenantContact_LoginSuccessCallback);txtSale_NewTenantContact_Name.focus();}}},autoLoad:false,listeners:{write:function write(){var saved=vNewTenantContactStore.getAt(0);var savedID=saved.getId();var newContact=new vTenantContact({ContactID:savedID,Name:saved.get('Name')});vTenantContactsStore.add(newContact);cmbSalesRepresentative.setValue(saved.get('Name'));NewTenantContactDialog.modal('hide');Dear_Notification_Info('A new sales representative has been added.');cmbSalesRepresentative.focus();}}});Sale_NewTenantContact_Clear();} function Sale_NewTenantContact_Save(){if(!window.__HighlightInvalidFields.validation(['tdSale_NewTenantContact_Name'])){return false;} var Name=dearHelper.control.getValue(txtSale_NewTenantContact_Name);var Phone=dearHelper.control.getValue(txtSale_NewTenantContact_Phone);var Fax=dearHelper.control.getValue(txtSale_NewTenantContact_Fax);var Email=dearHelper.control.getValue(txtSale_NewTenantContact_Email);var Website=dearHelper.control.getValue(txtSale_NewTenantContact_Website);var Comment=dearHelper.control.getValue(txtSale_NewTenantContact_Comment);if(vNewTenantContactStore.getCount()==1){var model=vNewTenantContactStore.getAt(0);model.set('Name',Name);model.set('Phone',Phone);model.set('Fax',Fax);model.set('Email',Email);model.set('Website',Website);model.set('Comment',Comment);model.set('DefaultForType',false);model.set('Type','Sale');}else{var model=new NewvTenantContact({Name:Name,Phone:Phone,Fax:Fax,Email:Email,Website:Website,DefaultForType:false,Type:'Sale',Comment:Comment});vNewTenantContactStore.add(model);} NewEntityType='Contact';vNewTenantContactStore.save();} function Sale_NewTenantContact_Cancel(){NewTenantContactDialog.modal('hide');};function TenantPaymentTerm_NewTerm_LoginSuccessCallback(operation){if(operation.action!='read'){TenantPaymentTerm_NewTerm_Save();}} function TenantPaymentTerm_NewTerm_Show(NewTermCallback){window.NewTermCallback=NewTermCallback;if(typeof NewTermDialog=='undefined'){TenantPaymentTerm_NewTerm_Init();}else{window.txtTenantPaymentTerm_NewTerm_Days_PreviousValue=0;dearHelper.control.setValue(txtTenantPaymentTerm_NewTerm_Name,'');dearHelper.control.setValue(cmbTenantPaymentTerm_NewTerm_Method,'1');dearHelper.control.setValue(txtTenantPaymentTerm_NewTerm_Days,'0');NewvTenantPaymentTermStore.removeAll();NewvTenantPaymentTermStore.commitChanges();} NewTermDialog.modal('show');} function TenantPaymentTerm_NewTerm_Init(){Ext.define('vTenantPaymentTermNew',{idProperty:'TermID',extend:'Ext.data.Model',fields:[{name:'TermID',type:'string',persist:false},{name:'Name',type:'string'},{name:'Days',type:'int'},{name:'Method',type:'int'},{name:'DueNextMonth',type:'int'},{name:'IsActive',type:'bool'},{name:'IsDefault',type:'bool'}]});window.txtTenantPaymentTerm_NewTerm_Name=dearHelper.control.init('#tdTenantPaymentTerm_NewTerm_Name',{tabIndex:301});window.cmbTenantPaymentTerm_NewTerm_Method=dearHelper.control.init('#tdTenantPaymentTerm_NewTerm_Method',{tabIndex:302});window.txtTenantPaymentTerm_NewTerm_Days=dearHelper.control.init('#tdTenantPaymentTerm_NewTerm_Days',{tabIndex:303});dearHelper.control.addNumberMask(txtTenantPaymentTerm_NewTerm_Days);window.cmbTenantPaymentTerm_NewTerm_Method.on('change',function(){if(window.cmbTenantPaymentTerm_NewTerm_Method.val()==3){window.txtTenantPaymentTerm_NewTerm_Days.val('');window.txtTenantPaymentTerm_NewTerm_Days.attr('placeholder','Not applicable');dearHelper.control.setDisabled(window.txtTenantPaymentTerm_NewTerm_Days,true);}else{window.txtTenantPaymentTerm_NewTerm_Days.val(window.txtTenantPaymentTerm_NewTerm_Days_PreviousValue).trigger('change');dearHelper.control.setDisabled(window.txtTenantPaymentTerm_NewTerm_Days,false);window.txtTenantPaymentTerm_NewTerm_Days.removeAttr('placeholder');}});window.cmbTenantPaymentTerm_NewTerm_Method.trigger('change');window.txtTenantPaymentTerm_NewTerm_Days.on('change',function(){if(window.txtTenantPaymentTerm_NewTerm_Days.val()==''||window.txtTenantPaymentTerm_NewTerm_Days.val()=='-'){window.txtTenantPaymentTerm_NewTerm_Days.val(0);} var max=999;if(window.cmbTenantPaymentTerm_NewTerm_Method.val()==2){max=31;} var value=this.value;value=parseFloat(value);if(value<0||isNaN(value)){this.value=0;}else if(value>max){this.value=max;} window.txtTenantPaymentTerm_NewTerm_Days_PreviousValue=this.value;});window.txtTenantPaymentTerm_NewTerm_Days.trigger('change');window.txtTenantPaymentTerm_NewTerm_Days.on('change',function(){if(window.txtTenantPaymentTerm_NewTerm_Days.val()==''){window.txtTenantPaymentTerm_NewTerm_Days.val(0);}});window.txtTenantPaymentTerm_NewTerm_Days.trigger('change');window.NewvTenantPaymentTermStore=Ext.create('Ext.data.JsonStore',{model:'vTenantPaymentTermNew',proxy:{type:'rest',url:'/api/TenantPaymentTerm_Index_vTenantPaymentTerm',writer:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,TenantPaymentTerm_NewTerm_LoginSuccessCallback);txtTenantPaymentTerm_NewTerm_Name.focus();}}},listeners:{write:function write(){var saved=NewvTenantPaymentTermStore.getAt(0);window.NewTermCallback(saved);NewTermDialog.modal('hide');Dear_Notification_Info('A new term has been created.');}}});window.NewTermDialog=$('#TenantPaymentTerm_NewTerm_Content');window.NewTermDialog.on('shown.bs.modal',function(){txtTenantPaymentTerm_NewTerm_Name.focus();});} function TenantPaymentTerm_NewTerm_Save(){if(!window.__HighlightInvalidFields.validation(['tdTenantPaymentTerm_NewTerm_Name','tdTenantPaymentTerm_NewTerm_Method','tdTenantPaymentTerm_NewTerm_Days'])){return false;} var Name=dearHelper.control.getValue(txtTenantPaymentTerm_NewTerm_Name);var Days=dearHelper.control.getValue(txtTenantPaymentTerm_NewTerm_Days);var Method=dearHelper.control.getValue(cmbTenantPaymentTerm_NewTerm_Method);var error='';if(!Name){error+='Please enter name of the payment term.
';} if(!Days&&Method!=3){error+='Please enter no of days for the payment term.
';} if(error){Dear_Notification_Error(error);return;} if(NewvTenantPaymentTermStore.getCount()==1){var model=NewvTenantPaymentTermStore.getAt(0);model.set('Name',Name);model.set('Days',Days);model.set('Method',Method);model.set('DueNextMonth',-1);model.set('IsActive',true);model.set('IsDefault',false);}else{var model=new vTenantPaymentTermNew({Name:Name,Days:Days,Method:Method,DueNextMonth:-1,IsActive:true,IsDefault:false});NewvTenantPaymentTermStore.add(model);} NewEntityType='Term';NewvTenantPaymentTermStore.save();} function TenantPaymentTerm_NewTerm_Cancel(){NewTermDialog.modal('hide');};function Sale_Quote_ApplyDiscounts(submitAfterAction,callback,OnlyDiscountedProducts){var discountRecord=Sale_Index_Get_DiscountType('FreeShipping');if(discountRecord){Sale_Quote_Apply_FreeShippingDiscount(discountRecord);return;} if(typeof OnlyDiscountedProducts==='undefined'){OnlyDiscountedProducts=false;} Sale_Index_LoadPrices(cmbPriceTier.getValue(),submitAfterAction,callback,OnlyDiscountedProducts);} function Sale_Quote_IsLinesFieldEditable(value,record){if(value=='Tax rule'&&StatusTracker.quote.readOnlyTaxAccounts){return false;} if(value!='Tax rule'&&StatusTracker.quote.readOnly){return false;} if(PricesDiscountsPermission!='Full'&&(value=='Price'||value=='Discount')&&(record.get('Discount')!=0||value=='Discount')){return false;} if(CountrySpecificKey!==''&&value=='Tax rule'&&typeof Sale_CountrySpecific_LinesTaxEditable!=='undefined'){if(!Sale_CountrySpecific_LinesTaxEditable()){return false;}} return true;} function Sale_Quote_IsAdditionalLinesFieldEditable(value){if(value=='Tax rule'&&StatusTracker.quote.readOnlyTaxAccounts){return false;} if(value!='Tax rule'&&StatusTracker.quote.readOnly){return false;} if(CountrySpecificKey!==''&&value=='Tax rule'&&typeof Sale_CountrySpecific_AdditionalChargesTaxEditable!=='undefined'){if(!Sale_CountrySpecific_AdditionalChargesTaxEditable()){return false;}} return true;} function Sale_Quote_IsPaymentLinesFieldEditable(value,record){if(StatusTracker.deposits.readOnly){return false;} if(value=='Conversion rate'){var customerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency').toUpperCase();if(Sale_Index_GetBankAccountCurrency(record.get('AccountCode'))==customerCurrency){return false;}} return true;} function Sale_Quote_CreateControls(){window.txtOpportunity_Memo=dearHelper.control.init('#tdOpportunity_Memo',{textAutoHeight:true});Ext.override(Ext.view.DragZone,{getDragText:function getDragText(){if(this.dragText=='{Name}'){return this.dragData.records[0].data.Name;} if(this.dragText=='{Description}'){return this.dragData.records[0].data.Description;}}});window.vOpportunityLinesEditing=Ext.create('Ext.grid.plugin.CellEditing',{clicksToEdit:1,listeners:{beforeedit:function beforeedit(editor,e,eOpts){if(!HasPriceInfoAccess){return false;} if(e.field=='TaxRule'&&StatusTracker.quote.readOnlyTaxAccounts){return false;} if(e.field!='TaxRule'&&StatusTracker.quote.readOnly){return false;} if(StatusTracker.quote.readOnlyLines&&!StatusTracker.quote.allowChangeAuthorized){return false;} if(PricesDiscountsPermission!='Full'&&(e.field=='Price'||e.field=='Discount')&&(e.value!=0||e.field=='Discount')){return false;} if(CountrySpecificKey!==''&&e.field=='TaxRule'&&typeof Sale_CountrySpecific_LinesTaxEditable!=='undefined'){if(!Sale_CountrySpecific_LinesTaxEditable()){return false;}} if(e.field=='ProductCode'||e.field=='Name'){QuoteProductStore.getProxy().extraParams={lang:currentUILang,TaskLocationID:cmbLocation.getValue(),currencyRate:txtSale_Index_CurrencyConversionRate.getValue(),customerID:Opportunity_Index_GetOpportunityProperty('CustomerID')};var columnEditor=vOpportunityLinesGrid.columns[e.colIdx].getEditor();columnEditor.bindStore(QuoteProductStore);}},validateedit:SaleEditCalculator,edit:function edit(editor,e){if(e.field=='ProductCode'&&e.value!=e.originalValue){var count=QuoteProductStore.getCount();for(var i=0;i0){Sale_Order_ApplyDiscounts(false,function(){Opportunity_Authorize();});}else{Opportunity_Authorize();}});$('#divSetInProgress').click(function myfunction(){StatusTracker.setOpportunityStatus(StatusTracker.statuses.inProgress);window.PlannedOperation='';Opportunity_Index_Submit();});$('#btApprove').click(function(){StatusTracker.setOpportunityStatus(StatusTracker.statuses.won);Opportunity_Index_Submit();});$('#btReject').click(function(){StatusTracker.setOpportunityStatus(StatusTracker.statuses.inReview);Opportunity_Index_Submit();});$('#btReview').click(function(){dearSwal({title:'Confirmation',text:'This will change the opportunity status back to draft. You will need to complete and authorise your changes again. Would you like to proceed anyway?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes!',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){StatusTracker.setOpportunityStatus(StatusTracker.statuses.draft);Opportunity_Index_Submit();}});});$('#btMarkAsLost').click(function(){StatusTracker.setOpportunityStatus(StatusTracker.statuses.lost);Opportunity_Index_Submit();});$('#divExport_Quote').click(Sale_Quote_Download);$('#divImport_Quote').click(Sale_Quote_ShowUploadDialog);window.vOpportunityLinesGrid=Ext.create('Ext.grid.Panel',{header:false,border:false,ddGroup:'vOpportunityLinesDDGroup',enableDragDrop:true,stateful:true,stateId:"OpportunityLines".concat(randomGridInc()),cls:'edit-grid',maxHeight:700,emptyText:'You do not have any products in this opportunity.',viewConfig:{plugins:{ptype:'gridviewdragdrop',dragText:'{Name}'},listeners:{drop:function drop(){this.refresh();}},markDirty:false},listeners:{viewready:GridTooltipsListener,beforestatesave:function beforestatesave(){if(StatusTracker.quote.readOnly){$('#Sale_Quote_AddQuoteLinesRecordLink').parent().addClass('hiddenContent');$('#Sale_Quote_AddQuoteLinesRecordLink').addClass('hiddenContent');}else{$('#Sale_Quote_AddQuoteLinesRecordLink').parent().removeClass('hiddenContent');$('#Sale_Quote_AddQuoteLinesRecordLink').removeClass('hiddenContent');}}},columns:[GetValidationColumnConfig('vOpportunityLinesGrid','Sale_Quote_Lines_ResetLayout','auto','vOpportunityLinesGrid'),{header:'Product',flex:3,dataIndex:'ProductCode',disableQTip:true,editor:new Ext.ux.ComboBox({store:QuoteProductStore,queryMode:'remote',typeAhead:true,queryParam:'Name',minChars:0,triggerAction:'query',tdCls:'colImage',selectOnTab:true,displayField:'ProductCode',valueField:'ProductCode',selectOnFocus:true,forseSelection:true,matchFieldWidth:false,enableKeyEvents:true,listConfig:{tpl:tpl_productFullWithModal('Sale_Quote_NewProduct'),itemSelector:'.x-boundlist-item',width:600,listeners:{beforeshow:function beforeshow(picker){}}},listeners:{specialkey:function specialkey(field,e){ColumnTab(e);},beforequery:function beforequery(queryEvent,eOpts){if(window.resetLastQueryQuote===true){this.lastQuery=null;window.resetLastQueryQuote=false;} queryEvent.query=window.QuoteProductStoreQuery;},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.QuoteProductStoreQuery=Me.getRawValue();}}}}),renderer:function renderer(val,meta,record){return Common_RenderProductCellWithImg(val,meta,record,'QuoteLineID');}},{header:'Comment',flex:1,dataIndex:'Comment',renderer:function renderer(val){return AdjustMultilineContent(val);},editor:new Ext.form.field.TextArea({fieldCls:'normalWrapWithImage',width:600,grow:true,listeners:{specialkey:function specialkey(field,e){ColumnTab(e);}}}),summaryType:'count',summaryRenderer:function summaryRenderer(){return'Total:';}},{header:'Unit',flex:1,dataIndex:'UnitOfMeasure',hidden:true,renderer:function renderer(value){var rec=vTenantUnitOfMeasureStore.getById(value);if(rec!=null){return RenderHTMLText(rec.get('Unit'));}else{return'';}}},{header:'Quantity',flex:1,dataIndex:'Quantity',align:'right',editor:new Ext.form.field.Text({selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vOpportunityLinesGrid,vOpportunityLinesEditing,e);ColumnTab(e);}}}),summaryType:'sum',summaryRenderer:function summaryRenderer(value){if(HasPriceInfoAccess){return"".concat(DEARRound(value,4),"");}else{return'No access';}}},{header:'Price',flex:1,dataIndex:'Price',align:'right',renderer:function renderer(val){if(HasPriceInfoAccess){if(val!=null){return DEARPriceFormat(val);}else{return'';}}else{return'No access';}},editor:new Ext.form.field.Text({selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vOpportunityLinesGrid,vOpportunityLinesEditing,e);ColumnTab(e);}}})},{header:'Discount',flex:1,dataIndex:'Discount',align:'right',xtype:'numbercolumn',format:'0',editor:new Ext.form.field.Number({allowBlank:false,hideTrigger:true,decimalPrecision:4,step:0,selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){ColumnTab(e);UpDownArrowGridHandler(vOpportunityLinesGrid,vOpportunityLinesEditing,e);}}}),renderer:function renderer(val){return"".concat(val,"%");}},{header:'Tax rule',flex:1,dataIndex:'TaxRule',editor:new Ext.ux.ComboBox({store:vTenantTaxationRuleStore,queryMode:'local',typeAhead:true,minChars:0,triggerAction:'all',selectOnTab:true,displayField:'Description',valueField:'RuleID',selectOnFocus:true,forseSelection:true,matchFieldWidth:false,listConfig:{tpl:tpl_simpleList(),itemSelector:'.x-boundlist-item',width:150,listeners:{beforeshow:function beforeshow(picker){picker.minWidth=picker.up('combobox').getSize().width;}}},listeners:{beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;},specialkey:function specialkey(field,e){ColumnTab(e);}}}),renderer:function renderer(val){var rec=vTenantTaxationRuleStore.getById(val);if(rec!=null){var description=RenderHTMLText(rec.get('Description'));if(window.IsSaleTaxManagementServiceEnabled===true){var toolTipText=Ext.String.format(val===window.SaleTaxManagementRuleID?'Tax will be calculated by {0}.':'This tax has been calculated by {0}: {1}',window.SaleTaxManagementServiceName,description);return"").concat(description,"");}else{return description;}}else{return'';}}},{header:'Margin',flex:1,dataIndex:'AverageCost',itemId:'colMargin_Quote',hideable:false,sortable:false,align:'right',renderer:function renderer(val,meta,record){var TaxPercent=record.get('TaxPercent');var TaxInclusive=Opportunity_Index_GetOpportunityProperty('TaxInclusive');var Amount=0;var discount=record.get('Discount');var price=record.get('Price');Amount=price;if(discount>0){Amount-=price*discount/100;} var BaseAmount=Amount;if(TaxPercent>0&&TaxInclusive){Amount-=BaseAmount*TaxPercent/100;} var PurchasePrice=val;var SalePrice=Amount;var rate=txtSale_Index_CurrencyConversionRate.getValue();SalePrice=SalePrice*rate;if(SalePrice<0.000045){SalePrice=0;} var Margin=SalePrice==0?0:(SalePrice-PurchasePrice)*100/SalePrice;Margin=DEARRound(Margin,2);if(Margin>0){return"".concat(DEARMoneyFormat(Margin),"%");}else if(Margin<0){return"".concat(DEARMoneyFormat(Margin),"%");}else{return"".concat(DEARMoneyFormat(Margin),"%");}}},{header:'Total',flex:1,dataIndex:'Total',align:'right',renderer:function renderer(val){if(HasPriceInfoAccess){if(val!=null){return"".concat(DEARMoneyFormat(val),"");}else{return val;}}else{return'No access';}},summaryType:'sum',summaryRenderer:function summaryRenderer(value){if(HasPriceInfoAccess){return"".concat(DEARMoneyFormat(value),"");}else{return'No access';}}},window.extExtension.column.getDelete({id:'colDelete_QuoteLines',listeners:{click:function click(grid,td,rowIndex){vOpportunityLinesStore.removeAt(rowIndex);Sale_Quote_UpdateTotals();}}})],selModel:{selType:'cellmodel'},renderTo:'divQuoteLines',flex:1,plugins:[vOpportunityLinesEditing],features:[{ftype:'summary'}]});window.vOpportunityAdditionalChargesEditing=Ext.create('Ext.grid.plugin.CellEditing',{clicksToEdit:1,listeners:{beforeedit:function beforeedit(editor,e){if(!HasPriceInfoAccess){return false;} if(e.field=='TaxRule'&&StatusTracker.quote.readOnlyTaxAccounts){return false;} if(e.field!='TaxRule'&&StatusTracker.quote.readOnly){return false;} if(CountrySpecificKey!==''&&e.field=='TaxRule'&&typeof Sale_CountrySpecific_AdditionalChargesTaxEditable!=='undefined'){if(!Sale_CountrySpecific_AdditionalChargesTaxEditable()){return false;}}},validateedit:SaleEditCalculator,edit:function edit(editor,e){if(e.field=='TaxRule'&&e.value!=e.originalValue){var rec=vTenantTaxationRuleStore.getById(e.value);if(rec!=null){if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){e.record.set('TaxPercent',rec.get('EffectivePercentInclusive'));}else{e.record.set('TaxPercent',rec.get('EffectivePercentExclusive'));} if(CountrySpecificKey!==''&&typeof Sale_CountrySpecific_TaxRateOverride!=='undefined'){Sale_CountrySpecific_TaxRateOverride(e.record);} UpdateAdditionalTaxAndTotal(e.record);Sale_Quote_UpdateTotals();}} if(e.field=='Description'&&e.value!=e.originalValue){var count=ServiceStore.getCount();var serviceFound=false;for(var i=0;itype to search...';}}},{header:'Comment',flex:1,dataIndex:'Comment',renderer:function renderer(val){return AdjustMultilineContent(val);},editor:new Ext.form.field.TextArea({fieldCls:'normalWrapWithImage',width:600,grow:true,listeners:{specialkey:function specialkey(field,e){ColumnTab(e);}}}),summaryType:'count',summaryRenderer:function summaryRenderer(){return'Total:';}},{header:'Quantity',flex:1,dataIndex:'Quantity',align:'right',editor:new Ext.form.field.Text({selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vOpportunityAdditionalChargesGrid,vOpportunityAdditionalChargesEditing,e);ColumnTab(e);}}})},{header:'Price',flex:1,dataIndex:'Amount',align:'right',renderer:function renderer(val){if(HasPriceInfoAccess){if(val!=null){return DEARPriceFormat(val);}else{return'';}}else{return'No access';}},editor:new Ext.form.field.Text({selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vOpportunityAdditionalChargesGrid,vOpportunityAdditionalChargesEditing,e);ColumnTab(e);}}})},{header:'Discount',flex:1,dataIndex:'Discount',align:'right',xtype:'numbercolumn',format:'0',editor:new Ext.form.field.Number({allowBlank:false,hideTrigger:true,decimalPrecision:4,step:0,selectOnFocus:true,listeners:{specialkey:function specialkey(field,e){UpDownArrowGridHandler(vOpportunityAdditionalChargesGrid,vOpportunityAdditionalChargesEditing,e);ColumnTab(e);}}}),renderer:function renderer(val,meta,record){return"".concat(val,"%");}},{header:'Tax rule',flex:2,dataIndex:'TaxRule',editor:new Ext.ux.ComboBox({store:vTenantTaxationRuleStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,displayField:'Description',valueField:'RuleID',selectOnFocus:true,forseSelection:true,matchFieldWidth:false,listConfig:{tpl:tpl_simpleList(),itemSelector:'.x-boundlist-item',width:150,listeners:{beforeshow:function beforeshow(picker){picker.minWidth=picker.up('combobox').getSize().width;}}},listeners:{specialkey:function specialkey(field,e){ColumnTab(e);}}}),renderer:function renderer(val,meta,record){if(!IsEmptyID(val)){var rec=vTenantTaxationRuleStore.getById(val);if(rec!=null){var description=RenderHTMLText(rec.get('Description'));if(window.IsSaleTaxManagementServiceEnabled===true){var toolTipText=Ext.String.format(val===window.SaleTaxManagementRuleID?'Tax will be calculated by {0}.':'This tax has been calculated by {0}: {1}',window.SaleTaxManagementServiceName,description);return"").concat(description,"");}else{return description;}}} return'';}},{header:'Total',flex:1,dataIndex:'Total',align:'right',renderer:function renderer(val,meta,record){if(HasPriceInfoAccess){if(val!=null){return"".concat(DEARMoneyFormat(val),"");}else{return val;}}else{return'No access';}}},window.extExtension.column.getDelete({id:'colDelete_QuoteAdditionalCharges',listeners:{click:function click(grid,td,rowIndex){vOpportunityAdditionalChargesStore.removeAt(rowIndex);Sale_Quote_UpdateTotals();}}})],selModel:{selType:'cellmodel'},renderTo:'divQuoteAdditionalChargesLines',flex:1,plugins:[vOpportunityAdditionalChargesEditing],features:[{ftype:'summary'}]});window.DepositsEditing=Ext.create('Ext.grid.plugin.CellEditing',{clicksToEdit:1,listeners:{beforeedit:function beforeedit(editor,e){if(!HasPriceInfoAccess){return false;} if(StatusTracker.deposits.readOnly){return false;} if(e.field=='CurrencyConversionRate'){var customerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency').toUpperCase();var accountCode=e.record.get('AccountCode');if(Sale_Index_GetBankAccountCurrency(accountCode)==customerCurrency){return false;}}else{var cnt=vSaleTaskCreditStore.getCount();for(var i=0;i").concat(RenderHTMLText(value),"");}else{return RenderHTMLText(value);}}},{header:'Product name',width:250,dataIndex:'Name',sortable:false,menuDisabled:true,renderer:function renderer(value,metaData,record){var error=record.get('NameError');if(error!=null&&error!=''){return"").concat(RenderHTMLText(value),"");}else{return RenderHTMLText(value);}}},{header:'Quantity',width:100,dataIndex:'Quantity',sortable:false,menuDisabled:true,renderer:function renderer(value,metaData,record){var error=record.get('QuantityError');if(error!=null&&error!=''){return"").concat(RenderHTMLText(value),"");}else{return RenderHTMLText(value);}}},{header:'Price',width:100,dataIndex:'Price',sortable:false,menuDisabled:true,renderer:function renderer(value,metaData,record){if(HasPriceInfoAccess){var error=record.get('PriceError');if(error!=null&&error!=''){return"").concat(RenderHTMLText(value),"");}else{return RenderHTMLText(value);}}else{return'No access';}}},{header:'Discount',width:100,dataIndex:'Discount',sortable:false,menuDisabled:true,renderer:function renderer(value,metaData,record){var error=record.get('DiscountError');if(error!=null&&error!=''){return"").concat(RenderHTMLText(value),"");}else{return RenderHTMLText(value);}}}],flex:1,renderTo:'UploadSaleQuoteLinesExceptionsGrid'});var uploader=new Dropzone('#QuoteDropContainer',{paramName:'file',maxFilesize:32,uploadMultiple:false,parallelUploads:1,url:'/Opportunity/UploadOpportunityTemplate',method:'post',dictDefaultMessage:'Click here to upload attachment...',createImageThumbnails:false,clickable:true,acceptedFiles:'.txt,.csv',dictInvalidFileType:'Only .txt and .csv files are supported.',init:function init(){this.hiddenFileInput.removeAttribute('multiple');this.on('complete',function(data){if(data&&data.xhr&&data.xhr.response){if(data.xhr.status===200){Sale_UploadQuoteLines_Completed({result:JSON.parse(data.xhr.response),textStatus:'success'},true);}else{Sale_UploadQuoteLines_Completed({result:JSON.parse(data.xhr.response),textStatus:'success'},false);} $('.dz-complete').remove();dearHelper.blockUI.hide();} this.hiddenFileInput.removeAttribute('multiple');});this.on('error',function(file,message){Dear_Notification_Error(message);this.removeFile(file);dearHelper.blockUI.hide();});}});} function Sale_Quote_ProcessBulkLoad(){vOpportunityLinesStore.removeAll();var a=new Array();QuoteBulkStore.each(function(record){var r=record.copy();r.set('QuoteLineID',guid());var TaxRule=r.get('TaxRule');var rec=vTenantTaxationRuleStore.getById(TaxRule);if(window.IsSaleTaxManagementServiceEnabled===true){r.set('TaxRule',window.SaleTaxManagementRuleID);r.set('TaxPercent',0);}else if(IsEmptyID(TaxRule)||rec==null){r.set('TaxRule',cmbTax.getValue());r.set('TaxPercent',Opportunity_Index_GetOpportunityProperty('TaxPercent'));}else{if(CountrySpecificKey!==''&&typeof Sale_OverrideTaxOnLine!=='undefined'){rec=Sale_OverrideTaxOnLine(rec);r.set('TaxRule',rec.getId());} if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){r.set('TaxPercent',rec.get('EffectivePercentInclusive'));}else{r.set('TaxPercent',rec.get('EffectivePercentExclusive'));}} r.setDirty();a.push(r);});vOpportunityLinesStore.add(a);Sale_Quote_UpdateLinesCompleteGrid();} function Sale_Quote_ShowUploadDialog(){UploadQuoteDialog.modal('show');} function Sale_Quote_Upload(data){Dear_Notification_Info('Uploading the file...');data.submit();} function Sale_UploadQuoteLines_Completed(data,isSuccess){if(isSuccess&&data.textStatus=='success'){if(data.result.ErrorMessage){Dear_Notification_Error(data.result.ErrorMessage);if(data.result.ErrorLines&&data.result.ErrorLines.length>0){Ext.get('UploadQuoteLinesExceptionsContainer').removeCls('hiddenContent');QuoteLinesUploadErrorsStore2.removeAll();QuoteLinesUploadErrorsStore2.loadData(data.result.ErrorLines);}else{Ext.get('UploadQuoteLinesExceptionsContainer').addCls('hiddenContent');}}else{QuoteBulkStore.removeAll();QuoteBulkStore.loadData(data.result.Lines);Sale_Quote_ProcessBulkLoad();UploadQuoteDialog.modal('hide');}}else{var message=Ext.String.format('Server communication error: {0}',data.textStatus);Dear_Notification_Error(message);}} function Sale_Quote_Download(){document.getElementById('OpportunityLines').value=Ext.encode(Ext.pluck(vOpportunityLinesStore.data.items,'data'));document.getElementById('frmDownloadQuote').submit();} function Sale_Quote_UpdateTotals(){if(typeof vOpportunityLinesStore!=='undefined'&&typeof vOpportunityAdditionalChargesStore!=='undefined'){var TaxInclusive=Opportunity_Index_GetOpportunityProperty('TaxInclusive');var Amount=0;var Tax=0;var TotalQuantity=0;vOpportunityLinesStore.each(function(record){Amount+=record.get('Total');Tax+=record.get('Tax');TotalQuantity+=record.get('Quantity');});var QuoteLines_Total=Ext.get('QuoteLines_Total');if(HasPriceInfoAccess){if(QuoteLines_Total!=null){QuoteLines_Total.setHTML(DEARMoneyFormat(DEARRound(Amount,2)));}} Tax=DEARRound(Tax,2);if(TaxInclusive){Amount-=Tax;} var LinesTotal=Amount+Tax;var LinesGoodsTotal=Amount;var LinesTaxTotal=Tax;var QuoteLines_Quantity_Total=Ext.get('QuoteLines_Quantity_Total');if(QuoteLines_Quantity_Total!=null){QuoteLines_Quantity_Total.setHTML(DEARRound(TotalQuantity,4));} var Sale_Quote_GoodsTotal=Ext.get('Sale_Quote_GoodsTotal');var Sale_Quote_TaxTotal=Ext.get('Sale_Quote_TaxTotal');var Sale_Quote_Total=Ext.get('Sale_Quote_Total');if(HasPriceInfoAccess){if(Sale_Quote_GoodsTotal!=null){Sale_Quote_GoodsTotal.setHTML(DEARMoneyFormat(LinesGoodsTotal));} if(Sale_Quote_TaxTotal!=null){Sale_Quote_TaxTotal.setHTML(DEARMoneyFormat(LinesTaxTotal));} if(Sale_Quote_Total!=null){Sale_Quote_Total.setHTML(DEARMoneyFormat(LinesTotal));}}else{Sale_Quote_GoodsTotal.setHTML('No access');Sale_Quote_TaxTotal.setHTML('No access');Sale_Quote_Total.setHTML('No access');} Amount=0;Tax=0;vOpportunityAdditionalChargesStore.each(function(record){Tax+=record.get('Tax');Amount+=record.get('Total');});Tax=DEARRound(Tax,2);if(TaxInclusive){Amount-=Tax;} Amount=DEARRound(Amount,2);var AdditionalChargesLinesGoodsTotal=Amount;var AdditionalChargesLinesTaxTotal=Tax;var AdditionalChargesLinesTotal=Amount+Tax;var Sale_Quote_AdditionalChargesLinesGoodsTotal=Ext.get('Sale_Quote_AdditionalChargesLinesGoodsTotal');var Sale_Quote_AdditionalChargesLinesTaxTotal=Ext.get('Sale_Quote_AdditionalChargesLinesTaxTotal');var Sale_Quote_AdditionalChargesLinesTotal=Ext.get('Sale_Quote_AdditionalChargesLinesTotal');if(HasPriceInfoAccess){if(Sale_Quote_AdditionalChargesLinesGoodsTotal!=null){Sale_Quote_AdditionalChargesLinesGoodsTotal.setHTML(DEARMoneyFormat(AdditionalChargesLinesGoodsTotal));} if(Sale_Quote_AdditionalChargesLinesTaxTotal!=null){Sale_Quote_AdditionalChargesLinesTaxTotal.setHTML(DEARMoneyFormat(AdditionalChargesLinesTaxTotal));} if(Sale_Quote_AdditionalChargesLinesTotal!=null){Sale_Quote_AdditionalChargesLinesTotal.setHTML(DEARMoneyFormat(AdditionalChargesLinesTotal));}}else{Sale_Quote_AdditionalChargesLinesGoodsTotal.setHTML('No access');Sale_Quote_AdditionalChargesLinesTaxTotal.setHTML('No access');Sale_Quote_AdditionalChargesLinesTotal.setHTML('No access');} var TotalGoodsTotal=LinesGoodsTotal+AdditionalChargesLinesGoodsTotal;var TotalTaxTotal=LinesTaxTotal+AdditionalChargesLinesTaxTotal;var TotalCustomerCurrency=LinesTotal+AdditionalChargesLinesTotal;var Sale_Quote_GrandGoodsTotal=Ext.get('Sale_Quote_GrandGoodsTotal');var Sale_Quote_GrandTaxTotal=Ext.get('Sale_Quote_GrandTaxTotal');var Sale_Quote_GrandTotal=Ext.get('Sale_Quote_GrandTotal');if(HasPriceInfoAccess){if(Sale_Quote_GrandGoodsTotal!=null){Sale_Quote_GrandGoodsTotal.setHTML(DEARMoneyFormat(TotalGoodsTotal));} if(Sale_Quote_GrandTaxTotal!=null){Sale_Quote_GrandTaxTotal.setHTML(DEARMoneyFormat(TotalTaxTotal));} if(Sale_Quote_GrandTotal!=null){Sale_Quote_GrandTotal.setHTML(DEARMoneyFormat(TotalCustomerCurrency));}}else{Sale_Quote_GrandGoodsTotal.setHTML('No access');Sale_Quote_GrandTaxTotal.setHTML('No access');Sale_Quote_GrandTotal.setHTML('No access');} var tenantCurrency=Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase();var customerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency').toUpperCase();if(HasPriceInfoAccess){var Sale_Quote_GrandCustomerCurrencyTotalCaption=Ext.get('Sale_Quote_GrandCustomerCurrencyTotalCaption');if(Sale_Quote_GrandCustomerCurrencyTotalCaption!=null&&customerCurrency!=''&&customerCurrency!=null){Sale_Quote_GrandCustomerCurrencyTotalCaption.setHTML(Ext.String.format('({0})',customerCurrency));}} var rate=txtSale_Index_CurrencyConversionRate.getValue();var TotalTenantCurrency=TotalCustomerCurrency*rate;TotalTenantCurrency=DEARRound(TotalTenantCurrency,2);if(tenantCurrency!=''&&customerCurrency!=''&&tenantCurrency!=null&&customerCurrency!=null&&tenantCurrency!=customerCurrency){var Sale_Quote_GrandTenantCurrencyTotalCaption=Ext.get('Sale_Quote_GrandTenantCurrencyTotalCaption');if(Sale_Quote_GrandTenantCurrencyTotalCaption!=null){Sale_Quote_GrandTenantCurrencyTotalCaption.setHTML(Ext.String.format('({0})',tenantCurrency));} var Sale_Quote_GrandTenantCurrencyTotal=Ext.get('Sale_Quote_GrandTenantCurrencyTotal');if(Sale_Quote_GrandTenantCurrencyTotal!=null){Sale_Quote_GrandTenantCurrencyTotal.setHTML(DEARMoneyFormat(TotalTenantCurrency));} if(Sale_Quote_GrandTenantCurrencyTotalCaption!=null&&Sale_Quote_GrandTenantCurrencyTotalCaption.hasCls('hiddenContent')){Sale_Quote_GrandTenantCurrencyTotalCaption.removeCls('hiddenContent');} if(Sale_Quote_GrandTenantCurrencyTotal!=null&&Sale_Quote_GrandTenantCurrencyTotal.hasCls('hiddenContent')){Sale_Quote_GrandTenantCurrencyTotal.removeCls('hiddenContent');} $('#Sale_Quote_GrandTenantCurrencyTotalBlock').removeClass('hiddenContent');}else{if(Sale_Quote_GrandTenantCurrencyTotalCaption!=null&&!Sale_Quote_GrandTenantCurrencyTotalCaption.hasCls('hiddenContent')){Sale_Quote_GrandTenantCurrencyTotalCaption.addCls('hiddenContent');} if(Sale_Quote_GrandTenantCurrencyTotal!=null&&!Sale_Quote_GrandTenantCurrencyTotal.hasCls('hiddenContent')){Sale_Quote_GrandTenantCurrencyTotal.addCls('hiddenContent');} $('#Sale_Quote_GrandTenantCurrencyTotalBlock').addClass('hiddenContent');}}} function Sale_Quote_UpdateLinesCompleteGrid(){if(typeof vOpportunityLinesStore!=='undefined'){vOpportunityLinesStore.each(UpdateTaxAndTotal);Sale_Quote_UpdateTotals();}} function Sale_Quote_AddQuoteLinesRecord(){if(!StatusTracker.quote.readOnly){var QuoteLineID=guid();var r=Ext.create('vOpportunityLines',{QuoteLineID:QuoteLineID,Quantity:getDefaultQuoteQuantity(),Price:0,LineOrder:0,Discount:Opportunity_Index_GetOpportunityProperty('Discount'),Total:0,CostingMethod:'FIFO',Tax:0,DropShipMode:'N',TaxRule:cmbTax.getValue(),TaxPercent:Opportunity_Index_GetOpportunityProperty('TaxPercent'),ValidationText:'',ValidationState:'Good'});r.setDirty();vOpportunityLinesStore.add(r);vOpportunityLinesEditing.startEdit(r,vOpportunityLinesGrid.columns[1]);}} function Sale_Quote_Apply_FreeShippingDiscount(discountRecord){var discountRecordType=discountRecord.get('Type');var chargeCount=vOpportunityAdditionalChargesStore.getCount();var createDiscount=false;var discountTitle='';var discountSubTitle='';var parentAmount=0;for(var i=0;i=0){continue;} if(parentDescription.indexOf('Shipping')>=0){discountTitle=discountRecordType.concat(' ',parentDescription);discountSubTitle=discountRecordType.concat(' ',parentComment);parentAmount=charge.get('Amount');createDiscount=true;for(var j=0;j0){description=inputDescription;} var comment='';if(inputComment&&inputComment.length>0){comment=inputComment;} var amount=0;if(!isNaN(parseFloat(inputAmount))){amount=inputAmount;} if(!StatusTracker.quote.readOnly){var record=null;var _TaxPercent=0;var TaxRule=cmbTax.getValue();var QuoteCostID=guid();if(TaxRule!=null&&TaxRule!=''){var recTaxRule=cmbTax.findRecordByValue(TaxRule);if(recTaxRule!=null){if(Opportunity_Index_GetOpportunityProperty('TaxInclusive')){_TaxPercent=recTaxRule.get('EffectivePercentInclusive');}else{_TaxPercent=recTaxRule.get('EffectivePercentExclusive');} TaxRule=recTaxRule.getId();} record=Ext.create('vOpportunityAdditionalCharges',{QuoteCostID:QuoteCostID,Description:description,TaxRule:TaxRule,Quantity:1,Amount:amount,Discount:Opportunity_Index_GetOpportunityProperty('Discount'),TaxPercent:_TaxPercent,Total:0,Tax:0,LineOrder:0,ValidationText:'',ValidationState:'Good',Comment:comment});}else{record=Ext.create('vOpportunityAdditionalCharges',{QuoteCostID:QuoteCostID,Description:description,Quantity:1,Amount:amount,Discount:Opportunity_Index_GetOpportunityProperty('Discount'),TaxPercent:0,Total:0,Tax:0,LineOrder:0,ValidationText:'',ValidationState:'Good',Comment:comment});} record.setDirty();vOpportunityAdditionalChargesStore.add(record);if(amount===0){vOpportunityAdditionalChargesEditing.startEdit(record,vOpportunityAdditionalChargesGrid.columns[1]);} if(record){UpdateAdditionalTaxAndTotal(record);Sale_Quote_UpdateTotals();}}} function Sale_Quote_AddDepositsRecord(){if(!StatusTracker.deposits.readOnly){if(AccountCustomerCreditStore.getCount()>0){var IsCancelled=StatusTracker.isCancelled;var IsSaved=!IsEmptyID(Opportunity_Index_GetOpportunityProperty('OpportunityID'));var val=Opportunity_Index_GetOpportunityProperty('CustomerID');var customerAssigned=!(typeof val==='undefined'||val===null||val==='');if(!customerAssigned){Dear_Notification_Warning('You must select a customer.');return;} if(IsCancelled||!IsSaved){Dear_Notification_Warning('Sale task must be saved before adding a customer credit.');return;}else{Sale_NewDeposit_Show(Opportunity_Index_GetOpportunityProperty('CustomerCurrency'),false);}}else{Dear_Notification_Warning('Please specify a customer credit account in your account mapping before saving the changes.');}}} function Sale_Quote_PrepareForSave(){if(typeof vOpportunityLinesStore==='undefined'||vOpportunityLinesStore===null){return;} if(typeof vOpportunityAdditionalChargesStore==='undefined'||vOpportunityAdditionalChargesStore===null){return;} vOpportunityLinesStore.suspendEvents();vOpportunityAdditionalChargesStore.suspendEvents();var quoteDirty=IsStoreDirty(vOpportunityLinesStore);var allCount=vOpportunityLinesStore.getCount();for(var i=allCount-1;i>=0;i--){var qLine=vOpportunityLinesStore.getAt(i);if(IsEmptyID(qLine.get('ProductID'))&&qLine.get('Price')===0&&qLine.get('Quantity')===0&&qLine.get('Tax')===0&&qLine.get('Total')===0){vOpportunityLinesStore.removeAt(i);}} if(!quoteDirty){vOpportunityLinesStore.commitChanges();} allCount=vOpportunityAdditionalChargesStore.getCount();var dirty=IsStoreDirty(vOpportunityAdditionalChargesStore);for(var i=allCount-1;i>=0;i--){var iLine=vOpportunityAdditionalChargesStore.getAt(i);if(iLine.get('Description')===''&&iLine.get('Amount')===0&&iLine.get('Quantity')===0&&iLine.get('Tax')===0&&iLine.get('Total')===0){vOpportunityAdditionalChargesStore.removeAt(i);}} if(!dirty){vOpportunityAdditionalChargesStore.commitChanges();} allCount=vOpportunityLinesStore.getCount();for(var i=0;i
  • {[Ext.String.htmlEncode(values.Name)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewCustomer();},blur:function blur(element,forceSelection){HideComboInputElement(element,forceSelection);if(IsEmptyID(Opportunity_Index_GetOpportunityProperty('OpportunityID'))){Ext.get('formCaption').setHTML('New opportunity');}else{var _cmbCustomer$getValue;var TrancatedCustomerName=(_cmbCustomer$getValue=cmbCustomer.getValue())!==null&&_cmbCustomer$getValue!==void 0?_cmbCustomer$getValue:'';if(TrancatedCustomerName.length>70){TrancatedCustomerName="".concat(TrancatedCustomerName.substring(0,60),"...");} Ext.get('formCaption').setHTML(Ext.String.format('Opportunity #{0} for {1}',Ext.String.htmlEncode(Opportunity_Index_GetOpportunityProperty('OpportunityNumber')),Ext.String.htmlEncode(TrancatedCustomerName)));}},focus:ShowInputElement,beforequery:function beforequery(queryEvent,eOpts){queryEvent.query=window.vOpportunity_CustomerStoreQuery;},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.vOpportunity_CustomerStoreQuery=Me.getRawValue();}},change:Opportunity_Customer_ChangeEvent,select:Opportunity_CustomerCombo_SelectEvent}});window.vOpportunity_ShipAnotherCustomerStore=Ext.create('Ext.data.JsonStore',{model:'vOpportunity_Customer',proxy:{type:'rest',url:'/api/Opportunity_Index_vOpportunity_Customer',reader:{type:'json'},listeners:{exception:Sale_Index_HandleLoadException}}});vOpportunity_ShipAnotherCustomerStore.getProxy().extraParams={lang:currentUILang,CountrySpecificKey:CountrySpecificKey};window.cmbShipAnotherCustomer=Ext.create('Ext.ux.ComboBox',{store:vOpportunity_ShipAnotherCustomerStore,queryMode:'remote',typeAhead:true,queryParam:'Name',minChars:0,triggerAction:'query',inputId:'cmbShipAnotherCustomer',selectOnTab:true,displayField:'Name',valueField:'Name',renderTo:'Sale_Index_Ship_Another_Customer',selectOnFocus:true,forseSelection:true,emptyText:'type to search...',enableKeyEvents:true,listeners:{blur:function blur(element,forceSelection){window.vOpportunity_ShipAnotherCustomerStoreQuery=element.getRawValue();HideComboInputElement(element,forceSelection);window.cmbShipAnotherCustomer.setRawValue(window.vOpportunity_ShipAnotherCustomerStoreQuery);},focus:ShowInputElement,beforequery:function beforequery(queryEvent,eOpts){if(window.vOpportunity_ShipAnotherCustomerStoreQuery){queryEvent.query=window.vOpportunity_ShipAnotherCustomerStoreQuery;}},keyup:function keyup(Me,e,eOpts){if(!e.isNavKeyPress()&&!e.isSpecialKey()||e.getKey()==e.BACKSPACE){window.vOpportunity_ShipAnotherCustomerStoreQuery=Me.getRawValue();}},change:function change(field,newValue){var searchedIndex=vOpportunity_ShipAnotherCustomerStore.find('Name',newValue);var selected=null;if(searchedIndex!=-1){selected=vOpportunity_ShipAnotherCustomerStore.getAt(searchedIndex);} if(selected!=null){cmbShippingAddressLine1.setValue(null);txtShippingAddressLine2.setValue(null);Opportunity_Index_SetOpportunityProperty('ShipAddressID',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);txtShipToContact.setValue(null);txtShipToCompany.setValue(null);vOpportunity_ShipAnotherCustomerAddressStore.removeAll(true);}else{vOpportunity_ShipAnotherCustomerAddressStore.removeAll(true);}},select:function select(field){var newValue=cmbShipAnotherCustomer.getValue();var searchedIndex=vOpportunity_ShipAnotherCustomerStore.find('Name',newValue);var selected=null;if(searchedIndex!=-1){selected=vOpportunity_ShipAnotherCustomerStore.getAt(searchedIndex);} if(selected!=null){cmbShippingAddressLine1.setValue(null);txtShippingAddressLine2.setValue(null);Opportunity_Index_SetOpportunityProperty('ShipAddressID',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);vOpportunity_ShipAnotherCustomerAddressStore.removeAll(true);if(!IsEmptyID(selected.getId())){vOpportunity_ShipAnotherCustomerAddressStore.getProxy().extraParams={CustomerID:selected.getId()};vOpportunity_ShipAnotherCustomerAddressStore.load();}}else{vOpportunity_ShipAnotherCustomerAddressStore.removeAll(true);Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);txtShipToContact.setValue(null);txtShipToCompany.setValue(null);}}}});window.cmbShipAnotherAddressLine1=Ext.create('Ext.ux.ComboBox',{store:vOpportunity_ShipAnotherCustomerAddressStore,queryMode:'local',triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Line1',forceSelection:false,valueField:'AddressID',renderTo:'Sale_Index_SippingAnotherAddressLine1',emptyText:'choose...',selectOnFocus:true,inputId:'cmbShippingAnotherAddressLine1',listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Line1)]}
    {[Ext.String.htmlEncode(values.Line2)]}
',itemSelector:'li.x-boundlist-item'},listeners:{select:function select(field,records){if(records.length==1){dearHelper.control.setValue(txtSale_EditAddress_Line1,records[0].get('AddressLine1'));dearHelper.control.setValue(txtSale_EditAddress_Line2,records[0].get('AddressLine2'));dearHelper.control.setValue(txtSale_EditAddress_CitySuburb,records[0].get('AddressCitySuburb'));dearHelper.control.setValue(txtSale_EditAddress_StateProvince,records[0].get('AddressStateProvince'));dearHelper.control.setValue(txtSale_EditAddress_ZipPostCode,records[0].get('AddressZipPostCode'));dearHelper.control.setValue(cmbSale_EditAddress_Country,records[0].get('AddressCountry'));}},change:function change(field,newValue){var recordIndex=vOpportunity_ShipAnotherCustomerAddressStore.find('AddressID',newValue);var record=vOpportunity_ShipAnotherCustomerAddressStore.getAt(recordIndex);if(record!=null){dearHelper.control.setValue(txtSale_EditAddress_Line1,record.get('AddressLine1'));dearHelper.control.setValue(txtSale_EditAddress_Line2,record.get('AddressLine2'));dearHelper.control.setValue(txtSale_EditAddress_CitySuburb,record.get('AddressCitySuburb'));dearHelper.control.setValue(txtSale_EditAddress_StateProvince,record.get('AddressStateProvince'));dearHelper.control.setValue(txtSale_EditAddress_ZipPostCode,record.get('AddressZipPostCode'));dearHelper.control.setValue(cmbSale_EditAddress_Country,record.get('AddressCountry'));}},blur:HideComboInputElement,focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.cmbContact=Ext.create('Ext.ux.ComboBoxAdd',{store:vOpportunity_CustomerContactStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,inputId:'cmbContact',displayField:'Name',valueField:'Name',renderTo:'Sale_Index_Contact',emptyText:'choose...',selectOnFocus:true,tabIndex:3,listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Name)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewCustomerContact();},select:function select(combo,records){if(records.length==1){txtPhone.setValue(records[0].get('Phone'));txtEmail.setValue(records[0].get('Email'));if(chkHeaderShipToOther.getValue()==false){txtShipToContact.setValue(records[0].get('Name'));}}},blur:HideComboInputElement,focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.txtPhone=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_Phone',emptyText:'write...',inputId:'txtPhone',selectOnFocus:true,tabIndex:5});window.txtEmail=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_Email',emptyText:'write...',inputId:'txtEmail',selectOnFocus:true,tabIndex:7});window.cmbBillingAddressLine1=Ext.create('Ext.ux.ComboBoxAdd',{store:vOpportunity_CustomerAddressStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Line1',valueField:'Line1',renderTo:'Sale_Index_BillingAddressLine1',emptyText:'Address',selectOnFocus:true,tabIndex:8,inputId:'cmbBillingAddressLine1',listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Line1)]}
    {[Ext.String.htmlEncode(values.Line2)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewBillingAddress();},select:function select(combo,records){if(records.length==1){txtBillingAddressLine2.setValue(records[0].get('Line2'));}},blur:HideComboInputElement,focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.txtBillingAddressLine2=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_BillingAddressLine2',emptyText:'City, state, country, zip',selectOnFocus:true,tabIndex:10,inputId:'txtBillingAddressLine2'});window.cmbTax=Ext.create('Ext.ux.ComboBox',{store:vTenantTaxationRuleStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Description',valueField:'RuleID',renderTo:'Sale_Index_Tax',emptyText:'choose...',selectOnFocus:true,tabIndex:17,forceSelection:true,inputId:'cmbTax',listeners:{change:function change(combo,taxID){if(!FirstLoad){var record=vTenantTaxationRuleStore.getById(taxID);if(record!==null){Opportunity_Index_SetOpportunityProperty('TaxPercent',record.get('EffectivePercent'));chkSale_Index_Tax_Inclusive.setValue(record.get('Inclusive'));}}},blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.chkSale_Index_Tax_Inclusive=Ext.create('Ext.form.field.Checkbox',{renderTo:'Sale_Index_Tax_Inclusive',cls:'x-form-type-checkbox',inputId:'chkSale_Index_Tax_Inclusive',tabIndex:18,listeners:{change:function change(me,newValue){Sale_Index_UpdateTaxInclusive(newValue);}}});window.cmbPriceTier=Ext.create('Ext.ux.ComboBox',{store:vSalesPriceTiersStore,queryMode:'local',editable:false,triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Name',valueField:'Code',renderTo:'Sale_Index_PriceTier',emptyText:'choose...',tabIndex:11,forceSelection:true,inputId:'cmbPriceTier',listeners:{change:function change(Me,newValue){Sale_Index_LoadPrices(newValue);},blur:HideComboInputElement,focus:ShowInputElement}});window.cmbTerms=Ext.create('Ext.ux.ComboBoxAdd',{store:vTenantPaymentTermStore,queryMode:'local',typeAhead:true,inputId:'cmbTerms',triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Name',valueField:'Name',renderTo:'Sale_Index_Terms',emptyText:'choose...',selectOnFocus:true,tabIndex:12,forceSelection:true,listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Name)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewTerm();},select:function select(combo,records){if(records.length==1){Opportunity_Index_SetOpportunityProperty('TermDays',records[0].get('Days'));Opportunity_Index_SetOpportunityProperty('TermMethod',records[0].get('Method'));Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',records[0].get('DueNextMonth'));}},blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.txtCustomerReference=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_CustomerReference',selectOnFocus:true,tabIndex:7,inputId:'cmbCustomerReference'});window.txtShipToContact=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_ShipToContact',selectOnFocus:true,tabIndex:24,inputId:'cmbShipToContact'});window.txtShipToCompany=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_ShipToCompany',selectOnFocus:true,tabIndex:23,inputId:'cmbShipToCompany'});window.cmbSalesRepresentative=Ext.create('Ext.ux.ComboBoxAdd',{store:vTenantContactsStore,queryMode:'local',typeAhead:true,inputId:'cmbSalesRepresentative',triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Name',valueField:'Name',renderTo:'Sale_Index_SalesRepresentative',emptyText:'choose...',selectOnFocus:true,tabIndex:14,listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Name)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewContact();},blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.cmbLocation=Ext.create('Ext.ux.ComboBox',{store:vTenantLocationNoneFixedAssetStore,queryMode:'local',typeAhead:true,triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Description',valueField:'LocationID',tabIndex:21,renderTo:'Sale_Index_Location',emptyText:'choose...',selectOnFocus:true,inputId:'cmbLocation',listeners:{select:function select(){if(ProductStore.getCount()>0){ProductStore.removeAll();ProductStore.getProxy().extraParams={lang:currentUILang,TaskLocationID:cmbLocation.getValue(),Name:ProductStoreQuery,currencyRate:txtSale_Index_CurrencyConversionRate.getValue(),customerID:Opportunity_Index_GetOpportunityProperty('CustomerID')};ProductStore.load();}},blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;},change:function change(field,newValue){var searchedIndex=vTenantLocationNoneFixedAssetStore.findBy(function(record){return record.data.LocationID===newValue;});var selected=null;if(searchedIndex!=-1){selected=vTenantLocationNoneFixedAssetStore.getAt(searchedIndex);} if(selected!=null){QuickLinks.Tooltips.changeLocation(selected.getId(),selected.get('Description'));}else{QuickLinks.Tooltips.changeLocation(null,null);}}}});window.cmbDefaultAccount=new Ext.ux.ComboBox({store:vChartOfAccountsLinesStore,queryMode:'local',typeAhead:true,minChars:0,triggerAction:'all',selectOnTab:true,displayField:'DisplayName',valueField:'Code',inputId:'cmbDefaultAccount',renderTo:'tdSale_Index_DefaultAccount',emptyText:'choose...',tabIndex:16,selectOnFocus:true,forseSelection:true,listConfig:{cls:'nowrap',minWidth:250},listeners:{blur:function blur(Me){HideComboInputElement(Me,true);},focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.txtSale_Index_CurrencyConversionRate=Ext.create('Ext.ux.NumericFieldWithAction',{inputId:'Sale_Index_CurrencyConversionRate',renderTo:'tdSale_Index_CurrencyConversionRate',selectOnFocus:true,hidable:true,decimalPrecision:5,hideTrigger:true,step:0,currencySymbol:null,minValue:0.00001,alwaysDisplayDecimals:true,value:1,tabIndex:17,buttonIconCls:'icon19-sync',buttonHint:'Get rate',enableKeyEvents:true,listeners:{change:function change(){if(!FirstLoad&&typeof vSalePaymentLinesStore!=='undefined'){var customerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency').toUpperCase();var baseCurrency=Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase();vSalePaymentLinesStore.each(function(rec){if(Sale_Index_GetBankAccountCurrency(rec.get('AccountCode'))==customerCurrency){if(baseCurrency==customerCurrency){rec.set('CurrencyConversionRate',1);}else{rec.set('CurrencyConversionRate',txtSale_Index_CurrencyConversionRate.getValue());}}});vSaleCreditNotePaymentLinesStore.each(function(rec){if(Sale_Index_GetBankAccountCurrency(rec.get('AccountCode'))==customerCurrency){if(baseCurrency==customerCurrency){rec.set('CurrencyConversionRate',1);}else{rec.set('CurrencyConversionRate',txtSale_Index_CurrencyConversionRate.getValue());}}});Sale_Quote_UpdateTotals();Sale_Order_UpdateTotals();Sale_Invoice_UpdateTotals();Sale_CreditNote_UpdateTotals();Sale_Quote_ApplyDiscounts(null,null,true);}},customAction:function customAction(){Sale_Index_GetRate();}}});window.dtDate=Ext.create('Ext.form.field.Date',{renderTo:'Sale_Index_Date',emptyText:'choose...',defaultType:'datefield',inputId:'dtDate',altFormats:dearAltFormats,format:UserDateFormat,tabIndex:22,selectOnFocus:true,listeners:{blur:HideDateInputElement,focus:ShowInputElement}});window.cmbShippingAddressLine1=Ext.create('Ext.ux.ComboBoxAdd',{store:vOpportunity_CustomerAddressStore,queryMode:'local',triggerAction:'all',selectOnTab:true,lazyRender:true,displayField:'Line1',forceSelection:false,valueField:'Line1',renderTo:'Sale_Index_SippingAddressLine1',emptyText:'choose...',selectOnFocus:true,tabIndex:26,inputId:'cmbShippingAddressLine1',listConfig:{tpl:'
  • {[Ext.String.htmlEncode(values.Line1)]}
    {[Ext.String.htmlEncode(values.Line2)]}
',itemSelector:'li.x-boundlist-item'},listeners:{add:function add(){Sale_Index_NewShippingAddress();},select:function select(combo,records){if(records.length==1){txtShippingAddressLine2.setValue(records[0].get('Line2'));Opportunity_Index_SetOpportunityProperty('ShipAddressID',records[0].get('AddressID'));Opportunity_Index_SetOpportunityProperty('ShipToAddress1',records[0].get('AddressLine1'));Opportunity_Index_SetOpportunityProperty('ShipToAddress2',records[0].get('AddressLine2'));Opportunity_Index_SetOpportunityProperty('ShipToCity',records[0].get('AddressCitySuburb'));Opportunity_Index_SetOpportunityProperty('ShipToState',records[0].get('AddressStateProvince'));Opportunity_Index_SetOpportunityProperty('ShipToCountry',records[0].get('AddressCountry'));Opportunity_Index_SetOpportunityProperty('ShipToPostCode',records[0].get('AddressZipPostCode'));}},change:function change(me,newValue){if(newValue&&!FirstLoad){var addr=vOpportunity_CustomerAddressStore.findRecord('AddressLine1',newValue);if(!addr){addr=vOpportunity_CustomerAddressStore.findRecord('Line1',newValue);} var code=addr?addr.get('TaxExemptionReasonCode'):null;CommonSale.Avalara.selectValue(code);}},blur:HideComboInputElement,focus:ShowInputElement,beforequery:function beforequery(qe){qe.query=new RegExp(qe.query,'i');qe.forceAll=true;}}});window.txtShippingAddressLine2=Ext.create('Ext.form.field.Text',{renderTo:'Sale_Index_SippingAddressLine2',emptyText:'choose...',selectOnFocus:true,tabIndex:27,inputId:'txtShippingAddressLine2'});window.chkHeaderShipToOther=Ext.create('Ext.form.field.Checkbox',{renderTo:'Sale_Index_ShipToOther',tabIndex:25,inputId:'chkHeaderShipToOther',cls:'x-form-type-checkbox',listeners:{change:function change(me,newValue){var masterTask=OpportunityUpdated.getAt(0);masterTask.set('ShipToOther',newValue);if(newValue){if(!window.fromLoad){Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);txtShipToContact.setValue(null);txtShipToCompany.setValue(null);} $('#Sale_Index_CustomerAddress').hide();$('#Sale_Index_RecepientAddress').show();$('#Sale_Index_RecepientAddress_Button').show();}else{$('#Sale_Index_CustomerAddress').show();$('#Sale_Index_RecepientAddress').hide();$('#Sale_Index_RecepientAddress_Button').hide();var shipAddressID=masterTask.get('ShipAddressID');if(shipAddressID!=null){var addressRec=vOpportunity_CustomerAddressStore.getById(shipAddressID);if(addressRec!=null){cmbShippingAddressLine1.setValue(addressRec.get('Line1'));txtShippingAddressLine2.setValue(addressRec.get('Line2'));txtShipToCompany.setValue(cmbCustomer.getValue());txtShipToContact.setValue(cmbContact.getValue());Opportunity_Index_SetOpportunityProperty('ShipToAddress1',addressRec.get('AddressLine1'));Opportunity_Index_SetOpportunityProperty('ShipToAddress2',addressRec.get('AddressLine2'));Opportunity_Index_SetOpportunityProperty('ShipToCity',addressRec.get('AddressCitySuburb'));Opportunity_Index_SetOpportunityProperty('ShipToState',addressRec.get('AddressStateProvince'));Opportunity_Index_SetOpportunityProperty('ShipToCountry',addressRec.get('AddressCountry'));Opportunity_Index_SetOpportunityProperty('ShipToPostCode',addressRec.get('AddressZipPostCode'));}}} Sale_Index_UpdateOtherAddress();}}});window.textHeaderShipToAddress=dearHelper.control.init('#tdSale_Index_ShipToAddress',{textAutoHeight:true});$('#Sale_Index_EditOtherAddress').click(Sale_Index_EditOtherAddress);window.txtCarrierService=$('#Sale_Index_ShippingCarrierService');$('#Sale_Index_ShippingCarrierServiceLookup').click(Sale_Index_LookupCarrier);window.CarrierLookupDialog=$('#Sale_LookupCourierDialog_Content');window.txtOpportunityComment=dearHelper.control.init('#divStickyNote',{tabIndex:32,textAutoHeight:true});$('#taskHeaderCollapse').click(function(){setTimeout(function(){Sale_Index_UpdateControlSizes();dearHelper.control.updateAutosize();},200);});} function Sale_Index_UpdateTaxInclusive(NewInclusive){var OldInclusive=Opportunity_Index_GetOpportunityProperty('TaxInclusive');if(NewInclusive!=OldInclusive){Opportunity_Index_SetOpportunityProperty('TaxInclusive',NewInclusive);if(typeof vOpportunityLinesStore!=='undefined'&&typeof vOpportunityAdditionalChargesStore!=='undefined'){vOpportunityLinesStore.each(function(record){var rule=vTenantTaxationRuleStore.getById(record.get('TaxRule'));if(rule!=null){if(NewInclusive){record.set('TaxPercent',rule.get('EffectivePercentInclusive'));}else{record.set('TaxPercent',rule.get('EffectivePercentExclusive'));} UpdateTaxAndTotal(record);}});vOpportunityAdditionalChargesStore.each(function(record){var rule=vTenantTaxationRuleStore.getById(record.get('TaxRule'));if(rule!=null){if(NewInclusive){record.set('TaxPercent',rule.get('EffectivePercentInclusive'));}else{record.set('TaxPercent',rule.get('EffectivePercentExclusive'));} UpdateAdditionalTaxAndTotal(record);}});Sale_Quote_UpdateTotals();}}} function Opportunity_Index_SetOpportunityProperty(propertyName,value,skipSetDirty){if(OpportunityUpdated.getCount()===1){if(skipSetDirty!==true){OpportunityUpdated.getAt(0).set(propertyName,value);}else{OpportunityUpdated.getAt(0).data[propertyName]=value;}}} function Opportunity_Index_GetOpportunityProperty(propertyName){if(OpportunityUpdated.getCount()==1){return OpportunityUpdated.getAt(0).get(propertyName);} return null;} function Opportunity_Index_GetOriginalOpportunityProperty(propertyName){if(OpportunityOriginal.getCount()==1){return OpportunityOriginal.getAt(0).get(propertyName);} return null;} function Opportunity_Index_ApplyChangesToOpportunity(){if(OpportunityUpdated.getCount()==1){var record=OpportunityUpdated.getAt(0);attributeSetHelper.prepareSave();record.set('CustomerName',cmbCustomer.getValue());record.set('Contact',cmbContact.getValue());record.set('Phone',txtPhone.getValue());record.set('Email',txtEmail.getValue().trim());record.set('BillingAddressLine1',cmbBillingAddressLine1.getValue());record.set('BillingAddressLine2',txtBillingAddressLine2.getValue());if(record.get('Currency')!=null&&record.get('CustomerCurrency')!=null&&record.get('Currency').toUpperCase()!=record.get('CustomerCurrency').toUpperCase()){record.set('CurrencyConversionRate',txtSale_Index_CurrencyConversionRate.getValue());}else{record.set('CurrencyConversionRate',1);} record.set('TaxSchema',cmbTax.getValue());record.set('TaxInclusive',chkSale_Index_Tax_Inclusive.getValue());record.set('PriceTier',cmbPriceTier.getValue());record.set('Terms',cmbTerms.getValue());record.set('CustomerReference',txtCustomerReference.getValue());record.set('ShipToContact',txtShipToContact.getValue());record.set('ShipToCompany',txtShipToCompany.getValue());record.set('SalesRepresentative',cmbSalesRepresentative.getValue());record.set('OpportunityLocation',cmbLocation.getRawValue());record.set('OpportunityLocationID',cmbLocation.getValue());record.set('DefaultAccount',cmbDefaultAccount.getValue());record.set('OpportunityDate',dtDate.getValue());record.set('ShippingAddressLine1',cmbShippingAddressLine1.getValue());record.set('ShippingAddressLine2',txtShippingAddressLine2.getValue());if(record.get('ShipToOther')!==true){var address=vOpportunity_CustomerAddressStore.getById(record.get('ShipAddressID'));if(address!=null){Opportunity_Index_SetOpportunityProperty('ShipToAddress1',address.get('AddressLine1'));Opportunity_Index_SetOpportunityProperty('ShipToAddress2',address.get('AddressLine2'));Opportunity_Index_SetOpportunityProperty('ShipToCity',address.get('AddressCitySuburb'));Opportunity_Index_SetOpportunityProperty('ShipToState',address.get('AddressStateProvince'));Opportunity_Index_SetOpportunityProperty('ShipToCountry',address.get('AddressCountry'));Opportunity_Index_SetOpportunityProperty('ShipToPostCode',address.get('AddressZipPostCode'));}} record.set('OpportunityComment',dearHelper.control.getValue(txtOpportunityComment));record.set('OpportunityMemo',dearHelper.control.getValue(txtOpportunity_Memo));record.set('ShipToOther',chkHeaderShipToOther.getValue());}} function Opportunity_Index_ProcessLoad(){if(OpportunityUpdated.getCount()==1){StatusTracker.isLoading=true;var record=OpportunityUpdated.getAt(0);if(!window.attributeSetHelper.hasInit()){window.attributeSetHelper.init(record,AttributeSetStore.getById(window.CurrentAttributeSet));}else{window.attributeSetHelper.reInit(record);} window.attributeSetHelper.processData();var CustomerName=record.get('CustomerName');if(CustomerName!=null&&CustomerName!=''&&vOpportunity_CustomerStore.find('Name',CustomerName)==-1){var newCustomer=new vOpportunity_Customer({CustomerID:record.get('CustomerID'),Name:CustomerName,Currency:record.get('CustomerCurrency'),Comments:record.get('SaleTaskMemoInternal'),DefaultCarrier:record.get('Carrier'),Discount:record.get('Discount')});vOpportunity_CustomerStore.add(newCustomer);} if(CustomerName!=null&&CustomerName!=''){cmbCustomer.setValue(CustomerName);} cmbContact.setValue(record.get('Contact'));txtPhone.setValue(record.get('Phone'));txtEmail.setValue(record.get('Email'));cmbBillingAddressLine1.setValue(record.get('BillingAddressLine1'));txtBillingAddressLine2.setValue(record.get('BillingAddressLine2'));txtSale_Index_CurrencyConversionRate.setValue(record.get('CurrencyConversionRate'));if(record.get('Currency')==null){record.set('Currency',TenantCurrency);} var count=vTenantTaxationRuleStore.getCount();if(count==1&&IsEmptyID(record.get('TaxSchema'))){var rec=vTenantTaxationRuleStore.getAt(0);if(IsEmptyID(record.get('TaxSchema'))){record.set('TaxPercent',rec.get('EffectivePercent'));record.set('TaxInclusive',rec.get('Inclusive'));} cmbTax.setValue(rec.getId());}else if(!IsEmptyID(record.get('TaxSchema'))){cmbTax.setValue(record.get('TaxSchema'));} chkSale_Index_Tax_Inclusive.setValue(record.get('TaxInclusive'));count=vSalesPriceTiersStore.getCount();if(count==1){var rec=vSalesPriceTiersStore.getAt(0);cmbPriceTier.setValue(rec.getId());}else if(record.get('PriceTier')>0){cmbPriceTier.setValue(record.get('PriceTier'));} var Terms=record.get('Terms');if(!IsEmptyID(Terms)){cmbTerms.setValue(Terms);}else if(vTenantPaymentTermStore.getCount()>0){var termRec=vTenantPaymentTermStore.getAt(0);cmbTerms.setValue(termRec.get('Name'));record.set('TermDays',termRec.get('Days'));record.set('TermMethod',termRec.get('Method'));record.set('TermDueNextMonth',termRec.get('DueNextMonth'));} txtCustomerReference.setValue(record.get('CustomerReference'));txtShipToContact.setValue(record.get('ShipToContact'));txtShipToCompany.setValue(record.get('ShipToCompany'));if(vTenantContactsStore.getCount()==1){var rec=vTenantContactsStore.getAt(0);cmbSalesRepresentative.setValue(rec.get('Name'));}else{cmbSalesRepresentative.setValue(record.get('SalesRepresentative'));} cmbLocation.setValue(record.get('OpportunityLocationID'));cmbLocation.setRawValue(record.get('OpportunityLocation'));var defAcc=record.get('DefaultAccount');if(defAcc!=null&&defAcc!=''){cmbDefaultAccount.setValue(defAcc);} dtDate.setValue(record.get('OpportunityDate'));cmbShippingAddressLine1.setValue(record.get('ShippingAddressLine1'));txtShippingAddressLine2.setValue(record.get('ShippingAddressLine2'));dearHelper.control.setValue(txtOpportunityComment,record.get('OpportunityComment'));dearHelper.control.setValue(txtOpportunity_Memo,record.get('OpportunityMemo'));if(IsEmptyID(record.get('OpportunityID'))){Ext.get('formCaption').setHTML('New opportunity');StatusTracker.setOpportunityStatus(StatusTracker.statuses.draft);Opportunity_Index_UpdateStatus('Draft','draft');}else{if(FirstLoad&&!HeadersVisible){Sale_Index_CollapseToggle();} var TrancatedCustomerName=CustomerName;if(TrancatedCustomerName.length>70){TrancatedCustomerName="".concat(TrancatedCustomerName.substring(0,60),"...");} Ext.get('formCaption').setHTML(Ext.String.format('Opportunity #{0} for {1}',Ext.String.htmlEncode(record.get('OpportunityNumber')),Ext.String.htmlEncode(TrancatedCustomerName)));if(!record.get('OpportunityStatus')){Opportunity_Index_UpdateStatus('Draft','draft');}else{var st=StatusTracker.StatusDetails[record.get('OpportunityStatus')];Opportunity_Index_UpdateStatus(st.title,st.clColor);}} var dispCarServName=record.get('CarrierServiceDisplayName').trim();if(dispCarServName.length<1){dispCarServName="".concat(record.get('CarrierCode')," ").concat(record.get('CarrierServiceCode')).trim();} dearHelper.control.setValue(txtCarrierService,dispCarServName);window.vOpportunityLinesStore=record.vOpportunityLines();vOpportunityLinesGrid.reconfigure(vOpportunityLinesStore);window.vOpportunityAdditionalChargesStore=record.vOpportunityAdditionalCharges();vOpportunityAdditionalChargesGrid.reconfigure(vOpportunityAdditionalChargesStore);IsReadOnly=record.get('OpportunityStatus')!=='DRAFT'&&record.get('OpportunityStatus')!=='IN PROGRESS'&&record.get('OpportunityStatus')>''||window.AddEditPermission!=='Full';StatusTracker.ProcessLoad();if(record.get('OpportunityStatus')==StatusTracker.statuses["void"]||record.get('OpportunityStatus')==StatusTracker.statuses.converted){Sale_Index_ApplyReadOnlyState();} Opportunity_Index_AdjustMainToolbarActions();Sale_Index_UpdateRateConversionLabel();var OpportunityID=record.get('OpportunityID');var divUploadContainer=Ext.get('divUploadContainer');var divAttachments=Ext.get('divAttachments');var divUploadImpossible=Ext.get('divUploadImpossible');if(IsReadOnly){$('#divAttachmentUpload').addClass('hiddenContent');if(divUploadContainer!=null){divUploadContainer.addCls('hiddenContent');} if(divUploadImpossible!=null){divUploadImpossible.addCls('hiddenContent');}}else{$('#divAttachmentUpload').removeClass('hiddenContent');if(IsEmptyID(OpportunityID)){if(divUploadContainer!=null){divUploadContainer.addCls('hiddenContent');} if(divUploadImpossible!=null){divUploadImpossible.removeCls('hiddenContent');}}else{if(divUploadContainer!=null){divUploadContainer.removeCls('hiddenContent');} if(divUploadImpossible!=null){divUploadImpossible.addCls('hiddenContent');}} var IDToUpload=document.getElementById('IDToUpload');if(IDToUpload!=null){IDToUpload.value=OpportunityID;}} AttachmentsStore.getProxy().extraParams={OpportunityID:OpportunityID};StatusTracker.isLoading=false;StatusTracker.updateOpportunityStatus();StatusTracker.header.applyState();Opportunity_Index_SetReadonly_Attribute(IsReadOnly);Sale_Index_UpdateTaxInclusive(record.get('TaxInclusive'));OpportunityUpdated.commitChanges();vOpportunityLinesStore.commitChanges();vOpportunityAdditionalChargesStore.commitChanges();Sale_Index_UpdateOtherAddress(record.get('ShipToOther'),!FirstLoad);window.Tasks_taskListDropDown.load();var countrySpecificData=record.get('CountrySpecificData');if(countrySpecificData!=null&&typeof Sale_LoadCountrySpecificData!=='undefined'){Sale_LoadCountrySpecificData(countrySpecificData);} var invoiceFromNetwork=false;var orderFromNetwork=false;if(invoiceFromNetwork){$('#networkingIconInvoice').removeClass('hiddenContent');}else{$('#networkingIconInvoice').addClass('hiddenContent');} $(document).trigger('resize');}} function Opportunity_Index_UpdateStatus(statusName,statusClass){var statusTitle=$('#Sale_Index_Status');statusTitle.removeClass().addClass("status-wrapper ".concat(statusClass)).html(statusName);} function Sale_Index_UpdateConversionRateInPaymentLine(FromCurrency,ToCurrency,record){var paramsObj=new Object();paramsObj.From=FromCurrency;paramsObj.To=ToCurrency;var date=record.get('DatePaid');if(date!=null){paramsObj.Date=Common_Index_FormatDate(date);} Ext.Ajax.request({url:'/api/GetRate',method:'GET',params:paramsObj,success:function success(response){var rate=parseFloat(response.responseText);record.set('CurrencyConversionRate',rate);}});} function Sale_Index_GetConversionRate(CustomerCurrency,TenantCurrency){if(CustomerCurrency==TenantCurrency){txtSale_Index_CurrencyConversionRate.setValue(1);Sale_Index_UpdateRateConversionLabel();}else{var paramsObj=new Object();paramsObj.From=CustomerCurrency;paramsObj.To=TenantCurrency;Ext.Ajax.request({url:'/api/GetRate',method:'GET',params:paramsObj,success:function success(response){var rate=parseFloat(response.responseText);txtSale_Index_CurrencyConversionRate.setValue(rate);Sale_Index_UpdateRateConversionLabel();},failure:function failure(response){txtSale_Index_CurrencyConversionRate.setValue(1);Sale_Index_UpdateRateConversionLabel();Dear_Notification_Warning('Failed to acquire currency exchange rate. Please provide the rate manually.');}});}} function Sale_Index_UpdateRateConversionLabel(){var CustomerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency').toUpperCase();var TenantCurrency=Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase();var content='';if(CustomerCurrency!=null&&CustomerCurrency!=''&&TenantCurrency!=null&&TenantCurrency!=''){content=Ext.String.format('{0} units per {1}',TenantCurrency,CustomerCurrency);if(CustomerCurrency==TenantCurrency){SetButtonVisible('divRate',false);txtSale_Index_CurrencyConversionRate.setDisabled(true);}else{var lockDate=AccessInfoStore.getAt(0).get('TenantLockDate');SetButtonVisible('divRate',true);StatusTracker.header.applyCurrencyConversionRateState();}}else{SetButtonVisible('divRate',false);content='Rate:';} Ext.get('lblSale_Index_CurrencyConversionRate').setHTML(content);Sale_Quote_UpdateTotals();} function Sale_Index_NewCustomer(){cmbCustomer.collapse();window.NewCustomerOrigin='Main';Sale_NewCustomer_Show();} function Sale_Index_NewContact(){cmbSalesRepresentative.collapse();Sale_NewTenantContact_Show();} function Sale_Index_NewCustomerContact(){cmbContact.collapse();if(!IsEmptyID(Opportunity_Index_GetOpportunityProperty('CustomerID'))||!IsEmptyID(Opportunity_Index_GetOpportunityProperty('LeadID'))){Opportunity_NewContact_Show();}else{Dear_Notification_Warning('In order to complete this action, please create a customer record. The currently provided information is insufficient to complete the action.');}} function Sale_Index_NewTerm(){cmbTerms.collapse();if(Quickbooks){Dear_Notification_Warning("Please add a new term in QuickBooks and click 'Sync now'.");}else{TenantPaymentTerm_NewTerm_Show(Sale_Index_NewTerm_callback);}} function Sale_Index_NewTerm_callback(newTerm){vTenantPaymentTermStore.add(newTerm.copy());cmbTerms.setValue(newTerm.get('Name'));Opportunity_Index_SetOpportunityProperty('TermDays',newTerm.get('Days'));Opportunity_Index_SetOpportunityProperty('TermMethod',newTerm.get('Method'));Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',newTerm.get('DueNextMonth'));cmbTerms.focus();} function Sale_Index_NewBillingAddress(){cmbBillingAddressLine1.collapse();if(!IsEmptyID(Opportunity_Index_GetOpportunityProperty('CustomerID'))||!IsEmptyID(Opportunity_Index_GetOpportunityProperty('LeadID'))){window.NewAddressOrigin='Billing';Opportunity_NewAddress_Show();}else{Dear_Notification_Warning('In order to complete this action, please create a customer record. The currently provided information is insufficient to complete the action.');}} function Sale_Index_NewShippingAddress(){cmbShippingAddressLine1.collapse();if(!IsEmptyID(Opportunity_Index_GetOpportunityProperty('CustomerID'))||!IsEmptyID(Opportunity_Index_GetOpportunityProperty('LeadID'))){window.NewAddressOrigin='Shipping';Opportunity_NewAddress_Show();}else{Dear_Notification_Warning('In order to complete this action, please create a customer record. The currently provided information is insufficient to complete the action.');}} function Sale_LookupCourierDialog_Select(){var selectedFakeID=$('#divLookupCourierDialogGrid_List').val();if(selectedFakeID==null||selectedFakeID==''){Dear_Notification_Error('Please select a carrier/service from the list.');return;} var rec=LookupCarrierStore.getById(selectedFakeID);if(rec!=null){Opportunity_Index_SetOpportunityProperty('CarrierServiceDisplayName',rec.get('DisplayName'));dearHelper.control.setValue(window.txtCarrierService,rec.get('DisplayName'));Opportunity_Index_SetOpportunityProperty('CarrierCode',rec.get('CarrierCode'));Opportunity_Index_SetOpportunityProperty('CarrierServiceCode',rec.get('ServiceCode'));}else{Dear_Notification_Error('Please select a carrier/service from the list.');return;} Sale_LookupCourierDialog_Cancel();} function Sale_Index_AdjustAttributeWidth(attributeCustomField){if(attributeCustomField!=null){var width=$("#".concat(attributeCustomField.container.id)).width();attributeCustomField.setWidth(width);}} function Opportunity_Index_SetReadonlyForAttribute(attributeCustomField){var isReadOnly=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(attributeCustomField!=null){attributeCustomField.setReadOnly(isReadOnly);}} function Sale_Index_TryGetValueFrom(attributeCustomField){if(attributeCustomField!=null){return attributeCustomField.getValue();} return'';} function Sale_Index_TrySetValue(attributeCustomField,value){if(attributeCustomField!=null){if(attributeCustomField.$className=='Ext.form.field.Checkbox'&&value&&value.length>0){value=value.toLowerCase();} attributeCustomField.setValue(value);}} function Sale_Index_GetRate(){var selectedId=Opportunity_Index_GetOpportunityProperty('CustomerID');var selected=vOpportunity_CustomerStore.getById(selectedId);var selectedCustomerCurrency=selected.get('Currency').toUpperCase();Opportunity_Index_SetOpportunityProperty('CustomerCurrency',selectedCustomerCurrency);var tenantCurrency=Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase();if(selectedCustomerCurrency==tenantCurrency){txtSale_Index_CurrencyConversionRate.setValue(1);Sale_Index_UpdateRateConversionLabel();}else{Sale_Index_GetConversionRate(selectedCustomerCurrency,tenantCurrency);}} function Sale_Index_EditOtherAddress(){Sale_EditAddress_Show(OpportunityUpdated.getAt(0));} function Sale_Index_UpdateOtherAddress(fromLoad,skipOrderLoad){var ffTask=OpportunityUpdated.getAt(0);var shipToTenantAndContact=txtShipToCompany.getValue();if(shipToTenantAndContact!=''){shipToTenantAndContact="".concat(shipToTenantAndContact.trim(),", ");} shipToTenantAndContact+=txtShipToContact.getValue();if(shipToTenantAndContact!=null){shipToTenantAndContact=shipToTenantAndContact.replace(' ',' ').trim();shipToTenantAndContact=shipToTenantAndContact.replace(' ',' ').trim();shipToTenantAndContact=shipToTenantAndContact.replace(' ',' ').trim();} var shipToOtherAddress="".concat(ffTask.get('ShipToAddress1')," ").concat(ffTask.get('ShipToAddress2'));if(shipToOtherAddress.trim()!=''){shipToOtherAddress="".concat(shipToOtherAddress.trim(),"\n");} shipToOtherAddress+="".concat(ffTask.get('ShipToCity')," ").concat(ffTask.get('ShipToState')," ").concat(ffTask.get('ShipToPostCode')," ").concat(ffTask.get('ShipToCountry'));if(shipToOtherAddress!=null){shipToOtherAddress=shipToOtherAddress.replace(' ',' ').trim();shipToOtherAddress=shipToOtherAddress.replace(' ',' ').trim();shipToOtherAddress=shipToOtherAddress.replace(' ',' ').trim();} window.fromLoad=fromLoad;chkHeaderShipToOther.setValue(ffTask.get('ShipToOther'));dearHelper.control.setValue(textHeaderShipToAddress,shipToOtherAddress);var differentAddress=ffTask.get('ShipToOther');if(differentAddress){$('.Sale_Index_CustomerAddress').hide();$('#Sale_Index_RecepientAddress').show();$('#Sale_Index_RecepientAddress_Button').show();}else{$('.Sale_Index_CustomerAddress').show();$('#Sale_Index_RecepientAddress').hide();$('#Sale_Index_RecepientAddress_Button').hide();}} function Sale_Index_LookupCarrier(){var jsonData=Sale_Index_GetLookupCarrierPayload();if(LookupCarrierStore.getCount()==0||LookupCarrierStore.proxy.extraParams.jsonData!=jsonData){LookupCarrierStore.getProxy().extraParams={shippingServiceID:window.ShippingLabelServiceID,carrierCode:Opportunity_Index_GetOpportunityProperty('CarrierCode'),serviceCode:Opportunity_Index_GetOpportunityProperty('CarrierServiceCode'),jsonData:jsonData};dearHelper.blockUI.show('Please wait...');LookupCarrierStore.load({callback:function callback(records,operation,success){Sale_LookupcourierDialog_UpdateContent();dearHelper.blockUI.hide();if(success){if(records!=null&&records.length>0){window.CarrierLookupDialog.modal('show');}else{Dear_Notification_WarningNoHide('Carriers not found');}}}});}else{Sale_LookupcourierDialog_UpdateContent();window.CarrierLookupDialog.modal('show');}} function Sale_Index_GetLookupCarrierPayload(){var task=OpportunityUpdated.getAt(0);var storeToWork=task.vSaleOrderLinesStore;if(!StatusTracker.quote.IsCompleted()){storeToWork=task.vSaleQuoteLinesStore;} var items=[];if(storeToWork!=null){storeToWork.each(function(record){if(record.get('ProductID')!==''){items.push({ProductID:record.get('ProductID'),Quantity:record.get('Quantity'),UnitOfMeasure:record.get('UnitOfMeasure'),Price:record.get('Price'),Tax:record.get('Tax'),Total:record.get('Total')});}});} return JSON.stringify({ShipToCountry:Opportunity_Index_GetOpportunityProperty('ShipToCountry'),ShipToState:Opportunity_Index_GetOpportunityProperty('ShipToState'),ShipToPostCode:Opportunity_Index_GetOpportunityProperty('ShipToPostCode'),ShipToCity:Opportunity_Index_GetOpportunityProperty('ShipToCity'),ShipToAddress1:Opportunity_Index_GetOpportunityProperty('ShipToAddress1'),ShipToAddress2:Opportunity_Index_GetOpportunityProperty('ShipToAddress2'),CustomerID:Opportunity_Index_GetOpportunityProperty('CustomerID'),CustomerCurrency:Opportunity_Index_GetOpportunityProperty('CustomerCurrency'),TaxInclusive:Opportunity_Index_GetOpportunityProperty('TaxInclusive'),TaxSchema:cmbTax.getValue(),LocationID:cmbLocation.getValue(),Items:items});} function Sale_LookupcourierDialog_UpdateContent(){$('#divLookupCourierDialogGrid').html('');var newContent='';$('#divLookupCourierDialogGrid').html(newContent);$('#divLookupCourierDialogGrid_List').selectpicker('refresh');if(selCount==1){setTimeout(function(){$('#divLookupCourierDialogGrid_List').val(selId);},150);}} function Sale_LookupCourierDialog_Cancel(){window.CarrierLookupDialog.modal('hide');} function Opportunity_Customer_ChangeEvent(field,newValue){if(newValue===null||newValue===''){Opportunity_Customer_SelectEvent(field,newValue);}} function Opportunity_CustomerCombo_SelectEvent(model){Opportunity_Customer_SelectEvent(model,model.value);} function Opportunity_Customer_SelectEvent(field){var newValue=cmbCustomer.getValue();var searchedIndex=vOpportunity_CustomerStore.findBy(function(record){return record.data.Name===newValue;});var selected=null;if(searchedIndex!=-1){var selected=vOpportunity_CustomerStore.getAt(searchedIndex);}else{cmbCustomer.setValue(null);} if(selected!=null){Opportunity_Index_SetOpportunityProperty('CustomerName',newValue);if(chkHeaderShipToOther.getValue()==false){txtShipToCompany.setValue(newValue);} if(selected.get('isLead')){Opportunity_Index_SetOpportunityProperty('CustomerID',null);Opportunity_Index_SetOpportunityProperty('LeadID',selected.getId());}else{Opportunity_Index_SetOpportunityProperty('CustomerID',selected.getId());Opportunity_Index_SetOpportunityProperty('LeadID',null);} var customerCarrierDefault=null;var customerCarrierDefaultDesc='';if(selected.get('DefaultCarrier')!=null){customerCarrierDefault=vTenantCarrierStore.getById(selected.get('DefaultCarrier'));if(customerCarrierDefault!=null){customerCarrierDefaultDesc=customerCarrierDefault.get('Description');}} Opportunity_Index_SetOpportunityProperty('CarrierServiceDisplayName',customerCarrierDefaultDesc);dearHelper.control.setValue(window.txtCarrierService,customerCarrierDefaultDesc);Opportunity_Index_SetOpportunityProperty('CarrierCode',null);Opportunity_Index_SetOpportunityProperty('CarrierServiceCode',null);var beforeChangeCustomerCurrency=Opportunity_Index_GetOpportunityProperty('CustomerCurrency');if(beforeChangeCustomerCurrency==null){beforeChangeCustomerCurrency='';} beforeChangeCustomerCurrency=beforeChangeCustomerCurrency.toUpperCase();var selectedCustomerCurrency=selected.get('Currency').toUpperCase();Opportunity_Index_SetOpportunityProperty('CustomerCurrency',selectedCustomerCurrency);if(beforeChangeCustomerCurrency!=selectedCustomerCurrency){var tenantCurrency=Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase();if(selectedCustomerCurrency==tenantCurrency){txtSale_Index_CurrencyConversionRate.setValue(1);Sale_Index_UpdateRateConversionLabel();}else{Sale_Index_GetConversionRate(selectedCustomerCurrency,tenantCurrency);}} if(newValue==Opportunity_Index_GetOriginalOpportunityProperty('CustomerName')){cmbTerms.setValue(Opportunity_Index_GetOriginalOpportunityProperty('Terms'));Opportunity_Index_SetOpportunityProperty('TermDays',Opportunity_Index_GetOriginalOpportunityProperty('TermDays'));Opportunity_Index_SetOpportunityProperty('TermMethod',Opportunity_Index_GetOriginalOpportunityProperty('TermMethod'));Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',Opportunity_Index_GetOriginalOpportunityProperty('TermDueNextMonth'));cmbContact.setValue(Opportunity_Index_GetOriginalOpportunityProperty('Contact'));txtPhone.setValue(Opportunity_Index_GetOriginalOpportunityProperty('Phone'));txtEmail.setValue(Opportunity_Index_GetOriginalOpportunityProperty('Email'));cmbBillingAddressLine1.setValue(Opportunity_Index_GetOriginalOpportunityProperty('BillingAddressLine1'));txtBillingAddressLine2.setValue(Opportunity_Index_GetOriginalOpportunityProperty('BillingAddressLine2'));cmbShippingAddressLine1.setValue(Opportunity_Index_GetOriginalOpportunityProperty('ShippingAddressLine1'));txtShippingAddressLine2.setValue(Opportunity_Index_GetOriginalOpportunityProperty('ShippingAddressLine2'));Opportunity_Index_SetOpportunityProperty('ShipAddressID',Opportunity_Index_GetOriginalOpportunityProperty('ShipAddressID'));Opportunity_Index_SetOpportunityProperty('ShipToAddress1',Opportunity_Index_GetOriginalOpportunityProperty('ShipToAddress1'));Opportunity_Index_SetOpportunityProperty('ShipToAddress2',Opportunity_Index_GetOriginalOpportunityProperty('ShipToAddress2'));Opportunity_Index_SetOpportunityProperty('ShipToCity',Opportunity_Index_GetOriginalOpportunityProperty('ShipToCity'));Opportunity_Index_SetOpportunityProperty('ShipToState',Opportunity_Index_GetOriginalOpportunityProperty('ShipToState'));Opportunity_Index_SetOpportunityProperty('ShipToCountry',Opportunity_Index_GetOriginalOpportunityProperty('ShipToCountry'));Opportunity_Index_SetOpportunityProperty('ShipToPostCode',Opportunity_Index_GetOriginalOpportunityProperty('ShipToPostCode'));if(window.IsSaleTaxManagementServiceEnabled!==true){cmbTax.setValue(Opportunity_Index_GetOriginalOpportunityProperty('TaxSchema'));Opportunity_Index_SetOpportunityProperty('TaxPercent',Opportunity_Index_GetOriginalOpportunityProperty('TaxPercent'));Sale_Index_UpdateTaxInclusive(Opportunity_Index_GetOriginalOpportunityProperty('TaxInclusive'));} var PriceTier=Opportunity_Index_GetOriginalOpportunityProperty('PriceTier');if(PriceTier>0){cmbPriceTier.setValue(PriceTier);} cmbLocation.setValue(Opportunity_Index_GetOriginalOpportunityProperty('OrderLocationID'));var originalDefaultAccount=Opportunity_Index_GetOriginalOpportunityProperty('DefaultAccount');if(originalDefaultAccount!=null&&originalDefaultAccount!=''){cmbDefaultAccount.setValue(originalDefaultAccount);} cmbSalesRepresentative.setValue(Opportunity_Index_GetOriginalOpportunityProperty('SalesRepresentative'));Opportunity_Index_SetOpportunityProperty('Discount',Opportunity_Index_GetOriginalOpportunityProperty('Discount'));dearHelper.control.setValue(txtOpportunityComment,Opportunity_Index_GetOriginalOpportunityProperty('OpportunityComment'));dearHelper.control.setValue(txtOpportunity_Memo,Opportunity_Index_GetOriginalOpportunityProperty('OpportunityMemo'));}else{var selectedCustomerTerms=selected.get('PaymentTerm');if(!IsEmptyID(selectedCustomerTerms)){var defaultPaymentTerm=vTenantPaymentTermStore.getById(selectedCustomerTerms);if(defaultPaymentTerm!=null){cmbTerms.setValue(defaultPaymentTerm.get('Name'));Opportunity_Index_SetOpportunityProperty('TermDays',defaultPaymentTerm.get('Days'));Opportunity_Index_SetOpportunityProperty('TermMethod',defaultPaymentTerm.get('Method'));Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',defaultPaymentTerm.get('DueNextMonth'));}}else if(vTenantPaymentTermStore.getCount()==1){var paymentTerm=vTenantPaymentTermStore.getAt(0);cmbTerms.setValue(paymentTerm.get('Name'));Opportunity_Index_SetOpportunityProperty('TermDays',paymentTerm.get('Days'));Opportunity_Index_SetOpportunityProperty('TermMethod',paymentTerm.get('Method'));Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',paymentTerm.get('DueNextMonth'));}else{cmbTerms.setValue(null);Opportunity_Index_SetOpportunityProperty('TermDays',null);Opportunity_Index_SetOpportunityProperty('TermDueNextMonth',-1);} cmbContact.setValue(null);txtPhone.setValue(null);txtEmail.setValue(null);cmbBillingAddressLine1.setValue(null);txtBillingAddressLine2.setValue(null);cmbShippingAddressLine1.setValue(null);txtShippingAddressLine2.setValue(null);Opportunity_Index_SetOpportunityProperty('ShipAddressID',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);if(window.IsSaleTaxManagementServiceEnabled!==true){var selectedTax=selected.get('TaxRule');if(!IsEmptyID(selectedTax)){var defaultTax=vTenantTaxationRuleStore.getById(selectedTax);cmbTax.setValue(selectedTax);if(defaultTax!=null){Opportunity_Index_SetOpportunityProperty('TaxPercent',defaultTax.get('EffectivePercent'));Sale_Index_UpdateTaxInclusive(defaultTax.get('Inclusive'));}}else if(vTenantTaxationRuleStore.getCount()==1){var defaultTax=vTenantTaxationRuleStore.getAt(0);cmbTax.setValue(defaultTax.getId());Opportunity_Index_SetOpportunityProperty('TaxPercent',defaultTax.get('EffectivePercent'));Sale_Index_UpdateTaxInclusive(defaultTax.get('Inclusive'));}else{cmbTax.setValue(null);Opportunity_Index_SetOpportunityProperty('TaxPercent',0);Sale_Index_UpdateTaxInclusive(false);}} var selectedPriceTier=selected.get('SalePriceTier');if(selectedPriceTier>0){cmbPriceTier.setValue(selectedPriceTier);}else if(vSalesPriceTiersStore.getCount()>0){cmbPriceTier.setValue(vSalesPriceTiersStore.getAt(0).getId());} var selectedLocation=selected.get('DefaultLocation');if(!IsEmptyID(selectedLocation)){var locationRec=vTenantLocationStore.getById(selectedLocation);if(locationRec!=null){cmbLocation.setValue(locationRec.get('LocationID'));}}else if(vTenantLocationStore.getCount()==1){cmbLocation.setValue(vTenantLocationStore.getAt(0).get('LocationID'));}else{cmbLocation.setValue(null);} var selectedAccount=selected.get('AccountCode');if(selectedAccount!=null&&selectedAccount!=''){cmbDefaultAccount.setValue(selectedAccount);}else if(vChartOfAccountsLinesStore.getCount()>0){cmbDefaultAccount.setValue(vChartOfAccountsLinesStore.getAt(0).getId());} var selectedSalesRepresentative=selected.get('DefaultSalesRepresentative');if(!IsEmptyID(selectedSalesRepresentative)){cmbSalesRepresentative.setValue(vTenantContactsStore.getById(selectedSalesRepresentative).get('Name'));}else if(vTenantContactsStore.getCount()==1){cmbSalesRepresentative.setValue(vTenantContactsStore.getAt(0).get('Name'));}else{cmbSalesRepresentative.setValue(null);} dearHelper.control.setValue(txtOpportunityComment,selected.get('Comments'));Opportunity_Index_SetOpportunityProperty('Discount',selected.get('Discount'));if(CountrySpecificKey!=''&&typeof Sale_Customer_Changed!='undefined'){Sale_Customer_Changed(selected);}} vOpportunity_CustomerContactStore.removeAll(true);vOpportunity_CustomerAddressStore.removeAll(true);if(!IsEmptyID(selected.getId())){vOpportunity_CustomerContactStore.getProxy().extraParams={CustomerID:selected.getId(),isLead:selected.get('isLead')};vOpportunity_CustomerContactStore.load();vOpportunity_CustomerAddressStore.getProxy().extraParams={CustomerID:selected.getId(),isLead:selected.get('isLead')};vOpportunity_CustomerAddressStore.load();}}else{vOpportunity_CustomerContactStore.removeAll(true);vOpportunity_CustomerAddressStore.removeAll(true);Opportunity_Index_SetOpportunityProperty('CustomerID',null);Opportunity_Index_SetOpportunityProperty('LeadID',null);Opportunity_Index_SetOpportunityProperty('CreditLimit',0);Opportunity_Index_SetOpportunityProperty('CustomerCurrency',Opportunity_Index_GetOpportunityProperty('Currency').toUpperCase());Opportunity_Index_SetOpportunityProperty('ShipToAddress1',null);Opportunity_Index_SetOpportunityProperty('ShipToAddress2',null);Opportunity_Index_SetOpportunityProperty('ShipToCity',null);Opportunity_Index_SetOpportunityProperty('ShipToState',null);Opportunity_Index_SetOpportunityProperty('ShipToCountry',null);Opportunity_Index_SetOpportunityProperty('ShipToPostCode',null);if(chkHeaderShipToOther.getValue()==false){txtShipToCompany.setValue(null);txtShipToContact.setValue(null);} txtSale_Index_CurrencyConversionRate.setValue(1);Sale_Index_UpdateRateConversionLabel();} window.resetLastQueryQuote=true;window.resetLastQuery=true;Sale_Quote_ApplyDiscounts(null,null,true);} function Sale_Index_SetDefaultLocation(){var customerId=Opportunity_Index_GetOpportunityProperty('CustomerID');var customer=vOpportunity_CustomerStore.getById(customerId);if(customer){var selectedLocation=customer.get('DefaultLocation');if(!IsEmptyID(selectedLocation)){var locationRec=vTenantLocationStore.getById(selectedLocation);if(locationRec!=null){cmbLocation.setValue(locationRec.get('LocationID'));}}else if(vTenantLocationStore.getCount()>0){var defaultLocation=null;vTenantLocationStore.each(function(item){if(item.get('IsDefault')){defaultLocation=item;}});defaultLocation=defaultLocation||vTenantLocationStore.getAt(0);cmbLocation.setValue(defaultLocation.get('LocationID'));}else{cmbLocation.setValue(null);}}else{cmbLocation.setValue(null);}} function Opportunity_Index_StartConvert(){if(PlannedOperation!==''&&PlannedOperation!=='convertStart'){return;} dearSwal({title:'Confirmation',text:'Converting an opportunity to a sale quote is irreversible. Converting will remove the opportunity from this list, and no further opportunity actions can be performed. Actions can be performed on the newly converted sale quote. Do you want to proceed with the conversion?',type:'warning',showCancelButton:true,confirmButtonClass:'btn-danger',confirmButtonText:'Yes',cancelButtonText:'No',closeOnConfirm:true,closeOnCancel:true},function(isConfirm){if(isConfirm){dearHelper.blockUI.show('Please wait...');PlannedOperation='convertStart';Opportunity_Index_Submit();}});} function Opportunity_Index_LeadConvert(){var currentOpp=OpportunityOriginal.getRange()[0].getData(true);if(currentOpp.CustomerID){window.CustomerID4Conversion=currentOpp.CustomerID;Opportunity_Index_Convert();return;} Ext.Ajax.request({url:'/api/Opportunity_Index_vOpportunity_Customer/Customer',method:'GET',params:{name:currentOpp.CustomerName},timeout:2000000,success:function success(response){var rsp=JSON.parse(response.responseText);if(rsp){window.CustomerID4Conversion=rsp;Opportunity_Index_Convert();}else{LeadWrapperStore.getProxy().extraParams={id:currentOpp.LeadID,CountrySpecificKey:CountrySpecificKey};LeadWrapperStore.load();}},failure:function failure(response){dearHelper.blockUI.hide();Dear_Notification_Error(response.responseText);}});} function Opportunity_Index_ConvertFinish(){if(PlannedOperation!==''&&PlannedOperation!=='convertFinish'){return;} dearHelper.blockUI.show('Please wait...');var currentOpp=OpportunityOriginal.getRange()[0].getData(true);$.post('/Opportunity/CloneAttachments',{SaleTaskID:window.ConvertedSaleTaskID,OpportunityID:currentOpp.OpportunityID},function(res){if(res.Status!=='ok'){dearHelper.blockUI.hide();Dear_Notification_Error(res.Message);}else{window.location.href="/Sale#".concat(window.ConvertedSaleTaskID);}}).fail(function(){dearHelper.blockUI.hide();Dear_Notification_Error('Server request error');});} function Opportunity_Index_Convert(){var o=OpportunityOriginal.getRange()[0].getData(true);if(o.vOpportunityAdditionalCharges.length==0&&o.vOpportunityLines.length==0){dearHelper.blockUI.hide();Dear_Notification_Warning('Opportunity is empty.');return;} var additionalCharges=new Array();for(var i=0;i0);SetButtonVisible('divDiscounts_Quote',!StatusTracker.quote.readOnly&&DiscountCount>0);SetButtonVisible('divImport_Quote',!StatusTracker.quote.readOnly);$('#divQuote .btnRemoveCoupon a').toggle(!disabled);vOpportunityLinesGrid.getView().getHeaderCt().child('#colDelete_QuoteLines').setVisible(!StatusTracker.quote.readOnly);SetButtonVisible('divNewAdditionalCostLine_Quote',!StatusTracker.quote.readOnly);vOpportunityAdditionalChargesGrid.getView().getHeaderCt().child('#colDelete_QuoteAdditionalCharges').setVisible(!StatusTracker.quote.readOnly);if(Sale_GetActiveTab()=='tabQuote'){vOpportunityLinesGrid.getView().refresh();vOpportunityAdditionalChargesGrid.getView().refresh();} dearHelper.control.setDisabled(txtOpportunity_Memo,StatusTracker.quote.readOnly);};};function Opportunity_Index_CreateStores(){window.vOpportunity_CustomerStoreQuery='';window.vOpportunity_ShipSAnotherCustomerStoreQuery='';window.FamilyStore=Ext.create('Ext.data.JsonStore',{model:'Family',proxy:{type:'rest',url:'/api/Opportunity_Index_Family',reader:{type:'json'}}});window.SupplierStore=Ext.create('Ext.data.JsonStore',{model:'vSupplier',proxy:{type:'rest',url:'/api/Sale_Index_vSupplier',reader:{type:'json'}}});window.AccountCurrencyStore=Ext.create('Ext.data.JsonStore',{model:'AccountCurrency',proxy:{type:'rest',reader:{type:'json',root:'AccountCurrencies'}}});window.AttributeSetStore=Ext.create('Ext.data.JsonStore',{model:'vTenantAttributeSet',proxy:{type:'rest',reader:{type:'json',root:'vTenantAttributeSets'}}});window.vTenantInventoryCategoryStore=Ext.create('Ext.data.JsonStore',{model:'vTenantInventoryCategory',proxy:{type:'rest',url:'/api/Opportunity_Index_Category',reader:{type:'json'}}});window.QuoteBulkStore=Ext.create('Ext.data.JsonStore',{model:'vOpportunityLines'});window.FamilyStoreQuery='';window.FamilyOptions1Store=Ext.create('Ext.data.JsonStore',{model:'FamilyOption'});window.FamilyOptions2Store=Ext.create('Ext.data.JsonStore',{model:'FamilyOption'});window.FamilyOptions3Store=Ext.create('Ext.data.JsonStore',{model:'FamilyOption'});window.FamilyProductsStore=Ext.create('Ext.data.JsonStore',{model:'FamilyProduct',proxy:{type:'rest',url:'/api/Opportunity_Index_FamilyProducts',reader:{type:'json'},listeners:{exception:function exception(proxy,response,operation){ProcessException(response,operation,function(){});}}},listeners:{load:Sale_Family_ProcessLoad}});window.MethodStore=Ext.create('Ext.data.JsonStore',{model:'vTermsMethod'});MethodStore.add(Ext.create('vTermsMethod',{ID:1,Name:'Number of days'}));MethodStore.add(Ext.create('vTermsMethod',{ID:2,Name:'Day of next month'}));MethodStore.add(Ext.create('vTermsMethod',{ID:3,Name:'Last day of next month'}));MethodStore.add(Ext.create('vTermsMethod',{ID:5,Name:'Days since the end of the month'}));window.FrequencyStore=Ext.create('Ext.data.JsonStore',{model:'RecurringFrequency'});FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Weekly',Name:'Weekly'}));FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Fortnightly',Name:'Fortnightly'}));FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Monthly',Name:'Monthly'}));FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Quarterly',Name:'Quarterly'}));FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Half-Yearly',Name:'Half-yearly'}));FrequencyStore.add(Ext.create('RecurringFrequency',{Value:'Annually',Name:'Annually'}));window.AttachmentsStore=Ext.create('Ext.data.JsonStore',{model:'vOpportunityAttachement',proxy:{type:'rest',url:'/api/Opportunity_Index_vOpportunityAttachement',reader:{type:'json'},writer:{type:'json'},listeners:{exception:Sale_Index_HandleLoadException}},listeners:{load:function load(){if(PrintInProgress){PrintInProgress=false;var task=new Ext.util.DelayedTask(function(){document.getElementById('linkPrint').click();});task.delay(200);}}}});window.vTenantCarrierStore=Ext.create('Ext.data.JsonStore',{model:'vTenantCarrierWithShippingOptions',proxy:{type:'rest',reader:{type:'json',root:'vTenantCarriersWithShippingOptions'}}});window.vTenantContactsStore=Ext.create('Ext.data.JsonStore',{model:'vTenantContact',proxy:{type:'rest',reader:{type:'json',root:'vTenantContacts'}}});window.vOpportunity_CustomerContactStore=Ext.create('Ext.data.JsonStore',{model:'vOpportunity_CustomerContact',proxy:{type:'rest',url:'/api/Opportunity_Index_vOpportunity_CustomerContact',reader:{type:'json'},listeners:{exception:Sale_Index_HandleLoadException}},listeners:{load:function load(){if(cmbCustomer.getValue()!=Opportunity_Index_GetOriginalOpportunityProperty('CustomerName')&&JobID==null){var currentCustomerID=Opportunity_Index_GetOpportunityProperty('CustomerID');var loadedContactsCount=vOpportunity_CustomerContactStore.getCount();if(loadedContactsCount==1){var termRec=vOpportunity_CustomerContactStore.getAt(0);if(termRec.get('CustomerID')==currentCustomerID){cmbContact.setValue(termRec.get('Name'));Opportunity_Index_SetOpportunityProperty('ShipToContact',termRec.get('Name'));txtPhone.setValue(termRec.get('Phone'));txtEmail.setValue(termRec.get('Email'));}}else{for(var i=0;i0){var ssRec=vShippingLabelProvidersStore.getAt(0);window.ShippingLabelServiceID=ssRec.get('ID');window.ShippingLabelServiceSupportsConsolidated=ssRec.get('SupportsConsolidatedShipment');printShippingLabels=ssRec.get('PrintShippingLabels')&&ssRec.get('IsDefault');for(var i=1;i>>((i&0x03)<<3)&0xff;} return _rnds;};} var BufferClass=typeof(Buffer)=='function'?Buffer:Array;var _byteToHex=[];var _hexToByte={};for(var i=0;i<256;i++){_byteToHex[i]=(i+0x100).toString(16).substr(1);_hexToByte[_byteToHex[i]]=i;} function parse(s,buf,offset){var i=(buf&&offset)||0,ii=0;buf=buf||[];s.toLowerCase().replace(/[0-9a-f]{2}/g,function(oct){if(ii<16){buf[i+ii++]=_hexToByte[oct];}});while(ii<16){buf[i+ii++]=0;} return buf;} function unparse(buf,offset){var i=offset||0,bth=_byteToHex;return bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+'-'+ bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]]+ bth[buf[i++]]+bth[buf[i++]];} var _seedBytes=_rng();var _nodeId=[_seedBytes[0]|0x01,_seedBytes[1],_seedBytes[2],_seedBytes[3],_seedBytes[4],_seedBytes[5]];var _clockseq=(_seedBytes[6]<<8|_seedBytes[7])&0x3fff;var _lastMSecs=0,_lastNSecs=0;function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var clockseq=options.clockseq!=null?options.clockseq:_clockseq;var msecs=options.msecs!=null?options.msecs:new Date().getTime();var nsecs=options.nsecs!=null?options.nsecs:_lastNSecs+1;var dt=(msecs-_lastMSecs)+(nsecs-_lastNSecs)/10000;if(dt<0&&options.clockseq==null){clockseq=clockseq+1&0x3fff;} if((dt<0||msecs>_lastMSecs)&&options.nsecs==null){nsecs=0;} if(nsecs>=10000){throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');} _lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=12219292800000;var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;var tmh=(msecs/0x100000000*10000)&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;b[i++]=tmh>>>24&0xf|0x10;b[i++]=tmh>>>16&0xff;b[i++]=clockseq>>>8|0x80;b[i++]=clockseq&0xff;var node=options.node||_nodeId;for(var n=0;n<6;n++){b[i+n]=node[n];} return buf?buf:unparse(b);} function v4(options,buf,offset){var i=buf&&offset||0;if(typeof(options)=='string'){buf=options=='binary'?new BufferClass(16):null;options=null;} options=options||{};var rnds=options.random||(options.rng||_rng)();rnds[6]=(rnds[6]&0x0f)|0x40;rnds[8]=(rnds[8]&0x3f)|0x80;if(buf){for(var ii=0;ii<16;ii++){buf[i+ii]=rnds[ii];}} return buf||unparse(rnds);} var uuid=v4;uuid.v1=v1;uuid.v4=v4;uuid.parse=parse;uuid.unparse=unparse;uuid.BufferClass=BufferClass;if(_global.define&&define.amd){define(function(){return uuid;});}else if(typeof(module)!='undefined'&&module.exports){module.exports=uuid;}else{var _previousRoot=_global.uuid;uuid.noConflict=function(){_global.uuid=_previousRoot;return uuid;};_global.uuid=uuid;}}).call(this);;var taskHelper=taskHelper||{};taskHelper.taskListDropDown=function(selector,options){var _self=this.taskListDropDown;var _container;var _settings={url:'/api/TaskShared_TaskList_vTask',workflowUrl:'/api/TaskShared_Workflow_WorkflowProcess',entityType:'',entityID:'',isChild:false,changed:$.noop};var _tasks;var _isInitialized=false;var _permissions;var _deliveryNoteDialog;var _tplTaskListItem='
'+'
{5} {1}{7}
'+' {2} '+' {3} '+' {4} '+'
';function initialize(selector,options){_container=$(selector);_settings=$.extend(true,{},_settings,options);_deliveryNoteDialog=new TaskDeliveryNotesComponent();if(_container.length==0){throw'Container is not defined.';} if(window.LoadingTaskAccessInfo==true){Task_AddCheckAccessCallback(function(){_init.call(_self);});}else{_init();}} function updateEntityData(options){var _options=$.extend(true,{},options);if(window.LoadingTaskAccessInfo==true){Task_AddCheckAccessCallback(function(){_updateEntityData.call(_self,_options);});}else{_updateEntityData(_options);}} function _updateEntityData(options){if(_isInitialized==true){_settings=$.extend(true,{},_settings,options);if(!IsEmptyID(_settings.entityID)&&_settings.entityType&&_settings.entityType.length>0){_container.removeClass('hiddenContent');load();}else{_container.addClass('hiddenContent');}}} function _init(){if(window.TaskModule_IsEnable==true&&(window.TaskModule_AllTasks==true||window.TaskModule_CanAssignTasks==true||window.TaskModule_CanBeAssigned==true||window.TaskModule_Management==true)){_isInitialized=true;_bindEvents();if(!IsEmptyID(_settings.entityID)&&_settings.entityType&&_settings.entityType.length>0){_container.removeClass('hiddenContent');} if(window.TaskModule_Management==true){$('.btn-new-task',_container).removeClass('hiddenContent');}else{$('.btn-new-task',_container).addClass('hiddenContent');}}else{_container.addClass('hiddenContent');}} function load(){if(_isInitialized==true&&!IsEmptyID(_settings.entityID)&&_settings.entityType&&_settings.entityType.length>0){_container.find('.tasklist-content').empty();dearHelper.control.unblockUI();$(document).on('click.bs.dropdown','.btn-refresh-task, .task-list-notes-btn, #Task_DeliveryNotes',function(e){e.stopPropagation();});var _target=_container.closest('.form-control').find('.dropdown-menu');dearHelper.control.blockUI(_target);Ext.Ajax.request({url:_settings.url,method:'GET',headers:window.TaskClientTimeHeader,params:{entityType:_settings.entityType,entityID:_settings.entityID,isChild:_settings.isChild},success:function success(response){var result=JSON.parse(response.responseText);_tasks=result.tasks;_permissions=result.permissions;var text='';if(_tasks&&_tasks.length>0){text+=_tasks.length;if(_tasks.length==1){text+=' '+'task';}else{text+=' '+'tasks';}}else{text='0 tasks';} $('.tasklist-taskcount',_container).html(text);_buildContent();dearHelper.control.unblockUI(_target);},failure:function failure(response){Dear_Notification_Error('Failed to load tasks.');}});}} function open(){$('ul.dropdown-menu',_container).dropdown('toggle');} function _bindEvents(){$('.btn-new-task',_container).on('click',function(){Task_New({EntityType:_settings.entityType,EntityID:_settings.entityID},{AsignedToControlDisabled:!_permissions.CanAssignTasks,visibility:{entityLink:false}},function(task){load();if(typeof _settings.changed==='function'){_settings.changed();}},function(){load();});});$('.btn-refresh-task',_container).on('click',function(e){e.preventDefault();load();});_container.on('click','.tasklist-item',function(e){var id=$(this).attr('data-id');var _task=_getById(id);if(_task!=null){if(e.target.classList.contains('task-list-notes-btn')){_deliveryNoteDialog.open(_task);}else{taskHelper.taskDialog.open(_task,{AsignedToControlDisabled:!_permissions.CanAssignTasks,visibility:{entityLink:false}},function(task,action){load();if(typeof _settings.changed==='function'){_settings.changed();}},function(){load();});}}else{throw'Task not found.';}});$('#WorkflowModal_selWorkflow').select2({ajax:{url:'/api/TaskShared_Workflow_vWorkflow',dataType:'json',data:function data(params){return{name:params.term||'',page:params.page||1,entityType:window.__taskListDropDown_entitytype};},processResults:function processResults(data,params){params.page=params.page||1;return{results:data.Result,pagination:{more:params.page*150){var content='';for(var i=0;i<_tasks.length;i++){var task=_tasks[i];var isDelivery=task.TaskCategoryName==='Delivery'&&task.IsCategoryPredefined;var startDateStr='';if(task.StartDate!=null){startDateStr=_getDateTime(task.IsAllDay,task.StartDate,task.EndDate);} var taskCategory='';if(task.TaskCategoryName){taskCategory="").concat(task.TaskCategoryName,"");} var completed='';var completedClass='';var overdueClass='';if(task.IsCompleted){completed=" ");completedClass='completed';}else if(Task_IsOverdueTask(task.IsAllDay,moment(task.StartDate).toDate(),moment(task.EndDate).toDate())){overdueClass='overdue';} var notesBtnContent='';var id="".concat(task.TaskID,"_notesBtn");if(isDelivery){notesBtnContent="");} content+=Ext.String.format(_tplTaskListItem,task.TaskID,task.Name,startDateStr,task.UserName?task.UserName:'',taskCategory,completed,"".concat(completedClass," ").concat(overdueClass),notesBtnContent);} $content.html(content);}else{var t='You have no tasks.';$content.html("
".concat(t,"
"));} _updateScroller();} function _getDateTime(isAllDay,startDate,endDate){startDate=moment(startDate);endDate=moment(endDate);var dateStr='';if(isAllDay==false){dateStr=startDate.format(TaskModule_DateTimeFormat);if(startDate.format(TaskModule_DateFormat)==endDate.format(TaskModule_DateFormat)){dateStr+=" - ".concat(endDate.format(TaskModule_TimeFormat));}else{dateStr+=" - ".concat(endDate.format(TaskModule_DateTimeFormat));}}else{dateStr=startDate.format(TaskModule_DateFormat);} return dateStr;} function _getById(id){var task=null;if(_tasks&&_tasks.length>0){for(var i=0;i<_tasks.length;i++){if(_tasks[i].TaskID==id){task=_tasks[i];break;}}} return task;} function _updateScroller($container){var $container=$('.tasklist-content',_container);if($container.data('enscroll')){$container.enscroll('resize');}else{$container.enscroll();}} function _openWorkflowDialog(){$('#WorkflowModal_selWorkflow').empty();window.__taskListDropDown_entitytype=_settings.entityType;$('#WorkflowModal_save').off('click');$('#WorkflowModal_save').on('click',function(){var startDate=tbWorkflowDate.getValue();startDate=moment(startDate).format();data=$('#WorkflowModal_selWorkflow').select2('data');if(!data||data.length==0){Dear_Notification_Error('Workflow is not selected.');}else{var workflowID=data[0].id;_startWorkflow(workflowID,startDate);}});$('#WorkflowModal_startWorflow').modal('show');} function _startWorkflow(workflowID,startDate){dearHelper.blockUI.show();Ext.Ajax.request({url:_settings.workflowUrl,method:'POST',headers:window.TaskClientTimeHeader,params:{EntityID:_settings.entityID,EntityType:_settings.entityType,WorkflowID:workflowID,StartDate:startDate,LinkTo:$('#formCaption').text()},success:function success(response){dearHelper.blockUI.hide();$('#WorkflowModal_startWorflow').modal('hide');Dear_Notification_Success('Workflow successfully started.');load();},failure:function failure(response){ProcessException(response);}});} initialize(selector,options);return{load:load,open:open,updateEntityData:updateEntityData};};;var DFVHandler=DFVHandler||{};DFVHandler=function(){var _cacheResponses={cacheProducts:null,cacheCustomers:null,cacheSuppliers:null};var _fieldsElements={fieldsProducts:[],fieldsCustomers:[],fieldsSuppliers:[]};var _defaultFieldValuesConstant;function init(entityType,fieldsElements,defaultFieldValuesConstant){if(!entityType){throw'Entity type is not defined.';} if(defaultFieldValuesConstant){_defaultFieldValuesConstant=defaultFieldValuesConstant;} if(!_defaultFieldValuesConstant){throw'Default field constants are not defined.';} switch(entityType){case _defaultFieldValuesConstant.EntityTypes.Product:{_fieldsElements.fieldsProducts=fieldsElements;break;} case _defaultFieldValuesConstant.EntityTypes.Customer:{_fieldsElements.fieldsCustomers=fieldsElements;break;} case _defaultFieldValuesConstant.EntityTypes.Supplier:{_fieldsElements.fieldsSuppliers=fieldsElements;break;}}} function getValuesAsync(entityType,callback){if(!entityType){throw'Entity type is not defined.';} var result=_getCache(entityType);if(result){if(callback&&typeof callback==='function'){callback(result);}else{return result;}}else{Ext.Ajax.request({url:'/api/DefaultFieldValues',method:'GET',params:{entityType:entityType},success:function success(response){if(response&&response.responseText){var data=Ext.JSON.decode(response.responseText);_setCache(entityType,data);if(callback&&typeof callback==='function'){callback(data);}else{return data;}}},failure:function failure(){Dear_Notification_Error('An unknown error occurred. Please try again later.');}});}} function saveValuesAsync(entityType,data){if(!entityType){throw'Entity type is not defined.';} if(!data){data=_prepareData(entityType);} dearHelper.blockUI.show();Ext.Ajax.request({url:"/api/DefaultFieldValues/".concat(entityType),method:'POST',jsonData:Ext.encode(data),success:function success(response){dearHelper.blockUI.hide();_setCache(entityType,null);Dear_Notification_Success('Changes saved successfully.');},failure:function failure(){dearHelper.blockUI.hide();Dear_Notification_Error('Save operation failed.');}});} function setValues(entityType,data,callbackIfNoData){if(data&&data.length>0){for(var i=0;i0){for(var i=0;i1){for(var j=0;j0){currentValue=currentValue.toLowerCase();} control=Ext.create('Ext.form.field.Checkbox',{id:cmpId,checked:currentValue,controlType:controlType,renderTo:renderTo,readOnly:IsReadOnly,inputId:inputId,tabIndex:tabIndex,cls:'x-form-type-checkbox'});$("#".concat(renderTo)).closest('.form-control').addClass('form-control-checkbox');break;case'Numeric':control=Ext.create('Ext.ux.NumericField',{id:cmpId,renderTo:renderTo,inputId:inputId,controlType:controlType,baseCls:'pull-right',selectOnFocus:true,fieldStyle:'text-align: right',hideTrigger:true,step:0,currencySymbol:null,alwaysDisplayDecimals:false,decimalPrecision:4,readOnly:IsReadOnly,tabIndex:tabIndex,maxLength:15,enforceMaxLength:true,listeners:{},fieldCls:'InputText DEARInputNoBorder'});break;case'Date':control=Ext.create('Ext.form.field.Date',{id:cmpId,renderTo:renderTo,controlType:controlType,emptyText:'choose...',defaultType:'datefield',inputId:inputId,altFormats:dearAltFormats,format:UserDateFormat,selectOnFocus:true,readOnly:IsReadOnly,tabIndex:tabIndex,listeners:{blur:HideDateInputElement,focus:ShowInputElement}});break;default:break;} if(control){_controls.push({index:index,control:control});}} function prepareSave(taskUpdated){if(taskUpdated){for(var i=1;i<=10;i++){var value=getValue(i);if(value){var type=getControl(i).controlType;if(type=='Checkbox'&&typeof value==='boolean'){value=value.toString();}else if(type=='Date'){value=Common_AttributeSet_ConvertToDateString(value);}} if(taskUpdated.get("CustomField".concat(i))!=value){var oldValue=taskUpdated.get("CustomField".concat(i));taskUpdated.set("CustomField".concat(i),value);if(oldValue!=taskUpdated.get("CustomField".concat(i))){taskUpdated.setDirty();}}}}} return{initTemplate:initTemplate,init:init,getControl:getControl,getValue:getValue,setWidth:setWidth,prepareSave:prepareSave};}();;function Lead_Common_InitStatusModels(){Ext.define('LeadStatusList',{idProperty:'StatusID',extend:'Ext.data.Model',fields:[{name:'StatusID',type:'string'},{name:'Name',type:'string'},{name:'IsKanban',type:'bool'},{name:'Position',type:'int'},{name:'PositionLocal',type:'int'}]});window.LeadStatusStore=Ext.create('Ext.data.JsonStore',{model:'LeadStatusList',proxy:{type:'rest',url:'/LeadStatus/FullList',reader:{type:'json'}},autoLoad:false});};function AttributeSetHelper(idPrefix){var divAttributeSet;var currentAttributeSet;var attributesControlsHasCreated=false;var createdControls=[];var taskUpdated;var prefix=idPrefix?"".concat(idPrefix,"_"):'';var attributeSetStore;var initialized=false;function init(taskObj,attributeSetStoreOrigin){divAttributeSet=$('#'+"".concat(prefix,"divAttributeSet"));taskUpdated=taskObj;if(attributeSetStoreOrigin){if(attributeSetStoreOrigin.isStore){attributeSetStore=attributeSetStoreOrigin;}else{currentAttributeSet=attributeSetStoreOrigin;}} initialized=true;} function reInit(taskObj){var _taskUpdated;var attributeSet=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(((_taskUpdated=taskUpdated)===null||_taskUpdated===void 0?void 0:_taskUpdated.getId())!=taskObj.getId()){createdControls=[];} taskUpdated=taskObj;if(attributeSet&&(currentAttributeSet==null||currentAttributeSet.getId()!=attributeSet.getId())){if(attributeSet.getId()==emptyGuid){attributeSet=null;} currentAttributeSet=attributeSet;createdControls=[];}} function updateCustomAttributeLabels(){if(taskUpdated==null){return;} var setRecord=_getOrderAttributSet();if(setRecord!=null){_destroyAttributesComponents();var showAttributesEditForm=false;for(var counter=1;counter<=10;counter++){var labelValue=setRecord.get("Column".concat(counter));var controlType=setRecord.get("Column".concat(counter,"Type"));var values=setRecord.get("Column".concat(counter,"Values"));var customFieldID="".concat(prefix,"CustomField").concat(counter);var lblCustomFieldID="".concat(prefix,"lblCustomField").concat(counter);var liCustomFieldID="".concat(prefix,"liCustomField").concat(counter);var $field=$("#".concat(liCustomFieldID));var $parentGridCell=$field.parents('.grid-col-4');var $container=$parentGridCell.length?$parentGridCell:$field;var currentValue='';if(taskUpdated!=null){currentValue=taskUpdated.get("CustomField".concat(counter));} if(labelValue==null||labelValue===''||controlType==='Not used'){$container.hideContent();}else{var createdControl=_createControlOfType(controlType,customFieldID,'',values,counter,currentValue);var element=Ext.get(lblCustomFieldID);if(element!=null){if(controlType==='Checkbox'){$("#".concat(element.id)).parent().addClass('form-control-checkbox');}} element.setHTML(labelValue);$container.showContent();if(showAttributesEditForm===false){showAttributesEditForm=true;} if(IsReadOnly){_setReadonlyForAttribute(createdControl,true);} createdControls[counter]=createdControl;}} _showAttributeSetEditForm(showAttributesEditForm);} attributesControlsHasCreated=true;} function prepareSave(){if(taskUpdated){for(var i=1;i<=10;i++){var control=createdControls[i];if(control){var value=control.getValue();if(value){var type=control.controlType;if(type=='Checkbox'&&typeof value==='boolean'){value=value.toString();}else if(type=='Date'){value=Common_AttributeSet_ConvertToDateString(value);}} if(taskUpdated.get("CustomField".concat(i))!=value){var oldValue=taskUpdated.get("CustomField".concat(i));taskUpdated.set("CustomField".concat(i),value);if(oldValue!=taskUpdated.get("CustomField".concat(i))){taskUpdated.setDirty();}}}}}} function processData(){if(!createdControls||createdControls.length==0){updateCustomAttributeLabels();} setTimeout(function(){for(var i=1;i0){value=value.toLowerCase();} control.setValue(value);}}},200);_showAttributeSetEditForm(!!_getOrderAttributSet());} function _destroyAttributesComponents(){if(attributesControlsHasCreated){for(var i=1;i<=10;i++){var cmpId="".concat(prefix,"custom_attribute_").concat(i);var cmp=Ext.getCmp(cmpId);if(cmp!=null){cmp.destroy();var lblCustomFieldID="#".concat(prefix,"lblCustomField").concat(i);$(lblCustomFieldID).html('');$(lblCustomFieldID).parent().removeClass('form-control-checkbox');}}}} function _createControlOfType(controlType,renderTo,inputId,availValues,index,currentValue){var cmpId="".concat(prefix,"custom_attribute_").concat(index);var cmp=Ext.getCmp(cmpId);if(cmp!=null){if(currentValue!=null&¤tValue!==''){if(controlType=='Checkbox'){currentValue=currentValue.toLowerCase();} cmp.setValue(currentValue);} return;} if(currentValue!==''&&controlType===''){controlType='Text';} var control=null;switch(controlType){case'Text':control=Ext.create('Ext.form.field.Text',{id:cmpId,controlType:controlType,width:200,renderTo:renderTo,selectOnFocus:true,inputId:inputId,fieldCls:'InputText DEARInputNoBorder'});break;case'List':var sValues=availValues.split(';');var array=[];if(currentValue!=null&¤tValue!==''){array.push({value:currentValue,name:currentValue});} for(var i=0;i1){for(var j=0;j0){currentAttributeSet=attributeSetStore.getAt(0);return currentAttributeSet;} return null;} function tryToCopyFrom(copyFromID,entityObj){var entityType='supplier';var copyTo=entityObj.get('SupplierID')||entityObj.get('CustomerID');if(copyTo!=entityObj.get('SupplierID')){entityType='customer';} var updateFieldValues=function updateFieldValues(data){for(var i=0;i0){if(control.$className=='Ext.form.field.Checkbox'){value=value.toLowerCase();} control.setValue(value);}}else{control.setValue(value);}}}};if(IsEmptyID(copyFromID)||copyFromID!=entityObj.get('AttributeSet')){if(!IsEmptyID(copyFromID)){updateFieldValues(null);} return;} Ext.Ajax.request({url:'/api/TenantAttributeSet_Index_vTenantAttributeSet/GetCopyFrom',method:'GET',params:{id:currentAttributeSet.getId(),fromID:entityObj.get('AttributeSet'),entityID:copyTo,entityType:entityType},callback:function callback(options,success,response){if(success&&response.responseText){var data=JSON.parse(response.responseText);updateFieldValues(data);}else{Dear_Notification_Warning('Purchase order and supplier attribute fields must be equivalent (same number of attributes, field names, and attribute type). Please adjust the attribute fields of the purchase or supplier sets to be equivalent to continue. The same set can be used for both.');updateFieldValues(null);}}});} function _setOperationReadOnly(stage){if(!IsReadOnly){for(var i=0;i{"use strict";;function _classCallCheck(a,n){if(!(a instanceof n))throw new TypeError("Cannot call a class as a function");};function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);};function toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.");} return("string"===r?String:Number)(t);};function toPropertyKey(t){var i=toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+"";};function _defineProperties(e,r){for(var t=0;t'):'';}},{id:'colChangedBy',tdCls:'colChangedBy',header:'User',flex:2,sortable:false,dataIndex:'ChangedBy'}],renderTo:'divHistoryLines',flex:1}));} window.HistoryLog_Init=function(url){return new HistoryLog(url);};})();