zettapi_client
Version:
Client side CRUD operations in angular to use with zettapi_server rest api to get started quickly in any CMS project
2 lines • 52.2 kB
JavaScript
function dlKeyCode(){return{restrict:"A",link:function(e,t,n){t.bind("keypress",function(t){var r=t.which||t.keyCode;r==n.code&&e.$apply(function(){e.$eval(n.dlKeyCode,{$event:t})})})}}}var app=angular.module("zapi",["ngSanitize","ngAnimate","ui.bootstrap","blockUI","chart.js","btford.socket-io","ngCsv","ngTable","selector","ngIdle","pascalprecht.translate","ngPasswordMeter"]).config(["TitleProvider","$locationProvider",function(e,t){e.enabled(!1),t.hashPrefix("")}]).provider("zapi",["apiEntityMap",function(e){var t,n={},r=!1,i="";return{getRoutes:function(e){if("undefined"==typeof n[e.entity])return"entity/entity.notfound.html";if("undefined"==typeof n[e.entity][e.action])return"entity/entity.notfound.html";switch(e.action){case"edit":return"entity/entity.edit.html";case"view":return"undefined"==typeof e.id?"entity/entity.notfound.html":"entity/entity.view.html";case"list":return"undefined"!=typeof e.id?"entity/entity.notfound.html":"entity/entity.list.html";default:return"entity/entity.notfound.html"}},setMap:function(t){n=e;for(var r in t)n[r]=t[r]},setServerUrl:function(e){i=e||""},setWebsocket:function(e){t=e||void 0},setIdle:function(e){r=e},$get:function(){return{entityMap:n,idle:r,serverUrl:i,websocketUrl:t}}}}]);app.controller("entityCtrl",["$entity","zapi","$page","mySocket","$routeParams","$controller","$location","$scope","$uibModal","blockUI","NgTableParams","$translate","$license",function($entity,zapi,$page,mySocket,$routeParams,$controller,$location,$scope,$uibModal,blockUI,NgTableParams,$translate,$license){function get(e,t,n){$translate(["api.entity.getData","api.entity.errorData"]).then(function(r){blockUI.start(r["api.entity.getData"]),getLookups($scope.lookup,function(i,a){return i?(swal("Não foi possível obter os dados",r["api.entity.errorData"],"warning"),blockUI.stop(),n(i)):($scope.lookup=a,$routeParams.id||"edit"!==$routeParams.action?void $entity.get(e,t).then(function(e){t?$scope.item=e.data:($scope.items=e.data,$scope.table.params=new NgTableParams({},{dataset:$scope.items}))}).catch(function(e){swal("Não foi possível obter os dados",r["api.entity.errorData"],"warning")}).finally(function(){blockUI.stop(),n()}):(blockUI.stop(),n()))})})}function getLookups(e,t){return e&&e.length?t(null,e):void $entity.getLookups($routeParams.entity,function(e,n){return e?t(e):void t(null,n)})}function setEdit(e){e?$scope.item=angular.copy(e):$scope.item="function"==typeof $scope.blank?$scope.blank():{}}function loadFinished(){if($routeParams.entity){try{$controller($routeParams.entity+"Ctrl",{$scope:$scope})}catch(e){console.log(e)}var websocket;websocket="undefined"==typeof zapi.entityMap[$routeParams.entity].websocket?$routeParams.entity:eval(zapi.entityMap[$routeParams.entity].websocket)+"."+$routeParams.entity,mySocket.on(websocket+".remove",onThisEntityRemove),mySocket.on(websocket+".new",onThisEntityAdd),mySocket.on(websocket+".edit",onThisEntityEdit)}}function onThisEntityAdd(e){switch(console.log("io.on","add",e),$routeParams.action){case"list":$scope.items.unshift(e),$scope.table.params.total($scope.items.length),$scope.table.params.reload()}}function onThisEntityEdit(e){switch(console.log("io.on","edit",e),$routeParams.action){case"list":for(var t=0;t<$scope.items.length;t++)if($scope.items[t]._id===e._id){$scope.items[t]=e,$scope.table.params.reload();break}break;case"view":case"edit":$scope.item._id===e._id&&($scope.item=e)}}function onThisEntityRemove(e){switch(console.log("io.on","remove",e),$routeParams.action){case"list":for(var t=0;t<$scope.items.length;t++)if($scope.items[t]._id===e){$scope.items.splice(t,1),$scope.table.params.total($scope.items.length),$scope.table.params.reload();break}break;case"view":case"edit":$scope.item._id===e._id&&(swal("Outro utilizador apagou esta página","Iremos redireciona-lo para a lista actualizada de "+$scope.entity.title,"info"),$location.path("/"+$routeParams.entity+"/list"))}}function initialize(e){$scope.entity=zapi.entityMap[$routeParams.entity];var t=["api.entity.whereyougo","api.entity.newRecord","api.entity.editRecord","api.entity.viewRecord"];$scope.entity&&t.push($scope.entity.title),$translate(t).then(function(t){if($page.setTitle(t["api.entity.whereyougo"]),$scope.entity){if("undefined"!=typeof $scope.entity.license){var n=$license.isLicensed($scope.entity.license);if(!n)return $license.notify($scope.entity.license)}switch($routeParams.action){case"edit":$routeParams.id?($page.setTitle(t[$scope.entity.title]+"-"+t["api.entity.editRecord"]),get($routeParams.entity,$routeParams.id,e)):($page.setTitle(t[$scope.entity.title]+"-"+t["api.entity.newRecord"]),get($routeParams.entity,null,e));break;case"view":if(!$routeParams.id)return;$page.setTitle(t[$scope.entity.title]+"-"+t["api.entity.viewRecord"]),get($routeParams.entity,$routeParams.id,e);break;case"list":if($routeParams.id)return;$page.setTitle(t[$scope.entity.title]),get($routeParams.entity,null,e);break;default:return}}})}function skip(e){e()}$scope.table={params:null},$scope.console=null,$scope.entities=zapi.entityMap,$scope.entityName=$routeParams.entity,$scope.lookup={},$scope.items=[],$scope.item={},$scope.newFile={},$scope.add=function(e,t,n){$translate(["api.entity.sendData",$scope.entity.title,"api.entity.newRecordSuccess","api.entity.editRecordSuccess"]).then(function(r){blockUI.start(r["api.entity.sendData"]);var i="function"==typeof t?t:skip;i(function(t){return t?swal("Antes de guardar",t,"info"):void $entity.add($routeParams.entity,e).then(function(t){e._id?swal("Alterado",r[$scope.entity.title]+r["api.entity.newRecordSuccess"],"success"):swal("Criado",r[$scope.entity.title]+r["api.entity.editRecordSuccess"],"success"),"function"==typeof n&&n()}).catch(function(e){swal("Erro ao Guardar",e.data,"error"),"function"==typeof n&&n(e.data)}).finally(function(){blockUI.stop()})})})},$scope.remove=function(e){$translate(["api.entity.checkRemove",$scope.entity.title,"api.entity.deleteRecordSuccess"]).then(function(t){blockUI.start(t["api.entity.checkRemove"]),$entity.remove($routeParams.entity,e).then(function(e){swal("Removido",t[$scope.entity.title]+t["api.entity.deleteRecordSuccess"],"success")}).catch(function(e){swal("Erro ao Remover",e.error?e.error:e.data,"warning")}).finally(function(){blockUI.stop()})})},$scope.openEdit=function(e){if(!$scope.entity.modal){var t=$location.path();return t=t.substring(0,t.lastIndexOf("/"))+"/edit",e?$location.path(t+"/"+e._id):$location.path(t)}setEdit(e);var n=$uibModal.open({animation:!0,templateUrl:"entity/entity.modal.html",controller:"entityModalCtrl",size:"lg",backdrop:"static",scope:$scope});n.result.then(function(e){},function(){$translate("api.entity.cancelRecord").then(function(e){console.log(e)}),$scope.item={}})},$scope.validate=function(){if("function"==typeof $scope.getError){var e=$scope.getError($scope.item,$scope.items);if(e.disabled)return $scope.console=e.tooltip,!0}return $scope.console=null,!1},$scope.flattenArray=$entity.flattenArray,$scope.applySearch=function(e){var t=angular.copy(e.text);e.inverted&&(t="!"+t),$scope.table.params.filter({$:t})},initialize(loadFinished)}]),app.controller("entityModalCtrl",["$uibModalInstance","$scope",function(e,t){t.ok=function(){t.add(t.item,t.onBeforeSave,function(e){e||t.$close(t.item)})},t.cancel=function(){t.$dismiss("cancel")}}]),app.filter("dateFilter",function(){return function(e,t,n,r){if("undefined"!=typeof e&&e instanceof Array){n="undefined"==typeof n?new Date("1999-01-01"):new Date(n),r="undefined"==typeof r?new Date:new Date(r);var i=[];return e.forEach(function(e){var a=new Date(e[t]);a>=n&&a<=r&&i.push(e)}),i}}}),app.filter("makePositive",function(){return function(e){if("undefined"!=typeof e)return Math.abs(e)}}),app.filter("orderObjectBy",function(){return function(e,t,n){var r=[];return angular.forEach(e,function(e){r.push(e)}),r.sort(function(e,n){return e[t]>n[t]?1:-1}),n&&r.reverse(),r}}),app.service("$address",["$http","blockUI","zapi",function(e,t,n){this.getAddressPT=function(r,i){return this.validateZipcode(r)?i("Código postal inválido"):(t.start("A procurar arruamento..."),void e.get(n.serverUrl+"/api/address/pt/"+r).then(function(e){i(null,e.data)}).catch(function(e){i(e)}).finally(function(){t.stop()}))},this.validateZipcode=function(e){if(!e)return!0;"string"!=typeof e&&(e+="");var t=e.split("-");return t.length<1||t.length>2||(!!isNaN(t[0])||t.length>1&&isNaN(t[1]))},this.getCoordinates=function(e,t){try{var n=new google.maps.Geocoder;n.geocode({address:e},function(e,n){return n!==google.maps.GeocoderStatus.OK?t(n):void t(null,{lat:e[0].geometry.location.lat(),lng:e[0].geometry.location.lng()})})}catch(e){t(e)}}}]),app.factory("$auth",["$http","$crypto","blockUI","$location","anonymousPages","customPages","routeDepth","$rootScope","Idle","zapi","$translate",function(e,t,n,r,i,a,o,s,c,l,u){function p(e){var t=e.split("/"),n=[];return t.forEach(function(e){e&&n.push(e)}),n}var d={currentUser:null,login:function(r,i,a){return u("api.services.auth.loginLoad",function(e){n.start(e)},function(e){n.start(e)}),e.post(l.serverUrl+"/api/session/login/",{username:r,password:t.isMd5(i)?i:t.md5(i)}).then(function(e){l.idle&&c.watch(),d.currentUser=e.data.user,a()}).catch(function(e){u(["api.services.auth.loginErrorTitle","api.services.auth.loginErrorContent"]).then(function(e){swal(e["api.services.auth.loginErrorTitle"],e["api.services.auth.loginErrorContent"],"error")},function(e){swal(e.api_service_auth_loginerrortitle,e.api_service_auth_loginerrorcontent,"error")}),a(!0)}).finally(function(){n.stop()})},logout:function(){e.get(l.serverUrl+"/api/session/logout").then(function(e){l.idle&&c.unwatch(),d.currentUser=null,s.login={},r.path("/")})},requestCurrentUser:function(t){return d.isAuthenticated()?t(null,d.currentUser):void e.get(l.serverUrl+"/api/session/currentuser").then(function(e){d.currentUser=e.data.user,t(null,d.currentUser)}).catch(function(e){d.currentUser=null,t(e)})},isAuthenticated:function(){return!!d.currentUser},activateAccount:function(t,r){if(!t)return r(!0);var i=t.split("&");return 2!==i.length?r(!0):(u("api.services.auth.activateAccountLoad",function(e){n.start(e)},function(e){n.start(e)}),void e.post(l.serverUrl+"/api/user/activate/",{email:i[0],code:i[1]}).then(function(e){r(null,e.data)}).catch(function(e){u(["api.services.auth.activateAccountErrorTitle","api.services.auth.activateAccountErrorContent"]).then(function(e){swal({title:e["api.services.auth.activateAccountErrorTitle"],text:e["api.services.auth.activateAccountErrorContent"],type:"info",confirmButtonText:"OK"})},function(e){swal({title:e.api_service_auth_activateaccounterrortitle,text:e.api_service_auth_activateaccounterrorcontent,type:"info",confirmButtonText:"OK"})}),r(!0)}).finally(function(){n.stop()}))},resetPassword:function(t,r,i){return u("api.services.auth.resetPasswordLoad",function(e){n.start(e)},function(e){n.start(e)}),e.post(l.serverUrl+"/api/user/resetpassword/",{email:t,username:r}).then(function(e){u(["api.services.auth.resetPasswordSuccessTitle","api.services.auth.resetPasswordSuccessContent"]).then(function(e){swal(e["api.services.auth.resetPasswordSuccessTitle"],e["api.services.auth.resetPasswordSuccessContent"],"success")},function(e){swal(e.api_service_auth_resetpasswordsuccesstitle,e.api_service_auth_resetpasswordsuccesscontent,"success")}),i()}).catch(function(e){u(["api.services.auth.resetPasswordErrorTitle","api.services.auth.resetPasswordErrorContent"]).then(function(e){swal(e["api.services.auth.resetPasswordErrorTitle"],e["api.services.auth.resetPasswordErrorContent"],"error")},function(e){swal(e.api_service_auth_resetpassworderrortitle,e.api_service_auth_resetpassworderrorcontent,"error")}),i(!0)}).finally(function(){n.stop()})},changePassword:function(r,i,a,o){if(i){if(i!==a)return void u(["api.services.auth.changepasswordWrongPasswordTitle","api.services.auth.changepasswordWrongPasswordContent"]).then(function(e){swal(e["api.services.auth.changepasswordWrongPasswordTitle"],e["api.services.auth.changepasswordWrongPasswordContent"],"error")},function(e){swal(e.api_service_auth_changepasswordwrongpasswordtitle,e.api_service_auth_changepasswordwrongpasswordcontent,"error")});r.newPassword=t.md5(i),u("api.services.auth.changepasswordLoad",function(e){n.start(e)},function(e){n.start(e)}),e.post(l.serverUrl+"/api/user/changepassword/",r).then(function(e){u(["api.services.auth.changepasswordSuccessTitle","api.services.auth.changepasswordSuccessContent","api.services.auth.changepasswordSuccessBtnOk"]).then(function(e){swal({title:e["api.services.auth.changepasswordSuccessTitle"],text:e["api.services.auth.changepasswordSuccessContent"],type:"info",confirmButtonText:e["api.services.auth.changepasswordSuccessBtnOk"]})},function(e){swal({title:e.api_service_auth_changepasswordsuccesstitle,text:e.api_service_auth_changepasswordsuccesscontent,type:"info",confirmButtonText:e.api_service_auth_changepasswordsuccessbtnok})}),o()}).catch(function(e){u(["api.services.auth.changepasswordErrorTitle","api.services.auth.changepasswordErrorContent"]).then(function(e){swal(e["api.services.auth.changepasswordErrorTitle"],e["api.services.auth.changepasswordErrorContent"],"error")},function(e){swal(e.api_service_auth_changepassworderrortitle,e.api_service_auth_changepassworderrorcontent,"error")}),o(!0)}).finally(function(){n.stop()})}},isPageAnonymous:function(){var e=p(r.path());return e instanceof Array&&(0===e.length||i.some(function(t){return t===e[0]}))},isPageCustom:function(){var e=p(r.path());return e instanceof Array&&(0!==e.length&&a.some(function(t){return!(t.length<e.length)&&!t.some(function(t,n){return"%"!==t&&t!==e[n]})}))},getNextRoute:function(e){return function(t,n,r){var i=n.substring(n.indexOf("/#/")+3),a=p(i);return d.isPageAnonymous()?e():(d.currentUser=null,void d.requestCurrentUser(function(t,n){if(s.login=(t?{}:n)||{},!s.login._id)return e("Sem sessão iniciada. Isto pode ocorrer por motivos de inactividade, aceder à mesma conta noutro computador ou actualização recente ao servidor.",n);if("profile"===a[0])return e(null,n);var r=d.isPageCustom();if(r)return e(null,n);var i=l.entityMap[a[o]];if(!i)return e("A página que está a tentar consultar não existe",n);if(a.length<=o+1)return e("A página que está a tentar consultar não existe",n);var c=i[a[o+1]];return c?n.role.admin?e(null,n):c.admin?e("A página que está a tentar consultar não existe",n):void e(null,n):e("A página que está a tentar consultar não existe",n)}))}},isAnonymous:function(){return!d.isLoggedIn()},isLoggedIn:function(){return!!d.currentUser&&!!d.currentUser._id},isAdmin:function(){return!!d.isLoggedIn()&&d.currentUser.role.admin}};return d}]),app.service("$calendar",["moment",function(e){var t={};this.addEventType=function(e,n,r){return"object"!=typeof r?console.log("promise of unexpected type for eventType "+e):"function"!=typeof r.then?console.log("promise of unexpected type for eventType "+e):(t[e]||(t[e]={}),t[e]={label:n,promise:r,visible:!0,data:[]},void r.then(function(n){n.forEach(function(t){t.type=e}),t[e].data=n}).catch(function(e){console.log(e)}))},this.getEventTypes=function(){var e=[];for(var n in t)e.push({type:n,label:t[n].label,visible:t[n].visible,count:t[n].data.length});return e},this.getEvents=function(){var e=[];for(var n in t)t[n].visible&&(e=e.concat(t[n].data));return e},this.toggleEventType=function(e){return t[e]?(t[e].visible=!t[e].visible,console.log(t),t):console.log(e,t)},this.newEvent=function(t,n,r){"undefined"==typeof t&&console.log("invalid title for event",t),"undefined"==typeof n&&console.log("invalid start for event",n),_start=e(n),_start.isValid()||console.log("invalid date start for event",n),r&&(_end=e(r),_end.isValid()||console.log("invalid date end for event",r));var i={title:t,startsAt:new Date(n),draggable:!1,resizable:!1,incrementsBadgeTotal:!0,allDay:!0};return r&&(i.endsAt=new Date(r)),i}}]),app.constant("zapiPath","node_modules/zettapi_client/lib/"),app.constant("chartTypes",[["bar","doughnut","pie","horizontalBar"],["line","radar"],["bubble","polar-area"]]),app.constant("graphOptions",{responsive:!0,responsiveAnimationDuration:1500,tooltip:{enabled:!0},elements:{line:{tension:.4,stepped:!1}}}),app.constant("apiEntityMap",{activity:{title:"api.pages.activity.title",list:{admin:!0}},alert:{title:"api.pages.alert.title",list:{admin:!0},edit:{admin:!0},modal:!0},country:{title:"Países",list:{admin:!0}},error:{title:"api.pages.error.title",list:{admin:!0}},holiday:{title:"Feriados",lookup:["country"],list:{admin:!0},edit:{admin:!0},modal:!0},maintenance:{title:"Agendamento de Manutenção",list:{admin:!0},edit:{admin:!0},modal:!0},message:{title:"api.pages.message.title",list:{admin:!0}},role:{title:"api.pages.role.title",list:{admin:!0},edit:{admin:!0},modal:!0},task:{title:"api.pages.task.title",list:{admin:!0},edit:{admin:!0},modal:!0},user:{title:"api.pages.user.title",lookup:["role"],list:{admin:!1},edit:{admin:!1},modal:!0}}),app.service("$crypto",function(){function e(e,t){var o=e[0],s=e[1],c=e[2],l=e[3];o=n(o,s,c,l,t[0],7,-680876936),l=n(l,o,s,c,t[1],12,-389564586),c=n(c,l,o,s,t[2],17,606105819),s=n(s,c,l,o,t[3],22,-1044525330),o=n(o,s,c,l,t[4],7,-176418897),l=n(l,o,s,c,t[5],12,1200080426),c=n(c,l,o,s,t[6],17,-1473231341),s=n(s,c,l,o,t[7],22,-45705983),o=n(o,s,c,l,t[8],7,1770035416),l=n(l,o,s,c,t[9],12,-1958414417),c=n(c,l,o,s,t[10],17,-42063),s=n(s,c,l,o,t[11],22,-1990404162),o=n(o,s,c,l,t[12],7,1804603682),l=n(l,o,s,c,t[13],12,-40341101),c=n(c,l,o,s,t[14],17,-1502002290),s=n(s,c,l,o,t[15],22,1236535329),o=r(o,s,c,l,t[1],5,-165796510),l=r(l,o,s,c,t[6],9,-1069501632),c=r(c,l,o,s,t[11],14,643717713),s=r(s,c,l,o,t[0],20,-373897302),o=r(o,s,c,l,t[5],5,-701558691),l=r(l,o,s,c,t[10],9,38016083),c=r(c,l,o,s,t[15],14,-660478335),s=r(s,c,l,o,t[4],20,-405537848),o=r(o,s,c,l,t[9],5,568446438),l=r(l,o,s,c,t[14],9,-1019803690),c=r(c,l,o,s,t[3],14,-187363961),s=r(s,c,l,o,t[8],20,1163531501),o=r(o,s,c,l,t[13],5,-1444681467),l=r(l,o,s,c,t[2],9,-51403784),c=r(c,l,o,s,t[7],14,1735328473),s=r(s,c,l,o,t[12],20,-1926607734),o=i(o,s,c,l,t[5],4,-378558),l=i(l,o,s,c,t[8],11,-2022574463),c=i(c,l,o,s,t[11],16,1839030562),s=i(s,c,l,o,t[14],23,-35309556),o=i(o,s,c,l,t[1],4,-1530992060),l=i(l,o,s,c,t[4],11,1272893353),c=i(c,l,o,s,t[7],16,-155497632),s=i(s,c,l,o,t[10],23,-1094730640),o=i(o,s,c,l,t[13],4,681279174),l=i(l,o,s,c,t[0],11,-358537222),c=i(c,l,o,s,t[3],16,-722521979),s=i(s,c,l,o,t[6],23,76029189),o=i(o,s,c,l,t[9],4,-640364487),l=i(l,o,s,c,t[12],11,-421815835),c=i(c,l,o,s,t[15],16,530742520),s=i(s,c,l,o,t[2],23,-995338651),o=a(o,s,c,l,t[0],6,-198630844),l=a(l,o,s,c,t[7],10,1126891415),c=a(c,l,o,s,t[14],15,-1416354905),s=a(s,c,l,o,t[5],21,-57434055),o=a(o,s,c,l,t[12],6,1700485571),l=a(l,o,s,c,t[3],10,-1894986606),c=a(c,l,o,s,t[10],15,-1051523),s=a(s,c,l,o,t[1],21,-2054922799),o=a(o,s,c,l,t[8],6,1873313359),l=a(l,o,s,c,t[15],10,-30611744),c=a(c,l,o,s,t[6],15,-1560198380),s=a(s,c,l,o,t[13],21,1309151649),o=a(o,s,c,l,t[4],6,-145523070),l=a(l,o,s,c,t[11],10,-1120210379),c=a(c,l,o,s,t[2],15,718787259),s=a(s,c,l,o,t[9],21,-343485551),e[0]=p(o,e[0]),e[1]=p(s,e[1]),e[2]=p(c,e[2]),e[3]=p(l,e[3])}function t(e,t,n,r,i,a){return t=p(p(t,e),p(r,a)),p(t<<i|t>>>32-i,n)}function n(e,n,r,i,a,o,s){return t(n&r|~n&i,e,n,a,o,s)}function r(e,n,r,i,a,o,s){return t(n&i|r&~i,e,n,a,o,s)}function i(e,n,r,i,a,o,s){return t(n^r^i,e,n,a,o,s)}function a(e,n,r,i,a,o,s){return t(r^(n|~i),e,n,a,o,s)}function o(t){txt="";var n,r=t.length,i=[1732584193,-271733879,-1732584194,271733878];for(n=64;n<=t.length;n+=64)e(i,s(t.substring(n-64,n)));t=t.substring(n-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n<t.length;n++)a[n>>2]|=t.charCodeAt(n)<<(n%4<<3);if(a[n>>2]|=128<<(n%4<<3),n>55)for(e(i,a),n=0;n<16;n++)a[n]=0;return a[14]=8*r,e(i,a),i}function s(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function c(e){for(var t="",n=0;n<4;n++)t+=u[e>>8*n+4&15]+u[e>>8*n&15];return t}function l(e){for(var t=0;t<e.length;t++)e[t]=c(e[t]);return e.join("")}var u="0123456789abcdef".split("");this.md5=function(e){return l(o(e))},this.isMd5=function(e){return/^[a-fA-F0-9]{32}$/.test(e)};var p=function(e,t){return e+t&4294967295};"5d41402abc4b2a76b9719d911017c592"!=this.md5("hello")&&(p=function(e,t){var n=(65535&e)+(65535&t),r=(e>>16)+(t>>16)+(n>>16);return r<<16|65535&n})}),app.factory("$date",["moment",function(e){var t={};return t.collisionDetection=function(t,n,r){if(t=e(t).format("YYYY-MM-DD"),n=n?e(n).format("YYYY-MM-DD"):t,n<t)return null;for(var i=0;i<r.length;i++){var a=e(r[i].dateStart).format("YYYY-MM-DD"),o=a;if(r[i].dateEnd&&(o=e(r[i].dateEnd).format("YYYY-MM-DD")),o>t&&o<=n)return!0;if(a>=t&&a<n)return!0;if(a<=t&&o>=n)return!0;if(a>=t&&o<=n)return!0}return!1},t.extractMinutes=function(e){try{return t.pad(e.getHours())+":"+t.pad(e.getMinutes())}catch(n){return e=new Date(e),t.pad(e.getHours())+":"+t.pad(e.getMinutes())}},t.calculateTimespan=function(t,n){var r;r=n?e(n):e();var i=new Date(t),a=e.duration(r.diff(i));return a.asMinutes().toFixed(2)},t.totalMinutes=function(e){var t=e.split(":");1==t.length&&t.push(0);var n=parseInt(t[0]),r=parseInt(t[1]);return 60*n+r},t.pad=function(e,t){var n=e+"";for(t=t||2;n.length<t;)n="0"+n;return n},t.getTotalMinutes=function(e){var t=e.split(":");if(0===t.length||t.length>2)return null;1==t.length&&t.push(0);var n=parseInt(t[0]);if(n<0||n>23)return null;var r=parseInt(t[1]);return r<0||r>59?null:60*n+r},t.getWeekNumber=function(e){e=new Date(+e),e.setHours(0,0,0),e.setDate(e.getDate()+4-(e.getDay()||7));var t=new Date(e.getFullYear(),0,1),n=Math.ceil(((e-t)/864e5+1)/7);return[e.getFullYear(),n]},t.weeksInYear=function(e){var n,r=11,i=31;do d=new Date(e,r,i--),n=t.getWeekNumber(d)[1];while(1==n);return n},t.getDateOfISOWeek=function(e,t){var n=new Date(t,0,1+7*(e-1)),r=n.getDay(),i=n;return r<=4?i.setDate(n.getDate()-n.getDay()+1):i.setDate(n.getDate()+8-n.getDay()),i},t}]),app.service("$entity",["$http","$q","blockUI","$auth","zapi",function(e,t,n,r,i){function a(e){function t(e,r){if(Object(e)!==e)n[r]=e;else if(Array.isArray(e)){for(var i=0,a=e.length;i<a;i++)t(e[i],r+"["+i+"]");0===a&&(n[r]=[])}else{var o=!0;for(var s in e)o=!1,t(e[s],r?r+"."+s:s);o&&r&&(n[r]={})}}var n={};return t(e,""),n}var o=this;this.get=function(t,n){return n?e.get(i.serverUrl+"/api/"+t+"/list/"+n):e.get(i.serverUrl+"/api/"+t+"/list")},this.getByKey=function(t,n,r,a){var o=i.serverUrl+"/api/"+t+"/fetch",s={params:n};return"function"==typeof a&&(s.transformResponse=a),"function"!=typeof r?e.get(o,s):void e.get(o,s).then(function(e){r(null,e)}).catch(function(e){r(e)})},this.setFormFiles=function(e,t,n){if(t&&"string"!=typeof t)if(t.length)for(var r=0;r<t.length;r++)o.setFormFiles(e,t[r],n+"["+r+"]");else for(var i in t)if("object"==typeof t[i])if("newFile"===i)for(var a in t[i]){var s=n?n+"."+a:a;e.append(s,t[i][a])}else o.setFormFiles(e,t[i],n?n+"."+i:i)},this.add=function(t,n){var r="/api/"+t+"/add/";n._id&&(r+=n._id);var a=new FormData;return"message"!==t&&o.setFormFiles(a,n),a.append("item",angular.toJson(n)),e.post(i.serverUrl+r,a,{transformRequest:angular.identity,headers:{"Content-Type":void 0}})},this.update=function(t,n,r){return e.post(i.serverUrl+"/api/"+t+"/update/"+n,r)},this.getLookups=function(e,n){if(!i.entityMap[e].lookup)return n();if(0===i.entityMap[e].lookup.length)return n();for(var r=[],a=0;a<i.entityMap[e].lookup.length;a++){var s=i.entityMap[e].lookup[a];r.push(o.get(s))}t.all(r).then(function(t){for(var r={},a=0;a<t.length;a++)r[i.entityMap[e].lookup[a]]=t[a].data;n(null,r)},function(e){n(e)})},this.getMany=function(e,n){var r=e,i=[];r.forEach(function(e){i.push(o.get(e))});var a={};t.all(i).then(function(e){e.forEach(function(e,t){a[r[t]]=e.data}),n(null,a)},function(e){n(e)})},this.validate=function(e,t,n){return"function"==typeof i.entityMap[e].service.validate&&i.entityMap[e].service.validate(t,n)},this.remove=function(t,n){var r="_id";"undefined"!=typeof i.entityMap[t].id&&(r=i.entityMap[t].id);var a=i.serverUrl+"/api/"+t+"/remove/"+n[r];return e.get(a)},this.blank=function(e){return"function"!=typeof i.entityMap[e].service.blank?{}:i.entityMap[e].service.blank()},this.flattenArray=function(e,t){var n,r=[],i=[],o=[];return e.forEach(function(e){var t=a(e);for(n in t)i.indexOf(n)===-1&&i.push(n);r.push(t)}),t||o.push(i),r.forEach(function(e){var n;t?n=e:(n=[],i.forEach(function(t){"undefined"==typeof e[t]?n.push(""):n.push(e[t])})),o.push(n)}),o}}]),app.service("ErrorSvc",function(){this.validationArgs=function(e,t){return{disabled:e,tooltip:t}}}),app.service("$graph",["$http","graphOptions","zapi",function(e,t,n){this.get=function(r,i,a,o,s,c,l,u,p){var d={query:a,obj:o,seriesKey:s,dataKey:c,labelsKey:l};"undefined"==typeof p&&(p="mongo"),e.post(n.serverUrl+"/api/graph/auto/"+r+"/"+i+"/"+p,d).then(function(e){e.data.options=angular.copy(t),e.data.series.length>0&&(e.data.options.legend={display:!0}),u(e.data)}).catch(function(e){swal("Atenção",e.data,"warning"),u()})},this.custom=function(r,i,a){var o="sql"===r?"sql":"mongo";e.get(n.serverUrl+"/api/graph/custom/"+r+"/"+i+"/"+o,{cache:!0}).then(function(e){e.data.options=angular.copy(t),"undefined"!=typeof e.data.series&&e.data.series.length>0&&(e.data.options.legend={display:!0}),a(e.data)}).catch(function(e){swal("Atenção",e.data,"warning"),a()})}}]),app.service("$holiday",function(){function calculateNextOccurrence(holiday){var date,currentYear=(new Date).getFullYear();switch(holiday.format){case"static":var day=holiday.date.split("/")[0],month=holiday.date.split("/")[1];date=new Date(currentYear+"/"+month+"/"+day),new Date>=date&&(date=new Date(currentYear+1+"/"+month+"/"+day));break;case"dynamic":if(eval("my_function = "+holiday.formula),"function"!=typeof my_function)return;date=my_function(currentYear),date<new Date&&(date=my_function(currentYear+1))}return date}this.getDayHolidays=function(e,t){for(var n=[],r=0;r<e.length;r++)this.dayMatch(e[r].holiday,t)&&n.push(e[r].holiday);return n},this.dayMatch=function(e,t){t instanceof Date||(t=new Date(t));var n=t.getDate(),r=t.getMonth()+1,i=calculateNextOccurrence(e);return n===i.getDate()&&r===i.getMonth()+1},this.calculateNextOccurrence=function(e){return moment(calculateNextOccurrence(e)).format("YYYY-MM-DD")}}),app.service("$license",["$rootScope","$modal","$uibModalStack","$location","$timeout",function(e,t,n,r,i){function a(){n.dismissAll(),r.path("/profile")}this.isLicensed=function(t){return"undefined"==typeof t||!!e.login&&(!!e.login.license&&(e.login.license.modules instanceof Array&&(e.login.license.modules.find(function(e){return t===e})||!1)))},this.notify=function(e){"undefined"!=typeof e&&i(function(){t.open("unlicensed","md",{moduleId:e},a,a)})}}]),app.service("$list",["$http","blockUI","mySocket","zapi",function(e,t,n,r){this.getMetadata=function(n){t.start("A obter listagens disponíveis..."),e.get(r.serverUrl+"/api/list/getall").then(function(e){e.data.forEach(function(e){e.values={}}),n(e.data)}).catch(function(e){console.log(e),swal("Atenção","Não foi possível obter as listagens disponíveis, por favor actualize a página","warning"),n([])}).finally(function(){t.stop()})},this.get=function(i,a,o,s){return 0===a.length?swal("Atenção","Selecione pelo menos uma exploração","warning"):(t.start("A obter listagem..."),void e.get(r.serverUrl+"/api/list/values/"+i.name,{params:{query:i.values,dbs:a}}).then(function(e){n.on(o,function(e){"undefined"!=typeof e.ok?(t.stop(),s(e.ok)):"undefined"!=typeof e.error?(t.stop(),swal("Ocorreu um erro",e.error,"error"),s([])):"undefined"!=typeof e.message&&t.message(e.message)})}).catch(function(e){swal("Atenção",e.data,"warning"),t.stop()}))}}]),app.service("$measure",["$http","zapi",function(e,t){this.getByType=function(n){return e.get(t.serverUrl+"/api/unit/measure/"+n)}}]),app.service("$modal",["zapiPath","$uibModal",function(e,t){this.open=function(e,n,r,i,a){var o=t.open({animation:!0,templateUrl:"./modal/"+e+"/"+e+".html",controller:e+"Ctrl",size:n,backdrop:"static",resolve:{data:function(){return r}}});i=i||function(){},a=a||function(){},o.result.then(i,a)},this._open=function(n,r,i,a,o){var s=t.open({animation:!0,templateUrl:e+"/modal/"+n+"/"+n+".html",controller:n+"Ctrl",size:r,backdrop:"static",resolve:{data:function(){return i}}});a=a||function(){},o=o||function(){},s.result.then(a,o)}}]),app.service("$newsletter",["$entity","blockUI",function(e,t){this.subscribe=function(n){n&&(t.start("A gravar email..."),e.add("newsletter",n).then(function(e){swal("Newsletter","Email gravado com sucesso","success")}).catch(function(e){swal("Newsletter","Não foi possível registar o seu email de momento por favor tente novamente","warning")}).finally(function(){callback(),t.stop()}))}}]),app.factory("$page",["projectTitle",function(e){var t=" - "+e,n="";return{title:function(){return n+t},setTitle:function(e){n=e}}}]),app.service("$report",["$http","blockUI","$httpParamSerializer","zapi",function(e,t,n,r){this.getMetadata=function(n,i){t.start("A obter meta dados..."),e.get(r.serverUrl+"/api/report/metadata/"+n).then(function(e){i(null,e.data)}).catch(function(e){i(e.data)}).finally(function(){t.stop()})},this.getReport=function(i,a,o){t.start("A obter dados..."),e.get(r.serverUrl+"/api/report/get/"+i+"?"+n(a)).then(function(e){o(null,e.data)}).catch(function(e){o(e.data)}).finally(function(){t.stop()})}}]),app.service("$role",["$http","zapi",function(e,t){this.getPermissions=function(){return e.get(t.serverUrl+"/api/role/permissions")}}]),app.service("$task",["$http","blockUI","$route","zapi",function(e,t,n,r){this.toggleState=function(i){t.start("A executar..."),e.get(r.serverUrl+"/api/task/toggle/"+i._id).then(function(e){n.reload()}).catch(function(e){swal("Tarefas","Ocorreu um erro ao alternar o estado da tarefa. Erro: "+e.data,"error")}).finally(function(){t.stop()})},this.run=function(t){return e.get(r.serverUrl+"/api/task/run/"+t._id)},this.getTypes=function(n){t.start("A obter dados..."),e.get(r.serverUrl+"/api/task/types").then(function(e){n(e.data)}).catch(function(e){swal("Tarefas","Não foi possível atualizar a lista de tarefas neste momento. Tente novamente. Erro: "+e.data,"error"),n([])}).finally(function(){t.stop()})}}]),app.service("$validate",function(){function e(e){switch(e){case"0":return 0;case"1":return 1;case"2":return 2;case"3":return 3;case"4":return 4;case"5":return 5;case"6":return 6;case"7":return 7;case"8":return 8;case"9":return 9;case"A":return 10;case"B":return 11;case"C":return 12;case"D":return 13;case"E":return 14;case"F":return 15;case"G":return 16;case"H":return 17;case"I":return 18;case"J":return 19;case"K":return 20;case"L":return 21;case"M":return 22;case"N":return 23;case"O":return 24;case"P":return 25;case"Q":return 26;case"R":return 27;case"S":return 28;case"T":return 29;case"U":return 30;case"V":return 31;case"W":return 32;case"X":return 33;case"Y":return 34;case"Z":return 35;default:return-1}}function t(e){return!!e&&("string"==typeof e||e instanceof String)}this.nif=function(e){if(!t(e))return!1;var n=new RegExp("[1,2,5,6,7,8,9]\\d{8}");if(!e.match(n))return!1;var r=0;for(i=0;i<8;i++)r+=parseInt(e[i])*(9-i);var a=11-r%11;return a>=10&&(a=0),a===parseInt(e[8])},this.niss=function(e){if(!t(e))return!1;if(e=e.replace(/\s+/g,""),11!==e.length)return!1;for(var n=[29,23,19,17,13,11,7,5,3,2],r=0,i=0;i<e.length-1;i++)r+=parseInt(e[i]*n[i]);r=9-parseInt(r%10);var a=parseInt(e[e.length-1]);return r===a},this.cc=function(n){if(!t(n))return!1;var r=0,i=!1;if(12!==n.length)return!1;for(var a=n.length-1;a>=0;--a){var o=e(n[a]);if(o===-1)return!1;i&&(o*=2,o>9&&(o-=9)),r+=o,i=!i}return r%10===0},this.nib=function(e){if(!t(e))return!1;var n=new RegExp("^\\d{21}$");if(!e.match(n))return!1;for(var r=0,i=0;i<19;i++)r+=parseInt(e[i]),r*=10,r%=97;return r=98-10*r%97,parseInt(e.substring(19,21))===r}}),app.factory("mySocket",["zapi","socketFactory",function(e,t){if("undefined"==typeof e.websocketUrl)return t();var n=io.connect(e.websocketUrl);return t({ioSocket:n});
}]),app.controller("attachmentsCtrl",function(){}),app.controller("ccCtrl",function(){}),app.controller("fromCtrl",function(){}),app.controller("toCtrl",function(){}),app.directive("zlActivation",["zapiPath",function(e){return{restrict:"E",scope:{zlClass:"@?",onComplete:"&?"},replace:!1,templateUrl:e+"/directives/activation/activation.html",controller:["$scope","$auth","$location","$routeParams",function(e,t,n,r){e.user=null,"undefined"==typeof e.zlClass&&(e.zlClass="form-control input-lg"),t.activateAccount(r.code,function(t,n){return t?swal("Atenção",t,"warning"):void(e.user=n)}),e.changePassword=function(r){t.changePassword(e.user,r.password,r.repeat,function(t){return"function"==typeof e.onComplete()?e.onComplete()(t,e.user):t?swal("Atenção",t,"warning"):void n.path("/")})}}]}}]),app.directive("zlAddress",["zapiPath",function(e){return{restrict:"E",scope:{item:"=",countries:"=",zlClass:"@?",disable:"=?",countryValue:"@?"},replace:!1,templateUrl:e+"/directives/address/address.html",controller:["$scope","$address",function(e,t){e.disable=e.disable||!1,e.zlClass=e.zlClass||"form-control",e.getAddressPT=function(n){t.getAddressPT(n,function(r,i){return r?(e.item.addressDetails=void 0,e.item.address=void 0,e.item.city=void 0,e.item.locality=void 0,e.item.county=void 0,e.item.country=void 0,swal("Atenção","Não foi possível completar o arruamento","warning")):(e.item.address=i.address,e.item.city=i.city,e.item.locality=i.locality,e.item.county=i.county,e.item.country=e.countryValue?i.country[e.countryValue]:i.country,void t.getCoordinates(n,function(t,n){t||(e.item.coords=n)}))})},e.validateZipcode=t.validateZipcode}]}}]),app.directive("apiMenuItem",["zapiPath",function(e){return{restrict:"E",scope:!1,replace:!0,templateUrl:e+"/directives/apiMenuItem/apiMenuItem.html"}}]),app.directive("zlCalendar",["zapiPath",function(e){return{restrict:"E",scope:{calendarView:"=?",calendarTitle:"@"},replace:!1,templateUrl:e+"/directives/calendar/calendar.html",controller:["$scope","$calendar",function(e,t){e.calendarView=e.calendarView||"month",e.viewDate=new Date,e.isCellOpen=!0,e.eventTypes=t.getEventTypes(),e.events=t.getEvents(),e.toggleEventType=function(n){e.eventTypes=t.toggleEventType(n),e.events=t.getEvents()},e.toggle=function(e,t,n){e.preventDefault(),e.stopPropagation(),n[t]=!n[t]},e.groupEvents=function(e){e.groups={},e.events.forEach(function(t){e.groups[t.type]=e.groups[t.type]||[],e.groups[t.type].push(t)})}}]}}]),app.directive("zlChangePassword",["zapiPath",function(e){return{restrict:"E",scope:{zlClass:"@?"},replace:!1,templateUrl:e+"/directives/changePassword/changePassword.html",controller:["$scope","$auth","$rootScope",function(e,t,n){"undefined"==typeof e.zlClass&&(e.zlClass="form-control input-lg"),e.changePassword=function(e){t.changePassword(n.login,e.password,e.repeat,function(e){return e?swal("Atenção",e,"warning"):void t.logout()})}}]}}]),app.directive("console",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,templateUrl:e+"/directives/console/console.html"}}]),app.directive("zlContainer",["zapiPath",function(e){return{restrict:"E",replace:!1,templateUrl:e+"/directives/container/container.html",scope:{entity:"@",item:"=",lookup:"=",label:"@",var:"@",key:"@",isVisible:"&?",isMovable:"@",noInsert:"@",removable:"@",api:"@?",approvalMaxLevel:"@"},controller:["$scope","$rootScope","$controller","$timeout",function(t,n,r,i){function a(e,r){var i,a;if(t.item[t.var]||(t.item[t.var]=[]),t.key){var o={property:null,key:null};if(e[t.key])o.key=e[t.key];else for(a in e)if(e[a][t.key]){o.property=a,o.key=e[a][t.key];break}if(o.key)for(i=0;i<t.item[t.var].length;i++){var s=o.property?t.item[t.var][i][o.property]:t.item[t.var][i];if(s[t.key]===o.key)return r("Registo duplicado em "+t.label)}}else for(i=0;i<t.item[t.var].length;i++)if(t.item[t.var][i]===e)return r("Registo duplicado em "+t.label);t.item[t.var].unshift(e),t.approvalMaxLevel&&t.approvalMaxLevel&&(e.approval={level:n.login.role.approvalLevel,maxLevel:t.approvalMaxLevel}),r()}t.zapiPath=e,t.key?t.newContainerItem={}:t.newContainerItem="",t.append=function(e){a(e,function(e){return e?swal("Atenção",e,"warning"):void(t.key?t.newContainerItem={}:t.newContainerItem="")})},t.remove=function(e){var n=t.item[t.var].indexOf(e);n!=-1&&t.item[t.var].splice(n,1)},t.validate=function(e){if(!e)return!0;if(t.key&&0===Object.keys(e).length&&JSON.stringify(e)===JSON.stringify({}))return!0;if("function"==typeof t.getError){var n=t.getError(e,t.item[t.var]);if(n.disabled)return t.console=n.tooltip,!0}return t.console=null,!1},t.pushBack=function(e){var n=t.item[t.var].splice(e,1);t.item[t.var].splice(e-1,0,n[0])},t.pushForward=function(e){var n=t.item[t.var].splice(e,1);t.item[t.var].splice(e+1,0,n[0])},i(function(){r(t.var+"Ctrl",{$scope:t})})}]}}]),app.directive("contenteditable",function(){return{require:"ngModel",link:function(e,t,n,r){function i(){r.$setViewValue(t.html())}r.$render=function(){t.html(r.$viewValue||"")},t.bind("blur keyup change",function(){e.$apply(i)})}}}),app.directive("zlCountry",["zapiPath",function(e){return{restrict:"E",scope:{item:"=",var:"@",label:"@",lookup:"=",disable:"=?",valueAttr:"@?"},replace:!1,templateUrl:e+"/directives/country/country.html",controller:["$scope",function(e){e.disable=e.disable||!1}]}}]),app.directive("zlFile",["zapiPath",function(e){return{restrict:"A",scope:{item:"=",var:"=",docid:"="},replace:!1,link:function(e,t,n){e.docid&&e.docid._id&&(e.docid=e.docid._id)},templateUrl:e+"/directives/document/file.html"}}]),app.directive("fileModel",["$parse",function(e){return{restrict:"A",replace:!1,link:function(t,n,r){var i=e(r.fileModel),a=i.assign;n.bind("change",function(){t.$apply(function(){a(t,n[0].files[0])})})}}}]),app.directive("entityEdit",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,link:function(t,n,r){var i=t.entity.custom?"entity/":e+"/entity/";t.contentUrl=i+t.entityName+"/"+t.entityName+".edit.html"},template:'<div ng-include="contentUrl"></div>'}}]),app.directive("entityList",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,link:function(t,n,r){var i=t.entity.custom?"entity/":e+"/entity/";t.contentUrl=i+t.entityName+"/"+t.entityName+".list.html"},template:'<div ng-include src="contentUrl" include-replace></div>'}}]),app.directive("entityView",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,link:function(t,n,r){var i=t.entity.custom?"entity/":e+"entity/";t.contentUrl=i+t.entityName+"/"+t.entityName+".view.html"},template:'<div ng-include="contentUrl"></div>'}}]),app.directive("zlDynamicField",["zapiPath",function(e){return{restrict:"E",scope:{field:"=",model:"=",key:"@",zlClass:"@?"},replace:!1,template:'<div ng-include src="contentUrl" include-replace></div>',controller:["$scope",function(t){function n(n){if(n){var r=t.field.type||"Unknown";"ObjectId"===t.field.type&&"undefined"==typeof t.field.ref&&(r="String"),t.contentUrl=e+"/directives/dynamicField/"+r+".html"}}"undefined"==typeof t.zlClass&&(t.zlClass="form-control input-lg"),t.$watch("field.type",n)}]}}]),app.directive("zlGraph",["zapiPath",function(e){return{restrict:"E",scope:{item:"=",custom:"@?"},replace:!1,templateUrl:e+"/directives/graph/graph.html",controller:["$scope","blockUI","$graph","chartTypes",function(e,t,n,r){function i(){if(o.start("A criar gráfico..."),"string"==typeof e.custom){var t=e.custom.split("|");n.custom(t[0],t[1],a)}else n.get(e.item.namespace,e.item.collection,e.item.query,e.item.obj,e.item.seriesKey,e.item.dataKey,e.item.labelsKey,a,e.item.driver)}function a(t){e.chart=t,o.stop()}var o=t.instances.get("graphBlockUI");e.chart={},i(),e.getNext=function(){var t=r[e.item.dimension].indexOf(e.item.type)+1;return r[e.item.dimension][t===r[e.item.dimension].length?0:t]},e.toggle=function(){e.item.type=e.getNext()}}]}}]),app.directive("zlIdle",function(){return{restrict:"A",scope:!0,controller:["$scope","$location","$auth",function(e,t,n){e.$on("IdleStart",function(){swal("Atenção","Devido à sua inactividade irá ser disconectado em 5 segundos","info")}),e.$on("IdleEnd",function(){console.log("IdleEnd")}),e.$on("IdleTimeout",function(){n.logout(),t.path("/")})}]}}),app.directive("ngClick",["$license",function(e){function t(t,n){t.bind("click",function(t){t.preventDefault(),e.notify(n)})}return{restrict:"A",replace:!1,link:function(n,r,i){if("undefined"!=typeof i.license){var a=e.isLicensed(i.license);return a?void 0:t(r,i.license)}}}}]),app.directive("zlList",["zapiPath",function(e){return{restrict:"E",scope:{dbs:"=",channel:"@"},replace:!1,templateUrl:e+"/directives/list/list.html",controller:["$scope","$list","NgTableParams","$httpParamSerializer","$timeout",function(e,t,n,r,i){function a(){i(function(){1===e.dbs.length&&e.selectedDbs.push(e.dbs[0]),t.getMetadata(function(t){e.lists=t})})}e.items=[],e.tableParams=null,e.list={name:"",parameters:[],values:{}},e.selectedDbs=[],a(),e.reset=function(){e.items=[],e.tableParams=null},e.get=function(r){t.get(r,e.selectedDbs,e.channel,function(t){var i={},a={dataset:t};r.group&&(i.group=r.group),"undefined"!=typeof r.groupOptions&&(a.groupOptions=r.groupOptions),e.items=t,e.tableParams=new n(i,a)})},e.getExcelUrl=function(t){return"/api/list/values/"+t.name+"?xls=1&"+r({query:t.values,dbs:e.selectedDbs})},e.applySearch=function(t){var n=angular.copy(t.text);t.inverted&&(n="!"+n),e.tableParams.filter({$:n})}}]}}]),app.directive("zlLogin",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,templateUrl:e+"/directives/login/login.html",controller:["blockUI","$auth","$location","$scope","$uibModalStack",function(e,t,n,r,i){function a(){r.username="",r.password=""}r.login=function(){r.validateLogin()||t.login(r.username,r.password,function(e){e?a():(n.path("/profile"),i.dismissAll())})},r.validateLogin=function(){return!r.username||!r.password}}]}}]),app.directive("zlMaintenance",function(){return{restrict:"A",scope:!0,controller:["mySocket","$timeout",function(e,t){e.on("maintenance",function(e){swal("Manutenção Programada",e,"info")})}]}}),app.directive("zlNewsletter",["zapiPath",function(e){return{restrict:"E",scope:!0,replace:!1,templateUrl:e+"/directives/newsletter/newsletter.html",controller:["$scope","$newsletter",function(e,t){e.saveEmail=function(n){t.subscribe(n,function(){e.newsItem={}})}}]}}]),app.directive("asDate",function(){return{require:"^ngModel",restrict:"A",link:function(e,t,n,r){r.$formatters.splice(0,r.$formatters.length),r.$parsers.splice(0,r.$parsers.length),r.$formatters.push(function(e){if(e)return new Date(e).toISOString().slice(0,10)}),r.$parsers.push(function(e){return e})}}}),app.directive("dlKeyCode",dlKeyCode),app.directive("asFloat",function(){return{require:"^ngModel",restrict:"A",link:function(e,t,n,r){r.$formatters.splice(0,r.$formatters.length),r.$parsers.splice(0,r.$parsers.length),r.$formatters.push(function(e){if(e)return parseFloat(e)}),r.$parsers.push(function(e){return e})}}}),app.directive("asInteger",function(){return{require:"^ngModel",restrict:"A",link:function(e,t,n,r){r.$formatters.splice(0,r.$formatters.length),r.$parsers.splice(0,r.$parsers.length),r.$formatters.push(function(e){if(e)return parseInt(e)}),r.$parsers.push(function(e){return e})}}}),app.directive("lettersOnly",function(){return{require:"ngModel",link:function(e,t,n,r){function i(e){if(e){var t=e.replace(/[^A-Za-z]/g,"");return t!==e&&(r.$setViewValue(t),r.$render()),t}}"true"===n.lettersOnly&&r.$parsers.push(i)}}}),app.directive("numbersOnly",function(){return{require:"ngModel",link:function(e,t,n,r){function i(e){if(e){var t=e.replace(/[^0-9]/g,"");return t!==e&&(r.$setViewValue(t),r.$render()),t}}"true"===n.numbersOnly&&r.$parsers.push(i)}}}),app.directive("zlQueryBuilder",["zapiPath",function(e){return{restrict:"E",scope:{field:"=",model:"=",key:"@",zlClass:"@?"},replace:!1,template:'<div ng-include src="contentUrl" include-replace></div>',controller:["$scope",function(t){function n(n){if(n){var r=t.field.type||"Unknown";"ObjectId"===t.field.type&&"undefined"==typeof t.field.ref&&(r="String"),t.contentUrl=e+"/directives/queryBuilder/"+r+".html"}}"undefined"==typeof t.zlClass&&(t.zlClass="form-control input-lg"),t.$watch("field.type",n)}]}}]),app.directive("zlReport",["zapiPath",function(e){return{restrict:"E",scope:{reportKey:"@"},replace:!1,templateUrl:e+"/directives/report/report.html",controller:["$scope","NgTableParams","$entity","moment","$report","$httpParamSerializer","blockUI","$route",function(e,t,n,r,i,a,o,s){function c(){e.tableParams=null,e.cols=[],e.item={select:[],query:[],sort:{}}}function l(){i.getMetadata(e.reportKey,function(t,n){return t?swal("Atenção",t,"error"):void(e.fields=n.fields)}),o.start("A obter listagens guardadas..."),n.getByKey("report",{key:e.reportKey}).then(function(t){e.savedItems=t.data}).catch(function(e){swal("Atenção",e.data,"error")}).finally(function(){o.stop()})}e.savedItems=[],e.fields=[],e.activeTab=0,c(),l(),e.reset=c,e.appendQuery=function(){e.item.query.push({})},e.removeQuery=function(t){e.item.query.splice(t,1)},e.getReport=function(a){var o={};e.cols=[],a.select.forEach(function(t){var n=e.fields.find(function(e){return e.id==t}),r="undefined"==typeof n.name?n.invoke:n.name;"Date"===n.type&&(o[r]=!0),e.cols.push({field:r,title:n.caption,sortable:"'"+r+"'",show:!0})}),i.getReport(e.reportKey,a,function(i,a){if(i)return swal("Ocorreu um problema",a,"error");var s=n.flattenArray(a,!0);s.forEach(function(e){for(var t in e)o[t]&&(e[t]=r(e[t]).format("YYYY-MM-DD"))}),e.items=s,e.tableParams=new t({},{dataset:s})})},e.loadReport=function(t,n){e.item=t,e.activeTab=n},e.saveReport=function(t){t.key=e.reportKey,o.start("A guardar listagem..."),n.add("report",t).then(function(e){swal("Guardado","A listagem foi guardada com sucesso. Poderá reutiliza-la no futuro a partir do separador 'Restaurar'","success"),s.reload()}).catch(function(e){swal("Atenção",e.data,"warning")}).finally(function(){o.stop()})},e.getExcelUrl=function(t){return"/api/report/get/"+e.reportKey+"?xls=1&"+a(t)},e.applySearch=function(t){var n=angular.copy(t.text);t.inverted&&(n="!"+n),e.tableParams.filter({$:n})}}]}}]),app.directive("zlReset",["zapiPath",function(e){return{restrict:"E",scope:{item:"=",zlClass:"@?"},replace:!1,templateUrl:e+"/directives/reset/reset.html",controller:["$scope","$auth","$location","blockUI",function(e,t,n,r){"undefined"==typeof e.zlClass&&(e.zlClass="form-control input-lg"),e.reset=function(r){e.validateReset(r)||t.resetPassword(r.email,r.username,function(e){return e?swal("Atenção",e,"warning"):void n.path("/")})},e.validateReset=function(e){return!e||(!e.email||!e.username)}}]}}]),app.directive("zlSignup",["zapiPath",function(e){return{restrict:"E",scope:{item:"=",zlClass:"@?",onComplete:"&?"},replace:!1,templateUrl:e+"/directives/signup/signup.html",controller:["$scope","blockUI","$entity","$uibModalStack",function(e,t,n,r){"undefined"==typeof e.zlClass&&(e.zlClass="form-control input-lg"),e.signup=function(i){e.validateSignup(i)||(t.start("A reservar conta..."),n.add("user",i).then(function(t){return"function"==typeof e.onComplete()?e.onComplete()():(swal("Está quase!","Consulte o seu email para ativar a conta de utilizador","success"),void r.dismissAll())}).catch(function(e){swal("Erro",e.data,"error")}).finally(function(){t.stop()}))},e.validateSignup=function(e){if(!e)return!0;if(!e.username)return!0;var t=new RegExp("^[a-zA-Z0-9.-_$@*!]{3,30}$");return!t.test(e.username)||!e.email}}]}}]),app.controller("activityCtrl",["$scope",function(e){}]),app.controller("alertCtrl",function(){}),app.controller("countryCtrl",["$scope",function(e){}]),app.controller("errorCtrl",["$scope","$modal",function(e,t){e.openModal=t._open}]),app.controller("holidayCtrl",["ErrorSvc","$scope","$holiday",function(ErrorSvc,$scope,$holiday){$scope.getError=function(holiday,holidays){if($scope.nextOccurrence=null,!holiday)return ErrorSvc.validationArgs(!0);if(!holiday.name)return ErrorSvc.validationArgs(!0,"Introduza um nome do feriado");if(""===holiday.name.trim())return ErrorSvc.validationArgs(!0,"Introduza um nome do feriado");for(var i=0;i<holidays.length;i++)if(holidays[i].name==holiday.name&&holiday._id!=holidays[i]._id)return ErrorSvc.validationArgs(!0,"Feriado já existente");if(!holiday.date&&!holiday.formula)return ErrorSvc.validationArgs(!0,"Impossivel calcular próxima ocorrência para este feriado");if(holiday.date){var pattern=/^(?:(?:[12][0-9]|0[1-9])\/(02)|(?:30|[12][0-9]|0[1-9])\/(?:(?:0[469]|11))|(?:3[01]|[12][0-9]|0[1-9])\/(?:(?:0[13578]|1[02])))$/;if(!pattern.test(holiday.date))return ErrorSvc.validationArgs(!0,"A data deve ser no formato dd/mm")}else if(holiday.formula)try{var currentYear=(new Date).getFullYear();eval("my_function = "+holiday.formula);var d=my_function(currentYear);if("[object Date]"!==Object.prototype.toString.call(d))return ErrorSvc.validationArgs(!0,"Data inválida");if(isNaN(d.getTime()))return ErrorSvc.validationArgs(!0,"Data inválida")}catch(e){return ErrorSvc.validationArgs(!0,"A formula que introduziu contém um erro: "+e)}return ErrorSvc.validationArgs(!1)},$scope.items.forEach(function(e){e.next=$holiday.calculateNextOccurrence(e)})}]),app.controller("maintenanceCtrl",function(){}),app.controller("messageCtrl",["$scope","$modal",function(e,t){e.openModal=t._open}]),app.controller("roleCtrl",["ErrorSvc","$scope","$role",function(e,t,n){t.permissions={},n.getPermissions().then(function(e){t.permissions=e.data}),t.togglePermissions=function(e){t.item.permissions||(t.item.permissions={});for(var n in t.permissions){t.item.permissions[n]||(t.item.permissions[n]={});for(var r in t.permissions[n])"label"!==r&&(t.item.permissions[n][r]=e)}},t.getError=function(t,n){if(!t)return e.validationArgs(!0);if(!t.name)return e.validationArgs(!0,"Introduza um nome para o perfil de utilizador");if(""===t.name.trim())return e.validationArgs(!0,"Introduza um nome para o perfil de utilizador");for(var r=0;r<n.length;r++)if(n[r].name==t.name&&n[r]._id!=t._id)return e.validationArgs(!0,"Perfil de utilizad