cronapp-common-js 4.0.1 → 4.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
var ISO_PATTERN=new RegExp("(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))"),TIME_PATTERN=new RegExp("PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d+)?)?S)?"),DEP_PATTERN=new RegExp("\\{\\{(.*?)\\|raw\\}\\}"),HTTP_STATUS=new RegExp("HTTP\\/1\\.1 (\\d+) (.*)"),DS_ID=new RegExp("[\\w\\_\\.\\d]+");const isCronapiApiPath=t=>/^\/?api\/cronapi\/.*\/?$/.test(t);!function(t){var s={callback:function(){},runOnLoad:!0,frequency:100,previousVisibility:null},a={checkVisibility:function(t,s){if(jQuery.contains(document,t[0])){var r=s.previousVisibility,o=t.is(":visible");s.previousVisibility=o;var h=null==r;h?s.runOnLoad&&s.callback(t,o,h):r!==o&&s.callback(t,o,h),setTimeout((function(){a.checkVisibility(t,s)}),s.frequency)}}};t.fn.visibilityChanged=function(r){var o=t.extend({},s,r);return this.each((function(){a.checkVisibility(t(this),o)}))}}(jQuery);var initDatasource=function(t,s,a,r,o,h,c,l,d,u,p,f){var v=parseInt(9999*Math.random());if(cronapi.internal.isJsonString(a.headers)){let t=JSON.parse(a.headers);t.push({key:"origin-path",type:"string",value:d.path()}),a.headers=JSON.stringify(t)}else{var y="origin-path:"+d.path();void 0===a.headers||null===a.headers?a.headers=y:a.headers=a.headers.concat(";",y)}var m,D={name:a.name,entity:a.entity,apiVersion:a.apiVersion,enabled:!a.hasOwnProperty("enabled")||"true"===a.enabled,keys:a.keys,endpoint:a.endpoint,lazy:"true"===a.lazy,append:!a.hasOwnProperty("append")||"true"===a.append,prepend:a.hasOwnProperty("prepend")&&""===a.prepend||"true"===a.prepend,watch:a.watch,rowsPerPage:a.rowsPerPage,offset:a.offset,filterURL:a.filter,watchFilter:a.watchFilter,deleteMessage:a.deleteMessage||""===a.deleteMessage?a.deleteMessage:l.instant("General.RemoveData"),headers:a.headers,autoPost:"true"===a.autoPost,autoRefresh:void 0!==a.autoRefresh&&null!==a.autoRefresh?a.autoRefresh:0,onError:a.onError,onAfterFill:a.onAfterFill,onBeforeCreate:a.onBeforeCreate,onAfterCreate:a.onAfterCreate,onBeforeUpdate:a.onBeforeUpdate,onAfterUpdate:a.onAfterUpdate,onBeforeDelete:a.onBeforeDelete,onAfterDelete:a.onAfterDelete,onChangeStatus:a.onChangeStatus,onGet:a.onGet,onPost:a.onPost,onPut:a.onPut,onDelete:a.onDelete,defaultNotSpecifiedErrorMessage:l.instant("General.ErrorOnServerCommunication"),dependentBy:a.dependentBy,dependentLazyPost:a.dependentLazyPost,batchPost:"true"===a.batchpost,dependentLazyPostField:a.dependentLazyPostField,parameters:a.parameters,parametersNullStrategy:a.parametersNullStrategy?a.parametersNullStrategy:"default",parametersExpression:$(s).attr("parameters"),conditionExpression:$(s).attr("condition"),condition:a.condition,orderBy:a.orderBy,loadDataStrategy:a.loadDataStrategy,schema:a.schema?JSON.parse(a.schema):void 0,checkRequired:!a.hasOwnProperty("checkrequired")||""===a.checkrequired||"true"===a.checkrequired,fetchOnVisible:void 0!==a.fetchOnVisible&&null!==a.fetchOnVisible&&"true"===a.fetchOnVisible,offline:"true"===a.offline,insideModal:"true"===a.insideModal},b={filter:!0,entity:!0,enabled:!0,parameters:!0};if(t.params){for(var M in t.params)if(t.params.hasOwnProperty(M)){var w=t.params[M];if(M.startsWith("$"+a.name+".")){var S=M.split(".");2==S.length&&("$filterMode"==S[1]?D.startMode=w:(m?m+=";":m="",isNaN(w)?m+=S[1]+"='"+w+"'":m+=S[1]+"="+w))}}m&&(D.parameters=m,D.parametersExpression=m)}v=parseInt(9999*Math.random());var L,O=r.initDataset(D,t,p,h,f,v,l);a.$observe("filter",(function(t){O.isPostingBatchData()||(b.filter?o((function(){b.filter=!1}),0):(o.cancel(L),L=o((function(){O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","filter",t):O.filter(t,(function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"filter")})),O.lastFilterParsed=t}),100)))})),m||a.$observe("parameters",(function(t){O.isPostingBatchData()||O.parameters!=t&&(O.parameters=t,o.cancel(L),L=o((function(){O.callDataSourceEvents("changeDependency","parameters",O.parameters),O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","parameters",O.parameters):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"parameters")}})}),0))}));let _={lastCondition:void 0,timeForCondition:void 0,typingSpeedLimit:1e3,maxWaitingValue:1e3,wait:function(){if(this.timeForCondition=0,this.lastCondition){(new Date).getTime()-this.lastCondition.getTime()<this.typingSpeedLimit&&(this.timeForCondition=this.maxWaitingValue)}return this.lastCondition=new Date,this.timeForCondition}};a.$observe("condition",(function(t){if(!O.isPostingBatchData()&&O.condition!=t){if(O.condition=t,"button"===O.loadDataStrategy)return;o.cancel(L),L=o((function(){O.callDataSourceEvents("changeDependency","condition",O.condition),O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","condition",O.condition):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"condition")}})}),_.wait())}})),a.$observe("enabled",(function(t){var s="true"===t;O.enabled!=s&&(O.enabled=s,O.enabled&&(o.cancel(L),L=o((function(){O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","enabled",O.parameters):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"enabled")}})}),200)))})),a.$observe("entity",(function(t){O.entity=t,O.entity.match(DS_ID)&&!isCronapiApiPath(O.entity)&&(O.entity="api/cronapi/odata/v2/"+O.entity.replaceAll(".","/")),b.entity?o((function(){b.entity=!1})):(o.cancel(L),L=o((function(){O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"entity")}})}),200))})),a.$observe("offline",(function(t){O.offline="true"===t})),t.$on("$destroy",(function(){u[a.name]&&u[a.name+".instanceId"]==v&&(u[a.name].destroy(),delete window[a.name],delete u[a.name],delete u[a.name+".instanceId"])}))};angular.module("datasourcejs",[]).factory("DatasetManager",["$http","$q","$timeout","$rootScope","$window","Notification","SyncService",function($http,$q,$timeout,$rootScope,$window,Notification,SyncService){this.datasets={};let DatasetManagerUtil={getMainScope:function(){return angular.element(document.getElementById("main-view")).scope()},resolveExpressionMap:async function(t){let s,a=this.getMainScope();if(cronapi.internal.isJsonString(t)){s={};let o=JSON.parse(t);for(var r in o){let t=o[r];if("blockly"===t.type){let r=this.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");s[t.key]=await a.$eval(r(t.value))}else"expression"===t.type?s[t.key]=a.$eval(t.value):s[t.key]=t.value}}return s},getHeaders:async function(t){let s;if(t&&t.length>0)if(cronapi.internal.isJsonString(t))s=await this.resolveExpressionMap(t);else{s={};let r,o=t.trim().split(";");for(var a=0;a<o.length;a++)r=o[a].split(":"),2===r.length&&(s[r[0]]=r[1])}return s&&(s["X-From-DataSource"]="true"),s},onMatchRegex:function(t,s,a){return r=>{let o=t.exec(r);return o&&o.length?r.split(s).join(a+s):r}}};const $httpLegacy=t=>{var s={verb:t.method,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return DatasetManagerUtil.getHeaders(t.headers).then(function(s){if(t.headers=s||t.headers,t.offlineMode){SyncService.toQueue(t);let s=t.originalObject||t.rawData||t.data;this.successCallback(s,200,null,t)}else{let s=$http(t);s.then((t=>{this.successCallback&&this.successCallback(t.data,t.status,t.headers,t.config)})),s.catch((t=>{this.errorCallback&&this.errorCallback(t.data,t.status,t.headers,t.config)}))}}.bind(s)),s};var DataSet=function(name,scope,fetchOnVisible){var NO_IMAGE_UPLOAD="data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjEyOHB4IiBoZWlnaHQ9IjEyOHB4IiB2aWV3Qm94PSIwIDAgNDQuNTAyIDQ0LjUwMiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDQuNTAyIDQ0LjUwMjsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8Zz4KCTxnPgoJCTxwYXRoIGQ9Ik05Ljg2MiwzNS42MzhoMjQuNzc5YzAtNS41NDYtMy44NjMtMTAuMjAzLTkuMTEzLTExLjYwNGMyLjc1LTEuMjQ4LDQuNjY4LTQuMDEzLDQuNjY4LTcuMjI5ICAgIGMwLTQuMzg4LTMuNTU5LTcuOTQyLTcuOTQyLTcuOTQyYy00LjM4NywwLTcuOTQzLDMuNTU3LTcuOTQzLDcuOTQyYzAsMy4yMTksMS45MTYsNS45OCw0LjY2OCw3LjIyOSAgICBDMTMuNzI1LDI1LjQzNSw5Ljg2MiwzMC4wOTIsOS44NjIsMzUuNjM4eiIgZmlsbD0iIzkxOTE5MSIvPgoJCTxwYXRoIGQ9Ik0xLjUsMTQuMTY5YzAuODI4LDAsMS41LTAuNjcyLDEuNS0xLjVWNC4zMzNoOC4zMzZjMC44MjgsMCwxLjUtMC42NzIsMS41LTEuNWMwLTAuODI4LTAuNjcyLTEuNS0xLjUtMS41SDIuNzc1ICAgIEMxLjI0NCwxLjMzMywwLDIuNTc3LDAsNC4xMDh2OC41NjFDMCwxMy40OTcsMC42NywxNC4xNjksMS41LDE0LjE2OXoiIGZpbGw9IiM5MTkxOTEiLz4KCQk8cGF0aCBkPSJNNDEuNzI3LDEuMzMzaC04LjU2MmMtMC44MjcsMC0xLjUsMC42NzItMS41LDEuNWMwLDAuODI4LDAuNjczLDEuNSwxLjUsMS41aDguMzM2djguMzM2YzAsMC44MjgsMC42NzMsMS41LDEuNSwxLjUgICAgczEuNS0wLjY3MiwxLjUtMS41di04LjU2QzQ0LjUwMiwyLjU3OSw0My4yNTYsMS4zMzMsNDEuNzI3LDEuMzMzeiIgZmlsbD0iIzkxOTE5MSIvPgoJCTxwYXRoIGQ9Ik00My4wMDIsMzAuMzMzYy0wLjgyOCwwLTEuNSwwLjY3Mi0xLjUsMS41djguMzM2aC04LjMzNmMtMC44MjgsMC0xLjUsMC42NzItMS41LDEuNXMwLjY3MiwxLjUsMS41LDEuNWg4LjU2ICAgIGMxLjUzLDAsMi43NzYtMS4yNDYsMi43NzYtMi43NzZ2LTguNTZDNDQuNTAyLDMxLjAwNSw0My44MywzMC4zMzMsNDMuMDAyLDMwLjMzM3oiIGZpbGw9IiM5MTkxOTEiLz4KCQk8cGF0aCBkPSJNMTEuMzM2LDQwLjE2OUgzdi04LjMzNmMwLTAuODI4LTAuNjcyLTEuNS0xLjUtMS41Yy0wLjgzLDAtMS41LDAuNjcyLTEuNSwxLjV2OC41NmMwLDEuNTMsMS4yNDQsMi43NzYsMi43NzUsMi43NzZoOC41NjEgICAgYzAuODI4LDAsMS41LTAuNjcyLDEuNS0xLjVTMTIuMTY1LDQwLjE2OSwxMS4zMzYsNDAuMTY5eiIgZmlsbD0iIzkxOTE5MSIvPgoJPC9nPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=",NO_FILE_UPLOAD="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4IiB2aWV3Qm94PSIwIDAgNTQ4LjE3NiA1NDguMTc2IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1NDguMTc2IDU0OC4xNzY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPGc+Cgk8cGF0aCBkPSJNNTI0LjMyNiwyOTcuMzUyYy0xNS44OTYtMTkuODktMzYuMjEtMzIuNzgyLTYwLjk1OS0zOC42ODRjNy44MS0xMS44LDExLjcwNC0yNC45MzQsMTEuNzA0LTM5LjM5OSAgIGMwLTIwLjE3Ny03LjEzOS0zNy40MDEtMjEuNDA5LTUxLjY3OGMtMTQuMjczLTE0LjI3Mi0zMS40OTgtMjEuNDExLTUxLjY3NS0yMS40MTFjLTE4LjA4MywwLTMzLjg3OSw1LjkwMS00Ny4zOSwxNy43MDMgICBjLTExLjIyNS0yNy40MS0yOS4xNzEtNDkuMzkzLTUzLjgxNy02NS45NWMtMjQuNjQ2LTE2LjU2Mi01MS44MTgtMjQuODQyLTgxLjUxNC0yNC44NDJjLTQwLjM0OSwwLTc0LjgwMiwxNC4yNzktMTAzLjM1Myw0Mi44MyAgIGMtMjguNTUzLDI4LjU0NC00Mi44MjUsNjIuOTk5LTQyLjgyNSwxMDMuMzUxYzAsMi40NzQsMC4xOTEsNi41NjcsMC41NzEsMTIuMjc1Yy0yMi40NTksMTAuNDY5LTQwLjM0OSwyNi4xNzEtNTMuNjc2LDQ3LjEwNiAgIEM2LjY2MSwyOTkuNTk0LDAsMzIyLjQzLDAsMzQ3LjE3OWMwLDM1LjIxNCwxMi41MTcsNjUuMzI5LDM3LjU0NCw5MC4zNThjMjUuMDI4LDI1LjAzNyw1NS4xNSwzNy41NDgsOTAuMzYyLDM3LjU0OGgzMTAuNjM2ICAgYzMwLjI1OSwwLDU2LjA5Ni0xMC43MTEsNzcuNTEyLTMyLjEyYzIxLjQxMy0yMS40MDksMzIuMTIxLTQ3LjI0NiwzMi4xMjEtNzcuNTE2QzU0OC4xNzIsMzM5Ljk0NCw1NDAuMjIzLDMxNy4yNDgsNTI0LjMyNiwyOTcuMzUyICAgeiBNMzYyLjcyOSwyODkuNjQ4Yy0xLjgxMywxLjgwNC0zLjk0OSwyLjcwNy02LjQyLDIuNzA3aC02My45NTN2MTAwLjUwMmMwLDIuNDcxLTAuOTAzLDQuNjEzLTIuNzExLDYuNDIgICBjLTEuODEzLDEuODEzLTMuOTQ5LDIuNzExLTYuNDIsMi43MTFoLTU0LjgyNmMtMi40NzQsMC00LjYxNS0wLjg5Ny02LjQyMy0yLjcxMWMtMS44MDQtMS44MDctMi43MTItMy45NDktMi43MTItNi40MlYyOTIuMzU1ICAgSDE1NS4zMWMtMi42NjIsMC00Ljg1My0wLjg1NS02LjU2My0yLjU2M2MtMS43MTMtMS43MTQtMi41NjgtMy45MDQtMi41NjgtNi41NjZjMC0yLjI4NiwwLjk1LTQuNTcyLDIuODUyLTYuODU1bDEwMC4yMTMtMTAwLjIxICAgYzEuNzEzLTEuNzE0LDMuOTAzLTIuNTcsNi41NjctMi41N2MyLjY2NiwwLDQuODU2LDAuODU2LDYuNTY3LDIuNTdsMTAwLjQ5OSwxMDAuNDk1YzEuNzE0LDEuNzEyLDIuNTYyLDMuOTAxLDIuNTYyLDYuNTcxICAgQzM2NS40MzgsMjg1LjY5NiwzNjQuNTM1LDI4Ny44NDUsMzYyLjcyOSwyODkuNjQ4eiIgZmlsbD0iI2NlY2VjZSIvPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=";this.fetchOnVisible=fetchOnVisible,this.parent=$("[name='"+name+"']").parent(),this.fetchOnVisible&&this.parent.visibilityChanged({callback:function(t,s,a){s&&this.holdServiceCall&&this.holdServiceCall()}.bind(this),runOnLoad:!1,frequency:100}),this.Notification=Notification,this.$scope=scope,this.noImageUpload=NO_IMAGE_UPLOAD,this.noFileUpload=NO_FILE_UPLOAD,this.$apply=function(t){scope.safeApply(t)}.bind(scope),this.columns=[],this.data=[],this.name=name,this.keys=[],this.enabled=!0,this.endpoint=null,this.active={},this.inserting=!1,this.editing=!1,this.fetchSize=2,this.observers=[],this.rowsPerPage=null,this.append=!0,this.headers=null,this.responseHeaders=null,this._activeValues=null,this.errorMessage="",this.onError=null,this.links=null,this.loadedFinish=null,this.lastLoadedTime=0,this.lastFilterParsed=null,this.rowsCount=-1,this.events={},this.busy=!1,this.cursor=0,this._savedProps,this.hasMoreResults=!1,this.loaded=!1,this.unregisterDataWatch=null,this.dependentBufferLazyPostData=null,this.lastAction=null,this.dependentData=null,this.hasMemoryData=!1,this.batchPost=!1,this.caseInsensitive=null,this.terms=null,this.checkRequired=!0,this.schema;var _self=this,service=null;function reverseArr(t){if(t){for(var s=new Array,a=t.length-1;a>=0;a--)s.push(t[a]);return s}return[]}function toBase64(t,s){var a=new FileReader;a.readAsDataURL(t),a.onload=function(t){var a=t.target.result.substr(t.target.result.indexOf("base64,")+7);s(a)}}function uuid(){var t,s,a="";for(t=0;t<32;t++)s=16*Math.random()|0,8!=t&&12!=t&&16!=t&&20!=t||(a+="-"),a+=(12==t?4:16==t?3&s|8:s).toString(16);return a}this.odataFile=[],this.destroy=function(){},this.init=function(){var dsScope=this;service={save:function(t){return this.call(_self.entity,"POST",t,!0)},update:function(t,s){return this.call(t,"PUT",s,!1)},remove:function(t,s){return this.call(t,"DELETE",s,!0)},call:function(t,s,a,r){var o={},h=t.indexOf("/cronapi/query/")>=0;if(h){o.inputs=[a];var c,l,d={};if(_self.busy=!0,t=(t=t.replace("/specificSearch","")).replace("/generalSearch",""),_self&&_self.$scope&&_self.$scope.vars)for(var u in d.vars={},_self.$scope.vars)d.vars[u]=_self.$scope.vars[u];for(var p in _self.$scope)_self.$scope[p]&&_self.$scope[p].constructor&&"DataSet"==_self.$scope[p].constructor.name&&(d[p]={},d[p].active=_self.$scope[p].active);o.fields=d}else o=a;var f={};for(var p in _self.copy(o,f,!0),delete f.__original,delete f.__status,delete f.__originalIdx,delete f.__sender,delete f.__$id,delete f.__parentId,delete f.$$hashKey,delete f.__fromMemory,delete f.__odatafiles,delete f.__$masterExpression,f)p.indexOf("__odataFile_")>-1&&(f[p.replace("__odataFile_","")]=void 0,delete f[p]);for(var p in f)if(f.hasOwnProperty(p)){let t=f[p];_self.isAutoGeneratedValue(t)&&delete f[p]}var v=function(t,s,a,r,o){if(_self.busy=!1,c&&(_self.isOData()?null!=t.d&&null!=t.d.result?(_self.normalizeData(t.d.result),c(t.d.result,!0,o)):null!=t.d?(_self.normalizeObject(t.d),c(t.d,!0,o)):c(t,!0,o):c(h?t.value:t,!0,o)),h||_self.isOData()){var l=t;_self.isOData()&&((l={}).commands=t.__callback,_self.normalizeData(l.commands)),_self.$scope.cronapi.evalInContext(JSON.stringify(l))}},y=_self.getParentDatasource();let m=y.getBatchDataItem(o);if(m&&m.result){let t=y.batchServiceData.indexOf(m);y.batchServiceData.splice(t,1),$timeout((()=>{v(m.result)}),0),this.$promise={}}else this.$promise=_self.getService(s,o)({method:s,url:_self.removeSlash((window.hostApp||"")+t),data:"DELETE"!=s&&o?JSON.stringify(f):null,headers:_self.headers,rawData:o?f:null,originalObject:o||null,urlPart:t,offlineMode:_self.isOfflineMode()}).success(v).error((function(t,s,a,r){var o;_self.busy=!1,o=_self.isOData()?t.error.message.value:h&&t.value?t.value:t,_self.handleError(o),l&&l(o)}));return this.$promise.then=function(t){return c=t,this},this.$promise.error=function(t){return l=t,this},this}},this.isAutoGeneratedValue=function(t){return"string"==typeof t&&t.length>10&&(t.startsWith("$autogenerated$")||t.substring(1).startsWith("$autogenerated$"))},this.getIndexedDB=function(t){return window.indexedDB||(window.indexedDB=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,window.IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction||window.msIDBTransaction,window.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange),{properties:t,successCallback:null,errorCallback:null,type:null,args:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this},post:function(){return this.type="put",this.args=arguments,this},put:function(){return this.type="put",this.args=arguments,this},delete:function(){return this.type="delete",this.args=arguments,this},get:function(){return this.type="getAll",this.args=arguments,this},call:function(){request=window.indexedDB.open(this.properties.dbname,this.properties.dbversion||1),request.onerror=function(t){this.errorCallback&&this.errorCallback(t)}.bind(this),request.onsuccess=function(t){this.proceed(t.target.result)}.bind(this),request.onupgradeneeded=function(t){var s=t.target.result;s.createObjectStore(this.properties.objectStore,{keyPath:this.properties.key}).transaction.oncomplete=function(t){s.transaction(this.properties.objectStore,"readwrite").objectStore(this.properties.objectStore).add({id:123,name:"Jose"})}.bind(this)}.bind(this)},proceed:function(t){if(this.type){var s=t.transaction(this.properties.objectStore,"readwrite").objectStore(this.properties.objectStore);s[this.type].apply(s,this.args).onsuccess=function(t){this.successCallback&&("put"===this.type?this.successCallback(this.args[0]):this.successCallback(t.target.result))}.bind(this)}else this.successCallback&&this.successCallback()}}},this.batchServiceData=[],this.getBatchService=function(t){return function(s){var a={verb:t,properties:s,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return $timeout(function(){var r=this.getParentDatasource();let o=s.originalObject||s.rawData||s.data||this.active,h=this.entity;"PUT"==t&&(h=this.getEditionURL(o)),"DELETE"==t&&(h=this.getDeletionURL(o)),h.indexOf("/")>0&&(h=h.substring(h.lastIndexOf("/")+1,h.length)),r.batchServiceData.push({entity:h,data:o,promise:a}),a.successCallback&&a.successCallback.call(this,o,null,null,null,!0)}.bind(this)),a}.bind(this)},this.batchEnabled=function(t){return!(!t||!this.hasPendingChanges())&&null==this.getBatchDataItem(t)},this.getBatchDataItem=function(t){if(t){var s=this.getParentDatasource();for(let a=0;a<s.batchServiceData.length;a++){if(s.batchServiceData[a].data.__$id==t.__$id)return s.batchServiceData[a]}}return null},this.performBatchPost=function(t){return new Promise(((s,a)=>{let r="batch_"+this.uuidv4(),o="";o+="--"+r+"\n";let h="changeset_"+this.uuidv4();o+="Content-Type: multipart/mixed; boundary="+h+"\n";for(let t=0;t<this.batchServiceData.length;t++){let s=this.batchServiceData[t];o+="--"+h+"\n",o+="Content-Type: application/http\n",o+="Content-Transfer-Encoding:binary\n",o+=s.promise.properties.method+" "+s.entity+" HTTP/1.1\n",o+="Content-Type: application/json\n",o+="Accept: application/json\n",o+="X-Master-Id: "+s.promise.properties.originalObject.__$id+"\n",s.promise.properties.originalObject.__$masterExpression&&(o+="X-Detail-Fill: "+s.promise.properties.originalObject.__$masterExpression+"\n");let a=s.promise.properties.headers;for(var c in a)a.hasOwnProperty(c)&&(o+=c+": "+a[c]+"\n");"DELETE"!=s.promise.properties.method&&(o+=s.promise.properties.data+"\n")}o+="--"+h+"--\n",o+="--"+r+"--\n",console.log(o);let l=this.entity;l.indexOf("/")>0&&(l=l.substring(0,l.lastIndexOf("/")));let d={};this.copy(this.headers,d),d["Content-Type"]="multipart/mixed; boundary="+r;let u=(t,s,a,r)=>{let o;this.batchServiceData.length>0&&(o=this.batchServiceData[0].promise.errorCallback),o?o(t,s,a,r,!1):this.handleError(t),this.batchServiceData=[]};$httpLegacy({method:"POST",url:_self.removeSlash((window.hostApp||"")+l+"/$batch"),data:o,headers:d,offlineMode:_self.isOfflineMode()}).success(function(s,a,r,o,h){let c=this.parseBatchResult(s);for(let t=0;t<c.length;t++)if(c[t].status>=400)return void u(c[t].data,c[t].status);for(let t=0;t<this.batchServiceData.length;t++)this.batchServiceData[t].result=c[t]&&null!=c[t].data?c[t].data:this.batchServiceData[t].data;if(t)t();else{let t;this.batchServiceData.length>0&&(t=this.batchServiceData[0].promise.successCallback),t&&(this.batchServiceData.splice(0,1),t(c[0].data,c[0].status,r,o,!1))}}.bind(this)).error(u)}))},this.parseBatchResult=function(t){let s,a=[],r=t.split("\n");for(let t=0;t<r.length;t++){let o=r[t];if(o.startsWith("{")&&a.push({status:s,data:JSON.parse(o)}),o.startsWith("HTTP/1.1"))s=HTTP_STATUS.exec(o)[1];o.startsWith("HTTP/1.1")&&o.indexOf("No Content")>0&&a.push({status:s,data:null})}return a},this.uuidv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var s=16*Math.random()|0;return("x"==t?s:3&s|8).toString(16)}))},this.getService=function(verb,object){_self=this;var event=eval("this.on"+verb);return"GET"===verb&&(event||this.isLocalData()||this.isNavigatorOffline())?function(t){var s={verb:verb,properties:t,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return $timeout(function(){var t,s={currentData:this.properties.rawData||this.properties.data||_self.active,filter:this.properties.filter||"",datasource:_self,selectedIndex:_self.cursor,index:_self.cursor,selectedRow:_self.active,item:_self.active,selectedKeys:_self.getKeyValues(_self.active,!0),selectedKey:_self.getFirstKeyValue(_self.active,!0),callback:this.successCallback};if(event)(t=_self.$scope.$eval(event,s))instanceof Promise?t.then(function(t){t&&"[object Array]"!==Object.prototype.toString.call(t)&&(t=[t]),_self.$scope.safeApply(function(){this.successCallback(t)}.bind(this))}.bind(this)).catch(function(t){_self.handleError(t)}.bind(this)):t&&this.successCallback(t);else{let t=_self.getPouchDB();if("GET"!=this.verb||this.properties.filter){if("GET"==this.verb){var a=peg$parse(this.properties.filter);t.find({selector:a}).catch(this.errorCallback).then(function(t){t.rows=t.docs,t.total_rows=t.rows.length,this.successCallback&&this.successCallback(t)}.bind(this))}}else t.allDocs({include_docs:!0,attachments:!0}).catch(this.errorCallback).then(function(t){for(var s=[],a=0;a<t.rows.length;a++)s.push(t.rows[a].doc);t.rows=s,this.successCallback&&this.successCallback(t)}.bind(this))}}.bind(s),0),s}:(this.hasOfflineSupport()&&object&&this.operationPouchDB(verb,object),this.batchEnabled(object)&&"GET"!=verb?this.getBatchService(verb):$httpLegacy)},this.isBusy=function(){return this.busy},this.isLoaded=function(){return this.loaded},this.toString=function(){return"[Datasource]"},this.handleAfterCallBack=function(t,s){if(t)try{var a={currentData:this.data,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(_self.active,!0),callback:s};this.$scope.$eval(t,a)}catch(t){this.handleError(t)}},this.handleBeforeCallBack=async function(t,s){var a=!0;let r=DatasetManagerUtil.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");if(t)try{var o={currentData:this.data,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(_self.active,!0),callback:s};await this.$scope.$eval(r(t),o)}catch(t){a=!1,this.handleError(t)}return a},this.handleError=function(t){if(console.log(t),t instanceof XMLDocument){var s=t.getElementsByTagName("message")[0].textContent;t=s,console.log(t)}var a="";if(t)if("[object String]"===Object.prototype.toString.call(t))a=t;else{s=t.msg||t.desc||t.message||t.error||t.responseText;this.isOData()&&t.error.message&&t.error.message.value&&(s=t.error.message.value),s&&(a=s)}a||(a=this.defaultNotSpecifiedErrorMessage);if(result=/<h1>(.*)<\/h1>/gim.exec(a),result&&result.length>=2&&(a=result[1]),this.errorMessage=a,this.onError&&""!==this.onError){if("string"==typeof this.onError)try{var r={currentData:this.active,filter:"",error:a,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(this.active,!0),callback:this.successCallback},o=this.$scope.$eval(this.onError,r);"function"==typeof o&&(this.onError=o)}catch(t){isValid=!1,Notification.error(t)}}else this.onError=function(t){Notification.error(t)};"function"==typeof this.onError&&this.onError.call(this,a)},this.observers&&this.observers.length>0&&$rootScope.$watch(function(){return this.active}.bind(this),function(t){t&&this.notifyObservers(t)}.bind(this),!0)},this.setFile=function(t,s,a){t&&"pattern"===t.$error||t&&toBase64(t,(function(t){this.$apply=function(t){s[a]=t,scope.$apply(s)}.bind(scope),this.$apply(t)}))},this.downloadFile=function(t,s){if(void 0!==s){for(var a=(window.hostApp||"")+this.entity+"/download/"+t,r=0;r<s.length;r++)a+="/"+s[r];$http({url:a,method:"GET",responseType:"arraybuffer"}).then((function(t){var s=new Blob([t.data],{type:"application/*"});$window.open(URL.createObjectURL(s))}))}},this.openImage=function(t){if(-1==t.indexOf("https://")&&-1==t.indexOf("http://")){var s="data:image/png;base64,"+t;$window.open("","_blank","height=300,width=400").document.write('<img src="'+s+'"/>')}else $window.open(t,"_blank","height=300,width=400")},this.byteSize=function(t){if(!angular.isString(t))return"";function s(t,s){return-1!==s.indexOf(t,s.length-t.length)}return function(t){return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")+" bytes"}(function(t){return t.length/4*3-function(t){return s("==",t)?2:s("=",t)?1:0}(t)}(t))},this.insert=async function(obj,onSuccess,onError,forceSave){await this.handleBeforeCallBack(this.onBeforeCreate)&&(!this.dependentLazyPost&&!this.batchPost||forceSave?service.save(obj).$promise.error(onError).then(onSuccess):(obj.__status="inserted",this.dependentLazyPost&&(obj.__parentId=eval(this.dependentLazyPost).active.__$id),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData),onSuccess&&onSuccess(obj)))},this.addDependentDatasource=function(dts){this.children||(this.children=[]),this.children.push(dts),this.dependentLazyPost?eval(this.dependentLazyPost).addDependentDatasource(dts):(this.dependentData||(this.dependentData=[]),this.dependentData.push(dts))},this.getParentDatasource=function(){return this.dependentLazyPost?eval(this.dependentLazyPost).getParentDatasource():this},this.updateObjectAtIndex=function(t,s,a){s=s||this.data,this.copy(t,s[a]),t.__$id=s[a].__$id,delete s[a].__status,delete s[a].__original,delete s[a].__originalIdx,delete s[a].__odatafiles,delete s[a].__$masterExpression},this.cleanDependentBuffer=function(){var t=[];$(this.data).each((function(){this.__status?"updated"==this.__status&&t.push(this.__original):t.push(this)})),this.data.length=0;for(var s=0;s<t.length;s++)delete t[s].__status,delete t[s].__original,delete t[s].__originalIdx,this.data.push(t[s]);if(this.postDeleteData)for(s=0;s<this.postDeleteData.length;s++)delete this.postDeleteData[s].__status,delete this.postDeleteData[s].__original,delete this.postDeleteData[s].__originalIdx,this.data.push(this.postDeleteData[s]);this.data&&this.data.length>0?(this.cursor=0,this.active=this.data[0]):(this.cursor=-1,this.active=null),this.busy=!1,this.editing=!1,this.inserting=!1,this.postDeleteData=null,this.hasMemoryData=!1,this.notifyPendingChanges(this.hasMemoryData),this.events.read&&this.callDataSourceEvents("read",this.data),this.events.afterchanges&&this.callDataSourceEvents("afterchanges",this.data)},this.cancelBatchData=function(t){this.dependentData&&$(reverseArr(this.dependentData)).each((function(){this.cleanDependentBuffer()})),this.cleanDependentBuffer(),this.batchServiceData=[],t&&t()},this.flushDependencies=function(t,s){var a=[];if(this.dependentData){var r=function(){reduce(this.dependentData,function(t,r){a.push(t.storeDependentBuffer((function(){r()}),void 0,s))}.bind(this),function(){t&&t(a)}.bind(this))}.bind(this);reduce(reverseArr(this.dependentData),function(t,a){t.storeDependentBuffer((function(){a()}),!0,s)}.bind(this),function(){r()}.bind(this))}else t&&t(a)},this.postBatchData=function(t,s){let a=!s;s||(this.batchServiceData=[]);let r=()=>{a?(a=!1,this.performBatchPost(function(){this.postBatchData(t,!0)}.bind(this))):t&&t()};this.postingBatch=!0;var o=[],h=function(){this.storeDependentBuffer(function(){o.push(this.storeDependentBuffer(function(){reduce(this.dependentData,function(t,s){o.push(t.storeDependentBuffer((function(){s()}),!1,a))}.bind(this),function(){this.postingBatch=!1;for(var t=0;t<o.length;t++)o[t]();r&&r()}.bind(this))}.bind(this),!1,a))}.bind(this),!0,a)}.bind(this);reduce(reverseArr(this.dependentData),function(t,s){t.storeDependentBuffer((function(){s()}),!0,a)}.bind(this),function(){h()}.bind(this))};var reduce=function(t,s,a){t&&0!=t.length?t.reduce((function(t,a){return t.then((function(){return new Promise((function(t){s(a,t)}))}))}),Promise.resolve()).then((function(){a()})):a()};this.storeDependentBuffer=function(callback,onlyRemove,batchMode){var _self=this,dependentDS=eval(_self.dependentLazyPost);this.batchPost&&(dependentDS=this);var array=[];if(!onlyRemove&&(array=array.concat(_self.data),_self.memoryData))for(key in _self.memoryData)if(_self.memoryData.hasOwnProperty(key)){for(var mem=_self.memoryData[key],x=0;x<mem.data.length;x++)mem.data[x].__fromMemory=!0;array=array.concat(mem.data)}_self.postDeleteData&&(array=array.concat(_self.postDeleteData));var func=function(t,s){if(t.__status){if(!_self.parameters&&(_self.dependentLazyPostField&&(t[_self.dependentLazyPostField]=dependentDS.active),_self.entity.indexOf("//")>-1)){var a=dependentDS.getKeyValues(dependentDS.active),r="";for(var o in a)a.hasOwnProperty(o)&&(r+="/"+a[o]);r+="/",_self.entity=_self.entity.replace("//",r)}if(_self.parameters){var h=_self.getParametersMap(t.__parentId?t.__parentId:null);for(var o in h)h.hasOwnProperty(o)&&updateObjectValue(t,o,h[o]);let s=_self.getParametersBatchExpression(t.__parentId?t.__parentId:null);t.__$masterExpression=s}"inserted"==t.__status?(c=t,batchMode||(l=_self.processODataFiles(c)),_self.insert(c,(function(t,a,r){if(r)s();else{var o=c.__sender,h=_self.getIndexOfListTempBuffer(c,array),d=!1,u=t;h>=0&&(u=array[h],d=array[h].__fromMemory,_self.updateObjectAtIndex(t,array,h)),_self.events.create&&!d&&(o&&((t=array[h]).__sender=o),_self.callDataSourceEvents("create",t),delete t.__sender),l&&l.length>0?_self.sendODataFiles(l,t,function(t){_self.copy(t.data,u)}.bind(this),(function(){s()})):s()}}),(function(){s()}),!0)):"updated"==t.__status?function(t){var a;batchMode||(a=_self.processODataFiles(t)),_self.update(t,(function(r,o,h){if(h)s();else{var c=t.__sender,l=_self.getIndexOfListTempBuffer(t,array),d=!1,u=r;l>=0&&(u=array[l],d=array[l].__fromMemory,_self.updateObjectAtIndex(r,array,l),r=array[l]),_self.events.update&&!d&&(c&&(r.__sender=c),_self.callDataSourceEvents("update",r),delete r.__sender),a&&a.length>0?_self.sendODataFiles(a,r,function(t){_self.copy(t.data,u)}.bind(this),(function(){s()})):s()}}),(function(){s()}),!0)}(t):"deleted"==t.__status&&onlyRemove?function(t){_self.remove(t,(function(a,r,o){if(o)s();else{if(_self.events.delete){var h={};_self.copy(t,h),delete h.__status,delete h.__original,delete h.__originalIdx,_self.callDataSourceEvents("delete",h)}s()}}),!0,null,(function(){s()}))}(t):s()}else s();var c,l},resetFunc=function(){onlyRemove||(this.busy=!1,this.editing=!1,this.inserting=!1,this.hasMemoryData=!1,this.memoryData=null,batchMode||this.notifyPendingChanges(this.hasMemoryData),this.events.afterchanges&&!batchMode&&this.callDataSourceEvents("afterchanges",this.data))}.bind(this);return reduce(array,func,function(){callback&&callback(),batchMode||(this.postDeleteData=null)}.bind(this)),resetFunc},this.getIndexOfListTempBuffer=function(t,s){s=s||this.data;for(var a=0;a<s.length;a++)if(s[a].__$id&&t.__$id&&s[a].__$id==t.__$id)return a;return-1},this.getObjectAsString=function(t,s){return null!=s&&null!=s||(s=!0),this.isOData()?window.objToOData(t,s):null==t?"":"number"==typeof t?t+"@@number":t instanceof Date?t.toISOString()+"@@datetime":"boolean"==typeof t?t+"@@boolean":t+""},this.update=async function(t,s,a,r){await this.handleBeforeCallBack(this.onBeforeUpdate)&&(!this.dependentLazyPost&&!this.batchPost||r?service.update(this.getEditionURL(t,r),t).$promise.error(a).then(s):s&&s(t))},this.validateFields=function(t,s){var a=$(t);if(a.length>0&&"checkbox"!==a.get(0).type){var r=$('label[for="'+a.get(0).id+'"]'),o=a.get(0).id;return r.length>0&&(o=r.text())&&(o=o.replaceAll("\n","").trim()),s&&(Notification.error(s.replace("{0}",o)),$(a.get(0)).addClass("ng-touched").removeClass("ng-untouched"),a.get(0).focus&&a.get(0).focus()),!1}return!0},this.getPatterns=function(){return $('input[ng-model*="'+this.name+'."]').filter((function(t){return $(this).attr("pattern")}))},this.missingRequiredField=function(t){if(this.getPatterns().length>0)return!1;if(this.checkRequired){var s=this.validateFields('[required][ng-model*="'+this.name+'."].ng-invalid-required',t?"":this.translate.instant("FieldIsRequired"));return!(s=(s=s&&this.validateFields('[required][ng-model*="'+this.name+'."].ng-empty',t?"":this.translate.instant("FieldIsRequired")))&&this.validateFields('[ng-model*="'+this.name+'."].ng-invalid',t?"":this.translate.instant("FieldIsInvalid")))}return!1},this.hasInvalidField=function(){return!(this.getPatterns().length>0)&&(!!this.checkRequired&&$('input[ng-model*="'+this.name+'."]:invalid').not("input[type=checkbox]").not(".ng-empty").length>0)},this.postSilent=function(t,s){this.post(t,s,!0)},this.updateActive=function(t){for(var s in t)t.hasOwnProperty(s)&&"__status"!=s&&(this.active[s]=t[s])},this.processODataFiles=function(t){var s=[];for(var a in t)if(a.indexOf("__odataFile_")>-1){var r={field:a.replace("__odataFile_",""),value:t[a]};s.push(r),t[r.field]=void 0,delete t[a]}return s},this.sendODataFiles=function(t,s,a,r){if(s&&t&&t.length>0){var o=this.entity,h=this.getKeyValues(s),c=["("],l=0;for(var d in h)l>0&&c.push(","),c.push(d),c.push("="),c.push(window.objToOData(h[d])),l++;c.push(")"),o+=c.join("");var u=JSON.parse(localStorage.getItem("_u"));reduce(t,function(t,r){let h=(window.hostApp||"")+o+"/"+t.field+"/$value";if(_self.isOfflineMode()){let o={method:"PUT",data:t.value,url:h,headers:_self.headers};SyncService.toQueue(o),cronapi.internal.fileToBase64(t.value,(o=>{s[t.field]=o,a&&a({field:t.field,data:s}),r()}))}else{var c=t.value,l=new XMLHttpRequest;l.open("PUT",h),l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.setRequestHeader("X-File-Name",c.name),l.setRequestHeader("Content-Type",(c.type||"application/octet-stream")+";charset=UTF-8"),window.isUsingCookie()||l.setRequestHeader("X-AUTH-TOKEN",u?.token);const d=document.cookie.match(new RegExp("(^| )XSRF-TOKEN=([^;]+)"));d&&l.setRequestHeader("X-XSRF-TOKEN",d[2]),l.onreadystatechange=function(){if(4===l.readyState&&500===l.status){var h=(new DOMParser).parseFromString(l.response,"text/xml");this.handleError(h)}4===l.readyState&&201===l.status&&service.call(o,"GET",{},!1).$promise.error((function(t){Notification.error("Error send file")})).then((function(o,h){a?a({field:t.field,data:o}):s[t.field]=o[t.field],r()}))}.bind(this),l.send(c)}}.bind(this),function(){r&&r()}.bind(this))}else r&&r()},this.getFieldSchema=function(t){var s;if(this.schema)for(var a=0;a<this.schema.length;a++)if(this.schema[a].name==t){s=this.schema[a];break}return s},this.asyncPost=function(t,s,a){setTimeout(function(){this.post(t,s,a)}.bind(this),100)},this.copyWithoutAngularObj=function(){var t={};for(var s in this)this.hasOwnProperty(s)&&!s.startsWith("$")&&(t[s]=this[s]);return t},this.post=function(onSuccess,onError,silent,keepBuffer){!silent&&this.missingRequiredField()||!silent&&this.hasInvalidField()||(keepBuffer||(this.batchServiceData=[]),this.lastAction="post",this.busy=!0,this.inserting?this.insert(this.active,function(t,s,a){if(!a||!this.dependentData||this.dependentLazyPost||this.batchPost){this.active.__sender&&(t.__sender=this.active.__sender),this.active.__$id&&(t.__$id=this.active.__$id);var r=function(a){if(this.active=t,this.handleAfterCallBack(this.onAfterCreate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),this.events.create&&s&&(this.callDataSourceEvents("create",this.active),delete _self.active.__sender),this.events.memorycreate&&!s&&this.callDataSourceEvents("memorycreate",this.active),a)for(let t=0;t<a.length;t++)a[t]()}.bind(this),o=function(){this.data.push(t),!this.dependentData||this.dependentLazyPost||this.batchPost?r():this.flushDependencies(r,!1)}.bind(this);if(s){var h=this.processODataFiles(this.active);h&&h.length>0?this.sendODataFiles(h,t,function(s){this.copy(s.data,t)}.bind(this),function(){o()}.bind(this)):o()}else o()}else this.flushDependencies((()=>{this.performBatchPost((()=>{this.post(onSuccess,onError,silent,!0)}))}),!0)}.bind(this),onError):this.editing?this.update(this.active,function(obj,hotData,batchPostponed){if(!batchPostponed||!this.dependentData||this.dependentLazyPost||this.batchPost){var odataFiles,foundRow;hotData&&(odataFiles=this.processODataFiles(this.active));var keyObj=this.getKeyValues(this.lastActive);this.data.forEach(function(currentRow){var found;if(this.lastActive.__$id&¤tRow.__$id)found=this.lastActive.__$id==currentRow.__$id;else{var dataKeys=this.getKeyValues(currentRow);for(var key in keyObj){if(!dataKeys[key]||dataKeys[key]!==keyObj[key]){found=!1;break}found=!0}}if(found){foundRow=currentRow;var lastActive={};this.copy(this.lastActive,lastActive),this.copy(obj,currentRow),this.lastActive&&this.lastActive.__sender&&(currentRow.__sender=this.lastActive.__sender),this.active=currentRow,!this.dependentLazyPost&&!this.batchPost||currentRow.__status||(currentRow.__status="updated",currentRow.__original=lastActive,this.hasMemoryData=!0,this.dependentLazyPost&&(currentRow.__parentId=eval(this.dependentLazyPost).active.__$id)),this.notifyPendingChanges(this.hasMemoryData),this.events.update&&hotData&&(this.callDataSourceEvents("update",this.active),delete this.active.__sender),this.events.memoryupdate&&!hotData&&this.callDataSourceEvents("memoryupdate",this.active)}}.bind(this));var back=function(t){if(foundRow&&this.handleAfterCallBack(this.onAfterUpdate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),t)for(let s=0;s<t.length;s++)t[s]()}.bind(this),func=function(t){hotData&&odataFiles&&odataFiles.length>0?this.sendODataFiles(odataFiles,foundRow,function(t){this.copy(t.data,foundRow)}.bind(this),function(){this.events.update&&hotData&&this.callDataSourceEvents("update",foundRow),back(t)}.bind(this)):back(t)}.bind(this);!this.dependentData||this.dependentLazyPost||this.batchPost?func():this.flushDependencies(func)}else this.flushDependencies((()=>{this.performBatchPost((()=>{this.post(onSuccess,onError,silent,!0)}))}),batchPostponed)}.bind(this),onError):0==this.data.length?this.startInserting(this.active,function(){this.post(onSuccess,onError,silent)}.bind(this)):this.startEditing(null,function(){this.post(onSuccess,onError,silent)}.bind(this)))},this.notifyPendingChanges=function(value){console.log("notifyPendingChanges : "+value),this.events.pendingchanges&&this.callDataSourceEvents("pendingchanges",value),this.dependentLazyPost&&eval(this.dependentLazyPost).notifyPendingChanges(value)},this.notifyPendingChanges=function(value){console.log("notifyPendingChanges : "+value),this.events.pendingchanges&&this.callDataSourceEvents("pendingchanges",value),this.dependentLazyPost&&eval(this.dependentLazyPost).notifyPendingChanges(value)},this.getConditionParams=function(){if(this.condition)try{var t=this.$interpolate(this.conditionExpression)(this.$scope),s=JSON.parse(t);if("object"==typeof s){if(s.params){let t;for(var a=0;a<s.params.length;a++){var r=s.params[a].fieldValue;r.length>=2&&"'"==r.charAt(0)&&"'"==r.charAt(r.length-1)&&(r=r.substring(1,r.length-1)),""!==r&&null!=r&&(t?t+="&":t="",t+=s.params[a].fieldName+"="+encodeURIComponent(r))}return t}}}catch(t){console.log(t)}},this.getDeletionURL=function(t,s){var a=this.getKeyValues(t.__original?t.__original:t,s),r="";this.isOData()&&(r="(");var o=0;for(var h in a)a.hasOwnProperty(h)&&(this.isOData()?(o>0&&(r+=","),r+=h+"="+this.getObjectAsString(a[h])):r+="/"+a[h],o++);this.isOData()&&(r+=")",r=encodeURI(r));var c=this.entity;this.entity.endsWith("/")&&(c=c.substring(0,c.length-1)),c+=r;let l=this.getConditionParams();return l&&(c=c+"?"+l),c},this.getEditionURL=function(t,s){var a=this.getKeyValues(t.__original?t.__original:t,s),r="";for(var o in this.isOData()&&(r="("),a)a.hasOwnProperty(o)&&(this.isOData()?r+=("("==r?"":",")+o+"="+this.getObjectAsString(a[o]):r+="/"+a[o]);this.isOData()&&(r+=")",r=encodeURI(r));var h=this.entity;this.entity.endsWith("/")&&(h=h.substring(0,h.length-1)),h+=r;let c=this.getConditionParams();return c&&(h=h+"?"+c),h},this.refreshActive=function(t,s){if(this.active&&"inserted"!=this.active.__status){var a=this.getEditionURL(this.active),r=this.getKeyValues(this.active);this.$promise=this.getService("GET")({method:"GET",url:a,headers:this.headers}).success(function(a,o,h,c){var l=null;this.isOData()?(l=a.d,this.normalizeObject(l)):a&&a.length>0&&(l=a[0]);var d=-1,u=0;this.data.forEach(function(t){var s=!1,a=0,o=0;for(var h in r)o++,t[h]&&t[h]===r[h]&&a++;a==o&&(s=!0),s&&(d=u,l&&(this.copy(l,t),this.copy(l,this.active))),u++}.bind(this)),-1!=d?(this.events.update&&this.callDataSourceEvents("update",this.active),t&&t(this.active)):s&&s()}.bind(this)).error(function(t,a,r,o){s&&s()}.bind(this))}else t&&t(this.active)},this.buildURL=function(t,s){var a=this.getKeyValues(this.active,!1,s);"object"!=typeof t&&(t=[t]);var r="",o=0;for(var h in a){var c;if(a.hasOwnProperty(h))c=Array.isArray(t)?t[o]:t[h],o>0&&(r+=" and "),r+=h+" eq "+this.getObjectAsString(c);o++}return r},this.findObj=function(t,s,a,r,o){let h=o||deepCopy(this.keys),c=function(s){for(let a=0;a<h.length;a++)if(objectsAreEqual(t[a],s[h[a]]))return s}.bind(this),l=this.data.filter(c);if(l&&l.length>0)a&&a(l);else{var d,u=this.buildURL(t,o);d={params:{$filter:u}},null!=u&&0!=u.length||(d={}),this.fetch(d,{success:function(t){if(a){let s=t.filter(c);a(s)}}.bind(this),error:function(t){r&&r()}},void 0,{lookup:!0})}},this.getColumn=function(t){var s=[];return $.each(this.data,(function(a,r){s.push(r[t])})),s},this.onBackNomalState=function(){this.$scope.safeApply(function(){this.busy=!1,this.editing=!1,this.inserting=!1;let t=this.dependentData&&this.dependentData.filter((t=>t.inserting||t.editing));!t||t.forEach((t=>t.cancel())),this.noticeStatusChange()}.bind(this))},this.cancel=function(){this.inserting&&(this.cursor>=0?this.active=this.data[this.cursor]:this.active={}),this.editing&&(this.active=this.lastActive),this.onBackNomalState(),this.lastAction="cancel",this.dependentData&&$(this.dependentData).each((function(){this.cleanDependentBuffer()})),this.batchServiceData=[]},this.removeODataFields=function(t){for(var s in t)t.hasOwnProperty(s)&&t[s]&&t[s].__deferred&&delete t[s];return t},this.retrieveDefaultValues=function(t,s){if(this.isEventData()||this.isLocalData()||this.isOfflineMode())this.$scope.safeApply(function(){this.active={},(this.isLocalData()||this.isOfflineMode())&&(this.active[this.keys[0]]=this.uuidv4()),this.updateWithParams(),s&&s()}.bind(this));else if(t)this.active=t||{},this.updateWithParams(),s&&s();else if(this.entity.indexOf("cronapi")>=0||this.isOData()){var a=this.entity;a+=this.entity.endsWith("/")?"__new__":"/__new__",this.$promise=$httpLegacy({method:"GET",url:this.removeSlash((window.hostApp||"")+a),headers:this.headers}).success(function(t,a,r,o){this.isOData()?(this.active=this.removeODataFields(t.d),this.normalizeData(this.active)):this.active=t,this.updateWithParams(),s&&s()}.bind(this)).error(function(t,a,r,o){this.active={},this.updateWithParams(),s&&s()}.bind(this))}else this.active={},this.updateWithParams(),s&&s()};var updateObjectValue=function(t,s,a){for(var r=s.split("."),o=0;o<r.length;o++){var h=r[o];o==r.length-1?t[h]=a:(void 0!==t[h]&&null!=t[h]||(t[h]={}),t=t[h])}};this.updateWithParams=function(){if(this.parameters){var t=this.getParametersMap();for(var s in t)t.hasOwnProperty(s)&&updateObjectValue(this.active,s,t[s])}},this.resetFieldsStatus=function(){var t=setInterval((function(){$('input[ng-model*="'+this.name+'."]').is(":visible")?($('input[ng-model*="'+this.name+'."]:invalid:empty').removeClass("ng-invalid ng-invalid-required"),clearInterval(t)):$('input[ng-model*="'+this.name+'."].cronMultiSelect')&&clearInterval(t)}),100)},this.noticeStatusChange=function(){this.changeTitle(),this.handleBeforeCallBack(this.onChangeStatus)},this.changeTitle=function(){if($("#starter").length&&$("#starter").attr("primary-datasource")===this.name){var t=this.translate.instant($rootScope.viewTitleOnly),s=$rootScope.systemName&&$rootScope.systemName.length?" - "+$rootScope.systemName:"";this.inserting?t+=" - "+this.translate.instant("Inserting"):this.editing&&(t+=" - "+this.translate.instant("Editing")),$("h1.title:first").text(t),window.document.title=t+s}},this.startInserting=function(t,s){this.retrieveDefaultValues(t,function(){if(this.active.__$id||(this.active.__$id=uuid()),this.children&&this.children.length){let t=this.getKeyValues(this.active);for(let s in t)t.hasOwnProperty(s)&&(null!=t[s]&&null!=t[s]||"_objectKey"!=s||(this.active[s]="$autogenerated$"+this.uuidv4()))}this.inserting=!0,this.onStartInserting&&this.onStartInserting(),s&&s(this.active),this.events.creating&&this.callDataSourceEvents("creating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()}.bind(this))},this.operationPouchDB=function(t,s,a){if(!SyncService.synchronizing&&(this.hasOfflineSupport()||this.isLocalData())&&t&&"GET"!==t){let r=this.getPouchDB();"DELETE"==t?r.get(s._objectKey).then(function(t){return r.remove(t)}.bind(this)).then(a).catch((function(t){console.error(t)})):this.$scope.cronapi.internal.updatePouchDB(r,[s],a)}},this.getPouchDB=function(){return cronapi.internal.getPouchDB(_self.localDBName)},this.isNavigatorOffline=function(){return!navigator.onLine},this.hasOfflineSupport=function(){return this.offline},this.isOfflineMode=function(){return this.isNavigatorOffline()&&this.hasOfflineSupport()},this.startEditing=function(t,s){if(t)this.active=this.copy(t),this.lastActive=t;else{if(0==this.data.length)return void this.startInserting(null,s);this.lastActive=this.active,this.active=this.copy(this.active)}this.editing=!0,s&&s(this.active),this.events.editing&&this.callDataSourceEvents("updating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()},this.removeSilent=function(t,s,a){this.remove(t,null,!1,s,a,!0)},this.remove=function(t,s,a,r,o,h){this.busy=!0;var c=async function(t,s){t||(t=this.active);var h=this.getKeyValues(t,a);s=s||function(s,a,o){if(!o){for(var c=0;c<this.data.length;c++){var l;if(t.__$id&&this.data[c].__$id)l=this.data[c].__$id==t.__$id;else{var d=this.getKeyValues(this.data[c]);for(var u in h)if(h.hasOwnProperty(u)){if(!d[u]||d[u]!==h[u]){l=!1;break}l=!0}}if(l){if(this.dependentLazyPost||this.batchPost){var p={};this.copy(this.data[c],p),p.__status="deleted",p.__originalIdx=c,this.events.memorydelete&&this.callDataSourceEvents("memorydelete",p),"inserted"!=this.data[c].__status&&(this.postDeleteData||(this.postDeleteData=[]),this.postDeleteData.push(p),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData))}this.data.splice(c,1);var f=c-1;f<0&&(f=0),f>this.data.length-1&&(f=this.data.length),this.data[f]?(this.active=this.data[f],this.cursor=f):(this.active=null,this.cursor=-1),this.onBackNomalState();break}}this.handleAfterCallBack(this.onAfterDelete),r&&r(t),this.events.delete&&a&&this.callDataSourceEvents("delete",t)}}.bind(this),await this.handleBeforeCallBack(this.onBeforeDelete)&&(!this.dependentLazyPost&&!this.batchPost||a?service.remove(this.getDeletionURL(t,a),t).$promise.error(o).then(s):s())}.bind(this);if(!a&&!h&&this.deleteMessage&&this.deleteMessage.length>0){let a={title:this.translate.instant("yes"),value:function(){c(t,s)}},r=[{title:this.translate.instant("no"),primaryValue:"true",value:()=>{this.filter()}},a];window.cronapi.notification.confirmDialogAlert("warning",this.translate.instant("Users.view.Confirmacao"),this.deleteMessage,r)}else c(t,s)},this.getKeyValues=function(rowData,forceOriginalKeys,useKeys){for(var keys=useKeys||this.keys,keyValues={},i=0;i<keys.length;i++){var key=keys[i],rowKey=null;try{rowKey=Array.isArray(rowData)?eval("rowData[0]."+key):eval("rowData."+key)}catch(t){}keyValues[key]=rowKey}return keyValues}.bind(this),this.getFirstKeyValue=function(rowData,forceOriginalKeys){for(var keys=this.keys,keyValues={},i=0;i<this.keys.length;i++){var key=this.keys[i],rowKey=null;try{rowKey=eval("rowData."+key)}catch(t){}return rowKey}}.bind(this),this.objectIsEquals=function(t,s){var a=this.getKeyValues(t),r=this.getKeyValues(s);for(var o in a)if(a.hasOwnProperty(o)){if(!r.hasOwnProperty(o))return!1;if(a[o]!==r[o])return!1}return!0},this.hasNext=function(){return this.data&&this.cursor<this.data.length-1},this.hasPrevious=function(){return this.data&&this.cursor>0},this.order=function(t){this._savedProps.order=t},this.getActiveValues=function(){return this.active&&!this._activeValues&&$rootScope.$watch(function(t){return this.active}.bind(this),function(t,s){this._activeValues=this.getRowValues(this.active)}.bind(this),!0),this._activeValues},this.__defineGetter__("activeValues",(function(){return _self.getActiveValues()})),this.getRowValues=function(t){var s=[];for(var a in t)t.hasOwnProperty(a)&&s.push(t[a]);return s},this.next=function(){return this.hasNext()||this.nextPage(),this.active=this.copy(this.data[++this.cursor],{}),this.active},this.nextPage=function(t){var s=(window.hostApp||"")+this.entity;this.hasNextPage()?(1==this.apiVersion||-1==s.indexOf("/cronapi/")?this.offset=parseInt(this.offset)+parseInt(this.rowsPerPage):this.offset=parseInt(this.offset)+1,this._savedProps&&this._savedProps.params&&delete this._savedProps.params.$skip,this.fetch(this._savedProps,{success:function(a){(!a||a.length<parseInt(this.rowsPerPage))&&(1!=this.apiVersion&&-1!=s.indexOf("/cronapi/")||(this.offset=parseInt(this.offset)-this.data.length)),t&&t()},canceled:function(){t&&t()},error:function(){t&&t()}},!0)):t&&t()},this.prevPage=function(){this.append||this.preppend||(this.offset=parseInt(this.offset)-this.data.length,this._savedProps&&this._savedProps.params&&delete this._savedProps.params.$skip,this.offset<0?this.offset=0:this.offset>=0&&this.fetch(this._savedProps,{success:function(t){t&&0!==t.length||(this.offset=0)}},!0))},this.hasNextPage=function(){return this.hasMoreResults&&-1!=this.rowsPerPage},this.hasPrevPage=function(){return this.offset>0&&!this.append&&!this.prepend},this.previous=function(){if(!this.hasPrevious())throw"Dataset Overflor Error";return this.active=this.copy(this.data[--this.cursor],{}),this.active},this.findObjInDs=function(t,s){var a=!1,r=null;if(null==t)return r;var o=null,h=null;let c=s=>{var r=this.data[s];for(var o in l)a=!(!t.hasOwnProperty(o)||t[o]!==r[o]);return a};if("object"==typeof t&&null!==t){var l;this.data.length>0&&(l=this.getKeyValues(this.data[0]));for(var d=0;d<this.data.length;d++)if(t.__$id&&this.data[d].__$id&&(a=t.__$id==this.data[d].__$id)||(a=c(d)),a){o=d,h=this.copy(this.data[o],{});var u=this.getKeyValues(this.data[o]),p=!0;for(var f in u)if(void 0===u[f]){p=!1;break}p||this.fetchChildren()}}else if(Array.isArray(this.keys))for(d=0;d<this.data.length;d++)this.data[d][this.keys[0]]===t&&(o=d,h=this.copy(this.data[o],{}),a=!0);return null!==h&&(r=h,s&&(r={cursor:o,obj:h})),r},this.goTo=function(t,s){var a=this.findObjInDs(t,!0);return null!==a?(this.cursor=a.cursor,this.active=a.obj,this.active):a},this.getCursor=function(){return this.cursor},this.filter=function(t,s){var a=this.offset;this.offset=0,this.fetch({path:t},{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=a},success:function(t){s&&s(t)}})},this.doSearchAll=function(t,s){this.searchTimeout=null;var a=this.offset;this.offset=0,this.fetch({params:{filter:"%"+t+"%",filterCaseInsensitive:!!s}},{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=a}})},this.searchAll=function(t,s){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.searchTimeout=setTimeout(function(){this.doSearchAll(t,s)}.bind(this),500)},this.doSearch=function(t,s){this.searchTimeout=null;var a,r=this.offset;this.offset=0,this.isOData()?(a={params:{$filter:t}},null!=t&&0!=t.length||(a={})):a={params:{filter:t,filterCaseInsensitive:!!s}},this.fetch(a,{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=r}})},this.search=function(t,s){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.caseInsensitive=s,this.terms=t,this.searchTimeout=setTimeout(function(){this.doSearch(t,s)}.bind(this),500)},this.refresh=function(t,s,a){this.cleanup(),void 0===a&&(a=0),t.length>=a&&this.filter(s+"/"+t)},this.cleanup=function(t){t||(t={}),this.offset=0,this.rowsCount=-1,this.data.length=0,t.ignoreAtive||(this.cursor=-1,this.active={}),this.hasMoreResults=!1},this.current=function(){return this.active||this.data[0]},this.getLink=function(t){if(this.links)for(var s=0;s<this.links.length;s++)if(this.links[s].rel==t)return this.links[s].href},this.isOData=function(){return this.entity.indexOf("odata")>0},this.isEventData=function(){return void 0!==this.onGET&&null!==this.onGET&&""!==this.onGET},this.isLocalData=function(){return 0==this.entity.indexOf("local://")},this.normalizeValue=function(t,s,a){return null!=s&&null!=s||(s=!1),window.oDataToObj(t,s,a)},this.normalizeObject=function(t){for(var s in t)if(t.hasOwnProperty(s)){var a=t[s];if(a)if("object"==typeof a)this.normalizeObject(a);else{let r=this.getFieldFromSchema(s);t[s]=this.normalizeValue(a,void 0,r)}}},this.normalizeData=function(t){if(t){delete t.__metadata;for(var s=0;s<t.length;s++)this.normalizeObject(t[s])}return t},this.getAllData=function(){var t=[];if(t=t.concat(this.data),this.memoryData)for(key in this.memoryData)if(this.memoryData.hasOwnProperty(key)){var s=this.memoryData[key];s.data&&(t=t.concat(s.data))}return this.postDeleteData&&(t=t.concat(this.postDeleteData)),t},this.getParametersMap=function(parentId){var map={},parameters,obj,mapParams;if(parentId){parameters=this.parametersExpression;for(var arr=eval(this.dependentLazyPost).getAllData(),i=0;i<arr.length;i++)if(arr[i].__$id==parentId){obj=arr[i];break}mapParams=this.getParametersMap()}else parameters=this.parameters;if(parameters&¶meters.length>0)for(var parts=parameters.split(";"),i=0;i<parts.length;i++){var part=parts[i],binary=part.split("=");if(2==binary.length){var value=binary[1];if(parentId)if(binary[1].match(DEP_PATTERN)){var g=DEP_PATTERN.exec(value);if(-1!=g[1].indexOf(".active.")){var field=g[1].replace(this.dependentLazyPost+".active.","");obj&&(map[binary[0]]=obj[field])}else map[binary[0]]=mapParams[binary[0]]}else map[binary[0]]=mapParams[binary[0]];else map[binary[0]]=binary[1]?this.normalizeValue(value,!0):null}}return map},this.setParameters=function(t){this.parameters=t,this.fetch({params:{}})},this.getParametersBatchExpression=function(parentId){var expression="",parameters,obj;parameters=this.parametersExpression;let ds=eval(this.dependentLazyPost);if(ds){var arr=ds.getAllData();if(ds.active&&ds.active.__$id==parentId)obj=ds.active;else for(var i=0;i<arr.length;i++)if(arr[i].__$id==parentId){obj=arr[i];break}}if(parameters&¶meters.length>0)for(var parts=parameters.split(";"),i=0;i<parts.length;i++){var part=parts[i],binary=part.split("=");if(2==binary.length){var value=binary[1];if(binary[1].match(DEP_PATTERN)){var g=DEP_PATTERN.exec(value);if(-1!=g[1].indexOf(".active.")){var field=g[1].replace(this.dependentLazyPost+".active.","");obj&&(""!=expression&&(expression+=","),expression+=binary[0]+":$"+parentId+"."+field)}}}}return expression},this.removeSlash=function(t){return 0==t.indexOf("http://")?"http://"+t.substring(7).split("//").join("/"):0==t.indexOf("https://")?"https://"+t.substring(8).split("//").join("/"):t},this.setDataSourceEvents=function(t){this.events=t},this.addDataSourceEvents=function(t){for(var s in t)t.hasOwnProperty(s)&&(this.events[s]||(this.events[s]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[s])&&(this.events[s]=[this.events[s]]),this.events[s].push(t[s]))},this.removeDataSourceEvents=function(t){for(var s in t)if(t.hasOwnProperty(s)){this.events[s]||(this.events[s]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[s])&&(this.events[s]=[this.events[s]]);for(var a=[].concat(this.events[s]),r=0;r<a.length;r++)a[r]==t[s]&&this.events[s].splice(r,1)}},this.callDataSourceEvents=function(t,s){if(this.events){var a=this.events[t];if(a){"[object Array]"!==Object.prototype.toString.call(a)&&(a=[a]);for(var r=[],o=1;o<arguments.length;o++)r.push(arguments[o]);var h=[];for(o=0;o<a.length;o++)h.push(a[o]);for(var c=0;c<h.length;c++)try{h[c].apply(null,r)}catch(t){console.log("Error","Event no more exist in datasource")}}}},this.storeInMemory=function(t){this.memoryData||(this.memoryData={});var s={data:[],cursor:this.cursor,params:this.getParametersMap(),rowCount:this.getRowsCount()};s.data=deepCopy(this.data,s.data),this.memoryData[t]=s},this.restoreFromMemory=function(t){this.memoryData||(this.memoryData={});var s=this.memoryData[t];return s&&(this.cursor=s.cursor,this.rowsCount=s.rowCount),delete this.memoryData[t],deepCopy(s.data)},this.hasPendingChanges=function(){var t=this.hasMemoryData;return this.children&&$(this.children).each((function(){t=t||this.hasPendingChanges()})),t},this.isPostingBatchData=function(){var isPosting=1==this.postingBatch;return this.dependentLazyPost&&(isPosting=isPosting||eval(this.dependentLazyPost).isPostingBatchData()),isPosting},this.fetchChildren=function(t){this.children?reduce(this.children,function(t,s){t.fetch({},(function(){s()}))}.bind(this),function(){t&&t()}.bind(this)):t&&t()};var splitExpression=function(t){var s,a=null;-1!=t.indexOf("@=")?(a=t.trim().split("@="),s="="):-1!=t.indexOf("<=")?(a=t.trim().split("<="),s="<="):-1!=t.indexOf(">=")?(a=t.trim().split(">="),s=">="):-1!=t.indexOf(">")?(a=t.trim().split(">"),s=">"):-1!=t.indexOf("<")?(a=t.trim().split("<"),s="<"):(a=t.trim().split("="),s="=");var r=typeof this.normalizeValue(a[1],!0);return this.isOData()?"="==s&&"string"==r?"startswith(tolower("+a[0]+"), "+a[1].toLowerCase()+")":"="==s?a[0]+" eq "+a[1]:"!="==s?a[0]+" ne "+a[1]:">"==s?a[0]+" gt {"+a[1]:">="==s?a[0]+" ge "+a[1]:"<"==s?a[0]+" lt "+a[1]:"<="==s?a[0]+" le "+a[1]:void 0:"string"==r?a[0]+"@"+s+"%"+a[1]+"%":a[0]+s+a[1]}.bind(this),parseFilterExpression=function(t){var s="";if(t){var a=t.split(";"),r=!0;if(a.length>0)for(var o=/[\w\d]+=.+/gm,h=0;h<a.length;h++){if(!a[h].match(o)){r=!1;break}}if(r)for(h=0;h<a.length;h++){var c=splitExpression(a[h]);""!=s&&(s+=this.isOData()?" and ":";"),s+=c}else s=t}return s}.bind(this),getQueryOperator=function(t){return"="==t?" eq ":"!="==t?" ne ":">"==t?" gt ":">="==t?" ge ":"<"==t?" lt ":"<="==t?" le ":void 0}.bind(this),executeRight=function(right){var result="";if(null!=right&&null!=right)if(right.startsWith(":")||right.startsWith("datetimeoffset'")||right.startsWith("datetime'"))result=right;else{if(right&&"string"==typeof right&&right.length>=2&&("'"==right.charAt(0)&&"'"==right.charAt(right.length-1)||'"'==right.charAt(0)&&'"'==right.charAt(right.length-1)))try{result=eval("'"+right.substring(1,right.length-1).replaceAll("'","\\'")+"'")}catch(e){result=eval(right)}else""!=right&&(result=eval(right));result instanceof Date?result="datetimeoffset'"+result.toISOString()+"'":"string"==typeof result?result="'"+result+"'":void 0!==result&&null!=result||(result="null")}return result}.bind(this);this.isEmpty=function(t){return""===t||null==t||"''"===t},this.getFieldFromSchema=function(t){if(this.schema)for(var s=0;s<this.schema.length;s++)if(this.schema[s].name===t)return this.schema[s].type;return null},this.parserCondition=function(t,s,a){var r="",o=t.type;if(s||(s="default"),t.args)for(var h=0;h<t.args.length;h++){var c=t.args[h],l=o;if(c.args&&c.args.length>0){var d=this.parserCondition(c,s);!this.isEmpty(d)||"ignore"!=s&&"clean"!=s?this.isEmpty(d)||(a&&(a.count=a.count?a.count+1:1),""!=r&&(r+=" "+l.toLowerCase()+" "),r+="( "+d+" ) "):a&&(a.clean="clean"==s)}else{d=executeRight(c.right);if(!this.isEmpty(d)||"ignore"!=s&&"clean"!=s&&"wait"!=s){if(!this.isEmpty(d)){var u=!0,p=void 0;if("DateTime"===this.getFieldFromSchema(c.left)&&-1===d.indexOf("datetime")&&(u=(p=this.$scope.cronapi.dateTime.getMomentObj(d)).isValid()),u)if(a&&(a.count=a.count?a.count+1:1),""!=r&&(r+=" "+l.toLowerCase()+" "),"%"==c.type)this.isLocalData()?r+="contains("+c.left+", "+d.toLowerCase()+")":r+="substringof("+d.toLowerCase()+", tolower("+c.left+"))";else if(p){var f=p.toDate().getTimezoneOffset(),v=timeZoneOffset-f;p.add(v,"minutes"),r+=c.left+getQueryOperator(c.type)+"datetimeoffset'"+p.toISOString()+"'"}else r+=c.left+getQueryOperator(c.type)+d;else"null"===d&&(r+=`${c.left} ${getQueryOperator(c.type)} null`)}}else a&&(a.clean="clean"==s,a.wait="wait"==s)}}return r.trim()}.bind(this),this.refreshData=function(t){if(!this.lastFetch||this.hasMemoryData||!this.enabled||this.inserting||this.editing)t&&t();else{window.Pace&&(window.Pace.options.ajax.trackWebSockets=!1,window.Pace.options.ajax.trackMethods=[]);var s=function(){window.Pace&&(window.Pace.options.ajax.trackWebSockets=!0,window.Pace.options.ajax.trackMethods=["PUT","POST","GET"]),t&&t()},a={success:s,error:s};this.lastFilter=null,this.lastFetch.fetchOptions=this.lastFetch.fetchOptions||{},this.lastFetch.fetchOptions.active=this.copy(this.active),this.lastFetch.fetchOptions.active.__$id=void 0,this.fetch(this.lastFetch.properties,a,this.lastFetch.isNextOrPrev,this.lastFetch.fetchOptions,!0)}},this.startAutoRefresh=function(){this.autoRefresh>0&&setTimeout(function(){this.refreshData(function(){this.startAutoRefresh()}.bind(this))}.bind(this),this.autoRefresh)},this.isParentBusy=function(){return!!this.dependentLazyPost&&(eval(this.dependentLazyPost).busy||eval(this.dependentLazyPost).isParentBusy())},this.fetch=function(properties,callbacksObj,isNextOrPrev,fetchOptions,silent,fromVisibleEvent){fetchOptions||(fetchOptions={});let busy=this.busy,masterDetail=this.parameters&&this.parameters.length>0;if(fetchOptions.ignoreBusy&&(busy=!1),busy||this.postingBatch||!masterDetail&&this.isParentBusy())return void setTimeout(function(){this.fetch(properties,callbacksObj,isNextOrPrev,fetchOptions)}.bind(this),1e3);var callbacks=callbacksObj||{};this.lastFetch={properties:properties,isNextOrPrev:isNextOrPrev,fetchOptions:fetchOptions};var sucessHandler=function(data,headers,raw){var springVersion=!1;this.responseHeaders=headers||{};var total=-1;this.entity.indexOf("//")>-1&&this.entity.indexOf("://")<0&&(data=[]),raw||(data?"[object Array]"!==Object.prototype.toString.call(data)&&(data&&data.links&&"[object Array]"===Object.prototype.toString.call(data.content)?(this.links=data.links,data=data.content,springVersion=!0):this.isOfflineMode()?(total=data.total_rows,data=this.$scope.cronapi.internal.normalizePouchDBData(data.rows,!0)):this.isOData()?(total=parseInt(data.d.__count),data=data.d.results,this.normalizeData(data)):this.isLocalData()?(total=data.total_rows,data=data.rows,this.normalizeData(data)):data=[data]):data=[]);for(var n=0;n<data.length;n++)data[n].__$id||(data[n].__$id=uuid());if(!fetchOptions.lookup&&(this.fetched=!0,callbacks.beforeFill&&callbacks.beforeFill.apply(this,this.data),isNextOrPrev?(this.prepend&&Array.prototype.unshift.apply(this.data,data),this.append&&Array.prototype.push.apply(this.data,data),this.prepend||this.append||(Array.prototype.push.apply(this.data,data),fetchOptions.ignoreAtive||(this.data.length>0?fetchOptions.active?this.goTo(fetchOptions.active):this.$scope.safeApply((()=>{this.active=data[0],this.cursor=0})):(this.active={},this.cursor=-1)))):(this.cleanup(fetchOptions),-1!=total&&(this.rowsCount=total),Array.prototype.push.apply(this.data,data),this.data.length>0&&(fetchOptions.ignoreAtive||(fetchOptions.active?this.goTo(fetchOptions.active):this.$scope.safeApply((()=>{this.active=data[0],this.cursor=0}))))),this.columns=[],this.data.length>0))for(var i=0;i<this.data[0].length;i++)this.columns.push(this.getColumn(i));if(callbacks.success&&callbacks.success.call(this,data),!fetchOptions.lookup){this.events.read&&this.callDataSourceEvents("read",data),this.hasMoreResults=data.length>=this.rowsPerPage,springVersion&&(this.hasMoreResults=null!=this.getLink("next")),this.isOfflineMode()&&(this.hasMoreResults=!1),this.autoPost&&this.startAutoPost(),this.loaded=!0,this.loadedFinish=!0,this.lastLoadedTime=Date.now(),this.handleAfterCallBack(this.onAfterFill);var thisDatasourceName=this.name;this.isOData()||$("datasource").each((function(idx,elem){var dependentBy=null,dependent=window[elem.getAttribute("name")];if(dependent&&""!==elem.getAttribute("dependent-by")&&null!=elem.getAttribute("dependent-by")){try{dependentBy=JSON.parse(elem.getAttribute("dependent-by"))}catch(ex){dependentBy=eval(elem.getAttribute("dependent-by"))}dependentBy?dependentBy.name==thisDatasourceName&&(dependent.filterURL||eval(dependent.name).fetch()):console.log("O dependente "+elem.getAttribute("dependent-by")+" do pai "+thisDatasourceName+" ainda não existe.")}}))}if("insert"==this.startMode&&(this.startMode=null,this.startInserting()),"edit"==this.startMode&&(this.startMode=null,this.startEditing()),this.autoRefresh>0&&!this.autoRefreshStarted&&(this.autoRefreshStarted=!0,this.startAutoRefresh()),!this.isOfflineMode()&&this.hasOfflineSupport()){var db=this.getPouchDB();this.$scope.cronapi.internal.updatePouchDB(db,data)}}.bind(this);if(this.busy)return void(callbacks.canceled&&callbacks.canceled());if(this.entity.indexOf("//")>-1&&this.entity.indexOf("://")<0)return void(callbacks.canceled&&callbacks.canceled());if(!this.enabled)return this.cleanup(),void(callbacks.canceled&&callbacks.canceled());var props=properties||{};props.params=props.params||{};var resourceURL=(window.hostApp||"")+this.entity+(props.path||this.lastFilterParsed||""),filter="",order="",cleanData=!1,canProceed=!0,urlParams;if(this.parameters&&this.parameters.length>0){var parsedParameters;parsedParameters=fetchOptions.lookup?this.$interpolate(this.parametersExpression)(this.$scope):this.parameters;for(var parts=parsedParameters.split(";"),partsExpression=this.parametersExpression.split(";"),i=0;i<parts.length;i++){var part=parts[i],partExpression=partsExpression[i],binary=part.split("="),binaryExpression=partExpression.split("=");if(2==binary.length){var filterClause,g=DEP_PATTERN.exec(binaryExpression[1]);if((this.isEmpty(binary[1])||this.isAutoGeneratedValue(binary[1]))&&this.dependentLazyPost&&g[1]&&g[1].startsWith(this.dependentLazyPost+".")){if("clean"==this.parametersNullStrategy||"default"==this.parametersNullStrategy){cleanData=!0;var dds=eval(this.dependentLazyPost);filterClause=dds.active&&dds.active.__$id?eval(this.dependentLazyPost).active.__$id:"memory"}}else this.isEmpty(binary[1])?"clean"!=this.parametersNullStrategy&&"default"!=this.parametersNullStrategy||(filterClause="null",cleanData=!0):filterClause=this.getObjectAsString(this.normalizeValue(binary[1],!0),!1);filterClause&&(filterClause=binary[0]+getQueryOperator("=")+filterClause,""!=filter&&(filter+=this.isOData()?" and ":";"),filter+=filterClause)}}}if(!canProceed)return void(callbacks.canceled&&callbacks.canceled());let waitData=!1;if(this.condition){try{var parsedCondition;parsedCondition=fetchOptions.lookup?this.$interpolate(this.conditionExpression)(this.$scope):this.condition;var obj=JSON.parse(parsedCondition);if("object"==typeof obj){var resultData={};obj.expression?this.conditionOdata=this.parserCondition(obj.expression,this.parametersNullStrategy,resultData):this.conditionOdata=this.parserCondition(obj,this.parametersNullStrategy,resultData);var filterCount=0;let t=this.conditionExpression.match(/{{(?!null).*?}}/g);if(t&&(filterCount=t.length),!cleanData&&resultData.clean&&(cleanData=!0),!cleanData&&resultData.wait&&(waitData=!0),cleanData||"one"!==this.loadDataStrategy||resultData.count&&!(resultData.count<1)||(cleanData=!0),!cleanData&&"all"===this.loadDataStrategy&&filterCount&&(!resultData.count||resultData.count<filterCount)&&(cleanData=!0),cleanData||"button"!==this.loadDataStrategy||"button"===fetchOptions.origin||(cleanData=!0),obj.params)for(var i=0;i<obj.params.length;i++){var value=obj.params[i].fieldValue;value.length>=2&&"'"==value.charAt(0)&&"'"==value.charAt(value.length-1)&&(value=value.substring(1,value.length-1)),""!==value&&null!=value&&(props.params[obj.params[i].fieldName]=value)}}else this.conditionOdata=this.condition}catch(t){console.log(t)}var conditionFilter=parseFilterExpression(this.conditionOdata);conditionFilter&&(""!=filter&&(filter+=this.isOData()?" and ":";"),filter+=conditionFilter)}if(this.orderBy)for(var orders=this.orderBy.split(";"),i=0;i<orders.length;i++){var orderField=orders[i];orderField&&(""!=order&&(order+=this.isOData()?",":";"),this.isOData()?order+=orderField.replace("|ASC"," asc").replace("|DESC"," desc"):order+=orderField)}if(this.dependentLazyPost&&!this.parameters&&!this.condition&&!fromVisibleEvent&&eval(this.dependentLazyPost).active){var checkRequestId="",keyDependentLazyPost=this.getKeyValues(eval(this.dependentLazyPost).active);for(var key in keyDependentLazyPost){checkRequestId=keyDependentLazyPost[key];break}if(checkRequestId&&checkRequestId.length>0&&-1==resourceURL.indexOf(checkRequestId))return void(callbacks.canceled&&callbacks.canceled())}this.rowsPerPage>0&&(this.isOData()?(void 0!==props.params.$top&&null!==props.params.$top||(props.params.$top=this.rowsPerPage),void 0!==props.params.$skip&&null!==props.params.$skip||(props.params.$skip=parseInt(this.offset)*parseInt(this.rowsPerPage)),props.params.$inlinecount="allpages"):1==this.apiVersion||-1==resourceURL.indexOf("/cronapi/")?(props.params.limit=this.rowsPerPage,props.params.offset=this.offset):(props.params.size=this.rowsPerPage,props.params.page=this.offset));var paramFilter=null;this.isOData()&&props.params.$filter&&(paramFilter=props.params.$filter),!this.isOData()&&props.params.filter&&(paramFilter=props.params.filter),paramFilter&&(filter&&""!=filter?this.isOData()?(filter+=" and (",filter+=paramFilter+")"):(filter+=";",filter+=paramFilter):filter=paramFilter);var paramOrder=null,localSuccess;if(this.isOData()&&props.params.$orderby&&(paramOrder=props.params.$orderby),!this.isOData()&&props.params.order&&(paramOrder=props.params.order),paramOrder&&(order=paramOrder),filter&&(this.isOData()?props.params.$filter=filter:props.params.filter=filter),order&&(this.isOData()?props.params.$orderby=order:props.params.order=order),this.hasMemoryData&&filter){if(this.memoryData||(this.memoryData={}),this.lastFilter==filter)return void(callbacks.canceled&&callbacks.canceled());var id=filter,mem=this.memoryData[id];if(mem){this.storeInMemory(this.lastFilter);var data=this.restoreFromMemory(id);return this.lastFilter=filter,void sucessHandler(data,null,!0)}localSuccess=function(){this.storeInMemory(this.lastFilter)}.bind(this)}if(this.stopAutoPost(),this._savedProps=props,waitData)return void setTimeout(function(){fetchOptions.ignoreBusy=!0,this.fetch(properties,callbacksObj,isNextOrPrev,fetchOptions)}.bind(this),100);if(cleanData)return localSuccess&&localSuccess(),this.lastFilter=filter,void sucessHandler([],null,!0);this.busy=!0;var httpError=function(t,s,a,r){this.busy=!1,silent||this.handleError(t),callbacks.error&&callbacks.error.call(this,t)}.bind(this);let callService=function(){this.$promise=this.getService("GET")({method:"GET",url:this.removeSlash(resourceURL),params:props.params,headers:this.headers,filter:filter,offlineMode:this.isOfflineMode()}).success(function(t,s,a,r){localSuccess&&localSuccess(),this.lastFilter=filter,this.busy=!1,sucessHandler(t,a?a():null)}.bind(this)).error(function(t,s,a,r){httpError(t,s,a,r)}.bind(this))}.bind(this);this.fetchOnVisible&&!this.parent.is(":visible")?this.holdServiceCall=callService:(this.holdServiceCall=void 0,callService())},this.getRowsCount=function(){return-1!=this.rowsCount?this.rowsCount:this.data.length},this.notifyObservers=function(){for(var t in this.observers)if(this.observers.hasOwnProperty(t)){var s=this.observers[t];$timeout(function(){s.notify.call(s,this.active)}.bind(this),1)}},this.notify=function(t){if(t){var s=this.watchFilter;s=s.replace(/\{([A-z][A-z|0-9]*)\}/gim,(function(s,a){return t.hasOwnProperty(a)?t[a]:""})),this.fetch({params:{q:s}})}},this.addObserver=function(t){this.observers.push(t)},this.sum=function(t){for(var s=0,a=0;a<this.data.length;a++)this.data[a][t]&&(s+=this.data[a][t]);return s},this.copy=function(t,s,a){if(null===t||"[object Object]"!==Object.prototype.toString.call(t))return t;for(var r in s=s||{},t)t.hasOwnProperty(r)&&-1==r.indexOf("$$")&&(s[r]=this.copy(t[r]));if(a)for(var o=0;o<this.keys.length;o++){var h=s[r=this.keys[o]];""!=h&&null!=h||delete s[r]}return s};var deepCopyArray=function(t,s){if(null===t||"[object Array]"!==Object.prototype.toString.call(t))return t;s=s||[];for(var a=0;a<t.length;a++)s.push(deepCopy(t[a]));return s},deepCopy=function(t,s){if("[object Array]"===Object.prototype.toString.call(t))return deepCopyArray(t,s);if(null===t||"[object Object]"!==Object.prototype.toString.call(t))return t;for(var a in s=s||{},t)t.hasOwnProperty(a)&&(s[a]=deepCopy(t[a]));return s};if(this.startAutoPost=function(){this.unregisterDataWatch=$rootScope.$watch(function(){return this.data}.bind(this),function(t,s){if(this.enabled){var a=t.length-s.length;if(a>0)for(var r=1;r<=a;r++)this.insert(t[t.length-r],(function(){}));else if(a<0){var o=this,h=s.filter((function(s){return 0==t.filter((function(t){return o.objectIsEquals(s,t)})).length}));for(r=0;r<h.length;r++)this.remove(h[r],(function(){}))}}else this.unregisterDataWatch()}.bind(this))},this.stopAutoPost=function(){this.unregisterDataWatch&&(this.unregisterDataWatch(),this.unregisterDataWatch=void 0)},this.hasDataBuffered=function(){return!!(this.dependentBufferLazyPostData&&this.dependentBufferLazyPostData.length>0)},window.afterDatasourceCreate){var args=[$q,$timeout,$rootScope,$window,Notification];window.afterDatasourceCreate.apply(this,args)}this.init()};return this.storeDataset=function(t){this.datasets[t.name]=t},this.initDataset=function(props,scope,$compile,$parse,$interpolate,instanceId,translate){var endpoint=props.endpoint?props.endpoint:"",dts=new DataSet(props.name,scope,props.fetchOnVisible);let canStoreDataset=!0;$rootScope[props.name]&&!$rootScope[props.name].insideModal&&props.insideModal?(canStoreDataset=!1,console.log(`%c${translate.instant("Datasource.Error").toUpperCase()} - ${translate.instant("Datasource.Duplicate").toUpperCase()}${props.name.toUpperCase()}`,"background: #000; color: #FFF; font-size:14px;")):($rootScope[props.name]=dts,window[props.name]=dts,$rootScope[props.name+".instanceId"]=instanceId);var defaultApiVersion=1;if(dts.entity=props.entity,dts.localDBName=props.entity,!isCronapiApiPath(dts.entity))if(dts.entity.match(DS_ID))dts.entity="api/cronapi/odata/v2/"+dts.entity.replaceAll(".","/");else if(dts.isLocalData()){var path=dts.entity.substring(dts.entity.indexOf("//")+2,dts.entity.length).split("/");dts.localDBType=dts.entity.substring(0,dts.entity.indexOf("://")),dts.localDBName=path[0],dts.localDBStorage=path[1],dts.localDBVersion=path[2]||1}if(app&&app.config&&app.config.datasourceApiVersion&&(defaultApiVersion=app.config.datasourceApiVersion),dts.translate=translate,dts.apiVersion=props.apiVersion?parseInt(props.apiVersion):defaultApiVersion,dts.keys=props.keys&&props.keys.length>0?props.keys.split(","):[],dts.rowsPerPage=props.rowsPerPage?props.rowsPerPage:100,dts.append=props.append,dts.prepend=props.prepend,dts.endpoint=props.endpoint,dts.filterURL=props.filterURL,dts.autoPost=props.autoPost,dts.autoRefresh=props.autoRefresh,dts.deleteMessage=props.deleteMessage,dts.enabled=props.enabled,dts.offset=props.offset?props.offset:0,dts.onError=props.onError,dts.defaultNotSpecifiedErrorMessage=props.defaultNotSpecifiedErrorMessage,dts.onAfterFill=props.onAfterFill,dts.onBeforeCreate=props.onBeforeCreate,dts.onAfterCreate=props.onAfterCreate,dts.onBeforeUpdate=props.onBeforeUpdate,dts.onAfterUpdate=props.onAfterUpdate,dts.onBeforeDelete=props.onBeforeDelete,dts.onAfterDelete=props.onAfterDelete,dts.onChangeStatus=props.onChangeStatus,dts.onGET=props.onGet,dts.onPOST=props.onPost,dts.onPUT=props.onPut,dts.onDELETE=props.onDelete,dts.dependentBy=props.dependentBy,dts.parameters=props.parameters,dts.parametersNullStrategy=props.parametersNullStrategy,dts.parametersExpression=props.parametersExpression,dts.checkRequired=props.checkRequired,dts.batchPost=props.batchPost,dts.condition=props.condition,dts.conditionExpression=props.conditionExpression,dts.orderBy=props.orderBy,dts.schema=props.schema,dts.startMode=props.startMode,dts.lazy=props.lazy,dts.$compile=$compile,dts.$parse=$parse,dts.$interpolate=$interpolate,dts.loadDataStrategy=props.loadDataStrategy,dts.offline=props.offline,dts.insideModal=props.insideModal,props.dependentLazyPost&&props.dependentLazyPost.length>0&&(dts.dependentLazyPost=props.dependentLazyPost,setTimeout((()=>{eval(dts.dependentLazyPost).addDependentDatasource(dts)}),0)),dts.dependentLazyPostField=props.dependentLazyPostField,dts.headers=props.headers,canStoreDataset&&this.storeDataset(dts),dts.allowFetch=!0,dts.dependentBy&&""!==dts.dependentBy&&""!==dts.dependentBy.trim()){dts.allowFetch=!1;var dependentBy=null;try{dependentBy=JSON.parse(dependentBy)}catch(ex){dependentBy=eval(dependentBy)}dependentBy&&dependentBy.loadedFinish&&(dts.allowFetch=!0)}if(!props.lazy&&dts.allowFetch&&"[object String]"!==Object.prototype.toString.call(props.watch)&&!props.filterURL){var queryObj={};setTimeout(function(){dts.fetch({params:queryObj},{success:function(t){t&&t.length>0&&(this.active=t[0],this.cursor=0)}})}.bind(this),0)}return props.lazy&&props.autoPost&&dts.startAutoPost(),props.watch&&"[object String]"===Object.prototype.toString.call(props.watch)&&(this.registerObserver(props.watch,dts),dts.watchFilter=props.watchFilter),props.filterURL&&props.filterURL.length>0&&dts.allowFetch&&dts.filter(props.filterURL),dts},this.registerObserver=function(t,s){this.datasets[t].addObserver(s)},this}]).directive("datasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate",function(t,s,a,r,o,h,c,l,d){return{restrict:"E",priority:9999999,scope:!0,template:"",link:function(t,s,a){!function(t,a,r){$(t).each((function(){var t=$(this),o=$(document.createElement(r),{html:t.html()});$.each(this.attributes,(function(){o.attr(this.name,this.value)})),o.attr("inside-modal",$(s).closest(".modal").length>0);var h=t.data("events");if(h)for(var c in h)for(var d in h[c])o[c](h[c][d].handler);l(o)(a),t.replaceWith(o)}))}(s,t,"cronapp-datasource")}}}]);let datasourceRepeat=1;app.directive("crnRepeat",["DatasetManager","$compile","$parse","$injector","$rootScope",function(DatasetManager,$compile,$parse,$injector,$rootScope){return{restrict:"A",priority:9999998,terminal:!0,link:function(scope,element,attrs,controllers,transclude){const indexAttribute=(t,s,a)=>{let r=t.parent().find(`[data-repeater=${s}]`);r.each&&r.each(((t,s)=>{$(s).find(`[${a}]`).each(((s,r)=>{let o=$(r),h=`${o.attr(`${a}`)}-cronapp-${t}`;o.attr(`${a}`,h)}))}))};$(window).ready((()=>{datasourceRepeat++;let isDatasource=!1,dataRepeaterId=`datasourceRepeat${datasourceRepeat}`;if(attrs.crnRepeat){if(scope.data=DatasetManager.datasets,scope.data[attrs.crnRepeat])scope[dataRepeaterId]=scope.data[attrs.crnRepeat],isDatasource=!0;else{scope[dataRepeaterId]=[];var value=$parse(attrs.crnRepeat)(scope);value instanceof String&&value.startsWith("[")&&value.endsWith("]")&&(value=eval(value)),scope[dataRepeaterId]=value}isDatasource?(element.attr("ng-init",attrs.crnRepeat+" = {}; "+attrs.crnRepeat+".active = rowData"),element.attr("ng-repeat",`rowData in ${dataRepeaterId}.data`)):element.attr("ng-repeat",`rowData in ${dataRepeaterId}`),element.attr("data-repeater",dataRepeaterId)}var tagName=element[0].tagName;$compile(element,null,9999998)(scope);let watchForRepeater=isDatasource?`${dataRepeaterId}.data`:`${dataRepeaterId}`;scope.$watchCollection(watchForRepeater,(function(t,s){"ion-slide"==tagName.toLowerCase()&&$injector.get("$ionicSlideBoxDelegate").update();indexAttribute(element,dataRepeaterId,"id"),indexAttribute(element,dataRepeaterId,"for")}))}))}}}]).directive("crnDatasource",["DatasetManager","$parse","$rootScope",function(t,s,a){return{restrict:"A",scope:!0,priority:9999998,link:function(a,r,o){a.data=t.datasets,a.data[o.crnDatasource]?a.datasource=a.data[o.crnDatasource]:(a.datasource={},a.datasource.data=s(o.crnDatasource)(a))}}}]).directive("cronappDatasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate","SyncService",function(t,s,a,r,o,h,c,l,d,u){return{restrict:"E",scope:!0,template:"",link:function(u,p,f){initDatasource(u,p,f,t,s,a,r,o,h,c,l,d)}}}]),angular.module("sync.service",[]).service("SyncService",["$http",function(t){let s={start:function(){this.dbSync=this.getSyncServicePouchDB(),this.observeConnection()},observeConnection:async function(){setInterval((()=>this.isNavigatorOffline()||this.synchronizeOfflineData()),15e3)},toQueue:function(t){let s={data:t,created:Date.now()};this.dbSync.post(s).catch((t=>console.error(t)))},synchronizeOnError:async function(t,s,a){this.synchronizing=!1,console.log("Error synchronizing doc",s,"response",t)},synchronizeOnSuccess:async function(t,s){try{await this.dbSync.remove(t),this.removeArray(t,s),s.length>0?this.sendData(s[0],s):this.synchronizing=!1}catch(t){this.synchronizing=!1}},canByPassError:function(t){let s=!1;if(t.data&&t.data.error&&t.data.error.message&&t.data.error.message.value){switch(t.data.error.message.value){case"Não foi possível encontrar a entidade requisitada.":case"Requested entity could not be found.":s=!0}}return s},sendData:async function(s,a){let r=s.data;t(r).then((()=>this.synchronizeOnSuccess(s,a))).catch((t=>this.canByPassError(t)&&this.synchronizeOnSuccess(s,a)||this.synchronizeOnError(t,s,a))),console.log(`Synchronization - sended record number ${a.length}`)},optimizeQueue:function(t){t.rows.filter((t=>"DELETE"===t.doc.data.method)).forEach((async s=>{t.rows.filter((t=>{let a=t.doc.data.originalObject||t.doc.data.rawData,r=s.doc.data.originalObject||s.doc.data.rawData;return a&&r&&a._objectKey===r._objectKey&&"DELETE"!==t.doc.data.method})).forEach((async s=>{this.dbSync.remove(s.doc),this.removeArray(s,t.rows)}))}));let s=[];return t.rows.forEach((t=>s.push(t.doc))),s.sort(((t,s)=>t.created-s.created)),s},synchronizeOfflineData:async function(){try{if(!this.synchronizing){let t=await this.dbSync.allDocs({include_docs:!0,attachments:!0});if(t.rows.length){console.log("Synchronization started"),this.synchronizing=!0;let s=this.optimizeQueue(t);this.sendData(s[0],s)}}}catch(t){console.log(t)}},removeArray(t,s){if(t&&s){let a=s.indexOf(t);a>-1&&s.splice(a,1)}},isNavigatorOffline:function(){return!navigator.onLine},getSyncServicePouchDB:function(){return cronapi.internal.getPouchDB("syncService")},synchronizing:null,dbSync:null,lastStatus:null};return s.start(),s}]);
|
|
1
|
+
var ISO_PATTERN=new RegExp("(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))"),TIME_PATTERN=new RegExp("PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d+)?)?S)?"),DEP_PATTERN=new RegExp("\\{\\{(.*?)\\|raw\\}\\}"),HTTP_STATUS=new RegExp("HTTP\\/1\\.1 (\\d+) (.*)"),DS_ID=new RegExp("[\\w\\_\\.\\d]+");const isCronapiApiPath=t=>/^\/?api\/cronapi\/.*\/?$/.test(t);!function(t){var s={callback:function(){},runOnLoad:!0,frequency:100,previousVisibility:null},a={checkVisibility:function(t,s){if(jQuery.contains(document,t[0])){var r=s.previousVisibility,o=t.is(":visible");s.previousVisibility=o;var h=null==r;h?s.runOnLoad&&s.callback(t,o,h):r!==o&&s.callback(t,o,h),setTimeout((function(){a.checkVisibility(t,s)}),s.frequency)}}};t.fn.visibilityChanged=function(r){var o=t.extend({},s,r);return this.each((function(){a.checkVisibility(t(this),o)}))}}(jQuery);var initDatasource=function(t,s,a,r,o,h,c,l,d,u,p,f){var v=parseInt(9999*Math.random());if(cronapi.internal.isJsonString(a.headers)){let t=JSON.parse(a.headers);t.push({key:"origin-path",type:"string",value:d.path()}),a.headers=JSON.stringify(t)}else{var y="origin-path:"+d.path();void 0===a.headers||null===a.headers?a.headers=y:a.headers=a.headers.concat(";",y)}var m,D={name:a.name,entity:a.entity,apiVersion:a.apiVersion,enabled:!a.hasOwnProperty("enabled")||"true"===a.enabled,keys:a.keys,endpoint:a.endpoint,lazy:"true"===a.lazy,append:!a.hasOwnProperty("append")||"true"===a.append,prepend:a.hasOwnProperty("prepend")&&""===a.prepend||"true"===a.prepend,watch:a.watch,rowsPerPage:a.rowsPerPage,offset:a.offset,filterURL:a.filter,watchFilter:a.watchFilter,deleteMessage:a.deleteMessage||""===a.deleteMessage?a.deleteMessage:l.instant("General.RemoveData"),headers:a.headers,autoPost:"true"===a.autoPost,autoRefresh:void 0!==a.autoRefresh&&null!==a.autoRefresh?a.autoRefresh:0,onError:a.onError,onAfterFill:a.onAfterFill,onBeforeCreate:a.onBeforeCreate,onAfterCreate:a.onAfterCreate,onBeforeUpdate:a.onBeforeUpdate,onAfterUpdate:a.onAfterUpdate,onBeforeDelete:a.onBeforeDelete,onAfterDelete:a.onAfterDelete,onChangeStatus:a.onChangeStatus,onGet:a.onGet,onPost:a.onPost,onPut:a.onPut,onDelete:a.onDelete,defaultNotSpecifiedErrorMessage:l.instant("General.ErrorOnServerCommunication"),dependentBy:a.dependentBy,dependentLazyPost:a.dependentLazyPost,batchPost:"true"===a.batchpost,dependentLazyPostField:a.dependentLazyPostField,parameters:a.parameters,parametersNullStrategy:a.parametersNullStrategy?a.parametersNullStrategy:"default",parametersExpression:$(s).attr("parameters"),conditionExpression:$(s).attr("condition"),condition:a.condition,orderBy:a.orderBy,loadDataStrategy:a.loadDataStrategy,schema:a.schema?JSON.parse(a.schema):void 0,checkRequired:!a.hasOwnProperty("checkrequired")||""===a.checkrequired||"true"===a.checkrequired,fetchOnVisible:void 0!==a.fetchOnVisible&&null!==a.fetchOnVisible&&"true"===a.fetchOnVisible,offline:"true"===a.offline,insideModal:"true"===a.insideModal},b={filter:!0,entity:!0,enabled:!0,parameters:!0};if(t.params){for(var M in t.params)if(t.params.hasOwnProperty(M)){var w=t.params[M];if(M.startsWith("$"+a.name+".")){var S=M.split(".");2==S.length&&("$filterMode"==S[1]?D.startMode=w:(m?m+=";":m="",isNaN(w)?m+=S[1]+"='"+w+"'":m+=S[1]+"="+w))}}m&&(D.parameters=m,D.parametersExpression=m)}v=parseInt(9999*Math.random());var L,O=r.initDataset(D,t,p,h,f,v,l);a.$observe("filter",(function(t){O.isPostingBatchData()||(b.filter?o((function(){b.filter=!1}),0):(o.cancel(L),L=o((function(){O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","filter",t):O.filter(t,(function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"filter")})),O.lastFilterParsed=t}),100)))})),m||a.$observe("parameters",(function(t){O.isPostingBatchData()||O.parameters!=t&&(O.parameters=t,o.cancel(L),L=o((function(){O.callDataSourceEvents("changeDependency","parameters",O.parameters),O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","parameters",O.parameters):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"parameters")}})}),0))}));let _={lastCondition:void 0,timeForCondition:void 0,typingSpeedLimit:1e3,maxWaitingValue:1e3,wait:function(){if(this.timeForCondition=0,this.lastCondition){(new Date).getTime()-this.lastCondition.getTime()<this.typingSpeedLimit&&(this.timeForCondition=this.maxWaitingValue)}return this.lastCondition=new Date,this.timeForCondition}};a.$observe("condition",(function(t){if(!O.isPostingBatchData()&&O.condition!=t){if(O.condition=t,"button"===O.loadDataStrategy)return;o.cancel(L),L=o((function(){O.callDataSourceEvents("changeDependency","condition",O.condition),O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","condition",O.condition):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"condition")}})}),_.wait())}})),a.$observe("enabled",(function(t){var s="true"===t;O.enabled!=s&&(O.enabled=s,O.enabled&&(o.cancel(L),L=o((function(){O.events.overRideRefresh?O.callDataSourceEvents("overRideRefresh","enabled",O.parameters):O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"enabled")}})}),200)))})),a.$observe("entity",(function(t){O.entity=t,O.entity.match(DS_ID)&&!isCronapiApiPath(O.entity)&&(O.entity="api/cronapi/odata/v2/"+O.entity.replaceAll(".","/")),b.entity?o((function(){b.entity=!1})):(o.cancel(L),L=o((function(){O.fetch({params:{}},{success:function(t){O.events.refresh&&O.callDataSourceEvents("refresh",t,"entity")}})}),200))})),a.$observe("offline",(function(t){O.offline="true"===t})),t.$on("$destroy",(function(){u[a.name]&&u[a.name+".instanceId"]==v&&(u[a.name].destroy(),delete window[a.name],delete u[a.name],delete u[a.name+".instanceId"])}))};angular.module("datasourcejs",[]).factory("DatasetManager",["$http","$q","$timeout","$rootScope","$window","Notification","SyncService",function($http,$q,$timeout,$rootScope,$window,Notification,SyncService){this.datasets={};let DatasetManagerUtil={getMainScope:function(){return angular.element(document.getElementById("main-view")).scope()},resolveExpressionMap:async function(t){let s,a=this.getMainScope();if(cronapi.internal.isJsonString(t)){s={};let o=JSON.parse(t);for(var r in o){let t=o[r];if("blockly"===t.type){let r=this.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");s[t.key]=await a.$eval(r(t.value))}else"expression"===t.type?s[t.key]=a.$eval(t.value):s[t.key]=t.value}}return s},getHeaders:async function(t){let s;if(t&&t.length>0)if(cronapi.internal.isJsonString(t))s=await this.resolveExpressionMap(t);else{s={};let r,o=t.trim().split(";");for(var a=0;a<o.length;a++)r=o[a].split(":"),2===r.length&&(s[r[0]]=r[1])}return s&&(s["X-From-DataSource"]="true"),s},onMatchRegex:function(t,s,a){return r=>{let o=t.exec(r);return o&&o.length?r.split(s).join(a+s):r}}};const $httpLegacy=t=>{var s={verb:t.method,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return DatasetManagerUtil.getHeaders(t.headers).then(function(s){if(t.headers=s||t.headers,t.offlineMode){SyncService.toQueue(t);let s=t.originalObject||t.rawData||t.data;this.successCallback(s,200,null,t)}else{let s=$http(t);s.then((t=>{this.successCallback&&this.successCallback(t.data,t.status,t.headers,t.config)})),s.catch((t=>{this.errorCallback&&this.errorCallback(t.data,t.status,t.headers,t.config)}))}}.bind(s)),s};var DataSet=function(name,scope,fetchOnVisible){var NO_IMAGE_UPLOAD="data:image/svg+xml;utf8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjEyOHB4IiBoZWlnaHQ9IjEyOHB4IiB2aWV3Qm94PSIwIDAgNDQuNTAyIDQ0LjUwMiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDQuNTAyIDQ0LjUwMjsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8Zz4KCTxnPgoJCTxwYXRoIGQ9Ik05Ljg2MiwzNS42MzhoMjQuNzc5YzAtNS41NDYtMy44NjMtMTAuMjAzLTkuMTEzLTExLjYwNGMyLjc1LTEuMjQ4LDQuNjY4LTQuMDEzLDQuNjY4LTcuMjI5ICAgIGMwLTQuMzg4LTMuNTU5LTcuOTQyLTcuOTQyLTcuOTQyYy00LjM4NywwLTcuOTQzLDMuNTU3LTcuOTQzLDcuOTQyYzAsMy4yMTksMS45MTYsNS45OCw0LjY2OCw3LjIyOSAgICBDMTMuNzI1LDI1LjQzNSw5Ljg2MiwzMC4wOTIsOS44NjIsMzUuNjM4eiIgZmlsbD0iIzkxOTE5MSIvPgoJCTxwYXRoIGQ9Ik0xLjUsMTQuMTY5YzAuODI4LDAsMS41LTAuNjcyLDEuNS0xLjVWNC4zMzNoOC4zMzZjMC44MjgsMCwxLjUtMC42NzIsMS41LTEuNWMwLTAuODI4LTAuNjcyLTEuNS0xLjUtMS41SDIuNzc1ICAgIEMxLjI0NCwxLjMzMywwLDIuNTc3LDAsNC4xMDh2OC41NjFDMCwxMy40OTcsMC42NywxNC4xNjksMS41LDE0LjE2OXoiIGZpbGw9IiM5MTkxOTEiLz4KCQk8cGF0aCBkPSJNNDEuNzI3LDEuMzMzaC04LjU2MmMtMC44MjcsMC0xLjUsMC42NzItMS41LDEuNWMwLDAuODI4LDAuNjczLDEuNSwxLjUsMS41aDguMzM2djguMzM2YzAsMC44MjgsMC42NzMsMS41LDEuNSwxLjUgICAgczEuNS0wLjY3MiwxLjUtMS41di04LjU2QzQ0LjUwMiwyLjU3OSw0My4yNTYsMS4zMzMsNDEuNzI3LDEuMzMzeiIgZmlsbD0iIzkxOTE5MSIvPgoJCTxwYXRoIGQ9Ik00My4wMDIsMzAuMzMzYy0wLjgyOCwwLTEuNSwwLjY3Mi0xLjUsMS41djguMzM2aC04LjMzNmMtMC44MjgsMC0xLjUsMC42NzItMS41LDEuNXMwLjY3MiwxLjUsMS41LDEuNWg4LjU2ICAgIGMxLjUzLDAsMi43NzYtMS4yNDYsMi43NzYtMi43NzZ2LTguNTZDNDQuNTAyLDMxLjAwNSw0My44MywzMC4zMzMsNDMuMDAyLDMwLjMzM3oiIGZpbGw9IiM5MTkxOTEiLz4KCQk8cGF0aCBkPSJNMTEuMzM2LDQwLjE2OUgzdi04LjMzNmMwLTAuODI4LTAuNjcyLTEuNS0xLjUtMS41Yy0wLjgzLDAtMS41LDAuNjcyLTEuNSwxLjV2OC41NmMwLDEuNTMsMS4yNDQsMi43NzYsMi43NzUsMi43NzZoOC41NjEgICAgYzAuODI4LDAsMS41LTAuNjcyLDEuNS0xLjVTMTIuMTY1LDQwLjE2OSwxMS4zMzYsNDAuMTY5eiIgZmlsbD0iIzkxOTE5MSIvPgoJPC9nPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=",NO_FILE_UPLOAD="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjUxMnB4IiBoZWlnaHQ9IjUxMnB4IiB2aWV3Qm94PSIwIDAgNTQ4LjE3NiA1NDguMTc2IiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCA1NDguMTc2IDU0OC4xNzY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPGc+Cgk8cGF0aCBkPSJNNTI0LjMyNiwyOTcuMzUyYy0xNS44OTYtMTkuODktMzYuMjEtMzIuNzgyLTYwLjk1OS0zOC42ODRjNy44MS0xMS44LDExLjcwNC0yNC45MzQsMTEuNzA0LTM5LjM5OSAgIGMwLTIwLjE3Ny03LjEzOS0zNy40MDEtMjEuNDA5LTUxLjY3OGMtMTQuMjczLTE0LjI3Mi0zMS40OTgtMjEuNDExLTUxLjY3NS0yMS40MTFjLTE4LjA4MywwLTMzLjg3OSw1LjkwMS00Ny4zOSwxNy43MDMgICBjLTExLjIyNS0yNy40MS0yOS4xNzEtNDkuMzkzLTUzLjgxNy02NS45NWMtMjQuNjQ2LTE2LjU2Mi01MS44MTgtMjQuODQyLTgxLjUxNC0yNC44NDJjLTQwLjM0OSwwLTc0LjgwMiwxNC4yNzktMTAzLjM1Myw0Mi44MyAgIGMtMjguNTUzLDI4LjU0NC00Mi44MjUsNjIuOTk5LTQyLjgyNSwxMDMuMzUxYzAsMi40NzQsMC4xOTEsNi41NjcsMC41NzEsMTIuMjc1Yy0yMi40NTksMTAuNDY5LTQwLjM0OSwyNi4xNzEtNTMuNjc2LDQ3LjEwNiAgIEM2LjY2MSwyOTkuNTk0LDAsMzIyLjQzLDAsMzQ3LjE3OWMwLDM1LjIxNCwxMi41MTcsNjUuMzI5LDM3LjU0NCw5MC4zNThjMjUuMDI4LDI1LjAzNyw1NS4xNSwzNy41NDgsOTAuMzYyLDM3LjU0OGgzMTAuNjM2ICAgYzMwLjI1OSwwLDU2LjA5Ni0xMC43MTEsNzcuNTEyLTMyLjEyYzIxLjQxMy0yMS40MDksMzIuMTIxLTQ3LjI0NiwzMi4xMjEtNzcuNTE2QzU0OC4xNzIsMzM5Ljk0NCw1NDAuMjIzLDMxNy4yNDgsNTI0LjMyNiwyOTcuMzUyICAgeiBNMzYyLjcyOSwyODkuNjQ4Yy0xLjgxMywxLjgwNC0zLjk0OSwyLjcwNy02LjQyLDIuNzA3aC02My45NTN2MTAwLjUwMmMwLDIuNDcxLTAuOTAzLDQuNjEzLTIuNzExLDYuNDIgICBjLTEuODEzLDEuODEzLTMuOTQ5LDIuNzExLTYuNDIsMi43MTFoLTU0LjgyNmMtMi40NzQsMC00LjYxNS0wLjg5Ny02LjQyMy0yLjcxMWMtMS44MDQtMS44MDctMi43MTItMy45NDktMi43MTItNi40MlYyOTIuMzU1ICAgSDE1NS4zMWMtMi42NjIsMC00Ljg1My0wLjg1NS02LjU2My0yLjU2M2MtMS43MTMtMS43MTQtMi41NjgtMy45MDQtMi41NjgtNi41NjZjMC0yLjI4NiwwLjk1LTQuNTcyLDIuODUyLTYuODU1bDEwMC4yMTMtMTAwLjIxICAgYzEuNzEzLTEuNzE0LDMuOTAzLTIuNTcsNi41NjctMi41N2MyLjY2NiwwLDQuODU2LDAuODU2LDYuNTY3LDIuNTdsMTAwLjQ5OSwxMDAuNDk1YzEuNzE0LDEuNzEyLDIuNTYyLDMuOTAxLDIuNTYyLDYuNTcxICAgQzM2NS40MzgsMjg1LjY5NiwzNjQuNTM1LDI4Ny44NDUsMzYyLjcyOSwyODkuNjQ4eiIgZmlsbD0iI2NlY2VjZSIvPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+CjxnPgo8L2c+Cjwvc3ZnPgo=";this.fetchOnVisible=fetchOnVisible,this.parent=$("[name='"+name+"']").parent(),this.fetchOnVisible&&this.parent.visibilityChanged({callback:function(t,s,a){s&&this.holdServiceCall&&this.holdServiceCall()}.bind(this),runOnLoad:!1,frequency:100}),this.Notification=Notification,this.$scope=scope,this.noImageUpload=NO_IMAGE_UPLOAD,this.noFileUpload=NO_FILE_UPLOAD,this.$apply=function(t){scope.safeApply(t)}.bind(scope),this.columns=[],this.data=[],this.name=name,this.keys=[],this.enabled=!0,this.endpoint=null,this.active={},this.inserting=!1,this.editing=!1,this.fetchSize=2,this.observers=[],this.rowsPerPage=null,this.append=!0,this.headers=null,this.responseHeaders=null,this._activeValues=null,this.errorMessage="",this.onError=null,this.links=null,this.loadedFinish=null,this.lastLoadedTime=0,this.lastFilterParsed=null,this.rowsCount=-1,this.events={},this.busy=!1,this.cursor=0,this._savedProps,this.hasMoreResults=!1,this.loaded=!1,this.unregisterDataWatch=null,this.dependentBufferLazyPostData=null,this.lastAction=null,this.dependentData=null,this.hasMemoryData=!1,this.batchPost=!1,this.caseInsensitive=null,this.terms=null,this.checkRequired=!0,this.schema;var _self=this,service=null;function reverseArr(t){if(t){for(var s=new Array,a=t.length-1;a>=0;a--)s.push(t[a]);return s}return[]}function toBase64(t,s){var a=new FileReader;a.readAsDataURL(t),a.onload=function(t){var a=t.target.result.substr(t.target.result.indexOf("base64,")+7);s(a)}}function uuid(){var t,s,a="";for(t=0;t<32;t++)s=16*Math.random()|0,8!=t&&12!=t&&16!=t&&20!=t||(a+="-"),a+=(12==t?4:16==t?3&s|8:s).toString(16);return a}this.odataFile=[],this.destroy=function(){},this.init=function(){var dsScope=this;service={save:function(t){return this.call(_self.entity,"POST",t,!0)},update:function(t,s){return this.call(t,"PUT",s,!1)},remove:function(t,s){return this.call(t,"DELETE",s,!0)},call:function(t,s,a,r){var o={},h=t.indexOf("/cronapi/query/")>=0;if(h){o.inputs=[a];var c,l,d={};if(_self.busy=!0,t=(t=t.replace("/specificSearch","")).replace("/generalSearch",""),_self&&_self.$scope&&_self.$scope.vars)for(var u in d.vars={},_self.$scope.vars)d.vars[u]=_self.$scope.vars[u];for(var p in _self.$scope)_self.$scope[p]&&_self.$scope[p].constructor&&"DataSet"==_self.$scope[p].constructor.name&&(d[p]={},d[p].active=_self.$scope[p].active);o.fields=d}else o=a;var f={};for(var p in _self.copy(o,f,!0),delete f.__original,delete f.__status,delete f.__originalIdx,delete f.__sender,delete f.__$id,delete f.__parentId,delete f.$$hashKey,delete f.__fromMemory,delete f.__odatafiles,delete f.__$masterExpression,f)p.indexOf("__odataFile_")>-1&&(f[p.replace("__odataFile_","")]=void 0,delete f[p]);for(var p in f)if(f.hasOwnProperty(p)){let t=f[p];_self.isAutoGeneratedValue(t)&&delete f[p]}var v=function(t,s,a,r,o){if(_self.busy=!1,c&&(_self.isOData()?null!=t.d&&null!=t.d.result?(_self.normalizeData(t.d.result),c(t.d.result,!0,o)):null!=t.d?(_self.normalizeObject(t.d),c(t.d,!0,o)):c(t,!0,o):c(h?t.value:t,!0,o)),h||_self.isOData()){var l=t;_self.isOData()&&((l={}).commands=t.__callback,_self.normalizeData(l.commands)),_self.$scope.cronapi.evalInContext(JSON.stringify(l))}},y=_self.getParentDatasource();let m=y.getBatchDataItem(o);if(m&&m.result){let t=y.batchServiceData.indexOf(m);y.batchServiceData.splice(t,1),$timeout((()=>{v(m.result)}),0),this.$promise={}}else this.$promise=_self.getService(s,o)({method:s,url:_self.removeSlash((window.hostApp||"")+t),data:"DELETE"!=s&&o?JSON.stringify(f):null,headers:_self.headers,rawData:o?f:null,originalObject:o||null,urlPart:t,offlineMode:_self.isOfflineMode()}).success(v).error((function(t,s,a,r){var o;_self.busy=!1,o=_self.isOData()?t.error.message.value:h&&t.value?t.value:t,_self.handleError(o),l&&l(o)}));return this.$promise.then=function(t){return c=t,this},this.$promise.error=function(t){return l=t,this},this}},this.isAutoGeneratedValue=function(t){return"string"==typeof t&&t.length>10&&(t.startsWith("$autogenerated$")||t.substring(1).startsWith("$autogenerated$"))},this.getIndexedDB=function(t){return window.indexedDB||(window.indexedDB=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,window.IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction||window.msIDBTransaction,window.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange),{properties:t,successCallback:null,errorCallback:null,type:null,args:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this},post:function(){return this.type="put",this.args=arguments,this},put:function(){return this.type="put",this.args=arguments,this},delete:function(){return this.type="delete",this.args=arguments,this},get:function(){return this.type="getAll",this.args=arguments,this},call:function(){request=window.indexedDB.open(this.properties.dbname,this.properties.dbversion||1),request.onerror=function(t){this.errorCallback&&this.errorCallback(t)}.bind(this),request.onsuccess=function(t){this.proceed(t.target.result)}.bind(this),request.onupgradeneeded=function(t){var s=t.target.result;s.createObjectStore(this.properties.objectStore,{keyPath:this.properties.key}).transaction.oncomplete=function(t){s.transaction(this.properties.objectStore,"readwrite").objectStore(this.properties.objectStore).add({id:123,name:"Jose"})}.bind(this)}.bind(this)},proceed:function(t){if(this.type){var s=t.transaction(this.properties.objectStore,"readwrite").objectStore(this.properties.objectStore);s[this.type].apply(s,this.args).onsuccess=function(t){this.successCallback&&("put"===this.type?this.successCallback(this.args[0]):this.successCallback(t.target.result))}.bind(this)}else this.successCallback&&this.successCallback()}}},this.batchServiceData=[],this.getBatchService=function(t){return function(s){var a={verb:t,properties:s,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return $timeout(function(){var r=this.getParentDatasource();let o=s.originalObject||s.rawData||s.data||this.active,h=this.entity;"PUT"==t&&(h=this.getEditionURL(o)),"DELETE"==t&&(h=this.getDeletionURL(o)),h.indexOf("/")>0&&(h=h.substring(h.lastIndexOf("/")+1,h.length)),r.batchServiceData.push({entity:h,data:o,promise:a}),a.successCallback&&a.successCallback.call(this,o,null,null,null,!0)}.bind(this)),a}.bind(this)},this.batchEnabled=function(t){return!(!t||!this.hasPendingChanges())&&null==this.getBatchDataItem(t)},this.getBatchDataItem=function(t){if(t){var s=this.getParentDatasource();for(let a=0;a<s.batchServiceData.length;a++){if(s.batchServiceData[a].data.__$id==t.__$id)return s.batchServiceData[a]}}return null},this.performBatchPost=function(t){return new Promise(((s,a)=>{let r="batch_"+this.uuidv4(),o="";o+="--"+r+"\n";let h="changeset_"+this.uuidv4();o+="Content-Type: multipart/mixed; boundary="+h+"\n";for(let t=0;t<this.batchServiceData.length;t++){let s=this.batchServiceData[t];o+="--"+h+"\n",o+="Content-Type: application/http\n",o+="Content-Transfer-Encoding:binary\n",o+=s.promise.properties.method+" "+s.entity+" HTTP/1.1\n",o+="Content-Type: application/json\n",o+="Accept: application/json\n",o+="X-Master-Id: "+s.promise.properties.originalObject.__$id+"\n",s.promise.properties.originalObject.__$masterExpression&&(o+="X-Detail-Fill: "+s.promise.properties.originalObject.__$masterExpression+"\n");let a=s.promise.properties.headers;for(var c in a)a.hasOwnProperty(c)&&(o+=c+": "+a[c]+"\n");"DELETE"!=s.promise.properties.method&&(o+=s.promise.properties.data+"\n")}o+="--"+h+"--\n",o+="--"+r+"--\n",console.log(o);let l=this.entity;l.indexOf("/")>0&&(l=l.substring(0,l.lastIndexOf("/")));let d={};this.copy(this.headers,d),d["Content-Type"]="multipart/mixed; boundary="+r;let u=(t,s,a,r)=>{let o;this.batchServiceData.length>0&&(o=this.batchServiceData[0].promise.errorCallback),o?o(t,s,a,r,!1):this.handleError(t),this.batchServiceData=[]};$httpLegacy({method:"POST",url:_self.removeSlash((window.hostApp||"")+l+"/$batch"),data:o,headers:d,offlineMode:_self.isOfflineMode()}).success(function(s,a,r,o,h){let c=this.parseBatchResult(s);for(let t=0;t<c.length;t++)if(c[t].status>=400)return void u(c[t].data,c[t].status);for(let t=0;t<this.batchServiceData.length;t++)this.batchServiceData[t].result=c[t]&&null!=c[t].data?c[t].data:this.batchServiceData[t].data;if(t)t();else{let t;this.batchServiceData.length>0&&(t=this.batchServiceData[0].promise.successCallback),t&&(this.batchServiceData.splice(0,1),t(c[0].data,c[0].status,r,o,!1))}}.bind(this)).error(u)}))},this.parseBatchResult=function(t){let s,a=[],r=t.split("\n");for(let t=0;t<r.length;t++){let o=r[t];if(o.startsWith("{")&&a.push({status:s,data:JSON.parse(o)}),o.startsWith("HTTP/1.1"))s=HTTP_STATUS.exec(o)[1];o.startsWith("HTTP/1.1")&&o.indexOf("No Content")>0&&a.push({status:s,data:null})}return a},this.uuidv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var s=16*Math.random()|0;return("x"==t?s:3&s|8).toString(16)}))},this.getService=function(verb,object){_self=this;var event=eval("this.on"+verb);return"GET"===verb&&(event||this.isLocalData()||this.isNavigatorOffline())?function(t){var s={verb:verb,properties:t,successCallback:null,errorCallback:null,success:function(t){return this.successCallback=t,this},error:function(t){return this.errorCallback=t,this}};return $timeout(function(){var t,s={currentData:this.properties.rawData||this.properties.data||_self.active,filter:this.properties.filter||"",datasource:_self,selectedIndex:_self.cursor,index:_self.cursor,selectedRow:_self.active,item:_self.active,selectedKeys:_self.getKeyValues(_self.active,!0),selectedKey:_self.getFirstKeyValue(_self.active,!0),callback:this.successCallback};if(event)(t=_self.$scope.$eval(event,s))instanceof Promise?t.then(function(t){t&&"[object Array]"!==Object.prototype.toString.call(t)&&(t=[t]),_self.$scope.safeApply(function(){this.successCallback(t)}.bind(this))}.bind(this)).catch(function(t){_self.handleError(t)}.bind(this)):t&&this.successCallback(t);else{let t=_self.getPouchDB();if("GET"!=this.verb||this.properties.filter){if("GET"==this.verb){var a=peg$parse(this.properties.filter);t.find({selector:a}).catch(this.errorCallback).then(function(t){t.rows=t.docs,t.total_rows=t.rows.length,this.successCallback&&this.successCallback(t)}.bind(this))}}else t.allDocs({include_docs:!0,attachments:!0}).catch(this.errorCallback).then(function(t){for(var s=[],a=0;a<t.rows.length;a++)s.push(t.rows[a].doc);t.rows=s,this.successCallback&&this.successCallback(t)}.bind(this))}}.bind(s),0),s}:(this.hasOfflineSupport()&&object&&this.operationPouchDB(verb,object),this.batchEnabled(object)&&"GET"!=verb?this.getBatchService(verb):$httpLegacy)},this.isBusy=function(){return this.busy},this.isLoaded=function(){return this.loaded},this.toString=function(){return"[Datasource]"},this.handleAfterCallBack=function(t,s){if(t)try{var a={currentData:this.data,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(_self.active,!0),callback:s};this.$scope.$eval(t,a)}catch(t){this.handleError(t)}},this.handleBeforeCallBack=async function(t,s){var a=!0;let r=DatasetManagerUtil.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");if(t)try{var o={currentData:this.data,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(_self.active,!0),callback:s};await this.$scope.$eval(r(t),o)}catch(t){a=!1,this.handleError(t)}return a},this.handleError=function(t){if(console.log(t),t instanceof XMLDocument){var s=t.getElementsByTagName("message")[0].textContent;t=s,console.log(t)}var a="";if(t)if("[object String]"===Object.prototype.toString.call(t))a=t;else{s=t.msg||t.desc||t.message||t.error||t.responseText;this.isOData()&&t.error.message&&t.error.message.value&&(s=t.error.message.value),s&&(a=s)}a||(a=this.defaultNotSpecifiedErrorMessage);if(result=/<h1>(.*)<\/h1>/gim.exec(a),result&&result.length>=2&&(a=result[1]),this.errorMessage=a,this.onError&&""!==this.onError){if("string"==typeof this.onError)try{var r={currentData:this.active,filter:"",error:a,datasource:this,selectedIndex:this.cursor,index:this.cursor,selectedRow:this.active,item:this.active,selectedKeys:this.getKeyValues(this.active,!0),selectedKey:this.getFirstKeyValue(this.active,!0),callback:this.successCallback},o=this.$scope.$eval(this.onError,r);"function"==typeof o&&(this.onError=o)}catch(t){isValid=!1,Notification.error(t)}}else this.onError=function(t){Notification.error(t)};"function"==typeof this.onError&&this.onError.call(this,a)},this.observers&&this.observers.length>0&&$rootScope.$watch(function(){return this.active}.bind(this),function(t){t&&this.notifyObservers(t)}.bind(this),!0)},this.setFile=function(t,s,a){t&&"pattern"===t.$error||t&&toBase64(t,(function(t){this.$apply=function(t){s[a]=t,scope.$apply(s)}.bind(scope),this.$apply(t)}))},this.downloadFile=function(t,s){if(void 0!==s){for(var a=(window.hostApp||"")+this.entity+"/download/"+t,r=0;r<s.length;r++)a+="/"+s[r];$http({url:a,method:"GET",responseType:"arraybuffer"}).then((function(t){var s=new Blob([t.data],{type:"application/*"});$window.open(URL.createObjectURL(s))}))}},this.openImage=function(t){if(-1==t.indexOf("https://")&&-1==t.indexOf("http://")){var s="data:image/png;base64,"+t;$window.open("","_blank","height=300,width=400").document.write('<img src="'+s+'"/>')}else $window.open(t,"_blank","height=300,width=400")},this.byteSize=function(t){if(!angular.isString(t))return"";function s(t,s){return-1!==s.indexOf(t,s.length-t.length)}return function(t){return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")+" bytes"}(function(t){return t.length/4*3-function(t){return s("==",t)?2:s("=",t)?1:0}(t)}(t))},this.insert=async function(obj,onSuccess,onError,forceSave){await this.handleBeforeCallBack(this.onBeforeCreate)&&(!this.dependentLazyPost&&!this.batchPost||forceSave?service.save(obj).$promise.error(onError).then(onSuccess):(obj.__status="inserted",this.dependentLazyPost&&(obj.__parentId=eval(this.dependentLazyPost).active.__$id),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData),onSuccess&&onSuccess(obj)))},this.addDependentDatasource=function(dts){this.children||(this.children=[]),this.children.push(dts),this.dependentLazyPost?eval(this.dependentLazyPost).addDependentDatasource(dts):(this.dependentData||(this.dependentData=[]),this.dependentData.push(dts))},this.getParentDatasource=function(){return this.dependentLazyPost?eval(this.dependentLazyPost).getParentDatasource():this},this.updateObjectAtIndex=function(t,s,a){s=s||this.data,this.copy(t,s[a]),t.__$id=s[a].__$id,delete s[a].__status,delete s[a].__original,delete s[a].__originalIdx,delete s[a].__odatafiles,delete s[a].__$masterExpression},this.cleanDependentBuffer=function(){var t=[];$(this.data).each((function(){this.__status?"updated"==this.__status&&t.push(this.__original):t.push(this)})),this.data.length=0;for(var s=0;s<t.length;s++)delete t[s].__status,delete t[s].__original,delete t[s].__originalIdx,this.data.push(t[s]);if(this.postDeleteData)for(s=0;s<this.postDeleteData.length;s++)delete this.postDeleteData[s].__status,delete this.postDeleteData[s].__original,delete this.postDeleteData[s].__originalIdx,this.data.push(this.postDeleteData[s]);this.data&&this.data.length>0?(this.cursor=0,this.active=this.data[0]):(this.cursor=-1,this.active=null),this.busy=!1,this.editing=!1,this.inserting=!1,this.postDeleteData=null,this.hasMemoryData=!1,this.notifyPendingChanges(this.hasMemoryData),this.events.read&&this.callDataSourceEvents("read",this.data),this.events.afterchanges&&this.callDataSourceEvents("afterchanges",this.data)},this.cancelBatchData=function(t){this.dependentData&&$(reverseArr(this.dependentData)).each((function(){this.cleanDependentBuffer()})),this.cleanDependentBuffer(),this.batchServiceData=[],t&&t()},this.flushDependencies=function(t,s){var a=[];if(this.dependentData){var r=function(){reduce(this.dependentData,function(t,r){a.push(t.storeDependentBuffer((function(){r()}),void 0,s))}.bind(this),function(){t&&t(a)}.bind(this))}.bind(this);reduce(reverseArr(this.dependentData),function(t,a){t.storeDependentBuffer((function(){a()}),!0,s)}.bind(this),function(){r()}.bind(this))}else t&&t(a)},this.postBatchData=function(t,s){let a=!s;s||(this.batchServiceData=[]);let r=()=>{a?(a=!1,this.performBatchPost(function(){this.postBatchData(t,!0)}.bind(this))):t&&t()};this.postingBatch=!0;var o=[],h=function(){this.storeDependentBuffer(function(){o.push(this.storeDependentBuffer(function(){reduce(this.dependentData,function(t,s){o.push(t.storeDependentBuffer((function(){s()}),!1,a))}.bind(this),function(){this.postingBatch=!1;for(var t=0;t<o.length;t++)o[t]();r&&r()}.bind(this))}.bind(this),!1,a))}.bind(this),!0,a)}.bind(this);reduce(reverseArr(this.dependentData),function(t,s){t.storeDependentBuffer((function(){s()}),!0,a)}.bind(this),function(){h()}.bind(this))};var reduce=function(t,s,a){t&&0!=t.length?t.reduce((function(t,a){return t.then((function(){return new Promise((function(t){s(a,t)}))}))}),Promise.resolve()).then((function(){a()})):a()};this.storeDependentBuffer=function(callback,onlyRemove,batchMode){var _self=this,dependentDS=eval(_self.dependentLazyPost);this.batchPost&&(dependentDS=this);var array=[];if(!onlyRemove&&(array=array.concat(_self.data),_self.memoryData))for(key in _self.memoryData)if(_self.memoryData.hasOwnProperty(key)){for(var mem=_self.memoryData[key],x=0;x<mem.data.length;x++)mem.data[x].__fromMemory=!0;array=array.concat(mem.data)}_self.postDeleteData&&(array=array.concat(_self.postDeleteData));var func=function(t,s){if(t.__status){if(!_self.parameters&&(_self.dependentLazyPostField&&(t[_self.dependentLazyPostField]=dependentDS.active),_self.entity.indexOf("//")>-1)){var a=dependentDS.getKeyValues(dependentDS.active),r="";for(var o in a)a.hasOwnProperty(o)&&(r+="/"+a[o]);r+="/",_self.entity=_self.entity.replace("//",r)}if(_self.parameters){var h=_self.getParametersMap(t.__parentId?t.__parentId:null);for(var o in h)h.hasOwnProperty(o)&&updateObjectValue(t,o,h[o]);let s=_self.getParametersBatchExpression(t.__parentId?t.__parentId:null);t.__$masterExpression=s}"inserted"==t.__status?(c=t,batchMode||(l=_self.processODataFiles(c)),_self.insert(c,(function(t,a,r){if(r)s();else{var o=c.__sender,h=_self.getIndexOfListTempBuffer(c,array),d=!1,u=t;h>=0&&(u=array[h],d=array[h].__fromMemory,_self.updateObjectAtIndex(t,array,h)),_self.events.create&&!d&&(o&&((t=array[h]).__sender=o),_self.callDataSourceEvents("create",t),delete t.__sender),l&&l.length>0?_self.sendODataFiles(l,t,function(t){_self.copy(t.data,u)}.bind(this),(function(){s()})):s()}}),(function(){s()}),!0)):"updated"==t.__status?function(t){var a;batchMode||(a=_self.processODataFiles(t)),_self.update(t,(function(r,o,h){if(h)s();else{var c=t.__sender,l=_self.getIndexOfListTempBuffer(t,array),d=!1,u=r;l>=0&&(u=array[l],d=array[l].__fromMemory,_self.updateObjectAtIndex(r,array,l),r=array[l]),_self.events.update&&!d&&(c&&(r.__sender=c),_self.callDataSourceEvents("update",r),delete r.__sender),a&&a.length>0?_self.sendODataFiles(a,r,function(t){_self.copy(t.data,u)}.bind(this),(function(){s()})):s()}}),(function(){s()}),!0)}(t):"deleted"==t.__status&&onlyRemove?function(t){_self.remove(t,(function(a,r,o){if(o)s();else{if(_self.events.delete){var h={};_self.copy(t,h),delete h.__status,delete h.__original,delete h.__originalIdx,_self.callDataSourceEvents("delete",h)}s()}}),!0,null,(function(){s()}))}(t):s()}else s();var c,l},resetFunc=function(){onlyRemove||(this.busy=!1,this.editing=!1,this.inserting=!1,this.hasMemoryData=!1,this.memoryData=null,batchMode||this.notifyPendingChanges(this.hasMemoryData),this.events.afterchanges&&!batchMode&&this.callDataSourceEvents("afterchanges",this.data))}.bind(this);return reduce(array,func,function(){callback&&callback(),batchMode||(this.postDeleteData=null)}.bind(this)),resetFunc},this.getIndexOfListTempBuffer=function(t,s){s=s||this.data;for(var a=0;a<s.length;a++)if(s[a].__$id&&t.__$id&&s[a].__$id==t.__$id)return a;return-1},this.getObjectAsString=function(t,s){return null!=s&&null!=s||(s=!0),this.isOData()?window.objToOData(t,s):null==t?"":"number"==typeof t?t+"@@number":t instanceof Date?t.toISOString()+"@@datetime":"boolean"==typeof t?t+"@@boolean":t+""},this.update=async function(t,s,a,r){await this.handleBeforeCallBack(this.onBeforeUpdate)&&(!this.dependentLazyPost&&!this.batchPost||r?service.update(this.getEditionURL(t,r),t).$promise.error(a).then(s):s&&s(t))},this.validateFields=function(t,s){var a=$(t);if(a.length>0&&"checkbox"!==a.get(0).type){var r=$('label[for="'+a.get(0).id+'"]'),o=a.get(0).id;return r.length>0&&(o=r.text())&&(o=o.replaceAll("\n","").trim()),s&&(Notification.error(s.replace("{0}",o)),$(a.get(0)).addClass("ng-touched").removeClass("ng-untouched"),a.get(0).focus&&a.get(0).focus()),!1}return!0},this.getPatterns=function(){return $('input[ng-model*="'+this.name+'."]').filter((function(t){return $(this).attr("pattern")}))},this.missingRequiredField=function(t){if(this.getPatterns().length>0)return!1;if(this.checkRequired){var s=this.validateFields('[required][ng-model*="'+this.name+'."].ng-invalid-required',t?"":this.translate.instant("FieldIsRequired"));return!(s=(s=s&&this.validateFields('[required][ng-model*="'+this.name+'."].ng-empty',t?"":this.translate.instant("FieldIsRequired")))&&this.validateFields('[ng-model*="'+this.name+'."].ng-invalid',t?"":this.translate.instant("FieldIsInvalid")))}return!1},this.hasInvalidField=function(){return!(this.getPatterns().length>0)&&(!!this.checkRequired&&$('input[ng-model*="'+this.name+'."]:invalid').not("input[type=checkbox]").not(".ng-empty").length>0)},this.postSilent=function(t,s){this.post(t,s,!0)},this.updateActive=function(t){for(var s in t)t.hasOwnProperty(s)&&"__status"!=s&&(this.active[s]=t[s])},this.processODataFiles=function(t){var s=[];for(var a in t)if(a.indexOf("__odataFile_")>-1){var r={field:a.replace("__odataFile_",""),value:t[a]};s.push(r),t[r.field]=void 0,delete t[a]}return s},this.sendODataFiles=function(t,s,a,r){if(s&&t&&t.length>0){var o=this.entity,h=this.getKeyValues(s),c=["("],l=0;for(var d in h)l>0&&c.push(","),c.push(d),c.push("="),c.push(window.objToOData(h[d])),l++;c.push(")"),o+=c.join("");var u=JSON.parse(localStorage.getItem("_u"));reduce(t,function(t,r){let h=(window.hostApp||"")+o+"/"+t.field+"/$value";if(_self.isOfflineMode()){let o={method:"PUT",data:t.value,url:h,headers:_self.headers};SyncService.toQueue(o),cronapi.internal.fileToBase64(t.value,(o=>{s[t.field]=o,a&&a({field:t.field,data:s}),r()}))}else{var c=t.value,l=new XMLHttpRequest;l.open("PUT",h),l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.setRequestHeader("X-File-Name",c.name),l.setRequestHeader("Content-Type",(c.type||"application/octet-stream")+";charset=UTF-8"),window.isUsingCookie()||l.setRequestHeader("X-AUTH-TOKEN",u?.token);const d=localStorage.getItem("csrfToken");d&&l.setRequestHeader("X-CSRF-TOKEN",d),l.onreadystatechange=function(){if(4===l.readyState){const t=l.getResponseHeader("X-CSRF-TOKEN");t&&localStorage.setItem("csrfToken",t)}if(4===l.readyState&&500===l.status){var h=(new DOMParser).parseFromString(l.response,"text/xml");this.handleError(h)}4===l.readyState&&201===l.status&&service.call(o,"GET",{},!1).$promise.error((function(t){Notification.error("Error send file")})).then((function(o,h){a?a({field:t.field,data:o}):s[t.field]=o[t.field],r()}))}.bind(this),l.send(c)}}.bind(this),function(){r&&r()}.bind(this))}else r&&r()},this.getFieldSchema=function(t){var s;if(this.schema)for(var a=0;a<this.schema.length;a++)if(this.schema[a].name==t){s=this.schema[a];break}return s},this.asyncPost=function(t,s,a){setTimeout(function(){this.post(t,s,a)}.bind(this),100)},this.copyWithoutAngularObj=function(){var t={};for(var s in this)this.hasOwnProperty(s)&&!s.startsWith("$")&&(t[s]=this[s]);return t},this.post=function(onSuccess,onError,silent,keepBuffer){!silent&&this.missingRequiredField()||!silent&&this.hasInvalidField()||(keepBuffer||(this.batchServiceData=[]),this.lastAction="post",this.busy=!0,this.inserting?this.insert(this.active,function(t,s,a){if(!a||!this.dependentData||this.dependentLazyPost||this.batchPost){this.active.__sender&&(t.__sender=this.active.__sender),this.active.__$id&&(t.__$id=this.active.__$id);var r=function(a){if(this.active=t,this.handleAfterCallBack(this.onAfterCreate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),this.events.create&&s&&(this.callDataSourceEvents("create",this.active),delete _self.active.__sender),this.events.memorycreate&&!s&&this.callDataSourceEvents("memorycreate",this.active),a)for(let t=0;t<a.length;t++)a[t]()}.bind(this),o=function(){this.data.push(t),!this.dependentData||this.dependentLazyPost||this.batchPost?r():this.flushDependencies(r,!1)}.bind(this);if(s){var h=this.processODataFiles(this.active);h&&h.length>0?this.sendODataFiles(h,t,function(s){this.copy(s.data,t)}.bind(this),function(){o()}.bind(this)):o()}else o()}else this.flushDependencies((()=>{this.performBatchPost((()=>{this.post(onSuccess,onError,silent,!0)}))}),!0)}.bind(this),onError):this.editing?this.update(this.active,function(obj,hotData,batchPostponed){if(!batchPostponed||!this.dependentData||this.dependentLazyPost||this.batchPost){var odataFiles,foundRow;hotData&&(odataFiles=this.processODataFiles(this.active));var keyObj=this.getKeyValues(this.lastActive);this.data.forEach(function(currentRow){var found;if(this.lastActive.__$id&¤tRow.__$id)found=this.lastActive.__$id==currentRow.__$id;else{var dataKeys=this.getKeyValues(currentRow);for(var key in keyObj){if(!dataKeys[key]||dataKeys[key]!==keyObj[key]){found=!1;break}found=!0}}if(found){foundRow=currentRow;var lastActive={};this.copy(this.lastActive,lastActive),this.copy(obj,currentRow),this.lastActive&&this.lastActive.__sender&&(currentRow.__sender=this.lastActive.__sender),this.active=currentRow,!this.dependentLazyPost&&!this.batchPost||currentRow.__status||(currentRow.__status="updated",currentRow.__original=lastActive,this.hasMemoryData=!0,this.dependentLazyPost&&(currentRow.__parentId=eval(this.dependentLazyPost).active.__$id)),this.notifyPendingChanges(this.hasMemoryData),this.events.update&&hotData&&(this.callDataSourceEvents("update",this.active),delete this.active.__sender),this.events.memoryupdate&&!hotData&&this.callDataSourceEvents("memoryupdate",this.active)}}.bind(this));var back=function(t){if(foundRow&&this.handleAfterCallBack(this.onAfterUpdate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),t)for(let s=0;s<t.length;s++)t[s]()}.bind(this),func=function(t){hotData&&odataFiles&&odataFiles.length>0?this.sendODataFiles(odataFiles,foundRow,function(t){this.copy(t.data,foundRow)}.bind(this),function(){this.events.update&&hotData&&this.callDataSourceEvents("update",foundRow),back(t)}.bind(this)):back(t)}.bind(this);!this.dependentData||this.dependentLazyPost||this.batchPost?func():this.flushDependencies(func)}else this.flushDependencies((()=>{this.performBatchPost((()=>{this.post(onSuccess,onError,silent,!0)}))}),batchPostponed)}.bind(this),onError):0==this.data.length?this.startInserting(this.active,function(){this.post(onSuccess,onError,silent)}.bind(this)):this.startEditing(null,function(){this.post(onSuccess,onError,silent)}.bind(this)))},this.notifyPendingChanges=function(value){console.log("notifyPendingChanges : "+value),this.events.pendingchanges&&this.callDataSourceEvents("pendingchanges",value),this.dependentLazyPost&&eval(this.dependentLazyPost).notifyPendingChanges(value)},this.notifyPendingChanges=function(value){console.log("notifyPendingChanges : "+value),this.events.pendingchanges&&this.callDataSourceEvents("pendingchanges",value),this.dependentLazyPost&&eval(this.dependentLazyPost).notifyPendingChanges(value)},this.getConditionParams=function(){if(this.condition)try{var t=this.$interpolate(this.conditionExpression)(this.$scope),s=JSON.parse(t);if("object"==typeof s){if(s.params){let t;for(var a=0;a<s.params.length;a++){var r=s.params[a].fieldValue;r.length>=2&&"'"==r.charAt(0)&&"'"==r.charAt(r.length-1)&&(r=r.substring(1,r.length-1)),""!==r&&null!=r&&(t?t+="&":t="",t+=s.params[a].fieldName+"="+encodeURIComponent(r))}return t}}}catch(t){console.log(t)}},this.getDeletionURL=function(t,s){var a=this.getKeyValues(t.__original?t.__original:t,s),r="";this.isOData()&&(r="(");var o=0;for(var h in a)a.hasOwnProperty(h)&&(this.isOData()?(o>0&&(r+=","),r+=h+"="+this.getObjectAsString(a[h])):r+="/"+a[h],o++);this.isOData()&&(r+=")",r=encodeURI(r));var c=this.entity;this.entity.endsWith("/")&&(c=c.substring(0,c.length-1)),c+=r;let l=this.getConditionParams();return l&&(c=c+"?"+l),c},this.getEditionURL=function(t,s){var a=this.getKeyValues(t.__original?t.__original:t,s),r="";for(var o in this.isOData()&&(r="("),a)a.hasOwnProperty(o)&&(this.isOData()?r+=("("==r?"":",")+o+"="+this.getObjectAsString(a[o]):r+="/"+a[o]);this.isOData()&&(r+=")",r=encodeURI(r));var h=this.entity;this.entity.endsWith("/")&&(h=h.substring(0,h.length-1)),h+=r;let c=this.getConditionParams();return c&&(h=h+"?"+c),h},this.refreshActive=function(t,s){if(this.active&&"inserted"!=this.active.__status){var a=this.getEditionURL(this.active),r=this.getKeyValues(this.active);this.$promise=this.getService("GET")({method:"GET",url:a,headers:this.headers}).success(function(a,o,h,c){var l=null;this.isOData()?(l=a.d,this.normalizeObject(l)):a&&a.length>0&&(l=a[0]);var d=-1,u=0;this.data.forEach(function(t){var s=!1,a=0,o=0;for(var h in r)o++,t[h]&&t[h]===r[h]&&a++;a==o&&(s=!0),s&&(d=u,l&&(this.copy(l,t),this.copy(l,this.active))),u++}.bind(this)),-1!=d?(this.events.update&&this.callDataSourceEvents("update",this.active),t&&t(this.active)):s&&s()}.bind(this)).error(function(t,a,r,o){s&&s()}.bind(this))}else t&&t(this.active)},this.buildURL=function(t,s){var a=this.getKeyValues(this.active,!1,s);"object"!=typeof t&&(t=[t]);var r="",o=0;for(var h in a){var c;if(a.hasOwnProperty(h))c=Array.isArray(t)?t[o]:t[h],o>0&&(r+=" and "),r+=h+" eq "+this.getObjectAsString(c);o++}return r},this.findObj=function(t,s,a,r,o){let h=o||deepCopy(this.keys),c=function(s){for(let a=0;a<h.length;a++)if(objectsAreEqual(t[a],s[h[a]]))return s}.bind(this),l=this.data.filter(c);if(l&&l.length>0)a&&a(l);else{var d,u=this.buildURL(t,o);d={params:{$filter:u}},null!=u&&0!=u.length||(d={}),this.fetch(d,{success:function(t){if(a){let s=t.filter(c);a(s)}}.bind(this),error:function(t){r&&r()}},void 0,{lookup:!0})}},this.getColumn=function(t){var s=[];return $.each(this.data,(function(a,r){s.push(r[t])})),s},this.onBackNomalState=function(){this.$scope.safeApply(function(){this.busy=!1,this.editing=!1,this.inserting=!1;let t=this.dependentData&&this.dependentData.filter((t=>t.inserting||t.editing));!t||t.forEach((t=>t.cancel())),this.noticeStatusChange()}.bind(this))},this.cancel=function(){this.inserting&&(this.cursor>=0?this.active=this.data[this.cursor]:this.active={}),this.editing&&(this.active=this.lastActive),this.onBackNomalState(),this.lastAction="cancel",this.dependentData&&$(this.dependentData).each((function(){this.cleanDependentBuffer()})),this.batchServiceData=[]},this.removeODataFields=function(t){for(var s in t)t.hasOwnProperty(s)&&t[s]&&t[s].__deferred&&delete t[s];return t},this.retrieveDefaultValues=function(t,s){if(this.isEventData()||this.isLocalData()||this.isOfflineMode())this.$scope.safeApply(function(){this.active={},(this.isLocalData()||this.isOfflineMode())&&(this.active[this.keys[0]]=this.uuidv4()),this.updateWithParams(),s&&s()}.bind(this));else if(t)this.active=t||{},this.updateWithParams(),s&&s();else if(this.entity.indexOf("cronapi")>=0||this.isOData()){var a=this.entity;a+=this.entity.endsWith("/")?"__new__":"/__new__",this.$promise=$httpLegacy({method:"GET",url:this.removeSlash((window.hostApp||"")+a),headers:this.headers}).success(function(t,a,r,o){this.isOData()?(this.active=this.removeODataFields(t.d),this.normalizeData(this.active)):this.active=t,this.updateWithParams(),s&&s()}.bind(this)).error(function(t,a,r,o){this.active={},this.updateWithParams(),s&&s()}.bind(this))}else this.active={},this.updateWithParams(),s&&s()};var updateObjectValue=function(t,s,a){for(var r=s.split("."),o=0;o<r.length;o++){var h=r[o];o==r.length-1?t[h]=a:(void 0!==t[h]&&null!=t[h]||(t[h]={}),t=t[h])}};this.updateWithParams=function(){if(this.parameters){var t=this.getParametersMap();for(var s in t)t.hasOwnProperty(s)&&updateObjectValue(this.active,s,t[s])}},this.resetFieldsStatus=function(){var t=setInterval((function(){$('input[ng-model*="'+this.name+'."]').is(":visible")?($('input[ng-model*="'+this.name+'."]:invalid:empty').removeClass("ng-invalid ng-invalid-required"),clearInterval(t)):$('input[ng-model*="'+this.name+'."].cronMultiSelect')&&clearInterval(t)}),100)},this.noticeStatusChange=function(){this.changeTitle(),this.handleBeforeCallBack(this.onChangeStatus)},this.changeTitle=function(){if($("#starter").length&&$("#starter").attr("primary-datasource")===this.name){var t=this.translate.instant($rootScope.viewTitleOnly),s=$rootScope.systemName&&$rootScope.systemName.length?" - "+$rootScope.systemName:"";this.inserting?t+=" - "+this.translate.instant("Inserting"):this.editing&&(t+=" - "+this.translate.instant("Editing")),$("h1.title:first").text(t),window.document.title=t+s}},this.startInserting=function(t,s){this.retrieveDefaultValues(t,function(){if(this.active.__$id||(this.active.__$id=uuid()),this.children&&this.children.length){let t=this.getKeyValues(this.active);for(let s in t)t.hasOwnProperty(s)&&(null!=t[s]&&null!=t[s]||"_objectKey"!=s||(this.active[s]="$autogenerated$"+this.uuidv4()))}this.inserting=!0,this.onStartInserting&&this.onStartInserting(),s&&s(this.active),this.events.creating&&this.callDataSourceEvents("creating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()}.bind(this))},this.operationPouchDB=function(t,s,a){if(!SyncService.synchronizing&&(this.hasOfflineSupport()||this.isLocalData())&&t&&"GET"!==t){let r=this.getPouchDB();"DELETE"==t?r.get(s._objectKey).then(function(t){return r.remove(t)}.bind(this)).then(a).catch((function(t){console.error(t)})):this.$scope.cronapi.internal.updatePouchDB(r,[s],a)}},this.getPouchDB=function(){return cronapi.internal.getPouchDB(_self.localDBName)},this.isNavigatorOffline=function(){return!navigator.onLine},this.hasOfflineSupport=function(){return this.offline},this.isOfflineMode=function(){return this.isNavigatorOffline()&&this.hasOfflineSupport()},this.startEditing=function(t,s){if(t)this.active=this.copy(t),this.lastActive=t;else{if(0==this.data.length)return void this.startInserting(null,s);this.lastActive=this.active,this.active=this.copy(this.active)}this.editing=!0,s&&s(this.active),this.events.editing&&this.callDataSourceEvents("updating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()},this.removeSilent=function(t,s,a){this.remove(t,null,!1,s,a,!0)},this.remove=function(t,s,a,r,o,h){this.busy=!0;var c=async function(t,s){t||(t=this.active);var h=this.getKeyValues(t,a);s=s||function(s,a,o){if(!o){for(var c=0;c<this.data.length;c++){var l;if(t.__$id&&this.data[c].__$id)l=this.data[c].__$id==t.__$id;else{var d=this.getKeyValues(this.data[c]);for(var u in h)if(h.hasOwnProperty(u)){if(!d[u]||d[u]!==h[u]){l=!1;break}l=!0}}if(l){if(this.dependentLazyPost||this.batchPost){var p={};this.copy(this.data[c],p),p.__status="deleted",p.__originalIdx=c,this.events.memorydelete&&this.callDataSourceEvents("memorydelete",p),"inserted"!=this.data[c].__status&&(this.postDeleteData||(this.postDeleteData=[]),this.postDeleteData.push(p),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData))}this.data.splice(c,1);var f=c-1;f<0&&(f=0),f>this.data.length-1&&(f=this.data.length),this.data[f]?(this.active=this.data[f],this.cursor=f):(this.active=null,this.cursor=-1),this.onBackNomalState();break}}this.handleAfterCallBack(this.onAfterDelete),r&&r(t),this.events.delete&&a&&this.callDataSourceEvents("delete",t)}}.bind(this),await this.handleBeforeCallBack(this.onBeforeDelete)&&(!this.dependentLazyPost&&!this.batchPost||a?service.remove(this.getDeletionURL(t,a),t).$promise.error(o).then(s):s())}.bind(this);if(!a&&!h&&this.deleteMessage&&this.deleteMessage.length>0){let a={title:this.translate.instant("yes"),value:function(){c(t,s)}},r=[{title:this.translate.instant("no"),primaryValue:"true",value:()=>{this.filter()}},a];window.cronapi.notification.confirmDialogAlert("warning",this.translate.instant("Users.view.Confirmacao"),this.deleteMessage,r)}else c(t,s)},this.getKeyValues=function(rowData,forceOriginalKeys,useKeys){for(var keys=useKeys||this.keys,keyValues={},i=0;i<keys.length;i++){var key=keys[i],rowKey=null;try{rowKey=Array.isArray(rowData)?eval("rowData[0]."+key):eval("rowData."+key)}catch(t){}keyValues[key]=rowKey}return keyValues}.bind(this),this.getFirstKeyValue=function(rowData,forceOriginalKeys){for(var keys=this.keys,keyValues={},i=0;i<this.keys.length;i++){var key=this.keys[i],rowKey=null;try{rowKey=eval("rowData."+key)}catch(t){}return rowKey}}.bind(this),this.objectIsEquals=function(t,s){var a=this.getKeyValues(t),r=this.getKeyValues(s);for(var o in a)if(a.hasOwnProperty(o)){if(!r.hasOwnProperty(o))return!1;if(a[o]!==r[o])return!1}return!0},this.hasNext=function(){return this.data&&this.cursor<this.data.length-1},this.hasPrevious=function(){return this.data&&this.cursor>0},this.order=function(t){this._savedProps.order=t},this.getActiveValues=function(){return this.active&&!this._activeValues&&$rootScope.$watch(function(t){return this.active}.bind(this),function(t,s){this._activeValues=this.getRowValues(this.active)}.bind(this),!0),this._activeValues},this.__defineGetter__("activeValues",(function(){return _self.getActiveValues()})),this.getRowValues=function(t){var s=[];for(var a in t)t.hasOwnProperty(a)&&s.push(t[a]);return s},this.next=function(){return this.hasNext()||this.nextPage(),this.active=this.copy(this.data[++this.cursor],{}),this.active},this.nextPage=function(t){var s=(window.hostApp||"")+this.entity;this.hasNextPage()?(1==this.apiVersion||-1==s.indexOf("/cronapi/")?this.offset=parseInt(this.offset)+parseInt(this.rowsPerPage):this.offset=parseInt(this.offset)+1,this._savedProps&&this._savedProps.params&&delete this._savedProps.params.$skip,this.fetch(this._savedProps,{success:function(a){(!a||a.length<parseInt(this.rowsPerPage))&&(1!=this.apiVersion&&-1!=s.indexOf("/cronapi/")||(this.offset=parseInt(this.offset)-this.data.length)),t&&t()},canceled:function(){t&&t()},error:function(){t&&t()}},!0)):t&&t()},this.prevPage=function(){this.append||this.preppend||(this.offset=parseInt(this.offset)-this.data.length,this._savedProps&&this._savedProps.params&&delete this._savedProps.params.$skip,this.offset<0?this.offset=0:this.offset>=0&&this.fetch(this._savedProps,{success:function(t){t&&0!==t.length||(this.offset=0)}},!0))},this.hasNextPage=function(){return this.hasMoreResults&&-1!=this.rowsPerPage},this.hasPrevPage=function(){return this.offset>0&&!this.append&&!this.prepend},this.previous=function(){if(!this.hasPrevious())throw"Dataset Overflor Error";return this.active=this.copy(this.data[--this.cursor],{}),this.active},this.findObjInDs=function(t,s){var a=!1,r=null;if(null==t)return r;var o=null,h=null;let c=s=>{var r=this.data[s];for(var o in l)a=!(!t.hasOwnProperty(o)||t[o]!==r[o]);return a};if("object"==typeof t&&null!==t){var l;this.data.length>0&&(l=this.getKeyValues(this.data[0]));for(var d=0;d<this.data.length;d++)if(t.__$id&&this.data[d].__$id&&(a=t.__$id==this.data[d].__$id)||(a=c(d)),a){o=d,h=this.copy(this.data[o],{});var u=this.getKeyValues(this.data[o]),p=!0;for(var f in u)if(void 0===u[f]){p=!1;break}p||this.fetchChildren()}}else if(Array.isArray(this.keys))for(d=0;d<this.data.length;d++)this.data[d][this.keys[0]]===t&&(o=d,h=this.copy(this.data[o],{}),a=!0);return null!==h&&(r=h,s&&(r={cursor:o,obj:h})),r},this.goTo=function(t,s){var a=this.findObjInDs(t,!0);return null!==a?(this.cursor=a.cursor,this.active=a.obj,this.active):a},this.getCursor=function(){return this.cursor},this.filter=function(t,s){var a=this.offset;this.offset=0,this.fetch({path:t},{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=a},success:function(t){s&&s(t)}})},this.doSearchAll=function(t,s){this.searchTimeout=null;var a=this.offset;this.offset=0,this.fetch({params:{filter:"%"+t+"%",filterCaseInsensitive:!!s}},{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=a}})},this.searchAll=function(t,s){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.searchTimeout=setTimeout(function(){this.doSearchAll(t,s)}.bind(this),500)},this.doSearch=function(t,s){this.searchTimeout=null;var a,r=this.offset;this.offset=0,this.isOData()?(a={params:{$filter:t}},null!=t&&0!=t.length||(a={})):a={params:{filter:t,filterCaseInsensitive:!!s}},this.fetch(a,{beforeFill:function(t){this.cleanup()},error:function(t){this.offset=r}})},this.search=function(t,s){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.caseInsensitive=s,this.terms=t,this.searchTimeout=setTimeout(function(){this.doSearch(t,s)}.bind(this),500)},this.refresh=function(t,s,a){this.cleanup(),void 0===a&&(a=0),t.length>=a&&this.filter(s+"/"+t)},this.cleanup=function(t){t||(t={}),this.offset=0,this.rowsCount=-1,this.data.length=0,t.ignoreAtive||(this.cursor=-1,this.active={}),this.hasMoreResults=!1},this.current=function(){return this.active||this.data[0]},this.getLink=function(t){if(this.links)for(var s=0;s<this.links.length;s++)if(this.links[s].rel==t)return this.links[s].href},this.isOData=function(){return this.entity.indexOf("odata")>0},this.isEventData=function(){return void 0!==this.onGET&&null!==this.onGET&&""!==this.onGET},this.isLocalData=function(){return 0==this.entity.indexOf("local://")},this.normalizeValue=function(t,s,a){return null!=s&&null!=s||(s=!1),window.oDataToObj(t,s,a)},this.normalizeObject=function(t){for(var s in t)if(t.hasOwnProperty(s)){var a=t[s];if(a)if("object"==typeof a)this.normalizeObject(a);else{let r=this.getFieldFromSchema(s);t[s]=this.normalizeValue(a,void 0,r)}}},this.normalizeData=function(t){if(t){delete t.__metadata;for(var s=0;s<t.length;s++)this.normalizeObject(t[s])}return t},this.getAllData=function(){var t=[];if(t=t.concat(this.data),this.memoryData)for(key in this.memoryData)if(this.memoryData.hasOwnProperty(key)){var s=this.memoryData[key];s.data&&(t=t.concat(s.data))}return this.postDeleteData&&(t=t.concat(this.postDeleteData)),t},this.getParametersMap=function(parentId){var map={},parameters,obj,mapParams;if(parentId){parameters=this.parametersExpression;for(var arr=eval(this.dependentLazyPost).getAllData(),i=0;i<arr.length;i++)if(arr[i].__$id==parentId){obj=arr[i];break}mapParams=this.getParametersMap()}else parameters=this.parameters;if(parameters&¶meters.length>0)for(var parts=parameters.split(";"),i=0;i<parts.length;i++){var part=parts[i],binary=part.split("=");if(2==binary.length){var value=binary[1];if(parentId)if(binary[1].match(DEP_PATTERN)){var g=DEP_PATTERN.exec(value);if(-1!=g[1].indexOf(".active.")){var field=g[1].replace(this.dependentLazyPost+".active.","");obj&&(map[binary[0]]=obj[field])}else map[binary[0]]=mapParams[binary[0]]}else map[binary[0]]=mapParams[binary[0]];else map[binary[0]]=binary[1]?this.normalizeValue(value,!0):null}}return map},this.setParameters=function(t){this.parameters=t,this.fetch({params:{}})},this.getParametersBatchExpression=function(parentId){var expression="",parameters,obj;parameters=this.parametersExpression;let ds=eval(this.dependentLazyPost);if(ds){var arr=ds.getAllData();if(ds.active&&ds.active.__$id==parentId)obj=ds.active;else for(var i=0;i<arr.length;i++)if(arr[i].__$id==parentId){obj=arr[i];break}}if(parameters&¶meters.length>0)for(var parts=parameters.split(";"),i=0;i<parts.length;i++){var part=parts[i],binary=part.split("=");if(2==binary.length){var value=binary[1];if(binary[1].match(DEP_PATTERN)){var g=DEP_PATTERN.exec(value);if(-1!=g[1].indexOf(".active.")){var field=g[1].replace(this.dependentLazyPost+".active.","");obj&&(""!=expression&&(expression+=","),expression+=binary[0]+":$"+parentId+"."+field)}}}}return expression},this.removeSlash=function(t){return 0==t.indexOf("http://")?"http://"+t.substring(7).split("//").join("/"):0==t.indexOf("https://")?"https://"+t.substring(8).split("//").join("/"):t},this.setDataSourceEvents=function(t){this.events=t},this.addDataSourceEvents=function(t){for(var s in t)t.hasOwnProperty(s)&&(this.events[s]||(this.events[s]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[s])&&(this.events[s]=[this.events[s]]),this.events[s].push(t[s]))},this.removeDataSourceEvents=function(t){for(var s in t)if(t.hasOwnProperty(s)){this.events[s]||(this.events[s]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[s])&&(this.events[s]=[this.events[s]]);for(var a=[].concat(this.events[s]),r=0;r<a.length;r++)a[r]==t[s]&&this.events[s].splice(r,1)}},this.callDataSourceEvents=function(t,s){if(this.events){var a=this.events[t];if(a){"[object Array]"!==Object.prototype.toString.call(a)&&(a=[a]);for(var r=[],o=1;o<arguments.length;o++)r.push(arguments[o]);var h=[];for(o=0;o<a.length;o++)h.push(a[o]);for(var c=0;c<h.length;c++)try{h[c].apply(null,r)}catch(t){console.log("Error","Event no more exist in datasource")}}}},this.storeInMemory=function(t){this.memoryData||(this.memoryData={});var s={data:[],cursor:this.cursor,params:this.getParametersMap(),rowCount:this.getRowsCount()};s.data=deepCopy(this.data,s.data),this.memoryData[t]=s},this.restoreFromMemory=function(t){this.memoryData||(this.memoryData={});var s=this.memoryData[t];return s&&(this.cursor=s.cursor,this.rowsCount=s.rowCount),delete this.memoryData[t],deepCopy(s.data)},this.hasPendingChanges=function(){var t=this.hasMemoryData;return this.children&&$(this.children).each((function(){t=t||this.hasPendingChanges()})),t},this.isPostingBatchData=function(){var isPosting=1==this.postingBatch;return this.dependentLazyPost&&(isPosting=isPosting||eval(this.dependentLazyPost).isPostingBatchData()),isPosting},this.fetchChildren=function(t){this.children?reduce(this.children,function(t,s){t.fetch({},(function(){s()}))}.bind(this),function(){t&&t()}.bind(this)):t&&t()};var splitExpression=function(t){var s,a=null;-1!=t.indexOf("@=")?(a=t.trim().split("@="),s="="):-1!=t.indexOf("<=")?(a=t.trim().split("<="),s="<="):-1!=t.indexOf(">=")?(a=t.trim().split(">="),s=">="):-1!=t.indexOf(">")?(a=t.trim().split(">"),s=">"):-1!=t.indexOf("<")?(a=t.trim().split("<"),s="<"):(a=t.trim().split("="),s="=");var r=typeof this.normalizeValue(a[1],!0);return this.isOData()?"="==s&&"string"==r?"startswith(tolower("+a[0]+"), "+a[1].toLowerCase()+")":"="==s?a[0]+" eq "+a[1]:"!="==s?a[0]+" ne "+a[1]:">"==s?a[0]+" gt {"+a[1]:">="==s?a[0]+" ge "+a[1]:"<"==s?a[0]+" lt "+a[1]:"<="==s?a[0]+" le "+a[1]:void 0:"string"==r?a[0]+"@"+s+"%"+a[1]+"%":a[0]+s+a[1]}.bind(this),parseFilterExpression=function(t){var s="";if(t){var a=t.split(";"),r=!0;if(a.length>0)for(var o=/[\w\d]+=.+/gm,h=0;h<a.length;h++){if(!a[h].match(o)){r=!1;break}}if(r)for(h=0;h<a.length;h++){var c=splitExpression(a[h]);""!=s&&(s+=this.isOData()?" and ":";"),s+=c}else s=t}return s}.bind(this),getQueryOperator=function(t){return"="==t?" eq ":"!="==t?" ne ":">"==t?" gt ":">="==t?" ge ":"<"==t?" lt ":"<="==t?" le ":void 0}.bind(this),executeRight=function(right){var result="";if(null!=right&&null!=right)if(right.startsWith(":")||right.startsWith("datetimeoffset'")||right.startsWith("datetime'"))result=right;else{if(right&&"string"==typeof right&&right.length>=2&&("'"==right.charAt(0)&&"'"==right.charAt(right.length-1)||'"'==right.charAt(0)&&'"'==right.charAt(right.length-1)))try{result=eval("'"+right.substring(1,right.length-1).replaceAll("'","\\'")+"'")}catch(e){result=eval(right)}else""!=right&&(result=eval(right));result instanceof Date?result="datetimeoffset'"+result.toISOString()+"'":"string"==typeof result?result="'"+result+"'":void 0!==result&&null!=result||(result="null")}return result}.bind(this);this.isEmpty=function(t){return""===t||null==t||"''"===t},this.getFieldFromSchema=function(t){if(this.schema)for(var s=0;s<this.schema.length;s++)if(this.schema[s].name===t)return this.schema[s].type;return null},this.parserCondition=function(t,s,a){var r="",o=t.type;if(s||(s="default"),t.args)for(var h=0;h<t.args.length;h++){var c=t.args[h],l=o;if(c.args&&c.args.length>0){var d=this.parserCondition(c,s);!this.isEmpty(d)||"ignore"!=s&&"clean"!=s?this.isEmpty(d)||(a&&(a.count=a.count?a.count+1:1),""!=r&&(r+=" "+l.toLowerCase()+" "),r+="( "+d+" ) "):a&&(a.clean="clean"==s)}else{d=executeRight(c.right);if(!this.isEmpty(d)||"ignore"!=s&&"clean"!=s&&"wait"!=s){if(!this.isEmpty(d)){var u=!0,p=void 0;if("DateTime"===this.getFieldFromSchema(c.left)&&-1===d.indexOf("datetime")&&(u=(p=this.$scope.cronapi.dateTime.getMomentObj(d)).isValid()),u)if(a&&(a.count=a.count?a.count+1:1),""!=r&&(r+=" "+l.toLowerCase()+" "),"%"==c.type)this.isLocalData()?r+="contains("+c.left+", "+d.toLowerCase()+")":r+="substringof("+d.toLowerCase()+", tolower("+c.left+"))";else if(p){var f=p.toDate().getTimezoneOffset(),v=timeZoneOffset-f;p.add(v,"minutes"),r+=c.left+getQueryOperator(c.type)+"datetimeoffset'"+p.toISOString()+"'"}else r+=c.left+getQueryOperator(c.type)+d;else"null"===d&&(r+=`${c.left} ${getQueryOperator(c.type)} null`)}}else a&&(a.clean="clean"==s,a.wait="wait"==s)}}return r.trim()}.bind(this),this.refreshData=function(t){if(!this.lastFetch||this.hasMemoryData||!this.enabled||this.inserting||this.editing)t&&t();else{window.Pace&&(window.Pace.options.ajax.trackWebSockets=!1,window.Pace.options.ajax.trackMethods=[]);var s=function(){window.Pace&&(window.Pace.options.ajax.trackWebSockets=!0,window.Pace.options.ajax.trackMethods=["PUT","POST","GET"]),t&&t()},a={success:s,error:s};this.lastFilter=null,this.lastFetch.fetchOptions=this.lastFetch.fetchOptions||{},this.lastFetch.fetchOptions.active=this.copy(this.active),this.lastFetch.fetchOptions.active.__$id=void 0,this.fetch(this.lastFetch.properties,a,this.lastFetch.isNextOrPrev,this.lastFetch.fetchOptions,!0)}},this.startAutoRefresh=function(){this.autoRefresh>0&&setTimeout(function(){this.refreshData(function(){this.startAutoRefresh()}.bind(this))}.bind(this),this.autoRefresh)},this.isParentBusy=function(){return!!this.dependentLazyPost&&(eval(this.dependentLazyPost).busy||eval(this.dependentLazyPost).isParentBusy())},this.fetch=function(properties,callbacksObj,isNextOrPrev,fetchOptions,silent,fromVisibleEvent){fetchOptions||(fetchOptions={});let busy=this.busy,masterDetail=this.parameters&&this.parameters.length>0;if(fetchOptions.ignoreBusy&&(busy=!1),busy||this.postingBatch||!masterDetail&&this.isParentBusy())return void setTimeout(function(){this.fetch(properties,callbacksObj,isNextOrPrev,fetchOptions)}.bind(this),1e3);var callbacks=callbacksObj||{};this.lastFetch={properties:properties,isNextOrPrev:isNextOrPrev,fetchOptions:fetchOptions};var sucessHandler=function(data,headers,raw){var springVersion=!1;this.responseHeaders=headers||{};var total=-1;this.entity.indexOf("//")>-1&&this.entity.indexOf("://")<0&&(data=[]),raw||(data?"[object Array]"!==Object.prototype.toString.call(data)&&(data&&data.links&&"[object Array]"===Object.prototype.toString.call(data.content)?(this.links=data.links,data=data.content,springVersion=!0):this.isOfflineMode()?(total=data.total_rows,data=this.$scope.cronapi.internal.normalizePouchDBData(data.rows,!0)):this.isOData()?(total=parseInt(data.d.__count),data=data.d.results,this.normalizeData(data)):this.isLocalData()?(total=data.total_rows,data=data.rows,this.normalizeData(data)):data=[data]):data=[]);for(var n=0;n<data.length;n++)data[n].__$id||(data[n].__$id=uuid());if(!fetchOptions.lookup&&(this.fetched=!0,callbacks.beforeFill&&callbacks.beforeFill.apply(this,this.data),isNextOrPrev?(this.prepend&&Array.prototype.unshift.apply(this.data,data),this.append&&Array.prototype.push.apply(this.data,data),this.prepend||this.append||(Array.prototype.push.apply(this.data,data),fetchOptions.ignoreAtive||(this.data.length>0?fetchOptions.active?this.goTo(fetchOptions.active):this.$scope.safeApply((()=>{this.active=data[0],this.cursor=0})):(this.active={},this.cursor=-1)))):(this.cleanup(fetchOptions),-1!=total&&(this.rowsCount=total),Array.prototype.push.apply(this.data,data),this.data.length>0&&(fetchOptions.ignoreAtive||(fetchOptions.active?this.goTo(fetchOptions.active):this.$scope.safeApply((()=>{this.active=data[0],this.cursor=0}))))),this.columns=[],this.data.length>0))for(var i=0;i<this.data[0].length;i++)this.columns.push(this.getColumn(i));if(callbacks.success&&callbacks.success.call(this,data),!fetchOptions.lookup){this.events.read&&this.callDataSourceEvents("read",data),this.hasMoreResults=data.length>=this.rowsPerPage,springVersion&&(this.hasMoreResults=null!=this.getLink("next")),this.isOfflineMode()&&(this.hasMoreResults=!1),this.autoPost&&this.startAutoPost(),this.loaded=!0,this.loadedFinish=!0,this.lastLoadedTime=Date.now(),this.handleAfterCallBack(this.onAfterFill);var thisDatasourceName=this.name;this.isOData()||$("datasource").each((function(idx,elem){var dependentBy=null,dependent=window[elem.getAttribute("name")];if(dependent&&""!==elem.getAttribute("dependent-by")&&null!=elem.getAttribute("dependent-by")){try{dependentBy=JSON.parse(elem.getAttribute("dependent-by"))}catch(ex){dependentBy=eval(elem.getAttribute("dependent-by"))}dependentBy?dependentBy.name==thisDatasourceName&&(dependent.filterURL||eval(dependent.name).fetch()):console.log("O dependente "+elem.getAttribute("dependent-by")+" do pai "+thisDatasourceName+" ainda não existe.")}}))}if("insert"==this.startMode&&(this.startMode=null,this.startInserting()),"edit"==this.startMode&&(this.startMode=null,this.startEditing()),this.autoRefresh>0&&!this.autoRefreshStarted&&(this.autoRefreshStarted=!0,this.startAutoRefresh()),!this.isOfflineMode()&&this.hasOfflineSupport()){var db=this.getPouchDB();this.$scope.cronapi.internal.updatePouchDB(db,data)}}.bind(this);if(this.busy)return void(callbacks.canceled&&callbacks.canceled());if(this.entity.indexOf("//")>-1&&this.entity.indexOf("://")<0)return void(callbacks.canceled&&callbacks.canceled());if(!this.enabled)return this.cleanup(),void(callbacks.canceled&&callbacks.canceled());var props=properties||{};props.params=props.params||{};var resourceURL=(window.hostApp||"")+this.entity+(props.path||this.lastFilterParsed||""),filter="",order="",cleanData=!1,canProceed=!0,urlParams;if(this.parameters&&this.parameters.length>0){var parsedParameters;parsedParameters=fetchOptions.lookup?this.$interpolate(this.parametersExpression)(this.$scope):this.parameters;for(var parts=parsedParameters.split(";"),partsExpression=this.parametersExpression.split(";"),i=0;i<parts.length;i++){var part=parts[i],partExpression=partsExpression[i],binary=part.split("="),binaryExpression=partExpression.split("=");if(2==binary.length){var filterClause,g=DEP_PATTERN.exec(binaryExpression[1]);if((this.isEmpty(binary[1])||this.isAutoGeneratedValue(binary[1]))&&this.dependentLazyPost&&g[1]&&g[1].startsWith(this.dependentLazyPost+".")){if("clean"==this.parametersNullStrategy||"default"==this.parametersNullStrategy){cleanData=!0;var dds=eval(this.dependentLazyPost);filterClause=dds.active&&dds.active.__$id?eval(this.dependentLazyPost).active.__$id:"memory"}}else this.isEmpty(binary[1])?"clean"!=this.parametersNullStrategy&&"default"!=this.parametersNullStrategy||(filterClause="null",cleanData=!0):filterClause=this.getObjectAsString(this.normalizeValue(binary[1],!0),!1);filterClause&&(filterClause=binary[0]+getQueryOperator("=")+filterClause,""!=filter&&(filter+=this.isOData()?" and ":";"),filter+=filterClause)}}}if(!canProceed)return void(callbacks.canceled&&callbacks.canceled());let waitData=!1;if(this.condition){try{var parsedCondition;parsedCondition=fetchOptions.lookup?this.$interpolate(this.conditionExpression)(this.$scope):this.condition;var obj=JSON.parse(parsedCondition);if("object"==typeof obj){var resultData={};obj.expression?this.conditionOdata=this.parserCondition(obj.expression,this.parametersNullStrategy,resultData):this.conditionOdata=this.parserCondition(obj,this.parametersNullStrategy,resultData);var filterCount=0;let t=this.conditionExpression.match(/{{(?!null).*?}}/g);if(t&&(filterCount=t.length),!cleanData&&resultData.clean&&(cleanData=!0),!cleanData&&resultData.wait&&(waitData=!0),cleanData||"one"!==this.loadDataStrategy||resultData.count&&!(resultData.count<1)||(cleanData=!0),!cleanData&&"all"===this.loadDataStrategy&&filterCount&&(!resultData.count||resultData.count<filterCount)&&(cleanData=!0),cleanData||"button"!==this.loadDataStrategy||"button"===fetchOptions.origin||(cleanData=!0),obj.params)for(var i=0;i<obj.params.length;i++){var value=obj.params[i].fieldValue;value.length>=2&&"'"==value.charAt(0)&&"'"==value.charAt(value.length-1)&&(value=value.substring(1,value.length-1)),""!==value&&null!=value&&(props.params[obj.params[i].fieldName]=value)}}else this.conditionOdata=this.condition}catch(t){console.log(t)}var conditionFilter=parseFilterExpression(this.conditionOdata);conditionFilter&&(""!=filter&&(filter+=this.isOData()?" and ":";"),filter+=conditionFilter)}if(this.orderBy)for(var orders=this.orderBy.split(";"),i=0;i<orders.length;i++){var orderField=orders[i];orderField&&(""!=order&&(order+=this.isOData()?",":";"),this.isOData()?order+=orderField.replace("|ASC"," asc").replace("|DESC"," desc"):order+=orderField)}if(this.dependentLazyPost&&!this.parameters&&!this.condition&&!fromVisibleEvent&&eval(this.dependentLazyPost).active){var checkRequestId="",keyDependentLazyPost=this.getKeyValues(eval(this.dependentLazyPost).active);for(var key in keyDependentLazyPost){checkRequestId=keyDependentLazyPost[key];break}if(checkRequestId&&checkRequestId.length>0&&-1==resourceURL.indexOf(checkRequestId))return void(callbacks.canceled&&callbacks.canceled())}this.rowsPerPage>0&&(this.isOData()?(void 0!==props.params.$top&&null!==props.params.$top||(props.params.$top=this.rowsPerPage),void 0!==props.params.$skip&&null!==props.params.$skip||(props.params.$skip=parseInt(this.offset)*parseInt(this.rowsPerPage)),props.params.$inlinecount="allpages"):1==this.apiVersion||-1==resourceURL.indexOf("/cronapi/")?(props.params.limit=this.rowsPerPage,props.params.offset=this.offset):(props.params.size=this.rowsPerPage,props.params.page=this.offset));var paramFilter=null;this.isOData()&&props.params.$filter&&(paramFilter=props.params.$filter),!this.isOData()&&props.params.filter&&(paramFilter=props.params.filter),paramFilter&&(filter&&""!=filter?this.isOData()?(filter+=" and (",filter+=paramFilter+")"):(filter+=";",filter+=paramFilter):filter=paramFilter);var paramOrder=null,localSuccess;if(this.isOData()&&props.params.$orderby&&(paramOrder=props.params.$orderby),!this.isOData()&&props.params.order&&(paramOrder=props.params.order),paramOrder&&(order=paramOrder),filter&&(this.isOData()?props.params.$filter=filter:props.params.filter=filter),order&&(this.isOData()?props.params.$orderby=order:props.params.order=order),this.hasMemoryData&&filter){if(this.memoryData||(this.memoryData={}),this.lastFilter==filter)return void(callbacks.canceled&&callbacks.canceled());var id=filter,mem=this.memoryData[id];if(mem){this.storeInMemory(this.lastFilter);var data=this.restoreFromMemory(id);return this.lastFilter=filter,void sucessHandler(data,null,!0)}localSuccess=function(){this.storeInMemory(this.lastFilter)}.bind(this)}if(this.stopAutoPost(),this._savedProps=props,waitData)return void setTimeout(function(){fetchOptions.ignoreBusy=!0,this.fetch(properties,callbacksObj,isNextOrPrev,fetchOptions)}.bind(this),100);if(cleanData)return localSuccess&&localSuccess(),this.lastFilter=filter,void sucessHandler([],null,!0);this.busy=!0;var httpError=function(t,s,a,r){this.busy=!1,silent||this.handleError(t),callbacks.error&&callbacks.error.call(this,t)}.bind(this);let callService=function(){this.$promise=this.getService("GET")({method:"GET",url:this.removeSlash(resourceURL),params:props.params,headers:this.headers,filter:filter,offlineMode:this.isOfflineMode()}).success(function(t,s,a,r){localSuccess&&localSuccess(),this.lastFilter=filter,this.busy=!1,sucessHandler(t,a?a():null)}.bind(this)).error(function(t,s,a,r){httpError(t,s,a,r)}.bind(this))}.bind(this);this.fetchOnVisible&&!this.parent.is(":visible")?this.holdServiceCall=callService:(this.holdServiceCall=void 0,callService())},this.getRowsCount=function(){return-1!=this.rowsCount?this.rowsCount:this.data.length},this.notifyObservers=function(){for(var t in this.observers)if(this.observers.hasOwnProperty(t)){var s=this.observers[t];$timeout(function(){s.notify.call(s,this.active)}.bind(this),1)}},this.notify=function(t){if(t){var s=this.watchFilter;s=s.replace(/\{([A-z][A-z|0-9]*)\}/gim,(function(s,a){return t.hasOwnProperty(a)?t[a]:""})),this.fetch({params:{q:s}})}},this.addObserver=function(t){this.observers.push(t)},this.sum=function(t){for(var s=0,a=0;a<this.data.length;a++)this.data[a][t]&&(s+=this.data[a][t]);return s},this.copy=function(t,s,a){if(null===t||"[object Object]"!==Object.prototype.toString.call(t))return t;for(var r in s=s||{},t)t.hasOwnProperty(r)&&-1==r.indexOf("$$")&&(s[r]=this.copy(t[r]));if(a)for(var o=0;o<this.keys.length;o++){var h=s[r=this.keys[o]];""!=h&&null!=h||delete s[r]}return s};var deepCopyArray=function(t,s){if(null===t||"[object Array]"!==Object.prototype.toString.call(t))return t;s=s||[];for(var a=0;a<t.length;a++)s.push(deepCopy(t[a]));return s},deepCopy=function(t,s){if("[object Array]"===Object.prototype.toString.call(t))return deepCopyArray(t,s);if(null===t||"[object Object]"!==Object.prototype.toString.call(t))return t;for(var a in s=s||{},t)t.hasOwnProperty(a)&&(s[a]=deepCopy(t[a]));return s};if(this.startAutoPost=function(){this.unregisterDataWatch=$rootScope.$watch(function(){return this.data}.bind(this),function(t,s){if(this.enabled){var a=t.length-s.length;if(a>0)for(var r=1;r<=a;r++)this.insert(t[t.length-r],(function(){}));else if(a<0){var o=this,h=s.filter((function(s){return 0==t.filter((function(t){return o.objectIsEquals(s,t)})).length}));for(r=0;r<h.length;r++)this.remove(h[r],(function(){}))}}else this.unregisterDataWatch()}.bind(this))},this.stopAutoPost=function(){this.unregisterDataWatch&&(this.unregisterDataWatch(),this.unregisterDataWatch=void 0)},this.hasDataBuffered=function(){return!!(this.dependentBufferLazyPostData&&this.dependentBufferLazyPostData.length>0)},window.afterDatasourceCreate){var args=[$q,$timeout,$rootScope,$window,Notification];window.afterDatasourceCreate.apply(this,args)}this.init()};return this.storeDataset=function(t){this.datasets[t.name]=t},this.initDataset=function(props,scope,$compile,$parse,$interpolate,instanceId,translate){var endpoint=props.endpoint?props.endpoint:"",dts=new DataSet(props.name,scope,props.fetchOnVisible);let canStoreDataset=!0;$rootScope[props.name]&&!$rootScope[props.name].insideModal&&props.insideModal?(canStoreDataset=!1,console.log(`%c${translate.instant("Datasource.Error").toUpperCase()} - ${translate.instant("Datasource.Duplicate").toUpperCase()}${props.name.toUpperCase()}`,"background: #000; color: #FFF; font-size:14px;")):($rootScope[props.name]=dts,window[props.name]=dts,$rootScope[props.name+".instanceId"]=instanceId);var defaultApiVersion=1;if(dts.entity=props.entity,dts.localDBName=props.entity,!isCronapiApiPath(dts.entity))if(dts.entity.match(DS_ID))dts.entity="api/cronapi/odata/v2/"+dts.entity.replaceAll(".","/");else if(dts.isLocalData()){var path=dts.entity.substring(dts.entity.indexOf("//")+2,dts.entity.length).split("/");dts.localDBType=dts.entity.substring(0,dts.entity.indexOf("://")),dts.localDBName=path[0],dts.localDBStorage=path[1],dts.localDBVersion=path[2]||1}if(app&&app.config&&app.config.datasourceApiVersion&&(defaultApiVersion=app.config.datasourceApiVersion),dts.translate=translate,dts.apiVersion=props.apiVersion?parseInt(props.apiVersion):defaultApiVersion,dts.keys=props.keys&&props.keys.length>0?props.keys.split(","):[],dts.rowsPerPage=props.rowsPerPage?props.rowsPerPage:100,dts.append=props.append,dts.prepend=props.prepend,dts.endpoint=props.endpoint,dts.filterURL=props.filterURL,dts.autoPost=props.autoPost,dts.autoRefresh=props.autoRefresh,dts.deleteMessage=props.deleteMessage,dts.enabled=props.enabled,dts.offset=props.offset?props.offset:0,dts.onError=props.onError,dts.defaultNotSpecifiedErrorMessage=props.defaultNotSpecifiedErrorMessage,dts.onAfterFill=props.onAfterFill,dts.onBeforeCreate=props.onBeforeCreate,dts.onAfterCreate=props.onAfterCreate,dts.onBeforeUpdate=props.onBeforeUpdate,dts.onAfterUpdate=props.onAfterUpdate,dts.onBeforeDelete=props.onBeforeDelete,dts.onAfterDelete=props.onAfterDelete,dts.onChangeStatus=props.onChangeStatus,dts.onGET=props.onGet,dts.onPOST=props.onPost,dts.onPUT=props.onPut,dts.onDELETE=props.onDelete,dts.dependentBy=props.dependentBy,dts.parameters=props.parameters,dts.parametersNullStrategy=props.parametersNullStrategy,dts.parametersExpression=props.parametersExpression,dts.checkRequired=props.checkRequired,dts.batchPost=props.batchPost,dts.condition=props.condition,dts.conditionExpression=props.conditionExpression,dts.orderBy=props.orderBy,dts.schema=props.schema,dts.startMode=props.startMode,dts.lazy=props.lazy,dts.$compile=$compile,dts.$parse=$parse,dts.$interpolate=$interpolate,dts.loadDataStrategy=props.loadDataStrategy,dts.offline=props.offline,dts.insideModal=props.insideModal,props.dependentLazyPost&&props.dependentLazyPost.length>0&&(dts.dependentLazyPost=props.dependentLazyPost,setTimeout((()=>{eval(dts.dependentLazyPost).addDependentDatasource(dts)}),0)),dts.dependentLazyPostField=props.dependentLazyPostField,dts.headers=props.headers,canStoreDataset&&this.storeDataset(dts),dts.allowFetch=!0,dts.dependentBy&&""!==dts.dependentBy&&""!==dts.dependentBy.trim()){dts.allowFetch=!1;var dependentBy=null;try{dependentBy=JSON.parse(dependentBy)}catch(ex){dependentBy=eval(dependentBy)}dependentBy&&dependentBy.loadedFinish&&(dts.allowFetch=!0)}if(!props.lazy&&dts.allowFetch&&"[object String]"!==Object.prototype.toString.call(props.watch)&&!props.filterURL){var queryObj={};setTimeout(function(){dts.fetch({params:queryObj},{success:function(t){t&&t.length>0&&(this.active=t[0],this.cursor=0)}})}.bind(this),0)}return props.lazy&&props.autoPost&&dts.startAutoPost(),props.watch&&"[object String]"===Object.prototype.toString.call(props.watch)&&(this.registerObserver(props.watch,dts),dts.watchFilter=props.watchFilter),props.filterURL&&props.filterURL.length>0&&dts.allowFetch&&dts.filter(props.filterURL),dts},this.registerObserver=function(t,s){this.datasets[t].addObserver(s)},this}]).directive("datasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate",function(t,s,a,r,o,h,c,l,d){return{restrict:"E",priority:9999999,scope:!0,template:"",link:function(t,s,a){!function(t,a,r){$(t).each((function(){var t=$(this),o=$(document.createElement(r),{html:t.html()});$.each(this.attributes,(function(){o.attr(this.name,this.value)})),o.attr("inside-modal",$(s).closest(".modal").length>0);var h=t.data("events");if(h)for(var c in h)for(var d in h[c])o[c](h[c][d].handler);l(o)(a),t.replaceWith(o)}))}(s,t,"cronapp-datasource")}}}]);let datasourceRepeat=1;app.directive("crnRepeat",["DatasetManager","$compile","$parse","$injector","$rootScope",function(DatasetManager,$compile,$parse,$injector,$rootScope){return{restrict:"A",priority:9999998,terminal:!0,link:function(scope,element,attrs,controllers,transclude){const indexAttribute=(t,s,a)=>{let r=t.parent().find(`[data-repeater=${s}]`);r.each&&r.each(((t,s)=>{$(s).find(`[${a}]`).each(((s,r)=>{let o=$(r),h=`${o.attr(`${a}`)}-cronapp-${t}`;o.attr(`${a}`,h)}))}))};$(window).ready((()=>{datasourceRepeat++;let isDatasource=!1,dataRepeaterId=`datasourceRepeat${datasourceRepeat}`;if(attrs.crnRepeat){if(scope.data=DatasetManager.datasets,scope.data[attrs.crnRepeat])scope[dataRepeaterId]=scope.data[attrs.crnRepeat],isDatasource=!0;else{scope[dataRepeaterId]=[];var value=$parse(attrs.crnRepeat)(scope);value instanceof String&&value.startsWith("[")&&value.endsWith("]")&&(value=eval(value)),scope[dataRepeaterId]=value}isDatasource?(element.attr("ng-init",attrs.crnRepeat+" = {}; "+attrs.crnRepeat+".active = rowData"),element.attr("ng-repeat",`rowData in ${dataRepeaterId}.data`)):element.attr("ng-repeat",`rowData in ${dataRepeaterId}`),element.attr("data-repeater",dataRepeaterId)}var tagName=element[0].tagName;$compile(element,null,9999998)(scope);let watchForRepeater=isDatasource?`${dataRepeaterId}.data`:`${dataRepeaterId}`;scope.$watchCollection(watchForRepeater,(function(t,s){"ion-slide"==tagName.toLowerCase()&&$injector.get("$ionicSlideBoxDelegate").update();indexAttribute(element,dataRepeaterId,"id"),indexAttribute(element,dataRepeaterId,"for")}))}))}}}]).directive("crnDatasource",["DatasetManager","$parse","$rootScope",function(t,s,a){return{restrict:"A",scope:!0,priority:9999998,link:function(a,r,o){a.data=t.datasets,a.data[o.crnDatasource]?a.datasource=a.data[o.crnDatasource]:(a.datasource={},a.datasource.data=s(o.crnDatasource)(a))}}}]).directive("cronappDatasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate","SyncService",function(t,s,a,r,o,h,c,l,d,u){return{restrict:"E",scope:!0,template:"",link:function(u,p,f){initDatasource(u,p,f,t,s,a,r,o,h,c,l,d)}}}]),angular.module("sync.service",[]).service("SyncService",["$http",function(t){let s={start:function(){this.dbSync=this.getSyncServicePouchDB(),this.observeConnection()},observeConnection:async function(){setInterval((()=>this.isNavigatorOffline()||this.synchronizeOfflineData()),15e3)},toQueue:function(t){let s={data:t,created:Date.now()};this.dbSync.post(s).catch((t=>console.error(t)))},synchronizeOnError:async function(t,s,a){this.synchronizing=!1,console.log("Error synchronizing doc",s,"response",t)},synchronizeOnSuccess:async function(t,s){try{await this.dbSync.remove(t),this.removeArray(t,s),s.length>0?this.sendData(s[0],s):this.synchronizing=!1}catch(t){this.synchronizing=!1}},canByPassError:function(t){let s=!1;if(t.data&&t.data.error&&t.data.error.message&&t.data.error.message.value){switch(t.data.error.message.value){case"Não foi possível encontrar a entidade requisitada.":case"Requested entity could not be found.":s=!0}}return s},sendData:async function(s,a){let r=s.data;t(r).then((()=>this.synchronizeOnSuccess(s,a))).catch((t=>this.canByPassError(t)&&this.synchronizeOnSuccess(s,a)||this.synchronizeOnError(t,s,a))),console.log(`Synchronization - sended record number ${a.length}`)},optimizeQueue:function(t){t.rows.filter((t=>"DELETE"===t.doc.data.method)).forEach((async s=>{t.rows.filter((t=>{let a=t.doc.data.originalObject||t.doc.data.rawData,r=s.doc.data.originalObject||s.doc.data.rawData;return a&&r&&a._objectKey===r._objectKey&&"DELETE"!==t.doc.data.method})).forEach((async s=>{this.dbSync.remove(s.doc),this.removeArray(s,t.rows)}))}));let s=[];return t.rows.forEach((t=>s.push(t.doc))),s.sort(((t,s)=>t.created-s.created)),s},synchronizeOfflineData:async function(){try{if(!this.synchronizing){let t=await this.dbSync.allDocs({include_docs:!0,attachments:!0});if(t.rows.length){console.log("Synchronization started"),this.synchronizing=!0;let s=this.optimizeQueue(t);this.sendData(s[0],s)}}}catch(t){console.log(t)}},removeArray(t,s){if(t&&s){let a=s.indexOf(t);a>-1&&s.splice(a,1)}},isNavigatorOffline:function(){return!navigator.onLine},getSyncServicePouchDB:function(){return cronapi.internal.getPouchDB("syncService")},synchronizing:null,dbSync:null,lastStatus:null};return s.start(),s}]);
|
|
@@ -2014,12 +2014,19 @@ angular.module('datasourcejs', [])
|
|
|
2014
2014
|
xhr.setRequestHeader('X-AUTH-TOKEN', _u?.token);
|
|
2015
2015
|
}
|
|
2016
2016
|
|
|
2017
|
-
|
|
2017
|
+
// Get CSRF token from localStorage (consistent with other implementations)
|
|
2018
|
+
const csrfToken = localStorage.getItem('csrfToken');
|
|
2018
2019
|
if (csrfToken) {
|
|
2019
|
-
xhr.setRequestHeader('X-
|
|
2020
|
+
xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
|
|
2020
2021
|
}
|
|
2021
2022
|
|
|
2022
2023
|
xhr.onreadystatechange = function(){
|
|
2024
|
+
if (xhr.readyState === 4) {
|
|
2025
|
+
const newToken = xhr.getResponseHeader('X-CSRF-TOKEN');
|
|
2026
|
+
if (newToken) {
|
|
2027
|
+
localStorage.setItem('csrfToken', newToken);
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2023
2030
|
if(xhr.readyState === 4 && xhr.status === 500){
|
|
2024
2031
|
var parser = new DOMParser();
|
|
2025
2032
|
var error = parser.parseFromString(xhr.response,"text/xml");
|