forked from Catalysts/cat-angular-bower
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat-angular.min.js
3 lines (3 loc) · 51.3 KB
/
cat-angular.min.js
1
2
3
function CatBaseDetailController($scope,$stateParams,$location,$window,$globalMessages,$controller,$log,catBreadcrumbsService,config){$scope.detail=config.detail,$scope.editDetail=void 0,$scope.$fieldErrors={};var endpoint=config.endpoint,baseUrl=config.baseUrl,templateUrls=config.templateUrls,Model=config.Model;$scope.uiStack=catBreadcrumbsService.generateFromConfig(config),catBreadcrumbsService.push("new"===$stateParams.id?{title:"New",key:"cc.catalysts.general.new"}:{}),$scope.editTemplate=templateUrls.edit,_.isObject(templateUrls.view)?($scope.mainViewTemplate=templateUrls.view.main,$scope.additionalViewTemplate=templateUrls.view.additional):$scope.mainViewTemplate=templateUrls.view,$scope.baseUrl=baseUrl,$scope.title=function(){var data=$scope.detail;return _.isUndefined(data)?"":data.breadcrumbTitle?data.breadcrumbTitle():data.name?data.name:data.id};var update=function(){catBreadcrumbsService.replaceLast({title:$scope.title()})};$scope.reloadDetails=function(){endpoint.get($stateParams.id).then(function(data){$scope.detail=data,update()})},$scope.exists=!!$stateParams.id&&"new"!==$stateParams.id,$scope.add=function(){$scope.editDetail=new Model,_.isFunction($scope.editDetail.setParent)&&$scope.editDetail.setParent(config.parents[0])},$scope.edit=function(){$scope.editDetail=angular.copy($scope.detail),_.isFunction($scope.editDetail.setParent)&&$scope.editDetail.setParent(config.parents[0])},$scope.cancelEdit=function(){$scope.$broadcast("formReset"),$scope.exists?($scope.editDetail=void 0,$globalMessages.clearMessages(),$scope.$fieldErrors=void 0):$window.history.back()},$scope.remove=function(){endpoint.remove($scope.detail.id).then(function(){if(_.isEmpty($scope.uiStack))$location.path(baseUrl);else{var parentUrl=$scope.uiStack[$scope.uiStack.length-1].url;$location.path(parentUrl.substring(1,parentUrl.indexOf("?"))),$location.search("tab",endpoint.getEndpointName())}})},$scope.save=function(){endpoint.save($scope.editDetail).then(function(data){$globalMessages.clearMessages(),$scope.$fieldErrors=void 0,$scope.exists?($scope.editDetail=void 0,$scope.detail=data,update()):($scope.$broadcast("formReset"),$location.path(baseUrl+"/"+data.id))},function(response){if(!response.data.fieldErrors)return void($scope.$fieldErrors=void 0);var fieldErrors={};_.forEach(response.data.fieldErrors,function(fieldError){fieldErrors[fieldError.field]=fieldErrors[fieldError.field]||[],fieldErrors[fieldError.field].push(fieldError.message)}),$scope.$fieldErrors=fieldErrors,$scope.$broadcast("fieldErrors",fieldErrors)})},$scope.baseTabsController=["$scope",function($tabsScope){$controller("CatBaseTabsController",{$scope:$tabsScope,config:config})}];try{$controller(config.controller,{$scope:$scope,detail:config.detail,parents:config.parents,config:config})}catch(unused){$log.info("Couldn't instantiate controller with name "+config.controller)}$scope.exists?update():$scope.edit()}function CatBaseListController($scope,$controller,$log,catBreadcrumbsService,config){_.isUndefined(config.listData)?$log.warn("No listData available!"):(this.titleKey="cc.catalysts.cat-breadcrumbs.entry."+config.listData.endpoint.getEndpointName(),catBreadcrumbsService.set([{title:config.title,key:this.titleKey}]),$scope.listData=config.listData),this.title=config.title,this.searchProps=config.searchProps,this.config=config,this.getUrlForId=function(id){return"#"+config.baseUrl+"/"+id},this.getUrlForNewPage=function(){return this.getUrlForId("new")};try{$controller(config.controller,{$scope:$scope,listData:config.listData,config:config})}catch(unused){$log.info("Couldn't instantiate controller with name "+config.controller)}}function CatBaseTabsController($scope,$controller,$stateParams,$location,config){var endpoint=config.endpoint;$scope.tabs=config.tabs,$scope.tabNames=_.map(config.tabs,"name"),$scope.activeTab={},$scope.activateTab=function(tab){$scope.$broadcast("tab-"+tab+"-active"),_.forEach($scope.tabs,function(currentTab){$scope.activeTab[currentTab.name]=!1}),$scope.activeTab[tab]=!0},$scope.selectTab=function(tabName){_.isUndefined($location.search().tab)&&tabName===$scope.tabNames[0]||$location.search("tab",tabName)};var isTabActive=function(tab){return tab.name===$scope.tabNames[0]&&_.isUndefined($stateParams.tab)?!0:$stateParams.tab===tab.name};$scope.$watchCollection(function(){return $location.search()},function(newValue){_.isString(newValue.tab)?$scope.activateTab(newValue.tab):_.isUndefined(newValue.tab)&&$scope.activateTab($scope.tabNames[0])}),$scope.getTabName=function(tab){return window.cat.util.pluralize(window.cat.util.capitalize(tab))},_.forEach($scope.tabs,function(tab){$scope.activeTab[tab.name]=isTabActive(tab)});for(var parentUrl=endpoint.getEndpointName(),parentTemplateNamePrefix=endpoint.getEndpointName(),currentEndpoint=endpoint;!_.isUndefined(currentEndpoint.parentEndpoint);){currentEndpoint=endpoint.parentEndpoint;var parentEndpointName=currentEndpoint.getEndpointName();parentUrl=parentEndpointName+"/"+parentUrl,parentTemplateNamePrefix=parentEndpointName+"-"+parentTemplateNamePrefix}$scope.getTabTemplate=function(tab){return parentUrl+"/"+tab+"/"+parentTemplateNamePrefix+"-"+tab+"-list.tpl.html"};var _getDefaultTabControllerName=function(tab){return window.cat.util.capitalize(endpoint.getEndpointName())+window.cat.util.capitalize(tab.name)+"Controller"},_getTabControllerName=function(tab){return tab.controller?tab.controller:_getDefaultTabControllerName(tab)},tabIndex=0;$scope.tabController=["$scope","catListDataLoadingService",function($tabScope,catListDataLoadingService){var activeTab=$scope.tabs[tabIndex++],tabControllerName=_getTabControllerName(activeTab);$tabScope.getSearchRequest=function(){return new window.cat.SearchRequest},$tabScope.getEndpoint=function(){return config.detail[activeTab.name]},$tabScope.loadListData=function(){catListDataLoadingService.load($tabScope.getEndpoint(),$tabScope.getSearchRequest()).then(function(data){$tabScope.listData=data})},$tabScope.$on("tab-"+activeTab.name+"-active",function(){_.isUndefined($scope.listData)&&$tabScope.loadListData()}),$controller(tabControllerName,{$scope:$tabScope,detail:config.detail,parents:config.parents,config:config}),$scope.activeTab[activeTab.name]===!0&&$scope.activateTab(activeTab.name)}]}function CatSelectLink(scope,element){element.addClass("form-control")}function CatSelectController($scope,$log,catApiService,catSelectConfigService){var options=catSelectConfigService.getConfig($scope.config,$scope.options);if(_.isUndefined(options))throw new Error('At least one of "config" or "options" has to be specified');var transport,quietMillis,searchRequestFunc=options.search||function(term,page){return{"search.name":term,page:page}},filterFunc=options.filter||function(){return!0};if(_.isArray(options.endpoint))transport=function(queryParams){return queryParams.success({elements:options.endpoint})},quietMillis=0;else if(_.isFunction(options.endpoint))transport=options.endpoint,quietMillis=500;else if(_.isObject(options.endpoint))transport=fetchElements(options.endpoint,options.sort),quietMillis=500;else{if(!_.isString(options.endpoint))return $log.error("The given endpoint has to be one of the following types: array, object, string or function - but was "+typeof options.endpoint),void($scope.elements=[]);var api=catApiService[options.endpoint];if(!api)return $log.error('No api endpoint "'+options.endpoint+'" defined'),void($scope.elements=[]);transport=fetchElements(api,options.sort),quietMillis=500}$scope.selectOptions=_.assign({placeholder:" ",minimumInputLength:0,adaptDropdownCssClass:function(cssClass){return _.contains(["ng-valid","ng-invalid","ng-pristine","ng-dirty"],cssClass)?cssClass:null},ajax:{data:searchRequestFunc,quietMillis:quietMillis,transport:transport,results:function(data,page){var more=(page*options.size||100)<data.totalCount;return{results:_.filter(data.elements,filterFunc),more:more}}},formatResult:function(element){return element.name},formatSelection:function(element){return element.name}},options["ui-select2"])}function CatSelectDirective(){return{restrict:"EA",replace:!0,priority:1,scope:{options:"=?",id:"@",config:"@?"},link:CatSelectLink,controller:CatSelectController,template:'<input type="text" ui-select2="selectOptions">'}}function CatApiEndpoint(url,endpointConfig,$http,catConversionService){var that=this,_endpointName=endpointConfig.name,config=endpointConfig.config,_endpointUrl=url+(config.url||endpointConfig.name),_childEndpointSettings=endpointConfig.children,_res=_.memoize(function(id){var url=_endpointUrl+"/"+id+"/",ret={};return _.forEach(_.keys(_childEndpointSettings),function(path){ret[path]=new CatApiEndpoint(url,_childEndpointSettings[path],$http,catConversionService),ret[path].parentEndpoint=that,ret[path].parentId=id,ret[path].parentInfo=function(){return that.info(id)}}),ret}),_addChildEndpoints=function(data){_.merge(data,_res(data.id))},_mapResponse=function(data){var object=catConversionService.toClient(data,config);return _.isUndefined(object.id)||_addChildEndpoints(object),_.isArray(object)&&_.forEach(object,_addChildEndpoints),_.isArray(object.elements)&&_.forEach(object.elements,_addChildEndpoints),object},_removeEndpoints=function(object){var endpoints=_res(object.id);return _.forEach(_.keys(endpoints),function(key){delete object[key]}),object},_getSearchQuery=function(searchRequest){return searchRequest&&searchRequest instanceof window.cat.SearchRequest?"?"+searchRequest.urlEncoded():""};this.res=function(id){return _res(id)},this.getEndpointUrl=function(){return _endpointUrl},this.getEndpointName=function(){return _endpointName},this.list=function(searchRequest){return $http.get(_endpointUrl+_getSearchQuery(searchRequest)).then(function(response){return _mapResponse(response.data)})},this.all=function(){return $http.get(_endpointUrl+"/all").then(function(response){return _.map(response.data,function(elem){return _mapResponse(elem)})})},this.get=function(id){return $http.get(_endpointUrl+"/"+id).then(function(response){return _mapResponse(response.data)})},this.info=function(id){return $http.get(_endpointUrl+"/"+id+"?info").then(function(response){return response.data})},this.save=function(object){return object.id?$http.put(_endpointUrl+"/"+object.id,_removeEndpoints(object)).then(function(response){return _mapResponse(response.data)}):$http.post(_endpointUrl,_removeEndpoints(object)).then(function(response){return _mapResponse(response.data)})},this.remove=function(url){return $http({method:"DELETE",url:_endpointUrl+"/"+url})},this.custom={},this.custom.get=function(url,searchRequest){return $http.get([_endpointUrl,url].join("/")+_getSearchQuery(searchRequest))},this.custom.post=function(url,object){return $http.post([_endpointUrl,url].join("/"),object)},this.custom.put=function(url,object){return $http.put([_endpointUrl,url].join("/"),object)}}function EndpointConfig(name,config){var that=this;if(this.config=config||{},this.children={},this.name=name,this.child=function(childName,childConfig){return _.isUndefined(childConfig)||(this.children[childName]=new EndpointConfig(childName,childConfig),this.children[childName].parent=this),this.children[childName]},!_.isUndefined(this.config.children)){var childrenConfig=this.config.children;delete this.config.children,_.forEach(_.keys(childrenConfig),function(childName){that.child(childName,childrenConfig[childName])})}}function CatApiServiceProvider(){var _urlPrefix="/api/";this.endpoint=function(name,settings){return _.isUndefined(settings)||(_endpoints[name]=new EndpointConfig(name,settings)),_endpoints[name]},this.$get=["$http","catConversionService",function($http,catConversionService){var catApiService={};return _.forEach(_.keys(_endpoints),function(path){catApiService[path]=new CatApiEndpoint(_urlPrefix,_endpoints[path],$http,catConversionService)}),catApiService}]}function CatBreadcrumbsService(catBreadcrumbs){function capitalize(string){return string.charAt(0).toUpperCase()+string.substring(1)}function splitShiftAndJoin(path,amount){return _.initial(path.split("/"),amount).join("/")}var that=this;this.clear=function(){catBreadcrumbs.length=0},this.set=function(bcs){that.clear(),_.forEach(bcs,function(bc){catBreadcrumbs.push(bc)})},this.get=function(){return catBreadcrumbs},this.addFirst=function(entry){catBreadcrumbs.unshift(entry)},this.removeFirst=function(){return catBreadcrumbs.shift()},this.push=function(entry){catBreadcrumbs.push(entry)},this.pop=function(){return catBreadcrumbs.pop()},this.length=function(){return catBreadcrumbs.length},this.replaceLast=function(newVal){catBreadcrumbs[catBreadcrumbs.length-1]=newVal},this.generateFromConfig=function(config){that.clear();var uiStack=[];if(_.isUndefined(config.endpoint.parentEndpoint))that.push({title:capitalize(window.cat.util.pluralize(config.endpoint.getEndpointName())),key:"cc.catalysts.cat-breadcrumbs.entry."+config.endpoint.getEndpointName(),url:"#"+config.baseUrl});else for(var currentEndpoint=config.endpoint,parentEndpoint=currentEndpoint.parentEndpoint,parentUrl=config.baseUrl,count=0;!_.isUndefined(parentEndpoint);){var parent=config.parents[count++];parentUrl=splitShiftAndJoin(parentUrl,1);var detailBreadcrumb={url:"#"+parentUrl+"?tab="+currentEndpoint.getEndpointName(),title:parent.name};uiStack.unshift(detailBreadcrumb),that.addFirst(detailBreadcrumb),parentUrl=splitShiftAndJoin(parentUrl,1);var breadcrumb={title:capitalize(window.cat.util.pluralize(parentEndpoint.getEndpointName())),key:"cc.catalysts.cat-breadcrumbs.entry."+config.endpoint.getEndpointName(),url:"#"+parentUrl};that.addFirst(breadcrumb),currentEndpoint=parentEndpoint,parentEndpoint=currentEndpoint.parentEndpoint}return uiStack}}function CatConversionService(catConversionFunctions){this.toClient=function(serverData,context){return catConversionFunctions.toClient(serverData,context)},this.toServer=function(clientData){return catConversionFunctions.toServer(clientData)}}function _convertToClientModel(data,context){return!_.isUndefined(context)&&_.isFunction(context.model)?new context.model(data):data}function _convertToClientData(serverData,context){if(_.isUndefined(serverData))return void 0;if(_.isArray(serverData))return _.map(serverData,function(data){return _convertToClientModel(data,context)});if(_.isNumber(serverData.totalCount)){var copy=_.clone(serverData),facets=[];serverData.facets&&(facets=_.map(serverData.facets,function(facet){return new window.cat.Facet(facet)}));var result={totalCount:serverData.totalCount,facets:facets,elements:_.map(serverData.elements,function(elem){return _convertToClientData(elem,context)})};return delete copy.totalCount,delete copy.elements,delete copy.facets,_.assign(result,copy)}return _.isUndefined(context)?serverData:_convertToClientModel(serverData,context)}function CatI18nLocaleService($q,$locale,CAT_I18N_DEFAULT_LOCALE){this.getLanguageOfLocale=function(locale){return _.isUndefined(locale)?void 0:-1!==locale.indexOf("-")?locale.split("-")[0]:locale},this.getCurrentLocale=function(){return $locale.id},this.getDefaultLocale=function(){return CAT_I18N_DEFAULT_LOCALE}}function CatI18nMessageSourceService($q,catI18nLocaleService,CAT_I18N_DEFAULT_LOCALE){function _getLocale(locale){return locale||catI18nLocaleService.getDefaultLocale()}function _getMessages(locale){var localeId=_getLocale(locale),messages=window.cat.i18n[localeId];return _.isUndefined(messages)&&(messages=_getMessages(catI18nLocaleService.getLanguageOfLocale(localeId))),localeId!==CAT_I18N_DEFAULT_LOCALE&&_.isUndefined(messages)&&(messages=_getMessages(CAT_I18N_DEFAULT_LOCALE)),messages}this.getMessages=function(locale){return $q.when(_getMessages(locale))},this.getMessage=function(key,locale){var bundle=_getMessages(locale);return _.isUndefined(bundle)||_.isUndefined(bundle[key])?$q.reject("No message found for key '"+key+"' and the given locale '"+_getLocale(locale)+"'"):$q.when(bundle[key])},this.hasMessage=function(key,locale){var bundle=_getMessages(locale);return $q.when(!_.isUndefined(bundle)&&!_.isUndefined(bundle[key]))}}function CatI18nService($q,$log,catI18nMessageSourceService,catI18nMessageParameterResolver){var that=this;this.translate=function(key,parameters,locale){var deferred=$q.defer(),model=parameters;return _.isArray(parameters)&¶meters.forEach(function(value,idx){model["p"+idx]=value}),that.canTranslate(key,locale).then(function(canTranslate){if(canTranslate)catI18nMessageSourceService.getMessage(key,locale).then(function(message){try{deferred.resolve(catI18nMessageParameterResolver(message,model))}catch(e){$log.warn(e),deferred.reject(e)}},function(reason){$log.warn(reason),deferred.reject(reason)});else{var reason="No translation for key '"+key+"' available!";$log.warn(reason),deferred.reject(reason)}},deferred.reject),deferred.promise},this.canTranslate=function(key,locale){var deferred=$q.defer();return catI18nMessageSourceService.getMessages(locale).then(function(messages){deferred.resolve(!_.isUndefined(messages)&&!_.isUndefined(messages[key]))},function(reason){$q.reject(reason)}),deferred.promise}}function CatRouteServiceProvider($stateProvider){function _getListUrl(baseUrl,name,config){var listUrl=baseUrl+"/"+window.cat.util.pluralize(name.toLowerCase());return config&&config.url&&(listUrl=baseUrl+"/"+config.url),listUrl}function _registerAbstractState(url,name){$stateProvider.state(name,{"abstract":!0,template:"<ui-view></ui-view>",url:url})}function _getStateName(name,config){return config&&config.parent?config.parent+"."+name:name}function _registerDetailState(config,name){var stateName=_getStateName(name,config),detailConfig=_getDetailConfig(config,name);$stateProvider.state(stateName+".detail",detailConfig),config&&"tabs"===config.additionalViewTemplate&&$stateProvider.state(stateName+".tab",{"abstract":!0,template:"<ui-view></ui-view>",url:"/:"+name.toLowerCase()+"Id"})}function _registerListState(config,name){var stateName=_getStateName(name,config),listConfig=_getListConfig(config,name);$stateProvider.state(stateName+".list",listConfig)}function _getDetailConfig(config,name){return window.cat.util.route.detail(_.assign({name:name},config))}function _getListConfig(config,name){return window.cat.util.route.list(_.assign({name:name},config))}var viewNames=[];this.detailRoute=function(baseUrl,name,config){var stateName=_getStateName(name,config);viewNames.push(stateName);var listUrl=_getListUrl(baseUrl,name,config);_registerAbstractState(listUrl,stateName),_registerDetailState(config,name)},this.listAndDetailRoute=function(baseUrl,name,config){var stateName=_getStateName(name,config);viewNames.push(stateName),_.isUndefined(config)&&(config={});var listUrl=_getListUrl(baseUrl,name,config);_registerAbstractState(listUrl,stateName),_registerDetailState(config.details,name),_registerListState(config.list,name)},this.$get=function(){return viewNames}}function assignDeep(target,source){return _.assign(target,source,function(targetProperty,sourceProperty){return _.isObject(targetProperty)&&_.isObject(sourceProperty)?assignDeep(targetProperty,sourceProperty):sourceProperty})}function CatSelectConfigService(configs){this.getConfig=function(name,options){var config=configs[name];return _.isUndefined(config)&&_.isUndefined(options)?void 0:assignDeep(_.clone(config)||{},options)}}function CatSelectConfigServiceProvider(){var configs={};this.config=function(name,config){return _.isUndefined(config)||(configs[name]=config),configs[name]},this.$get=function(){return new CatSelectConfigService(configs)}}function CatViewServiceProvider(catRouteServiceProvider,catApiServiceProvider){var viewNames=[],endpointNames=[];this.listAndDetailView=function(baseUrl,name,config){var endpointName=name.toLowerCase(),url=window.cat.util.pluralize(endpointName);config&&(url=config.url||url);var endpoint={model:window.cat.util.defaultModelResolver(name),url:url};config&&(endpoint=_.assign(endpoint,config.endpoint)),viewNames.push(name),endpointNames.push(endpointName),catApiServiceProvider.endpoint(name.toLowerCase(),endpoint),catRouteServiceProvider.listAndDetailRoute(baseUrl,name,config)},this.$get=function(){return{views:viewNames,endpoints:endpointNames}}}function MenuEntry(menuEntryId,options,parent){this.id=menuEntryId,this.completeId=parent.completeId+"."+this.id;var _options=options;this.getOptions=function(){return _options},this.isGroup=function(){return!1},this.isMenu=function(){return!1}}function MenuGroup(groupId,options,parent){var that=this;this.id=groupId,this.completeId=parent.completeId+"."+this.id;var _menuEntries=[],_options=options;this.addMenuEntry=function(menuEntryId,options){_menuEntries.push(new MenuEntry(menuEntryId,options,that))},this.getOptions=function(){return _options},this.getEntries=function(){return _.sortBy(_menuEntries,function(entry){return entry.getOptions().sortOrder||1e4})},this.isGroup=function(){return!0},this.isMenu=function(){return!1}}function Menu(menuId,options){var that=this;this.id=menuId,this.completeId=this.id;var _menuEntries=[],_menuGroups={},_options=options;this.addMenuGroup=function(groupId,options){_menuGroups[groupId]=new MenuGroup(groupId,options,that)},this.addMenuEntry=function(groupId,menuEntryId,options){_.isUndefined(groupId)?_menuEntries.push(new MenuEntry(menuEntryId,options,that)):_menuGroups[groupId].addMenuEntry(menuEntryId,options)},this.getGroups=function(){return _.sortBy(_.map(_menuGroups,function(menuGroup){return menuGroup}),function(menuGroup){return menuGroup.getOptions().sortOrder||1e4})},this.getEntries=function(groupId){return _.isUndefined(groupId)?_.sortBy(_menuEntries,function(entry){return entry.getOptions().sortOrder||1e4}):_menuGroups[groupId].getEntries()},this.getFlattened=function(){return _.flatten([_menuEntries,_.map(this.getGroups(),function(group){return[group,group.getEntries()]})])},this.isMenu=function(){return!0},this.isGroup=function(){return!1},this.getOptions=function(){return _options}}function MenuBar(menuBarId,options){this.id=menuBarId;var _menus={},_options=options;this.addMenu=function(menuId,options){_menus[menuId]=new Menu(menuId,options)},this.addMenuGroup=function(menuId,groupId,options){_menus[menuId].addMenuGroup(groupId,options)},this.addMenuEntry=function(menuId,groupId,menuEntryId,options){_menus[menuId].addMenuEntry(groupId,menuEntryId,options)},this.getMenus=function(){return _.map(_menus,function(menu){return menu})},this.getOptions=function(){return _options}}function MainMenuProvider(){var _mainMenu=new MenuBar("main.menu",{}),_menus=[],_groups=[],_entries=[];this.menu=function(moduleId,options){_menus.push({menuId:moduleId,options:options})},this.menuGroup=function(moduleId,groupId,options){_groups.push({menuId:moduleId,groupId:groupId,options:options})},this.menuEntry=function(moduleId,groupId,entryId,options){_.isUndefined(options)&&(options=entryId,entryId=groupId,groupId=void 0),_entries.push({menuId:moduleId,groupId:groupId,entryId:entryId,options:options})},this.$get=function(){return _.forEach(_menus,function(menu){_mainMenu.addMenu(menu.menuId,menu.options)}),_.forEach(_groups,function(group){_mainMenu.addMenuGroup(group.menuId,group.groupId,group.options)}),_.forEach(_entries,function(entry){_mainMenu.addMenuEntry(entry.menuId,entry.groupId,entry.entryId,entry.options)}),_mainMenu}}window.cat={},angular.module("cat.filters.replaceText",[]),angular.module("cat.filters",["cat.filters.replaceText"]),angular.module("cat.template",["ui.bootstrap.tpls"]),angular.module("cat.service.conversion",[]),angular.module("cat.service.api",["cat.service.conversion"]),angular.module("cat.service.breadcrumbs",[]),angular.module("cat.service.i18n",[]),angular.module("cat.service.listDataLoading",["cat.service.api"]),angular.module("cat.service.route",["ui.router"]),angular.module("cat.service.selectConfig",[]),angular.module("cat.service.view",["cat.service.api","cat.service.route"]),angular.module("cat.service.loading",["angularSpinner"]),angular.module("cat.service.message",[]),angular.module("cat.service.httpIntercept",["cat.service.loading","cat.service.message"]),angular.module("cat.service.menu",[]),angular.module("cat.service",["cat.service.conversion","cat.service.api","cat.service.breadcrumbs","cat.service.i18n","cat.service.listDataLoading","cat.service.route","cat.service.selectConfig","cat.service.view","cat.service.loading","cat.service.httpIntercept","cat.service.menu","cat.service.message"]),angular.module("cat.directives.autofocus",[]),angular.module("cat.directives.checkbox",[]),angular.module("cat.directives.confirmClick",[]),angular.module("cat.directives.fieldErrors",[]),angular.module("cat.directives.inputs",[]),angular.module("cat.directives.loadMore",[]),angular.module("cat.directives.menu",["cat.service.menu"]),angular.module("cat.directives.select",["ui.select2","cat.service.api","cat.service.selectConfig"]),angular.module("cat.directives.i18n",["cat.service.i18n"]),angular.module("cat.directives.paginated",["ui.bootstrap.pagination","cat.service.listDataLoading","cat.service.i18n"]),angular.module("cat.directives.facets",["cat.directives.paginated"]),angular.module("cat.directives.sortable",["cat.directives.paginated"]),angular.module("cat.directives.form",[]),angular.module("cat.directives.numbersOnly",[]),angular.module("cat.controller.base.list",["cat.service.breadcrumbs"]),angular.module("cat.controller.base.tabs",[]),angular.module("cat.controller.base.detail",["cat.service.breadcrumbs","cat.controller.base.tabs"]),angular.module("cat.controller",["cat.controller.base.detail","cat.controller.base.list"]),angular.module("cat.directives",["cat.template","cat.directives.autofocus","cat.directives.checkbox","cat.directives.confirmClick","cat.directives.fieldErrors","cat.directives.inputs","cat.directives.loadMore","cat.directives.menu","cat.directives.select","cat.directives.i18n","cat.directives.paginated","cat.directives.facets","cat.directives.sortable","cat.directives.form","cat.directives.numbersOnly"]),angular.module("cat",["cat.service","cat.template","cat.directives","cat.filters","cat.controller"]),window.cat=window.cat||{},window.cat.FacetTerm=function(data){void 0===data&&(data={}),this.id=data.id,this.name=data.name,this.count=data.count},window.cat.Facet=function(data){void 0===data&&(data={}),this.name=data.name,this.terms=_.map(data.facets,function(facet){return new window.cat.FacetTerm(facet)})},window.cat=window.cat||{},window.cat.SearchRequest=function(searchUrlParams){var lastEncoded,_pagination={page:1,size:100},_sort={},_search={};searchUrlParams&&!_.isEmpty(searchUrlParams)&&(_pagination.page=searchUrlParams.page||_pagination.page,_pagination.size=searchUrlParams.size||_pagination.size,_sort.property=searchUrlParams.sort||_sort.property,_sort.isDesc=searchUrlParams.rev||_sort.isDesc,_.forEach(_.keys(searchUrlParams),function(param){param.indexOf("search.")>-1&¶m.length>7&&(_search[param.substring(7)]=searchUrlParams[param])}));var _encodeSort=function(){return _sort.property?"sort="+_sort.property+":"+(_sort.isDesc===!0||"true"===_sort.isDesc?"desc":"asc"):""},_encodePagination=function(){return"page="+(_pagination.page?Math.max(0,_pagination.page-1):0)+"&size="+_pagination.size||100},_concatenate=function(result,next){return result?next?result+"&"+next:result:next},_encodeSearch=function(){return _search&&!_.isEmpty(_search)?$.param(_search):""},urlEndoded=function(){return _([_encodePagination(),_encodeSort(),_encodeSearch()]).reduce(_concatenate)};this.pagination=function(pagination){return void 0===pagination?_pagination:_pagination=pagination},this.sort=function(sort){return void 0===sort?_sort:_sort=sort},this.search=function(search){return void 0===search?_search:_search=search},this.urlEncoded=function(){return lastEncoded=urlEndoded()},this.isDirty=function(){return lastEncoded!==urlEndoded()},this.setSearch=function($location){var ret={};ret.page=_pagination.page,ret.size=_pagination.size,_sort.property&&(ret.sort=_sort.property,ret.rev=_sort.isDesc||!1),_.forEach(_.keys(_search),function(s){ret["search."+s]=_search[s]}),$location.search(ret)}},CatBaseDetailController.$inject=["$scope","$stateParams","$location","$window","$globalMessages","$controller","$log","catBreadcrumbsService","config"],angular.module("cat.controller.base.detail").controller("CatBaseDetailController",CatBaseDetailController),angular.module("cat.controller.base.list").controller("CatBaseListController",["$scope","$controller","$log","catBreadcrumbsService","config",CatBaseListController]),CatBaseTabsController.$inject=["$scope","$controller","$stateParams","$location","config"],angular.module("cat.controller.base.tabs").controller("CatBaseTabsController",CatBaseTabsController),angular.module("cat.directives.autofocus").directive("catAutofocus",["$timeout",function($timeout){return{restrict:"A",link:function(scope,element){$timeout(function(){_.isUndefined(element.data("select2"))?element[0].focus():element.select2("open")},100)}}}]),angular.module("cat.directives.checkbox").directive("catCheckbox",function(){return{replace:!0,restrict:"E",scope:{checked:"="},link:function(scope,element){element.addClass(scope.checked?"glyphicon glyphicon-check":"glyphicon glyphicon-unchecked")}}}),angular.module("cat.directives.confirmClick").directive("catConfirmClick",function(){return{restrict:"A",link:function(scope,element,attr){var msg=attr.catConfirmClick||"Are you sure?",clickAction=attr.catOnConfirm;element.bind("click",function(){window.confirm(msg)&&scope.$eval(clickAction)})}}}),angular.module("cat.directives.facets").directive("catFacets",function(){function _initDefaults(scope){_.isUndefined(scope.listData)&&(scope.listData=scope.$parent.listData)}function _checkConditions(scope){if(_.isUndefined(scope.listData))throw new Error("listData was not defined and couldn't be found with default value");if(_.isUndefined(scope.listData.facets))throw new Error("No facets are available within given listData")}return{replace:!0,restrict:"E",scope:{listData:"=?",names:"="},require:"^catPaginated",templateUrl:"template/cat-facets.tpl.html",link:function(scope,element,attrs,catPaginatedController){_initDefaults(scope),_checkConditions(scope),scope.catPaginatedController=catPaginatedController},controller:["$scope",function($scope){function _search(search){return $scope.catPaginatedController.getSearchRequest().search(search)}$scope.isActive=function(facet){return!!$scope.catPaginatedController.getSearch()[facet.name]},$scope.facetName=function(facet){return void 0!==$scope.names&&void 0!==$scope.names[facet.name]?$scope.names[facet.name]:facet.name},$scope.facets={},$scope.facetChanged=function(facet){var search=_search(),value=$scope.facets[facet.name];value?search[facet.name]=value:delete search[facet.name]},$scope.initFacets=function(){_.forEach($scope.listData.facets,function(facet){$scope.isActive(facet)&&($scope.facets[facet.name]=$scope.catPaginatedController.getSearch()[facet.name])})},$scope.facetSelectOptions={allowClear:!0}}]}}),angular.module("cat.directives.fieldErrors").directive("catFieldErrors",function(){return{replace:"true",restrict:"E",scope:{errors:"=",name:"@"},template:'<div class="label label-danger" ng-if="errors[name]"><ul><li ng-repeat="error in errors[name]">{{error}}</li></ul></div>'}}),angular.module("cat.directives.i18n").directive("catI18n",["$log","$rootScope","catI18nService",function($log,$rootScope,catI18nService){function _translate(scope,element){return scope.key?void catI18nService.translate(scope.key,scope.params).then(function(message){element.text(message)},function(){}):void $log.warn("No key was given for cat-i18n!")}return{restrict:"A",scope:{key:"@catI18n",params:"=?i18nParams",watchParams:"=?i18nWatchParams"},link:function(scope,element){_translate(scope,element),scope.params&&scope.watchParams===!0&&scope.$watch("params",function(){_translate(scope,element)},!0),$rootScope.$on("cat-i18n-refresh",function(){_translate(scope,element)})}}}]),angular.module("cat.directives.inputs").directive("input",function(){return{require:"ngModel",restrict:"E",link:function(scope,element,attrs,ctrl){scope.$on("fieldErrors",function(event,fieldErrors){if(fieldErrors&&attrs.id){var valid=!fieldErrors[attrs.id];
ctrl.$setValidity(attrs.id,valid)}})}}}).directive("catInputGroup",function(){return{restrict:"A",transclude:!0,scope:{errors:"=",label:"@",name:"@"},link:function(scope,element){element.addClass("form-group")},templateUrl:"template/cat-input.tpl.html"}}),angular.module("cat.directives.loadMore").directive("catLoadMore",function(){return{replace:!0,restrict:"A",link:function(scope,element,attrs){var initialCount=parseInt(attrs.catLoadMore);if(scope.$parent.elementsCount=scope.$parent.elementsCount||initialCount,scope.$parent.elements=scope.$parent.elements||[],scope.$parent.elements.push(element),scope.$parent.elements.length>scope.$parent.elementsCount&&element.addClass("hidden"),!element.parent().next().length&&scope.$parent.elements.length>scope.$parent.elementsCount){var elt=$('<a href="#">Show more</a>');elt.on({click:function(){return scope.$parent.elementsCount+=initialCount,scope.$parent.elements.length<=scope.$parent.elementsCount&&elt.addClass("hidden"),scope.$parent.elements.forEach(function(elt,ind){ind<scope.$parent.elementsCount&&elt.removeClass("hidden")}),!1}}),element.parent().after(elt)}}}}),angular.module("cat.directives.menu").directive("catMainMenu",["$mainMenu","$rootScope",function($mainMenu,$rootScope){return{restrict:"E",scope:{},link:function(scope){scope.menus=$mainMenu.getMenus(),scope.isVisible=function(entry){var visible=!1;return entry.isMenu()||entry.isGroup()?(_.forEach(entry.getEntries(),function(subEntry){visible=visible||scope.isVisible(subEntry)}),entry.isMenu()&&_.forEach(entry.getGroups(),function(groups){visible=visible||scope.isVisible(groups)}),visible):scope.isAllowed(entry)},scope.isAllowed=function(entry){var rights=entry.getOptions().rights;if(rights){if(_.isArray(rights)){for(var allowed=!0,i=0;i<rights.length;i++)allowed=allowed&&$rootScope.isAllowed(rights[i]);return allowed}return $rootScope.isAllowed(rights)}return!0}},templateUrl:"template/cat-main-menu.tpl.html"}}]),angular.module("cat.directives.paginated").directive("catPaginated",["$log","catI18nService",function($log,catI18nService){var SEARCH_PROP_KEY="cc.catalysts.cat-paginated.search.prop";return{replace:!0,restrict:"E",transclude:!0,scope:{listData:"=?",syncLocation:"=?"},templateUrl:"template/cat-paginated.tpl.html",link:function(scope,element,attrs){attrs.searchProps&&(scope.searchProps=_.filter(attrs.searchProps.split(","),function(prop){return!!prop}),scope.searchPropertyPlaceholders={},_.forEach(scope.searchProps,function(searchProp){scope.searchPropertyPlaceholders[searchProp]="Search by "+searchProp,catI18nService.translate(SEARCH_PROP_KEY,{prop:searchProp}).then(function(message){scope.searchPropertyPlaceholders[searchProp]=message})}))},controllerAs:"catPaginatedController",controller:["$scope","$location","$timeout","$rootScope","catListDataLoadingService","catI18nService",function($scope,$location,$timeout,$rootScope,catListDataLoadingService,catI18nService){function handlePaginationTextResponse(prop){return function(message){$scope.paginationText[prop]=message}}function _loadPaginationTranslations(){catI18nService.translate(PAGINATION_PREVIOUS_KEY).then(handlePaginationTextResponse("previous")),catI18nService.translate(PAGINATION_NEXT_KEY).then(handlePaginationTextResponse("next")),catI18nService.translate(PAGINATION_FIRST_KEY).then(handlePaginationTextResponse("first")),catI18nService.translate(PAGINATION_LAST_KEY).then(handlePaginationTextResponse("last"))}function updateLocation(){$scope.syncLocation!==!1&&(searchRequest.setSearch($location),$location.replace())}var that=this,searchTimeout=null,DELAY_ON_SEARCH=500,PAGINATION_PREVIOUS_KEY="cc.catalysts.cat-paginated.pagination.previous",PAGINATION_NEXT_KEY="cc.catalysts.cat-paginated.pagination.next",PAGINATION_FIRST_KEY="cc.catalysts.cat-paginated.pagination.first",PAGINATION_LAST_KEY="cc.catalysts.cat-paginated.pagination.last";if(_.isUndefined($scope.listData)&&($scope.listData=$scope.$parent.listData,_.isUndefined($scope.listData)))throw new Error("listData was not defined and couldn't be found with default value");_.isUndefined($scope.syncLocation)&&($scope.syncLocation=_.isUndefined($scope.$parent.detail)),$scope.paginationText={previous:"Previous",next:"Next",first:"First",last:"Last"},_loadPaginationTranslations(),$rootScope.$on("cat-i18n-refresh",function(){_loadPaginationTranslations()}),$scope.listData.search=$scope.listData.search||$scope.listData.searchRequest.search()||{};var searchRequest=$scope.listData.searchRequest,reload=function(delay){$timeout.cancel(searchTimeout),searchTimeout=$timeout(function(){searchRequest.isDirty()&&catListDataLoadingService.load($scope.listData.endpoint,searchRequest).then(function(data){_.assign($scope.listData,data)})},delay||0)};$scope.$watch("listData.sort",function(newVal){newVal&&(console.log("broadcasting sort changed: "+angular.toJson(newVal)),$scope.$parent.$broadcast("SortChanged",newVal))},!0),$scope.$watch("listData.pagination",function(){searchRequest.pagination($scope.listData.pagination),updateLocation(),reload()},!0);var searchChanged=function(value,delay){searchRequest.search(value),updateLocation(),$scope.listData.pagination.page=1,reload(delay)},updateSearch=function(value){var search=searchRequest.search();_.assign(search,value),searchChanged(value,DELAY_ON_SEARCH)};$scope.$watch("listData.search",updateSearch,!0),this.sort=function(value){searchRequest.sort(value),updateLocation(),$scope.listData.pagination.page=1,reload()},this.getSearch=function(){return searchRequest.search()},this.getSearchRequest=function(){return searchRequest},$scope.$on("SortChanged",function(event,value){that.sort(value)})}]}}]);var fetchElements=function(endpoint,sort){return function(queryParams){var searchRequest=new window.cat.SearchRequest(queryParams.data);return searchRequest.sort(sort||{property:"name",isDesc:!1}),endpoint.list(searchRequest).then(queryParams.success)}};CatSelectController.$inject=["$scope","$log","catApiService","catSelectConfigService"],angular.module("cat.directives.select").directive("catSelect",CatSelectDirective),angular.module("cat.directives.sortable").directive("catSortable",["$compile",function($compile){return{restrict:"AC",require:"^catPaginated",link:function(scope,element,attrs,catPaginatedController){var title=element.text(),property=attrs.catSortable||title.toLowerCase().trim();scope.sort=scope.listData.searchRequest.sort(),scope.catPaginatedController=catPaginatedController;var icon="glyphicon-sort-by-attributes";attrs.sortMode&&("numeric"===attrs.sortMode?icon="glyphicon-sort-by-order":"alphabet"===attrs.sortMode&&(icon="glyphicon-sort-by-alphabet")),element.text(""),element.append($compile('<a class="sort-link" href="" ng-click="toggleSort(\''+property+'\')" cat-i18n="cc.catalysts.cat-sortable.sort.'+property+'">'+title+' <span class="glyphicon" ng-class="{\''+icon+"': sort.property == '"+property+"' && !sort.isDesc, '"+icon+"-alt': sort.property == '"+property+"' && sort.isDesc}\"></span></a>")(scope))},controller:["$scope",function($scope){$scope.toggleSort=function(property){$scope.sort.property===property?$scope.sort.isDesc=!$scope.sort.isDesc:($scope.sort.property=property,$scope.sort.isDesc=!1),$scope.catPaginatedController.sort($scope.sort)},$scope.$on("SortChanged",function(event,value){$scope.sort=value})}]}}]),angular.module("cat.directives.form").directive("form",["$timeout",function($timeout){return{restrict:"E",scope:!0,require:"form",link:function(scope,element,attrs,formCtrl){var warningMessage=attrs.eocsWarnOnNavIfDirty||"You have unsaved changes. Leave the page?";$timeout(function(){formCtrl.$setPristine(!0)},50),scope.$on("formReset",function(){formCtrl.$setPristine(!0)}),scope.$on("formDirty",function(){formCtrl.$setDirty(!0)}),scope.$on("$locationChangeStart",function(event){formCtrl.$dirty&&(window.confirm(warningMessage)||event.preventDefault())}),$(window).on("beforeunload",function(){return formCtrl.$dirty?warningMessage:void 0}),scope.$on("$destroy",function(){$(window).unbind("beforeunload")})}}}]),angular.module("cat.directives.numbersOnly").directive("numbersOnly",function(){return{require:"ngModel",link:function(scope,element,attrs,modelCtrl){modelCtrl.$parsers.push(function(inputValue){if(!inputValue)return"";var pattern="[^0-9]";attrs.hasOwnProperty("allowFraction")&&(pattern="[^0-9,.]");var transformedInput=inputValue.replace(new RegExp(pattern,"g"),"");return transformedInput!==inputValue&&(modelCtrl.$setViewValue(transformedInput),modelCtrl.$render()),transformedInput})}}}),window.cat.i18n=window.cat.i18n||{},window.cat.i18n.de=window.cat.i18n.de||{},_.assign(window.cat.i18n.de,{"cc.catalysts.cat-paginated.itemsFound":"{{count}} Einträge gefunden. Einträge {{firstResult}}-{{lastResult}}","cc.catalysts.cat-paginated.noItemsFound":"Keine Einträge gefunden","cc.catalysts.general.new":"Neu"}),window.cat.i18n=window.cat.i18n||{},window.cat.i18n.en=window.cat.i18n.en||{},_.assign(window.cat.i18n.en,{"cc.catalysts.cat-paginated.itemsFound":"{{count}} entries found. Entries {{firstResult}}-{{lastResult}}","cc.catalysts.cat-paginated.noItemsFound":"No entries found","cc.catalysts.general.new":"New"}),angular.module("cat.filters.replaceText").filter("replaceText",function(){return function(text,pattern,options,replacement){return void 0===pattern&&(pattern="\n"),void 0===options&&(options="g"),void 0===replacement&&(replacement=", "),text?String(text).replace(new RegExp(pattern,options),replacement):text}});var _endpoints={};angular.module("cat.service.api").provider("catApiService",CatApiServiceProvider),angular.module("cat.service.api").provider("$api",CatApiServiceProvider),CatBreadcrumbsService.$inject=["catBreadcrumbs"],angular.module("cat.service.breadcrumbs").value("catBreadcrumbs",[]).service("catBreadcrumbsService",CatBreadcrumbsService),CatConversionService.$inject=["catConversionFunctions"],angular.module("cat.service.conversion").value("catConversionFunctions",{toClient:_convertToClientData,toServer:function(clientData){return clientData}}).service("catConversionService",CatConversionService),angular.module("cat.service.i18n").constant("CAT_I18N_DEFAULT_LOCALE","de").service("catI18nLocaleService",["$q","$locale","CAT_I18N_DEFAULT_LOCALE",CatI18nLocaleService]),angular.module("cat.service.i18n").service("catI18nMessageSourceService",["$q","catI18nLocaleService","CAT_I18N_DEFAULT_LOCALE",CatI18nMessageSourceService]),angular.module("cat.service.i18n").value("catI18nMessageParameterResolver",function(message,parameters){return _.template(message,parameters||{},{interpolate:/{{([\s\S\d]+?)}}/g})}).service("catI18nService",["$q","$log","catI18nMessageSourceService","catI18nMessageParameterResolver",CatI18nService]),angular.module("cat.service.listDataLoading").factory("catListDataLoadingService",["catApiService","$state","$location","$q",function(catApiService,$state,$location,$q){var load=function(endpoint,searchRequest){var deferred=$q.defer();return endpoint.list(searchRequest).then(function(data){var pagination=searchRequest.pagination(),result={count:data.totalCount,collection:data.elements,pagination:pagination,firstResult:(pagination.page-1)*pagination.size+1,lastResult:Math.min(pagination.page*pagination.size,data.totalCount),facets:data.facets,isSinglePageList:data.totalCount<=pagination.size,endpoint:endpoint,searchRequest:searchRequest};delete data.totalCount,delete data.elements,delete data.facets,deferred.resolve(_.assign(result,data))},function(reason){deferred.reject(reason)}),deferred.promise},resolve=function(endpointName,defaultSort){var searchRequest=new window.cat.SearchRequest($location.search());return defaultSort||(defaultSort={property:"name",isDesc:!1}),defaultSort&&!$location.search().sort&&searchRequest.sort(defaultSort),load(catApiService[endpointName],searchRequest)};return{load:load,resolve:resolve}}]),CatRouteServiceProvider.$inject=["$stateProvider"],angular.module("cat.service.route").provider("catRouteService",CatRouteServiceProvider),angular.module("cat.service.selectConfig").provider("catSelectConfigService",CatSelectConfigServiceProvider),CatViewServiceProvider.$inject=["catRouteServiceProvider","catApiServiceProvider"],angular.module("cat.service.view").provider("catViewService",CatViewServiceProvider),angular.module("cat.service.httpIntercept").factory("errorHttpInterceptor",["$q","$globalMessages","loadingService",function($q,$globalMessages,loadingService){return{request:function(config){return loadingService.start(),config},requestError:function(rejection){return loadingService.stop(),$q.reject(rejection)},response:function(success){return loadingService.stop(),success},responseError:function(rejection){if(loadingService.stop(),$globalMessages.clearMessages("error"),rejection.data.error){var error="["+rejection.status+" - "+rejection.statusText+"] "+rejection.data.error;rejection.data.cause&&(error+="\n"+rejection.data.cause),$globalMessages.addMessage("error",error)}return rejection.data.globalErrors&&$globalMessages.addMessages("error",rejection.data.globalErrors),$q.reject(rejection)}}}]).config(["$httpProvider",function($httpProvider){$httpProvider.interceptors.push("errorHttpInterceptor")}]),angular.module("cat.service.loading").factory("loadingService",["$rootScope","usSpinnerService","$timeout",function($rootScope,usSpinnerService,$timeout){var startTime,startTimer,stopTimer,timeout=50,animationDuration=200,activeCount=0,start=function(){activeCount||startTimer||(stopTimer&&($timeout.cancel(stopTimer),stopTimer=void 0),startTimer=$timeout(function(){usSpinnerService.spin("loading-spinner"),$rootScope.loading=!0,startTime=(new Date).getTime()},timeout)),activeCount++},stop=function(){if(activeCount--,!activeCount&&!stopTimer){startTimer&&($timeout.cancel(startTimer),startTimer=void 0);var now=(new Date).getTime(),stopTimeout=timeout+Math.max(animationDuration-(now-startTime),0);stopTimer=$timeout(function(){usSpinnerService.stop("loading-spinner"),$rootScope.loading=!1},stopTimeout)}};return $rootScope.$on("$stateChangeStart",function(){start()}),$rootScope.$on("$stateChangeSuccess",function(){stop()}),$rootScope.$on("$stateChangeError",function(){stop()}),{start:start,stop:stop}}]),angular.module("cat.service.menu").provider("$mainMenu",MainMenuProvider),angular.module("cat.service.message").service("$globalMessages",["$rootScope",function($rootScope){var messages={},self=this;this.getMessages=function(type){return type?messages[type]:[]},this.hasMessages=function(type){return type?!!messages[type]&&0!==messages[type].length:!1},this.clearMessages=function(type){return type?void(messages[type]=[]):void(messages={})},this.addMessage=function(type,message){type&&(messages[type]||self.clearMessages(type),messages[type].push(message))},this.addMessages=function(type,messages){type&&_.forEach(messages,function(message){self.addMessage(type,message)})},this.setMessages=function(type,messages){type&&(self.clearMessages(type),messages&&self.addMessages(type,messages))},$rootScope.$on("$stateChangeSuccess",function(){self.clearMessages()})}]),window.cat.util=window.cat.util||{},window.cat.util.pluralize=function(string){if(_.isUndefined(string)||0===string.length)return"";var lastChar=string[string.length-1];switch(lastChar){case"y":return string.substring(0,string.length-1)+"ies";case"s":return string+"es";default:return string+"s"}},window.cat.util.capitalize=function(string){return _.isUndefined(string)||0===string.length?"":string.substring(0,1).toUpperCase()+string.substring(1,string.length)},window.cat.util=window.cat.util||{},window.cat.models=window.cat.models||{},window.cat.util.defaultModelResolver=function(name){return window.cat.models[name]};var toLowerCaseName=function(name){return name?name.toLowerCase():""},getBaseUrl=function($location,$stateParams,baseUrl){if(!_.isUndefined(baseUrl))return baseUrl;var path=$location.path();return _.isUndefined($stateParams.id)?path:path.substring(0,path.lastIndexOf("/"))},listRoute=function(config){function getListDataPromise(catListDataLoadingService){return catListDataLoadingService.resolve(config.endpoint||name,config.defaultSort)}function getResolvedConfig($q,$stateParams,$location,catListDataLoadingService){var deferredConfig=$q.defer(),resolvedConfig={controller:config.controller||config.name+"Controller",baseUrl:getBaseUrl($location,$stateParams,config.baseUrl),title:window.cat.util.pluralize(config.name),searchProps:config.searchProps||window.cat.util.defaultListSearchProps,listTemplateUrl:config.listTemplateUrl||name+"/"+name+"-list.tpl.html"};return getListDataPromise(catListDataLoadingService).then(function(listData){resolvedConfig.listData=listData,deferredConfig.resolve(resolvedConfig)}),deferredConfig.promise}var name=toLowerCaseName(config.name);return{url:config.url||"",reloadOnSearch:!1,controller:"CatBaseListController",controllerAs:"catBaseListController",templateUrl:config.templateUrl||"template/cat-base-list.tpl.html",resolve:{config:getResolvedConfig}}},detailRoute=function(config){function getEndpoint($stateParams,catApiService){var endpoint=catApiService[endpointName];return _.isArray(parentEndpointNames)&&(_.forEach(parentEndpointNames,function(parentEndpointName,idx){var currentEndpoint;currentEndpoint=0===idx?catApiService[parentEndpointName]:endpoint[parentEndpointName],endpoint=currentEndpoint.res($stateParams[parentEndpointName+"Id"])}),endpoint=endpoint[endpointName]),endpoint}function getDetailData($stateParams,$q,endpoint){var detailPromise,detailId=$stateParams.id;return detailPromise="new"===detailId?$q.when(new Model):endpoint.get(detailId)}function getConfig($location,$stateParams,$q,catApiService){var deferred=$q.defer(),endpoint=getEndpoint($stateParams,catApiService),baseUrl=getBaseUrl($location,$stateParams,config.baseUrl),resolvedConfig={controller:config.controller||config.name+"DetailsController",endpoint:endpoint,Model:Model,templateUrls:templateUrls,tabs:tabs,baseUrl:baseUrl},detailPromise=getDetailData($stateParams,$q,endpoint);detailPromise.then(function(data){resolvedConfig.detail=data});var parentsPromise=getParentInfo($q,endpoint);return parentsPromise.then(function(parents){resolvedConfig.parents=parents}),$q.all([detailPromise,parentsPromise]).then(function(){deferred.resolve(resolvedConfig)},function(reason){deferred.reject(reason)}),deferred.promise}function getParentInfo($q,endpoint){if(_.isUndefined(endpoint)||_.isUndefined(endpoint.parentInfo))return $q.when([]);var deferred=$q.defer(),parents=[];return endpoint.parentInfo().then(function(parent){parents.push(parent),getParentInfo($q,endpoint.parentEndpoint).then(function(response){parents.push(response),parents=_.flatten(parents),deferred.resolve(parents)},function(error){deferred.reject(error)})},function(error){deferred.reject(error)}),deferred.promise}var endpointName,parentEndpointNames;_.isString(config.endpoint)?endpointName=config.endpoint:_.isObject(config.endpoint)?(parentEndpointNames=config.endpoint.parents,endpointName=config.endpoint.name):endpointName=toLowerCaseName(config.name);var Model=config.model||window.cat.util.defaultModelResolver(config.name),parentUrl="",parentTemplateNamePrefix="";_.isArray(parentEndpointNames)&&_.forEach(parentEndpointNames,function(parentEndpointName){parentUrl+=parentEndpointName,parentUrl+="/",parentTemplateNamePrefix+=parentEndpointName,parentTemplateNamePrefix+="-"});var tabs,templateUrls={edit:parentUrl+endpointName+"/"+parentTemplateNamePrefix+endpointName+"-details-edit.tpl.html",view:parentUrl+endpointName+"/"+parentTemplateNamePrefix+endpointName+"-details-view.tpl.html"};return config.additionalViewTemplate===!0?templateUrls.view={main:templateUrls.view,additional:parentUrl+endpointName+"/"+parentTemplateNamePrefix+endpointName+"-additional-details-view.tpl.html"}:"tabs"===config.additionalViewTemplate&&(templateUrls.view={main:templateUrls.view,additional:"template/cat-base-additional-details-tabs-view.tpl.html"},tabs=config.additionalViewTemplateTabs),{url:config.url||"/:id",templateUrl:config.templateUrl||"template/cat-base-detail.tpl.html",controller:"CatBaseDetailController",reloadOnSearch:config.reloadOnSearch,resolve:{config:getConfig}}};window.cat.util.route={list:listRoute,detail:detailRoute};
//# sourceMappingURL=cat-angular.min.js.map