cronapp-common-js
Version:
Cronapp Commons Functions
1 lines • 84.8 kB
JavaScript
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)}))}}.b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NzExLTYuNDIsMi43MTFoLTU0LjgyNmMtMi40NzQsMC00LjYxNS0wLjg5Ny02LjQyMy0yLjcxMWMtMS44MDQtMS44MDctMi43MTItMy45NDktMi43MTItNi40MlYyOTIuMzU1ICAgSDE1NS4zMWMtMi42NjIsMC00Ljg1My0wLjg1NS02LjU2My0yLjU2M2MtMS43MTMtMS43MTQtMi41NjgtMy45MDQtMi41NjgtNi41NjZjMC0yLjI4NiwwLjk1LTQuNTcyLDIuODUyLTYuODU1bDEwMC4yMTMtMTAwLjIxICAgYzEuNzEzLTEuNzE0LDMuOTAzLTIuNTcsNi41NjctMi41N2MyLjY2NiwwLDQuODU2LDAuODU2LDYuNTY3LDIuNTdsMTAwLjQ5OSwxMDAuNDk1YzEuNzE0LDEuNzEyLDIuNTYyLDMuOTAxLDIuNTYyLDYuNTcxICAgQzM2NS40MzgsMjg1LjY5NiwzNjQuNTM1LDI4Ny44NDUsMzYyLjcyOSwyODkuNjQ4eiIgZmlsbD0iI2NlY2VjZSIvPgo8L2c+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.