cronapp-common-js 3.2.1-SP.4 → 4.0.0

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=/(\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=/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+)?)?S)?/,DEP_PATTERN=/\{\{(.*?)\|raw\}\}/,HTTP_STATUS=/HTTP\/1\.1 (\d+) (.*)/,DS_ID=/[\w\_\.\d]+/;const isCronapiApiPath=e=>/^\/?api\/cronapi\/.*\/?$/.test(e);(function(e){var t={callback:function(){},runOnLoad:!0,frequency:100,previousVisibility:null},a={};a.checkVisibility=function(e,t){if(jQuery.contains(document,e[0])){var n=t.previousVisibility,s=e.is(":visible");t.previousVisibility=s;var r=null==n;r?t.runOnLoad&&t.callback(e,s,r):n!==s&&t.callback(e,s,r),setTimeout(function(){a.checkVisibility(e,t)},t.frequency)}},e.fn.visibilityChanged=function(n){var s=e.extend({},t,n);return this.each(function(){a.checkVisibility(e(this),s)})}})(jQuery);var initDatasource=function(e,t,a,n,s,r,i,o,d,c,l,u){var p=parseInt(9999*Math.random());if(cronapi.internal.isJsonString(a.headers)){let e=JSON.parse(a.headers);e.push({key:"origin-path",type:"string",value:d.path()}),a.headers=JSON.stringify(e)}else{var g="origin-path:"+d.path();a.headers=void 0===a.headers||null===a.headers?g:a.headers.concat(";",g)}var y,h={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:o.instant("General.RemoveData"),headers:a.headers,autoPost:"true"===a.autoPost,autoRefresh:a.autoRefresh!==void 0&&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:o.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:$(t).attr("parameters"),conditionExpression:$(t).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:!(a.fetchOnVisible===void 0||null===a.fetchOnVisible)&&"true"===a.fetchOnVisible,offline:!("true"!==a.offline),insideModal:!("true"!==a.insideModal)},f={filter:!0,entity:!0,enabled:!0,parameters:!0};if(e.params){for(var m in e.params)if(e.params.hasOwnProperty(m)){var D=e.params[m];if(m.startsWith("$"+a.name+".")){var M=m.split(".");2==M.length&&("$filterMode"==M[1]?h.startMode=D:(y?y+=";":y="",y+=isNaN(D)?M[1]+"='"+D+"'":M[1]+"="+D))}}y&&(h.parameters=y,h.parametersExpression=y)}var L,p=parseInt(9999*Math.random()),v=n.initDataset(h,e,l,r,u,p,o);a.$observe("filter",function(e){v.isPostingBatchData()||(f.filter?s(function(){f.filter=!1},0):(s.cancel(L),L=s(function(){v.events.overRideRefresh?v.callDataSourceEvents("overRideRefresh","filter",e):v.filter(e,function(e){v.events.refresh&&v.callDataSourceEvents("refresh",e,"filter")}),v.lastFilterParsed=e},100)))}),y||a.$observe("parameters",function(e){v.isPostingBatchData()||v.parameters!=e&&(v.parameters=e,s.cancel(L),L=s(function(){v.callDataSourceEvents("changeDependency","parameters",v.parameters),v.events.overRideRefresh?v.callDataSourceEvents("overRideRefresh","parameters",v.parameters):v.fetch({params:{}},{success:function(e){v.events.refresh&&v.callDataSourceEvents("refresh",e,"parameters")}})},0))});let b={lastCondition:void 0,timeForCondition:void 0,typingSpeedLimit:1e3,maxWaitingValue:1e3,wait:function(){if(this.timeForCondition=0,this.lastCondition){let e=new Date().getTime()-this.lastCondition.getTime();e<this.typingSpeedLimit&&(this.timeForCondition=this.maxWaitingValue)}return this.lastCondition=new Date,this.timeForCondition}};a.$observe("condition",function(e){if(!v.isPostingBatchData()&&v.condition!=e){if(v.condition=e,"button"===v.loadDataStrategy)return;s.cancel(L),L=s(function(){v.callDataSourceEvents("changeDependency","condition",v.condition),v.events.overRideRefresh?v.callDataSourceEvents("overRideRefresh","condition",v.condition):v.fetch({params:{}},{success:function(e){v.events.refresh&&v.callDataSourceEvents("refresh",e,"condition")}})},b.wait())}}),a.$observe("enabled",function(e){var t="true"===e;v.enabled!=t&&(v.enabled=t,v.enabled&&(s.cancel(L),L=s(function(){v.events.overRideRefresh?v.callDataSourceEvents("overRideRefresh","enabled",v.parameters):v.fetch({params:{}},{success:function(e){v.events.refresh&&v.callDataSourceEvents("refresh",e,"enabled")}})},200)))}),a.$observe("entity",function(e){v.entity=e,v.entity.match(DS_ID)&&!isCronapiApiPath(v.entity)&&(v.entity="api/cronapi/odata/v2/"+v.entity.replaceAll(".","/")),f.entity?s(function(){f.entity=!1}):(s.cancel(L),L=s(function(){v.fetch({params:{}},{success:function(e){v.events.refresh&&v.callDataSourceEvents("refresh",e,"entity")}})},200))}),a.$observe("offline",function(e){v.offline="true"===e}),e.$on("$destroy",function(){c[a.name]&&c[a.name+".instanceId"]==p&&(c[a.name].destroy(),delete window[a.name],delete c[a.name],delete c[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(e){let t,a=this.getMainScope();if(cronapi.internal.isJsonString(e)){t={};let s=JSON.parse(e);for(var n in s){let e=s[n];if("blockly"===e.type){let n=this.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");t[e.key]=await a.$eval(n(e.value))}else t[e.key]="expression"===e.type?a.$eval(e.value):e.value}}return t},getHeaders:async function(e){let t;if(e&&0<e.length)if(!cronapi.internal.isJsonString(e)){t={};let n,s=e.trim().split(";");for(var a=0;a<s.length;a++)n=s[a].split(":"),2===n.length&&(t[n[0]]=n[1])}else t=await this.resolveExpressionMap(e);return t&&(t["X-From-DataSource"]="true"),t},onMatchRegex:function(e,t,a){return n=>{let s=e.exec(n);return s&&s.length?n.split(t).join(a+t):n}}};const $httpLegacy=e=>{var t={verb:e.method,successCallback:null,errorCallback:null,success:function(e){return this.successCallback=e,this},error:function(e){return this.errorCallback=e,this}};return DatasetManagerUtil.getHeaders(e.headers).then(function(t){if(e.headers=t||e.headers,e.offlineMode){SyncService.toQueue(e);let t=e.originalObject||e.rawData||e.data;this.successCallback(t,200,null,e)}else{let t=$http(e);t.then(e=>{this.successCallback&&this.successCallback(e.data,e.status,e.headers,e.config)}),t.catch(e=>{this.errorCallback&&this.errorCallback(e.data,e.status,e.headers,e.config)})}}.bind(t)),t};var DataSet=function(name,scope,fetchOnVisible){function reverseArr(e){if(e){for(var t=[],a=e.length-1;0<=a;a--)t.push(e[a]);return t}return[]}function toBase64(e,t){var a=new FileReader;a.readAsDataURL(e),a.onload=function(a){var e=a.target.result.substr(a.target.result.indexOf("base64,")+7);t(e)}}function uuid(){var e,t,a="";for(e=0;32>e;e++)t=0|16*Math.random(),(8==e||12==e||16==e||20==e)&&(a+="-"),a+=(12==e?4:16==e?8|3&t:t).toString(16);return a}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(e,t){t&&this.holdServiceCall&&this.holdServiceCall()}.bind(this),runOnLoad:!1,frequency:100}),this.Notification=Notification,this.$scope=scope,this.noImageUpload="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=",this.noFileUpload=NO_FILE_UPLOAD,this.$apply=function(e){scope.safeApply(e)}.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;this.odataFile=[],this.destroy=function(){},this.init=function(){var dsScope=this;service={save:function(e){return this.call(_self.entity,"POST",e,!0)},update:function(e,t){return this.call(e,"PUT",t,!1)},remove:function(e,t){return this.call(e,"DELETE",t,!0)},call:function(e,t,a){var n={},s=0<=e.indexOf("/cronapi/query/");if(s){n.inputs=[a];var r,i,o={};if(_self.busy=!0,e=e.replace("/specificSearch",""),e=e.replace("/generalSearch",""),_self&&_self.$scope&&_self.$scope.vars)for(var d in o.vars={},_self.$scope.vars)o.vars[d]=_self.$scope.vars[d];for(var c in _self.$scope)_self.$scope[c]&&_self.$scope[c].constructor&&"DataSet"==_self.$scope[c].constructor.name&&(o[c]={},o[c].active=_self.$scope[c].active);n.fields=o}else n=a;var l={};for(var c in _self.copy(n,l,!0),delete l.__original,delete l.__status,delete l.__originalIdx,delete l.__sender,delete l.__$id,delete l.__parentId,delete l.$$hashKey,delete l.__fromMemory,delete l.__odatafiles,delete l.__$masterExpression,l)-1<c.indexOf("__odataFile_")&&(l[c.replace("__odataFile_","")]=void 0,delete l[c]);for(var c in l)if(l.hasOwnProperty(c)){let e=l[c];_self.isAutoGeneratedValue(e)&&delete l[c]}var u=function(e,t,a,n,i){if(_self.busy=!1,r&&(_self.isOData()?null!=e.d&&null!=e.d.result?(_self.normalizeData(e.d.result),r(e.d.result,!0,i)):null==e.d?r(e,!0,i):(_self.normalizeObject(e.d),r(e.d,!0,i)):r(s?e.value:e,!0,i)),s||_self.isOData()){var o=e;_self.isOData()&&(o={},o.commands=e.__callback,_self.normalizeData(o.commands)),_self.$scope.cronapi.evalInContext(JSON.stringify(o))}},p=_self.getParentDatasource();let g=p.getBatchDataItem(n);if(g&&g.result){let e=p.batchServiceData.indexOf(g);p.batchServiceData.splice(e,1),$timeout(()=>{u(g.result)},0),this.$promise={}}else this.$promise=_self.getService(t,n)({method:t,url:_self.removeSlash((window.hostApp||"")+e),data:"DELETE"==t?null:n?JSON.stringify(l):null,headers:_self.headers,rawData:n?l:null,originalObject:n?n:null,urlPart:e,offlineMode:_self.isOfflineMode()}).success(u).error(function(e){_self.busy=!1;var t;t=_self.isOData()?e.error.message.value:s&&e.value?e.value:e,_self.handleError(t),i&&i(t)});return this.$promise.then=function(e){return r=e,this},this.$promise.error=function(e){return i=e,this},this}},this.isAutoGeneratedValue=function(e){return"string"==typeof e&&10<e.length&&(e.startsWith("$autogenerated$")||e.substring(1).startsWith("$autogenerated$"))},this.getIndexedDB=function(e){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:e,successCallback:null,errorCallback:null,type:null,args:null,success:function(e){return this.successCallback=e,this},error:function(e){return this.errorCallback=e,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(e){this.errorCallback&&this.errorCallback(e)}.bind(this),request.onsuccess=function(e){this.proceed(e.target.result)}.bind(this),request.onupgradeneeded=function(e){var t=e.target.result,a=t.createObjectStore(this.properties.objectStore,{keyPath:this.properties.key});a.transaction.oncomplete=function(){var e=t.transaction(this.properties.objectStore,"readwrite").objectStore(this.properties.objectStore);e.add({id:123,name:"Jose"})}.bind(this)}.bind(this)},proceed:function(e){if(this.type){var t=e.transaction(this.properties.objectStore,"readwrite"),a=t.objectStore(this.properties.objectStore),n=a[this.type].apply(a,this.args);n.onsuccess=function(e){this.successCallback&&("put"===this.type?this.successCallback(this.args[0]):this.successCallback(e.target.result))}.bind(this)}else this.successCallback&&this.successCallback()}}},this.batchServiceData=[],this.getBatchService=function(e){return function(t){var a={verb:e,properties:t,successCallback:null,errorCallback:null,success:function(e){return this.successCallback=e,this},error:function(e){return this.errorCallback=e,this}};return $timeout(function(){var n=this.getParentDatasource();let s=t.originalObject||t.rawData||t.data||this.active,r=this.entity;"PUT"==e&&(r=this.getEditionURL(s)),"DELETE"==e&&(r=this.getDeletionURL(s)),0<r.indexOf("/")&&(r=r.substring(r.lastIndexOf("/")+1,r.length)),n.batchServiceData.push({entity:r,data:s,promise:a}),a.successCallback&&a.successCallback.call(this,s,null,null,null,!0)}.bind(this)),a}.bind(this)},this.batchEnabled=function(e){return!!(e&&this.hasPendingChanges())&&null==this.getBatchDataItem(e)},this.getBatchDataItem=function(e){if(e){var t=this.getParentDatasource();for(let a,n=0;n<t.batchServiceData.length;n++)if(a=t.batchServiceData[n].data,a.__$id==e.__$id)return t.batchServiceData[n]}return null},this.performBatchPost=function(e){return new Promise(()=>{let t="batch_"+this.uuidv4(),a="";a+="--"+t+"\n";let n="changeset_"+this.uuidv4();a+="Content-Type: multipart/mixed; boundary="+n+"\n";for(let e,t=0;t<this.batchServiceData.length;t++){e=this.batchServiceData[t],a+="--"+n+"\n",a+="Content-Type: application/http\n",a+="Content-Transfer-Encoding:binary\n",a+=e.promise.properties.method+" "+e.entity+" HTTP/1.1\n",a+="Content-Type: application/json\n",a+="Accept: application/json\n",a+="X-Master-Id: "+e.promise.properties.originalObject.__$id+"\n",e.promise.properties.originalObject.__$masterExpression&&(a+="X-Detail-Fill: "+e.promise.properties.originalObject.__$masterExpression+"\n");let r=e.promise.properties.headers;for(var s in r)r.hasOwnProperty(s)&&(a+=s+": "+r[s]+"\n");"DELETE"!=e.promise.properties.method&&(a+=e.promise.properties.data+"\n")}a+="--"+n+"--\n",a+="--"+t+"--\n",console.log(a);let r=this.entity;0<r.indexOf("/")&&(r=r.substring(0,r.lastIndexOf("/")));let i={};this.copy(this.headers,i),i["Content-Type"]="multipart/mixed; boundary="+t;let o=(e,t,a,n)=>{let s;0<this.batchServiceData.length&&(s=this.batchServiceData[0].promise.errorCallback),s?s(e,t,a,n,!1):this.handleError(e),this.batchServiceData=[]};$httpLegacy({method:"POST",url:_self.removeSlash((window.hostApp||"")+r+"/$batch"),data:a,headers:i,offlineMode:_self.isOfflineMode()}).success(function(t,a,n,s){let r=this.parseBatchResult(t);for(let e=0;e<r.length;e++)if(400<=r[e].status)return void o(r[e].data,r[e].status);for(let e=0;e<this.batchServiceData.length;e++)this.batchServiceData[e].result=r[e]&&null!=r[e].data?r[e].data:this.batchServiceData[e].data;if(e)e();else{let e;0<this.batchServiceData.length&&(e=this.batchServiceData[0].promise.successCallback),e&&(this.batchServiceData.splice(0,1),e(r[0].data,r[0].status,n,s,!1))}}.bind(this)).error(o)})},this.parseBatchResult=function(e){let t,a=[],n=e.split("\n");for(let r,i=0;i<n.length;i++){if(r=n[i],r.startsWith("{")&&a.push({status:t,data:JSON.parse(r)}),r.startsWith("HTTP/1.1")){var s=HTTP_STATUS.exec(r);t=s[1]}r.startsWith("HTTP/1.1")&&0<r.indexOf("No Content")&&a.push({status:t,data:null})}return a},this.uuidv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=0|16*Math.random(),a="x"==e?t:8|3&t;return a.toString(16)})},this.getService=function(verb,object){_self=this;var event=eval("this.on"+verb);return"GET"===verb&&(event||this.isLocalData()||this.isNavigatorOffline())?function(e){var t={verb:verb,properties:e,successCallback:null,errorCallback:null,success:function(e){return this.successCallback=e,this},error:function(e){return this.errorCallback=e,this}};return $timeout(function(){var e,t={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)e=_self.$scope.$eval(event,t),e instanceof Promise?e.then(function(e){e&&"[object Array]"!==Object.prototype.toString.call(e)&&(e=[e]),_self.$scope.safeApply(function(){this.successCallback(e)}.bind(this))}.bind(this)).catch(function(e){_self.handleError(e)}.bind(this)):e&&this.successCallback(e);else{let e=_self.getPouchDB();if("GET"==this.verb&&!this.properties.filter)e.allDocs({include_docs:!0,attachments:!0}).catch(this.errorCallback).then(function(e){for(var t=[],a=0;a<e.rows.length;a++)t.push(e.rows[a].doc);e.rows=t,this.successCallback&&this.successCallback(e)}.bind(this));else if("GET"==this.verb){var a=peg$parse(this.properties.filter);e.find({selector:a}).catch(this.errorCallback).then(function(e){e.rows=e.docs,e.total_rows=e.rows.length,this.successCallback&&this.successCallback(e)}.bind(this))}}}.bind(t),0),t}:(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(e,t){if(e)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:t};this.$scope.$eval(e,a)}catch(t){this.handleError(t)}},this.handleBeforeCallBack=async function(e,t){var a=!0;let n=DatasetManagerUtil.onMatchRegex(/cronapi.server/g,".run(",".toPromise().disableNotification()");if(e)try{var s={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:t};await this.$scope.$eval(n(e),s)}catch(t){a=!1,this.handleError(t)}return a},this.handleError=function(e){if(console.log(e),e instanceof XMLDocument){var t=e.getElementsByTagName("message")[0].textContent;e=t,console.log(e)}var a="";if(e)if("[object String]"===Object.prototype.toString.call(e))a=e;else{var t=e.msg||e.desc||e.message||e.error||e.responseText;this.isOData()&&e.error.message&&e.error.message.value&&(t=e.error.message.value),t&&(a=t)}a||(a=this.defaultNotSpecifiedErrorMessage);if(result=/<h1>(.*)<\/h1>/gmi.exec(a),result&&2<=result.length&&(a=result[1]),this.errorMessage=a,!(this.onError&&""!==this.onError))this.onError=function(e){Notification.error(e)};else if("string"==typeof this.onError)try{var n={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},s=this.$scope.$eval(this.onError,n);"function"==typeof s&&(this.onError=s)}catch(t){isValid=!1,Notification.error(t)}"function"==typeof this.onError&&this.onError.call(this,a)},this.observers&&0<this.observers.length&&$rootScope.$watch(function(){return this.active}.bind(this),function(e){e&&this.notifyObservers(e)}.bind(this),!0)},this.setFile=function(e,t,a){e&&"pattern"===e.$error||e&&toBase64(e,function(e){this.$apply=function(e){t[a]=e,scope.$apply(t)}.bind(scope),this.$apply(e)})},this.downloadFile=function(e,t){if(void 0!==t){for(var a=(window.hostApp||"")+this.entity+"/download/"+e,n=0;n<t.length;n++)a+="/"+t[n];var s={url:a,method:"GET",responseType:"arraybuffer"};$http(s).then(function(e){var t=new Blob([e.data],{type:"application/*"});$window.open(URL.createObjectURL(t))})}},this.openImage=function(e){if(-1==e.indexOf("https://")&&-1==e.indexOf("http://")){var t=$window.open("","_blank","height=300,width=400");t.document.write("<img src=\""+("data:image/png;base64,"+e)+"\"/>")}else $window.open(e,"_blank","height=300,width=400")},this.byteSize=function(e){function t(e,t){return-1!==t.indexOf(e,t.length-e.length)}function a(e){return t("==",e)?2:t("=",e)?1:0}return angular.isString(e)?function(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")+" bytes"}(function(e){return 3*(e.length/4)-a(e)}(e)):""},this.insert=async function(obj,onSuccess,onError,forceSave){(await this.handleBeforeCallBack(this.onBeforeCreate))&&((this.dependentLazyPost||this.batchPost)&&!forceSave?(obj.__status="inserted",this.dependentLazyPost&&(obj.__parentId=eval(this.dependentLazyPost).active.__$id),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData),onSuccess&&onSuccess(obj)):service.save(obj).$promise.error(onError).then(onSuccess))},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(e,t,a){t=t||this.data,this.copy(e,t[a]),e.__$id=t[a].__$id,delete t[a].__status,delete t[a].__original,delete t[a].__originalIdx,delete t[a].__odatafiles,delete t[a].__$masterExpression},this.cleanDependentBuffer=function(){var e=[];$(this.data).each(function(){this.__status?"updated"==this.__status&&e.push(this.__original):e.push(this)}),this.data.length=0;for(var t=0;t<e.length;t++)delete e[t].__status,delete e[t].__original,delete e[t].__originalIdx,this.data.push(e[t]);if(this.postDeleteData)for(var t=0;t<this.postDeleteData.length;t++)delete this.postDeleteData[t].__status,delete this.postDeleteData[t].__original,delete this.postDeleteData[t].__originalIdx,this.data.push(this.postDeleteData[t]);this.data&&0<this.data.length?(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(e){this.dependentData&&$(reverseArr(this.dependentData)).each(function(){this.cleanDependentBuffer()}),this.cleanDependentBuffer(),this.batchServiceData=[],e&&e()},this.flushDependencies=function(e,t){var a=[];if(this.dependentData){var n=function(){reduce(this.dependentData,function(e,n){a.push(e.storeDependentBuffer(function(){n()},void 0,t))}.bind(this),function(){e&&e(a)}.bind(this))}.bind(this);reduce(reverseArr(this.dependentData),function(e,a){e.storeDependentBuffer(function(){a()},!0,t)}.bind(this),function(){n()}.bind(this))}else e&&e(a)},this.postBatchData=function(e,t){let a=!t;t||(this.batchServiceData=[]);let n=()=>{a?(a=!1,this.performBatchPost(function(){this.postBatchData(e,!0)}.bind(this))):e&&e()};this.postingBatch=!0;var s=[],r=function(){this.storeDependentBuffer(function(){s.push(this.storeDependentBuffer(function(){reduce(this.dependentData,function(e,t){s.push(e.storeDependentBuffer(function(){t()},!1,a))}.bind(this),function(){this.postingBatch=!1;for(var e=0;e<s.length;e++)s[e]();n&&n()}.bind(this))}.bind(this),!1,a))}.bind(this),!0,a)}.bind(this);reduce(reverseArr(this.dependentData),function(e,t){e.storeDependentBuffer(function(){t()},!0,a)}.bind(this),function(){r()}.bind(this))};var reduce=function(e,t,a){if(!e||0==e.length)a();else{var n=e.reduce(function(e,a){return e.then(function(){return new Promise(function(e){t(a,e)})})},Promise.resolve());n.then(function(){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(e,t){if(e.__status){if(!_self.parameters&&(_self.dependentLazyPostField&&(e[_self.dependentLazyPostField]=dependentDS.active),-1<_self.entity.indexOf("//"))){var a=dependentDS.getKeyValues(dependentDS.active),n="";for(var s in a)a.hasOwnProperty(s)&&(n+="/"+a[s]);n+="/",_self.entity=_self.entity.replace("//",n)}if(_self.parameters){var r=_self.getParametersMap(e.__parentId?e.__parentId:null);for(var s in r)r.hasOwnProperty(s)&&updateObjectValue(e,s,r[s]);let t=_self.getParametersBatchExpression(e.__parentId?e.__parentId:null);e.__$masterExpression=t}"inserted"==e.__status?function(e){var a;batchMode||(a=_self.processODataFiles(e)),_self.insert(e,function(n,s,r){if(r)return void t();var i=e.__sender,o=_self.getIndexOfListTempBuffer(e,array),d=!1,c=n;0<=o&&(c=array[o],d=array[o].__fromMemory,_self.updateObjectAtIndex(n,array,o)),_self.events.create&&!d&&(i&&(n=array[o],n.__sender=i),_self.callDataSourceEvents("create",n),delete n.__sender),a&&0<a.length?_self.sendODataFiles(a,n,function(e){_self.copy(e.data,c)}.bind(this),function(){t()}):t()},function(){t()},!0)}(e):"updated"==e.__status?function(e){var a;batchMode||(a=_self.processODataFiles(e)),_self.update(e,function(n,s,r){if(r)return void t();var i=e.__sender,o=_self.getIndexOfListTempBuffer(e,array),d=!1,c=n;0<=o&&(c=array[o],d=array[o].__fromMemory,_self.updateObjectAtIndex(n,array,o),n=array[o]),_self.events.update&&!d&&(i&&(n.__sender=i),_self.callDataSourceEvents("update",n),delete n.__sender),a&&0<a.length?_self.sendODataFiles(a,n,function(e){_self.copy(e.data,c)}.bind(this),function(){t()}):t()},function(){t()},!0)}(e):"deleted"==e.__status&&onlyRemove?function(e){_self.remove(e,function(a,n,s){if(s)return void t();if(_self.events.delete){var r={};_self.copy(e,r),delete r.__status,delete r.__original,delete r.__originalIdx,_self.callDataSourceEvents("delete",r)}t()},!0,null,function(){t()})}(e):t()}else t()},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(e,t){t=t||this.data;for(var a=0;a<t.length;a++)if(t[a].__$id&&e.__$id&&t[a].__$id==e.__$id)return a;return-1},this.getObjectAsString=function(e,t){return((null==t||null==t)&&(t=!0),this.isOData())?window.objToOData(e,t):null==e?"":"number"==typeof e?e+"@@number":e instanceof Date?e.toISOString()+"@@datetime":"boolean"==typeof e?e+"@@boolean":e+""},this.update=async function(e,t,a,n){(await this.handleBeforeCallBack(this.onBeforeUpdate))&&((this.dependentLazyPost||this.batchPost)&&!n?t&&t(e):service.update(this.getEditionURL(e,n),e).$promise.error(a).then(t))},this.validateFields=function(e,t){var a=$(e);if(0<a.length&&"checkbox"!==a.get(0).type){var n=$("label[for=\""+a.get(0).id+"\"]"),s=a.get(0).id;return 0<n.length&&(s=n.text(),s&&(s=s.replaceAll("\n","").trim())),t&&(Notification.error(t.replace("{0}",s)),$(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(){return $(this).attr("pattern")})},this.missingRequiredField=function(e){if(0<this.getPatterns().length)return!1;if(this.checkRequired){var t=this.validateFields("[required][ng-model*=\""+this.name+".\"].ng-invalid-required",e?"":this.translate.instant("FieldIsRequired"));return t=t&&this.validateFields("[required][ng-model*=\""+this.name+".\"].ng-empty",e?"":this.translate.instant("FieldIsRequired")),t=t&&this.validateFields("[ng-model*=\""+this.name+".\"].ng-invalid",e?"":this.translate.instant("FieldIsInvalid")),!t}return!1},this.hasInvalidField=function(){return!(0<this.getPatterns().length)&&!!this.checkRequired&&0<$("input[ng-model*=\""+this.name+".\"]:invalid").not("input[type=checkbox]").not(".ng-empty").length},this.postSilent=function(e,t){this.post(e,t,!0)},this.updateActive=function(e){for(var t in e)e.hasOwnProperty(t)&&"__status"!=t&&(this.active[t]=e[t])},this.processODataFiles=function(e){var t=[];for(var a in e)if(-1<a.indexOf("__odataFile_")){var n={field:a.replace("__odataFile_",""),value:e[a]};t.push(n),e[n.field]=void 0,delete e[a]}return t},this.sendODataFiles=function(e,t,a,n){if(t&&e&&0<e.length){var s=this.entity,r=this.getKeyValues(t),i=["("],o=0;for(var d in r)0<o&&i.push(","),i.push(d),i.push("="),i.push(window.objToOData(r[d])),o++;i.push(")"),s+=i.join("");var c=JSON.parse(localStorage.getItem("_u"));reduce(e,function(e,n){let r=(window.hostApp||"")+s+"/"+e.field+"/$value";if(!_self.isOfflineMode()){var i=e.value,o=new XMLHttpRequest;o.open("PUT",r),o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.setRequestHeader("X-File-Name",i.name),o.setRequestHeader("Content-Type",(i.type||"application/octet-stream")+";charset=UTF-8"),window.isUsingCookie()||o.setRequestHeader("X-AUTH-TOKEN",c?.token),o.onreadystatechange=function(){if(4===o.readyState&&500===o.status){var r=new DOMParser,i=r.parseFromString(o.response,"text/xml");this.handleError(i)}4===o.readyState&&201===o.status&&service.call(s,"GET",{},!1).$promise.error(function(){Notification.error("Error send file")}).then(function(s){a?a({field:e.field,data:s}):t[e.field]=s[e.field],n()})}.bind(this),o.send(i)}else{let s={method:"PUT",data:e.value,url:r,headers:_self.headers};SyncService.toQueue(s),cronapi.internal.fileToBase64(e.value,s=>{t[e.field]=s,a&&a({field:e.field,data:t}),n()})}}.bind(this),function(){n&&n()}.bind(this))}else n&&n()},this.getFieldSchema=function(e){var t;if(this.schema)for(var a=0;a<this.schema.length;a++)if(this.schema[a].name==e){t=this.schema[a];break}return t},this.asyncPost=function(e,t,a){setTimeout(function(){this.post(e,t,a)}.bind(this),100)},this.copyWithoutAngularObj=function(){var e={};for(var t in this)this.hasOwnProperty(t)&&!t.startsWith("$")&&(e[t]=this[t]);return e},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(e,t,a){if(a&&this.dependentData&&!this.dependentLazyPost&&!this.batchPost)return void this.flushDependencies(()=>{this.performBatchPost(()=>{this.post(onSuccess,onError,silent,!0)})},!0);this.active.__sender&&(e.__sender=this.active.__sender),this.active.__$id&&(e.__$id=this.active.__$id);var n=function(a){if(this.active=e,this.handleAfterCallBack(this.onAfterCreate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),this.events.create&&t&&(this.callDataSourceEvents("create",this.active),delete _self.active.__sender),this.events.memorycreate&&!t&&this.callDataSourceEvents("memorycreate",this.active),a)for(let e=0;e<a.length;e++)a[e]()}.bind(this),s=function(){this.data.push(e),!this.dependentData||this.dependentLazyPost||this.batchPost?n():this.flushDependencies(n,!1)}.bind(this);if(!t)s();else{var r=this.processODataFiles(this.active);r&&0<r.length?this.sendODataFiles(r,e,function(t){this.copy(t.data,e)}.bind(this),function(){s()}.bind(this)):s()}}.bind(this),onError):this.editing?this.update(this.active,function(obj,hotData,batchPostponed){if(batchPostponed&&this.dependentData&&!this.dependentLazyPost&&!this.batchPost)return void this.flushDependencies(()=>{this.performBatchPost(()=>{this.post(onSuccess,onError,silent,!0)})},batchPostponed);var odataFiles;hotData&&(odataFiles=this.processODataFiles(this.active));var foundRow,keyObj=this.getKeyValues(this.lastActive);this.data.forEach(function(currentRow){var found;if(this.lastActive.__$id&&currentRow.__$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=!0;else{found=!1;break}}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(e){if(foundRow&&this.handleAfterCallBack(this.onAfterUpdate),this.onBackNomalState(),onSuccess&&onSuccess(this.active),e)for(let t=0;t<e.length;t++)e[t]()}.bind(this),func=function(e){hotData?odataFiles&&0<odataFiles.length?this.sendODataFiles(odataFiles,foundRow,function(e){this.copy(e.data,foundRow)}.bind(this),function(){this.events.update&&hotData&&this.callDataSourceEvents("update",foundRow),back(e)}.bind(this)):back(e):back(e)}.bind(this);!this.dependentData||this.dependentLazyPost||this.batchPost?func():this.flushDependencies(func)}.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 e=this.$interpolate(this.conditionExpression)(this.$scope),t=JSON.parse(e);if("object"==typeof t){if(t.params){let e;for(var a,n=0;n<t.params.length;n++)a=t.params[n].fieldValue,2<=a.length&&"'"==a.charAt(0)&&"'"==a.charAt(a.length-1)&&(a=a.substring(1,a.length-1)),""!==a&&void 0!==a&&null!==a&&(e?e+="&":e="",e+=t.params[n].fieldName+"="+encodeURIComponent(a));return e}}}catch(t){console.log(t)}},this.getDeletionURL=function(e,t){var a=this.getKeyValues(e.__original?e.__original:e,t),n="";this.isOData()&&(n="(");var s=0;for(var r in a)a.hasOwnProperty(r)&&(this.isOData()?(0<s&&(n+=","),n+=r+"="+this.getObjectAsString(a[r])):n+="/"+a[r],s++);this.isOData()&&(n+=")",n=encodeURI(n));var i=this.entity;this.entity.endsWith("/")&&(i=i.substring(0,i.length-1)),i+=n;let o=this.getConditionParams();return o&&(i=i+"?"+o),i},this.getEditionURL=function(e,t){var a=this.getKeyValues(e.__original?e.__original:e,t),n="";for(var s in this.isOData()&&(n="("),a)a.hasOwnProperty(s)&&(n+=this.isOData()?("("==n?"":",")+s+"="+this.getObjectAsString(a[s]):"/"+a[s]);this.isOData()&&(n+=")",n=encodeURI(n));var r=this.entity;this.entity.endsWith("/")&&(r=r.substring(0,r.length-1)),r+=n;let i=this.getConditionParams();return i&&(r=r+"?"+i),r},this.refreshActive=function(e,t){if(this.active&&"inserted"!=this.active.__status){var a=this.getEditionURL(this.active),n=this.getKeyValues(this.active);this.$promise=this.getService("GET")({method:"GET",url:a,headers:this.headers}).success(function(a){var s=null;this.isOData()?(s=a.d,this.normalizeObject(s)):a&&0<a.length&&(s=a[0]);var r=-1,o=0;this.data.forEach(function(e){var t=!1,a=0,i=0;for(var d in n)i++,e[d]&&e[d]===n[d]&&a++;a==i&&(t=!0),t&&(r=o,s&&(this.copy(s,e),this.copy(s,this.active))),o++}.bind(this)),-1==r?t&&t():(this.events.update&&this.callDataSourceEvents("update",this.active),e&&e(this.active))}.bind(this)).error(function(){t&&t()}.bind(this))}else e&&e(this.active)},this.buildURL=function(e,t){var a=this.getKeyValues(this.active,!1,t);"object"!=typeof e&&(e=[e]);var n="",s=0;for(var r in a){if(a.hasOwnProperty(r)){var i;i=Array.isArray(e)?e[s]:e[r],0<s&&(n+=" and "),n+=r+" eq "+this.getObjectAsString(i)}s++}return n},this.findObj=function(e,t,a,n,s){let r=s||deepCopy(this.keys),i=function(t){for(let a=0;a<r.length;a++)if(objectsAreEqual(e[a],t[r[a]]))return t}.bind(this),o=this.data.filter(i);if(o&&0<o.length)return void(a&&a(o));var d,c=this.buildURL(e,s);d={params:{$filter:c}},(null==c||0==c.length)&&(d={}),this.fetch(d,{success:function(e){if(a){let t=e.filter(i);a(t)}}.bind(this),error:function(){n&&n()}},void 0,{lookup:!0})},this.getColumn=function(e){var t=[];return $.each(this.data,function(a,n){t.push(n[e])}),t},this.onBackNomalState=function(){this.$scope.safeApply(function(){this.busy=!1,this.editing=!1,this.inserting=!1;let e=this.dependentData&&this.dependentData.filter(e=>e.inserting||e.editing);e&&e.forEach(e=>e.cancel()),this.noticeStatusChange()}.bind(this))},this.cancel=function(){this.inserting&&(0<=this.cursor?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(e){for(var t in e)e.hasOwnProperty(t)&&e[t]&&e[t].__deferred&&delete e[t];return e},this.retrieveDefaultValues=function(e,t){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(),t&&t()}.bind(this));else if(e)this.active=e||{},this.updateWithParams(),t&&t();else if(0<=this.entity.indexOf("cronapi")||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(e){this.isOData()?(this.active=this.removeODataFields(e.d),this.normalizeData(this.active)):this.active=e,this.updateWithParams(),t&&t()}.bind(this)).error(function(){this.active={},this.updateWithParams(),t&&t()}.bind(this))}else this.active={},this.updateWithParams(),t&&t()};var updateObjectValue=function(e,t,a){for(var n,s=t.split("."),r=0;r<s.length;r++)n=s[r],r==s.length-1?e[n]=a:((void 0===e[n]||null==e[n])&&(e[n]={}),e=e[n])};this.updateWithParams=function(){if(this.parameters){var e=this.getParametersMap();for(var t in e)e.hasOwnProperty(t)&&updateObjectValue(this.active,t,e[t])}},this.resetFieldsStatus=function(){var e=setInterval(function(){$("input[ng-model*=\""+this.name+".\"]").is(":visible")?($("input[ng-model*=\""+this.name+".\"]:invalid:empty").removeClass("ng-invalid ng-invalid-required"),clearInterval(e)):$("input[ng-model*=\""+this.name+".\"].cronMultiSelect")&&clearInterval(e)},100)},this.noticeStatusChange=function(){this.changeTitle(),this.handleBeforeCallBack(this.onChangeStatus)},this.changeTitle=function(){if($("#starter").length&&$("#starter").attr("primary-datasource")===this.name){var e=this.translate.instant($rootScope.viewTitleOnly),t=$rootScope.systemName&&$rootScope.systemName.length?" - "+$rootScope.systemName:"";this.inserting?e+=" - "+this.translate.instant("Inserting"):this.editing&&(e+=" - "+this.translate.instant("Editing")),$("h1.title:first").text(e),window.document.title=e+t}},this.startInserting=function(e,t){this.retrieveDefaultValues(e,function(){if(this.active.__$id||(this.active.__$id=uuid()),this.children&&this.children.length){let e=this.getKeyValues(this.active);for(let t in e)e.hasOwnProperty(t)&&(null==e[t]||null==e[t])&&"_objectKey"==t&&(this.active[t]="$autogenerated$"+this.uuidv4())}this.inserting=!0,this.onStartInserting&&this.onStartInserting(),t&&t(this.active),this.events.creating&&this.callDataSourceEvents("creating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()}.bind(this))},this.operationPouchDB=function(e,t,a){if(!SyncService.synchronizing&&(this.hasOfflineSupport()||this.isLocalData())&&e&&"GET"!==e){let n=this.getPouchDB();"DELETE"==e?n.get(t._objectKey).then(function(e){return n.remove(e)}.bind(this)).then(a).catch(function(e){console.error(e)}):this.$scope.cronapi.internal.updatePouchDB(n,[t],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(e,t){if(e)this.active=this.copy(e),this.lastActive=e;else{if(0==this.data.length)return void this.startInserting(null,t);this.lastActive=this.active,this.active=this.copy(this.active)}this.editing=!0,t&&t(this.active),this.events.editing&&this.callDataSourceEvents("updating",this.active),this.resetFieldsStatus(),this.noticeStatusChange()},this.removeSilent=function(e,t,a){this.remove(e,null,!1,t,a,!0)},this.remove=function(e,t,a,n,s,r){this.busy=!0;var i=async function(e,t){e||(e=this.active);var r=this.getKeyValues(e,a);t=t||function(t,a,s){if(!s){for(var o=0;o<this.data.length;o++){var d;if(e.__$id&&this.data[o].__$id)d=this.data[o].__$id==e.__$id;else{var c=this.getKeyValues(this.data[o]);for(var l in r)if(r.hasOwnProperty(l))if(c[l]&&c[l]===r[l])d=!0;else{d=!1;break}}if(d){if(this.dependentLazyPost||this.batchPost){var u={};this.copy(this.data[o],u),u.__status="deleted",u.__originalIdx=o,this.events.memorydelete&&this.callDataSourceEvents("memorydelete",u),"inserted"!=this.data[o].__status&&(!this.postDeleteData&&(this.postDeleteData=[]),this.postDeleteData.push(u),this.hasMemoryData=!0,this.notifyPendingChanges(this.hasMemoryData))}this.data.splice(o,1);var p=o-1;0>p&&(p=0),p>this.data.length-1&&(p=this.data.length),this.data[p]?(this.active=this.data[p],this.cursor=p):(this.active=null,this.cursor=-1),this.onBackNomalState();break}}this.handleAfterCallBack(this.onAfterDelete),n&&n(e),this.events.delete&&a&&this.callDataSourceEvents("delete",e)}}.bind(this),(await this.handleBeforeCallBack(this.onBeforeDelete))&&((this.dependentLazyPost||this.batchPost)&&!a?t():service.remove(this.getDeletionURL(e,a),e).$promise.error(s).then(t))}.bind(this);if(!a&&!r&&this.deleteMessage&&0<this.deleteMessage.length){let a={title:this.translate.instant("yes"),value:function(){i(e,t)}},n={title:this.translate.instant("no"),primaryValue:"true",value:()=>{this.filter()}};window.cronapi.notification.confirmDialogAlert("warning",this.translate.instant("Users.view.Confirmacao"),this.deleteMessage,[n,a])}else i(e,t)},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(e,t){var a=this.getKeyValues(e),n=this.getKeyValues(t);for(var s in a)if(a.hasOwnProperty(s)){if(!n.hasOwnProperty(s))return!1;if(a[s]!==n[s])return!1}return!0},this.hasNext=function(){return this.data&&this.cursor<this.data.length-1},this.hasPrevious=function(){return this.data&&0<this.cursor},this.order=function(e){this._savedProps.order=e},this.getActiveValues=function(){return this.active&&!this._activeValues&&$rootScope.$watch(function(){return this.active}.bind(this),function(){this._activeValues=this.getRowValues(this.active)}.bind(this),!0),this._activeValues},this.__defineGetter__("activeValues",function(){return _self.getActiveValues()}),this.getRowValues=function(e){var t=[];for(var a in e)e.hasOwnProperty(a)&&t.push(e[a]);return t},this.next=function(){return this.hasNext()||this.nextPage(),this.active=this.copy(this.data[++this.cursor],{}),this.active},this.nextPage=function(e){var t=(window.hostApp||"")+this.entity;return this.hasNextPage()?void(this.offset=1==this.apiVersion||-1==t.indexOf("/cronapi/")?parseInt(this.offset)+parseInt(this.rowsPerPage):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==t.indexOf("/cronapi/"))&&(this.offset=parseInt(this.offset)-this.data.length),e&&e()},canceled:function(){e&&e()},error:function(){e&&e()}},!0)):void(e&&e())},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,0>this.offset?this.offset=0:0<=this.offset&&this.fetch(this._savedProps,{success:function(e){e&&0!==e.length||(this.offset=0)}},!0))},this.hasNextPage=function(){return this.hasMoreResults&&-1!=this.rowsPerPage},this.hasPrevPage=function(){return 0<this.offset&&!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(e,t){var a=!1,n=null;if(null===e||void 0===e)return n;var s=null,r=null;let o=t=>{var n=this.data[t];for(var s in d)a=!!(e.hasOwnProperty(s)&&e[s]===n[s]);return a};if("object"==typeof e&&null!==e){var d;0<this.data.length&&(d=this.getKeyValues(this.data[0]));for(var c=0;c<this.data.length;c++)if(e.__$id&&this.data[c].__$id?(a=e.__$id==this.data[c].__$id,!a&&(a=o(c))):a=o(c),a){s=c,r=this.copy(this.data[s],{});var l=this.getKeyValues(this.data[s]),u=!0;for(var p in l)if(void 0===l[p]){u=!1;break}u||this.fetchChildren()}}else if(Array.isArray(this.keys))for(var c=0;c<this.data.length;c++)this.data[c][this.keys[0]]===e&&(s=c,r=this.copy(this.data[s],{}),a=!0);return null!==r&&(n=r,t&&(n={cursor:s,obj:r})),n},this.goTo=function(e){var t=this.findObjInDs(e,!0);return null===t?t:(this.cursor=t.cursor,this.active=t.obj,this.active)},this.getCursor=function(){return this.cursor},this.filter=function(e,t){var a=this.offset;this.offset=0,this.fetch({path:e},{beforeFill:function(){this.cleanup()},error:function(){this.offset=a},success:function(e){t&&t(e)}})},this.doSearchAll=function(e,t){this.searchTimeout=null;var a=this.offset;this.offset=0,this.fetch({params:{filter:"%"+e+"%",filterCaseInsensitive:!!t}},{beforeFill:function(){this.cleanup()},error:function(){this.offset=a}})},this.searchAll=function(e,t){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.searchTimeout=setTimeout(function(){this.doSearchAll(e,t)}.bind(this),500)},this.doSearch=function(e,t){this.searchTimeout=null;var a=this.offset;this.offset=0;var n;this.isOData()?(n={params:{$filter:e}},(null==e||0==e.length)&&(n={})):n={params:{filter:e,filterCaseInsensitive:!!t}},this.fetch(n,{beforeFill:function(){this.cleanup()},error:function(){this.offset=a}})},this.search=function(e,t){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null),this.caseInsensitive=t,this.terms=e,this.searchTimeout=setTimeout(function(){this.doSearch(e,t)}.bind(this),500)},this.refresh=function(e,t,a){this.cleanup(),void 0===a&&(a=0),e.length>=a&&this.filter(t+"/"+e)},this.cleanup=function(e){e||(e={}),this.offset=0,this.rowsCount=-1,this.data.length=0,e.ignoreAtive||(this.cursor=-1,this.active={}),this.hasMoreResults=!1},this.current=function(){return this.active||this.data[0]},this.getLink=function(e){if(this.links)for(var t=0;t<this.links.length;t++)if(this.links[t].rel==e)return this.links[t].href},this.isOData=function(){return 0<this.entity.indexOf("odata")},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(e,t,a){return(null==t||null==t)&&(t=!1),window.oDataToObj(e,t,a)},this.normalizeObject=function(e){for(var t in e)if(e.hasOwnProperty(t)){var a=e[t];if(a)if("object"==typeof a)this.normalizeObject(a);else{let n=this.getFieldFromSchema(t);e[t]=this.normalizeValue(a,void 0,n)}}},this.normalizeData=function(e){if(e){delete e.__metadata;for(var t=0;t<e.length;t++)this.normalizeObject(e[t])}return e},this.getAllData=function(){var e=[];if(e=e.concat(this.data),this.memoryData)for(key in this.memoryData)if(this.memoryData.hasOwnProperty(key)){var t=this.memoryData[key];t.data&&(e=e.concat(t.data))}return this.postDeleteData&&(e=e.concat(this.postDeleteData)),e},this.getParametersMap=function(parentId){var parameters,obj,mapParams,map={};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&&0<parameters.length)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)map[binary[0]]=binary[1]?this.normalizeValue(value,!0):null;else 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]]}}return map},this.setParameters=function(e){this.parameters=e,this.fetch({params:{}})},this.getParametersBatchExpression=function(parentId){var parameters,obj,expression="";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&&0<parameters.length)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(e){return 0==e.indexOf("http://")?"http://"+e.substring(7).split("//").join("/"):0==e.indexOf("https://")?"https://"+e.substring(8).split("//").join("/"):e},this.setDataSourceEvents=function(e){this.events=e},this.addDataSourceEvents=function(e){for(var t in e)e.hasOwnProperty(t)&&(this.events[t]||(this.events[t]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[t])&&(this.events[t]=[this.events[t]]),this.events[t].push(e[t]))},this.removeDataSourceEvents=function(e){for(var t in e)if(e.hasOwnProperty(t)){this.events[t]||(this.events[t]=[]),"[object Array]"!==Object.prototype.toString.call(this.events[t])&&(this.events[t]=[this.events[t]]);for(var a=[].concat(this.events[t]),n=0;n<a.length;n++)a[n]==e[t]&&this.events[t].splice(n,1)}},this.callDataSourceEvents=function(e){if(this.events){var t=this.events[e];if(t){"[object Array]"!==Object.prototype.toString.call(t)&&(t=[t]);for(var a=[],n=1;n<arguments.length;n++)a.push(arguments[n]);for(var s=[],n=0;n<t.length;n++)s.push(t[n]);for(var r=0;r<s.length;r++)try{s[r].apply(null,a)}catch(e){console.log("Error","Event no more exist in datasource")}}}},this.storeInMemory=function(e){this.memoryData||(this.memoryData={});var t={data:[],cursor:this.cursor,params:this.getParametersMap(),rowCount:this.getRowsCount()};t.data=deepCopy(this.data,t.data),this.memoryData[e]=t},this.restoreFromMemory=function(e){this.memoryData||(this.memoryData={});var t=this.memoryData[e];return t&&(this.cursor=t.cursor,this.rowsCount=t.rowCount),delete this.memoryData[e],deepCopy(t.data)},this.hasPendingChanges=function(){var e=this.hasMemoryData;return this.children&&$(this.children).each(function(){e=e||this.hasPendingChanges()}),e},this.isPostingBatchData=function(){var isPosting=!0==this.postingBatch;return this.dependentLazyPost&&(isPosting=isPosting||eval(this.dependentLazyPost).isPostingBatchData()),isPosting},this.fetchChildren=function(e){this.children?reduce(this.children,function(e,t){e.fetch({},function(){t()})}.bind(this),function(){e&&e()}.bind(this)):e&&e()};var splitExpression=function(e){var t,a=null;-1==e.indexOf("@=")?-1==e.indexOf("<=")?-1==e.indexOf(">=")?-1==e.indexOf(">")?-1==e.indexOf("<")?(a=e.trim().split("="),t="="):(a=e.trim().split("<"),t="<"):(a=e.trim().split(">"),t=">"):(a=e.trim().split(">="),t=">="):(a=e.trim().split("<="),t="<="):(a=e.trim().split("@="),t="=");var n=typeof this.normalizeValue(a[1],!0);if(this.isOData()){if("="==t&&"string"==n)return"startswith(tolower("+a[0]+"), "+a[1].toLowerCase()+")";if("="==t)return a[0]+" eq "+a[1];if("!="==t)return a[0]+" ne "+a[1];if(">"==t)return a[0]+" gt {"+a[1];if(">="==t)return a[0]+" ge "+a[1];if("<"==t)return a[0]+" lt "+a[1];if("<="==t)return a[0]+" le "+a[1]}else return"string"==n?a[0]+"@"+t+"%"+a[1]+"%":a[0]+t+a[1]}.bind(this),parseFilterExpression=function(e){var t="";if(e){var a=e.split(";"),n=!0;if(0<a.length)for(var s,r=/[\w\d]+=.+/gm,o=0;o<a.length;o++)if(s=a[o].match(r),!s){n=!1;break}if(n)for(var d,o=0;o<a.length;o++)d=splitExpression(a[o]),""!=t&&(t+=this.isOData()?" and ":";"),t+=d;else t=e}return t}.bind(this),getQueryOperator=function(e){return"="==e?" eq ":"!="==e?" ne ":">"==e?" gt ":">="==e?" ge ":"<"==e?" lt ":"<="==e?" 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&&2<=right.length&&("'"==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(e){return""===e||void 0===e||null===e||"''"===e},this.getFieldFromSchema=function(e){if(this.schema)for(var t=0;t<this.schema.length;t++)if(this.schema[t].name===e)return this.schema[t].type;return null},this.parserCondition=function(e,t,a){var n="",s=e.type;if(t||(t="default"),e.args)for(var r=0;r<e.args.length;r++){var o=e.args[r],d=s;if(o.args&&0<o.args.length){var c=this.parserCondition(o,t);this.isEmpty(c)&&("ignore"==t||"clean"==t)?a&&(a.clean="clean"==t):!this.isEmpty(c)&&(a&&(a.count=a.count?a.count+1:1),""!=n&&(n+=" "+d.toLowerCase()+" "),n+="( "+c+" ) ")}else{var c=executeRight(o.right);if(this.isEmpty(c)&&("ignore"==t||"clean"==t||"wait"==t))a&&(a.clean="clean"==t,a.wait="wait"==t);else if(!this.isEmpty(c)){var l=!0,u="DateTime"===this.getFieldFromSchema(o.left),p=void 0;if(u&&-1===c.indexOf("datetime")&&(p=this.$scope.cronapi.dateTime.getMomentObj(c),l=p.isValid()),!l)"null"===c&&(n+=`${o.left} ${getQueryOperator(o.type)} null`);else if(a&&(a.count=a.count?a.count+1:1),""!=n&&(n+=" "+d.toLowerCase()+" "),"%"==o.type)n+=this.isLocalData()?"contains("+o.left+", "+c.toLowerCase()+")":"substringof("+c.toLowerCase()+", tolower("+o.left+"))";else if(p){var g=p.toDate().getTimezoneOffset(),y=timeZoneOffset-g;p.add(y,"minutes"),n+=o.left+getQueryOperator(o.type)+"datetimeoffset'"+p.toISOString()+"'"}else n+=o.left+getQueryOperator(o.type)+c}}}return n.trim()}.bind(this),this.refreshData=function(e){if(this.lastFetch&&!this.hasMemoryData&&this.enabled&&!this.inserting&&!this.editing){window.Pace&&(window.Pace.options.ajax.trackWebSockets=!1,window.Pace.options.ajax.trackMethods=[]);var t=function(){window.Pace&&(window.Pace.options.ajax.trackWebSockets=!0,window.Pace.options.ajax.trackMethods=["PUT","POST","GET"]),e&&e()};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,{success:t,error:t},this.lastFetch.isNextOrPrev,this.lastFetch.fetchOptions,!0)}else e&&e()},this.startAutoRefresh=function(){0<this.autoRefresh&&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&&0<this.parameters.length;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;-1<this.entity.indexOf("//")&&0>this.entity.indexOf("://")&&(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&&(0<this.data.length?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),0<this.data.length&&!fetchOptions.ignoreAtive&&(fetchOptions.active?this.goTo(fetchOptions.active):this.$scope.safeApply(()=>{this.active=data[0],this.cursor=0}))),this.columns=[],0<this.data.length))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\xE3o existe.")}})}if("insert"==this.startMode&&(this.startMode=null,this.startInserting()),"edit"==this.startMode&&(this.startMode=null,this.startEditing()),0<this.autoRefresh&&!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(-1<this.entity.indexOf("//")&&0>this.entity.indexOf("://"))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;if(this.parameters&&0<this.parameters.length){var 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+".")))this.isEmpty(binary[1])?("clean"==this.parametersNullStrategy||"default"==this.parametersNullStrategy)&&(filterClause="null",cleanData=!0):filterClause=this.getObjectAsString(this.normalizeValue(binary[1],!0),!1);else 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"}filterClause&&(filterClause=binary[0]+getQueryOperator("=")+filterClause,""!=filter&&(filter+=this.isOData()?" and ":";"),filter+=filterClause)}}}if(!canProceed)return void(callbacks.canceled&&callbacks.canceled());var urlParams;let waitData=!1;if(this.condition){try{var parsedCondition=fetchOptions.lookup?this.$interpolate(this.conditionExpression)(this.$scope):this.condition;var obj=JSON.parse(parsedCondition);if("object"==typeof obj){var resultData={};this.conditionOdata=obj.expression?this.parserCondition(obj.expression,this.parametersNullStrategy,resultData):this.parserCondition(obj,this.parametersNullStrategy,resultData);var filterCount=0;let e=this.conditionExpression.match(/{{(?!null).*?}}/g);if(e&&(filterCount=e.length),!cleanData&&resultData.clean&&(cleanData=!0),!cleanData&&resultData.wait&&(waitData=!0),cleanData||"one"!==this.loadDataStrategy||resultData.count&&!(1>resultData.count)||(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 value,i=0;i<obj.params.length;i++)value=obj.params[i].fieldValue,2<=value.length&&"'"==value.charAt(0)&&"'"==value.charAt(value.length-1)&&(value=value.substring(1,value.length-1)),""!==value&&void 0!==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 orderField,orders=this.orderBy.split(";"),i=0;i<orders.length;i++)orderField=orders[i],orderField&&(""!=order&&(order+=this.isOData()?",":";"),order+=this.isOData()?orderField.replace("|ASC"," asc").replace("|DESC"," desc"):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&&0<checkRequestId.length&&-1==resourceURL.indexOf(checkRequestId))return void(callbacks.canceled&&callbacks.canceled())}0<this.rowsPerPage&&(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;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);var localSuccess;if(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(e){this.busy=!1,silent||this.handleError(e),callbacks.error&&callbacks.error.call(this,e)}.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(e,t,a){localSuccess&&localSuccess(),this.lastFilter=filter,this.busy=!1,a?sucessHandler(e,a()):sucessHandler(e,null)}.bind(this)).error(function(e,t,a,n){httpError(e,t,a,n)}.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.data.length:this.rowsCount},this.notifyObservers=function(){for(var e in this.observers)if(this.observers.hasOwnProperty(e)){var t=this.observers[e];$timeout(function(){t.notify.call(t,this.active)}.bind(this),1)}},this.notify=function(e){if(e){var t=this.watchFilter;t=t.replace(/\{([A-z][A-z|0-9]*)\}/gim,function(t,a){return e.hasOwnProperty(a)?e[a]:""}),this.fetch({params:{q:t}})}},this.addObserver=function(e){this.observers.push(e)},this.sum=function(e){for(var t=0,a=0;a<this.data.length;a++)this.data[a][e]&&(t+=this.data[a][e]);return t},this.copy=function(e,t,a){if(null===e||"[object Object]"!==Object.prototype.toString.call(e))return e;for(var n in t=t||{},e)e.hasOwnProperty(n)&&-1==n.indexOf("$$")&&(t[n]=this.copy(e[n]));if(a)for(var s=0;s<this.keys.length;s++){var n=this.keys[s],r=t[n];(""==r||null==r)&&delete t[n]}return t};var deepCopyArray=function(e,t){if(null===e||"[object Array]"!==Object.prototype.toString.call(e))return e;t=t||[];for(var a=0;a<e.length;a++)t.push(deepCopy(e[a]));return t},deepCopy=function(e,t){if("[object Array]"===Object.prototype.toString.call(e))return deepCopyArray(e,t);if(null===e||"[object Object]"!==Object.prototype.toString.call(e))return e;for(var a in t=t||{},e)e.hasOwnProperty(a)&&(t[a]=deepCopy(e[a]));return t};if(this.startAutoPost=function(){this.unregisterDataWatch=$rootScope.$watch(function(){return this.data}.bind(this),function(e,t){if(!this.enabled)return void this.unregisterDataWatch();var a=e.length-t.length;if(0<a)for(var n=1;n<=a;n++)this.insert(e[e.length-n],function(){});else if(0>a)for(var s=this,r=t.filter(function(t){return 0==e.filter(function(e){return s.objectIsEquals(t,e)}).length}),n=0;n<r.length;n++)this.remove(r[n],function(){})}.bind(this))},this.stopAutoPost=function(){this.unregisterDataWatch&&(this.unregisterDataWatch(),this.unregisterDataWatch=void 0)},this.hasDataBuffered=function(){return!!(this.dependentBufferLazyPostData&&0<this.dependentBufferLazyPostData.length)},window.afterDatasourceCreate){var args=[$q,$timeout,$rootScope,$window,Notification];window.afterDatasourceCreate.apply(this,args)}this.init()};return this.storeDataset=function(e){this.datasets[e.name]=e},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&&0<props.keys.length?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&&0<props.dependentLazyPost.length&&(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(e){e&&0<e.length&&(this.active=e[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&&0<props.filterURL.length&&dts.allowFetch&&dts.filter(props.filterURL),dts},this.registerObserver=function(e,t){this.datasets[e].addObserver(t)},this}]).directive("datasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate",function(e,t,a,n,s,r,i,o){return{restrict:"E",priority:9999999,scope:!0,template:"",link:function(e,t){(function(e,a,n){$(e).each(function(){var e=$(this),s=$(document.createElement(n),{html:e.html()});$.each(this.attributes,function(){s.attr(this.name,this.value)}),s.attr("inside-modal",0<$(t).closest(".modal").length);var r=e.data("events");if(r)for(var i in r)for(var d in r[i])s[i](r[i][d].handler);o(s)(a),e.replaceWith(s)})})(t,e,"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=(e,t,a)=>{let n=e.parent().find(`[data-repeater=${t}]`);n.each&&n.each((e,t)=>{let n=$(t);n.find(`[${a}]`).each((t,n)=>{let s=$(n),r=s.attr(`${a}`);s.attr(`${a}`,`${r}-cronapp-${e}`)})})};$(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(){if("ion-slide"==tagName.toLowerCase()){var e=$injector.get("$ionicSlideBoxDelegate");e.update()}indexAttribute(element,dataRepeaterId,"id"),indexAttribute(element,dataRepeaterId,"for")})})}}}]).directive("crnDatasource",["DatasetManager","$parse","$rootScope",function(e,t){return{restrict:"A",scope:!0,priority:9999998,link:function(a,n,s){a.data=e.datasets,a.data[s.crnDatasource]?a.datasource=a.data[s.crnDatasource]:(a.datasource={},a.datasource.data=t(s.crnDatasource)(a))}}}]).directive("cronappDatasource",["DatasetManager","$timeout","$parse","Notification","$translate","$location","$rootScope","$compile","$interpolate","SyncService",function(e,t,a,n,s,r,i,o,d){return{restrict:"E",scope:!0,template:"",link:function(c,l,u){initDatasource(c,l,u,e,t,a,n,s,r,i,o,d)}}}]),angular.module("sync.service",[]).service("SyncService",["$http",function(e){let t={start:function(){this.dbSync=this.getSyncServicePouchDB(),this.observeConnection()},observeConnection:async function(){setInterval(()=>this.isNavigatorOffline()||this.synchronizeOfflineData(),15000)},toQueue:function(e){let t={data:e,created:Date.now()};this.dbSync.post(t).catch(e=>console.error(e))},synchronizeOnError:async function(t,e){this.synchronizing=!1,console.log("Error synchronizing doc",e,"response",t)},synchronizeOnSuccess:async function(e,t){try{await this.dbSync.remove(e),this.removeArray(e,t),0<t.length?this.sendData(t[0],t):this.synchronizing=!1}catch(t){this.synchronizing=!1}},canByPassError:function(t){let e=!1;if(t.data&&t.data.error&&t.data.error.message&&t.data.error.message.value){let a=t.data.error.message.value;"N\xE3o foi poss\xEDvel encontrar a entidade requisitada."===a||"Requested entity could not be found."===a?e=!0:void 0}return e},sendData:async function(t,a){let n=t.data;e(n).then(()=>this.synchronizeOnSuccess(t,a)).catch(n=>this.canByPassError(n)&&this.synchronizeOnSuccess(t,a)||this.synchronizeOnError(n,t,a)),console.log(`Synchronization - sended record number ${a.length}`)},optimizeQueue:function(e){let t=e.rows.filter(e=>"DELETE"===e.doc.data.method);t.forEach(async t=>{let a=e.rows.filter(e=>{let a=e.doc.data.originalObject||e.doc.data.rawData,n=t.doc.data.originalObject||t.doc.data.rawData;return a&&n&&a._objectKey===n._objectKey&&"DELETE"!==e.doc.data.method});a.forEach(async t=>{this.dbSync.remove(t.doc),this.removeArray(t,e.rows)})});let a=[];return e.rows.forEach(e=>a.push(e.doc)),a.sort((e,t)=>e.created-t.created),a},synchronizeOfflineData:async function(){try{if(!this.synchronizing){let e=await this.dbSync.allDocs({include_docs:!0,attachments:!0});if(e.rows.length){console.log("Synchronization started"),this.synchronizing=!0;let t=this.optimizeQueue(e);this.sendData(t[0],t)}}}catch(t){console.log(t)}},removeArray(e,t){if(e&&t){let a=t.indexOf(e);-1<a&&t.splice(a,1)}},isNavigatorOffline:function(){return!navigator.onLine},getSyncServicePouchDB:function(){return cronapi.internal.getPouchDB("syncService")},synchronizing:null,dbSync:null,lastStatus:null};return t.start(),t}]);
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&&currentRow.__$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&&parameters.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&&parameters.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}]);
package/dist/js/parser.js CHANGED
@@ -1 +1 @@
1
- (function(){var ISO_PATTERN=/^(\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=/^PT(?:(\d\d?)H)?(?:(\d\d?)M)?(?:(\d\d?)(?:\.(\d\d?\d?)?)?S)?$/,NUMBER_STR_PATTERN=/\d+/;window.stringToJs=function(a){var b="";if(a!=null&&null!=a){a=a.toString();for(var d,e=0;e<a.length;e++)d=a.charAt(e),"\\"==d?b+="\\\\":"'"==d?b+="\\'":"\""==d?b+="\\\"":"\n"==d?b+="\\n":"\r"==d||(b+=d)}return b},window.objToOData=function(a,b){return((null==b||null==b)&&(b=!0),null==a||null==a)?"null":"number"==typeof a||"boolean"==typeof a?a+"":a instanceof Date?"datetimeoffset'"+a.toISOString()+"'":"string"==typeof a&&b?"'"+a.replaceAll("'","''")+"'":"'"+a+"'"},window.objectsAreEqual=function(a,b,c){return a=oDataToObj(a,void 0,c),b=oDataToObj(b,void 0,c),a instanceof Date&&b instanceof Date?a.getTime()==b.getTime():a==b},window.oDataToObj=function(a,b,c){if((null==b||null==b)&&(b=!0),"string"==typeof a){if(c&&"String"==c)return a;if(10<=a.length&&a.match(ISO_PATTERN)&&100>a.length)return new Date(a);if(4<=a.length&&a.match(TIME_PATTERN)&&100>a.length)try{var d=moment().utcOffset(window.systemTimeZoneOffset,!0),e=TIME_PATTERN.exec(a);return d=d.hour(e[1]).minute(e[2]).second(e[3]).year(1970).dayOfYear(1).month(0),d.toDate()}catch(b){return a}else{if(10<=a.length&&"/Date("==a.substring(0,6)&&")/"==a.substring(a.length-2,a.length)){var f=a.substring(6,a.length-2);return new Date(parseInt(f))}if(20<=a.length&&"datetime'"==a.substring(0,9)&&"'"==a.substring(a.length-1,a.length)){var f=a.substring(9,a.length-1);return f.match(NUMBER_STR_PATTERN)?new Date(parseInt(f)):new Date(f)}if(20<=a.length&&"datetimeoffset'"==a.substring(0,15)&&"'"==a.substring(a.length-1,a.length)){var f=a.substring(15,a.length-1);return f.match(NUMBER_STR_PATTERN)?new Date(parseInt(f)):new Date(f)}if(2<=a.length&&("'"==a.charAt(0)&&"'"==a.charAt(a.length-1)||"\""==a.charAt(0)&&"\""==a.charAt(a.length-1))){var f=a.substring(1,a.length-1);return f}if("true"==a||"false"==a)return"true"==a;if("null"==a)return null;if(!c&&a&&a.startsWith("0"))return a;if(!isNaN(a)&&!isNaN(parseFloat(a)))return parseFloat(a)}}return a},window.parseXml=function(a){var b=null;if(window.DOMParser)try{b=new DOMParser().parseFromString(a,"text/xml")}catch(a){b=null}else if(window.ActiveXObject)try{b=new ActiveXObject("Microsoft.XMLDOM"),b.async=!1,b.loadXML(a)||console.log(b.parseError.reason+b.parseError.srcText)}catch(a){b=null}return b},window.xml2json=function(a,b){var c={toObj:function(a){var b={};if(1==a.nodeType){if(a.attributes.length)for(var d=0;d<a.attributes.length;d++)b["@"+a.attributes[d].nodeName]=(a.attributes[d].nodeValue||"").toString();if(a.firstChild){for(var e=0,f=0,g=!1,h=a.firstChild;h;h=h.nextSibling)1==h.nodeType?g=!0:3==h.nodeType&&h.nodeValue.match(/[^ \f\n\r\t\v]/)?e++:4==h.nodeType&&f++;if(g){if(2>e&&2>f){c.removeWhite(a);for(var h=a.firstChild;h;h=h.nextSibling)3==h.nodeType?b["#text"]=c.escape(h.nodeValue):4==h.nodeType?b["#cdata"]=c.escape(h.nodeValue):b[c.normalizeName(h.nodeName)]?b[c.normalizeName(h.nodeName)]instanceof Array?b[c.normalizeName(h.nodeName)][b[c.normalizeName(h.nodeName)].length]=c.toObj(h):b[c.normalizeName(h.nodeName)]=[b[c.normalizeName(h.nodeName)],c.toObj(h)]:b[c.normalizeName(h.nodeName)]=c.toObj(h)}else a.attributes.length?b["#text"]=c.escape(c.innerXml(a)):b=c.escape(c.innerXml(a));}else if(e)a.attributes.length?b["#text"]=c.escape(c.innerXml(a)):b=c.escape(c.innerXml(a));else if(f)if(1<f)b=c.escape(c.innerXml(a));else for(var h=a.firstChild;h;h=h.nextSibling)b["#cdata"]=c.escape(h.nodeValue)}a.attributes.length||a.firstChild||(b=null)}else 9==a.nodeType?b=c.toObj(a.documentElement):console.log("unhandled node type: "+a.nodeType);return b},normalizeName:function(a){if(a&&5<a.length&&0==a.indexOf("cron-")){a=a.substr(5);var b="",c=!1;for(var d in a){var e=a.charAt(d);c&&"-"!=e?(b+=e.toUpperCase(),c=!1):"-"==e?c=!0:b+=e.toLowerCase()}return b}},toJson:function(a,b,d){var e=b?"\""+b+"\"":"";if(a instanceof Array){for(var f=0,g=a.length;f<g;f++)a[f]=c.toJson(a[f],"",d+"\t");e+=(b?":[":"[")+(1<a.length?"\n"+d+"\t"+a.join(",\n"+d+"\t")+"\n"+d:a.join(""))+"]"}else if(null==a)e+=(b&&":")+"null";else if("object"==typeof a){var h=[];for(var j in a)h[h.length]=c.toJson(a[j],j,d+"\t");e+=(b?":{":"{")+(1<h.length?"\n"+d+"\t"+h.join(",\n"+d+"\t")+"\n"+d:h.join(""))+"}"}else if("string"==typeof a){var k=$.trim(a.toString());e+=(b&&":")+"\""+c.htmlDecode(k)+"\""}else e+=(b&&":")+c.htmlDecode($.trim(a.toString()));return e},htmlDecode:function(a){var b=new DOMParser().parseFromString(a,"text/html");return b.documentElement.textContent},innerXml:function(a){var b="";if("innerHTML"in a)b=a.innerHTML;else for(var d=function(a){var b="";if(1==a.nodeType){b+="<"+a.nodeName;for(var e=0;e<a.attributes.length;e++)b+=" "+a.attributes[e].nodeName+"=\""+(a.attributes[e].nodeValue||"").toString()+"\"";if(a.firstChild){b+=">";for(var f=a.firstChild;f;f=f.nextSibling)b+=d(f);b+="</"+a.nodeName+">"}else b+="/>"}else 3==a.nodeType?b+=a.nodeValue:4==a.nodeType&&(b+="<![CDATA["+a.nodeValue+"]]>");return b},e=a.firstChild;e;e=e.nextSibling)b+=d(e);return b},escape:function(a){return a.trim().replace(/[\\]/g,"\\\\").replace(/[\"]/g,"\\\"").replace(/[\n]/g,"\\n").replace(/[\r]/g,"\\r")},removeWhite:function(a){a.normalize();for(var b=a.firstChild;b;)if(!(3==b.nodeType))1==b.nodeType?(c.removeWhite(b),b=b.nextSibling):b=b.nextSibling;else if(!b.nodeValue.match(/[^ \f\n\r\t\v]/)){var d=b.nextSibling;a.removeChild(b),b=d}else b=b.nextSibling;return a}};9==a.nodeType&&(a=a.documentElement);var d=c.toJson(c.toObj(c.removeWhite(a)),a.nodeName,"\t");return"{\n"+b+(b?d.replace(/\t/g,b):d.replace(/\t|\n/g,""))+"\n}"},window.json2xml=function(b,d){var e=b,a=document.createElement(d),g=function(a){return{}.toString.call(a).split(" ")[1].slice(0,-1).toLowerCase()},h=function(a){var b="";for(var c in a){var d=a.charAt(c);0<c&&d==d.toUpperCase()&&(b+="-"),b+=d.toLowerCase()}return"cron-"+b},i=function(b,d,c){if("array"!=g(c)&&"object"!=g(c))"null"!=g(c)&&d.appendChild(document.createTextNode(c));else for(var a in c){var e=c[a];if("__type"==a&&"object"==g(c))d.setAttribute("__type",e);else if("object"==g(e)){var f=d.appendChild(document.createElementNS(null,h(a)));b(b,f,e)}else if("array"==g(e))for(var i in e){var f=d.appendChild(document.createElementNS(null,h(a)));b(b,f,e[i],!0)}else{var j=document.createElementNS(null,h(a));"null"!=g(e)&&("string"==g(e)&&(e=e.trim()),j.appendChild(document.createTextNode(e)));var f=d.appendChild(j)}}};return i(i,a,e,"array"==g(e)),a.outerHTML},window.buildElementOptions=function(a){var b=$(a).closest("[data-component]").find("cron-options"),c=parseXml("<cron-options>"+$(b).html()+"</cron-options>"),d=xml2json(c);return d&&(d=d.slice(1),d=d.substring(0,d.length-1),d=d.trim(),d=d.replace(/undefined"cron-options":/gm,""),d=d.replace(/"undefined"/gm,""),d=d.replace(/"undefined:"/gm,""),d=d.replace(/undefined:/gm,""),d=d.replace(/undefined/gm,""),d=d.replace(/"cron-options":/gm,"")),d},window.objectClone=function(a,b){var c;if(null==a||"object"!=typeof a)return a;if(a instanceof Date)return c=new Date,c.setTime(a.getTime()),c;if(a instanceof Array){c=[];for(var d=0,e=a.length;d<e;d++)c[d]=objectClone(a[d],void 0);return c}var f=function(a,b){if(!b)return!0;for(var c in b)if(a==c)return!0;return!1},g=function(a){return a&&"[object Function]"==={}.toString.call(a)};if(a instanceof Object){for(var h in c={},a)a.hasOwnProperty(h)&&null!=a[h]&&("_"!=h.substr(0,1)||"_objectKey"==h)&&!g(a[h])&&f(h,b)&&(c[h]=objectClone(a[h],b[h]));return c}throw new Error("Unable to copy obj! Its type isn't supported.")},window.getOperatorODATA=function(a,b,c){if("%"==b)return"substringof("+c+", "+a+")";return"="==b?a+" eq "+c:"!="==b?a+" ne "+c:">"==b?a+" gt "+c:">="==b?a+" ge "+c:"<"==b?a+" lt "+c:"<="==b?a+" le "+c:void 0},window.executeRight=function(right){var result="null";return null!=right&&null!=right&&(right.startsWith(":")||right.startsWith("datetimeoffset'")||right.startsWith("datetime'")?result=right:(result=eval(right),result instanceof Date?result="datetimeoffset'"+result.toISOString()+"'":"string"==typeof result?result="'"+result+"'":(void 0===result||null==result)&&(result="null"))),result},window.parserOdata=function(a){var b="",c=a.type;if(a.args)for(var d=0;d<a.args.length;d++){var e=a.args[d],f=c;0==d&&(f=""),b=e.args&&0<e.args.length?b+" "+f.toLowerCase()+" ( "+parserOdata(e)+" ) ":b+" "+f.toLowerCase()+" "+getOperatorODATA(e.left,e.type,executeRight(e.right))}return b.trim()}})();
1
+ (function(){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\\d?)H)?(?:(\\d\\d?)M)?(?:(\\d\\d?)(?:\\.(\\d\\d?\\d?)?)?S)?$"),NUMBER_STR_PATTERN=new RegExp("\\d+");window.stringToJs=function(e){var t="";if(null!=e&&null!=e){e=e.toString();for(var n=0;n<e.length;n++){var r=e.charAt(n);"\\"==r?t+="\\\\":"'"==r?t+="\\'":'"'==r?t+='\\"':"\n"==r?t+="\\n":"\r"==r||(t+=r)}}return t},window.objToOData=function(e,t){return null!=t&&null!=t||(t=!0),null==e||null==e?"null":"number"==typeof e||"boolean"==typeof e?e+"":e instanceof Date?"datetimeoffset'"+e.toISOString()+"'":"string"==typeof e&&t?"'"+e.replaceAll("'","''")+"'":"'"+e+"'"},window.objectsAreEqual=function(e,t,n){return e=oDataToObj(e,void 0,n),t=oDataToObj(t,void 0,n),e instanceof Date&&t instanceof Date?e.getTime()==t.getTime():e==t},window.oDataToObj=function(e,t,n){if(null!=t&&null!=t||(t=!0),"string"==typeof e){if(n&&"String"==n)return e;if(e.length>=10&&e.match(ISO_PATTERN)&&e.length<100)return new Date(e);if(e.length>=4&&e.match(TIME_PATTERN)&&e.length<100)try{var r=moment().utcOffset(window.systemTimeZoneOffset,!0),o=TIME_PATTERN.exec(e);return(r=r.hour(o[1]).minute(o[2]).second(o[3]).year(1970).dayOfYear(1).month(0)).toDate()}catch(t){return e}else{if(e.length>=10&&"/Date("==e.substring(0,6)&&")/"==e.substring(e.length-2,e.length)){var i=e.substring(6,e.length-2);return new Date(parseInt(i))}if(e.length>=20&&"datetime'"==e.substring(0,9)&&"'"==e.substring(e.length-1,e.length))return(i=e.substring(9,e.length-1)).match(NUMBER_STR_PATTERN)?new Date(parseInt(i)):new Date(i);if(e.length>=20&&"datetimeoffset'"==e.substring(0,15)&&"'"==e.substring(e.length-1,e.length))return(i=e.substring(15,e.length-1)).match(NUMBER_STR_PATTERN)?new Date(parseInt(i)):new Date(i);if(e.length>=2&&("'"==e.charAt(0)&&"'"==e.charAt(e.length-1)||'"'==e.charAt(0)&&'"'==e.charAt(e.length-1)))return i=e.substring(1,e.length-1);if("true"==e||"false"==e)return"true"==e;if("null"==e)return null;if(!n&&e&&e.startsWith("0"))return e;if(!isNaN(e)&&!isNaN(parseFloat(e)))return parseFloat(e)}}return e},window.parseXml=function(e){var t=null;if(window.DOMParser)try{t=(new DOMParser).parseFromString(e,"text/xml")}catch(e){t=null}else if(window.ActiveXObject)try{(t=new ActiveXObject("Microsoft.XMLDOM")).async=!1,t.loadXML(e)||console.log(t.parseError.reason+t.parseError.srcText)}catch(e){t=null}return t},window.xml2json=function(e,t){var n={toObj:function(e){var t={};if(1==e.nodeType){if(e.attributes.length)for(var r=0;r<e.attributes.length;r++)t["@"+e.attributes[r].nodeName]=(e.attributes[r].nodeValue||"").toString();if(e.firstChild){for(var o=0,i=0,a=!1,l=e.firstChild;l;l=l.nextSibling)1==l.nodeType?a=!0:3==l.nodeType&&l.nodeValue.match(/[^ \f\n\r\t\v]/)?o++:4==l.nodeType&&i++;if(a)if(o<2&&i<2){n.removeWhite(e);for(l=e.firstChild;l;l=l.nextSibling)3==l.nodeType?t["#text"]=n.escape(l.nodeValue):4==l.nodeType?t["#cdata"]=n.escape(l.nodeValue):t[n.normalizeName(l.nodeName)]?t[n.normalizeName(l.nodeName)]instanceof Array?t[n.normalizeName(l.nodeName)][t[n.normalizeName(l.nodeName)].length]=n.toObj(l):t[n.normalizeName(l.nodeName)]=[t[n.normalizeName(l.nodeName)],n.toObj(l)]:t[n.normalizeName(l.nodeName)]=n.toObj(l)}else e.attributes.length?t["#text"]=n.escape(n.innerXml(e)):t=n.escape(n.innerXml(e));else if(o)e.attributes.length?t["#text"]=n.escape(n.innerXml(e)):t=n.escape(n.innerXml(e));else if(i)if(i>1)t=n.escape(n.innerXml(e));else for(l=e.firstChild;l;l=l.nextSibling)t["#cdata"]=n.escape(l.nodeValue)}e.attributes.length||e.firstChild||(t=null)}else 9==e.nodeType?t=n.toObj(e.documentElement):console.log("unhandled node type: "+e.nodeType);return t},normalizeName:function(e){if(e&&e.length>5&&0==e.indexOf("cron-")){e=e.substr(5);var t="",n=!1;for(var r in e){var o=e.charAt(r);n&&"-"!=o?(t+=o.toUpperCase(),n=!1):"-"==o?n=!0:t+=o.toLowerCase()}return t}},toJson:function(e,t,r){var o=t?'"'+t+'"':"";if(e instanceof Array){for(var i=0,a=e.length;i<a;i++)e[i]=n.toJson(e[i],"",r+"\t");o+=(t?":[":"[")+(e.length>1?"\n"+r+"\t"+e.join(",\n"+r+"\t")+"\n"+r:e.join(""))+"]"}else if(null==e)o+=(t&&":")+"null";else if("object"==typeof e){var l=[];for(var s in e)l[l.length]=n.toJson(e[s],s,r+"\t");o+=(t?":{":"{")+(l.length>1?"\n"+r+"\t"+l.join(",\n"+r+"\t")+"\n"+r:l.join(""))+"}"}else if("string"==typeof e){var u=$.trim(e.toString());o+=(t&&":")+'"'+n.htmlDecode(u)+'"'}else o+=(t&&":")+n.htmlDecode($.trim(e.toString()));return o},htmlDecode:function(e){return(new DOMParser).parseFromString(e,"text/html").documentElement.textContent},innerXml:function(e){var t="";if("innerHTML"in e)t=e.innerHTML;else for(var n=function(e){var t="";if(1==e.nodeType){t+="<"+e.nodeName;for(var r=0;r<e.attributes.length;r++)t+=" "+e.attributes[r].nodeName+'="'+(e.attributes[r].nodeValue||"").toString()+'"';if(e.firstChild){t+=">";for(var o=e.firstChild;o;o=o.nextSibling)t+=n(o);t+="</"+e.nodeName+">"}else t+="/>"}else 3==e.nodeType?t+=e.nodeValue:4==e.nodeType&&(t+="<![CDATA["+e.nodeValue+"]]>");return t},r=e.firstChild;r;r=r.nextSibling)t+=n(r);return t},escape:function(e){return e.trim().replace(/[\\]/g,"\\\\").replace(/[\"]/g,'\\"').replace(/[\n]/g,"\\n").replace(/[\r]/g,"\\r")},removeWhite:function(e){e.normalize();for(var t=e.firstChild;t;)if(3==t.nodeType)if(t.nodeValue.match(/[^ \f\n\r\t\v]/))t=t.nextSibling;else{var r=t.nextSibling;e.removeChild(t),t=r}else 1==t.nodeType?(n.removeWhite(t),t=t.nextSibling):t=t.nextSibling;return e}};9==e.nodeType&&(e=e.documentElement);var r=n.toJson(n.toObj(n.removeWhite(e)),e.nodeName,"\t");return"{\n"+t+(t?r.replace(/\t/g,t):r.replace(/\t|\n/g,""))+"\n}"},window.json2xml=function(e,t){var n=e,r=document.createElement(t),o=function(e){return{}.toString.call(e).split(" ")[1].slice(0,-1).toLowerCase()},i=function(e){var t="";for(var n in e){var r=e.charAt(n);n>0&&r==r.toUpperCase()&&(t+="-"),t+=r.toLowerCase()}return"cron-"+t},a=function(e,t,n,r){if("array"!=o(n)&&"object"!=o(n))"null"!=o(n)&&t.appendChild(document.createTextNode(n));else for(var a in n){var l=n[a];if("__type"==a&&"object"==o(n))t.setAttribute("__type",l);else if("object"==o(l))e(e,t.appendChild(document.createElementNS(null,i(a))),l);else if("array"==o(l))for(var s in l){e(e,t.appendChild(document.createElementNS(null,i(a))),l[s],!0)}else{var u=document.createElementNS(null,i(a));"null"!=o(l)&&("string"==o(l)&&(l=l.trim()),u.appendChild(document.createTextNode(l)));t.appendChild(u)}}};return a(a,r,n,o(n)),r.outerHTML},window.buildElementOptions=function(e){var t=$(e).closest("[data-component]").find("cron-options"),n=parseXml("<cron-options>"+$(t).html()+"</cron-options>"),r=xml2json(n);return r&&(r=(r=(r=(r=(r=(r=(r=(r=(r=r.slice(1)).substring(0,r.length-1)).trim()).replace(/undefined"cron-options":/gm,"")).replace(/"undefined"/gm,"")).replace(/"undefined:"/gm,"")).replace(/undefined:/gm,"")).replace(/undefined/gm,"")).replace(/"cron-options":/gm,"")),r},window.objectClone=function(e,t){var n;if(null==e||"object"!=typeof e)return e;if(e instanceof Date)return(n=new Date).setTime(e.getTime()),n;if(e instanceof Array){n=[];for(var r=0,o=e.length;r<o;r++)n[r]=objectClone(e[r],void 0);return n}var i,a=function(e,t){if(t){for(var n in t)if(e==n)return!0;return!1}return!0};if(e instanceof Object){for(var l in n={},e)!e.hasOwnProperty(l)||null==e[l]||"_"==l.substr(0,1)&&"_objectKey"!=l||(i=e[l])&&"[object Function]"==={}.toString.call(i)||!a(l,t)||(n[l]=objectClone(e[l],t[l]));return n}throw new Error("Unable to copy obj! Its type isn't supported.")},window.getOperatorODATA=function(e,t,n){return"%"==t?"substringof("+n+", "+e+")":"="==t?e+" eq "+n:"!="==t?e+" ne "+n:">"==t?e+" gt "+n:">="==t?e+" ge "+n:"<"==t?e+" lt "+n:"<="==t?e+" le "+n:void 0},window.executeRight=function(right){var result="null";return null!=right&&null!=right&&(right.startsWith(":")||right.startsWith("datetimeoffset'")||right.startsWith("datetime'")?result=right:(result=eval(right),result instanceof Date?result="datetimeoffset'"+result.toISOString()+"'":"string"==typeof result?result="'"+result+"'":void 0!==result&&null!=result||(result="null"))),result},window.parserOdata=function(e){var t="",n=e.type;if(e.args)for(var r=0;r<e.args.length;r++){var o=e.args[r],i=n;0==r&&(i=""),t=o.args&&o.args.length>0?t+" "+i.toLowerCase()+" ( "+parserOdata(o)+" ) ":t+" "+i.toLowerCase()+" "+getOperatorODATA(o.left,o.type,executeRight(o.right))}return t.trim()}})();
package/gulpfile.js CHANGED
@@ -1,24 +1,18 @@
1
- var gulp = require('gulp'),
2
- autoprefixer = require('gulp-autoprefixer'),
3
- uglify = require('gulp-uglify'),
4
- rename = require('gulp-rename'),
5
- notify = require('gulp-notify'),
6
- uglifycss = require('gulp-uglifycss'),
7
- imagemin = require('gulp-imagemin'),
8
- htmlmin = require('gulp-htmlmin'),
9
- ngAnnotate = require('gulp-ng-annotate-patched'),
10
- minify = require("gulp-babel-minify");
11
- gulp.task('minify-js', function() {
12
- return gulp.src(['js/**'])
13
- .pipe(ngAnnotate())
14
- .pipe(minify({
15
- mangle: {
16
- keepClassName: true
17
- }
18
- }))
19
- .pipe(gulp.dest('dist/js/'));
1
+ import gulp from 'gulp';
2
+ import ngAnnotate from 'gulp-ng-annotate-patched';
3
+ import terser from 'gulp-terser';
4
+
5
+ gulp.task('minify', function () {
6
+ return gulp.src(['js/**/*.js'])
7
+ .pipe(ngAnnotate())
8
+ .pipe(terser({
9
+ mangle: {
10
+ keep_classnames : true
11
+ }
12
+ }))
13
+ .pipe(gulp.dest('dist/js/'));
20
14
  });
21
15
 
22
- gulp.task('build', ['minify-js']);
16
+ gulp.task('build', gulp.series('minify'));
23
17
 
24
- gulp.task('default', ['build']);
18
+ gulp.task('default', gulp.series('build'));
@@ -2014,6 +2014,11 @@ angular.module('datasourcejs', [])
2014
2014
  xhr.setRequestHeader('X-AUTH-TOKEN', _u?.token);
2015
2015
  }
2016
2016
 
2017
+ const csrfToken = document.cookie.match(new RegExp('(^| )XSRF-TOKEN=([^;]+)'));
2018
+ if (csrfToken) {
2019
+ xhr.setRequestHeader('X-XSRF-TOKEN', csrfToken[2]);
2020
+ }
2021
+
2017
2022
  xhr.onreadystatechange = function(){
2018
2023
  if(xhr.readyState === 4 && xhr.status === 500){
2019
2024
  var parser = new DOMParser();
@@ -5337,4 +5342,4 @@ angular.module('sync.service', []).service('SyncService', function($http) {
5337
5342
  syncService.start();
5338
5343
 
5339
5344
  return syncService;
5340
- });
5345
+ });
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "cronapp-common-js",
3
- "version": "3.2.1-SP.4",
3
+ "version": "4.0.0",
4
4
  "description": "Cronapp Commons Functions",
5
5
  "main": "parser.js",
6
+ "type": "module",
6
7
  "scripts": {
8
+ "build": "gulp",
7
9
  "test": "echo \"Error: no test specified\" && exit 1"
8
10
  },
9
11
  "repository": {
@@ -22,16 +24,15 @@
22
24
  "javascript"
23
25
  ],
24
26
  "devDependencies": {
25
- "gulp": "^3.9.1",
26
- "gulp-autoprefixer": "^3.1.1",
27
- "gulp-babel": "^8.0.0",
28
- "gulp-babel-minify": "^0.5.1",
29
- "gulp-htmlmin": "^1.3.0",
30
- "gulp-imagemin": "^2.4.0",
27
+ "gulp": "^5.0.0",
28
+ "gulp-autoprefixer": "^9.0.0",
29
+ "gulp-htmlmin": "^5.0.1",
30
+ "gulp-imagemin": "^9.1.0",
31
31
  "gulp-ng-annotate-patched": "^0.1.1",
32
- "gulp-notify": "^3.0.0",
33
- "gulp-rename": "^1.2.2",
32
+ "gulp-notify": "^5.0.0",
33
+ "gulp-rename": "^2.0.0",
34
+ "gulp-terser": "^2.1.0",
34
35
  "gulp-uglify": "^3.0.2",
35
36
  "gulp-uglifycss": "^1.0.8"
36
37
  }
37
- }
38
+ }